mask-privacy 1.0.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +179 -22
  3. package/dist/index.d.mts +283 -62
  4. package/dist/index.d.ts +283 -62
  5. package/dist/index.js +6295 -5517
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +6281 -5497
  8. package/dist/index.mjs.map +1 -1
  9. package/examples/test_local_nlp.ts +21 -0
  10. package/jest.config.js +1 -0
  11. package/package.json +28 -13
  12. package/src/cli.ts +79 -0
  13. package/src/client.ts +70 -39
  14. package/src/config.ts +75 -0
  15. package/src/core/crypto.ts +158 -39
  16. package/src/core/dlp/assessor.ts +109 -0
  17. package/src/core/dlp/handlers.ts +237 -0
  18. package/src/core/dlp/index.ts +29 -0
  19. package/src/core/dlp/registry.ts +272 -0
  20. package/src/core/dlp/scorer.ts +109 -0
  21. package/src/core/exceptions.ts +3 -0
  22. package/src/core/fpe.ts +58 -91
  23. package/src/core/fpe_utils.ts +85 -0
  24. package/src/core/key_provider.ts +131 -50
  25. package/src/core/nlp_worker.js +45 -0
  26. package/src/core/remote_scanner.ts +87 -0
  27. package/src/core/scanner.ts +149 -81
  28. package/src/core/search.ts +52 -0
  29. package/src/core/timeout.ts +32 -0
  30. package/src/core/transformers_scanner.ts +228 -0
  31. package/src/core/utils.ts +85 -44
  32. package/src/core/vault.ts +284 -146
  33. package/src/index.ts +18 -2
  34. package/src/integrations/adk_hooks.ts +12 -7
  35. package/src/integrations/langchain_hooks.ts +20 -11
  36. package/src/integrations/llamaindex_hooks.ts +14 -5
  37. package/src/telemetry/audit_logger.ts +132 -76
  38. package/tests/async.test.ts +2 -1
  39. package/tests/audit_logger.test.ts +7 -11
  40. package/tests/exceptions.test.ts +8 -1
  41. package/tests/fail_strategy.test.ts +32 -27
  42. package/tests/fpe.test.ts +34 -27
  43. package/tests/hooks.test.ts +1 -1
  44. package/tests/jest.setup.ts +66 -0
  45. package/tests/key_provider.test.ts +36 -18
  46. package/tests/langchain.test.ts +15 -4
  47. package/tests/llamaindex.test.ts +11 -1
  48. package/tests/ner_masking.test.ts +59 -0
  49. package/tests/remote_scanner.test.ts +73 -0
  50. package/tests/search.test.ts +59 -0
  51. package/tests/security_hardening.test.ts +52 -0
  52. package/tests/test_cross.ts +14 -0
  53. package/tests/vault.test.ts +11 -11
  54. package/tests/vault_backends.test.ts +23 -15
  55. package/.test_audit.db +0 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Mask AI Solutions
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -27,9 +27,9 @@ Instead of trusting the LLM to safeguard plain-text data, the system strictly en
27
27
 
28
28
  This guarantees that the LLM can orchestrate workflows involving sensitive data without ever actually exposing the raw data to the model or its remote provider logs.
29
29
 
30
- Additionally, we solve two critical sub-issues to make this enterprise-ready:
31
- 1. **The Statefulness Trap**: Traditional "vaults" break down in multi-node Kubernetes environments. We support pluggable distributed vaults (Redis, DynamoDB, Memcached) so detokenization state is instantly shared across all your horizontally scaled pods.
32
- 2. **The Schema Trap**: Strict downstream tools will crash if handed a random token. We use Format-Preserving Tokenization backed by an encrypted vault to generate tokens that retain the exact format of the original data (Emails, US Phones, SSNs, 16-digit Credit Cards, 9-digit Routing Numbers). Tokens look like real data; the real values are stored encrypted and retrieved via the vault.
30
+ Additionally, the SDK addresses two technical considerations for production use:
31
+ 1. **Distributed State Management**: Traditional "vaults" may lose state in multi-node environments. Pluggable backends (Redis, DynamoDB, Memcached) ensure detokenization state is shared across all pods.
32
+ 2. **Schema Compatibility**: Downstream tools frequently require specific formats. Format-Preserving Tokenization (Emails, US Phones, SSNs, etc.) generates tokens that retain the format of original data.
33
33
 
