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