@bymax-one/nest-logger 1.4.16 → 1.4.18

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,6 +1,6 @@
1
1
  import { join } from 'path';
2
2
  import { fileURLToPath } from 'url';
3
- import { Injectable, Inject, HttpStatus, Catch, ConfigurableModuleBuilder, Module, HttpException, SetMetadata } from '@nestjs/common';
3
+ import { Injectable, Inject, HttpStatus, Catch, Optional, ConfigurableModuleBuilder, Module, HttpException, SetMetadata } from '@nestjs/common';
4
4
  import { HttpAdapterHost, APP_INTERCEPTOR, APP_FILTER } from '@nestjs/core';
5
5
  import { types } from 'util';
6
6
  import { tap, catchError, throwError } from 'rxjs';
@@ -22,15 +22,31 @@ var __decorateParam = (index, decorator) => (target, key) => decorator(target, k
22
22
  var getFilename = () => fileURLToPath(import.meta.url);
23
23
  var __filename$1 = /* @__PURE__ */ getFilename();
24
24
 
25
+ // src/server/constants/lifecycle-timeouts.constants.ts
26
+ var DEFAULT_HOOK_TIMEOUT_MS = 1e4;
27
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
28
+ var DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
29
+ var DEFAULT_QUEUE_MAX_BYTES = 33554432;
30
+ var MIN_QUEUE_MAX_BYTES = 1024;
31
+ var MAX_QUEUE_MAX_BYTES = 2147483647;
32
+
25
33
  // src/server/config/default-options.ts
26
34
  var DEFAULT_HTTP = {
27
35
  isEnabled: false,
28
36
  shouldCaptureExceptions: true,
29
37
  shouldGenerateRequestId: true,
30
38
  excludePaths: [/^\/health$/, /^\/health\/live$/, /^\/health\/ready$/, /^\/metrics$/],
39
+ secretPathSegments: [],
31
40
  tenantIdHeader: "x-tenant-id",
32
41
  tenantIdResolver: void 0
33
42
  };
43
+ function resolveShutdown(given) {
44
+ const timeoutMs = given?.timeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
45
+ return Object.freeze({
46
+ timeoutMs,
47
+ drainTimeoutMs: given?.drainTimeoutMs ?? Math.min(DEFAULT_DRAIN_TIMEOUT_MS, timeoutMs)
48
+ });
49
+ }
34
50
  var DEFAULT_OTEL = {
35
51
  shouldAutoInjectTraceContext: true,
36
52
  fieldFormat: "camelCase",
@@ -77,10 +93,16 @@ function applyDefaults(options) {
77
93
  destinations: Object.freeze([...options.destinations ?? []]),
78
94
  http: Object.freeze({
79
95
  ...http,
80
- excludePaths: Object.freeze([...http.excludePaths])
96
+ excludePaths: Object.freeze([...http.excludePaths]),
97
+ secretPathSegments: Object.freeze([...http.secretPathSegments])
81
98
  }),
82
99
  otel: Object.freeze(otel),
83
100
  maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
101
+ destinationHookTimeoutMs: options.destinationHookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS,
102
+ shutdown: resolveShutdown(options.shutdown),
103
+ destinationQueue: Object.freeze({
104
+ maxBytes: options.destinationQueue?.maxBytes ?? DEFAULT_QUEUE_MAX_BYTES
105
+ }),
84
106
  errorOwnFields: options.errorOwnFields ?? "all",
85
107
  errorOwnFieldNames: Object.freeze([...options.errorOwnFieldNames ?? []]),
86
108
  serializers: Object.freeze({ ...options.serializers ?? {} }),
@@ -144,6 +166,41 @@ function checkGroup(path2, value) {
144
166
  if (!isRecord(value)) reject(path2, "must be an object", value);
145
167
  return value;
146
168
  }
169
+ var MAX_TIMER_MS = 2147483647;
170
+ function checkTimerMs(path2, value) {
171
+ if (value === void 0) return;
172
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_TIMER_MS) {
173
+ reject(path2, `must be an integer from 1 to ${String(MAX_TIMER_MS)}`, value);
174
+ }
175
+ }
176
+ function validateQueue(options) {
177
+ const queue = checkGroup("destinationQueue", options.destinationQueue);
178
+ const maxBytes = queue?.["maxBytes"];
179
+ if (maxBytes === void 0 || maxBytes === 0) return;
180
+ if (typeof maxBytes !== "number" || !Number.isInteger(maxBytes) || maxBytes < MIN_QUEUE_MAX_BYTES || maxBytes > MAX_QUEUE_MAX_BYTES) {
181
+ reject(
182
+ "destinationQueue.maxBytes",
183
+ `must be 0 (no bound) or an integer from ${String(MIN_QUEUE_MAX_BYTES)} to ${String(MAX_QUEUE_MAX_BYTES)}`,
184
+ maxBytes
185
+ );
186
+ }
187
+ }
188
+ function validateLifecycle(options) {
189
+ checkTimerMs("destinationHookTimeoutMs", options.destinationHookTimeoutMs);
190
+ const shutdown = checkGroup("shutdown", options.shutdown);
191
+ if (shutdown === void 0) return;
192
+ checkTimerMs("shutdown.timeoutMs", shutdown["timeoutMs"]);
193
+ checkTimerMs("shutdown.drainTimeoutMs", shutdown["drainTimeoutMs"]);
194
+ const { timeoutMs, drainTimeoutMs } = shutdown;
195
+ const total = typeof timeoutMs === "number" ? timeoutMs : DEFAULT_SHUTDOWN_TIMEOUT_MS;
196
+ if (typeof drainTimeoutMs === "number" && drainTimeoutMs > total) {
197
+ reject(
198
+ "shutdown.drainTimeoutMs",
199
+ "must not exceed shutdown.timeoutMs, which covers the drain and every onShutdown",
200
+ drainTimeoutMs
201
+ );
202
+ }
203
+ }
147
204
  function validateCore(options) {
148
205
  if (!options.service) {
149
206
  throw new Error("[BymaxLoggerModule] options.service is required");
@@ -277,23 +334,25 @@ function validateDestinations(options) {
277
334
  }
278
335
  destinations.forEach((entry, index) => validateDestination(entry, index));
279
336
  }
337
+ function checkRegExpList(path2, value) {
338
+ if (value === void 0) return;
339
+ if (!Array.isArray(value)) {
340
+ reject(path2, "must be an array of RegExp", value);
341
+ }
342
+ value.forEach((pattern, index) => {
343
+ if (!types.isRegExp(pattern)) {
344
+ reject(`${path2}[${String(index)}]`, "must be a RegExp", pattern);
345
+ }
346
+ });
347
+ }
280
348
  function validateHttp(options) {
281
349
  const http = checkGroup("http", options.http);
282
350
  if (http === void 0) return;
283
351
  checkBoolean("http.isEnabled", http["isEnabled"]);
284
352
  checkBoolean("http.shouldCaptureExceptions", http["shouldCaptureExceptions"]);
285
353
  checkBoolean("http.shouldGenerateRequestId", http["shouldGenerateRequestId"]);
286
- const excludePaths = http["excludePaths"];
287
- if (excludePaths !== void 0) {
288
- if (!Array.isArray(excludePaths)) {
289
- reject("http.excludePaths", "must be an array of RegExp", excludePaths);
290
- }
291
- excludePaths.forEach((pattern, index) => {
292
- if (!types.isRegExp(pattern)) {
293
- reject(`http.excludePaths[${String(index)}]`, "must be a RegExp", pattern);
294
- }
295
- });
296
- }
354
+ checkRegExpList("http.excludePaths", http["excludePaths"]);
355
+ checkRegExpList("http.secretPathSegments", http["secretPathSegments"]);
297
356
  const tenantIdHeader = http["tenantIdHeader"];
298
357
  if (tenantIdHeader !== void 0 && tenantIdHeader !== false && !isNonEmptyString(tenantIdHeader)) {
299
358
  reject("http.tenantIdHeader", "must be a non-empty string or false", tenantIdHeader);
@@ -321,6 +380,8 @@ function validateOptions(options) {
321
380
  validateCustomization(options);
322
381
  validateErrorFields(options);
323
382
  validateDestinations(options);
383
+ validateLifecycle(options);
384
+ validateQueue(options);
324
385
  validateHttp(options);
325
386
  validateOtel(options);
326
387
  }
@@ -951,6 +1012,15 @@ var DefaultStdoutDestination = class {
951
1012
  this.minLevel = opts.minLevel;
952
1013
  }
953
1014
  }
1015
+ /**
1016
+ * The bytes `process.stdout` holds that have not reached its reader.
1017
+ *
1018
+ * @returns `process.stdout.writableLength`, in bytes since Node decodes a string chunk to a
1019
+ * buffer before queueing it.
1020
+ */
1021
+ queuedBytes() {
1022
+ return process.stdout.writableLength;
1023
+ }
954
1024
  /**
955
1025
  * Write a serialized JSON log entry (terminated with `\n`) to `stdout`.
956
1026
  *
@@ -1050,32 +1120,89 @@ function readUserAgent(req) {
1050
1120
  return typeof raw === "string" ? raw : UNKNOWN_USER_AGENT;
1051
1121
  }
1052
1122
 
1123
+ // src/server/utils/matches-exclude-path.util.ts
1124
+ function matchesExcludePath(patterns, path2) {
1125
+ return patterns.some((pattern) => {
1126
+ if (pattern.global || pattern.sticky) {
1127
+ pattern.lastIndex = 0;
1128
+ }
1129
+ return pattern.test(path2);
1130
+ });
1131
+ }
1132
+
1053
1133
  // src/server/utils/normalize-url.util.ts
1054
1134
  var UUID_REGEX = /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?![0-9a-f])/gi;
1055
1135
  var ULID_REGEX = /\/[0-9A-HJKMNP-TV-Z]{26}(?![0-9A-HJKMNP-TV-Z])/g;
1056
1136
  var NANOID_REGEX = /\/[A-Za-z0-9_-]{21}(?![A-Za-z0-9_-])/g;
1057
1137
  var NUMERIC_ID_REGEX = /\/\d+/g;
1058
1138
  var ID_PLACEHOLDER = "/:id";
1059
- function normalizeUrl(url) {
1060
- return stripQueryString(url).replace(UUID_REGEX, ID_PLACEHOLDER).replace(ULID_REGEX, ID_PLACEHOLDER).replace(NANOID_REGEX, ID_PLACEHOLDER).replace(NUMERIC_ID_REGEX, ID_PLACEHOLDER);
1139
+ var SECRET_PLACEHOLDER = ":redacted";
1140
+ var HEX_SECRET_REGEX = /^[0-9a-f]{32,}$/i;
1141
+ var JWT_SECRET_REGEX = /^eyJ[\w-]*\.[\w-]+\.[\w-]*$/;
1142
+ var TOKEN_SECRET_REGEX = /^[A-Za-z0-9_+/-]{32,}={0,2}$/;
1143
+ var SLUG_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)+$/;
1144
+ var HEX_RUN_REGEX = /[0-9a-f]{32}/i;
1145
+ var UUID_SEGMENT_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1146
+ var EMAIL_SECRET_REGEX = /^[^@\s]+@[^@\s.]+(?:\.[^@\s.]+)+$/;
1147
+ function decodeSegment(segment) {
1148
+ try {
1149
+ return decodeURIComponent(segment);
1150
+ } catch {
1151
+ return segment;
1152
+ }
1153
+ }
1154
+ function isSecretSegment(segment, extra) {
1155
+ if (segment === "") return false;
1156
+ const decoded = decodeSegment(segment);
1157
+ return looksLikeToken(decoded) || looksLikeToken(withoutExtension(decoded)) || hasTokenPart(decoded) || EMAIL_SECRET_REGEX.test(decoded) || matchesExcludePath(extra, decoded);
1158
+ }
1159
+ function hasTokenPart(segment) {
1160
+ return segment.split(".").some(looksLikeToken);
1161
+ }
1162
+ function withoutExtension(segment) {
1163
+ const dot = segment.lastIndexOf(".");
1164
+ const dotAfterStart = dot > 0;
1165
+ return dotAfterStart && segment.length - dot <= 9 ? segment.slice(0, dot) : segment;
1166
+ }
1167
+ function looksLikeToken(value) {
1168
+ return HEX_SECRET_REGEX.test(value) || HEX_RUN_REGEX.test(value) || JWT_SECRET_REGEX.test(value) || TOKEN_SECRET_REGEX.test(value) && !SLUG_REGEX.test(value) && !UUID_SEGMENT_REGEX.test(value);
1169
+ }
1170
+ function secretPathSegments(url, extra = []) {
1171
+ const found = /* @__PURE__ */ new Set();
1172
+ for (const segment of stripQueryString(url).split("/")) {
1173
+ if (isSecretSegment(segment, extra)) found.add(segment);
1174
+ }
1175
+ return [...found];
1176
+ }
1177
+ function scrubSecretSegments(path2, extra = []) {
1178
+ return path2.split("/").map((segment) => isSecretSegment(segment, extra) ? SECRET_PLACEHOLDER : segment).join("/");
1179
+ }
1180
+ function normalizeUrl(url, extra = []) {
1181
+ return scrubSecretSegments(stripQueryString(url), extra).replace(UUID_REGEX, ID_PLACEHOLDER).replace(ULID_REGEX, ID_PLACEHOLDER).replace(NANOID_REGEX, ID_PLACEHOLDER).replace(NUMERIC_ID_REGEX, ID_PLACEHOLDER);
1061
1182
  }
1062
1183
  function stripQueryString(url) {
1063
1184
  const queryStart = url.indexOf("?");
1064
1185
  return queryStart === -1 ? url : url.slice(0, queryStart);
1065
1186
  }
1066
- function withoutRequestQuery(text, ...urls) {
1187
+ function withoutRequestSecrets(text, extra, ...urls) {
1067
1188
  let result = text;
1189
+ const segments = /* @__PURE__ */ new Set();
1068
1190
  for (const url of urls) {
1069
1191
  if (url === void 0) continue;
1070
1192
  const queryStart = url.indexOf("?");
1071
1193
  if (queryStart !== -1 && url.length - queryStart > 1) {
1072
1194
  result = result.split(url.slice(queryStart)).join("");
1073
1195
  }
1196
+ for (const segment of secretPathSegments(url, extra)) segments.add(segment);
1197
+ }
1198
+ if (segments.size > 0) {
1199
+ const alternation = [...segments].sort((left, right) => right.length - left.length).map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
1200
+ result = result.replace(new RegExp(alternation, "g"), SECRET_PLACEHOLDER);
1074
1201
  }
1075
1202
  return result;
1076
1203
  }
1077
- function withoutRequestQueryIfText(value, ...urls) {
1078
- return typeof value === "string" ? withoutRequestQuery(value, ...urls) : value;
1204
+ function withoutRequestSecretsIfText(value, extra, ...urls) {
1205
+ return typeof value === "string" ? withoutRequestSecrets(value, extra, ...urls) : value;
1079
1206
  }
1080
1207
 
1081
1208
  // src/server/filters/http-exception.filter.ts
@@ -1088,9 +1215,12 @@ var HttpExceptionFilter = class {
1088
1215
  * @param logger - The structured logger exception entries are written to.
1089
1216
  * Injected by token explicitly: the package is bundled without
1090
1217
  * `emitDecoratorMetadata`, so implicit class-type injection would not resolve.
1218
+ * @param options - Resolved module options, read for `http.secretPathSegments`. Optional, so a
1219
+ * filter built by hand with the logger alone keeps the built-in credential patterns.
1091
1220
  */
1092
- constructor(logger) {
1221
+ constructor(logger, options) {
1093
1222
  this.logger = logger;
1223
+ this.secretPathSegments = options?.http.secretPathSegments ?? [];
1094
1224
  }
1095
1225
  /**
1096
1226
  * Log the exception at the status-appropriate level and write the JSON
@@ -1104,7 +1234,7 @@ var HttpExceptionFilter = class {
1104
1234
  const res = ctx.getResponse();
1105
1235
  const req = ctx.getRequest();
1106
1236
  const userId = req.user?.sub ?? req.user?.id;
1107
- const url = stripQueryString(req.url);
1237
+ const url = scrubSecretSegments(stripQueryString(req.url), this.secretPathSegments);
1108
1238
  if (exception instanceof HttpException) {
1109
1239
  const status = exception.getStatus();
1110
1240
  const parserError = readRecordedParserError(req);
@@ -1124,7 +1254,12 @@ var HttpExceptionFilter = class {
1124
1254
  } else {
1125
1255
  this.logger.warnStructured(
1126
1256
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
1127
- parserError?.logMessage ?? withoutRequestQuery(exception.message, req.originalUrl, req.url),
1257
+ parserError?.logMessage ?? withoutRequestSecrets(
1258
+ exception.message,
1259
+ this.secretPathSegments,
1260
+ req.originalUrl,
1261
+ req.url
1262
+ ),
1128
1263
  userId,
1129
1264
  metadata
1130
1265
  );
@@ -1154,7 +1289,7 @@ var HttpExceptionFilter = class {
1154
1289
  const { method, url, userId } = request;
1155
1290
  this.logger.warnStructured(
1156
1291
  RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
1157
- withoutRequestQuery(clientError.logMessage, ...rawUrls),
1292
+ withoutRequestSecrets(clientError.logMessage, this.secretPathSegments, ...rawUrls),
1158
1293
  userId,
1159
1294
  {
1160
1295
  method,
@@ -1189,20 +1324,10 @@ var HttpExceptionFilter = class {
1189
1324
  };
1190
1325
  HttpExceptionFilter = __decorateClass([
1191
1326
  Catch(),
1192
- __decorateParam(0, Inject(PinoLoggerService))
1327
+ __decorateParam(0, Inject(PinoLoggerService)),
1328
+ __decorateParam(1, Optional()),
1329
+ __decorateParam(1, Inject(LOGGER_OPTIONS_TOKEN))
1193
1330
  ], HttpExceptionFilter);
1194
-
1195
- // src/server/utils/matches-exclude-path.util.ts
1196
- function matchesExcludePath(patterns, path2) {
1197
- return patterns.some((pattern) => {
1198
- if (pattern.global || pattern.sticky) {
1199
- pattern.lastIndex = 0;
1200
- }
1201
- return pattern.test(path2);
1202
- });
1203
- }
1204
-
1205
- // src/server/interceptors/http-logging.interceptor.ts
1206
1331
  var HTTP_SUCCESS_MIN = 200;
1207
1332
  var HttpLoggingInterceptor = class {
1208
1333
  /**
@@ -1215,6 +1340,7 @@ var HttpLoggingInterceptor = class {
1215
1340
  constructor(logger, options) {
1216
1341
  this.logger = logger;
1217
1342
  this.excludePaths = options.http.excludePaths;
1343
+ this.secretPathSegments = options.http.secretPathSegments;
1218
1344
  }
1219
1345
  /**
1220
1346
  * Whether a request path bypasses HTTP logging (matches any `excludePaths`).
@@ -1246,7 +1372,7 @@ var HttpLoggingInterceptor = class {
1246
1372
  }
1247
1373
  const userAgent = readUserAgent(req);
1248
1374
  const userId = readUserId(req);
1249
- const normalizedUrl = normalizeUrl(url);
1375
+ const normalizedUrl = normalizeUrl(url, this.secretPathSegments);
1250
1376
  const start = Date.now();
1251
1377
  this.logger.info(RESERVED_LOG_KEYS.HTTP_REQUEST_START, `${method} ${normalizedUrl}`, userId, {
1252
1378
  method,
@@ -1254,7 +1380,7 @@ var HttpLoggingInterceptor = class {
1254
1380
  // Query string stripped: it may carry secrets (reset tokens, OAuth codes)
1255
1381
  // that Pino's path-based redaction cannot scrub from a string value. The
1256
1382
  // raw (un-normalized) path is kept for per-request debugging.
1257
- fullUrl: stripQueryString(url),
1383
+ fullUrl: scrubSecretSegments(stripQueryString(url), this.secretPathSegments),
1258
1384
  ip,
1259
1385
  userAgent
1260
1386
  });
@@ -1352,7 +1478,9 @@ var HttpLoggingInterceptor = class {
1352
1478
  url,
1353
1479
  statusCode,
1354
1480
  duration,
1355
- errorMessage: cutIfText(withoutRequestQueryIfText(err.message, ...rawUrls))
1481
+ errorMessage: cutIfText(
1482
+ withoutRequestSecretsIfText(err.message, this.secretPathSegments, ...rawUrls)
1483
+ )
1356
1484
  }
1357
1485
  );
1358
1486
  }
@@ -1390,7 +1518,9 @@ var HttpLoggingInterceptor = class {
1390
1518
  url,
1391
1519
  statusCode: clientError.status,
1392
1520
  duration,
1393
- errorMessage: cutIfText(withoutRequestQueryIfText(clientError.logMessage, ...rawUrls)),
1521
+ errorMessage: cutIfText(
1522
+ withoutRequestSecretsIfText(clientError.logMessage, this.secretPathSegments, ...rawUrls)
1523
+ ),
1394
1524
  bodyParserType: clientError.bodyParserType
1395
1525
  }
1396
1526
  );
@@ -1812,7 +1942,47 @@ var REDACT_COMMON_FIELDS = [
1812
1942
  "cookie",
1813
1943
  "set-cookie",
1814
1944
  "x-api-key",
1815
- "x-auth-token"
1945
+ "x-auth-token",
1946
+ // The spellings systems actually write. The default `'names'` matching is case-insensitive, so
1947
+ // `accessToken` already covers `ACCESSTOKEN`, but not `access_token` (the OAuth wire name) or
1948
+ // `access-token`: those are different names. The legacy `'paths'` engine is case-sensitive, so
1949
+ // the all-lowercase `apikey` and `sessiontoken` are listed too.
1950
+ // OAuth and API credentials, snake case.
1951
+ "access_token",
1952
+ "refresh_token",
1953
+ "id_token",
1954
+ "api_key",
1955
+ "apikey",
1956
+ "api_secret",
1957
+ "client_secret",
1958
+ "signing_secret",
1959
+ "private_key",
1960
+ "secret_key",
1961
+ "secretKey",
1962
+ // The same, kebab case.
1963
+ "access-token",
1964
+ "refresh-token",
1965
+ "id-token",
1966
+ "api-key",
1967
+ "client-secret",
1968
+ "private-key",
1969
+ // Session and CSRF credentials, in the spellings of a cookie, a header and a body field. A bare
1970
+ // `sessionId` is deliberately absent: many applications carry it as a correlation key, and the
1971
+ // only way to get such a field back would be to turn every default off.
1972
+ "proxy-authorization",
1973
+ "session_token",
1974
+ "sessionToken",
1975
+ "sessiontoken",
1976
+ "session-token",
1977
+ "x-csrf-token",
1978
+ "x-xsrf-token",
1979
+ "csrf_token",
1980
+ "csrfToken",
1981
+ "csrf-token",
1982
+ // The password family, snake case.
1983
+ "password_hash",
1984
+ "new_password",
1985
+ "old_password"
1816
1986
  ];
1817
1987
  var REDACT_ABSOLUTE_PATHS = [
1818
1988
  "req.headers.authorization",
@@ -1828,14 +1998,15 @@ var DEFAULT_REDACT_PATHS = [
1828
1998
  ];
1829
1999
 
1830
2000
  // src/server/utils/report-destination-failure.util.ts
1831
- function reportDestinationFailure(logKey, name, cause, msg) {
2001
+ function reportDestinationFailure(logKey, name, cause, msg, suppressed = 0) {
1832
2002
  writeStderrSafely(
1833
2003
  JSON.stringify({
1834
2004
  level: "error",
1835
2005
  logKey,
1836
2006
  destination: toSingleLineMessage(name),
1837
2007
  err: describeCause(cause),
1838
- msg: toSingleLineMessage(msg)
2008
+ msg: toSingleLineMessage(msg),
2009
+ ...suppressed > 0 ? { suppressed } : {}
1839
2010
  }) + "\n"
1840
2011
  );
1841
2012
  }
@@ -1978,29 +2149,108 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
1978
2149
  const sources = shouldSkipDefaults ? [extraPaths] : [DEFAULT_REDACT_PATHS, extraPaths];
1979
2150
  return Array.from(new Set(sources.flat()));
1980
2151
  }
1981
- function reportWriteFailure(destination, cause) {
2152
+ function reportWriteFailure(destination, cause, due) {
1982
2153
  const name = safeDestinationName(destination);
1983
2154
  reportDestinationFailure(
1984
2155
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_WRITE_FAILED,
1985
2156
  name,
1986
2157
  cause,
1987
- `Log destination "${name}" failed to write; the entry was dropped`
2158
+ `Log destination "${name}" failed to write; the entry was dropped`,
2159
+ due - 1
1988
2160
  );
1989
2161
  }
1990
2162
  function rescueToStdout(payload) {
1991
2163
  writeStdoutSafely(payload);
1992
2164
  }
1993
- function destinationToStream(destination, health) {
1994
- return new Writable({
2165
+ function ownQueuedBytes(destination) {
2166
+ try {
2167
+ const bytes = destination.queuedBytes?.() ?? 0;
2168
+ const positive = Number.isFinite(bytes) && bytes > 0;
2169
+ return positive ? bytes : 0;
2170
+ } catch {
2171
+ return 0;
2172
+ }
2173
+ }
2174
+ var BoundedWritable = class extends Writable {
2175
+ constructor(destination, health, maxBytes, queue, options) {
2176
+ super(options);
2177
+ this.destination = destination;
2178
+ this.health = health;
2179
+ this.maxBytes = maxBytes;
2180
+ this.queue = queue;
2181
+ }
2182
+ /**
2183
+ * A destroyed stream holds nothing: Writable fails the chunks still buffered without calling the
2184
+ * write handler, so nothing else would release their bytes.
2185
+ */
2186
+ _destroy(error, callback) {
2187
+ this.queue.bytes = 0;
2188
+ super._destroy(error, callback);
2189
+ }
2190
+ /** The bytes of NDJSON waiting for the destination, the write in flight included. */
2191
+ get queuedBytes() {
2192
+ return this.queue.bytes;
2193
+ }
2194
+ write(chunk, encodingOrCallback, callback) {
2195
+ if (this.writableEnded || this.destroyed) {
2196
+ return this.forward(chunk, encodingOrCallback, callback);
2197
+ }
2198
+ const bytes = Buffer.byteLength(chunk);
2199
+ const held = this.heldBytes();
2200
+ if (this.maxBytes > 0 && held > 0 && held + bytes > this.maxBytes) {
2201
+ this.dropped();
2202
+ const done = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
2203
+ done?.();
2204
+ return true;
2205
+ }
2206
+ this.queue.bytes += bytes;
2207
+ return this.forward(chunk, encodingOrCallback, callback);
2208
+ }
2209
+ /** `Writable.write` for either of its two signatures. */
2210
+ forward(chunk, encodingOrCallback, callback) {
2211
+ return typeof encodingOrCallback === "function" ? super.write(chunk, encodingOrCallback) : super.write(chunk, encodingOrCallback ?? "utf8", callback);
2212
+ }
2213
+ /**
2214
+ * What the entry would queue behind. A live destination holds its module queue and what it reports
2215
+ * in a buffer of its own. A failed destination receives nothing, so what it reports does not count,
2216
+ * and the one elected to rescue entries writes them to stdout, whose queue is what grows.
2217
+ */
2218
+ heldBytes() {
2219
+ if (!this.health.isFailed(this.destination)) {
2220
+ return this.queue.bytes + ownQueuedBytes(this.destination);
2221
+ }
2222
+ return this.health.shouldRescue(this.destination) ? this.queue.bytes + process.stdout.writableLength : 0;
2223
+ }
2224
+ /** Count the drop, and write the report when one is due. */
2225
+ dropped() {
2226
+ const due = this.health.recordDrop(this.destination, performance.now());
2227
+ if (due === void 0) return;
2228
+ const name = toSingleLineMessage(safeDestinationName(this.destination));
2229
+ writeStderrSafely(
2230
+ `[DestinationRegistry] Destination "${name}" queue full: ${String(due)} entries dropped since the last report (limit ${String(this.maxBytes)} bytes)
2231
+ `
2232
+ );
2233
+ }
2234
+ };
2235
+ function destinationToStream(destination, health, maxQueueBytes = 0) {
2236
+ const queue = { bytes: 0 };
2237
+ const stream = new BoundedWritable(destination, health, maxQueueBytes, queue, {
1995
2238
  // Keep string chunks as strings (Node's default re-encodes them to Buffers
1996
2239
  // before `_write`): the common Pino path emits NDJSON strings, so this skips
1997
2240
  // a string→Buffer→string round-trip on the hot logging path.
1998
2241
  // Stryker disable next-line BooleanLiteral: equivalent for every chunk this stream receives — with `true`, Node encodes the string to a Buffer and `write()` below decodes it back with `toString('utf-8')`. Pino writes UTF-8 NDJSON strings at the default encoding, so the round-trip returns the identical string. It is NOT equivalent in general: a `write(chunk, 'latin1')` would round-trip through UTF-8 and change non-ASCII bytes, which is unreachable here because nothing writes to this stream but Pino. The flag stays because it skips the round-trip on the hot logging path.
1999
2242
  decodeStrings: false,
2000
- write(chunk, _encoding, callback) {
2243
+ write(chunk, _encoding, settled) {
2244
+ const bytes = Buffer.byteLength(chunk);
2245
+ const callback = (error) => {
2246
+ queue.bytes = Math.max(0, queue.bytes - bytes);
2247
+ settled(error);
2248
+ };
2001
2249
  const onFailure = (cause) => {
2002
- health.markWriteFailed(destination);
2003
- reportWriteFailure(destination, cause);
2250
+ const due = health.recordWriteFailure(destination, performance.now());
2251
+ if (due !== void 0) {
2252
+ reportWriteFailure(destination, cause, due);
2253
+ }
2004
2254
  callback();
2005
2255
  };
2006
2256
  try {
@@ -2033,6 +2283,15 @@ function destinationToStream(destination, health) {
2033
2283
  }
2034
2284
  }
2035
2285
  });
2286
+ return stream;
2287
+ }
2288
+
2289
+ // src/server/utils/censor-raw-headers.util.ts
2290
+ function censorRawHeaders(raw, sensitive, censor) {
2291
+ return raw.map((entry, index) => {
2292
+ const name = index % 2 === 1 ? raw[index - 1] : void 0;
2293
+ return typeof name === "string" && sensitive.has(name.toLowerCase()) ? censor : entry;
2294
+ });
2036
2295
  }
2037
2296
 
2038
2297
  // src/server/utils/redact-error-clone.util.ts
@@ -2152,6 +2411,10 @@ function addErrorParts(copy, error, ownKeys, host, depth2) {
2152
2411
  }
2153
2412
 
2154
2413
  // src/server/utils/redact-by-name.util.ts
2414
+ var RAW_HEADER_KEYS = /* @__PURE__ */ new Set(["rawheaders", "rawtrailers"]);
2415
+ function censorHeaderArray(key, walked, rules) {
2416
+ return RAW_HEADER_KEYS.has(key.toLowerCase()) && Array.isArray(walked) ? censorRawHeaders(walked, rules.headerNames, rules.censor) : walked;
2417
+ }
2155
2418
  var REDACT_MAX_TRAVERSAL_DEPTH = 100;
2156
2419
  var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
2157
2420
  var REDACT_MAX_VISITS = 2e5;
@@ -2280,13 +2543,17 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
2280
2543
  defineOwn(
2281
2544
  copy,
2282
2545
  key,
2283
- rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
2284
- scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
2285
- rules,
2286
- depth2 + 1,
2287
- ancestors,
2288
- true,
2289
- inSerialized || !honorToJson && rules.serializedKeys.has(key)
2546
+ rules.sensitive.has(key.toLowerCase()) ? rules.censor : censorHeaderArray(
2547
+ key,
2548
+ walk(
2549
+ scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
2550
+ rules,
2551
+ depth2 + 1,
2552
+ ancestors,
2553
+ true,
2554
+ inSerialized || !honorToJson && rules.serializedKeys.has(key)
2555
+ ),
2556
+ rules
2290
2557
  )
2291
2558
  );
2292
2559
  }
@@ -2316,9 +2583,10 @@ function errorPartsHost(rules, ancestors, inSerialized) {
2316
2583
  hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
2317
2584
  };
2318
2585
  }
2319
- function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames) {
2586
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames, headerNames) {
2320
2587
  const rules = {
2321
2588
  sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
2589
+ headerNames: new Set(Array.from(headerNames ?? fieldNames, (name) => name.toLowerCase())),
2322
2590
  censor,
2323
2591
  serializedKeys: new Set(serializedKeys),
2324
2592
  errorsAsData: serializedKeys !== void 0,
@@ -2465,6 +2733,39 @@ function extraServiceFields(service) {
2465
2733
  return extras;
2466
2734
  }
2467
2735
 
2736
+ // src/server/utils/serialize-request.util.ts
2737
+ function isObject2(value) {
2738
+ return typeof value === "object" && value !== null;
2739
+ }
2740
+ function isRequest(value) {
2741
+ if (!isObject2(value)) return false;
2742
+ const { rawHeaders, method, socket } = value;
2743
+ return Array.isArray(rawHeaders) || typeof method === "string" && isObject2(socket);
2744
+ }
2745
+ function copyHeaders(headers) {
2746
+ return isObject2(headers) ? { ...headers } : {};
2747
+ }
2748
+ function serializeRequestValue(input, secretSegments = []) {
2749
+ try {
2750
+ if (!isRequest(input)) return input;
2751
+ const url = input.originalUrl ?? input.url;
2752
+ const socket = input.socket;
2753
+ return {
2754
+ method: input.method,
2755
+ url: typeof url === "string" ? scrubSecretSegments(stripQueryString(url), secretSegments) : url,
2756
+ headers: copyHeaders(input.headers),
2757
+ remoteAddress: socket?.remoteAddress
2758
+ };
2759
+ } catch {
2760
+ return { _unserializable: "request" };
2761
+ }
2762
+ }
2763
+ function withSerializedRequest(record, secretSegments = []) {
2764
+ const request = record["req"];
2765
+ const serialized = serializeRequestValue(request, secretSegments);
2766
+ return serialized === request ? record : { ...record, req: serialized };
2767
+ }
2768
+
2468
2769
  // src/server/utils/truncate-large-entries.ts
2469
2770
  var PREVIEW_LENGTH = 200;
2470
2771
  function createSizeBoundedSerializer(baseSerializer, maxBytes) {
@@ -2578,10 +2879,11 @@ function namesInsideErrors(options) {
2578
2879
  return options.shouldDisableDefaultRedact ? void 0 : REDACT_COMMON_FIELDS;
2579
2880
  }
2580
2881
  function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
2581
- const names = coversNames ? [
2882
+ const allNames = [
2582
2883
  ...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
2583
2884
  ...options.redactPaths.flatMap((path2) => leafNameOf(path2) ?? [])
2584
- ] : [];
2885
+ ];
2886
+ const names = coversNames ? allNames : [];
2585
2887
  const ownFields = ownFieldPolicyOf(options);
2586
2888
  const walks = names.length > 0 || ownFields.safe;
2587
2889
  if (!walks && resolveRedactOption(options) === void 0) {
@@ -2593,8 +2895,17 @@ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = tr
2593
2895
  ["err", ...Object.keys(options.serializers)],
2594
2896
  void 0,
2595
2897
  ownFields,
2596
- coversNames ? void 0 : namesInsideErrors(options)
2597
- ) : createNameRedactor(names, options.redactCensor, void 0, void 0, ownFields);
2898
+ coversNames ? void 0 : namesInsideErrors(options),
2899
+ allNames
2900
+ ) : createNameRedactor(
2901
+ names,
2902
+ options.redactCensor,
2903
+ void 0,
2904
+ void 0,
2905
+ ownFields,
2906
+ void 0,
2907
+ allNames
2908
+ );
2598
2909
  }
2599
2910
  function resolveRedactOption(options) {
2600
2911
  const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
@@ -2609,6 +2920,7 @@ function buildPinoInstance(options, logContext, destinations, health) {
2609
2920
  const redactSerialized = buildNameRedactor(options);
2610
2921
  const ownFields = ownFieldPolicyOf(options);
2611
2922
  const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
2923
+ const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
2612
2924
  const serializers = {
2613
2925
  err: bound((error) => serializeErrorValue(error, ownFields)),
2614
2926
  ...Object.fromEntries(
@@ -2656,7 +2968,10 @@ function buildPinoInstance(options, logContext, destinations, health) {
2656
2968
  // sensitive, which `pino-factory.spec.ts` pins.
2657
2969
  log: (record) => withSemconvException(
2658
2970
  withEventName(
2659
- redactRecord(record, true),
2971
+ redactRecord(
2972
+ hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2973
+ true
2974
+ ),
2660
2975
  options.eventNameField
2661
2976
  ),
2662
2977
  options.errorFormat
@@ -2681,16 +2996,34 @@ function buildPinoInstance(options, logContext, destinations, health) {
2681
2996
  }
2682
2997
  }
2683
2998
  };
2684
- const streams = destinations.map((destination) => ({
2685
- // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
2686
- // consumer implementing `minLevel` as a throwing getter would fail the factory
2687
- // and the application would never start — earlier than any fail-soft path can
2688
- // contain. Unreadable and absent give the same answer: the module level.
2689
- level: safeMinLevel(destination) ?? options.level,
2690
- stream: destinationToStream(destination, health)
2691
- }));
2999
+ const streams = destinations.map((destination) => {
3000
+ const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
3001
+ health.registerStream(destination, stream);
3002
+ return {
3003
+ // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
3004
+ // consumer implementing `minLevel` as a throwing getter would fail the factory
3005
+ // and the application would never start — earlier than any fail-soft path can
3006
+ // contain. Unreadable and absent give the same answer: the module level.
3007
+ level: safeMinLevel(destination) ?? options.level,
3008
+ stream
3009
+ };
3010
+ });
2692
3011
  return pino(pinoOptions, pino.multistream(streams));
2693
3012
  }
3013
+ var DROP_REPORT_INTERVAL_MS = 1e4;
3014
+ function countInWindow(records, destination, now) {
3015
+ const record = records.get(destination) ?? { total: 0, unreported: 0, lastReportAt: void 0 };
3016
+ records.set(destination, record);
3017
+ record.total += 1;
3018
+ record.unreported += 1;
3019
+ if (record.lastReportAt !== void 0 && now - record.lastReportAt < DROP_REPORT_INTERVAL_MS) {
3020
+ return void 0;
3021
+ }
3022
+ record.lastReportAt = now;
3023
+ const due = record.unreported;
3024
+ record.unreported = 0;
3025
+ return due;
3026
+ }
2694
3027
  var DestinationHealth = class {
2695
3028
  constructor() {
2696
3029
  /** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
@@ -2734,6 +3067,12 @@ var DestinationHealth = class {
2734
3067
  * when the last one settles.
2735
3068
  */
2736
3069
  this.pendingWrites = /* @__PURE__ */ new Map();
3070
+ /** The `Writable` that fronts each destination, whose buffer is the queue of entries it holds. */
3071
+ this.streams = /* @__PURE__ */ new Map();
3072
+ /** Entries dropped for want of queue room, per destination, and when the last one was reported. */
3073
+ this.drops = /* @__PURE__ */ new Map();
3074
+ /** Writes a destination refused, per destination, and when the last one was reported. */
3075
+ this.writeFailures = /* @__PURE__ */ new Map();
2737
3076
  /**
2738
3077
  * The rescuer's severity index within {@link LOG_LEVEL_PRIORITY}. Starts above
2739
3078
  * every real level so the first `markFailed` always wins the comparison.
@@ -2752,6 +3091,77 @@ var DestinationHealth = class {
2752
3091
  markWriteFailed(destination) {
2753
3092
  this.writeFailed.add(destination);
2754
3093
  }
3094
+ /**
3095
+ * Record one entry dropped because the destination's queue was full, and say whether the drop is
3096
+ * due a report.
3097
+ *
3098
+ * A report is due on the first drop and then at most once every {@link DROP_REPORT_INTERVAL_MS},
3099
+ * so a sustained overflow costs one stderr line per window and not one per entry.
3100
+ *
3101
+ * @param destination - The destination whose queue was full.
3102
+ * @param now - A monotonic reading in milliseconds (`performance.now()`).
3103
+ * @returns The number of drops since the last report when one is due, otherwise `undefined`.
3104
+ */
3105
+ recordDrop(destination, now) {
3106
+ this.writeFailed.add(destination);
3107
+ return countInWindow(this.drops, destination, now);
3108
+ }
3109
+ /**
3110
+ * Record one write the destination refused (it threw or rejected), and say whether the failure is
3111
+ * due a report.
3112
+ *
3113
+ * The destination is marked as having failed a write at once, as {@link markWriteFailed} does; only
3114
+ * the report is windowed, in the same way as {@link recordDrop}: the first failure is due at once
3115
+ * and then at most once every {@link DROP_REPORT_INTERVAL_MS}, so a destination that refuses every
3116
+ * entry costs one stderr line per window and not one per entry.
3117
+ *
3118
+ * @param destination - The destination whose write failed.
3119
+ * @param now - A monotonic reading in milliseconds (`performance.now()`).
3120
+ * @returns The number of failures since the last report, this one included, when one is due,
3121
+ * otherwise `undefined`.
3122
+ */
3123
+ recordWriteFailure(destination, now) {
3124
+ this.writeFailed.add(destination);
3125
+ return countInWindow(this.writeFailures, destination, now);
3126
+ }
3127
+ /**
3128
+ * How many writes a destination has refused since startup.
3129
+ *
3130
+ * @param destination - The destination to ask about.
3131
+ * @returns The count, `0` when none.
3132
+ */
3133
+ failedWriteTotal(destination) {
3134
+ return this.writeFailures.get(destination)?.total ?? 0;
3135
+ }
3136
+ /**
3137
+ * How many entries a destination has had dropped for want of queue room.
3138
+ *
3139
+ * @param destination - The destination to ask about.
3140
+ * @returns The count since startup, `0` when none.
3141
+ */
3142
+ droppedTotal(destination) {
3143
+ return this.drops.get(destination)?.total ?? 0;
3144
+ }
3145
+ /**
3146
+ * Record the stream that fronts a destination, whose buffer is the queue of entries it holds.
3147
+ *
3148
+ * @param destination - The destination.
3149
+ * @param stream - Its `Writable` adapter, read only for the bytes it holds queued.
3150
+ */
3151
+ registerStream(destination, stream) {
3152
+ this.streams.set(destination, stream);
3153
+ }
3154
+ /**
3155
+ * How much a destination still holds: the size of what Pino has written to its stream and the
3156
+ * destination has not yet taken, the write in flight included. Zero means nothing is queued.
3157
+ *
3158
+ * @param destination - The destination to ask about.
3159
+ * @returns The queued size in bytes of NDJSON, `0` for a
3160
+ * destination whose stream is not known.
3161
+ */
3162
+ queuedSize(destination) {
3163
+ return this.streams.get(destination)?.queuedBytes ?? 0;
3164
+ }
2755
3165
  /**
2756
3166
  * Record that an asynchronous write to a destination has started.
2757
3167
  *
@@ -2861,6 +3271,34 @@ var DestinationHealth = class {
2861
3271
  DestinationHealth = __decorateClass([
2862
3272
  Injectable()
2863
3273
  ], DestinationHealth);
3274
+
3275
+ // src/server/utils/with-timeout.util.ts
3276
+ var HookTimeoutError = class extends Error {
3277
+ constructor(timeoutMs) {
3278
+ super(`did not settle within ${String(timeoutMs)} ms`);
3279
+ this.timeoutMs = timeoutMs;
3280
+ this.name = "HookTimeoutError";
3281
+ }
3282
+ };
3283
+ function withTimeout(work, ms) {
3284
+ return new Promise((resolve, reject2) => {
3285
+ const timer = setTimeout(() => {
3286
+ reject2(new HookTimeoutError(ms));
3287
+ }, ms);
3288
+ const settle = (done) => (...args) => {
3289
+ clearTimeout(timer);
3290
+ done(...args);
3291
+ };
3292
+ try {
3293
+ Promise.resolve(work()).then(settle(resolve), settle(reject2));
3294
+ } catch (cause) {
3295
+ settle(reject2)(cause);
3296
+ }
3297
+ });
3298
+ }
3299
+
3300
+ // src/server/services/destination-registry.service.ts
3301
+ var DRAIN_POLL_MS = 5;
2864
3302
  var DestinationRegistry = class {
2865
3303
  /**
2866
3304
  * @param registered - Every destination declared under
@@ -2905,7 +3343,7 @@ var DestinationRegistry = class {
2905
3343
  async onModuleInit() {
2906
3344
  for (const destination of this.registered) {
2907
3345
  try {
2908
- await destination.onInit?.();
3346
+ await withTimeout(() => destination.onInit?.(), this.options.destinationHookTimeoutMs);
2909
3347
  this.active.push(destination);
2910
3348
  this.health.markHealthy(destination, this.effectiveLevelOf(destination));
2911
3349
  } catch (cause) {
@@ -2937,12 +3375,15 @@ var DestinationRegistry = class {
2937
3375
  async notifyRegistryReady() {
2938
3376
  for (const destination of this.registered) {
2939
3377
  try {
2940
- await destination.onRegistryReady?.({
2941
- heldEntriesDeliveredElsewhere: this.health.deliveredByHealthySink(
2942
- destination,
2943
- this.effectiveLevelOf(destination)
2944
- )
2945
- });
3378
+ await withTimeout(
3379
+ () => destination.onRegistryReady?.({
3380
+ heldEntriesDeliveredElsewhere: this.health.deliveredByHealthySink(
3381
+ destination,
3382
+ this.effectiveLevelOf(destination)
3383
+ )
3384
+ }),
3385
+ this.options.destinationHookTimeoutMs
3386
+ );
2946
3387
  } catch (cause) {
2947
3388
  this.reportHookFailure(destination, cause);
2948
3389
  }
@@ -3060,6 +3501,9 @@ var DestinationRegistry = class {
3060
3501
  * point in the shutdown sequence.
3061
3502
  */
3062
3503
  async onApplicationShutdown() {
3504
+ const startedAt = performance.now();
3505
+ const { timeoutMs, drainTimeoutMs } = this.options.shutdown;
3506
+ const deadline = startedAt + timeoutMs;
3063
3507
  this.logger.info(
3064
3508
  RESERVED_LOG_KEYS.LOGGER_SHUTDOWN_OK,
3065
3509
  "BymaxLoggerModule shutting down",
@@ -3069,13 +3513,82 @@ var DestinationRegistry = class {
3069
3513
  await new Promise((resolve) => {
3070
3514
  setImmediate(resolve);
3071
3515
  });
3516
+ await this.drain(Math.min(deadline, startedAt + drainTimeoutMs));
3517
+ const skipped = [];
3072
3518
  for (const destination of [...this.active].reverse()) {
3519
+ const remaining = deadline - performance.now();
3520
+ if (remaining <= 0) {
3521
+ skipped.push(toSingleLineMessage(safeDestinationName(destination)));
3522
+ continue;
3523
+ }
3073
3524
  try {
3074
- await destination.onShutdown?.();
3525
+ await withTimeout(() => destination.onShutdown?.(), remaining);
3075
3526
  } catch (cause) {
3076
3527
  this.reportShutdownFailure(destination, cause);
3077
3528
  }
3078
3529
  }
3530
+ this.reportDropTotals();
3531
+ if (skipped.length > 0) {
3532
+ writeStderrSafely(
3533
+ `[DestinationRegistry] Shutdown budget of ${String(timeoutMs)} ms spent; onShutdown not called for: ${skipped.map((name) => `"${name}"`).join(", ")}
3534
+ `
3535
+ );
3536
+ }
3537
+ }
3538
+ /**
3539
+ * Say, once, how many entries each destination had dropped for want of queue room, when any did.
3540
+ * It carries the name and the count and no entry content.
3541
+ */
3542
+ reportDropTotals() {
3543
+ for (const destination of this.registered) {
3544
+ const name = toSingleLineMessage(safeDestinationName(destination));
3545
+ const total = this.health.droppedTotal(destination);
3546
+ if (total > 0) {
3547
+ writeStderrSafely(
3548
+ `[DestinationRegistry] Destination "${name}" dropped ${String(total)} entries in total because its queue was full
3549
+ `
3550
+ );
3551
+ }
3552
+ const failed = this.health.failedWriteTotal(destination);
3553
+ if (failed > 1) {
3554
+ writeStderrSafely(
3555
+ `[DestinationRegistry] Destination "${name}" failed ${String(failed)} writes in total; each dropped its entry
3556
+ `
3557
+ );
3558
+ }
3559
+ }
3560
+ }
3561
+ /**
3562
+ * Wait until no active destination holds a queued entry, or the drain deadline passes.
3563
+ *
3564
+ * A destination reads its entries from a `Writable` that buffers what Pino has written, and it
3565
+ * takes them one at a time. `onShutdown` is its signal to flush and close, so a write that begins
3566
+ * after it is a write on a closed resource. The wait does not end the streams, because Pino may
3567
+ * still log while the application shuts down, and an entry written after the end of a stream is an
3568
+ * error. An entry written during the wait extends it, up to the deadline. When the deadline ends it,
3569
+ * one line names the destinations and their queued sizes; it carries no entry content.
3570
+ *
3571
+ * @param drainDeadline - The time, in `performance.now()` milliseconds, the wait ends at.
3572
+ */
3573
+ async drain(drainDeadline) {
3574
+ for (; ; ) {
3575
+ const queued = this.active.filter((destination) => this.health.queuedSize(destination) > 0);
3576
+ if (queued.length === 0) return;
3577
+ const remaining = drainDeadline - performance.now();
3578
+ if (remaining <= 0) {
3579
+ const named = queued.map(
3580
+ (destination) => `"${toSingleLineMessage(safeDestinationName(destination))}" (${String(this.health.queuedSize(destination))})`
3581
+ );
3582
+ writeStderrSafely(
3583
+ `[DestinationRegistry] Shutdown drain ended with entries still queued, by size: ${named.join(", ")}
3584
+ `
3585
+ );
3586
+ return;
3587
+ }
3588
+ await new Promise((resolve) => {
3589
+ setTimeout(resolve, Math.min(DRAIN_POLL_MS, remaining));
3590
+ });
3591
+ }
3079
3592
  }
3080
3593
  /**
3081
3594
  * Report a failing `onShutdown` on stderr without letting the report itself
@@ -3579,6 +4092,7 @@ var HttpAccessLogMiddleware = class {
3579
4092
  this.logContext = logContext;
3580
4093
  this.isEnabled = options.http.isEnabled;
3581
4094
  this.excludePaths = options.http.excludePaths;
4095
+ this.secretPathSegments = options.http.secretPathSegments;
3582
4096
  }
3583
4097
  /**
3584
4098
  * Emit START, arm the terminal entry on `'close'`, and continue the chain.
@@ -3604,14 +4118,14 @@ var HttpAccessLogMiddleware = class {
3604
4118
  }
3605
4119
  markRecorderActive(req);
3606
4120
  const method = req.method;
3607
- const url = normalizeUrl(target);
4121
+ const url = normalizeUrl(target, this.secretPathSegments);
3608
4122
  const start = Date.now();
3609
4123
  this.logger.info(RESERVED_LOG_KEYS.HTTP_REQUEST_START, `${method} ${url}`, readUserId(req), {
3610
4124
  method,
3611
4125
  url,
3612
4126
  // Query string stripped: it may carry secrets (reset tokens, OAuth codes)
3613
4127
  // that no key-name redaction can scrub out of a string VALUE.
3614
- fullUrl: path2,
4128
+ fullUrl: scrubSecretSegments(path2, this.secretPathSegments),
3615
4129
  // Conventional for an access log and personal data under GDPR/LGPD. Its
3616
4130
  // fidelity is the app's to establish: behind a proxy it is only the real
3617
4131
  // client when the app configures `trust proxy`, and a value the app has not
@@ -3676,7 +4190,12 @@ var HttpAccessLogMiddleware = class {
3676
4190
  recorded === void 0 ? meta : {
3677
4191
  ...meta,
3678
4192
  errorMessage: cutIfText(
3679
- withoutRequestQueryIfText(recorded.error.message, req.originalUrl, req.url)
4193
+ withoutRequestSecretsIfText(
4194
+ recorded.error.message,
4195
+ this.secretPathSegments,
4196
+ req.originalUrl,
4197
+ req.url
4198
+ )
3680
4199
  )
3681
4200
  }
3682
4201
  );
@@ -3764,6 +4283,10 @@ var PinoUnexpectedErrorSink = class {
3764
4283
  if (report.correlationId !== void 0) {
3765
4284
  metadata["correlationId"] = report.correlationId;
3766
4285
  }
4286
+ if (isCount(report.repeated)) {
4287
+ metadata["repeated"] = report.repeated;
4288
+ }
4289
+ Object.assign(metadata, exceptionFields(report.error));
3767
4290
  this.logger.errorStructured(
3768
4291
  RESERVED_LOG_KEYS.HTTP_UNEXPECTED_ERROR,
3769
4292
  toLoggableError(report.error),
@@ -3787,6 +4310,34 @@ PinoUnexpectedErrorSink = __decorateClass([
3787
4310
  function toLoggableError(value) {
3788
4311
  return isErrorLike(value) ? value : sanitizeError(value);
3789
4312
  }
4313
+ var MAX_CODE_LENGTH = 128;
4314
+ function isCount(value) {
4315
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
4316
+ }
4317
+ function isRecord2(value) {
4318
+ return typeof value === "object" && value !== null;
4319
+ }
4320
+ function exceptionFields(error) {
4321
+ try {
4322
+ if (!isRecord2(error) || typeof error["getResponse"] !== "function") return {};
4323
+ const response = error["getResponse"]();
4324
+ if (!isRecord2(response)) return {};
4325
+ const nested = response["error"];
4326
+ const carrier = isRecord2(nested) && typeof nested["code"] === "string" ? nested : response;
4327
+ const fields = {};
4328
+ const code = carrier["code"];
4329
+ if (typeof code === "string") {
4330
+ fields["errorCode"] = code.slice(0, MAX_CODE_LENGTH);
4331
+ }
4332
+ const details = carrier["details"];
4333
+ if (isRecord2(details)) {
4334
+ fields["errorDetails"] = details;
4335
+ }
4336
+ return fields;
4337
+ } catch {
4338
+ return {};
4339
+ }
4340
+ }
3790
4341
  var INJECT_LOGGER_CONTEXT_METADATA_KEY = "bymax_logger:context";
3791
4342
  function InjectLogger(context) {
3792
4343
  return (target, propertyKey, parameterIndex) => {