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