@bymax-one/nest-logger 1.4.12 → 1.4.14

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.
@@ -1,8 +1,104 @@
1
1
  import * as _nestjs_common from '@nestjs/common';
2
- import { ModuleMetadata, Type, DynamicModule, INestApplication, LoggerService, OnApplicationShutdown, ExceptionFilter, ArgumentsHost, NestInterceptor, ExecutionContext, CallHandler, MiddlewareConsumer, NestMiddleware, CustomDecorator } from '@nestjs/common';
2
+ import { ModuleMetadata, Type, NestModule, MiddlewareConsumer, DynamicModule, INestApplication, LoggerService, OnApplicationShutdown, ExceptionFilter, ArgumentsHost, NestInterceptor, ExecutionContext, CallHandler, NestMiddleware, CustomDecorator } from '@nestjs/common';
3
+ import { HttpAdapterHost } from '@nestjs/core';
3
4
  import { Logger } from 'pino';
4
5
  import { Observable } from 'rxjs';
5
6
 
7
+ /**
8
+ * Minimal HTTP request/response contracts the logging layer reads.
9
+ *
10
+ * Layer: server/interfaces — exported structural contracts shared by the HTTP
11
+ * logging interceptor, the exception filter and the request-id middleware. They
12
+ * are part of the public API: they appear in those components' published
13
+ * signatures, so a consumer calling `RequestIdMiddleware.use()` directly needs
14
+ * to be able to name them. Declared structurally, listing only the members
15
+ * those three actually touch, so the published declarations depend on no HTTP
16
+ * framework's types. Naming Express's
17
+ * `Request`/`Response` here would make the emitted `.d.ts` import from
18
+ * `express`, forcing every consumer that compiles with `skipLibCheck: false` to
19
+ * install `@types/express` whether or not they use those signatures.
20
+ *
21
+ * The shapes mirror what the Express adapter provides — `status().json()` and
22
+ * `setHeader()` are Express/Node response methods — so this is not an
23
+ * adapter-agnostic abstraction; a Fastify adapter remains unsupported. An
24
+ * Express request and response satisfy these contracts structurally, with no
25
+ * cast at the call site.
26
+ */
27
+ /** Raw inbound headers, as the HTTP layer delivers them. */
28
+ type IncomingHeaders = Record<string, string | string[] | undefined>;
29
+ /**
30
+ * The inbound request members the logging layer reads.
31
+ *
32
+ * `user` is populated by upstream auth in the consumer app (a guard or
33
+ * middleware). The acting-user id is read as `sub` first, then `id`: a JWT principal
34
+ * (every `@bymax-one/nest-auth` token) names it `sub`, while an ORM-style principal
35
+ * names it `id`. The JWT subject wins when both are present, since it is the
36
+ * authenticated identity. Reading only `id` — as this once did — silently dropped
37
+ * the user field for every JWT-authenticated request.
38
+ */
39
+ interface LoggableRequest {
40
+ /** Inbound headers — read for correlation ids and the user agent. */
41
+ readonly headers: IncomingHeaders;
42
+ /** HTTP verb, logged as-is. */
43
+ readonly method: string;
44
+ /** Request target, normalized and query-stripped before it reaches a log. */
45
+ readonly url: string;
46
+ /**
47
+ * The request target as it arrived, before any mount point was stripped.
48
+ *
49
+ * Middleware mounted at a path sees `url` RELATIVE to that mount: measured
50
+ * under `setGlobalPrefix('api')`, a request for `/api/users/7` reaches a
51
+ * root-mounted middleware as `url = '/users/7'` and
52
+ * `originalUrl = '/api/users/7'`, and `/api` itself arrives as `url = '/'`.
53
+ * Logging `url` there would drop the prefix from every entry and make an
54
+ * `excludePaths` pattern written against the real path stop matching. Absent
55
+ * on adapters that do not provide it, in which case `url` is already whole.
56
+ */
57
+ readonly originalUrl?: string | undefined;
58
+ /** Client address when the adapter resolves one. */
59
+ readonly ip?: string | undefined;
60
+ /**
61
+ * Authenticated principal, when upstream auth attached one. `id` is the
62
+ * ORM-style identifier; `sub` is the JWT subject claim. The logging layer reads
63
+ * whichever is present.
64
+ */
65
+ readonly user?: {
66
+ readonly id?: string | undefined;
67
+ readonly sub?: string | undefined;
68
+ } | undefined;
69
+ }
70
+ /**
71
+ * The outbound response members the logging layer writes or reads: the status
72
+ * for the terminal log entry, `setHeader` to echo the correlation id, and the
73
+ * chainable `status().json()` used by the exception filter to emit a body.
74
+ */
75
+ interface LoggableResponse {
76
+ /** Status code, read when logging the completed request. */
77
+ readonly statusCode: number;
78
+ /**
79
+ * `true` once every byte has been flushed to the socket. Read in the `'close'`
80
+ * handler to tell a delivered response from one the client never received:
81
+ * `'close'` fires for both, and `'finish'` never fires for an aborted request
82
+ * at all. It is what keeps an aborted request from being logged as the success
83
+ * the handler intended.
84
+ */
85
+ readonly writableFinished: boolean;
86
+ /** Sets a response header (used for the correlation id). */
87
+ setHeader(name: string, value: string): void;
88
+ /** Selects the status code and returns the chainable body writer. */
89
+ status(code: number): {
90
+ json(body: unknown): unknown;
91
+ };
92
+ /**
93
+ * Registers a lifecycle listener. Only `'close'` is used: it fires exactly
94
+ * once whether the response completed or the connection died early, where
95
+ * `'finish'` is blind to the aborted case.
96
+ */
97
+ on(event: 'close', listener: () => void): unknown;
98
+ }
99
+ /** Continuation passed to a middleware; invoked with no arguments here. */
100
+ type NextHandler = () => void;
101
+
6
102
  /**
7
103
  * Pino log levels (mirrored to NestJS-compatible names).
8
104
  *
@@ -295,9 +391,34 @@ interface HttpOptions {
295
391
  * crafted URL into a ReDoS vector. The defaults are anchored and safe.
296
392
  */
