anonyma 1.0.0 → 1.1.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 (183) hide show
  1. package/CHANGELOG.md +273 -144
  2. package/README.md +427 -143
  3. package/dist/ai/index.cjs +522 -0
  4. package/dist/ai/index.cjs.map +1 -0
  5. package/dist/ai/index.d.cts +322 -0
  6. package/dist/ai/index.d.ts +322 -0
  7. package/dist/ai/index.js +505 -0
  8. package/dist/ai/index.js.map +1 -0
  9. package/dist/audit/index.cjs +359 -0
  10. package/dist/audit/index.cjs.map +1 -0
  11. package/dist/audit/index.d.cts +287 -0
  12. package/dist/audit/index.d.ts +287 -0
  13. package/dist/audit/index.js +340 -0
  14. package/dist/audit/index.js.map +1 -0
  15. package/dist/chunk-26IHMQHL.cjs +662 -0
  16. package/dist/chunk-26IHMQHL.cjs.map +1 -0
  17. package/dist/chunk-2F2GWGTB.js +174 -0
  18. package/dist/chunk-2F2GWGTB.js.map +1 -0
  19. package/dist/chunk-2NNMJ55L.cjs +45 -0
  20. package/dist/chunk-2NNMJ55L.cjs.map +1 -0
  21. package/dist/chunk-2YG7R4KJ.cjs +114 -0
  22. package/dist/chunk-2YG7R4KJ.cjs.map +1 -0
  23. package/dist/chunk-2ZZHLCEJ.js +237 -0
  24. package/dist/chunk-2ZZHLCEJ.js.map +1 -0
  25. package/dist/chunk-3CY6ATKS.cjs +308 -0
  26. package/dist/chunk-3CY6ATKS.cjs.map +1 -0
  27. package/dist/chunk-3D5ZCJ7R.js +268 -0
  28. package/dist/chunk-3D5ZCJ7R.js.map +1 -0
  29. package/dist/chunk-6LDAIJBL.js +103 -0
  30. package/dist/chunk-6LDAIJBL.js.map +1 -0
  31. package/dist/chunk-7HK2V5Q4.js +111 -0
  32. package/dist/chunk-7HK2V5Q4.js.map +1 -0
  33. package/dist/chunk-AAP472NG.js +177 -0
  34. package/dist/chunk-AAP472NG.js.map +1 -0
  35. package/dist/chunk-AP4JIUNW.js +42 -0
  36. package/dist/chunk-AP4JIUNW.js.map +1 -0
  37. package/dist/chunk-BBJPQPGP.js +457 -0
  38. package/dist/chunk-BBJPQPGP.js.map +1 -0
  39. package/dist/chunk-CRXRJZEV.cjs +82 -0
  40. package/dist/chunk-CRXRJZEV.cjs.map +1 -0
  41. package/dist/chunk-E3PICZYI.js +20 -0
  42. package/dist/chunk-E3PICZYI.js.map +1 -0
  43. package/dist/chunk-F7O2FA3F.cjs +1255 -0
  44. package/dist/chunk-F7O2FA3F.cjs.map +1 -0
  45. package/dist/chunk-FB56NAAH.cjs +243 -0
  46. package/dist/chunk-FB56NAAH.cjs.map +1 -0
  47. package/dist/chunk-G4AN7FND.js +1063 -0
  48. package/dist/chunk-G4AN7FND.js.map +1 -0
  49. package/dist/chunk-GS3FRH4K.js +294 -0
  50. package/dist/chunk-GS3FRH4K.js.map +1 -0
  51. package/dist/chunk-GYMG5OI3.cjs +186 -0
  52. package/dist/chunk-GYMG5OI3.cjs.map +1 -0
  53. package/dist/chunk-IHEIYZPL.cjs +301 -0
  54. package/dist/chunk-IHEIYZPL.cjs.map +1 -0
  55. package/dist/chunk-IJAMLYOT.cjs +1087 -0
  56. package/dist/chunk-IJAMLYOT.cjs.map +1 -0
  57. package/dist/chunk-ISL5B4LU.cjs +181 -0
  58. package/dist/chunk-ISL5B4LU.cjs.map +1 -0
  59. package/dist/chunk-JKW36IPT.js +179 -0
  60. package/dist/chunk-JKW36IPT.js.map +1 -0
  61. package/dist/chunk-KOCQBDI4.cjs +179 -0
  62. package/dist/chunk-KOCQBDI4.cjs.map +1 -0
  63. package/dist/chunk-OGNLB2KA.js +79 -0
  64. package/dist/chunk-OGNLB2KA.js.map +1 -0
  65. package/dist/chunk-PKHZ7CVI.js +28 -0
  66. package/dist/chunk-PKHZ7CVI.js.map +1 -0
  67. package/dist/chunk-QYD4F6T7.cjs +114 -0
  68. package/dist/chunk-QYD4F6T7.cjs.map +1 -0
  69. package/dist/chunk-RCW5IPPR.js +1288 -0
  70. package/dist/chunk-RCW5IPPR.js.map +1 -0
  71. package/dist/chunk-RMMKYHUN.cjs +35 -0
  72. package/dist/chunk-RMMKYHUN.cjs.map +1 -0
  73. package/dist/chunk-S4BJ2ADB.cjs +22 -0
  74. package/dist/chunk-S4BJ2ADB.cjs.map +1 -0
  75. package/dist/chunk-S7NH6CHY.cjs +462 -0
  76. package/dist/chunk-S7NH6CHY.cjs.map +1 -0
  77. package/dist/chunk-SIHPDZXA.js +176 -0
  78. package/dist/chunk-SIHPDZXA.js.map +1 -0
  79. package/dist/chunk-TW7PM3UJ.cjs +30 -0
  80. package/dist/chunk-TW7PM3UJ.cjs.map +1 -0
  81. package/dist/chunk-UA3EOFBS.cjs +1322 -0
  82. package/dist/chunk-UA3EOFBS.cjs.map +1 -0
  83. package/dist/chunk-VE4CCW7W.js +32 -0
  84. package/dist/chunk-VE4CCW7W.js.map +1 -0
  85. package/dist/chunk-W6RBCHYF.js +651 -0
  86. package/dist/chunk-W6RBCHYF.js.map +1 -0
  87. package/dist/chunk-WLJN7GIS.cjs +189 -0
  88. package/dist/chunk-WLJN7GIS.cjs.map +1 -0
  89. package/dist/chunk-YMLR375Z.js +1244 -0
  90. package/dist/chunk-YMLR375Z.js.map +1 -0
  91. package/dist/compliance/index.cjs +88 -0
  92. package/dist/compliance/index.cjs.map +1 -0
  93. package/dist/compliance/index.d.cts +277 -0
  94. package/dist/compliance/index.d.ts +277 -0
  95. package/dist/compliance/index.js +47 -0
  96. package/dist/compliance/index.js.map +1 -0
  97. package/dist/crypto.cjs +12 -136
  98. package/dist/crypto.cjs.map +1 -1
  99. package/dist/crypto.d.cts +4 -3
  100. package/dist/crypto.d.ts +4 -3
  101. package/dist/crypto.js +3 -137
  102. package/dist/crypto.js.map +1 -1
  103. package/dist/detectors/index.cjs +146 -1483
  104. package/dist/detectors/index.cjs.map +1 -1
  105. package/dist/detectors/index.d.cts +1 -1
  106. package/dist/detectors/index.d.ts +1 -1
  107. package/dist/detectors/index.js +3 -1449
  108. package/dist/detectors/index.js.map +1 -1
  109. package/dist/engine/index.cjs +441 -0
  110. package/dist/engine/index.cjs.map +1 -0
  111. package/dist/engine/index.d.cts +728 -0
  112. package/dist/engine/index.d.ts +728 -0
  113. package/dist/engine/index.js +189 -0
  114. package/dist/engine/index.js.map +1 -0
  115. package/dist/hash-2PSYNDMM.cjs +14 -0
  116. package/dist/hash-2PSYNDMM.cjs.map +1 -0
  117. package/dist/hash-CELLDNKN.js +5 -0
  118. package/dist/hash-CELLDNKN.js.map +1 -0
  119. package/dist/index.cjs +153 -2816
  120. package/dist/index.cjs.map +1 -1
  121. package/dist/index.d.cts +93 -11
  122. package/dist/index.d.ts +93 -11
  123. package/dist/index.js +13 -2791
  124. package/dist/index.js.map +1 -1
  125. package/dist/json-CKDvlRtl.d.ts +147 -0
  126. package/dist/json-s8ny-RCo.d.cts +147 -0
  127. package/dist/mcp/index.cjs +751 -0
  128. package/dist/mcp/index.cjs.map +1 -0
  129. package/dist/mcp/index.d.cts +226 -0
  130. package/dist/mcp/index.d.ts +226 -0
  131. package/dist/mcp/index.js +744 -0
  132. package/dist/mcp/index.js.map +1 -0
  133. package/dist/middleware/express.cjs +93 -0
  134. package/dist/middleware/express.cjs.map +1 -0
  135. package/dist/middleware/express.d.cts +90 -0
  136. package/dist/middleware/express.d.ts +90 -0
  137. package/dist/middleware/express.js +91 -0
  138. package/dist/middleware/express.js.map +1 -0
  139. package/dist/middleware/hono.cjs +58 -0
  140. package/dist/middleware/hono.cjs.map +1 -0
  141. package/dist/middleware/hono.d.cts +75 -0
  142. package/dist/middleware/hono.d.ts +75 -0
  143. package/dist/middleware/hono.js +56 -0
  144. package/dist/middleware/hono.js.map +1 -0
  145. package/dist/middleware/index.cjs +24 -0
  146. package/dist/middleware/index.cjs.map +1 -0
  147. package/dist/middleware/index.d.cts +106 -0
  148. package/dist/middleware/index.d.ts +106 -0
  149. package/dist/middleware/index.js +15 -0
  150. package/dist/middleware/index.js.map +1 -0
  151. package/dist/schemas.cjs +5 -5
  152. package/dist/schemas.cjs.map +1 -1
  153. package/dist/schemas.d.cts +20 -10
  154. package/dist/schemas.d.ts +20 -10
  155. package/dist/schemas.js +5 -5
  156. package/dist/schemas.js.map +1 -1
  157. package/dist/session-BdRftyZ5.d.cts +102 -0
  158. package/dist/session-Cs2zlNQp.d.ts +102 -0
  159. package/dist/stream.cjs +13 -2262
  160. package/dist/stream.cjs.map +1 -1
  161. package/dist/stream.d.cts +1 -1
  162. package/dist/stream.d.ts +1 -1
  163. package/dist/stream.js +6 -2255
  164. package/dist/stream.js.map +1 -1
  165. package/dist/types--tPm_AjY.d.ts +199 -0
  166. package/dist/types-0BJH_wqc.d.cts +199 -0
  167. package/dist/types-CPUhjvl8.d.cts +629 -0
  168. package/dist/types-Dtht33aq.d.ts +629 -0
  169. package/dist/{types-D-9HzVuy.d.cts → types-EJTj_BKY.d.cts} +38 -7
  170. package/dist/{types-D-9HzVuy.d.ts → types-EJTj_BKY.d.ts} +38 -7
  171. package/dist/types-Zt_bZvwS.d.cts +182 -0
  172. package/dist/types-Zt_bZvwS.d.ts +182 -0
  173. package/dist/validators.cjs +39 -181
  174. package/dist/validators.cjs.map +1 -1
  175. package/dist/validators.js +1 -174
  176. package/dist/validators.js.map +1 -1
  177. package/dist/vault/index.cjs +688 -0
  178. package/dist/vault/index.cjs.map +1 -0
  179. package/dist/vault/index.d.cts +385 -0
  180. package/dist/vault/index.d.ts +385 -0
  181. package/dist/vault/index.js +669 -0
  182. package/dist/vault/index.js.map +1 -0
  183. package/package.json +128 -11
