Changelog
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
Unreleased
1.3.2 — 2026-11-22
Patch release that publishes anonyma-mcp 0.1.1. The library's behaviour is unchanged.
Fixed
anonyma-mcp0.1.1: on Windows,anonyma-mcp-proxyandrunStdioProxy()report a server command that does not exist ("could not start the server") instead of exiting with status 1 silently. The command is looked up onPATHwithPATHEXT, ascmd.exedoes, before it is started; a server found as an.exeor.comfile now starts without a shell, and batch files such asnpx.cmdstill start throughcmd.exe(#51).
1.3.1 — 2026-11-21
Patch release: documentation, and a bundler warning fixed. The library's behaviour is unchanged.
Added
- A documentation site, https://izaccavalheiro.github.io/anonyma/: getting started, recipes, the library guide, the API reference, generated tables of categories, presets, regulations and checksums, the benchmarks, a blog, and the playground, all in one place. Its Content Security Policy forbids every connection, so the playground cannot send what is typed into it. It replaces the stand-alone playground page.
Changed
- The site is the main documentation, and the README a short overview that links to it. The
library guide is written on the site, one page per topic, with pages of their own for the span
engine, keys and token vaults, the audit trail, regulations and policies, objects and records,
and HTTP middleware. The npm package's
homepageis the site.
Fixed
- Bundlers no longer warn about the dynamic import that reaches Web Crypto on Node.js 18: it now
carries
webpackIgnoreas well as@vite-ignore. - Documentation: the batch example passed
concurrencyas an option, whichanonymizeBatchAsync()ignores — it is the third argument. The coverage badge said 90%; the gate is 100%. The API reference held a stale second copy of itself. - Documentation: a non-empty
ruleslist in the options ofanonymize()is also the list of categories replaced, and takes the place of a preset's rules. The guide and the API reference now say so, and show how to change one category of a preset withcompilePipeline()(#47).
1.3.0 — 2026-11-21
Minor release: checksum validation and context proximity for detection, Brazilian and European
formats, combined compliance presets and signed anonymization receipts. Everything is additive,
with two changes to what is detected: more phone numbers and street addresses are found (see
Changed), and the validating pipelines of "anonyma/engine" leave national IDs whose check
digits fail. Some types are wider: preset accepts a list of presets wherever it is accepted,
and PatternSpec has validator and context members.
Added
- Checksum validators in
"anonyma/validators":abaRoutingChecksum,cnpjChecksum(numeric and the alphanumeric CNPJ issued from July 2026),npiChecksum,imeiChecksum,bsnChecksum(Dutch eleven test),ptNifChecksum,spanishIdChecksum(DNI and NIE),italianFiscalCodeChecksum,frNirChecksum(with Corsica's 2A and 2B),chineseResidentIdChecksum(ISO 7064 MOD 11-2),australianTfnChecksum,swedishPersonnummerChecksumandpixPayloadChecksum(CRC-16 of a PIX payload).CHECKSUMSnames every validator, old and new, for declarative patterns. - Validating national-ID detection.
detectNationalIdStrict()("anonyma/detectors") andstrictNationalIdDetector("anonyma/engine") discard national IDs whose check digits fail: Canadian SIN, South African ID, UK NINO, Aadhaar, Chinese resident ID, CPF, Swedish personnummer, Spanish DNI/NIE, Italian fiscal code, French NIR, Australian TFN, Portuguese NIF and Dutch BSN. A number that fails one country's check can still be another's. The validating pipelines (detection: "precise", the default ofcompilePipeline()and of the AI, MCP and middleware modules built on it) use it. - Context proximity.
withContext(detector, { keywords, window, boost, required })("anonyma/engine") raises the confidence of a hit that has one of the keywords withinwindowwords before it (three by default), or, withrequired, drops the hits that have none. A declarative pattern takes the same options ascontext, and the check digits it must pass asvalidator(a name fromCHECKSUMS), incompilePipeline()and in policy documents. - Brazilian identifiers. CNPJ (
tax-id), punctuated or after a label, numeric or alphanumeric, with valid check digits; RG (national-id) after an RG label; PIX payloads (bank-account), verified by their CRC, and PIX random keys after a PIX label. - Combined presets.
combinePresets(["lgpd", "hipaa"]), and a list of presets wherever one preset is accepted:anonymize(),anonymizeAsync(),createAnonymizer()andcompilePipeline(). The combination detects every category of every preset; each category gets the most protective of the presets' strategies (judged by whether it can be reversed, whether its outputs can be linked and how much of the value it leaves in clear), the preset listed first winning a tie. - Receipts.
createReceiptIssuer({ key })("anonyma/audit") issues anAnonymaReceiptfor an anonymized text: the time, the library version, the presets and policy, the number of replaced values per category, a SHA-256 digest of the output and, on request, a keyed digest of the input, signed with HMAC-SHA-256.verify()detects a receipt that was altered, signed with another key, or issued for another output or input. A receipt never contains a value. sanitizeJsonText()andsanitizeJsonTextAsync()("anonyma/ai"): a JSON text sanitized without losing numbers that a JavaScript number cannot hold, such as 20-digit IDs, whichJSON.parsewould round. A text in which nothing was replaced comes back unchanged.- Receipts for outputs too large to hold in memory:
issue()takesoutputDigest(the SHA-256 of the output) in place oftext, andcountsin place ofspansormatches. VERSION, the version of the package, exported from"anonyma".anonyma-cli0.1.0, a new companion package: theanonymacommand scrubs and scans text, JSON Lines and CSV files as streams, in constant memory, with presets, policies, column selection, gzip and signed receipts.
Changed
- More phone numbers are detected. Brazilian numbers (
(11) 91234-5678,11 91234-5678), and the national formats of France, the United Kingdom, Spain, Italy and the German-speaking countries, each in the grouping the country writes it in. An international number may have up to two separators between its digits, so+55 (11) 91234-5678and+55 11 91234-5678are found whole: 1.2.0 found no match in the first and replaced only+55 11 91234in the second, leaving-5678in the output. - More street addresses are detected: European and Brazilian streets such as
Musterstraße 12,Kerkstraat 12,12 rue de la Paix,Calle Mayor 5,Via Roma 10andAv. Paulista, 1578, with the postcode and town that follow them. - A US routing number whose check digits hold is reported with confidence 0.9 instead of 0.85.
Fixed
- Chunked streams no longer drop line breaks between card numbers. When the left context
that
createChunkTransformer(),createAsyncChunkTransformer()andcreatePipelineStream()keep between scans began inside a replaced card number, the end of that card and the start of the next line could pass the Luhn check as a card of their own, and the line break between them was replaced with it. The context now starts at the beginning of such a detection, and chunked output equals whole-text output again.
Notes
- The companion packages are named
anonyma-vercel-aiandanonyma-mcp. 1.2.0 introduced them as@anonyma/vercel-aiand@anonyma/mcp, but the@anonymascope is not available on npm, and they were never published under those names. Their folders (packages/vercel-ai,packages/mcp), APIs and theanonyma-mcp-proxycommand are unchanged. - The plan for this release proposed separate preset packages (
preset-lgpd,preset-gdpr,preset-hipaa). The presets and every detector they need are already part ofanonyma, which has no dependencies, so separate packages would add nothing but versions to keep in step; a list of presets gives the same composition.
1.2.0 — 2026-11-21
Minor release: plugins for createAnonymizer(), token vaults, edge runtimes, and companion
packages for the Vercel AI SDK and MCP. Everything is additive or a fix. Some types are wider:
the Anonymizer methods accept plugin strategy options (see Changed), and
SessionSnapshot.format (and TokenFormat) now include "brace", so an exhaustive switch
over a snapshot's format needs a case for it. The new packages, @anonyma/vercel-ai 0.1.0 and @anonyma/mcp 0.1.0, are versioned on their
own and require anonyma ^1.2.0.
anonyma/schemas now accepts zod 4 as well as zod 3. Its zod 3 floor rises from 3.23 to 3.25.4, the
first release whose zod/v3 entry point loads and type-checks; on an older zod 3, npm update zod
stays within zod 3.
Added
- Plugins.
createAnonymizer()applies thepluginsof its configuration, which 1.1.0 listed under "Known limitations" (#6). The methods of the anonymizer use their detectors, strategies and validators: a plugin detector replaces the built-in detector of its category (customDetectorstake precedence over it), rules, default strategies and field rules name a plugin strategy as{ strategy, options }, and a match is kept only when every plugin validator of its category accepts it.createAnonymizer()throws aValidationErrorwhen two plugins have the same name, register a detector for the same category or a strategy under the same name, or when a strategy has the name of a built-in one, and anUnknownCategoryErrorfor a detector or validator keyed by a name that is not a category. The standalone functions do not apply plugins. - Types
PluginStrategyOptionsandStrategyFunction, exported from"anonyma".AnonymizationRule,AnonymizeOptions,FieldRuleandFieldRuleMaptake an optional type parameter for the strategy options they hold,StrategyOptionsby default. - Token vaults.
AnonymaVault— any object withstore(key, value)andretrieve(key), synchronous or asynchronous —InMemoryVault, andrestore(text, vault), exported from"anonyma"and"anonyma/vault".restore()scans once and matches whole tokens, so{{PERSON_1}}is never found inside{{PERSON_10}}, and restored values are not scanned again. tokenize(text, { vault })andtokenizeAsync(text, { vault })store their tokens in a vault, numbered after those it already holds; a value the vault already holds keeps its token. With a vault,formatdefaults to"brace".createVaultTokenizer()("anonyma/vault"): a tokenization provider backed by anAnonymaVault, for the span engine, the LLM guard and the streaming restorers. It probes the vault before issuing a number, so a new tokenizer never overwrites an earlier one's tokens, and serialises allocations against an asynchronous vault.format: "brace"({{EMAIL_1}}) fortokenize(), the session tokenizer and the LLM guard, with stream hold-back for tokens split inside{{or}}, and lenient restoration of{EMAIL_1}and{{ email_01 }}.- Runtime checks (
scripts/runtime/): the same feature checks run against the build on Node.js, Bun, Deno and Cloudflare Workers (workerd through Miniflare, bundled with esbuild aswrangler deploydoes, withoutnodejs_compat). CI runs them in a newruntimesjob. @anonyma/vercel-ai0.1.0 (packages/vercel-ai): a typed AI SDK 7 middleware,withAnonyma()and drop-ingenerateText()/streamText(), tested against the real SDK.@anonyma/mcp0.1.0 (packages/mcp): a privacy guard for MCP connections, theanonyma-mcp-proxycommand that puts any stdio MCP server behind it, andguardMcpClient()for MCP SDK clients. Tested against the official MCP SDK.- The repository is an npm workspace;
packages/*are type-checked, tested, built and validated in a newpackagesCI job.
Changed
- The methods of
AnonymizerandAnonymizerConfig.defaultStrategyacceptPluginStrategyOptionswherever they acceptedStrategyOptions; the options of a built-in strategy are type-checked as before. An object that implementsAnonymizerwith parameter types of its own, such as a test double, may have to widen them. createAnonymizer()throwsUnsupportedStrategyErrorwhendefaultStrategynames a strategy that neither anonyma nor one of the plugins provides, instead of when it first applies it.- The optional
zodpeer dependency is^3.25.4 || ^4.0.0(was^3.23.0)."anonyma/schemas"importszod/v3, which both majors provide, so its declarations are the same whichever zod is installed. They were built against zod 3 and named types that zod 4 does not have. Every zod 3 release is subject to a high-severity advisory fixed in zod 4.6.6.
Fixed
detokenize()andrestoreFromLLM()left tokens whose prefix contains a digit —[IPV4_0001],[IPV6_0001]— unresolved.toLanguageModelMiddleware()restored tokens in streamed text but not in streamed reasoning (reasoning-delta), althoughwrapGeneraterestored both.sanitizeJson()and the LLM guard listed exempted members whose value isundefinedornullasunscanned. The Vercel AI SDK sendsproviderOptions: undefinedon every message, so anonSanitizedhook that refuses unscanned content refused every request.
1.1.1 — 2026-10-05
Patch release. The 1.x functions now exempt a detected value only when it equals an allowlist
entry, as documented; since 1.0.0 they also exempted every value that contained one. Code that
relied on such partial matches will see those values anonymized, and can use allowlistPatterns
to match a part of a value instead. The span engine ("anonyma/engine") is unchanged.
Fixed
allowlistskips a detected value only when the value equals an entry, as documented. Entries were matched as substrings, soallowlist: ["bob@example.com"]also leftjimbob@example.comin the output ofanonymize(),anonymizeAsync(),tokenize(),sanitizeForLLM()and the methods ofcreateAnonymizer(); an entry naming a domain left every address of that domain, and an empty entry left every value. A value that merely contains an entry is now anonymized.allowlistPatternsstill match a part of a value.createAnonymizer().tokenize()matchedallowlistentries as regular expressions: an entry containing(threw aSyntaxError, and"x.y@example.com"also exempted"xzy@example.com".allowlistPatternswith thegoryflag skipped only every other matching value, becauseRegExp.test()kept itslastIndexbetween values, and left the caller's pattern with a changedlastIndex. These flags are now ignored.
Added
- Plugins.
createAnonymizer()applies thepluginsof its configuration, which 1.1.0 listed under "Known limitations" (#6). The methods of the anonymizer use their detectors, strategies and validators: a plugin detector replaces the built-in detector of its category (customDetectorstake precedence over it), rules, default strategies and field rules name a plugin strategy as{ strategy, options }, and a match is kept only when every plugin validator of its category accepts it.createAnonymizer()throws aValidationErrorwhen two plugins have the same name, register a detector for the same category or a strategy under the same name, or when a strategy has the name of a built-in one, and anUnknownCategoryErrorfor a detector or validator keyed by a name that is not a category. The standalone functions do not apply plugins. - Types
PluginStrategyOptionsandStrategyFunction, exported from"anonyma".AnonymizationRule,AnonymizeOptions,FieldRuleandFieldRuleMaptake an optional type parameter for the strategy options they hold,StrategyOptionsby default.
Changed
- The methods of
AnonymizerandAnonymizerConfig.defaultStrategyacceptPluginStrategyOptionswherever they acceptedStrategyOptions; the options of a built-in strategy are type-checked as before. An object that implementsAnonymizerwith parameter types of its own, such as a test double, may have to widen them. createAnonymizer()throwsUnsupportedStrategyErrorwhendefaultStrategynames a strategy that neither anonyma nor one of the plugins provides, instead of when it first applies it.
1.1.0 — 2026-10-05
Additive release. The 1.0 functions (anonymize, tokenize, anonymizeObject, the streams,
sanitizeForLLM, …) keep their behaviour, apart from the fixes listed under "Fixed". Text
processed with the hipaa and ccpa presets may have more values replaced (see "Changed").
The subpath exports anonyma/engine, /vault, /audit, /compliance, /ai, /mcp and
/middleware are new. They were experimental in 1.1.0-beta.0 and are stable from this release:
they follow semantic versioning like the rest of the package.
Changes since 1.1.0-beta.0:
- The error classes added in this release are exported from
"anonyma". The pre-release did not export them from any entry point, so they could not be used withinstanceof. - The subpath exports are no longer experimental.
- The warnings that
anonymize()andanonymizeAsync()print for a strategy they do not apply name the span engine, which applies it, instead ofanonymizeAsync(), which does not. - The README and the TSDoc describe the subpath modules, and say which declared options the 1.x functions do not apply (see "Known limitations").
- Releases are published through npm trusted publishing only, and a stable version only from a
commit on
main. The tests also run on Node.js 26.
Added
"anonyma/engine"— span-based engine.createPipeline()andcompilePipeline()build a reusable pipeline withscan,test,transformandtransformAsync. Overlapping detections are resolved so that no detected character is left in the output, the confidence filter runs before overlap resolution, output is assembled in one pass, and a synchronous transform throwsAsyncStrategyErrorinstead of substituting another strategy.createChunkTransformer()andcreatePipelineStream()detect values that are split across chunks.- Validating detectors for email, US SSN, IBAN, IPv4, IPv6 and payment cards
(
emailDetector,ssnDetector,ibanDetector,ipv4Detector,ipv6Detector,creditCardDetector), plusdefineDetector(),defineRegexDetector()andfromLegacyDetector(). The 1.x detectors are available to the engine asLEGACY_DETECTORS. "anonyma/vault"—createSessionTokenizer(),createKeyedTokenizer(),createSealedTokenizer(),createKeyRing()(versioned keys, HKDF per purpose, rotation, destruction),createMemoryVault(),rewrapVault(),shredKey(),restoreTokens(),tokenizeWith()."anonyma/audit"—createAuditLogger()(hash-chained records without personal data),verifyAuditChain(),memorySink(),lineSink(),summarizeSpans(),inputChecksum()."anonyma/compliance"—REGULATIONS(GDPR, LGPD, PIPEDA, CCPA/CPRA, HIPAA, PCI DSS with citations and coverage gaps),parsePolicy()/checkPolicy(),policyToSpec(),describeStrategy(),planErasure()."anonyma/ai"—sanitizeJson()/sanitizeJsonAsync(),createLlmGuard(),createRestoreStream(),restoreChunks()with lenses,restoreJsonText(),toLanguageModelMiddleware()."anonyma/mcp"— MCP tool and resource declarations (MCP_TOOLS,MCP_RESOURCES,MCP_RESOURCE_TEMPLATES) and a dependency-free server (createMcpServer(),serveStdio())."anonyma/middleware","anonyma/middleware/express","anonyma/middleware/hono"—createScrubber(),anonymaExpress(),anonymaHono().- Presets
lgpdandpipeda. - Error classes
AsyncStrategyError,KeyManagementError,TokenVaultError,PolicyErrorandAuditIntegrityError, exported from"anonyma"like the others. ./package.jsonin the export map.- Benchmark (
npm run bench,bench/) and labelled detector corpora (tests/fixtures/corpus/). - Development dependencies
fast-check,expressandhonofor property-based and integration tests.
Changed
- Preset
hipaaalso detectscredit-card,iban,passport,license-plateandsocial-media; its description no longer claims to cover all 18 Safe Harbor identifiers. Presetccpaalso detectsmedical-record,health-insuranceandapi-key. Text processed with these presets may have more values replaced than before. - Build: entry points share code chunks (
splitting: true). Every entry point now uses the same class instances, soinstanceof AnonymaErrorholds for errors thrown by any subpath. Thedist/layout gainschunk-*.jsfiles. PresetNotFoundErrorlists the eight presets.- Releases are built and published by GitHub Actions from a version tag, through npm trusted publishing, with an npm provenance attestation, a GitHub build attestation and a CycloneDX SBOM attached to the GitHub release.
- Development needs Node.js 22.22 or newer. The package still supports Node.js 18: every release is installed and exercised on Node.js 18, 20, 22, 24 and 26.
Fixed
hash(),encrypt()anddecrypt()on Node.js 18 threw because they readglobalThis.crypto, which that runtime does not define. They now fall back to the Web Crypto implementation innode:crypto.detectDateOfBirth()dropped every date that preceded a date of a more confident format ("born 12/05/1987. Admitted on March 3, 2021."lost the first date): its overlap check compared positions instead of testing for intersection.mask()withpreserveFormatand the genericsynthesize()copied letters and digits outside ASCII into their output. Letters and digits of every script are now replaced.synthesize()no longer crashes, or returns[object Undefined], for a category named like anObject.prototypemember (constructor,toString, …).- The warning printed when
anonymize()oranonymizeAsync()redacts a value whose rule istokenize,encryptorsynthesizeadvisedanonymizeAsync(), which redacts it too.
Known limitations
The 1.0 documentation described behaviour that the 1.x functions do not have. The documentation now describes what they do; the behaviour itself is unchanged:
anonymize(),anonymizeAsync()and the functions built on them redact a value whose rule istokenize,encryptorsynthesize, with a warning, and the synchronous functions replace ahashrule with a seeded pseudonym. A pipeline from"anonyma/engine"applies every strategy.createAnonymizer()does not applyplugins(AnonymaPlugin).- With
presetset,anonymize()ignoresenabledCategories; a pipeline can add categories to a preset. tokenize()does not applyformat: "custom"withtokenTemplate, nordeterministic: false, and no function applieslocales.AnonymizeOptionsSchema.parse()removespreset,allowlist,confidenceThreshold,localesand the other options the schema does not describe.
1.1.0-beta.0 — 2026-10-04
Pre-release of 1.1.0, published under the next dist-tag. Its changes are listed under
1.1.0, together with the changes made since.
1.0.0 — 2026-03-06
Added
Core API ("anonyma")
-
detect(text, categories?, customDetectors?, aggressive?)— Scan a string for PII and return a sorted, non-overlapping array ofPiiMatchobjects. An optionalcategoriesarray restricts scanning to a subset;customDetectorsoverride built-in detectors per category;aggressive: trueswitches to the expandedAGGRESSIVE_DETECTOR_REGISTRY. -
anonymize(text, options?)— Synchronous detect-and-replace pipeline. Applies the configured strategy to every match and returns{ text, matches }. Async strategies (hash,encrypt,tokenize,synthesize) fall back to a safe synchronous substitute and emit aconsole.warn; useanonymizeAsync()for those strategies. -
anonymizeAsync(text, options?)— Fully async variant ofanonymize(). Supports all eight strategies natively, includinghash(SHA-256),encrypt(AES-GCM),tokenize, andsynthesize. -
anonymizeRecord(record, rules)— Field-level anonymization of plain objects.rulesis aFieldRuleMapkeyed by dot-notation paths (e.g."user.email"); only the specified fields are processed and the rest of the object is cloned unchanged. -
anonymizeObject<T>(obj, options?)— Deep recursive anonymization of any JSON-serializable object tree. Walks arrays, nested objects, and mixed structures; all string leaves are passed through the fullanonymize()pipeline. Returns a deep clone — the original is never mutated. Detects circular references and throwsValidationErrorwith a clear message. -
hasPII(text, categories?, customDetectors?)— Boolean check for PII presence. Uses an early-exit optimisation: scanning stops immediately after the first detector returns a match, making this significantly faster than a fulldetect()call when the answer istrue. -
createAnonymizer(config?)— Factory that produces a reusableAnonymizerinstance with built-in configuration. Returned instances exposeanonymize(),anonymizeAsync(),detect(),anonymizeRecord(),anonymizeObject(),tokenize(), andhasPII()— all pre-bound to the factory config and accepting per-call overrides.
Reversible Tokenization ("anonyma")
-
tokenize(text, options?)— Replace all detected PII with opaque, reversible tokens ([EMAIL_0001],[PHONE_0001], etc.). Returns{ text, mapping, tokens }wheremappingis aMap<token, originalValue>. Supportsangle,bracket, andcustomtoken formats; atokenTemplatefunction can fully control the token shape. -
tokenizeAsync(text, options?)— Async variant oftokenize(). -
detokenize(text, mapping)— Restore a tokenized string. Returns{ text, replacedCount, unresolved }— tokens absent from the mapping are left unchanged and listed inunresolvedso callers can detect data loss.
LLM Pipeline Helpers ("anonyma")
-
sanitizeForLLM(text, options?)— Convenience wrapper aroundtokenize()with defaults tuned for large-language-model use (format: "bracket", aggressive mode off to minimise false-positive noise in prompts). Returns aTokenizeResult; pass themappingtorestoreFromLLM(). -
restoreFromLLM(response, mapping)— Swap tokens back into the LLM's response text. Tokens use a safe character set ([CATEGORY_NNNN]) that language models rarely re-format, maximising round-trip fidelity.
Batch Processing ("anonyma")
-
anonymizeBatch(texts, options?)— Synchronously anonymize an array of strings. Each item is processed independently; a failure in one item does not abort the rest. ReturnsBatchResult<AnonymizeResult>[]with per-itemok/errordiscriminant. -
anonymizeBatchAsync(texts, options?, concurrency?)— Async batch anonymization. Items run in parallel viaPromise.allSettled. An optionalconcurrencycap limits simultaneous in-flight items, controlling memory pressure for large datasets. -
tokenizeBatch(texts, options?)— Batch tokenization. Each item receives its own independent token counter sequence (tokens do not cross item boundaries). -
detectBatch(texts, categories?)— Batch PII detection. ReturnsBatchResult<PiiMatch[]>[].
Compliance Presets ("anonyma")
-
getPreset(name)— Retrieve aPresetConfigby name. ThrowsPresetNotFoundErrorfor unknown names. -
PRESET_REGISTRY— Read-only map of all six built-in presets keyed by name.
Six presets are available out of the box, each pre-configuring enabledCategories and
defaultStrategy:
| Preset | Default Strategy | Coverage |
|---|---|---|
"gdpr" | pseudonymize | All personal data categories defined by the EU GDPR. |
"hipaa" | redact | All 18 HIPAA Safe Harbor identifiers for PHI de-identification. |
"ccpa" | redact | Consumer data categories defined by the California Consumer Privacy Act. |
"pci-dss" | redact (card numbers: mask keepTrailing 4) | Cardholder and sensitive authentication data per PCI-DSS. |
"sox" | redact | Financial records and corporate officer identifiers for SOX audit trails. |
"ferpa" | redact | Student education records as defined by FERPA. |
Anonymization Strategies ("anonyma")
Eight strategies are available. The first five are synchronous; the final three require
anonymizeAsync() (or the dedicated encrypt/hash/synthesize functions):
-
mask(value, options?)— Replace inner characters with a mask character (default"*"). Options:keepLeading,keepTrailing(characters to leave visible),maskChar(single character), andpreserveFormat(format-preserving masking: letters becomeX, digits become0, separators are preserved — e.g.123-45-6789→000-00-0000). -
redact(value, options?)— Replace the entire value with a configurable label. Default label:[REDACTED]. -
pseudonymize(value, options?)— Replace with a deterministic pseudo-identifier. When aseedis supplied, the same(value, seed)pair always produces the same pseudonym, enabling consistent replacement across a dataset. Without a seed, a random pseudonym is generated. A customprefix(default"id_") is prepended. -
generalize(value, options?)— Replace a numeric value with a bucket range. DefaultbucketSizeof10turns27into"20-29". Useful for age or year fields where relative ranges retain analytical utility. -
hash(value, options?)— Async SHA-256 hash (requires Web Crypto / Node ≥ 18). Options:truncate(number of hex characters to keep, default16) andpepper(a per-deployment secret mixed into the hash to prevent rainbow-table reversal). -
encrypt(value, options)/decrypt(ciphertext, options)— Async AES-256-GCM encryption (requires Web Crypto / Node ≥ 18). Provide either apassphrase(key derived via PBKDF2 + SHA-256, 100,000 iterations) or rawkeyBytes(16 or 32 bytes for AES-128/256). Output format:"<encoding>:<iv>:<ciphertext>"where both IV and payload are encoded asbase64(default) orhex. Also exported from the dedicated"anonyma/crypto"subpath. -
synthesize(value, options?)— Replace PII with structurally valid, format- preserving synthetic data. The generator is deterministic: the same(value, seed)pair always yields the same synthetic stand-in, preserving referential integrity across a dataset without retaining real PII. Synthetic generators are built in foremail,phone,ssn,credit-card,ipv4,ipv6,url,iban,date-of-birth,name,address,passport,drivers-license,national-id,bank-account,cryptocurrency,tax-id,medical-record,health-insurance,prescription,api-key,social-media,vin,license-plate,tracking-numberandcase-number. -
tokenize(as a strategy) — Whenstrategy: "tokenize"is supplied in a rule set, the value is replaced with a reversible opaque token. This is the same mechanism that powers the top-leveltokenize()function.
PII Detectors ("anonyma/detectors")
All detectors are pure functions (text: string) => PiiMatch[] and can be imported
individually for maximum tree-shaking. Twenty-seven categories are supported.
Email, Network & Identity
| Function | Confidence | Notes |
|---|---|---|
detectEmail | 0.99 | RFC 5321 email addresses. |
detectEmailAggressive | 0.75 | Obfuscated formats, e.g. user [at] example [dot] com. |
detectIpv4 | 0.98 | Dotted-decimal IPv4 with optional CIDR notation. |
detectIpv6 | 0.98 | Full and compressed IPv6 addresses. |
detectUrl | 0.95 | http and https URLs with paths, query strings, and fragments. |
detectApiKey | — | Common API key patterns (hex strings, Bearer tokens, sk-/pk-/ghp_-prefixed keys, etc.). |
detectSocialMedia | — | Social media handles (@username) and profile URL patterns. |
Phone & Identity Numbers
| Function | Confidence | Notes |
|---|---|---|
detectPhone | 0.90 | North American + E.164 international formats. |
detectPhoneAggressive | 0.70 | 7-digit local formats (e.g. 555-1234). |
detectSsn | 0.95 | US Social Security Numbers with format and known-invalid range exclusions. |
detectSsnAggressive | 0.80 | Expanded SSN pattern set. |
Financial
| Function | Confidence | Notes |
|---|---|---|
detectCreditCard | 0.97 | 13–19 digit card numbers validated with the Luhn algorithm. |
detectCreditCardAggressive | 0.80 | Also catches masked formats ****-****-****-1234. |
detectIban | 0.99 | IBAN strings validated with the ISO 13616 MOD-97 algorithm. |
detectBankAccount | — | Common bank account number formats. |
detectCryptocurrency | — | Bitcoin, Ethereum, and other common cryptocurrency wallet addresses. |
detectTaxId | — | US EIN and common international tax identification number formats. |
Personal Information
| Function | Confidence | Notes |
|---|---|---|
detectName | 0.75 | Heuristic: catches names preceded by greeting/salutation keywords (Dear, Hi, Hello, To, From, Patient, Client, Defendant, etc.). Not an NLP-based named-entity recogniser. |
detectNameAggressive | 0.65 | Extends detectName with title-prefix patterns (Mr., Mrs., Ms., Dr., Prof.). |
detectDateOfBirth | 0.78–0.88 | ISO 8601, US (MM/DD/YYYY), European (DD/MM/YYYY), and long-form date patterns. |
detectAddress | — | Multi-line postal address patterns (street number, city, state/zip). |
detectPassport | — | Passport number formats for major issuing countries. |
detectDriversLicense | — | US and international driver's licence number patterns. |
detectNationalId | — | National identity document numbers (SSN-adjacent, Aadhaar, NINO, etc.). |
Healthcare
| Function | Notes |
|---|---|
detectMedicalRecord | Medical record number (MRN) patterns. |
detectHealthInsurance | Health insurance member ID and policy number patterns. |
detectPrescription | Prescription and DEA registration number patterns. |
Vehicles & Transportation
| Function | Notes |
|---|---|
detectVin | 17-character Vehicle Identification Numbers validated with the ISO 3779 mod-11 checksum. |
detectVinAggressive | Expanded VIN pattern set for partial or obfuscated VINs. |
detectLicensePlate | Common licence plate formats across multiple countries. |
detectTrackingNumber | Shipping tracking numbers (UPS, FedEx, USPS, DHL formats). |
Government & Legal
| Function | Notes |
|---|---|
detectCaseNumber | Court case number formats (YYYY-CV-NNNNN and variants). |
detectCompanyRegistration | Company registration and incorporation number formats. |
Registries
-
DETECTOR_REGISTRY— Pre-assembledRecord<PiiCategory, Detector>using all standard-confidence detectors. Keyed byPiiCategory. -
AGGRESSIVE_DETECTOR_REGISTRY— Pre-assembled registry using every available aggressive variant in place of its standard counterpart. Enables detection of obfuscated or partial PII at the cost of a higher false-positive rate.
AnonymizeOptions Reference
| Option | Type | Default | Description |
|---|---|---|---|
rules | AnonymizationRule[] | [] | Per-category strategy overrides. When non-empty, only listed categories are scanned. |
defaultStrategy | StrategyOptions | { strategy: "redact" } | Strategy applied to any category not covered by rules. |
includeMatches | boolean | false | Include the PiiMatch array in the result. |
customDetectors | Partial<Record<PiiCategory, Detector>> | — | Replace built-in detectors on a per-category basis. |
customPatterns | CustomPattern[] | — | Ad-hoc RegExp patterns merged into the detection pipeline. Matches participate in standard overlap deduplication. |
globalReplacement | string | — | Replace every detected entity with this exact string, overriding all strategy settings. |
consistentTokens | boolean | false | Map repeated identical PII values to the same token within a single call (e.g. EMAIL_1, EMAIL_1 for the same address appearing twice). Different values get different counters. |
aggressive | boolean | false | Switch to AGGRESSIVE_DETECTOR_REGISTRY for all built-in categories. |
enabledCategories | Partial<Record<PiiCategory, boolean>> | — | Convenience boolean map. Only categories set to true are active; rules takes precedence for categories it covers. |
allowlist | string[] | [] | Exact values to never anonymize (case-insensitive by default). |
allowlistPatterns | RegExp[] | [] | Regular expressions matched against detected values; matches are skipped. |
allowlistCaseSensitive | boolean | false | Make allowlist string matching case-sensitive. |
confidenceThreshold | number | 0 | Minimum confidence score [0, 1] for a match to be anonymized. |
preset | CompliancePreset | — | Apply a compliance preset as the base configuration. Explicit rules and defaultStrategy take precedence. |
locales | Locale[] | ["global"] | Activate locale-specific detector patterns. Values: "global", "us", "uk", "eu", "ca", "au", "br", "in", "cn", "jp", "kr", "za". |
Error Classes ("anonyma")
All errors extend AnonymaError and carry a machine-readable code string, enabling
precise switch/instanceof error handling.
| Class | Code | Extra Properties | When Thrown |
|---|---|---|---|
AnonymaError | — | code: string | Base class; never thrown directly. |
ValidationError | VALIDATION_ERROR | field: string | A function argument fails validation (wrong type, out-of-range value, etc.). |
UnsupportedStrategyError | UNSUPPORTED_STRATEGY | strategy: string | An unrecognised strategy name is passed. |
UnknownCategoryError | UNKNOWN_CATEGORY | category: string | A rule or config references an unknown PII category. |
CryptoNotAvailableError | CRYPTO_NOT_AVAILABLE | — | globalThis.crypto.subtle is absent (Node < 18 or no polyfill). |
EncryptionError | ENCRYPTION_ERROR | operation: "encrypt" | "decrypt" | The underlying AES-GCM operation fails (wrong key, corrupt ciphertext, etc.). |
PresetNotFoundError | PRESET_NOT_FOUND | preset: string | getPreset() is called with an unknown preset name. |
AllowlistMatchError | ALLOWLIST_MATCH_ERROR | field: string | An allowlist configuration entry is malformed. |
BatchProcessingError | BATCH_PROCESSING_ERROR | succeeded, failed, total: number | One or more items in a batch fail; carries partial result counts. |
Streaming API ("anonyma/stream")
Requires the WHATWG Streams API: Node.js ≥ 18 (native global TransformStream) or a
browser with Streams API support. Throws ValidationError if TransformStream is
unavailable.
-
createAnonymizeStream(options?)— Returns aTransformStream<string, AnonymizeResult>that anonymizes each string chunk synchronously. Input chunks must be complete strings (e.g. individual lines); partial-chunk reassembly is the caller's responsibility. -
createAnonymizeStreamAsync(options?)— Async variant that usesanonymizeAsync()internally. Supportshash,encrypt, and all other async strategies within a stream pipeline. -
createTokenizeStream(options?)— Returns aTransformStream<string, TokenizeResult>that tokenizes each chunk independently. Each chunk receives its own token counter sequence; for a shared token map across chunks, manage tokenization externally.
Checksum Validators ("anonyma/validators")
Pure validation functions for PII checksum and format algorithms. All accept a string and
return boolean.
| Function | Algorithm / Standard | Notes |
|---|---|---|
luhn(digits) | Luhn (ISO/IEC 7812) | Credit/debit card numbers and some national IDs. |
verhoeff(digits) | Verhoeff | Indian Aadhaar numbers and some other national IDs. |
nhsMod11(value) | NHS mod-11 | UK NHS 10-digit numbers (with or without spaces/hyphens). |
cpfChecksum(value) | Brazilian CPF | 11-digit CPF with two check digits; rejects all-same-digit sequences. |
vinChecksum(vin) | ISO 3779 mod-11 | 17-character Vehicle Identification Numbers. |
deaChecksum(value) | DEA mod-10 | US Drug Enforcement Administration registration numbers. |
ibanMod97(value) | ISO 13616 mod-97 | IBAN strings (15–34 characters, with or without spaces). |
ninoValid(value) | UK NINO format | UK National Insurance Numbers; rejects invalid letter prefixes. |
aadhaarFormat(value) | Aadhaar format | 12-digit Indian Aadhaar; does not start with 0 or 1. |
Encryption Utilities ("anonyma/crypto")
Standalone re-export of the AES-GCM primitives for callers that need raw encrypt/decrypt access without the full anonymization pipeline.
encrypt(value, options)— AES-256-GCM encryption. Acceptspassphrase(PBKDF2- derived,anonyma_kdf_v1salt, 100,000 iterations) or rawkeyBytes(16 or 32 bytes). Output:"<encoding>:<iv>:<ciphertext>"(base64orhex).decrypt(ciphertext, options)— Decrypts a value produced byencrypt(). Must use the samepassphraseorkeyBytes.EncryptOptionstype is also exported from this subpath.
Zod Schemas & AI / MCP Definitions ("anonyma/schemas")
Requires zod as a peer dependency. Import from "anonyma/schemas".
Zod Schemas
| Export | Validates |
|---|---|
PiiCategorySchema | All 27 PiiCategory string literals. |
MaskOptionsSchema | MaskOptions including maskChar, keepLeading, keepTrailing. |
RedactOptionsSchema | RedactOptions with label. |
PseudonymizeOptionsSchema | PseudonymizeOptions with seed and prefix. |
HashOptionsSchema | HashOptions with truncate and pepper. |
GeneralizeOptionsSchema | GeneralizeOptions with bucketSize. |
StrategyOptionsSchema | Discriminated union of all strategy option shapes. |
PiiMatchSchema | PiiMatch output object. |
AnonymizeResultSchema | AnonymizeResult with text and matches. |
AnonymizationRuleSchema | Single { category, strategy } rule. |
CustomPatternSchema | CustomPattern with pattern (RegExp instance), category, confidence, label. |
AnonymizeOptionsSchema | Full AnonymizeOptions input object. |
FieldRuleSchema | Single field-level { strategy } rule. |
FieldRuleMapSchema | Record<string, FieldRule> for anonymizeRecord(). |
OpenAI / MCP Tool Definitions
Pre-built OpenAiFunctionDefinition objects ready to pass to the OpenAI client's
tools array or an MCP server's tool registry:
ANONYMIZE_TOOL_DEFINITION— Function definition foranonymize().DETECT_TOOL_DEFINITION— Function definition fordetect().HAS_PII_TOOL_DEFINITION— Function definition forhasPII().ANONYMIZE_OBJECT_TOOL_DEFINITION— Function definition foranonymizeObject().
Capability Manifest
ANONYMA_MANIFEST— Machine-readableas constobject describing all capabilities, supported categories, strategy descriptions, and option keys. Intended for inclusion in AI agent system prompts so models can self-discover available tools.
Inferred TypeScript Types
All Zod schema input/output types are re-exported as TypeScript types:
PiiCategoryInput, StrategyOptionsInput, AnonymizeOptionsInput,
AnonymizationRuleInput, CustomPatternInput, PiiMatchOutput,
AnonymizeResultOutput, FieldRuleInput, FieldRuleMapInput.
TypeScript Types ("anonyma")
All types are zero-cost, type-only exports (stripped by tsc; no runtime overhead).
| Type | Description |
|---|---|
PiiCategory | Union of all 27 supported category string literals. |
PiiMatch | { category, value, start, end, confidence } — a single detected PII entity. |
CustomPattern | { pattern: RegExp; category?; confidence?; label? } — ad-hoc detection pattern. |
Locale | "global" | "us" | "uk" | "eu" | "ca" | "au" | "br" | "in" | "cn" | "jp" | "kr" | "za" |
CompliancePreset | "gdpr" | "hipaa" | "ccpa" | "pci-dss" | "sox" | "ferpa" |
StrategyName | "mask" | "redact" | "pseudonymize" | "hash" | "generalize" | "tokenize" | "encrypt" | "synthesize" |
StrategyOptions | Discriminated union of all per-strategy option shapes. |
MaskOptions | { maskChar?, keepLeading?, keepTrailing?, preserveFormat? } |
RedactOptions | { label? } |
PseudonymizeOptions | { seed?, prefix? } |
HashOptions | { truncate?, pepper? } |
GeneralizeOptions | { bucketSize? } |
EncryptOptions | { passphrase?, keyBytes?, encoding? } |
SynthesizeOptions | { seed?, locale? } |
AnonymizationRule | { category: PiiCategory, strategy: StrategyOptions } |
AnonymizeOptions | Full options accepted by anonymize() and anonymizeAsync(). |
AnonymizeResult | { text: string, matches: ReadonlyArray<PiiMatch> } |
TokenFormat | "angle" | "bracket" | "custom" |
TokenizeOptions | Options for tokenize() including categories, format, tokenTemplate, deterministic, aggressive, locales, confidenceThreshold, allowlist. |
TokenizeResult | { text, mapping: ReadonlyMap<string, string>, tokens: TokenMatch[] } |
DetokenizeResult | { text, replacedCount, unresolved: string[] } |
TokenMatch | { token, original, category, start, end } |
BatchResult<T> | Discriminated union: { index, ok: true, value: T } | { index, ok: false, error: Error } |
FieldRule | { strategy: StrategyOptions } |
FieldRuleMap | Record<string, FieldRule> — dot-notation paths for anonymizeRecord(). |
Detector | (text: string) => PiiMatch[] — detector function signature. |
DetectorRegistry | Record<PiiCategory, Detector> |
Anonymizer | Interface returned by createAnonymizer(). |
AnonymizerConfig | Config accepted by createAnonymizer(). |
AnonymaPlugin | { name, detectors?, strategies?, validators? } — plugin extension point. |
ValidatorFunction | (value: string) => boolean |
StrategyFunction | (value: string, options?) => string |
PresetConfig | Full configuration shape for a compliance preset. |
Package & Infrastructure
- Dual ESM + CJS output via
tsupwithsideEffects: falsefor full tree-shaking support in all bundlers. - Full TypeScript declarations —
.d.ts+.d.ctsfiles generated for every subpath. - Six subpath exports:
"anonyma","anonyma/detectors","anonyma/schemas","anonyma/validators","anonyma/crypto","anonyma/stream". - Zero runtime dependencies — the main package and all subpaths except
"anonyma/schemas"have no external dependencies."anonyma/schemas"requireszodas a peer dependency. - GitHub Actions CI — lint (
eslint), typecheck (tsc --noEmit), test, and build on Node.js 18, 20, and 22. - GitHub Actions Release — automated npm publish with provenance on version tag push.
- Vitest test suite with ≥ 90% coverage target across statements, branches, and functions.
- ESLint flat config (v9) with strict TypeScript rules.
- Prettier code formatting.
- MIT License.