@bymax-one/nest-logger 1.4.16 → 1.4.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +124 -1
- package/README.md +76 -41
- package/dist/server/index.cjs +550 -74
- package/dist/server/index.d.cts +110 -6
- package/dist/server/index.d.ts +110 -6
- package/dist/server/index.mjs +551 -75
- package/package.json +2 -2
package/dist/server/index.mjs
CHANGED
|
@@ -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
|
-
|
|
287
|
-
|
|
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,86 @@ 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
|
-
|
|
1060
|
-
|
|
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)) || EMAIL_SECRET_REGEX.test(decoded) || matchesExcludePath(extra, decoded);
|
|
1158
|
+
}
|
|
1159
|
+
function withoutExtension(segment) {
|
|
1160
|
+
const dot = segment.lastIndexOf(".");
|
|
1161
|
+
const dotAfterStart = dot > 0;
|
|
1162
|
+
return dotAfterStart && segment.length - dot <= 9 ? segment.slice(0, dot) : segment;
|
|
1163
|
+
}
|
|
1164
|
+
function looksLikeToken(value) {
|
|
1165
|
+
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);
|
|
1166
|
+
}
|
|
1167
|
+
function secretPathSegments(url, extra = []) {
|
|
1168
|
+
const found = /* @__PURE__ */ new Set();
|
|
1169
|
+
for (const segment of stripQueryString(url).split("/")) {
|
|
1170
|
+
if (isSecretSegment(segment, extra)) found.add(segment);
|
|
1171
|
+
}
|
|
1172
|
+
return [...found];
|
|
1173
|
+
}
|
|
1174
|
+
function scrubSecretSegments(path2, extra = []) {
|
|
1175
|
+
return path2.split("/").map((segment) => isSecretSegment(segment, extra) ? SECRET_PLACEHOLDER : segment).join("/");
|
|
1176
|
+
}
|
|
1177
|
+
function normalizeUrl(url, extra = []) {
|
|
1178
|
+
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
1179
|
}
|
|
1062
1180
|
function stripQueryString(url) {
|
|
1063
1181
|
const queryStart = url.indexOf("?");
|
|
1064
1182
|
return queryStart === -1 ? url : url.slice(0, queryStart);
|
|
1065
1183
|
}
|
|
1066
|
-
function
|
|
1184
|
+
function withoutRequestSecrets(text, extra, ...urls) {
|
|
1067
1185
|
let result = text;
|
|
1186
|
+
const segments = /* @__PURE__ */ new Set();
|
|
1068
1187
|
for (const url of urls) {
|
|
1069
1188
|
if (url === void 0) continue;
|
|
1070
1189
|
const queryStart = url.indexOf("?");
|
|
1071
1190
|
if (queryStart !== -1 && url.length - queryStart > 1) {
|
|
1072
1191
|
result = result.split(url.slice(queryStart)).join("");
|
|
1073
1192
|
}
|
|
1193
|
+
for (const segment of secretPathSegments(url, extra)) segments.add(segment);
|
|
1194
|
+
}
|
|
1195
|
+
if (segments.size > 0) {
|
|
1196
|
+
const alternation = [...segments].sort((left, right) => right.length - left.length).map((segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
|
|
1197
|
+
result = result.replace(new RegExp(alternation, "g"), SECRET_PLACEHOLDER);
|
|
1074
1198
|
}
|
|
1075
1199
|
return result;
|
|
1076
1200
|
}
|
|
1077
|
-
function
|
|
1078
|
-
return typeof value === "string" ?
|
|
1201
|
+
function withoutRequestSecretsIfText(value, extra, ...urls) {
|
|
1202
|
+
return typeof value === "string" ? withoutRequestSecrets(value, extra, ...urls) : value;
|
|
1079
1203
|
}
|
|
1080
1204
|
|
|
1081
1205
|
// src/server/filters/http-exception.filter.ts
|
|
@@ -1088,9 +1212,12 @@ var HttpExceptionFilter = class {
|
|
|
1088
1212
|
* @param logger - The structured logger exception entries are written to.
|
|
1089
1213
|
* Injected by token explicitly: the package is bundled without
|
|
1090
1214
|
* `emitDecoratorMetadata`, so implicit class-type injection would not resolve.
|
|
1215
|
+
* @param options - Resolved module options, read for `http.secretPathSegments`. Optional, so a
|
|
1216
|
+
* filter built by hand with the logger alone keeps the built-in credential patterns.
|
|
1091
1217
|
*/
|
|
1092
|
-
constructor(logger) {
|
|
1218
|
+
constructor(logger, options) {
|
|
1093
1219
|
this.logger = logger;
|
|
1220
|
+
this.secretPathSegments = options?.http.secretPathSegments ?? [];
|
|
1094
1221
|
}
|
|
1095
1222
|
/**
|
|
1096
1223
|
* Log the exception at the status-appropriate level and write the JSON
|
|
@@ -1104,7 +1231,7 @@ var HttpExceptionFilter = class {
|
|
|
1104
1231
|
const res = ctx.getResponse();
|
|
1105
1232
|
const req = ctx.getRequest();
|
|
1106
1233
|
const userId = req.user?.sub ?? req.user?.id;
|
|
1107
|
-
const url = stripQueryString(req.url);
|
|
1234
|
+
const url = scrubSecretSegments(stripQueryString(req.url), this.secretPathSegments);
|
|
1108
1235
|
if (exception instanceof HttpException) {
|
|
1109
1236
|
const status = exception.getStatus();
|
|
1110
1237
|
const parserError = readRecordedParserError(req);
|
|
@@ -1124,7 +1251,12 @@ var HttpExceptionFilter = class {
|
|
|
1124
1251
|
} else {
|
|
1125
1252
|
this.logger.warnStructured(
|
|
1126
1253
|
RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
|
|
1127
|
-
parserError?.logMessage ??
|
|
1254
|
+
parserError?.logMessage ?? withoutRequestSecrets(
|
|
1255
|
+
exception.message,
|
|
1256
|
+
this.secretPathSegments,
|
|
1257
|
+
req.originalUrl,
|
|
1258
|
+
req.url
|
|
1259
|
+
),
|
|
1128
1260
|
userId,
|
|
1129
1261
|
metadata
|
|
1130
1262
|
);
|
|
@@ -1154,7 +1286,7 @@ var HttpExceptionFilter = class {
|
|
|
1154
1286
|
const { method, url, userId } = request;
|
|
1155
1287
|
this.logger.warnStructured(
|
|
1156
1288
|
RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
|
|
1157
|
-
|
|
1289
|
+
withoutRequestSecrets(clientError.logMessage, this.secretPathSegments, ...rawUrls),
|
|
1158
1290
|
userId,
|
|
1159
1291
|
{
|
|
1160
1292
|
method,
|
|
@@ -1189,20 +1321,10 @@ var HttpExceptionFilter = class {
|
|
|
1189
1321
|
};
|
|
1190
1322
|
HttpExceptionFilter = __decorateClass([
|
|
1191
1323
|
Catch(),
|
|
1192
|
-
__decorateParam(0, Inject(PinoLoggerService))
|
|
1324
|
+
__decorateParam(0, Inject(PinoLoggerService)),
|
|
1325
|
+
__decorateParam(1, Optional()),
|
|
1326
|
+
__decorateParam(1, Inject(LOGGER_OPTIONS_TOKEN))
|
|
1193
1327
|
], 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
1328
|
var HTTP_SUCCESS_MIN = 200;
|
|
1207
1329
|
var HttpLoggingInterceptor = class {
|
|
1208
1330
|
/**
|
|
@@ -1215,6 +1337,7 @@ var HttpLoggingInterceptor = class {
|
|
|
1215
1337
|
constructor(logger, options) {
|
|
1216
1338
|
this.logger = logger;
|
|
1217
1339
|
this.excludePaths = options.http.excludePaths;
|
|
1340
|
+
this.secretPathSegments = options.http.secretPathSegments;
|
|
1218
1341
|
}
|
|
1219
1342
|
/**
|
|
1220
1343
|
* Whether a request path bypasses HTTP logging (matches any `excludePaths`).
|
|
@@ -1246,7 +1369,7 @@ var HttpLoggingInterceptor = class {
|
|
|
1246
1369
|
}
|
|
1247
1370
|
const userAgent = readUserAgent(req);
|
|
1248
1371
|
const userId = readUserId(req);
|
|
1249
|
-
const normalizedUrl = normalizeUrl(url);
|
|
1372
|
+
const normalizedUrl = normalizeUrl(url, this.secretPathSegments);
|
|
1250
1373
|
const start = Date.now();
|
|
1251
1374
|
this.logger.info(RESERVED_LOG_KEYS.HTTP_REQUEST_START, `${method} ${normalizedUrl}`, userId, {
|
|
1252
1375
|
method,
|
|
@@ -1254,7 +1377,7 @@ var HttpLoggingInterceptor = class {
|
|
|
1254
1377
|
// Query string stripped: it may carry secrets (reset tokens, OAuth codes)
|
|
1255
1378
|
// that Pino's path-based redaction cannot scrub from a string value. The
|
|
1256
1379
|
// raw (un-normalized) path is kept for per-request debugging.
|
|
1257
|
-
fullUrl: stripQueryString(url),
|
|
1380
|
+
fullUrl: scrubSecretSegments(stripQueryString(url), this.secretPathSegments),
|
|
1258
1381
|
ip,
|
|
1259
1382
|
userAgent
|
|
1260
1383
|
});
|
|
@@ -1352,7 +1475,9 @@ var HttpLoggingInterceptor = class {
|
|
|
1352
1475
|
url,
|
|
1353
1476
|
statusCode,
|
|
1354
1477
|
duration,
|
|
1355
|
-
errorMessage: cutIfText(
|
|
1478
|
+
errorMessage: cutIfText(
|
|
1479
|
+
withoutRequestSecretsIfText(err.message, this.secretPathSegments, ...rawUrls)
|
|
1480
|
+
)
|
|
1356
1481
|
}
|
|
1357
1482
|
);
|
|
1358
1483
|
}
|
|
@@ -1390,7 +1515,9 @@ var HttpLoggingInterceptor = class {
|
|
|
1390
1515
|
url,
|
|
1391
1516
|
statusCode: clientError.status,
|
|
1392
1517
|
duration,
|
|
1393
|
-
errorMessage: cutIfText(
|
|
1518
|
+
errorMessage: cutIfText(
|
|
1519
|
+
withoutRequestSecretsIfText(clientError.logMessage, this.secretPathSegments, ...rawUrls)
|
|
1520
|
+
),
|
|
1394
1521
|
bodyParserType: clientError.bodyParserType
|
|
1395
1522
|
}
|
|
1396
1523
|
);
|
|
@@ -1812,7 +1939,47 @@ var REDACT_COMMON_FIELDS = [
|
|
|
1812
1939
|
"cookie",
|
|
1813
1940
|
"set-cookie",
|
|
1814
1941
|
"x-api-key",
|
|
1815
|
-
"x-auth-token"
|
|
1942
|
+
"x-auth-token",
|
|
1943
|
+
// The spellings systems actually write. The default `'names'` matching is case-insensitive, so
|
|
1944
|
+
// `accessToken` already covers `ACCESSTOKEN`, but not `access_token` (the OAuth wire name) or
|
|
1945
|
+
// `access-token`: those are different names. The legacy `'paths'` engine is case-sensitive, so
|
|
1946
|
+
// the all-lowercase `apikey` and `sessiontoken` are listed too.
|
|
1947
|
+
// OAuth and API credentials, snake case.
|
|
1948
|
+
"access_token",
|
|
1949
|
+
"refresh_token",
|
|
1950
|
+
"id_token",
|
|
1951
|
+
"api_key",
|
|
1952
|
+
"apikey",
|
|
1953
|
+
"api_secret",
|
|
1954
|
+
"client_secret",
|
|
1955
|
+
"signing_secret",
|
|
1956
|
+
"private_key",
|
|
1957
|
+
"secret_key",
|
|
1958
|
+
"secretKey",
|
|
1959
|
+
// The same, kebab case.
|
|
1960
|
+
"access-token",
|
|
1961
|
+
"refresh-token",
|
|
1962
|
+
"id-token",
|
|
1963
|
+
"api-key",
|
|
1964
|
+
"client-secret",
|
|
1965
|
+
"private-key",
|
|
1966
|
+
// Session and CSRF credentials, in the spellings of a cookie, a header and a body field. A bare
|
|
1967
|
+
// `sessionId` is deliberately absent: many applications carry it as a correlation key, and the
|
|
1968
|
+
// only way to get such a field back would be to turn every default off.
|
|
1969
|
+
"proxy-authorization",
|
|
1970
|
+
"session_token",
|
|
1971
|
+
"sessionToken",
|
|
1972
|
+
"sessiontoken",
|
|
1973
|
+
"session-token",
|
|
1974
|
+
"x-csrf-token",
|
|
1975
|
+
"x-xsrf-token",
|
|
1976
|
+
"csrf_token",
|
|
1977
|
+
"csrfToken",
|
|
1978
|
+
"csrf-token",
|
|
1979
|
+
// The password family, snake case.
|
|
1980
|
+
"password_hash",
|
|
1981
|
+
"new_password",
|
|
1982
|
+
"old_password"
|
|
1816
1983
|
];
|
|
1817
1984
|
var REDACT_ABSOLUTE_PATHS = [
|
|
1818
1985
|
"req.headers.authorization",
|
|
@@ -1990,14 +2157,90 @@ function reportWriteFailure(destination, cause) {
|
|
|
1990
2157
|
function rescueToStdout(payload) {
|
|
1991
2158
|
writeStdoutSafely(payload);
|
|
1992
2159
|
}
|
|
1993
|
-
function
|
|
1994
|
-
|
|
2160
|
+
function ownQueuedBytes(destination) {
|
|
2161
|
+
try {
|
|
2162
|
+
const bytes = destination.queuedBytes?.() ?? 0;
|
|
2163
|
+
const positive = Number.isFinite(bytes) && bytes > 0;
|
|
2164
|
+
return positive ? bytes : 0;
|
|
2165
|
+
} catch {
|
|
2166
|
+
return 0;
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
var BoundedWritable = class extends Writable {
|
|
2170
|
+
constructor(destination, health, maxBytes, queue, options) {
|
|
2171
|
+
super(options);
|
|
2172
|
+
this.destination = destination;
|
|
2173
|
+
this.health = health;
|
|
2174
|
+
this.maxBytes = maxBytes;
|
|
2175
|
+
this.queue = queue;
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* A destroyed stream holds nothing: Writable fails the chunks still buffered without calling the
|
|
2179
|
+
* write handler, so nothing else would release their bytes.
|
|
2180
|
+
*/
|
|
2181
|
+
_destroy(error, callback) {
|
|
2182
|
+
this.queue.bytes = 0;
|
|
2183
|
+
super._destroy(error, callback);
|
|
2184
|
+
}
|
|
2185
|
+
/** The bytes of NDJSON waiting for the destination, the write in flight included. */
|
|
2186
|
+
get queuedBytes() {
|
|
2187
|
+
return this.queue.bytes;
|
|
2188
|
+
}
|
|
2189
|
+
write(chunk, encodingOrCallback, callback) {
|
|
2190
|
+
if (this.writableEnded || this.destroyed) {
|
|
2191
|
+
return this.forward(chunk, encodingOrCallback, callback);
|
|
2192
|
+
}
|
|
2193
|
+
const bytes = Buffer.byteLength(chunk);
|
|
2194
|
+
const held = this.heldBytes();
|
|
2195
|
+
if (this.maxBytes > 0 && held > 0 && held + bytes > this.maxBytes) {
|
|
2196
|
+
this.dropped();
|
|
2197
|
+
const done = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
|
|
2198
|
+
done?.();
|
|
2199
|
+
return true;
|
|
2200
|
+
}
|
|
2201
|
+
this.queue.bytes += bytes;
|
|
2202
|
+
return this.forward(chunk, encodingOrCallback, callback);
|
|
2203
|
+
}
|
|
2204
|
+
/** `Writable.write` for either of its two signatures. */
|
|
2205
|
+
forward(chunk, encodingOrCallback, callback) {
|
|
2206
|
+
return typeof encodingOrCallback === "function" ? super.write(chunk, encodingOrCallback) : super.write(chunk, encodingOrCallback ?? "utf8", callback);
|
|
2207
|
+
}
|
|
2208
|
+
/**
|
|
2209
|
+
* What the entry would queue behind. A live destination holds its module queue and what it reports
|
|
2210
|
+
* in a buffer of its own. A failed destination receives nothing, so what it reports does not count,
|
|
2211
|
+
* and the one elected to rescue entries writes them to stdout, whose queue is what grows.
|
|
2212
|
+
*/
|
|
2213
|
+
heldBytes() {
|
|
2214
|
+
if (!this.health.isFailed(this.destination)) {
|
|
2215
|
+
return this.queue.bytes + ownQueuedBytes(this.destination);
|
|
2216
|
+
}
|
|
2217
|
+
return this.health.shouldRescue(this.destination) ? this.queue.bytes + process.stdout.writableLength : 0;
|
|
2218
|
+
}
|
|
2219
|
+
/** Count the drop, and write the report when one is due. */
|
|
2220
|
+
dropped() {
|
|
2221
|
+
const due = this.health.recordDrop(this.destination, performance.now());
|
|
2222
|
+
if (due === void 0) return;
|
|
2223
|
+
const name = toSingleLineMessage(safeDestinationName(this.destination));
|
|
2224
|
+
writeStderrSafely(
|
|
2225
|
+
`[DestinationRegistry] Destination "${name}" queue full: ${String(due)} entries dropped since the last report (limit ${String(this.maxBytes)} bytes)
|
|
2226
|
+
`
|
|
2227
|
+
);
|
|
2228
|
+
}
|
|
2229
|
+
};
|
|
2230
|
+
function destinationToStream(destination, health, maxQueueBytes = 0) {
|
|
2231
|
+
const queue = { bytes: 0 };
|
|
2232
|
+
const stream = new BoundedWritable(destination, health, maxQueueBytes, queue, {
|
|
1995
2233
|
// Keep string chunks as strings (Node's default re-encodes them to Buffers
|
|
1996
2234
|
// before `_write`): the common Pino path emits NDJSON strings, so this skips
|
|
1997
2235
|
// a string→Buffer→string round-trip on the hot logging path.
|
|
1998
2236
|
// 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
2237
|
decodeStrings: false,
|
|
2000
|
-
write(chunk, _encoding,
|
|
2238
|
+
write(chunk, _encoding, settled) {
|
|
2239
|
+
const bytes = Buffer.byteLength(chunk);
|
|
2240
|
+
const callback = (error) => {
|
|
2241
|
+
queue.bytes = Math.max(0, queue.bytes - bytes);
|
|
2242
|
+
settled(error);
|
|
2243
|
+
};
|
|
2001
2244
|
const onFailure = (cause) => {
|
|
2002
2245
|
health.markWriteFailed(destination);
|
|
2003
2246
|
reportWriteFailure(destination, cause);
|
|
@@ -2033,6 +2276,15 @@ function destinationToStream(destination, health) {
|
|
|
2033
2276
|
}
|
|
2034
2277
|
}
|
|
2035
2278
|
});
|
|
2279
|
+
return stream;
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
// src/server/utils/censor-raw-headers.util.ts
|
|
2283
|
+
function censorRawHeaders(raw, sensitive, censor) {
|
|
2284
|
+
return raw.map((entry, index) => {
|
|
2285
|
+
const name = index % 2 === 1 ? raw[index - 1] : void 0;
|
|
2286
|
+
return typeof name === "string" && sensitive.has(name.toLowerCase()) ? censor : entry;
|
|
2287
|
+
});
|
|
2036
2288
|
}
|
|
2037
2289
|
|
|
2038
2290
|
// src/server/utils/redact-error-clone.util.ts
|
|
@@ -2152,6 +2404,10 @@ function addErrorParts(copy, error, ownKeys, host, depth2) {
|
|
|
2152
2404
|
}
|
|
2153
2405
|
|
|
2154
2406
|
// src/server/utils/redact-by-name.util.ts
|
|
2407
|
+
var RAW_HEADER_KEYS = /* @__PURE__ */ new Set(["rawheaders", "rawtrailers"]);
|
|
2408
|
+
function censorHeaderArray(key, walked, rules) {
|
|
2409
|
+
return RAW_HEADER_KEYS.has(key.toLowerCase()) && Array.isArray(walked) ? censorRawHeaders(walked, rules.headerNames, rules.censor) : walked;
|
|
2410
|
+
}
|
|
2155
2411
|
var REDACT_MAX_TRAVERSAL_DEPTH = 100;
|
|
2156
2412
|
var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
|
|
2157
2413
|
var REDACT_MAX_VISITS = 2e5;
|
|
@@ -2280,13 +2536,17 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
|
|
|
2280
2536
|
defineOwn(
|
|
2281
2537
|
copy,
|
|
2282
2538
|
key,
|
|
2283
|
-
rules.sensitive.has(key.toLowerCase()) ? rules.censor :
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2539
|
+
rules.sensitive.has(key.toLowerCase()) ? rules.censor : censorHeaderArray(
|
|
2540
|
+
key,
|
|
2541
|
+
walk(
|
|
2542
|
+
scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
|
|
2543
|
+
rules,
|
|
2544
|
+
depth2 + 1,
|
|
2545
|
+
ancestors,
|
|
2546
|
+
true,
|
|
2547
|
+
inSerialized || !honorToJson && rules.serializedKeys.has(key)
|
|
2548
|
+
),
|
|
2549
|
+
rules
|
|
2290
2550
|
)
|
|
2291
2551
|
);
|
|
2292
2552
|
}
|
|
@@ -2316,9 +2576,10 @@ function errorPartsHost(rules, ancestors, inSerialized) {
|
|
|
2316
2576
|
hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
|
|
2317
2577
|
};
|
|
2318
2578
|
}
|
|
2319
|
-
function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames) {
|
|
2579
|
+
function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames, headerNames) {
|
|
2320
2580
|
const rules = {
|
|
2321
2581
|
sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
|
|
2582
|
+
headerNames: new Set(Array.from(headerNames ?? fieldNames, (name) => name.toLowerCase())),
|
|
2322
2583
|
censor,
|
|
2323
2584
|
serializedKeys: new Set(serializedKeys),
|
|
2324
2585
|
errorsAsData: serializedKeys !== void 0,
|
|
@@ -2465,6 +2726,39 @@ function extraServiceFields(service) {
|
|
|
2465
2726
|
return extras;
|
|
2466
2727
|
}
|
|
2467
2728
|
|
|
2729
|
+
// src/server/utils/serialize-request.util.ts
|
|
2730
|
+
function isObject2(value) {
|
|
2731
|
+
return typeof value === "object" && value !== null;
|
|
2732
|
+
}
|
|
2733
|
+
function isRequest(value) {
|
|
2734
|
+
if (!isObject2(value)) return false;
|
|
2735
|
+
const { rawHeaders, method, socket } = value;
|
|
2736
|
+
return Array.isArray(rawHeaders) || typeof method === "string" && isObject2(socket);
|
|
2737
|
+
}
|
|
2738
|
+
function copyHeaders(headers) {
|
|
2739
|
+
return isObject2(headers) ? { ...headers } : {};
|
|
2740
|
+
}
|
|
2741
|
+
function serializeRequestValue(input, secretSegments = []) {
|
|
2742
|
+
try {
|
|
2743
|
+
if (!isRequest(input)) return input;
|
|
2744
|
+
const url = input.originalUrl ?? input.url;
|
|
2745
|
+
const socket = input.socket;
|
|
2746
|
+
return {
|
|
2747
|
+
method: input.method,
|
|
2748
|
+
url: typeof url === "string" ? scrubSecretSegments(stripQueryString(url), secretSegments) : url,
|
|
2749
|
+
headers: copyHeaders(input.headers),
|
|
2750
|
+
remoteAddress: socket?.remoteAddress
|
|
2751
|
+
};
|
|
2752
|
+
} catch {
|
|
2753
|
+
return { _unserializable: "request" };
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
function withSerializedRequest(record, secretSegments = []) {
|
|
2757
|
+
const request = record["req"];
|
|
2758
|
+
const serialized = serializeRequestValue(request, secretSegments);
|
|
2759
|
+
return serialized === request ? record : { ...record, req: serialized };
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2468
2762
|
// src/server/utils/truncate-large-entries.ts
|
|
2469
2763
|
var PREVIEW_LENGTH = 200;
|
|
2470
2764
|
function createSizeBoundedSerializer(baseSerializer, maxBytes) {
|
|
@@ -2578,10 +2872,11 @@ function namesInsideErrors(options) {
|
|
|
2578
2872
|
return options.shouldDisableDefaultRedact ? void 0 : REDACT_COMMON_FIELDS;
|
|
2579
2873
|
}
|
|
2580
2874
|
function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
|
|
2581
|
-
const
|
|
2875
|
+
const allNames = [
|
|
2582
2876
|
...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
|
|
2583
2877
|
...options.redactPaths.flatMap((path2) => leafNameOf(path2) ?? [])
|
|
2584
|
-
]
|
|
2878
|
+
];
|
|
2879
|
+
const names = coversNames ? allNames : [];
|
|
2585
2880
|
const ownFields = ownFieldPolicyOf(options);
|
|
2586
2881
|
const walks = names.length > 0 || ownFields.safe;
|
|
2587
2882
|
if (!walks && resolveRedactOption(options) === void 0) {
|
|
@@ -2593,8 +2888,17 @@ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = tr
|
|
|
2593
2888
|
["err", ...Object.keys(options.serializers)],
|
|
2594
2889
|
void 0,
|
|
2595
2890
|
ownFields,
|
|
2596
|
-
coversNames ? void 0 : namesInsideErrors(options)
|
|
2597
|
-
|
|
2891
|
+
coversNames ? void 0 : namesInsideErrors(options),
|
|
2892
|
+
allNames
|
|
2893
|
+
) : createNameRedactor(
|
|
2894
|
+
names,
|
|
2895
|
+
options.redactCensor,
|
|
2896
|
+
void 0,
|
|
2897
|
+
void 0,
|
|
2898
|
+
ownFields,
|
|
2899
|
+
void 0,
|
|
2900
|
+
allNames
|
|
2901
|
+
);
|
|
2598
2902
|
}
|
|
2599
2903
|
function resolveRedactOption(options) {
|
|
2600
2904
|
const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
|
|
@@ -2609,6 +2913,7 @@ function buildPinoInstance(options, logContext, destinations, health) {
|
|
|
2609
2913
|
const redactSerialized = buildNameRedactor(options);
|
|
2610
2914
|
const ownFields = ownFieldPolicyOf(options);
|
|
2611
2915
|
const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
|
|
2916
|
+
const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
|
|
2612
2917
|
const serializers = {
|
|
2613
2918
|
err: bound((error) => serializeErrorValue(error, ownFields)),
|
|
2614
2919
|
...Object.fromEntries(
|
|
@@ -2656,7 +2961,10 @@ function buildPinoInstance(options, logContext, destinations, health) {
|
|
|
2656
2961
|
// sensitive, which `pino-factory.spec.ts` pins.
|
|
2657
2962
|
log: (record) => withSemconvException(
|
|
2658
2963
|
withEventName(
|
|
2659
|
-
redactRecord(
|
|
2964
|
+
redactRecord(
|
|
2965
|
+
hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
|
|
2966
|
+
true
|
|
2967
|
+
),
|
|
2660
2968
|
options.eventNameField
|
|
2661
2969
|
),
|
|
2662
2970
|
options.errorFormat
|
|
@@ -2681,16 +2989,21 @@ function buildPinoInstance(options, logContext, destinations, health) {
|
|
|
2681
2989
|
}
|
|
2682
2990
|
}
|
|
2683
2991
|
};
|
|
2684
|
-
const streams = destinations.map((destination) =>
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2992
|
+
const streams = destinations.map((destination) => {
|
|
2993
|
+
const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
|
|
2994
|
+
health.registerStream(destination, stream);
|
|
2995
|
+
return {
|
|
2996
|
+
// Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
|
|
2997
|
+
// consumer implementing `minLevel` as a throwing getter would fail the factory
|
|
2998
|
+
// and the application would never start — earlier than any fail-soft path can
|
|
2999
|
+
// contain. Unreadable and absent give the same answer: the module level.
|
|
3000
|
+
level: safeMinLevel(destination) ?? options.level,
|
|
3001
|
+
stream
|
|
3002
|
+
};
|
|
3003
|
+
});
|
|
2692
3004
|
return pino(pinoOptions, pino.multistream(streams));
|
|
2693
3005
|
}
|
|
3006
|
+
var DROP_REPORT_INTERVAL_MS = 1e4;
|
|
2694
3007
|
var DestinationHealth = class {
|
|
2695
3008
|
constructor() {
|
|
2696
3009
|
/** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
|
|
@@ -2734,6 +3047,10 @@ var DestinationHealth = class {
|
|
|
2734
3047
|
* when the last one settles.
|
|
2735
3048
|
*/
|
|
2736
3049
|
this.pendingWrites = /* @__PURE__ */ new Map();
|
|
3050
|
+
/** The `Writable` that fronts each destination, whose buffer is the queue of entries it holds. */
|
|
3051
|
+
this.streams = /* @__PURE__ */ new Map();
|
|
3052
|
+
/** Entries dropped for want of queue room, per destination, and when the last one was reported. */
|
|
3053
|
+
this.drops = /* @__PURE__ */ new Map();
|
|
2737
3054
|
/**
|
|
2738
3055
|
* The rescuer's severity index within {@link LOG_LEVEL_PRIORITY}. Starts above
|
|
2739
3056
|
* every real level so the first `markFailed` always wins the comparison.
|
|
@@ -2752,6 +3069,64 @@ var DestinationHealth = class {
|
|
|
2752
3069
|
markWriteFailed(destination) {
|
|
2753
3070
|
this.writeFailed.add(destination);
|
|
2754
3071
|
}
|
|
3072
|
+
/**
|
|
3073
|
+
* Record one entry dropped because the destination's queue was full, and say whether the drop is
|
|
3074
|
+
* due a report.
|
|
3075
|
+
*
|
|
3076
|
+
* A report is due on the first drop and then at most once every {@link DROP_REPORT_INTERVAL_MS},
|
|
3077
|
+
* so a sustained overflow costs one stderr line per window and not one per entry.
|
|
3078
|
+
*
|
|
3079
|
+
* @param destination - The destination whose queue was full.
|
|
3080
|
+
* @param now - A monotonic reading in milliseconds (`performance.now()`).
|
|
3081
|
+
* @returns The number of drops since the last report when one is due, otherwise `undefined`.
|
|
3082
|
+
*/
|
|
3083
|
+
recordDrop(destination, now) {
|
|
3084
|
+
const record = this.drops.get(destination) ?? {
|
|
3085
|
+
total: 0,
|
|
3086
|
+
unreported: 0,
|
|
3087
|
+
lastReportAt: void 0
|
|
3088
|
+
};
|
|
3089
|
+
this.drops.set(destination, record);
|
|
3090
|
+
record.total += 1;
|
|
3091
|
+
record.unreported += 1;
|
|
3092
|
+
this.writeFailed.add(destination);
|
|
3093
|
+
if (record.lastReportAt !== void 0 && now - record.lastReportAt < DROP_REPORT_INTERVAL_MS) {
|
|
3094
|
+
return void 0;
|
|
3095
|
+
}
|
|
3096
|
+
record.lastReportAt = now;
|
|
3097
|
+
const due = record.unreported;
|
|
3098
|
+
record.unreported = 0;
|
|
3099
|
+
return due;
|
|
3100
|
+
}
|
|
3101
|
+
/**
|
|
3102
|
+
* How many entries a destination has had dropped for want of queue room.
|
|
3103
|
+
*
|
|
3104
|
+
* @param destination - The destination to ask about.
|
|
3105
|
+
* @returns The count since startup, `0` when none.
|
|
3106
|
+
*/
|
|
3107
|
+
droppedTotal(destination) {
|
|
3108
|
+
return this.drops.get(destination)?.total ?? 0;
|
|
3109
|
+
}
|
|
3110
|
+
/**
|
|
3111
|
+
* Record the stream that fronts a destination, whose buffer is the queue of entries it holds.
|
|
3112
|
+
*
|
|
3113
|
+
* @param destination - The destination.
|
|
3114
|
+
* @param stream - Its `Writable` adapter, read only for the bytes it holds queued.
|
|
3115
|
+
*/
|
|
3116
|
+
registerStream(destination, stream) {
|
|
3117
|
+
this.streams.set(destination, stream);
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* How much a destination still holds: the size of what Pino has written to its stream and the
|
|
3121
|
+
* destination has not yet taken, the write in flight included. Zero means nothing is queued.
|
|
3122
|
+
*
|
|
3123
|
+
* @param destination - The destination to ask about.
|
|
3124
|
+
* @returns The queued size in bytes of NDJSON, `0` for a
|
|
3125
|
+
* destination whose stream is not known.
|
|
3126
|
+
*/
|
|
3127
|
+
queuedSize(destination) {
|
|
3128
|
+
return this.streams.get(destination)?.queuedBytes ?? 0;
|
|
3129
|
+
}
|
|
2755
3130
|
/**
|
|
2756
3131
|
* Record that an asynchronous write to a destination has started.
|
|
2757
3132
|
*
|
|
@@ -2861,6 +3236,34 @@ var DestinationHealth = class {
|
|
|
2861
3236
|
DestinationHealth = __decorateClass([
|
|
2862
3237
|
Injectable()
|
|
2863
3238
|
], DestinationHealth);
|
|
3239
|
+
|
|
3240
|
+
// src/server/utils/with-timeout.util.ts
|
|
3241
|
+
var HookTimeoutError = class extends Error {
|
|
3242
|
+
constructor(timeoutMs) {
|
|
3243
|
+
super(`did not settle within ${String(timeoutMs)} ms`);
|
|
3244
|
+
this.timeoutMs = timeoutMs;
|
|
3245
|
+
this.name = "HookTimeoutError";
|
|
3246
|
+
}
|
|
3247
|
+
};
|
|
3248
|
+
function withTimeout(work, ms) {
|
|
3249
|
+
return new Promise((resolve, reject2) => {
|
|
3250
|
+
const timer = setTimeout(() => {
|
|
3251
|
+
reject2(new HookTimeoutError(ms));
|
|
3252
|
+
}, ms);
|
|
3253
|
+
const settle = (done) => (...args) => {
|
|
3254
|
+
clearTimeout(timer);
|
|
3255
|
+
done(...args);
|
|
3256
|
+
};
|
|
3257
|
+
try {
|
|
3258
|
+
Promise.resolve(work()).then(settle(resolve), settle(reject2));
|
|
3259
|
+
} catch (cause) {
|
|
3260
|
+
settle(reject2)(cause);
|
|
3261
|
+
}
|
|
3262
|
+
});
|
|
3263
|
+
}
|
|
3264
|
+
|
|
3265
|
+
// src/server/services/destination-registry.service.ts
|
|
3266
|
+
var DRAIN_POLL_MS = 5;
|
|
2864
3267
|
var DestinationRegistry = class {
|
|
2865
3268
|
/**
|
|
2866
3269
|
* @param registered - Every destination declared under
|
|
@@ -2905,7 +3308,7 @@ var DestinationRegistry = class {
|
|
|
2905
3308
|
async onModuleInit() {
|
|
2906
3309
|
for (const destination of this.registered) {
|
|
2907
3310
|
try {
|
|
2908
|
-
await destination.onInit?.();
|
|
3311
|
+
await withTimeout(() => destination.onInit?.(), this.options.destinationHookTimeoutMs);
|
|
2909
3312
|
this.active.push(destination);
|
|
2910
3313
|
this.health.markHealthy(destination, this.effectiveLevelOf(destination));
|
|
2911
3314
|
} catch (cause) {
|
|
@@ -2937,12 +3340,15 @@ var DestinationRegistry = class {
|
|
|
2937
3340
|
async notifyRegistryReady() {
|
|
2938
3341
|
for (const destination of this.registered) {
|
|
2939
3342
|
try {
|
|
2940
|
-
await
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
3343
|
+
await withTimeout(
|
|
3344
|
+
() => destination.onRegistryReady?.({
|
|
3345
|
+
heldEntriesDeliveredElsewhere: this.health.deliveredByHealthySink(
|
|
3346
|
+
destination,
|
|
3347
|
+
this.effectiveLevelOf(destination)
|
|
3348
|
+
)
|
|
3349
|
+
}),
|
|
3350
|
+
this.options.destinationHookTimeoutMs
|
|
3351
|
+
);
|
|
2946
3352
|
} catch (cause) {
|
|
2947
3353
|
this.reportHookFailure(destination, cause);
|
|
2948
3354
|
}
|
|
@@ -3060,6 +3466,9 @@ var DestinationRegistry = class {
|
|
|
3060
3466
|
* point in the shutdown sequence.
|
|
3061
3467
|
*/
|
|
3062
3468
|
async onApplicationShutdown() {
|
|
3469
|
+
const startedAt = performance.now();
|
|
3470
|
+
const { timeoutMs, drainTimeoutMs } = this.options.shutdown;
|
|
3471
|
+
const deadline = startedAt + timeoutMs;
|
|
3063
3472
|
this.logger.info(
|
|
3064
3473
|
RESERVED_LOG_KEYS.LOGGER_SHUTDOWN_OK,
|
|
3065
3474
|
"BymaxLoggerModule shutting down",
|
|
@@ -3069,13 +3478,74 @@ var DestinationRegistry = class {
|
|
|
3069
3478
|
await new Promise((resolve) => {
|
|
3070
3479
|
setImmediate(resolve);
|
|
3071
3480
|
});
|
|
3481
|
+
await this.drain(Math.min(deadline, startedAt + drainTimeoutMs));
|
|
3482
|
+
const skipped = [];
|
|
3072
3483
|
for (const destination of [...this.active].reverse()) {
|
|
3484
|
+
const remaining = deadline - performance.now();
|
|
3485
|
+
if (remaining <= 0) {
|
|
3486
|
+
skipped.push(toSingleLineMessage(safeDestinationName(destination)));
|
|
3487
|
+
continue;
|
|
3488
|
+
}
|
|
3073
3489
|
try {
|
|
3074
|
-
await destination.onShutdown?.();
|
|
3490
|
+
await withTimeout(() => destination.onShutdown?.(), remaining);
|
|
3075
3491
|
} catch (cause) {
|
|
3076
3492
|
this.reportShutdownFailure(destination, cause);
|
|
3077
3493
|
}
|
|
3078
3494
|
}
|
|
3495
|
+
this.reportDropTotals();
|
|
3496
|
+
if (skipped.length > 0) {
|
|
3497
|
+
writeStderrSafely(
|
|
3498
|
+
`[DestinationRegistry] Shutdown budget of ${String(timeoutMs)} ms spent; onShutdown not called for: ${skipped.map((name) => `"${name}"`).join(", ")}
|
|
3499
|
+
`
|
|
3500
|
+
);
|
|
3501
|
+
}
|
|
3502
|
+
}
|
|
3503
|
+
/**
|
|
3504
|
+
* Say, once, how many entries each destination had dropped for want of queue room, when any did.
|
|
3505
|
+
* It carries the name and the count and no entry content.
|
|
3506
|
+
*/
|
|
3507
|
+
reportDropTotals() {
|
|
3508
|
+
for (const destination of this.registered) {
|
|
3509
|
+
const total = this.health.droppedTotal(destination);
|
|
3510
|
+
if (total > 0) {
|
|
3511
|
+
writeStderrSafely(
|
|
3512
|
+
`[DestinationRegistry] Destination "${toSingleLineMessage(safeDestinationName(destination))}" dropped ${String(total)} entries in total because its queue was full
|
|
3513
|
+
`
|
|
3514
|
+
);
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
/**
|
|
3519
|
+
* Wait until no active destination holds a queued entry, or the drain deadline passes.
|
|
3520
|
+
*
|
|
3521
|
+
* A destination reads its entries from a `Writable` that buffers what Pino has written, and it
|
|
3522
|
+
* takes them one at a time. `onShutdown` is its signal to flush and close, so a write that begins
|
|
3523
|
+
* after it is a write on a closed resource. The wait does not end the streams, because Pino may
|
|
3524
|
+
* still log while the application shuts down, and an entry written after the end of a stream is an
|
|
3525
|
+
* error. An entry written during the wait extends it, up to the deadline. When the deadline ends it,
|
|
3526
|
+
* one line names the destinations and their queued sizes; it carries no entry content.
|
|
3527
|
+
*
|
|
3528
|
+
* @param drainDeadline - The time, in `performance.now()` milliseconds, the wait ends at.
|
|
3529
|
+
*/
|
|
3530
|
+
async drain(drainDeadline) {
|
|
3531
|
+
for (; ; ) {
|
|
3532
|
+
const queued = this.active.filter((destination) => this.health.queuedSize(destination) > 0);
|
|
3533
|
+
if (queued.length === 0) return;
|
|
3534
|
+
const remaining = drainDeadline - performance.now();
|
|
3535
|
+
if (remaining <= 0) {
|
|
3536
|
+
const named = queued.map(
|
|
3537
|
+
(destination) => `"${toSingleLineMessage(safeDestinationName(destination))}" (${String(this.health.queuedSize(destination))})`
|
|
3538
|
+
);
|
|
3539
|
+
writeStderrSafely(
|
|
3540
|
+
`[DestinationRegistry] Shutdown drain ended with entries still queued, by size: ${named.join(", ")}
|
|
3541
|
+
`
|
|
3542
|
+
);
|
|
3543
|
+
return;
|
|
3544
|
+
}
|
|
3545
|
+
await new Promise((resolve) => {
|
|
3546
|
+
setTimeout(resolve, Math.min(DRAIN_POLL_MS, remaining));
|
|
3547
|
+
});
|
|
3548
|
+
}
|
|
3079
3549
|
}
|
|
3080
3550
|
/**
|
|
3081
3551
|
* Report a failing `onShutdown` on stderr without letting the report itself
|
|
@@ -3579,6 +4049,7 @@ var HttpAccessLogMiddleware = class {
|
|
|
3579
4049
|
this.logContext = logContext;
|
|
3580
4050
|
this.isEnabled = options.http.isEnabled;
|
|
3581
4051
|
this.excludePaths = options.http.excludePaths;
|
|
4052
|
+
this.secretPathSegments = options.http.secretPathSegments;
|
|
3582
4053
|
}
|
|
3583
4054
|
/**
|
|
3584
4055
|
* Emit START, arm the terminal entry on `'close'`, and continue the chain.
|
|
@@ -3604,14 +4075,14 @@ var HttpAccessLogMiddleware = class {
|
|
|
3604
4075
|
}
|
|
3605
4076
|
markRecorderActive(req);
|
|
3606
4077
|
const method = req.method;
|
|
3607
|
-
const url = normalizeUrl(target);
|
|
4078
|
+
const url = normalizeUrl(target, this.secretPathSegments);
|
|
3608
4079
|
const start = Date.now();
|
|
3609
4080
|
this.logger.info(RESERVED_LOG_KEYS.HTTP_REQUEST_START, `${method} ${url}`, readUserId(req), {
|
|
3610
4081
|
method,
|
|
3611
4082
|
url,
|
|
3612
4083
|
// Query string stripped: it may carry secrets (reset tokens, OAuth codes)
|
|
3613
4084
|
// that no key-name redaction can scrub out of a string VALUE.
|
|
3614
|
-
fullUrl: path2,
|
|
4085
|
+
fullUrl: scrubSecretSegments(path2, this.secretPathSegments),
|
|
3615
4086
|
// Conventional for an access log and personal data under GDPR/LGPD. Its
|
|
3616
4087
|
// fidelity is the app's to establish: behind a proxy it is only the real
|
|
3617
4088
|
// client when the app configures `trust proxy`, and a value the app has not
|
|
@@ -3676,7 +4147,12 @@ var HttpAccessLogMiddleware = class {
|
|
|
3676
4147
|
recorded === void 0 ? meta : {
|
|
3677
4148
|
...meta,
|
|
3678
4149
|
errorMessage: cutIfText(
|
|
3679
|
-
|
|
4150
|
+
withoutRequestSecretsIfText(
|
|
4151
|
+
recorded.error.message,
|
|
4152
|
+
this.secretPathSegments,
|
|
4153
|
+
req.originalUrl,
|
|
4154
|
+
req.url
|
|
4155
|
+
)
|
|
3680
4156
|
)
|
|
3681
4157
|
}
|
|
3682
4158
|
);
|