@@ -0,0 +1,277 @@
1
+ import { P as PiiCategory } from '../types-EJTj_BKY.js';
2
+ import { R as RegulationId, a as RegulationProfile, S as StrategyTraits, P as ProtectionRequirement, b as Policy, c as PolicyIssue, d as PolicyDocument } from '../types--tPm_AjY.js';
3
+ export { C as CategoryRule, e as CoverageGap, L as LegalReference } from '../types--tPm_AjY.js';
4
+ import { T as TokenizationProvider, S as StrategySpec, c as PipelineSpec } from '../types-Dtht33aq.js';
5
+
6
+ /**
7
+ * @module compliance/regulations
8
+ * @description Regulation profiles: which categories of data each instrument
9
+ * brings into scope, under which provision, and what protection the
10
+ * transformed value must have.
11
+ *
12
+ * The profiles describe technical measures. They are not legal advice, and a
13
+ * profile cannot make a system compliant on its own: every profile lists the
14
+ * data elements its instrument names that this library cannot detect.
15
+ */
16
+
17
+ /**
18
+ * Every regulation profile, keyed by identifier.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { REGULATIONS } from "anonyma/compliance";
23
+ *
24
+ * for (const rule of REGULATIONS.hipaa.rules) {
25
+ * console.log(rule.category, rule.references[0]?.citation);
26
+ * }
27
+ * ```
28
+ */
29
+ declare const REGULATIONS: Readonly<Record<RegulationId, RegulationProfile>>;
30
+ /**
31
+ * Whether `id` names a regulation profile.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * isRegulationId("hipaa"); // true
36
+ * isRegulationId("sox"); // false
37
+ * ```
38
+ */
39
+ declare function isRegulationId(id: unknown): id is RegulationId;
40
+ /**
41
+ * Get a regulation profile.
42
+ *
43
+ * @param id - The regulation identifier.
44
+ * @returns The profile.
45
+ * @throws {@link ValidationError} When `id` does not name a regulation profile.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * getRegulation("pci-dss").rules.find((rule) => rule.category === "credit-card")?.requirement;
50
+ * // { keyed: true, maxRevealed: { leading: 6, trailing: 4 } }
51
+ * ```
52
+ */
53
+ declare function getRegulation(id: RegulationId): RegulationProfile;
54
+ /**
55
+ * One row of the compliance mapping matrix.
56
+ */
57
+ interface MatrixRow {
58
+ /** The regulation. */
59
+ readonly regulation: RegulationId;
60
+ /** The category of data. */
61
+ readonly category: PiiCategory;
62
+ /** Citations that bring the category into scope. */
63
+ readonly citations: readonly string[];
64
+ /** The minimum protection, in words. */
65
+ readonly requirement: string;
66
+ /** The strategy the built-in preset applies. */
67
+ readonly recommended: string;
68
+ }
69
+ /**
70
+ * The compliance mapping matrix as data: one row per regulation and category.
71
+ *
72
+ * @returns The rows, ordered by regulation and then by category.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * complianceMatrix().filter((row) => row.category === "credit-card");
77
+ * ```
78
+ */
79
+ declare function complianceMatrix(): MatrixRow[];
80
+
81
+ /**
82
+ * @module compliance/traits
83
+ * @description Describes what a strategy configuration does to a value, and
84
+ * checks it against the protection a regulation requires.
85
+ */
86
+
87
+ /**
88
+ * What is known about the tokenization provider behind a `tokenize` strategy.
89
+ */
90
+ type TokenizationInfo = Pick<TokenizationProvider, "scheme" | "reversible">;
91
+ /**
92
+ * Describe what a strategy does to a value.
93
+ *
94
+ * @param spec - The strategy.
95
+ * @param tokenization - The provider behind a `tokenize` strategy. When it is
96
+ * not given, `tokenize` is described as its most permissive form: reversible
97
+ * and computed from the value with a key.
98
+ * @returns The traits of the strategy.
99
+ *
100
+ * @remarks
101
+ * - `pseudonymize` with a seed is described as derived and **not** keyed: the
102
+ * 1.x construction is a non-cryptographic hash that can be recomputed from
103
+ * one known pair.
104
+ * - `generalize` is described as revealing everything, because numeric input
105
+ * keeps all but its last digits.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * describeStrategy({ strategy: "mask", keepTrailing: 4 });
110
+ * // { reversible: false, derived: false, keyed: false, linkable: false, revealed: { leading: 0, trailing: 4 } }
111
+ * ```
112
+ */
113
+ declare function describeStrategy(spec: StrategySpec, tokenization?: TokenizationInfo): StrategyTraits;
114
+ /**
115
+ * Check traits against a requirement.
116
+ *
117
+ * @param traits - What the strategy does.
118
+ * @param requirement - What the regulation requires.
119
+ * @returns One short reason per violated restriction; empty when the requirement is met.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * checkRequirement(describeStrategy({ strategy: "hash" }), { keyed: true });
124
+ * // ["the output is computed from the value without a secret key"]
125
+ * ```
126
+ */
127
+ declare function checkRequirement(traits: StrategyTraits, requirement: ProtectionRequirement): string[];
128
+
129
+ /**
130
+ * @module compliance/policy
131
+ * @description The policy document parser: turns untrusted JSON into a checked
132
+ * {@link Policy}, reporting every structural problem and every requirement of
133
+ * an extended regulation that the document violates.
134
+ */
135
+
136
+ /**
137
+ * Options accepted by {@link checkPolicy} and {@link parsePolicy}.
138
+ */
139
+ interface PolicyOptions {
140
+ /**
141
+ * The provider that will back `tokenize` strategies. Requirements such as
142
+ * "not derived from the value" depend on it.
143
+ */
144
+ readonly tokenization?: TokenizationInfo;
145
+ }
146
+ /**
147
+ * Result of {@link checkPolicy}.
148
+ */
149
+ interface PolicyCheck {
150
+ /** The checked policy; absent when the document has errors. */
151
+ readonly policy?: Policy;
152
+ /** Every problem found, errors first. */
153
+ readonly issues: readonly PolicyIssue[];
154
+ }
155
+ /**
156
+ * Check a policy document without throwing.
157
+ *
158
+ * @param input - The document, typically the result of `JSON.parse`.
159
+ * @param options - What is known about the runtime the policy will run in.
160
+ * @returns The policy when there are no errors, and every issue found.
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * const { policy, issues } = checkPolicy({
165
+ * version: 1,
166
+ * id: "payments",
167
+ * extends: ["pci-dss"],
168
+ * rules: { "credit-card": { strategy: "mask", keepLeading: 8, keepTrailing: 4 } },
169
+ * });
170
+ * // policy === undefined
171
+ * // issues[0].code === "requirement-violated"
172
+ * // issues[0].reference.citation === "PCI DSS v4.0.1 Req. 3.4.1"
173
+ * ```
174
+ */
175
+ declare function checkPolicy(input: unknown, options?: PolicyOptions): PolicyCheck;
176
+ /**
177
+ * Parse and check a policy document.
178
+ *
179
+ * @param input - The document, typically the result of `JSON.parse`.
180
+ * @param options - What is known about the runtime the policy will run in.
181
+ * @returns The checked {@link Policy}.
182
+ * @throws {@link PolicyError} When the document is malformed or violates a requirement of a
183
+ * regulation it extends. `issues` lists every problem.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * import { compilePipeline } from "anonyma/engine";
188
+ * import { parsePolicy, policyToSpec } from "anonyma/compliance";
189
+ *
190
+ * const policy = parsePolicy(JSON.parse(await readFile("policy.json", "utf8")));
191
+ * const pipeline = compilePipeline(policyToSpec(policy));
192
+ * ```
193
+ */
194
+ declare function parsePolicy(input: unknown, options?: PolicyOptions): Policy;
195
+ /**
196
+ * Convert a checked policy into a pipeline specification for
197
+ * `compilePipeline()`.
198
+ *
199
+ * @param policy - A policy returned by {@link parsePolicy} or {@link checkPolicy}.
200
+ * @returns The equivalent {@link PipelineSpec}.
201
+ *
202
+ * @example
203
+ * ```ts
204
+ * const pipeline = compilePipeline(policyToSpec(policy), { tokenization });
205
+ * ```
206
+ */
207
+ declare function policyToSpec(policy: Policy): PipelineSpec;
208
+ /**
209
+ * The policy document equivalent to a regulation profile with its recommended
210
+ * strategies — a starting point for a custom policy.
211
+ *
212
+ * @param regulation - The regulation to start from.
213
+ * @returns A policy document that extends the regulation.
214
+ *
215
+ * @example
216
+ * ```ts
217
+ * const document = { ...regulationPolicy("hipaa"), id: "clinic", allow: ["noreply@clinic.example"] };
218
+ * const policy = parsePolicy(document);
219
+ * ```
220
+ */
221
+ declare function regulationPolicy(regulation: RegulationId): PolicyDocument;
222
+
223
+ /**
224
+ * @module compliance/erasure
225
+ * @description The right-to-be-forgotten protocol: what has to happen for an
226
+ * erasure request to be honoured, depending on how the data was transformed.
227
+ */
228
+
229
+ /**
230
+ * What an erasure request requires for data transformed with a given strategy.
231
+ *
232
+ * - `"none"`: the output is not computed from the value and cannot be
233
+ * restored, so nothing about the person remains to erase.
234
+ * - `"delete-vault-entries"`: delete the vault records of the data subject
235
+ * (`KeyedTokenizer.forgetSubject()` or `forgetToken()`); the tokens left in
236
+ * downstream data no longer resolve.
237
+ * - `"destroy-key"`: discard the key version (`shredKey()`); everything
238
+ * sealed or keyed under it becomes unrecoverable or unlinkable. This affects
239
+ * every data subject under that key.
240
+ * - `"delete-outputs"`: the outputs themselves have to be deleted or
241
+ * re-processed, because anyone can recompute them from a guessed value.
242
+ */
243
+ type ErasureAction = "none" | "delete-vault-entries" | "destroy-key" | "delete-outputs";
244
+ /**
245
+ * How to honour an erasure request for one strategy.
246
+ */
247
+ interface ErasurePlan {
248
+ /** What has to be done. */
249
+ readonly action: ErasureAction;
250
+ /** Whether outputs that stay in downstream data can still be linked to the person afterwards. */
251
+ readonly linkableAfterwards: boolean;
252
+ /** Why, in one sentence. */
253
+ readonly reason: string;
254
+ }
255
+ /**
256
+ * Determine what an erasure request requires for data transformed with `spec`.
257
+ *
258
+ * The distinction that matters is between outputs that are gone for good
259
+ * (redaction, masking, random pseudonyms), outputs that only a key or vault
260
+ * can connect back to the person (tokens, ciphertext, keyed hashes), and
261
+ * outputs that anyone can connect back by recomputing them (unkeyed hashes).
262
+ *
263
+ * @param spec - The strategy the data was transformed with.
264
+ * @param tokenization - The provider behind a `tokenize` strategy.
265
+ * @returns The erasure plan.
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * planErasure({ strategy: "redact" }).action; // "none"
270
+ * planErasure({ strategy: "hash" }).action; // "delete-outputs"
271
+ * planErasure({ strategy: "tokenize" }, { scheme: "keyed", reversible: true }).action; // "delete-vault-entries"
272
+ * planErasure({ strategy: "encrypt" }).action; // "destroy-key"
273
+ * ```
274
+ */
275
+ declare function planErasure(spec: StrategySpec, tokenization?: TokenizationInfo): ErasurePlan;
276
+
277
+ export { type ErasureAction, type ErasurePlan, type MatrixRow, Policy, type PolicyCheck, PolicyDocument, PolicyIssue, type PolicyOptions, ProtectionRequirement, REGULATIONS, RegulationId, RegulationProfile, StrategyTraits, type TokenizationInfo, checkPolicy, checkRequirement, complianceMatrix, describeStrategy, getRegulation, isRegulationId, parsePolicy, planErasure, policyToSpec, regulationPolicy };
@@ -0,0 +1,47 @@
1
+ import { describeStrategy } from '../chunk-YMLR375Z.js';
2
+ export { REGULATIONS, checkPolicy, checkRequirement, complianceMatrix, describeStrategy, getRegulation, isRegulationId, parsePolicy, policyToSpec, regulationPolicy } from '../chunk-YMLR375Z.js';
3
+ import '../chunk-3D5ZCJ7R.js';
4
+ import '../chunk-RCW5IPPR.js';
5
+ import '../chunk-SIHPDZXA.js';
6
+ import '../chunk-2F2GWGTB.js';
7
+
8
+ // src/compliance/erasure.ts
9
+ function planErasure(spec, tokenization) {
10
+ const traits = describeStrategy(spec, tokenization);
11
+ if (spec.strategy === "tokenize" && traits.reversible) {
12
+ const stateless = tokenization?.scheme === "sealed";
13
+ return stateless ? {
14
+ action: "destroy-key",
15
+ linkableAfterwards: false,
16
+ reason: "Sealed tokens carry the value; only destroying the key version makes them unrecoverable."
17
+ } : {
18
+ action: "delete-vault-entries",
19
+ linkableAfterwards: traits.derived,
20
+ reason: traits.derived ? "Deleting the vault records makes the tokens unresolvable; the key holder can still recompute a token from a guessed value until the key version is destroyed." : "Deleting the session or vault records makes the tokens unresolvable, and the tokens say nothing about the value."
21
+ };
22
+ }
23
+ if (traits.reversible || traits.derived && traits.keyed) {
24
+ return {
25
+ action: "destroy-key",
26
+ linkableAfterwards: false,
27
+ reason: "The output can only be restored or recomputed with the key; destroying the key version ends that."
28
+ };
29
+ }
30
+ if (traits.derived || traits.revealed === "all") {
31
+ return {
32
+ action: "delete-outputs",
33
+ linkableAfterwards: true,
34
+ reason: "The output is computed from the value without a secret, so anyone can recompute it from a guessed value; it remains personal data."
35
+ };
36
+ }
37
+ const partial = traits.revealed.leading + traits.revealed.trailing > 0;
38
+ return {
39
+ action: "none",
40
+ linkableAfterwards: partial,
41
+ reason: partial ? "The value cannot be restored, but the characters left visible may still help to single a person out." : "The output is not computed from the value and cannot be restored."
42
+ };
43
+ }
44
+
45
+ export { planErasure };
46
+ //# sourceMappingURL=index.js.map
47
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/compliance/erasure.ts"],"names":[],"mappings":";;;;;;;;AA0DO,SAAS,WAAA,CAAY,MAAoB,YAAA,EAA8C;AAC5F,EAAA,MAAM,MAAA,GAAS,gBAAA,CAAiB,IAAA,EAAM,YAAY,CAAA;AAElD,EAAA,IAAI,IAAA,CAAK,QAAA,KAAa,UAAA,IAAc,MAAA,CAAO,UAAA,EAAY;AACrD,IAAA,MAAM,SAAA,GAAY,cAAc,MAAA,KAAW,QAAA;AAC3C,IAAA,OAAO,SAAA,GACH;AAAA,MACE,MAAA,EAAQ,aAAA;AAAA,MACR,kBAAA,EAAoB,KAAA;AAAA,MACpB,MAAA,EACE;AAAA,KACJ,GACA;AAAA,MACE,MAAA,EAAQ,sBAAA;AAAA,MACR,oBAAoB,MAAA,CAAO,OAAA;AAAA,MAC3B,MAAA,EAAQ,MAAA,CAAO,OAAA,GACX,+JAAA,GACA;AAAA,KACN;AAAA,EACN;AACA,EAAA,IAAI,MAAA,CAAO,UAAA,IAAe,MAAA,CAAO,OAAA,IAAW,OAAO,KAAA,EAAQ;AACzD,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,aAAA;AAAA,MACR,kBAAA,EAAoB,KAAA;AAAA,MACpB,MAAA,EACE;AAAA,KACJ;AAAA,EACF;AACA,EAAA,IAAI,MAAA,CAAO,OAAA,IAAW,MAAA,CAAO,QAAA,KAAa,KAAA,EAAO;AAC/C,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,gBAAA;AAAA,MACR,kBAAA,EAAoB,IAAA;AAAA,MACpB,MAAA,EACE;AAAA,KACJ;AAAA,EACF;AACA,EAAA,MAAM,UAAU,MAAA,CAAO,QAAA,CAAS,OAAA,GAAU,MAAA,CAAO,SAAS,QAAA,GAAW,CAAA;AACrE,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,MAAA;AAAA,IACR,kBAAA,EAAoB,OAAA;AAAA,IACpB,MAAA,EAAQ,UACJ,sGAAA,GACA;AAAA,GACN;AACF","file":"index.js","sourcesContent":["/**\n * @module compliance/erasure\n * @description The right-to-be-forgotten protocol: what has to happen for an\n * erasure request to be honoured, depending on how the data was transformed.\n */\n\nimport type { StrategySpec } from \"../engine/types.js\";\nimport { describeStrategy } from \"./traits.js\";\nimport type { TokenizationInfo } from \"./traits.js\";\n\n/**\n * What an erasure request requires for data transformed with a given strategy.\n *\n * - `\"none\"`: the output is not computed from the value and cannot be\n * restored, so nothing about the person remains to erase.\n * - `\"delete-vault-entries\"`: delete the vault records of the data subject\n * (`KeyedTokenizer.forgetSubject()` or `forgetToken()`); the tokens left in\n * downstream data no longer resolve.\n * - `\"destroy-key\"`: discard the key version (`shredKey()`); everything\n * sealed or keyed under it becomes unrecoverable or unlinkable. This affects\n * every data subject under that key.\n * - `\"delete-outputs\"`: the outputs themselves have to be deleted or\n * re-processed, because anyone can recompute them from a guessed value.\n */\nexport type ErasureAction = \"none\" | \"delete-vault-entries\" | \"destroy-key\" | \"delete-outputs\";\n\n/**\n * How to honour an erasure request for one strategy.\n */\nexport interface ErasurePlan {\n /** What has to be done. */\n readonly action: ErasureAction;\n /** Whether outputs that stay in downstream data can still be linked to the person afterwards. */\n readonly linkableAfterwards: boolean;\n /** Why, in one sentence. */\n readonly reason: string;\n}\n\n/**\n * Determine what an erasure request requires for data transformed with `spec`.\n *\n * The distinction that matters is between outputs that are gone for good\n * (redaction, masking, random pseudonyms), outputs that only a key or vault\n * can connect back to the person (tokens, ciphertext, keyed hashes), and\n * outputs that anyone can connect back by recomputing them (unkeyed hashes).\n *\n * @param spec - The strategy the data was transformed with.\n * @param tokenization - The provider behind a `tokenize` strategy.\n * @returns The erasure plan.\n *\n * @example\n * ```ts\n * planErasure({ strategy: \"redact\" }).action; // \"none\"\n * planErasure({ strategy: \"hash\" }).action; // \"delete-outputs\"\n * planErasure({ strategy: \"tokenize\" }, { scheme: \"keyed\", reversible: true }).action; // \"delete-vault-entries\"\n * planErasure({ strategy: \"encrypt\" }).action; // \"destroy-key\"\n * ```\n */\nexport function planErasure(spec: StrategySpec, tokenization?: TokenizationInfo): ErasurePlan {\n const traits = describeStrategy(spec, tokenization);\n\n if (spec.strategy === \"tokenize\" && traits.reversible) {\n const stateless = tokenization?.scheme === \"sealed\";\n return stateless\n ? {\n action: \"destroy-key\",\n linkableAfterwards: false,\n reason:\n \"Sealed tokens carry the value; only destroying the key version makes them unrecoverable.\",\n }\n : {\n action: \"delete-vault-entries\",\n linkableAfterwards: traits.derived,\n reason: traits.derived\n ? \"Deleting the vault records makes the tokens unresolvable; the key holder can still recompute a token from a guessed value until the key version is destroyed.\"\n : \"Deleting the session or vault records makes the tokens unresolvable, and the tokens say nothing about the value.\",\n };\n }\n if (traits.reversible || (traits.derived && traits.keyed)) {\n return {\n action: \"destroy-key\",\n linkableAfterwards: false,\n reason:\n \"The output can only be restored or recomputed with the key; destroying the key version ends that.\",\n };\n }\n if (traits.derived || traits.revealed === \"all\") {\n return {\n action: \"delete-outputs\",\n linkableAfterwards: true,\n reason:\n \"The output is computed from the value without a secret, so anyone can recompute it from a guessed value; it remains personal data.\",\n };\n }\n const partial = traits.revealed.leading + traits.revealed.trailing > 0;\n return {\n action: \"none\",\n linkableAfterwards: partial,\n reason: partial\n ? \"The value cannot be restored, but the characters left visible may still help to single a person out.\"\n : \"The output is not computed from the value and cannot be restored.\",\n };\n}\n"]}
package/dist/crypto.cjs CHANGED
@@ -1,142 +1,18 @@
1
1
  'use strict';
