@bymax-one/nest-logger 1.4.15 → 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 +136 -1
- package/README.md +280 -808
- 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.cjs
CHANGED
|
@@ -25,15 +25,31 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
25
25
|
};
|
|
26
26
|
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
27
27
|
|
|
28
|
+
// src/server/constants/lifecycle-timeouts.constants.ts
|
|
29
|
+
var DEFAULT_HOOK_TIMEOUT_MS = 1e4;
|
|
30
|
+
var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
|
|
31
|
+
var DEFAULT_DRAIN_TIMEOUT_MS = 5e3;
|
|
32
|
+
var DEFAULT_QUEUE_MAX_BYTES = 33554432;
|
|
33
|
+
var MIN_QUEUE_MAX_BYTES = 1024;
|
|
34
|
+
var MAX_QUEUE_MAX_BYTES = 2147483647;
|
|
35
|
+
|
|
28
36
|
// src/server/config/default-options.ts
|
|
29
37
|
var DEFAULT_HTTP = {
|
|
30
38
|
isEnabled: false,
|
|
31
39
|
shouldCaptureExceptions: true,
|
|
32
40
|
shouldGenerateRequestId: true,
|
|
33
41
|
excludePaths: [/^\/health$/, /^\/health\/live$/, /^\/health\/ready$/, /^\/metrics$/],
|
|
42
|
+
secretPathSegments: [],
|
|
34
43
|
tenantIdHeader: "x-tenant-id",
|
|
35
44
|
tenantIdResolver: void 0
|
|
36
45
|
};
|
|
46
|
+
function resolveShutdown(given) {
|
|
47
|
+
const timeoutMs = given?.timeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
48
|
+
return Object.freeze({
|
|
49
|
+
timeoutMs,
|
|
50
|
+
drainTimeoutMs: given?.drainTimeoutMs ?? Math.min(DEFAULT_DRAIN_TIMEOUT_MS, timeoutMs)
|
|
51
|
+
});
|
|
52
|
+
}
|
|
37
53
|
var DEFAULT_OTEL = {
|
|
38
54
|
shouldAutoInjectTraceContext: true,
|
|
39
55
|
fieldFormat: "camelCase",
|
|
@@ -80,10 +96,16 @@ function applyDefaults(options) {
|
|
|
80
96
|
destinations: Object.freeze([...options.destinations ?? []]),
|
|
81
97
|
http: Object.freeze({
|
|
82
98
|
...http,
|
|
83
|
-
excludePaths: Object.freeze([...http.excludePaths])
|
|
99
|
+
excludePaths: Object.freeze([...http.excludePaths]),
|
|
100
|
+
secretPathSegments: Object.freeze([...http.secretPathSegments])
|
|
84
101
|
}),
|
|
85
102
|
otel: Object.freeze(otel),
|
|
86
103
|
maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
|
|
104
|
+
destinationHookTimeoutMs: options.destinationHookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS,
|
|
105
|
+
shutdown: resolveShutdown(options.shutdown),
|
|
106
|
+
destinationQueue: Object.freeze({
|
|
107
|
+
maxBytes: options.destinationQueue?.maxBytes ?? DEFAULT_QUEUE_MAX_BYTES
|
|
108
|
+
}),
|
|
87
109
|
errorOwnFields: options.errorOwnFields ?? "all",
|
|
88
110
|
errorOwnFieldNames: Object.freeze([...options.errorOwnFieldNames ?? []]),
|
|
89
111
|
serializers: Object.freeze({ ...options.serializers ?? {} }),
|
|
@@ -147,6 +169,41 @@ function checkGroup(path, value) {
|
|
|
147
169
|
if (!isRecord(value)) reject(path, "must be an object", value);
|
|
148
170
|
return value;
|
|
149
171
|
}
|
|
172
|
+
var MAX_TIMER_MS = 2147483647;
|
|
173
|
+
function checkTimerMs(path, value) {
|
|
174
|
+
if (value === void 0) return;
|
|
175
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_TIMER_MS) {
|
|
176
|
+
reject(path, `must be an integer from 1 to ${String(MAX_TIMER_MS)}`, value);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function validateQueue(options) {
|
|
180
|
+
const queue = checkGroup("destinationQueue", options.destinationQueue);
|
|
181
|
+
const maxBytes = queue?.["maxBytes"];
|
|
182
|
+
if (maxBytes === void 0 || maxBytes === 0) return;
|
|
183
|
+
if (typeof maxBytes !== "number" || !Number.isInteger(maxBytes) || maxBytes < MIN_QUEUE_MAX_BYTES || maxBytes > MAX_QUEUE_MAX_BYTES) {
|
|
184
|
+
reject(
|
|
185
|
+
"destinationQueue.maxBytes",
|
|
186
|
+
`must be 0 (no bound) or an integer from ${String(MIN_QUEUE_MAX_BYTES)} to ${String(MAX_QUEUE_MAX_BYTES)}`,
|
|
187
|
+
maxBytes
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function validateLifecycle(options) {
|
|
192
|
+
checkTimerMs("destinationHookTimeoutMs", options.destinationHookTimeoutMs);
|
|
193
|
+
const shutdown = checkGroup("shutdown", options.shutdown);
|
|
194
|
+
if (shutdown === void 0) return;
|
|
195
|
+
checkTimerMs("shutdown.timeoutMs", shutdown["timeoutMs"]);
|
|
196
|
+
checkTimerMs("shutdown.drainTimeoutMs", shutdown["drainTimeoutMs"]);
|
|
197
|
+
const { timeoutMs, drainTimeoutMs } = shutdown;
|
|
198
|
+
const total = typeof timeoutMs === "number" ? timeoutMs : DEFAULT_SHUTDOWN_TIMEOUT_MS;
|
|
199
|
+
if (typeof drainTimeoutMs === "number" && drainTimeoutMs > total) {
|
|
200
|
+
reject(
|
|
201
|
+
"shutdown.drainTimeoutMs",
|
|
202
|
+
"must not exceed shutdown.timeoutMs, which covers the drain and every onShutdown",
|
|
203
|
+
drainTimeoutMs
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
150
207
|
function validateCore(options) {
|
|
151
208
|
if (!options.service) {
|
|
152
209
|
throw new Error("[BymaxLoggerModule] options.service is required");
|
|
@@ -280,23 +337,25 @@ function validateDestinations(options) {
|
|
|
280
337
|
}
|
|
281
338
|
destinations.forEach((entry, index) => validateDestination(entry, index));
|
|
282
339
|
}
|
|
340
|
+
function checkRegExpList(path, value) {
|
|
341
|
+
if (value === void 0) return;
|
|
342
|
+
if (!Array.isArray(value)) {
|
|
343
|
+
reject(path, "must be an array of RegExp", value);
|
|
344
|
+
}
|
|
345
|
+
value.forEach((pattern, index) => {
|
|
346
|
+
if (!util.types.isRegExp(pattern)) {
|
|
347
|
+
reject(`${path}[${String(index)}]`, "must be a RegExp", pattern);
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
}
|
|
283
351
|
function validateHttp(options) {
|
|
284
352
|
const http = checkGroup("http", options.http);
|
|
285
353
|
if (http === void 0) return;
|
|
286
354
|
checkBoolean("http.isEnabled", http["isEnabled"]);
|
|
287
355
|
checkBoolean("http.shouldCaptureExceptions", http["shouldCaptureExceptions"]);
|
|
288
356
|
checkBoolean("http.shouldGenerateRequestId", http["shouldGenerateRequestId"]);
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
if (!Array.isArray(excludePaths)) {
|
|
292
|
-
reject("http.excludePaths", "must be an array of RegExp", excludePaths);
|
|
293
|
-
}
|
|
294
|
-
excludePaths.forEach((pattern, index) => {
|
|
295
|
-
if (!util.types.isRegExp(pattern)) {
|
|
296
|
-
reject(`http.excludePaths[${String(index)}]`, "must be a RegExp", pattern);
|
|
297
|
-
}
|
|
298
|
-
});
|
|
299
|
-
}
|
|
357
|
+
checkRegExpList("http.excludePaths", http["excludePaths"]);
|
|
358
|
+
checkRegExpList("http.secretPathSegments", http["secretPathSegments"]);
|
|
300
359
|
const tenantIdHeader = http["tenantIdHeader"];
|
|
301
360
|
if (tenantIdHeader !== void 0 && tenantIdHeader !== false && !isNonEmptyString(tenantIdHeader)) {
|
|
302
361
|
reject("http.tenantIdHeader", "must be a non-empty string or false", tenantIdHeader);
|
|
@@ -324,6 +383,8 @@ function validateOptions(options) {
|
|
|
324
383
|
validateCustomization(options);
|
|
325
384
|
validateErrorFields(options);
|
|
326
385
|
validateDestinations(options);
|
|
386
|
+
validateLifecycle(options);
|
|
387
|
+
validateQueue(options);
|
|
327
388
|
validateHttp(options);
|
|
328
389
|
validateOtel(options);
|
|
329
390
|
}
|
|
@@ -954,6 +1015,15 @@ exports.DefaultStdoutDestination = class DefaultStdoutDestination {
|
|
|
954
1015
|
this.minLevel = opts.minLevel;
|
|
955
1016
|
}
|
|
956
1017
|
}
|
|
1018
|
+
/**
|
|
1019
|
+
* The bytes `process.stdout` holds that have not reached its reader.
|
|
1020
|
+
*
|
|
1021
|
+
* @returns `process.stdout.writableLength`, in bytes since Node decodes a string chunk to a
|
|
1022
|
+
* buffer before queueing it.
|
|
1023
|
+
*/
|
|
1024
|
+
queuedBytes() {
|
|
1025
|
+
return process.stdout.writableLength;
|
|
1026
|
+
}
|
|
957
1027
|
/**
|
|
958
1028
|
* Write a serialized JSON log entry (terminated with `\n`) to `stdout`.
|
|
959
1029
|
*
|
|
@@ -1053,32 +1123,86 @@ function readUserAgent(req) {
|
|
|
1053
1123
|
return typeof raw === "string" ? raw : UNKNOWN_USER_AGENT;
|
|
1054
1124
|
}
|
|
1055
1125
|
|
|
1126
|
+
// src/server/utils/matches-exclude-path.util.ts
|
|
1127
|
+
function matchesExcludePath(patterns, path) {
|
|
1128
|
+
return patterns.some((pattern) => {
|
|
1129
|
+
if (pattern.global || pattern.sticky) {
|
|
1130
|
+
pattern.lastIndex = 0;
|
|
1131
|
+
}
|
|
1132
|
+
return pattern.test(path);
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1056
1136
|
// src/server/utils/normalize-url.util.ts
|
|
1057
1137
|
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;
|
|
1058
1138
|
var ULID_REGEX = /\/[0-9A-HJKMNP-TV-Z]{26}(?![0-9A-HJKMNP-TV-Z])/g;
|
|
1059
1139
|
var NANOID_REGEX = /\/[A-Za-z0-9_-]{21}(?![A-Za-z0-9_-])/g;
|
|
1060
1140
|
var NUMERIC_ID_REGEX = /\/\d+/g;
|
|
1061
1141
|
var ID_PLACEHOLDER = "/:id";
|
|
1062
|
-
|
|
1063
|
-
|
|
1142
|
+
var SECRET_PLACEHOLDER = ":redacted";
|
|
1143
|
+
var HEX_SECRET_REGEX = /^[0-9a-f]{32,}$/i;
|
|
1144
|
+
var JWT_SECRET_REGEX = /^eyJ[\w-]*\.[\w-]+\.[\w-]*$/;
|
|
1145
|
+
var TOKEN_SECRET_REGEX = /^[A-Za-z0-9_+/-]{32,}={0,2}$/;
|
|
1146
|
+
var SLUG_REGEX = /^[a-z0-9]+(?:[-_][a-z0-9]+)+$/;
|
|
1147
|
+
var HEX_RUN_REGEX = /[0-9a-f]{32}/i;
|
|
1148
|
+
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;
|
|
1149
|
+
var EMAIL_SECRET_REGEX = /^[^@\s]+@[^@\s.]+(?:\.[^@\s.]+)+$/;
|
|
1150
|
+
function decodeSegment(segment) {
|
|
1151
|
+
try {
|
|
1152
|
+
return decodeURIComponent(segment);
|
|
1153
|
+
} catch {
|
|
1154
|
+
return segment;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
function isSecretSegment(segment, extra) {
|
|
1158
|
+
if (segment === "") return false;
|
|
1159
|
+
const decoded = decodeSegment(segment);
|
|
1160
|
+
return looksLikeToken(decoded) || looksLikeToken(withoutExtension(decoded)) || EMAIL_SECRET_REGEX.test(decoded) || matchesExcludePath(extra, decoded);
|
|
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(path, extra = []) {
|
|
1178
|
+
return path.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);
|
|
1064
1182
|
}
|
|
1065
1183
|
function stripQueryString(url) {
|
|
1066
1184
|
const queryStart = url.indexOf("?");
|
|
1067
1185
|
return queryStart === -1 ? url : url.slice(0, queryStart);
|
|
1068
1186
|
}
|
|
1069
|
-
function
|
|
1187
|
+
function withoutRequestSecrets(text, extra, ...urls) {
|
|
1070
1188
|
let result = text;
|
|
1189
|
+
const segments = /* @__PURE__ */ new Set();
|
|
1071
1190
|
for (const url of urls) {
|
|
1072
1191
|
if (url === void 0) continue;
|
|
1073
1192
|
const queryStart = url.indexOf("?");
|
|
1074
1193
|
if (queryStart !== -1 && url.length - queryStart > 1) {
|
|
1075
1194
|
result = result.split(url.slice(queryStart)).join("");
|
|
1076
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);
|
|
1077
1201
|
}
|
|
1078
1202
|
return result;
|
|
1079
1203
|
}
|
|
1080
|
-
function
|
|
1081
|
-
return typeof value === "string" ?
|
|
1204
|
+
function withoutRequestSecretsIfText(value, extra, ...urls) {
|
|
1205
|
+
return typeof value === "string" ? withoutRequestSecrets(value, extra, ...urls) : value;
|
|
1082
1206
|
}
|
|
1083
1207
|
|
|
1084
1208
|
// src/server/filters/http-exception.filter.ts
|
|
@@ -1091,9 +1215,12 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
|
|
|
1091
1215
|
* @param logger - The structured logger exception entries are written to.
|
|
1092
1216
|
* Injected by token explicitly: the package is bundled without
|
|
1093
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.
|
|
1094
1220
|
*/
|
|
1095
|
-
constructor(logger) {
|
|
1221
|
+
constructor(logger, options) {
|
|
1096
1222
|
this.logger = logger;
|
|
1223
|
+
this.secretPathSegments = options?.http.secretPathSegments ?? [];
|
|
1097
1224
|
}
|
|
1098
1225
|
/**
|
|
1099
1226
|
* Log the exception at the status-appropriate level and write the JSON
|
|
@@ -1107,7 +1234,7 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
|
|
|
1107
1234
|
const res = ctx.getResponse();
|
|
1108
1235
|
const req = ctx.getRequest();
|
|
1109
1236
|
const userId = req.user?.sub ?? req.user?.id;
|
|
1110
|
-
const url = stripQueryString(req.url);
|
|
1237
|
+
const url = scrubSecretSegments(stripQueryString(req.url), this.secretPathSegments);
|
|
1111
1238
|
if (exception instanceof common.HttpException) {
|
|
1112
1239
|
const status = exception.getStatus();
|
|
1113
1240
|
const parserError = readRecordedParserError(req);
|
|
@@ -1127,7 +1254,12 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
|
|
|
1127
1254
|
} else {
|
|
1128
1255
|
this.logger.warnStructured(
|
|
1129
1256
|
RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
|
|
1130
|
-
parserError?.logMessage ??
|
|
1257
|
+
parserError?.logMessage ?? withoutRequestSecrets(
|
|
1258
|
+
exception.message,
|
|
1259
|
+
this.secretPathSegments,
|
|
1260
|
+
req.originalUrl,
|
|
1261
|
+
req.url
|
|
1262
|
+
),
|
|
1131
1263
|
userId,
|
|
1132
1264
|
metadata
|
|
1133
1265
|
);
|
|
@@ -1157,7 +1289,7 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
|
|
|
1157
1289
|
const { method, url, userId } = request;
|
|
1158
1290
|
this.logger.warnStructured(
|
|
1159
1291
|
RESERVED_LOG_KEYS.HTTP_EXCEPTION_HANDLED,
|
|
1160
|
-
|
|
1292
|
+
withoutRequestSecrets(clientError.logMessage, this.secretPathSegments, ...rawUrls),
|
|
1161
1293
|
userId,
|
|
1162
1294
|
{
|
|
1163
1295
|
method,
|
|
@@ -1192,20 +1324,10 @@ exports.HttpExceptionFilter = class HttpExceptionFilter {
|
|
|
1192
1324
|
};
|
|
1193
1325
|
exports.HttpExceptionFilter = __decorateClass([
|
|
1194
1326
|
common.Catch(),
|
|
1195
|
-
__decorateParam(0, common.Inject(exports.PinoLoggerService))
|
|
1327
|
+
__decorateParam(0, common.Inject(exports.PinoLoggerService)),
|
|
1328
|
+
__decorateParam(1, common.Optional()),
|
|
1329
|
+
__decorateParam(1, common.Inject(LOGGER_OPTIONS_TOKEN))
|
|
1196
1330
|
], exports.HttpExceptionFilter);
|
|
1197
|
-
|
|
1198
|
-
// src/server/utils/matches-exclude-path.util.ts
|
|
1199
|
-
function matchesExcludePath(patterns, path) {
|
|
1200
|
-
return patterns.some((pattern) => {
|
|
1201
|
-
if (pattern.global || pattern.sticky) {
|
|
1202
|
-
pattern.lastIndex = 0;
|
|
1203
|
-
}
|
|
1204
|
-
return pattern.test(path);
|
|
1205
|
-
});
|
|
1206
|
-
}
|
|
1207
|
-
|
|
1208
|
-
// src/server/interceptors/http-logging.interceptor.ts
|
|
1209
1331
|
var HTTP_SUCCESS_MIN = 200;
|
|
1210
1332
|
exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
1211
1333
|
/**
|
|
@@ -1218,6 +1340,7 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1218
1340
|
constructor(logger, options) {
|
|
1219
1341
|
this.logger = logger;
|
|
1220
1342
|
this.excludePaths = options.http.excludePaths;
|
|
1343
|
+
this.secretPathSegments = options.http.secretPathSegments;
|
|
1221
1344
|
}
|
|
1222
1345
|
/**
|
|
1223
1346
|
* Whether a request path bypasses HTTP logging (matches any `excludePaths`).
|
|
@@ -1249,7 +1372,7 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1249
1372
|
}
|
|
1250
1373
|
const userAgent = readUserAgent(req);
|
|
1251
1374
|
const userId = readUserId(req);
|
|
1252
|
-
const normalizedUrl = normalizeUrl(url);
|
|
1375
|
+
const normalizedUrl = normalizeUrl(url, this.secretPathSegments);
|
|
1253
1376
|
const start = Date.now();
|
|
1254
1377
|
this.logger.info(RESERVED_LOG_KEYS.HTTP_REQUEST_START, `${method} ${normalizedUrl}`, userId, {
|
|
1255
1378
|
method,
|
|
@@ -1257,7 +1380,7 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1257
1380
|
// Query string stripped: it may carry secrets (reset tokens, OAuth codes)
|
|
1258
1381
|
// that Pino's path-based redaction cannot scrub from a string value. The
|
|
1259
1382
|
// raw (un-normalized) path is kept for per-request debugging.
|
|
1260
|
-
fullUrl: stripQueryString(url),
|
|
1383
|
+
fullUrl: scrubSecretSegments(stripQueryString(url), this.secretPathSegments),
|
|
1261
1384
|
ip,
|
|
1262
1385
|
userAgent
|
|
1263
1386
|
});
|
|
@@ -1355,7 +1478,9 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1355
1478
|
url,
|
|
1356
1479
|
statusCode,
|
|
1357
1480
|
duration,
|
|
1358
|
-
errorMessage: cutIfText(
|
|
1481
|
+
errorMessage: cutIfText(
|
|
1482
|
+
withoutRequestSecretsIfText(err.message, this.secretPathSegments, ...rawUrls)
|
|
1483
|
+
)
|
|
1359
1484
|
}
|
|
1360
1485
|
);
|
|
1361
1486
|
}
|
|
@@ -1393,7 +1518,9 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1393
1518
|
url,
|
|
1394
1519
|
statusCode: clientError.status,
|
|
1395
1520
|
duration,
|
|
1396
|
-
errorMessage: cutIfText(
|
|
1521
|
+
errorMessage: cutIfText(
|
|
1522
|
+
withoutRequestSecretsIfText(clientError.logMessage, this.secretPathSegments, ...rawUrls)
|
|
1523
|
+
),
|
|
1397
1524
|
bodyParserType: clientError.bodyParserType
|
|
1398
1525
|
}
|
|
1399
1526
|
);
|
|
@@ -1815,7 +1942,47 @@ var REDACT_COMMON_FIELDS = [
|
|
|
1815
1942
|
"cookie",
|
|
1816
1943
|
"set-cookie",
|
|
1817
1944
|
"x-api-key",
|
|
1818
|
-
"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"
|
|
1819
1986
|
];
|
|
1820
1987
|
var REDACT_ABSOLUTE_PATHS = [
|
|
1821
1988
|
"req.headers.authorization",
|
|
@@ -1993,14 +2160,90 @@ function reportWriteFailure(destination, cause) {
|
|
|
1993
2160
|
function rescueToStdout(payload) {
|
|
1994
2161
|
writeStdoutSafely(payload);
|
|
1995
2162
|
}
|
|
1996
|
-
function
|
|
1997
|
-
|
|
2163
|
+
function ownQueuedBytes(destination) {
|
|
2164
|
+
try {
|
|
2165
|
+
const bytes = destination.queuedBytes?.() ?? 0;
|
|
2166
|
+
const positive = Number.isFinite(bytes) && bytes > 0;
|
|
2167
|
+
return positive ? bytes : 0;
|
|
2168
|
+
} catch {
|
|
2169
|
+
return 0;
|
|
2170
|
+
}
|
|
2171
|
+
}
|
|
2172
|
+
var BoundedWritable = class extends stream.Writable {
|
|
2173
|
+
constructor(destination, health, maxBytes, queue, options) {
|
|
2174
|
+
super(options);
|
|
2175
|
+
this.destination = destination;
|
|
2176
|
+
this.health = health;
|
|
2177
|
+
this.maxBytes = maxBytes;
|
|
2178
|
+
this.queue = queue;
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* A destroyed stream holds nothing: Writable fails the chunks still buffered without calling the
|
|
2182
|
+
* write handler, so nothing else would release their bytes.
|
|
2183
|
+
*/
|
|
2184
|
+
_destroy(error, callback) {
|
|
2185
|
+
this.queue.bytes = 0;
|
|
2186
|
+
super._destroy(error, callback);
|
|
2187
|
+
}
|
|
2188
|
+
/** The bytes of NDJSON waiting for the destination, the write in flight included. */
|
|
2189
|
+
get queuedBytes() {
|
|
2190
|
+
return this.queue.bytes;
|
|
2191
|
+
}
|
|
2192
|
+
write(chunk, encodingOrCallback, callback) {
|
|
2193
|
+
if (this.writableEnded || this.destroyed) {
|
|
2194
|
+
return this.forward(chunk, encodingOrCallback, callback);
|
|
2195
|
+
}
|
|
2196
|
+
const bytes = Buffer.byteLength(chunk);
|
|
2197
|
+
const held = this.heldBytes();
|
|
2198
|
+
if (this.maxBytes > 0 && held > 0 && held + bytes > this.maxBytes) {
|
|
2199
|
+
this.dropped();
|
|
2200
|
+
const done = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
|
|
2201
|
+
done?.();
|
|
2202
|
+
return true;
|
|
2203
|
+
}
|
|
2204
|
+
this.queue.bytes += bytes;
|
|
2205
|
+
return this.forward(chunk, encodingOrCallback, callback);
|
|
2206
|
+
}
|
|
2207
|
+
/** `Writable.write` for either of its two signatures. */
|
|
2208
|
+
forward(chunk, encodingOrCallback, callback) {
|
|
2209
|
+
return typeof encodingOrCallback === "function" ? super.write(chunk, encodingOrCallback) : super.write(chunk, encodingOrCallback ?? "utf8", callback);
|
|
2210
|
+
}
|
|
2211
|
+
/**
|
|
2212
|
+
* What the entry would queue behind. A live destination holds its module queue and what it reports
|
|
2213
|
+
* in a buffer of its own. A failed destination receives nothing, so what it reports does not count,
|
|
2214
|
+
* and the one elected to rescue entries writes them to stdout, whose queue is what grows.
|
|
2215
|
+
*/
|
|
2216
|
+
heldBytes() {
|
|
2217
|
+
if (!this.health.isFailed(this.destination)) {
|
|
2218
|
+
return this.queue.bytes + ownQueuedBytes(this.destination);
|
|
2219
|
+
}
|
|
2220
|
+
return this.health.shouldRescue(this.destination) ? this.queue.bytes + process.stdout.writableLength : 0;
|
|
2221
|
+
}
|
|
2222
|
+
/** Count the drop, and write the report when one is due. */
|
|
2223
|
+
dropped() {
|
|
2224
|
+
const due = this.health.recordDrop(this.destination, performance.now());
|
|
2225
|
+
if (due === void 0) return;
|
|
2226
|
+
const name = toSingleLineMessage(safeDestinationName(this.destination));
|
|
2227
|
+
writeStderrSafely(
|
|
2228
|
+
`[DestinationRegistry] Destination "${name}" queue full: ${String(due)} entries dropped since the last report (limit ${String(this.maxBytes)} bytes)
|
|
2229
|
+
`
|
|
2230
|
+
);
|
|
2231
|
+
}
|
|
2232
|
+
};
|
|
2233
|
+
function destinationToStream(destination, health, maxQueueBytes = 0) {
|
|
2234
|
+
const queue = { bytes: 0 };
|
|
2235
|
+
const stream = new BoundedWritable(destination, health, maxQueueBytes, queue, {
|
|
1998
2236
|
// Keep string chunks as strings (Node's default re-encodes them to Buffers
|
|
1999
2237
|
// before `_write`): the common Pino path emits NDJSON strings, so this skips
|
|
2000
2238
|
// a string→Buffer→string round-trip on the hot logging path.
|
|
2001
2239
|
// 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.
|
|
2002
2240
|
decodeStrings: false,
|
|
2003
|
-
write(chunk, _encoding,
|
|
2241
|
+
write(chunk, _encoding, settled) {
|
|
2242
|
+
const bytes = Buffer.byteLength(chunk);
|
|
2243
|
+
const callback = (error) => {
|
|
2244
|
+
queue.bytes = Math.max(0, queue.bytes - bytes);
|
|
2245
|
+
settled(error);
|
|
2246
|
+
};
|
|
2004
2247
|
const onFailure = (cause) => {
|
|
2005
2248
|
health.markWriteFailed(destination);
|
|
2006
2249
|
reportWriteFailure(destination, cause);
|
|
@@ -2036,6 +2279,15 @@ function destinationToStream(destination, health) {
|
|
|
2036
2279
|
}
|
|
2037
2280
|
}
|
|
2038
2281
|
});
|
|
2282
|
+
return stream;
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
// src/server/utils/censor-raw-headers.util.ts
|
|
2286
|
+
function censorRawHeaders(raw, sensitive, censor) {
|
|
2287
|
+
return raw.map((entry, index) => {
|
|
2288
|
+
const name = index % 2 === 1 ? raw[index - 1] : void 0;
|
|
2289
|
+
return typeof name === "string" && sensitive.has(name.toLowerCase()) ? censor : entry;
|
|
2290
|
+
});
|
|
2039
2291
|
}
|
|
2040
2292
|
|
|
2041
2293
|
// src/server/utils/redact-error-clone.util.ts
|
|
@@ -2155,6 +2407,10 @@ function addErrorParts(copy, error, ownKeys, host, depth2) {
|
|
|
2155
2407
|
}
|
|
2156
2408
|
|
|
2157
2409
|
// src/server/utils/redact-by-name.util.ts
|
|
2410
|
+
var RAW_HEADER_KEYS = /* @__PURE__ */ new Set(["rawheaders", "rawtrailers"]);
|
|
2411
|
+
function censorHeaderArray(key, walked, rules) {
|
|
2412
|
+
return RAW_HEADER_KEYS.has(key.toLowerCase()) && Array.isArray(walked) ? censorRawHeaders(walked, rules.headerNames, rules.censor) : walked;
|
|
2413
|
+
}
|
|
2158
2414
|
var REDACT_MAX_TRAVERSAL_DEPTH = 100;
|
|
2159
2415
|
var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
|
|
2160
2416
|
var REDACT_MAX_VISITS = 2e5;
|
|
@@ -2283,13 +2539,17 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
|
|
|
2283
2539
|
defineOwn(
|
|
2284
2540
|
copy,
|
|
2285
2541
|
key,
|
|
2286
|
-
rules.sensitive.has(key.toLowerCase()) ? rules.censor :
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2542
|
+
rules.sensitive.has(key.toLowerCase()) ? rules.censor : censorHeaderArray(
|
|
2543
|
+
key,
|
|
2544
|
+
walk(
|
|
2545
|
+
scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
|
|
2546
|
+
rules,
|
|
2547
|
+
depth2 + 1,
|
|
2548
|
+
ancestors,
|
|
2549
|
+
true,
|
|
2550
|
+
inSerialized || !honorToJson && rules.serializedKeys.has(key)
|
|
2551
|
+
),
|
|
2552
|
+
rules
|
|
2293
2553
|
)
|
|
2294
2554
|
);
|
|
2295
2555
|
}
|
|
@@ -2319,9 +2579,10 @@ function errorPartsHost(rules, ancestors, inSerialized) {
|
|
|
2319
2579
|
hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
|
|
2320
2580
|
};
|
|
2321
2581
|
}
|
|
2322
|
-
function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames) {
|
|
2582
|
+
function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames, headerNames) {
|
|
2323
2583
|
const rules = {
|
|
2324
2584
|
sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
|
|
2585
|
+
headerNames: new Set(Array.from(headerNames ?? fieldNames, (name) => name.toLowerCase())),
|
|
2325
2586
|
censor,
|
|
2326
2587
|
serializedKeys: new Set(serializedKeys),
|
|
2327
2588
|
errorsAsData: serializedKeys !== void 0,
|
|
@@ -2468,6 +2729,39 @@ function extraServiceFields(service) {
|
|
|
2468
2729
|
return extras;
|
|
2469
2730
|
}
|
|
2470
2731
|
|
|
2732
|
+
// src/server/utils/serialize-request.util.ts
|
|
2733
|
+
function isObject2(value) {
|
|
2734
|
+
return typeof value === "object" && value !== null;
|
|
2735
|
+
}
|
|
2736
|
+
function isRequest(value) {
|
|
2737
|
+
if (!isObject2(value)) return false;
|
|
2738
|
+
const { rawHeaders, method, socket } = value;
|
|
2739
|
+
return Array.isArray(rawHeaders) || typeof method === "string" && isObject2(socket);
|
|
2740
|
+
}
|
|
2741
|
+
function copyHeaders(headers) {
|
|
2742
|
+
return isObject2(headers) ? { ...headers } : {};
|
|
2743
|
+
}
|
|
2744
|
+
function serializeRequestValue(input, secretSegments = []) {
|
|
2745
|
+
try {
|
|
2746
|
+
if (!isRequest(input)) return input;
|
|
2747
|
+
const url = input.originalUrl ?? input.url;
|
|
2748
|
+
const socket = input.socket;
|
|
2749
|
+
return {
|
|
2750
|
+
method: input.method,
|
|
2751
|
+
url: typeof url === "string" ? scrubSecretSegments(stripQueryString(url), secretSegments) : url,
|
|
2752
|
+
headers: copyHeaders(input.headers),
|
|
2753
|
+
remoteAddress: socket?.remoteAddress
|
|
2754
|
+
};
|
|
2755
|
+
} catch {
|
|
2756
|
+
return { _unserializable: "request" };
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
function withSerializedRequest(record, secretSegments = []) {
|
|
2760
|
+
const request = record["req"];
|
|
2761
|
+
const serialized = serializeRequestValue(request, secretSegments);
|
|
2762
|
+
return serialized === request ? record : { ...record, req: serialized };
|
|
2763
|
+
}
|
|
2764
|
+
|
|
2471
2765
|
// src/server/utils/truncate-large-entries.ts
|
|
2472
2766
|
var PREVIEW_LENGTH = 200;
|
|
2473
2767
|
function createSizeBoundedSerializer(baseSerializer, maxBytes) {
|
|
@@ -2581,10 +2875,11 @@ function namesInsideErrors(options) {
|
|
|
2581
2875
|
return options.shouldDisableDefaultRedact ? void 0 : REDACT_COMMON_FIELDS;
|
|
2582
2876
|
}
|
|
2583
2877
|
function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
|
|
2584
|
-
const
|
|
2878
|
+
const allNames = [
|
|
2585
2879
|
...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
|
|
2586
2880
|
...options.redactPaths.flatMap((path) => leafNameOf(path) ?? [])
|
|
2587
|
-
]
|
|
2881
|
+
];
|
|
2882
|
+
const names = coversNames ? allNames : [];
|
|
2588
2883
|
const ownFields = ownFieldPolicyOf(options);
|
|
2589
2884
|
const walks = names.length > 0 || ownFields.safe;
|
|
2590
2885
|
if (!walks && resolveRedactOption(options) === void 0) {
|
|
@@ -2596,8 +2891,17 @@ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = tr
|
|
|
2596
2891
|
["err", ...Object.keys(options.serializers)],
|
|
2597
2892
|
void 0,
|
|
2598
2893
|
ownFields,
|
|
2599
|
-
coversNames ? void 0 : namesInsideErrors(options)
|
|
2600
|
-
|
|
2894
|
+
coversNames ? void 0 : namesInsideErrors(options),
|
|
2895
|
+
allNames
|
|
2896
|
+
) : createNameRedactor(
|
|
2897
|
+
names,
|
|
2898
|
+
options.redactCensor,
|
|
2899
|
+
void 0,
|
|
2900
|
+
void 0,
|
|
2901
|
+
ownFields,
|
|
2902
|
+
void 0,
|
|
2903
|
+
allNames
|
|
2904
|
+
);
|
|
2601
2905
|
}
|
|
2602
2906
|
function resolveRedactOption(options) {
|
|
2603
2907
|
const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
|
|
@@ -2612,6 +2916,7 @@ function buildPinoInstance(options, logContext, destinations, health) {
|
|
|
2612
2916
|
const redactSerialized = buildNameRedactor(options);
|
|
2613
2917
|
const ownFields = ownFieldPolicyOf(options);
|
|
2614
2918
|
const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
|
|
2919
|
+
const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
|
|
2615
2920
|
const serializers = {
|
|
2616
2921
|
err: bound((error) => serializeErrorValue(error, ownFields)),
|
|
2617
2922
|
...Object.fromEntries(
|
|
@@ -2659,7 +2964,10 @@ function buildPinoInstance(options, logContext, destinations, health) {
|
|
|
2659
2964
|
// sensitive, which `pino-factory.spec.ts` pins.
|
|
2660
2965
|
log: (record) => withSemconvException(
|
|
2661
2966
|
withEventName(
|
|
2662
|
-
redactRecord(
|
|
2967
|
+
redactRecord(
|
|
2968
|
+
hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
|
|
2969
|
+
true
|
|
2970
|
+
),
|
|
2663
2971
|
options.eventNameField
|
|
2664
2972
|
),
|
|
2665
2973
|
options.errorFormat
|
|
@@ -2684,16 +2992,21 @@ function buildPinoInstance(options, logContext, destinations, health) {
|
|
|
2684
2992
|
}
|
|
2685
2993
|
}
|
|
2686
2994
|
};
|
|
2687
|
-
const streams = destinations.map((destination) =>
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2995
|
+
const streams = destinations.map((destination) => {
|
|
2996
|
+
const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
|
|
2997
|
+
health.registerStream(destination, stream);
|
|
2998
|
+
return {
|
|
2999
|
+
// Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
|
|
3000
|
+
// consumer implementing `minLevel` as a throwing getter would fail the factory
|
|
3001
|
+
// and the application would never start — earlier than any fail-soft path can
|
|
3002
|
+
// contain. Unreadable and absent give the same answer: the module level.
|
|
3003
|
+
level: safeMinLevel(destination) ?? options.level,
|
|
3004
|
+
stream
|
|
3005
|
+
};
|
|
3006
|
+
});
|
|
2695
3007
|
return pino__default.default(pinoOptions, pino__default.default.multistream(streams));
|
|
2696
3008
|
}
|
|
3009
|
+
var DROP_REPORT_INTERVAL_MS = 1e4;
|
|
2697
3010
|
var DestinationHealth = class {
|
|
2698
3011
|
constructor() {
|
|
2699
3012
|
/** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
|
|
@@ -2737,6 +3050,10 @@ var DestinationHealth = class {
|
|
|
2737
3050
|
* when the last one settles.
|
|
2738
3051
|
*/
|
|
2739
3052
|
this.pendingWrites = /* @__PURE__ */ new Map();
|
|
3053
|
+
/** The `Writable` that fronts each destination, whose buffer is the queue of entries it holds. */
|
|
3054
|
+
this.streams = /* @__PURE__ */ new Map();
|
|
3055
|
+
/** Entries dropped for want of queue room, per destination, and when the last one was reported. */
|
|
3056
|
+
this.drops = /* @__PURE__ */ new Map();
|
|
2740
3057
|
/**
|
|
2741
3058
|
* The rescuer's severity index within {@link LOG_LEVEL_PRIORITY}. Starts above
|
|
2742
3059
|
* every real level so the first `markFailed` always wins the comparison.
|
|
@@ -2755,6 +3072,64 @@ var DestinationHealth = class {
|
|
|
2755
3072
|
markWriteFailed(destination) {
|
|
2756
3073
|
this.writeFailed.add(destination);
|
|
2757
3074
|
}
|
|
3075
|
+
/**
|
|
3076
|
+
* Record one entry dropped because the destination's queue was full, and say whether the drop is
|
|
3077
|
+
* due a report.
|
|
3078
|
+
*
|
|
3079
|
+
* A report is due on the first drop and then at most once every {@link DROP_REPORT_INTERVAL_MS},
|
|
3080
|
+
* so a sustained overflow costs one stderr line per window and not one per entry.
|
|
3081
|
+
*
|
|
3082
|
+
* @param destination - The destination whose queue was full.
|
|
3083
|
+
* @param now - A monotonic reading in milliseconds (`performance.now()`).
|
|
3084
|
+
* @returns The number of drops since the last report when one is due, otherwise `undefined`.
|
|
3085
|
+
*/
|
|
3086
|
+
recordDrop(destination, now) {
|
|
3087
|
+
const record = this.drops.get(destination) ?? {
|
|
3088
|
+
total: 0,
|
|
3089
|
+
unreported: 0,
|
|
3090
|
+
lastReportAt: void 0
|
|
3091
|
+
};
|
|
3092
|
+
this.drops.set(destination, record);
|
|
3093
|
+
record.total += 1;
|
|
3094
|
+
record.unreported += 1;
|
|
3095
|
+
this.writeFailed.add(destination);
|
|
3096
|
+
if (record.lastReportAt !== void 0 && now - record.lastReportAt < DROP_REPORT_INTERVAL_MS) {
|
|
3097
|
+
return void 0;
|
|
3098
|
+
}
|
|
3099
|
+
record.lastReportAt = now;
|
|
3100
|
+
const due = record.unreported;
|
|
3101
|
+
record.unreported = 0;
|
|
3102
|
+
return due;
|
|
3103
|
+
}
|
|
3104
|
+
/**
|
|
3105
|
+
* How many entries a destination has had dropped for want of queue room.
|
|
3106
|
+
*
|
|
3107
|
+
* @param destination - The destination to ask about.
|
|
3108
|
+
* @returns The count since startup, `0` when none.
|
|
3109
|
+
*/
|
|
3110
|
+
droppedTotal(destination) {
|
|
3111
|
+
return this.drops.get(destination)?.total ?? 0;
|
|
3112
|
+
}
|
|
3113
|
+
/**
|
|
3114
|
+
* Record the stream that fronts a destination, whose buffer is the queue of entries it holds.
|
|
3115
|
+
*
|
|
3116
|
+
* @param destination - The destination.
|
|
3117
|
+
* @param stream - Its `Writable` adapter, read only for the bytes it holds queued.
|
|
3118
|
+
*/
|
|
3119
|
+
registerStream(destination, stream) {
|
|
3120
|
+
this.streams.set(destination, stream);
|
|
3121
|
+
}
|
|
3122
|
+
/**
|
|
3123
|
+
* How much a destination still holds: the size of what Pino has written to its stream and the
|
|
3124
|
+
* destination has not yet taken, the write in flight included. Zero means nothing is queued.
|
|
3125
|
+
*
|
|
3126
|
+
* @param destination - The destination to ask about.
|
|
3127
|
+
* @returns The queued size in bytes of NDJSON, `0` for a
|
|
3128
|
+
* destination whose stream is not known.
|
|
3129
|
+
*/
|
|
3130
|
+
queuedSize(destination) {
|
|
3131
|
+
return this.streams.get(destination)?.queuedBytes ?? 0;
|
|
3132
|
+
}
|
|
2758
3133
|
/**
|
|
2759
3134
|
* Record that an asynchronous write to a destination has started.
|
|
2760
3135
|
*
|
|
@@ -2864,6 +3239,34 @@ var DestinationHealth = class {
|
|
|
2864
3239
|
DestinationHealth = __decorateClass([
|
|
2865
3240
|
common.Injectable()
|
|
2866
3241
|
], DestinationHealth);
|
|
3242
|
+
|
|
3243
|
+
// src/server/utils/with-timeout.util.ts
|
|
3244
|
+
var HookTimeoutError = class extends Error {
|
|
3245
|
+
constructor(timeoutMs) {
|
|
3246
|
+
super(`did not settle within ${String(timeoutMs)} ms`);
|
|
3247
|
+
this.timeoutMs = timeoutMs;
|
|
3248
|
+
this.name = "HookTimeoutError";
|
|
3249
|
+
}
|
|
3250
|
+
};
|
|
3251
|
+
function withTimeout(work, ms) {
|
|
3252
|
+
return new Promise((resolve, reject2) => {
|
|
3253
|
+
const timer = setTimeout(() => {
|
|
3254
|
+
reject2(new HookTimeoutError(ms));
|
|
3255
|
+
}, ms);
|
|
3256
|
+
const settle = (done) => (...args) => {
|
|
3257
|
+
clearTimeout(timer);
|
|
3258
|
+
done(...args);
|
|
3259
|
+
};
|
|
3260
|
+
try {
|
|
3261
|
+
Promise.resolve(work()).then(settle(resolve), settle(reject2));
|
|
3262
|
+
} catch (cause) {
|
|
3263
|
+
settle(reject2)(cause);
|
|
3264
|
+
}
|
|
3265
|
+
});
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
// src/server/services/destination-registry.service.ts
|
|
3269
|
+
var DRAIN_POLL_MS = 5;
|
|
2867
3270
|
var DestinationRegistry = class {
|
|
2868
3271
|
/**
|
|
2869
3272
|
* @param registered - Every destination declared under
|
|
@@ -2908,7 +3311,7 @@ var DestinationRegistry = class {
|
|
|
2908
3311
|
async onModuleInit() {
|
|
2909
3312
|
for (const destination of this.registered) {
|
|
2910
3313
|
try {
|
|
2911
|
-
await destination.onInit?.();
|
|
3314
|
+
await withTimeout(() => destination.onInit?.(), this.options.destinationHookTimeoutMs);
|
|
2912
3315
|
this.active.push(destination);
|
|
2913
3316
|
this.health.markHealthy(destination, this.effectiveLevelOf(destination));
|
|
2914
3317
|
} catch (cause) {
|
|
@@ -2940,12 +3343,15 @@ var DestinationRegistry = class {
|
|
|
2940
3343
|
async notifyRegistryReady() {
|
|
2941
3344
|
for (const destination of this.registered) {
|
|
2942
3345
|
try {
|
|
2943
|
-
await
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
3346
|
+
await withTimeout(
|
|
3347
|
+
() => destination.onRegistryReady?.({
|
|
3348
|
+
heldEntriesDeliveredElsewhere: this.health.deliveredByHealthySink(
|
|
3349
|
+
destination,
|
|
3350
|
+
this.effectiveLevelOf(destination)
|
|
3351
|
+
)
|
|
3352
|
+
}),
|
|
3353
|
+
this.options.destinationHookTimeoutMs
|
|
3354
|
+
);
|
|
2949
3355
|
} catch (cause) {
|
|
2950
3356
|
this.reportHookFailure(destination, cause);
|
|
2951
3357
|
}
|
|
@@ -3063,6 +3469,9 @@ var DestinationRegistry = class {
|
|
|
3063
3469
|
* point in the shutdown sequence.
|
|
3064
3470
|
*/
|
|
3065
3471
|
async onApplicationShutdown() {
|
|
3472
|
+
const startedAt = performance.now();
|
|
3473
|
+
const { timeoutMs, drainTimeoutMs } = this.options.shutdown;
|
|
3474
|
+
const deadline = startedAt + timeoutMs;
|
|
3066
3475
|
this.logger.info(
|
|
3067
3476
|
RESERVED_LOG_KEYS.LOGGER_SHUTDOWN_OK,
|
|
3068
3477
|
"BymaxLoggerModule shutting down",
|
|
@@ -3072,13 +3481,74 @@ var DestinationRegistry = class {
|
|
|
3072
3481
|
await new Promise((resolve) => {
|
|
3073
3482
|
setImmediate(resolve);
|
|
3074
3483
|
});
|
|
3484
|
+
await this.drain(Math.min(deadline, startedAt + drainTimeoutMs));
|
|
3485
|
+
const skipped = [];
|
|
3075
3486
|
for (const destination of [...this.active].reverse()) {
|
|
3487
|
+
const remaining = deadline - performance.now();
|
|
3488
|
+
if (remaining <= 0) {
|
|
3489
|
+
skipped.push(toSingleLineMessage(safeDestinationName(destination)));
|
|
3490
|
+
continue;
|
|
3491
|
+
}
|
|
3076
3492
|
try {
|
|
3077
|
-
await destination.onShutdown?.();
|
|
3493
|
+
await withTimeout(() => destination.onShutdown?.(), remaining);
|
|
3078
3494
|
} catch (cause) {
|
|
3079
3495
|
this.reportShutdownFailure(destination, cause);
|
|
3080
3496
|
}
|
|
3081
3497
|
}
|
|
3498
|
+
this.reportDropTotals();
|
|
3499
|
+
if (skipped.length > 0) {
|
|
3500
|
+
writeStderrSafely(
|
|
3501
|
+
`[DestinationRegistry] Shutdown budget of ${String(timeoutMs)} ms spent; onShutdown not called for: ${skipped.map((name) => `"${name}"`).join(", ")}
|
|
3502
|
+
`
|
|
3503
|
+
);
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
/**
|
|
3507
|
+
* Say, once, how many entries each destination had dropped for want of queue room, when any did.
|
|
3508
|
+
* It carries the name and the count and no entry content.
|
|
3509
|
+
*/
|
|
3510
|
+
reportDropTotals() {
|
|
3511
|
+
for (const destination of this.registered) {
|
|
3512
|
+
const total = this.health.droppedTotal(destination);
|
|
3513
|
+
if (total > 0) {
|
|
3514
|
+
writeStderrSafely(
|
|
3515
|
+
`[DestinationRegistry] Destination "${toSingleLineMessage(safeDestinationName(destination))}" dropped ${String(total)} entries in total because its queue was full
|
|
3516
|
+
`
|
|
3517
|
+
);
|
|
3518
|
+
}
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
/**
|
|
3522
|
+
* Wait until no active destination holds a queued entry, or the drain deadline passes.
|
|
3523
|
+
*
|
|
3524
|
+
* A destination reads its entries from a `Writable` that buffers what Pino has written, and it
|
|
3525
|
+
* takes them one at a time. `onShutdown` is its signal to flush and close, so a write that begins
|
|
3526
|
+
* after it is a write on a closed resource. The wait does not end the streams, because Pino may
|
|
3527
|
+
* still log while the application shuts down, and an entry written after the end of a stream is an
|
|
3528
|
+
* error. An entry written during the wait extends it, up to the deadline. When the deadline ends it,
|
|
3529
|
+
* one line names the destinations and their queued sizes; it carries no entry content.
|
|
3530
|
+
*
|
|
3531
|
+
* @param drainDeadline - The time, in `performance.now()` milliseconds, the wait ends at.
|
|
3532
|
+
*/
|
|
3533
|
+
async drain(drainDeadline) {
|
|
3534
|
+
for (; ; ) {
|
|
3535
|
+
const queued = this.active.filter((destination) => this.health.queuedSize(destination) > 0);
|
|
3536
|
+
if (queued.length === 0) return;
|
|
3537
|
+
const remaining = drainDeadline - performance.now();
|
|
3538
|
+
if (remaining <= 0) {
|
|
3539
|
+
const named = queued.map(
|
|
3540
|
+
(destination) => `"${toSingleLineMessage(safeDestinationName(destination))}" (${String(this.health.queuedSize(destination))})`
|
|
3541
|
+
);
|
|
3542
|
+
writeStderrSafely(
|
|
3543
|
+
`[DestinationRegistry] Shutdown drain ended with entries still queued, by size: ${named.join(", ")}
|
|
3544
|
+
`
|
|
3545
|
+
);
|
|
3546
|
+
return;
|
|
3547
|
+
}
|
|
3548
|
+
await new Promise((resolve) => {
|
|
3549
|
+
setTimeout(resolve, Math.min(DRAIN_POLL_MS, remaining));
|
|
3550
|
+
});
|
|
3551
|
+
}
|
|
3082
3552
|
}
|
|
3083
3553
|
/**
|
|
3084
3554
|
* Report a failing `onShutdown` on stderr without letting the report itself
|
|
@@ -3582,6 +4052,7 @@ exports.HttpAccessLogMiddleware = class HttpAccessLogMiddleware {
|
|
|
3582
4052
|
this.logContext = logContext;
|
|
3583
4053
|
this.isEnabled = options.http.isEnabled;
|
|
3584
4054
|
this.excludePaths = options.http.excludePaths;
|
|
4055
|
+
this.secretPathSegments = options.http.secretPathSegments;
|
|
3585
4056
|
}
|
|
3586
4057
|
/**
|
|
3587
4058
|
* Emit START, arm the terminal entry on `'close'`, and continue the chain.
|
|
@@ -3607,14 +4078,14 @@ exports.HttpAccessLogMiddleware = class HttpAccessLogMiddleware {
|
|
|
3607
4078
|
}
|
|
3608
4079
|
markRecorderActive(req);
|
|
3609
4080
|
const method = req.method;
|
|
3610
|
-
const url = normalizeUrl(target);
|
|
4081
|
+
const url = normalizeUrl(target, this.secretPathSegments);
|
|
3611
4082
|
const start = Date.now();
|
|
3612
4083
|
this.logger.info(RESERVED_LOG_KEYS.HTTP_REQUEST_START, `${method} ${url}`, readUserId(req), {
|
|
3613
4084
|
method,
|
|
3614
4085
|
url,
|
|
3615
4086
|
// Query string stripped: it may carry secrets (reset tokens, OAuth codes)
|
|
3616
4087
|
// that no key-name redaction can scrub out of a string VALUE.
|
|
3617
|
-
fullUrl: path,
|
|
4088
|
+
fullUrl: scrubSecretSegments(path, this.secretPathSegments),
|
|
3618
4089
|
// Conventional for an access log and personal data under GDPR/LGPD. Its
|
|
3619
4090
|
// fidelity is the app's to establish: behind a proxy it is only the real
|
|
3620
4091
|
// client when the app configures `trust proxy`, and a value the app has not
|
|
@@ -3679,7 +4150,12 @@ exports.HttpAccessLogMiddleware = class HttpAccessLogMiddleware {
|
|
|
3679
4150
|
recorded === void 0 ? meta : {
|
|
3680
4151
|
...meta,
|
|
3681
4152
|
errorMessage: cutIfText(
|
|
3682
|
-
|
|
4153
|
+
withoutRequestSecretsIfText(
|
|
4154
|
+
recorded.error.message,
|
|
4155
|
+
this.secretPathSegments,
|
|
4156
|
+
req.originalUrl,
|
|
4157
|
+
req.url
|
|
4158
|
+
)
|
|
3683
4159
|
)
|
|
3684
4160
|
}
|
|
3685
4161
|
);
|