cipher-kit 2.0.0-beta.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +241 -66
  2. package/dist/{chunk-3FJZA77A.cjs → chunk-3UX5MZ2P.cjs} +2 -2
  3. package/dist/chunk-3UX5MZ2P.cjs.map +1 -0
  4. package/dist/{chunk-7WPZVN7G.js → chunk-4MFF6V3R.js} +3 -3
  5. package/dist/chunk-4MFF6V3R.js.map +1 -0
  6. package/dist/{chunk-BWE6JWHY.js → chunk-ACFPMIXO.js} +3 -3
  7. package/dist/chunk-ACFPMIXO.js.map +1 -0
  8. package/dist/{chunk-CEXY7GOU.cjs → chunk-CVCDAHDW.cjs} +130 -130
  9. package/dist/chunk-CVCDAHDW.cjs.map +1 -0
  10. package/dist/{chunk-YAZRJN6X.js → chunk-FKSYSPJR.js} +2 -2
  11. package/dist/chunk-FKSYSPJR.js.map +1 -0
  12. package/dist/{chunk-WLLCFK4U.cjs → chunk-N2EW2FDZ.cjs} +125 -125
  13. package/dist/chunk-N2EW2FDZ.cjs.map +1 -0
  14. package/dist/{export-DX7bFv-3.d.cts → export-55tHE0Bw.d.cts} +12 -12
  15. package/dist/{export-DPAoLdh1.d.ts → export-BMvZq46v.d.ts} +12 -12
  16. package/dist/{export-Du70yDea.d.cts → export-CQNsJFh_.d.cts} +12 -12
  17. package/dist/{export-DjUgZ7dz.d.ts → export-llM6c7Do.d.ts} +12 -12
  18. package/dist/index.cjs +11 -11
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +3 -3
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +3 -3
  23. package/dist/index.js.map +1 -1
  24. package/dist/node.cjs +32 -32
  25. package/dist/node.d.cts +2 -2
  26. package/dist/node.d.ts +2 -2
  27. package/dist/node.js +2 -2
  28. package/dist/{validate-DrBddQyu.d.cts → validate-EHuJC5QQ.d.cts} +3 -3
  29. package/dist/{validate-DrBddQyu.d.ts → validate-EHuJC5QQ.d.ts} +3 -3
  30. package/dist/web-api.cjs +32 -32
  31. package/dist/web-api.d.cts +2 -2
  32. package/dist/web-api.d.ts +2 -2
  33. package/dist/web-api.js +2 -2
  34. package/package.json +4 -3
  35. package/dist/chunk-3FJZA77A.cjs.map +0 -1
  36. package/dist/chunk-7WPZVN7G.js.map +0 -1
  37. package/dist/chunk-BWE6JWHY.js.map +0 -1
  38. package/dist/chunk-CEXY7GOU.cjs.map +0 -1
  39. package/dist/chunk-WLLCFK4U.cjs.map +0 -1
  40. package/dist/chunk-YAZRJN6X.js.map +0 -1
package/README.md CHANGED
@@ -3,16 +3,15 @@
3
3
 
4
4
  <h1 align="center" style="font-weight:900;">cipher-kit</h1>
5
5
 
6
- <!-- TODO -->
7
6
  <p align="center">
8
- Secure, Lightweight, and Cross-Platform <br/>
9
- Encryption, Decryption, and Hashing <br/>
10
- for Web, Node.js, Deno, Bun, and Cloudflare Workers
7
+ Secure, Modern, and Cross-Platform <br/>
8
+ Cryptography Helpers for Web, Node.js, <br/>
9
+ Deno, Bun, and Cloudflare Workers
11
10
  </p>
12
11
 
13
12
  <a href="https://opensource.org/licenses/MIT" rel="nofollow"><img src="https://img.shields.io/github/license/WolfieLeader/npm?color=DC343B" alt="License"></a>
14
13
  <a href="https://www.npmjs.com/package/cipher-kit" rel="nofollow"><img src="https://img.shields.io/npm/v/cipher-kit?color=0078D4" alt="npm version"></a>
15
- <a href="https://www.npmjs.com/package/cipher-kit" rel="nofollow"><img src="https://img.shields.io/npm/dy/cipher-kit.svg?color=03C03C" alt="npm downloads"></a>
14
+ <a href="https://www.npmjs.com/package/cipher-kit" rel="nofollow"><img src="https://img.shields.io/npm/dt/cipher-kit.svg?color=03C03C" alt="npm downloads"></a>
16
15
  <a href="https://github.com/WolfieLeader/npm" rel="nofollow"><img src="https://img.shields.io/github/stars/WolfieLeader/npm" alt="stars"></a>
17
16
 
18
17
  </div>
@@ -22,10 +21,10 @@
22
21
  - 🛡️ **Secure and Flexible** - Uses best practices and modern cryptographic techniques, while providing a flexible and simple API.
23
22
  - 📦 **All-in-One Toolkit** – Combines encryption, hashing, encoding, serialization, and more into a single package.
24
23
  - 🌐 **Cross-Platform** – Works seamlessly across Web, Node.js, Deno, Bun, and Cloudflare Workers.
25
- - 💡 **Typed and Ergonomic** - Type safe and provides throwing and non-throwing (`Result`) APIs.
26
- - 🌳 **Tree-Shakable** - import root or platform-specific modules to reduce bundle size.
24
+ - 💡 **Typed and Ergonomic** - Type-safe API with both throwing and non-throwing (`Result`) flavors.
25
+ - 🌳 **Tree-Shakable** - Import from the root or from platform-specific entry points to keep bundles lean.
27
26
  - 🚫 **Zero Dependencies** – Fully self-contained, no external libraries required.
28
- - 🍼 **Explain like I'm five** - Newbie-friendly explanations and documentation.
27
+ - 🍼 **Explain Like I'm Five** - Newbie-friendly explanations and documentation.
29
28
 
30
29
  ## Installation 🔥
31
30
 
@@ -39,65 +38,110 @@ pnpm install cipher-kit@latest
39
38
  bun add cipher-kit@latest
