anonyma 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,142 @@
1
+ 'use strict';
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
+ };
40
+
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
+
139
+ exports.decrypt = decrypt;
140
+ exports.encrypt = encrypt;
141
+ //# sourceMappingURL=crypto.cjs.map
142
+ //# sourceMappingURL=crypto.cjs.map
@@ -0,0 +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,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AA,MAAM,IAAA,GAAO,GAAA,CAAI,MAAA,CAAO,gBAAgB,CAAA;AACxC,MAAA,GAAA,GAAM,MAAM,SAAA,CAAU,MAAA,EAAQ,OAAA,CAAQ,YAAY,IAAI,CAAA;AAAA,IACxD,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,eAAA,CAAgB,SAAA,EAAW,IAAI,KAAA,CAAM,oCAAoC,CAAC,CAAA;AAAA,IACtF;AAEA,IAAA,MAAM,QAAA,GAAW,MAAM,MAAA,CAAO,OAAA,CAAQ,EAAE,MAAM,SAAA,EAAW,EAAA,EAAiC,EAAG,GAAA,EAAK,OAAiC,CAAA;AACnI,IAAA,OAAO,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,QAAQ,CAAA;AAAA,EAC1C,SAAS,GAAA,EAAK;AACZ,IAAA,IAAI,GAAA,YAAe,iBAAiB,MAAM,GAAA;AAC1C,IAAA,MAAM,IAAI,eAAA,CAAgB,SAAA,EAAW,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"]}
@@ -0,0 +1,51 @@
1
+ import { E as EncryptOptions } from './types-D-9HzVuy.cjs';
2
+
3
+ /**
4
+ * @module strategies/encrypt
5
+ * @description The `encrypt` anonymization strategy — uses AES-GCM via the
6
+ * Web Crypto API (Node ≥ 18 / browsers with Web Crypto support).
7
+ *
8
+ * The output format is `"<encoding>:<iv>:<ciphertext>"` where `<iv>` is the
9
+ * random 12-byte initialisation vector and `<ciphertext>` is the encrypted
10
+ * payload. Both parts are encoded in the same format (base64 or hex).
11
+ *
12
+ * @throws {@link CryptoNotAvailableError} When `globalThis.crypto.subtle` is not present.
13
+ * @throws {@link EncryptionError} When the underlying Web Crypto operation fails.
14
+ */
15
+
16
+ /**
17
+ * Encrypt `value` using AES-GCM.
18
+ *
19
+ * @param value - The plaintext string.
20
+ * @param options - Encryption options including key/passphrase and encoding.
21
+ * @returns A promise resolving to the `"<encoding>:<iv>:<ciphertext>"` string.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { encrypt } from "anonyma";
26
+ *
27
+ * const ciphertext = await encrypt("alice@example.com", {
28
+ * strategy: "encrypt",
29
+ * passphrase: "s3cr3t",
30
+ * });
31
+ * // "base64:abc...==:xyz...=="
32
+ * ```
33
+ */
34
+ declare function encrypt(value: string, options: EncryptOptions): Promise<string>;
35
+ /**
36
+ * Decrypt a ciphertext produced by {@link encrypt}.
37
+ *
38
+ * @param ciphertext - The `"<encoding>:<iv>:<payload>"` string.
39
+ * @param options - Must include the same `passphrase` or `keyBytes` used to encrypt.
40
+ * @returns A promise resolving to the original plaintext string.
41
+ *
42
+ * @throws {@link EncryptionError} When decryption fails (wrong key, corrupt data, etc.).
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const plain = await decrypt("base64:abc...==:xyz...==", { passphrase: "s3cr3t" });
47
+ * ```
48
+ */
49
+ declare function decrypt(ciphertext: string, options: EncryptOptions): Promise<string>;
50
+
51
+ export { EncryptOptions, decrypt, encrypt };
@@ -0,0 +1,51 @@
1
+ import { E as EncryptOptions } from './types-D-9HzVuy.js';
2
+
3
+ /**
4
+ * @module strategies/encrypt
5
+ * @description The `encrypt` anonymization strategy — uses AES-GCM via the
6
+ * Web Crypto API (Node ≥ 18 / browsers with Web Crypto support).
7
+ *
8
+ * The output format is `"<encoding>:<iv>:<ciphertext>"` where `<iv>` is the
9
+ * random 12-byte initialisation vector and `<ciphertext>` is the encrypted
10
+ * payload. Both parts are encoded in the same format (base64 or hex).
11
+ *
12
+ * @throws {@link CryptoNotAvailableError} When `globalThis.crypto.subtle` is not present.
13
+ * @throws {@link EncryptionError} When the underlying Web Crypto operation fails.
14
+ */
15
+
16
+ /**
17
+ * Encrypt `value` using AES-GCM.
18
+ *
19
+ * @param value - The plaintext string.
20
+ * @param options - Encryption options including key/passphrase and encoding.
21
+ * @returns A promise resolving to the `"<encoding>:<iv>:<ciphertext>"` string.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { encrypt } from "anonyma";
26
+ *
27
+ * const ciphertext = await encrypt("alice@example.com", {
28
+ * strategy: "encrypt",
29
+ * passphrase: "s3cr3t",
30
+ * });
31
+ * // "base64:abc...==:xyz...=="
32
+ * ```
33
+ */
34
+ declare function encrypt(value: string, options: EncryptOptions): Promise<string>;
35
+ /**
36
+ * Decrypt a ciphertext produced by {@link encrypt}.
37
+ *
38
+ * @param ciphertext - The `"<encoding>:<iv>:<payload>"` string.
39
+ * @param options - Must include the same `passphrase` or `keyBytes` used to encrypt.
40
+ * @returns A promise resolving to the original plaintext string.
41
+ *
42
+ * @throws {@link EncryptionError} When decryption fails (wrong key, corrupt data, etc.).
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const plain = await decrypt("base64:abc...==:xyz...==", { passphrase: "s3cr3t" });
47
+ * ```
48
+ */
49
+ declare function decrypt(ciphertext: string, options: EncryptOptions): Promise<string>;
50
+
51
+ export { EncryptOptions, decrypt, encrypt };
package/dist/crypto.js ADDED
@@ -0,0 +1,139 @@
1
+ // src/errors.ts
2
+ var AnonymaError = class extends Error {
3
+ /** Machine-readable error code. */
4
+ code;
5
+ constructor(message, code) {
6
+ super(message);
7
+ this.name = "AnonymaError";
8
+ this.code = code;
9
+ Object.setPrototypeOf(this, new.target.prototype);
10
+ }
11
+ };
12
+ var CryptoNotAvailableError = class extends AnonymaError {
13
+ constructor() {
14
+ super(
15
+ "The Web Crypto API (globalThis.crypto.subtle) is not available in this environment. Upgrade to Node.js \u2265 18 or use a polyfill.",
16
+ "CRYPTO_NOT_AVAILABLE"
17
+ );
18
+ this.name = "CryptoNotAvailableError";
19
+ Object.setPrototypeOf(this, new.target.prototype);
20
+ }
21
+ };
22
+ var EncryptionError = class extends AnonymaError {
23
+ /** The operation that failed (`"encrypt"` or `"decrypt"`). */
24
+ operation;
25
+ constructor(operation, cause) {
26
+ super(
27
+ `Encryption operation "${operation}" failed.${cause instanceof Error ? ` Cause: ${cause.message}` : ""}`,
28
+ "ENCRYPTION_ERROR"
29
+ );
30
+ this.name = "EncryptionError";
31
+ this.operation = operation;
32
+ if (cause !== void 0) {
33
+ this.cause = cause;
34
+ }
35
+ Object.setPrototypeOf(this, new.target.prototype);
36
+ }
37
+ };
38
+
39
+ // src/strategies/encrypt.ts
40
+ function requireCrypto() {
41
+ if (typeof globalThis.crypto.subtle === "undefined") throw new CryptoNotAvailableError();
42
+ return globalThis.crypto.subtle;
43
+ }
44
+ function toBase64(buf) {
45
+ return btoa(String.fromCharCode(...new Uint8Array(buf)));
46
+ }
47
+ function fromBase64(s) {
48
+ return Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
49
+ }
50
+ function toHex(buf) {
51
+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
52
+ }
53
+ function fromHex(s) {
54
+ const bytes = [];
55
+ for (let i = 0; i < s.length; i += 2) bytes.push(parseInt(s.slice(i, i + 2), 16));
56
+ return new Uint8Array(bytes);
57
+ }
58
+ async function deriveKey(subtle, passphrase, salt) {
59
+ const enc = new TextEncoder();
60
+ const baseKey = await subtle.importKey(
61
+ "raw",
62
+ enc.encode(passphrase),
63
+ "PBKDF2",
64
+ false,
65
+ ["deriveKey"]
66
+ );
67
+ return subtle.deriveKey(
68
+ { name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" },
69
+ baseKey,
70
+ { name: "AES-GCM", length: 256 },
71
+ false,
72
+ ["encrypt", "decrypt"]
73
+ );
74
+ }
75
+ async function importRawKey(subtle, keyBytes) {
76
+ if (keyBytes.length !== 16 && keyBytes.length !== 32) {
77
+ throw new EncryptionError("encrypt", new Error("keyBytes must be 16 or 32 bytes"));
78
+ }
79
+ return subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
80
+ }
81
+ async function encrypt(value, options) {
82
+ const subtle = requireCrypto();
83
+ const encoding = options.encoding ?? "base64";
84
+ try {
85
+ const enc = new TextEncoder();
86
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
87
+ let key;
88
+ if (options.keyBytes) {
89
+ key = await importRawKey(subtle, options.keyBytes);
90
+ } else if (options.passphrase) {
91
+ const salt = enc.encode("anonyma_kdf_v1");
92
+ key = await deriveKey(subtle, options.passphrase, salt);
93
+ } else {
94
+ throw new EncryptionError("encrypt", new Error("Provide `passphrase` or `keyBytes`"));
95
+ }
96
+ const cipherBuf = await subtle.encrypt(
97
+ { name: "AES-GCM", iv },
98
+ key,
99
+ enc.encode(value)
100
+ );
101
+ const encode = encoding === "hex" ? toHex : toBase64;
102
+ return `${encoding}:${encode(iv.buffer)}:${encode(cipherBuf)}`;
103
+ } catch (err) {
104
+ if (err instanceof EncryptionError) throw err;
105
+ throw new EncryptionError("encrypt", err);
106
+ }
107
+ }
108
+ async function decrypt(ciphertext, options) {
109
+ const subtle = requireCrypto();
110
+ const parts = ciphertext.split(":");
111
+ if (parts.length !== 3) {
112
+ throw new EncryptionError("decrypt", new Error("Malformed ciphertext \u2014 expected `encoding:iv:payload`"));
113
+ }
114
+ const [encoding, ivEncoded, payloadEncoded] = parts;
115
+ const decode = encoding === "hex" ? fromHex : fromBase64;
116
+ try {
117
+ const iv = decode(ivEncoded);
118
+ const payload = decode(payloadEncoded);
119
+ const enc = new TextEncoder();
120
+ let key;
121
+ if (options.keyBytes) {
122
+ key = await importRawKey(subtle, options.keyBytes);
123
+ } else if (options.passphrase) {
124
+ const salt = enc.encode("anonyma_kdf_v1");
125
+ key = await deriveKey(subtle, options.passphrase, salt);
126
+ } else {
127
+ throw new EncryptionError("decrypt", new Error("Provide `passphrase` or `keyBytes`"));
128
+ }
129
+ const plainBuf = await subtle.decrypt({ name: "AES-GCM", iv }, key, payload);
130
+ return new TextDecoder().decode(plainBuf);
131
+ } catch (err) {
132
+ if (err instanceof EncryptionError) throw err;
133
+ throw new EncryptionError("decrypt", err);
134
+ }
135
+ }
136
+
137
+ export { decrypt, encrypt };
138
+ //# sourceMappingURL=crypto.js.map
139
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +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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,YAAA,CAAa,MAAA,EAAQ,OAAA,CAAQ,QAAQ,CAAA;AAAA,IACnD,CAAA,MAAA,IAAW,QAAQ,UAAA,EAAY;AAC7B,MAAA,MAAM,IAAA,GAAO,GAAA,CAAI,MAAA,CAAO,gBAAgB,CAAA;AACxC,MAAA,GAAA,GAAM,MAAM,SAAA,CAAU,MAAA,EAAQ,OAAA,CAAQ,YAAY,IAAI,CAAA;AAAA,IACxD,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,eAAA,CAAgB,SAAA,EAAW,IAAI,KAAA,CAAM,oCAAoC,CAAC,CAAA;AAAA,IACtF;AAEA,IAAA,MAAM,QAAA,GAAW,MAAM,MAAA,CAAO,OAAA,CAAQ,EAAE,MAAM,SAAA,EAAW,EAAA,EAAiC,EAAG,GAAA,EAAK,OAAiC,CAAA;AACnI,IAAA,OAAO,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,QAAQ,CAAA;AAAA,EAC1C,SAAS,GAAA,EAAK;AACZ,IAAA,IAAI,GAAA,YAAe,iBAAiB,MAAM,GAAA;AAC1C,IAAA,MAAM,IAAI,eAAA,CAAgB,SAAA,EAAW,GAAG,CAAA;AAAA,EAC1C;AACF","file":"crypto.js","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"]}