anonyma 1.1.0 → 1.2.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 (171) hide show
  1. package/CHANGELOG.md +131 -2
  2. package/README.md +125 -7
  3. package/dist/ai/index.cjs +31 -20
  4. package/dist/ai/index.cjs.map +1 -1
  5. package/dist/ai/index.d.cts +5 -5
  6. package/dist/ai/index.d.ts +5 -5
  7. package/dist/ai/index.js +24 -13
  8. package/dist/ai/index.js.map +1 -1
  9. package/dist/audit/index.cjs +14 -14
  10. package/dist/audit/index.d.cts +2 -2
  11. package/dist/audit/index.d.ts +2 -2
  12. package/dist/audit/index.js +9 -9
  13. package/dist/{chunk-YMLR375Z.js → chunk-264R3VFP.js} +4 -3
  14. package/dist/chunk-264R3VFP.js.map +1 -0
  15. package/dist/{chunk-ISL5B4LU.cjs → chunk-32U3DM7M.cjs} +11 -11
  16. package/dist/{chunk-ISL5B4LU.cjs.map → chunk-32U3DM7M.cjs.map} +1 -1
  17. package/dist/{chunk-26IHMQHL.cjs → chunk-42ZZZUMO.cjs} +245 -85
  18. package/dist/chunk-42ZZZUMO.cjs.map +1 -0
  19. package/dist/chunk-4BYN6GVK.js +213 -0
  20. package/dist/chunk-4BYN6GVK.js.map +1 -0
  21. package/dist/{chunk-JKW36IPT.js → chunk-A2OMTO3L.js} +4 -4
  22. package/dist/{chunk-JKW36IPT.js.map → chunk-A2OMTO3L.js.map} +1 -1
  23. package/dist/{chunk-TW7PM3UJ.cjs → chunk-AITKBKQX.cjs} +2 -2
  24. package/dist/{chunk-TW7PM3UJ.cjs.map → chunk-AITKBKQX.cjs.map} +1 -1
  25. package/dist/{chunk-G4AN7FND.js → chunk-BWE4O2ES.js} +23 -9
  26. package/dist/chunk-BWE4O2ES.js.map +1 -0
  27. package/dist/{chunk-GS3FRH4K.js → chunk-CMJXIEBA.js} +2 -2
  28. package/dist/chunk-CMJXIEBA.js.map +1 -0
  29. package/dist/{chunk-GYMG5OI3.cjs → chunk-ESVFPMG4.cjs} +2 -2
  30. package/dist/{chunk-GYMG5OI3.cjs.map → chunk-ESVFPMG4.cjs.map} +1 -1
  31. package/dist/{chunk-2YG7R4KJ.cjs → chunk-EUNLKSYP.cjs} +5 -5
  32. package/dist/{chunk-2YG7R4KJ.cjs.map → chunk-EUNLKSYP.cjs.map} +1 -1
  33. package/dist/{chunk-S7NH6CHY.cjs → chunk-F3BYJFUM.cjs} +5 -3
  34. package/dist/chunk-F3BYJFUM.cjs.map +1 -0
  35. package/dist/{chunk-IJAMLYOT.cjs → chunk-HDHQXVUM.cjs} +50 -36
  36. package/dist/chunk-HDHQXVUM.cjs.map +1 -0
  37. package/dist/{chunk-OGNLB2KA.js → chunk-HFAIBE3T.js} +3 -3
  38. package/dist/{chunk-OGNLB2KA.js.map → chunk-HFAIBE3T.js.map} +1 -1
  39. package/dist/{chunk-PKHZ7CVI.js → chunk-IBDFBUFZ.js} +2 -2
  40. package/dist/chunk-IBDFBUFZ.js.map +1 -0
  41. package/dist/{chunk-3CY6ATKS.cjs → chunk-JBH2EFFF.cjs} +36 -36
  42. package/dist/{chunk-3CY6ATKS.cjs.map → chunk-JBH2EFFF.cjs.map} +1 -1
  43. package/dist/chunk-JPU7KQZX.cjs +82 -0
  44. package/dist/{chunk-CRXRJZEV.cjs.map → chunk-JPU7KQZX.cjs.map} +1 -1
  45. package/dist/{chunk-E3PICZYI.js → chunk-KHT23UVV.js} +3 -3
  46. package/dist/{chunk-E3PICZYI.js.map → chunk-KHT23UVV.js.map} +1 -1
  47. package/dist/{chunk-2ZZHLCEJ.js → chunk-LAZIR73I.js} +18 -87
  48. package/dist/chunk-LAZIR73I.js.map +1 -0
  49. package/dist/{chunk-FB56NAAH.cjs → chunk-NO4ZCIM6.cjs} +19 -92
  50. package/dist/chunk-NO4ZCIM6.cjs.map +1 -0
  51. package/dist/{chunk-S4BJ2ADB.cjs → chunk-PCU6AG7H.cjs} +4 -4
  52. package/dist/{chunk-S4BJ2ADB.cjs.map → chunk-PCU6AG7H.cjs.map} +1 -1
  53. package/dist/{chunk-W6RBCHYF.js → chunk-PSZHBY5V.js} +235 -75
  54. package/dist/chunk-PSZHBY5V.js.map +1 -0
  55. package/dist/{chunk-6LDAIJBL.js → chunk-QBBJR7DZ.js} +2 -2
  56. package/dist/{chunk-6LDAIJBL.js.map → chunk-QBBJR7DZ.js.map} +1 -1
  57. package/dist/{chunk-3D5ZCJ7R.js → chunk-QHQ2AU45.js} +3 -3
  58. package/dist/{chunk-3D5ZCJ7R.js.map → chunk-QHQ2AU45.js.map} +1 -1
  59. package/dist/{chunk-IHEIYZPL.cjs → chunk-RJX27YEX.cjs} +2 -2
  60. package/dist/chunk-RJX27YEX.cjs.map +1 -0
  61. package/dist/{chunk-QYD4F6T7.cjs → chunk-ROXNQKOA.cjs} +2 -2
  62. package/dist/{chunk-QYD4F6T7.cjs.map → chunk-ROXNQKOA.cjs.map} +1 -1
  63. package/dist/chunk-SHEXFU6T.js +107 -0
  64. package/dist/chunk-SHEXFU6T.js.map +1 -0
  65. package/dist/chunk-T2KIN6VL.cjs +218 -0
  66. package/dist/chunk-T2KIN6VL.cjs.map +1 -0
  67. package/dist/{chunk-RCW5IPPR.js → chunk-UCT6HDUD.js} +3 -3
  68. package/dist/{chunk-RCW5IPPR.js.map → chunk-UCT6HDUD.js.map} +1 -1
  69. package/dist/chunk-UN74SYHV.cjs +115 -0
  70. package/dist/chunk-UN74SYHV.cjs.map +1 -0
  71. package/dist/{chunk-F7O2FA3F.cjs → chunk-VAO3Y3HZ.cjs} +7 -6
  72. package/dist/chunk-VAO3Y3HZ.cjs.map +1 -0
  73. package/dist/{chunk-BBJPQPGP.js → chunk-VE3OSDM7.js} +5 -3
  74. package/dist/chunk-VE3OSDM7.js.map +1 -0
  75. package/dist/{chunk-7HK2V5Q4.js → chunk-X7IVXKDE.js} +3 -3
  76. package/dist/{chunk-7HK2V5Q4.js.map → chunk-X7IVXKDE.js.map} +1 -1
  77. package/dist/{chunk-UA3EOFBS.cjs → chunk-XVCVIUZS.cjs} +8 -8
  78. package/dist/{chunk-UA3EOFBS.cjs.map → chunk-XVCVIUZS.cjs.map} +1 -1
  79. package/dist/{chunk-SIHPDZXA.js → chunk-YSTC7WRF.js} +2 -2
  80. package/dist/{chunk-SIHPDZXA.js.map → chunk-YSTC7WRF.js.map} +1 -1
  81. package/dist/compliance/index.cjs +15 -15
  82. package/dist/compliance/index.d.cts +4 -4
  83. package/dist/compliance/index.d.ts +4 -4
  84. package/dist/compliance/index.js +5 -5
  85. package/dist/crypto.cjs +4 -4
  86. package/dist/crypto.d.cts +1 -1
  87. package/dist/crypto.d.ts +1 -1
  88. package/dist/crypto.js +2 -2
  89. package/dist/detectors/index.cjs +38 -38
  90. package/dist/detectors/index.d.cts +1 -1
  91. package/dist/detectors/index.d.ts +1 -1
  92. package/dist/detectors/index.js +3 -3
  93. package/dist/engine/index.cjs +70 -70
  94. package/dist/engine/index.d.cts +3 -3
  95. package/dist/engine/index.d.ts +3 -3
  96. package/dist/engine/index.js +8 -8
  97. package/dist/hash-P2VGKVFP.cjs +14 -0
  98. package/dist/{hash-2PSYNDMM.cjs.map → hash-P2VGKVFP.cjs.map} +1 -1
  99. package/dist/hash-T6YJG3DU.js +5 -0
  100. package/dist/{hash-CELLDNKN.js.map → hash-T6YJG3DU.js.map} +1 -1
  101. package/dist/index.cjs +44 -34
  102. package/dist/index.cjs.map +1 -1
  103. package/dist/index.d.cts +23 -5
  104. package/dist/index.d.ts +23 -5
  105. package/dist/index.js +11 -9
  106. package/dist/index.js.map +1 -1
  107. package/dist/{json-s8ny-RCo.d.cts → json-BXN577tt.d.cts} +3 -2
  108. package/dist/{json-CKDvlRtl.d.ts → json-BudrzkOQ.d.ts} +3 -2
  109. package/dist/mcp/index.cjs +29 -28
  110. package/dist/mcp/index.cjs.map +1 -1
  111. package/dist/mcp/index.js +14 -13
  112. package/dist/mcp/index.js.map +1 -1
  113. package/dist/middleware/express.cjs +11 -11
  114. package/dist/middleware/express.d.cts +3 -3
  115. package/dist/middleware/express.d.ts +3 -3
  116. package/dist/middleware/express.js +10 -10
  117. package/dist/middleware/hono.cjs +11 -11
  118. package/dist/middleware/hono.d.cts +3 -3
  119. package/dist/middleware/hono.d.ts +3 -3
  120. package/dist/middleware/hono.js +10 -10
  121. package/dist/middleware/index.cjs +11 -11
  122. package/dist/middleware/index.d.cts +3 -3
  123. package/dist/middleware/index.d.ts +3 -3
  124. package/dist/middleware/index.js +10 -10
  125. package/dist/schemas.cjs +47 -47
  126. package/dist/schemas.cjs.map +1 -1
  127. package/dist/schemas.d.cts +2 -2
  128. package/dist/schemas.d.ts +2 -2
  129. package/dist/schemas.js +2 -2
  130. package/dist/schemas.js.map +1 -1
  131. package/dist/{session-BdRftyZ5.d.cts → session-CPXEQ2uC.d.cts} +18 -5
  132. package/dist/{session-Cs2zlNQp.d.ts → session-D3WMN6fE.d.ts} +18 -5
  133. package/dist/stream.cjs +10 -8
  134. package/dist/stream.cjs.map +1 -1
  135. package/dist/stream.d.cts +1 -1
  136. package/dist/stream.d.ts +1 -1
  137. package/dist/stream.js +7 -5
  138. package/dist/stream.js.map +1 -1
  139. package/dist/{types-Dtht33aq.d.ts → types-B3VjDuP8.d.cts} +2 -282
  140. package/dist/{types--tPm_AjY.d.ts → types-DHAVKfzT.d.ts} +2 -2
  141. package/dist/types-LZHFEgx5.d.cts +1083 -0
  142. package/dist/types-LZHFEgx5.d.ts +1083 -0
  143. package/dist/{types-0BJH_wqc.d.cts → types-vmONSbz4.d.cts} +2 -2
  144. package/dist/{types-CPUhjvl8.d.cts → types-yZHnS7yv.d.ts} +2 -282
  145. package/dist/validators.cjs +10 -10
  146. package/dist/validators.js +1 -1
  147. package/dist/vault/index.cjs +65 -46
  148. package/dist/vault/index.cjs.map +1 -1
  149. package/dist/vault/index.d.cts +98 -5
  150. package/dist/vault/index.d.ts +98 -5
  151. package/dist/vault/index.js +11 -5
  152. package/dist/vault/index.js.map +1 -1
  153. package/package.json +16 -7
  154. package/dist/chunk-26IHMQHL.cjs.map +0 -1
  155. package/dist/chunk-2ZZHLCEJ.js.map +0 -1
  156. package/dist/chunk-BBJPQPGP.js.map +0 -1
  157. package/dist/chunk-CRXRJZEV.cjs +0 -82
  158. package/dist/chunk-F7O2FA3F.cjs.map +0 -1
  159. package/dist/chunk-FB56NAAH.cjs.map +0 -1
  160. package/dist/chunk-G4AN7FND.js.map +0 -1
  161. package/dist/chunk-GS3FRH4K.js.map +0 -1
  162. package/dist/chunk-IHEIYZPL.cjs.map +0 -1
  163. package/dist/chunk-IJAMLYOT.cjs.map +0 -1
  164. package/dist/chunk-PKHZ7CVI.js.map +0 -1
  165. package/dist/chunk-S7NH6CHY.cjs.map +0 -1
  166. package/dist/chunk-W6RBCHYF.js.map +0 -1
  167. package/dist/chunk-YMLR375Z.js.map +0 -1
  168. package/dist/hash-2PSYNDMM.cjs +0 -14
  169. package/dist/hash-CELLDNKN.js +0 -5
  170. package/dist/types-EJTj_BKY.d.cts +0 -584
  171. package/dist/types-EJTj_BKY.d.ts +0 -584
