@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/CHANGELOG.md +24 -0
- package/README.md +211 -34
- package/dist/src/index.d.mts +51 -0
- package/dist/src/index.d.mts.map +1 -1
- package/dist/src/jwt-service.provider.d.mts +50 -0
- package/dist/src/jwt-service.provider.d.mts.map +1 -1
- package/dist/src/jwt.service.d.mts +170 -0
- package/dist/src/jwt.service.d.mts.map +1 -1
- package/dist/src/options/jwt-service.options.d.mts +106 -0
- package/dist/src/options/jwt-service.options.d.mts.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/lib/index.cjs +668 -0
- package/lib/index.cjs.map +1 -0
- package/lib/index.d.cts +936 -0
- package/lib/index.d.cts.map +1 -0
- package/lib/index.d.mts +936 -21
- package/lib/index.d.mts.map +1 -0
- package/lib/index.mjs +610 -270
- package/lib/index.mjs.map +1 -1
- package/package.json +5 -5
- package/project.json +2 -2
- package/src/index.mts +54 -0
- package/src/jwt-service.provider.mts +50 -0
- package/src/jwt.service.mts +170 -0
- package/src/options/jwt-service.options.mts +106 -0
- package/tsdown.config.mts +33 -0
- package/lib/_tsup-dts-rollup.d.mts +0 -624
- package/lib/_tsup-dts-rollup.d.ts +0 -624
- package/lib/index.d.ts +0 -21
- package/lib/index.js +0 -301
- package/lib/index.js.map +0 -1
- package/tsup.config.mts +0 -12
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.7.0] - 2025-12-18
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **Comprehensive JSDoc Documentation**: Added detailed JSDoc comments to all public APIs including:
|
|
13
|
+
- `JwtService` class and all methods (`sign`, `signAsync`, `verify`, `verifyAsync`, `decode`)
|
|
14
|
+
- `provideJwtService` function with overloads
|
|
15
|
+
- Type definitions and interfaces (`JwtServiceOptions`, `JwtSignOptions`, `JwtVerifyOptions`, etc.)
|
|
16
|
+
- Error classes (`TokenExpiredError`, `NotBeforeError`, `JsonWebTokenError`)
|
|
17
|
+
- **Enhanced README**: Improved documentation with better examples, clearer API reference, and usage patterns
|
|
18
|
+
|
|
19
|
+
### Documentation
|
|
20
|
+
|
|
21
|
+
- Complete JSDoc comments for better IDE support and developer experience
|
|
22
|
+
- Updated README with comprehensive examples and API documentation
|
|
23
|
+
- Clarified usage patterns for synchronous and asynchronous operations
|
|
24
|
+
- Added examples for different JWT algorithms and key management strategies
|
package/README.md
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## Overview
|
|
4
4
|
|
|
5
|
-
Navios JWT is a TypeScript library that provides a robust implementation for JSON Web Token (JWT)
|
|
5
|
+
Navios JWT is a TypeScript library that provides a robust implementation for JSON Web Token (JWT) operations in Navios applications. It wraps the functionality of the `jsonwebtoken` library with a service-oriented approach that integrates seamlessly with the Navios dependency injection system.
|
|
6
6
|
|
|
7
|
-
It was forked from a [NestJS](https://github.com/nestjs/jwt) library and is designed to be used with the Navios framework, providing a
|
|
7
|
+
It was forked from a [NestJS](https://github.com/nestjs/jwt) library and is designed to be used with the Navios framework, providing a type-safe and developer-friendly experience for signing and verifying JWTs.
|
|
8
8
|
|
|
9
9
|
## Installation
|
|
10
10
|
|
|
@@ -16,84 +16,222 @@ yarn add @navios/jwt
|
|
|
16
16
|
|
|
17
17
|
## Features
|
|
18
18
|
|
|
19
|
-
- Token
|
|
20
|
-
- Token
|
|
21
|
-
- Support for
|
|
22
|
-
-
|
|
23
|
-
- Type
|
|
19
|
+
- **Token Signing**: Create JWTs with customizable options (expiration, algorithm, claims, etc.)
|
|
20
|
+
- **Token Verification**: Comprehensive validation with support for all standard JWT claims
|
|
21
|
+
- **Multiple Algorithms**: Support for symmetric (HS256, HS384, HS512) and asymmetric (RS256, ES256, PS256, etc.) algorithms
|
|
22
|
+
- **Dependency Injection**: Seamless integration with Navios DI system
|
|
23
|
+
- **Type Safety**: Full TypeScript support with Zod schema validation
|
|
24
|
+
- **Async Support**: Both synchronous and asynchronous APIs for flexible key management
|
|
25
|
+
- **Dynamic Key Providers**: Support for dynamic secret/key resolution based on request context
|
|
24
26
|
|
|
25
|
-
##
|
|
27
|
+
## Quick Start
|
|
26
28
|
|
|
27
29
|
### Basic Setup
|
|
28
30
|
|
|
29
31
|
```typescript
|
|
30
|
-
import { inject } from '@navios/core'
|
|
31
32
|
import { provideJwtService } from '@navios/jwt'
|
|
32
33
|
|
|
33
|
-
|
|
34
|
+
// Static configuration
|
|
35
|
+
const JwtService = provideJwtService({
|
|
34
36
|
secret: 'your-secret-key',
|
|
35
37
|
signOptions: {
|
|
36
38
|
expiresIn: '1h',
|
|
39
|
+
algorithm: 'HS256',
|
|
40
|
+
},
|
|
41
|
+
verifyOptions: {
|
|
42
|
+
algorithms: ['HS256'],
|
|
37
43
|
},
|
|
38
|
-
})
|
|
39
|
-
// Or with factory
|
|
40
|
-
const JwtService = provideJwtService(async () => {
|
|
41
|
-
const config = await inject(ConfigService)
|
|
42
|
-
return config.jwt
|
|
43
44
|
})
|
|
44
45
|
```
|
|
45
46
|
|
|
46
|
-
###
|
|
47
|
+
### Using with Dependency Injection
|
|
47
48
|
|
|
48
49
|
```typescript
|
|
49
|
-
|
|
50
|
-
import { Injectable, syncInject } from '@navios/core'
|
|
51
|
-
//or to load without options
|
|
50
|
+
import { Injectable, inject } from '@navios/core'
|
|
52
51
|
import { JwtService } from '@navios/jwt'
|
|
53
52
|
|
|
54
|
-
import { JwtService } from '../service/jwt.service.mjs'
|
|
55
|
-
|
|
56
53
|
@Injectable()
|
|
57
54
|
class AuthService {
|
|
58
|
-
jwtService =
|
|
55
|
+
jwtService = inject(JwtService)
|
|
56
|
+
|
|
57
|
+
async login(userId: string, role: string) {
|
|
58
|
+
// Sign a token
|
|
59
|
+
const token = this.jwtService.sign(
|
|
60
|
+
{ userId, role },
|
|
61
|
+
{ expiresIn: '1h' }
|
|
62
|
+
)
|
|
63
|
+
return { token }
|
|
64
|
+
}
|
|
59
65
|
|
|
60
|
-
async
|
|
61
|
-
|
|
62
|
-
|
|
66
|
+
async validateToken(token: string) {
|
|
67
|
+
try {
|
|
68
|
+
// Verify and decode the token
|
|
69
|
+
const payload = this.jwtService.verify<{ userId: string; role: string }>(token)
|
|
70
|
+
return payload
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error instanceof TokenExpiredError) {
|
|
73
|
+
throw new Error('Token expired')
|
|
74
|
+
}
|
|
75
|
+
throw error
|
|
76
|
+
}
|
|
63
77
|
}
|
|
64
78
|
}
|
|
65
79
|
```
|
|
66
80
|
|
|
81
|
+
## Usage Examples
|
|
82
|
+
|
|
83
|
+
### Async Configuration
|
|
84
|
+
|
|
85
|
+
When you need to load configuration dynamically:
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
import { provideJwtService } from '@navios/jwt'
|
|
89
|
+
import { inject } from '@navios/core'
|
|
90
|
+
|
|
91
|
+
const JwtService = provideJwtService(async () => {
|
|
92
|
+
const configService = await inject(ConfigService)
|
|
93
|
+
return {
|
|
94
|
+
secret: configService.jwt.secret,
|
|
95
|
+
signOptions: {
|
|
96
|
+
expiresIn: configService.jwt.expiresIn,
|
|
97
|
+
algorithm: configService.jwt.algorithm,
|
|
98
|
+
},
|
|
99
|
+
}
|
|
100
|
+
})
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Asymmetric Keys (RS256)
|
|
104
|
+
|
|
105
|
+
For applications using RSA or ECDSA keys:
|
|
106
|
+
|
|
107
|
+
```typescript
|
|
108
|
+
import { provideJwtService } from '@navios/jwt'
|
|
109
|
+
import fs from 'fs'
|
|
110
|
+
|
|
111
|
+
const JwtService = provideJwtService({
|
|
112
|
+
privateKey: fs.readFileSync('private.pem'),
|
|
113
|
+
publicKey: fs.readFileSync('public.pem'),
|
|
114
|
+
signOptions: {
|
|
115
|
+
algorithm: 'RS256',
|
|
116
|
+
expiresIn: '1h',
|
|
117
|
+
},
|
|
118
|
+
verifyOptions: {
|
|
119
|
+
algorithms: ['RS256'],
|
|
120
|
+
},
|
|
121
|
+
})
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### Dynamic Key Provider
|
|
125
|
+
|
|
126
|
+
For applications that need to resolve keys dynamically based on the token:
|
|
127
|
+
|
|
128
|
+
```typescript
|
|
129
|
+
import { provideJwtService, RequestType } from '@navios/jwt'
|
|
130
|
+
|
|
131
|
+
const JwtService = provideJwtService({
|
|
132
|
+
secretOrKeyProvider: (requestType, token, options) => {
|
|
133
|
+
if (requestType === RequestType.Sign) {
|
|
134
|
+
// Return signing key
|
|
135
|
+
return getSigningKey()
|
|
136
|
+
} else {
|
|
137
|
+
// Extract key ID from token and return corresponding public key
|
|
138
|
+
const decoded = jwt.decode(token, { complete: true })
|
|
139
|
+
const kid = decoded?.header?.kid
|
|
140
|
+
return getPublicKeyByKid(kid)
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Signing Tokens
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
// Synchronous signing
|
|
150
|
+
const token = jwtService.sign(
|
|
151
|
+
{ userId: '123', role: 'admin' },
|
|
152
|
+
{ expiresIn: '1h' }
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
// Asynchronous signing (for async key providers)
|
|
156
|
+
const token = await jwtService.signAsync(
|
|
157
|
+
{ userId: '123', role: 'admin' },
|
|
158
|
+
{ expiresIn: '1h' }
|
|
159
|
+
)
|
|
160
|
+
```
|
|
161
|
+
|
|
67
162
|
### Verifying Tokens
|
|
68
163
|
|
|
69
164
|
```typescript
|
|
165
|
+
// Synchronous verification
|
|
70
166
|
try {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
console.log(payload) // { userId: 123, role: 'admin', iat: 1234567890, exp: 1234571490 }
|
|
167
|
+
const payload = jwtService.verify<{ userId: string; role: string }>(token)
|
|
168
|
+
console.log(payload.userId) // '123'
|
|
74
169
|
} catch (error) {
|
|
75
|
-
// Handle verification errors
|
|
76
170
|
if (error instanceof TokenExpiredError) {
|
|
77
171
|
console.error('Token expired')
|
|
78
172
|
} else if (error instanceof JsonWebTokenError) {
|
|
79
173
|
console.error('Invalid token')
|
|
80
174
|
}
|
|
81
175
|
}
|
|
176
|
+
|
|
177
|
+
// Asynchronous verification (for async key providers)
|
|
178
|
+
try {
|
|
179
|
+
const payload = await jwtService.verifyAsync<{ userId: string }>(token)
|
|
180
|
+
console.log(payload.userId)
|
|
181
|
+
} catch (error) {
|
|
182
|
+
// Handle errors
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### Decoding Without Verification
|
|
187
|
+
|
|
188
|
+
```typescript
|
|
189
|
+
// Decode without verification (use with caution)
|
|
190
|
+
const payload = jwtService.decode<{ userId: string }>(token)
|
|
191
|
+
if (payload) {
|
|
192
|
+
console.log(payload.userId)
|
|
193
|
+
}
|
|
82
194
|
```
|
|
83
195
|
|
|
84
196
|
## API Reference
|
|
85
197
|
|
|
86
|
-
###
|
|
198
|
+
### `JwtService`
|
|
199
|
+
|
|
200
|
+
The main service class for JWT operations.
|
|
201
|
+
|
|
202
|
+
#### Methods
|
|
203
|
+
|
|
204
|
+
- **`sign(payload, options?)`**: Signs a JWT payload synchronously
|
|
205
|
+
- **`signAsync(payload, options?)`**: Signs a JWT payload asynchronously
|
|
206
|
+
- **`verify<T>(token, options?)`**: Verifies and decodes a JWT token synchronously
|
|
207
|
+
- **`verifyAsync<T>(token, options?)`**: Verifies and decodes a JWT token asynchronously
|
|
208
|
+
- **`decode<T>(token, options?)`**: Decodes a JWT token without verification
|
|
209
|
+
|
|
210
|
+
### `provideJwtService(config)`
|
|
211
|
+
|
|
212
|
+
Creates a JWT service provider for dependency injection.
|
|
213
|
+
|
|
214
|
+
**Overloads:**
|
|
215
|
+
- `provideJwtService(config: JwtServiceOptions)`: Static configuration
|
|
216
|
+
- `provideJwtService(config: () => Promise<JwtServiceOptions>)`: Async factory configuration
|
|
217
|
+
|
|
218
|
+
### `JwtServiceOptions`
|
|
87
219
|
|
|
88
220
|
Configuration options for the JWT service:
|
|
89
221
|
|
|
90
222
|
```typescript
|
|
91
223
|
interface JwtServiceOptions {
|
|
224
|
+
/** Default options for signing tokens */
|
|
92
225
|
signOptions?: SignOptions
|
|
226
|
+
/** Default secret for symmetric algorithms (HS256, HS384, HS512) */
|
|
93
227
|
secret?: string
|
|
228
|
+
/** Default public key for asymmetric algorithms (RS256, ES256, etc.) */
|
|
94
229
|
publicKey?: string | Buffer
|
|
230
|
+
/** Default private key for asymmetric algorithms */
|
|
95
231
|
privateKey?: Secret
|
|
232
|
+
/** Default options for verifying tokens */
|
|
96
233
|
verifyOptions?: VerifyOptions
|
|
234
|
+
/** Optional function to dynamically resolve secrets/keys */
|
|
97
235
|
secretOrKeyProvider?: (
|
|
98
236
|
requestType: RequestType,
|
|
99
237
|
token?: string,
|
|
@@ -102,13 +240,52 @@ interface JwtServiceOptions {
|
|
|
102
240
|
}
|
|
103
241
|
```
|
|
104
242
|
|
|
105
|
-
### Error
|
|
243
|
+
### Error Classes
|
|
106
244
|
|
|
107
245
|
The library exports error classes from the underlying `jsonwebtoken` library:
|
|
108
246
|
|
|
109
|
-
-
|
|
110
|
-
- `
|
|
111
|
-
-
|
|
247
|
+
- **`TokenExpiredError`**: Thrown when the token has expired
|
|
248
|
+
- `expiredAt`: Date when the token expired
|
|
249
|
+
- **`NotBeforeError`**: Thrown when the token is not yet valid (nbf claim)
|
|
250
|
+
- `date`: Date when the token becomes valid
|
|
251
|
+
- **`JsonWebTokenError`**: Base class for all JWT errors
|
|
252
|
+
- `message`: Error message describing the issue
|
|
253
|
+
|
|
254
|
+
### Type Definitions
|
|
255
|
+
|
|
256
|
+
- **`SignOptions`**: Options for signing tokens (algorithm, expiration, audience, issuer, etc.)
|
|
257
|
+
- **`VerifyOptions`**: Options for verifying tokens (algorithms, audience, issuer, expiration handling, etc.)
|
|
258
|
+
- **`JwtSignOptions`**: Extends `SignOptions` with `secret` and `privateKey` properties
|
|
259
|
+
- **`JwtVerifyOptions`**: Extends `VerifyOptions` with `secret` and `publicKey` properties
|
|
260
|
+
- **`RequestType`**: Enum for distinguishing sign vs verify operations (`Sign` | `Verify`)
|
|
261
|
+
|
|
262
|
+
## Best Practices
|
|
263
|
+
|
|
264
|
+
1. **Always use `verify()` or `verifyAsync()`** for production code. Never use `decode()` for security-sensitive operations.
|
|
265
|
+
|
|
266
|
+
2. **Use async methods** when using `secretOrKeyProvider` that returns a Promise.
|
|
267
|
+
|
|
268
|
+
3. **Specify allowed algorithms** in `verifyOptions` to prevent algorithm confusion attacks:
|
|
269
|
+
```typescript
|
|
270
|
+
verifyOptions: {
|
|
271
|
+
algorithms: ['HS256', 'RS256'], // Explicitly allow only these algorithms
|
|
272
|
+
}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
4. **Set appropriate expiration times** based on your security requirements:
|
|
276
|
+
```typescript
|
|
277
|
+
signOptions: {
|
|
278
|
+
expiresIn: '15m', // Short-lived access tokens
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
5. **Use asymmetric keys** for distributed systems where public keys can be shared:
|
|
283
|
+
```typescript
|
|
284
|
+
// Sign with private key
|
|
285
|
+
privateKey: fs.readFileSync('private.pem')
|
|
286
|
+
// Verify with public key (can be shared)
|
|
287
|
+
publicKey: fs.readFileSync('public.pem')
|
|
288
|
+
```
|
|
112
289
|
|
|
113
290
|
## Contributing
|
|
114
291
|
|
package/dist/src/index.d.mts
CHANGED
|
@@ -2,7 +2,58 @@ import jwt from 'jsonwebtoken';
|
|
|
2
2
|
export * from './options/jwt-service.options.mjs';
|
|
3
3
|
export * from './jwt.service.mjs';
|
|
4
4
|
export * from './jwt-service.provider.mjs';
|
|
5
|
+
/**
|
|
6
|
+
* Error thrown when a JWT token has expired.
|
|
7
|
+
*
|
|
8
|
+
* This error is thrown by `verify()` and `verifyAsync()` when the token's
|
|
9
|
+
* expiration time (exp claim) has passed.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* try {
|
|
14
|
+
* jwtService.verify(token)
|
|
15
|
+
* } catch (error) {
|
|
16
|
+
* if (error instanceof TokenExpiredError) {
|
|
17
|
+
* console.error('Token expired at:', error.expiredAt)
|
|
18
|
+
* }
|
|
19
|
+
* }
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
5
22
|
export declare const TokenExpiredError: typeof jwt.TokenExpiredError;
|
|
23
|
+
/**
|
|
24
|
+
* Error thrown when a JWT token is not yet valid.
|
|
25
|
+
*
|
|
26
|
+
* This error is thrown by `verify()` and `verifyAsync()` when the token's
|
|
27
|
+
* "not before" time (nbf claim) is in the future.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```ts
|
|
31
|
+
* try {
|
|
32
|
+
* jwtService.verify(token)
|
|
33
|
+
* } catch (error) {
|
|
34
|
+
* if (error instanceof NotBeforeError) {
|
|
35
|
+
* console.error('Token not valid until:', error.date)
|
|
36
|
+
* }
|
|
37
|
+
* }
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
6
40
|
export declare const NotBeforeError: typeof jwt.NotBeforeError;
|
|
41
|
+
/**
|
|
42
|
+
* Base error class for JWT-related errors.
|
|
43
|
+
*
|
|
44
|
+
* This is the base class for all JWT errors including `TokenExpiredError`
|
|
45
|
+
* and `NotBeforeError`. It's thrown for invalid or malformed tokens.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```ts
|
|
49
|
+
* try {
|
|
50
|
+
* jwtService.verify(token)
|
|
51
|
+
* } catch (error) {
|
|
52
|
+
* if (error instanceof JsonWebTokenError) {
|
|
53
|
+
* console.error('JWT error:', error.message)
|
|
54
|
+
* }
|
|
55
|
+
* }
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
7
58
|
export declare const JsonWebTokenError: typeof jwt.JsonWebTokenError;
|
|
8
59
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/src/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/index.mts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,cAAc,CAAA;AAE9B,cAAc,mCAAmC,CAAA;AACjD,cAAc,mBAAmB,CAAA;AACjC,cAAc,4BAA4B,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../src/index.mts"],"names":[],"mappings":"AAAA,OAAO,GAAG,MAAM,cAAc,CAAA;AAE9B,cAAc,mCAAmC,CAAA;AACjD,cAAc,mBAAmB,CAAA;AACjC,cAAc,4BAA4B,CAAA;AAE1C;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,iBAAiB,8BAAwB,CAAA;AAEtD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,cAAc,2BAAqB,CAAA;AAEhD;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,iBAAiB,8BAAwB,CAAA"}
|
|
@@ -2,6 +2,56 @@ import type { BoundInjectionToken, FactoryInjectionToken } from '@navios/core';
|
|
|
2
2
|
import type { JwtServiceOptions } from './options/jwt-service.options.mjs';
|
|
3
3
|
import { JwtService } from './jwt.service.mjs';
|
|
4
4
|
import { JwtServiceOptionsSchema } from './options/jwt-service.options.mjs';
|
|
5
|
+
/**
|
|
6
|
+
* Creates a JWT service provider for dependency injection.
|
|
7
|
+
*
|
|
8
|
+
* This function creates an injection token that can be used to register and resolve
|
|
9
|
+
* `JwtService` instances in the Navios dependency injection container. It supports
|
|
10
|
+
* both static configuration and async factory functions for dynamic configuration.
|
|
11
|
+
*
|
|
12
|
+
* @param config - Static JWT service configuration options
|
|
13
|
+
* @returns A bound injection token that can be used with `inject()` or `syncInject()`
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* // Static configuration
|
|
18
|
+
* const JwtService = provideJwtService({
|
|
19
|
+
* secret: 'your-secret-key',
|
|
20
|
+
* signOptions: { expiresIn: '1h' },
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* @Injectable()
|
|
24
|
+
* class AuthService {
|
|
25
|
+
* jwtService = inject(JwtService)
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
5
29
|
export declare function provideJwtService(config: JwtServiceOptions): BoundInjectionToken<JwtService, typeof JwtServiceOptionsSchema>;
|
|
30
|
+
/**
|
|
31
|
+
* Creates a JWT service provider with async configuration factory.
|
|
32
|
+
*
|
|
33
|
+
* Use this overload when you need to load configuration asynchronously, such as
|
|
34
|
+
* fetching secrets from a configuration service or environment variables.
|
|
35
|
+
*
|
|
36
|
+
* @param config - Async factory function that returns JWT service configuration
|
|
37
|
+
* @returns A factory injection token that resolves configuration asynchronously
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```ts
|
|
41
|
+
* // Async configuration
|
|
42
|
+
* const JwtService = provideJwtService(async () => {
|
|
43
|
+
* const configService = await inject(ConfigService)
|
|
44
|
+
* return {
|
|
45
|
+
* secret: configService.jwt.secret,
|
|
46
|
+
* signOptions: { expiresIn: configService.jwt.expiresIn },
|
|
47
|
+
* }
|
|
48
|
+
* })
|
|
49
|
+
*
|
|
50
|
+
* @Injectable()
|
|
51
|
+
* class AuthService {
|
|
52
|
+
* jwtService = inject(JwtService)
|
|
53
|
+
* }
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
6
56
|
export declare function provideJwtService(config: () => Promise<JwtServiceOptions>): FactoryInjectionToken<JwtService, typeof JwtServiceOptionsSchema>;
|
|
7
57
|
//# sourceMappingURL=jwt-service.provider.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt-service.provider.d.mts","sourceRoot":"","sources":["../../src/jwt-service.provider.mts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AAI9E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AAE1E,OAAO,EAAE,UAAU,EAAmB,MAAM,mBAAmB,CAAA;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAA;AAE3E,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,iBAAiB,GACxB,mBAAmB,CAAC,UAAU,EAAE,OAAO,uBAAuB,CAAC,CAAA;AAClE,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,OAAO,CAAC,iBAAiB,CAAC,GACvC,qBAAqB,CAAC,UAAU,EAAE,OAAO,uBAAuB,CAAC,CAAA"}
|
|
1
|
+
{"version":3,"file":"jwt-service.provider.d.mts","sourceRoot":"","sources":["../../src/jwt-service.provider.mts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AAI9E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAA;AAE1E,OAAO,EAAE,UAAU,EAAmB,MAAM,mBAAmB,CAAA;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAA;AAE3E;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,iBAAiB,GACxB,mBAAmB,CAAC,UAAU,EAAE,OAAO,uBAAuB,CAAC,CAAA;AAClE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,OAAO,CAAC,iBAAiB,CAAC,GACvC,qBAAqB,CAAC,UAAU,EAAE,OAAO,uBAAuB,CAAC,CAAA"}
|
|
@@ -2,6 +2,11 @@ import { InjectionToken } from '@navios/core';
|
|
|
2
2
|
import jwt from 'jsonwebtoken';
|
|
3
3
|
import type { JwtServiceOptions, JwtSignOptions, JwtVerifyOptions, SignOptions } from './options/jwt-service.options.mjs';
|
|
4
4
|
import { RequestType } from './options/jwt-service.options.mjs';
|
|
5
|
+
/**
|
|
6
|
+
* Injection token for JwtService.
|
|
7
|
+
*
|
|
8
|
+
* Used internally by the dependency injection system to register and resolve JwtService instances.
|
|
9
|
+
*/
|
|
5
10
|
export declare const JwtServiceToken: InjectionToken<unknown, import("zod/v4").ZodObject<{
|
|
6
11
|
signOptions: import("zod/v4").ZodOptional<import("zod/v4").ZodObject<{
|
|
7
12
|
algorithm: import("zod/v4").ZodOptional<import("zod/v4").ZodEnum<{
|
|
@@ -189,16 +194,181 @@ export declare const JwtServiceToken: InjectionToken<unknown, import("zod/v4").Z
|
|
|
189
194
|
passphrase: import("zod/v4").ZodString;
|
|
190
195
|
}, import("zod/v4/core").$strip>]>>]>>>;
|
|
191
196
|
}, import("zod/v4/core").$strip>, true>;
|
|
197
|
+
/**
|
|
198
|
+
* Service for signing, verifying, and decoding JSON Web Tokens (JWTs).
|
|
199
|
+
*
|
|
200
|
+
* This service provides a type-safe wrapper around the `jsonwebtoken` library with
|
|
201
|
+
* seamless integration into Navios's dependency injection system. It supports both
|
|
202
|
+
* symmetric (HS256, HS384, HS512) and asymmetric (RS256, ES256, etc.) algorithms.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* ```ts
|
|
206
|
+
* import { provideJwtService } from '@navios/jwt'
|
|
207
|
+
* import { inject } from '@navios/core'
|
|
208
|
+
*
|
|
209
|
+
* const JwtService = provideJwtService({
|
|
210
|
+
* secret: 'your-secret-key',
|
|
211
|
+
* signOptions: { expiresIn: '1h' },
|
|
212
|
+
* })
|
|
213
|
+
*
|
|
214
|
+
* @Injectable()
|
|
215
|
+
* class AuthService {
|
|
216
|
+
* jwtService = inject(JwtService)
|
|
217
|
+
*
|
|
218
|
+
* async login(userId: string) {
|
|
219
|
+
* const token = this.jwtService.sign({ userId, role: 'user' })
|
|
220
|
+
* return token
|
|
221
|
+
* }
|
|
222
|
+
* }
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
192
225
|
export declare class JwtService {
|
|
193
226
|
private readonly options;
|
|
194
227
|
logger: import("@navios/core").LoggerInstance;
|
|
228
|
+
/**
|
|
229
|
+
* Creates a new JwtService instance.
|
|
230
|
+
*
|
|
231
|
+
* @param options - Configuration options for the JWT service
|
|
232
|
+
*/
|
|
195
233
|
constructor(options?: JwtServiceOptions);
|
|
234
|
+
/**
|
|
235
|
+
* Signs a JWT payload synchronously.
|
|
236
|
+
*
|
|
237
|
+
* When the payload is a string, only `secret` and `privateKey` options are allowed.
|
|
238
|
+
* For object or Buffer payloads, all sign options are available.
|
|
239
|
+
*
|
|
240
|
+
* @param payload - The payload to sign. Can be a string, Buffer, or object.
|
|
241
|
+
* @param options - Signing options. When payload is a string, only `secret` and `privateKey` are allowed.
|
|
242
|
+
* @returns The signed JWT token as a string
|
|
243
|
+
* @throws {Error} If `secretOrKeyProvider` returns a Promise (use `signAsync` instead)
|
|
244
|
+
* @throws {Error} If payload is a string and invalid options are provided
|
|
245
|
+
*
|
|
246
|
+
* @example
|
|
247
|
+
* ```ts
|
|
248
|
+
* // Sign with object payload
|
|
249
|
+
* const token = jwtService.sign(
|
|
250
|
+
* { userId: '123', role: 'admin' },
|
|
251
|
+
* { expiresIn: '1h' }
|
|
252
|
+
* )
|
|
253
|
+
*
|
|
254
|
+
* // Sign with string payload (limited options)
|
|
255
|
+
* const token = jwtService.sign('payload-string', { secret: 'key' })
|
|
256
|
+
* ```
|
|
257
|
+
*/
|
|
196
258
|
sign(payload: string, options?: Omit<JwtSignOptions, keyof SignOptions>): string;
|
|
259
|
+
/**
|
|
260
|
+
* Signs a JWT payload synchronously.
|
|
261
|
+
*
|
|
262
|
+
* @param payload - The payload to sign. Can be a Buffer or object.
|
|
263
|
+
* @param options - Signing options including algorithm, expiration, etc.
|
|
264
|
+
* @returns The signed JWT token as a string
|
|
265
|
+
*/
|
|
197
266
|
sign(payload: Buffer | object, options?: JwtSignOptions): string;
|
|
267
|
+
/**
|
|
268
|
+
* Signs a JWT payload asynchronously.
|
|
269
|
+
*
|
|
270
|
+
* Use this method when `secretOrKeyProvider` returns a Promise or when you need
|
|
271
|
+
* to handle async key resolution. Supports the same payload types and options as `sign()`.
|
|
272
|
+
*
|
|
273
|
+
* @param payload - The payload to sign. Can be a string, Buffer, or object.
|
|
274
|
+
* @param options - Signing options. When payload is a string, only `secret` and `privateKey` are allowed.
|
|
275
|
+
* @returns A Promise that resolves to the signed JWT token as a string
|
|
276
|
+
* @throws {Error} If payload is a string and invalid options are provided
|
|
277
|
+
*
|
|
278
|
+
* @example
|
|
279
|
+
* ```ts
|
|
280
|
+
* // Sign with async key provider
|
|
281
|
+
* const token = await jwtService.signAsync(
|
|
282
|
+
* { userId: '123' },
|
|
283
|
+
* { expiresIn: '1h' }
|
|
284
|
+
* )
|
|
285
|
+
* ```
|
|
286
|
+
*/
|
|
198
287
|
signAsync(payload: string, options?: Omit<JwtSignOptions, keyof jwt.SignOptions>): Promise<string>;
|
|
288
|
+
/**
|
|
289
|
+
* Signs a JWT payload asynchronously.
|
|
290
|
+
*
|
|
291
|
+
* @param payload - The payload to sign. Can be a Buffer or object.
|
|
292
|
+
* @param options - Signing options including algorithm, expiration, etc.
|
|
293
|
+
* @returns A Promise that resolves to the signed JWT token as a string
|
|
294
|
+
*/
|
|
199
295
|
signAsync(payload: Buffer | object, options?: JwtSignOptions): Promise<string>;
|
|
296
|
+
/**
|
|
297
|
+
* Verifies and decodes a JWT token synchronously.
|
|
298
|
+
*
|
|
299
|
+
* This method validates the token's signature, expiration, and other claims
|
|
300
|
+
* according to the provided options. If verification fails, an error is thrown.
|
|
301
|
+
*
|
|
302
|
+
* @template T - The expected type of the decoded payload
|
|
303
|
+
* @param token - The JWT token string to verify
|
|
304
|
+
* @param options - Verification options including algorithms, audience, issuer, etc.
|
|
305
|
+
* @returns The decoded payload as type T
|
|
306
|
+
* @throws {TokenExpiredError} If the token has expired
|
|
307
|
+
* @throws {NotBeforeError} If the token is not yet valid (nbf claim)
|
|
308
|
+
* @throws {JsonWebTokenError} If the token is invalid or malformed
|
|
309
|
+
* @throws {Error} If `secretOrKeyProvider` returns a Promise (use `verifyAsync` instead)
|
|
310
|
+
*
|
|
311
|
+
* @example
|
|
312
|
+
* ```ts
|
|
313
|
+
* try {
|
|
314
|
+
* const payload = jwtService.verify<{ userId: string; role: string }>(token)
|
|
315
|
+
* console.log(payload.userId) // '123'
|
|
316
|
+
* } catch (error) {
|
|
317
|
+
* if (error instanceof TokenExpiredError) {
|
|
318
|
+
* console.error('Token expired')
|
|
319
|
+
* }
|
|
320
|
+
* }
|
|
321
|
+
* ```
|
|
322
|
+
*/
|
|
200
323
|
verify<T extends object = any>(token: string, options?: JwtVerifyOptions): T;
|
|
324
|
+
/**
|
|
325
|
+
* Verifies and decodes a JWT token asynchronously.
|
|
326
|
+
*
|
|
327
|
+
* Use this method when `secretOrKeyProvider` returns a Promise or when you need
|
|
328
|
+
* to handle async key resolution. Provides the same validation as `verify()`.
|
|
329
|
+
*
|
|
330
|
+
* @template T - The expected type of the decoded payload
|
|
331
|
+
* @param token - The JWT token string to verify
|
|
332
|
+
* @param options - Verification options including algorithms, audience, issuer, etc.
|
|
333
|
+
* @returns A Promise that resolves to the decoded payload as type T
|
|
334
|
+
* @throws {TokenExpiredError} If the token has expired
|
|
335
|
+
* @throws {NotBeforeError} If the token is not yet valid (nbf claim)
|
|
336
|
+
* @throws {JsonWebTokenError} If the token is invalid or malformed
|
|
337
|
+
*
|
|
338
|
+
* @example
|
|
339
|
+
* ```ts
|
|
340
|
+
* try {
|
|
341
|
+
* const payload = await jwtService.verifyAsync<{ userId: string }>(token)
|
|
342
|
+
* console.log(payload.userId)
|
|
343
|
+
* } catch (error) {
|
|
344
|
+
* if (error instanceof TokenExpiredError) {
|
|
345
|
+
* console.error('Token expired')
|
|
346
|
+
* }
|
|
347
|
+
* }
|
|
348
|
+
* ```
|
|
349
|
+
*/
|
|
201
350
|
verifyAsync<T extends object = any>(token: string, options?: JwtVerifyOptions): Promise<T>;
|
|
351
|
+
/**
|
|
352
|
+
* Decodes a JWT token without verification.
|
|
353
|
+
*
|
|
354
|
+
* This method decodes the token without validating its signature or claims.
|
|
355
|
+
* Use this only when you need to inspect the token contents without verification.
|
|
356
|
+
* For secure token validation, use `verify()` or `verifyAsync()` instead.
|
|
357
|
+
*
|
|
358
|
+
* @template T - The expected type of the decoded payload
|
|
359
|
+
* @param token - The JWT token string to decode
|
|
360
|
+
* @param options - Decode options (complete, json, etc.)
|
|
361
|
+
* @returns The decoded payload as type T, or null if decoding fails
|
|
362
|
+
*
|
|
363
|
+
* @example
|
|
364
|
+
* ```ts
|
|
365
|
+
* // Decode without verification (not recommended for production)
|
|
366
|
+
* const payload = jwtService.decode<{ userId: string }>(token)
|
|
367
|
+
* if (payload) {
|
|
368
|
+
* console.log(payload.userId)
|
|
369
|
+
* }
|
|
370
|
+
* ```
|
|
371
|
+
*/
|
|
202
372
|
decode<T = any>(token: string, options?: jwt.DecodeOptions): T;
|
|
203
373
|
private mergeJwtOptions;
|
|
204
374
|
private getSecretKey;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt.service.d.mts","sourceRoot":"","sources":["../../src/jwt.service.mts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,cAAc,EAAU,MAAM,cAAc,CAAA;AAEzE,OAAO,GAAG,MAAM,cAAc,CAAA;AAE9B,OAAO,KAAK,EAEV,iBAAiB,EACjB,cAAc,EACd,gBAAgB,EAChB,WAAW,EAEZ,MAAM,mCAAmC,CAAA;AAE1C,OAAO,EAEL,WAAW,EACZ,MAAM,mCAAmC,CAAA;AAE1C,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uCAG3B,CAAA;AAED,qBAGa,UAAU;
|
|
1
|
+
{"version":3,"file":"jwt.service.d.mts","sourceRoot":"","sources":["../../src/jwt.service.mts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,cAAc,EAAU,MAAM,cAAc,CAAA;AAEzE,OAAO,GAAG,MAAM,cAAc,CAAA;AAE9B,OAAO,KAAK,EAEV,iBAAiB,EACjB,cAAc,EACd,gBAAgB,EAChB,WAAW,EAEZ,MAAM,mCAAmC,CAAA;AAE1C,OAAO,EAEL,WAAW,EACZ,MAAM,mCAAmC,CAAA;AAE1C;;;;GAIG;AACH,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uCAG3B,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,qBAGa,UAAU;IAUT,OAAO,CAAC,QAAQ,CAAC,OAAO;IATpC,MAAM,wCAEJ;IAEF;;;;OAIG;gBAC0B,OAAO,GAAE,iBAAsB;IAE5D;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,IAAI,CACF,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,EAAE,MAAM,WAAW,CAAC,GAChD,MAAM;IACT;;;;;;OAMG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,MAAM;IAuChE;;;;;;;;;;;;;;;;;;;OAmBG;IACH,SAAS,CACP,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,IAAI,CAAC,cAAc,EAAE,MAAM,GAAG,CAAC,WAAW,CAAC,GACpD,OAAO,CAAC,MAAM,CAAC;IAClB;;;;;;OAMG;IACH,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAuC9E;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACH,MAAM,CAAC,CAAC,SAAS,MAAM,GAAG,GAAG,EAC3B,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,gBAAqB,GAC7B,CAAC;IAqBJ;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,WAAW,CAAC,CAAC,SAAS,MAAM,GAAG,GAAG,EAChC,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,CAAC,CAAC;IAsBb;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,MAAM,CAAC,CAAC,GAAG,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC,aAAa,GAAG,CAAC;IAI9D,OAAO,CAAC,eAAe;IAmBvB,OAAO,CAAC,YAAY;CAkBrB"}
|