Repository navigation
Expand file tree
/
Copy pathjwt-validator.ts
More file actions
198 lines (168 loc) · 6.38 KB
/
Copy pathjwt-validator.ts
File metadata and controls
198 lines (168 loc) · 6.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import jwt, { VerifyOptions } from 'jsonwebtoken';
import jwksClient, { JwksClient, SigningKey } from 'jwks-rsa';
import { logger } from '../../core/Logger.js';
export interface TokenClaims {
sub: string;
iss: string;
aud: string | string[];
exp: number;
nbf?: number;
iat?: number;
scope?: string;
[key: string]: unknown;
}
export interface JWTValidationConfig {
jwksUri: string;
audience: string;
issuer: string;
algorithms?: string[];
cacheTTL?: number;
rateLimit?: boolean;
cacheMaxEntries?: number;
}
export class JWTValidator {
private jwksClient: JwksClient;
private config: Required<JWTValidationConfig>;
constructor(config: JWTValidationConfig) {
this.config = {
algorithms: config.algorithms || ['RS256', 'ES256'],
cacheTTL: config.cacheTTL || 900000,
rateLimit: config.rateLimit ?? true,
cacheMaxEntries: config.cacheMaxEntries || 5,
...config,
};
this.jwksClient = jwksClient({
jwksUri: this.config.jwksUri,
cache: true,
cacheMaxEntries: this.config.cacheMaxEntries,
cacheMaxAge: this.config.cacheTTL,
rateLimit: this.config.rateLimit,
jwksRequestsPerMinute: this.config.rateLimit ? 10 : undefined,
});
logger.debug(
`JWTValidator initialized with JWKS URI: ${this.config.jwksUri}, audience: ${this.config.audience}`
);
}
async validate(token: string): Promise<TokenClaims> {
try {
logger.debug('Starting JWT validation');
const decoded = jwt.decode(token, { complete: true });
if (!decoded || typeof decoded === 'string') {
throw new Error('Invalid token format: unable to decode');
}
logger.debug(`Token decoded, kid: ${decoded.header.kid}, alg: ${decoded.header.alg}`);
if (!decoded.header.kid) {
throw new Error('Invalid token: missing kid in header');
}
if (!this.config.algorithms.includes(decoded.header.alg)) {
throw new Error(
`Invalid token algorithm: ${decoded.header.alg}. Expected one of: ${this.config.algorithms.join(', ')}`
);
}
const key = await this.getSigningKey(decoded.header.kid);
logger.debug('Verifying token signature and claims');
const verified = await this.verifyToken(token, key);
logger.debug('JWT validation successful');
return verified;
} catch (error) {
if (error instanceof Error) {
logger.error(`JWT validation failed: ${error.message}`);
throw error;
}
throw new Error('JWT validation failed: Unknown error');
}
}
private async getSigningKey(kid: string): Promise<string> {
try {
logger.debug(`Fetching signing key for kid: ${kid}`);
const key: SigningKey = await this.jwksClient.getSigningKey(kid);
const publicKey = key.getPublicKey();
logger.debug('Signing key retrieved successfully');
return publicKey;
} catch (error) {
if (error instanceof Error) {
logger.error(`Failed to fetch signing key: ${error.message}`);
throw new Error(`Failed to fetch signing key: ${error.message}`);
}
throw new Error('Failed to fetch signing key: Unknown error');
}
}
private async verifyToken(token: string, publicKey: string): Promise<TokenClaims> {
return new Promise((resolve, reject) => {
const options: VerifyOptions = {
algorithms: this.config.algorithms as jwt.Algorithm[],
issuer: this.config.issuer,
complete: false,
};
// Only validate audience if not set to wildcard
// For Cognito Access Tokens, 'aud' is missing but 'client_id' is present.
// We disable the library's strict check and handle it manually in the callback.
// if (this.config.audience !== '*') {
// options.audience = this.config.audience;
// }
jwt.verify(token, publicKey, options, (err, decoded) => {
if (err) {
if (err.name === 'TokenExpiredError') {
logger.warn('Token has expired');
reject(new Error('Token has expired'));
} else if (err.name === 'JsonWebTokenError') {
logger.warn(`Token verification failed: ${err.message}`);
reject(new Error(`Token verification failed: ${err.message}`));
} else if (err.name === 'NotBeforeError') {
logger.warn('Token not yet valid (nbf claim)');
reject(new Error('Token not yet valid'));
} else {
logger.error(`Token verification error: ${err.message}`);
reject(new Error(`Token verification error: ${err.message}`));
}
return;
}
if (!decoded || typeof decoded === 'string') {
reject(new Error('Invalid token payload'));
return;
}
const claims = decoded as TokenClaims;
if (!claims.sub) {
reject(new Error('Token missing required claim: sub'));
return;
}
if (!claims.iss) {
reject(new Error('Token missing required claim: iss'));
return;
}
// Only require aud/client_id claim if not set to wildcard
if (this.config.audience !== '*') {
const aud = claims.aud;
const clientId = claims.client_id as string | undefined;
const expectedAudience = this.config.audience;
let isValidAudience = false;
// Check 'aud' claim (ID Tokens)
if (aud) {
if (Array.isArray(aud)) {
if (aud.includes(expectedAudience)) isValidAudience = true;
} else {
if (aud === expectedAudience) isValidAudience = true;
}
}
// Check 'client_id' claim (Access Tokens)
if (!isValidAudience && clientId) {
if (clientId === expectedAudience) isValidAudience = true;
}
if (!isValidAudience) {
reject(new Error(`Token audience mismatch. Expected ${expectedAudience}, got aud: ${aud}, client_id: ${clientId}`));
return;
}
}
if (!claims.exp) {
reject(new Error('Token missing required claim: exp'));
return;
}
const audInfo = claims.aud
? `aud: ${Array.isArray(claims.aud) ? claims.aud.join(', ') : claims.aud}`
: 'aud: <not present - wildcard mode>';
logger.debug(`Token claims validated - sub: ${claims.sub}, iss: ${claims.iss}, ${audInfo}`);
resolve(claims);
});
});
}
}