@yuva-devlab/auth-server 0.2.0 → 1.0.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 +219 -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 +214 -63
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var crypto = require('crypto');
|
|
3
4
|
var errors = require('@yuva-devlab/errors');
|
|
4
5
|
var logger$1 = require('@yuva-devlab/logger');
|
|
5
6
|
|
|
7
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
|
+
|
|
9
|
+
var crypto__default = /*#__PURE__*/_interopDefault(crypto);
|
|
10
|
+
|
|
6
11
|
// src/constants/auth.constants.ts
|
|
7
12
|
var DEFAULT_AUTH_HEADER = "authorization";
|
|
8
13
|
var DEFAULT_API_KEY_HEADER = "x-api-key";
|
|
9
14
|
var DEFAULT_BEARER_PREFIX = "Bearer ";
|
|
10
15
|
var DEFAULT_JWKS_CACHE_TTL_MS = 36e5;
|
|
16
|
+
var DEFAULT_API_KEY_CACHE_TTL_MS = 3e5;
|
|
11
17
|
var DEFAULT_PUBLIC_PATHS = Object.freeze([
|
|
12
18
|
"/health",
|
|
13
19
|
"/ready",
|
|
@@ -32,32 +38,19 @@ var JwksValidator = class {
|
|
|
32
38
|
issuer;
|
|
33
39
|
cacheTtlMs;
|
|
34
40
|
keyCache = /* @__PURE__ */ new Map();
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
* @param config - JWKS configuration parameters
|
|
39
|
-
*/
|
|
40
|
-
constructor(config) {
|
|
41
|
-
this.jwksUri = config.jwksUri;
|
|
41
|
+
jwksSetCache = null;
|
|
42
|
+
constructor(config = {}) {
|
|
43
|
+
this.jwksUri = config.jwksUri ?? (config.issuer ? `${config.issuer}/.well-known/jwks.json` : void 0) ?? (typeof process !== "undefined" ? process.env?.DEVLAB_PORTAL_API_URL ? `${process.env.DEVLAB_PORTAL_API_URL}/.well-known/jwks.json` : void 0 : void 0) ?? "";
|
|
42
44
|
this.audience = config.audience;
|
|
43
45
|
this.issuer = config.issuer;
|
|
44
46
|
this.cacheTtlMs = config.cacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;
|
|
45
|
-
logger.debug("[constructor] JwksValidator initialized", {
|
|
46
|
-
jwksUri: this.jwksUri,
|
|
47
|
-
issuer: this.issuer,
|
|
48
|
-
audience: this.audience
|
|
49
|
-
});
|
|
50
47
|
}
|
|
51
|
-
/**
|
|
52
|
-
* Decodes a JWT token without verifying cryptographic signature.
|
|
53
|
-
*
|
|
54
|
-
* @param token - Base64Url encoded JWT string
|
|
55
|
-
* @returns Header and payload objects
|
|
56
|
-
*/
|
|
57
48
|
parseUnverified(token) {
|
|
58
49
|
const parts = token.split(".");
|
|
59
50
|
if (parts.length !== 3) {
|
|
60
|
-
throw new errors.UnauthorizedError(
|
|
51
|
+
throw new errors.UnauthorizedError(
|
|
52
|
+
"Malformed JWT token format: expected 3 segments"
|
|
53
|
+
);
|
|
61
54
|
}
|
|
62
55
|
try {
|
|
63
56
|
const header = JSON.parse(
|
|
@@ -66,68 +59,230 @@ var JwksValidator = class {
|
|
|
66
59
|
const payload = JSON.parse(
|
|
67
60
|
Buffer.from(parts[1], "base64url").toString("utf-8")
|
|
68
61
|
);
|
|
69
|
-
return {
|
|
62
|
+
return {
|
|
63
|
+
header,
|
|
64
|
+
payload,
|
|
65
|
+
rawHeader: parts[0],
|
|
66
|
+
rawPayload: parts[1],
|
|
67
|
+
signature: parts[2]
|
|
68
|
+
};
|
|
70
69
|
} catch {
|
|
71
|
-
throw new errors.UnauthorizedError("Unable to decode JWT payload");
|
|
70
|
+
throw new errors.UnauthorizedError("Unable to decode JWT header or payload");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async fetchJwks() {
|
|
74
|
+
if (!this.jwksUri) {
|
|
75
|
+
throw new errors.UnauthorizedError(
|
|
76
|
+
"JwksValidator: jwksUri, issuer, or DEVLAB_PORTAL_API_URL must be configured"
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
const now = Date.now();
|
|
80
|
+
if (this.jwksSetCache && this.jwksSetCache.expiresAt > now) {
|
|
81
|
+
return this.jwksSetCache.keys;
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
const res = await fetch(this.jwksUri, {
|
|
85
|
+
headers: { Accept: "application/json" },
|
|
86
|
+
signal: AbortSignal.timeout(5e3)
|
|
87
|
+
});
|
|
88
|
+
if (!res.ok) {
|
|
89
|
+
throw new Error(`JWKS endpoint returned HTTP ${res.status}`);
|
|
90
|
+
}
|
|
91
|
+
const body = await res.json();
|
|
92
|
+
const keys = body.keys ?? [];
|
|
93
|
+
this.jwksSetCache = { keys, expiresAt: now + this.cacheTtlMs };
|
|
94
|
+
return keys;
|
|
95
|
+
} catch (err) {
|
|
96
|
+
logger.error("[fetchJwks] Failed to fetch JWKS public keys", {
|
|
97
|
+
uri: this.jwksUri,
|
|
98
|
+
err
|
|
99
|
+
});
|
|
100
|
+
if (this.jwksSetCache?.keys) return this.jwksSetCache.keys;
|
|
101
|
+
throw new errors.UnauthorizedError("Authentication service JWKS unreachable");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async resolveKeyObject(kid) {
|
|
105
|
+
const now = Date.now();
|
|
106
|
+
const cacheKey = kid ?? "__default__";
|
|
107
|
+
const cached = this.keyCache.get(cacheKey);
|
|
108
|
+
if (cached && cached.expiresAt > now) {
|
|
109
|
+
return cached.keyObject;
|
|
110
|
+
}
|
|
111
|
+
const jwks = await this.fetchJwks();
|
|
112
|
+
const matched = kid ? jwks.find((k) => k.kid === kid) : jwks[0];
|
|
113
|
+
if (!matched) {
|
|
114
|
+
throw new errors.UnauthorizedError(
|
|
115
|
+
`No matching JWK public key found for kid: ${kid ?? "default"}`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
const keyObject = crypto__default.default.createPublicKey({
|
|
120
|
+
key: matched,
|
|
121
|
+
format: "jwk"
|
|
122
|
+
});
|
|
123
|
+
this.keyCache.set(cacheKey, {
|
|
124
|
+
keyObject,
|
|
125
|
+
expiresAt: now + this.cacheTtlMs
|
|
126
|
+
});
|
|
127
|
+
return keyObject;
|
|
128
|
+
} catch (err) {
|
|
129
|
+
logger.error("[resolveKeyObject] Failed to parse JWK public key", {
|
|
130
|
+
kid,
|
|
131
|
+
err
|
|
132
|
+
});
|
|
133
|
+
throw new errors.UnauthorizedError("Invalid JWK public key format");
|
|
72
134
|
}
|
|
73
135
|
}
|
|
74
|
-
/**
|
|
75
|
-
* Verifies standard claims (exp, nbf, iss, aud) on a JWT token.
|
|
76
|
-
*
|
|
77
|
-
* @param token - Bearer access token
|
|
78
|
-
* @returns Validated JwtPayload claims
|
|
79
|
-
*/
|
|
80
136
|
async verifyToken(token) {
|
|
81
|
-
const { payload } = this.parseUnverified(token);
|
|
137
|
+
const { header, payload, rawHeader, rawPayload, signature } = this.parseUnverified(token);
|
|
138
|
+
if (header.alg && header.alg !== "RS256") {
|
|
139
|
+
throw new errors.UnauthorizedError(
|
|
140
|
+
`Unsupported signing algorithm: ${header.alg}. Expected RS256`
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
const kid = typeof header.kid === "string" ? header.kid : void 0;
|
|
144
|
+
const keyObject = await this.resolveKeyObject(kid);
|
|
145
|
+
const data = Buffer.from(`${rawHeader}.${rawPayload}`);
|
|
146
|
+
const sigBuffer = Buffer.from(signature, "base64url");
|
|
147
|
+
const isSignatureValid = crypto__default.default.verify(
|
|
148
|
+
"RSA-SHA256",
|
|
149
|
+
data,
|
|
150
|
+
keyObject,
|
|
151
|
+
sigBuffer
|
|
152
|
+
);
|
|
153
|
+
if (!isSignatureValid) {
|
|
154
|
+
logger.warn("[verifyToken] Cryptographic signature check failed", {
|
|
155
|
+
sub: payload.sub,
|
|
156
|
+
kid
|
|
157
|
+
});
|
|
158
|
+
throw new errors.UnauthorizedError("Invalid token signature");
|
|
159
|
+
}
|
|
82
160
|
const nowSeconds = Math.floor(Date.now() / 1e3);
|
|
83
161
|
if (typeof payload.exp === "number" && nowSeconds >= payload.exp) {
|
|
84
|
-
logger.warn("[verifyToken] Token has expired", {
|
|
85
|
-
exp: payload.exp,
|
|
86
|
-
now: nowSeconds
|
|
87
|
-
});
|
|
88
162
|
throw new errors.UnauthorizedError("Authentication token has expired");
|
|
89
163
|
}
|
|
90
164
|
if (typeof payload.nbf === "number" && nowSeconds < payload.nbf) {
|
|
91
|
-
logger.warn("[verifyToken] Token not yet valid", {
|
|
92
|
-
nbf: payload.nbf,
|
|
93
|
-
now: nowSeconds
|
|
94
|
-
});
|
|
95
165
|
throw new errors.UnauthorizedError("Authentication token is not yet active");
|
|
96
166
|
}
|
|
97
167
|
if (this.issuer && payload.iss && payload.iss !== this.issuer) {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
});
|
|
102
|
-
throw new errors.UnauthorizedError("Token issuer mismatch");
|
|
168
|
+
throw new errors.UnauthorizedError(
|
|
169
|
+
`Token issuer mismatch: expected ${this.issuer}, got ${payload.iss}`
|
|
170
|
+
);
|
|
103
171
|
}
|
|
104
172
|
if (this.audience && payload.aud) {
|
|
105
173
|
const audList = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
106
174
|
if (!audList.includes(this.audience)) {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
});
|
|
111
|
-
throw new errors.UnauthorizedError("Token audience mismatch");
|
|
175
|
+
throw new errors.UnauthorizedError(
|
|
176
|
+
`Token audience mismatch: expected ${this.audience}`
|
|
177
|
+
);
|
|
112
178
|
}
|
|
113
179
|
}
|
|
114
|
-
logger.debug("[verifyToken] Successfully validated token claims", {
|
|
115
|
-
sub: payload.sub
|
|
116
|
-
});
|
|
117
180
|
return payload;
|
|
118
181
|
}
|
|
119
|
-
/**
|
|
120
|
-
* Clears cached public keys from memory.
|
|
121
|
-
*/
|
|
122
182
|
clearKeyCache() {
|
|
123
183
|
this.keyCache.clear();
|
|
184
|
+
this.jwksSetCache = null;
|
|
124
185
|
logger.info("[clearKeyCache] JWKS public key cache cleared");
|
|
125
186
|
}
|
|
126
187
|
};
|
|
127
|
-
var logger2 = logger$1.loggerWithConfig(new logger$1.Logger("
|
|
188
|
+
var logger2 = logger$1.loggerWithConfig(new logger$1.Logger("M2mApiKeyValidator"));
|
|
189
|
+
var M2mApiKeyValidator = class {
|
|
190
|
+
authUrl;
|
|
191
|
+
cacheTtlMs;
|
|
192
|
+
requiredClientId;
|
|
193
|
+
requiredScopes;
|
|
194
|
+
keyCache = /* @__PURE__ */ new Map();
|
|
195
|
+
constructor(config = {}) {
|
|
196
|
+
this.authUrl = config.authUrl ?? config.portalUrl ?? process.env.DEVLAB_PORTAL_API_URL;
|
|
197
|
+
this.cacheTtlMs = config.cacheTtlMs ?? DEFAULT_API_KEY_CACHE_TTL_MS;
|
|
198
|
+
this.requiredClientId = config.requiredClientId ?? config.requiredAppId;
|
|
199
|
+
this.requiredScopes = config.requiredScopes;
|
|
200
|
+
}
|
|
201
|
+
async validateKey(rawKey) {
|
|
202
|
+
const trimmed = rawKey.trim();
|
|
203
|
+
if (!trimmed.startsWith("dlk_")) {
|
|
204
|
+
throw new errors.UnauthorizedError("Malformed API key: expected 'dlk_' prefix");
|
|
205
|
+
}
|
|
206
|
+
if (!this.authUrl) {
|
|
207
|
+
throw new errors.UnauthorizedError(
|
|
208
|
+
"M2mApiKeyValidator: authUrl or DEVLAB_PORTAL_API_URL must be configured for validation"
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
const now = Date.now();
|
|
212
|
+
const cached = this.keyCache.get(trimmed);
|
|
213
|
+
if (cached && cached.expiresAt > now) {
|
|
214
|
+
return this.enforceKeyConstraints(cached.result);
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
const url = `${this.authUrl}/api/v1/api-keys/validate`;
|
|
218
|
+
const res = await fetch(url, {
|
|
219
|
+
headers: {
|
|
220
|
+
Accept: "application/json",
|
|
221
|
+
Authorization: `Bearer ${trimmed}`
|
|
222
|
+
},
|
|
223
|
+
signal: AbortSignal.timeout(5e3)
|
|
224
|
+
});
|
|
225
|
+
if (!res.ok) {
|
|
226
|
+
throw new Error(
|
|
227
|
+
`Authentication validation endpoint returned HTTP ${res.status}`
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
const body = await res.json();
|
|
231
|
+
if (!body.valid) {
|
|
232
|
+
throw new errors.UnauthorizedError(body.reason ?? "Invalid machine API key");
|
|
233
|
+
}
|
|
234
|
+
this.keyCache.set(trimmed, {
|
|
235
|
+
result: body,
|
|
236
|
+
expiresAt: now + this.cacheTtlMs
|
|
237
|
+
});
|
|
238
|
+
return this.enforceKeyConstraints(body);
|
|
239
|
+
} catch (err) {
|
|
240
|
+
if (err instanceof errors.UnauthorizedError || err instanceof errors.ForbiddenError) {
|
|
241
|
+
throw err;
|
|
242
|
+
}
|
|
243
|
+
logger2.error("[validateKey] Network error during API key introspection", {
|
|
244
|
+
err
|
|
245
|
+
});
|
|
246
|
+
throw new errors.UnauthorizedError(
|
|
247
|
+
"Authentication service unreachable for API key verification"
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
enforceKeyConstraints(result) {
|
|
252
|
+
if (this.requiredClientId && result.appId && result.appId !== this.requiredClientId) {
|
|
253
|
+
const keyScopes = result.scopes ?? [];
|
|
254
|
+
const hasWildcard = keyScopes.includes("*") || keyScopes.includes(`${this.requiredClientId}:*`) || keyScopes.includes(this.requiredClientId);
|
|
255
|
+
if (!hasWildcard) {
|
|
256
|
+
throw new errors.ForbiddenError(
|
|
257
|
+
"API key assigned to " + result.appId + ", required " + this.requiredClientId
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (this.requiredScopes && this.requiredScopes.length > 0) {
|
|
262
|
+
const keyScopes = result.scopes ?? [];
|
|
263
|
+
const hasWildcard = keyScopes.includes("*");
|
|
264
|
+
if (!hasWildcard) {
|
|
265
|
+
const hasAll = this.requiredScopes.every(
|
|
266
|
+
(scope) => keyScopes.includes(scope)
|
|
267
|
+
);
|
|
268
|
+
if (!hasAll) {
|
|
269
|
+
throw new errors.ForbiddenError(
|
|
270
|
+
"API key lacks required scopes: [" + this.requiredScopes.join(", ") + "]"
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return result;
|
|
276
|
+
}
|
|
277
|
+
clearCache() {
|
|
278
|
+
this.keyCache.clear();
|
|
279
|
+
logger2.info("[clearCache] API key validation cache cleared");
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
var logger3 = logger$1.loggerWithConfig(new logger$1.Logger("AuthGuards"));
|
|
128
283
|
function requireUser(ctx, requiredRoles) {
|
|
129
284
|
if (!ctx.authenticated || !ctx.user) {
|
|
130
|
-
|
|
285
|
+
logger3.warn(
|
|
131
286
|
"[requireUser] Request rejected: missing authenticated user context"
|
|
132
287
|
);
|
|
133
288
|
throw new errors.UnauthorizedError(
|
|
@@ -137,7 +292,7 @@ function requireUser(ctx, requiredRoles) {
|
|
|
137
292
|
if (requiredRoles && requiredRoles.length > 0) {
|
|
138
293
|
const hasRole = requiredRoles.some((role) => ctx.roles.includes(role));
|
|
139
294
|
if (!hasRole) {
|
|
140
|
-
|
|
295
|
+
logger3.warn("[requireUser] User lacks required roles", {
|
|
141
296
|
userId: ctx.user.id,
|
|
142
297
|
userRoles: ctx.roles,
|
|
143
298
|
requiredRoles
|
|
@@ -151,7 +306,7 @@ function requireUser(ctx, requiredRoles) {
|
|
|
151
306
|
}
|
|
152
307
|
function requireApiKey(ctx) {
|
|
153
308
|
if (!ctx.authenticated || !ctx.apiKey) {
|
|
154
|
-
|
|
309
|
+
logger3.warn("[requireApiKey] Request rejected: missing machine API key");
|
|
155
310
|
throw new errors.UnauthorizedError(
|
|
156
311
|
"Authentication required: valid API key required"
|
|
157
312
|
);
|
|
@@ -160,19 +315,19 @@ function requireApiKey(ctx) {
|
|
|
160
315
|
}
|
|
161
316
|
function requireScope(ctx, scope) {
|
|
162
317
|
if (!ctx.roles.includes(scope)) {
|
|
163
|
-
|
|
318
|
+
logger3.warn("[requireScope] Missing required scope", {
|
|
164
319
|
roles: ctx.roles,
|
|
165
320
|
requiredScope: scope
|
|
166
321
|
});
|
|
167
322
|
throw new errors.ForbiddenError(`Missing required scope: '${scope}'`);
|
|
168
323
|
}
|
|
169
324
|
}
|
|
170
|
-
var
|
|
325
|
+
var logger4 = logger$1.loggerWithConfig(new logger$1.Logger("AuthMiddleware"));
|
|
171
326
|
function createAppKillSwitchMiddleware(getAppStatus) {
|
|
172
327
|
return async (req, res) => {
|
|
173
328
|
const status = await getAppStatus();
|
|
174
329
|
if (status === "INACTIVE" /* INACTIVE */ || status === "MAINTENANCE" /* MAINTENANCE */) {
|
|
175
|
-
|
|
330
|
+
logger4.warn(
|
|
176
331
|
"[killSwitch] Application is inactive or under maintenance; request rejected",
|
|
177
332
|
{
|
|
178
333
|
url: req.url,
|
|
@@ -216,7 +371,7 @@ function createAuthMiddleware(options) {
|
|
|
216
371
|
if (apiKey && options.validateApiKey) {
|
|
217
372
|
const apiKeyCtx = await options.validateApiKey(apiKey);
|
|
218
373
|
if (apiKeyCtx?.authenticated) {
|
|
219
|
-
|
|
374
|
+
logger4.info("[authenticate] Authenticated via API Key", {
|
|
220
375
|
path: urlPath
|
|
221
376
|
});
|
|
222
377
|
req.authContext = apiKeyCtx;
|
|
@@ -229,14 +384,14 @@ function createAuthMiddleware(options) {
|
|
|
229
384
|
const token = authHeader.slice(DEFAULT_BEARER_PREFIX.length).trim();
|
|
230
385
|
const tokenCtx = await options.validateToken(token);
|
|
231
386
|
if (tokenCtx?.authenticated) {
|
|
232
|
-
|
|
387
|
+
logger4.info("[authenticate] Authenticated via Bearer token", {
|
|
233
388
|
path: urlPath
|
|
234
389
|
});
|
|
235
390
|
req.authContext = tokenCtx;
|
|
236
391
|
return true;
|
|
237
392
|
}
|
|
238
393
|
}
|
|
239
|
-
|
|
394
|
+
logger4.warn("[authenticate] Unauthorized request rejected", {
|
|
240
395
|
path: urlPath,
|
|
241
396
|
method: req.method
|
|
242
397
|
});
|
|
@@ -255,6 +410,7 @@ function createAuthMiddleware(options) {
|
|
|
255
410
|
}
|
|
256
411
|
|
|
257
412
|
exports.AppStatus = AppStatus;
|
|
413
|
+
exports.DEFAULT_API_KEY_CACHE_TTL_MS = DEFAULT_API_KEY_CACHE_TTL_MS;
|
|
258
414
|
exports.DEFAULT_API_KEY_HEADER = DEFAULT_API_KEY_HEADER;
|
|
259
415
|
exports.DEFAULT_AUTH_HEADER = DEFAULT_AUTH_HEADER;
|
|
260
416
|
exports.DEFAULT_BEARER_PREFIX = DEFAULT_BEARER_PREFIX;
|
|
@@ -264,6 +420,7 @@ exports.HTTP_STATUS_FORBIDDEN = HTTP_STATUS_FORBIDDEN;
|
|
|
264
420
|
exports.HTTP_STATUS_SERVICE_UNAVAILABLE = HTTP_STATUS_SERVICE_UNAVAILABLE;
|
|
265
421
|
exports.HTTP_STATUS_UNAUTHORIZED = HTTP_STATUS_UNAUTHORIZED;
|
|
266
422
|
exports.JwksValidator = JwksValidator;
|
|
423
|
+
exports.M2mApiKeyValidator = M2mApiKeyValidator;
|
|
267
424
|
exports.createAppKillSwitchMiddleware = createAppKillSwitchMiddleware;
|
|
268
425
|
exports.createAuthMiddleware = createAuthMiddleware;
|
|
269
426
|
exports.requireApiKey = requireApiKey;
|
package/dist/index.cjs.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.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CAAW,KAAA,CAAM,qBAAA,CAAsB,MAAM,EAAE,IAAA,EAAK;AAClE,MAAA,MAAM,QAAA,GAAW,MAAM,OAAA,CAAQ,aAAA,CAAc,KAAK,CAAA;AAClD,MAAA,IAAI,UAAU,aAAA,EAAe;AAC3B,QAAAA,OAAAA,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.cjs","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","loggerWithConfig","Logger","UnauthorizedError","crypto","logger","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,QAAA,CAAA,GAAS,QAAA;AAET,EAAAA,WAAA,UAAA,CAAA,GAAW,UAAA;AAEX,EAAAA,WAAA,aAAA,CAAA,GAAc,aAAA;AANJ,EAAA,OAAAA,UAAAA;AAAA,CAAA,EAAA,SAAA,IAAA,EAAA;ACGZ,IAAM,MAAA,GAASC,yBAAA,CAAiB,IAAIC,eAAA,CAAO,eAAe,CAAC,CAAA;AAkBpD,IAAM,gBAAN,MAAoB;AAAA,EACR,OAAA;AAAA,EACA,QAAA;AAAA,EACA,MAAA;AAAA,EACA,UAAA;AAAA,EACT,QAAA,uBAAe,GAAA,EAAuB;AAAA,EACtC,YAAA,GAGG,IAAA;AAAA,EAEJ,WAAA,CAAY,MAAA,GAA8B,EAAC,EAAG;AACnD,IAAA,IAAA,CAAK,OAAA,GACH,OAAO,OAAA,KACN,MAAA,CAAO,SAAS,CAAA,EAAG,MAAA,CAAO,MAAM,CAAA,sBAAA,CAAA,GAA2B,MAAA,CAAA,KAC3D,OAAO,YAAY,WAAA,GAChB,OAAA,CAAQ,KAAK,qBAAA,GACX,CAAA,EAAG,QAAQ,GAAA,CAAI,qBAAqB,CAAA,sBAAA,CAAA,GAC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AAM,cAAA;AAAA,UACN,OAAA,EACE;AAAA;AACJ,OACD;AAAA,KACH;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF","file":"index.cjs","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_PORTAL_API_URL\n ? `${process.env.DEVLAB_PORTAL_API_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_PORTAL_API_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 ?? config.portalUrl ?? process.env.DEVLAB_PORTAL_API_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_PORTAL_API_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 const keyScopes = result.scopes ?? [];\n const hasWildcard =\n keyScopes.includes(\"*\") ||\n keyScopes.includes(`${this.requiredClientId}:*`) ||\n keyScopes.includes(this.requiredClientId);\n if (!hasWildcard) {\n throw new ForbiddenError(\n \"API key assigned to \" +\n result.appId +\n \", required \" +\n this.requiredClientId,\n );\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"]}
|