@yuva-devlab/auth-server 0.2.0 → 0.3.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/dist/index.cjs +215 -62
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +77 -36
- package/dist/index.d.ts +77 -36
- package/dist/index.js +210 -63
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
1
2
|
import { UnauthorizedError, ForbiddenError } from '@yuva-devlab/errors';
|
|
2
3
|
import { loggerWithConfig, Logger } from '@yuva-devlab/logger';
|
|
3
4
|
|
|
@@ -6,6 +7,7 @@ var DEFAULT_AUTH_HEADER = "authorization";
|
|
|
6
7
|
var DEFAULT_API_KEY_HEADER = "x-api-key";
|
|
7
8
|
var DEFAULT_BEARER_PREFIX = "Bearer ";
|
|
8
9
|
var DEFAULT_JWKS_CACHE_TTL_MS = 36e5;
|
|
10
|
+
var DEFAULT_API_KEY_CACHE_TTL_MS = 3e5;
|
|
9
11
|
var DEFAULT_PUBLIC_PATHS = Object.freeze([
|
|
10
12
|
"/health",
|
|
11
13
|
"/ready",
|
|
@@ -30,32 +32,19 @@ var JwksValidator = class {
|
|
|
30
32
|
issuer;
|
|
31
33
|
cacheTtlMs;
|
|
32
34
|
keyCache = /* @__PURE__ */ new Map();
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
* @param config - JWKS configuration parameters
|
|
37
|
-
*/
|
|
38
|
-
constructor(config) {
|
|
39
|
-
this.jwksUri = config.jwksUri;
|
|
35
|
+
jwksSetCache = null;
|
|
36
|
+
constructor(config = {}) {
|
|
37
|
+
this.jwksUri = config.jwksUri ?? (config.issuer ? `${config.issuer}/.well-known/jwks.json` : void 0) ?? (typeof process !== "undefined" ? process.env?.DEVLAB_JWKS_URI ?? (process.env?.DEVLAB_AUTH_URL ? `${process.env.DEVLAB_AUTH_URL}/.well-known/jwks.json` : void 0) : void 0) ?? "";
|
|
40
38
|
this.audience = config.audience;
|
|
41
39
|
this.issuer = config.issuer;
|
|
42
40
|
this.cacheTtlMs = config.cacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;
|
|
43
|
-
logger.debug("[constructor] JwksValidator initialized", {
|
|
44
|
-
jwksUri: this.jwksUri,
|
|
45
|
-
issuer: this.issuer,
|
|
46
|
-
audience: this.audience
|
|
47
|
-
});
|
|
48
41
|
}
|
|
49
|
-
/**
|
|
50
|
-
* Decodes a JWT token without verifying cryptographic signature.
|
|
51
|
-
*
|
|
52
|
-
* @param token - Base64Url encoded JWT string
|
|
53
|
-
* @returns Header and payload objects
|
|
54
|
-
*/
|
|
55
42
|
parseUnverified(token) {
|
|
56
43
|
const parts = token.split(".");
|
|
57
44
|
if (parts.length !== 3) {
|
|
58
|
-
throw new UnauthorizedError(
|
|
45
|
+
throw new UnauthorizedError(
|
|
46
|
+
"Malformed JWT token format: expected 3 segments"
|
|
47
|
+
);
|
|
59
48
|
}
|
|
60
49
|
try {
|
|
61
50
|
const header = JSON.parse(
|
|
@@ -64,68 +53,226 @@ var JwksValidator = class {
|
|
|
64
53
|
const payload = JSON.parse(
|
|
65
54
|
Buffer.from(parts[1], "base64url").toString("utf-8")
|
|
66
55
|
);
|
|
67
|
-
return {
|
|
56
|
+
return {
|
|
57
|
+
header,
|
|
58
|
+
payload,
|
|
59
|
+
rawHeader: parts[0],
|
|
60
|
+
rawPayload: parts[1],
|
|
61
|
+
signature: parts[2]
|
|
62
|
+
};
|
|
68
63
|
} catch {
|
|
69
|
-
throw new UnauthorizedError("Unable to decode JWT payload");
|
|
64
|
+
throw new UnauthorizedError("Unable to decode JWT header or payload");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async fetchJwks() {
|
|
68
|
+
if (!this.jwksUri) {
|
|
69
|
+
throw new UnauthorizedError(
|
|
70
|
+
"JwksValidator: jwksUri, issuer, or DEVLAB_AUTH_URL must be configured"
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
const now = Date.now();
|
|
74
|
+
if (this.jwksSetCache && this.jwksSetCache.expiresAt > now) {
|
|
75
|
+
return this.jwksSetCache.keys;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
const res = await fetch(this.jwksUri, {
|
|
79
|
+
headers: { Accept: "application/json" },
|
|
80
|
+
signal: AbortSignal.timeout(5e3)
|
|
81
|
+
});
|
|
82
|
+
if (!res.ok) {
|
|
83
|
+
throw new Error(`JWKS endpoint returned HTTP ${res.status}`);
|
|
84
|
+
}
|
|
85
|
+
const body = await res.json();
|
|
86
|
+
const keys = body.keys ?? [];
|
|
87
|
+
this.jwksSetCache = { keys, expiresAt: now + this.cacheTtlMs };
|
|
88
|
+
return keys;
|
|
89
|
+
} catch (err) {
|
|
90
|
+
logger.error("[fetchJwks] Failed to fetch JWKS public keys", {
|
|
91
|
+
uri: this.jwksUri,
|
|
92
|
+
err
|
|
93
|
+
});
|
|
94
|
+
if (this.jwksSetCache?.keys) return this.jwksSetCache.keys;
|
|
95
|
+
throw new UnauthorizedError("Authentication service JWKS unreachable");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async resolveKeyObject(kid) {
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
const cacheKey = kid ?? "__default__";
|
|
101
|
+
const cached = this.keyCache.get(cacheKey);
|
|
102
|
+
if (cached && cached.expiresAt > now) {
|
|
103
|
+
return cached.keyObject;
|
|
104
|
+
}
|
|
105
|
+
const jwks = await this.fetchJwks();
|
|
106
|
+
const matched = kid ? jwks.find((k) => k.kid === kid) : jwks[0];
|
|
107
|
+
if (!matched) {
|
|
108
|
+
throw new UnauthorizedError(
|
|
109
|
+
`No matching JWK public key found for kid: ${kid ?? "default"}`
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
const keyObject = crypto.createPublicKey({
|
|
114
|
+
key: matched,
|
|
115
|
+
format: "jwk"
|
|
116
|
+
});
|
|
117
|
+
this.keyCache.set(cacheKey, {
|
|
118
|
+
keyObject,
|
|
119
|
+
expiresAt: now + this.cacheTtlMs
|
|
120
|
+
});
|
|
121
|
+
return keyObject;
|
|
122
|
+
} catch (err) {
|
|
123
|
+
logger.error("[resolveKeyObject] Failed to parse JWK public key", {
|
|
124
|
+
kid,
|
|
125
|
+
err
|
|
126
|
+
});
|
|
127
|
+
throw new UnauthorizedError("Invalid JWK public key format");
|
|
70
128
|
}
|
|
71
129
|
}
|
|
72
|
-
/**
|
|
73
|
-
* Verifies standard claims (exp, nbf, iss, aud) on a JWT token.
|
|
74
|
-
*
|
|
75
|
-
* @param token - Bearer access token
|
|
76
|
-
* @returns Validated JwtPayload claims
|
|
77
|
-
*/
|
|
78
130
|
async verifyToken(token) {
|
|
79
|
-
const { payload } = this.parseUnverified(token);
|
|
131
|
+
const { header, payload, rawHeader, rawPayload, signature } = this.parseUnverified(token);
|
|
132
|
+
if (header.alg && header.alg !== "RS256") {
|
|
133
|
+
throw new UnauthorizedError(
|
|
134
|
+
`Unsupported signing algorithm: ${header.alg}. Expected RS256`
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
const kid = typeof header.kid === "string" ? header.kid : void 0;
|
|
138
|
+
const keyObject = await this.resolveKeyObject(kid);
|
|
139
|
+
const data = Buffer.from(`${rawHeader}.${rawPayload}`);
|
|
140
|
+
const sigBuffer = Buffer.from(signature, "base64url");
|
|
141
|
+
const isSignatureValid = crypto.verify(
|
|
142
|
+
"RSA-SHA256",
|
|
143
|
+
data,
|
|
144
|
+
keyObject,
|
|
145
|
+
sigBuffer
|
|
146
|
+
);
|
|
147
|
+
if (!isSignatureValid) {
|
|
148
|
+
logger.warn("[verifyToken] Cryptographic signature check failed", {
|
|
149
|
+
sub: payload.sub,
|
|
150
|
+
kid
|
|
151
|
+
});
|
|
152
|
+
throw new UnauthorizedError("Invalid token signature");
|
|
153
|
+
}
|
|
80
154
|
const nowSeconds = Math.floor(Date.now() / 1e3);
|
|
81
155
|
if (typeof payload.exp === "number" && nowSeconds >= payload.exp) {
|
|
82
|
-
logger.warn("[verifyToken] Token has expired", {
|
|
83
|
-
exp: payload.exp,
|
|
84
|
-
now: nowSeconds
|
|
85
|
-
});
|
|
86
156
|
throw new UnauthorizedError("Authentication token has expired");
|
|
87
157
|
}
|
|
88
158
|
if (typeof payload.nbf === "number" && nowSeconds < payload.nbf) {
|
|
89
|
-
logger.warn("[verifyToken] Token not yet valid", {
|
|
90
|
-
nbf: payload.nbf,
|
|
91
|
-
now: nowSeconds
|
|
92
|
-
});
|
|
93
159
|
throw new UnauthorizedError("Authentication token is not yet active");
|
|
94
160
|
}
|
|
95
161
|
if (this.issuer && payload.iss && payload.iss !== this.issuer) {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
});
|
|
100
|
-
throw new UnauthorizedError("Token issuer mismatch");
|
|
162
|
+
throw new UnauthorizedError(
|
|
163
|
+
`Token issuer mismatch: expected ${this.issuer}, got ${payload.iss}`
|
|
164
|
+
);
|
|
101
165
|
}
|
|
102
166
|
if (this.audience && payload.aud) {
|
|
103
167
|
const audList = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
104
168
|
if (!audList.includes(this.audience)) {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
});
|
|
109
|
-
throw new UnauthorizedError("Token audience mismatch");
|
|
169
|
+
throw new UnauthorizedError(
|
|
170
|
+
`Token audience mismatch: expected ${this.audience}`
|
|
171
|
+
);
|
|
110
172
|
}
|
|
111
173
|
}
|
|
112
|
-
logger.debug("[verifyToken] Successfully validated token claims", {
|
|
113
|
-
sub: payload.sub
|
|
114
|
-
});
|
|
115
174
|
return payload;
|
|
116
175
|
}
|
|
117
|
-
/**
|
|
118
|
-
* Clears cached public keys from memory.
|
|
119
|
-
*/
|
|
120
176
|
clearKeyCache() {
|
|
121
177
|
this.keyCache.clear();
|
|
178
|
+
this.jwksSetCache = null;
|
|
122
179
|
logger.info("[clearKeyCache] JWKS public key cache cleared");
|
|
123
180
|
}
|
|
124
181
|
};
|
|
125
|
-
var logger2 = loggerWithConfig(new Logger("
|
|
182
|
+
var logger2 = loggerWithConfig(new Logger("M2mApiKeyValidator"));
|
|
183
|
+
var M2mApiKeyValidator = class {
|
|
184
|
+
authUrl;
|
|
185
|
+
cacheTtlMs;
|
|
186
|
+
requiredClientId;
|
|
187
|
+
requiredScopes;
|
|
188
|
+
keyCache = /* @__PURE__ */ new Map();
|
|
189
|
+
constructor(config = {}) {
|
|
190
|
+
this.authUrl = config.authUrl ?? config.portalUrl ?? process.env.DEVLAB_AUTH_URL ?? process.env.DEVLAB_PORTAL_URL;
|
|
191
|
+
this.cacheTtlMs = config.cacheTtlMs ?? DEFAULT_API_KEY_CACHE_TTL_MS;
|
|
192
|
+
this.requiredClientId = config.requiredClientId ?? config.requiredAppId;
|
|
193
|
+
this.requiredScopes = config.requiredScopes;
|
|
194
|
+
}
|
|
195
|
+
async validateKey(rawKey) {
|
|
196
|
+
const trimmed = rawKey.trim();
|
|
197
|
+
if (!trimmed.startsWith("dlk_")) {
|
|
198
|
+
throw new UnauthorizedError("Malformed API key: expected 'dlk_' prefix");
|
|
199
|
+
}
|
|
200
|
+
if (!this.authUrl) {
|
|
201
|
+
throw new UnauthorizedError(
|
|
202
|
+
"M2mApiKeyValidator: authUrl or DEVLAB_AUTH_URL must be configured for validation"
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
const now = Date.now();
|
|
206
|
+
const cached = this.keyCache.get(trimmed);
|
|
207
|
+
if (cached && cached.expiresAt > now) {
|
|
208
|
+
return this.enforceKeyConstraints(cached.result);
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
const url = `${this.authUrl}/api/v1/api-keys/validate`;
|
|
212
|
+
const res = await fetch(url, {
|
|
213
|
+
headers: {
|
|
214
|
+
Accept: "application/json",
|
|
215
|
+
Authorization: `Bearer ${trimmed}`
|
|
216
|
+
},
|
|
217
|
+
signal: AbortSignal.timeout(5e3)
|
|
218
|
+
});
|
|
219
|
+
if (!res.ok) {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`Authentication validation endpoint returned HTTP ${res.status}`
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
const body = await res.json();
|
|
225
|
+
if (!body.valid) {
|
|
226
|
+
throw new UnauthorizedError(body.reason ?? "Invalid machine API key");
|
|
227
|
+
}
|
|
228
|
+
this.keyCache.set(trimmed, {
|
|
229
|
+
result: body,
|
|
230
|
+
expiresAt: now + this.cacheTtlMs
|
|
231
|
+
});
|
|
232
|
+
return this.enforceKeyConstraints(body);
|
|
233
|
+
} catch (err) {
|
|
234
|
+
if (err instanceof UnauthorizedError || err instanceof ForbiddenError) {
|
|
235
|
+
throw err;
|
|
236
|
+
}
|
|
237
|
+
logger2.error("[validateKey] Network error during API key introspection", {
|
|
238
|
+
err
|
|
239
|
+
});
|
|
240
|
+
throw new UnauthorizedError(
|
|
241
|
+
"Authentication service unreachable for API key verification"
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
enforceKeyConstraints(result) {
|
|
246
|
+
if (this.requiredClientId && result.appId && result.appId !== this.requiredClientId) {
|
|
247
|
+
throw new ForbiddenError(
|
|
248
|
+
"API key assigned to " + result.appId + ", required " + this.requiredClientId
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
if (this.requiredScopes && this.requiredScopes.length > 0) {
|
|
252
|
+
const keyScopes = result.scopes ?? [];
|
|
253
|
+
const hasWildcard = keyScopes.includes("*");
|
|
254
|
+
if (!hasWildcard) {
|
|
255
|
+
const hasAll = this.requiredScopes.every(
|
|
256
|
+
(scope) => keyScopes.includes(scope)
|
|
257
|
+
);
|
|
258
|
+
if (!hasAll) {
|
|
259
|
+
throw new ForbiddenError(
|
|
260
|
+
"API key lacks required scopes: [" + this.requiredScopes.join(", ") + "]"
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return result;
|
|
266
|
+
}
|
|
267
|
+
clearCache() {
|
|
268
|
+
this.keyCache.clear();
|
|
269
|
+
logger2.info("[clearCache] API key validation cache cleared");
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
var logger3 = loggerWithConfig(new Logger("AuthGuards"));
|
|
126
273
|
function requireUser(ctx, requiredRoles) {
|
|
127
274
|
if (!ctx.authenticated || !ctx.user) {
|
|
128
|
-
|
|
275
|
+
logger3.warn(
|
|
129
276
|
"[requireUser] Request rejected: missing authenticated user context"
|
|
130
277
|
);
|
|
131
278
|
throw new UnauthorizedError(
|
|
@@ -135,7 +282,7 @@ function requireUser(ctx, requiredRoles) {
|
|
|
135
282
|
if (requiredRoles && requiredRoles.length > 0) {
|
|
136
283
|
const hasRole = requiredRoles.some((role) => ctx.roles.includes(role));
|
|
137
284
|
if (!hasRole) {
|
|
138
|
-
|
|
285
|
+
logger3.warn("[requireUser] User lacks required roles", {
|
|
139
286
|
userId: ctx.user.id,
|
|
140
287
|
userRoles: ctx.roles,
|
|
141
288
|
requiredRoles
|
|
@@ -149,7 +296,7 @@ function requireUser(ctx, requiredRoles) {
|
|
|
149
296
|
}
|
|
150
297
|
function requireApiKey(ctx) {
|
|
151
298
|
if (!ctx.authenticated || !ctx.apiKey) {
|
|
152
|
-
|
|
299
|
+
logger3.warn("[requireApiKey] Request rejected: missing machine API key");
|
|
153
300
|
throw new UnauthorizedError(
|
|
154
301
|
"Authentication required: valid API key required"
|
|
155
302
|
);
|
|
@@ -158,19 +305,19 @@ function requireApiKey(ctx) {
|
|
|
158
305
|
}
|
|
159
306
|
function requireScope(ctx, scope) {
|
|
160
307
|
if (!ctx.roles.includes(scope)) {
|
|
161
|
-
|
|
308
|
+
logger3.warn("[requireScope] Missing required scope", {
|
|
162
309
|
roles: ctx.roles,
|
|
163
310
|
requiredScope: scope
|
|
164
311
|
});
|
|
165
312
|
throw new ForbiddenError(`Missing required scope: '${scope}'`);
|
|
166
313
|
}
|
|
167
314
|
}
|
|
168
|
-
var
|
|
315
|
+
var logger4 = loggerWithConfig(new Logger("AuthMiddleware"));
|
|
169
316
|
function createAppKillSwitchMiddleware(getAppStatus) {
|
|
170
317
|
return async (req, res) => {
|
|
171
318
|
const status = await getAppStatus();
|
|
172
319
|
if (status === "INACTIVE" /* INACTIVE */ || status === "MAINTENANCE" /* MAINTENANCE */) {
|
|
173
|
-
|
|
320
|
+
logger4.warn(
|
|
174
321
|
"[killSwitch] Application is inactive or under maintenance; request rejected",
|
|
175
322
|
{
|
|
176
323
|
url: req.url,
|
|
@@ -214,7 +361,7 @@ function createAuthMiddleware(options) {
|
|
|
214
361
|
if (apiKey && options.validateApiKey) {
|
|
215
362
|
const apiKeyCtx = await options.validateApiKey(apiKey);
|
|
216
363
|
if (apiKeyCtx?.authenticated) {
|
|
217
|
-
|
|
364
|
+
logger4.info("[authenticate] Authenticated via API Key", {
|
|
218
365
|
path: urlPath
|
|
219
366
|
});
|
|
220
367
|
req.authContext = apiKeyCtx;
|
|
@@ -227,14 +374,14 @@ function createAuthMiddleware(options) {
|
|
|
227
374
|
const token = authHeader.slice(DEFAULT_BEARER_PREFIX.length).trim();
|
|
228
375
|
const tokenCtx = await options.validateToken(token);
|
|
229
376
|
if (tokenCtx?.authenticated) {
|
|
230
|
-
|
|
377
|
+
logger4.info("[authenticate] Authenticated via Bearer token", {
|
|
231
378
|
path: urlPath
|
|
232
379
|
});
|
|
233
380
|
req.authContext = tokenCtx;
|
|
234
381
|
return true;
|
|
235
382
|
}
|
|
236
383
|
}
|
|
237
|
-
|
|
384
|
+
logger4.warn("[authenticate] Unauthorized request rejected", {
|
|
238
385
|
path: urlPath,
|
|
239
386
|
method: req.method
|
|
240
387
|
});
|
|
@@ -252,6 +399,6 @@ function createAuthMiddleware(options) {
|
|
|
252
399
|
};
|
|
253
400
|
}
|
|
254
401
|
|
|
255
|
-
export { AppStatus, DEFAULT_API_KEY_HEADER, DEFAULT_AUTH_HEADER, DEFAULT_BEARER_PREFIX, DEFAULT_JWKS_CACHE_TTL_MS, DEFAULT_PUBLIC_PATHS, HTTP_STATUS_FORBIDDEN, HTTP_STATUS_SERVICE_UNAVAILABLE, HTTP_STATUS_UNAUTHORIZED, JwksValidator, createAppKillSwitchMiddleware, createAuthMiddleware, requireApiKey, requireScope, requireUser };
|
|
402
|
+
export { AppStatus, DEFAULT_API_KEY_CACHE_TTL_MS, DEFAULT_API_KEY_HEADER, DEFAULT_AUTH_HEADER, DEFAULT_BEARER_PREFIX, DEFAULT_JWKS_CACHE_TTL_MS, DEFAULT_PUBLIC_PATHS, HTTP_STATUS_FORBIDDEN, HTTP_STATUS_SERVICE_UNAVAILABLE, HTTP_STATUS_UNAUTHORIZED, JwksValidator, M2mApiKeyValidator, createAppKillSwitchMiddleware, createAuthMiddleware, requireApiKey, requireScope, requireUser };
|
|
256
403
|
//# sourceMappingURL=index.js.map
|
|
257
404
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/constants/auth.constants.ts","../src/types/auth.types.ts","../src/token/jwt-validator.ts","../src/guards/auth-guards.ts","../src/middleware/auth-middleware.ts"],"names":["AppStatus","logger","loggerWithConfig","Logger","UnauthorizedError"],"mappings":";;;;AAOO,IAAM,mBAAA,GAAsB;AAG5B,IAAM,sBAAA,GAAyB;AAG/B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,yBAAA,GAA4B;AAGlC,IAAM,oBAAA,GAAuB,OAAO,MAAA,CAAO;AAAA,EAChD,SAAA;AAAA,EACA,QAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAC;AAGM,IAAM,wBAAA,GAA2B;AAGjC,IAAM,qBAAA,GAAwB;AAG9B,IAAM,+BAAA,GAAkC;;;ACxBxC,IAAK,SAAA,qBAAAA,UAAAA,KAAL;AAEL,EAAAA,WAAA,QAAA,CAAA,GAAS,QAAA;AAET,EAAAA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UAAA,GAAa,wBAAA;AACjB,IAAA,GAAA,CAAI,SAAA,CAAU,gBAAgB,kBAAkB,CAAA;AAChD,IAAA,GAAA,CAAI,GAAA;AAAA,MACF,KAAK,SAAA,CAAU;AAAA,QACb,KAAA,EAAO;AAAA,UACL,IAAA,EAAM,cAAA;AAAA,UACN,OAAA,EACE;AAAA;AACJ,OACD;AAAA,KACH;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * @file packages/auth-server/src/constants/auth.constants.ts\n * @description Centralized constants and header keys for server-side authentication.\n * @module @yuva-devlab/auth-server\n */\n\n/** Standard Authorization HTTP header name (lowercase for case-insensitive lookup) */\nexport const DEFAULT_AUTH_HEADER = \"authorization\";\n\n/** Standard machine-to-machine API key HTTP header name */\nexport const DEFAULT_API_KEY_HEADER = \"x-api-key\";\n\n/** Standard Bearer token prefix */\nexport const DEFAULT_BEARER_PREFIX = \"Bearer \";\n\n/** Default cache time-to-live for fetched RS256 JWKS public keys (1 hour) */\nexport const DEFAULT_JWKS_CACHE_TTL_MS = 3_600_000;\n\n/** Default public endpoints bypassing mandatory authentication */\nexport const DEFAULT_PUBLIC_PATHS = Object.freeze([\n \"/health\",\n \"/ready\",\n \"/live\",\n \"/metrics\",\n]);\n\n/** HTTP Status Code for unauthenticated requests */\nexport const HTTP_STATUS_UNAUTHORIZED = 401;\n\n/** HTTP Status Code for unauthorized / forbidden role requests */\nexport const HTTP_STATUS_FORBIDDEN = 403;\n\n/** HTTP Status Code returned when an application is deactivated or killed */\nexport const HTTP_STATUS_SERVICE_UNAVAILABLE = 503;\n","/**\n * @file packages/auth-server/src/types/auth.types.ts\n * @description Type definitions and contracts for server authentication, JWKS, and app lifecycle.\n * @module @yuva-devlab/auth-server\n */\n\n/**\n * Operational state of an application on the DevLab platform.\n */\nexport enum AppStatus {\n /** Application is fully operational and serving traffic */\n ACTIVE = \"ACTIVE\",\n /** Application has been administratively disabled / deactivated (Kill-Switch triggered) */\n INACTIVE = \"INACTIVE\",\n /** Application is undergoing scheduled maintenance */\n MAINTENANCE = \"MAINTENANCE\",\n}\n\n/**\n * Authenticated user profile representation.\n */\nexport interface AuthUser {\n /** Canonical user UUID */\n readonly id: string;\n /** Primary user email address */\n readonly email?: string;\n /** Granted role slugs */\n readonly roles: readonly string[];\n /** Tenant isolation partition ID */\n readonly tenantId?: string;\n /** Arbitrary profile metadata */\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Machine-to-machine API key credential.\n */\nexport interface ApiKey {\n /** Primary API key UUID */\n readonly id: string;\n /** Secure key string */\n readonly key: string;\n /** Human-readable key name or description */\n readonly name: string;\n /** Scoped roles granted to this key */\n readonly roles: readonly string[];\n /** Tenant ID partition */\n readonly tenantId?: string;\n /** Active status flag */\n readonly isEnabled: boolean;\n}\n\n/**\n * Evaluated authentication context attached to inbound requests.\n */\nexport interface AuthContext {\n /** Whether the request carries valid credentials */\n readonly authenticated: boolean;\n /** Authenticated user if authenticated via session/JWT */\n readonly user?: AuthUser;\n /** Authenticated API key if authenticated via machine credential */\n readonly apiKey?: ApiKey;\n /** Consolidated roles granted across user or API key */\n readonly roles: readonly string[];\n /** Whether the host application is currently active on the platform */\n readonly isAppActive: boolean;\n /** Detailed app status */\n readonly appStatus?: AppStatus;\n /** Tenant partition ID */\n readonly tenantId?: string;\n /** Distributed trace request identifier */\n readonly requestId?: string;\n}\n\n/**\n * Configuration for verifying RS256 JWTs against a remote JWKS endpoint.\n */\nexport interface JwksConfig {\n /** JWKS endpoint URI exposing JSON Web Keys */\n readonly jwksUri: string;\n /** Expected audience claim */\n readonly audience?: string;\n /** Expected issuer claim */\n readonly issuer?: string;\n /** In-memory cache duration for public keys in milliseconds */\n readonly cacheTtlMs?: number;\n}\n\n/**\n * Decoded JWT claims payload.\n */\nexport interface JwtPayload {\n readonly sub: string;\n readonly iss?: string;\n readonly aud?: string | readonly string[];\n readonly exp?: number;\n readonly nbf?: number;\n readonly iat?: number;\n readonly email?: string;\n readonly roles?: readonly string[];\n readonly tenantId?: string;\n readonly [key: string]: unknown;\n}\n","/**\n * @file packages/auth-server/src/token/jwt-validator.ts\n * @description In-memory cached RS256 JWKS validator for authenticating JWT session tokens.\n * @module @yuva-devlab/auth-server\n */\n\nimport { UnauthorizedError } from \"@yuva-devlab/errors\";\nimport { Logger, loggerWithConfig } from \"@yuva-devlab/logger\";\nimport { DEFAULT_JWKS_CACHE_TTL_MS } from \"../constants\";\nimport type { JwksConfig, JwtPayload } from \"../types\";\n\nconst logger = loggerWithConfig(new Logger(\"JwksValidator\"));\n\n/**\n * Validates JWT access tokens against an in-memory cached JWKS public key set.\n *\n * @example\n * ```typescript\n * import { JwksValidator } from \"@yuva-devlab/auth-server\";\n *\n * const validator = new JwksValidator({\n * jwksUri: \"https://auth.devlab.io/.well-known/jwks.json\",\n * issuer: \"https://auth.devlab.io\",\n * audience: \"api.devlab.io\",\n * });\n *\n * const claims = await validator.verifyToken(token);\n * ```\n */\nexport class JwksValidator {\n private readonly jwksUri: string;\n private readonly audience?: string;\n private readonly issuer?: string;\n private readonly cacheTtlMs: number;\n private keyCache = new Map<string, { key: string; expiresAt: number }>();\n\n /**\n * Initializes the JWKS validator.\n *\n * @param config - JWKS configuration parameters\n */\n public constructor(config: JwksConfig) {\n this.jwksUri = config.jwksUri;\n this.audience = config.audience;\n this.issuer = config.issuer;\n this.cacheTtlMs = config.cacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;\n\n logger.debug(\"[constructor] JwksValidator initialized\", {\n jwksUri: this.jwksUri,\n issuer: this.issuer,\n audience: this.audience,\n });\n }\n\n /**\n * Decodes a JWT token without verifying cryptographic signature.\n *\n * @param token - Base64Url encoded JWT string\n * @returns Header and payload objects\n */\n public parseUnverified(token: string): {\n header: Record<string, unknown>;\n payload: JwtPayload;\n } {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n throw new UnauthorizedError(\"Malformed JWT token format\");\n }\n\n try {\n const header = JSON.parse(\n Buffer.from(parts[0]!, \"base64url\").toString(\"utf-8\"),\n ) as Record<string, unknown>;\n const payload = JSON.parse(\n Buffer.from(parts[1]!, \"base64url\").toString(\"utf-8\"),\n ) as JwtPayload;\n\n return { header, payload };\n } catch {\n throw new UnauthorizedError(\"Unable to decode JWT payload\");\n }\n }\n\n /**\n * Verifies standard claims (exp, nbf, iss, aud) on a JWT token.\n *\n * @param token - Bearer access token\n * @returns Validated JwtPayload claims\n */\n public async verifyToken(token: string): Promise<JwtPayload> {\n const { payload } = this.parseUnverified(token);\n const nowSeconds = Math.floor(Date.now() / 1000);\n\n // 1. Validate Expiration (exp)\n if (typeof payload.exp === \"number\" && nowSeconds >= payload.exp) {\n logger.warn(\"[verifyToken] Token has expired\", {\n exp: payload.exp,\n now: nowSeconds,\n });\n throw new UnauthorizedError(\"Authentication token has expired\");\n }\n\n // 2. Validate Not Before (nbf)\n if (typeof payload.nbf === \"number\" && nowSeconds < payload.nbf) {\n logger.warn(\"[verifyToken] Token not yet valid\", {\n nbf: payload.nbf,\n now: nowSeconds,\n });\n throw new UnauthorizedError(\"Authentication token is not yet active\");\n }\n\n // 3. Validate Issuer (iss)\n if (this.issuer && payload.iss && payload.iss !== this.issuer) {\n logger.warn(\"[verifyToken] Issuer mismatch\", {\n expected: this.issuer,\n actual: payload.iss,\n });\n throw new UnauthorizedError(\"Token issuer mismatch\");\n }\n\n // 4. Validate Audience (aud)\n if (this.audience && payload.aud) {\n const audList = Array.isArray(payload.aud) ? payload.aud : [payload.aud];\n if (!audList.includes(this.audience)) {\n logger.warn(\"[verifyToken] Audience mismatch\", {\n expected: this.audience,\n actual: payload.aud,\n });\n throw new UnauthorizedError(\"Token audience mismatch\");\n }\n }\n\n logger.debug(\"[verifyToken] Successfully validated token claims\", {\n sub: payload.sub,\n });\n return payload;\n }\n\n /**\n * Clears cached public keys from memory.\n */\n public clearKeyCache(): void {\n this.keyCache.clear();\n logger.info(\"[clearKeyCache] JWKS public key cache cleared\");\n }\n}\n","/**\n * @file packages/auth-server/src/guards/auth-guards.ts\n * @description Authorization assertions and scope/role enforcement guards.\n * @module @yuva-devlab/auth-server\n */\n\nimport { ForbiddenError, UnauthorizedError } from \"@yuva-devlab/errors\";\nimport { Logger, loggerWithConfig } from \"@yuva-devlab/logger\";\nimport type { ApiKey, AuthContext, AuthUser } from \"../types\";\n\nconst logger = loggerWithConfig(new Logger(\"AuthGuards\"));\n\n/**\n * Asserts that the request is authenticated with an active user session and optional role requirements.\n *\n * @param ctx - Inbound request auth context\n * @param requiredRoles - Optional list of required roles (user must possess at least one)\n * @returns Authenticated AuthUser\n * @throws UnauthorizedError if not authenticated as a user\n * @throws ForbiddenError if user lacks the required roles\n *\n * @example\n * ```typescript\n * const user = requireUser(ctx, [\"admin\", \"operator\"]);\n * ```\n */\nexport function requireUser(\n ctx: AuthContext,\n requiredRoles?: readonly string[],\n): AuthUser {\n if (!ctx.authenticated || !ctx.user) {\n logger.warn(\n \"[requireUser] Request rejected: missing authenticated user context\",\n );\n throw new UnauthorizedError(\n \"Authentication required: valid user session required\",\n );\n }\n\n if (requiredRoles && requiredRoles.length > 0) {\n const hasRole = requiredRoles.some((role) => ctx.roles.includes(role));\n if (!hasRole) {\n logger.warn(\"[requireUser] User lacks required roles\", {\n userId: ctx.user.id,\n userRoles: ctx.roles,\n requiredRoles,\n });\n throw new ForbiddenError(\n `Insufficient privileges: requires one of [${requiredRoles.join(\", \")}]`,\n );\n }\n }\n\n return ctx.user;\n}\n\n/**\n * Asserts that the request is authenticated via a machine-to-machine API key.\n *\n * @param ctx - Inbound request auth context\n * @returns Authenticated ApiKey\n * @throws UnauthorizedError if not authenticated via an API key\n */\nexport function requireApiKey(ctx: AuthContext): ApiKey {\n if (!ctx.authenticated || !ctx.apiKey) {\n logger.warn(\"[requireApiKey] Request rejected: missing machine API key\");\n throw new UnauthorizedError(\n \"Authentication required: valid API key required\",\n );\n }\n\n return ctx.apiKey;\n}\n\n/**\n * Asserts that the authenticated context (user or API key) possesses a specific operational scope.\n *\n * @param ctx - Inbound request auth context\n * @param scope - Required scope or permission string\n * @throws ForbiddenError if scope is missing\n */\nexport function requireScope(ctx: AuthContext, scope: string): void {\n if (!ctx.roles.includes(scope)) {\n logger.warn(\"[requireScope] Missing required scope\", {\n roles: ctx.roles,\n requiredScope: scope,\n });\n throw new ForbiddenError(`Missing required scope: '${scope}'`);\n }\n}\n","/**\n * @file packages/auth-server/src/middleware/auth-middleware.ts\n * @description Universal HTTP middleware providing platform kill-switch enforcement and credential validation.\n * @module @yuva-devlab/auth-server\n */\n\nimport { Logger, loggerWithConfig } from \"@yuva-devlab/logger\";\nimport {\n DEFAULT_API_KEY_HEADER,\n DEFAULT_AUTH_HEADER,\n DEFAULT_BEARER_PREFIX,\n DEFAULT_PUBLIC_PATHS,\n HTTP_STATUS_SERVICE_UNAVAILABLE,\n HTTP_STATUS_UNAUTHORIZED,\n} from \"../constants\";\nimport { AppStatus, type AuthContext } from \"../types\";\n\nconst logger = loggerWithConfig(new Logger(\"AuthMiddleware\"));\n\n/**\n * Minimal HTTP request and response interfaces for framework neutrality (Express, Fastify, Node http).\n */\nexport interface GenericHttpRequest {\n url?: string;\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n authContext?: AuthContext;\n}\n\nexport interface GenericHttpResponse {\n statusCode?: number;\n setHeader(name: string, value: string): void;\n end(body?: string): void;\n}\n\n/**\n * Creates a kill-switch middleware that intercepts all traffic if an application is deactivated.\n *\n * @param getAppStatus - Callback returning current platform status of the application\n * @returns Middleware function returning true if allowed to proceed, false if blocked (503)\n *\n * @example\n * ```typescript\n * const killSwitch = createAppKillSwitchMiddleware(() => appState.status);\n * const allowed = await killSwitch(req, res);\n * if (!allowed) return;\n * ```\n */\nexport function createAppKillSwitchMiddleware(\n getAppStatus: () => Promise<AppStatus> | AppStatus,\n) {\n return async (\n req: GenericHttpRequest,\n res: GenericHttpResponse,\n ): Promise<boolean> => {\n const status = await getAppStatus();\n\n // If application has been administratively disabled or put into maintenance\n if (status === AppStatus.INACTIVE || status === AppStatus.MAINTENANCE) {\n logger.warn(\n \"[killSwitch] Application is inactive or under maintenance; request rejected\",\n {\n url: req.url,\n method: req.method,\n appStatus: status,\n },\n );\n\n res.statusCode = HTTP_STATUS_SERVICE_UNAVAILABLE;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(\n JSON.stringify({\n error: {\n code: \"APP_DEACTIVATED\",\n message:\n status === AppStatus.MAINTENANCE\n ? \"Application is currently undergoing scheduled maintenance\"\n : \"Application has been deactivated by platform administrators\",\n status,\n },\n }),\n );\n return false;\n }\n\n return true;\n };\n}\n\n/**\n * Options configuring request authentication middleware.\n */\nexport interface CreateAuthMiddlewareOptions {\n /** Whitelisted public endpoints bypassing authentication */\n publicPaths?: readonly string[];\n /** Function resolving an API key against store */\n validateApiKey?: (key: string) => Promise<AuthContext | null>;\n /** Function resolving a Bearer session token against JWKS or session store */\n validateToken?: (token: string) => Promise<AuthContext | null>;\n}\n\n/**\n * Universal authentication middleware verifying API keys and Bearer tokens.\n *\n * @param options - Configuration options\n * @returns Middleware handler\n */\nexport function createAuthMiddleware(options: CreateAuthMiddlewareOptions) {\n const publicPaths = new Set([\n ...DEFAULT_PUBLIC_PATHS,\n ...(options.publicPaths ?? []),\n ]);\n\n return async (\n req: GenericHttpRequest,\n res: GenericHttpResponse,\n ): Promise<boolean> => {\n const urlPath = (req.url || \"/\").split(\"?\")[0] || \"/\";\n\n // 1. Bypass authentication for whitelisted public paths\n if (publicPaths.has(urlPath)) {\n req.authContext = {\n authenticated: false,\n roles: [],\n isAppActive: true,\n };\n return true;\n }\n\n // 2. Check for Machine-to-Machine API Key\n const rawApiKey = req.headers[DEFAULT_API_KEY_HEADER];\n const apiKey = typeof rawApiKey === \"string\" ? rawApiKey.trim() : undefined;\n\n if (apiKey && options.validateApiKey) {\n const apiKeyCtx = await options.validateApiKey(apiKey);\n if (apiKeyCtx?.authenticated) {\n logger.info(\"[authenticate] Authenticated via API Key\", {\n path: urlPath,\n });\n req.authContext = apiKeyCtx;\n return true;\n }\n }\n\n // 3. Check for Bearer Token\n const rawAuth = req.headers[DEFAULT_AUTH_HEADER];\n const authHeader = typeof rawAuth === \"string\" ? rawAuth.trim() : undefined;\n\n if (\n authHeader?.startsWith(DEFAULT_BEARER_PREFIX) &&\n options.validateToken\n ) {\n const token = authHeader.slice(DEFAULT_BEARER_PREFIX.length).trim();\n const tokenCtx = await options.validateToken(token);\n if (tokenCtx?.authenticated) {\n logger.info(\"[authenticate] Authenticated via Bearer token\", {\n path: urlPath,\n });\n req.authContext = tokenCtx;\n return true;\n }\n }\n\n // 4. Reject with 401 Unauthorized\n logger.warn(\"[authenticate] Unauthorized request rejected\", {\n path: urlPath,\n method: req.method,\n });\n\n res.statusCode = HTTP_STATUS_UNAUTHORIZED;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(\n JSON.stringify({\n error: {\n code: \"UNAUTHORIZED\",\n message:\n \"Missing or invalid authentication credentials (Bearer token or API key required)\",\n },\n }),\n );\n return false;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants/auth.constants.ts","../src/types/auth.types.ts","../src/token/jwt-validator.ts","../src/token/m2m-validator.ts","../src/guards/auth-guards.ts","../src/middleware/auth-middleware.ts"],"names":["AppStatus","logger","loggerWithConfig","Logger","UnauthorizedError","ForbiddenError"],"mappings":";;;;;AAOO,IAAM,mBAAA,GAAsB;AAG5B,IAAM,sBAAA,GAAyB;AAG/B,IAAM,qBAAA,GAAwB;AAG9B,IAAM,yBAAA,GAA4B;AAGlC,IAAM,4BAAA,GAA+B;AAGrC,IAAM,oBAAA,GAAuB,OAAO,MAAA,CAAO;AAAA,EAChD,SAAA;AAAA,EACA,QAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAC;AAGM,IAAM,wBAAA,GAA2B;AAGjC,IAAM,qBAAA,GAAwB;AAG9B,IAAM,+BAAA,GAAkC;;;AC3BxC,IAAK,SAAA,qBAAAA,UAAAA,KAAL;AAEL,EAAAA,WAAA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CAAO,KAAK,+CAAA,EAAiD;AAAA,UAC3D,IAAA,EAAM;AAAA,SACP,CAAA;AACD,QAAA,GAAA,CAAI,WAAA,GAAc,QAAA;AAClB,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF;AAGA,IAAAA,OAAAA,CAAO,KAAK,8CAAA,EAAgD;AAAA,MAC1D,IAAA,EAAM,OAAA;AAAA,MACN,QAAQ,GAAA,CAAI;AAAA,KACb,CAAA;AAED,IAAA,GAAA,CAAI,UAAA,GAAa,wBAAA;AACjB,IAAA,GAAA,CAAI,SAAA,CAAU,gBAAgB,kBAAkB,CAAA;AAChD,IAAA,GAAA,CAAI,GAAA;AAAA,MACF,KAAK,SAAA,CAAU;AAAA,QACb,KAAA,EAAO;AAAA,UACL,IAAA,EAAM,cAAA;AAAA,UACN,OAAA,EACE;AAAA;AACJ,OACD;AAAA,KACH;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * @file packages/auth-server/src/constants/auth.constants.ts\n * @description Centralized constants and header keys for server-side authentication.\n * @module @yuva-devlab/auth-server\n */\n\n/** Standard Authorization HTTP header name (lowercase for case-insensitive lookup) */\nexport const DEFAULT_AUTH_HEADER = \"authorization\";\n\n/** Standard machine-to-machine API key HTTP header name */\nexport const DEFAULT_API_KEY_HEADER = \"x-api-key\";\n\n/** Standard Bearer token prefix */\nexport const DEFAULT_BEARER_PREFIX = \"Bearer \";\n\n/** Default cache time-to-live for fetched RS256 JWKS public keys (1 hour) */\nexport const DEFAULT_JWKS_CACHE_TTL_MS = 3_600_000;\n\n/** Default cache time-to-live for validated M2M API keys (5 minutes) */\nexport const DEFAULT_API_KEY_CACHE_TTL_MS = 300_000;\n\n/** Default public endpoints bypassing mandatory authentication */\nexport const DEFAULT_PUBLIC_PATHS = Object.freeze([\n \"/health\",\n \"/ready\",\n \"/live\",\n \"/metrics\",\n]);\n\n/** HTTP Status Code for unauthenticated requests */\nexport const HTTP_STATUS_UNAUTHORIZED = 401;\n\n/** HTTP Status Code for unauthorized / forbidden role requests */\nexport const HTTP_STATUS_FORBIDDEN = 403;\n\n/** HTTP Status Code returned when an application is deactivated or killed */\nexport const HTTP_STATUS_SERVICE_UNAVAILABLE = 503;\n","/**\n * @file packages/auth-server/src/types/auth.types.ts\n * @description Type definitions and contracts for server authentication, JWKS, and app lifecycle.\n * @module @yuva-devlab/auth-server\n */\n\n/**\n * Operational state of an application on the DevLab platform.\n */\nexport enum AppStatus {\n /** Application is fully operational and serving traffic */\n ACTIVE = \"ACTIVE\",\n /** Application has been administratively disabled / deactivated (Kill-Switch triggered) */\n INACTIVE = \"INACTIVE\",\n /** Application is undergoing scheduled maintenance */\n MAINTENANCE = \"MAINTENANCE\",\n}\n\n/**\n * Authenticated user profile representation.\n */\nexport interface AuthUser {\n /** Canonical user UUID */\n readonly id: string;\n /** Primary user email address */\n readonly email?: string;\n /** Granted role slugs */\n readonly roles: readonly string[];\n /** Tenant isolation partition ID */\n readonly tenantId?: string;\n /** Arbitrary profile metadata */\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * Machine-to-machine API key credential.\n */\nexport interface ApiKey {\n /** Primary API key UUID */\n readonly id: string;\n /** Secure key string */\n readonly key: string;\n /** Human-readable key name or description */\n readonly name: string;\n /** Scoped roles granted to this key */\n readonly roles: readonly string[];\n /** Tenant ID partition */\n readonly tenantId?: string;\n /** Active status flag */\n readonly isEnabled: boolean;\n}\n\n/**\n * Evaluated authentication context attached to inbound requests.\n */\nexport interface AuthContext {\n /** Whether the request carries valid credentials */\n readonly authenticated: boolean;\n /** Authenticated user if authenticated via session/JWT */\n readonly user?: AuthUser;\n /** Authenticated API key if authenticated via machine credential */\n readonly apiKey?: ApiKey;\n /** Consolidated roles granted across user or API key */\n readonly roles: readonly string[];\n /** Whether the host application is currently active on the platform */\n readonly isAppActive: boolean;\n /** Detailed app status */\n readonly appStatus?: AppStatus;\n /** Tenant partition ID */\n readonly tenantId?: string;\n /** Distributed trace request identifier */\n readonly requestId?: string;\n}\n\n/**\n * Configuration for verifying RS256 JWTs against a remote JWKS endpoint.\n */\nexport interface JwksConfig {\n /** JWKS endpoint URI exposing JSON Web Keys */\n readonly jwksUri: string;\n /** Expected audience claim */\n readonly audience?: string;\n /** Expected issuer claim */\n readonly issuer?: string;\n /** In-memory cache duration for public keys in milliseconds */\n readonly cacheTtlMs?: number;\n}\n\n/**\n * Decoded JWT claims payload.\n */\n\n/**\n * Result of validating a Machine-to-Machine API key against the DevLab Portal.\n */\nexport interface ApiKeyValidationResult {\n /** Whether the API key is active, valid, and unexpired */\n readonly valid: boolean;\n /** Primary API key UUID */\n readonly keyId?: string;\n /** Name assigned to this machine key */\n readonly name?: string;\n /** Target application slug this key belongs to */\n readonly appId?: string;\n /** Target application display name */\n readonly appName?: string;\n /** Scopes and permissions granted to this key */\n readonly scopes?: readonly string[];\n /** Allowed requests per minute limit */\n readonly rateLimitRpm?: number;\n /** Human-readable rejection reason if invalid */\n readonly reason?: string;\n}\n\n/**\n * Configuration options for Machine-to-Machine API key validation.\n */\nexport interface M2mConfig {\n /** Base URL of the authentication server / identity provider */\n readonly authUrl?: string;\n /** Legacy alias for authUrl */\n readonly portalUrl?: string;\n /** In-memory cache duration for validated API keys in milliseconds */\n readonly cacheTtlMs?: number;\n /** Expected client or application identifier */\n readonly requiredClientId?: string;\n /** Legacy alias for requiredClientId */\n readonly requiredAppId?: string;\n /** Required operational scopes that must be granted to the API key */\n readonly requiredScopes?: readonly string[];\n}\n\nexport interface JwtPayload {\n readonly sub: string;\n readonly iss?: string;\n readonly aud?: string | readonly string[];\n readonly exp?: number;\n readonly nbf?: number;\n readonly iat?: number;\n readonly email?: string;\n readonly name?: string;\n readonly role?: string;\n readonly roles?: readonly string[];\n readonly tenantId?: string;\n readonly tenant_id?: string;\n readonly tenant_slug?: string;\n readonly tenant_name?: string;\n readonly apps?: readonly string[];\n readonly appId?: string;\n readonly [key: string]: unknown;\n}\n","/**\n * @file packages/auth-server/src/token/jwt-validator.ts\n * @description RS256 JWKS validator providing cryptographic signature verification and claims checking.\n * @module @yuva-devlab/auth-server\n */\n\nimport crypto from \"node:crypto\";\nimport { UnauthorizedError } from \"@yuva-devlab/errors\";\nimport { Logger, loggerWithConfig } from \"@yuva-devlab/logger\";\nimport { DEFAULT_JWKS_CACHE_TTL_MS } from \"../constants\";\nimport type { JwksConfig, JwtPayload } from \"../types\";\n\nconst logger = loggerWithConfig(new Logger(\"JwksValidator\"));\n\ninterface CachedKey {\n readonly keyObject: crypto.KeyObject;\n readonly expiresAt: number;\n}\n\ninterface JwkRecord {\n readonly kid?: string;\n readonly kty: string;\n readonly alg?: string;\n readonly use?: string;\n readonly [key: string]: unknown;\n}\n\n/**\n * Validates JWT access tokens against an in-memory cached JWKS public key set.\n */\nexport class JwksValidator {\n private readonly jwksUri: string;\n private readonly audience?: string;\n private readonly issuer?: string;\n private readonly cacheTtlMs: number;\n private keyCache = new Map<string, CachedKey>();\n private jwksSetCache: {\n keys: readonly JwkRecord[];\n expiresAt: number;\n } | null = null;\n\n public constructor(config: Partial<JwksConfig> = {}) {\n this.jwksUri =\n config.jwksUri ??\n (config.issuer ? `${config.issuer}/.well-known/jwks.json` : undefined) ??\n (typeof process !== \"undefined\"\n ? (process.env?.DEVLAB_JWKS_URI ??\n (process.env?.DEVLAB_AUTH_URL\n ? `${process.env.DEVLAB_AUTH_URL}/.well-known/jwks.json`\n : undefined))\n : undefined) ??\n \"\";\n this.audience = config.audience;\n this.issuer = config.issuer;\n this.cacheTtlMs = config.cacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;\n }\n\n public parseUnverified(token: string): {\n header: Record<string, unknown>;\n payload: JwtPayload;\n rawHeader: string;\n rawPayload: string;\n signature: string;\n } {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n throw new UnauthorizedError(\n \"Malformed JWT token format: expected 3 segments\",\n );\n }\n\n try {\n const header = JSON.parse(\n Buffer.from(parts[0]!, \"base64url\").toString(\"utf-8\"),\n ) as Record<string, unknown>;\n const payload = JSON.parse(\n Buffer.from(parts[1]!, \"base64url\").toString(\"utf-8\"),\n ) as JwtPayload;\n return {\n header,\n payload,\n rawHeader: parts[0]!,\n rawPayload: parts[1]!,\n signature: parts[2]!,\n };\n } catch {\n throw new UnauthorizedError(\"Unable to decode JWT header or payload\");\n }\n }\n\n private async fetchJwks(): Promise<readonly JwkRecord[]> {\n if (!this.jwksUri) {\n throw new UnauthorizedError(\n \"JwksValidator: jwksUri, issuer, or DEVLAB_AUTH_URL must be configured\",\n );\n }\n const now = Date.now();\n if (this.jwksSetCache && this.jwksSetCache.expiresAt > now) {\n return this.jwksSetCache.keys;\n }\n\n try {\n const res = await fetch(this.jwksUri, {\n headers: { Accept: \"application/json\" },\n signal: AbortSignal.timeout(5000),\n });\n\n if (!res.ok) {\n throw new Error(`JWKS endpoint returned HTTP ${res.status}`);\n }\n\n const body = (await res.json()) as { keys?: readonly JwkRecord[] };\n const keys = body.keys ?? [];\n this.jwksSetCache = { keys, expiresAt: now + this.cacheTtlMs };\n return keys;\n } catch (err) {\n logger.error(\"[fetchJwks] Failed to fetch JWKS public keys\", {\n uri: this.jwksUri,\n err,\n });\n if (this.jwksSetCache?.keys) return this.jwksSetCache.keys;\n throw new UnauthorizedError(\"Authentication service JWKS unreachable\");\n }\n }\n\n private async resolveKeyObject(kid?: string): Promise<crypto.KeyObject> {\n const now = Date.now();\n const cacheKey = kid ?? \"__default__\";\n const cached = this.keyCache.get(cacheKey);\n\n if (cached && cached.expiresAt > now) {\n return cached.keyObject;\n }\n\n const jwks = await this.fetchJwks();\n const matched = kid ? jwks.find((k) => k.kid === kid) : jwks[0];\n\n if (!matched) {\n throw new UnauthorizedError(\n `No matching JWK public key found for kid: ${kid ?? \"default\"}`,\n );\n }\n\n try {\n const keyObject = crypto.createPublicKey({\n key: matched as crypto.JsonWebKey,\n format: \"jwk\",\n });\n this.keyCache.set(cacheKey, {\n keyObject,\n expiresAt: now + this.cacheTtlMs,\n });\n return keyObject;\n } catch (err) {\n logger.error(\"[resolveKeyObject] Failed to parse JWK public key\", {\n kid,\n err,\n });\n throw new UnauthorizedError(\"Invalid JWK public key format\");\n }\n }\n\n public async verifyToken(token: string): Promise<JwtPayload> {\n const { header, payload, rawHeader, rawPayload, signature } =\n this.parseUnverified(token);\n\n if (header.alg && header.alg !== \"RS256\") {\n throw new UnauthorizedError(\n `Unsupported signing algorithm: ${header.alg}. Expected RS256`,\n );\n }\n\n const kid = typeof header.kid === \"string\" ? header.kid : undefined;\n const keyObject = await this.resolveKeyObject(kid);\n\n const data = Buffer.from(`${rawHeader}.${rawPayload}`);\n const sigBuffer = Buffer.from(signature, \"base64url\");\n const isSignatureValid = crypto.verify(\n \"RSA-SHA256\",\n data,\n keyObject,\n sigBuffer,\n );\n\n if (!isSignatureValid) {\n logger.warn(\"[verifyToken] Cryptographic signature check failed\", {\n sub: payload.sub,\n kid,\n });\n throw new UnauthorizedError(\"Invalid token signature\");\n }\n\n const nowSeconds = Math.floor(Date.now() / 1000);\n if (typeof payload.exp === \"number\" && nowSeconds >= payload.exp) {\n throw new UnauthorizedError(\"Authentication token has expired\");\n }\n\n if (typeof payload.nbf === \"number\" && nowSeconds < payload.nbf) {\n throw new UnauthorizedError(\"Authentication token is not yet active\");\n }\n\n if (this.issuer && payload.iss && payload.iss !== this.issuer) {\n throw new UnauthorizedError(\n `Token issuer mismatch: expected ${this.issuer}, got ${payload.iss}`,\n );\n }\n\n if (this.audience && payload.aud) {\n const audList = Array.isArray(payload.aud) ? payload.aud : [payload.aud];\n if (!audList.includes(this.audience)) {\n throw new UnauthorizedError(\n `Token audience mismatch: expected ${this.audience}`,\n );\n }\n }\n\n return payload;\n }\n\n public clearKeyCache(): void {\n this.keyCache.clear();\n this.jwksSetCache = null;\n logger.info(\"[clearKeyCache] JWKS public key cache cleared\");\n }\n}\n","/**\n * @file packages/auth-server/src/token/m2m-validator.ts\n * @description In-memory cached Machine-to-Machine API key validator introspecting the auth provider.\n * @module @yuva-devlab/auth-server\n */\n\nimport { ForbiddenError, UnauthorizedError } from \"@yuva-devlab/errors\";\nimport { Logger, loggerWithConfig } from \"@yuva-devlab/logger\";\nimport { DEFAULT_API_KEY_CACHE_TTL_MS } from \"../constants\";\nimport type { ApiKeyValidationResult, M2mConfig } from \"../types\";\n\nconst logger = loggerWithConfig(new Logger(\"M2mApiKeyValidator\"));\n\ninterface CachedApiKey {\n readonly result: ApiKeyValidationResult;\n readonly expiresAt: number;\n}\n\n/**\n * Validates machine-to-machine API keys against central authentication server with in-memory caching.\n */\nexport class M2mApiKeyValidator {\n private readonly authUrl?: string;\n private readonly cacheTtlMs: number;\n private readonly requiredClientId?: string;\n private readonly requiredScopes?: readonly string[];\n private readonly keyCache = new Map<string, CachedApiKey>();\n\n public constructor(config: Partial<M2mConfig> = {}) {\n this.authUrl =\n config.authUrl ??\n config.portalUrl ??\n process.env.DEVLAB_AUTH_URL ??\n process.env.DEVLAB_PORTAL_URL;\n this.cacheTtlMs = config.cacheTtlMs ?? DEFAULT_API_KEY_CACHE_TTL_MS;\n this.requiredClientId = config.requiredClientId ?? config.requiredAppId;\n this.requiredScopes = config.requiredScopes;\n }\n\n public async validateKey(rawKey: string): Promise<ApiKeyValidationResult> {\n const trimmed = rawKey.trim();\n if (!trimmed.startsWith(\"dlk_\")) {\n throw new UnauthorizedError(\"Malformed API key: expected 'dlk_' prefix\");\n }\n\n if (!this.authUrl) {\n throw new UnauthorizedError(\n \"M2mApiKeyValidator: authUrl or DEVLAB_AUTH_URL must be configured for validation\",\n );\n }\n\n const now = Date.now();\n const cached = this.keyCache.get(trimmed);\n if (cached && cached.expiresAt > now) {\n return this.enforceKeyConstraints(cached.result);\n }\n\n try {\n const url = `${this.authUrl}/api/v1/api-keys/validate`;\n const res = await fetch(url, {\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${trimmed}`,\n },\n signal: AbortSignal.timeout(5000),\n });\n\n if (!res.ok) {\n throw new Error(\n `Authentication validation endpoint returned HTTP ${res.status}`,\n );\n }\n\n const body = (await res.json()) as ApiKeyValidationResult;\n if (!body.valid) {\n throw new UnauthorizedError(body.reason ?? \"Invalid machine API key\");\n }\n\n this.keyCache.set(trimmed, {\n result: body,\n expiresAt: now + this.cacheTtlMs,\n });\n\n return this.enforceKeyConstraints(body);\n } catch (err) {\n if (err instanceof UnauthorizedError || err instanceof ForbiddenError) {\n throw err;\n }\n logger.error(\"[validateKey] Network error during API key introspection\", {\n err,\n });\n throw new UnauthorizedError(\n \"Authentication service unreachable for API key verification\",\n );\n }\n }\n\n private enforceKeyConstraints(\n result: ApiKeyValidationResult,\n ): ApiKeyValidationResult {\n if (\n this.requiredClientId &&\n result.appId &&\n result.appId !== this.requiredClientId\n ) {\n throw new ForbiddenError(\n \"API key assigned to \" +\n result.appId +\n \", required \" +\n this.requiredClientId,\n );\n }\n\n if (this.requiredScopes && this.requiredScopes.length > 0) {\n const keyScopes = result.scopes ?? [];\n const hasWildcard = keyScopes.includes(\"*\");\n if (!hasWildcard) {\n const hasAll = this.requiredScopes.every((scope) =>\n keyScopes.includes(scope),\n );\n if (!hasAll) {\n throw new ForbiddenError(\n \"API key lacks required scopes: [\" +\n this.requiredScopes.join(\", \") +\n \"]\",\n );\n }\n }\n }\n\n return result;\n }\n\n public clearCache(): void {\n this.keyCache.clear();\n logger.info(\"[clearCache] API key validation cache cleared\");\n }\n}\n","/**\n * @file packages/auth-server/src/guards/auth-guards.ts\n * @description Authorization assertions and scope/role enforcement guards.\n * @module @yuva-devlab/auth-server\n */\n\nimport { ForbiddenError, UnauthorizedError } from \"@yuva-devlab/errors\";\nimport { Logger, loggerWithConfig } from \"@yuva-devlab/logger\";\nimport type { ApiKey, AuthContext, AuthUser } from \"../types\";\n\nconst logger = loggerWithConfig(new Logger(\"AuthGuards\"));\n\n/**\n * Asserts that the request is authenticated with an active user session and optional role requirements.\n *\n * @param ctx - Inbound request auth context\n * @param requiredRoles - Optional list of required roles (user must possess at least one)\n * @returns Authenticated AuthUser\n * @throws UnauthorizedError if not authenticated as a user\n * @throws ForbiddenError if user lacks the required roles\n *\n * @example\n * ```typescript\n * const user = requireUser(ctx, [\"admin\", \"operator\"]);\n * ```\n */\nexport function requireUser(\n ctx: AuthContext,\n requiredRoles?: readonly string[],\n): AuthUser {\n if (!ctx.authenticated || !ctx.user) {\n logger.warn(\n \"[requireUser] Request rejected: missing authenticated user context\",\n );\n throw new UnauthorizedError(\n \"Authentication required: valid user session required\",\n );\n }\n\n if (requiredRoles && requiredRoles.length > 0) {\n const hasRole = requiredRoles.some((role) => ctx.roles.includes(role));\n if (!hasRole) {\n logger.warn(\"[requireUser] User lacks required roles\", {\n userId: ctx.user.id,\n userRoles: ctx.roles,\n requiredRoles,\n });\n throw new ForbiddenError(\n `Insufficient privileges: requires one of [${requiredRoles.join(\", \")}]`,\n );\n }\n }\n\n return ctx.user;\n}\n\n/**\n * Asserts that the request is authenticated via a machine-to-machine API key.\n *\n * @param ctx - Inbound request auth context\n * @returns Authenticated ApiKey\n * @throws UnauthorizedError if not authenticated via an API key\n */\nexport function requireApiKey(ctx: AuthContext): ApiKey {\n if (!ctx.authenticated || !ctx.apiKey) {\n logger.warn(\"[requireApiKey] Request rejected: missing machine API key\");\n throw new UnauthorizedError(\n \"Authentication required: valid API key required\",\n );\n }\n\n return ctx.apiKey;\n}\n\n/**\n * Asserts that the authenticated context (user or API key) possesses a specific operational scope.\n *\n * @param ctx - Inbound request auth context\n * @param scope - Required scope or permission string\n * @throws ForbiddenError if scope is missing\n */\nexport function requireScope(ctx: AuthContext, scope: string): void {\n if (!ctx.roles.includes(scope)) {\n logger.warn(\"[requireScope] Missing required scope\", {\n roles: ctx.roles,\n requiredScope: scope,\n });\n throw new ForbiddenError(`Missing required scope: '${scope}'`);\n }\n}\n","/**\n * @file packages/auth-server/src/middleware/auth-middleware.ts\n * @description Universal HTTP middleware providing platform kill-switch enforcement and credential validation.\n * @module @yuva-devlab/auth-server\n */\n\nimport { Logger, loggerWithConfig } from \"@yuva-devlab/logger\";\nimport {\n DEFAULT_API_KEY_HEADER,\n DEFAULT_AUTH_HEADER,\n DEFAULT_BEARER_PREFIX,\n DEFAULT_PUBLIC_PATHS,\n HTTP_STATUS_SERVICE_UNAVAILABLE,\n HTTP_STATUS_UNAUTHORIZED,\n} from \"../constants\";\nimport { AppStatus, type AuthContext } from \"../types\";\n\nconst logger = loggerWithConfig(new Logger(\"AuthMiddleware\"));\n\n/**\n * Minimal HTTP request and response interfaces for framework neutrality (Express, Fastify, Node http).\n */\nexport interface GenericHttpRequest {\n url?: string;\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n authContext?: AuthContext;\n}\n\nexport interface GenericHttpResponse {\n statusCode?: number;\n setHeader(name: string, value: string): void;\n end(body?: string): void;\n}\n\n/**\n * Creates a kill-switch middleware that intercepts all traffic if an application is deactivated.\n *\n * @param getAppStatus - Callback returning current platform status of the application\n * @returns Middleware function returning true if allowed to proceed, false if blocked (503)\n *\n * @example\n * ```typescript\n * const killSwitch = createAppKillSwitchMiddleware(() => appState.status);\n * const allowed = await killSwitch(req, res);\n * if (!allowed) return;\n * ```\n */\nexport function createAppKillSwitchMiddleware(\n getAppStatus: () => Promise<AppStatus> | AppStatus,\n) {\n return async (\n req: GenericHttpRequest,\n res: GenericHttpResponse,\n ): Promise<boolean> => {\n const status = await getAppStatus();\n\n // If application has been administratively disabled or put into maintenance\n if (status === AppStatus.INACTIVE || status === AppStatus.MAINTENANCE) {\n logger.warn(\n \"[killSwitch] Application is inactive or under maintenance; request rejected\",\n {\n url: req.url,\n method: req.method,\n appStatus: status,\n },\n );\n\n res.statusCode = HTTP_STATUS_SERVICE_UNAVAILABLE;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(\n JSON.stringify({\n error: {\n code: \"APP_DEACTIVATED\",\n message:\n status === AppStatus.MAINTENANCE\n ? \"Application is currently undergoing scheduled maintenance\"\n : \"Application has been deactivated by platform administrators\",\n status,\n },\n }),\n );\n return false;\n }\n\n return true;\n };\n}\n\n/**\n * Options configuring request authentication middleware.\n */\nexport interface CreateAuthMiddlewareOptions {\n /** Whitelisted public endpoints bypassing authentication */\n publicPaths?: readonly string[];\n /** Function resolving an API key against store */\n validateApiKey?: (key: string) => Promise<AuthContext | null>;\n /** Function resolving a Bearer session token against JWKS or session store */\n validateToken?: (token: string) => Promise<AuthContext | null>;\n}\n\n/**\n * Universal authentication middleware verifying API keys and Bearer tokens.\n *\n * @param options - Configuration options\n * @returns Middleware handler\n */\nexport function createAuthMiddleware(options: CreateAuthMiddlewareOptions) {\n const publicPaths = new Set([\n ...DEFAULT_PUBLIC_PATHS,\n ...(options.publicPaths ?? []),\n ]);\n\n return async (\n req: GenericHttpRequest,\n res: GenericHttpResponse,\n ): Promise<boolean> => {\n const urlPath = (req.url || \"/\").split(\"?\")[0] || \"/\";\n\n // 1. Bypass authentication for whitelisted public paths\n if (publicPaths.has(urlPath)) {\n req.authContext = {\n authenticated: false,\n roles: [],\n isAppActive: true,\n };\n return true;\n }\n\n // 2. Check for Machine-to-Machine API Key\n const rawApiKey = req.headers[DEFAULT_API_KEY_HEADER];\n const apiKey = typeof rawApiKey === \"string\" ? rawApiKey.trim() : undefined;\n\n if (apiKey && options.validateApiKey) {\n const apiKeyCtx = await options.validateApiKey(apiKey);\n if (apiKeyCtx?.authenticated) {\n logger.info(\"[authenticate] Authenticated via API Key\", {\n path: urlPath,\n });\n req.authContext = apiKeyCtx;\n return true;\n }\n }\n\n // 3. Check for Bearer Token\n const rawAuth = req.headers[DEFAULT_AUTH_HEADER];\n const authHeader = typeof rawAuth === \"string\" ? rawAuth.trim() : undefined;\n\n if (\n authHeader?.startsWith(DEFAULT_BEARER_PREFIX) &&\n options.validateToken\n ) {\n const token = authHeader.slice(DEFAULT_BEARER_PREFIX.length).trim();\n const tokenCtx = await options.validateToken(token);\n if (tokenCtx?.authenticated) {\n logger.info(\"[authenticate] Authenticated via Bearer token\", {\n path: urlPath,\n });\n req.authContext = tokenCtx;\n return true;\n }\n }\n\n // 4. Reject with 401 Unauthorized\n logger.warn(\"[authenticate] Unauthorized request rejected\", {\n path: urlPath,\n method: req.method,\n });\n\n res.statusCode = HTTP_STATUS_UNAUTHORIZED;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(\n JSON.stringify({\n error: {\n code: \"UNAUTHORIZED\",\n message:\n \"Missing or invalid authentication credentials (Bearer token or API key required)\",\n },\n }),\n );\n return false;\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yuva-devlab/auth-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Server-side authentication guards, cached JWKS validator, and kill-switch middleware for DevLab",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -26,8 +26,8 @@
|
|
|
26
26
|
"license": "MIT",
|
|
27
27
|
"dependencies": {
|
|
28
28
|
"zod": "^3.25.76",
|
|
29
|
-
"@yuva-devlab/
|
|
30
|
-
"@yuva-devlab/
|
|
29
|
+
"@yuva-devlab/logger": "1.2.0",
|
|
30
|
+
"@yuva-devlab/errors": "0.2.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@types/node": "^24.10.1",
|
|
@@ -35,8 +35,8 @@
|
|
|
35
35
|
"prettier": "^3.9.8",
|
|
36
36
|
"tsup": "^8.5.1",
|
|
37
37
|
"typescript": "^6.0.3",
|
|
38
|
-
"@yuva-devlab/eslint-config": "0.1.1",
|
|
39
38
|
"@yuva-devlab/prettier-config": "0.1.1",
|
|
39
|
+
"@yuva-devlab/eslint-config": "0.1.1",
|
|
40
40
|
"@yuva-devlab/typescript-config": "0.1.1"
|
|
41
41
|
},
|
|
42
42
|
"scripts": {
|