Skip to main content

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-mcp 0.1.1: on Windows, anonyma-mcp-proxy and runStdioProxy() 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 on PATH with PATHEXT, as cmd.exe does, before it is started; a server found as an .exe or .com file now starts without a shell, and batch files such as npx.cmd still start through cmd.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 homepage is the site.

Fixed​

  • Bundlers no longer warn about the dynamic import that reaches Web Crypto on Node.js 18: it now carries webpackIgnore as well as @vite-ignore.
  • Documentation: the batch example passed concurrency as an option, which anonymizeBatchAsync() 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 rules list in the options of anonymize() 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 with compilePipeline() (#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, swedishPersonnummerChecksum and pixPayloadChecksum (CRC-16 of a PIX payload). CHECKSUMS names every validator, old and new, for declarative patterns.
  • Validating national-ID detection. detectNationalIdStrict() ("anonyma/detectors") and strictNationalIdDetector ("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 of compilePipeline() 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 within window words before it (three by default), or, with required, drops the hits that have none. A declarative pattern takes the same options as context, and the check digits it must pass as validator (a name from CHECKSUMS), in compilePipeline() 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() and compilePipeline(). 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 an AnonymaReceipt for 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() and sanitizeJsonTextAsync() ("anonyma/ai"): a JSON text sanitized without losing numbers that a JavaScript number cannot hold, such as 20-digit IDs, which JSON.parse would round. A text in which nothing was replaced comes back unchanged.
  • Receipts for outputs too large to hold in memory: issue() takes outputDigest (the SHA-256 of the output) in place of text, and counts in place of spans or matches.
  • VERSION, the version of the package, exported from "anonyma".
  • anonyma-cli 0.1.0, a new companion package: the anonyma command 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-5678 and +55 11 91234-5678 are found whole: 1.2.0 found no match in the first and replaced only +55 11 91234 in the second, leaving -5678 in 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 10 and Av. 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() and createPipelineStream() 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-ai and anonyma-mcp. 1.2.0 introduced them as @anonyma/vercel-ai and @anonyma/mcp, but the @anonyma scope is not available on npm, and they were never published under those names. Their folders (packages/vercel-ai, packages/mcp), APIs and the anonyma-mcp-proxy command 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 of anonyma, 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 the plugins of 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 (customDetectors take 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 a ValidationError when 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 an UnknownCategoryError for a detector or validator keyed by a name that is not a category. The standalone functions do not apply plugins.
  • Types PluginStrategyOptions and StrategyFunction, exported from "anonyma". AnonymizationRule, AnonymizeOptions, FieldRule and FieldRuleMap take an optional type parameter for the strategy options they hold, StrategyOptions by default.
  • Token vaults. AnonymaVault — any object with store(key, value) and retrieve(key), synchronous or asynchronous — InMemoryVault, and restore(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 }) and tokenizeAsync(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, format defaults to "brace".
  • createVaultTokenizer() ("anonyma/vault"): a tokenization provider backed by an AnonymaVault, 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}}) for tokenize(), 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 as wrangler deploy does, without nodejs_compat). CI runs them in a new runtimes job.
  • @anonyma/vercel-ai 0.1.0 (packages/vercel-ai): a typed AI SDK 7 middleware, withAnonyma() and drop-in generateText() / streamText(), tested against the real SDK.
  • @anonyma/mcp 0.1.0 (packages/mcp): a privacy guard for MCP connections, the anonyma-mcp-proxy command that puts any stdio MCP server behind it, and guardMcpClient() 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 new packages CI job.