2
2
 
3
- // src/errors.ts
4
- var AnonymaError = class extends Error {
5
- /** Machine-readable error code. */
6
- code;
7
- constructor(message, code) {
8
- super(message);
9
- this.name = "AnonymaError";
10
- this.code = code;
11
- Object.setPrototypeOf(this, new.target.prototype);
12
- }
13
- };
14
- var CryptoNotAvailableError = class extends AnonymaError {
15
- constructor() {
16
- super(
17
- "The Web Crypto API (globalThis.crypto.subtle) is not available in this environment. Upgrade to Node.js \u2265 18 or use a polyfill.",
18
- "CRYPTO_NOT_AVAILABLE"
19
- );
20
- this.name = "CryptoNotAvailableError";
21
- Object.setPrototypeOf(this, new.target.prototype);
22
- }
23
- };
24
- var EncryptionError = class extends AnonymaError {
25
- /** The operation that failed (`"encrypt"` or `"decrypt"`). */
26
- operation;
27
- constructor(operation, cause) {
28
- super(
29
- `Encryption operation "${operation}" failed.${cause instanceof Error ? ` Cause: ${cause.message}` : ""}`,
30
- "ENCRYPTION_ERROR"
31
- );
32
- this.name = "EncryptionError";
33
- this.operation = operation;
34
- if (cause !== void 0) {
35
- this.cause = cause;
36
- }
37
- Object.setPrototypeOf(this, new.target.prototype);
38
- }
39
- };
3
+ var chunk2YG7R4KJ_cjs = require('./chunk-2YG7R4KJ.cjs');
4
+ require('./chunk-TW7PM3UJ.cjs');
5
+ require('./chunk-WLJN7GIS.cjs');
40
6
 