40
39
  ```
41
40
 
42
- ## Usage 🪛
43
-
44
- ### The `try` Prefix (Non-Throwing `Result` API)
41
+ ## Quick Start 🚀
45
42
 
46
- The `try` prefix functions return a `Result<T>` object that indicates success or failure without throwing exceptions.
43
+ ```typescript
44
+ // Node.js Quick Start
45
+ import { createSecretKey, encrypt, decrypt } from "cipher-kit/node";
47
46
 
48
- This is useful in scenarios where you want to handle errors gracefully without using `try/catch` blocks.
47
+ const nodeSecretKey = createSecretKey("my-passphrase");
48
+ const encrypted = encrypt("Hello World!", nodeSecretKey);
49
+ const decrypted = decrypt(encrypted, nodeSecretKey);
50
+ console.log(decrypted); // "Hello World!"
49
51
 
50
- ```typescript
51
- // Throwing version - simpler but requires try/catch
52
- const message = encrypt('Secret message', secretKey);
53
- console.log(`Encrypted message: ${message}`);
52
+ // Web Quick Start
53
+ import { createSecretKey, encrypt, decrypt } from "cipher-kit/web-api";
54
54
 
55
- // Non-throwing version - returns a Result<T> object
56
- const message = tryEncrypt('Secret message', secretKey);
57
- if (message.success) {
58
- console.log(`Encrypted message: ${message.result}`);
59
- } else {
60
- console.error(`Encryption failed: ${message.error.message} - ${message.error.description}`);
61
- }
55
+ const webSecretKey = await createSecretKey("my-passphrase");
56
+ const encrypted = await encrypt("Hello World!", webSecretKey);
57
+ const decrypted = await decrypt(encrypted, webSecretKey);
58
+ console.log(decrypted); // "Hello World!"
62
59
  ```
63
60
 
