data-mask-policy
data-mask-policy is a policy-driven library for masking PII and redacting structured data in Node.js, TypeScript, and Python. Give it a record and a JSON policy, and it returns a sanitized copy. A rule can mask an email in every item of an array, redact a customer identifier, or remove an access token before the record leaves your application.
Use it at the point where an API response, structured log, data export, or AI tool payload is about to be shared. For example, a support API can keep a transaction reference and show only the last four digits of a card number. A policy with an explicit field allowlist also drops internal fields added later.
Define the policy once and reuse it across requests and services. Both implementations accept the same JSON policy format and run locally with zero runtime dependencies.
Install · Industry use cases · JavaScript and TypeScript API · Python API · Documentation links
Install
Install with your package manager.
npm install data-mask-policy
python -m pip install data-mask-policy
The JavaScript package supports Node.js 22, 24, and 26 with ESM, CommonJS, and TypeScript declarations. The Python package supports CPython 3.10–3.14. Versioned distributions and checksums are also available on the GitHub release.
If you downloaded a package from the GitHub release, install it from your download directory. npm tarball · Python wheel
npm install ./data-mask-policy-0.1.0.tgz
python -m pip install ./data_mask_policy-0.1.0-py3-none-any.whl
Quick start
import { createMasker, maskEmail } from 'data-mask-policy';
console.log(maskEmail('demo@example.test')); // d***@example.test
const masker = createMasker({
schemaVersion: 1,
defaultAction: 'remove',
allowPaths: ['orders[*].id', 'orders[*].email'],
rules: [{ id: 'contact', path: 'orders[*].email', strategy: 'email' }],
});
console.log(masker.apply({ orders: [{ id: 7, email: 'demo@example.test', internal: 'synthetic' }] }));
// { orders: [{ id: 7, email: 'd***@example.test' }] }
from data_mask_policy import create_masker, mask_email
print(mask_email("demo@example.test")) # d***@example.test
masker = create_masker({
"schemaVersion": 1,
"defaultAction": "remove",
"allowPaths": ["orders[*].id", "orders[*].email"],
"rules": [{"id": "contact", "path": "orders[*].email", "strategy": "email"}],
})
print(masker.apply({"orders": [{"id": 7, "email": "demo@example.test", "internal": "synthetic"}]}))
# {'orders': [{'id': 7, 'email': 'd***@example.test'}]}
CommonJS uses synchronous require('data-mask-policy'). TypeScript exports types for both module systems. Python ships a typed, pure-Python wheel.
Industry use cases
The banking, healthcare, e-commerce, and SaaS sections below include copy-and-run snippets. The industry guide gives a Node.js and Python command for each of the 20 policies, with synthetic input and verified output.
Read the full industry use case guide · Open the runnable JSON fixtures
Fields you can mask by industry
These rows show the exact field names used by the runnable examples. In your own payload, set path to the field you want to protect. For nested data, you can use a path like orders[*].email to mask the email in every order.
| Industry | Field to protect | Strategy | Protected field in output | Field kept |
|---|---|---|---|---|
| Banking and financial services | cardNumber |
card |
***1234 |
transactionRef |
| Insurance | beneficiaryName |
redact |
[REDACTED] |
claimRef |
| Healthcare | patientId |
redact |
[REDACTED] |
appointmentStatus |
| E-commerce | email |
email |
d***@example.test |
orderId |
| Retail | loyaltyId |
identifier |
***0123 |
activity |
| Human resources | salary |
redact for roles outside authorized HR |
[REDACTED] |
jobFamily |
| Recruitment | candidatePhone |
remove |
Field omitted | stage |
| Education | studentId |
identifier |
***0123 |
enrollmentStatus |
| Travel | passport |
passport |
***001 |
bookingRef |
| Hospitality | guestEmail |
remove |
Field omitted | roomStatus |
| Government and public services | citizenId |
redact |
[REDACTED] |
status |
| Telecommunications | subscriberRef |
identifier |
***0123 |
activation |
| Manufacturing | contractPrice |
replace |
withheld |
lineStatus |
| Logistics | deliveryAddress |
remove |
Field omitted | shipmentStatus |
| Legal services | clientName |
redact |
[REDACTED] |
matterStatus |
| Real estate | ownerContact |
remove |
Field omitted | listingStatus |
| SaaS | token |
remove |
Field omitted | incident |
| Cybersecurity | authorization |
redact |
[REDACTED] |
event |
| Data analytics | userIp |
ip |
*** |
eventType |
| AI agents | customerEmail |
remove |
Field omitted | action |
Banking and financial services
A customer support receipt needs the transaction reference and the last four digits of the card. This policy permits those two fields and masks the card number. The internal processor note is dropped because the allowlist excludes it. The input below is synthetic.
Node.js
After installing the package, save this as receipt.mjs and run node receipt.mjs.
import { createMasker } from 'data-mask-policy';
const receiptMasker = createMasker({
schemaVersion: 1,
defaultAction: 'remove',
allowPaths: ['transactionRef', 'cardNumber'],
rules: [{ id: 'mask-card', path: 'cardNumber', strategy: 'card', required: true }],
});
const receipt = {
transactionRef: 'TX-DEMO-1',
cardNumber: '0000000000001234',
processorNote: 'synthetic internal detail',
};
console.log(JSON.stringify(receiptMasker.apply(receipt)));
// {"transactionRef":"TX-DEMO-1","cardNumber":"***1234"}
Python
Save this as receipt.py and run python receipt.py after installing the Python package.
import json
from data_mask_policy import create_masker
receipt_masker = create_masker({
"schemaVersion": 1,
"defaultAction": "remove",
"allowPaths": ["transactionRef", "cardNumber"],
"rules": [{"id": "mask-card", "path": "cardNumber", "strategy": "card", "required": True}],
})
receipt = {
"transactionRef": "TX-DEMO-1",
"cardNumber": "0000000000001234",
"processorNote": "synthetic internal detail",
}
print(json.dumps(receipt_masker.apply(receipt), separators=(",", ":")))
# {"transactionRef":"TX-DEMO-1","cardNumber":"***1234"}
View the banking and financial services policy example
Insurance
Share the claim reference with an external review queue and replace the beneficiary name with [REDACTED]. View the insurance policy example
Healthcare
Apply this policy before exporting appointment status. It redacts the patient ID and excludes clinical notes from the result.
import { createMasker } from 'data-mask-policy';
const appointmentMasker = createMasker({
schemaVersion: 1,
defaultAction: 'remove',
allowPaths: ['appointmentStatus', 'patientId'],
rules: [{ id: 'redact-patient', path: 'patientId', strategy: 'redact' }],
});
const appointment = {
appointmentStatus: 'checked-in',
patientId: 'PAT-DEMO-7',
clinicalNotes: 'synthetic internal note',
};
console.log(JSON.stringify(appointmentMasker.apply(appointment)));
// {"appointmentStatus":"checked-in","patientId":"[REDACTED]"}
View the healthcare policy example
E-commerce
Use this policy on an order support response to keep the order ID and partially mask the customer email.
import json
from data_mask_policy import create_masker
order_masker = create_masker({
"schemaVersion": 1,
"defaultAction": "remove",
"allowPaths": ["orderId", "email"],
"rules": [{"id": "mask-email", "path": "email", "strategy": "email"}],
})
order = {"orderId": "ORDER-DEMO", "email": "demo@example.test", "internalNote": "synthetic"}
print(json.dumps(order_masker.apply(order), separators=(",", ":")))
# {"orderId":"ORDER-DEMO","email":"d***@example.test"}
View the e-commerce policy example
Retail
A loyalty kiosk can show points activity and the final four characters of a loyalty ID. The policy uses path to select loyaltyId, strategy to apply identifier masking, and options.visibleSuffix to set how many characters to show. The strict allowlist also keeps activity and excludes any other fields.
{
"schemaVersion": 1,
"defaultAction": "remove",
"allowPaths": [
"activity",
"loyaltyId"
],
"rules": [
{
"id": "mask-loyalty-id",
"path": "loyaltyId",
"strategy": "identifier",
"options": {
"visibleSuffix": 4,
"maskChar": "*"
}
}
]
}
With synthetic input {"activity":"points-earned","loyaltyId":"LOYALTY-0123","newInternalField":"synthetic internal detail"}, the result is {"activity":"points-earned","loyaltyId":"***0123"}.
Use the runnable Retail fixture from a checkout of this repository. View the retail policy example
Human resources
Keep job family in an employee view and redact salary when the authenticated role falls outside authorized HR. View the human resources policy example
Recruitment
Share a candidate's pipeline stage with the hiring panel and remove the candidate's phone number. View the recruitment policy example
Education
Send enrollment status to the program coordinator with a partial student reference. View the education policy example
Travel
Keep the booking reference for support and show only a short suffix of the passport number. View the travel policy example
Hospitality
Send room readiness to housekeeping and omit the guest email from that view. View the hospitality policy example
Government and public services
Show application stage to the service desk and redact citizen identifiers. View the government and public services policy example
Telecommunications
Show line activation status with a partially masked subscriber reference. View the telecommunications policy example
Manufacturing
Share production status with a vendor and replace the contract price with withheld. View the manufacturing policy example
Logistics
Send the shipment status to a warehouse display and omit the delivery address. View the logistics policy example
Legal services
Share matter status with billing and redact the client name. View the legal services policy example
Real estate
Export listing workflow status for reporting and remove the owner's contact field. View the real estate policy example
SaaS
Sanitize a tenant diagnostic record before sharing it with customer support. The policy keeps the incident ID and removes the access token.
import { createMasker } from 'data-mask-policy';
const diagnosticMasker = createMasker({
schemaVersion: 1,
defaultAction: 'remove',
allowPaths: ['incident', 'token'],
rules: [{ id: 'strip-token', path: 'token', strategy: 'remove' }],
});
const diagnostic = { incident: 'INC-DEMO', token: 'synthetic-access-token' };
console.log(JSON.stringify(diagnosticMasker.apply(diagnostic)));
// {"incident":"INC-DEMO"}
Cybersecurity
Keep the authentication event name and redact the authorization header before writing the structured log. View the cybersecurity policy example
Data analytics
Keep the event type and fully mask the source IP address before exporting a row. View the data analytics policy example
AI agents
Keep the tool action and remove the customer email before sending the tool result into a model request. View the AI agents policy example
JavaScript and TypeScript API
Import createMasker from data-mask-policy in Node.js. TypeScript declarations cover the policy, input, outputs, and typed errors. Use maskObject(data, policy) for a one-off call, or reuse createMasker(policy).apply(data) in a request handler. CommonJS consumers can use require('data-mask-policy'). Use applyWithReport when you need the masked value and aggregate diagnostics.
Open the JavaScript and TypeScript API reference
import { createMasker } from 'data-mask-policy';
const masker = createMasker({
schemaVersion: 1,
rules: [{ id: 'strip-token', path: 'token', strategy: 'remove' }],
});
const { data, report } = masker.applyWithReport({ id: 7, token: 'synthetic' });
console.log(data, report.removedFields); // { id: 7 } 1
Python API
Import create_masker from data_mask_policy. Use mask_object(data, policy) for a one-off call, or reuse create_masker(policy).apply(data, context=...) in a service or export job. apply_with_report returns the sanitized value and aggregate diagnostics. The package ships Python type information.
from data_mask_policy import create_masker
masker = create_masker({
"schemaVersion": 1,
"rules": [{"id": "strip-token", "path": "token", "strategy": "remove"}],
})
result = masker.apply_with_report({"id": 7, "token": "synthetic"})
print(result["data"], result["report"]["removedFields"]) # {'id': 7} 1
Policy reference
A policy declares schemaVersion: 1 and a list of rules. Each rule names a path, such as orders[*].email, and a strategy. Preserve mode carries unmatched fields through. Set defaultAction: "remove" and use allowPaths to keep only explicitly approved output fields. Use required rules to fail when a field must be present.
Context-aware masking
Use application-verified facts such as the role from an authenticated session. Read the context and precedence rules
import { createMasker } from 'data-mask-policy';
const payroll = createMasker({
schemaVersion: 1,
rules: [{
id: 'staff-salary',
path: 'salary',
strategy: 'redact',
required: true,
when: { field: 'role', operator: 'notEquals', value: 'authorized-hr' },
}],
});
console.log(payroll.apply({ salary: 120000 }, { context: { role: 'support' } }));
// { salary: '[REDACTED]' }
Comparisons fail closed if a required context attribute is missing. Python passes the same context with apply(record, context=...).
JSON Schema
Use the Draft 2020-12 schema in an editor or CI check to catch malformed policy documents. The runtime adds validation for rule overlap, path restrictions, registered strategies, and configured limits.
Shared semantics
A policy uses the same field-path grammar, conditions, strategy options, and precedence in both runtimes. Array indexes refer to the original input. Active rules that match the same target require distinct priorities, and the highest priority wins. Required matches, strict projection, and missing trusted context follow the same rules in JavaScript and Python.
Read the shared policy semantics
Masking strategies
Use redact to replace a value with a redaction marker, remove to drop a field, and replace to substitute a constant. Full, partial, prefix, and suffix masking control how much of a value stays visible. Email, phone, card, name, identifier, account, IP, and regional presets provide field-specific defaults.
See the masking strategy options and defaults
| Masking option | What it controls |
|---|---|
visiblePrefix and visibleSuffix |
Characters to keep at the start and end for strategies that support visible characters, such as identifier and partial. |
maskChar |
The character that replaces hidden text. Defaults to *. |
maskLength or preserveLength |
A fixed mask length or one replacement character for each hidden character. |
replacement |
The constant to use with replace, or an optional text marker with redact. |
invalidInput |
For text strategies, redact an invalid value or raise a typed error. |
Trusted custom strategies
See custom strategies and typed errors.
from data_mask_policy import create_masker
def public_reference(value, options):
if not isinstance(value, str) or len(value) <= 3:
return "[REDACTED]"
return options["prefix"] + "***" + value[-3:]
custom = create_masker({
"schemaVersion": 1,
"rules": [{"id": "reference", "path": "ref", "strategy": "public-ref", "options": {"prefix": "REF-"}}],
}, strategies={"public-ref": public_reference})
print(custom.apply({"ref": "DEMO0123"})) # {'ref': 'REF-***123'}
Framework integrations
Compile the policy during startup and apply it just before sending an API response, logging an event, exporting a row, or submitting structured data to a model. The runnable examples cover Express, Fastify, NestJS, Next.js, GraphQL, and Pino on Node.js, plus FastAPI, Django, Flask, Pandas, and PySpark in Python. Use application-verified context for role-based rules.
Open the framework integration guide
Apply a policy at an HTTP response boundary
- List the fields the destination actually needs and choose a default action. Use strict projection for a public API, outbound event, or other fixed output contract.
- Compile the policy once at startup. Pass trusted request context only when a rule needs it.
- Apply the policy before serializing a response, writing a log, exporting a row, or sending structured data to an AI tool.
- If masking fails, stop the response or export. Test the expected output with synthetic records, including a record with a new field and a record with missing context.
The following Node.js example adapts a compiled masker to an HTTP response. For an Express or Fastify app, use the same boundary before your framework writes the JSON body. See the JavaScript framework examples
import { createMasker, MaskError } from 'data-mask-policy';
const outbound = createMasker({
schemaVersion: 1,
defaultAction: 'remove',
allowPaths: ['id', 'email'],
rules: [{ id: 'mask-email', path: 'email', strategy: 'email', required: true }],
});
function serializeCustomer(record) {
try {
const safe = outbound.apply(record);
return { statusCode: 200, body: JSON.stringify(safe) };
} catch (error) {
if (!(error instanceof MaskError)) throw error;
return { statusCode: 500, body: '{"error":"masking_failed"}' };
}
}
console.log(serializeCustomer({ id: 7, email: 'demo@example.test', token: 'synthetic' }));
// { statusCode: 200, body: '{"id":7,"email":"d***@example.test"}' }
Performance measurements
The benchmark report records median and tail latency for single values, compiled policy reuse, strict projection, diagnostic reports, and batches. The compiled one-record benchmark measured a median of 31.5 µs on Node.js and 92.0 µs on CPython in the documented test environment. Use the benchmark scripts to measure your own payload shapes and policy sizes.
See the benchmark results and how to reproduce them
Troubleshooting
For INVALID_CONTEXT, check that the application supplies the expected trusted attributes. For MISSING_REQUIRED_FIELD, check the path against a synthetic copy of the expected record shape. If strict projection removes a field you expected, review the allowlist and matched-rule report. Return a controlled error when masking fails.
Look up error codes and troubleshooting steps
Architecture
The TypeScript and Python engines compile the same JSON policy format into reusable maskers. They resolve paths and trusted conditions, apply the configured transformations, and return a separate sanitized value. The shared fixtures compare output and error codes across the two engines.
Read how the two policy engines are structured
Adoption guide
Start with one outbound flow, such as support responses or structured logs. Inventory its fields, define the output allowlist, and add synthetic fixtures for ordinary and elevated roles, missing fields, and newly added fields. Store the policy with the service and reuse the fixture suite wherever the policy runs.
Security boundaries
Apply masking before a payload reaches a logger, serializer, export, or external provider. Keep authorization in the host application and pass verified context to policy rules. Review custom strategies as application code and keep identifying data out of rule IDs and diagnostics. Partially masked values can still identify people.
Review the security boundaries
Contributing
Use synthetic records in bug reports and tests. For policy behavior changes, add or update shared fixtures and run the documentation and conformance checks for both runtimes before opening a pull request.
Read the contribution and test instructions
Code of Conduct
Treat contributors respectfully, give constructive technical feedback, and protect people's privacy. Raise conduct concerns privately with a maintainer and keep personal details out of public issues.
Security reporting
Report vulnerabilities through GitHub's private vulnerability reporting form. Include the affected version, runtime, expected behavior, and a minimal synthetic reproduction. Keep credentials and customer data out of the report.
Read the security reporting policy · Open a private vulnerability report
MIT license
The MIT license permits use, modification, and redistribution, including in commercial software. Preserve the copyright and permission notice when distributing the software.
Author
Kotcherla Murali Krishna · mkkotcherla
Documentation links
- JavaScript and TypeScript API
- Python API
- Policy reference
- JSON Schema
- Shared semantics
- Masking strategies
- Industry use cases
- Framework integrations
- Performance measurements
- Troubleshooting
- Architecture
- Adoption guide
- Security boundaries
- Contributing
- Code of Conduct
- Security reporting
- MIT license
- Shared industry fixtures
Metadata
Release files for data-mask-policy 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| data_mask_policy-0.1.0.tar.gz | 32.4 kB | Without provenance | Details for data_mask_policy-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| data_mask_policy-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for data_mask_policy-0.1.0-py3-none-any.whl |
Total release size: 51.2 kB
Release files / data_mask_policy-0.1.0.tar.gz
| Download URL | data_mask_policy-0.1.0.tar.gz |
|---|---|
| Size | 32.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
31d967aa63836b244d96af1a9a453ce14cda7b6733ba11ad7b04a1a9a4a8dcbe
|
|
BLAKE2b-256 checksum How to use checksums |
073cfba5182f5cb83f1b7cf31db17096f170cf153af708241938e44c24ce5ca0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.8
|
Release files / data_mask_policy-0.1.0-py3-none-any.whl
| Download URL | data_mask_policy-0.1.0-py3-none-any.whl |
|---|---|
| Size | 18.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
52f6d3aa08068af480c877bffc7efeefd43fc86c976801674a9ff6a58a5d2871
|
|
BLAKE2b-256 checksum How to use checksums |
58fa9e646305eb215cc05f1b91616317f13ddaeece0e3fc8b231e53d2edbc188
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.8
|
Security for data-mask-policy 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.