41
- // src/strategies/encrypt.ts
42
- function requireCrypto() {
43
- if (typeof globalThis.crypto.subtle === "undefined") throw new CryptoNotAvailableError();
44
- return globalThis.crypto.subtle;
45
- }
46
- function toBase64(buf) {
47
- return btoa(String.fromCharCode(...new Uint8Array(buf)));
48
- }
49
- function fromBase64(s) {
50
- return Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
51
- }
52
- function toHex(buf) {
53
- return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
54
- }
55
- function fromHex(s) {
56
- const bytes = [];
57
- for (let i = 0; i < s.length; i += 2) bytes.push(parseInt(s.slice(i, i + 2), 16));
58
- return new Uint8Array(bytes);
59
- }
60
- async function deriveKey(subtle, passphrase, salt) {
61
- const enc = new TextEncoder();
62
- const baseKey = await subtle.importKey(
63
- "raw",
64
- enc.encode(passphrase),
65
- "PBKDF2",
66
- false,
67
- ["deriveKey"]
68
- );
69
- return subtle.deriveKey(
70
- { name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" },
71
- baseKey,
72
- { name: "AES-GCM", length: 256 },
73
- false,
74
- ["encrypt", "decrypt"]
75
- );
76
- }
77
- async function importRawKey(subtle, keyBytes) {
78
- if (keyBytes.length !== 16 && keyBytes.length !== 32) {
79
- throw new EncryptionError("encrypt", new Error("keyBytes must be 16 or 32 bytes"));
80
- }
81
- return subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
82
- }
83
- async function encrypt(value, options) {
84
- const subtle = requireCrypto();
85
- const encoding = options.encoding ?? "base64";
86
- try {
87
- const enc = new TextEncoder();
88
- const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
89
- let key;
90
- if (options.keyBytes) {
91
- key = await importRawKey(subtle, options.keyBytes);
92
- } else if (options.passphrase) {
93
- const salt = enc.encode("anonyma_kdf_v1");
94
- key = await deriveKey(subtle, options.passphrase, salt);
95
- } else {
96
- throw new EncryptionError("encrypt", new Error("Provide `passphrase` or `keyBytes`"));
97
- }
98
- const cipherBuf = await subtle.encrypt(
99
- { name: "AES-GCM", iv },
100
- key,
101
- enc.encode(value)
102
- );
103
- const encode = encoding === "hex" ? toHex : toBase64;
104
- return `${encoding}:${encode(iv.buffer)}:${encode(cipherBuf)}`;
105
- } catch (err) {
106
- if (err instanceof EncryptionError) throw err;
107
- throw new EncryptionError("encrypt", err);
108
- }
109
- }
110
- async function decrypt(ciphertext, options) {
111
- const subtle = requireCrypto();
112
- const parts = ciphertext.split(":");
113
- if (parts.length !== 3) {
114
- throw new EncryptionError("decrypt", new Error("Malformed ciphertext \u2014 expected `encoding:iv:payload`"));
115
- }
116
- const [encoding, ivEncoded, payloadEncoded] = parts;
117
- const decode = encoding === "hex" ? fromHex : fromBase64;
118
- try {
119
- const iv = decode(ivEncoded);
120
- const payload = decode(payloadEncoded);
121
- const enc = new TextEncoder();
122
- let key;
123
- if (options.keyBytes) {
124
- key = await importRawKey(subtle, options.keyBytes);
125
- } else if (options.passphrase) {
126
- const salt = enc.encode("anonyma_kdf_v1");
127
- key = await deriveKey(subtle, options.passphrase, salt);
128
- } else {
129
- throw new EncryptionError("decrypt", new Error("Provide `passphrase` or `keyBytes`"));
130
- }
131
- const plainBuf = await subtle.decrypt({ name: "AES-GCM", iv }, key, payload);
132
- return new TextDecoder().decode(plainBuf);
133
- } catch (err) {
134
- if (err instanceof EncryptionError) throw err;
135
- throw new EncryptionError("decrypt", err);
136
- }
137
- }
138
7
 
139
- exports.decrypt = decrypt;
140
- exports.encrypt = encrypt;
8
+
9
+ Object.defineProperty(exports, "decrypt", {
10
+ enumerable: true,
11
+ get: function () { return chunk2YG7R4KJ_cjs.decrypt; }
12
+ });
13
+ Object.defineProperty(exports, "encrypt", {
14
+ enumerable: true,
15
+ get: function () { return chunk2YG7R4KJ_cjs.encrypt; }
16
+ });
141
17
  //# sourceMappingURL=crypto.cjs.map
142
18
  //# sourceMappingURL=crypto.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/strategies/encrypt.ts"],"names":[],"mappings":";;;AAwBO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA;AAAA,EAEtB,IAAA;AAAA,EAET,WAAA,CAAY,SAAiB,IAAA,EAAc;AAChD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAEZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,CAAA;AA0EO,IAAM,uBAAA,GAAN,cAAsC,YAAA,CAAa;AAAA,EACjD,WAAA,GAAc;AACnB,IAAA,KAAA;AAAA,MACE,qIAAA;AAAA,MAEA;AAAA,KACF;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,CAAA;AAUO,IAAM,eAAA,GAAN,cAA8B,YAAA,CAAa;AAAA;AAAA,EAEhC,SAAA;AAAA,EAET,WAAA,CAAY,WAAkC,KAAA,EAAiB;AACpE,IAAA,KAAA;AAAA,MACE,CAAA,sBAAA,EAAyB,SAAS,CAAA,SAAA,EAAY,KAAA,YAAiB,QAAQ,CAAA,QAAA,EAAW,KAAA,CAAM,OAAO,CAAA,CAAA,GAAK,EAAE,CAAA,CAAA;AAAA,MACtG;AAAA,KACF;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,SAA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W,GAAG,CAAA;AAAA,EAC1C;AACF","file":"crypto.cjs","sourcesContent":["/**\n * @module errors\n * @description Typed error classes for the anonyma library.\n *\n * All errors extend `AnonymaError` so consumers can use a single `instanceof` check.\n *\n * @example\n * ```ts\n * import { AnonymaError, ValidationError } from \"anonyma\";\n *\n * try {\n * mask(value, { keepLeading: -1 });\n * } catch (err) {\n * if (err instanceof ValidationError) {\n * console.error(\"bad input:\", err.message, err.field);\n * }\n * }\n * ```\n */\n\n/**\n * Base class for all errors thrown by the anonyma library.\n * Consumers can use `err instanceof AnonymaError` to narrowly handle library errors.\n */\nexport class AnonymaError extends Error {\n /** Machine-readable error code. */\n public readonly code: string;\n\n public constructor(message: string, code: string) {\n super(message);\n this.name = \"AnonymaError\";\n this.code = code;\n // Maintain proper prototype chain in transpiled ES5 environments.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a function receives an argument that fails validation.\n *\n * @example\n * ```ts\n * throw new ValidationError(\"keepLeading\", \"must be a non-negative integer\");\n * ```\n */\nexport class ValidationError extends AnonymaError {\n /** The name of the invalid field or parameter. */\n public readonly field: string;\n\n public constructor(field: string, reason: string) {\n super(`Validation failed for \\`${field}\\`: ${reason}`, \"VALIDATION_ERROR\");\n this.name = \"ValidationError\";\n this.field = field;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an unsupported strategy name is encountered.\n *\n * @example\n * ```ts\n * throw new UnsupportedStrategyError(\"foobar\");\n * ```\n */\nexport class UnsupportedStrategyError extends AnonymaError {\n /** The strategy name that was not recognised. */\n public readonly strategy: string;\n\n public constructor(strategy: string) {\n super(\n `Unsupported anonymization strategy: \"${strategy}\". ` +\n `Supported strategies are: mask, redact, pseudonymize, hash, generalize.`,\n \"UNSUPPORTED_STRATEGY\",\n );\n this.name = \"UnsupportedStrategyError\";\n this.strategy = strategy;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an unknown PII category is referenced in a rule or config.\n *\n * @example\n * ```ts\n * throw new UnknownCategoryError(\"passport\");\n * ```\n */\nexport class UnknownCategoryError extends AnonymaError {\n /** The category name that was not recognised. */\n public readonly category: string;\n\n public constructor(category: string) {\n super(\n `Unknown PII category: \"${category}\". ` +\n `Supported categories are: email, phone, ssn, credit-card, ipv4, ipv6, url, iban, date-of-birth.`,\n \"UNKNOWN_CATEGORY\",\n );\n this.name = \"UnknownCategoryError\";\n this.category = category;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when the runtime environment does not support a required Web Crypto API.\n * This is only relevant for the `hash` and `encrypt` strategies.\n */\nexport class CryptoNotAvailableError extends AnonymaError {\n public constructor() {\n super(\n \"The Web Crypto API (globalThis.crypto.subtle) is not available in this environment. \" +\n \"Upgrade to Node.js ≥ 18 or use a polyfill.\",\n \"CRYPTO_NOT_AVAILABLE\",\n );\n this.name = \"CryptoNotAvailableError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when encryption or decryption fails.\n *\n * @example\n * ```ts\n * throw new EncryptionError(\"encrypt\", originalError);\n * ```\n */\nexport class EncryptionError extends AnonymaError {\n /** The operation that failed (`\"encrypt\"` or `\"decrypt\"`). */\n public readonly operation: \"encrypt\" | \"decrypt\";\n\n public constructor(operation: \"encrypt\" | \"decrypt\", cause?: unknown) {\n super(\n `Encryption operation \"${operation}\" failed.${cause instanceof Error ? ` Cause: ${cause.message}` : \"\"}`,\n \"ENCRYPTION_ERROR\",\n );\n this.name = \"EncryptionError\";\n this.operation = operation;\n if (cause !== undefined) {\n (this as { cause?: unknown }).cause = cause;\n }\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an unknown compliance preset name is referenced.\n *\n * @example\n * ```ts\n * throw new PresetNotFoundError(\"unknown-preset\");\n * ```\n */\nexport class PresetNotFoundError extends AnonymaError {\n /** The preset name that was not recognised. */\n public readonly preset: string;\n\n public constructor(preset: string) {\n super(\n `Unknown compliance preset: \"${preset}\". ` +\n `Available presets are: gdpr, hipaa, ccpa, pci-dss, sox, ferpa.`,\n \"PRESET_NOT_FOUND\",\n );\n this.name = \"PresetNotFoundError\";\n this.preset = preset;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when an allowlist configuration entry is invalid.\n *\n * @example\n * ```ts\n * throw new AllowlistMatchError(\"allowlist[0]\", \"must be a non-empty string\");\n * ```\n */\nexport class AllowlistMatchError extends AnonymaError {\n /** The allowlist entry or field that was invalid. */\n public readonly field: string;\n\n public constructor(field: string, reason: string) {\n super(`Invalid allowlist configuration for \\`${field}\\`: ${reason}`, \"ALLOWLIST_MATCH_ERROR\");\n this.name = \"AllowlistMatchError\";\n this.field = field;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a batch processing operation encounters errors.\n * Contains partial results for items that succeeded.\n *\n * @example\n * ```ts\n * try {\n * anonymizeBatch(texts);\n * } catch (err) {\n * if (err instanceof BatchProcessingError) {\n * console.log(`${err.failed} items failed, ${err.succeeded} succeeded`);\n * }\n * }\n * ```\n */\nexport class BatchProcessingError extends AnonymaError {\n /** Number of items that succeeded. */\n public readonly succeeded: number;\n /** Number of items that failed. */\n public readonly failed: number;\n /** Total items submitted. */\n public readonly total: number;\n\n public constructor(succeeded: number, failed: number, total: number) {\n super(\n `Batch processing completed with errors: ${String(succeeded)}/${String(total)} succeeded, ${String(failed)} failed.`,\n \"BATCH_PROCESSING_ERROR\",\n );\n this.name = \"BatchProcessingError\";\n this.succeeded = succeeded;\n this.failed = failed;\n this.total = total;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n","/**\n * @module strategies/encrypt\n * @description The `encrypt` anonymization strategy — uses AES-GCM via the\n * Web Crypto API (Node ≥ 18 / browsers with Web Crypto support).\n *\n * The output format is `\"<encoding>:<iv>:<ciphertext>\"` where `<iv>` is the\n * random 12-byte initialisation vector and `<ciphertext>` is the encrypted\n * payload. Both parts are encoded in the same format (base64 or hex).\n *\n * @throws {@link CryptoNotAvailableError} When `globalThis.crypto.subtle` is not present.\n * @throws {@link EncryptionError} When the underlying Web Crypto operation fails.\n */\n\nimport { CryptoNotAvailableError, EncryptionError } from \"../errors.js\";\nimport type { EncryptOptions } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction requireCrypto(): SubtleCrypto {\n if (typeof globalThis.crypto.subtle === \"undefined\") throw new CryptoNotAvailableError();\n return globalThis.crypto.subtle;\n}\n\nfunction toBase64(buf: ArrayBuffer): string {\n return btoa(String.fromCharCode(...new Uint8Array(buf)));\n}\n\nfunction fromBase64(s: string): Uint8Array {\n return Uint8Array.from(atob(s), (c) => c.charCodeAt(0));\n}\n\nfunction toHex(buf: ArrayBuffer): string {\n return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction fromHex(s: string): Uint8Array {\n const bytes: number[] = [];\n for (let i = 0; i < s.length; i += 2) bytes.push(parseInt(s.slice(i, i + 2), 16));\n return new Uint8Array(bytes);\n}\n\n/**\n * Derive a 256-bit AES-GCM key from a passphrase string using PBKDF2 + SHA-256.\n *\n * @internal\n */\nasync function deriveKey(\n subtle: SubtleCrypto,\n passphrase: string,\n salt: Uint8Array,\n): Promise<CryptoKey> {\n const enc = new TextEncoder();\n const baseKey = await subtle.importKey(\n \"raw\",\n enc.encode(passphrase) as unknown as ArrayBuffer,\n \"PBKDF2\",\n false,\n [\"deriveKey\"],\n );\n\n return subtle.deriveKey(\n { name: \"PBKDF2\", salt: salt as unknown as ArrayBuffer, iterations: 100_000, hash: \"SHA-256\" },\n baseKey,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n}\n\n/**\n * Derive an AES-GCM key from a raw 16- or 32-byte `Uint8Array`.\n *\n * @internal\n */\nasync function importRawKey(subtle: SubtleCrypto, keyBytes: Uint8Array): Promise<CryptoKey> {\n if (keyBytes.length !== 16 && keyBytes.length !== 32) {\n throw new EncryptionError(\"encrypt\", new Error(\"keyBytes must be 16 or 32 bytes\"));\n }\n return subtle.importKey(\"raw\", keyBytes as unknown as ArrayBuffer, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Encrypt `value` using AES-GCM.\n *\n * @param value - The plaintext string.\n * @param options - Encryption options including key/passphrase and encoding.\n * @returns A promise resolving to the `\"<encoding>:<iv>:<ciphertext>\"` string.\n *\n * @example\n * ```ts\n * import { encrypt } from \"anonyma\";\n *\n * const ciphertext = await encrypt(\"alice@example.com\", {\n * strategy: \"encrypt\",\n * passphrase: \"s3cr3t\",\n * });\n * // \"base64:abc...==:xyz...==\"\n * ```\n */\nexport async function encrypt(value: string, options: EncryptOptions): Promise<string> {\n const subtle = requireCrypto();\n const encoding = options.encoding ?? \"base64\";\n\n try {\n const enc = new TextEncoder();\n const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));\n\n let key: CryptoKey;\n if (options.keyBytes) {\n // 16- or 32-byte raw key\n key = await importRawKey(subtle, options.keyBytes);\n } else if (options.passphrase) {\n // Derive from passphrase using PBKDF2. Use a fixed well-known salt so\n // the same passphrase always produces the same key (deterministic).\n const salt = enc.encode(\"anonyma_kdf_v1\");\n key = await deriveKey(subtle, options.passphrase, salt);\n } else {\n throw new EncryptionError(\"encrypt\", new Error(\"Provide `passphrase` or `keyBytes`\"));\n }\n\n const cipherBuf = await subtle.encrypt(\n { name: \"AES-GCM\", iv: iv as unknown as ArrayBuffer },\n key,\n enc.encode(value) as unknown as ArrayBuffer,\n );\n\n const encode = encoding === \"hex\" ? toHex : toBase64;\n return `${encoding}:${encode(iv.buffer)}:${encode(cipherBuf)}`;\n } catch (err) {\n if (err instanceof EncryptionError) throw err;\n throw new EncryptionError(\"encrypt\", err);\n }\n}\n\n/**\n * Decrypt a ciphertext produced by {@link encrypt}.\n *\n * @param ciphertext - The `\"<encoding>:<iv>:<payload>\"` string.\n * @param options - Must include the same `passphrase` or `keyBytes` used to encrypt.\n * @returns A promise resolving to the original plaintext string.\n *\n * @throws {@link EncryptionError} When decryption fails (wrong key, corrupt data, etc.).\n *\n * @example\n * ```ts\n * const plain = await decrypt(\"base64:abc...==:xyz...==\", { passphrase: \"s3cr3t\" });\n * ```\n */\nexport async function decrypt(ciphertext: string, options: EncryptOptions): Promise<string> {\n const subtle = requireCrypto();\n\n const parts = ciphertext.split(\":\");\n if (parts.length !== 3) {\n throw new EncryptionError(\"decrypt\", new Error(\"Malformed ciphertext — expected `encoding:iv:payload`\"));\n }\n\n const [encoding, ivEncoded, payloadEncoded] = parts as [string, string, string];\n const decode = encoding === \"hex\" ? fromHex : fromBase64;\n\n try {\n const iv = decode(ivEncoded);\n const payload = decode(payloadEncoded);\n\n const enc = new TextEncoder();\n let key: CryptoKey;\n if (options.keyBytes) {\n key = await importRawKey(subtle, options.keyBytes);\n } else if (options.passphrase) {\n const salt = enc.encode(\"anonyma_kdf_v1\");\n key = await deriveKey(subtle, options.passphrase, salt);\n } else {\n throw new EncryptionError(\"decrypt\", new Error(\"Provide `passphrase` or `keyBytes`\"));\n }\n\n const plainBuf = await subtle.decrypt({ name: \"AES-GCM\", iv: iv as unknown as ArrayBuffer }, key, payload as unknown as ArrayBuffer);\n return new TextDecoder().decode(plainBuf);\n } catch (err) {\n if (err instanceof EncryptionError) throw err;\n throw new EncryptionError(\"decrypt\", err);\n }\n}\n"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"crypto.cjs"}
package/dist/crypto.d.cts CHANGED
@@ -1,15 +1,16 @@
1
- import { E as EncryptOptions } from './types-D-9HzVuy.cjs';
1
+ import { E as EncryptOptions } from './types-EJTj_BKY.cjs';
2
2
 
3
3
  /**
4
4
  * @module strategies/encrypt
5
5
  * @description The `encrypt` anonymization strategy — uses AES-GCM via the
6
- * Web Crypto API (Node ≥ 18 / browsers with Web Crypto support).
6
+ * Web Crypto API: `globalThis.crypto` where the runtime exposes it, and Node's
7
+ * own implementation (`node:crypto`) on Node.js 18, which does not.
7
8
  *
8
9
  * The output format is `"<encoding>:<iv>:<ciphertext>"` where `<iv>` is the
9
10
  * random 12-byte initialisation vector and `<ciphertext>` is the encrypted
10
11
  * payload. Both parts are encoded in the same format (base64 or hex).
11
12
  *
12
- * @throws {@link CryptoNotAvailableError} When `globalThis.crypto.subtle` is not present.
13
+ * @throws {@link CryptoNotAvailableError} When the runtime has no Web Crypto API at all.
13
14
  * @throws {@link EncryptionError} When the underlying Web Crypto operation fails.
14
15
  */
15
16
 
package/dist/crypto.d.ts CHANGED
@@ -1,15 +1,16 @@
1
- import { E as EncryptOptions } from './types-D-9HzVuy.js';
1
+ import { E as EncryptOptions } from './types-EJTj_BKY.js';
2
2
 
3
3
  /**
4
4
  * @module strategies/encrypt
5
5
  * @description The `encrypt` anonymization strategy — uses AES-GCM via the
6
- * Web Crypto API (Node ≥ 18 / browsers with Web Crypto support).
6
+ * Web Crypto API: `globalThis.crypto` where the runtime exposes it, and Node's
7
+ * own implementation (`node:crypto`) on Node.js 18, which does not.
7
8
  *
8
9
  * The output format is `"<encoding>:<iv>:<ciphertext>"` where `<iv>` is the
9
10
  * random 12-byte initialisation vector and `<ciphertext>` is the encrypted
10
11
  * payload. Both parts are encoded in the same format (base64 or hex).
11
12
  *
12
- * @throws {@link CryptoNotAvailableError} When `globalThis.crypto.subtle` is not present.
13
+ * @throws {@link CryptoNotAvailableError} When the runtime has no Web Crypto API at all.
13
14
  * @throws {@link EncryptionError} When the underlying Web Crypto operation fails.
14
15
  */
15
16