@bymax-one/nest-logger 1.4.11 → 1.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -1
- package/README.md +16 -0
- package/dist/server/index.cjs +652 -527
- package/dist/server/index.d.cts +46 -2
- package/dist/server/index.d.ts +46 -2
- package/dist/server/index.mjs +652 -527
- package/package.json +2 -1
package/dist/server/index.cjs
CHANGED
|
@@ -4,12 +4,12 @@ var common = require('@nestjs/common');
|
|
|
4
4
|
var core = require('@nestjs/core');
|
|
5
5
|
var util = require('util');
|
|
6
6
|
var rxjs = require('rxjs');
|
|
7
|
+
var crypto = require('crypto');
|
|
8
|
+
var async_hooks = require('async_hooks');
|
|
7
9
|
var pino = require('pino');
|
|
8
10
|
var module$1 = require('module');
|
|
9
11
|
var path = require('path');
|
|
10
12
|
var stream = require('stream');
|
|
11
|
-
var async_hooks = require('async_hooks');
|
|
12
|
-
var crypto = require('crypto');
|
|
13
13
|
|
|
14
14
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
15
15
|
|
|
@@ -965,6 +965,23 @@ exports.DefaultStdoutDestination = __decorateClass([
|
|
|
965
965
|
common.Injectable()
|
|
966
966
|
], exports.DefaultStdoutDestination);
|
|
967
967
|
|
|
968
|
+
// src/server/utils/exposed-client-error.util.ts
|
|
969
|
+
var MIN_CLIENT_STATUS = 400;
|
|
970
|
+
var MAX_CLIENT_STATUS = 499;
|
|
971
|
+
function readExposedClientError(value) {
|
|
972
|
+
try {
|
|
973
|
+
const candidate = value;
|
|
974
|
+
const status = candidate.status ?? candidate.statusCode;
|
|
975
|
+
const message = value.message;
|
|
976
|
+
const isClientStatus = typeof status === "number" && Number.isInteger(status) && status >= MIN_CLIENT_STATUS && status <= MAX_CLIENT_STATUS;
|
|
977
|
+
if (candidate.expose !== true || !isClientStatus || typeof message !== "string")
|
|
978
|
+
return void 0;
|
|
979
|
+
return { status, message };
|
|
980
|
+
} catch {
|
|
981
|
+
return void 0;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
|
|
968
985
|
// src/server/utils/normalize-url.util.ts
|
|
969
986
|
var UUID_REGEX = /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?![0-9a-f])/gi;
|
|
970
987
|
var ULID_REGEX = /\/[0-9A-HJKMNP-TV-Z]{26}(?![0-9A-HJKMNP-TV-Z])/g;
|
|
@@ -1007,9 +1024,9 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
|
|
|
1007
1024
|
const userId = req.user?.sub ?? req.user?.id;
|
|
1008
1025
|
const url = stripQueryString(req.url);
|
|
1009
1026
|
if (exception instanceof common.HttpException) {
|
|
1010
|
-
const
|
|
1011
|
-
const metadata = { method: req.method, url, status
|
|
1012
|
-
if (
|
|
1027
|
+
const status = exception.getStatus();
|
|
1028
|
+
const metadata = { method: req.method, url, status };
|
|
1029
|
+
if (status >= common.HttpStatus.INTERNAL_SERVER_ERROR) {
|
|
1013
1030
|
this.logger.errorStructured(
|
|
1014
1031
|
RESERVED_LOG_KEYS.HTTP_EXCEPTION_UNHANDLED,
|
|
1015
1032
|
sanitizeError(exception),
|
|
@@ -1024,19 +1041,51 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
|
|
|
1024
1041
|
metadata
|
|
1025
1042
|
);
|
|
1026
1043
|
}
|
|
1027
|
-
res.status(
|
|
1044
|
+
res.status(status).json(exception.getResponse());
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
const clientError = readExposedClientError(exception);
|
|
1048
|
+
if (clientError !== void 0) {
|
|
1049
|
+
this.answerClientError(clientError, res, { method: req.method, url, userId });
|
|
1028
1050
|
return;
|
|
1029
1051
|
}
|
|
1052
|
+
this.answerUnhandled(exception, res, { method: req.method, url, userId });
|
|
1053
|
+
}
|
|
1054
|
+
/**
|
|
1055
|
+
* Log an exposed client error as handled and answer it with its own status and message.
|
|
1056
|
+
*
|
|
1057
|
+
* @param clientError - The status and message the error exposes.
|
|
1058
|
+
* @param res - The response to write.
|
|
1059
|
+
* @param request - The request facts every entry carries.
|
|
1060
|
+
*/
|
|
1061
|
+
answerClientError(clientError, res, request) {
|
|
1062
|
+
const { method, url, userId } = request;
|
|
1063
|
+
this.logger.warnStructured(
|
|
1064
|
+
RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
|
|
1065
|
+
clientError.message,
|
|
1066
|
+
userId,
|
|
1067
|
+
{ method, url, status: clientError.status }
|
|
1068
|
+
);
|
|
1069
|
+
res.status(clientError.status).json({
|
|
1070
|
+
statusCode: clientError.status,
|
|
1071
|
+
message: clientError.message
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* Log any other non-`HttpException` as unhandled and answer it with the fixed 500 body.
|
|
1076
|
+
*
|
|
1077
|
+
* @param exception - The thrown value.
|
|
1078
|
+
* @param res - The response to write.
|
|
1079
|
+
* @param request - The request facts every entry carries.
|
|
1080
|
+
*/
|
|
1081
|
+
answerUnhandled(exception, res, request) {
|
|
1082
|
+
const { method, url, userId } = request;
|
|
1030
1083
|
const status = common.HttpStatus.INTERNAL_SERVER_ERROR;
|
|
1031
1084
|
this.logger.errorStructured(
|
|
1032
1085
|
RESERVED_LOG_KEYS.HTTP_EXCEPTION_UNHANDLED,
|
|
1033
1086
|
sanitizeError(exception),
|
|
1034
1087
|
userId,
|
|
1035
|
-
{
|
|
1036
|
-
method: req.method,
|
|
1037
|
-
url,
|
|
1038
|
-
status
|
|
1039
|
-
}
|
|
1088
|
+
{ method, url, status }
|
|
1040
1089
|
);
|
|
1041
1090
|
res.status(status).json(INTERNAL_ERROR_BODY);
|
|
1042
1091
|
}
|
|
@@ -1217,8 +1266,8 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1217
1266
|
}
|
|
1218
1267
|
/**
|
|
1219
1268
|
* Log a thrown completion: SERVER_ERROR (error level, with stack) for 5xx,
|
|
1220
|
-
* CLIENT_ERROR (warn level) for an `HttpException` below 500
|
|
1221
|
-
*
|
|
1269
|
+
* CLIENT_ERROR (warn level) for an `HttpException` below 500 or an exposed `http-errors`
|
|
1270
|
+
* client error. Any other non-`HttpException` maps to 500, so it is reported as a server error.
|
|
1222
1271
|
*
|
|
1223
1272
|
* @param err - The thrown value (anything).
|
|
1224
1273
|
* @param method - The HTTP method.
|
|
@@ -1246,6 +1295,11 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1246
1295
|
}
|
|
1247
1296
|
return;
|
|
1248
1297
|
}
|
|
1298
|
+
const clientError = readExposedClientError(err);
|
|
1299
|
+
if (clientError !== void 0) {
|
|
1300
|
+
this.logClientError(clientError, method, url, userId, duration);
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1249
1303
|
this.logger.errorStructured(RESERVED_LOG_KEYS.HTTP_REQUEST_SERVER_ERROR, toError(err), userId, {
|
|
1250
1304
|
method,
|
|
1251
1305
|
url,
|
|
@@ -1253,6 +1307,29 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1253
1307
|
duration
|
|
1254
1308
|
});
|
|
1255
1309
|
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Log an exposed `http-errors` client error as CLIENT_ERROR at warn level.
|
|
1312
|
+
*
|
|
1313
|
+
* @param clientError - The status and message the error exposes.
|
|
1314
|
+
* @param method - The HTTP method.
|
|
1315
|
+
* @param url - The normalized request URL.
|
|
1316
|
+
* @param userId - The acting user id, when known.
|
|
1317
|
+
* @param duration - The elapsed time in milliseconds.
|
|
1318
|
+
*/
|
|
1319
|
+
logClientError(clientError, method, url, userId, duration) {
|
|
1320
|
+
this.logger.warnStructured(
|
|
1321
|
+
RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
|
|
1322
|
+
`${method} ${url} \u2192 ${clientError.status}`,
|
|
1323
|
+
userId,
|
|
1324
|
+
{
|
|
1325
|
+
method,
|
|
1326
|
+
url,
|
|
1327
|
+
statusCode: clientError.status,
|
|
1328
|
+
duration,
|
|
1329
|
+
errorMessage: cutIfText(clientError.message)
|
|
1330
|
+
}
|
|
1331
|
+
);
|
|
1332
|
+
}
|
|
1256
1333
|
};
|
|
1257
1334
|
exports.HttpLoggingInterceptor = __decorateClass([
|
|
1258
1335
|
common.Injectable(),
|
|
@@ -1286,146 +1363,443 @@ var {
|
|
|
1286
1363
|
// disabled" without a dead nullish branch.
|
|
1287
1364
|
global: extras.isGlobal !== false
|
|
1288
1365
|
})).build();
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
{ length: REDACT_MAX_DEPTH },
|
|
1294
|
-
(_, idx) => "*" + ".*".repeat(idx)
|
|
1295
|
-
);
|
|
1296
|
-
var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
|
|
1297
|
-
var REDACT_COMMON_FIELDS = [
|
|
1298
|
-
// Passwords (5)
|
|
1299
|
-
"password",
|
|
1300
|
-
"passwordHash",
|
|
1301
|
-
"passwordConfirm",
|
|
1302
|
-
"newPassword",
|
|
1303
|
-
"oldPassword",
|
|
1304
|
-
// Tokens (6)
|
|
1305
|
-
"token",
|
|
1306
|
-
"accessToken",
|
|
1307
|
-
"refreshToken",
|
|
1308
|
-
"idToken",
|
|
1309
|
-
"apiKey",
|
|
1310
|
-
"apiSecret",
|
|
1311
|
-
// MFA (3)
|
|
1312
|
-
"mfaSecret",
|
|
1313
|
-
"mfaRecoveryCodes",
|
|
1314
|
-
"totpSecret",
|
|
1315
|
-
// Payment / PCI DSS (5)
|
|
1316
|
-
"cardNumber",
|
|
1317
|
-
"cardCvv",
|
|
1318
|
-
"cvv",
|
|
1319
|
-
"cvc",
|
|
1320
|
-
"cardExpiry",
|
|
1321
|
-
// Personal documents — BR / LGPD (3)
|
|
1322
|
-
"cpf",
|
|
1323
|
-
"cnpj",
|
|
1324
|
-
"rg",
|
|
1325
|
-
// Generic secrets (4) — the most common short-form credential field names
|
|
1326
|
-
"secret",
|
|
1327
|
-
"clientSecret",
|
|
1328
|
-
"signingSecret",
|
|
1329
|
-
"privateKey",
|
|
1330
|
-
// Conservative PII (1) — consumer can disable if logging email is justified
|
|
1331
|
-
"email",
|
|
1332
|
-
// Credential-bearing HTTP header names (5). These also appear in
|
|
1333
|
-
// {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
|
|
1334
|
-
// shapes — which covered ONLY those two shapes. A headers bag logged under any
|
|
1335
|
-
// other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
|
|
1336
|
-
// common things written while debugging an integration) wrote the bearer token
|
|
1337
|
-
// in clear. Listed here as bare names, they are caught wherever they appear.
|
|
1338
|
-
// Node lower-cases inbound header names, so the lower-case spelling is the one
|
|
1339
|
-
// that can actually reach a log.
|
|
1340
|
-
"authorization",
|
|
1341
|
-
"cookie",
|
|
1342
|
-
"set-cookie",
|
|
1343
|
-
"x-api-key",
|
|
1344
|
-
"x-auth-token"
|
|
1345
|
-
];
|
|
1346
|
-
var REDACT_ABSOLUTE_PATHS = [
|
|
1347
|
-
"req.headers.authorization",
|
|
1348
|
-
"req.headers.cookie",
|
|
1349
|
-
'req.headers["x-api-key"]',
|
|
1350
|
-
'req.headers["x-auth-token"]',
|
|
1351
|
-
'res.headers["set-cookie"]'
|
|
1352
|
-
];
|
|
1353
|
-
var DEFAULT_REDACT_PATHS = [
|
|
1354
|
-
...REDACT_COMMON_FIELDS,
|
|
1355
|
-
...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
|
|
1356
|
-
...REDACT_ABSOLUTE_PATHS
|
|
1357
|
-
];
|
|
1358
|
-
|
|
1359
|
-
// src/server/utils/report-destination-failure.util.ts
|
|
1360
|
-
function reportDestinationFailure(logKey, name, cause, msg) {
|
|
1361
|
-
writeStderrSafely(
|
|
1362
|
-
JSON.stringify({
|
|
1363
|
-
level: "error",
|
|
1364
|
-
logKey,
|
|
1365
|
-
destination: toSingleLineMessage(name),
|
|
1366
|
-
err: describeCause(cause),
|
|
1367
|
-
msg: toSingleLineMessage(msg)
|
|
1368
|
-
}) + "\n"
|
|
1369
|
-
);
|
|
1370
|
-
}
|
|
1371
|
-
var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
|
|
1372
|
-
function describeCause(cause) {
|
|
1373
|
-
try {
|
|
1374
|
-
return isError(cause) ? {
|
|
1375
|
-
type: toBoundedMessage(String(cause.name)),
|
|
1376
|
-
message: toBoundedMessage(String(cause.message))
|
|
1377
|
-
} : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
|
|
1378
|
-
} catch {
|
|
1379
|
-
return UNREADABLE_CAUSE;
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
function safeDestinationName(destination) {
|
|
1383
|
-
try {
|
|
1384
|
-
return String(destination.name);
|
|
1385
|
-
} catch {
|
|
1386
|
-
return "unknown";
|
|
1387
|
-
}
|
|
1388
|
-
}
|
|
1389
|
-
function isLogLevel(value) {
|
|
1390
|
-
return LOG_LEVEL_PRIORITY.includes(value);
|
|
1391
|
-
}
|
|
1392
|
-
var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
|
|
1393
|
-
function safeMinLevel(destination) {
|
|
1394
|
-
if (resolvedMinLevels.has(destination)) {
|
|
1395
|
-
return resolvedMinLevels.get(destination);
|
|
1366
|
+
var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
|
|
1367
|
+
exports.LogContextService = class LogContextService {
|
|
1368
|
+
constructor() {
|
|
1369
|
+
this.als = new async_hooks.AsyncLocalStorage();
|
|
1396
1370
|
}
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1371
|
+
/**
|
|
1372
|
+
* Run `callback` inside a fresh context scope. Every log emitted
|
|
1373
|
+
* synchronously or asynchronously within the callback inherits `context`.
|
|
1374
|
+
*
|
|
1375
|
+
* **A nested `run()` REPLACES the enclosing context, it does not extend it.**
|
|
1376
|
+
* The scope starts from `context` alone, so a field an outer scope had set —
|
|
1377
|
+
* a `tenantId` resolved at the edge, say — is absent for the whole inner
|
|
1378
|
+
* scope: nothing throws, `get()` simply returns `undefined`, and the field is
|
|
1379
|
+
* missing from every entry the callback emits. Reach for {@link runMerged}
|
|
1380
|
+
* when the inner scope should extend the outer one.
|
|
1381
|
+
*
|
|
1382
|
+
* Replacement is the deliberate default because the opposite leaks: a
|
|
1383
|
+
* background job started inside a request scope would silently inherit the
|
|
1384
|
+
* caller's `userId` and attribute its entries to a user who never triggered
|
|
1385
|
+
* it. A missing field is visibly missing; an inherited one is wrong while
|
|
1386
|
+
* looking right.
|
|
1387
|
+
*
|
|
1388
|
+
* @typeParam T - Return type of the callback.
|
|
1389
|
+
* @param context - Initial context bag for the scope. Becomes the WHOLE scope.
|
|
1390
|
+
* @param callback - Function executed within the scope.
|
|
1391
|
+
* @returns Whatever `callback` returns.
|
|
1392
|
+
* @example
|
|
1393
|
+
* logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
|
|
1394
|
+
* await userService.create(dto) // logs carry requestId + tenantId
|
|
1395
|
+
* })
|
|
1396
|
+
*/
|
|
1397
|
+
run(context, callback) {
|
|
1398
|
+
return this.als.run(this.sanitizeContext(context), callback);
|
|
1402
1399
|
}
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1400
|
+
/**
|
|
1401
|
+
* Run `callback` inside a scope that EXTENDS the enclosing one: the active
|
|
1402
|
+
* context's fields are carried in, and `context` overrides them key by key.
|
|
1403
|
+
*
|
|
1404
|
+
* The explicit counterpart to {@link run}'s replacement semantics, for the
|
|
1405
|
+
* case where an inner scope is genuinely a refinement of the outer — adding a
|
|
1406
|
+
* `userId` once authentication resolved it, without having to restate the
|
|
1407
|
+
* `requestId` the middleware already set.
|
|
1408
|
+
*
|
|
1409
|
+
* Outside any scope there is nothing to merge and this behaves exactly like
|
|
1410
|
+
* {@link run}. Writes inside the new scope never reach the enclosing one: the
|
|
1411
|
+
* merge produces a fresh object, so the outer context is intact after the
|
|
1412
|
+
* callback returns.
|
|
1413
|
+
*
|
|
1414
|
+
* @typeParam T - Return type of the callback.
|
|
1415
|
+
* @param context - Fields to add or override on top of the active context.
|
|
1416
|
+
* @param callback - Function executed within the merged scope.
|
|
1417
|
+
* @returns Whatever `callback` returns.
|
|
1418
|
+
* @example
|
|
1419
|
+
* logContext.run({ requestId: 'r_1' }, () => {
|
|
1420
|
+
* logContext.runMerged({ userId: 'u_1' }, () => {
|
|
1421
|
+
* logContext.get('requestId') // 'r_1' — carried in from the outer scope
|
|
1422
|
+
* })
|
|
1423
|
+
* })
|
|
1424
|
+
*/
|
|
1425
|
+
runMerged(context, callback) {
|
|
1426
|
+
const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
|
|
1427
|
+
return this.als.run(merged, callback);
|
|
1415
1428
|
}
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
return
|
|
1429
|
+
/**
|
|
1430
|
+
* Read the active context, or `undefined` when called outside any scope.
|
|
1431
|
+
*
|
|
1432
|
+
* @returns The active `LogContext`, or `undefined`.
|
|
1433
|
+
*/
|
|
1434
|
+
getStore() {
|
|
1435
|
+
return this.als.getStore();
|
|
1423
1436
|
}
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1437
|
+
/**
|
|
1438
|
+
* Add or override a single field on the active context.
|
|
1439
|
+
*
|
|
1440
|
+
* @param key - Field name to set.
|
|
1441
|
+
* @param value - Field value.
|
|
1442
|
+
* @throws Error When called outside a `run()` scope, or with a prototype-polluting key.
|
|
1443
|
+
*/
|
|
1444
|
+
set(key, value) {
|
|
1445
|
+
const store = this.als.getStore();
|
|
1446
|
+
if (!store) {
|
|
1447
|
+
throw new Error("[LogContextService] set() called outside run() scope");
|
|
1448
|
+
}
|
|
1449
|
+
if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
1450
|
+
throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
|
|
1451
|
+
}
|
|
1452
|
+
Reflect.set(store, key, value);
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Read a single field from the active context.
|
|
1456
|
+
*
|
|
1457
|
+
* @typeParam T - Expected value type (caller-asserted).
|
|
1458
|
+
* @param key - Field name to read.
|
|
1459
|
+
* @returns The value cast to `T`, or `undefined` when unset / out of scope.
|
|
1460
|
+
*/
|
|
1461
|
+
get(key) {
|
|
1462
|
+
const store = this.als.getStore();
|
|
1463
|
+
if (!store) {
|
|
1464
|
+
return void 0;
|
|
1465
|
+
}
|
|
1466
|
+
return Reflect.get(store, key);
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* Strip prototype-polluting keys from a caller-supplied context so an own
|
|
1470
|
+
* `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
|
|
1471
|
+
* untrusted payload) can never reach the store — and, via the trace mixin's
|
|
1472
|
+
* `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
|
|
1473
|
+
* but drops the key rather than throwing: a logging concern must never crash
|
|
1474
|
+
* the request that produced it.
|
|
1475
|
+
*
|
|
1476
|
+
* @param context - The raw context bag passed to `run()`.
|
|
1477
|
+
* @returns A shallow copy with any forbidden keys removed.
|
|
1478
|
+
*/
|
|
1479
|
+
sanitizeContext(context) {
|
|
1480
|
+
const safe = {};
|
|
1481
|
+
for (const key of Object.keys(context)) {
|
|
1482
|
+
if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
1483
|
+
Reflect.set(safe, key, Reflect.get(context, key));
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
return safe;
|
|
1487
|
+
}
|
|
1488
|
+
};
|
|
1489
|
+
exports.LogContextService = __decorateClass([
|
|
1490
|
+
common.Injectable()
|
|
1491
|
+
], exports.LogContextService);
|
|
1492
|
+
|
|
1493
|
+
// src/server/middlewares/request-id.middleware.ts
|
|
1494
|
+
var REQUEST_ID_HEADER = "x-request-id";
|
|
1495
|
+
var MAX_CORRELATION_ID_LENGTH = 256;
|
|
1496
|
+
var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
|
|
1497
|
+
var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
|
|
1498
|
+
function isAcceptableHeaderValue(value) {
|
|
1499
|
+
return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
|
|
1500
|
+
}
|
|
1501
|
+
exports.RequestIdMiddleware = class RequestIdMiddleware {
|
|
1502
|
+
/**
|
|
1503
|
+
* @param logContext - The AsyncLocalStorage-backed context service. Injected by
|
|
1504
|
+
* token explicitly: the package is bundled without `emitDecoratorMetadata`,
|
|
1505
|
+
* so implicit class-type injection would not resolve.
|
|
1506
|
+
* @param options - Resolved module options (read for `http.tenantIdHeader` and
|
|
1507
|
+
* `http.shouldGenerateRequestId`).
|
|
1508
|
+
*/
|
|
1509
|
+
constructor(logContext, options) {
|
|
1510
|
+
this.logContext = logContext;
|
|
1511
|
+
this.tenantIdHeader = options.http.tenantIdHeader;
|
|
1512
|
+
this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* Echo or mint the `x-request-id`, expose it on the response, and run the
|
|
1516
|
+
* remainder of the request inside its own log-context scope.
|
|
1517
|
+
*
|
|
1518
|
+
* Idempotent: mounting this middleware twice on the same request mints one id,
|
|
1519
|
+
* not two. The request gets its OWN store, started from the enclosing scope's
|
|
1520
|
+
* correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
|
|
1521
|
+
* else, because no other field can be known to belong to this request.
|
|
1522
|
+
*
|
|
1523
|
+
* An enclosing scope's `requestId` is never adopted and never echoed: adoption
|
|
1524
|
+
* reads a value this middleware recorded on the REQUEST, which a scope opened
|
|
1525
|
+
* elsewhere does not have. What the two generation modes do with one, measured
|
|
1526
|
+
* on two requests sharing a long-lived enclosing scope:
|
|
1527
|
+
*
|
|
1528
|
+
* - `shouldGenerateRequestId: true` (default) — each request mints its own
|
|
1529
|
+
* id, the two requests differ, and the enclosing value reaches neither the
|
|
1530
|
+
* header nor the entries.
|
|
1531
|
+
* - `shouldGenerateRequestId: false` with no inbound header — nothing is
|
|
1532
|
+
* minted, so the request scope inherits the enclosing `requestId` and every
|
|
1533
|
+
* request inside that scope logs under it. No header is exposed. That is
|
|
1534
|
+
* the consumer's own scope being inherited, not correlation being reused,
|
|
1535
|
+
* and it is the configuration that says the gateway owns the id.
|
|
1536
|
+
*
|
|
1537
|
+
* @param req - The incoming request (Express satisfies the contract).
|
|
1538
|
+
* @param res - The outgoing response (Express satisfies the contract).
|
|
1539
|
+
* @param next - The next handler in the chain.
|
|
1540
|
+
*/
|
|
1541
|
+
use(req, res, next) {
|
|
1542
|
+
if (isCorrelationOpened(req)) {
|
|
1543
|
+
const ownRequestId = readOwnRequestId(req);
|
|
1544
|
+
if (ownRequestId !== void 0) {
|
|
1545
|
+
this.adoptExistingScope(ownRequestId, req, res);
|
|
1546
|
+
}
|
|
1547
|
+
next();
|
|
1548
|
+
return;
|
|
1549
|
+
}
|
|
1550
|
+
markCorrelationOpened(req);
|
|
1551
|
+
const context = this.inheritableContext();
|
|
1552
|
+
const requestId = this.resolveRequestId(req);
|
|
1553
|
+
if (requestId !== void 0) {
|
|
1554
|
+
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
1555
|
+
context.requestId = requestId;
|
|
1556
|
+
markOwnRequestId(req, requestId);
|
|
1557
|
+
}
|
|
1558
|
+
if (context.tenantId === void 0) {
|
|
1559
|
+
const tenantId = this.resolveTenantId(req);
|
|
1560
|
+
if (tenantId !== void 0) {
|
|
1561
|
+
context.tenantId = tenantId;
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
this.logContext.run(context, () => next());
|
|
1565
|
+
}
|
|
1566
|
+
/**
|
|
1567
|
+
* The enclosing scope's fields that a request scope may start from.
|
|
1568
|
+
*
|
|
1569
|
+
* Plain `run()` would discard everything the caller had set and a plain merge
|
|
1570
|
+
* would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
|
|
1571
|
+
* the middle a request scope actually needs.
|
|
1572
|
+
*
|
|
1573
|
+
* @returns A fresh bag, never the enclosing store itself, so writes inside the
|
|
1574
|
+
* request never reach the scope that opened it.
|
|
1575
|
+
*/
|
|
1576
|
+
inheritableContext() {
|
|
1577
|
+
const store = { ...this.logContext.getStore() };
|
|
1578
|
+
const inherited = {};
|
|
1579
|
+
for (const key of INHERITABLE_CONTEXT_KEYS) {
|
|
1580
|
+
const value = Reflect.get(store, key);
|
|
1581
|
+
if (value !== void 0) {
|
|
1582
|
+
Reflect.set(inherited, key, value);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
return inherited;
|
|
1586
|
+
}
|
|
1587
|
+
/**
|
|
1588
|
+
* Second mount on a request that already carries a correlation id: echo the id
|
|
1589
|
+
* onto the response and fill in a tenant the scope does not have yet, without
|
|
1590
|
+
* opening another scope.
|
|
1591
|
+
*
|
|
1592
|
+
* Nothing is minted and nothing already set is overwritten, so a third mount —
|
|
1593
|
+
* or a thirtieth — changes nothing. The response header is written on every
|
|
1594
|
+
* pass because the enclosing scope may have been opened by consumer code that
|
|
1595
|
+
* never exposed it.
|
|
1596
|
+
*
|
|
1597
|
+
* @param requestId - The id already in scope, which wins.
|
|
1598
|
+
* @param req - The incoming request, read for the tenant header.
|
|
1599
|
+
* @param res - The outgoing response, where the effective id is exposed.
|
|
1600
|
+
*/
|
|
1601
|
+
adoptExistingScope(requestId, req, res) {
|
|
1602
|
+
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
1603
|
+
this.logContext.set("requestId", requestId);
|
|
1604
|
+
if (this.logContext.get("tenantId") === void 0) {
|
|
1605
|
+
const tenantId = this.resolveTenantId(req);
|
|
1606
|
+
if (tenantId !== void 0) {
|
|
1607
|
+
this.logContext.set("tenantId", tenantId);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* The correlation id for this request: the inbound header when acceptable,
|
|
1613
|
+
* otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
|
|
1614
|
+
* off and the caller sent none, which leaves correlation to the upstream
|
|
1615
|
+
* gateway.
|
|
1616
|
+
*
|
|
1617
|
+
* @param req - The incoming request.
|
|
1618
|
+
* @returns The id, or `undefined` when none is available and none is minted.
|
|
1619
|
+
*/
|
|
1620
|
+
resolveRequestId(req) {
|
|
1621
|
+
const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
|
|
1622
|
+
const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
|
|
1623
|
+
return fromHeader ?? (this.shouldGenerateRequestId ? crypto.randomUUID() : void 0);
|
|
1624
|
+
}
|
|
1625
|
+
/**
|
|
1626
|
+
* The tenant id carried by the configured header, when it is acceptable.
|
|
1627
|
+
*
|
|
1628
|
+
* Never minted: a tenant is an assertion about who the request belongs to, and
|
|
1629
|
+
* inventing one would be a fabricated claim rather than a correlation aid.
|
|
1630
|
+
*
|
|
1631
|
+
* @param req - The incoming request.
|
|
1632
|
+
* @returns The tenant id, or `undefined`.
|
|
1633
|
+
*/
|
|
1634
|
+
resolveTenantId(req) {
|
|
1635
|
+
const raw = Reflect.get(req.headers, this.tenantIdHeader);
|
|
1636
|
+
return isAcceptableHeaderValue(raw) ? raw : void 0;
|
|
1637
|
+
}
|
|
1638
|
+
};
|
|
1639
|
+
exports.RequestIdMiddleware = __decorateClass([
|
|
1640
|
+
common.Injectable(),
|
|
1641
|
+
__decorateParam(0, common.Inject(exports.LogContextService)),
|
|
1642
|
+
__decorateParam(1, common.Inject(LOGGER_OPTIONS_TOKEN))
|
|
1643
|
+
], exports.RequestIdMiddleware);
|
|
1644
|
+
|
|
1645
|
+
// src/server/middlewares/apply-request-context.ts
|
|
1646
|
+
function applyRequestContext(app) {
|
|
1647
|
+
let requestId;
|
|
1648
|
+
try {
|
|
1649
|
+
requestId = new exports.RequestIdMiddleware(
|
|
1650
|
+
app.get(exports.LogContextService),
|
|
1651
|
+
app.get(LOGGER_OPTIONS_TOKEN)
|
|
1652
|
+
);
|
|
1653
|
+
} catch (cause) {
|
|
1654
|
+
throw new Error(
|
|
1655
|
+
"[BymaxLoggerModule] useRequestContext(app) called but BymaxLoggerModule was not imported",
|
|
1656
|
+
{ cause }
|
|
1657
|
+
);
|
|
1658
|
+
}
|
|
1659
|
+
app.use((req, res, next) => {
|
|
1660
|
+
requestId.use(req, res, next);
|
|
1661
|
+
});
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
// src/server/constants/default-redact-paths.constants.ts
|
|
1665
|
+
var REDACT_MAX_DEPTH = 4;
|
|
1666
|
+
var WILDCARD_PREFIXES = Array.from(
|
|
1667
|
+
{ length: REDACT_MAX_DEPTH },
|
|
1668
|
+
(_, idx) => "*" + ".*".repeat(idx)
|
|
1669
|
+
);
|
|
1670
|
+
var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
|
|
1671
|
+
var REDACT_COMMON_FIELDS = [
|
|
1672
|
+
// Passwords (5)
|
|
1673
|
+
"password",
|
|
1674
|
+
"passwordHash",
|
|
1675
|
+
"passwordConfirm",
|
|
1676
|
+
"newPassword",
|
|
1677
|
+
"oldPassword",
|
|
1678
|
+
// Tokens (6)
|
|
1679
|
+
"token",
|
|
1680
|
+
"accessToken",
|
|
1681
|
+
"refreshToken",
|
|
1682
|
+
"idToken",
|
|
1683
|
+
"apiKey",
|
|
1684
|
+
"apiSecret",
|
|
1685
|
+
// MFA (3)
|
|
1686
|
+
"mfaSecret",
|
|
1687
|
+
"mfaRecoveryCodes",
|
|
1688
|
+
"totpSecret",
|
|
1689
|
+
// Payment / PCI DSS (5)
|
|
1690
|
+
"cardNumber",
|
|
1691
|
+
"cardCvv",
|
|
1692
|
+
"cvv",
|
|
1693
|
+
"cvc",
|
|
1694
|
+
"cardExpiry",
|
|
1695
|
+
// Personal documents — BR / LGPD (3)
|
|
1696
|
+
"cpf",
|
|
1697
|
+
"cnpj",
|
|
1698
|
+
"rg",
|
|
1699
|
+
// Generic secrets (4) — the most common short-form credential field names
|
|
1700
|
+
"secret",
|
|
1701
|
+
"clientSecret",
|
|
1702
|
+
"signingSecret",
|
|
1703
|
+
"privateKey",
|
|
1704
|
+
// Conservative PII (1) — consumer can disable if logging email is justified
|
|
1705
|
+
"email",
|
|
1706
|
+
// Credential-bearing HTTP header names (5). These also appear in
|
|
1707
|
+
// {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
|
|
1708
|
+
// shapes — which covered ONLY those two shapes. A headers bag logged under any
|
|
1709
|
+
// other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
|
|
1710
|
+
// common things written while debugging an integration) wrote the bearer token
|
|
1711
|
+
// in clear. Listed here as bare names, they are caught wherever they appear.
|
|
1712
|
+
// Node lower-cases inbound header names, so the lower-case spelling is the one
|
|
1713
|
+
// that can actually reach a log.
|
|
1714
|
+
"authorization",
|
|
1715
|
+
"cookie",
|
|
1716
|
+
"set-cookie",
|
|
1717
|
+
"x-api-key",
|
|
1718
|
+
"x-auth-token"
|
|
1719
|
+
];
|
|
1720
|
+
var REDACT_ABSOLUTE_PATHS = [
|
|
1721
|
+
"req.headers.authorization",
|
|
1722
|
+
"req.headers.cookie",
|
|
1723
|
+
'req.headers["x-api-key"]',
|
|
1724
|
+
'req.headers["x-auth-token"]',
|
|
1725
|
+
'res.headers["set-cookie"]'
|
|
1726
|
+
];
|
|
1727
|
+
var DEFAULT_REDACT_PATHS = [
|
|
1728
|
+
...REDACT_COMMON_FIELDS,
|
|
1729
|
+
...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
|
|
1730
|
+
...REDACT_ABSOLUTE_PATHS
|
|
1731
|
+
];
|
|
1732
|
+
|
|
1733
|
+
// src/server/utils/report-destination-failure.util.ts
|
|
1734
|
+
function reportDestinationFailure(logKey, name, cause, msg) {
|
|
1735
|
+
writeStderrSafely(
|
|
1736
|
+
JSON.stringify({
|
|
1737
|
+
level: "error",
|
|
1738
|
+
logKey,
|
|
1739
|
+
destination: toSingleLineMessage(name),
|
|
1740
|
+
err: describeCause(cause),
|
|
1741
|
+
msg: toSingleLineMessage(msg)
|
|
1742
|
+
}) + "\n"
|
|
1743
|
+
);
|
|
1744
|
+
}
|
|
1745
|
+
var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
|
|
1746
|
+
function describeCause(cause) {
|
|
1747
|
+
try {
|
|
1748
|
+
return isError(cause) ? {
|
|
1749
|
+
type: toBoundedMessage(String(cause.name)),
|
|
1750
|
+
message: toBoundedMessage(String(cause.message))
|
|
1751
|
+
} : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
|
|
1752
|
+
} catch {
|
|
1753
|
+
return UNREADABLE_CAUSE;
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
function safeDestinationName(destination) {
|
|
1757
|
+
try {
|
|
1758
|
+
return String(destination.name);
|
|
1759
|
+
} catch {
|
|
1760
|
+
return "unknown";
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
function isLogLevel(value) {
|
|
1764
|
+
return LOG_LEVEL_PRIORITY.includes(value);
|
|
1765
|
+
}
|
|
1766
|
+
var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
|
|
1767
|
+
function safeMinLevel(destination) {
|
|
1768
|
+
if (resolvedMinLevels.has(destination)) {
|
|
1769
|
+
return resolvedMinLevels.get(destination);
|
|
1770
|
+
}
|
|
1771
|
+
let resolved;
|
|
1772
|
+
try {
|
|
1773
|
+
const read = destination.minLevel;
|
|
1774
|
+
resolved = isLogLevel(read) ? read : void 0;
|
|
1775
|
+
} catch {
|
|
1776
|
+
}
|
|
1777
|
+
resolvedMinLevels.set(destination, resolved);
|
|
1778
|
+
return resolved;
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
// src/server/utils/otel-detector.ts
|
|
1782
|
+
var brokenInstallWarned = false;
|
|
1783
|
+
function isOtelApiMissing(cause) {
|
|
1784
|
+
try {
|
|
1785
|
+
const { code, message } = cause;
|
|
1786
|
+
return code === "MODULE_NOT_FOUND" && /^Cannot find module '@opentelemetry\/api'/.test(String(message));
|
|
1787
|
+
} catch {
|
|
1788
|
+
return false;
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
function loadTraceApiFrom(anchor) {
|
|
1792
|
+
let from;
|
|
1793
|
+
try {
|
|
1794
|
+
from = anchor();
|
|
1795
|
+
} catch {
|
|
1796
|
+
return { api: void 0 };
|
|
1797
|
+
}
|
|
1798
|
+
try {
|
|
1799
|
+
const mod = module$1.createRequire(from)("@opentelemetry/api");
|
|
1800
|
+
const trace = typeof mod === "object" && mod !== null || typeof mod === "function" ? mod.trace : void 0;
|
|
1801
|
+
if (typeof trace?.getActiveSpan !== "function") {
|
|
1802
|
+
throw new TypeError("@opentelemetry/api resolved but exports no usable `trace` namespace");
|
|
1429
1803
|
}
|
|
1430
1804
|
return { api: trace };
|
|
1431
1805
|
} catch (cause) {
|
|
@@ -1737,69 +2111,76 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
|
|
|
1737
2111
|
if (ArrayBuffer.isView(value)) {
|
|
1738
2112
|
return withBinaryAsSize(value);
|
|
1739
2113
|
}
|
|
1740
|
-
const
|
|
1741
|
-
const resolvedToJson = resolveToJson(value, plain);
|
|
2114
|
+
const method = resolveToJson(value, rules.ownFields.safe).method;
|
|
1742
2115
|
ancestors.add(value);
|
|
1743
2116
|
try {
|
|
1744
|
-
|
|
1745
|
-
const toJson = honorToJson && !ownsItsForm ? resolvedToJson.method : void 0;
|
|
1746
|
-
if (toJson !== void 0) {
|
|
1747
|
-
if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
|
|
1748
|
-
return rules.censor;
|
|
1749
|
-
}
|
|
1750
|
-
return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
|
|
1751
|
-
}
|
|
1752
|
-
if (typeof value === "function") {
|
|
1753
|
-
return plain ? void 0 : value;
|
|
1754
|
-
}
|
|
1755
|
-
if (Array.isArray(value)) {
|
|
1756
|
-
return walkArray(value, rules, depth2, ancestors, inSerialized);
|
|
1757
|
-
}
|
|
1758
|
-
const source = value;
|
|
1759
|
-
const keys = Object.keys(source);
|
|
1760
|
-
const asData = isError(value) && (plain || rules.errorsAsData && !inSerialized);
|
|
1761
|
-
const clone = isError(value) ? cloneError(value) : void 0;
|
|
1762
|
-
const copy = clone !== void 0 && !asData ? clone : {};
|
|
1763
|
-
const scrubbed = isError(value) && (plain || !inSerialized);
|
|
1764
|
-
const omitted = /* @__PURE__ */ new Set();
|
|
1765
|
-
for (const key of keys) {
|
|
1766
|
-
const read = Reflect.get(source, key);
|
|
1767
|
-
const current = scrubbed ? ownFieldForLog(source, key, read, rules.ownFields) : read;
|
|
1768
|
-
if (current === OMIT_OWN_FIELD) {
|
|
1769
|
-
Reflect.deleteProperty(copy, key);
|
|
1770
|
-
omitted.add(key);
|
|
1771
|
-
continue;
|
|
1772
|
-
}
|
|
1773
|
-
defineOwn(
|
|
1774
|
-
copy,
|
|
1775
|
-
key,
|
|
1776
|
-
rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
|
|
1777
|
-
// An own enumerable `name`, `message` or `stack` of an `Error` is the same text as
|
|
1778
|
-
// the part the walk would add, so it is cut the same way.
|
|
1779
|
-
scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
|
|
1780
|
-
rules,
|
|
1781
|
-
depth2 + 1,
|
|
1782
|
-
ancestors,
|
|
1783
|
-
true,
|
|
1784
|
-
inSerialized || !honorToJson && rules.serializedKeys.has(key)
|
|
1785
|
-
)
|
|
1786
|
-
);
|
|
1787
|
-
}
|
|
1788
|
-
if (asData) {
|
|
1789
|
-
const written = keys.filter((key) => !omitted.has(key));
|
|
1790
|
-
addErrorParts(
|
|
1791
|
-
copy,
|
|
1792
|
-
value,
|
|
1793
|
-
written,
|
|
1794
|
-
errorPartsHost(rules, ancestors, inSerialized),
|
|
1795
|
-
depth2
|
|
1796
|
-
);
|
|
1797
|
-
}
|
|
1798
|
-
return copy;
|
|
2117
|
+
return walkForm(value, method, rules, depth2, ancestors, honorToJson, inSerialized);
|
|
1799
2118
|
} finally {
|
|
1800
2119
|
ancestors.delete(value);
|
|
1801
2120
|
}
|
|
1802
2121
|
}
|
|
2122
|
+
function walkForm(value, method, rules, depth2, ancestors, honorToJson, inSerialized) {
|
|
2123
|
+
const plain = rules.ownFields.safe;
|
|
2124
|
+
const toJson = honorToJson && !(plain && isError(value)) ? method : void 0;
|
|
2125
|
+
if (toJson !== void 0) {
|
|
2126
|
+
return walkToJsonOutput(value, toJson, rules, depth2, ancestors, inSerialized);
|
|
2127
|
+
}
|
|
2128
|
+
if (typeof value === "function") {
|
|
2129
|
+
return plain ? void 0 : value;
|
|
2130
|
+
}
|
|
2131
|
+
if (Array.isArray(value)) {
|
|
2132
|
+
return walkArray(value, rules, depth2, ancestors, inSerialized);
|
|
2133
|
+
}
|
|
2134
|
+
return walkProperties(value, rules, depth2, ancestors, honorToJson, inSerialized);
|
|
2135
|
+
}
|
|
2136
|
+
function walkToJsonOutput(value, toJson, rules, depth2, ancestors, inSerialized) {
|
|
2137
|
+
if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
|
|
2138
|
+
return rules.censor;
|
|
2139
|
+
}
|
|
2140
|
+
return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
|
|
2141
|
+
}
|
|
2142
|
+
function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerialized) {
|
|
2143
|
+
const source = value;
|
|
2144
|
+
const keys = Object.keys(source);
|
|
2145
|
+
const { safe } = rules.ownFields;
|
|
2146
|
+
const asData = isError(value) && (safe || rules.errorsAsData && !inSerialized);
|
|
2147
|
+
const copy = startCopy(value, asData);
|
|
2148
|
+
const scrubbed = isError(value) && (safe || !inSerialized);
|
|
2149
|
+
const omitted = /* @__PURE__ */ new Set();
|
|
2150
|
+
for (const key of keys) {
|
|
2151
|
+
const read = Reflect.get(source, key);
|
|
2152
|
+
const current = scrubbed ? ownFieldForLog(source, key, read, rules.ownFields) : read;
|
|
2153
|
+
if (current === OMIT_OWN_FIELD) {
|
|
2154
|
+
Reflect.deleteProperty(copy, key);
|
|
2155
|
+
omitted.add(key);
|
|
2156
|
+
continue;
|
|
2157
|
+
}
|
|
2158
|
+
defineOwn(
|
|
2159
|
+
copy,
|
|
2160
|
+
key,
|
|
2161
|
+
rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
|
|
2162
|
+
scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
|
|
2163
|
+
rules,
|
|
2164
|
+
depth2 + 1,
|
|
2165
|
+
ancestors,
|
|
2166
|
+
true,
|
|
2167
|
+
inSerialized || !honorToJson && rules.serializedKeys.has(key)
|
|
2168
|
+
)
|
|
2169
|
+
);
|
|
2170
|
+
}
|
|
2171
|
+
if (asData) {
|
|
2172
|
+
const host = errorPartsHost(rules, ancestors, inSerialized);
|
|
2173
|
+
addErrorParts(copy, value, without(keys, omitted), host, depth2);
|
|
2174
|
+
}
|
|
2175
|
+
return copy;
|
|
2176
|
+
}
|
|
2177
|
+
function without(keys, omitted) {
|
|
2178
|
+
return keys.filter((key) => !omitted.has(key));
|
|
2179
|
+
}
|
|
2180
|
+
function startCopy(value, asData) {
|
|
2181
|
+
const clone = isError(value) ? cloneError(value) : void 0;
|
|
2182
|
+
return clone !== void 0 && !asData ? clone : {};
|
|
2183
|
+
}
|
|
1803
2184
|
function errorPartsHost(rules, ancestors, inSerialized) {
|
|
1804
2185
|
return {
|
|
1805
2186
|
sensitive: rules.sensitive,
|
|
@@ -2562,190 +2943,64 @@ var DestinationRegistry = class {
|
|
|
2562
2943
|
} catch (cause) {
|
|
2563
2944
|
this.reportShutdownFailure(destination, cause);
|
|
2564
2945
|
}
|
|
2565
|
-
}
|
|
2566
|
-
}
|
|
2567
|
-
/**
|
|
2568
|
-
* Report a failing `onShutdown` on stderr without letting the report itself
|
|
2569
|
-
* abort the teardown of the destinations still queued behind it.
|
|
2570
|
-
*
|
|
2571
|
-
* The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
|
|
2572
|
-
* an `Error` with hostile getters, and `String(cause)` on a value with a
|
|
2573
|
-
* throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
|
|
2574
|
-
* the `catch` that exists to keep one bad sink from mattering, so an escape
|
|
2575
|
-
* here would propagate out of `onApplicationShutdown` and skip every remaining
|
|
2576
|
-
* destination's flush. The never-throw contract has to cover READING the value,
|
|
2577
|
-
* not just writing it, which is the same correction `reportDestinationFailure`
|
|
2578
|
-
* already carries.
|
|
2579
|
-
*
|
|
2580
|
-
* The text is escaped for the same reason every other terminal-bound path is:
|
|
2581
|
-
* a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
|
|
2582
|
-
* newlines and neutralizes everything else that can drive a terminal.
|
|
2583
|
-
*
|
|
2584
|
-
* The DESTINATION is passed rather than its name, so that read happens in here
|
|
2585
|
-
* too. `name` is declared `readonly name: string` but nothing stops a consumer
|
|
2586
|
-
* implementing it as a getter, and reading it at the call site would put it back
|
|
2587
|
-
* outside the guard — inside the `catch`, where a throw has the same cost.
|
|
2588
|
-
*
|
|
2589
|
-
* Two separate guards, not one: a name that cannot be read must not also cost
|
|
2590
|
-
* the failure detail, and a detail that cannot be read must not cost the name.
|
|
2591
|
-
* Either alone still identifies which sink failed.
|
|
2592
|
-
*
|
|
2593
|
-
* @param destination - The destination whose `onShutdown` threw.
|
|
2594
|
-
* @param cause - The thrown value, of any shape.
|
|
2595
|
-
*/
|
|
2596
|
-
reportShutdownFailure(destination, cause) {
|
|
2597
|
-
const name = toSingleLineMessage(safeDestinationName(destination));
|
|
2598
|
-
let detail = "UnknownError";
|
|
2599
|
-
try {
|
|
2600
|
-
const stack = isErrorLike(cause) ? cause.stack : void 0;
|
|
2601
|
-
detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
|
|
2602
|
-
} catch {
|
|
2603
|
-
}
|
|
2604
|
-
writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
|
|
2605
|
-
`);
|
|
2606
|
-
}
|
|
2607
|
-
/**
|
|
2608
|
-
* The destinations that initialized successfully.
|
|
2609
|
-
*
|
|
2610
|
-
* @returns A read-only view of the active destination set.
|
|
2611
|
-
*/
|
|
2612
|
-
getActive() {
|
|
2613
|
-
return this.active;
|
|
2614
|
-
}
|
|
2615
|
-
};
|
|
2616
|
-
DestinationRegistry = __decorateClass([
|
|
2617
|
-
common.Injectable(),
|
|
2618
|
-
__decorateParam(0, common.Inject(LOGGER_DESTINATIONS_TOKEN)),
|
|
2619
|
-
__decorateParam(1, common.Inject(exports.PinoLoggerService)),
|
|
2620
|
-
__decorateParam(2, common.Inject(LOGGER_OPTIONS_TOKEN)),
|
|
2621
|
-
__decorateParam(3, common.Inject(DestinationHealth))
|
|
2622
|
-
], DestinationRegistry);
|
|
2623
|
-
var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
|
|
2624
|
-
exports.LogContextService = class LogContextService {
|
|
2625
|
-
constructor() {
|
|
2626
|
-
this.als = new async_hooks.AsyncLocalStorage();
|
|
2627
|
-
}
|
|
2628
|
-
/**
|
|
2629
|
-
* Run `callback` inside a fresh context scope. Every log emitted
|
|
2630
|
-
* synchronously or asynchronously within the callback inherits `context`.
|
|
2631
|
-
*
|
|
2632
|
-
* **A nested `run()` REPLACES the enclosing context, it does not extend it.**
|
|
2633
|
-
* The scope starts from `context` alone, so a field an outer scope had set —
|
|
2634
|
-
* a `tenantId` resolved at the edge, say — is absent for the whole inner
|
|
2635
|
-
* scope: nothing throws, `get()` simply returns `undefined`, and the field is
|
|
2636
|
-
* missing from every entry the callback emits. Reach for {@link runMerged}
|
|
2637
|
-
* when the inner scope should extend the outer one.
|
|
2638
|
-
*
|
|
2639
|
-
* Replacement is the deliberate default because the opposite leaks: a
|
|
2640
|
-
* background job started inside a request scope would silently inherit the
|
|
2641
|
-
* caller's `userId` and attribute its entries to a user who never triggered
|
|
2642
|
-
* it. A missing field is visibly missing; an inherited one is wrong while
|
|
2643
|
-
* looking right.
|
|
2644
|
-
*
|
|
2645
|
-
* @typeParam T - Return type of the callback.
|
|
2646
|
-
* @param context - Initial context bag for the scope. Becomes the WHOLE scope.
|
|
2647
|
-
* @param callback - Function executed within the scope.
|
|
2648
|
-
* @returns Whatever `callback` returns.
|
|
2649
|
-
* @example
|
|
2650
|
-
* logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
|
|
2651
|
-
* await userService.create(dto) // logs carry requestId + tenantId
|
|
2652
|
-
* })
|
|
2653
|
-
*/
|
|
2654
|
-
run(context, callback) {
|
|
2655
|
-
return this.als.run(this.sanitizeContext(context), callback);
|
|
2656
|
-
}
|
|
2657
|
-
/**
|
|
2658
|
-
* Run `callback` inside a scope that EXTENDS the enclosing one: the active
|
|
2659
|
-
* context's fields are carried in, and `context` overrides them key by key.
|
|
2660
|
-
*
|
|
2661
|
-
* The explicit counterpart to {@link run}'s replacement semantics, for the
|
|
2662
|
-
* case where an inner scope is genuinely a refinement of the outer — adding a
|
|
2663
|
-
* `userId` once authentication resolved it, without having to restate the
|
|
2664
|
-
* `requestId` the middleware already set.
|
|
2665
|
-
*
|
|
2666
|
-
* Outside any scope there is nothing to merge and this behaves exactly like
|
|
2667
|
-
* {@link run}. Writes inside the new scope never reach the enclosing one: the
|
|
2668
|
-
* merge produces a fresh object, so the outer context is intact after the
|
|
2669
|
-
* callback returns.
|
|
2670
|
-
*
|
|
2671
|
-
* @typeParam T - Return type of the callback.
|
|
2672
|
-
* @param context - Fields to add or override on top of the active context.
|
|
2673
|
-
* @param callback - Function executed within the merged scope.
|
|
2674
|
-
* @returns Whatever `callback` returns.
|
|
2675
|
-
* @example
|
|
2676
|
-
* logContext.run({ requestId: 'r_1' }, () => {
|
|
2677
|
-
* logContext.runMerged({ userId: 'u_1' }, () => {
|
|
2678
|
-
* logContext.get('requestId') // 'r_1' — carried in from the outer scope
|
|
2679
|
-
* })
|
|
2680
|
-
* })
|
|
2681
|
-
*/
|
|
2682
|
-
runMerged(context, callback) {
|
|
2683
|
-
const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
|
|
2684
|
-
return this.als.run(merged, callback);
|
|
2946
|
+
}
|
|
2685
2947
|
}
|
|
2686
2948
|
/**
|
|
2687
|
-
*
|
|
2949
|
+
* Report a failing `onShutdown` on stderr without letting the report itself
|
|
2950
|
+
* abort the teardown of the destinations still queued behind it.
|
|
2688
2951
|
*
|
|
2689
|
-
*
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
*
|
|
2952
|
+
* The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
|
|
2953
|
+
* an `Error` with hostile getters, and `String(cause)` on a value with a
|
|
2954
|
+
* throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
|
|
2955
|
+
* the `catch` that exists to keep one bad sink from mattering, so an escape
|
|
2956
|
+
* here would propagate out of `onApplicationShutdown` and skip every remaining
|
|
2957
|
+
* destination's flush. The never-throw contract has to cover READING the value,
|
|
2958
|
+
* not just writing it, which is the same correction `reportDestinationFailure`
|
|
2959
|
+
* already carries.
|
|
2696
2960
|
*
|
|
2697
|
-
*
|
|
2698
|
-
*
|
|
2699
|
-
*
|
|
2700
|
-
*/
|
|
2701
|
-
set(key, value) {
|
|
2702
|
-
const store = this.als.getStore();
|
|
2703
|
-
if (!store) {
|
|
2704
|
-
throw new Error("[LogContextService] set() called outside run() scope");
|
|
2705
|
-
}
|
|
2706
|
-
if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
2707
|
-
throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
|
|
2708
|
-
}
|
|
2709
|
-
Reflect.set(store, key, value);
|
|
2710
|
-
}
|
|
2711
|
-
/**
|
|
2712
|
-
* Read a single field from the active context.
|
|
2961
|
+
* The text is escaped for the same reason every other terminal-bound path is:
|
|
2962
|
+
* a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
|
|
2963
|
+
* newlines and neutralizes everything else that can drive a terminal.
|
|
2713
2964
|
*
|
|
2714
|
-
*
|
|
2715
|
-
*
|
|
2716
|
-
*
|
|
2965
|
+
* The DESTINATION is passed rather than its name, so that read happens in here
|
|
2966
|
+
* too. `name` is declared `readonly name: string` but nothing stops a consumer
|
|
2967
|
+
* implementing it as a getter, and reading it at the call site would put it back
|
|
2968
|
+
* outside the guard — inside the `catch`, where a throw has the same cost.
|
|
2969
|
+
*
|
|
2970
|
+
* Two separate guards, not one: a name that cannot be read must not also cost
|
|
2971
|
+
* the failure detail, and a detail that cannot be read must not cost the name.
|
|
2972
|
+
* Either alone still identifies which sink failed.
|
|
2973
|
+
*
|
|
2974
|
+
* @param destination - The destination whose `onShutdown` threw.
|
|
2975
|
+
* @param cause - The thrown value, of any shape.
|
|
2717
2976
|
*/
|
|
2718
|
-
|
|
2719
|
-
const
|
|
2720
|
-
|
|
2721
|
-
|
|
2977
|
+
reportShutdownFailure(destination, cause) {
|
|
2978
|
+
const name = toSingleLineMessage(safeDestinationName(destination));
|
|
2979
|
+
let detail = "UnknownError";
|
|
2980
|
+
try {
|
|
2981
|
+
const stack = isErrorLike(cause) ? cause.stack : void 0;
|
|
2982
|
+
detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
|
|
2983
|
+
} catch {
|
|
2722
2984
|
}
|
|
2723
|
-
|
|
2985
|
+
writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
|
|
2986
|
+
`);
|
|
2724
2987
|
}
|
|
2725
2988
|
/**
|
|
2726
|
-
*
|
|
2727
|
-
* `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
|
|
2728
|
-
* untrusted payload) can never reach the store — and, via the trace mixin's
|
|
2729
|
-
* `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
|
|
2730
|
-
* but drops the key rather than throwing: a logging concern must never crash
|
|
2731
|
-
* the request that produced it.
|
|
2989
|
+
* The destinations that initialized successfully.
|
|
2732
2990
|
*
|
|
2733
|
-
* @
|
|
2734
|
-
* @returns A shallow copy with any forbidden keys removed.
|
|
2991
|
+
* @returns A read-only view of the active destination set.
|
|
2735
2992
|
*/
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
for (const key of Object.keys(context)) {
|
|
2739
|
-
if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
2740
|
-
Reflect.set(safe, key, Reflect.get(context, key));
|
|
2741
|
-
}
|
|
2742
|
-
}
|
|
2743
|
-
return safe;
|
|
2993
|
+
getActive() {
|
|
2994
|
+
return this.active;
|
|
2744
2995
|
}
|
|
2745
2996
|
};
|
|
2746
|
-
|
|
2747
|
-
common.Injectable()
|
|
2748
|
-
|
|
2997
|
+
DestinationRegistry = __decorateClass([
|
|
2998
|
+
common.Injectable(),
|
|
2999
|
+
__decorateParam(0, common.Inject(LOGGER_DESTINATIONS_TOKEN)),
|
|
3000
|
+
__decorateParam(1, common.Inject(exports.PinoLoggerService)),
|
|
3001
|
+
__decorateParam(2, common.Inject(LOGGER_OPTIONS_TOKEN)),
|
|
3002
|
+
__decorateParam(3, common.Inject(DestinationHealth))
|
|
3003
|
+
], DestinationRegistry);
|
|
2749
3004
|
|
|
2750
3005
|
// src/server/logger.module.ts
|
|
2751
3006
|
function resolveDestinations(options) {
|
|
@@ -2913,6 +3168,26 @@ exports.BymaxLoggerModule = class BymaxLoggerModule extends BymaxLoggerModuleBas
|
|
|
2913
3168
|
app.useLogger(logger);
|
|
2914
3169
|
app.flushLogs();
|
|
2915
3170
|
}
|
|
3171
|
+
/**
|
|
3172
|
+
* Open the request-id correlation scope ahead of the body parser, so a request the parser
|
|
3173
|
+
* refuses (malformed JSON, an unsupported content encoding, a body over the limit) still has its
|
|
3174
|
+
* `requestId`, and the `x-request-id` response header, where an exception filter reads it.
|
|
3175
|
+
*
|
|
3176
|
+
* Call once in `main.ts` AFTER creating the app and BEFORE `app.init()` / `app.listen(...)`.
|
|
3177
|
+
* It mounts only the scope. `applyAccessLog(app)` and `applyRequestIdMiddleware(consumer)` can
|
|
3178
|
+
* be used as well: a second mount of the middleware reuses the scope this one opened.
|
|
3179
|
+
*
|
|
3180
|
+
* @param app - The Nest application returned by `NestFactory.create()`.
|
|
3181
|
+
* @throws Error When `BymaxLoggerModule` was not imported.
|
|
3182
|
+
* @example
|
|
3183
|
+
* const app = await NestFactory.create(AppModule, { bufferLogs: true })
|
|
3184
|
+
* BymaxLoggerModule.useNestLogger(app)
|
|
3185
|
+
* BymaxLoggerModule.useRequestContext(app)
|
|
3186
|
+
* await app.listen(3000)
|
|
3187
|
+
*/
|
|
3188
|
+
static useRequestContext(app) {
|
|
3189
|
+
applyRequestContext(app);
|
|
3190
|
+
}
|
|
2916
3191
|
};
|
|
2917
3192
|
exports.BymaxLoggerModule = __decorateClass([
|
|
2918
3193
|
common.Module({})
|
|
@@ -3263,156 +3538,6 @@ exports.HttpAccessLogMiddleware = __decorateClass([
|
|
|
3263
3538
|
__decorateParam(1, common.Inject(exports.LogContextService)),
|
|
3264
3539
|
__decorateParam(2, common.Inject(LOGGER_OPTIONS_TOKEN))
|
|
3265
3540
|
], exports.HttpAccessLogMiddleware);
|
|
3266
|
-
var REQUEST_ID_HEADER = "x-request-id";
|
|
3267
|
-
var MAX_CORRELATION_ID_LENGTH = 256;
|
|
3268
|
-
var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
|
|
3269
|
-
var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
|
|
3270
|
-
function isAcceptableHeaderValue(value) {
|
|
3271
|
-
return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
|
|
3272
|
-
}
|
|
3273
|
-
exports.RequestIdMiddleware = class RequestIdMiddleware {
|
|
3274
|
-
/**
|
|
3275
|
-
* @param logContext - The AsyncLocalStorage-backed context service. Injected by
|
|
3276
|
-
* token explicitly: the package is bundled without `emitDecoratorMetadata`,
|
|
3277
|
-
* so implicit class-type injection would not resolve.
|
|
3278
|
-
* @param options - Resolved module options (read for `http.tenantIdHeader` and
|
|
3279
|
-
* `http.shouldGenerateRequestId`).
|
|
3280
|
-
*/
|
|
3281
|
-
constructor(logContext, options) {
|
|
3282
|
-
this.logContext = logContext;
|
|
3283
|
-
this.tenantIdHeader = options.http.tenantIdHeader;
|
|
3284
|
-
this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
|
|
3285
|
-
}
|
|
3286
|
-
/**
|
|
3287
|
-
* Echo or mint the `x-request-id`, expose it on the response, and run the
|
|
3288
|
-
* remainder of the request inside its own log-context scope.
|
|
3289
|
-
*
|
|
3290
|
-
* Idempotent: mounting this middleware twice on the same request mints one id,
|
|
3291
|
-
* not two. The request gets its OWN store, started from the enclosing scope's
|
|
3292
|
-
* correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
|
|
3293
|
-
* else, because no other field can be known to belong to this request.
|
|
3294
|
-
*
|
|
3295
|
-
* An enclosing scope's `requestId` is never adopted and never echoed: adoption
|
|
3296
|
-
* reads a value this middleware recorded on the REQUEST, which a scope opened
|
|
3297
|
-
* elsewhere does not have. What the two generation modes do with one, measured
|
|
3298
|
-
* on two requests sharing a long-lived enclosing scope:
|
|
3299
|
-
*
|
|
3300
|
-
* - `shouldGenerateRequestId: true` (default) — each request mints its own
|
|
3301
|
-
* id, the two requests differ, and the enclosing value reaches neither the
|
|
3302
|
-
* header nor the entries.
|
|
3303
|
-
* - `shouldGenerateRequestId: false` with no inbound header — nothing is
|
|
3304
|
-
* minted, so the request scope inherits the enclosing `requestId` and every
|
|
3305
|
-
* request inside that scope logs under it. No header is exposed. That is
|
|
3306
|
-
* the consumer's own scope being inherited, not correlation being reused,
|
|
3307
|
-
* and it is the configuration that says the gateway owns the id.
|
|
3308
|
-
*
|
|
3309
|
-
* @param req - The incoming request (Express satisfies the contract).
|
|
3310
|
-
* @param res - The outgoing response (Express satisfies the contract).
|
|
3311
|
-
* @param next - The next handler in the chain.
|
|
3312
|
-
*/
|
|
3313
|
-
use(req, res, next) {
|
|
3314
|
-
if (isCorrelationOpened(req)) {
|
|
3315
|
-
const ownRequestId = readOwnRequestId(req);
|
|
3316
|
-
if (ownRequestId !== void 0) {
|
|
3317
|
-
this.adoptExistingScope(ownRequestId, req, res);
|
|
3318
|
-
}
|
|
3319
|
-
next();
|
|
3320
|
-
return;
|
|
3321
|
-
}
|
|
3322
|
-
markCorrelationOpened(req);
|
|
3323
|
-
const context = this.inheritableContext();
|
|
3324
|
-
const requestId = this.resolveRequestId(req);
|
|
3325
|
-
if (requestId !== void 0) {
|
|
3326
|
-
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
3327
|
-
context.requestId = requestId;
|
|
3328
|
-
markOwnRequestId(req, requestId);
|
|
3329
|
-
}
|
|
3330
|
-
if (context.tenantId === void 0) {
|
|
3331
|
-
const tenantId = this.resolveTenantId(req);
|
|
3332
|
-
if (tenantId !== void 0) {
|
|
3333
|
-
context.tenantId = tenantId;
|
|
3334
|
-
}
|
|
3335
|
-
}
|
|
3336
|
-
this.logContext.run(context, () => next());
|
|
3337
|
-
}
|
|
3338
|
-
/**
|
|
3339
|
-
* The enclosing scope's fields that a request scope may start from.
|
|
3340
|
-
*
|
|
3341
|
-
* Plain `run()` would discard everything the caller had set and a plain merge
|
|
3342
|
-
* would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
|
|
3343
|
-
* the middle a request scope actually needs.
|
|
3344
|
-
*
|
|
3345
|
-
* @returns A fresh bag, never the enclosing store itself, so writes inside the
|
|
3346
|
-
* request never reach the scope that opened it.
|
|
3347
|
-
*/
|
|
3348
|
-
inheritableContext() {
|
|
3349
|
-
const store = { ...this.logContext.getStore() };
|
|
3350
|
-
const inherited = {};
|
|
3351
|
-
for (const key of INHERITABLE_CONTEXT_KEYS) {
|
|
3352
|
-
const value = Reflect.get(store, key);
|
|
3353
|
-
if (value !== void 0) {
|
|
3354
|
-
Reflect.set(inherited, key, value);
|
|
3355
|
-
}
|
|
3356
|
-
}
|
|
3357
|
-
return inherited;
|
|
3358
|
-
}
|
|
3359
|
-
/**
|
|
3360
|
-
* Second mount on a request that already carries a correlation id: echo the id
|
|
3361
|
-
* onto the response and fill in a tenant the scope does not have yet, without
|
|
3362
|
-
* opening another scope.
|
|
3363
|
-
*
|
|
3364
|
-
* Nothing is minted and nothing already set is overwritten, so a third mount —
|
|
3365
|
-
* or a thirtieth — changes nothing. The response header is written on every
|
|
3366
|
-
* pass because the enclosing scope may have been opened by consumer code that
|
|
3367
|
-
* never exposed it.
|
|
3368
|
-
*
|
|
3369
|
-
* @param requestId - The id already in scope, which wins.
|
|
3370
|
-
* @param req - The incoming request, read for the tenant header.
|
|
3371
|
-
* @param res - The outgoing response, where the effective id is exposed.
|
|
3372
|
-
*/
|
|
3373
|
-
adoptExistingScope(requestId, req, res) {
|
|
3374
|
-
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
3375
|
-
this.logContext.set("requestId", requestId);
|
|
3376
|
-
if (this.logContext.get("tenantId") === void 0) {
|
|
3377
|
-
const tenantId = this.resolveTenantId(req);
|
|
3378
|
-
if (tenantId !== void 0) {
|
|
3379
|
-
this.logContext.set("tenantId", tenantId);
|
|
3380
|
-
}
|
|
3381
|
-
}
|
|
3382
|
-
}
|
|
3383
|
-
/**
|
|
3384
|
-
* The correlation id for this request: the inbound header when acceptable,
|
|
3385
|
-
* otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
|
|
3386
|
-
* off and the caller sent none, which leaves correlation to the upstream
|
|
3387
|
-
* gateway.
|
|
3388
|
-
*
|
|
3389
|
-
* @param req - The incoming request.
|
|
3390
|
-
* @returns The id, or `undefined` when none is available and none is minted.
|
|
3391
|
-
*/
|
|
3392
|
-
resolveRequestId(req) {
|
|
3393
|
-
const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
|
|
3394
|
-
const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
|
|
3395
|
-
return fromHeader ?? (this.shouldGenerateRequestId ? crypto.randomUUID() : void 0);
|
|
3396
|
-
}
|
|
3397
|
-
/**
|
|
3398
|
-
* The tenant id carried by the configured header, when it is acceptable.
|
|
3399
|
-
*
|
|
3400
|
-
* Never minted: a tenant is an assertion about who the request belongs to, and
|
|
3401
|
-
* inventing one would be a fabricated claim rather than a correlation aid.
|
|
3402
|
-
*
|
|
3403
|
-
* @param req - The incoming request.
|
|
3404
|
-
* @returns The tenant id, or `undefined`.
|
|
3405
|
-
*/
|
|
3406
|
-
resolveTenantId(req) {
|
|
3407
|
-
const raw = Reflect.get(req.headers, this.tenantIdHeader);
|
|
3408
|
-
return isAcceptableHeaderValue(raw) ? raw : void 0;
|
|
3409
|
-
}
|
|
3410
|
-
};
|
|
3411
|
-
exports.RequestIdMiddleware = __decorateClass([
|
|
3412
|
-
common.Injectable(),
|
|
3413
|
-
__decorateParam(0, common.Inject(exports.LogContextService)),
|
|
3414
|
-
__decorateParam(1, common.Inject(LOGGER_OPTIONS_TOKEN))
|
|
3415
|
-
], exports.RequestIdMiddleware);
|
|
3416
3541
|
|
|
3417
3542
|
// src/server/middlewares/apply-access-log.ts
|
|
3418
3543
|
function resolveDependencies(app) {
|