@bymax-one/nest-logger 1.4.10 → 1.4.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -1
- package/README.md +53 -23
- package/dist/server/index.cjs +800 -612
- package/dist/server/index.d.cts +41 -1
- package/dist/server/index.d.ts +41 -1
- package/dist/server/index.mjs +800 -612
- package/package.json +1 -1
package/dist/server/index.cjs
CHANGED
|
@@ -4,12 +4,12 @@ var common = require('@nestjs/common');
|
|
|
4
4
|
var core = require('@nestjs/core');
|
|
5
5
|
var util = require('util');
|
|
6
6
|
var rxjs = require('rxjs');
|
|
7
|
+
var crypto = require('crypto');
|
|
8
|
+
var async_hooks = require('async_hooks');
|
|
7
9
|
var pino = require('pino');
|
|
8
10
|
var module$1 = require('module');
|
|
9
11
|
var path = require('path');
|
|
10
12
|
var stream = require('stream');
|
|
11
|
-
var async_hooks = require('async_hooks');
|
|
12
|
-
var crypto = require('crypto');
|
|
13
13
|
|
|
14
14
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
15
15
|
|
|
@@ -83,6 +83,8 @@ function applyDefaults(options) {
|
|
|
83
83
|
}),
|
|
84
84
|
otel: Object.freeze(otel),
|
|
85
85
|
maxEntrySizeBytes: options.maxEntrySizeBytes ?? DEFAULT_MAX_ENTRY_SIZE_BYTES,
|
|
86
|
+
errorOwnFields: options.errorOwnFields ?? "all",
|
|
87
|
+
errorOwnFieldNames: Object.freeze([...options.errorOwnFieldNames ?? []]),
|
|
86
88
|
serializers: Object.freeze({ ...options.serializers ?? {} }),
|
|
87
89
|
timestamp: options.timestamp ?? (() => (/* @__PURE__ */ new Date()).toISOString())
|
|
88
90
|
};
|
|
@@ -227,6 +229,20 @@ function validateCustomization(options) {
|
|
|
227
229
|
}
|
|
228
230
|
}
|
|
229
231
|
}
|
|
232
|
+
function validateErrorFields(options) {
|
|
233
|
+
const mode = options.errorOwnFields;
|
|
234
|
+
if (mode !== void 0 && mode !== "all" && mode !== "safe") {
|
|
235
|
+
reject("errorOwnFields", "must be 'all' or 'safe'", mode);
|
|
236
|
+
}
|
|
237
|
+
const names = options.errorOwnFieldNames;
|
|
238
|
+
if (names === void 0) return;
|
|
239
|
+
if (!Array.isArray(names)) reject("errorOwnFieldNames", "must be an array of strings", names);
|
|
240
|
+
names.forEach((entry, index) => {
|
|
241
|
+
if (!isNonEmptyString(entry)) {
|
|
242
|
+
reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry);
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
}
|
|
230
246
|
var UNREADABLE = /* @__PURE__ */ Symbol("unreadable");
|
|
231
247
|
function readMember(destination, key) {
|
|
232
248
|
try {
|
|
@@ -298,6 +314,7 @@ function validateOptions(options) {
|
|
|
298
314
|
validateCore(options);
|
|
299
315
|
validateClosedSets(options);
|
|
300
316
|
validateCustomization(options);
|
|
317
|
+
validateErrorFields(options);
|
|
301
318
|
validateDestinations(options);
|
|
302
319
|
validateHttp(options);
|
|
303
320
|
validateOtel(options);
|
|
@@ -353,6 +370,20 @@ var PROTOTYPE_POLLUTING_KEYS = /* @__PURE__ */ new Set([
|
|
|
353
370
|
"prototype"
|
|
354
371
|
]);
|
|
355
372
|
|
|
373
|
+
// src/server/utils/bounded-text.util.ts
|
|
374
|
+
var MAX_TEXT_LENGTH = 16384;
|
|
375
|
+
var TEXT_TRUNCATED = "\u2026[truncated]";
|
|
376
|
+
function cutIfText(value) {
|
|
377
|
+
return typeof value === "string" ? cutText(value) : value;
|
|
378
|
+
}
|
|
379
|
+
function cutText(text, alreadyCut = false) {
|
|
380
|
+
if (!alreadyCut && text.length <= MAX_TEXT_LENGTH) return text;
|
|
381
|
+
const head = text.slice(0, MAX_TEXT_LENGTH);
|
|
382
|
+
const last = head.charCodeAt(head.length - 1);
|
|
383
|
+
const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
|
|
384
|
+
return whole + TEXT_TRUNCATED;
|
|
385
|
+
}
|
|
386
|
+
|
|
356
387
|
// src/server/utils/escape-log-text.util.ts
|
|
357
388
|
var LINE_TERMINATORS = /* @__PURE__ */ new Set(["\r", "\n", "\x85", "\u2028", "\u2029"]);
|
|
358
389
|
var UNSAFE_IN_SINGLE_LINE = /[\u0000-\u0008\u000A-\u001F\u007F-\u009F\u2028\u2029]/g;
|
|
@@ -366,14 +397,35 @@ function toSingleLineMessage(text) {
|
|
|
366
397
|
(char) => LINE_TERMINATORS.has(char) ? "\\n" : toEscapeSequence(char)
|
|
367
398
|
);
|
|
368
399
|
}
|
|
400
|
+
function toBoundedMessage(text) {
|
|
401
|
+
return cutText(toSingleLineMessage(text));
|
|
402
|
+
}
|
|
369
403
|
function escapeControlCharacters(text) {
|
|
370
404
|
return text.replace(UNSAFE_IN_MULTILINE, toEscapeSequence);
|
|
371
405
|
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
406
|
+
function isError(value) {
|
|
407
|
+
try {
|
|
408
|
+
return util.types.isNativeError(value) || value instanceof Error;
|
|
409
|
+
} catch {
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
var DEFAULT_SAFE_ERROR_FIELDS = [
|
|
414
|
+
"code",
|
|
415
|
+
"errno",
|
|
416
|
+
"syscall",
|
|
417
|
+
"signal",
|
|
418
|
+
"status",
|
|
419
|
+
"statusCode",
|
|
420
|
+
"address",
|
|
421
|
+
"port",
|
|
422
|
+
"hostname",
|
|
423
|
+
"constraint",
|
|
424
|
+
"table",
|
|
425
|
+
"column",
|
|
426
|
+
"schema",
|
|
427
|
+
"routine"
|
|
428
|
+
];
|
|
377
429
|
var DERIVED_ERROR_FIELDS = /* @__PURE__ */ new Set([
|
|
378
430
|
"name",
|
|
379
431
|
"message",
|
|
@@ -381,15 +433,47 @@ var DERIVED_ERROR_FIELDS = /* @__PURE__ */ new Set([
|
|
|
381
433
|
"cause",
|
|
382
434
|
"errors"
|
|
383
435
|
]);
|
|
436
|
+
var ALL_OWN_FIELDS = { safe: false, names: /* @__PURE__ */ new Set() };
|
|
437
|
+
function createOwnFieldPolicy(mode, extraNames) {
|
|
438
|
+
if (mode === "all") return ALL_OWN_FIELDS;
|
|
439
|
+
return { safe: true, names: /* @__PURE__ */ new Set([...DEFAULT_SAFE_ERROR_FIELDS, ...extraNames]) };
|
|
440
|
+
}
|
|
441
|
+
function allowsOwnField(policy, key) {
|
|
442
|
+
return !policy.safe || DERIVED_ERROR_FIELDS.has(key) || key === "_errorFieldsIncomplete" || policy.names.has(key);
|
|
443
|
+
}
|
|
444
|
+
var TYPED_ARRAY_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(
|
|
445
|
+
Object.getPrototypeOf(Uint8Array.prototype),
|
|
446
|
+
"byteLength"
|
|
447
|
+
)?.get;
|
|
448
|
+
var DATA_VIEW_BYTE_LENGTH = Reflect.getOwnPropertyDescriptor(DataView.prototype, "byteLength")?.get;
|
|
449
|
+
function binaryMarker(view) {
|
|
450
|
+
const size = util.types.isDataView(view) ? DATA_VIEW_BYTE_LENGTH.call(view) : TYPED_ARRAY_BYTE_LENGTH.call(view);
|
|
451
|
+
return `[Binary ${size} bytes]`;
|
|
452
|
+
}
|
|
453
|
+
function withBinaryAsSize(value) {
|
|
454
|
+
if (ArrayBuffer.isView(value)) return binaryMarker(value);
|
|
455
|
+
if (!Array.isArray(value) || !value.some((member) => ArrayBuffer.isView(member))) return value;
|
|
456
|
+
return value.map(
|
|
457
|
+
(member) => ArrayBuffer.isView(member) ? binaryMarker(member) : member
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// src/server/utils/sanitize-error.util.ts
|
|
462
|
+
var DEFAULT_MAX_CAUSE_DEPTH = 3;
|
|
463
|
+
var MAX_AGGREGATE_ERRORS = 10;
|
|
464
|
+
var CIRCULAR_SENTINEL = "[Circular]";
|
|
384
465
|
function sanitizeError(err, options) {
|
|
385
|
-
const maxCauseDepth = DEFAULT_MAX_CAUSE_DEPTH;
|
|
386
|
-
return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0,
|
|
466
|
+
const maxCauseDepth = options?.maxCauseDepth ?? DEFAULT_MAX_CAUSE_DEPTH;
|
|
467
|
+
return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0, {
|
|
468
|
+
maxDepth: maxCauseDepth,
|
|
469
|
+
ownFields: options?.ownFields ?? ALL_OWN_FIELDS
|
|
470
|
+
});
|
|
387
471
|
}
|
|
388
472
|
function isErrorLike(value) {
|
|
389
473
|
try {
|
|
390
474
|
return readsAsError(value);
|
|
391
475
|
} catch {
|
|
392
|
-
return
|
|
476
|
+
return isError(value);
|
|
393
477
|
}
|
|
394
478
|
}
|
|
395
479
|
function readsAsError(value) {
|
|
@@ -399,40 +483,32 @@ function readsAsError(value) {
|
|
|
399
483
|
const candidate = value;
|
|
400
484
|
return typeof candidate.name === "string" && typeof candidate.message === "string";
|
|
401
485
|
}
|
|
402
|
-
function
|
|
403
|
-
try {
|
|
404
|
-
return value instanceof Error;
|
|
405
|
-
} catch {
|
|
406
|
-
return false;
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
function toSanitizedError(value, seen, depth2, maxDepth) {
|
|
486
|
+
function toSanitizedError(value, seen, depth2, walk2) {
|
|
410
487
|
try {
|
|
411
488
|
if (!readsAsError(value)) {
|
|
412
|
-
return { name: "UnknownError", message: String(value) };
|
|
489
|
+
return { name: "UnknownError", message: cutText(String(value)) };
|
|
413
490
|
}
|
|
414
491
|
seen.add(value);
|
|
415
|
-
const result = { name: value.name, message: value.message };
|
|
492
|
+
const result = { name: cutText(value.name), message: cutText(value.message) };
|
|
416
493
|
const stack = readOptional(() => value.stack, result);
|
|
417
494
|
if (stack !== void 0) {
|
|
418
495
|
result.stack = scrubStack(stack);
|
|
419
496
|
}
|
|
420
|
-
const isAtDepthLimit = depth2 >= maxDepth;
|
|
497
|
+
const isAtDepthLimit = depth2 >= walk2.maxDepth;
|
|
421
498
|
const cause = readOptional(() => value.cause, result);
|
|
422
499
|
if (cause !== void 0) {
|
|
423
|
-
result.cause = isAtDepthLimit ? createDepthMarker() : toSanitizedChild(cause, seen, depth2 + 1,
|
|
500
|
+
result.cause = isAtDepthLimit ? createDepthMarker() : toSanitizedChild(cause, seen, depth2 + 1, walk2);
|
|
424
501
|
}
|
|
425
502
|
const aggregated = readAggregatedErrors(value);
|
|
426
503
|
if (aggregated !== void 0) {
|
|
427
504
|
const capped = aggregated.slice(0, MAX_AGGREGATE_ERRORS);
|
|
428
505
|
result.errors = capped.map(
|
|
429
|
-
(inner) => isAtDepthLimit ? createDepthMarker() : toSanitizedChild(inner, seen, depth2 + 1,
|
|
506
|
+
(inner) => isAtDepthLimit ? createDepthMarker() : toSanitizedChild(inner, seen, depth2 + 1, walk2)
|
|
430
507
|
);
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
}
|
|
508
|
+
const left = carriedOmitted(aggregated) || aggregated.length - MAX_AGGREGATE_ERRORS;
|
|
509
|
+
if (left > 0) result.errors.push(createWidthMarker(left));
|
|
434
510
|
}
|
|
435
|
-
assignOwnErrorFields(result, value);
|
|
511
|
+
assignOwnErrorFields(result, value, walk2.ownFields);
|
|
436
512
|
return result;
|
|
437
513
|
} catch {
|
|
438
514
|
return { name: "SanitizeFailed", message: "Failed to sanitize the thrown value" };
|
|
@@ -446,21 +522,27 @@ function isDatabaseError(source) {
|
|
|
446
522
|
const code = Object.getOwnPropertyDescriptor(source, "code")?.value;
|
|
447
523
|
return typeof code === "string" && SQLSTATE.test(code);
|
|
448
524
|
}
|
|
449
|
-
function ownFieldForLog(source, key, value) {
|
|
525
|
+
function ownFieldForLog(source, key, value, policy = ALL_OWN_FIELDS) {
|
|
526
|
+
if (!allowsOwnField(policy, key)) return OMIT_OWN_FIELD;
|
|
450
527
|
if (ARGUMENT_FIELDS.has(key.toLowerCase())) return OMIT_OWN_FIELD;
|
|
451
528
|
if (DATABASE_VALUE_FIELDS.has(key) && isDatabaseError(source)) return OMIT_OWN_FIELD;
|
|
452
|
-
if (key !== "command" || typeof value !== "object" || value === null)
|
|
529
|
+
if (key !== "command" || typeof value !== "object" || value === null) {
|
|
530
|
+
return withBinaryAsSize(value);
|
|
531
|
+
}
|
|
453
532
|
const name = Object.getOwnPropertyDescriptor(value, "name")?.value;
|
|
454
533
|
return typeof name === "string" ? { name } : OMIT_OWN_FIELD;
|
|
455
534
|
}
|
|
456
|
-
function
|
|
535
|
+
function defineErrorField(target, key, value) {
|
|
536
|
+
Object.defineProperty(target, key, { value, enumerable: true });
|
|
537
|
+
}
|
|
538
|
+
function assignOwnErrorFields(target, source, policy = ALL_OWN_FIELDS) {
|
|
457
539
|
try {
|
|
458
540
|
const own = Array.isArray(source) ? {} : source;
|
|
459
541
|
for (const [key, field] of Object.entries(own)) {
|
|
460
|
-
const value = ownFieldForLog(own, key, field);
|
|
542
|
+
const value = ownFieldForLog(own, key, field, policy);
|
|
461
543
|
if (value === OMIT_OWN_FIELD) continue;
|
|
462
544
|
if (!Object.hasOwn(target, key) && !DERIVED_ERROR_FIELDS.has(key)) {
|
|
463
|
-
|
|
545
|
+
defineErrorField(target, key, value);
|
|
464
546
|
}
|
|
465
547
|
}
|
|
466
548
|
} catch {
|
|
@@ -478,34 +560,32 @@ function readOptional(read, node) {
|
|
|
478
560
|
return void 0;
|
|
479
561
|
}
|
|
480
562
|
}
|
|
481
|
-
function toSanitizedChild(value, seen, depth2,
|
|
563
|
+
function toSanitizedChild(value, seen, depth2, walk2) {
|
|
482
564
|
if (isObject(value) && seen.has(value)) {
|
|
483
565
|
return CIRCULAR_SENTINEL;
|
|
484
566
|
}
|
|
485
|
-
return toSanitizedError(value, seen, depth2,
|
|
567
|
+
return toSanitizedError(value, seen, depth2, walk2);
|
|
568
|
+
}
|
|
569
|
+
function carriedOmitted(list) {
|
|
570
|
+
if (list.length > MAX_AGGREGATE_ERRORS + 1) return 0;
|
|
571
|
+
try {
|
|
572
|
+
const cut = list.at(MAX_AGGREGATE_ERRORS);
|
|
573
|
+
const omitted = cut?._truncated === true ? cut._omitted : void 0;
|
|
574
|
+
return Number.isInteger(omitted) ? Math.max(omitted, 0) : 0;
|
|
575
|
+
} catch {
|
|
576
|
+
return 0;
|
|
577
|
+
}
|
|
486
578
|
}
|
|
487
579
|
function readAggregatedErrors(value) {
|
|
488
580
|
const candidate = value.errors;
|
|
489
581
|
return Array.isArray(candidate) ? candidate : void 0;
|
|
490
582
|
}
|
|
491
|
-
var
|
|
492
|
-
var STACK_TRUNCATED = "\u2026[truncated]";
|
|
493
|
-
var MAX_STACK_SCAN = 8 * MAX_STACK_LENGTH;
|
|
583
|
+
var MAX_STACK_SCAN = 8 * MAX_TEXT_LENGTH;
|
|
494
584
|
function scrubStack(stack) {
|
|
495
585
|
const scrubbed = escapeControlCharacters(
|
|
496
586
|
stack.slice(0, MAX_STACK_SCAN).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
|
|
497
587
|
);
|
|
498
|
-
return
|
|
499
|
-
}
|
|
500
|
-
function cutAtLimit(text, alreadyCut) {
|
|
501
|
-
if (!alreadyCut && text.length <= MAX_STACK_LENGTH) return text;
|
|
502
|
-
const head = text.slice(0, MAX_STACK_LENGTH);
|
|
503
|
-
const last = head.charCodeAt(head.length - 1);
|
|
504
|
-
const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
|
|
505
|
-
return whole + STACK_TRUNCATED;
|
|
506
|
-
}
|
|
507
|
-
function cutStack(stack) {
|
|
508
|
-
return cutAtLimit(stack, false);
|
|
588
|
+
return cutText(scrubbed, stack.length > MAX_STACK_SCAN);
|
|
509
589
|
}
|
|
510
590
|
function isObject(value) {
|
|
511
591
|
return typeof value === "object" && value !== null;
|
|
@@ -540,14 +620,14 @@ function withoutOwnedKeys(metadata) {
|
|
|
540
620
|
}
|
|
541
621
|
function safeErrorMessage(error) {
|
|
542
622
|
try {
|
|
543
|
-
return
|
|
623
|
+
return toBoundedMessage(String(error.message));
|
|
544
624
|
} catch {
|
|
545
625
|
return "Unreadable error message";
|
|
546
626
|
}
|
|
547
627
|
}
|
|
548
628
|
function safeLogMessage(message) {
|
|
549
629
|
try {
|
|
550
|
-
return
|
|
630
|
+
return toBoundedMessage(typeof message === "string" ? message : String(message));
|
|
551
631
|
} catch {
|
|
552
632
|
return "Unreadable log message";
|
|
553
633
|
}
|
|
@@ -621,7 +701,7 @@ exports.PinoLoggerService = class PinoLoggerService {
|
|
|
621
701
|
const context = typeof optionalParams[1] === "string" ? optionalParams[1] : this.context;
|
|
622
702
|
const payload = {};
|
|
623
703
|
assignIfDefined(payload, "context", context);
|
|
624
|
-
assignIfDefined(payload, "stack", stack === void 0 ? stack :
|
|
704
|
+
assignIfDefined(payload, "stack", stack === void 0 ? stack : cutText(stack));
|
|
625
705
|
assignIfDefined(payload, "err", findErrorParam(optionalParams));
|
|
626
706
|
this.pino.error(payload, safeLogMessage(message));
|
|
627
707
|
}
|
|
@@ -767,7 +847,7 @@ exports.PinoLoggerService = class PinoLoggerService {
|
|
|
767
847
|
const payload = { ...withoutOwnedKeys(metadata), logKey };
|
|
768
848
|
assignIfDefined(payload, "userId", userId);
|
|
769
849
|
assignIfDefined(payload, "context", this.context);
|
|
770
|
-
const line =
|
|
850
|
+
const line = toBoundedMessage(message);
|
|
771
851
|
if (level === "info") {
|
|
772
852
|
this.pino.info(payload, line);
|
|
773
853
|
} else {
|
|
@@ -1000,7 +1080,7 @@ function readRecordedError(req) {
|
|
|
1000
1080
|
return Reflect.get(req, RECORDED_ERROR);
|
|
1001
1081
|
}
|
|
1002
1082
|
function toError(thrown) {
|
|
1003
|
-
return thrown
|
|
1083
|
+
return isError(thrown) ? thrown : new Error(String(thrown));
|
|
1004
1084
|
}
|
|
1005
1085
|
function readUserId(req) {
|
|
1006
1086
|
return req.user?.sub ?? req.user?.id;
|
|
@@ -1161,7 +1241,7 @@ exports.HttpLoggingInterceptor = class HttpLoggingInterceptor {
|
|
|
1161
1241
|
RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
|
|
1162
1242
|
`${method} ${url} \u2192 ${statusCode}`,
|
|
1163
1243
|
userId,
|
|
1164
|
-
{ method, url, statusCode, duration, errorMessage: err.message }
|
|
1244
|
+
{ method, url, statusCode, duration, errorMessage: cutIfText(err.message) }
|
|
1165
1245
|
);
|
|
1166
1246
|
}
|
|
1167
1247
|
return;
|
|
@@ -1206,140 +1286,437 @@ var {
|
|
|
1206
1286
|
// disabled" without a dead nullish branch.
|
|
1207
1287
|
global: extras.isGlobal !== false
|
|
1208
1288
|
})).build();
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
{ length: REDACT_MAX_DEPTH },
|
|
1214
|
-
(_, idx) => "*" + ".*".repeat(idx)
|
|
1215
|
-
);
|
|
1216
|
-
var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
|
|
1217
|
-
var REDACT_COMMON_FIELDS = [
|
|
1218
|
-
// Passwords (5)
|
|
1219
|
-
"password",
|
|
1220
|
-
"passwordHash",
|
|
1221
|
-
"passwordConfirm",
|
|
1222
|
-
"newPassword",
|
|
1223
|
-
"oldPassword",
|
|
1224
|
-
// Tokens (6)
|
|
1225
|
-
"token",
|
|
1226
|
-
"accessToken",
|
|
1227
|
-
"refreshToken",
|
|
1228
|
-
"idToken",
|
|
1229
|
-
"apiKey",
|
|
1230
|
-
"apiSecret",
|
|
1231
|
-
// MFA (3)
|
|
1232
|
-
"mfaSecret",
|
|
1233
|
-
"mfaRecoveryCodes",
|
|
1234
|
-
"totpSecret",
|
|
1235
|
-
// Payment / PCI DSS (5)
|
|
1236
|
-
"cardNumber",
|
|
1237
|
-
"cardCvv",
|
|
1238
|
-
"cvv",
|
|
1239
|
-
"cvc",
|
|
1240
|
-
"cardExpiry",
|
|
1241
|
-
// Personal documents — BR / LGPD (3)
|
|
1242
|
-
"cpf",
|
|
1243
|
-
"cnpj",
|
|
1244
|
-
"rg",
|
|
1245
|
-
// Generic secrets (4) — the most common short-form credential field names
|
|
1246
|
-
"secret",
|
|
1247
|
-
"clientSecret",
|
|
1248
|
-
"signingSecret",
|
|
1249
|
-
"privateKey",
|
|
1250
|
-
// Conservative PII (1) — consumer can disable if logging email is justified
|
|
1251
|
-
"email",
|
|
1252
|
-
// Credential-bearing HTTP header names (5). These also appear in
|
|
1253
|
-
// {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
|
|
1254
|
-
// shapes — which covered ONLY those two shapes. A headers bag logged under any
|
|
1255
|
-
// other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
|
|
1256
|
-
// common things written while debugging an integration) wrote the bearer token
|
|
1257
|
-
// in clear. Listed here as bare names, they are caught wherever they appear.
|
|
1258
|
-
// Node lower-cases inbound header names, so the lower-case spelling is the one
|
|
1259
|
-
// that can actually reach a log.
|
|
1260
|
-
"authorization",
|
|
1261
|
-
"cookie",
|
|
1262
|
-
"set-cookie",
|
|
1263
|
-
"x-api-key",
|
|
1264
|
-
"x-auth-token"
|
|
1265
|
-
];
|
|
1266
|
-
var REDACT_ABSOLUTE_PATHS = [
|
|
1267
|
-
"req.headers.authorization",
|
|
1268
|
-
"req.headers.cookie",
|
|
1269
|
-
'req.headers["x-api-key"]',
|
|
1270
|
-
'req.headers["x-auth-token"]',
|
|
1271
|
-
'res.headers["set-cookie"]'
|
|
1272
|
-
];
|
|
1273
|
-
var DEFAULT_REDACT_PATHS = [
|
|
1274
|
-
...REDACT_COMMON_FIELDS,
|
|
1275
|
-
...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
|
|
1276
|
-
...REDACT_ABSOLUTE_PATHS
|
|
1277
|
-
];
|
|
1278
|
-
|
|
1279
|
-
// src/server/utils/report-destination-failure.util.ts
|
|
1280
|
-
function reportDestinationFailure(logKey, name, cause, msg) {
|
|
1281
|
-
writeStderrSafely(
|
|
1282
|
-
JSON.stringify({
|
|
1283
|
-
level: "error",
|
|
1284
|
-
logKey,
|
|
1285
|
-
destination: toSingleLineMessage(name),
|
|
1286
|
-
err: describeCause(cause),
|
|
1287
|
-
msg: toSingleLineMessage(msg)
|
|
1288
|
-
}) + "\n"
|
|
1289
|
-
);
|
|
1290
|
-
}
|
|
1291
|
-
var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
|
|
1292
|
-
function describeCause(cause) {
|
|
1293
|
-
try {
|
|
1294
|
-
return cause instanceof Error ? {
|
|
1295
|
-
type: toSingleLineMessage(String(cause.name)),
|
|
1296
|
-
message: toSingleLineMessage(String(cause.message))
|
|
1297
|
-
} : { type: "UnknownError", message: toSingleLineMessage(String(cause)) };
|
|
1298
|
-
} catch {
|
|
1299
|
-
return UNREADABLE_CAUSE;
|
|
1289
|
+
var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
|
|
1290
|
+
exports.LogContextService = class LogContextService {
|
|
1291
|
+
constructor() {
|
|
1292
|
+
this.als = new async_hooks.AsyncLocalStorage();
|
|
1300
1293
|
}
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1294
|
+
/**
|
|
1295
|
+
* Run `callback` inside a fresh context scope. Every log emitted
|
|
1296
|
+
* synchronously or asynchronously within the callback inherits `context`.
|
|
1297
|
+
*
|
|
1298
|
+
* **A nested `run()` REPLACES the enclosing context, it does not extend it.**
|
|
1299
|
+
* The scope starts from `context` alone, so a field an outer scope had set —
|
|
1300
|
+
* a `tenantId` resolved at the edge, say — is absent for the whole inner
|
|
1301
|
+
* scope: nothing throws, `get()` simply returns `undefined`, and the field is
|
|
1302
|
+
* missing from every entry the callback emits. Reach for {@link runMerged}
|
|
1303
|
+
* when the inner scope should extend the outer one.
|
|
1304
|
+
*
|
|
1305
|
+
* Replacement is the deliberate default because the opposite leaks: a
|
|
1306
|
+
* background job started inside a request scope would silently inherit the
|
|
1307
|
+
* caller's `userId` and attribute its entries to a user who never triggered
|
|
1308
|
+
* it. A missing field is visibly missing; an inherited one is wrong while
|
|
1309
|
+
* looking right.
|
|
1310
|
+
*
|
|
1311
|
+
* @typeParam T - Return type of the callback.
|
|
1312
|
+
* @param context - Initial context bag for the scope. Becomes the WHOLE scope.
|
|
1313
|
+
* @param callback - Function executed within the scope.
|
|
1314
|
+
* @returns Whatever `callback` returns.
|
|
1315
|
+
* @example
|
|
1316
|
+
* logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
|
|
1317
|
+
* await userService.create(dto) // logs carry requestId + tenantId
|
|
1318
|
+
* })
|
|
1319
|
+
*/
|
|
1320
|
+
run(context, callback) {
|
|
1321
|
+
return this.als.run(this.sanitizeContext(context), callback);
|
|
1307
1322
|
}
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1323
|
+
/**
|
|
1324
|
+
* Run `callback` inside a scope that EXTENDS the enclosing one: the active
|
|
1325
|
+
* context's fields are carried in, and `context` overrides them key by key.
|
|
1326
|
+
*
|
|
1327
|
+
* The explicit counterpart to {@link run}'s replacement semantics, for the
|
|
1328
|
+
* case where an inner scope is genuinely a refinement of the outer — adding a
|
|
1329
|
+
* `userId` once authentication resolved it, without having to restate the
|
|
1330
|
+
* `requestId` the middleware already set.
|
|
1331
|
+
*
|
|
1332
|
+
* Outside any scope there is nothing to merge and this behaves exactly like
|
|
1333
|
+
* {@link run}. Writes inside the new scope never reach the enclosing one: the
|
|
1334
|
+
* merge produces a fresh object, so the outer context is intact after the
|
|
1335
|
+
* callback returns.
|
|
1336
|
+
*
|
|
1337
|
+
* @typeParam T - Return type of the callback.
|
|
1338
|
+
* @param context - Fields to add or override on top of the active context.
|
|
1339
|
+
* @param callback - Function executed within the merged scope.
|
|
1340
|
+
* @returns Whatever `callback` returns.
|
|
1341
|
+
* @example
|
|
1342
|
+
* logContext.run({ requestId: 'r_1' }, () => {
|
|
1343
|
+
* logContext.runMerged({ userId: 'u_1' }, () => {
|
|
1344
|
+
* logContext.get('requestId') // 'r_1' — carried in from the outer scope
|
|
1345
|
+
* })
|
|
1346
|
+
* })
|
|
1347
|
+
*/
|
|
1348
|
+
runMerged(context, callback) {
|
|
1349
|
+
const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
|
|
1350
|
+
return this.als.run(merged, callback);
|
|
1316
1351
|
}
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1352
|
+
/**
|
|
1353
|
+
* Read the active context, or `undefined` when called outside any scope.
|
|
1354
|
+
*
|
|
1355
|
+
* @returns The active `LogContext`, or `undefined`.
|
|
1356
|
+
*/
|
|
1357
|
+
getStore() {
|
|
1358
|
+
return this.als.getStore();
|
|
1322
1359
|
}
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
const
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1360
|
+
/**
|
|
1361
|
+
* Add or override a single field on the active context.
|
|
1362
|
+
*
|
|
1363
|
+
* @param key - Field name to set.
|
|
1364
|
+
* @param value - Field value.
|
|
1365
|
+
* @throws Error When called outside a `run()` scope, or with a prototype-polluting key.
|
|
1366
|
+
*/
|
|
1367
|
+
set(key, value) {
|
|
1368
|
+
const store = this.als.getStore();
|
|
1369
|
+
if (!store) {
|
|
1370
|
+
throw new Error("[LogContextService] set() called outside run() scope");
|
|
1371
|
+
}
|
|
1372
|
+
if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
1373
|
+
throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
|
|
1374
|
+
}
|
|
1375
|
+
Reflect.set(store, key, value);
|
|
1335
1376
|
}
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1377
|
+
/**
|
|
1378
|
+
* Read a single field from the active context.
|
|
1379
|
+
*
|
|
1380
|
+
* @typeParam T - Expected value type (caller-asserted).
|
|
1381
|
+
* @param key - Field name to read.
|
|
1382
|
+
* @returns The value cast to `T`, or `undefined` when unset / out of scope.
|
|
1383
|
+
*/
|
|
1384
|
+
get(key) {
|
|
1385
|
+
const store = this.als.getStore();
|
|
1386
|
+
if (!store) {
|
|
1387
|
+
return void 0;
|
|
1388
|
+
}
|
|
1389
|
+
return Reflect.get(store, key);
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Strip prototype-polluting keys from a caller-supplied context so an own
|
|
1393
|
+
* `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
|
|
1394
|
+
* untrusted payload) can never reach the store — and, via the trace mixin's
|
|
1395
|
+
* `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
|
|
1396
|
+
* but drops the key rather than throwing: a logging concern must never crash
|
|
1397
|
+
* the request that produced it.
|
|
1398
|
+
*
|
|
1399
|
+
* @param context - The raw context bag passed to `run()`.
|
|
1400
|
+
* @returns A shallow copy with any forbidden keys removed.
|
|
1401
|
+
*/
|
|
1402
|
+
sanitizeContext(context) {
|
|
1403
|
+
const safe = {};
|
|
1404
|
+
for (const key of Object.keys(context)) {
|
|
1405
|
+
if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
1406
|
+
Reflect.set(safe, key, Reflect.get(context, key));
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
return safe;
|
|
1410
|
+
}
|
|
1411
|
+
};
|
|
1412
|
+
exports.LogContextService = __decorateClass([
|
|
1413
|
+
common.Injectable()
|
|
1414
|
+
], exports.LogContextService);
|
|
1415
|
+
|
|
1416
|
+
// src/server/middlewares/request-id.middleware.ts
|
|
1417
|
+
var REQUEST_ID_HEADER = "x-request-id";
|
|
1418
|
+
var MAX_CORRELATION_ID_LENGTH = 256;
|
|
1419
|
+
var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
|
|
1420
|
+
var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
|
|
1421
|
+
function isAcceptableHeaderValue(value) {
|
|
1422
|
+
return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
|
|
1423
|
+
}
|
|
1424
|
+
exports.RequestIdMiddleware = class RequestIdMiddleware {
|
|
1425
|
+
/**
|
|
1426
|
+
* @param logContext - The AsyncLocalStorage-backed context service. Injected by
|
|
1427
|
+
* token explicitly: the package is bundled without `emitDecoratorMetadata`,
|
|
1428
|
+
* so implicit class-type injection would not resolve.
|
|
1429
|
+
* @param options - Resolved module options (read for `http.tenantIdHeader` and
|
|
1430
|
+
* `http.shouldGenerateRequestId`).
|
|
1431
|
+
*/
|
|
1432
|
+
constructor(logContext, options) {
|
|
1433
|
+
this.logContext = logContext;
|
|
1434
|
+
this.tenantIdHeader = options.http.tenantIdHeader;
|
|
1435
|
+
this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* Echo or mint the `x-request-id`, expose it on the response, and run the
|
|
1439
|
+
* remainder of the request inside its own log-context scope.
|
|
1440
|
+
*
|
|
1441
|
+
* Idempotent: mounting this middleware twice on the same request mints one id,
|
|
1442
|
+
* not two. The request gets its OWN store, started from the enclosing scope's
|
|
1443
|
+
* correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
|
|
1444
|
+
* else, because no other field can be known to belong to this request.
|
|
1445
|
+
*
|
|
1446
|
+
* An enclosing scope's `requestId` is never adopted and never echoed: adoption
|
|
1447
|
+
* reads a value this middleware recorded on the REQUEST, which a scope opened
|
|
1448
|
+
* elsewhere does not have. What the two generation modes do with one, measured
|
|
1449
|
+
* on two requests sharing a long-lived enclosing scope:
|
|
1450
|
+
*
|
|
1451
|
+
* - `shouldGenerateRequestId: true` (default) — each request mints its own
|
|
1452
|
+
* id, the two requests differ, and the enclosing value reaches neither the
|
|
1453
|
+
* header nor the entries.
|
|
1454
|
+
* - `shouldGenerateRequestId: false` with no inbound header — nothing is
|
|
1455
|
+
* minted, so the request scope inherits the enclosing `requestId` and every
|
|
1456
|
+
* request inside that scope logs under it. No header is exposed. That is
|
|
1457
|
+
* the consumer's own scope being inherited, not correlation being reused,
|
|
1458
|
+
* and it is the configuration that says the gateway owns the id.
|
|
1459
|
+
*
|
|
1460
|
+
* @param req - The incoming request (Express satisfies the contract).
|
|
1461
|
+
* @param res - The outgoing response (Express satisfies the contract).
|
|
1462
|
+
* @param next - The next handler in the chain.
|
|
1463
|
+
*/
|
|
1464
|
+
use(req, res, next) {
|
|
1465
|
+
if (isCorrelationOpened(req)) {
|
|
1466
|
+
const ownRequestId = readOwnRequestId(req);
|
|
1467
|
+
if (ownRequestId !== void 0) {
|
|
1468
|
+
this.adoptExistingScope(ownRequestId, req, res);
|
|
1469
|
+
}
|
|
1470
|
+
next();
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
markCorrelationOpened(req);
|
|
1474
|
+
const context = this.inheritableContext();
|
|
1475
|
+
const requestId = this.resolveRequestId(req);
|
|
1476
|
+
if (requestId !== void 0) {
|
|
1477
|
+
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
1478
|
+
context.requestId = requestId;
|
|
1479
|
+
markOwnRequestId(req, requestId);
|
|
1480
|
+
}
|
|
1481
|
+
if (context.tenantId === void 0) {
|
|
1482
|
+
const tenantId = this.resolveTenantId(req);
|
|
1483
|
+
if (tenantId !== void 0) {
|
|
1484
|
+
context.tenantId = tenantId;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
this.logContext.run(context, () => next());
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* The enclosing scope's fields that a request scope may start from.
|
|
1491
|
+
*
|
|
1492
|
+
* Plain `run()` would discard everything the caller had set and a plain merge
|
|
1493
|
+
* would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
|
|
1494
|
+
* the middle a request scope actually needs.
|
|
1495
|
+
*
|
|
1496
|
+
* @returns A fresh bag, never the enclosing store itself, so writes inside the
|
|
1497
|
+
* request never reach the scope that opened it.
|
|
1498
|
+
*/
|
|
1499
|
+
inheritableContext() {
|
|
1500
|
+
const store = { ...this.logContext.getStore() };
|
|
1501
|
+
const inherited = {};
|
|
1502
|
+
for (const key of INHERITABLE_CONTEXT_KEYS) {
|
|
1503
|
+
const value = Reflect.get(store, key);
|
|
1504
|
+
if (value !== void 0) {
|
|
1505
|
+
Reflect.set(inherited, key, value);
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
return inherited;
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Second mount on a request that already carries a correlation id: echo the id
|
|
1512
|
+
* onto the response and fill in a tenant the scope does not have yet, without
|
|
1513
|
+
* opening another scope.
|
|
1514
|
+
*
|
|
1515
|
+
* Nothing is minted and nothing already set is overwritten, so a third mount —
|
|
1516
|
+
* or a thirtieth — changes nothing. The response header is written on every
|
|
1517
|
+
* pass because the enclosing scope may have been opened by consumer code that
|
|
1518
|
+
* never exposed it.
|
|
1519
|
+
*
|
|
1520
|
+
* @param requestId - The id already in scope, which wins.
|
|
1521
|
+
* @param req - The incoming request, read for the tenant header.
|
|
1522
|
+
* @param res - The outgoing response, where the effective id is exposed.
|
|
1523
|
+
*/
|
|
1524
|
+
adoptExistingScope(requestId, req, res) {
|
|
1525
|
+
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
1526
|
+
this.logContext.set("requestId", requestId);
|
|
1527
|
+
if (this.logContext.get("tenantId") === void 0) {
|
|
1528
|
+
const tenantId = this.resolveTenantId(req);
|
|
1529
|
+
if (tenantId !== void 0) {
|
|
1530
|
+
this.logContext.set("tenantId", tenantId);
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* The correlation id for this request: the inbound header when acceptable,
|
|
1536
|
+
* otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
|
|
1537
|
+
* off and the caller sent none, which leaves correlation to the upstream
|
|
1538
|
+
* gateway.
|
|
1539
|
+
*
|
|
1540
|
+
* @param req - The incoming request.
|
|
1541
|
+
* @returns The id, or `undefined` when none is available and none is minted.
|
|
1542
|
+
*/
|
|
1543
|
+
resolveRequestId(req) {
|
|
1544
|
+
const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
|
|
1545
|
+
const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
|
|
1546
|
+
return fromHeader ?? (this.shouldGenerateRequestId ? crypto.randomUUID() : void 0);
|
|
1547
|
+
}
|
|
1548
|
+
/**
|
|
1549
|
+
* The tenant id carried by the configured header, when it is acceptable.
|
|
1550
|
+
*
|
|
1551
|
+
* Never minted: a tenant is an assertion about who the request belongs to, and
|
|
1552
|
+
* inventing one would be a fabricated claim rather than a correlation aid.
|
|
1553
|
+
*
|
|
1554
|
+
* @param req - The incoming request.
|
|
1555
|
+
* @returns The tenant id, or `undefined`.
|
|
1556
|
+
*/
|
|
1557
|
+
resolveTenantId(req) {
|
|
1558
|
+
const raw = Reflect.get(req.headers, this.tenantIdHeader);
|
|
1559
|
+
return isAcceptableHeaderValue(raw) ? raw : void 0;
|
|
1560
|
+
}
|
|
1561
|
+
};
|
|
1562
|
+
exports.RequestIdMiddleware = __decorateClass([
|
|
1563
|
+
common.Injectable(),
|
|
1564
|
+
__decorateParam(0, common.Inject(exports.LogContextService)),
|
|
1565
|
+
__decorateParam(1, common.Inject(LOGGER_OPTIONS_TOKEN))
|
|
1566
|
+
], exports.RequestIdMiddleware);
|
|
1567
|
+
|
|
1568
|
+
// src/server/middlewares/apply-request-context.ts
|
|
1569
|
+
function applyRequestContext(app) {
|
|
1570
|
+
let requestId;
|
|
1571
|
+
try {
|
|
1572
|
+
requestId = new exports.RequestIdMiddleware(
|
|
1573
|
+
app.get(exports.LogContextService),
|
|
1574
|
+
app.get(LOGGER_OPTIONS_TOKEN)
|
|
1575
|
+
);
|
|
1576
|
+
} catch (cause) {
|
|
1577
|
+
throw new Error(
|
|
1578
|
+
"[BymaxLoggerModule] useRequestContext(app) called but BymaxLoggerModule was not imported",
|
|
1579
|
+
{ cause }
|
|
1580
|
+
);
|
|
1581
|
+
}
|
|
1582
|
+
app.use((req, res, next) => {
|
|
1583
|
+
requestId.use(req, res, next);
|
|
1584
|
+
});
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
// src/server/constants/default-redact-paths.constants.ts
|
|
1588
|
+
var REDACT_MAX_DEPTH = 4;
|
|
1589
|
+
var WILDCARD_PREFIXES = Array.from(
|
|
1590
|
+
{ length: REDACT_MAX_DEPTH },
|
|
1591
|
+
(_, idx) => "*" + ".*".repeat(idx)
|
|
1592
|
+
);
|
|
1593
|
+
var depth = (field) => WILDCARD_PREFIXES.map((prefix) => `${prefix}.${field}`);
|
|
1594
|
+
var REDACT_COMMON_FIELDS = [
|
|
1595
|
+
// Passwords (5)
|
|
1596
|
+
"password",
|
|
1597
|
+
"passwordHash",
|
|
1598
|
+
"passwordConfirm",
|
|
1599
|
+
"newPassword",
|
|
1600
|
+
"oldPassword",
|
|
1601
|
+
// Tokens (6)
|
|
1602
|
+
"token",
|
|
1603
|
+
"accessToken",
|
|
1604
|
+
"refreshToken",
|
|
1605
|
+
"idToken",
|
|
1606
|
+
"apiKey",
|
|
1607
|
+
"apiSecret",
|
|
1608
|
+
// MFA (3)
|
|
1609
|
+
"mfaSecret",
|
|
1610
|
+
"mfaRecoveryCodes",
|
|
1611
|
+
"totpSecret",
|
|
1612
|
+
// Payment / PCI DSS (5)
|
|
1613
|
+
"cardNumber",
|
|
1614
|
+
"cardCvv",
|
|
1615
|
+
"cvv",
|
|
1616
|
+
"cvc",
|
|
1617
|
+
"cardExpiry",
|
|
1618
|
+
// Personal documents — BR / LGPD (3)
|
|
1619
|
+
"cpf",
|
|
1620
|
+
"cnpj",
|
|
1621
|
+
"rg",
|
|
1622
|
+
// Generic secrets (4) — the most common short-form credential field names
|
|
1623
|
+
"secret",
|
|
1624
|
+
"clientSecret",
|
|
1625
|
+
"signingSecret",
|
|
1626
|
+
"privateKey",
|
|
1627
|
+
// Conservative PII (1) — consumer can disable if logging email is justified
|
|
1628
|
+
"email",
|
|
1629
|
+
// Credential-bearing HTTP header names (5). These also appear in
|
|
1630
|
+
// {@link REDACT_ABSOLUTE_PATHS}, pinned to the `req.headers` / `res.headers`
|
|
1631
|
+
// shapes — which covered ONLY those two shapes. A headers bag logged under any
|
|
1632
|
+
// other key (`logger.info(k, m, u, { headers: req.headers })`, one of the most
|
|
1633
|
+
// common things written while debugging an integration) wrote the bearer token
|
|
1634
|
+
// in clear. Listed here as bare names, they are caught wherever they appear.
|
|
1635
|
+
// Node lower-cases inbound header names, so the lower-case spelling is the one
|
|
1636
|
+
// that can actually reach a log.
|
|
1637
|
+
"authorization",
|
|
1638
|
+
"cookie",
|
|
1639
|
+
"set-cookie",
|
|
1640
|
+
"x-api-key",
|
|
1641
|
+
"x-auth-token"
|
|
1642
|
+
];
|
|
1643
|
+
var REDACT_ABSOLUTE_PATHS = [
|
|
1644
|
+
"req.headers.authorization",
|
|
1645
|
+
"req.headers.cookie",
|
|
1646
|
+
'req.headers["x-api-key"]',
|
|
1647
|
+
'req.headers["x-auth-token"]',
|
|
1648
|
+
'res.headers["set-cookie"]'
|
|
1649
|
+
];
|
|
1650
|
+
var DEFAULT_REDACT_PATHS = [
|
|
1651
|
+
...REDACT_COMMON_FIELDS,
|
|
1652
|
+
...REDACT_COMMON_FIELDS.flatMap((field) => depth(field)),
|
|
1653
|
+
...REDACT_ABSOLUTE_PATHS
|
|
1654
|
+
];
|
|
1655
|
+
|
|
1656
|
+
// src/server/utils/report-destination-failure.util.ts
|
|
1657
|
+
function reportDestinationFailure(logKey, name, cause, msg) {
|
|
1658
|
+
writeStderrSafely(
|
|
1659
|
+
JSON.stringify({
|
|
1660
|
+
level: "error",
|
|
1661
|
+
logKey,
|
|
1662
|
+
destination: toSingleLineMessage(name),
|
|
1663
|
+
err: describeCause(cause),
|
|
1664
|
+
msg: toSingleLineMessage(msg)
|
|
1665
|
+
}) + "\n"
|
|
1666
|
+
);
|
|
1667
|
+
}
|
|
1668
|
+
var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
|
|
1669
|
+
function describeCause(cause) {
|
|
1670
|
+
try {
|
|
1671
|
+
return isError(cause) ? {
|
|
1672
|
+
type: toBoundedMessage(String(cause.name)),
|
|
1673
|
+
message: toBoundedMessage(String(cause.message))
|
|
1674
|
+
} : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
|
|
1675
|
+
} catch {
|
|
1676
|
+
return UNREADABLE_CAUSE;
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
function safeDestinationName(destination) {
|
|
1680
|
+
try {
|
|
1681
|
+
return String(destination.name);
|
|
1682
|
+
} catch {
|
|
1683
|
+
return "unknown";
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
function isLogLevel(value) {
|
|
1687
|
+
return LOG_LEVEL_PRIORITY.includes(value);
|
|
1688
|
+
}
|
|
1689
|
+
var resolvedMinLevels = /* @__PURE__ */ new WeakMap();
|
|
1690
|
+
function safeMinLevel(destination) {
|
|
1691
|
+
if (resolvedMinLevels.has(destination)) {
|
|
1692
|
+
return resolvedMinLevels.get(destination);
|
|
1693
|
+
}
|
|
1694
|
+
let resolved;
|
|
1695
|
+
try {
|
|
1696
|
+
const read = destination.minLevel;
|
|
1697
|
+
resolved = isLogLevel(read) ? read : void 0;
|
|
1698
|
+
} catch {
|
|
1699
|
+
}
|
|
1700
|
+
resolvedMinLevels.set(destination, resolved);
|
|
1701
|
+
return resolved;
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
// src/server/utils/otel-detector.ts
|
|
1705
|
+
var brokenInstallWarned = false;
|
|
1706
|
+
function isOtelApiMissing(cause) {
|
|
1707
|
+
try {
|
|
1708
|
+
const { code, message } = cause;
|
|
1709
|
+
return code === "MODULE_NOT_FOUND" && /^Cannot find module '@opentelemetry\/api'/.test(String(message));
|
|
1710
|
+
} catch {
|
|
1711
|
+
return false;
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
function loadTraceApiFrom(anchor) {
|
|
1715
|
+
let from;
|
|
1716
|
+
try {
|
|
1717
|
+
from = anchor();
|
|
1718
|
+
} catch {
|
|
1719
|
+
return { api: void 0 };
|
|
1343
1720
|
}
|
|
1344
1721
|
try {
|
|
1345
1722
|
const mod = module$1.createRequire(from)("@opentelemetry/api");
|
|
@@ -1484,29 +1861,114 @@ function destinationToStream(destination, health) {
|
|
|
1484
1861
|
});
|
|
1485
1862
|
}
|
|
1486
1863
|
|
|
1864
|
+
// src/server/utils/redact-error-parts.util.ts
|
|
1865
|
+
function defineOwn(target, key, value) {
|
|
1866
|
+
Reflect.defineProperty(target, key, { value, enumerable: true });
|
|
1867
|
+
}
|
|
1868
|
+
var linkDepths = /* @__PURE__ */ new WeakMap();
|
|
1869
|
+
var ERROR_TEXT_FIELDS = /* @__PURE__ */ new Set(["name", "message", "stack"]);
|
|
1870
|
+
var INCOMPLETE_KEY = "_errorFieldsIncomplete";
|
|
1871
|
+
var widthMarkers = /* @__PURE__ */ new WeakSet();
|
|
1872
|
+
function capErrors(errors, host) {
|
|
1873
|
+
if (!Array.isArray(errors) || errors.length <= MAX_AGGREGATE_ERRORS) return errors;
|
|
1874
|
+
if (host.hasToJson(errors)) return errors;
|
|
1875
|
+
const kept = [];
|
|
1876
|
+
for (let index = 0; index < MAX_AGGREGATE_ERRORS; index++) kept.push(Reflect.get(errors, index));
|
|
1877
|
+
const marker = createWidthMarker(errors.length - MAX_AGGREGATE_ERRORS);
|
|
1878
|
+
widthMarkers.add(marker);
|
|
1879
|
+
kept.push(marker);
|
|
1880
|
+
return kept;
|
|
1881
|
+
}
|
|
1882
|
+
function linkTargets(value) {
|
|
1883
|
+
const targets = [];
|
|
1884
|
+
const take = (link) => {
|
|
1885
|
+
if (typeof link === "object" && link !== null) targets.push(link);
|
|
1886
|
+
};
|
|
1887
|
+
if (!Array.isArray(value)) take(value);
|
|
1888
|
+
else for (let index = 0; index < value.length; index++) take(Reflect.get(value, index));
|
|
1889
|
+
return targets;
|
|
1890
|
+
}
|
|
1891
|
+
function walkChainPart(value, level, host, depth2) {
|
|
1892
|
+
const targets = linkTargets(value);
|
|
1893
|
+
if (targets.length > 0 && level + 1 > DEFAULT_MAX_CAUSE_DEPTH) {
|
|
1894
|
+
if (Array.isArray(value) && host.nameKey === "name") {
|
|
1895
|
+
return Array.from({ length: value.length }, (_member, index) => {
|
|
1896
|
+
const member = Reflect.get(value, index);
|
|
1897
|
+
return typeof member === "object" && member !== null && widthMarkers.has(member) ? member : createDepthMarker();
|
|
1898
|
+
});
|
|
1899
|
+
}
|
|
1900
|
+
return createDepthMarker();
|
|
1901
|
+
}
|
|
1902
|
+
const before = new Map(targets.map((target) => [target, linkDepths.get(target)]));
|
|
1903
|
+
for (const target of targets) linkDepths.set(target, level + 1);
|
|
1904
|
+
try {
|
|
1905
|
+
return host.walk(value, depth2 + 1);
|
|
1906
|
+
} finally {
|
|
1907
|
+
before.forEach((earlier, target) => {
|
|
1908
|
+
if (earlier === void 0) linkDepths.delete(target);
|
|
1909
|
+
else linkDepths.set(target, earlier);
|
|
1910
|
+
});
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
function cutOrWalk(value, level, host, depth2) {
|
|
1914
|
+
return typeof value === "string" ? cutText(value) : walkChainPart(value, level, host, depth2);
|
|
1915
|
+
}
|
|
1916
|
+
function addErrorParts(copy, error, ownKeys, host, depth2) {
|
|
1917
|
+
const taken = new Set(ownKeys);
|
|
1918
|
+
const level = linkDepths.get(error) ?? 0;
|
|
1919
|
+
let incomplete = false;
|
|
1920
|
+
const add = (key, covers, read, write = (value) => walkChainPart(value, level, host, depth2)) => {
|
|
1921
|
+
if (taken.has(key)) return;
|
|
1922
|
+
try {
|
|
1923
|
+
const written = write(read());
|
|
1924
|
+
if (written === void 0) return;
|
|
1925
|
+
const covered = covers.some((name) => host.sensitive.has(name));
|
|
1926
|
+
defineOwn(copy, key, covered ? host.censor : written);
|
|
1927
|
+
} catch {
|
|
1928
|
+
incomplete = true;
|
|
1929
|
+
}
|
|
1930
|
+
};
|
|
1931
|
+
add(
|
|
1932
|
+
host.nameKey,
|
|
1933
|
+
[host.nameKey, "name"],
|
|
1934
|
+
() => error.name,
|
|
1935
|
+
(name) => cutOrWalk(name, level, host, depth2)
|
|
1936
|
+
);
|
|
1937
|
+
add(
|
|
1938
|
+
"message",
|
|
1939
|
+
["message"],
|
|
1940
|
+
() => error.message,
|
|
1941
|
+
(message) => cutOrWalk(message, level, host, depth2)
|
|
1942
|
+
);
|
|
1943
|
+
add(
|
|
1944
|
+
"stack",
|
|
1945
|
+
["stack", "name", "message"],
|
|
1946
|
+
() => error.stack,
|
|
1947
|
+
(stack) => typeof stack === "string" ? scrubStack(stack) : void 0
|
|
1948
|
+
);
|
|
1949
|
+
add("cause", ["cause"], () => error.cause);
|
|
1950
|
+
add("errors", ["errors"], () => capErrors(error.errors, host));
|
|
1951
|
+
if (incomplete && !taken.has(INCOMPLETE_KEY)) defineOwn(copy, INCOMPLETE_KEY, true);
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1487
1954
|
// src/server/utils/redact-by-name.util.ts
|
|
1488
1955
|
var REDACT_MAX_TRAVERSAL_DEPTH = 100;
|
|
1489
1956
|
var REDACT_DEPTH_EXCEEDED = "[REDACTION_DEPTH_EXCEEDED]";
|
|
1490
1957
|
var REDACT_MAX_VISITS = 2e5;
|
|
1491
1958
|
var REDACT_BUDGET_EXCEEDED = "[REDACTION_BUDGET_EXCEEDED]";
|
|
1492
1959
|
var REDACT_CIRCULAR = "[Circular]";
|
|
1493
|
-
function resolveToJson(value) {
|
|
1494
|
-
let
|
|
1495
|
-
let
|
|
1496
|
-
let current = value;
|
|
1960
|
+
function resolveToJson(value, viaGet = false) {
|
|
1961
|
+
let candidate = viaGet ? Reflect.get(value, "toJSON") : void 0;
|
|
1962
|
+
let current = viaGet ? null : value;
|
|
1497
1963
|
while (current !== null) {
|
|
1498
1964
|
const descriptor = Object.getOwnPropertyDescriptor(current, "toJSON");
|
|
1499
1965
|
if (descriptor !== void 0) {
|
|
1500
|
-
|
|
1501
|
-
candidate = getter === void 0 ? descriptor.value : getter.call(value);
|
|
1966
|
+
candidate = descriptor.get === void 0 ? descriptor.value : descriptor.get.call(value);
|
|
1502
1967
|
break;
|
|
1503
1968
|
}
|
|
1504
1969
|
current = Object.getPrototypeOf(current);
|
|
1505
1970
|
}
|
|
1506
|
-
return {
|
|
1507
|
-
method: typeof candidate === "function" ? candidate : void 0,
|
|
1508
|
-
fromAccessor: getter !== void 0
|
|
1509
|
-
};
|
|
1971
|
+
return { method: typeof candidate === "function" ? candidate : void 0 };
|
|
1510
1972
|
}
|
|
1511
1973
|
function cloneError(error) {
|
|
1512
1974
|
const descriptors = Object.getOwnPropertyDescriptors(error);
|
|
@@ -1520,10 +1982,6 @@ function cloneError(error) {
|
|
|
1520
1982
|
}
|
|
1521
1983
|
return clone;
|
|
1522
1984
|
}
|
|
1523
|
-
var BUFFER_TO_JSON = Buffer.prototype.toJSON;
|
|
1524
|
-
function defineOwn(target, key, value) {
|
|
1525
|
-
Reflect.defineProperty(target, key, { value, enumerable: true });
|
|
1526
|
-
}
|
|
1527
1985
|
function walkArray(value, rules, depth2, ancestors, inSerialized) {
|
|
1528
1986
|
const length = value.length;
|
|
1529
1987
|
const copy = [];
|
|
@@ -1536,12 +1994,12 @@ function walkArray(value, rules, depth2, ancestors, inSerialized) {
|
|
|
1536
1994
|
}
|
|
1537
1995
|
return copy;
|
|
1538
1996
|
}
|
|
1539
|
-
function walk(value, rules, depth2, ancestors, honorToJson
|
|
1997
|
+
function walk(value, rules, depth2, ancestors, honorToJson, inSerialized = false) {
|
|
1540
1998
|
if (value === null) {
|
|
1541
1999
|
return value;
|
|
1542
2000
|
}
|
|
1543
2001
|
if (typeof value !== "object" && typeof value !== "function") {
|
|
1544
|
-
return value;
|
|
2002
|
+
return typeof value === "symbol" && rules.ownFields.safe ? void 0 : value;
|
|
1545
2003
|
}
|
|
1546
2004
|
if (depth2 > REDACT_MAX_TRAVERSAL_DEPTH) {
|
|
1547
2005
|
return REDACT_DEPTH_EXCEEDED;
|
|
@@ -1552,7 +2010,7 @@ function walk(value, rules, depth2, ancestors, honorToJson = true, inSerialized
|
|
|
1552
2010
|
if (ancestors.has(value)) {
|
|
1553
2011
|
return REDACT_CIRCULAR;
|
|
1554
2012
|
}
|
|
1555
|
-
if (value
|
|
2013
|
+
if (isError(value)) {
|
|
1556
2014
|
return walkError(value, rules, depth2, ancestors, honorToJson, inSerialized);
|
|
1557
2015
|
}
|
|
1558
2016
|
return walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized);
|
|
@@ -1562,17 +2020,26 @@ function walkError(error, rules, depth2, ancestors, honorToJson, inSerialized) {
|
|
|
1562
2020
|
return walkObject(error, rules, depth2, ancestors, honorToJson, inSerialized);
|
|
1563
2021
|
} catch {
|
|
1564
2022
|
rules.visits.count--;
|
|
1565
|
-
return walk(
|
|
2023
|
+
return walk(
|
|
2024
|
+
sanitizeError(error, { ownFields: rules.ownFields }),
|
|
2025
|
+
rules,
|
|
2026
|
+
depth2,
|
|
2027
|
+
ancestors,
|
|
2028
|
+
honorToJson,
|
|
2029
|
+
inSerialized
|
|
2030
|
+
);
|
|
1566
2031
|
}
|
|
1567
2032
|
}
|
|
1568
2033
|
function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized) {
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
return value;
|
|
2034
|
+
if (ArrayBuffer.isView(value)) {
|
|
2035
|
+
return withBinaryAsSize(value);
|
|
1572
2036
|
}
|
|
2037
|
+
const plain = rules.ownFields.safe;
|
|
2038
|
+
const resolvedToJson = resolveToJson(value, plain);
|
|
1573
2039
|
ancestors.add(value);
|
|
1574
2040
|
try {
|
|
1575
|
-
const
|
|
2041
|
+
const ownsItsForm = rules.ownFields.safe && isError(value);
|
|
2042
|
+
const toJson = honorToJson && !ownsItsForm ? resolvedToJson.method : void 0;
|
|
1576
2043
|
if (toJson !== void 0) {
|
|
1577
2044
|
if (Object.keys(value).some((key) => rules.sensitive.has(key.toLowerCase()))) {
|
|
1578
2045
|
return rules.censor;
|
|
@@ -1580,28 +2047,33 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
|
|
|
1580
2047
|
return walk(toJson.call(value), rules, depth2 + 1, ancestors, true, inSerialized);
|
|
1581
2048
|
}
|
|
1582
2049
|
if (typeof value === "function") {
|
|
1583
|
-
return value;
|
|
2050
|
+
return plain ? void 0 : value;
|
|
1584
2051
|
}
|
|
1585
2052
|
if (Array.isArray(value)) {
|
|
1586
2053
|
return walkArray(value, rules, depth2, ancestors, inSerialized);
|
|
1587
2054
|
}
|
|
1588
2055
|
const source = value;
|
|
1589
2056
|
const keys = Object.keys(source);
|
|
1590
|
-
const asData = value
|
|
1591
|
-
const clone = value
|
|
2057
|
+
const asData = isError(value) && (plain || rules.errorsAsData && !inSerialized);
|
|
2058
|
+
const clone = isError(value) ? cloneError(value) : void 0;
|
|
1592
2059
|
const copy = clone !== void 0 && !asData ? clone : {};
|
|
1593
|
-
const scrubbed = value
|
|
2060
|
+
const scrubbed = isError(value) && (plain || !inSerialized);
|
|
2061
|
+
const omitted = /* @__PURE__ */ new Set();
|
|
1594
2062
|
for (const key of keys) {
|
|
1595
|
-
const
|
|
2063
|
+
const read = Reflect.get(source, key);
|
|
2064
|
+
const current = scrubbed ? ownFieldForLog(source, key, read, rules.ownFields) : read;
|
|
1596
2065
|
if (current === OMIT_OWN_FIELD) {
|
|
1597
2066
|
Reflect.deleteProperty(copy, key);
|
|
2067
|
+
omitted.add(key);
|
|
1598
2068
|
continue;
|
|
1599
2069
|
}
|
|
1600
2070
|
defineOwn(
|
|
1601
2071
|
copy,
|
|
1602
2072
|
key,
|
|
1603
2073
|
rules.sensitive.has(key.toLowerCase()) ? rules.censor : walk(
|
|
1604
|
-
|
|
2074
|
+
// An own enumerable `name`, `message` or `stack` of an `Error` is the same text as
|
|
2075
|
+
// the part the walk would add, so it is cut the same way.
|
|
2076
|
+
scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
|
|
1605
2077
|
rules,
|
|
1606
2078
|
depth2 + 1,
|
|
1607
2079
|
ancestors,
|
|
@@ -1610,79 +2082,42 @@ function walkObject(value, rules, depth2, ancestors, honorToJson, inSerialized)
|
|
|
1610
2082
|
)
|
|
1611
2083
|
);
|
|
1612
2084
|
}
|
|
1613
|
-
if (asData)
|
|
2085
|
+
if (asData) {
|
|
2086
|
+
const written = keys.filter((key) => !omitted.has(key));
|
|
2087
|
+
addErrorParts(
|
|
2088
|
+
copy,
|
|
2089
|
+
value,
|
|
2090
|
+
written,
|
|
2091
|
+
errorPartsHost(rules, ancestors, inSerialized),
|
|
2092
|
+
depth2
|
|
2093
|
+
);
|
|
2094
|
+
}
|
|
1614
2095
|
return copy;
|
|
1615
2096
|
} finally {
|
|
1616
2097
|
ancestors.delete(value);
|
|
1617
2098
|
}
|
|
1618
2099
|
}
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
const targets = [];
|
|
1631
|
-
const take = (link) => {
|
|
1632
|
-
if (typeof link === "object" && link !== null) targets.push(link);
|
|
1633
|
-
};
|
|
1634
|
-
if (!Array.isArray(value)) take(value);
|
|
1635
|
-
else for (let index = 0; index < value.length; index++) take(Reflect.get(value, index));
|
|
1636
|
-
return targets;
|
|
1637
|
-
}
|
|
1638
|
-
function walkChainPart(value, level, rules, depth2, ancestors) {
|
|
1639
|
-
const targets = linkTargets(value);
|
|
1640
|
-
if (targets.length > 0 && level + 1 > DEFAULT_MAX_CAUSE_DEPTH) return createDepthMarker();
|
|
1641
|
-
const before = new Map(targets.map((target) => [target, linkDepths.get(target)]));
|
|
1642
|
-
for (const target of targets) linkDepths.set(target, level + 1);
|
|
1643
|
-
try {
|
|
1644
|
-
return walk(value, rules, depth2 + 1, ancestors);
|
|
1645
|
-
} finally {
|
|
1646
|
-
before.forEach((earlier, target) => {
|
|
1647
|
-
if (earlier === void 0) linkDepths.delete(target);
|
|
1648
|
-
else linkDepths.set(target, earlier);
|
|
1649
|
-
});
|
|
1650
|
-
}
|
|
1651
|
-
}
|
|
1652
|
-
function addErrorParts(copy, error, ownKeys, rules, depth2, ancestors) {
|
|
1653
|
-
const taken = new Set(ownKeys);
|
|
1654
|
-
const level = linkDepths.get(error) ?? 0;
|
|
1655
|
-
let incomplete = false;
|
|
1656
|
-
const add = (key, covers, read, write = (value) => walkChainPart(value, level, rules, depth2, ancestors)) => {
|
|
1657
|
-
if (taken.has(key)) return;
|
|
1658
|
-
try {
|
|
1659
|
-
const written = write(read());
|
|
1660
|
-
if (written === void 0) return;
|
|
1661
|
-
const covered = covers.some((name) => rules.sensitive.has(name));
|
|
1662
|
-
defineOwn(copy, key, covered ? rules.censor : written);
|
|
1663
|
-
} catch {
|
|
1664
|
-
incomplete = true;
|
|
1665
|
-
}
|
|
2100
|
+
function errorPartsHost(rules, ancestors, inSerialized) {
|
|
2101
|
+
return {
|
|
2102
|
+
sensitive: rules.sensitive,
|
|
2103
|
+
censor: rules.censor,
|
|
2104
|
+
// What a serializer receives names the error `name`, as the error-like shape it reads does;
|
|
2105
|
+
// everything else keeps the `type` the written entries use.
|
|
2106
|
+
nameKey: inSerialized ? "name" : "type",
|
|
2107
|
+
walk: (value, depth2) => walk(value, rules, depth2, ancestors, true, inSerialized),
|
|
2108
|
+
// Under 'safe' the cap does not read a list's `toJSON`: a list over the cap becomes a fresh array
|
|
2109
|
+
// and is never read for it, and a list within the cap is read once, by the walk.
|
|
2110
|
+
hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
|
|
1666
2111
|
};
|
|
1667
|
-
add("type", ["type", "name"], () => error.name);
|
|
1668
|
-
add("message", ["message"], () => error.message);
|
|
1669
|
-
add(
|
|
1670
|
-
"stack",
|
|
1671
|
-
["stack", "name", "message"],
|
|
1672
|
-
() => error.stack,
|
|
1673
|
-
(stack) => typeof stack === "string" ? scrubStack(stack) : void 0
|
|
1674
|
-
);
|
|
1675
|
-
add("cause", ["cause"], () => error.cause);
|
|
1676
|
-
add("errors", ["errors"], () => capErrors(error.errors));
|
|
1677
|
-
if (incomplete && !taken.has(INCOMPLETE_KEY)) defineOwn(copy, INCOMPLETE_KEY, true);
|
|
1678
2112
|
}
|
|
1679
|
-
function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS) {
|
|
2113
|
+
function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS) {
|
|
1680
2114
|
const rules = {
|
|
1681
|
-
sensitive: new Set(
|
|
2115
|
+
sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
|
|
1682
2116
|
censor,
|
|
1683
2117
|
serializedKeys: new Set(serializedKeys),
|
|
1684
2118
|
errorsAsData: serializedKeys !== void 0,
|
|
1685
|
-
maxVisits
|
|
2119
|
+
maxVisits,
|
|
2120
|
+
ownFields
|
|
1686
2121
|
};
|
|
1687
2122
|
return (value, isRecordRoot = false) => {
|
|
1688
2123
|
try {
|
|
@@ -1859,8 +2294,8 @@ function leafNameOf(path) {
|
|
|
1859
2294
|
}
|
|
1860
2295
|
return leaf;
|
|
1861
2296
|
}
|
|
1862
|
-
function serializeErrorValue(value_) {
|
|
1863
|
-
const sanitized = sanitizeError(value_);
|
|
2297
|
+
function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS) {
|
|
2298
|
+
const sanitized = sanitizeError(value_, { ownFields });
|
|
1864
2299
|
const serialized = {
|
|
1865
2300
|
// `type` rather than `name`: the field consumers already query.
|
|
1866
2301
|
type: sanitized.name,
|
|
@@ -1885,11 +2320,11 @@ function withSemconvException(record, format) {
|
|
|
1885
2320
|
try {
|
|
1886
2321
|
const candidate = record["err"];
|
|
1887
2322
|
if (typeof candidate?.name === "string") {
|
|
1888
|
-
record["exception.type"] = candidate.name;
|
|
1889
|
-
record["error.type"] = candidate.name;
|
|
2323
|
+
record["exception.type"] = cutText(candidate.name);
|
|
2324
|
+
record["error.type"] = cutText(candidate.name);
|
|
1890
2325
|
}
|
|
1891
2326
|
if (typeof candidate?.message === "string") {
|
|
1892
|
-
record["exception.message"] = candidate.message;
|
|
2327
|
+
record["exception.message"] = cutText(candidate.message);
|
|
1893
2328
|
}
|
|
1894
2329
|
if (typeof candidate?.stack === "string") {
|
|
1895
2330
|
record["exception.stacktrace"] = scrubStack(candidate.stack);
|
|
@@ -1922,20 +2357,28 @@ function withEventName(record, field) {
|
|
|
1922
2357
|
}
|
|
1923
2358
|
var PASS_THROUGH = (value) => value;
|
|
1924
2359
|
function resolveNameRedactor(options) {
|
|
1925
|
-
|
|
1926
|
-
return PASS_THROUGH;
|
|
1927
|
-
}
|
|
1928
|
-
return buildNameRedactor(options, true);
|
|
2360
|
+
return buildNameRedactor(options, true, options.redactStrategy === "names");
|
|
1929
2361
|
}
|
|
1930
|
-
function
|
|
1931
|
-
|
|
2362
|
+
function ownFieldPolicyOf(options) {
|
|
2363
|
+
return createOwnFieldPolicy(options.errorOwnFields, options.errorOwnFieldNames);
|
|
2364
|
+
}
|
|
2365
|
+
function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = true) {
|
|
2366
|
+
const names = coversNames ? [
|
|
1932
2367
|
...options.shouldDisableDefaultRedact ? [] : REDACT_COMMON_FIELDS,
|
|
1933
2368
|
...options.redactPaths.flatMap((path) => leafNameOf(path) ?? [])
|
|
1934
|
-
];
|
|
1935
|
-
|
|
2369
|
+
] : [];
|
|
2370
|
+
const ownFields = ownFieldPolicyOf(options);
|
|
2371
|
+
const walks = names.length > 0 || ownFields.safe;
|
|
2372
|
+
if (!walks && resolveRedactOption(options) === void 0) {
|
|
1936
2373
|
return PASS_THROUGH;
|
|
1937
2374
|
}
|
|
1938
|
-
return nestedErrorsAsData
|
|
2375
|
+
return nestedErrorsAsData && walks ? createNameRedactor(
|
|
2376
|
+
names,
|
|
2377
|
+
options.redactCensor,
|
|
2378
|
+
["err", ...Object.keys(options.serializers)],
|
|
2379
|
+
void 0,
|
|
2380
|
+
ownFields
|
|
2381
|
+
) : createNameRedactor(names, options.redactCensor, void 0, void 0, ownFields);
|
|
1939
2382
|
}
|
|
1940
2383
|
function resolveRedactOption(options) {
|
|
1941
2384
|
const paths = options.redactStrategy === "paths" ? compileRedactPaths(options.redactPaths, options.shouldDisableDefaultRedact) : [...new Set(options.redactPaths)];
|
|
@@ -1948,9 +2391,10 @@ function buildPinoInstance(options, logContext, destinations, health) {
|
|
|
1948
2391
|
const maxBytes = options.maxEntrySizeBytes;
|
|
1949
2392
|
const redactRecord = resolveNameRedactor(options);
|
|
1950
2393
|
const redactSerialized = buildNameRedactor(options);
|
|
2394
|
+
const ownFields = ownFieldPolicyOf(options);
|
|
1951
2395
|
const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
|
|
1952
2396
|
const serializers = {
|
|
1953
|
-
err: bound(serializeErrorValue),
|
|
2397
|
+
err: bound((error) => serializeErrorValue(error, ownFields)),
|
|
1954
2398
|
...Object.fromEntries(
|
|
1955
2399
|
Object.entries(options.serializers).map(
|
|
1956
2400
|
([key, serializer]) => [key, bound(serializer)]
|
|
@@ -2414,191 +2858,65 @@ var DestinationRegistry = class {
|
|
|
2414
2858
|
await destination.onShutdown?.();
|
|
2415
2859
|
} catch (cause) {
|
|
2416
2860
|
this.reportShutdownFailure(destination, cause);
|
|
2417
|
-
}
|
|
2418
|
-
}
|
|
2419
|
-
}
|
|
2420
|
-
/**
|
|
2421
|
-
* Report a failing `onShutdown` on stderr without letting the report itself
|
|
2422
|
-
* abort the teardown of the destinations still queued behind it.
|
|
2423
|
-
*
|
|
2424
|
-
* The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
|
|
2425
|
-
* an `Error` with hostile getters, and `String(cause)` on a value with a
|
|
2426
|
-
* throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
|
|
2427
|
-
* the `catch` that exists to keep one bad sink from mattering, so an escape
|
|
2428
|
-
* here would propagate out of `onApplicationShutdown` and skip every remaining
|
|
2429
|
-
* destination's flush. The never-throw contract has to cover READING the value,
|
|
2430
|
-
* not just writing it, which is the same correction `reportDestinationFailure`
|
|
2431
|
-
* already carries.
|
|
2432
|
-
*
|
|
2433
|
-
* The text is escaped for the same reason every other terminal-bound path is:
|
|
2434
|
-
* a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
|
|
2435
|
-
* newlines and neutralizes everything else that can drive a terminal.
|
|
2436
|
-
*
|
|
2437
|
-
* The DESTINATION is passed rather than its name, so that read happens in here
|
|
2438
|
-
* too. `name` is declared `readonly name: string` but nothing stops a consumer
|
|
2439
|
-
* implementing it as a getter, and reading it at the call site would put it back
|
|
2440
|
-
* outside the guard — inside the `catch`, where a throw has the same cost.
|
|
2441
|
-
*
|
|
2442
|
-
* Two separate guards, not one: a name that cannot be read must not also cost
|
|
2443
|
-
* the failure detail, and a detail that cannot be read must not cost the name.
|
|
2444
|
-
* Either alone still identifies which sink failed.
|
|
2445
|
-
*
|
|
2446
|
-
* @param destination - The destination whose `onShutdown` threw.
|
|
2447
|
-
* @param cause - The thrown value, of any shape.
|
|
2448
|
-
*/
|
|
2449
|
-
reportShutdownFailure(destination, cause) {
|
|
2450
|
-
const name = toSingleLineMessage(safeDestinationName(destination));
|
|
2451
|
-
let detail = "UnknownError";
|
|
2452
|
-
try {
|
|
2453
|
-
const stack = isErrorLike(cause) ? cause.stack : void 0;
|
|
2454
|
-
detail = stack === void 0 ? toSingleLineMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutStack(String(stack)));
|
|
2455
|
-
} catch {
|
|
2456
|
-
}
|
|
2457
|
-
writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
|
|
2458
|
-
`);
|
|
2459
|
-
}
|
|
2460
|
-
/**
|
|
2461
|
-
* The destinations that initialized successfully.
|
|
2462
|
-
*
|
|
2463
|
-
* @returns A read-only view of the active destination set.
|
|
2464
|
-
*/
|
|
2465
|
-
getActive() {
|
|
2466
|
-
return this.active;
|
|
2467
|
-
}
|
|
2468
|
-
};
|
|
2469
|
-
DestinationRegistry = __decorateClass([
|
|
2470
|
-
common.Injectable(),
|
|
2471
|
-
__decorateParam(0, common.Inject(LOGGER_DESTINATIONS_TOKEN)),
|
|
2472
|
-
__decorateParam(1, common.Inject(exports.PinoLoggerService)),
|
|
2473
|
-
__decorateParam(2, common.Inject(LOGGER_OPTIONS_TOKEN)),
|
|
2474
|
-
__decorateParam(3, common.Inject(DestinationHealth))
|
|
2475
|
-
], DestinationRegistry);
|
|
2476
|
-
var FORBIDDEN_CONTEXT_KEYS = PROTOTYPE_POLLUTING_KEYS;
|
|
2477
|
-
exports.LogContextService = class LogContextService {
|
|
2478
|
-
constructor() {
|
|
2479
|
-
this.als = new async_hooks.AsyncLocalStorage();
|
|
2480
|
-
}
|
|
2481
|
-
/**
|
|
2482
|
-
* Run `callback` inside a fresh context scope. Every log emitted
|
|
2483
|
-
* synchronously or asynchronously within the callback inherits `context`.
|
|
2484
|
-
*
|
|
2485
|
-
* **A nested `run()` REPLACES the enclosing context, it does not extend it.**
|
|
2486
|
-
* The scope starts from `context` alone, so a field an outer scope had set —
|
|
2487
|
-
* a `tenantId` resolved at the edge, say — is absent for the whole inner
|
|
2488
|
-
* scope: nothing throws, `get()` simply returns `undefined`, and the field is
|
|
2489
|
-
* missing from every entry the callback emits. Reach for {@link runMerged}
|
|
2490
|
-
* when the inner scope should extend the outer one.
|
|
2491
|
-
*
|
|
2492
|
-
* Replacement is the deliberate default because the opposite leaks: a
|
|
2493
|
-
* background job started inside a request scope would silently inherit the
|
|
2494
|
-
* caller's `userId` and attribute its entries to a user who never triggered
|
|
2495
|
-
* it. A missing field is visibly missing; an inherited one is wrong while
|
|
2496
|
-
* looking right.
|
|
2497
|
-
*
|
|
2498
|
-
* @typeParam T - Return type of the callback.
|
|
2499
|
-
* @param context - Initial context bag for the scope. Becomes the WHOLE scope.
|
|
2500
|
-
* @param callback - Function executed within the scope.
|
|
2501
|
-
* @returns Whatever `callback` returns.
|
|
2502
|
-
* @example
|
|
2503
|
-
* logContext.run({ requestId: 'r_1', tenantId: 't_1' }, async () => {
|
|
2504
|
-
* await userService.create(dto) // logs carry requestId + tenantId
|
|
2505
|
-
* })
|
|
2506
|
-
*/
|
|
2507
|
-
run(context, callback) {
|
|
2508
|
-
return this.als.run(this.sanitizeContext(context), callback);
|
|
2509
|
-
}
|
|
2510
|
-
/**
|
|
2511
|
-
* Run `callback` inside a scope that EXTENDS the enclosing one: the active
|
|
2512
|
-
* context's fields are carried in, and `context` overrides them key by key.
|
|
2513
|
-
*
|
|
2514
|
-
* The explicit counterpart to {@link run}'s replacement semantics, for the
|
|
2515
|
-
* case where an inner scope is genuinely a refinement of the outer — adding a
|
|
2516
|
-
* `userId` once authentication resolved it, without having to restate the
|
|
2517
|
-
* `requestId` the middleware already set.
|
|
2518
|
-
*
|
|
2519
|
-
* Outside any scope there is nothing to merge and this behaves exactly like
|
|
2520
|
-
* {@link run}. Writes inside the new scope never reach the enclosing one: the
|
|
2521
|
-
* merge produces a fresh object, so the outer context is intact after the
|
|
2522
|
-
* callback returns.
|
|
2523
|
-
*
|
|
2524
|
-
* @typeParam T - Return type of the callback.
|
|
2525
|
-
* @param context - Fields to add or override on top of the active context.
|
|
2526
|
-
* @param callback - Function executed within the merged scope.
|
|
2527
|
-
* @returns Whatever `callback` returns.
|
|
2528
|
-
* @example
|
|
2529
|
-
* logContext.run({ requestId: 'r_1' }, () => {
|
|
2530
|
-
* logContext.runMerged({ userId: 'u_1' }, () => {
|
|
2531
|
-
* logContext.get('requestId') // 'r_1' — carried in from the outer scope
|
|
2532
|
-
* })
|
|
2533
|
-
* })
|
|
2534
|
-
*/
|
|
2535
|
-
runMerged(context, callback) {
|
|
2536
|
-
const merged = { ...this.als.getStore(), ...this.sanitizeContext(context) };
|
|
2537
|
-
return this.als.run(merged, callback);
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2538
2863
|
}
|
|
2539
2864
|
/**
|
|
2540
|
-
*
|
|
2865
|
+
* Report a failing `onShutdown` on stderr without letting the report itself
|
|
2866
|
+
* abort the teardown of the destinations still queued behind it.
|
|
2541
2867
|
*
|
|
2542
|
-
*
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
*
|
|
2868
|
+
* The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
|
|
2869
|
+
* an `Error` with hostile getters, and `String(cause)` on a value with a
|
|
2870
|
+
* throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
|
|
2871
|
+
* the `catch` that exists to keep one bad sink from mattering, so an escape
|
|
2872
|
+
* here would propagate out of `onApplicationShutdown` and skip every remaining
|
|
2873
|
+
* destination's flush. The never-throw contract has to cover READING the value,
|
|
2874
|
+
* not just writing it, which is the same correction `reportDestinationFailure`
|
|
2875
|
+
* already carries.
|
|
2549
2876
|
*
|
|
2550
|
-
*
|
|
2551
|
-
*
|
|
2552
|
-
*
|
|
2553
|
-
*/
|
|
2554
|
-
set(key, value) {
|
|
2555
|
-
const store = this.als.getStore();
|
|
2556
|
-
if (!store) {
|
|
2557
|
-
throw new Error("[LogContextService] set() called outside run() scope");
|
|
2558
|
-
}
|
|
2559
|
-
if (FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
2560
|
-
throw new Error(`[LogContextService] Refusing to set unsafe context key: ${key}`);
|
|
2561
|
-
}
|
|
2562
|
-
Reflect.set(store, key, value);
|
|
2563
|
-
}
|
|
2564
|
-
/**
|
|
2565
|
-
* Read a single field from the active context.
|
|
2877
|
+
* The text is escaped for the same reason every other terminal-bound path is:
|
|
2878
|
+
* a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
|
|
2879
|
+
* newlines and neutralizes everything else that can drive a terminal.
|
|
2566
2880
|
*
|
|
2567
|
-
*
|
|
2568
|
-
*
|
|
2569
|
-
*
|
|
2881
|
+
* The DESTINATION is passed rather than its name, so that read happens in here
|
|
2882
|
+
* too. `name` is declared `readonly name: string` but nothing stops a consumer
|
|
2883
|
+
* implementing it as a getter, and reading it at the call site would put it back
|
|
2884
|
+
* outside the guard — inside the `catch`, where a throw has the same cost.
|
|
2885
|
+
*
|
|
2886
|
+
* Two separate guards, not one: a name that cannot be read must not also cost
|
|
2887
|
+
* the failure detail, and a detail that cannot be read must not cost the name.
|
|
2888
|
+
* Either alone still identifies which sink failed.
|
|
2889
|
+
*
|
|
2890
|
+
* @param destination - The destination whose `onShutdown` threw.
|
|
2891
|
+
* @param cause - The thrown value, of any shape.
|
|
2570
2892
|
*/
|
|
2571
|
-
|
|
2572
|
-
const
|
|
2573
|
-
|
|
2574
|
-
|
|
2893
|
+
reportShutdownFailure(destination, cause) {
|
|
2894
|
+
const name = toSingleLineMessage(safeDestinationName(destination));
|
|
2895
|
+
let detail = "UnknownError";
|
|
2896
|
+
try {
|
|
2897
|
+
const stack = isErrorLike(cause) ? cause.stack : void 0;
|
|
2898
|
+
detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
|
|
2899
|
+
} catch {
|
|
2575
2900
|
}
|
|
2576
|
-
|
|
2901
|
+
writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
|
|
2902
|
+
`);
|
|
2577
2903
|
}
|
|
2578
2904
|
/**
|
|
2579
|
-
*
|
|
2580
|
-
* `__proto__` / `constructor` / `prototype` key (e.g. from `JSON.parse` of an
|
|
2581
|
-
* untrusted payload) can never reach the store — and, via the trace mixin's
|
|
2582
|
-
* `Object.assign`, the emitted log entry. Mirrors the guard `set()` enforces,
|
|
2583
|
-
* but drops the key rather than throwing: a logging concern must never crash
|
|
2584
|
-
* the request that produced it.
|
|
2905
|
+
* The destinations that initialized successfully.
|
|
2585
2906
|
*
|
|
2586
|
-
* @
|
|
2587
|
-
* @returns A shallow copy with any forbidden keys removed.
|
|
2907
|
+
* @returns A read-only view of the active destination set.
|
|
2588
2908
|
*/
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
for (const key of Object.keys(context)) {
|
|
2592
|
-
if (!FORBIDDEN_CONTEXT_KEYS.has(key)) {
|
|
2593
|
-
Reflect.set(safe, key, Reflect.get(context, key));
|
|
2594
|
-
}
|
|
2595
|
-
}
|
|
2596
|
-
return safe;
|
|
2909
|
+
getActive() {
|
|
2910
|
+
return this.active;
|
|
2597
2911
|
}
|
|
2598
2912
|
};
|
|
2599
|
-
|
|
2600
|
-
common.Injectable()
|
|
2601
|
-
|
|
2913
|
+
DestinationRegistry = __decorateClass([
|
|
2914
|
+
common.Injectable(),
|
|
2915
|
+
__decorateParam(0, common.Inject(LOGGER_DESTINATIONS_TOKEN)),
|
|
2916
|
+
__decorateParam(1, common.Inject(exports.PinoLoggerService)),
|
|
2917
|
+
__decorateParam(2, common.Inject(LOGGER_OPTIONS_TOKEN)),
|
|
2918
|
+
__decorateParam(3, common.Inject(DestinationHealth))
|
|
2919
|
+
], DestinationRegistry);
|
|
2602
2920
|
|
|
2603
2921
|
// src/server/logger.module.ts
|
|
2604
2922
|
function resolveDestinations(options) {
|
|
@@ -2766,6 +3084,26 @@ exports.BymaxLoggerModule = class BymaxLoggerModule extends BymaxLoggerModuleBas
|
|
|
2766
3084
|
app.useLogger(logger);
|
|
2767
3085
|
app.flushLogs();
|
|
2768
3086
|
}
|
|
3087
|
+
/**
|
|
3088
|
+
* Open the request-id correlation scope ahead of the body parser, so a request the parser
|
|
3089
|
+
* refuses (malformed JSON, an unsupported content encoding, a body over the limit) still has its
|
|
3090
|
+
* `requestId`, and the `x-request-id` response header, where an exception filter reads it.
|
|
3091
|
+
*
|
|
3092
|
+
* Call once in `main.ts` AFTER creating the app and BEFORE `app.init()` / `app.listen(...)`.
|
|
3093
|
+
* It mounts only the scope. `applyAccessLog(app)` and `applyRequestIdMiddleware(consumer)` can
|
|
3094
|
+
* be used as well: a second mount of the middleware reuses the scope this one opened.
|
|
3095
|
+
*
|
|
3096
|
+
* @param app - The Nest application returned by `NestFactory.create()`.
|
|
3097
|
+
* @throws Error When `BymaxLoggerModule` was not imported.
|
|
3098
|
+
* @example
|
|
3099
|
+
* const app = await NestFactory.create(AppModule, { bufferLogs: true })
|
|
3100
|
+
* BymaxLoggerModule.useNestLogger(app)
|
|
3101
|
+
* BymaxLoggerModule.useRequestContext(app)
|
|
3102
|
+
* await app.listen(3000)
|
|
3103
|
+
*/
|
|
3104
|
+
static useRequestContext(app) {
|
|
3105
|
+
applyRequestContext(app);
|
|
3106
|
+
}
|
|
2769
3107
|
};
|
|
2770
3108
|
exports.BymaxLoggerModule = __decorateClass([
|
|
2771
3109
|
common.Module({})
|
|
@@ -2794,7 +3132,7 @@ function isPinoPrettyMissing(cause) {
|
|
|
2794
3132
|
}
|
|
2795
3133
|
function describeFailure(cause) {
|
|
2796
3134
|
try {
|
|
2797
|
-
return
|
|
3135
|
+
return toBoundedMessage(isError(cause) ? cause.message : String(cause));
|
|
2798
3136
|
} catch {
|
|
2799
3137
|
return "unreadable value";
|
|
2800
3138
|
}
|
|
@@ -3098,7 +3436,7 @@ exports.HttpAccessLogMiddleware = class HttpAccessLogMiddleware {
|
|
|
3098
3436
|
RESERVED_LOG_KEYS.HTTP_REQUEST_CLIENT_ERROR,
|
|
3099
3437
|
`${method} ${url} \u2192 ${statusCode}`,
|
|
3100
3438
|
userId,
|
|
3101
|
-
recorded === void 0 ? meta : { ...meta, errorMessage: recorded.error.message }
|
|
3439
|
+
recorded === void 0 ? meta : { ...meta, errorMessage: cutIfText(recorded.error.message) }
|
|
3102
3440
|
);
|
|
3103
3441
|
return;
|
|
3104
3442
|
}
|
|
@@ -3116,156 +3454,6 @@ exports.HttpAccessLogMiddleware = __decorateClass([
|
|
|
3116
3454
|
__decorateParam(1, common.Inject(exports.LogContextService)),
|
|
3117
3455
|
__decorateParam(2, common.Inject(LOGGER_OPTIONS_TOKEN))
|
|
3118
3456
|
], exports.HttpAccessLogMiddleware);
|
|
3119
|
-
var REQUEST_ID_HEADER = "x-request-id";
|
|
3120
|
-
var MAX_CORRELATION_ID_LENGTH = 256;
|
|
3121
|
-
var CORRELATION_ID_CHARSET = /^[A-Za-z0-9._:/+=-]+$/;
|
|
3122
|
-
var INHERITABLE_CONTEXT_KEYS = ["requestId", "tenantId"];
|
|
3123
|
-
function isAcceptableHeaderValue(value) {
|
|
3124
|
-
return typeof value === "string" && value.length <= MAX_CORRELATION_ID_LENGTH && CORRELATION_ID_CHARSET.test(value);
|
|
3125
|
-
}
|
|
3126
|
-
exports.RequestIdMiddleware = class RequestIdMiddleware {
|
|
3127
|
-
/**
|
|
3128
|
-
* @param logContext - The AsyncLocalStorage-backed context service. Injected by
|
|
3129
|
-
* token explicitly: the package is bundled without `emitDecoratorMetadata`,
|
|
3130
|
-
* so implicit class-type injection would not resolve.
|
|
3131
|
-
* @param options - Resolved module options (read for `http.tenantIdHeader` and
|
|
3132
|
-
* `http.shouldGenerateRequestId`).
|
|
3133
|
-
*/
|
|
3134
|
-
constructor(logContext, options) {
|
|
3135
|
-
this.logContext = logContext;
|
|
3136
|
-
this.tenantIdHeader = options.http.tenantIdHeader;
|
|
3137
|
-
this.shouldGenerateRequestId = options.http.shouldGenerateRequestId;
|
|
3138
|
-
}
|
|
3139
|
-
/**
|
|
3140
|
-
* Echo or mint the `x-request-id`, expose it on the response, and run the
|
|
3141
|
-
* remainder of the request inside its own log-context scope.
|
|
3142
|
-
*
|
|
3143
|
-
* Idempotent: mounting this middleware twice on the same request mints one id,
|
|
3144
|
-
* not two. The request gets its OWN store, started from the enclosing scope's
|
|
3145
|
-
* correlation fields — see {@link INHERITABLE_CONTEXT_KEYS} — and nothing
|
|
3146
|
-
* else, because no other field can be known to belong to this request.
|
|
3147
|
-
*
|
|
3148
|
-
* An enclosing scope's `requestId` is never adopted and never echoed: adoption
|
|
3149
|
-
* reads a value this middleware recorded on the REQUEST, which a scope opened
|
|
3150
|
-
* elsewhere does not have. What the two generation modes do with one, measured
|
|
3151
|
-
* on two requests sharing a long-lived enclosing scope:
|
|
3152
|
-
*
|
|
3153
|
-
* - `shouldGenerateRequestId: true` (default) — each request mints its own
|
|
3154
|
-
* id, the two requests differ, and the enclosing value reaches neither the
|
|
3155
|
-
* header nor the entries.
|
|
3156
|
-
* - `shouldGenerateRequestId: false` with no inbound header — nothing is
|
|
3157
|
-
* minted, so the request scope inherits the enclosing `requestId` and every
|
|
3158
|
-
* request inside that scope logs under it. No header is exposed. That is
|
|
3159
|
-
* the consumer's own scope being inherited, not correlation being reused,
|
|
3160
|
-
* and it is the configuration that says the gateway owns the id.
|
|
3161
|
-
*
|
|
3162
|
-
* @param req - The incoming request (Express satisfies the contract).
|
|
3163
|
-
* @param res - The outgoing response (Express satisfies the contract).
|
|
3164
|
-
* @param next - The next handler in the chain.
|
|
3165
|
-
*/
|
|
3166
|
-
use(req, res, next) {
|
|
3167
|
-
if (isCorrelationOpened(req)) {
|
|
3168
|
-
const ownRequestId = readOwnRequestId(req);
|
|
3169
|
-
if (ownRequestId !== void 0) {
|
|
3170
|
-
this.adoptExistingScope(ownRequestId, req, res);
|
|
3171
|
-
}
|
|
3172
|
-
next();
|
|
3173
|
-
return;
|
|
3174
|
-
}
|
|
3175
|
-
markCorrelationOpened(req);
|
|
3176
|
-
const context = this.inheritableContext();
|
|
3177
|
-
const requestId = this.resolveRequestId(req);
|
|
3178
|
-
if (requestId !== void 0) {
|
|
3179
|
-
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
3180
|
-
context.requestId = requestId;
|
|
3181
|
-
markOwnRequestId(req, requestId);
|
|
3182
|
-
}
|
|
3183
|
-
if (context.tenantId === void 0) {
|
|
3184
|
-
const tenantId = this.resolveTenantId(req);
|
|
3185
|
-
if (tenantId !== void 0) {
|
|
3186
|
-
context.tenantId = tenantId;
|
|
3187
|
-
}
|
|
3188
|
-
}
|
|
3189
|
-
this.logContext.run(context, () => next());
|
|
3190
|
-
}
|
|
3191
|
-
/**
|
|
3192
|
-
* The enclosing scope's fields that a request scope may start from.
|
|
3193
|
-
*
|
|
3194
|
-
* Plain `run()` would discard everything the caller had set and a plain merge
|
|
3195
|
-
* would carry identity across requests; {@link INHERITABLE_CONTEXT_KEYS} is
|
|
3196
|
-
* the middle a request scope actually needs.
|
|
3197
|
-
*
|
|
3198
|
-
* @returns A fresh bag, never the enclosing store itself, so writes inside the
|
|
3199
|
-
* request never reach the scope that opened it.
|
|
3200
|
-
*/
|
|
3201
|
-
inheritableContext() {
|
|
3202
|
-
const store = { ...this.logContext.getStore() };
|
|
3203
|
-
const inherited = {};
|
|
3204
|
-
for (const key of INHERITABLE_CONTEXT_KEYS) {
|
|
3205
|
-
const value = Reflect.get(store, key);
|
|
3206
|
-
if (value !== void 0) {
|
|
3207
|
-
Reflect.set(inherited, key, value);
|
|
3208
|
-
}
|
|
3209
|
-
}
|
|
3210
|
-
return inherited;
|
|
3211
|
-
}
|
|
3212
|
-
/**
|
|
3213
|
-
* Second mount on a request that already carries a correlation id: echo the id
|
|
3214
|
-
* onto the response and fill in a tenant the scope does not have yet, without
|
|
3215
|
-
* opening another scope.
|
|
3216
|
-
*
|
|
3217
|
-
* Nothing is minted and nothing already set is overwritten, so a third mount —
|
|
3218
|
-
* or a thirtieth — changes nothing. The response header is written on every
|
|
3219
|
-
* pass because the enclosing scope may have been opened by consumer code that
|
|
3220
|
-
* never exposed it.
|
|
3221
|
-
*
|
|
3222
|
-
* @param requestId - The id already in scope, which wins.
|
|
3223
|
-
* @param req - The incoming request, read for the tenant header.
|
|
3224
|
-
* @param res - The outgoing response, where the effective id is exposed.
|
|
3225
|
-
*/
|
|
3226
|
-
adoptExistingScope(requestId, req, res) {
|
|
3227
|
-
res.setHeader(REQUEST_ID_HEADER, requestId);
|
|
3228
|
-
this.logContext.set("requestId", requestId);
|
|
3229
|
-
if (this.logContext.get("tenantId") === void 0) {
|
|
3230
|
-
const tenantId = this.resolveTenantId(req);
|
|
3231
|
-
if (tenantId !== void 0) {
|
|
3232
|
-
this.logContext.set("tenantId", tenantId);
|
|
3233
|
-
}
|
|
3234
|
-
}
|
|
3235
|
-
}
|
|
3236
|
-
/**
|
|
3237
|
-
* The correlation id for this request: the inbound header when acceptable,
|
|
3238
|
-
* otherwise a fresh UUID — or nothing at all when `shouldGenerateRequestId` is
|
|
3239
|
-
* off and the caller sent none, which leaves correlation to the upstream
|
|
3240
|
-
* gateway.
|
|
3241
|
-
*
|
|
3242
|
-
* @param req - The incoming request.
|
|
3243
|
-
* @returns The id, or `undefined` when none is available and none is minted.
|
|
3244
|
-
*/
|
|
3245
|
-
resolveRequestId(req) {
|
|
3246
|
-
const incoming = Reflect.get(req.headers, REQUEST_ID_HEADER);
|
|
3247
|
-
const fromHeader = isAcceptableHeaderValue(incoming) ? incoming : void 0;
|
|
3248
|
-
return fromHeader ?? (this.shouldGenerateRequestId ? crypto.randomUUID() : void 0);
|
|
3249
|
-
}
|
|
3250
|
-
/**
|
|
3251
|
-
* The tenant id carried by the configured header, when it is acceptable.
|
|
3252
|
-
*
|
|
3253
|
-
* Never minted: a tenant is an assertion about who the request belongs to, and
|
|
3254
|
-
* inventing one would be a fabricated claim rather than a correlation aid.
|
|
3255
|
-
*
|
|
3256
|
-
* @param req - The incoming request.
|
|
3257
|
-
* @returns The tenant id, or `undefined`.
|
|
3258
|
-
*/
|
|
3259
|
-
resolveTenantId(req) {
|
|
3260
|
-
const raw = Reflect.get(req.headers, this.tenantIdHeader);
|
|
3261
|
-
return isAcceptableHeaderValue(raw) ? raw : void 0;
|
|
3262
|
-
}
|
|
3263
|
-
};
|
|
3264
|
-
exports.RequestIdMiddleware = __decorateClass([
|
|
3265
|
-
common.Injectable(),
|
|
3266
|
-
__decorateParam(0, common.Inject(exports.LogContextService)),
|
|
3267
|
-
__decorateParam(1, common.Inject(LOGGER_OPTIONS_TOKEN))
|
|
3268
|
-
], exports.RequestIdMiddleware);
|
|
3269
3457
|
|
|
3270
3458
|
// src/server/middlewares/apply-access-log.ts
|
|
3271
3459
|
function resolveDependencies(app) {
|