@nestjs/observe 0.2.3 → 0.3.1

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.
Files changed (62) hide show
  1. package/README.md +38 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/agent/telemetry-wire-contract.js +1 -0
  4. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  5. package/dist/encoders/request-snapshot.encoder.js +1 -0
  6. package/dist/instrument/create-instance-decorator.instrument.js +2 -2
  7. package/dist/interfaces/observe-options.interface.d.ts +90 -4
  8. package/dist/interfaces/request-snapshot.interface.d.ts +8 -0
  9. package/dist/observe.constants.d.ts +16 -0
  10. package/dist/observe.constants.js +16 -0
  11. package/dist/observe.module.js +48 -4
  12. package/dist/outgoing/http.integration.d.ts +36 -0
  13. package/dist/outgoing/http.integration.js +127 -0
  14. package/dist/outgoing/mongodb.integration.d.ts +38 -0
  15. package/dist/outgoing/mongodb.integration.js +141 -0
  16. package/dist/outgoing/mysql2.integration.d.ts +20 -0
  17. package/dist/outgoing/mysql2.integration.js +89 -0
  18. package/dist/outgoing/outgoing-observe-agent.service.d.ts +17 -0
  19. package/dist/outgoing/outgoing-observe-agent.service.js +123 -0
  20. package/dist/outgoing/outgoing-span.recorder.d.ts +54 -0
  21. package/dist/outgoing/outgoing-span.recorder.js +94 -0
  22. package/dist/outgoing/patch-method.util.d.ts +15 -0
  23. package/dist/outgoing/patch-method.util.js +29 -0
  24. package/dist/outgoing/pg.integration.d.ts +22 -0
  25. package/dist/outgoing/pg.integration.js +66 -0
  26. package/dist/outgoing/sql-statement.util.d.ts +21 -0
  27. package/dist/outgoing/sql-statement.util.js +48 -0
  28. package/dist/protocols/bull-observe-agent.service.d.ts +28 -0
  29. package/dist/protocols/bull-observe-agent.service.js +130 -0
  30. package/dist/protocols/graphql-observe-agent.service.js +5 -2
  31. package/dist/protocols/graphql-operation-parser.d.ts +4 -4
  32. package/dist/protocols/graphql-operation-parser.js +28 -4
  33. package/dist/protocols/http-observe-agent.service.js +26 -7
  34. package/dist/protocols/job-trace-runner.d.ts +77 -0
  35. package/dist/protocols/job-trace-runner.js +196 -0
  36. package/dist/protocols/queue-observe-agent.service.d.ts +9 -4
  37. package/dist/protocols/queue-observe-agent.service.js +36 -95
  38. package/dist/protocols/ws-observe-agent.service.d.ts +39 -0
  39. package/dist/protocols/ws-observe-agent.service.js +180 -0
  40. package/dist/services/logger-patcher.service.js +18 -5
  41. package/dist/services/operation-trace.registry.d.ts +17 -1
  42. package/dist/services/operation-trace.registry.js +39 -7
  43. package/dist/services/stdout-forwarder.service.d.ts +14 -4
  44. package/dist/services/stdout-forwarder.service.js +49 -25
  45. package/dist/services/trace-sampler.service.d.ts +4 -0
  46. package/dist/services/tracer.service.js +5 -3
  47. package/dist/utils/capture-request.util.d.ts +57 -0
  48. package/dist/utils/capture-request.util.js +116 -0
  49. package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
  50. package/dist/utils/default-trace-id-generator.util.js +12 -1
  51. package/dist/utils/log-redactor.d.ts +20 -1
  52. package/dist/utils/log-redactor.js +54 -38
  53. package/dist/utils/optional-peer.util.d.ts +13 -0
  54. package/dist/utils/optional-peer.util.js +30 -0
  55. package/dist/utils/redact-url-query.d.ts +10 -1
  56. package/dist/utils/redact-url-query.js +16 -37
  57. package/dist/utils/sensitive-keys.d.ts +15 -0
  58. package/dist/utils/sensitive-keys.js +76 -0
  59. package/dist/utils/source-context.util.d.ts +6 -0
  60. package/dist/utils/source-context.util.js +113 -15
  61. package/dist/utils/source-map-resolver.util.js +12 -0
  62. package/package.json +35 -2
@@ -42,19 +42,26 @@ const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
42
42
  * inside this window, so it is redacted before the cut can split it.
