@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.
@@ -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
 
@@ -1286,152 +1286,449 @@ var {
1286
1286
  // disabled" without a dead nullish branch.
1287
1287
  global: extras.isGlobal !== false
1288
1288
  })).build();
1289
-
1290
- // src/server/constants/default-redact-paths.constants.ts
1291
- var REDACT_MAX_DEPTH = 4;
1292
- var WILDCARD_PREFIXES = Array.from(
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;
1289
+ var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
1290
+ exports.LogContextService = class LogContextService {
1291
+ constructor() {
1292
+ this.als = new async_hooks.AsyncLocalStorage();
1380
1293
  }
1381
- }
1382
- function safeDestinationName(destination) {
1383
- try {
1384
- return String(destination.name);
1385
- } catch {
1386
- return "unknown";
1294
+ /**
1295
+ * Run `callback` inside a fresh context scope. Every log emitted
1296
+ * synchronously or asynchronously within the callback inherits `context`.
1297
+ *
1298
+ * **A nested `run()` REPLACES the enclosing context, it does not extend it.**
1299
+ * The scope starts from `context` alone, so a field an outer scope had set —
1300
+ * a `tenantId` resolved at the edge, say — is absent for the whole inner
1301
+ * scope: nothing throws, `get()` simply returns `undefined`, and the field is
1302
+ * missing from every entry the callback emits. Reach for {@link runMerged}
1303
+ * when the inner scope should extend the outer one.
1304
+ *
1305
+ * Replacement is the deliberate default because the opposite leaks: a
1306
+ * background job started inside a request scope would silently inherit the
1307
+ * caller's `userId` and attribute its entries to a user who never triggered
1308
+ * it. A missing field is visibly missing; an inherited one is wrong while
1309
+ * looking right.
1310
+ *
1311
+ * @typeParam T - Return type of the callback.
1312
+ * @param context - Initial context bag for the scope. Becomes the WHOLE scope.
1313
+ * @param callback - Function executed within the scope.
1314
+ * @returns Whatever `callback` returns.
1315
+ * @example
1316
+ * logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
1317
+ * await userService.create(dto) // logs carry requestId + tenantId
1318
+ * })
1319
+ */
1320
+ run(context, callback) {
1321
+ return this.als.run(this.sanitizeContext(context), callback);
1387
1322
  }
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);
1323
+ /**
1324
+ * Run `callback` inside a scope that EXTENDS the enclosing one: the active
1325
+ * context's fields are carried in, and `context` overrides them key by key.
1326
+ *
1327
+ * The explicit counterpart to {@link run}'s replacement semantics, for the
1328
+ * case where an inner scope is genuinely a refinement of the outer — adding a
1329
+ * `userId` once authentication resolved it, without having to restate the
1330
+ * `requestId` the middleware already set.
1331
+ *
1332
+ * Outside any scope there is nothing to merge and this behaves exactly like
1333
+ * {@link run}. Writes inside the new scope never reach the enclosing one: the
1334
+ * merge produces a fresh object, so the outer context is intact after the
1335
+ * callback returns.
1336
+ *
1337
+ * @typeParam T - Return type of the callback.
1338
+ * @param context - Fields to add or override on top of the active context.
1339
+ * @param callback - Function executed within the merged scope.
1340
+ * @returns Whatever `callback` returns.
1341
+ * @example
1342
+ * logContext.run({ requestId: 'r_1' }, () => {
1343
+ * logContext.runMerged({ userId: 'u_1' }, () => {
1344
+ * logContext.get('requestId') // 'r_1' — carried in from the outer scope
1345
+ * })
1346
+ * })
1347
+ */
1348
+ runMerged(context, callback) {
1349
+ const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
1350
+ return this.als.run(merged, callback);
1396
1351
  }
1397
- let resolved;
1398
- try {
1399
- const read = destination.minLevel;
1400
- resolved = isLogLevel(read) ? read : void 0;
1401
- } catch {
1352
+ /**
1353
+ * Read the active context, or `undefined` when called outside any scope.
1354
+ *
1355
+ * @returns The active `LogContext`, or `undefined`.
1356
+ */
1357
+ getStore() {
1358
+ return this.als.getStore();
1402
1359
  }
1403
- resolvedMinLevels.set(destination, resolved);
1404
- return resolved;
1405
- }
1406
-
1407
- // src/server/utils/otel-detector.ts
1408
- var brokenInstallWarned = false;
1409
- function isOtelApiMissing(cause) {
1410
- try {
1411
- const { code, message } = cause;
1412
- return code === "MODULE_NOT_FOUND" && /^Cannot find module '@opentelemetry\/api'/.test(String(message));
1413
- } catch {
1414
- return false;
1360
+ /**
1361
+ * Add or override a single field on the active context.
1362
+ *
1363
+ * @param key - Field name to set.
1364
+ * @param value - Field value.
1365
+ * @throws Error When called outside a `run()` scope, or with a prototype-polluting key.
1366
+ */
1367
+ set(key, value) {
1368
+ const store = this.als.getStore();
1369
+ if (!store) {
1370
+ throw new Error("[LogContextService] set() called outside run() scope");
1371
+ }
1372
+ if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
1373
+ throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
1374
+ }
1375
+ Reflect.set(store, key, value);
1415
1376
  }
1416
- }
1417
- function loadTraceApiFrom(anchor) {
1418
- let from;
1419
- try {
1420
- from = anchor();
1421
- } catch {
1422
- return { api: void 0 };
1377
+ /**
1378
+ * Read a single field from the active context.
1379
+ *
1380
+ * @typeParam T - Expected value type (caller-asserted).
1381
+ * @param key - Field name to read.
1382
+ * @returns The value cast to `T`, or `undefined` when unset / out of scope.
1383
+ */
1384
+ get(key) {
1385
+ const store = this.als.getStore();
1386
+ if (!store) {
1387
+ return void 0;
1388
+ }
1389
+ return Reflect.get(store, key);
1423
1390
  }
1424
- try {
1425
- const mod = module$1.createRequire(from)("@opentelemetry/api");
1426
- const trace = typeof mod === "object" && mod !== null || typeof mod === "function" ? mod.trace : void 0;
1427
- if (typeof trace?.getActiveSpan !== "function") {
1428
- throw new TypeError("@opentelemetry/api resolved but exports no usable `trace` namespace");
1391
+ /**
1392
+ * Strip prototype-polluting keys from a caller-supplied context so an own
1393
+ * `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
1394
+ * untrusted payload) can never reach the store — and, via the trace mixin's
1395
+ * `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
1396
+ * but drops the key rather than throwing: a logging concern must never crash
1397
+ * the request that produced it.
1398
+ *
1399
+ * @param context - The raw context bag passed to `run()`.
1400
+ * @returns A shallow copy with any forbidden keys removed.
1401
+ */
1402
+ sanitizeContext(context) {
1403
+ const safe = {};
1404
+ for (const key of Object.keys(context)) {
1405
+ if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
1406
+ Reflect.set(safe, key, Reflect.get(context, key));
1407
+ }
1429
1408
  }
1430
- return { api: trace };
1431
- } catch (cause) {
1432
- return isOtelApiMissing(cause) ? { api: void 0 } : { api: void 0, broken: { cause } };
1409
+ return safe;
1433
1410
  }
1434
- }
1411
+ };
1412
+ exports.LogContextService = __decorateClass([
1413
+ common.Injectable()
1414
+ ], exports.LogContextService);
1415
+
1416
+ // src/server/middlewares/request-id.middleware.ts
1417
+ var REQUEST_ID_HEADER = "x-request-id";
1418
+ var MAX_CORRELATION_ID_LENGTH = 256;
1419
+ var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
1420
+ var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
1421
+ function isAcceptableHeaderValue(value) {
1422
+ return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
1423
+ }
1424
+ exports.RequestIdMiddleware = class RequestIdMiddleware {
1425
+ /**
1426
+ * @param logContext - The AsyncLocalStorage-backed context service. Injected by
1427
+ * token explicitly: the package is bundled without `emitDecoratorMetadata`,
1428
+ * so implicit class-type injection would not resolve.
1429
+ * @param options - Resolved module options (read for `http.tenantIdHeader` and
1430
+ * `http.shouldGenerateRequestId`).
1431
+ */
1432
+ constructor(logContext, options) {
1433
+ this.logContext = logContext;
1434
+ this.tenantIdHeader = options.http.tenantIdHeader;
1435
+ this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
1436
+ }
1437
+ /**
1438
+ * Echo or mint the `x-request-id`, expose it on the response, and run the
1439
+ * remainder of the request inside its own log-context scope.
1440
+ *
1441
+ * Idempotent: mounting this middleware twice on the same request mints one id,
1442
+ * not two. The request gets its OWN store, started from the enclosing scope's
1443
+ * correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
1444
+ * else, because no other field can be known to belong to this request.
1445
+ *
1446
+ * An enclosing scope's `requestId` is never adopted and never echoed: adoption
1447
+ * reads a value this middleware recorded on the REQUEST, which a scope opened
1448
+ * elsewhere does not have. What the two generation modes do with one, measured
1449
+ * on two requests sharing a long-lived enclosing scope:
1450
+ *
1451
+ * - `shouldGenerateRequestId: true` (default) — each request mints its own
1452
+ * id, the two requests differ, and the enclosing value reaches neither the
1453
+ * header nor the entries.
1454
+ * - `shouldGenerateRequestId: false` with no inbound header — nothing is
1455
+ * minted, so the request scope inherits the enclosing `requestId` and every
1456
+ * request inside that scope logs under it. No header is exposed. That is
1457
+ * the consumer's own scope being inherited, not correlation being reused,
1458
+ * and it is the configuration that says the gateway owns the id.
1459
+ *
1460
+ * @param req - The incoming request (Express satisfies the contract).
1461
+ * @param res - The outgoing response (Express satisfies the contract).
1462
+ * @param next - The next handler in the chain.
1463
+ */
1464
+ use(req, res, next) {
1465
+ if (isCorrelationOpened(req)) {
1466
+ const ownRequestId = readOwnRequestId(req);
1467
+ if (ownRequestId !== void 0) {
1468
+ this.adoptExistingScope(ownRequestId, req, res);
1469
+ }
1470
+ next();
1471
+ return;
1472
+ }
1473
+ markCorrelationOpened(req);
1474
+ const context = this.inheritableContext();
1475
+ const requestId = this.resolveRequestId(req);
1476
+ if (requestId !== void 0) {
1477
+ res.setHeader(REQUEST_ID_HEADER, requestId);
1478
+ context.requestId = requestId;
1479
+ markOwnRequestId(req, requestId);
1480
+ }
1481
+ if (context.tenantId === void 0) {
1482
+ const tenantId = this.resolveTenantId(req);
1483
+ if (tenantId !== void 0) {
1484
+ context.tenantId = tenantId;
1485
+ }
1486
+ }
1487
+ this.logContext.run(context, () => next());
1488
+ }
1489
+ /**
1490
+ * The enclosing scope's fields that a request scope may start from.
1491
+ *
1492
+ * Plain `run()` would discard everything the caller had set and a plain merge
1493
+ * would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
1494
+ * the middle a request scope actually needs.
1495
+ *
1496
+ * @returns A fresh bag, never the enclosing store itself, so writes inside the
1497
+ * request never reach the scope that opened it.
1498
+ */
1499
+ inheritableContext() {
1500
+ const store = { ...this.logContext.getStore() };
1501
+ const inherited = {};
1502
+ for (const key of INHERITABLE_CONTEXT_KEYS) {
1503
+ const value = Reflect.get(store, key);
1504
+ if (value !== void 0) {
1505
+ Reflect.set(inherited, key, value);
1506
+ }
1507
+ }
1508
+ return inherited;
1509
+ }
1510
+ /**
1511
+ * Second mount on a request that already carries a correlation id: echo the id
1512
+ * onto the response and fill in a tenant the scope does not have yet, without
1513
+ * opening another scope.
1514
+ *
1515
+ * Nothing is minted and nothing already set is overwritten, so a third mount —
1516
+ * or a thirtieth — changes nothing. The response header is written on every
1517
+ * pass because the enclosing scope may have been opened by consumer code that
1518
+ * never exposed it.
1519
+ *
1520
+ * @param requestId - The id already in scope, which wins.
1521
+ * @param req - The incoming request, read for the tenant header.
1522
+ * @param res - The outgoing response, where the effective id is exposed.
1523
+ */
1524
+ adoptExistingScope(requestId, req, res) {
1525
+ res.setHeader(REQUEST_ID_HEADER, requestId);
1526
+ this.logContext.set("requestId", requestId);
1527
+ if (this.logContext.get("tenantId") === void 0) {
1528
+ const tenantId = this.resolveTenantId(req);
1529
+ if (tenantId !== void 0) {
1530
+ this.logContext.set("tenantId", tenantId);
1531
+ }
1532
+ }
1533
+ }
1534
+ /**
1535
+ * The correlation id for this request: the inbound header when acceptable,
1536
+ * otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
1537
+ * off and the caller sent none, which leaves correlation to the upstream
1538
+ * gateway.
1539
+ *
1540
+ * @param req - The incoming request.
1541
+ * @returns The id, or `undefined` when none is available and none is minted.
1542
+ */
1543
+ resolveRequestId(req) {
1544
+ const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
1545
+ const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
1546
+ return fromHeader ?? (this.shouldGenerateRequestId ? crypto.randomUUID() : void 0);
1547
+ }
1548
+ /**
1549
+ * The tenant id carried by the configured header, when it is acceptable.
1550
+ *
1551
+ * Never minted: a tenant is an assertion about who the request belongs to, and
1552
+ * inventing one would be a fabricated claim rather than a correlation aid.
1553
+ *
1554
+ * @param req - The incoming request.
1555
+ * @returns The tenant id, or `undefined`.
1556
+ */
1557
+ resolveTenantId(req) {
1558
+ const raw = Reflect.get(req.headers, this.tenantIdHeader);
1559
+ return isAcceptableHeaderValue(raw) ? raw : void 0;
1560
+ }
1561
+ };
1562
+ exports.RequestIdMiddleware = __decorateClass([
1563
+ common.Injectable(),
1564
+ __decorateParam(0, common.Inject(exports.LogContextService)),
1565
+ __decorateParam(1, common.Inject(LOGGER_OPTIONS_TOKEN))
1566
+ ], exports.RequestIdMiddleware);
1567
+
1568
+ // src/server/middlewares/apply-request-context.ts
1569
+ function applyRequestContext(app) {
1570
+ let requestId;
1571
+ try {
1572
+ requestId = new exports.RequestIdMiddleware(
1573
+ app.get(exports.LogContextService),
1574
+ app.get(LOGGER_OPTIONS_TOKEN)
1575
+ );
1576
+ } catch (cause) {
1577
+ throw new Error(
1578
+ "[BymaxLoggerModule] useRequestContext(app) called but BymaxLoggerModule was not imported",
1579
+ { cause }
1580
+ );
1581
+ }
1582
+ app.use((req, res, next) => {
1583
+ requestId.use(req, res, next);
1584
+ });
1585
+ }
1586
+
1587
+ // src/server/constants/default-redact-paths.constants.ts
1588
+ var REDACT_MAX_DEPTH = 4;
1589
+ var WILDCARD_PREFIXES = Array.from(
1590
+ { length: REDACT_MAX_DEPTH },
1591
+ (_, idx) => "*" + ".*".repeat(idx)
1592
+ );
1593
+ var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
1594
+ var REDACT_COMMON_FIELDS = [
1595
+ // Passwords (5)
1596
+ "password",
1597
+ "passwordHash",
1598
+ "passwordConfirm",
1599
+ "newPassword",
1600
+ "oldPassword",
1601
+ // Tokens (6)
1602
+ "token",
1603
+ "accessToken",
1604
+ "refreshToken",
1605
+ "idToken",
1606
+ "apiKey",
1607
+ "apiSecret",
1608
+ // MFA (3)
1609
+ "mfaSecret",
1610
+ "mfaRecoveryCodes",
1611
+ "totpSecret",
1612
+ // Payment / PCI DSS (5)
1613
+ "cardNumber",
1614
+ "cardCvv",
1615
+ "cvv",
1616
+ "cvc",
1617
+ "cardExpiry",
1618
+ // Personal documents — BR / LGPD (3)
1619
+ "cpf",
1620
+ "cnpj",
1621
+ "rg",
1622
+ // Generic secrets (4) — the most common short-form credential field names
1623
+ "secret",
1624
+ "clientSecret",
1625
+ "signingSecret",
1626
+ "privateKey",
1627
+ // Conservative PII (1) — consumer can disable if logging email is justified
1628
+ "email",
1629
+ // Credential-bearing HTTP header names (5). These also appear in
1630
+ // {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
1631
+ // shapes — which covered ONLY those two shapes. A headers bag logged under any
1632
+ // other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
1633
+ // common things written while debugging an integration) wrote the bearer token
1634
+ // in clear. Listed here as bare names, they are caught wherever they appear.
1635
+ // Node lower-cases inbound header names, so the lower-case spelling is the one
1636
+ // that can actually reach a log.
1637
+ "authorization",
1638
+ "cookie",
1639
+ "set-cookie",
1640
+ "x-api-key",
1641
+ "x-auth-token"
1642
+ ];
1643
+ var REDACT_ABSOLUTE_PATHS = [
1644
+ "req.headers.authorization",
1645
+ "req.headers.cookie",
1646
+ 'req.headers["x-api-key"]',
1647
+ 'req.headers["x-auth-token"]',
1648
+ 'res.headers["set-cookie"]'
1649
+ ];
1650
+ var DEFAULT_REDACT_PATHS = [
1651
+ ...REDACT_COMMON_FIELDS,
1652
+ ...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
1653
+ ...REDACT_ABSOLUTE_PATHS
1654
+ ];
1655
+
1656
+ // src/server/utils/report-destination-failure.util.ts
1657
+ function reportDestinationFailure(logKey, name, cause, msg) {
1658
+ writeStderrSafely(
1659
+ JSON.stringify({
1660
+ level: "error",
1661
+ logKey,
1662
+ destination: toSingleLineMessage(name),
1663
+ err: describeCause(cause),
1664
+ msg: toSingleLineMessage(msg)
1665
+ }) + "\n"
1666
+ );
1667
+ }
1668
+ var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
1669
+ function describeCause(cause) {
1670
+ try {
1671
+ return isError(cause) ? {
1672
+ type: toBoundedMessage(String(cause.name)),
1673
+ message: toBoundedMessage(String(cause.message))
1674
+ } : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
1675
+ } catch {
1676
+ return UNREADABLE_CAUSE;
1677
+ }
1678
+ }
1679
+ function safeDestinationName(destination) {
1680
+ try {
1681
+ return String(destination.name);
1682
+ } catch {
1683
+ return "unknown";
1684
+ }
1685
+ }
1686
+ function isLogLevel(value) {
1687
+ return LOG_LEVEL_PRIORITY.includes(value);
1688
+ }
1689
+ var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
1690
+ function safeMinLevel(destination) {
1691
+ if (resolvedMinLevels.has(destination)) {
1692
+ return resolvedMinLevels.get(destination);
1693
+ }
1694
+ let resolved;
1695
+ try {
1696
+ const read = destination.minLevel;
1697
+ resolved = isLogLevel(read) ? read : void 0;
1698
+ } catch {
1699
+ }
1700
+ resolvedMinLevels.set(destination, resolved);
1701
+ return resolved;
1702
+ }
1703
+
1704
+ // src/server/utils/otel-detector.ts
1705
+ var brokenInstallWarned = false;
1706
+ function isOtelApiMissing(cause) {
1707
+ try {
1708
+ const { code, message } = cause;
1709
+ return code === "MODULE_NOT_FOUND" && /^Cannot find module '@opentelemetry\/api'/.test(String(message));
1710
+ } catch {
1711
+ return false;
1712
+ }
1713
+ }
1714
+ function loadTraceApiFrom(anchor) {
1715
+ let from;
1716
+ try {
1717
+ from = anchor();
1718
+ } catch {
1719
+ return { api: void 0 };
1720
+ }
1721
+ try {
1722
+ const mod = module$1.createRequire(from)("@opentelemetry/api");
1723
+ const trace = typeof mod === "object" && mod !== null || typeof mod === "function" ? mod.trace : void 0;
1724
+ if (typeof trace?.getActiveSpan !== "function") {
1725
+ throw new TypeError("@opentelemetry/api resolved but exports no usable `trace` namespace");
1726
+ }
1727
+ return { api: trace };
1728
+ } catch (cause) {
1729
+ return isOtelApiMissing(cause) ? { api: void 0 } : { api: void 0, broken: { cause } };
1730
+ }
1731
+ }
1435
1732
  function warnBrokenInstallOnce(cause) {
1436
1733
  if (brokenInstallWarned) {
1437
1734
  return;
@@ -2562,190 +2859,64 @@ var DestinationRegistry = class {
2562
2859
  } catch (cause) {
2563
2860
  this.reportShutdownFailure(destination, cause);
2564
2861
  }
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);
2862
+ }
2685
2863
  }
2686
2864
  /**
2687
- * Read the active context, or `undefined` when called outside any scope.
2865
+ * Report a failing `onShutdown` on stderr without letting the report itself
2866
+ * abort the teardown of the destinations still queued behind it.
2688
2867
  *
2689
- * @returns The active `LogContext`, or `undefined`.
2690
- */
2691
- getStore() {
2692
- return this.als.getStore();
2693
- }
2694
- /**
2695
- * Add or override a single field on the active context.
2868
+ * The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
2869
+ * an `Error` with hostile getters, and `String(cause)` on a value with a
2870
+ * throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
2871
+ * the `catch` that exists to keep one bad sink from mattering, so an escape
2872
+ * here would propagate out of `onApplicationShutdown` and skip every remaining
2873
+ * destination's flush. The never-throw contract has to cover READING the value,
2874
+ * not just writing it, which is the same correction `reportDestinationFailure`
2875
+ * already carries.
2696
2876
  *
2697
- * @param key - Field name to set.
2698
- * @param value - Field value.
2699
- * @throws Error When called outside a `run()` scope, or with a prototype-polluting key.
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.
2877
+ * The text is escaped for the same reason every other terminal-bound path is:
2878
+ * a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
2879
+ * newlines and neutralizes everything else that can drive a terminal.
2713
2880
  *
2714
- * @typeParam T - Expected value type (caller-asserted).
2715
- * @param key - Field name to read.
2716
- * @returns The value cast to `T`, or `undefined` when unset / out of scope.
2881
+ * The DESTINATION is passed rather than its name, so that read happens in here
2882
+ * too. `name` is declared `readonly name: string` but nothing stops a consumer
2883
+ * implementing it as a getter, and reading it at the call site would put it back
2884
+ * outside the guard — inside the `catch`, where a throw has the same cost.
2885
+ *
2886
+ * Two separate guards, not one: a name that cannot be read must not also cost
2887
+ * the failure detail, and a detail that cannot be read must not cost the name.
2888
+ * Either alone still identifies which sink failed.
2889
+ *
2890
+ * @param destination - The destination whose `onShutdown` threw.
2891
+ * @param cause - The thrown value, of any shape.
2717
2892
  */
2718
- get(key) {
2719
- const store = this.als.getStore();
2720
- if (!store) {
2721
- return void 0;
2893
+ reportShutdownFailure(destination, cause) {
2894
+ const name = toSingleLineMessage(safeDestinationName(destination));
2895
+ let detail = "UnknownError";
2896
+ try {
2897
+ const stack = isErrorLike(cause) ? cause.stack : void 0;
2898
+ detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
2899
+ } catch {
2722
2900
  }
2723
- return Reflect.get(store, key);
2901
+ writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
2902
+ `);
2724
2903
  }
2725
2904
  /**
2726
- * Strip prototype-polluting keys from a caller-supplied context so an own
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.
2905
+ * The destinations that initialized successfully.
2732
2906
  *
2733
- * @param context - The raw context bag passed to `run()`.
2734
- * @returns A shallow copy with any forbidden keys removed.
2907
+ * @returns A read-only view of the active destination set.
2735
2908
  */
2736
- sanitizeContext(context) {
2737
- const safe = {};
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;
2909
+ getActive() {
2910
+ return this.active;
2744
2911
  }
2745
2912
  };
2746
- exports.LogContextService = __decorateClass([
2747
- common.Injectable()
2748
- ], exports.LogContextService);
2913
+ DestinationRegistry = __decorateClass([
2914
+ common.Injectable(),
2915
+ __decorateParam(0, common.Inject(LOGGER_DESTINATIONS_TOKEN)),
2916
+ __decorateParam(1, common.Inject(exports.PinoLoggerService)),
2917
+ __decorateParam(2, common.Inject(LOGGER_OPTIONS_TOKEN)),
2918
+ __decorateParam(3, common.Inject(DestinationHealth))
2919
+ ], DestinationRegistry);
2749
2920
 
2750
2921
  // src/server/logger.module.ts
2751
2922
  function resolveDestinations(options) {
@@ -2913,6 +3084,26 @@ exports.BymaxLoggerModule = class BymaxLoggerModule extends BymaxLoggerModuleBas
2913
3084
  app.useLogger(logger);
2914
3085
  app.flushLogs();
2915
3086
  }
3087
+ /**
3088
+ * Open the request-id correlation scope ahead of the body parser, so a request the parser
3089
+ * refuses (malformed JSON, an unsupported content encoding, a body over the limit) still has its
3090
+ * `requestId`, and the `x-request-id` response header, where an exception filter reads it.
3091
+ *
3092
+ * Call once in `main.ts` AFTER creating the app and BEFORE `app.init()` / `app.listen(...)`.
3093
+ * It mounts only the scope. `applyAccessLog(app)` and `applyRequestIdMiddleware(consumer)` can
3094
+ * be used as well: a second mount of the middleware reuses the scope this one opened.
3095
+ *
3096
+ * @param app - The Nest application returned by `NestFactory.create()`.
3097
+ * @throws Error When `BymaxLoggerModule` was not imported.
3098
+ * @example
3099
+ * const app = await NestFactory.create(AppModule, { bufferLogs: true })
3100
+ * BymaxLoggerModule.useNestLogger(app)
3101
+ * BymaxLoggerModule.useRequestContext(app)
3102
+ * await app.listen(3000)
3103
+ */
3104
+ static useRequestContext(app) {
3105
+ applyRequestContext(app);
3106
+ }
2916
3107
  };
2917
3108
  exports.BymaxLoggerModule = __decorateClass([
2918
3109
  common.Module({})
@@ -3263,156 +3454,6 @@ exports.HttpAccessLogMiddleware = __decorateClass([
3263
3454
  __decorateParam(1, common.Inject(exports.LogContextService)),
3264
3455
  __decorateParam(2, common.Inject(LOGGER_OPTIONS_TOKEN))
3265
3456
  ], 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
3457
 
3417
3458
  // src/server/middlewares/apply-access-log.ts
3418
3459
  function resolveDependencies(app) {