Changed​

  • The methods of Anonymizer and AnonymizerConfig.defaultStrategy accept PluginStrategyOptions wherever they accepted StrategyOptions; the options of a built-in strategy are type-checked as before. An object that implements Anonymizer with parameter types of its own, such as a test double, may have to widen them.
  • createAnonymizer() throws UnsupportedStrategyError when defaultStrategy names a strategy that neither anonyma nor one of the plugins provides, instead of when it first applies it.
  • The optional zod peer dependency is ^3.25.4 || ^4.0.0 (was ^3.23.0). "anonyma/schemas" imports zod/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() and restoreFromLLM() 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), although wrapGenerate restored both.
  • sanitizeJson() and the LLM guard listed exempted members whose value is undefined or null as unscanned. The Vercel AI SDK sends providerOptions: undefined on every message, so an onSanitized hook 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​

  • allowlist skips a detected value only when the value equals an entry, as documented. Entries were matched as substrings, so allowlist: ["bob@example.com"] also left jimbob@example.com in the output of anonymize(), anonymizeAsync(), tokenize(), sanitizeForLLM() and the methods of createAnonymizer(); 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. allowlistPatterns still match a part of a value.
  • createAnonymizer().tokenize() matched allowlist entries as regular expressions: an entry containing ( threw a SyntaxError, and "x.y@example.com" also exempted "xzy@example.com".
  • allowlistPatterns with the g or y flag skipped only every other matching value, because RegExp.test() kept its lastIndex between values, and left the caller's pattern with a changed lastIndex. These flags are now ignored.

Added​

  • Plugins. createAnonymizer() applies the plugins of 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 (customDetectors take 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 a ValidationError when 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 an UnknownCategoryError for a detector or validator keyed by a name that is not a category. The standalone functions do not apply plugins.
  • Types PluginStrategyOptions and StrategyFunction, exported from "anonyma". AnonymizationRule, AnonymizeOptions, FieldRule and FieldRuleMap take an optional type parameter for the strategy options they hold, StrategyOptions by default.

Changed​

  • The methods of Anonymizer and AnonymizerConfig.defaultStrategy accept PluginStrategyOptions wherever they accepted StrategyOptions; the options of a built-in strategy are type-checked as before. An object that implements Anonymizer with parameter types of its own, such as a test double, may have to widen them.
  • createAnonymizer() throws UnsupportedStrategyError when defaultStrategy names 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 with instanceof.
  • The subpath exports are no longer experimental.
  • The warnings that anonymize() and anonymizeAsync() print for a strategy they do not apply name the span engine, which applies it, instead of anonymizeAsync(), 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() and compilePipeline() build a reusable pipeline with scan, test, transform and transformAsync. 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 throws AsyncStrategyError instead of substituting another strategy. createChunkTransformer() and createPipelineStream() 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), plus defineDetector(), defineRegexDetector() and fromLegacyDetector(). The 1.x detectors are available to the engine as LEGACY_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 lgpd and pipeda.
  • Error classes AsyncStrategyError, KeyManagementError, TokenVaultError, PolicyError and AuditIntegrityError, exported from "anonyma" like the others.
  • ./package.json in the export map.
  • Benchmark (npm run bench, bench/) and labelled detector corpora (tests/fixtures/corpus/).
  • Development dependencies fast-check, express and hono for property-based and integration tests.

Changed​

  • Preset hipaa also detects credit-card, iban, passport, license-plate and social-media; its description no longer claims to cover all 18 Safe Harbor identifiers. Preset ccpa also detects medical-record, health-insurance and api-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, so instanceof AnonymaError holds for errors thrown by any subpath. The dist/ layout gains chunk-*.js files.
  • PresetNotFoundError lists 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() and decrypt() on Node.js 18 threw because they read globalThis.crypto, which that runtime does not define. They now fall back to the Web Crypto implementation in node: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() with preserveFormat and the generic synthesize() 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 an Object.prototype member (constructor, toString, …).
  • The warning printed when anonymize() or anonymizeAsync() redacts a value whose rule is tokenize, encrypt or synthesize advised anonymizeAsync(), 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 is tokenize, encrypt or synthesize, with a warning, and the synchronous functions replace a hash rule with a seeded pseudonym. A pipeline from "anonyma/engine" applies every strategy.
  • createAnonymizer() does not apply plugins (AnonymaPlugin).
  • With preset set, anonymize() ignores enabledCategories; a pipeline can add categories to a preset.
  • tokenize() does not apply format: "custom" with tokenTemplate, nor deterministic: false, and no function applies locales.
  • AnonymizeOptionsSchema.parse() removes preset, allowlist, confidenceThreshold, locales and 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 of PiiMatch objects. An optional categories array restricts scanning to a subset; customDetectors override built-in detectors per category; aggressive: true switches to the expanded AGGRESSIVE_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 a console.warn; use anonymizeAsync() for those strategies.

  • anonymizeAsync(text, options?) — Fully async variant of anonymize(). Supports all eight strategies natively, including hash (SHA-256), encrypt (AES-GCM), tokenize, and synthesize.

  • anonymizeRecord(record, rules) — Field-level anonymization of plain objects. rules is a FieldRuleMap keyed 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 full anonymize() pipeline. Returns a deep clone — the original is never mutated. Detects circular references and throws ValidationError with 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 full detect() call when the answer is true.

  • createAnonymizer(config?) — Factory that produces a reusable Anonymizer instance with built-in configuration. Returned instances expose anonymize(), anonymizeAsync(), detect(), anonymizeRecord(), anonymizeObject(), tokenize(), and hasPII() — 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 } where mapping is a Map<token, originalValue>. Supports angle, bracket, and custom token formats; a tokenTemplate function can fully control the token shape.

  • tokenizeAsync(text, options?) — Async variant of tokenize().

  • detokenize(text, mapping) — Restore a tokenized string. Returns { text, replacedCount, unresolved } — tokens absent from the mapping are left unchanged and listed in unresolved so callers can detect data loss.