297
393
  excludePaths?: readonly RegExp[];
298
- /** Header name carrying the tenant identifier. Default: `x-tenant-id`. */
299
- tenantIdHeader?: string;
394
+ /**
395
+ * Header name carrying the tenant identifier, or `false` to read no header. Default:
396
+ * `x-tenant-id`.
397
+ *
398
+ * SECURITY: a `tenantId` taken from a header is what the CLIENT asserted. Any client can send any
399
+ * tenant, and every entry of its requests will carry it, so do not read it as who the request
400
+ * belongs to. A host that authenticates the tenant sets `false` or supplies
401
+ * {@link HttpOptions.tenantIdResolver}.
402
+ */
403
+ tenantIdHeader?: string | false;
404
+ /**
405
+ * Resolves the tenant id of a request on the server side, from what the host trusts (a session,
406
+ * a verified token an earlier middleware put on the request). When given it is the only source:
407
+ * the header is not read, whether the resolver answers or not. The middleware runs before guards,
408
+ * so the resolver sees only what an earlier middleware set; a tenant known later is set with
409
+ * `LogContextService.set('tenantId', ...)`. An answer that is not a string of at most 256
410
+ * characters drawn from `A-Z a-z 0-9 . _ : / + = -`, and a resolver that throws, give no tenant id.
411
+ * The resolver is synchronous: a promise it answers is no tenant id, and its rejection is absorbed.
412
+ */
413
+ tenantIdResolver?: (request: LoggableRequest) => string | undefined;
300
414
  }
415
+ /**
416
+ * The `http` options after defaults: every field is filled but the resolver, whose absence means the
417
+ * header is read.
418
+ */
419
+ type ResolvedHttpOptions = Required<Omit<HttpOptions, 'tenantIdResolver'>> & {
420
+ tenantIdResolver: HttpOptions['tenantIdResolver'];
421
+ };
301
422
  /**
302
423
  * OpenTelemetry integration tuning — applied by `TraceContextMixin` when the
303
424
  * `@opentelemetry/api` peer dependency is installed.
@@ -463,7 +584,7 @@ interface BymaxLoggerModuleOptions {
463
584
  * `BymaxLoggerModuleOptions` the consumer supplies.
464
585
  */