34
34
  ### How We Handle Data (Local-First by Default)
35
35
 
@@ -49,7 +49,7 @@ The Data Plane is the open-source, transparent, auditable runtime execution laye
49
49
  * **JIT Cryptography Engine:** The core pre-tool decryption and post-tool encryption hooks that intercept and mutate data in-flight.
50
50
  * **Format-Preserving Tokenization Router:** Ensures downstream databases and strict schemas don't break when handed a token. Tokens look like real data; the real values are stored encrypted and retrieved via the vault.
51
51
  * **Pluggable Distributed Vaults:** Support for enterprise-native caching layers (Redis, DynamoDB, Memcached) to ensure horizontally-scaled edge agents have synchronized access to detokenization mapping.
52
- * **Local Audit Logger:** An asynchronous AuditLogger that buffers privacy events to a local SQLite database and emits structured JSON logs for SIEM ingestion.
52
+ * **Local Audit Logger:** An asynchronous AuditLogger that buffers privacy events in memory and emits structured JSON logs to stdout for SIEM ingestion.
53
53
 
54
54
  ---
55
55
 
@@ -79,37 +79,151 @@ const client = new MaskClient({
79
79
  const safeToken = await client.encode("user@tenant.com");
80
80
  ```
81
81
 
82
- ### 3. Heuristic Safety mathematically guaranteed
83
- It is catastrophic if an SDK misidentifies a user's *real* SSN as a "token" and accidentally passes it in plaintext to an LLM. Mask's `looksLikeToken()` heuristic algorithm strictly uses universally invalid prefixes.
84
- * SSN tokens always begin with `000` (The Social Security Administration has never issued an Area Number of 000).
82
+ ### 3. Collision Avoidance
83
+ Mask prevents the misidentification of real data as tokens by using universally invalid prefixes for token generation:
84
+ * SSN tokens always begin with `000` (The Social Security Administration does not issue Area Numbers of 000).
85
85
  * Routing tokens always begin with `0000` (The Federal Reserve valid range starts at 01).
86
86
  * Credit Card tokens use the `4000-0000-0000` Visa reserved test BIN.
87
- By generating statistically impossible tokens, Mask guarantees it will never accidentally swallow real PII.
87
+
88
+ This prefix-based approach ensures that the SDK does not inadvertently process valid PII as an existing token.
89
+
90
+ Additional collision-proof prefixes for international identifiers:
91
+ * Turkish TCID tokens use the `990000` prefix (no valid Kimlik number starts with `99`).
92
+ * Saudi NID tokens use the `100000` prefix (length-constrained to avoid overlap with real IDs).
93
+ * UAE Emirates ID tokens use the `784-0000-` prefix (zeroed sub-fields are structurally invalid).
94
+ * IBAN tokens zero the check digits (`XX00...`), which always fails ISO 7064 Mod-97 verification.
88
95
 
89
96
  ### 4. Enterprise Async Support
90
97
  Mask is built from the ground up for high-concurrency Node.js environments. All core operations are asynchronous and promised-based. Calling `encode()`, `decode()`, or `scanAndTokenize()` allows your event loop to remain unblocked while handling PII tokenization tasks.
91
98
 
92
- ### 5. Pluggable Key Providers (AWS KMS / HashiCorp Vault)
93
- For zero-trust environments, `MASK_ENCRYPTION_KEY` no longer needs to live in a static environment variable. Developers can fetch secrets dynamically from AWS KMS, Azure Key Vault, or HashiCorp Vault at runtime and inject them into the `CryptoEngine`.
99
+ ### 5. Pluggable Key Management (Enterprise KMS)
100
+ For zero-trust environments, `MASK_ENCRYPTION_KEY` can be managed outside of static environment variables. Mask supports a pluggable `BaseKeyProvider` architecture that allows you to fetch secrets dynamically from dedicated Key Management Services.
101
+
102
+ #### Supported Providers
103
+ * **EnvKeyProvider (Default)**: Reads from `MASK_ENCRYPTION_KEY` and `MASK_MASTER_KEY`.
104
+ * **AwsKmsKeyProvider (Stub)**: Placeholder for AWS KMS. Requires implementation of `@aws-sdk/client-kms`.
105
+ * **AzureKeyVaultProvider (Stub)**: Placeholder for Azure Key Vault. Requires implementation of `@azure/keyvault-keys`.
106
+ * **HashiCorpVaultProvider (Stub)**: Placeholder for HashiCorp Vault.
107
+
108
+ > [!NOTE]
109
+ > All KMS stub providers are designed for **Fail-Shut** operation. If you attempt to use a stub provider that is not yet implemented, the SDK will throw an `Error` rather than fall back to insecure defaults.
94
110
 
95
- ### 6. Remote NLP Scanning
96
- Performance-sensitive deployments can now offload the NLP models (like spaCy or Presidio) to a centralized service using the `RemotePresidioScanner`. This permits "lightweight" edge workers (e.g., AWS Lambda) to run Mask with near-zero memory footprint.
111
+ #### Example: Implementing a Custom Provider
112
+ If you need to support a specific KMS today, you can easily implement the `BaseKeyProvider` interface:
113
+
114
+ ```typescript
115
+ import { BaseKeyProvider, setKeyProvider } from 'mask-privacy/core/key_provider';
116
+
117
+ class MyCustomKmsProvider extends BaseKeyProvider {
118
+ async getEncryptionKey(): Promise<string> {
119
+ // Logic to fetch from your KMS
120
+ return "your-secret-key";
121
+ }
122
+ async getMasterKey(): Promise<string> {
123
+ return "your-master-key";
124
+ }
125
+ }
126
+
127
+ setKeyProvider(new MyCustomKmsProvider());
128
+ ```
129
+
130
+ ### 6. Local NLP Scanning (Default)
131
+ Performance-sensitive deployments utilize the built-in `LocalTransformersScanner` by default. This uses HuggingFace Transformers to run PII detection locally within your Node.js process, eliminating the need for external NLP services.
97
132
 
98
133
  ### 7. Sub-string Detokenization
99
134
  Mask includes the ability to detokenize PII embedded within larger text blocks (like email bodies or chat messages). `detokenizeText()` uses high-performance regex to find and restore all tokens within a paragraph before they hit your tools.
100
135
 
101
- ## Installation and Setup
136
+ ## Multilingual PII Detection (Waterfall Pipeline)
137
+
138
+ Mask is built for the global enterprise. While many privacy tools are English-centric, the TypeScript SDK implements a **3-Tier Waterfall Detection** strategy designed for high-performance PII detection across 8 major languages using local ONNX models.
139
+
140
+ ### Supported Language Matrix
141
+
142
+ Mask provides first-class support for the following languages:
143
+
144
+ | Language | Code | Tier 0 (DLP) | Tier 2 (NLP Engine) |
145
+ | :--- | :--- | :--- | :--- |
146
+ | **English** | `en` | ✅ Full | DistilBERT (Simple) |
147
+ | **Spanish** | `es` | ✅ Full | BERT Multilingual |
148
+ | **French** | `fr` | ✅ Full | BERT Multilingual |
149
+ | **German** | `de` | ✅ Full | BERT Multilingual |
150
+ | **Turkish** | `tr` | ✅ Full | BERT Multilingual |
151
+ | **Arabic** | `ar` | ✅ Full | BERT Multilingual |
152
+ | **Japanese** | `ja` | ✅ Full | BERT Multilingual |
153
+ | **Chinese** | `zh` | ✅ Full | BERT Multilingual |
154
+
155
+ ### How the Waterfall Works: The Excising Mechanism
156
+
157
+ To maintain high performance, the TypeScript SDK does not simply run three separate scans. It uses a **Sequential Mutation** strategy:
158
+
159
+ 1. **Tier 0 & 1 (The Scouts):** The SDK first runs the high-speed DLP and Regex engines synchronously in the main thread.
160
+ 2. **Immediate Tokenization:** Any PII found by these tiers is **immediately replaced** by a token in the string buffer.
161
+ 3. **Tier 2 (The Heavy Infantry):** The expensive NLP engine (Transformers.js) only scans the *remaining* text. Because the PII has already been "excised" (cut out and replaced with tokens), the NLP engine doesn't waste compute on data already identified.
162
+ 4. **Bypass Logic:** All tiers are "token-aware." If a scan encounter a string that is already a Mask token, it skips it entirely, preventing redundant processing or "double-tokenization."
163
+
164
+ ---
165
+
166
+ ### Configuration & Environment Variables
167
+
168
+ Configure your multilingual environment using standard variables. These are parsed at runtime when the `LocalTransformersScanner` is initialized.
169
+
170
+ | Variable | Default | Description |
171
+ | :--- | :--- | :--- |
172
+ | `MASK_LANGUAGES` | `en` | Comma-separated list of languages (e.g., `en,es,fr,ar`). |
173
+ | `MASK_NLP_MODEL` | *(varies)* | Override the default model (e.g., `Xenova/bert-base-multilingual-cased-ner-hrl`). |
174
+ | `MASK_MODEL_CACHE_DIR` | `~/.cache` | Local directory for storing serialized ONNX models. |
175
+ | `MASK_NLP_MAX_WORKERS` | `4` | Number of worker processes/threads for NLP analysis. |
176
+ | `MASK_NLP_TIMEOUT_SECONDS` | `60` | Max seconds for a scan before timing out. |
177
+
178
+ ---
179
+
180
+ ### Automatic Model Management
181
+
182
+ The TypeScript SDK manages AI models automatically via the **Transformers.js** runtime.
102
183
 
103
- Install the core SDK via npm:
184
+ #### 1. Automatic Downloads
185
+ When you set `MASK_LANGUAGES` to include non-English languages, the scanner will automatically download the multilingual BERT model from Hugging Face on the first execution and cache it locally.
186
+
187
+ #### 2. Pre-Warming (Performance)
188
+ Upon initialization, the `LocalTransformersScanner` starts a worker pool and "pre-warms" the models. This ensures that the first real request doesn't suffer from high "cold-start" latency.
189
+
190
+ #### 3. Air-Gapped / Offline Environments
191
+ For high-security environments, you can pre-cache models. Run this script in your build pipeline:
104
192
  ```bash
105
- npm install mask-privacy
193
+ # Set a custom cache directory
194
+ export MASK_MODEL_CACHE_DIR="./models"
195
+
196
+ # Run a dummy scan to trigger the download
197
+ node -e "require('mask-privacy').getScanner().scanAndTokenize('John Doe')"
198
+
199
+ # Bundle the './models' folder with your container
106
200
  ```
107
201
 
108
- Add peer dependencies depending on your infrastructure:
202
+ ---
203
+
204
+ ### Performance & Latency Benchmarks
205
+
206
+ *Measured on 4-vCPU 8GB RAM Instance (Node.js 20+)*
207
+
208
+ | Tier | Engine | Avg. Latency | Rationale |
209
+ | :--- | :--- | :--- | :--- |
210
+ | Tier 0 | DLP (Heuristic) | ~2ms | Main-thread synchronous regex |
211
+ | Tier 1 | Regex (Deterministic) | ~1ms | Main-thread synchronous regex |
212
+ | Tier 2 | Transformers (Local) | 300ms - 800ms | Offloaded to Worker Threads (Piscina) |
213
+
214
+ **Total Overhead:** Usually **< 400ms** for standard chat lengths. Mask uses an **Excising Mechanism** to ensure that text already identified in Tiers 0/1 is removed from the NLP buffer, significantly accelerating the heavy Transformer inference.
215
+
216
+ ---
217
+
218
+ ### Installing AI Models (Production Ready)
219
+ The TypeScript SDK manages AI models automatically via **Transformers.js**. For production air-gapped environments or to avoid "cold-start" latency, we recommend using the pre-caching CLI:
220
+
109
221
  ```bash
110
- npm install ioredis # For Redis vaults
111
- npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb # For DynamoDB vaults
112
- npm install memjs # For Memcached vaults
222
+ npm install @huggingface/transformers # Required extra
223
+
224
+ # Pre-cache models for your required languages
225
+ export MASK_LANGUAGES="en,es,fr"
226
+ npx mask-privacy cache-models
113
227
  ```
114
228
 
115
229
  ### Framework Support
@@ -122,6 +236,24 @@ Mask supports major AI frameworks via built-in hooks:
122
236
 
123
237
  Before running your agents, Mask requires an encryption key and a vault backend selection.
124
238
 
239
+ #### Where to set these?
240
+ Select the method that best fits your deployment:
241
+
242
+ 1. **In a `.env` file (Recommended)**: Create a file in your project root.
243
+ ```env
244
+ MASK_LANGUAGES="es,en"
245
+ MASK_ENCRYPTION_KEY="your-key"
246
+ ```
247
+ Then load it using a library like `dotenv`.
248
+ 2. **In your Terminal**:
249
+ * **Bash**: `export MASK_LANGUAGES="es,en"`
250
+ * **PowerShell**: `$env:MASK_LANGUAGES="es,en"`
251
+ 3. **Directly in TypeScript/Node.js**:
252
+ ```typescript
253
+ process.env.MASK_LANGUAGES = "es,en";
254
+ // Ensure this happens BEFORE initializing the MaskClient
255
+ ```
256
+
125
257
  #### 1. Configure Keys
126
258
  By default, Mask reads from environment variables.
127
259
  ```bash
@@ -150,6 +282,28 @@ export MASK_DYNAMODB_REGION=us-east-1
150
282
  # For Memcached:
151
283
  export MASK_MEMCACHED_HOST=localhost
152
284
  export MASK_MEMCACHED_PORT=11211
285
+
286
+ #### 4. Security Guardrails: Fail-Shut by Default
287
+
288
+ To prevent accidental data leakage, Mask defaults to a **Fail-Shut** strategy. If the Vault or Key Provider is unreachable, the SDK will throw a `MaskVaultConnectionError`.
289
+
290
+ > [!IMPORTANT]
291
+ > **Environment Modes:**
292
+ > - **Production (Default):** Fail-Shut enabled. Strictly protects PII.
293
+ > - **Development:** Set `MASK_ENV=dev` to allow "Fail-Open" behavior (PII is returned as-is if the vault fails).
294
+
295
+ #### 5. Model Pre-caching CLI
296
+
297
+ For production air-gapped environments or to avoid "cold-start" latency, use the model pre-caching tool:
298
+
299
+ ```bash
300
+ # Cache English and Spanish models
301
+ export MASK_MODEL_CACHE_DIR="./models"
302
+ npx ts-node src/cli.ts cache-models --languages en,es
303
+ ```
304
+
305
+ # Configure MemoryVault cleanup aggressiveness (default: 0.01)
306
+ export MASK_VAULT_CLEANUP_FREQUENCY=0.05
153
307
  ```
154
308
 
155
309
  ---
@@ -236,11 +390,14 @@ The SDK includes a thread-safe, asynchronous AuditLogger built-in.
236
390
 
237
391
  As your agents encrypt and decrypt data, the logger buffers these privacy events (Action, Agent, TTL). **Raw PII is never logged.**
238
392
 
239
- Audit events are stored locally in a SQLite database (`.mask_audit.db`) and flushed to stdout as structured JSON. Pipe them into your existing Datadog or Splunk agents for SOC2/HIPAA compliance reporting.
393
+ Audit events are buffered in memory and flushed periodically to stdout as structured JSON. Pipe these logs into your existing Datadog or Splunk agents for SOC2/HIPAA compliance reporting.
394
+
395
+ The `AuditLogger` includes graceful shutdown hooks (`SIGTERM`, `SIGINT`) to ensure all buffered events are flushed before the process exits.
396
+
397
+ To prevent memory issues in high-volume environments, the buffer size can be capped:
240
398
 
241
- To disable the local SQLite buffer:
242
399
  ```bash
243
- export MASK_DISABLE_AUDIT_DB=true
400
+ export MASK_AUDIT_MAX_BUFFER_SIZE=5000
244
401
  ```
245
402
 
246
403
  ## License