LLM Pipeline Helpers ("anonyma")​

  • sanitizeForLLM(text, options?) — Convenience wrapper around tokenize() with defaults tuned for large-language-model use (format: "bracket", aggressive mode off to minimise false-positive noise in prompts). Returns a TokenizeResult; pass the mapping to restoreFromLLM().

  • 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. Returns BatchResult<AnonymizeResult>[] with per-item ok / error discriminant.

  • anonymizeBatchAsync(texts, options?, concurrency?) — Async batch anonymization. Items run in parallel via Promise.allSettled. An optional concurrency cap 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. Returns BatchResult<PiiMatch[]>[].


Compliance Presets ("anonyma")​

  • getPreset(name) — Retrieve a PresetConfig by name. Throws PresetNotFoundError for 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:

PresetDefault StrategyCoverage
"gdpr"pseudonymizeAll personal data categories defined by the EU GDPR.
"hipaa"redactAll 18 HIPAA Safe Harbor identifiers for PHI de-identification.
"ccpa"redactConsumer 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"redactFinancial records and corporate officer identifiers for SOX audit trails.
"ferpa"redactStudent 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), and preserveFormat (format-preserving masking: letters become X, digits become 0, 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 a seed is 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 custom prefix (default "id_") is prepended.

  • generalize(value, options?) — Replace a numeric value with a bucket range. Default bucketSize of 10 turns 27 into "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, default 16) and pepper (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 a passphrase (key derived via PBKDF2 + SHA-256, 100,000 iterations) or raw keyBytes (16 or 32 bytes for AES-128/256). Output format: "<encoding>:<iv>:<ciphertext>" where both IV and payload are encoded as base64 (default) or hex. 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 for email, 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-number and case-number.

  • tokenize (as a strategy) — When strategy: "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-level tokenize() 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

FunctionConfidenceNotes
detectEmail0.99RFC 5321 email addresses.
detectEmailAggressive0.75Obfuscated formats, e.g. user [at] example [dot] com.
detectIpv40.98Dotted-decimal IPv4 with optional CIDR notation.
detectIpv60.98Full and compressed IPv6 addresses.
detectUrl0.95http 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

FunctionConfidenceNotes
detectPhone0.90North American + E.164 international formats.
detectPhoneAggressive0.707-digit local formats (e.g. 555-1234).
detectSsn0.95US Social Security Numbers with format and known-invalid range exclusions.
detectSsnAggressive0.80Expanded SSN pattern set.

Financial

FunctionConfidenceNotes
detectCreditCard0.9713–19 digit card numbers validated with the Luhn algorithm.
detectCreditCardAggressive0.80Also catches masked formats ****-****-****-1234.
detectIban0.99IBAN 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

FunctionConfidenceNotes
detectName0.75Heuristic: catches names preceded by greeting/salutation keywords (Dear, Hi, Hello, To, From, Patient, Client, Defendant, etc.). Not an NLP-based named-entity recogniser.
detectNameAggressive0.65Extends detectName with title-prefix patterns (Mr., Mrs., Ms., Dr., Prof.).
detectDateOfBirth0.78–0.88ISO 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

FunctionNotes
detectMedicalRecordMedical record number (MRN) patterns.
detectHealthInsuranceHealth insurance member ID and policy number patterns.
detectPrescriptionPrescription and DEA registration number patterns.

Vehicles & Transportation

FunctionNotes
detectVin17-character Vehicle Identification Numbers validated with the ISO 3779 mod-11 checksum.
detectVinAggressiveExpanded VIN pattern set for partial or obfuscated VINs.
detectLicensePlateCommon licence plate formats across multiple countries.
detectTrackingNumberShipping tracking numbers (UPS, FedEx, USPS, DHL formats).

Government & Legal

FunctionNotes
detectCaseNumberCourt case number formats (YYYY-CV-NNNNN and variants).
detectCompanyRegistrationCompany registration and incorporation number formats.

Registries

  • DETECTOR_REGISTRY — Pre-assembled Record<PiiCategory, Detector> using all standard-confidence detectors. Keyed by PiiCategory.

  • 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​

OptionTypeDefaultDescription
rulesAnonymizationRule[][]Per-category strategy overrides. When non-empty, only listed categories are scanned.
defaultStrategyStrategyOptions{ strategy: "redact" }Strategy applied to any category not covered by rules.
includeMatchesbooleanfalseInclude the PiiMatch array in the result.
customDetectorsPartial<Record<PiiCategory, Detector>>—Replace built-in detectors on a per-category basis.
customPatternsCustomPattern[]—Ad-hoc RegExp patterns merged into the detection pipeline. Matches participate in standard overlap deduplication.
globalReplacementstring—Replace every detected entity with this exact string, overriding all strategy settings.
consistentTokensbooleanfalseMap 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.
aggressivebooleanfalseSwitch to AGGRESSIVE_DETECTOR_REGISTRY for all built-in categories.
enabledCategoriesPartial<Record<PiiCategory, boolean>>—Convenience boolean map. Only categories set to true are active; rules takes precedence for categories it covers.
allowliststring[][]Exact values to never anonymize (case-insensitive by default).
allowlistPatternsRegExp[][]Regular expressions matched against detected values; matches are skipped.
allowlistCaseSensitivebooleanfalseMake allowlist string matching case-sensitive.
confidenceThresholdnumber0Minimum confidence score [0, 1] for a match to be anonymized.
presetCompliancePreset—Apply a compliance preset as the base configuration. Explicit rules and defaultStrategy take precedence.
localesLocale[]["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.

ClassCodeExtra PropertiesWhen Thrown
AnonymaError—code: stringBase class; never thrown directly.
ValidationErrorVALIDATION_ERRORfield: stringA function argument fails validation (wrong type, out-of-range value, etc.).
UnsupportedStrategyErrorUNSUPPORTED_STRATEGYstrategy: stringAn unrecognised strategy name is passed.
UnknownCategoryErrorUNKNOWN_CATEGORYcategory: stringA rule or config references an unknown PII category.
CryptoNotAvailableErrorCRYPTO_NOT_AVAILABLE—globalThis.crypto.subtle is absent (Node < 18 or no polyfill).
EncryptionErrorENCRYPTION_ERRORoperation: "encrypt" | "decrypt"The underlying AES-GCM operation fails (wrong key, corrupt ciphertext, etc.).
PresetNotFoundErrorPRESET_NOT_FOUNDpreset: stringgetPreset() is called with an unknown preset name.
AllowlistMatchErrorALLOWLIST_MATCH_ERRORfield: stringAn allowlist configuration entry is malformed.
BatchProcessingErrorBATCH_PROCESSING_ERRORsucceeded, failed, total: numberOne 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 a TransformStream<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 uses anonymizeAsync() internally. Supports hash, encrypt, and all other async strategies within a stream pipeline.

  • createTokenizeStream(options?) — Returns a TransformStream<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.

FunctionAlgorithm / StandardNotes
luhn(digits)Luhn (ISO/IEC 7812)Credit/debit card numbers and some national IDs.
verhoeff(digits)VerhoeffIndian Aadhaar numbers and some other national IDs.
nhsMod11(value)NHS mod-11UK NHS 10-digit numbers (with or without spaces/hyphens).
cpfChecksum(value)Brazilian CPF11-digit CPF with two check digits; rejects all-same-digit sequences.
vinChecksum(vin)ISO 3779 mod-1117-character Vehicle Identification Numbers.
deaChecksum(value)DEA mod-10US Drug Enforcement Administration registration numbers.
ibanMod97(value)ISO 13616 mod-97IBAN strings (15–34 characters, with or without spaces).
ninoValid(value)UK NINO formatUK National Insurance Numbers; rejects invalid letter prefixes.
aadhaarFormat(value)Aadhaar format12-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. Accepts passphrase (PBKDF2- derived, anonyma_kdf_v1 salt, 100,000 iterations) or raw keyBytes (16 or 32 bytes). Output: "<encoding>:<iv>:<ciphertext>" (base64 or hex).
  • decrypt(ciphertext, options) — Decrypts a value produced by encrypt(). Must use the same passphrase or keyBytes.
  • EncryptOptions type 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

ExportValidates
PiiCategorySchemaAll 27 PiiCategory string literals.
MaskOptionsSchemaMaskOptions including maskChar, keepLeading, keepTrailing.
RedactOptionsSchemaRedactOptions with label.
PseudonymizeOptionsSchemaPseudonymizeOptions with seed and prefix.
HashOptionsSchemaHashOptions with truncate and pepper.
GeneralizeOptionsSchemaGeneralizeOptions with bucketSize.
StrategyOptionsSchemaDiscriminated union of all strategy option shapes.
PiiMatchSchemaPiiMatch output object.
AnonymizeResultSchemaAnonymizeResult with text and matches.
AnonymizationRuleSchemaSingle { category, strategy } rule.
CustomPatternSchemaCustomPattern with pattern (RegExp instance), category, confidence, label.
AnonymizeOptionsSchemaFull AnonymizeOptions input object.
FieldRuleSchemaSingle field-level { strategy } rule.
FieldRuleMapSchemaRecord<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 for anonymize().
  • DETECT_TOOL_DEFINITION — Function definition for detect().
  • HAS_PII_TOOL_DEFINITION — Function definition for hasPII().
  • ANONYMIZE_OBJECT_TOOL_DEFINITION — Function definition for anonymizeObject().

Capability Manifest

  • ANONYMA_MANIFEST — Machine-readable as const object 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).

TypeDescription
PiiCategoryUnion 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"
StrategyOptionsDiscriminated 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 }
AnonymizeOptionsFull options accepted by anonymize() and anonymizeAsync().
AnonymizeResult{ text: string, matches: ReadonlyArray<PiiMatch> }
TokenFormat"angle" | "bracket" | "custom"
TokenizeOptionsOptions 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 }
FieldRuleMapRecord<string, FieldRule> — dot-notation paths for anonymizeRecord().
Detector(text: string) => PiiMatch[] — detector function signature.
DetectorRegistryRecord<PiiCategory, Detector>
AnonymizerInterface returned by createAnonymizer().
AnonymizerConfigConfig accepted by createAnonymizer().
AnonymaPlugin{ name, detectors?, strategies?, validators? } — plugin extension point.
ValidatorFunction(value: string) => boolean
StrategyFunction(value: string, options?) => string
PresetConfigFull configuration shape for a compliance preset.

Package & Infrastructure​

  • Dual ESM + CJS output via tsup with sideEffects: false for full tree-shaking support in all bundlers.
  • Full TypeScript declarations — .d.ts + .d.cts files 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" requires zod as 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.