465
586
  type ResolvedBymaxLoggerModuleOptions = Readonly<Required<Omit<BymaxLoggerModuleOptions, 'http' | 'otel'>> & {
466
- http: Required<HttpOptions>;
587
+ http: ResolvedHttpOptions;
467
588
  otel: Required<OtelOptions>;
468
589
  }>;
469
590
  /**
@@ -525,7 +646,20 @@ declare const BymaxLoggerModuleBase: _nestjs_common.ConfigurableModuleCls<BymaxL
525
646
  declare const OPTIONS_TYPE: BymaxLoggerModuleOptions & Partial<BymaxLoggerModuleExtras>;
526
647
  declare const ASYNC_OPTIONS_TYPE: _nestjs_common.ConfigurableModuleAsyncOptions<BymaxLoggerModuleOptions, "createLoggerOptions"> & Partial<BymaxLoggerModuleExtras>;
527
648
 
528
- declare class BymaxLoggerModule extends BymaxLoggerModuleBase {
649
+ declare class BymaxLoggerModule extends BymaxLoggerModuleBase implements NestModule {
650
+ private readonly httpAdapterHost;
651
+ /**
652
+ * @param httpAdapterHost - The HTTP adapter, absent in an application with no HTTP server.
653
+ */
654
+ constructor(httpAdapterHost: HttpAdapterHost);
655
+ /**
656
+ * Mount the error layer that keeps the type of a body-parser error for the exception filter.
657
+ * It runs after the body parser, which Nest registers first, and before Nest's exception
658
+ * handler, and it passes every error on. Only the Express adapter has such a layer.
659
+ *
660
+ * @param _consumer - The middleware consumer, unused: an error layer is not consumer middleware.
661
+ */
662
+ configure(_consumer: MiddlewareConsumer): void;
529
663
  /**
530
664
  * Synchronous registration.
531
665
  *
@@ -1257,6 +1391,23 @@ declare class HttpExceptionFilter implements ExceptionFilter {
1257
1391
  * @param host - The arguments host (switched to HTTP).
1258
1392
  */
1259
1393
  catch(exception: unknown, host: ArgumentsHost): void;
1394
+ /**
1395
+ * Log an exposed client error as handled and answer it with its own status and message.
1396
+ *
1397
+ * @param clientError - The status and message the error exposes.
1398
+ * @param res - The response to write.
1399
+ * @param request - The request facts every entry carries.
1400
+ * @param rawUrls - The request's own URLs, whose query string a logged message must not carry.
1401
+ */
1402
+ private answerClientError;
1403
+ /**
1404
+ * Log any other non-`HttpException` as unhandled and answer it with the fixed 500 body.
1405
+ *
1406
+ * @param exception - The thrown value.
1407
+ * @param res - The response to write.
1408
+ * @param request - The request facts every entry carries.
1409
+ */
1410
+ private answerUnhandled;
1260
1411
  }
1261
1412
 
1262
1413
  /**
@@ -1318,16 +1469,28 @@ declare class HttpLoggingInterceptor implements NestInterceptor {
1318
1469
  private logSuccess;
1319
1470
  /**
1320
1471
  * Log a thrown completion: SERVER_ERROR (error level, with stack) for 5xx,
1321
- * CLIENT_ERROR (warn level) for an `HttpException` below 500. A non-`HttpException`
1322
- * always maps to 500, so it is reported as a server error.
1472
+ * CLIENT_ERROR (warn level) for an `HttpException` below 500 or an exposed `http-errors`
1473
+ * client error. Any other non-`HttpException` maps to 500, so it is reported as a server error.
1323
1474
  *
1324
1475
  * @param err - The thrown value (anything).
1325
1476
  * @param method - The HTTP method.
1326
1477
  * @param url - The normalized request URL.
1327
1478
  * @param userId - The acting user id, when known.
1328
1479
  * @param duration - The elapsed time in milliseconds.
1480
+ * @param rawUrls - The request's own URLs, whose query string a logged message must not carry.
1329
1481
  */