@@ -0,0 +1,1083 @@
1
+ /**
2
+ * @module vault/types
3
+ * @description Contracts for deterministic tokenization, key management and
4
+ * token vaults exposed as `"anonyma/vault"`. This module contains types only —
5
+ * it has no runtime code.
6
+ */
7
+ /**
8
+ * A value that may be returned directly or through a promise. Implementations
9
+ * backed by the Web Crypto API or by remote storage return promises; purely
10
+ * in-memory implementations may return plain values.
11
+ */
12
+ type MaybePromise<T> = T | Promise<T>;
13
+ /**
14
+ * Context of the value being tokenized.
15
+ */
16
+ interface TokenContext {
17
+ /** Category label of the value (e.g. `"email"`). */
18
+ readonly category: string;
19
+ /**
20
+ * Optional reference to the data subject the value belongs to. It is never
21
+ * stored in clear: vault-backed providers keep only a keyed digest of it, so
22
+ * that all tokens of one subject can later be erased.
23
+ */
24
+ readonly subject?: string;
25
+ }
26
+ /**
27
+ * Outcome of restoring the tokens found in a text.
28
+ */
29
+ interface RestoreResult {
30
+ /** The text with every resolvable token replaced by its original value. */
31
+ readonly text: string;
32
+ /** Number of token occurrences that were restored. */
33
+ readonly restored: number;
34
+ /** Token occurrences that could not be resolved, in document order. */
35
+ readonly unresolved: readonly string[];
36
+ }
37
+ /**
38
+ * Replaces values with tokens and, when the scheme is reversible, resolves
39
+ * tokens back to values.
40
+ *
41
+ * A provider is deterministic within its scope: the same category and value
42
+ * always yield the same token for the lifetime of a session provider, and for
43
+ * the lifetime of a key version for keyed providers.
44
+ */
45
+ interface TokenizationProvider {
46
+ /** Identifier of the scheme, recorded in audit events (e.g. `"session"`, `"keyed"`, `"sealed"`). */
47
+ readonly scheme: string;
48
+ /** Whether {@link TokenizationProvider.detokenize} can recover original values. */
49
+ readonly reversible: boolean;
50
+ /**
51
+ * A global regular expression that matches every token this provider can
52
+ * emit and nothing shorter than a whole token.
53
+ */
54
+ readonly tokenPattern: RegExp;
55
+ /**
56
+ * A regular expression that matches, anchored at the end of a string, any
57
+ * proper prefix of a token (for example `[EMAIL_00`). Stream restoration
58
+ * uses it to hold back an incomplete token until the rest arrives. When it
59
+ * is absent, streams hold back the last `maxTokenLength - 1` characters.
60
+ */
61
+ readonly partialTokenPattern?: RegExp;
62
+ /**
63
+ * Replace every token found in `text`. A provider implements it when it
64
+ * accepts more spellings of a token than `tokenPattern` matches (a session
65
+ * in lenient mode, for example); whole-text and stream restoration then go
66
+ * through it, so both accept the same spellings.
67
+ */
68
+ readonly restore?: (text: string) => MaybePromise<RestoreResult>;
69
+ /** Upper bound on the length of a token, used for stream hold-back. */
70
+ readonly maxTokenLength: number;
71
+ /** Return the token for `value`, creating it if necessary. */
72
+ readonly tokenize: (value: string, context: TokenContext) => MaybePromise<string>;
73
+ /**
74
+ * Resolve one token. Returns `undefined` when the token is unknown, erased,
75
+ * expired, fails authentication, or the scheme is irreversible.
76
+ */
77
+ readonly detokenize: (token: string) => MaybePromise<string | undefined>;
78
+ }
79
+ /**
80
+ * What a derived key is used for. Every purpose gets an independent key, so a
81
+ * key is never used for two different algorithms.
82
+ *
83
+ * - `"token-id"`: HMAC-SHA-256 key that derives deterministic token identifiers.
84
+ * - `"token-seal"`: AES-256-GCM key that encrypts original values.
85
+ * - `"subject-tag"`: HMAC-SHA-256 key that derives data-subject tags.
86
+ * - `"audit-mac"`: HMAC-SHA-256 key that authenticates audit records.
87
+ *
88
+ * Every key of a version is gone once the version is destroyed. An audit log
89
+ * must stay verifiable after data keys are shredded, so take its `audit-mac`
90
+ * key from a key ring of its own, whose versions are retired but not destroyed.
91
+ */
92
+ type KeyPurpose = "token-id" | "token-seal" | "subject-tag" | "audit-mac";
93
+ /**
94
+ * Lifecycle state of a key version.
95
+ *
96
+ * - `"active"`: used for new tokens and for decryption. Exactly one version is active.
97
+ * - `"retired"`: no longer used for new tokens; still available for decryption and verification.
98
+ * - `"destroyed"`: the key material has been discarded. Everything sealed under
99
+ * this version is permanently unrecoverable (crypto-shredding).
100
+ */
101
+ type KeyState = "active" | "retired" | "destroyed";
102
+ /**
103
+ * Secret input from which the keys of one version are derived.
104
+ */
105
+ type KeyMaterial = {
106
+ /** High-entropy secret bytes (at least 32). Used as HKDF input keying material. */
107
+ readonly kind: "raw";
108
+ readonly bytes: Uint8Array;
109
+ } | {
110
+ /** A passphrase, stretched with PBKDF2-HMAC-SHA-256 before HKDF. */
111
+ readonly kind: "passphrase";
112
+ readonly passphrase: string;
113
+ /** PBKDF2 iteration count. Defaults to 600,000 and may not be lower than 100,000. */
114
+ readonly iterations?: number;
115
+ };
116
+ /**
117
+ * Non-secret description of one key version. Safe to store next to the data.
118
+ */
119
+ interface KeyVersionInfo {
120
+ /** Version identifier: 1–16 characters from `[A-Za-z0-9]`. Embedded in tokens. */
121
+ readonly id: string;
122
+ /** Lifecycle state. */
123
+ readonly state: KeyState;
124
+ /** Creation time, milliseconds since the Unix epoch. */
125
+ readonly createdAt: number;
126
+ /** Key-derivation function applied to the material before HKDF. */
127
+ readonly kdf: "hkdf" | "pbkdf2-hkdf";
128
+ /** Salt for this version, base64url. Random, at least 16 bytes, not secret. */
129
+ readonly salt: string;
130
+ /** PBKDF2 iteration count, present when `kdf` is `"pbkdf2-hkdf"`. */
131
+ readonly iterations?: number;
132
+ }
133
+ /**
134
+ * Non-secret description of a key ring. Together with the secret material of
135
+ * each live version it is sufficient to reconstruct the ring.
136
+ */
137
+ interface KeyRingManifest {
138
+ /** Manifest format version. */
139
+ readonly v: 1;
140
+ /**
141
+ * Domain-separation label mixed into every derived key (tenant, dataset or
142
+ * environment). Two rings with different namespaces never produce the same
143
+ * token for the same value, even from identical material.
144
+ */
145
+ readonly namespace: string;
146
+ /** Identifier of the active version. */
147
+ readonly activeKeyId: string;
148
+ /** All versions, oldest first. */
149
+ readonly versions: readonly KeyVersionInfo[];
150
+ /**
151
+ * HMAC-SHA-256 (base64url) under a key of the active version. It covers the
152
+ * namespace, the active version, and every version's identifier, creation
153
+ * time, derivation parameters and salt. A manifest whose MAC does not verify
154
+ * is refused.
155
+ */
156
+ readonly mac: string;
157
+ }
158
+ /**
159
+ * A set of versioned secrets with independent, purpose-bound derived keys.
160
+ *
161
+ * A key ring is a stateful object: {@link KeyRing.rotate} and
162
+ * {@link KeyRing.destroy} change it in place.
163
+ */
164
+ interface KeyRing {
165
+ /** Identifier of the version used for new tokens. */
166
+ readonly activeKeyId: () => string;
167
+ /** The current non-secret manifest. */
168
+ readonly manifest: () => KeyRingManifest;
169
+ /**
170
+ * Derive the key of a version for a purpose. Derived keys are cached and
171
+ * non-extractable.
172
+ *
173
+ * @throws KeyManagementError When the version is unknown or destroyed.
174
+ */
175
+ readonly deriveKey: (keyId: string, purpose: KeyPurpose) => Promise<CryptoKey>;
176
+ /**
177
+ * Add a new version and make it active. The previously active version
178
+ * becomes `"retired"`.
179
+ *
180
+ * @throws KeyManagementError When `id` is already in use or malformed.
181
+ */
182
+ readonly rotate: (version: {
183
+ readonly id: string;
184
+ readonly material: KeyMaterial;
185
+ }) => Promise<void>;
186
+ /**
187
+ * Discard the material of a retired version.
188
+ *
189
+ * @throws KeyManagementError When the version is unknown or is the active version.
190
+ */
191
+ readonly destroy: (keyId: string) => void;
192
+ }
193
+ /**
194
+ * One vault entry. It holds no plaintext: the original value is sealed with
195
+ * AES-256-GCM under the `token-seal` key of `keyId`.
196
+ */
197
+ interface VaultRecord {
198
+ /** The token this record resolves. Primary key. */
199
+ readonly token: string;
200
+ /** Category label of the original value. */
201
+ readonly category: string;
202
+ /** Key version whose `token-seal` key sealed `sealed`. */
203
+ readonly keyId: string;
204
+ /** base64url of `iv (12 bytes) ‖ ciphertext ‖ tag (16 bytes)`. The token is bound as additional authenticated data. */
205
+ readonly sealed: string;
206
+ /**
207
+ * Keyed digest of the category and original value. It lets a provider tell
208
+ * a repeated value from an identifier collision without unsealing the record.
209
+ */
210
+ readonly check?: string;
211
+ /**
212
+ * The data subjects this value was tokenized for. A value shared by several
213
+ * subjects has one record and one entry per subject; erasing any of them
214
+ * deletes the record.
215
+ */
216
+ readonly subjects?: readonly SubjectReference[];
217
+ /** Creation time, milliseconds since the Unix epoch. Bound to `sealed`. */
218
+ readonly createdAt: number;
219
+ /**
220
+ * Expiry time, milliseconds since the Unix epoch. Expired records do not
221
+ * resolve. Bound to `sealed`: a record whose expiry was changed or removed
222
+ * no longer resolves.
223
+ */
224
+ readonly expiresAt?: number;
225
+ }
226
+ /**
227
+ * One data subject of a vault record. It holds no plaintext.
228
+ */
229
+ interface SubjectReference {
230
+ /** Keyed digest of the data-subject reference under the `subject-tag` key of the record's `keyId`. */
231
+ readonly tag: string;
232
+ /**
233
+ * The data-subject reference sealed under the `token-seal` key of the
234
+ * record's `keyId`. Key rotation unseals it to recompute `tag` under the new
235
+ * version, so erasure by subject keeps working after old versions are destroyed.
236
+ */
237
+ readonly sealed: string;
238
+ }
239
+ /**
240
+ * Storage for {@link VaultRecord}s. Implement this interface to keep the
241
+ * vault in Redis, a SQL table, a KV store, and so on.
242
+ */
243
+ interface TokenVault {
244
+ /** Fetch the record of a token. */
245
+ readonly get: (token: string) => MaybePromise<VaultRecord | undefined>;
246
+ /**
247
+ * Store `record` unless a record with the same token already exists.
248
+ * Returns the record that is stored after the call (the existing one or the new one).
249
+ */
250
+ readonly putIfAbsent: (record: VaultRecord) => MaybePromise<VaultRecord>;
251
+ /**
252
+ * Overwrite the record of `record.token`, but only while the stored record
253
+ * still is `expected` (same `keyId`, `sealed` and `subjects`). Returns
254
+ * `false`, and stores nothing, when the record was deleted or changed in the
255
+ * meantime. It never creates a record: an erasure that runs at the same time
256
+ * as a key rotation must win.
257
+ */
258
+ readonly replace: (record: VaultRecord, expected: VaultRecord) => MaybePromise<boolean>;
259
+ /** Delete the record of a token. Returns `true` when a record was deleted. */
260
+ readonly delete: (token: string) => MaybePromise<boolean>;
261
+ /** Enumerate all records. Required for key rotation and erasure by subject. */
262
+ readonly list: () => AsyncIterable<VaultRecord> | Iterable<VaultRecord>;
263
+ }
264
+ /**
265
+ * Proof that an erasure request was executed. It contains no personal data and
266
+ * is meant to be written to the audit log.
267
+ */
268
+ interface ErasureReceipt {
269
+ /** How the erasure was carried out. */
270
+ readonly method: "vault-delete" | "crypto-shred";
271
+ /** Number of vault records removed (`vault-delete`) or rendered unrecoverable (`crypto-shred`). */
272
+ readonly erased: number;
273
+ /** Key versions involved. */
274
+ readonly keyIds: readonly string[];
275
+ /** Keyed digest of the data-subject reference, for `vault-delete` by subject. */
276
+ readonly subjectTag?: string;
277
+ /** Completion time, milliseconds since the Unix epoch. */
278
+ readonly completedAt: number;
279
+ }
280
+
281
+ /**
282
+ * @module vault/anonyma-vault
283
+ * @description The minimal storage contract for reversible tokens, an
284
+ * in-memory implementation of it, and {@link restore}, which puts the original
285
+ * values back into a text.
286
+ *
287
+ * An {@link AnonymaVault} maps a token to the value it replaced. It is the
288
+ * storage behind {@link createVaultTokenizer} and `tokenize(text, { vault })`,
289
+ * and the input of {@link restore}. Its two methods may answer synchronously
290
+ * (an in-memory map) or asynchronously (Redis, a KV namespace, a SQL table).
291
+ *
292
+ * A vault holds original values in clear. Keep one per conversation or per
293
+ * request, and never let text from one user be restored against the vault of
294
+ * another: a user who writes a token of somebody else's vault into a prompt
295
+ * would otherwise get that person's data back.
296
+ */
297
+
298
+ /**
299
+ * Storage for reversible tokens: token in, original value out.
300
+ *
301
+ * Implement it to keep tokens somewhere other than memory. Both methods may
302
+ * return a promise.
303
+ *
304
+ * @example
305
+ * ```ts
306
+ * import type { AnonymaVault } from "anonyma";
307
+ *
308
+ * // A Cloudflare KV namespace, one key prefix per conversation.
309
+ * const kvVault = (kv: KVNamespace, conversation: string): AnonymaVault => ({
310
+ * store: (key, value) => kv.put(`${conversation}:${key}`, value, { expirationTtl: 3600 }),
311
+ * retrieve: async (key) => (await kv.get(`${conversation}:${key}`)) ?? undefined,
312
+ * });
313
+ * ```
314
+ */
315
+ interface AnonymaVault {
316
+ /** Remember that `key` (a token) stands for `value`. */
317
+ store(key: string, value: string): MaybePromise<void>;
318
+ /** The value `key` stands for, or `undefined` when the vault does not know it. */
319
+ retrieve(key: string): MaybePromise<string | undefined>;
320
+ }
321
+ /**
322
+ * An {@link AnonymaVault} that answers synchronously. With one, {@link restore}
323
+ * and `tokenize(text, { vault })` return their results directly.
324
+ */
325
+ interface SyncAnonymaVault extends AnonymaVault {
326
+ store(key: string, value: string): void;
327
+ retrieve(key: string): string | undefined;
328
+ }
329
+ /**
330
+ * Options accepted by {@link restore}.
331
+ */
332
+ interface RestoreOptions {
333
+ /**
334
+ * What a token looks like. Defaults to the numbered tokens anonyma issues in
335
+ * any shape: `{{EMAIL_1}}`, `[EMAIL_0001]` and `<EMAIL_1>`, with or without
336
+ * a tag. Each match is looked up in the vault as a whole, so make the
337
+ * pattern match whole tokens only.
338
+ */
339
+ readonly pattern?: RegExp;
340
+ }
341
+ /**
342
+ * The default {@link AnonymaVault}: a map in memory, for the lifetime of one
343
+ * request or one serverless invocation.
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * import { InMemoryVault, restore, tokenize } from "anonyma";
348
+ *
349
+ * const vault = new InMemoryVault();
350
+ * const { text } = tokenize("Mail john@example.com", { vault });
351
+ * // "Mail {{EMAIL_1}}"
352
+ * restore("Sent to {{EMAIL_1}}.", vault).text;
353
+ * // "Sent to john@example.com."
354
+ * ```
355
+ */
356
+ declare class InMemoryVault implements SyncAnonymaVault {
357
+ #private;
358
+ /**
359
+ * @param entries - Entries to start with, for example from {@link InMemoryVault.entries} of another vault.
360
+ */
361
+ constructor(entries?: Iterable<readonly [key: string, value: string]>);
362
+ /** Remember that `key` stands for `value`, replacing what it stood for before. */
363
+ store(key: string, value: string): void;
364
+ /** The value `key` stands for, or `undefined`. */
365
+ retrieve(key: string): string | undefined;
366
+ /** Forget one key. Returns `true` when it was known. */
367
+ delete(key: string): boolean;
368
+ /** Forget every key. */
369
+ clear(): void;
370
+ /** Number of keys held. */
371
+ get size(): number;
372
+ /**
373
+ * A copy of every entry, in the order they were stored. It contains
374
+ * original values: handle it as you would handle the data itself.
375
+ */
376
+ entries(): [key: string, value: string][];
377
+ }
378
+ /**
379
+ * Replace every token found in `text` with the value `vault` holds for it.
380
+ *
381
+ * The text is scanned once and each match is a whole token, delimiters
382
+ * included, so `{{PERSON_1}}` is never found inside `{{PERSON_10}}`. Restored
383
+ * values are not scanned again: a value that itself looks like a token stays
384
+ * as it is. Tokens the vault does not know are left in place and reported in
385
+ * `unresolved`.
386
+ *
387
+ * @param text - Text containing tokens, such as a model's answer.
388
+ * @param vault - The vault the tokens were stored in.
389
+ * @param options - A custom token pattern.
390
+ * @returns The restored text, the number of restored occurrences and the
391
+ * unresolved tokens; a promise of them when the vault is asynchronous.
392
+ * @throws {@link ValidationError} When `text` is not a string or `pattern` is not a RegExp.
393
+ *
394
+ * @example
395
+ * ```ts
396
+ * import { InMemoryVault, restore } from "anonyma";
397
+ *
398
+ * const vault = new InMemoryVault([
399
+ * ["{{PERSON_1}}", "Ada"],
400
+ * ["{{PERSON_10}}", "Grace"],
401
+ * ]);
402
+ * restore("{{PERSON_10}} met {{PERSON_1}}", vault).text; // "Grace met Ada"
403
+ *
404
+ * const { text } = await restore(answer, redisVault); // asynchronous vault
405
+ * ```
406
+ */
407
+ declare function restore(text: string, vault: SyncAnonymaVault, options?: RestoreOptions): RestoreResult;
408
+ declare function restore(text: string, vault: AnonymaVault, options?: RestoreOptions): Promise<RestoreResult>;
409
+
410
+ /**
411
+ * @module types
412
+ * @description Core TypeScript types and interfaces for the anonyma library.
413
+ */
414
+
415
+ /**
416
+ * All PII (Personally Identifiable Information) categories that anonyma can detect.
417
+ *
418
+ * @remarks
419
+ * `"name"` detection is heuristic — it catches names that follow greeting keywords,
420
+ * title prefixes (Mr./Dr./etc.), and context clues (patient, client, defendant, etc.).
421
+ * It is not an NLP-based name recogniser and may miss names that appear without
422
+ * any of these context signals.
423
+ */
424
+ type PiiCategory = "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" | "case-number" | "company-registration";
425
+ /**
426
+ * A detected PII entity within a text string.
427
+ */
428
+ interface PiiMatch {
429
+ /** The category of PII detected. */
430
+ readonly category: PiiCategory;
431
+ /** The verbatim matched value. */
432
+ readonly value: string;
433
+ /** Zero-based start index within the source string. */
434
+ readonly start: number;
435
+ /** Zero-based exclusive end index within the source string. */
436
+ readonly end: number;
437
+ /** Confidence score in the range [0, 1]. */
438
+ readonly confidence: number;
439
+ }
440
+ /**
441
+ * An ad-hoc regex pattern that participates in PII detection and anonymization
442
+ * alongside the built-in detectors.
443
+ *
444
+ * @example
445
+ * ```ts
446
+ * const pattern: CustomPattern = {
447
+ * pattern: /\bACME-\d{6}\b/g,
448
+ * category: "order-id",
449
+ * confidence: 0.9,
450
+ * label: "[ORDER_ID]",
451
+ * };
452
+ * ```
453
+ */
454
+ interface CustomPattern {
455
+ /**
456
+ * The regular expression to match. If the global flag is absent it will be
457
+ * added automatically before execution.
458
+ */
459
+ readonly pattern: RegExp;
460
+ /**
461
+ * Category label attached to matches. Defaults to `"custom"`.
462
+ * Does not need to be a built-in {@link PiiCategory}.
463
+ */
464
+ readonly category?: string;
465
+ /**
466
+ * Confidence score in [0, 1]. Defaults to `0.85`.
467
+ */
468
+ readonly confidence?: number;
469
+ /**
470
+ * Replacement label used when a match is replaced.
471
+ * Defaults to `"[REDACTED]"`.
472
+ */
473
+ readonly label?: string;
474
+ }
475
+ /**
476
+ * Locale codes for locale-aware PII detection. `"global"` covers universally-
477
+ * formatted PII (e.g. email, IPv4, credit card).
478
+ */
479
+ type Locale = "global" | "us" | "uk" | "eu" | "ca" | "au" | "br" | "in" | "cn" | "jp" | "kr" | "za";
480
+ /**
481
+ * Built-in compliance preset identifiers.
482
+ */
483
+ type CompliancePreset = "gdpr" | "lgpd" | "pipeda" | "hipaa" | "ccpa" | "pci-dss" | "sox" | "ferpa";
484
+ /**
485
+ * A single tokenized PII match.
486
+ */
487
+ interface TokenMatch {
488
+ /** The placeholder token, e.g. `<Email_1>` or `[EMAIL_a3f9]`. */
489
+ readonly token: string;
490
+ /** The original PII value. */
491
+ readonly original: string;
492
+ /** The PII category. */
493
+ readonly category: PiiCategory;
494
+ /** Zero-based start index within the source string. */
495
+ readonly start: number;
496
+ /** Zero-based exclusive end index within the source string. */
497
+ readonly end: number;
498
+ }
499
+ /**
500
+ * Result returned by `tokenize()`.
501
+ */
502
+ interface TokenizeResult {
503
+ /** The tokenized text with PII replaced by placeholder tokens. */
504
+ readonly text: string;
505
+ /** A map from token → original value for reversibility. */
506
+ readonly mapping: ReadonlyMap<string, string>;
507
+ /** All token match details. */
508
+ readonly tokens: readonly TokenMatch[];
509
+ }
510
+ /**
511
+ * Result returned by `detokenize()`.
512
+ */
513
+ interface DetokenizeResult {
514
+ /** The restored text with tokens replaced by original values. */
515
+ readonly text: string;
516
+ /** Number of tokens successfully replaced. */
517
+ readonly replacedCount: number;
518
+ /** Any tokens not found in the mapping (left unchanged in output). */
519
+ readonly unresolved: readonly string[];
520
+ }
521
+ /**
522
+ * Token format style.
523
+ * - `"bracket"`: `[CATEGORY_NNNN]` (default)
524
+ * - `"angle"`: `<CATEGORY_N>`
525
+ * - `"brace"`: `{{CATEGORY_N}}`
526
+ * - `"custom"`: declared for a `tokenTemplate` function, which `tokenize()`
527
+ * does not apply; it produces the angle format.
528
+ */
529
+ type TokenFormat = "angle" | "bracket" | "brace" | "custom";
530
+ /**
531
+ * Options accepted by `tokenize()`.
532
+ */
533
+ interface TokenizeOptions {
534
+ /**
535
+ * Categories to detect and tokenize. Defaults to all.
536
+ */
537
+ readonly categories?: readonly PiiCategory[];
538
+ /**
539
+ * Token format style. Defaults to `"bracket"`, or to `"brace"` when a
540
+ * `vault` is given.
541
+ */
542
+ readonly format?: TokenFormat;
543
+ /**
544
+ * Store the tokens in this vault. Tokens are numbered after those the vault
545
+ * already holds, and a value the vault already holds keeps its token, so one
546
+ * vault can serve every turn of a conversation; `restore(text, vault)` puts
547
+ * the values back. With a vault, values are compared exactly (not ignoring
548
+ * case) and tokens are numbered in document order. An asynchronous vault
549
+ * requires `tokenizeAsync()`.
550
+ */
551
+ readonly vault?: AnonymaVault;
552
+ /**
553
+ * Custom token template function, for `format: "custom"`.
554
+ *
555
+ * @remarks
556
+ * Not applied: `tokenize()` ignores it and produces the angle format.
557
+ *
558
+ * @param category - The PII category.
559
+ * @param counter - The incrementing counter for this category.
560
+ * @param value - The original matched value.
561
+ */
562
+ readonly tokenTemplate?: (category: string, counter: number, value: string) => string;
563
+ /**
564
+ * When `true`, identical PII values receive the same token. Defaults to `true`.
565
+ *
566
+ * @remarks
567
+ * Not applied: identical values always receive the same token.
568
+ */
569
+ readonly deterministic?: boolean;
570
+ /**
571
+ * When `true`, use aggressive detector patterns. Defaults to `false`.
572
+ */
573
+ readonly aggressive?: boolean;
574
+ /**
575
+ * Locales to enable for detection. Defaults to `["global"]`.
576
+ *
577
+ * @remarks
578
+ * Not applied: every detector runs, whatever the locale.
579
+ */
580
+ readonly locales?: readonly Locale[];
581
+ /**
582
+ * Confidence threshold - only tokenize matches at or above this score. Defaults to `0`.
583
+ */
584
+ readonly confidenceThreshold?: number;
585
+ /**
586
+ * Custom detector overrides (same as `AnonymizeOptions.customDetectors`).
587
+ */
588
+ readonly customDetectors?: Partial<Record<PiiCategory, Detector>>;
589
+ /**
590
+ * Values that should never be tokenized even when detected as PII. A
591
+ * detected value is skipped only when it equals an entry (case-insensitive
592
+ * by default); a value that merely contains an entry is tokenized.
593
+ */
594
+ readonly allowlist?: readonly string[];
595
+ /**
596
+ * When `true`, allowlist string matches are case-sensitive. Defaults to `false`.
597
+ */
598
+ readonly allowlistCaseSensitive?: boolean;
599
+ }
600
+ /**
601
+ * Options for the `encrypt` strategy.
602
+ */
603
+ interface EncryptOptions {
604
+ /**
605
+ * Passphrase used to derive an AES-256-GCM key via PBKDF2.
606
+ * Provide either `passphrase` or `keyBytes`, not both.
607
+ */
608
+ readonly passphrase?: string;
609
+ /**
610
+ * Raw key bytes (16 or 32 bytes) for AES-128 or AES-256 GCM.
611
+ * Provide either `keyBytes` or `passphrase`, not both.
612
+ */
613
+ readonly keyBytes?: Uint8Array;
614
+ /** Output encoding for the ciphertext. Defaults to `"base64"`. */
615
+ readonly encoding?: "base64" | "hex";
616
+ }
617
+ /**
618
+ * Options for the `synthesize` strategy.
619
+ */
620
+ interface SynthesizeOptions {
621
+ /**
622
+ * Optional seed string for deterministic output.
623
+ * Same seed + same value + same category always produces the same synthetic replacement.
624
+ */
625
+ readonly seed?: string;
626
+ /** Locale hint for locale-specific synthesis (e.g. phone-number format). */
627
+ readonly locale?: Locale;
628
+ }
629
+ /**
630
+ * Result of a batch processing operation.
631
+ */
632
+ /**
633
+ * A single item result from a batch processing operation.
634
+ *
635
+ * @example
636
+ * ```ts
637
+ * const results = anonymizeBatch(["alice@example.com", "bad input"]);
638
+ * for (const r of results) {
639
+ * if (r.ok) console.log(r.value.text);
640
+ * else console.error(`Item ${r.index} failed:`, r.error.message);
641
+ * }
642
+ * ```
643
+ */
644
+ type BatchResult<T> = {
645
+ readonly index: number;
646
+ readonly ok: true;
647
+ readonly value: T;
648
+ } | {
649
+ readonly index: number;
650
+ readonly ok: false;
651
+ readonly error: Error;
652
+ };
653
+ /**
654
+ * A validator function that performs checksum/format validation.
655
+ * Returns `true` if the value is valid.
656
+ */
657
+ type ValidatorFunction = (value: string) => boolean;
658
+ /**
659
+ * A strategy function that transforms a PII value to its anonymized form.
660
+ *
661
+ * @remarks
662
+ * A plugin strategy receives the detected value and the `options` of the
663
+ * {@link PluginStrategyOptions} that name it, and returns the replacement.
664
+ */
665
+ type StrategyFunction = (value: string, options?: Record<string, unknown>) => string;
666
+ /**
667
+ * An anonyma plugin: detectors, strategies and validators that
668
+ * `createAnonymizer()` adds to the anonymizer it creates.
669
+ *
670
+ * @remarks
671
+ * Plugins apply to the methods of that anonymizer. `anonymize()` and the other
672
+ * standalone functions do not use them.
673
+ *
674
+ * `createAnonymizer()` throws a `ValidationError` when two plugins have the
675
+ * same name, register a detector for the same category or a strategy under the
676
+ * same name, or when a strategy has the name of a built-in one. It throws an
677
+ * `UnknownCategoryError` for a detector or validator keyed by a name that is
678
+ * not a {@link PiiCategory}.
679
+ *
680
+ * @example
681
+ * ```ts
682
+ * const initials: AnonymaPlugin = {
683
+ * name: "initials",
684
+ * strategies: {
685
+ * initials: (value) => value.split(" ").map((word) => `${word.charAt(0)}.`).join(" "),
686
+ * },
687
+ * };
688
+ *
689
+ * createAnonymizer({ plugins: [initials] }).anonymize("Dear Jane Doe,", {
690
+ * rules: [{ category: "name", strategy: { strategy: "initials" } }],
691
+ * }).text;
692
+ * // "Dear J. D.,"
693
+ * ```
694
+ */
695
+ interface AnonymaPlugin {
696
+ /** Plugin name, unique among the plugins of an anonymizer. */
697
+ readonly name: string;
698
+ /**
699
+ * Detectors keyed by {@link PiiCategory}. Each replaces the built-in detector
700
+ * of its category, in the categories the anonymizer detects. The
701
+ * anonymizer's `customDetectors` take precedence over it.
702
+ */
703
+ readonly detectors?: Record<string, Detector>;
704
+ /**
705
+ * Strategies keyed by name, which {@link PluginStrategyOptions} name in the
706
+ * rules, the default strategy and the field rules of the anonymizer.
707
+ */
708
+ readonly strategies?: Record<string, StrategyFunction>;
709
+ /**
710
+ * Validators keyed by {@link PiiCategory}. A match of the category is kept,
711
+ * anonymized and reported only when every validator registered for the
712
+ * category accepts its value, whichever detector found it.
713
+ */
714
+ readonly validators?: Record<string, ValidatorFunction>;
715
+ }
716
+ /**
717
+ * Strategy options that name a strategy registered by a plugin
718
+ * ({@link AnonymaPlugin.strategies}). The methods of an anonymizer created
719
+ * with that plugin accept them wherever they accept {@link StrategyOptions}.
720
+ *
721
+ * @example
722
+ * ```ts
723
+ * { strategy: "initials", options: { separator: "-" } }
724
+ * ```
725
+ */
726
+ interface PluginStrategyOptions {
727
+ /** The name the plugin registers the strategy under. */
728
+ readonly strategy: string;
729
+ /** Passed to the strategy function as its second argument. */
730
+ readonly options?: Readonly<Record<string, unknown>>;
731
+ }
732
+ /**
733
+ * Built-in anonymization strategy identifiers.
734
+ */
735
+ type StrategyName = "mask" | "redact" | "pseudonymize" | "hash" | "generalize" | "tokenize" | "encrypt" | "synthesize";
736
+ /**
737
+ * Options for the `mask` strategy.
738
+ */
739
+ interface MaskOptions {
740
+ /** Character used as the mask. Defaults to `"*"`. */
741
+ readonly maskChar?: string;
742
+ /** Number of leading characters to keep visible. Defaults to `0`. */
743
+ readonly keepLeading?: number;
744
+ /** Number of trailing characters to keep visible. Defaults to `0`. */
745
+ readonly keepTrailing?: number;
746
+ /**
747
+ * When `true`, apply format-preserving masking: alphabetic chars → `X`,
748
+ * digits → `0`, separators and punctuation preserved.
749
+ *
750
+ * @example `123-45-6789` → `000-00-0000`, `john@example.com` → `XXXX@XXXXXXX.XXX`
751
+ */
752
+ readonly preserveFormat?: boolean;
753
+ }
754
+ /**
755
+ * Options for the `redact` strategy.
756
+ */
757
+ interface RedactOptions {
758
+ /** Replacement label. Defaults to `"[REDACTED]"`. */
759
+ readonly label?: string;
760
+ }
761
+ /**
762
+ * Options for the `pseudonymize` strategy.
763
+ */
764
+ interface PseudonymizeOptions {
765
+ /**
766
+ * Secret seed used for deterministic output. When provided the same input + seed
767
+ * always produces the same pseudonym, enabling consistent replacement across a dataset.
768
+ * When omitted, a random pseudonym is generated.
769
+ */
770
+ readonly seed?: string;
771
+ /** Namespace prefix appended to the pseudonym. Defaults to `"id_"`. */
772
+ readonly prefix?: string;
773
+ }
774
+ /**
775
+ * Options for the `hash` strategy.
776
+ */
777
+ interface HashOptions {
778
+ /** Number of hex characters to keep from the digest. Defaults to `16`. */
779
+ readonly truncate?: number;
780
+ /**
781
+ * Optional pepper (a per-deployment secret) mixed into the hash. Using a pepper
782
+ * ensures hashes cannot be reversed via rainbow tables.
783
+ */
784
+ readonly pepper?: string;
785
+ }
786
+ /**
787
+ * Options for the `generalize` strategy.
788
+ */
789
+ interface GeneralizeOptions {
790
+ /**
791
+ * For numeric fields: the bucket/range width. For example `10` turns `27` into `"20-29"`.
792
+ * Defaults to `10`.
793
+ */
794
+ readonly bucketSize?: number;
795
+ }
796
+ /**
797
+ * Union of all strategy option shapes.
798
+ */
799
+ type StrategyOptions = ({
800
+ strategy: "mask";
801
+ } & MaskOptions) | ({
802
+ strategy: "redact";
803
+ } & RedactOptions) | ({
804
+ strategy: "pseudonymize";
805
+ } & PseudonymizeOptions) | ({
806
+ strategy: "hash";
807
+ } & HashOptions) | ({
808
+ strategy: "generalize";
809
+ } & GeneralizeOptions) | ({
810
+ strategy: "tokenize";
811
+ } & Omit<TokenizeOptions, "categories" | "aggressive" | "locales" | "confidenceThreshold">) | ({
812
+ strategy: "encrypt";
813
+ } & EncryptOptions) | ({
814
+ strategy: "synthesize";
815
+ } & SynthesizeOptions & {
816
+ category?: PiiCategory;
817
+ });
818
+ /**
819
+ * A rule that maps a PII category to an anonymization strategy.
820
+ *
821
+ * @typeParam S - The strategy options a rule can hold. The methods of an
822
+ * anonymizer also accept {@link PluginStrategyOptions}.
823
+ */
824
+ interface AnonymizationRule<S extends StrategyOptions | PluginStrategyOptions = StrategyOptions> {
825
+ /** The PII category this rule applies to. */
826
+ readonly category: PiiCategory;
827
+ /** The strategy to apply. */
828
+ readonly strategy: S;
829
+ }
830
+ /**
831
+ * Options accepted by the top-level `anonymize()` function.
832
+ *
833
+ * @remarks
834
+ * `anonymize()`, `anonymizeAsync()` and the functions built on them apply the
835
+ * `redact`, `mask`, `pseudonymize` and `generalize` strategies, and `hash` in
836
+ * `anonymizeAsync()`. A value whose strategy is `tokenize`, `encrypt` or
837
+ * `synthesize` is redacted, with a warning; a pipeline from `"anonyma/engine"`
838
+ * applies every strategy.
839
+ *
840
+ * @typeParam S - The strategy options that `rules` and `defaultStrategy` can
841
+ * hold. The methods of an anonymizer also accept {@link PluginStrategyOptions}.
842
+ */
843
+ interface AnonymizeOptions<S extends StrategyOptions | PluginStrategyOptions = StrategyOptions> {
844
+ /**
845
+ * Per-category overrides. When specified, only the listed categories are processed;
846
+ * all others are left untouched.
847
+ */
848
+ readonly rules?: readonly AnonymizationRule<S>[];
849
+ /**
850
+ * Default strategy applied to any category not covered by `rules`.
851
+ * Defaults to `{ strategy: "redact" }`.
852
+ */
853
+ readonly defaultStrategy?: S;
854
+ /**
855
+ * When `true`, detected matches are included in the result object.
856
+ * Defaults to `false` for performance.
857
+ */
858
+ readonly includeMatches?: boolean;
859
+ /**
860
+ * Additional or overriding custom detectors per built-in category.
861
+ * Custom detectors are called instead of (not in addition to) the built-in detector
862
+ * for the specified category.
863
+ */
864
+ readonly customDetectors?: Partial<Record<PiiCategory, Detector>>;
865
+ /**
866
+ * Additional ad-hoc regex patterns to match and replace alongside built-in detectors.
867
+ * Custom pattern matches participate in the standard overlap deduplication.
868
+ */
869
+ readonly customPatterns?: readonly CustomPattern[];
870
+ /**
871
+ * When set, every detected PII entity (from all strategies) is replaced with
872
+ * this exact string, overriding per-category rules and `defaultStrategy`.
873
+ * Must be a non-empty string.
874
+ */
875
+ readonly globalReplacement?: string;
876
+ /**
877
+ * When `true`, identical PII values receive the same token across the entire
878
+ * `anonymize()` call (e.g. `EMAIL_1`), and different values get different tokens.
879
+ * Tokens are category-prefixed with incrementing counters.
880
+ * State is scoped to a single call — no cross-call leakage.
881
+ *
882
+ * @example `alice@example.com` → `EMAIL_1`, `bob@example.com` → `EMAIL_2`
883
+ */
884
+ readonly consistentTokens?: boolean;
885
+ /**
886
+ * When `true`, each detector uses its expanded, more permissive pattern set.
887
+ * This catches obfuscated or partial PII (e.g. `user [at] domain [dot] com`)
888
+ * at the cost of more false positives. Confidence scores are reduced accordingly.
889
+ */
890
+ readonly aggressive?: boolean;
891
+ /**
892
+ * Convenience enable/disable map for PII categories.
893
+ * Categories set to `true` are active; `false` or missing entries are excluded.
894
+ * When both `enabledCategories` and `rules` are provided, `rules` takes
895
+ * precedence for the categories it covers.
896
+ *
897
+ * @example
898
+ * ```ts
899
+ * anonymize(text, { enabledCategories: { email: true, phone: true, ssn: false } });
900
+ * ```
901
+ */
902
+ readonly enabledCategories?: Partial<Record<PiiCategory, boolean>>;
903
+ /**
904
+ * Exact values to exclude from detection (case-insensitive by default).
905
+ * Matches in the allowlist are skipped before strategy application. A
906
+ * detected value is skipped only when it equals an entry; a value that
907
+ * merely contains an entry is anonymized. Use `allowlistPatterns` to skip
908
+ * values by a part of them.
909
+ *
910
+ * @example `allowlist: ["noreply@company.com"]`
911
+ */
912
+ readonly allowlist?: readonly string[];
913
+ /**
914
+ * RegExp patterns for values to skip. Each is tested against the full PII
915
+ * value and skips it when it matches anywhere in it, so anchor a pattern
916
+ * with `^` and `$` to require a full match. The `g` and `y` flags are
917
+ * ignored.
918
+ *
919
+ * @example `allowlistPatterns: [/^192\.168\./]`
920
+ */
921
+ readonly allowlistPatterns?: readonly RegExp[];
922
+ /**
923
+ * When `allowlist` matching is case-sensitive. Defaults to `false` (case-insensitive).
924
+ */
925
+ readonly allowlistCaseSensitive?: boolean;
926
+ /**
927
+ * Minimum confidence score [0, 1] for a match to be anonymized.
928
+ * Matches below this threshold are left untouched. Defaults to `0` (process all).
929
+ */
930
+ readonly confidenceThreshold?: number;
931
+ /**
932
+ * Apply a built-in compliance preset, which pre-configures `enabledCategories`
933
+ * and `defaultStrategy`. Explicit `rules` and `defaultStrategy` options take
934
+ * precedence over preset values.
935
+ */
936
+ readonly preset?: CompliancePreset;
937
+ /**
938
+ * Locales to activate for locale-specific detectors.
939
+ * Defaults to `["global"]` which includes universally-formatted PII.
940
+ *
941
+ * @remarks
942
+ * Not applied: every detector runs, whatever the locale.
943
+ */
944
+ readonly locales?: readonly Locale[];
945
+ }
946
+ /**
947
+ * Result returned by `anonymize()`.
948
+ */
949
+ interface AnonymizeResult {
950
+ /** The anonymized text. */
951
+ readonly text: string;
952
+ /** Detected PII matches (only populated when `includeMatches: true`). */
953
+ readonly matches: readonly PiiMatch[];
954
+ }
955
+ /**
956
+ * A field-level rule for `anonymizeObject()` / `anonymizeRecord()`.
957
+ *
958
+ * @typeParam S - The strategy options the rule can hold. The methods of an
959
+ * anonymizer also accept {@link PluginStrategyOptions}.
960
+ */
961
+ interface FieldRule<S extends StrategyOptions | PluginStrategyOptions = StrategyOptions> {
962
+ /** The strategy to apply to this field's value. */
963
+ readonly strategy: S;
964
+ }
965
+ /**
966
+ * A mapping of object field paths → `FieldRule`.
967
+ * Dot-notation is supported for nested paths (e.g. `"user.email"`).
968
+ *
969
+ * @typeParam S - The strategy options the rules can hold. The methods of an
970
+ * anonymizer also accept {@link PluginStrategyOptions}.
971
+ */
972
+ type FieldRuleMap<S extends StrategyOptions | PluginStrategyOptions = StrategyOptions> = Readonly<Record<string, FieldRule<S>>>;
973
+ /**
974
+ * A function that finds PII matches of a specific category in a string.
975
+ *
976
+ * @param text - The input string to scan.
977
+ * @returns An array of matches (may be empty).
978
+ */
979
+ type Detector = (text: string) => PiiMatch[];
980
+ /**
981
+ * Registry of all available detectors keyed by PII category.
982
+ */
983
+ type DetectorRegistry = Readonly<Record<PiiCategory, Detector>>;
984
+ /**
985
+ * A configured, reusable anonymizer instance produced by `createAnonymizer()`.
986
+ *
987
+ * @remarks
988
+ * Its methods apply the plugins of its configuration
989
+ * ({@link AnonymizerConfig.plugins}): their rules and default strategy can
990
+ * name a plugin strategy with {@link PluginStrategyOptions}.
991
+ */
992
+ interface Anonymizer {
993
+ /**
994
+ * Anonymize a text string.
995
+ * @param text - The input text.
996
+ * @param options - Optional per-call overrides.
997
+ */
998
+ readonly anonymize: (text: string, options?: Partial<AnonymizeOptions<StrategyOptions | PluginStrategyOptions>>) => AnonymizeResult;
999
+ /**
1000
+ * Anonymize a text string asynchronously (supports `hash` and `encrypt` strategies natively).
1001
+ * @param text - The input text.
1002
+ * @param options - Optional per-call overrides.
1003
+ */
1004
+ readonly anonymizeAsync: (text: string, options?: Partial<AnonymizeOptions<StrategyOptions | PluginStrategyOptions>>) => Promise<AnonymizeResult>;
1005
+ /**
1006
+ * Detect all PII in a text string without anonymizing.
1007
+ * @param text - The input text.
1008
+ */
1009
+ readonly detect: (text: string) => PiiMatch[];
1010
+ /**
1011
+ * Anonymize specific fields in a plain record/object.
1012
+ * @param record - The input record.
1013
+ * @param rules - Field-level rules.
1014
+ */
1015
+ readonly anonymizeRecord: <T extends Record<string, unknown>>(record: T, rules: FieldRuleMap<StrategyOptions | PluginStrategyOptions>) => T;
1016
+ /**
1017
+ * Recursively anonymize all string values in a JSON-serializable object tree.
1018
+ * @param obj - The input object. Must be free of circular references.
1019
+ * @param options - Optional per-call anonymization overrides.
1020
+ */
1021
+ readonly anonymizeObject: <T extends object>(obj: T, options?: AnonymizeOptions<StrategyOptions | PluginStrategyOptions>) => T;
1022
+ /**
1023
+ * Tokenize PII in text for LLM-safe transmission.
1024
+ * @param text - The input text.
1025
+ * @param options - Tokenization options.
1026
+ */
1027
+ readonly tokenize: (text: string, options?: TokenizeOptions) => TokenizeResult;
1028
+ /**
1029
+ * Return `true` if `text` contains any detectable PII.
1030
+ * Stops scanning after the first match for performance.
1031
+ * @param text - The input text.
1032
+ */
1033
+ readonly hasPII: (text: string) => boolean;
1034
+ }
1035
+ /**
1036
+ * Configuration for `createAnonymizer()`.
1037
+ */
1038
+ interface AnonymizerConfig {
1039
+ /** Ordered list of categories to detect. Defaults to all built-in categories. */
1040
+ readonly categories?: readonly PiiCategory[];
1041
+ /**
1042
+ * Default strategy applied when no per-category rule is provided. It can name
1043
+ * a strategy of one of the `plugins`.
1044
+ */
1045
+ readonly defaultStrategy?: StrategyOptions | PluginStrategyOptions;
1046
+ /** Additional or overriding custom detectors. */
1047
+ readonly customDetectors?: Partial<Record<PiiCategory, Detector>>;
1048
+ /** Ad-hoc regex patterns applied alongside built-in detectors. */
1049
+ readonly customPatterns?: readonly CustomPattern[];
1050
+ /**
1051
+ * When set, every detected PII entity is replaced with this exact string.
1052
+ * Overrides `defaultStrategy` and per-category rules.
1053
+ */
1054
+ readonly globalReplacement?: string;
1055
+ /**
1056
+ * When `true`, identical PII values receive consistent tokens within a call.
1057
+ * @see {@link AnonymizeOptions.consistentTokens}
1058
+ */
1059
+ readonly consistentTokens?: boolean;
1060
+ /**
1061
+ * When `true`, detectors use expanded, more permissive patterns.
1062
+ * @see {@link AnonymizeOptions.aggressive}
1063
+ */
1064
+ readonly aggressive?: boolean;
1065
+ /**
1066
+ * Plugins whose detectors, strategies and validators the anonymizer applies.
1067
+ * See {@link AnonymaPlugin}.
1068
+ */
1069
+ readonly plugins?: readonly AnonymaPlugin[];
1070
+ /**
1071
+ * Apply a built-in compliance preset as the base for this anonymizer.
1072
+ */
1073
+ readonly preset?: CompliancePreset;
1074
+ /**
1075
+ * Locales to activate for locale-specific detectors.
1076
+ *
1077
+ * @remarks
1078
+ * Not applied: every detector runs, whatever the locale.
1079
+ */
1080
+ readonly locales?: readonly Locale[];
1081
+ }
1082
+
1083
+ export { type AnonymizeOptions as A, type BatchResult as B, type CompliancePreset as C, type Detector as D, type EncryptOptions as E, type FieldRuleMap as F, type GeneralizeOptions as G, type HashOptions as H, InMemoryVault as I, type DetectorRegistry as J, type KeyMaterial as K, type FieldRule as L, type MaybePromise as M, type Locale as N, type PluginStrategyOptions as O, type PiiCategory as P, type StrategyFunction as Q, type RestoreResult as R, type StrategyOptions as S, type TokenizeOptions as T, type StrategyName as U, type VaultRecord as V, type TokenFormat as W, type ValidatorFunction as X, type AnonymizeResult as a, type TokenizeResult as b, type TokenizationProvider as c, type TokenContext as d, type KeyRingManifest as e, type KeyRing as f, type ErasureReceipt as g, type TokenVault as h, type AnonymaVault as i, type SyncAnonymaVault as j, type KeyPurpose as k, type KeyState as l, type KeyVersionInfo as m, type RestoreOptions as n, type MaskOptions as o, type PseudonymizeOptions as p, type RedactOptions as q, restore as r, type SynthesizeOptions as s, type AnonymizerConfig as t, type Anonymizer as u, type PiiMatch as v, type DetokenizeResult as w, type AnonymizationRule as x, type AnonymaPlugin as y, type CustomPattern as z };