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