1330
1482
  private logError;
1483
+ /**
1484
+ * Log an exposed `http-errors` client error as CLIENT_ERROR at warn level.
1485
+ *
1486
+ * @param clientError - The status and message the error exposes.
1487
+ * @param method - The HTTP method.
1488
+ * @param url - The normalized request URL.
1489
+ * @param userId - The acting user id, when known.
1490
+ * @param duration - The elapsed time in milliseconds.
1491
+ * @param rawUrls - The request's own URLs, whose query string a logged message must not carry.
1492
+ */
1493
+ private logClientError;
1331
1494
  }
1332
1495
 
1333
1496
  /**
@@ -1430,101 +1593,6 @@ declare function applyAccessLog(app: INestApplication): void;
1430
1593
  */
1431
1594
  declare function applyRequestIdMiddleware(consumer: MiddlewareConsumer, routes?: string): void;
1432
1595
 
1433
- /**
1434
- * Minimal HTTP request/response contracts the logging layer reads.
1435
- *
1436
- * Layer: server/interfaces — exported structural contracts shared by the HTTP
1437
- * logging interceptor, the exception filter and the request-id middleware. They
1438
- * are part of the public API: they appear in those components' published
1439
- * signatures, so a consumer calling `RequestIdMiddleware.use()` directly needs
1440
- * to be able to name them. Declared structurally, listing only the members
1441
- * those three actually touch, so the published declarations depend on no HTTP
1442
- * framework's types. Naming Express's
1443
- * `Request`/`Response` here would make the emitted `.d.ts` import from
1444
- * `express`, forcing every consumer that compiles with `skipLibCheck: false` to
1445
- * install `@types/express` whether or not they use those signatures.
1446
- *
1447
- * The shapes mirror what the Express adapter provides — `status().json()` and
1448
- * `setHeader()` are Express/Node response methods — so this is not an
1449
- * adapter-agnostic abstraction; a Fastify adapter remains unsupported. An
1450
- * Express request and response satisfy these contracts structurally, with no
1451
- * cast at the call site.
1452
- */
1453
- /** Raw inbound headers, as the HTTP layer delivers them. */
1454
- type IncomingHeaders = Record<string, string | string[] | undefined>;
1455
- /**
1456
- * The inbound request members the logging layer reads.
1457
- *
1458
- * `user` is populated by upstream auth in the consumer app (a guard or
1459
- * middleware). The acting-user id is read as `sub` first, then `id`: a JWT principal
1460
- * (every `@bymax-one/nest-auth` token) names it `sub`, while an ORM-style principal
1461
- * names it `id`. The JWT subject wins when both are present, since it is the
1462
- * authenticated identity. Reading only `id` — as this once did — silently dropped
1463
- * the user field for every JWT-authenticated request.
1464
- */
1465
- interface LoggableRequest {
1466
- /** Inbound headers — read for correlation ids and the user agent. */
1467
- readonly headers: IncomingHeaders;
1468
- /** HTTP verb, logged as-is. */
1469
- readonly method: string;
1470
- /** Request target, normalized and query-stripped before it reaches a log. */
1471
- readonly url: string;
1472
- /**
1473
- * The request target as it arrived, before any mount point was stripped.
1474
- *
1475
- * Middleware mounted at a path sees `url` RELATIVE to that mount: measured
1476
- * under `setGlobalPrefix('api')`, a request for `/api/users/7` reaches a
1477
- * root-mounted middleware as `url = '/users/7'` and
1478
- * `originalUrl = '/api/users/7'`, and `/api` itself arrives as `url = '/'`.
1479
- * Logging `url` there would drop the prefix from every entry and make an
1480
- * `excludePaths` pattern written against the real path stop matching. Absent
1481
- * on adapters that do not provide it, in which case `url` is already whole.
1482
- */
1483
- readonly originalUrl?: string | undefined;
1484
- /** Client address when the adapter resolves one. */
1485
- readonly ip?: string | undefined;
1486
- /**
1487
- * Authenticated principal, when upstream auth attached one. `id` is the
1488
- * ORM-style identifier; `sub` is the JWT subject claim. The logging layer reads
1489
- * whichever is present.
1490
- */
1491
- readonly user?: {
1492
- readonly id?: string | undefined;
1493
- readonly sub?: string | undefined;
1494
- } | undefined;
1495
- }
1496
- /**
1497
- * The outbound response members the logging layer writes or reads: the status
1498
- * for the terminal log entry, `setHeader` to echo the correlation id, and the
1499
- * chainable `status().json()` used by the exception filter to emit a body.
1500
- */
1501
- interface LoggableResponse {
1502
- /** Status code, read when logging the completed request. */
1503
- readonly statusCode: number;
1504
- /**
1505
- * `true` once every byte has been flushed to the socket. Read in the `'close'`
1506
- * handler to tell a delivered response from one the client never received:
1507
- * `'close'` fires for both, and `'finish'` never fires for an aborted request
1508
- * at all. It is what keeps an aborted request from being logged as the success
1509
- * the handler intended.
1510
- */
1511
- readonly writableFinished: boolean;
1512
- /** Sets a response header (used for the correlation id). */
1513
- setHeader(name: string, value: string): void;
1514
- /** Selects the status code and returns the chainable body writer. */
1515
- status(code: number): {
1516
- json(body: unknown): unknown;
1517
- };
1518
- /**
1519
- * Registers a lifecycle listener. Only `'close'` is used: it fires exactly
1520
- * once whether the response completed or the connection died early, where
1521
- * `'finish'` is blind to the aborted case.
1522
- */
1523
- on(event: 'close', listener: () => void): unknown;
1524
- }
1525
- /** Continuation passed to a middleware; invoked with no arguments here. */
1526
- type NextHandler = () => void;
1527
-
1528
1596
  /**
1529
1597
  * Records the HTTP access log for every request, including the ones no
1530
1598
  * interceptor can observe.
@@ -1580,8 +1648,10 @@ declare class HttpAccessLogMiddleware implements NestMiddleware {
1580
1648
  */
