@navios/jwt 0.5.0 → 0.7.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.
package/lib/index.cjs ADDED
@@ -0,0 +1,668 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+ let jsonwebtoken = require("jsonwebtoken");
29
+ jsonwebtoken = __toESM(jsonwebtoken);
30
+ let zod_v4 = require("zod/v4");
31
+ let __navios_core = require("@navios/core");
32
+
33
+ //#region src/options/jwt-service.options.mts
34
+ /**
35
+ * Request type for secret or key provider functions.
36
+ *
37
+ * Used to distinguish between signing and verification operations when
38
+ * dynamically resolving secrets or keys.
39
+ */ var RequestType = /* @__PURE__ */ function(RequestType$1) {
40
+ /** Request is for signing a token */ RequestType$1["Sign"] = "Sign";
41
+ /** Request is for verifying a token */ RequestType$1["Verify"] = "Verify";
42
+ return RequestType$1;
43
+ }({});
44
+ /**
45
+ * Supported JWT algorithms.
46
+ *
47
+ * Includes symmetric (HMAC) and asymmetric (RSA, ECDSA, EdDSA) algorithms.
48
+ */ const AlgorithmType = zod_v4.z.enum([
49
+ "HS256",
50
+ "HS384",
51
+ "HS512",
52
+ "RS256",
53
+ "RS384",
54
+ "RS512",
55
+ "ES256",
56
+ "ES384",
57
+ "ES512",
58
+ "PS256",
59
+ "PS384",
60
+ "PS512",
61
+ "none"
62
+ ]);
63
+ /**
64
+ * JWT header schema.
65
+ *
66
+ * Defines the structure of the JWT header with standard claims.
67
+ */ const JwtHeaderSchema = zod_v4.z.object({
68
+ alg: AlgorithmType.or(zod_v4.z.string()),
69
+ typ: zod_v4.z.string().optional(),
70
+ cty: zod_v4.z.string().optional(),
71
+ crit: zod_v4.z.string().array().optional(),
72
+ kid: zod_v4.z.string().optional(),
73
+ jku: zod_v4.z.string().optional(),
74
+ x5u: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.array(zod_v4.z.string())]).optional(),
75
+ "x5t#S256": zod_v4.z.string().optional(),
76
+ x5t: zod_v4.z.string().optional(),
77
+ x5c: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.array(zod_v4.z.string())]).optional()
78
+ });
79
+ /**
80
+ * Schema for JWT signing options.
81
+ *
82
+ * Defines all available options for signing tokens including algorithm,
83
+ * expiration, audience, issuer, and other standard JWT claims.
84
+ */ const SignOptionsSchema = zod_v4.z.object({
85
+ algorithm: AlgorithmType.optional(),
86
+ keyid: zod_v4.z.string().optional(),
87
+ expiresIn: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.number()]).optional(),
88
+ notBefore: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.number()]).optional(),
89
+ audience: zod_v4.z.union([
90
+ zod_v4.z.string(),
91
+ zod_v4.z.instanceof(RegExp),
92
+ zod_v4.z.array(zod_v4.z.union([zod_v4.z.string(), zod_v4.z.instanceof(RegExp)]))
93
+ ]).optional(),
94
+ subject: zod_v4.z.string().optional(),
95
+ issuer: zod_v4.z.string().optional(),
96
+ jwtid: zod_v4.z.string().optional(),
97
+ mutatePayload: zod_v4.z.boolean().optional(),
98
+ noTimestamp: zod_v4.z.boolean().optional(),
99
+ header: JwtHeaderSchema.optional(),
100
+ encoding: zod_v4.z.string().optional(),
101
+ allowInsecureKeySizes: zod_v4.z.boolean().optional(),
102
+ allowInvalidAsymmetricKeyTypes: zod_v4.z.boolean().optional()
103
+ });
104
+ /**
105
+ * Schema for JWT verification options.
106
+ *
107
+ * Defines all available options for verifying tokens including allowed
108
+ * algorithms, audience, issuer, expiration handling, and other validation rules.
109
+ */ const VerifyOptionsSchema = zod_v4.z.object({
110
+ algorithms: AlgorithmType.array().optional(),
111
+ audience: zod_v4.z.union([
112
+ zod_v4.z.string(),
113
+ zod_v4.z.instanceof(RegExp),
114
+ zod_v4.z.array(zod_v4.z.union([zod_v4.z.string(), zod_v4.z.instanceof(RegExp)]))
115
+ ]).optional(),
116
+ clockTimestamp: zod_v4.z.number().optional(),
117
+ clockTolerance: zod_v4.z.number().optional(),
118
+ complete: zod_v4.z.boolean().optional(),
119
+ issuer: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.string().array()]).optional(),
120
+ ignoreExpiration: zod_v4.z.boolean().optional(),
121
+ ignoreNotBefore: zod_v4.z.boolean().optional(),
122
+ jwtid: zod_v4.z.string().optional(),
123
+ nonce: zod_v4.z.string().optional(),
124
+ subject: zod_v4.z.string().optional(),
125
+ maxAge: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.number()]).optional(),
126
+ allowInvalidAsymmetricKeyTypes: zod_v4.z.boolean().optional()
127
+ });
128
+ /**
129
+ * Schema for JWT secret/key types.
130
+ *
131
+ * Supports string secrets, Buffer objects, and key objects with passphrases.
132
+ */ const SecretSchema = zod_v4.z.union([
133
+ zod_v4.z.string(),
134
+ zod_v4.z.instanceof(Buffer),
135
+ zod_v4.z.object({ type: zod_v4.z.string() }).passthrough(),
136
+ zod_v4.z.object({
137
+ key: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.instanceof(Buffer)]),
138
+ passphrase: zod_v4.z.string()
139
+ })
140
+ ]);
141
+ const JwtServiceOptionsSchema = zod_v4.z.object({
142
+ signOptions: SignOptionsSchema.optional(),
143
+ secret: zod_v4.z.string().optional(),
144
+ publicKey: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.instanceof(Buffer)]).optional(),
145
+ privateKey: SecretSchema.optional(),
146
+ verifyOptions: VerifyOptionsSchema.optional(),
147
+ secretOrKeyProvider: zod_v4.z.function({
148
+ input: [
149
+ zod_v4.z.enum(RequestType),
150
+ zod_v4.z.any(),
151
+ zod_v4.z.union([SignOptionsSchema, VerifyOptionsSchema]).optional()
152
+ ],
153
+ output: zod_v4.z.union([SecretSchema, zod_v4.z.promise(SecretSchema)])
154
+ }).optional()
155
+ });
156
+
157
+ //#endregion
158
+ //#region src/jwt.service.mts
159
+ function applyDecs2203RFactory() {
160
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
161
+ return function addInitializer(initializer) {
162
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
163
+ assertCallable(initializer, "An initializer");
164
+ initializers.push(initializer);
165
+ };
166
+ }
167
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
168
+ var kindStr;
169
+ switch (kind) {
170
+ case 1:
171
+ kindStr = "accessor";
172
+ break;
173
+ case 2:
174
+ kindStr = "method";
175
+ break;
176
+ case 3:
177
+ kindStr = "getter";
178
+ break;
179
+ case 4:
180
+ kindStr = "setter";
181
+ break;
182
+ default: kindStr = "field";
183
+ }
184
+ var ctx = {
185
+ kind: kindStr,
186
+ name: isPrivate ? "#" + name : name,
187
+ static: isStatic,
188
+ private: isPrivate,
189
+ metadata
190
+ };
191
+ var decoratorFinishedRef = { v: false };
192
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
193
+ var get, set;
194
+ if (kind === 0) if (isPrivate) {
195
+ get = desc.get;
196
+ set = desc.set;
197
+ } else {
198
+ get = function() {
199
+ return this[name];
200
+ };
201
+ set = function(v) {
202
+ this[name] = v;
203
+ };
204
+ }
205
+ else if (kind === 2) get = function() {
206
+ return desc.value;
207
+ };
208
+ else {
209
+ if (kind === 1 || kind === 3) get = function() {
210
+ return desc.get.call(this);
211
+ };
212
+ if (kind === 1 || kind === 4) set = function(v) {
213
+ desc.set.call(this, v);
214
+ };
215
+ }
216
+ ctx.access = get && set ? {
217
+ get,
218
+ set
219
+ } : get ? { get } : { set };
220
+ try {
221
+ return dec(value, ctx);
222
+ } finally {
223
+ decoratorFinishedRef.v = true;
224
+ }
225
+ }
226
+ function assertNotFinished(decoratorFinishedRef, fnName) {
227
+ if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished");
228
+ }
229
+ function assertCallable(fn, hint) {
230
+ if (typeof fn !== "function") throw new TypeError(hint + " must be a function");
231
+ }
232
+ function assertValidReturnValue(kind, value) {
233
+ var type = typeof value;
234
+ if (kind === 1) {
235
+ if (type !== "object" || value === null) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
236
+ if (value.get !== void 0) assertCallable(value.get, "accessor.get");
237
+ if (value.set !== void 0) assertCallable(value.set, "accessor.set");
238
+ if (value.init !== void 0) assertCallable(value.init, "accessor.init");
239
+ } else if (type !== "function") {
240
+ var hint;
241
+ if (kind === 0) hint = "field";
242
+ else if (kind === 10) hint = "class";
243
+ else hint = "method";
244
+ throw new TypeError(hint + " decorators must return a function or void 0");
245
+ }
246
+ }
247
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
248
+ var decs = decInfo[0];
249
+ var desc, init, value;
250
+ if (isPrivate) if (kind === 0 || kind === 1) desc = {
251
+ get: decInfo[3],
252
+ set: decInfo[4]
253
+ };
254
+ else if (kind === 3) desc = { get: decInfo[3] };
255
+ else if (kind === 4) desc = { set: decInfo[3] };
256
+ else desc = { value: decInfo[3] };
257
+ else if (kind !== 0) desc = Object.getOwnPropertyDescriptor(base, name);
258
+ if (kind === 1) value = {
259
+ get: desc.get,
260
+ set: desc.set
261
+ };
262
+ else if (kind === 2) value = desc.value;
263
+ else if (kind === 3) value = desc.get;
264
+ else if (kind === 4) value = desc.set;
265
+ var newValue, get, set;
266
+ if (typeof decs === "function") {
267
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
268
+ if (newValue !== void 0) {
269
+ assertValidReturnValue(kind, newValue);
270
+ if (kind === 0) init = newValue;
271
+ else if (kind === 1) {
272
+ init = newValue.init;
273
+ get = newValue.get || value.get;
274
+ set = newValue.set || value.set;
275
+ value = {
276
+ get,
277
+ set
278
+ };
279
+ } else value = newValue;
280
+ }
281
+ } else for (var i = decs.length - 1; i >= 0; i--) {
282
+ var dec = decs[i];
283
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
284
+ if (newValue !== void 0) {
285
+ assertValidReturnValue(kind, newValue);
286
+ var newInit;
287
+ if (kind === 0) newInit = newValue;
288
+ else if (kind === 1) {
289
+ newInit = newValue.init;
290
+ get = newValue.get || value.get;
291
+ set = newValue.set || value.set;
292
+ value = {
293
+ get,
294
+ set
295
+ };
296
+ } else value = newValue;
297
+ if (newInit !== void 0) if (init === void 0) init = newInit;
298
+ else if (typeof init === "function") init = [init, newInit];
299
+ else init.push(newInit);
300
+ }
301
+ }
302
+ if (kind === 0 || kind === 1) {
303
+ if (init === void 0) init = function(instance, init$1) {
304
+ return init$1;
305
+ };
306
+ else if (typeof init !== "function") {
307
+ var ownInitializers = init;
308
+ init = function(instance, init$1) {
309
+ var value$1 = init$1;
310
+ for (var i$1 = 0; i$1 < ownInitializers.length; i$1++) value$1 = ownInitializers[i$1].call(instance, value$1);
311
+ return value$1;
312
+ };
313
+ } else {
314
+ var originalInitializer = init;
315
+ init = function(instance, init$1) {
316
+ return originalInitializer.call(instance, init$1);
317
+ };
318
+ }
319
+ ret.push(init);
320
+ }
321
+ if (kind !== 0) {
322
+ if (kind === 1) {
323
+ desc.get = value.get;
324
+ desc.set = value.set;
325
+ } else if (kind === 2) desc.value = value;
326
+ else if (kind === 3) desc.get = value;
327
+ else if (kind === 4) desc.set = value;
328
+ if (isPrivate) if (kind === 1) {
329
+ ret.push(function(instance, args) {
330
+ return value.get.call(instance, args);
331
+ });
332
+ ret.push(function(instance, args) {
333
+ return value.set.call(instance, args);
334
+ });
335
+ } else if (kind === 2) ret.push(value);
336
+ else ret.push(function(instance, args) {
337
+ return value.call(instance, args);
338
+ });
339
+ else Object.defineProperty(base, name, desc);
340
+ }
341
+ }
342
+ function applyMemberDecs(Class, decInfos, metadata) {
343
+ var ret = [];
344
+ var protoInitializers;
345
+ var staticInitializers;
346
+ var existingProtoNonFields = /* @__PURE__ */ new Map();
347
+ var existingStaticNonFields = /* @__PURE__ */ new Map();
348
+ for (var i = 0; i < decInfos.length; i++) {
349
+ var decInfo = decInfos[i];
350
+ if (!Array.isArray(decInfo)) continue;
351
+ var kind = decInfo[1];
352
+ var name = decInfo[2];
353
+ var isPrivate = decInfo.length > 3;
354
+ var isStatic = kind >= 5;
355
+ var base;
356
+ var initializers;
357
+ if (isStatic) {
358
+ base = Class;
359
+ kind = kind - 5;
360
+ staticInitializers = staticInitializers || [];
361
+ initializers = staticInitializers;
362
+ } else {
363
+ base = Class.prototype;
364
+ protoInitializers = protoInitializers || [];
365
+ initializers = protoInitializers;
366
+ }
367
+ if (kind !== 0 && !isPrivate) {
368
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
369
+ var existingKind = existingNonFields.get(name) || 0;
370
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
371
+ else if (!existingKind && kind > 2) existingNonFields.set(name, kind);
372
+ else existingNonFields.set(name, true);
373
+ }
374
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
375
+ }
376
+ pushInitializers(ret, protoInitializers);
377
+ pushInitializers(ret, staticInitializers);
378
+ return ret;
379
+ }
380
+ function pushInitializers(ret, initializers) {
381
+ if (initializers) ret.push(function(instance) {
382
+ for (var i = 0; i < initializers.length; i++) initializers[i].call(instance);
383
+ return instance;
384
+ });
385
+ }
386
+ function applyClassDecs(targetClass, classDecs, metadata) {
387
+ if (classDecs.length > 0) {
388
+ var initializers = [];
389
+ var newClass = targetClass;
390
+ var name = targetClass.name;
391
+ for (var i = classDecs.length - 1; i >= 0; i--) {
392
+ var decoratorFinishedRef = { v: false };
393
+ try {
394
+ var nextNewClass = classDecs[i](newClass, {
395
+ kind: "class",
396
+ name,
397
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
398
+ metadata
399
+ });
400
+ } finally {
401
+ decoratorFinishedRef.v = true;
402
+ }
403
+ if (nextNewClass !== void 0) {
404
+ assertValidReturnValue(10, nextNewClass);
405
+ newClass = nextNewClass;
406
+ }
407
+ }
408
+ return [defineMetadata(newClass, metadata), function() {
409
+ for (var i$1 = 0; i$1 < initializers.length; i$1++) initializers[i$1].call(newClass);
410
+ }];
411
+ }
412
+ }
413
+ function defineMetadata(Class, metadata) {
414
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
415
+ configurable: true,
416
+ enumerable: true,
417
+ value: metadata
418
+ });
419
+ }
420
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
421
+ if (parentClass !== void 0) var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
422
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
423
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
424
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
425
+ return {
426
+ e,
427
+ get c() {
428
+ return applyClassDecs(targetClass, classDecs, metadata);
429
+ }
430
+ };
431
+ };
432
+ }
433
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
434
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
435
+ }
436
+ var _dec, _initClass;
437
+ /**
438
+ * Injection token for JwtService.
439
+ *
440
+ * Used internally by the dependency injection system to register and resolve JwtService instances.
441
+ */ const JwtServiceToken = __navios_core.InjectionToken.create(Symbol.for("JwtService"), JwtServiceOptionsSchema);
442
+ let _JwtService;
443
+ _dec = (0, __navios_core.Injectable)({ token: JwtServiceToken });
444
+ var JwtService = class {
445
+ options;
446
+ static {
447
+ ({c: [_JwtService, _initClass]} = _apply_decs_2203_r(this, [], [_dec]));
448
+ }
449
+ /**
450
+ * Creates a new JwtService instance.
451
+ *
452
+ * @param options - Configuration options for the JWT service
453
+ */ constructor(options = {}) {
454
+ this.options = options;
455
+ }
456
+ logger = (0, __navios_core.inject)(__navios_core.Logger, { context: _JwtService.name });
457
+ sign(payload, options = {}) {
458
+ const signOptions = this.mergeJwtOptions({ ...options }, "signOptions");
459
+ const secret = this.getSecretKey(payload, options, "privateKey", RequestType.Sign);
460
+ if (secret instanceof Promise) {
461
+ secret.catch(() => {});
462
+ this.logger.warn("For async version of \"secretOrKeyProvider\", please use \"signAsync\".");
463
+ throw new Error();
464
+ }
465
+ const allowedSignOptKeys = ["secret", "privateKey"];
466
+ const signOptKeys = Object.keys(signOptions);
467
+ if (typeof payload === "string" && signOptKeys.some((k) => !allowedSignOptKeys.includes(k))) throw new Error("Payload as string is not allowed with the following sign options: " + signOptKeys.join(", "));
468
+ return jsonwebtoken.default.sign(payload, secret, signOptions);
469
+ }
470
+ signAsync(payload, options = {}) {
471
+ const signOptions = this.mergeJwtOptions({ ...options }, "signOptions");
472
+ const secret = this.getSecretKey(payload, options, "privateKey", RequestType.Sign);
473
+ const allowedSignOptKeys = ["secret", "privateKey"];
474
+ const signOptKeys = Object.keys(signOptions);
475
+ if (typeof payload === "string" && signOptKeys.some((k) => !allowedSignOptKeys.includes(k))) throw new Error("Payload as string is not allowed with the following sign options: " + signOptKeys.join(", "));
476
+ return new Promise((resolve, reject) => Promise.resolve().then(() => secret).then((scrt) => {
477
+ jsonwebtoken.default.sign(payload, scrt, signOptions, (err, encoded) => err ? reject(err) : resolve(encoded));
478
+ }));
479
+ }
480
+ /**
481
+ * Verifies and decodes a JWT token synchronously.
482
+ *
483
+ * This method validates the token's signature, expiration, and other claims
484
+ * according to the provided options. If verification fails, an error is thrown.
485
+ *
486
+ * @template T - The expected type of the decoded payload
487
+ * @param token - The JWT token string to verify
488
+ * @param options - Verification options including algorithms, audience, issuer, etc.
489
+ * @returns The decoded payload as type T
490
+ * @throws {TokenExpiredError} If the token has expired
491
+ * @throws {NotBeforeError} If the token is not yet valid (nbf claim)
492
+ * @throws {JsonWebTokenError} If the token is invalid or malformed
493
+ * @throws {Error} If `secretOrKeyProvider` returns a Promise (use `verifyAsync` instead)
494
+ *
495
+ * @example
496
+ * ```ts
497
+ * try {
498
+ * const payload = jwtService.verify<{ userId: string; role: string }>(token)
499
+ * console.log(payload.userId) // '123'
500
+ * } catch (error) {
501
+ * if (error instanceof TokenExpiredError) {
502
+ * console.error('Token expired')
503
+ * }
504
+ * }
505
+ * ```
506
+ */ verify(token, options = {}) {
507
+ const verifyOptions = this.mergeJwtOptions({ ...options }, "verifyOptions");
508
+ const secret = this.getSecretKey(token, options, "publicKey", RequestType.Verify);
509
+ if (secret instanceof Promise) {
510
+ secret.catch(() => {});
511
+ this.logger.warn("For async version of \"secretOrKeyProvider\", please use \"verifyAsync\".");
512
+ throw new Error();
513
+ }
514
+ return jsonwebtoken.default.verify(token, secret, verifyOptions);
515
+ }
516
+ /**
517
+ * Verifies and decodes a JWT token asynchronously.
518
+ *
519
+ * Use this method when `secretOrKeyProvider` returns a Promise or when you need
520
+ * to handle async key resolution. Provides the same validation as `verify()`.
521
+ *
522
+ * @template T - The expected type of the decoded payload
523
+ * @param token - The JWT token string to verify
524
+ * @param options - Verification options including algorithms, audience, issuer, etc.
525
+ * @returns A Promise that resolves to the decoded payload as type T
526
+ * @throws {TokenExpiredError} If the token has expired
527
+ * @throws {NotBeforeError} If the token is not yet valid (nbf claim)
528
+ * @throws {JsonWebTokenError} If the token is invalid or malformed
529
+ *
530
+ * @example
531
+ * ```ts
532
+ * try {
533
+ * const payload = await jwtService.verifyAsync<{ userId: string }>(token)
534
+ * console.log(payload.userId)
535
+ * } catch (error) {
536
+ * if (error instanceof TokenExpiredError) {
537
+ * console.error('Token expired')
538
+ * }
539
+ * }
540
+ * ```
541
+ */ verifyAsync(token, options = {}) {
542
+ const verifyOptions = this.mergeJwtOptions({ ...options }, "verifyOptions");
543
+ const secret = this.getSecretKey(token, options, "publicKey", RequestType.Verify);
544
+ return new Promise((resolve, reject) => Promise.resolve().then(() => secret).then((scrt) => {
545
+ jsonwebtoken.default.verify(token, scrt, verifyOptions, (err, decoded) => err ? reject(err) : resolve(decoded));
546
+ }).catch(reject));
547
+ }
548
+ /**
549
+ * Decodes a JWT token without verification.
550
+ *
551
+ * This method decodes the token without validating its signature or claims.
552
+ * Use this only when you need to inspect the token contents without verification.
553
+ * For secure token validation, use `verify()` or `verifyAsync()` instead.
554
+ *
555
+ * @template T - The expected type of the decoded payload
556
+ * @param token - The JWT token string to decode
557
+ * @param options - Decode options (complete, json, etc.)
558
+ * @returns The decoded payload as type T, or null if decoding fails
559
+ *
560
+ * @example
561
+ * ```ts
562
+ * // Decode without verification (not recommended for production)
563
+ * const payload = jwtService.decode<{ userId: string }>(token)
564
+ * if (payload) {
565
+ * console.log(payload.userId)
566
+ * }
567
+ * ```
568
+ */ decode(token, options) {
569
+ return jsonwebtoken.default.decode(token, options);
570
+ }
571
+ mergeJwtOptions(options, key) {
572
+ delete options.secret;
573
+ if (key === "signOptions") delete options.privateKey;
574
+ else delete options.publicKey;
575
+ return options ? {
576
+ ...this.options[key],
577
+ ...options
578
+ } : this.options[key];
579
+ }
580
+ getSecretKey(token, options, key, secretRequestType) {
581
+ return this.options.secretOrKeyProvider ? this.options.secretOrKeyProvider(secretRequestType, token, options) : options?.secret || this.options.secret || (key === "privateKey" ? options?.privateKey || this.options.privateKey : options?.publicKey || this.options.publicKey) || this.options[key];
582
+ }
583
+ static {
584
+ _initClass();
585
+ }
586
+ };
587
+
588
+ //#endregion
589
+ //#region src/jwt-service.provider.mts
590
+ function provideJwtService(config) {
591
+ if (typeof config === "function") return __navios_core.InjectionToken.factory(JwtServiceToken, config);
592
+ return __navios_core.InjectionToken.bound(JwtServiceToken, config);
593
+ }
594
+
595
+ //#endregion
596
+ //#region src/index.mts
597
+ /**
598
+ * Error thrown when a JWT token has expired.
599
+ *
600
+ * This error is thrown by `verify()` and `verifyAsync()` when the token's
601
+ * expiration time (exp claim) has passed.
602
+ *
603
+ * @example
604
+ * ```ts
605
+ * try {
606
+ * jwtService.verify(token)
607
+ * } catch (error) {
608
+ * if (error instanceof TokenExpiredError) {
609
+ * console.error('Token expired at:', error.expiredAt)
610
+ * }
611
+ * }
612
+ * ```
613
+ */ const TokenExpiredError = jsonwebtoken.default.TokenExpiredError;
614
+ /**
615
+ * Error thrown when a JWT token is not yet valid.
616
+ *
617
+ * This error is thrown by `verify()` and `verifyAsync()` when the token's
618
+ * "not before" time (nbf claim) is in the future.
619
+ *
620
+ * @example
621
+ * ```ts
622
+ * try {
623
+ * jwtService.verify(token)
624
+ * } catch (error) {
625
+ * if (error instanceof NotBeforeError) {
626
+ * console.error('Token not valid until:', error.date)
627
+ * }
628
+ * }
629
+ * ```
630
+ */ const NotBeforeError = jsonwebtoken.default.NotBeforeError;
631
+ /**
632
+ * Base error class for JWT-related errors.
633
+ *
634
+ * This is the base class for all JWT errors including `TokenExpiredError`
635
+ * and `NotBeforeError`. It's thrown for invalid or malformed tokens.
636
+ *
637
+ * @example
638
+ * ```ts
639
+ * try {
640
+ * jwtService.verify(token)
641
+ * } catch (error) {
642
+ * if (error instanceof JsonWebTokenError) {
643
+ * console.error('JWT error:', error.message)
644
+ * }
645
+ * }
646
+ * ```
647
+ */ const JsonWebTokenError = jsonwebtoken.default.JsonWebTokenError;
648
+
649
+ //#endregion
650
+ exports.AlgorithmType = AlgorithmType;
651
+ exports.JsonWebTokenError = JsonWebTokenError;
652
+ exports.JwtHeaderSchema = JwtHeaderSchema;
653
+ Object.defineProperty(exports, 'JwtService', {
654
+ enumerable: true,
655
+ get: function () {
656
+ return _JwtService;
657
+ }
658
+ });
659
+ exports.JwtServiceOptionsSchema = JwtServiceOptionsSchema;
660
+ exports.JwtServiceToken = JwtServiceToken;
661
+ exports.NotBeforeError = NotBeforeError;
662
+ exports.RequestType = RequestType;
663
+ exports.SecretSchema = SecretSchema;
664
+ exports.SignOptionsSchema = SignOptionsSchema;
665
+ exports.TokenExpiredError = TokenExpiredError;
666
+ exports.VerifyOptionsSchema = VerifyOptionsSchema;
667
+ exports.provideJwtService = provideJwtService;
668
+ //# sourceMappingURL=index.cjs.map