43
43
  */
44
44
  const MAX_PARSED_LINE_LENGTH = 16 * 1024;
45
+ const FORWARDED_STREAMS = ["stdout", "stderr"];
45
46
  let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderService {
46
47
  options;
47
48
  observeAgentSharedBuffer;
48
49
  als;
49
50
  logger = new Logger(StdoutForwarderService_1.name);
50
51
  /**
51
- * stdout arrives in chunks, not lines: a single write can carry half a line,
52
+ * Output arrives in chunks, not lines: a single write can carry half a line,
52
53
  * several lines, or a line split across two calls. Parsing a chunk directly
53
54
  * would mangle every log that straddles a boundary, so the trailing fragment
54
55
  * is held here until its newline shows up.
56
+ *
57
+ * One fragment per stream: stdout and stderr interleave freely, and joining
58
+ * the tail of one onto the head of the other would fuse two unrelated lines.
55
59
  */
56
- partialLine = "";
57
- originalWrite = null;
60
+ partialLines = {
61
+ stdout: "",
62
+ stderr: "",
63
+ };
64
+ originalWrites = null;
58
65
  /**
59
66
  * Null only when redaction has been switched off explicitly. Defaulting to on
60
67
  * matters more here than anywhere else in the agent: enabling `forwardLogs`
@@ -82,22 +89,37 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
82
89
  onModuleDestroy() {
83
90
  this.restore();
84
91
  }
92
+ /**
93
+ * Patches both stdout and stderr. Nest's `ConsoleLogger` writes `error` to
94
+ * stderr and every other level to stdout, so a stdout-only patch forwarded
95
+ * warnings and fatals but never a single error - including the line the
96
+ * exceptions handler writes for every unhandled exception.
97
+ */
85
98
  start() {
86
- if (this.originalWrite) {
99
+ if (this.originalWrites) {
87
100
  return;
88
101
  }
89
- // The unbound original is kept, so `restore` puts back exactly what was
102
+ // The unbound originals are kept, so `restore` puts back exactly what was
90
103
  // there. Storing the bound copy instead meant every start/restore cycle
91
104
  // left one more `bind` wrapper on the stream - and this module is designed
92
105
  // to be torn down and recreated.
93
- this.originalWrite = process.stdout.write;
94
- const originalWrite = process.stdout.write.bind(process.stdout);
95
- process.stdout.write = ((chunk, encoding, callback) => {
106
+ this.originalWrites = {
107
+ stdout: process.stdout.write,
108
+ stderr: process.stderr.write,
109
+ };
110
+ for (const name of FORWARDED_STREAMS) {
111
+ this.patch(name);
112
+ }
113
+ }
114
+ patch(name) {
115
+ const stream = process[name];
116
+ const originalWrite = stream.write.bind(stream);
117
+ stream.write = ((chunk, encoding, callback) => {
96
118
  if (typeof chunk === "string") {
97
119
  // Never let a forwarding failure take down the write it wrapped -
98
- // stdout has to keep working even if telemetry does not.
120
+ // the stream has to keep working even if telemetry does not.
99
121
  try {
100
- this.consume(chunk);
122
+ this.consume(chunk, name);
101
123
  }
102
124
  catch {
103
125
  // Intentionally silent: logging here would re-enter this same patched
@@ -108,43 +130,45 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
108
130
  });
109
131
  }
110
132
  /**
111
- * Restores the original stdout.write.
133
+ * Restores the original stdout and stderr writes.
112
134
  *
113
135
  * Without this the patch outlives the module - which matters in tests, where
114
136
  * a torn-down app would keep pushing into a buffer nobody drains, and in any
115
137
  * process that recreates the Nest application.
116
138
  */
117
139
  restore() {
118
- if (!this.originalWrite) {
140
+ if (!this.originalWrites) {
119
141
  return;
120
142
  }
121
- this.flushPartial();
122
- process.stdout.write = this.originalWrite;
123
- this.originalWrite = null;
143
+ for (const name of FORWARDED_STREAMS) {
144
+ this.flushPartial(name);
145
+ process[name].write = this.originalWrites[name];
146
+ }
147
+ this.originalWrites = null;
124
148
  }
125
- consume(chunk) {
126
- const combined = this.partialLine + chunk;
149
+ consume(chunk, name = "stdout") {
150
+ const combined = this.partialLines[name] + chunk;
127
151
  const segments = combined.split("\n");
128
152
  // The final segment has no newline yet, so it is either an incomplete line
129
153
  // or the empty string left by a chunk that ended cleanly.
130
- this.partialLine = segments.pop() ?? "";
154
+ this.partialLines[name] = segments.pop() ?? "";
131
155
  const entries = segments
132
156
  .filter((line) => line.trim().length > 0)
133
157
  .map((line) => this.toLogEntry(line));
134
158
  if (entries.length > 0) {
135
159
  this.observeAgentSharedBuffer.pushLogs(entries);
136
160
  }
137
- if (this.partialLine.length > MAX_PARTIAL_LINE_LENGTH) {
138
- this.flushPartial();
161
+ if (this.partialLines[name].length > MAX_PARTIAL_LINE_LENGTH) {
162
+ this.flushPartial(name);
139
163
  }
140
164
  }
141
- flushPartial() {
142
- if (this.partialLine.trim().length === 0) {
143
- this.partialLine = "";
165
+ flushPartial(name) {
166
+ const partialLine = this.partialLines[name];
167
+ this.partialLines[name] = "";
168
+ if (partialLine.trim().length === 0) {
144
169
  return;
145
170
  }
146
- this.observeAgentSharedBuffer.pushLogs([this.toLogEntry(this.partialLine)]);
147
- this.partialLine = "";
171
+ this.observeAgentSharedBuffer.pushLogs([this.toLogEntry(partialLine)]);
148
172
  }
149
173
  toLogEntry(rawLine) {
150
174
  const line = rawLine.length > MAX_PARSED_LINE_LENGTH
@@ -22,4 +22,8 @@ export declare class TraceSamplerService {
22
22
  shouldCapture(protocol: "graphql", attributes: {
23
23
  operationId: string;
24
24
  }): boolean;
25
+ shouldCapture(protocol: "ws", attributes: {
26
+ gateway: string;
27
+ pattern: string;
28
+ }): boolean;
25
29
  }
@@ -16,7 +16,7 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
16
16
  import { Gauge, Summary } from "../custom-metrics/index.js";
17
17
  import { Counter } from "../custom-metrics/counter.js";
18
18
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
19
- import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
19
+ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
20
20
  import { OperationTraceRegistry } from "./operation-trace.registry.js";
21
21
  let TracerService = class TracerService {
22
22
  operationTraceRegistry;
@@ -89,7 +89,8 @@ let TracerService = class TracerService {
89
89
  if (!store) {
90
90
  throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "captureError" method within an async context.');
91
91
  }
92
- const traceId = store.get(this.options.traceIdKey);
92
+ const traceId = store.get(TRACE_REGISTRY_KEY) ??
93
+ store.get(this.options.traceIdKey);
93
94
  if (typeof traceId !== "string") {
94
95
  // Reporting an error must not raise one. The registry warned and gave up
95
96
  // in this case anyway, so the outcome is unchanged.
@@ -209,7 +210,8 @@ let TracerService = class TracerService {
209
210
  * methods with no async context at all - and is reported the same way.
210
211
  */
211
212
  requireTraceId(store, method) {
212
- const traceId = store.get(this.options.traceIdKey);
213
+ const traceId = store.get(TRACE_REGISTRY_KEY) ??
214
+ store.get(this.options.traceIdKey);
213
215
  if (typeof traceId !== "string") {
214
216
  throw new Error(`No trace id found in the current context. Ensure that you are using the "${method}" method within a traced operation.`);
215
217
  }
@@ -0,0 +1,57 @@
1
+ import { LogRedactor } from "./log-redactor.js";
2
+ /**
3
+ * Headers recorded when the application names none. Chosen for what they are
4
+ * not: nothing here authenticates the caller, identifies a person or carries a
5
+ * session - no `authorization`, `cookie`, `x-forwarded-for` or custom `x-*`.
6
+ */
7
+ export declare const DEFAULT_CAPTURED_HEADERS: readonly ["accept", "content-length", "content-type", "host", "origin", "referer", "user-agent"];
8
+ export declare const DEFAULT_CAPTURED_BODY_BYTES = 2048;
9
+ export interface HttpCaptureOptions {
10
+ /**
11
+ * Names of the request headers to record with a failed request, or `false`
12
+ * to record none. Matched case-insensitively. Values still pass through
13
+ * redaction, so naming `authorization` here records `[REDACTED]`.
14
+ * @default DEFAULT_CAPTURED_HEADERS
15
+ */
16
+ headers?: readonly string[] | false;
17
+ /**
18
+ * Record the parsed request body of a failed request. Off by default: a body
19
+ * is the application's own data, and whether it may leave the process is
20
+ * not something an agent can decide. `maxBytes` caps the serialized size
21
+ * (default 2048, at most 16384); what does not fit is cut, and marked so.
22
+ * @default false
23
+ */
24
+ body?: boolean | {
25
+ maxBytes?: number;
26
+ };
27
+ /**
28
+ * Also capture requests that took at least this long, failed or not - the
29
+ * inputs behind a slow request are as hard to guess as those behind a
30
+ * failing one. Unset, only failed requests are captured.
31
+ * @example 2000
32
+ * @default undefined
33
+ */
34
+ slowerThanMs?: number;
35
+ }
36
+ export interface CapturedRequest {
37
+ headers?: Record<string, string>;
38
+ body?: string;
39
+ bodyTruncated?: true;
40
+ }
41
+ /**
42
+ * Whether a finished request is one whose inputs are worth keeping: it
43
+ * failed, or it ran past the configured threshold. Never the ordinary
44
+ * request - that keeps both the volume and the exposure to the exceptions
45
+ * rather than the traffic.
46
+ */
47
+ export declare function shouldCaptureRequest(snapshot: {
48
+ error?: unknown;
49
+ duration?: number;
50
+ }, options: HttpCaptureOptions | false | undefined): boolean;
51
+ /**
52
+ * What to record of a request `shouldCaptureRequest` picked, or `undefined`
53
+ * for nothing. Everything passes through the same redactor as error messages
54
+ * and forwarded logs - sensitive keys by name, secrets by pattern - before it
55
+ * is handed back.
56
+ */
57
+ export declare function captureRequest(req: unknown, options: HttpCaptureOptions | false | undefined, redactor: LogRedactor | null): CapturedRequest | undefined;
@@ -0,0 +1,116 @@
1
+ import { redactUrlQuery } from "./redact-url-query.js";
2
+ /**
3
+ * Headers recorded when the application names none. Chosen for what they are
4
+ * not: nothing here authenticates the caller, identifies a person or carries a
5
+ * session - no `authorization`, `cookie`, `x-forwarded-for` or custom `x-*`.
6
+ */
7
+ export const DEFAULT_CAPTURED_HEADERS = [
8
+ "accept",
9
+ "content-length",
10
+ "content-type",
11
+ "host",
12
+ "origin",
13
+ "referer",
14
+ "user-agent",
15
+ ];
16
+ export const DEFAULT_CAPTURED_BODY_BYTES = 2048;
17
+ const MAX_CAPTURED_BODY_BYTES = 16 * 1024;
18
+ const MAX_HEADER_VALUE_LENGTH = 512;
19
+ /**
20
+ * Whether a finished request is one whose inputs are worth keeping: it
21
+ * failed, or it ran past the configured threshold. Never the ordinary
22
+ * request - that keeps both the volume and the exposure to the exceptions
23
+ * rather than the traffic.
24
+ */
25
+ export function shouldCaptureRequest(snapshot, options) {
26
+ if (options === false) {
27
+ return false;
28
+ }
29
+ if (snapshot.error) {
30
+ return true;
31
+ }
32
+ const threshold = options?.slowerThanMs;
33
+ return (typeof threshold === "number" &&
34
+ threshold > 0 &&
35
+ typeof snapshot.duration === "number" &&
36
+ snapshot.duration >= threshold);
37
+ }
38
+ /**
39
+ * What to record of a request `shouldCaptureRequest` picked, or `undefined`
40
+ * for nothing. Everything passes through the same redactor as error messages
41
+ * and forwarded logs - sensitive keys by name, secrets by pattern - before it
42
+ * is handed back.
43
+ */
44
+ export function captureRequest(req, options, redactor) {
45
+ if (options === false || typeof req !== "object" || req === null) {
46
+ return undefined;
47
+ }
48
+ const request = req;
49
+ const captured = {};
50
+ const headerNames = options?.headers ?? DEFAULT_CAPTURED_HEADERS;
51
+ if (headerNames && request.headers) {
52
+ const headers = {};
53
+ for (const name of headerNames) {
54
+ const key = name.toLowerCase();
55
+ const value = request.headers[key];
56
+ if (typeof value !== "string" || value.length === 0) {
57
+ continue;
58
+ }
59
+ const bounded = value.slice(0, MAX_HEADER_VALUE_LENGTH);
60
+ // A referer is a URL, and its query string is where the tokens live.
61
+ headers[key] =
62
+ key === "referer" ? redactUrlQuery(bounded, redactor) : bounded;
63
+ }
64
+ if (Object.keys(headers).length > 0) {
65
+ captured.headers = (redactor ? redactor.redactAttributes(headers) : headers);
66
+ }
67
+ }
68
+ if (options?.body && request.body !== undefined && request.body !== null) {
69
+ const maxBytes = Math.min(typeof options.body === "object" && options.body.maxBytes
70
+ ? options.body.maxBytes
71
+ : DEFAULT_CAPTURED_BODY_BYTES, MAX_CAPTURED_BODY_BYTES);
72
+ const serialized = serializeBody(request.body, redactor);
73
+ if (serialized !== undefined) {
74
+ if (Buffer.byteLength(serialized) > maxBytes) {
75
+ const bytes = Buffer.from(serialized);
76
+ // Back off to a character boundary: a cut through a multi-byte
77
+ // character decodes to U+FFFD, three bytes where one was kept, and
78
+ // the body would come out over the cap it was just cut to.
79
+ let end = maxBytes;
80
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80) {
81
+ end -= 1;
82
+ }
83
+ captured.body = bytes.subarray(0, end).toString("utf8");
84
+ captured.bodyTruncated = true;
85
+ }
86
+ else {
87
+ captured.body = serialized;
88
+ }
89
+ }
90
+ }
91
+ return captured.headers || captured.body !== undefined ? captured : undefined;
92
+ }
93
+ /**
94
+ * Redaction runs on the parsed structure, before serialization and before the
95
+ * cut - key-based rules need the keys, and truncating first could ship the
96
+ * surviving half of a secret.
97
+ */
98
+ function serializeBody(body, redactor) {
99
+ if (typeof body === "string") {
100
+ return redactor ? redactor.redactMessage(body) : body;
101
+ }
102
+ if (Buffer.isBuffer(body) || typeof body !== "object") {
103
+ // A raw buffer is a file or an unparsed stream - nothing readable to show.
104
+ return undefined;
105
+ }
106
+ try {
107
+ const redacted = redactor
108
+ ? redactor.redactAttributes(body)
109
+ : body;
110
+ return JSON.stringify(redacted);
111
+ }
112
+ catch {
113
+ // Circular, or a getter that throws. Reporting an error must not raise one.
114
+ return undefined;
115
+ }
116
+ }
@@ -1 +1,13 @@
1
+ /**
2
+ * What an inbound `x-request-id` must look like to be adopted as the trace id.
3
+ *
4
+ * The header is client-supplied, so it is honoured only when it is a single,
5
+ * short, unambiguous token. Anything else - an array (Node folds repeated
6
+ * headers into one), an oversized value, control characters, exotic symbols -
7
+ * falls back to a random id: the header exists to let a proxy correlate its
8
+ * own logs with a trace, not to let an arbitrary caller choose what gets
9
+ * written into the telemetry store, collide with an existing trace, or inflate
10
+ * a row with an unbounded value.
11
+ */
12
+ export declare const REQUEST_ID_PATTERN: RegExp;
1
13
  export declare function defaultTraceIdGenerator(req: unknown): string;
@@ -10,7 +10,7 @@ import { uuidv7 } from "./uuid-v7.util.js";
10
10
  * written into the telemetry store, collide with an existing trace, or inflate
11
11
  * a row with an unbounded value.
12
12
  */
13
- const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
13
+ export const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
14
14
  export function defaultTraceIdGenerator(req) {
15
15
  if (typeof req === "object" && req !== null && "headers" in req) {
16
16
  const requestId = req.headers["x-request-id"];
@@ -18,6 +18,17 @@ export function defaultTraceIdGenerator(req) {
18
18
  return requestId;
19
19
  }
20
20
  }
21
+ // A microservice context, on a transport whose packets carry metadata: the
22
+ // id the calling service's client attached. Held to the same shape as the
23
+ // header - a packet is no more trustworthy than a request.
24
+ const getMetadata = req?.getMetadata;
25
+ if (typeof getMetadata === "function") {
26
+ const metadata = getMetadata.call(req);
27
+ const requestId = metadata?.["x-request-id"];
28
+ if (typeof requestId === "string" && REQUEST_ID_PATTERN.test(requestId)) {
29
+ return requestId;
30
+ }
31
+ }
21
32
  // Minted here, so it can carry its time - see uuidv7.
22
33
  return uuidv7();
23
34
  }
@@ -1,11 +1,30 @@
1
1
  import { RedactionOptions } from "../interfaces/observe-options.interface.js";
2
2
  export declare class LogRedactor {
3
3
  private readonly rules;
4
- private readonly sensitiveKeys;
4
+ private readonly sourceRules;
5
+ private readonly matchesSensitiveKey;
5
6
  private readonly replacement;
6
7
  private readonly redactCards;
7
8
  constructor(options?: RedactionOptions);
9
+ /**
10
+ * Whether a key names a credential - the built-in rules plus the configured
11
+ * `keys`. Exposed so a caller masking by key somewhere this class does not
12
+ * reach (a URL's query string) is held to the same list.
13
+ */
14
+ isSensitiveKey(key: string): boolean;
8
15
  redactMessage(message: string): string;
16
+ /**
17
+ * Redacts lines of source code read for a code frame.
18
+ *
19
+ * Source is shipped for the same reason a message is, and a literal in it -
20
+ * `password: "hunter2"`, a pasted key - is as much a secret there as in a
21
+ * log line. The lines are redacted as one text so a block spanning several
22
+ * (a PEM key in a template literal) is still seen whole, and every match
23
+ * keeps its newlines so the result has the same line count: a frame's
24
+ * `firstLine` and highlighted `line` index into this array.
25
+ */
26
+ redactSource(lines: string[]): string[];
27
+ private apply;
9
28
  redactAttributes(attributes: Record<string, unknown> | undefined): Record<string, unknown> | undefined;
10
29
  private redactValue;
11
30
  }
@@ -1,3 +1,4 @@
1
+ import { createSensitiveKeyMatcher, } from "./sensitive-keys.js";
1
2
  /**
2
3
  * Strips secrets out of log lines before they leave the process.
3
4
  *
@@ -18,35 +19,11 @@
18
19
  * a shape nothing here matches will still ship it.
19
20
  */
20
21
  const DEFAULT_REPLACEMENT = "[REDACTED]";
21
- /**
22
- * Attribute keys whose values are masked outright, whatever they contain.
23
- * Matched case-insensitively, ignoring `-` and `_`.
24
- */
25
- const DEFAULT_SENSITIVE_KEYS = [
26
- "password",
27
- "passwd",
28
- "pwd",
29
- "secret",
30
- "token",
31
- "accesstoken",
32
- "refreshtoken",
33
- "idtoken",
34
- "apikey",
35
- "authorization",
36
- "auth",
37
- "credential",
38
- "credentials",
39
- "privatekey",
40
- "accesskey",
41
- "secretkey",
42
- "sessionid",
43
- "cookie",
44
- "setcookie",
45
- ];
46
22
  /**
47
23
  * Key names recognised inside free text, as `key=value` or `"key": "value"`.
48
- * Kept in step with DEFAULT_SENSITIVE_KEYS but spelled for a regex, where the
49
- * separators are still present.
24
+ * Spelled for a regex, where the separators are still present. Unanchored on
25
+ * the left, so a compound name - `resetToken=`, `client_secret=` - matches on
26
+ * its ending, the same way `sensitive-keys.ts` matches a structured key.
50
27
  */
51
28
  const TEXT_KEY_ALTERNATION = [
52
29
  "password",
@@ -68,7 +45,17 @@ const TEXT_KEY_ALTERNATION = [
68
45
  "set-cookie",
69
46
  "cookie",
70
47
  ].join("|");
71
- function buildDefaultRules() {
48
+ /**
49
+ * `literalValuesOnly` is the variant for source code, where the text either
50
+ * side of a `:` or `=` is mostly identifiers: `const token = await sign(user)`
51
+ * assigns no secret, and masking `await` would shred every frame that mentions
52
+ * a credential by name. In source a secret is a literal, so only a quoted
53
+ * value is masked there.
54
+ */
55
+ function buildDefaultRules(literalValuesOnly = false) {
56
+ const value = literalValuesOnly
57
+ ? "(?:\"[^\"\\n]*\"|'[^'\\n]*'|`[^`]*`)"
58
+ : "(?:\"[^\"]*\"|'[^']*'|(?:Bearer|Basic|Token)\\s+\\S+|[^\\s,;&}\"']+)";
72
59
  return [
73
60
  // PEM blocks first: they span lines and would otherwise be partially eaten
74
61
  // by the narrower rules below.
@@ -93,7 +80,7 @@ function buildDefaultRules() {
93
80
  // form, so an already-masked `Authorization: Bearer [REDACTED]` collapses to
94
81
  // a single `[REDACTED]` rather than stacking two.
95
82
  {
96
- pattern: new RegExp(`((?:${TEXT_KEY_ALTERNATION})"?\\s*[:=]\\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic|Token)\\s+\\S+|[^\\s,;&}"']+)`, "gi"),
83
+ pattern: new RegExp(`((?:${TEXT_KEY_ALTERNATION})["']?\\s*[:=]\\s*)${value}`, "gi"),
97
84
  replace: (replacement, prefix) => `${prefix}${replacement}`,
98
85
  },
99
86
  // Bare JWTs - they show up outside any header often enough to matter.
@@ -143,7 +130,8 @@ function isLuhnValid(digits) {
143
130
  const MAX_ATTRIBUTE_DEPTH = 8;
144
131
  export class LogRedactor {
145
132
  rules;
146
- sensitiveKeys;
133
+ sourceRules;
134
+ matchesSensitiveKey;
147
135
  replacement;
148
136
  redactCards;
149
137
  constructor(options = {}) {
@@ -159,15 +147,46 @@ export class LogRedactor {
159
147
  replace: (replacement) => replacement,
160
148
  }));
161
149
  this.rules = [...defaults, ...extra];
162
- this.sensitiveKeys = new Set([...DEFAULT_SENSITIVE_KEYS, ...(options.keys ?? [])].map(normaliseKey));
150
+ this.sourceRules = [
151
+ ...(options.useDefaultPatterns === false ? [] : buildDefaultRules(true)),
152
+ ...extra,
153
+ ];
154
+ this.matchesSensitiveKey = createSensitiveKeyMatcher(options.keys);
155
+ }
156
+ /**
157
+ * Whether a key names a credential - the built-in rules plus the configured
158
+ * `keys`. Exposed so a caller masking by key somewhere this class does not
159
+ * reach (a URL's query string) is held to the same list.
160
+ */
161
+ isSensitiveKey(key) {
162
+ return this.matchesSensitiveKey(key);
163
163
  }
164
164
  redactMessage(message) {
165
- let output = message;
166
- for (const rule of this.rules) {
165
+ return this.apply(message, this.rules, false);
166
+ }
167
+ /**
168
+ * Redacts lines of source code read for a code frame.
169
+ *
170
+ * Source is shipped for the same reason a message is, and a literal in it -
171
+ * `password: "hunter2"`, a pasted key - is as much a secret there as in a
172
+ * log line. The lines are redacted as one text so a block spanning several
173
+ * (a PEM key in a template literal) is still seen whole, and every match
174
+ * keeps its newlines so the result has the same line count: a frame's
175
+ * `firstLine` and highlighted `line` index into this array.
176
+ */
177
+ redactSource(lines) {
178
+ return this.apply(lines.join("\n"), this.sourceRules, true).split("\n");
179
+ }
180
+ apply(text, rules, keepNewlines) {
181
+ let output = text;
182
+ const keep = (match, masked) => keepNewlines
183
+ ? masked + "\n".repeat(match.split("\n").length - 1)
184
+ : masked;
185
+ for (const rule of rules) {
167
186
  output = output.replace(rule.pattern, (...args) => {
168
187
  // String.replace passes offset and the whole string after the groups.
169
188
  const groups = args.slice(1, -2).map((group) => group ?? "");
170
- return rule.replace(this.replacement, ...groups);
189
+ return keep(args[0], rule.replace(this.replacement, ...groups));
171
190
  });
172
191
  }
173
192
  if (this.redactCards) {
@@ -202,7 +221,7 @@ export class LogRedactor {
202
221
  // A sensitive key masks its value whatever the shape - an object under
203
222
  // `credentials` is exactly what must not be walked into and partially
204
223
  // preserved.
205
- this.sensitiveKeys.has(normaliseKey(key))
224
+ this.matchesSensitiveKey(key)
206
225
  ? this.replacement
207
226
  : this.redactValue(item, depth + 1),
208
227
  ]));
@@ -210,6 +229,3 @@ export class LogRedactor {
210
229
  return value;
211
230
  }
212
231
  }
213
- function normaliseKey(key) {
214
- return key.toLowerCase().replace(/[-_]/g, "");
215
- }
@@ -40,3 +40,16 @@ export type OptionalPeerResult<T> = {
40
40
  /** Names a load failure for a log line: the message for an `Error`, `String` otherwise. */
41
41
  export declare function describePeerLoadError(error: unknown): string;
42
42
  export declare function loadOptionalPeer<T>(packageName: string, specifier?: string): OptionalPeerResult<T>;
43
+ /**
44
+ * Loads `specifier` the way another installed package would resolve it, or
45
+ * `undefined` when that package is absent or resolves nothing of its own.
46
+ *
47
+ * For a driver that an ORM depends on directly. npm gives the ORM a nested
48
+ * copy whenever the application's own version of the driver is outside the
49
+ * range the ORM asks for - `mongodb@6` beside a Mongoose that wants 7 - and a
50
+ * patch applied to the copy *this* package resolves never touches the one the
51
+ * ORM runs on. Queries through the ORM would then go unrecorded with nothing
52
+ * to say why. When both resolve to the same file the caller patches one
53
+ * prototype twice, which `patchMethod` is built to shrug off.
54
+ */
55
+ export declare function loadAsResolvedBy<T>(dependentPackage: string, specifier: string): T | undefined;
@@ -72,3 +72,33 @@ function resolveWithinPackage(require, packageName, specifier) {
72
72
  return undefined;
73
73
  }
74
74
  }
75
+ /**
76
+ * Loads `specifier` the way another installed package would resolve it, or
77
+ * `undefined` when that package is absent or resolves nothing of its own.
78
+ *
79
+ * For a driver that an ORM depends on directly. npm gives the ORM a nested
80
+ * copy whenever the application's own version of the driver is outside the
81
+ * range the ORM asks for - `mongodb@6` beside a Mongoose that wants 7 - and a
82
+ * patch applied to the copy *this* package resolves never touches the one the
83
+ * ORM runs on. Queries through the ORM would then go unrecorded with nothing
84
+ * to say why. When both resolve to the same file the caller patches one
85
+ * prototype twice, which `patchMethod` is built to shrug off.
86
+ */
87
+ export function loadAsResolvedBy(dependentPackage, specifier) {
88
+ try {
89
+ const require = createRequire(import.meta.url);
90
+ let anchor;
91
+ try {
92
+ anchor = require.resolve(`${dependentPackage}/package.json`);
93
+ }
94
+ catch {
95
+ // An `exports` map that does not list its own package.json. Any file
96
+ // inside the package anchors resolution equally well.
97
+ anchor = require.resolve(dependentPackage);
98
+ }
99
+ return createRequire(anchor)(specifier);
100
+ }
101
+ catch {
102
+ return undefined;
103
+ }
104
+ }
@@ -1,3 +1,4 @@
1
+ import { SensitiveKeyMatcher } from "./sensitive-keys.js";
1
2
  export declare const REDACTED = "[REDACTED]";
2
3
  /**
3
4
  * Masks the values of sensitive query parameters in a request URL.
@@ -16,4 +17,12 @@ export declare const REDACTED = "[REDACTED]";
16
17
  * anywhere in a URL mangles ordinary path segments and ids, and a redactor that
17
18
  * mangles real data is one somebody switches off.
18
19
  */
19
- export declare function redactUrlQuery(url: string): string;
20
+ export declare function redactUrlQuery(url: string,
21
+ /**
22
+ * The deployment's redactor, so its `redaction.keys` apply to a URL as they
23
+ * do to a log attribute. Without one the built-in rules still apply: masking
24
+ * a URL is not something `redaction.enabled: false` switches off.
25
+ */
26
+ redactor?: {
27
+ isSensitiveKey: SensitiveKeyMatcher;
28
+ } | null): string;