jsonauthtoken 3.0.3 → 3.0.4-beta-1

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,728 @@
1
+ // src/config/name.config.ts
2
+ var RUNTIME = ["node", "web"];
3
+ var NODE_RUNTIME = ["web", "node"];
4
+
5
+ // src/config/algo.config.ts
6
+ var SUPPORTED_ALGORITHM = {
7
+ node: [
8
+ { name: "AES-256-GCM", value: "aes-256-gcm", type: "symmetric" },
9
+ { name: "RSA+A256GCM", value: "rsa+a256gcm", type: "asymmetric" }
10
+ ],
11
+ web: [
12
+ { name: "AES-GCM", value: "AES-GCM", type: "symmetric" },
13
+ { name: "RSA+AES-GCM", value: "RSA+AES-GCM", type: "asymmetric" }
14
+ ]
15
+ };
16
+ function RUNTIME_DEFAULT_ALGORITHM(runtime) {
17
+ const algos = {
18
+ node: { name: "AES-256-GCM", value: "aes-256-gcm", type: "symmetric" },
19
+ web: { name: "AES-GCM", value: "AES-GCM", type: "symmetric" }
20
+ };
21
+ return algos[runtime];
22
+ }
23
+
24
+ // src/lib/encoading.lib.ts
25
+ function encoading(runtime, data) {
26
+ const json = JSON.stringify(data);
27
+ let base64;
28
+ if (runtime === "node") {
29
+ base64 = Buffer.from(json).toString("base64");
30
+ } else {
31
+ base64 = btoa(unescape(encodeURIComponent(json)));
32
+ }
33
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
34
+ }
35
+ var encoading_lib_default = encoading;
36
+
37
+ // src/lib/decoading.lib.ts
38
+ var decoading = (runtime, str) => {
39
+ const base64 = str.replace(/-/g, "+").replace(/_/g, "/");
40
+ const padding = "=".repeat((4 - base64.length % 4) % 4);
41
+ const base64WithPadding = base64 + padding;
42
+ let decoded;
43
+ if (runtime === "node") {
44
+ decoded = Buffer.from(base64WithPadding, "base64").toString("utf8");
45
+ } else {
46
+ decoded = decodeURIComponent(escape(atob(base64WithPadding)));
47
+ }
48
+ return JSON.parse(decoded);
49
+ };
50
+ var decoading_lib_default = decoading;
51
+
52
+ // src/lib/functions.lib.ts
53
+ function tokenFormatCreate(meta, encrypted) {
54
+ return `${encoading_lib_default(meta.runtime, meta)}:${encrypted}`;
55
+ }
56
+ function tokenFormatVerify(runtime, token) {
57
+ const index = token.indexOf(":");
58
+ if (index === -1) {
59
+ throw new Error("Invalid token format");
60
+ }
61
+ const metaPart = token.substring(0, index);
62
+ const encryptedPart = token.substring(index + 1);
63
+ const meta = decoading_lib_default(runtime, metaPart);
64
+ if (!meta) {
65
+ throw new Error("Invalid token format");
66
+ }
67
+ const algorithm = SUPPORTED_ALGORITHM[meta.runtime]?.find((e) => e.name === meta.algo);
68
+ if (!algorithm) {
69
+ throw new Error("Invalid token format");
70
+ }
71
+ if (algorithm.type !== meta.type) {
72
+ throw new Error("Invalid token format");
73
+ }
74
+ if (meta.type === "asymmetric") {
75
+ if (!meta.encryptedKey) {
76
+ throw new Error("Invalid token format");
77
+ }
78
+ }
79
+ if (!meta.iv) {
80
+ throw new Error("Invalid token format");
81
+ }
82
+ if (!RUNTIME.includes(meta.runtime)) {
83
+ throw new Error("Invalid token format");
84
+ }
85
+ if (meta.runtime === "node") {
86
+ if (!meta.tag) {
87
+ throw new Error("Invalid token format");
88
+ }
89
+ }
90
+ if (!meta.v) {
91
+ throw new Error("Invalid token format");
92
+ }
93
+ return { meta, encrypted: encryptedPart };
94
+ }
95
+ function isExpired(timeStamp) {
96
+ let currentTime = Math.floor(Date.now() / 1e3);
97
+ if (timeStamp < currentTime) {
98
+ return true;
99
+ } else {
100
+ return false;
101
+ }
102
+ }
103
+ function print({ dev = false, color = "green" }, ...args) {
104
+ if (!dev) return;
105
+ const colors = {
106
+ red: "\x1B[31m",
107
+ green: "\x1B[32m",
108
+ yellow: "\x1B[33m",
109
+ blue: "\x1B[34m",
110
+ magenta: "\x1B[35m",
111
+ cyan: "\x1B[36m",
112
+ white: "\x1B[37m",
113
+ reset: "\x1B[0m"
114
+ };
115
+ if (typeof window !== "undefined") {
116
+ console.log(`%c[jsonauthtoken]`, `color:${color}`, ...args);
117
+ } else {
118
+ const colorCode = colors[color] ?? colors.green;
119
+ console.log(`${colorCode}[jsonauthtoken]`, ...args, "\x1B[0m");
120
+ }
121
+ }
122
+
123
+ // src/lib/timeformat.ts
124
+ function jatTimeFormatter(input) {
125
+ if (typeof input === "number") {
126
+ if (input <= 0) {
127
+ throw new Error("Expiration time must be greater than zero.");
128
+ }
129
+ return Math.floor(Date.now() / 1e3) + input;
130
+ }
131
+ const regex = /^(\d+)(S|MIN|H|D|M|Y)$/i;
132
+ const match = input.match(regex);
133
+ if (!match) {
134
+ throw new Error("Invalid format. Use number or formats like 1S, 1MIN, 1H, 1D, 1M, or 1Y.");
135
+ }
136
+ const amount = parseInt(match[1], 10);
137
+ const unit = match[2].toUpperCase();
138
+ let seconds;
139
+ switch (unit) {
140
+ case "S":
141
+ seconds = amount;
142
+ break;
143
+ case "MIN":
144
+ seconds = amount * 60;
145
+ break;
146
+ case "H":
147
+ seconds = amount * 60 * 60;
148
+ break;
149
+ case "D":
150
+ seconds = amount * 24 * 60 * 60;
151
+ break;
152
+ case "M":
153
+ seconds = amount * 30 * 24 * 60 * 60;
154
+ break;
155
+ case "Y":
156
+ seconds = amount * 365 * 24 * 60 * 60;
157
+ break;
158
+ default:
159
+ throw new Error(`Unsupported time unit: ${unit}`);
160
+ }
161
+ return Math.floor(Date.now() / 1e3) + seconds;
162
+ }
163
+
164
+ // src/runtime/web.runtime.ts
165
+ var WebCrypto = class {
166
+ textEncoder = new TextEncoder();
167
+ textDecoder = new TextDecoder();
168
+ // Import AES key from password string
169
+ async __importAESKey(password) {
170
+ const passwordBuffer = this.textEncoder.encode(password);
171
+ const hashBuffer = await crypto.subtle.digest("SHA-256", passwordBuffer);
172
+ return await crypto.subtle.importKey(
173
+ "raw",
174
+ hashBuffer,
175
+ { name: "AES-GCM" },
176
+ false,
177
+ ["encrypt", "decrypt"]
178
+ );
179
+ }
180
+ //uint8Array to Base64
181
+ __uint8ArrayToBase64(uint8Array) {
182
+ let binary = "";
183
+ const len = uint8Array.byteLength;
184
+ for (let i = 0; i < len; i++) {
185
+ binary += String.fromCharCode(uint8Array[i]);
186
+ }
187
+ return btoa(binary);
188
+ }
189
+ //base64 to Uint8Array
190
+ __base64ToUint8Array(base64) {
191
+ const binaryString = atob(base64);
192
+ const len = binaryString.length;
193
+ const bytes = new Uint8Array(len);
194
+ for (let i = 0; i < len; i++) {
195
+ bytes[i] = binaryString.charCodeAt(i);
196
+ }
197
+ return bytes;
198
+ }
199
+ // ArrayBuffer to Base64
200
+ __arrayBufferToBase64(buffer) {
201
+ const bytes = new Uint8Array(buffer);
202
+ let binary = "";
203
+ for (let i = 0; i < bytes.length; i++) {
204
+ binary += String.fromCharCode(bytes[i]);
205
+ }
206
+ return btoa(binary);
207
+ }
208
+ //Base64 to ArrayBuffer
209
+ __base64ToArrayBuffer(base64) {
210
+ const binary = atob(base64);
211
+ const bytes = new Uint8Array(binary.length);
212
+ for (let i = 0; i < binary.length; i++) {
213
+ bytes[i] = binary.charCodeAt(i);
214
+ }
215
+ return bytes.buffer;
216
+ }
217
+ //PEM to ArrayBuffer
218
+ __pemToArrayBuffer(pem, type) {
219
+ const pemHeader = `-----BEGIN ${type} KEY-----`;
220
+ const pemFooter = `-----END ${type} KEY-----`;
221
+ const pemContents = pem.replace(pemHeader, "").replace(pemFooter, "").replace(/\\n/g, "").replace(/\s/g, "");
222
+ return this.__base64ToArrayBuffer(pemContents);
223
+ }
224
+ //ArrayBuffer to PEM
225
+ __arrayBufferToPem(buffer, type) {
226
+ const base64 = this.__arrayBufferToBase64(buffer);
227
+ const pemContents = base64.match(/.{1,64}/g)?.join("\n") || base64;
228
+ return `-----BEGIN ${type} KEY-----
229
+ ${pemContents}
230
+ -----END ${type} KEY-----`;
231
+ }
232
+ // Import RSA public key from PEM
233
+ async __importPublicKey(publicKeyPem) {
234
+ const keyData = this.__pemToArrayBuffer(publicKeyPem, "PUBLIC");
235
+ return await crypto.subtle.importKey(
236
+ "spki",
237
+ keyData,
238
+ {
239
+ name: "RSA-OAEP",
240
+ hash: "SHA-256"
241
+ },
242
+ true,
243
+ ["encrypt"]
244
+ );
245
+ }
246
+ // Import RSA private key from PEM
247
+ async __importPrivateKey(privateKeyPem) {
248
+ const keyData = this.__pemToArrayBuffer(privateKeyPem.replace(/\\n/g, "\n"), "PRIVATE");
249
+ return await crypto.subtle.importKey(
250
+ "pkcs8",
251
+ keyData,
252
+ {
253
+ name: "RSA-OAEP",
254
+ hash: "SHA-256"
255
+ },
256
+ true,
257
+ ["decrypt"]
258
+ );
259
+ }
260
+ // AES-256-GCM Encryption
261
+ async _encrypt(algo, key, payload) {
262
+ const iv = crypto.getRandomValues(new Uint8Array(12));
263
+ const data = this.textEncoder.encode(JSON.stringify(payload));
264
+ const encryptedBuffer = await crypto.subtle.encrypt(
265
+ {
266
+ name: algo,
267
+ iv,
268
+ tagLength: 128
269
+ },
270
+ key,
271
+ data
272
+ );
273
+ const encryptedBytes = new Uint8Array(encryptedBuffer);
274
+ return {
275
+ iv: this.__uint8ArrayToBase64(iv),
276
+ encrypted: this.__uint8ArrayToBase64(encryptedBytes)
277
+ };
278
+ }
279
+ // AES-256-GCM Decryption
280
+ async _decrypt(algo, key, encryptedData) {
281
+ const { iv, encrypted } = encryptedData;
282
+ const ivBuffer = this.__base64ToUint8Array(iv);
283
+ const encryptedBuffer = this.__base64ToUint8Array(encrypted);
284
+ try {
285
+ const decryptedBuffer = await crypto.subtle.decrypt(
286
+ {
287
+ name: algo,
288
+ iv: ivBuffer,
289
+ tagLength: 128
290
+ },
291
+ key,
292
+ encryptedBuffer
293
+ );
294
+ return JSON.parse(this.textDecoder.decode(decryptedBuffer));
295
+ } catch (error) {
296
+ throw new Error("Invalid Key");
297
+ }
298
+ }
299
+ // Generate RSA public key from private key PEM
300
+ async _rsaPublicKeyGeneration(privateKeyPem) {
301
+ const privateKey = await this.__importPrivateKey(privateKeyPem);
302
+ const jwk = await crypto.subtle.exportKey("jwk", privateKey);
303
+ delete jwk.d;
304
+ delete jwk.dp;
305
+ delete jwk.dq;
306
+ delete jwk.q;
307
+ delete jwk.qi;
308
+ jwk.key_ops = ["encrypt"];
309
+ const publicKey = await crypto.subtle.importKey(
310
+ "jwk",
311
+ jwk,
312
+ {
313
+ name: "RSA-OAEP",
314
+ hash: "SHA-256"
315
+ },
316
+ true,
317
+ ["encrypt"]
318
+ );
319
+ const exportedPublicKey = await crypto.subtle.exportKey("spki", publicKey);
320
+ return this.__arrayBufferToPem(exportedPublicKey, "PUBLIC");
321
+ }
322
+ async _rsaPrivatePublicKeyGeneration() {
323
+ const keyPair = await crypto.subtle.generateKey(
324
+ {
325
+ name: "RSA-OAEP",
326
+ modulusLength: 2048,
327
+ publicExponent: new Uint8Array([1, 0, 1]),
328
+ hash: "SHA-256"
329
+ },
330
+ true,
331
+ ["encrypt", "decrypt"]
332
+ );
333
+ const privateKeyBuffer = await crypto.subtle.exportKey("pkcs8", keyPair.privateKey);
334
+ const publicKeyBuffer = await crypto.subtle.exportKey("spki", keyPair.publicKey);
335
+ return {
336
+ privateKey: this.__arrayBufferToPem(privateKeyBuffer, "PRIVATE"),
337
+ publicKey: this.__arrayBufferToPem(publicKeyBuffer, "PUBLIC")
338
+ };
339
+ }
340
+ async encrypt(algo, key, payload, exp) {
341
+ const cryptoKey = await this.__importAESKey(key);
342
+ const newPayload = { payload, exp };
343
+ const { iv, encrypted } = await this._encrypt(algo, cryptoKey, newPayload);
344
+ return tokenFormatCreate(
345
+ {
346
+ runtime: "web",
347
+ algo: "AES-GCM",
348
+ type: "symmetric",
349
+ v: "1",
350
+ iv
351
+ },
352
+ encrypted
353
+ );
354
+ }
355
+ async decrypt(algo, key, encryptedData) {
356
+ const cryptoKey = await this.__importAESKey(key);
357
+ return await this._decrypt(algo, cryptoKey, encryptedData);
358
+ }
359
+ // Public method: Asymmetric encryption (RSA-OAEP + AES-256-GCM)
360
+ async encryptRSA(payload, publicKeyPem, exp) {
361
+ const symmetricKey = await crypto.subtle.generateKey(
362
+ { name: "AES-GCM", length: 256 },
363
+ true,
364
+ ["encrypt", "decrypt"]
365
+ );
366
+ const newPayload = { payload, exp };
367
+ const { iv, encrypted } = await this._encrypt("AES-GCM", symmetricKey, newPayload);
368
+ const symmetricKeyBuffer = await crypto.subtle.exportKey("raw", symmetricKey);
369
+ const publicKey = await this.__importPublicKey(publicKeyPem);
370
+ const encryptedSymmetricKey = await crypto.subtle.encrypt(
371
+ {
372
+ name: "RSA-OAEP"
373
+ },
374
+ publicKey,
375
+ symmetricKeyBuffer
376
+ );
377
+ return tokenFormatCreate(
378
+ {
379
+ runtime: "web",
380
+ algo: "RSA+AES-GCM",
381
+ type: "asymmetric",
382
+ v: "1",
383
+ iv,
384
+ encryptedKey: this.__arrayBufferToBase64(encryptedSymmetricKey)
385
+ },
386
+ encrypted
387
+ );
388
+ }
389
+ // Public method: Asymmetric decryption (RSA-OAEP + AES-256-GCM)
390
+ async decryptRSA(privateKeyPem, encryptedKey, encryptedData) {
391
+ const privateKey = await this.__importPrivateKey(privateKeyPem);
392
+ const encryptedKeyBuffer = this.__base64ToArrayBuffer(encryptedKey);
393
+ const decryptedSymmetricKeyBuffer = await crypto.subtle.decrypt(
394
+ {
395
+ name: "RSA-OAEP"
396
+ },
397
+ privateKey,
398
+ encryptedKeyBuffer
399
+ );
400
+ const symmetricKey = await crypto.subtle.importKey(
401
+ "raw",
402
+ decryptedSymmetricKeyBuffer,
403
+ { name: "AES-GCM" },
404
+ false,
405
+ ["decrypt"]
406
+ );
407
+ return await this._decrypt("AES-GCM", symmetricKey, encryptedData);
408
+ }
409
+ async rsaPrivatePublicKeyGeneration() {
410
+ return await this._rsaPrivatePublicKeyGeneration();
411
+ }
412
+ async rsaPublicKeyGeneration(privateKeyPem) {
413
+ return await this._rsaPublicKeyGeneration(privateKeyPem);
414
+ }
415
+ };
416
+
417
+ // src/runtime/node.runtime.ts
418
+ import crypto2 from "crypto";
419
+ var NodeCrypto = class {
420
+ _encrypt(algorithm, key, payload) {
421
+ const iv = crypto2.randomBytes(12);
422
+ const cipher = crypto2.createCipheriv(algorithm, key, iv);
423
+ const data = JSON.stringify(payload);
424
+ let encrypted = cipher.update(data, "utf8", "base64");
425
+ encrypted += cipher.final("base64");
426
+ const tag = cipher.getAuthTag().toString("base64");
427
+ return {
428
+ iv: iv.toString("base64"),
429
+ encrypted,
430
+ tag
431
+ };
432
+ }
433
+ _decrypt(algorithm, key, encryptedData) {
434
+ const { iv, encrypted, tag } = encryptedData;
435
+ const decipher = crypto2.createDecipheriv(
436
+ algorithm,
437
+ key,
438
+ Buffer.from(iv, "base64")
439
+ );
440
+ decipher.setAuthTag(Buffer.from(tag, "base64"));
441
+ try {
442
+ let decrypted = decipher.update(encrypted, "base64", "utf8");
443
+ decrypted += decipher.final("utf8");
444
+ return JSON.parse(decrypted);
445
+ } catch (error) {
446
+ throw new Error("Invalid Key");
447
+ }
448
+ }
449
+ _rsaPublicKeyGeneration(privateKeyPem) {
450
+ const privateKeyObject = crypto2.createPrivateKey({
451
+ key: privateKeyPem.replace(/\\n/g, "\n"),
452
+ format: "pem",
453
+ type: "pkcs8"
454
+ });
455
+ const publicKeyObject = crypto2.createPublicKey(privateKeyObject);
456
+ return publicKeyObject.export({ type: "spki", format: "pem" });
457
+ }
458
+ _rsaPrivatePublicKeyGeneration() {
459
+ const { publicKey, privateKey } = crypto2.generateKeyPairSync("rsa", {
460
+ modulusLength: 2048,
461
+ publicKeyEncoding: {
462
+ type: "spki",
463
+ format: "pem"
464
+ },
465
+ privateKeyEncoding: {
466
+ type: "pkcs8",
467
+ format: "pem"
468
+ }
469
+ });
470
+ return { privateKey, publicKey };
471
+ }
472
+ async encrypt(algo, key, payload, exp) {
473
+ const keyHash = crypto2.createHash("sha256").update(key).digest();
474
+ const newPayload = { payload, exp };
475
+ const { iv, encrypted, tag } = this._encrypt(algo, keyHash, newPayload);
476
+ return tokenFormatCreate(
477
+ {
478
+ runtime: "node",
479
+ algo: "AES-256-GCM",
480
+ type: "symmetric",
481
+ v: "1",
482
+ iv,
483
+ tag
484
+ },
485
+ encrypted
486
+ );
487
+ }
488
+ async decrypt(algo, key, encryptedData) {
489
+ const keyHash = crypto2.createHash("sha256").update(key).digest();
490
+ return this._decrypt(algo, keyHash, encryptedData);
491
+ }
492
+ // --- RSA-OAEP Hybrid ---
493
+ async encryptRSA(payload, publicKey, exp) {
494
+ const symmetricKey = crypto2.randomBytes(32);
495
+ const newPayload = { payload, exp };
496
+ const { iv, encrypted, tag } = this._encrypt("aes-256-gcm", symmetricKey, newPayload);
497
+ const encryptedSymmetricKey = crypto2.publicEncrypt(
498
+ {
499
+ key: publicKey,
500
+ padding: crypto2.constants.RSA_PKCS1_OAEP_PADDING,
501
+ oaepHash: "sha256"
502
+ },
503
+ symmetricKey
504
+ );
505
+ return tokenFormatCreate(
506
+ {
507
+ runtime: "node",
508
+ algo: "RSA+A256GCM",
509
+ type: "asymmetric",
510
+ v: "1",
511
+ iv,
512
+ tag,
513
+ encryptedKey: encryptedSymmetricKey.toString("base64")
514
+ },
515
+ encrypted
516
+ );
517
+ }
518
+ async decryptRSA(privateKey, encryptedKey, encryptedData) {
519
+ const decryptedSymmetricKey = crypto2.privateDecrypt(
520
+ {
521
+ key: privateKey,
522
+ padding: crypto2.constants.RSA_PKCS1_OAEP_PADDING,
523
+ oaepHash: "sha256"
524
+ },
525
+ Buffer.from(encryptedKey, "base64")
526
+ );
527
+ return this._decrypt("aes-256-gcm", decryptedSymmetricKey, encryptedData);
528
+ }
529
+ async rsaPrivatePublicKeyGeneration() {
530
+ return this._rsaPrivatePublicKeyGeneration();
531
+ }
532
+ async rsaPublicKeyGeneration(privateKeyPem) {
533
+ return this._rsaPublicKeyGeneration(privateKeyPem);
534
+ }
535
+ };
536
+
537
+ // src/node.index.ts
538
+ var NodeCryptoModule = class {
539
+ dev = false;
540
+ runtime;
541
+ web = new WebCrypto();
542
+ node = new NodeCrypto();
543
+ constructor({ runtime, dev } = {}) {
544
+ try {
545
+ if (dev) this.dev = true;
546
+ if (runtime) {
547
+ if (runtime && !NODE_RUNTIME.includes(runtime)) {
548
+ throw new Error("Unsupported runtime");
549
+ }
550
+ this.runtime = runtime;
551
+ } else {
552
+ this.runtime = "web";
553
+ }
554
+ print({ dev: this.dev }, "Current Runtime: ", this.runtime);
555
+ } catch (error) {
556
+ print({ dev: this.dev, color: "red" }, error);
557
+ throw error;
558
+ }
559
+ }
560
+ async createToken(algo, key, payload, exp) {
561
+ const algorithms = SUPPORTED_ALGORITHM[this.runtime];
562
+ const algoData = algorithms.find(({ name }) => {
563
+ return name == algo;
564
+ });
565
+ 6;
566
+ if (!algoData) {
567
+ throw new Error(`Algorithm ${algo} is not supported for ${this.runtime}`);
568
+ }
569
+ if (this.runtime === "web") {
570
+ if (algoData.type === "asymmetric") {
571
+ if (algoData.value !== "RSA+AES-GCM") {
572
+ throw new Error(`Algorithm ${algoData.name} is not supported for asymmetric encryption`);
573
+ }
574
+ return await this.web.encryptRSA(payload, key, exp);
575
+ } else {
576
+ if (algoData.value !== "AES-GCM") {
577
+ throw new Error(`Algorithm ${algoData.name} is not supported for symmetric encryption`);
578
+ }
579
+ return await this.web.encrypt(algoData.value, key, payload, exp);
580
+ }
581
+ } else {
582
+ if (algoData.type === "asymmetric") {
583
+ if (algoData.value !== "rsa+a256gcm") {
584
+ throw new Error(`Algorithm ${algoData.name} is not supported for asymmetric encryption`);
585
+ }
586
+ return await this.node.encryptRSA(payload, key, exp);
587
+ } else {
588
+ if (algoData.value !== "aes-256-gcm") {
589
+ throw new Error(`Algorithm ${algoData.name} is not supported for symmetric encryption`);
590
+ }
591
+ return await this.node.encrypt(algoData.value, key, payload, exp);
592
+ }
593
+ }
594
+ }
595
+ async verifyToken(token, key) {
596
+ const { meta, encrypted } = tokenFormatVerify(this.runtime, token);
597
+ const { runtime, algo, type, v, iv, tag, encryptedKey } = meta;
598
+ if (this.runtime !== runtime) {
599
+ throw new Error("Runtime not matching");
600
+ }
601
+ if (runtime === "web") {
602
+ if (type === "asymmetric") {
603
+ if (algo !== "RSA+AES-GCM") {
604
+ throw new Error(`Algorithm ${algo} is not supported for asymmetric encryption`);
605
+ }
606
+ return await this.web.decryptRSA(key, encryptedKey, { iv, encrypted });
607
+ } else {
608
+ if (algo !== "AES-GCM") {
609
+ throw new Error(`Algorithm ${algo} is not supported for symmetric encryption`);
610
+ }
611
+ return await this.web.decrypt("AES-GCM", key, { iv, encrypted });
612
+ }
613
+ } else {
614
+ if (type === "asymmetric") {
615
+ if (algo !== "RSA+A256GCM") {
616
+ throw new Error(`Algorithm ${algo} is not supported for asymmetric encryption`);
617
+ }
618
+ return await this.node.decryptRSA(key, encryptedKey, { iv, encrypted, tag });
619
+ } else {
620
+ if (algo !== "AES-256-GCM") {
621
+ throw new Error(`Algorithm ${algo} is not supported for symmetric encryption`);
622
+ }
623
+ return await this.node.decrypt("aes-256-gcm", key, { iv, encrypted, tag });
624
+ }
625
+ }
626
+ }
627
+ async create({ key, exp, algo }, payload) {
628
+ try {
629
+ if (!key) {
630
+ throw new Error("key is required to create token");
631
+ }
632
+ exp = exp ? jatTimeFormatter(exp) : jatTimeFormatter("5MIN");
633
+ const algorithm = algo || RUNTIME_DEFAULT_ALGORITHM("web").name;
634
+ return await this.createToken(algo, key, payload, exp);
635
+ } catch (error) {
636
+ print({ dev: this.dev, color: "red" }, error);
637
+ throw error;
638
+ }
639
+ }
640
+ async verify(token, key) {
641
+ try {
642
+ if (!token) {
643
+ throw new Error("Token is required to verify token");
644
+ }
645
+ if (!key) {
646
+ throw new Error("key is required to verify token");
647
+ }
648
+ const unfilterPayload = await this.verifyToken(token, key);
649
+ if (isExpired(unfilterPayload.exp)) {
650
+ throw new Error("Token expired");
651
+ }
652
+ return unfilterPayload.payload;
653
+ } catch (error) {
654
+ print({ dev: this.dev, color: "red" }, error);
655
+ throw error;
656
+ }
657
+ }
658
+ };
659
+ var PrivatePublicKeyGeneration = class {
660
+ web = new WebCrypto();
661
+ node = new NodeCrypto();
662
+ async generateKeyPair(runtime, dev) {
663
+ let finalRuntime = "web";
664
+ const development = dev === true ? true : false;
665
+ try {
666
+ if (runtime) {
667
+ if (!NODE_RUNTIME.includes(runtime)) {
668
+ throw new Error("Unsupported runtime");
669
+ }
670
+ finalRuntime = runtime;
671
+ }
672
+ const { privateKey, publicKey } = await this.web.rsaPrivatePublicKeyGeneration();
673
+ print({ dev: development, color: "green" }, "Current Runtime: ", finalRuntime);
674
+ print({ dev: development, color: "green" }, { privateKey, publicKey });
675
+ return { privateKey, publicKey };
676
+ } catch (error) {
677
+ print({ dev: development, color: "red" }, error);
678
+ throw error;
679
+ }
680
+ }
681
+ async generatePublicKey(privateKeyPem, runtime, dev) {
682
+ let finalRuntime = "web";
683
+ const development = dev === true ? true : false;
684
+ try {
685
+ if (runtime) {
686
+ if (!NODE_RUNTIME.includes(runtime)) {
687
+ throw new Error("Unsupported runtime");
688
+ }
689
+ finalRuntime = runtime;
690
+ }
691
+ const publicKey = await this.web.rsaPublicKeyGeneration(privateKeyPem);
692
+ print({ dev: development, color: "green" }, "Current Runtime: ", finalRuntime);
693
+ print({ dev: development, color: "green" }, publicKey);
694
+ return publicKey;
695
+ } catch (error) {
696
+ print({ dev: development, color: "red" }, error);
697
+ throw error;
698
+ }
699
+ }
700
+ };
701
+ var p2kgObject = new PrivatePublicKeyGeneration();
702
+ var generateKeyPair = (options) => {
703
+ const { runtime, dev } = options || {};
704
+ return p2kgObject.generateKeyPair(runtime, dev);
705
+ };
706
+ var generatePublicKey = (privateKeyPem, options) => {
707
+ const { runtime, dev } = options || {};
708
+ return p2kgObject.generatePublicKey(privateKeyPem, runtime, dev);
709
+ };
710
+ var JAT = ({ runtime, dev } = {}) => new NodeCryptoModule({ runtime, dev });
711
+ var getSupportedAlgorithm = () => SUPPORTED_ALGORITHM["web"];
712
+ var jat = JAT({});
713
+ var P2KG = {
714
+ generateKeyPair,
715
+ generatePublicKey
716
+ };
717
+ var jsonauthtoken = {
718
+ JAT,
719
+ P2KG
720
+ };
721
+ var node_index_default = jsonauthtoken;
722
+ export {
723
+ JAT,
724
+ NodeCryptoModule,
725
+ P2KG,
726
+ node_index_default as default,
727
+ getSupportedAlgorithm
728
+ };