64
- ### The `webKit` and `nodeKit` Objects
61
+ ## Usage 🪛
62
+
63
+ Table of Contents:
64
+
65
+ - [webKit and nodeKit](#webkit-and-nodekit-objects-)
66
+ - [The try Prefix](#the-try-prefix-non-throwing-result-api-)
67
+ - [Encryption & Decryption](#encryption--decryption-)
68
+ - [Secret Key Creation](#secret-key-creation-)
69
+ - [Encrypting Data](#encrypting-data-)
70
+ - [Decrypting Data](#decrypting-data-)
71
+ - [Encrypting & Decrypting Objects](#encrypting--decrypting-objects-)
72
+ - [Hashing](#hashing-)
73
+ - [UUID Generation](#uuid-generation-)
74
+ - [Password Hashing & Verification](#password-hashing--verification-)
75
+ - [Encoding & Decoding](#encoding--decoding-)
76
+ - [Object Serialization & Deserialization](#object-serialization--deserialization-)
77
+ - [Regex Utilities](#regex-utilities-)
78
+
79
+ ### `webKit` and `nodeKit` Objects 📦
65
80
 
66
81
  The `webKit` and `nodeKit` objects provide platform-specific implementations for Web (including Deno, Bun, and Cloudflare Workers) and Node.js environments, respectively.
67
82
 
68
83
  You can also import them directly from `cipher-kit/web-api` and `cipher-kit/node` for smaller bundle sizes.
69
84
 
70
85
  ```typescript
71
- import { webKit, nodeKit } from 'cipher-kit';
72
- import { isNodeSecretKey } from 'cipher-kit/node';
73
- import { isWebSecretKey } from 'cipher-kit/web-api';
86
+ // Option A: import helpers directly
87
+ import { isNodeSecretKey } from "cipher-kit/node";
88
+ import { isWebSecretKey } from "cipher-kit/web-api";
74
89
 
75
- // These are the same:
76
90
  function isSecretKey(key: unknown): boolean {
77
91
  return isNodeSecretKey(key) || isWebSecretKey(key);
78
92
  }
79
93
 
94
+ // Option B: via kits from the root export
95
+ import { webKit, nodeKit } from "cipher-kit";
96
+
80
97
  function isSecretKey(key: unknown): boolean {
81
98
  return nodeKit.isNodeSecretKey(key) || webKit.isWebSecretKey(key);
82
99
  }
83
100
  ```
84
101
 
85
- ### Encryption and Decryption
102
+ ### The `try` Prefix (Non-Throwing `Result` API) 🤔
86
103
 
87
- Encryption is the process of converting readable plaintext into unreadable ciphertext using an algorithm and a secret key to protect its confidentiality. Decryption is the reverse process, using the same algorithm and the correct key to convert the ciphertext back into its original, readable plaintext form.
104
+ The `try` prefix functions return a `Result<T>` object that indicates success or failure without throwing exceptions.
88
105
 
89
- The package provides functions for both encryption and decryption. On top of that the function provides `encryptObj` and `decryptObj` functions that work the same way but for objects (using JSON serialization).
106
+ This is useful in scenarios where you want to handle errors gracefully without using `try/catch` blocks.
90
107
 
91
- #### Secret Key Creation
108
+ ```typescript
109
+ // Throwing version - simpler but requires try/catch
110
+ const msg = encrypt("Secret message", secretKey);
111
+ console.log(`Encrypted message: ${msg}`);
112
+
113
+ // Non-throwing version - returns a Result<T> object
114
+ const msg = tryEncrypt("Secret message", secretKey);
115
+
116
+ // Either check for success status
117
+ if (msg.success) console.log(`Encrypted message: ${msg.result}`);
118
+ else console.error(`${msg.error.message} - ${msg.error.description}`);
119
+
120
+ // Or Check that there is no error
121
+ if (!msg.error) console.log(`Encrypted message: ${msg.result}`);
122
+ else console.error(`${msg.error.message} - ${msg.error.description}`);
123
+ ```
124
+
125
+ ### Encryption & Decryption 🤫
126
+
127
+ Encryption is the process of converting readable plaintext into unreadable ciphertext using an algorithm and a secret key to protect its confidentiality. Decryption is the reverse process, using the same algorithm and the correct key to convert the ciphertext back into its original, readable plaintext form.
128
+
129
+ #### _Secret Key Creation_ 🔑
92
130
 
93
131
  Before encrypting or decrypting data, you need to create a secret key.
94
132
 
95
133
  Each key is tied to a specific platform (Web or Node.js) and cannot be used interchangeably.
96
134
 
97
135
  ```typescript
98
- import { createSecretKey } from 'cipher-kit/node'; // or 'cipher-kit/web-api'
136
+ // Node.js example
137
+ import { createSecretKey } from "cipher-kit/node";
138
+
139
+ const nodeSecretKey = createSecretKey("my-passphrase");
99
140
 
100
- const secretKey = createSecretKey('my-passphrase');
141
+ // Web example
142
+ import { createSecretKey } from "cipher-kit/web-api";
143
+
144
+ const webSecretKey = await createSecretKey("my-passphrase");
101
145
  ```
102
146
 
103
147
  The function accepts an optional `options` as well, which allows you to customize the key derivation process.
@@ -105,10 +149,10 @@ The function accepts an optional `options` as well, which allows you to customiz
105
149
  ```typescript
106
150
  interface CreateSecretKeyOptions {
107
151
  // Which encryption algorithm to use (default: "aes256gcm")
108
- algorithm?: 'aes256gcm' | 'aes192gcm' | 'aes128gcm';
152
+ algorithm?: "aes256gcm" | "aes192gcm" | "aes128gcm";
109
153
 
110
154
  // Digest algorithm for HKDF (key derivation) (default: "sha256")
111
- digest?: 'sha256' | 'sha384' | 'sha512';
155
+ digest?: "sha256" | "sha384" | "sha512";
112
156
 
113
157
  // Optional salt for HKDF (key derivation), if you provide a random one it will return a different key each time (default: "cipher-kit-salt", must be >= 8 characters).
114
158
  salt?: string;
@@ -118,12 +162,24 @@ interface CreateSecretKeyOptions {
118
162
  }
119
163
  ```
120
164
 
121
- #### Encrypting Data
165
+ #### _Encrypting Data_ 🔐
166
+
167
+ Ciphertext formats differ between Web and Node.js platforms.
168
+
169
+ - Node.js - `iv.cipher.tag.` (3 parts)
170
+ - Web - `iv.cipherWithTag.` (2 parts)
122
171
 
123
172
  ```typescript
124
- import { encrypt } from 'cipher-kit/node'; // or 'cipher-kit/web-api'
173
+ // Node.js example
174
+ import { encrypt } from "cipher-kit/node";
175
+
176
+ const encrypted = encrypt("Hello, World!", nodeSecretKey);
177
+ console.log(`Encrypted: ${encrypted}`);
125
178
 
126
- const encrypted = encrypt('Hello, World!', secretKey);
179
+ // Web example
180
+ import { encrypt } from "cipher-kit/web-api";
181
+
182
+ const encrypted = await encrypt("Hello, World!", webSecretKey);
127
183
  console.log(`Encrypted: ${encrypted}`);
128
184
  ```
129
185
 
@@ -132,16 +188,25 @@ The function accepts an optional `options` parameter to customize the output enc
132
188
  ```typescript
133
189
  interface EncryptOptions {
134
190
  // Output ciphertext encoding(default: "base64url")
135
- encoding?: 'base64url' | 'base64' | 'hex';
191
+ encoding?: "base64url" | "base64" | "hex";
136
192
  }
137
193
  ```
138
194
 
139
- #### Decrypting Data
195
+ #### _Decrypting Data_ 🔓
196
+
197
+ Since ciphertext formats differ between Web and Node.js platforms, make sure to use the correct `decrypt` function for the platform where the data was encrypted.
140
198
 
141
199
  ```typescript
142
- import { decrypt } from 'cipher-kit/node'; // or 'cipher-kit/web-api'
200
+ // Node.js example
201
+ import { decrypt } from "cipher-kit/node";
202
+
203
+ const decrypted = decrypt(encrypted, nodeSecretKey);
204
+ console.log(`Decrypted: ${decrypted}`);
205
+
206
+ // Web example
207
+ import { decrypt } from "cipher-kit/web-api";
143
208
 
144
- const decrypted = decrypt(encrypted, secretKey);
209
+ const decrypted = await decrypt(encrypted, webSecretKey);
145
210
  console.log(`Decrypted: ${decrypted}`);
146
211
  ```
147
212
 
@@ -152,18 +217,53 @@ Make sure to use the same encoding that was used during encryption.
152
217
  ```typescript
153
218
  interface DecryptOptions {
154
219
  // Input ciphertext encoding (default: "base64url")
155
- encoding?: 'base64url' | 'base64' | 'hex';
220
+ encoding?: "base64url" | "base64" | "hex";
156
221
  }
157
222
  ```
158
223
 
159
- ### Hashing
224
+ #### _Encrypting & Decrypting Objects_ 🧬
225
+
226
+ ```typescript
227
+ // Node.js example
228
+ import { encryptObj, decryptObj } from "cipher-kit/node";
229
+
230
+ const obj = { name: "Alice", age: 30, city: "Wonderland" };
231
+
232
+ const encryptedObj = encryptObj(obj, nodeSecretKey);
233
+
234
+ const decryptedObj = decryptObj<typeof obj>(encryptedObj, nodeSecretKey);
235
+ console.log(`Decrypted Object:`, decryptedObj);
236
+
237
+ // Web example
238
+ import { encryptObj, decryptObj } from "cipher-kit/web-api";
239
+
240
+ const obj = { name: "Alice", age: 30, city: "Wonderland" };
241
+
242
+ const encryptedObj = await encryptObj(obj, webSecretKey);
243
+
244
+ const decryptedObj = await decryptObj<typeof obj>(encryptedObj, webSecretKey);
245
+ console.log(`Decrypted Object:`, decryptedObj);
246
+ ```
247
+
248
+ The `encryptObj` and `decryptObj` functions accept the same `options` parameters as `encrypt` and `decrypt`, respectively.
249
+
250
+ ### Hashing 🪄
160
251
 
161
252
  Hashing is a one-way process that uses an algorithm to transform data of any size into a fixed-length string of characters, called a hash value or digest. It serves as a digital fingerprint for the data, enabling quick data retrieval in hash tables, password storage, and file integrity checks. Key features include its irreversibility (you can't get the original data back from the hash).
162
253
 
254
+ Not suitable for storing passwords - use `hashPassword` instead.
255
+
163
256
  ```typescript
164
- import { hash } from 'cipher-kit/node'; // or 'cipher-kit/web-api'
257
+ // Node.js example
258
+ import { hash } from "cipher-kit/node";
259
+
260
+ const hashed = hash("Hello, World!");
261
+ console.log(`Hashed: ${hashed}`);
165
262
 
166
- const hashed = hash('Hello, World!');
263
+ // Web example
264
+ import { hash } from "cipher-kit/web-api";
265
+
266
+ const hashed = await hash("Hello, World!");
167
267
  console.log(`Hashed: ${hashed}`);
168
268
  ```
169
269
 
@@ -172,40 +272,56 @@ The function accepts an optional `options` parameter to customize the hashing pr
172
272
  ```typescript
173
273
  interface HashOptions {
174
274
  // Digest algorithm to use (default: "sha256").
175
- digest?: 'sha256' | 'sha384' | 'sha512';
275
+ digest?: "sha256" | "sha384" | "sha512";
176
276
 
177
277
  // Output encoding (default: "base64url").
178
- encoding?: 'base64url' | 'base64' | 'hex';
278
+ encoding?: "base64url" | "base64" | "hex";
179
279
  }
180
280
  ```
181
281
 
182
- ### UUID Generation
282
+ ### UUID Generation 🪪
183
283
 
184
284
  UUID (Universally Unique Identifier) is a 128-bit identifier used to uniquely identify information in computer systems. It is designed to be globally unique, meaning that no two UUIDs should be the same, even if generated on different systems or at different times. UUIDs are commonly used in databases, distributed systems, and applications where unique identification is crucial.
185
285
 
186
286
  ```typescript
187
- import { generateUUID } from 'cipher-kit/node'; // or 'cipher-kit/web-api'
287
+ // Node.js example
288
+ import { generateUuid } from "cipher-kit/node";
188
289
 
189
- const uuid = generateUUID();
290
+ const uuid = generateUuid();
291
+ console.log(`Generated UUID: ${uuid}`);
292
+
293
+ // Web example
294
+ import { generateUuid } from "cipher-kit/web-api";
295
+
296
+ const uuid = generateUuid();
190
297
  console.log(`Generated UUID: ${uuid}`);
191
298
  ```
192
299
 
193
- ### Password Hashing and Verification
300
+ ### Password Hashing & Verification 💎
194
301
 
195
302
  Password hashing is a one-way process that transforms a plaintext password into a fixed-length hash. Password hashing is crucial for securely storing passwords in databases, as it protects user credentials from being exposed in case of a data breach.
196
303
 
197
304
  Password hashing is different from general-purpose hashing because it often involves additional techniques like salting and key stretching to enhance security against brute-force attacks, and it's usually slower to compute to make rainbow table attacks less feasible.
198
305
 
199
- To verify a password, the same hashing process is applied to the input password, and the resulting hash is compared to the stored hash, in a time-safe manner to prevent timing attacks.
306
+ To verify a password, the same hashing process is applied to the input password, and the resulting hash is compared to the stored hash, in a constant-time comparison to prevent timing attacks.
200
307
 
201
308
  ```typescript
202
- import { hashPassword, verifyPassword } from 'cipher-kit/node'; // or 'cipher-kit/web-api'
309
+ // Node.js example
310
+ import { hashPassword, verifyPassword } from "cipher-kit/node";
311
+
312
+ const { hash, salt } = hashPassword("some-secure-password");
313
+ console.log(`Hashed Password: ${hash}`);
314
+
315
+ const isMatch = verifyPassword("some-secure-password", hash, salt);
316
+ console.log(`Password match: ${isMatch}`);
317
+
318
+ // Web example
319
+ import { hashPassword, verifyPassword } from "cipher-kit/web-api";
203
320
 
204
- const password = 'my-secure-password';
205
- const hashedPassword = hashPassword(password);
206
- console.log(`Hashed Password: ${hashedPassword}`);
321
+ const { hash, salt } = await hashPassword("some-secure-password");
322
+ console.log(`Hashed Password: ${hash}`);
207
323
 
208
- const isMatch = verifyPassword(password, hashedPassword);
324
+ const isMatch = await verifyPassword("some-secure-password", hash, salt);
209
325
  console.log(`Password match: ${isMatch}`);
210
326
  ```
211
327
 
@@ -214,10 +330,10 @@ The `hashPassword` and `verifyPassword` functions accept an optional `options` p
214
330
  ```typescript
215
331
  interface HashPasswordOptions {
216
332
  // Digest algorithm to use (default: "sha512").
217
- digest?: 'sha256' | 'sha384' | 'sha512';
333
+ digest?: "sha256" | "sha384" | "sha512";
218
334
 
219
335
  // Encoding format for the output hash (default: "base64url").
220
- encoding?: 'base64url' | 'base64' | 'hex';
336
+ encoding?: "base64url" | "base64" | "hex";
221
337
 
222
338
  // Length of the salt in bytes (default: 16 bytes, min: 8 bytes).
223
339
  saltLength?: number;
@@ -231,10 +347,10 @@ interface HashPasswordOptions {
231
347
 
232
348
  interface VerifyPasswordOptions {
233
349
  // Digest algorithm used during the original hashing (default: `'sha512'`).
234
- digest?: 'sha256' | 'sha384' | 'sha512';
350
+ digest?: "sha256" | "sha384" | "sha512";
235
351
 
236
352
  // Encoding format used during the original hashing (default: `'base64url'`).
237
- encoding?: 'base64url' | 'base64' | 'hex';
353
+ encoding?: "base64url" | "base64" | "hex";
238
354
 
239
355
  // Number of iterations used during the original hashing (default: `320000`).
240
356
  iterations?: number;
@@ -244,7 +360,62 @@ interface VerifyPasswordOptions {
244
360
  }
245
361
  ```
246
362
 
247
- <!-- TODO obj <-> string, bytes <-> string, regex -->
363
+ ### Encoding & Decoding 🧩
364
+
365
+ Encoding and decoding are processes used to convert data into a specific format for efficient transmission, storage, or representation. Encoding transforms data into a different format using a specific scheme, while decoding reverses this process to retrieve the original data. Common encoding schemes include Base64, Base64URL, and Hexadecimal (Hex).
366
+
367
+ ```typescript
368
+ // Node.js and Web example - works the same in both
369
+ import { convertStrToBytes, convertBytesToStr, convertEncoding } from "cipher-kit/node"; // or "cipher-kit/web-api"
370
+
371
+ // Encoding
372
+ const buffer = convertStrToBytes("Hello World!", "utf8"); // the input encoding
373
+ console.log(`Encoded: ${buffer}`);
374
+
375
+ // Decoding
376
+ const str = convertBytesToStr(buffer, "utf8"); // the output encoding
377
+ console.log(`Decoded: ${str}`);
378
+
379
+ // Convert between encodings
380
+ const base64 = convertEncoding("Hello World!", "utf8", "base64");
381
+ console.log(`Base64: ${base64}`);
382
+ ```
383
+
384
+ ### Object Serialization & Deserialization 🧬
385
+
386
+ Object serialization in JavaScript is the process of converting objects or arrays into a JSON string representation, that can be easily stored or transmitted. Deserialization is the reverse process, where the JSON string is parsed back into its original object or array structure.
387
+
388
+ ```typescript
389
+ import { stringifyObj, parseToObj } from "cipher-kit"; // works in both "cipher-kit/web-api" and "cipher-kit/node"
390
+
391
+ const obj = { name: "Alice", age: 30, city: "Wonderland" };
392
+
393
+ const jsonString = stringifyObj(obj);
394
+ console.log(`Serialized: ${jsonString}`);
395
+
396
+ const parsedObj = parseToObj<typeof obj>(jsonString);
397
+ console.log(`Deserialized:`, parsedObj);
398
+ ```
399
+
400
+ ### Regex Utilities 🔍
401
+
402
+ Regular expressions (regex) are sequences of characters that form search patterns, used for pattern matching within strings.
403
+
404
+ Before decrypting, you can validate the format (decryption functions already validate internally).
405
+
406
+ ```typescript
407
+ import { ENCRYPTED_REGEX, matchPattern } from "cipher-kit"; // works in both "cipher-kit/web-api" and "cipher-kit/node"
408
+
409
+ function isEncryptedFormat(message: string): boolean {
410
+ return matchPattern(message, "general"); // or "node" or "web"
411
+ }
412
+
413
+ // or
414
+
415
+ function isEncryptedFormat(message: string): boolean {
416
+ return ENCRYPTED_REGEX.general.test(message); // or "node" or "web"
417
+ }
418
+ ```
248
419
 
249
420
  ## Contributions 🤝
250
421
 
@@ -258,4 +429,8 @@ Want to contribute or suggest a feature?
258
429
 
259
430
  This project is licensed under the [MIT License](https://opensource.org/licenses/MIT).
260
431
 
261
- Thank you!
432
+ <div align="center">
433
+ <br/>
434
+ <div style="font-size: 14px; font-weight:bold;"> ⚒️ Crafted carefully by <a href="https://github.com/WolfieLeader" target="_blank" rel="nofollow">WolfieLeader</a></div>
435
+ <div style="font-size: 12px; font-style: italic;">Thank you!</div>
436
+ </div>
@@ -154,5 +154,5 @@ exports.stringifyObj = stringifyObj;
154
154
  exports.title = title;
155
155
  exports.tryParseToObj = tryParseToObj;
156
156
  exports.tryStringifyObj = tryStringifyObj;
157
- //# sourceMappingURL=chunk-3FJZA77A.cjs.map
158
- //# sourceMappingURL=chunk-3FJZA77A.cjs.map
157
+ //# sourceMappingURL=chunk-3UX5MZ2P.cjs.map
158
+ //# sourceMappingURL=chunk-3UX5MZ2P.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/helpers/consts.ts","../src/helpers/validate.ts","../src/helpers/error.ts","../src/helpers/object.ts"],"names":["nodeCrypto","title"],"mappings":";;;;;;;;;;;;;;;AAAO,IAAM,QAAA,GAAW,OAAO,MAAA,CAAO,CAAC,UAAU,WAAA,EAAa,KAAA,EAAO,MAAA,EAAQ,QAAQ,CAAU;AAExF,IAAM,kBAAkB,MAAA,CAAO,MAAA,CAAO,CAAC,QAAA,EAAU,WAAA,EAAa,KAAK,CAAU;AAE7E,IAAM,iBAAA,GAAoB,OAAO,MAAA,CAAO;AAAA,EAC7C,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,KAAK,SAAA,EAAU;AAAA,EACzC,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,KAAK,SAAA,EAAU;AAAA,EACzC,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,KAAK,SAAA;AACjC,CAAU;AAEH,IAAM,qBAAA,GAAwB,OAAO,MAAA,CAAO;AAAA,EACjD,SAAA,EAAW,EAAE,QAAA,EAAU,EAAA,EAAI,UAAU,EAAA,EAAI,IAAA,EAAM,aAAA,EAAe,GAAA,EAAK,SAAA,EAAU;AAAA,EAC7E,SAAA,EAAW,EAAE,QAAA,EAAU,EAAA,EAAI,UAAU,EAAA,EAAI,IAAA,EAAM,aAAA,EAAe,GAAA,EAAK,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AAA,IAAI,OAAO,MAAM,IAAI,KAAA,CAAM,aAAA,CAAc,KAAK,CAAC,CAAA;AAC/C,EAAA,OAAO,MAAA;AACT;AAEO,SAAS,YAAwD,GAAA,EAAoC;AAC1G,EAAA,IAAI;AACF,IAAA,IAAI,CAAC,MAAA,CAAO,GAAG,CAAA,EAAG,OAAO,IAAA,CAAK,EAAE,GAAA,EAAK,wBAAA,EAA0B,IAAA,EAAM,6BAAA,EAA+B,CAAA;AACpG,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAE1B,IAAA,IAAI,CAAC,MAAA,CAAO,GAAG,CAAA,EAAG,OAAO,IAAA,CAAK,EAAE,GAAA,EAAK,gCAAA,EAAkC,IAAA,EAAM,mCAAA,EAAqC,CAAA;AAClH,IAAA,OAAO,GAAA,CAAI,EAAE,MAAA,EAAQ,GAAA,EAAU,CAAA;AAAA,EACjC,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,IAAA,CAAK,EAAE,GAAA,EAAK,yBAAA,EAA2B,MAAM,SAAA,CAAU,KAAK,GAAG,CAAA;AAAA,EACxE;AACF;AAwBO,SAAS,cAA0D,GAAA,EAAoC;AAC5G,EAAA,OAAO,YAAe,GAAG,CAAA;AAC3B;AAwBO,SAAS,WAAuD,GAAA,EAAgB;AACrF,EAAA,MAAM,EAAE,MAAA,EAAQ,KAAA,EAAM,GAAI,YAAe,GAAG,CAAA;AAC5C,EAAA,IAAI,OAAO,MAAM,IAAI,KAAA,CAAM,aAAA,CAAc,KAAK,CAAC,CAAA;AAC/C,EAAA,OAAO,MAAA;AACT","file":"chunk-3UX5MZ2P.cjs","sourcesContent":["export const ENCODING = Object.freeze([\"base64\", \"base64url\", \"hex\", \"utf8\", \"latin1\"] as const);\r\n\r\nexport const CIPHER_ENCODING = Object.freeze([\"base64\", \"base64url\", \"hex\"] as const);\r\n\r\nexport const DIGEST_ALGORITHMS = Object.freeze({\r\n sha256: { node: \"sha256\", web: \"SHA-256\" },\r\n sha384: { node: \"sha384\", web: \"SHA-384\" },\r\n sha512: { node: \"sha512\", web: \"SHA-512\" },\r\n} as const);\r\n\r\nexport const ENCRYPTION_ALGORITHMS = Object.freeze({\r\n aes256gcm: { keyBytes: 32, ivLength: 12, node: \"aes-256-gcm\", web: \"AES-GCM\" },\r\n aes192gcm: { keyBytes: 24, ivLength: 12, node: \"aes-192-gcm\", web: \"AES-GCM\" },\r\n aes128gcm: { keyBytes: 16, ivLength: 12, node: \"aes-128-gcm\", web: \"AES-GCM\" },\r\n} as const);\r\n","import nodeCrypto from \"node:crypto\";\r\nimport type { SecretKey } from \"~/helpers/types\";\r\nimport { DIGEST_ALGORITHMS, ENCRYPTION_ALGORITHMS } from \"./consts\";\r\n\r\nexport function $isStr(x: unknown, min = 1): x is string {\r\n return x !== null && x !== undefined && typeof x === \"string\" && x.trim().length >= min;\r\n}\r\n\r\nexport function $isObj(x: unknown): x is Record<string, unknown> {\r\n if (typeof x !== \"object\" || x === null || x === undefined) return false;\r\n const proto = Object.getPrototypeOf(x);\r\n return proto === Object.prototype || proto === null;\r\n}\r\n\r\nexport function $isLooseObj(x: unknown): x is Record<string, unknown> {\r\n return typeof x === \"object\" && x !== null && x !== undefined;\r\n}\r\n\r\ntype InjectedSecretKey<Platform extends \"web\" | \"node\"> = SecretKey<Platform> & {\r\n readonly injected: (typeof ENCRYPTION_ALGORITHMS)[keyof typeof ENCRYPTION_ALGORITHMS];\r\n};\r\n\r\nconst expectedKeys = new Set([\"platform\", \"digest\", \"algorithm\", \"key\"]);\r\n\r\nexport function $isSecretKey<Platform extends \"node\" | \"web\">(\r\n x: unknown,\r\n platform: Platform,\r\n): InjectedSecretKey<Platform> | null {\r\n if (!$isLooseObj(x) || (platform !== \"node\" && platform !== \"web\") || x.platform !== platform) return null;\r\n\r\n const keys = Object.keys(x);\r\n if (keys.length !== expectedKeys.size) return null;\r\n for (const key of keys) if (!expectedKeys.has(key)) return null;\r\n for (const key of expectedKeys) if (!Object.hasOwn(x, key)) return null;\r\n\r\n if (\r\n typeof x.digest !== \"string\" ||\r\n !(x.digest in DIGEST_ALGORITHMS) ||\r\n typeof x.algorithm !== \"string\" ||\r\n !(x.algorithm in ENCRYPTION_ALGORITHMS) ||\r\n !$isLooseObj(x.key) ||\r\n x.key.type !== \"secret\"\r\n ) {\r\n return null;\r\n }\r\n\r\n const algorithm = ENCRYPTION_ALGORITHMS[x.algorithm as keyof typeof ENCRYPTION_ALGORITHMS];\r\n\r\n if (platform === \"node\") {\r\n if (\r\n !(x.key instanceof nodeCrypto.KeyObject) ||\r\n (typeof x.key.symmetricKeySize === \"number\" && x.key.symmetricKeySize !== algorithm.keyBytes)\r\n ) {\r\n return null;\r\n }\r\n return Object.freeze({ ...x, injected: algorithm }) as InjectedSecretKey<Platform>;\r\n }\r\n\r\n if (\r\n !$isLooseObj(x.key.algorithm) ||\r\n x.key.algorithm.name !== algorithm.web ||\r\n (typeof x.key.algorithm.length === \"number\" && x.key.algorithm.length !== algorithm.keyBytes * 8) ||\r\n typeof x.key.extractable !== \"boolean\" ||\r\n !Array.isArray(x.key.usages) ||\r\n x.key.usages.length !== 2 ||\r\n !(x.key.usages.includes(\"encrypt\") && x.key.usages.includes(\"decrypt\"))\r\n ) {\r\n return null;\r\n }\r\n return Object.freeze({ ...x, injected: algorithm }) as InjectedSecretKey<Platform>;\r\n}\r\n\r\n/**\r\n * Regular expressions for encrypted data patterns.\r\n *\r\n * - **node**: `\"iv.cipher.tag.\"` (three dot-separated parts plus a trailing dot)\r\n * - **web**: `\"iv.cipherWithTag.\"` (two parts plus a trailing dot)\r\n * - **general**: accepts both shapes (2 or 3 parts) with a trailing dot\r\n *\r\n * Each part is any non-empty string without dots.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You have a secret code you want to check. Before you check it,\r\n * you make sure it looks how a secret code should look.\r\n */\r\nexport const ENCRYPTED_REGEX = Object.freeze({\r\n node: /^([^.]+)\\.([^.]+)\\.([^.]+)\\.$/,\r\n web: /^([^.]+)\\.([^.]+)\\.$/,\r\n general: /^([^.]+)\\.([^.]+)(?:\\.([^.]+))?\\.$/,\r\n});\r\n\r\n/**\r\n * Checks if a string matches an expected encrypted payload shape.\r\n *\r\n * - **node**: `\"iv.cipher.tag.\"` (three dot-separated parts plus a trailing dot)\r\n * - **web**: `\"iv.cipherWithTag.\"` (two parts plus a trailing dot)\r\n * - **general**: accepts both shapes (2 or 3 parts) with a trailing dot\r\n *\r\n * Each part is any non-empty string without dots.\r\n *\r\n * This validates only the **shape**, not whether content is valid base64/hex, etc.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You have a secret code you want to check. Before you check it,\r\n * you make sure it looks how a secret code should look.\r\n *\r\n * @param data - The string to test.\r\n * @param format - Which layout to check: `'node'`, `'web'`, or `'general'`.\r\n * @returns `true` if the string matches the pattern; otherwise `false`.\r\n * @throws {Error} If an unknown `format` is provided.\r\n *\r\n * @example\r\n * ```ts\r\n * matchPattern(\"abc.def.ghi.\", \"node\"); // true\r\n * matchPattern(\"abc.def.\", \"web\"); // true\r\n * matchPattern(\"abc.def.\", \"node\"); // false\r\n * matchPattern(\"abc.def.ghi.\", \"general\"); // true\r\n * ```\r\n */\r\nexport function matchPattern(data: string, format: \"general\" | \"node\" | \"web\"): boolean {\r\n if (typeof data !== \"string\") return false;\r\n if (!(format in ENCRYPTED_REGEX)) throw new Error(`Unknown format: ${format}`);\r\n return ENCRYPTED_REGEX[format].test(data);\r\n}\r\n","import { $isObj } from \"./validate\";\r\n\r\n/**\r\n * Standardized error object for the `Result` type.\r\n * Always has a brief `message` and a more detailed `description`.\r\n */\r\nexport interface ResultErr {\r\n readonly message: string;\r\n readonly description: string;\r\n}\r\n\r\n/**\r\n * Discriminated union for functions that can succeed or fail.\r\n *\r\n * - On **success**:\r\n * - If `T` is an object - properties of `T` are **spread** into the result\r\n * along with `success: true`.\r\n * - Otherwise - `{ success: true, result: T }`.\r\n * - On **failure**: `{ success: false, error: E }`.\r\n *\r\n * @example\r\n * ```ts\r\n * // Primitive result\r\n * function getNum(): Result<number> {\r\n * return $ok(42);\r\n * }\r\n * const r1 = getNum();\r\n * if (r1.success) console.log(r1.result); // 42\r\n *\r\n * // Object result (spread)\r\n * function getObject(): Result<{ name: string; age: number }> {\r\n * return $ok({ name: 'Alice', age: 30 });\r\n * }\r\n * const r2 = getObject();\r\n * if (r2.success) console.log(r2.name, r2.age); // 'Alice' 30\r\n * ```\r\n */\r\nexport type Result<T, E = ResultErr> = T extends object\r\n ?\r\n | ({ readonly [K in keyof T]: T[K] } & { readonly success: true; readonly error?: undefined })\r\n | ({ readonly [K in keyof T]?: undefined } & { readonly success: false; readonly error: E })\r\n :\r\n | { readonly success: true; readonly result: T; readonly error?: undefined }\r\n | { readonly success: false; readonly error: E; readonly result?: undefined };\r\n\r\nexport function $ok<T>(result?: T): Result<T> {\r\n if ($isObj(result)) return { success: true, ...(result as T & object) } as Result<T>;\r\n return { success: true, result } as Result<T>;\r\n}\r\n\r\nexport function $err(err: { msg: string; desc: string }): Result<never, ResultErr>;\r\nexport function $err(err: ResultErr): Result<never, ResultErr>;\r\nexport function $err(err: { msg: string; desc: string } | ResultErr): Result<never, ResultErr> {\r\n return {\r\n success: false,\r\n error: {\r\n message: \"msg\" in err ? err.msg : err.message,\r\n description: \"desc\" in err ? err.desc : err.description,\r\n },\r\n } as Result<never, ResultErr>;\r\n}\r\n\r\nexport function $fmtError(error: unknown): string {\r\n if (typeof error === \"string\") return error;\r\n if (error instanceof Error) return error.message;\r\n return String(error);\r\n}\r\n\r\nexport function $fmtResultErr(err: ResultErr | undefined): string {\r\n if (!err) return \"Unknown error\";\r\n return `${err.message} - ${err.description}`;\r\n}\r\n\r\nexport function title(platform: \"web\" | \"node\", title: string): string {\r\n return `${platform === \"web\" ? \"Crypto Web API\" : \"Crypto NodeJS API\"} - ${title}`;\r\n}\r\n","import { $err, $fmtError, $fmtResultErr, $ok, type Result } from \"./error\";\r\nimport { $isObj, $isStr } from \"./validate\";\r\n\r\nexport function $stringifyObj<T extends object = Record<string, unknown>>(obj: T): Result<string> {\r\n try {\r\n if (!$isObj(obj)) return $err({ msg: \"Invalid object\", desc: \"Input is not a plain object\" });\r\n return $ok(JSON.stringify(obj));\r\n } catch (error) {\r\n return $err({ msg: \"Utility: Stringify error\", desc: $fmtError(error) });\r\n }\r\n}\r\n\r\n/**\r\n * Safely serializes a plain object to JSON without throwing.\r\n *\r\n * Wraps `JSON.stringify` and returns a `Result` containing the JSON string or an error.\r\n * Only plain objects (POJOs) are accepted. Class instances, Maps, Sets, etc. are rejected.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You have a box of toys (your object) and take a photo of it (a JSON string)\r\n * so you can send it to a friend.\r\n *\r\n * @template T - Plain object type to serialize.\r\n * @param obj - The object to stringify (must be a plain object).\r\n * @returns A `Result` with the JSON string on success, or an error.\r\n *\r\n * @example\r\n * ```ts\r\n * const res = tryStringifyObj({ a: 1 });\r\n * if (res.success) {\r\n * console.log(res.result); // {\"a\":1}\r\n * } else {\r\n * console.error(res.error.message, res.error.description);\r\n * }\r\n * ```\r\n */\r\nexport function tryStringifyObj<T extends object = Record<string, unknown>>(obj: T): Result<string> {\r\n return $stringifyObj(obj);\r\n}\r\n\r\n/**\r\n * Serializes a plain object to JSON (throwing).\r\n *\r\n * Wraps `JSON.stringify` and returns the result or throws an error.\r\n * Only plain objects (POJOs) are accepted. Class instances, Maps, Sets, etc. are rejected.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You have a box of toys (your object) and take a photo of it (a JSON string)\r\n * so you can send it to a friend.\r\n *\r\n * @template T - Plain object type to serialize.\r\n * @param obj - The object to stringify (must be a plain object).\r\n * @returns JSON string representation of the object.\r\n * @throws {Error} If `obj` is not a plain object or serialization fails.\r\n *\r\n * @example\r\n * ```ts\r\n * try {\r\n * const json = stringifyObj({ a: 1 }); // {\"a\":1}\r\n * } catch (error: unknown) {\r\n * console.error(error);\r\n * }\r\n * ```\r\n */\r\nexport function stringifyObj<T extends object = Record<string, unknown>>(obj: T): string {\r\n const { result, error } = $stringifyObj(obj);\r\n if (error) throw new Error($fmtResultErr(error));\r\n return result;\r\n}\r\n\r\nexport function $parseToObj<T extends object = Record<string, unknown>>(str: string): Result<{ result: T }> {\r\n try {\r\n if (!$isStr(str)) return $err({ msg: \"Utility: Invalid input\", desc: \"Input is not a valid string\" });\r\n const obj = JSON.parse(str);\r\n\r\n if (!$isObj(obj)) return $err({ msg: \"Utility: Invalid object format\", desc: \"Parsed data is not a plain object\" });\r\n return $ok({ result: obj as T });\r\n } catch (error) {\r\n return $err({ msg: \"Utility: Invalid format\", desc: $fmtError(error) });\r\n }\r\n}\r\n\r\n/**\r\n * Safely parses a JSON string to a plain object (non-throwing).\r\n *\r\n * Wraps `JSON.parse` and returns a `Result` containing the parsed object, or an error.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You rebuild your toy box (an object) from a photo you took (a JSON string).\r\n *\r\n * @template T - The expected object type.\r\n * @param str - The JSON string to parse.\r\n * @returns A `Result` with the parsed object on success, or an error.\r\n *\r\n * @example\r\n * ```ts\r\n * const res = tryParseToObj<{ a: number }>('{\"a\":1}');\r\n * if (res.success) {\r\n * console.log(res.result.a); // 1\r\n * } else {\r\n * console.error(res.error.message, res.error.description);\r\n * }\r\n * ```\r\n */\r\nexport function tryParseToObj<T extends object = Record<string, unknown>>(str: string): Result<{ result: T }> {\r\n return $parseToObj<T>(str);\r\n}\r\n\r\n/**\r\n * Parses a JSON string to a plain object (throwing).\r\n *\r\n * Wraps `JSON.parse` and returns the parsed object, or throws on failure.\r\n *\r\n * ### 🍼 Explain Like I'm Five\r\n * You rebuild your toy box (an object) from a photo you took (a JSON string).\r\n *\r\n * @template T - The expected object type.\r\n * @param str - The JSON string to parse.\r\n * @returns The parsed plain object.\r\n * @throws {Error} If the string can’t be parsed or doesn’t represent a plain object.\r\n *\r\n * @example\r\n * ```ts\r\n * try {\r\n * const obj = parseToObj<{ a: number }>('{\"a\":1}'); // obj.a === 1\r\n * } catch (error: unknown) {\r\n * console.error(error);\r\n * }\r\n * ```\r\n */\r\nexport function parseToObj<T extends object = Record<string, unknown>>(str: string): T {\r\n const { result, error } = $parseToObj<T>(str);\r\n if (error) throw new Error($fmtResultErr(error));\r\n return result;\r\n}\r\n"]}
@@ -1,4 +1,4 @@
1
- import { __export, $isSecretKey, $fmtResultErr, $ok, $err, $fmtError, title, $isStr, ENCRYPTION_ALGORITHMS, DIGEST_ALGORITHMS, CIPHER_ENCODING, matchPattern, $stringifyObj, $parseToObj, ENCODING } from './chunk-YAZRJN6X.js';
1
+ import { __export, $isSecretKey, $fmtResultErr, $ok, $err, $fmtError, title, $isStr, ENCRYPTION_ALGORITHMS, DIGEST_ALGORITHMS, CIPHER_ENCODING, matchPattern, $stringifyObj, $parseToObj, ENCODING } from './chunk-FKSYSPJR.js';
2
2
 
3
3
  // src/web/kit.ts
4
4
  var kit_exports = {};
@@ -563,5 +563,5 @@ function convertEncoding(data, from, to) {
563
563
  }
564
564
 
565
565
  export { convertBytesToStr, convertEncoding, convertStrToBytes, createSecretKey, decrypt, decryptObj, encrypt, encryptObj, generateUuid, hash, hashPassword, isWebSecretKey, kit_exports, tryConvertBytesToStr, tryConvertEncoding, tryConvertStrToBytes, tryCreateSecretKey, tryDecrypt, tryDecryptObj, tryEncrypt, tryEncryptObj, tryGenerateUuid, tryHash, tryHashPassword, verifyPassword };
566
- //# sourceMappingURL=chunk-7WPZVN7G.js.map
567
- //# sourceMappingURL=chunk-7WPZVN7G.js.map
566
+ //# sourceMappingURL=chunk-4MFF6V3R.js.map
567
+ //# sourceMappingURL=chunk-4MFF6V3R.js.map