@bymax-one/nest-logger 1.4.11 → 1.4.12
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 +33 -1
- package/README.md +11 -0
- package/dist/server/index.cjs +502 -461
- package/dist/server/index.d.cts +18 -0
- package/dist/server/index.d.ts +18 -0
- package/dist/server/index.mjs +502 -461
- package/package.json +1 -1
package/dist/server/index.mjs
CHANGED
|
@@ -4,11 +4,11 @@ import { Injectable, Inject, HttpStatus, Catch, ConfigurableModuleBuilder, Modul
|
|
|
4
4
|
import { APP_INTERCEPTOR, APP_FILTER } from '@nestjs/core';
|
|
5
5
|
import { types } from 'util';
|
|
6
6
|
import { tap, catchError, throwError } from 'rxjs';
|
|
7
|
+
import { randomUUID } from 'crypto';
|
|
8
|
+
import { AsyncLocalStorage, AsyncResource } from 'async_hooks';
|
|
7
9
|
import pino from 'pino';
|
|
8
10
|
import { createRequire } from 'module';
|
|
9
11
|
import { Writable } from 'stream';
|
|
10
|
-
import { AsyncLocalStorage, AsyncResource } from 'async_hooks';
|
|
11
|
-
import { randomUUID } from 'crypto';
|
|
12
12
|
|
|
13
13
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
14
14
|
var __decorateClass = (decorators, target, key, kind) => {
|
|
@@ -1283,152 +1283,449 @@ var {
|
|
|
1283
1283
|
// disabled" without a dead nullish branch.
|
|
1284
1284
|
global: extras.isGlobal !== false
|
|
1285
1285
|
})).build();
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
{ length: REDACT_MAX_DEPTH },
|
|
1291
|
-
(_, idx) => "*" + ".*".repeat(idx)
|
|
1292
|
-
);
|
|
1293
|
-
var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
|
|
1294
|
-
var REDACT_COMMON_FIELDS = [
|
|
1295
|
-
// Passwords (5)
|
|
1296
|
-
"password",
|
|
1297
|
-
"passwordHash",
|
|
1298
|
-
"passwordConfirm",
|
|
1299
|
-
"newPassword",
|
|
1300
|
-
"oldPassword",
|
|
1301
|
-
// Tokens (6)
|
|
1302
|
-
"token",
|
|
1303
|
-
"accessToken",
|
|
1304
|
-
"refreshToken",
|
|
1305
|
-
"idToken",
|
|
1306
|
-
"apiKey",
|
|
1307
|
-
"apiSecret",
|
|
1308
|
-
// MFA (3)
|
|
1309
|
-
"mfaSecret",
|
|
1310
|
-
"mfaRecoveryCodes",
|
|
1311
|
-
"totpSecret",
|
|
1312
|
-
// Payment / PCI DSS (5)
|
|
1313
|
-
"cardNumber",
|
|
1314
|
-
"cardCvv",
|
|
1315
|
-
"cvv",
|
|
1316
|
-
"cvc",
|
|
1317
|
-
"cardExpiry",
|
|
1318
|
-
// Personal documents — BR / LGPD (3)
|
|
1319
|
-
"cpf",
|
|
1320
|
-
"cnpj",
|
|
1321
|
-
"rg",
|
|
1322
|
-
// Generic secrets (4) — the most common short-form credential field names
|
|
1323
|
-
"secret",
|
|
1324
|
-
"clientSecret",
|
|
1325
|
-
"signingSecret",
|
|
1326
|
-
"privateKey",
|
|
1327
|
-
// Conservative PII (1) — consumer can disable if logging email is justified
|
|
1328
|
-
"email",
|
|
1329
|
-
// Credential-bearing HTTP header names (5). These also appear in
|
|
1330
|
-
// {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
|
|
1331
|
-
// shapes — which covered ONLY those two shapes. A headers bag logged under any
|
|
1332
|
-
// other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
|
|
1333
|
-
// common things written while debugging an integration) wrote the bearer token
|
|
1334
|
-
// in clear. Listed here as bare names, they are caught wherever they appear.
|
|
1335
|
-
// Node lower-cases inbound header names, so the lower-case spelling is the one
|
|
1336
|
-
// that can actually reach a log.
|
|
1337
|
-
"authorization",
|
|
1338
|
-
"cookie",
|
|
1339
|
-
"set-cookie",
|
|
1340
|
-
"x-api-key",
|
|
1341
|
-
"x-auth-token"
|
|
1342
|
-
];
|
|
1343
|
-
var REDACT_ABSOLUTE_PATHS = [
|
|
1344
|
-
"req.headers.authorization",
|
|
1345
|
-
"req.headers.cookie",
|
|
1346
|
-
'req.headers["x-api-key"]',
|
|
1347
|
-
'req.headers["x-auth-token"]',
|
|
1348
|
-
'res.headers["set-cookie"]'
|
|
1349
|
-
];
|
|
1350
|
-
var DEFAULT_REDACT_PATHS = [
|
|
1351
|
-
...REDACT_COMMON_FIELDS,
|
|
1352
|
-
...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
|
|
1353
|
-
...REDACT_ABSOLUTE_PATHS
|
|
1354
|
-
];
|
|
1355
|
-
|
|
1356
|
-
// src/server/utils/report-destination-failure.util.ts
|
|
1357
|
-
function reportDestinationFailure(logKey, name, cause, msg) {
|
|
1358
|
-
writeStderrSafely(
|
|
1359
|
-
JSON.stringify({
|
|
1360
|
-
level: "error",
|
|
1361
|
-
logKey,
|
|
1362
|
-
destination: toSingleLineMessage(name),
|
|
1363
|
-
err: describeCause(cause),
|
|
1364
|
-
msg: toSingleLineMessage(msg)
|
|
1365
|
-
}) + "\n"
|
|
1366
|
-
);
|
|
1367
|
-
}
|
|
1368
|
-
var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
|
|
1369
|
-
function describeCause(cause) {
|
|
1370
|
-
try {
|
|
1371
|
-
return isError(cause) ? {
|
|
1372
|
-
type: toBoundedMessage(String(cause.name)),
|
|
1373
|
-
message: toBoundedMessage(String(cause.message))
|
|
1374
|
-
} : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
|
|
1375
|
-
} catch {
|
|
1376
|
-
return UNREADABLE_CAUSE;
|
|
1286
|
+
var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
|
|
1287
|
+
var LogContextService = class {
|
|
1288
|
+
constructor() {
|
|
1289
|
+
this.als = new AsyncLocalStorage();
|
|
1377
1290
|
}
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1291
|
+
/**
|
|
1292
|
+
* Run `callback` inside a fresh context scope. Every log emitted
|
|
1293
|
+
* synchronously or asynchronously within the callback inherits `context`.
|
|
1294
|
+
*
|
|
1295
|
+
* **A nested `run()` REPLACES the enclosing context, it does not extend it.**
|
|
1296
|
+
* The scope starts from `context` alone, so a field an outer scope had set —
|
|
1297
|
+
* a `tenantId` resolved at the edge, say — is absent for the whole inner
|
|
1298
|
+
* scope: nothing throws, `get()` simply returns `undefined`, and the field is
|
|
1299
|
+
* missing from every entry the callback emits. Reach for {@link runMerged}
|
|
1300
|
+
* when the inner scope should extend the outer one.
|
|
1301
|
+
*
|
|
1302
|
+
* Replacement is the deliberate default because the opposite leaks: a
|
|
1303
|
+
* background job started inside a request scope would silently inherit the
|
|
1304
|
+
* caller's `userId` and attribute its entries to a user who never triggered
|
|
1305
|
+
* it. A missing field is visibly missing; an inherited one is wrong while
|
|
1306
|
+
* looking right.
|
|
1307
|
+
*
|
|
1308
|
+
* @typeParam T - Return type of the callback.
|
|
1309
|
+
* @param context - Initial context bag for the scope. Becomes the WHOLE scope.
|
|
1310
|
+
* @param callback - Function executed within the scope.
|
|
1311
|
+
* @returns Whatever `callback` returns.
|
|
1312
|
+
* @example
|
|
1313
|
+
* logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
|
|
1314
|
+
* await userService.create(dto) // logs carry requestId + tenantId
|
|
1315
|
+
* })
|
|
1316
|
+
*/
|
|
1317
|
+
run(context, callback) {
|
|
1318
|
+
return this.als.run(this.sanitizeContext(context), callback);
|
|
1384
1319
|
}
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1320
|
+
/**
|
|
1321
|
+
* Run `callback` inside a scope that EXTENDS the enclosing one: the active
|
|
1322
|
+
* context's fields are carried in, and `context` overrides them key by key.
|
|
1323
|
+
*
|
|
1324
|
+
* The explicit counterpart to {@link run}'s replacement semantics, for the
|
|
1325
|
+
* case where an inner scope is genuinely a refinement of the outer — adding a
|
|
1326
|
+
* `userId` once authentication resolved it, without having to restate the
|
|
1327
|
+
* `requestId` the middleware already set.
|
|
1328
|
+
*
|
|
1329
|
+
* Outside any scope there is nothing to merge and this behaves exactly like
|
|
1330
|
+
* {@link run}. Writes inside the new scope never reach the enclosing one: the
|
|
1331
|
+
* merge produces a fresh object, so the outer context is intact after the
|
|
1332
|
+
* callback returns.
|
|
1333
|
+
*
|
|
1334
|
+
* @typeParam T - Return type of the callback.
|
|
1335
|
+
* @param context - Fields to add or override on top of the active context.
|
|
1336
|
+
* @param callback - Function executed within the merged scope.
|
|
1337
|
+
* @returns Whatever `callback` returns.
|
|
1338
|
+
* @example
|
|
1339
|
+
* logContext.run({ requestId: 'r_1' }, () => {
|
|
1340
|
+
* logContext.runMerged({ userId: 'u_1' }, () => {
|
|
1341
|
+
* logContext.get('requestId') // 'r_1' — carried in from the outer scope
|
|
1342
|
+
* })
|
|
1343
|
+
* })
|
|
1344
|
+
*/
|
|
1345
|
+
runMerged(context, callback) {
|
|
1346
|
+
const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
|
|
1347
|
+
return this.als.run(merged, callback);
|
|
1393
1348
|
}
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1349
|
+
/**
|
|
1350
|
+
* Read the active context, or `undefined` when called outside any scope.
|
|
1351
|
+
*
|
|
1352
|
+
* @returns The active `LogContext`, or `undefined`.
|
|
1353
|
+
*/
|
|
1354
|
+
getStore() {
|
|
1355
|
+
return this.als.getStore();
|
|
1399
1356
|
}
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
const
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1357
|
+
/**
|
|
1358
|
+
* Add or override a single field on the active context.
|
|
1359
|
+
*
|
|
1360
|
+
* @param key - Field name to set.
|
|
1361
|
+
* @param value - Field value.
|
|
1362
|
+
* @throws Error When called outside a `run()` scope, or with a prototype-polluting key.
|
|
1363
|
+
*/
|
|
1364
|
+
set(key, value) {
|
|
1365
|
+
const store = this.als.getStore();
|
|
1366
|
+
if (!store) {
|
|
1367
|
+
throw new Error("[LogContextService] set() called outside run() scope");
|
|
1368
|
+
}
|
|
1369
|
+
if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
1370
|
+
throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
|
|
1371
|
+
}
|
|
1372
|
+
Reflect.set(store, key, value);
|
|
1412
1373
|
}
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1374
|
+
/**
|
|
1375
|
+
* Read a single field from the active context.
|
|
1376
|
+
*
|
|
1377
|
+
* @typeParam T - Expected value type (caller-asserted).
|
|
1378
|
+
* @param key - Field name to read.
|
|
1379
|
+
* @returns The value cast to `T`, or `undefined` when unset / out of scope.
|
|
1380
|
+
*/
|
|
1381
|
+
get(key) {
|
|
1382
|
+
const store = this.als.getStore();
|
|
1383
|
+
if (!store) {
|
|
1384
|
+
return void 0;
|
|
1385
|
+
}
|
|
1386
|
+
return Reflect.get(store, key);
|
|
1420
1387
|
}
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1388
|
+
/**
|
|
1389
|
+
* Strip prototype-polluting keys from a caller-supplied context so an own
|
|
1390
|
+
* `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
|
|
1391
|
+
* untrusted payload) can never reach the store — and, via the trace mixin's
|
|
1392
|
+
* `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
|
|
1393
|
+
* but drops the key rather than throwing: a logging concern must never crash
|
|
1394
|
+
* the request that produced it.
|
|
1395
|
+
*
|
|
1396
|
+
* @param context - The raw context bag passed to `run()`.
|
|
1397
|
+
* @returns A shallow copy with any forbidden keys removed.
|
|
1398
|
+
*/
|
|
1399
|
+
sanitizeContext(context) {
|
|
1400
|
+
const safe = {};
|
|
1401
|
+
for (const key of Object.keys(context)) {
|
|
1402
|
+
if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
1403
|
+
Reflect.set(safe, key, Reflect.get(context, key));
|
|
1404
|
+
}
|
|
1426
1405
|
}
|
|
1427
|
-
return
|
|
1428
|
-
} catch (cause) {
|
|
1429
|
-
return isOtelApiMissing(cause) ? { api: void 0 } : { api: void 0, broken: { cause } };
|
|
1406
|
+
return safe;
|
|
1430
1407
|
}
|
|
1431
|
-
}
|
|
1408
|
+
};
|
|
1409
|
+
LogContextService = __decorateClass([
|
|
1410
|
+
Injectable()
|
|
1411
|
+
], LogContextService);
|
|
1412
|
+
|
|
1413
|
+
// src/server/middlewares/request-id.middleware.ts
|
|
1414
|
+
var REQUEST_ID_HEADER = "x-request-id";
|
|
1415
|
+
var MAX_CORRELATION_ID_LENGTH = 256;
|
|
1416
|
+
var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
|
|
1417
|
+
var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
|
|
1418
|
+
function isAcceptableHeaderValue(value) {
|
|
1419
|
+
return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
|
|
1420
|
+
}
|
|
1421
|
+
var RequestIdMiddleware = class {
|
|
1422
|
+
/**
|
|
1423
|
+
* @param logContext - The AsyncLocalStorage-backed context service. Injected by
|
|
1424
|
+
* token explicitly: the package is bundled without `emitDecoratorMetadata`,
|
|
1425
|
+
* so implicit class-type injection would not resolve.
|
|
1426
|
+
* @param options - Resolved module options (read for `http.tenantIdHeader` and
|
|
1427
|
+
* `http.shouldGenerateRequestId`).
|
|
1428
|
+
*/
|
|
1429
|
+
constructor(logContext, options) {
|
|
1430
|
+
this.logContext = logContext;
|
|
1431
|
+
this.tenantIdHeader = options.http.tenantIdHeader;
|
|
1432
|
+
this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
|
|
1433
|
+
}
|
|
1434
|
+
/**
|
|
1435
|
+
* Echo or mint the `x-request-id`, expose it on the response, and run the
|
|
1436
|
+
* remainder of the request inside its own log-context scope.
|
|
1437
|
+
*
|
|
1438
|
+
* Idempotent: mounting this middleware twice on the same request mints one id,
|
|
1439
|
+
* not two. The request gets its OWN store, started from the enclosing scope's
|
|
1440
|
+
* correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
|
|
1441
|
+
* else, because no other field can be known to belong to this request.
|
|
1442
|
+
*
|
|
1443
|
+
* An enclosing scope's `requestId` is never adopted and never echoed: adoption
|
|
1444
|
+
* reads a value this middleware recorded on the REQUEST, which a scope opened
|
|
1445
|
+
* elsewhere does not have. What the two generation modes do with one, measured
|
|
1446
|
+
* on two requests sharing a long-lived enclosing scope:
|
|
1447
|
+
*
|
|
1448
|
+
* - `shouldGenerateRequestId: true` (default) — each request mints its own
|
|
1449
|
+
* id, the two requests differ, and the enclosing value reaches neither the
|
|
1450
|
+
* header nor the entries.
|
|
1451
|
+
* - `shouldGenerateRequestId: false` with no inbound header — nothing is
|
|
1452
|
+
* minted, so the request scope inherits the enclosing `requestId` and every
|
|
1453
|
+
* request inside that scope logs under it. No header is exposed. That is
|
|
1454
|
+
* the consumer's own scope being inherited, not correlation being reused,
|
|
1455
|
+
* and it is the configuration that says the gateway owns the id.
|
|
1456
|
+
*
|
|
1457
|
+
* @param req - The incoming request (Express satisfies the contract).
|
|
1458
|
+
* @param res - The outgoing response (Express satisfies the contract).
|
|
1459
|
+
* @param next - The next handler in the chain.
|
|
1460
|
+
*/
|
|
1461
|
+
use(req, res, next) {
|
|
1462
|
+
if (isCorrelationOpened(req)) {
|
|
1463
|
+
const ownRequestId = readOwnRequestId(req);
|
|
1464
|
+
if (ownRequestId !== void 0) {
|
|
1465
|
+
this.adoptExistingScope(ownRequestId, req, res);
|
|
1466
|
+
}
|
|
1467
|
+
next();
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
markCorrelationOpened(req);
|
|
1471
|
+
const context = this.inheritableContext();
|
|
1472
|
+
const requestId = this.resolveRequestId(req);
|
|
1473
|
+
if (requestId !== void 0) {
|
|
1474
|
+
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
1475
|
+
context.requestId = requestId;
|
|
1476
|
+
markOwnRequestId(req, requestId);
|
|
1477
|
+
}
|
|
1478
|
+
if (context.tenantId === void 0) {
|
|
1479
|
+
const tenantId = this.resolveTenantId(req);
|
|
1480
|
+
if (tenantId !== void 0) {
|
|
1481
|
+
context.tenantId = tenantId;
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
this.logContext.run(context, () => next());
|
|
1485
|
+
}
|
|
1486
|
+
/**
|
|
1487
|
+
* The enclosing scope's fields that a request scope may start from.
|
|
1488
|
+
*
|
|
1489
|
+
* Plain `run()` would discard everything the caller had set and a plain merge
|
|
1490
|
+
* would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
|
|
1491
|
+
* the middle a request scope actually needs.
|
|
1492
|
+
*
|
|
1493
|
+
* @returns A fresh bag, never the enclosing store itself, so writes inside the
|
|
1494
|
+
* request never reach the scope that opened it.
|
|
1495
|
+
*/
|
|
1496
|
+
inheritableContext() {
|
|
1497
|
+
const store = { ...this.logContext.getStore() };
|
|
1498
|
+
const inherited = {};
|
|
1499
|
+
for (const key of INHERITABLE_CONTEXT_KEYS) {
|
|
1500
|
+
const value = Reflect.get(store, key);
|
|
1501
|
+
if (value !== void 0) {
|
|
1502
|
+
Reflect.set(inherited, key, value);
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
return inherited;
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Second mount on a request that already carries a correlation id: echo the id
|
|
1509
|
+
* onto the response and fill in a tenant the scope does not have yet, without
|
|
1510
|
+
* opening another scope.
|
|
1511
|
+
*
|
|
1512
|
+
* Nothing is minted and nothing already set is overwritten, so a third mount —
|
|
1513
|
+
* or a thirtieth — changes nothing. The response header is written on every
|
|
1514
|
+
* pass because the enclosing scope may have been opened by consumer code that
|
|
1515
|
+
* never exposed it.
|
|
1516
|
+
*
|
|
1517
|
+
* @param requestId - The id already in scope, which wins.
|
|
1518
|
+
* @param req - The incoming request, read for the tenant header.
|
|
1519
|
+
* @param res - The outgoing response, where the effective id is exposed.
|
|
1520
|
+
*/
|
|
1521
|
+
adoptExistingScope(requestId, req, res) {
|
|
1522
|
+
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
1523
|
+
this.logContext.set("requestId", requestId);
|
|
1524
|
+
if (this.logContext.get("tenantId") === void 0) {
|
|
1525
|
+
const tenantId = this.resolveTenantId(req);
|
|
1526
|
+
if (tenantId !== void 0) {
|
|
1527
|
+
this.logContext.set("tenantId", tenantId);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* The correlation id for this request: the inbound header when acceptable,
|
|
1533
|
+
* otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
|
|
1534
|
+
* off and the caller sent none, which leaves correlation to the upstream
|
|
1535
|
+
* gateway.
|
|
1536
|
+
*
|
|
1537
|
+
* @param req - The incoming request.
|
|
1538
|
+
* @returns The id, or `undefined` when none is available and none is minted.
|
|
1539
|
+
*/
|
|
1540
|
+
resolveRequestId(req) {
|
|
1541
|
+
const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
|
|
1542
|
+
const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
|
|
1543
|
+
return fromHeader ?? (this.shouldGenerateRequestId ? randomUUID() : void 0);
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* The tenant id carried by the configured header, when it is acceptable.
|
|
1547
|
+
*
|
|
1548
|
+
* Never minted: a tenant is an assertion about who the request belongs to, and
|
|
1549
|
+
* inventing one would be a fabricated claim rather than a correlation aid.
|
|
1550
|
+
*
|
|
1551
|
+
* @param req - The incoming request.
|
|
1552
|
+
* @returns The tenant id, or `undefined`.
|
|
1553
|
+
*/
|
|
1554
|
+
resolveTenantId(req) {
|
|
1555
|
+
const raw = Reflect.get(req.headers, this.tenantIdHeader);
|
|
1556
|
+
return isAcceptableHeaderValue(raw) ? raw : void 0;
|
|
1557
|
+
}
|
|
1558
|
+
};
|
|
1559
|
+
RequestIdMiddleware = __decorateClass([
|
|
1560
|
+
Injectable(),
|
|
1561
|
+
__decorateParam(0, Inject(LogContextService)),
|
|
1562
|
+
__decorateParam(1, Inject(LOGGER_OPTIONS_TOKEN))
|
|
1563
|
+
], RequestIdMiddleware);
|
|
1564
|
+
|
|
1565
|
+
// src/server/middlewares/apply-request-context.ts
|
|
1566
|
+
function applyRequestContext(app) {
|
|
1567
|
+
let requestId;
|
|
1568
|
+
try {
|
|
1569
|
+
requestId = new RequestIdMiddleware(
|
|
1570
|
+
app.get(LogContextService),
|
|
1571
|
+
app.get(LOGGER_OPTIONS_TOKEN)
|
|
1572
|
+
);
|
|
1573
|
+
} catch (cause) {
|
|
1574
|
+
throw new Error(
|
|
1575
|
+
"[BymaxLoggerModule] useRequestContext(app) called but BymaxLoggerModule was not imported",
|
|
1576
|
+
{ cause }
|
|
1577
|
+
);
|
|
1578
|
+
}
|
|
1579
|
+
app.use((req, res, next) => {
|
|
1580
|
+
requestId.use(req, res, next);
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
// src/server/constants/default-redact-paths.constants.ts
|
|
1585
|
+
var REDACT_MAX_DEPTH = 4;
|
|
1586
|
+
var WILDCARD_PREFIXES = Array.from(
|
|
1587
|
+
{ length: REDACT_MAX_DEPTH },
|
|
1588
|
+
(_, idx) => "*" + ".*".repeat(idx)
|
|
1589
|
+
);
|
|
1590
|
+
var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
|
|
1591
|
+
var REDACT_COMMON_FIELDS = [
|
|
1592
|
+
// Passwords (5)
|
|
1593
|
+
"password",
|
|
1594
|
+
"passwordHash",
|
|
1595
|
+
"passwordConfirm",
|
|
1596
|
+
"newPassword",
|
|
1597
|
+
"oldPassword",
|
|
1598
|
+
// Tokens (6)
|
|
1599
|
+
"token",
|
|
1600
|
+
"accessToken",
|
|
1601
|
+
"refreshToken",
|
|
1602
|
+
"idToken",
|
|
1603
|
+
"apiKey",
|
|
1604
|
+
"apiSecret",
|
|
1605
|
+
// MFA (3)
|
|
1606
|
+
"mfaSecret",
|
|
1607
|
+
"mfaRecoveryCodes",
|
|
1608
|
+
"totpSecret",
|
|
1609
|
+
// Payment / PCI DSS (5)
|
|
1610
|
+
"cardNumber",
|
|
1611
|
+
"cardCvv",
|
|
1612
|
+
"cvv",
|
|
1613
|
+
"cvc",
|
|
1614
|
+
"cardExpiry",
|
|
1615
|
+
// Personal documents — BR / LGPD (3)
|
|
1616
|
+
"cpf",
|
|
1617
|
+
"cnpj",
|
|
1618
|
+
"rg",
|
|
1619
|
+
// Generic secrets (4) — the most common short-form credential field names
|
|
1620
|
+
"secret",
|
|
1621
|
+
"clientSecret",
|
|
1622
|
+
"signingSecret",
|
|
1623
|
+
"privateKey",
|
|
1624
|
+
// Conservative PII (1) — consumer can disable if logging email is justified
|
|
1625
|
+
"email",
|
|
1626
|
+
// Credential-bearing HTTP header names (5). These also appear in
|
|
1627
|
+
// {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
|
|
1628
|
+
// shapes — which covered ONLY those two shapes. A headers bag logged under any
|
|
1629
|
+
// other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
|
|
1630
|
+
// common things written while debugging an integration) wrote the bearer token
|
|
1631
|
+
// in clear. Listed here as bare names, they are caught wherever they appear.
|
|
1632
|
+
// Node lower-cases inbound header names, so the lower-case spelling is the one
|
|
1633
|
+
// that can actually reach a log.
|
|
1634
|
+
"authorization",
|
|
1635
|
+
"cookie",
|
|
1636
|
+
"set-cookie",
|
|
1637
|
+
"x-api-key",
|
|
1638
|
+
"x-auth-token"
|
|
1639
|
+
];
|
|
1640
|
+
var REDACT_ABSOLUTE_PATHS = [
|
|
1641
|
+
"req.headers.authorization",
|
|
1642
|
+
"req.headers.cookie",
|
|
1643
|
+
'req.headers["x-api-key"]',
|
|
1644
|
+
'req.headers["x-auth-token"]',
|
|
1645
|
+
'res.headers["set-cookie"]'
|
|
1646
|
+
];
|
|
1647
|
+
var DEFAULT_REDACT_PATHS = [
|
|
1648
|
+
...REDACT_COMMON_FIELDS,
|
|
1649
|
+
...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
|
|
1650
|
+
...REDACT_ABSOLUTE_PATHS
|
|
1651
|
+
];
|
|
1652
|
+
|
|
1653
|
+
// src/server/utils/report-destination-failure.util.ts
|
|
1654
|
+
function reportDestinationFailure(logKey, name, cause, msg) {
|
|
1655
|
+
writeStderrSafely(
|
|
1656
|
+
JSON.stringify({
|
|
1657
|
+
level: "error",
|
|
1658
|
+
logKey,
|
|
1659
|
+
destination: toSingleLineMessage(name),
|
|
1660
|
+
err: describeCause(cause),
|
|
1661
|
+
msg: toSingleLineMessage(msg)
|
|
1662
|
+
}) + "\n"
|
|
1663
|
+
);
|
|
1664
|
+
}
|
|
1665
|
+
var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
|
|
1666
|
+
function describeCause(cause) {
|
|
1667
|
+
try {
|
|
1668
|
+
return isError(cause) ? {
|
|
1669
|
+
type: toBoundedMessage(String(cause.name)),
|
|
1670
|
+
message: toBoundedMessage(String(cause.message))
|
|
1671
|
+
} : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
|
|
1672
|
+
} catch {
|
|
1673
|
+
return UNREADABLE_CAUSE;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
function safeDestinationName(destination) {
|
|
1677
|
+
try {
|
|
1678
|
+
return String(destination.name);
|
|
1679
|
+
} catch {
|
|
1680
|
+
return "unknown";
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
function isLogLevel(value) {
|
|
1684
|
+
return LOG_LEVEL_PRIORITY.includes(value);
|
|
1685
|
+
}
|
|
1686
|
+
var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
|
|
1687
|
+
function safeMinLevel(destination) {
|
|
1688
|
+
if (resolvedMinLevels.has(destination)) {
|
|
1689
|
+
return resolvedMinLevels.get(destination);
|
|
1690
|
+
}
|
|
1691
|
+
let resolved;
|
|
1692
|
+
try {
|
|
1693
|
+
const read = destination.minLevel;
|
|
1694
|
+
resolved = isLogLevel(read) ? read : void 0;
|
|
1695
|
+
} catch {
|
|
1696
|
+
}
|
|
1697
|
+
resolvedMinLevels.set(destination, resolved);
|
|
1698
|
+
return resolved;
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
// src/server/utils/otel-detector.ts
|
|
1702
|
+
var brokenInstallWarned = false;
|
|
1703
|
+
function isOtelApiMissing(cause) {
|
|
1704
|
+
try {
|
|
1705
|
+
const { code, message } = cause;
|
|
1706
|
+
return code === "MODULE_NOT_FOUND" && /^Cannot find module '@opentelemetry\/api'/.test(String(message));
|
|
1707
|
+
} catch {
|
|
1708
|
+
return false;
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
function loadTraceApiFrom(anchor) {
|
|
1712
|
+
let from;
|
|
1713
|
+
try {
|
|
1714
|
+
from = anchor();
|
|
1715
|
+
} catch {
|
|
1716
|
+
return { api: void 0 };
|
|
1717
|
+
}
|
|
1718
|
+
try {
|
|
1719
|
+
const mod = createRequire(from)("@opentelemetry/api");
|
|
1720
|
+
const trace = typeof mod === "object" && mod !== null || typeof mod === "function" ? mod.trace : void 0;
|
|
1721
|
+
if (typeof trace?.getActiveSpan !== "function") {
|
|
1722
|
+
throw new TypeError("@opentelemetry/api resolved but exports no usable `trace` namespace");
|
|
1723
|
+
}
|
|
1724
|
+
return { api: trace };
|
|
1725
|
+
} catch (cause) {
|
|
1726
|
+
return isOtelApiMissing(cause) ? { api: void 0 } : { api: void 0, broken: { cause } };
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1432
1729
|
function warnBrokenInstallOnce(cause) {
|
|
1433
1730
|
if (brokenInstallWarned) {
|
|
1434
1731
|
return;
|
|
@@ -2559,190 +2856,64 @@ var DestinationRegistry = class {
|
|
|
2559
2856
|
} catch (cause) {
|
|
2560
2857
|
this.reportShutdownFailure(destination, cause);
|
|
2561
2858
|
}
|
|
2562
|
-
}
|
|
2563
|
-
}
|
|
2564
|
-
/**
|
|
2565
|
-
* Report a failing `onShutdown` on stderr without letting the report itself
|
|
2566
|
-
* abort the teardown of the destinations still queued behind it.
|
|
2567
|
-
*
|
|
2568
|
-
* The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
|
|
2569
|
-
* an `Error` with hostile getters, and `String(cause)` on a value with a
|
|
2570
|
-
* throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
|
|
2571
|
-
* the `catch` that exists to keep one bad sink from mattering, so an escape
|
|
2572
|
-
* here would propagate out of `onApplicationShutdown` and skip every remaining
|
|
2573
|
-
* destination's flush. The never-throw contract has to cover READING the value,
|
|
2574
|
-
* not just writing it, which is the same correction `reportDestinationFailure`
|
|
2575
|
-
* already carries.
|
|
2576
|
-
*
|
|
2577
|
-
* The text is escaped for the same reason every other terminal-bound path is:
|
|
2578
|
-
* a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
|
|
2579
|
-
* newlines and neutralizes everything else that can drive a terminal.
|
|
2580
|
-
*
|
|
2581
|
-
* The DESTINATION is passed rather than its name, so that read happens in here
|
|
2582
|
-
* too. `name` is declared `readonly name: string` but nothing stops a consumer
|
|
2583
|
-
* implementing it as a getter, and reading it at the call site would put it back
|
|
2584
|
-
* outside the guard — inside the `catch`, where a throw has the same cost.
|
|
2585
|
-
*
|
|
2586
|
-
* Two separate guards, not one: a name that cannot be read must not also cost
|
|
2587
|
-
* the failure detail, and a detail that cannot be read must not cost the name.
|
|
2588
|
-
* Either alone still identifies which sink failed.
|
|
2589
|
-
*
|
|
2590
|
-
* @param destination - The destination whose `onShutdown` threw.
|
|
2591
|
-
* @param cause - The thrown value, of any shape.
|
|
2592
|
-
*/
|
|
2593
|
-
reportShutdownFailure(destination, cause) {
|
|
2594
|
-
const name = toSingleLineMessage(safeDestinationName(destination));
|
|
2595
|
-
let detail = "UnknownError";
|
|
2596
|
-
try {
|
|
2597
|
-
const stack = isErrorLike(cause) ? cause.stack : void 0;
|
|
2598
|
-
detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
|
|
2599
|
-
} catch {
|
|
2600
|
-
}
|
|
2601
|
-
writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
|
|
2602
|
-
`);
|
|
2603
|
-
}
|
|
2604
|
-
/**
|
|
2605
|
-
* The destinations that initialized successfully.
|
|
2606
|
-
*
|
|
2607
|
-
* @returns A read-only view of the active destination set.
|
|
2608
|
-
*/
|
|
2609
|
-
getActive() {
|
|
2610
|
-
return this.active;
|
|
2611
|
-
}
|
|
2612
|
-
};
|
|
2613
|
-
DestinationRegistry = __decorateClass([
|
|
2614
|
-
Injectable(),
|
|
2615
|
-
__decorateParam(0, Inject(LOGGER_DESTINATIONS_TOKEN)),
|
|
2616
|
-
__decorateParam(1, Inject(PinoLoggerService)),
|
|
2617
|
-
__decorateParam(2, Inject(LOGGER_OPTIONS_TOKEN)),
|
|
2618
|
-
__decorateParam(3, Inject(DestinationHealth))
|
|
2619
|
-
], DestinationRegistry);
|
|
2620
|
-
var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
|
|
2621
|
-
var LogContextService = class {
|
|
2622
|
-
constructor() {
|
|
2623
|
-
this.als = new AsyncLocalStorage();
|
|
2624
|
-
}
|
|
2625
|
-
/**
|
|
2626
|
-
* Run `callback` inside a fresh context scope. Every log emitted
|
|
2627
|
-
* synchronously or asynchronously within the callback inherits `context`.
|
|
2628
|
-
*
|
|
2629
|
-
* **A nested `run()` REPLACES the enclosing context, it does not extend it.**
|
|
2630
|
-
* The scope starts from `context` alone, so a field an outer scope had set —
|
|
2631
|
-
* a `tenantId` resolved at the edge, say — is absent for the whole inner
|
|
2632
|
-
* scope: nothing throws, `get()` simply returns `undefined`, and the field is
|
|
2633
|
-
* missing from every entry the callback emits. Reach for {@link runMerged}
|
|
2634
|
-
* when the inner scope should extend the outer one.
|
|
2635
|
-
*
|
|
2636
|
-
* Replacement is the deliberate default because the opposite leaks: a
|
|
2637
|
-
* background job started inside a request scope would silently inherit the
|
|
2638
|
-
* caller's `userId` and attribute its entries to a user who never triggered
|
|
2639
|
-
* it. A missing field is visibly missing; an inherited one is wrong while
|
|
2640
|
-
* looking right.
|
|
2641
|
-
*
|
|
2642
|
-
* @typeParam T - Return type of the callback.
|
|
2643
|
-
* @param context - Initial context bag for the scope. Becomes the WHOLE scope.
|
|
2644
|
-
* @param callback - Function executed within the scope.
|
|
2645
|
-
* @returns Whatever `callback` returns.
|
|
2646
|
-
* @example
|
|
2647
|
-
* logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
|
|
2648
|
-
* await userService.create(dto) // logs carry requestId + tenantId
|
|
2649
|
-
* })
|
|
2650
|
-
*/
|
|
2651
|
-
run(context, callback) {
|
|
2652
|
-
return this.als.run(this.sanitizeContext(context), callback);
|
|
2653
|
-
}
|
|
2654
|
-
/**
|
|
2655
|
-
* Run `callback` inside a scope that EXTENDS the enclosing one: the active
|
|
2656
|
-
* context's fields are carried in, and `context` overrides them key by key.
|
|
2657
|
-
*
|
|
2658
|
-
* The explicit counterpart to {@link run}'s replacement semantics, for the
|
|
2659
|
-
* case where an inner scope is genuinely a refinement of the outer — adding a
|
|
2660
|
-
* `userId` once authentication resolved it, without having to restate the
|
|
2661
|
-
* `requestId` the middleware already set.
|
|
2662
|
-
*
|
|
2663
|
-
* Outside any scope there is nothing to merge and this behaves exactly like
|
|
2664
|
-
* {@link run}. Writes inside the new scope never reach the enclosing one: the
|
|
2665
|
-
* merge produces a fresh object, so the outer context is intact after the
|
|
2666
|
-
* callback returns.
|
|
2667
|
-
*
|
|
2668
|
-
* @typeParam T - Return type of the callback.
|
|
2669
|
-
* @param context - Fields to add or override on top of the active context.
|
|
2670
|
-
* @param callback - Function executed within the merged scope.
|
|
2671
|
-
* @returns Whatever `callback` returns.
|
|
2672
|
-
* @example
|
|
2673
|
-
* logContext.run({ requestId: 'r_1' }, () => {
|
|
2674
|
-
* logContext.runMerged({ userId: 'u_1' }, () => {
|
|
2675
|
-
* logContext.get('requestId') // 'r_1' — carried in from the outer scope
|
|
2676
|
-
* })
|
|
2677
|
-
* })
|
|
2678
|
-
*/
|
|
2679
|
-
runMerged(context, callback) {
|
|
2680
|
-
const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
|
|
2681
|
-
return this.als.run(merged, callback);
|
|
2859
|
+
}
|
|
2682
2860
|
}
|
|
2683
2861
|
/**
|
|
2684
|
-
*
|
|
2862
|
+
* Report a failing `onShutdown` on stderr without letting the report itself
|
|
2863
|
+
* abort the teardown of the destinations still queued behind it.
|
|
2685
2864
|
*
|
|
2686
|
-
*
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
*
|
|
2865
|
+
* The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
|
|
2866
|
+
* an `Error` with hostile getters, and `String(cause)` on a value with a
|
|
2867
|
+
* throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
|
|
2868
|
+
* the `catch` that exists to keep one bad sink from mattering, so an escape
|
|
2869
|
+
* here would propagate out of `onApplicationShutdown` and skip every remaining
|
|
2870
|
+
* destination's flush. The never-throw contract has to cover READING the value,
|
|
2871
|
+
* not just writing it, which is the same correction `reportDestinationFailure`
|
|
2872
|
+
* already carries.
|
|
2693
2873
|
*
|
|
2694
|
-
*
|
|
2695
|
-
*
|
|
2696
|
-
*
|
|
2697
|
-
*/
|
|
2698
|
-
set(key, value) {
|
|
2699
|
-
const store = this.als.getStore();
|
|
2700
|
-
if (!store) {
|
|
2701
|
-
throw new Error("[LogContextService] set() called outside run() scope");
|
|
2702
|
-
}
|
|
2703
|
-
if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
2704
|
-
throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
|
|
2705
|
-
}
|
|
2706
|
-
Reflect.set(store, key, value);
|
|
2707
|
-
}
|
|
2708
|
-
/**
|
|
2709
|
-
* Read a single field from the active context.
|
|
2874
|
+
* The text is escaped for the same reason every other terminal-bound path is:
|
|
2875
|
+
* a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
|
|
2876
|
+
* newlines and neutralizes everything else that can drive a terminal.
|
|
2710
2877
|
*
|
|
2711
|
-
*
|
|
2712
|
-
*
|
|
2713
|
-
*
|
|
2878
|
+
* The DESTINATION is passed rather than its name, so that read happens in here
|
|
2879
|
+
* too. `name` is declared `readonly name: string` but nothing stops a consumer
|
|
2880
|
+
* implementing it as a getter, and reading it at the call site would put it back
|
|
2881
|
+
* outside the guard — inside the `catch`, where a throw has the same cost.
|
|
2882
|
+
*
|
|
2883
|
+
* Two separate guards, not one: a name that cannot be read must not also cost
|
|
2884
|
+
* the failure detail, and a detail that cannot be read must not cost the name.
|
|
2885
|
+
* Either alone still identifies which sink failed.
|
|
2886
|
+
*
|
|
2887
|
+
* @param destination - The destination whose `onShutdown` threw.
|
|
2888
|
+
* @param cause - The thrown value, of any shape.
|
|
2714
2889
|
*/
|
|
2715
|
-
|
|
2716
|
-
const
|
|
2717
|
-
|
|
2718
|
-
|
|
2890
|
+
reportShutdownFailure(destination, cause) {
|
|
2891
|
+
const name = toSingleLineMessage(safeDestinationName(destination));
|
|
2892
|
+
let detail = "UnknownError";
|
|
2893
|
+
try {
|
|
2894
|
+
const stack = isErrorLike(cause) ? cause.stack : void 0;
|
|
2895
|
+
detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
|
|
2896
|
+
} catch {
|
|
2719
2897
|
}
|
|
2720
|
-
|
|
2898
|
+
writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
|
|
2899
|
+
`);
|
|
2721
2900
|
}
|
|
2722
2901
|
/**
|
|
2723
|
-
*
|
|
2724
|
-
* `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
|
|
2725
|
-
* untrusted payload) can never reach the store — and, via the trace mixin's
|
|
2726
|
-
* `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
|
|
2727
|
-
* but drops the key rather than throwing: a logging concern must never crash
|
|
2728
|
-
* the request that produced it.
|
|
2902
|
+
* The destinations that initialized successfully.
|
|
2729
2903
|
*
|
|
2730
|
-
* @
|
|
2731
|
-
* @returns A shallow copy with any forbidden keys removed.
|
|
2904
|
+
* @returns A read-only view of the active destination set.
|
|
2732
2905
|
*/
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
for (const key of Object.keys(context)) {
|
|
2736
|
-
if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
2737
|
-
Reflect.set(safe, key, Reflect.get(context, key));
|
|
2738
|
-
}
|
|
2739
|
-
}
|
|
2740
|
-
return safe;
|
|
2906
|
+
getActive() {
|
|
2907
|
+
return this.active;
|
|
2741
2908
|
}
|
|
2742
2909
|
};
|
|
2743
|
-
|
|
2744
|
-
Injectable()
|
|
2745
|
-
|
|
2910
|
+
DestinationRegistry = __decorateClass([
|
|
2911
|
+
Injectable(),
|
|
2912
|
+
__decorateParam(0, Inject(LOGGER_DESTINATIONS_TOKEN)),
|
|
2913
|
+
__decorateParam(1, Inject(PinoLoggerService)),
|
|
2914
|
+
__decorateParam(2, Inject(LOGGER_OPTIONS_TOKEN)),
|
|
2915
|
+
__decorateParam(3, Inject(DestinationHealth))
|
|
2916
|
+
], DestinationRegistry);
|
|
2746
2917
|
|
|
2747
2918
|
// src/server/logger.module.ts
|
|
2748
2919
|
function resolveDestinations(options) {
|
|
@@ -2910,6 +3081,26 @@ var BymaxLoggerModule = class extends BymaxLoggerModuleBase {
|
|
|
2910
3081
|
app.useLogger(logger);
|
|
2911
3082
|
app.flushLogs();
|
|
2912
3083
|
}
|
|
3084
|
+
/**
|
|
3085
|
+
* Open the request-id correlation scope ahead of the body parser, so a request the parser
|
|
3086
|
+
* refuses (malformed JSON, an unsupported content encoding, a body over the limit) still has its
|
|
3087
|
+
* `requestId`, and the `x-request-id` response header, where an exception filter reads it.
|
|
3088
|
+
*
|
|
3089
|
+
* Call once in `main.ts` AFTER creating the app and BEFORE `app.init()` / `app.listen(...)`.
|
|
3090
|
+
* It mounts only the scope. `applyAccessLog(app)` and `applyRequestIdMiddleware(consumer)` can
|
|
3091
|
+
* be used as well: a second mount of the middleware reuses the scope this one opened.
|
|
3092
|
+
*
|
|
3093
|
+
* @param app - The Nest application returned by `NestFactory.create()`.
|
|
3094
|
+
* @throws Error When `BymaxLoggerModule` was not imported.
|
|
3095
|
+
* @example
|
|
3096
|
+
* const app = await NestFactory.create(AppModule, { bufferLogs: true })
|
|
3097
|
+
* BymaxLoggerModule.useNestLogger(app)
|
|
3098
|
+
* BymaxLoggerModule.useRequestContext(app)
|
|
3099
|
+
* await app.listen(3000)
|
|
3100
|
+
*/
|
|
3101
|
+
static useRequestContext(app) {
|
|
3102
|
+
applyRequestContext(app);
|
|
3103
|
+
}
|
|
2913
3104
|
};
|
|
2914
3105
|
BymaxLoggerModule = __decorateClass([
|
|
2915
3106
|
Module({})
|
|
@@ -3260,156 +3451,6 @@ HttpAccessLogMiddleware = __decorateClass([
|
|
|
3260
3451
|
__decorateParam(1, Inject(LogContextService)),
|
|
3261
3452
|
__decorateParam(2, Inject(LOGGER_OPTIONS_TOKEN))
|
|
3262
3453
|
], HttpAccessLogMiddleware);
|
|
3263
|
-
var REQUEST_ID_HEADER = "x-request-id";
|
|
3264
|
-
var MAX_CORRELATION_ID_LENGTH = 256;
|
|
3265
|
-
var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
|
|
3266
|
-
var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
|
|
3267
|
-
function isAcceptableHeaderValue(value) {
|
|
3268
|
-
return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
|
|
3269
|
-
}
|
|
3270
|
-
var RequestIdMiddleware = class {
|
|
3271
|
-
/**
|
|
3272
|
-
* @param logContext - The AsyncLocalStorage-backed context service. Injected by
|
|
3273
|
-
* token explicitly: the package is bundled without `emitDecoratorMetadata`,
|
|
3274
|
-
* so implicit class-type injection would not resolve.
|
|
3275
|
-
* @param options - Resolved module options (read for `http.tenantIdHeader` and
|
|
3276
|
-
* `http.shouldGenerateRequestId`).
|
|
3277
|
-
*/
|
|
3278
|
-
constructor(logContext, options) {
|
|
3279
|
-
this.logContext = logContext;
|
|
3280
|
-
this.tenantIdHeader = options.http.tenantIdHeader;
|
|
3281
|
-
this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
|
|
3282
|
-
}
|
|
3283
|
-
/**
|
|
3284
|
-
* Echo or mint the `x-request-id`, expose it on the response, and run the
|
|
3285
|
-
* remainder of the request inside its own log-context scope.
|
|
3286
|
-
*
|
|
3287
|
-
* Idempotent: mounting this middleware twice on the same request mints one id,
|
|
3288
|
-
* not two. The request gets its OWN store, started from the enclosing scope's
|
|
3289
|
-
* correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
|
|
3290
|
-
* else, because no other field can be known to belong to this request.
|
|
3291
|
-
*
|
|
3292
|
-
* An enclosing scope's `requestId` is never adopted and never echoed: adoption
|
|
3293
|
-
* reads a value this middleware recorded on the REQUEST, which a scope opened
|
|
3294
|
-
* elsewhere does not have. What the two generation modes do with one, measured
|
|
3295
|
-
* on two requests sharing a long-lived enclosing scope:
|
|
3296
|
-
*
|
|
3297
|
-
* - `shouldGenerateRequestId: true` (default) — each request mints its own
|
|
3298
|
-
* id, the two requests differ, and the enclosing value reaches neither the
|
|
3299
|
-
* header nor the entries.
|
|
3300
|
-
* - `shouldGenerateRequestId: false` with no inbound header — nothing is
|
|
3301
|
-
* minted, so the request scope inherits the enclosing `requestId` and every
|
|
3302
|
-
* request inside that scope logs under it. No header is exposed. That is
|
|
3303
|
-
* the consumer's own scope being inherited, not correlation being reused,
|
|
3304
|
-
* and it is the configuration that says the gateway owns the id.
|
|
3305
|
-
*
|
|
3306
|
-
* @param req - The incoming request (Express satisfies the contract).
|
|
3307
|
-
* @param res - The outgoing response (Express satisfies the contract).
|
|
3308
|
-
* @param next - The next handler in the chain.
|
|
3309
|
-
*/
|
|
3310
|
-
use(req, res, next) {
|
|
3311
|
-
if (isCorrelationOpened(req)) {
|
|
3312
|
-
const ownRequestId = readOwnRequestId(req);
|
|
3313
|
-
if (ownRequestId !== void 0) {
|
|
3314
|
-
this.adoptExistingScope(ownRequestId, req, res);
|
|
3315
|
-
}
|
|
3316
|
-
next();
|
|
3317
|
-
return;
|
|
3318
|
-
}
|
|
3319
|
-
markCorrelationOpened(req);
|
|
3320
|
-
const context = this.inheritableContext();
|
|
3321
|
-
const requestId = this.resolveRequestId(req);
|
|
3322
|
-
if (requestId !== void 0) {
|
|
3323
|
-
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
3324
|
-
context.requestId = requestId;
|
|
3325
|
-
markOwnRequestId(req, requestId);
|
|
3326
|
-
}
|
|
3327
|
-
if (context.tenantId === void 0) {
|
|
3328
|
-
const tenantId = this.resolveTenantId(req);
|
|
3329
|
-
if (tenantId !== void 0) {
|
|
3330
|
-
context.tenantId = tenantId;
|
|
3331
|
-
}
|
|
3332
|
-
}
|
|
3333
|
-
this.logContext.run(context, () => next());
|
|
3334
|
-
}
|
|
3335
|
-
/**
|
|
3336
|
-
* The enclosing scope's fields that a request scope may start from.
|
|
3337
|
-
*
|
|
3338
|
-
* Plain `run()` would discard everything the caller had set and a plain merge
|
|
3339
|
-
* would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
|
|
3340
|
-
* the middle a request scope actually needs.
|
|
3341
|
-
*
|
|
3342
|
-
* @returns A fresh bag, never the enclosing store itself, so writes inside the
|
|
3343
|
-
* request never reach the scope that opened it.
|
|
3344
|
-
*/
|
|
3345
|
-
inheritableContext() {
|
|
3346
|
-
const store = { ...this.logContext.getStore() };
|
|
3347
|
-
const inherited = {};
|
|
3348
|
-
for (const key of INHERITABLE_CONTEXT_KEYS) {
|
|
3349
|
-
const value = Reflect.get(store, key);
|
|
3350
|
-
if (value !== void 0) {
|
|
3351
|
-
Reflect.set(inherited, key, value);
|
|
3352
|
-
}
|
|
3353
|
-
}
|
|
3354
|
-
return inherited;
|
|
3355
|
-
}
|
|
3356
|
-
/**
|
|
3357
|
-
* Second mount on a request that already carries a correlation id: echo the id
|
|
3358
|
-
* onto the response and fill in a tenant the scope does not have yet, without
|
|
3359
|
-
* opening another scope.
|
|
3360
|
-
*
|
|
3361
|
-
* Nothing is minted and nothing already set is overwritten, so a third mount —
|
|
3362
|
-
* or a thirtieth — changes nothing. The response header is written on every
|
|
3363
|
-
* pass because the enclosing scope may have been opened by consumer code that
|
|
3364
|
-
* never exposed it.
|
|
3365
|
-
*
|
|
3366
|
-
* @param requestId - The id already in scope, which wins.
|
|
3367
|
-
* @param req - The incoming request, read for the tenant header.
|
|
3368
|
-
* @param res - The outgoing response, where the effective id is exposed.
|
|
3369
|
-
*/
|
|
3370
|
-
adoptExistingScope(requestId, req, res) {
|
|
3371
|
-
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
3372
|
-
this.logContext.set("requestId", requestId);
|
|
3373
|
-
if (this.logContext.get("tenantId") === void 0) {
|
|
3374
|
-
const tenantId = this.resolveTenantId(req);
|
|
3375
|
-
if (tenantId !== void 0) {
|
|
3376
|
-
this.logContext.set("tenantId", tenantId);
|
|
3377
|
-
}
|
|
3378
|
-
}
|
|
3379
|
-
}
|
|
3380
|
-
/**
|
|
3381
|
-
* The correlation id for this request: the inbound header when acceptable,
|
|
3382
|
-
* otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
|
|
3383
|
-
* off and the caller sent none, which leaves correlation to the upstream
|
|
3384
|
-
* gateway.
|
|
3385
|
-
*
|
|
3386
|
-
* @param req - The incoming request.
|
|
3387
|
-
* @returns The id, or `undefined` when none is available and none is minted.
|
|
3388
|
-
*/
|
|
3389
|
-
resolveRequestId(req) {
|
|
3390
|
-
const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
|
|
3391
|
-
const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
|
|
3392
|
-
return fromHeader ?? (this.shouldGenerateRequestId ? randomUUID() : void 0);
|
|
3393
|
-
}
|
|
3394
|
-
/**
|
|
3395
|
-
* The tenant id carried by the configured header, when it is acceptable.
|
|
3396
|
-
*
|
|
3397
|
-
* Never minted: a tenant is an assertion about who the request belongs to, and
|
|
3398
|
-
* inventing one would be a fabricated claim rather than a correlation aid.
|
|
3399
|
-
*
|
|
3400
|
-
* @param req - The incoming request.
|
|
3401
|
-
* @returns The tenant id, or `undefined`.
|
|
3402
|
-
*/
|
|
3403
|
-
resolveTenantId(req) {
|
|
3404
|
-
const raw = Reflect.get(req.headers, this.tenantIdHeader);
|
|
3405
|
-
return isAcceptableHeaderValue(raw) ? raw : void 0;
|
|
3406
|
-
}
|
|
3407
|
-
};
|
|
3408
|
-
RequestIdMiddleware = __decorateClass([
|
|
3409
|
-
Injectable(),
|
|
3410
|
-
__decorateParam(0, Inject(LogContextService)),
|
|
3411
|
-
__decorateParam(1, Inject(LOGGER_OPTIONS_TOKEN))
|
|
3412
|
-
], RequestIdMiddleware);
|
|
3413
3454
|
|
|
3414
3455
|
// src/server/middlewares/apply-access-log.ts
|
|
3415
3456
|
function resolveDependencies(app) {
|