1581
1649
  declare class RequestIdMiddleware implements NestMiddleware {
1582
1650
  private readonly logContext;
1583
- /** Header name carrying the tenant id, resolved from module options. */
1651
+ /** Header name carrying the tenant id, or `false` when no header is read. */
1584
1652
  private readonly tenantIdHeader;
1653
+ /** Server-side resolver of the tenant id; when set, the header is not read. */
1654
+ private readonly tenantIdResolver;
1585
1655
  /** Whether to mint a `requestId` when the inbound header is absent. */
1586
1656
  private readonly shouldGenerateRequestId;
1587
1657
  /**
@@ -1657,15 +1727,21 @@ declare class RequestIdMiddleware implements NestMiddleware {
1657
1727
  */
1658
1728
  private resolveRequestId;
1659
1729
  /**
1660
- * The tenant id carried by the configured header, when it is acceptable.
1730
+ * The tenant id of the request, when it is acceptable.
1661
1731
  *
1662
- * Never minted: a tenant is an assertion about who the request belongs to, and
1663
- * inventing one would be a fabricated claim rather than a correlation aid.
1732
+ * From the host's resolver when it gave one, else from the configured header, else none. Never
1733
+ * minted: a tenant is an assertion about who the request belongs to, and inventing one would be a
1734
+ * fabricated claim rather than a correlation aid.
1664
1735
  *
1665
1736
  * @param req - The incoming request.
1666
1737
  * @returns The tenant id, or `undefined`.
1667
1738
  */
1668
1739
  private resolveTenantId;
1740
+ /**
1741
+ * The answer of the host's resolver, when it is acceptable. A resolver that throws gives none: a
1742
+ * log context never costs the request.
1743
+ */
1744
+ private resolvedTenantId;
1669
1745
  }
1670
1746
 
1671
1747
  /**