@nestjs/observe 0.2.3 → 0.3.0

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 (59) 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/operation-trace.registry.d.ts +17 -1
  41. package/dist/services/operation-trace.registry.js +39 -7
  42. package/dist/services/trace-sampler.service.d.ts +4 -0
  43. package/dist/services/tracer.service.js +5 -3
  44. package/dist/utils/capture-request.util.d.ts +57 -0
  45. package/dist/utils/capture-request.util.js +116 -0
  46. package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
  47. package/dist/utils/default-trace-id-generator.util.js +12 -1
  48. package/dist/utils/log-redactor.d.ts +20 -1
  49. package/dist/utils/log-redactor.js +54 -38
  50. package/dist/utils/optional-peer.util.d.ts +13 -0
  51. package/dist/utils/optional-peer.util.js +30 -0
  52. package/dist/utils/redact-url-query.d.ts +10 -1
  53. package/dist/utils/redact-url-query.js +16 -37
  54. package/dist/utils/sensitive-keys.d.ts +15 -0
  55. package/dist/utils/sensitive-keys.js +76 -0
  56. package/dist/utils/source-context.util.d.ts +6 -0
  57. package/dist/utils/source-context.util.js +113 -15
  58. package/dist/utils/source-map-resolver.util.js +12 -0
  59. package/package.json +35 -2
@@ -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;
@@ -1,42 +1,14 @@
1
+ import { isSensitiveKeyByDefault, normaliseKey, } from "./sensitive-keys.js";
1
2
  /**
2
- * Query-string keys whose values never belong in stored telemetry.
3
+ * Query-string keys masked on top of the shared list in `sensitive-keys.ts`.
3
4
  *
4
- * Deliberately the same list the log redactor works from, spelled for query
5
- * parameters: a password-reset link is as sensitive in a URL as the same token
6
- * is in a log line, and two lists that drift apart mean one of the two paths
7
- * quietly stops protecting something.
8
- *
9
- * Matched case-insensitively, ignoring `-` and `_`, so `access_token`,
10
- * `accessToken` and `access-token` are one entry.
5
+ * These are sensitive in a URL and ordinary anywhere else, which is why they
6
+ * are not in the shared list: `?code=` is an OAuth authorization code and
7
+ * `?key=` an API key, but a log attribute called `code` is an error code and
8
+ * masking it would cost more than it protects.
11
9
  */
12
- const SENSITIVE_QUERY_KEYS = new Set([
13
- "password",
14
- "passwd",
15
- "pwd",
16
- "secret",
17
- "token",
18
- "accesstoken",
19
- "refreshtoken",
20
- "idtoken",
21
- "apikey",
22
- "apitoken",
23
- "authorization",
24
- "auth",
25
- "code",
26
- "credential",
27
- "credentials",
28
- "privatekey",
29
- "accesskey",
30
- "secretkey",
31
- "sessionid",
32
- "sig",
33
- "signature",
34
- "state",
35
- ]);
10
+ const URL_ONLY_SENSITIVE_KEYS = new Set(["code", "state", "sig", "key"]);
36
11
  export const REDACTED = "[REDACTED]";
37
- function normaliseKey(key) {
38
- return key.toLowerCase().replace(/[-_]/g, "");
39
- }
40
12
  /**
41
13
  * Masks the values of sensitive query parameters in a request URL.
42
14
  *
@@ -54,7 +26,13 @@ function normaliseKey(key) {
54
26
  * anywhere in a URL mangles ordinary path segments and ids, and a redactor that
55
27
  * mangles real data is one somebody switches off.
56
28
  */
57
- export function redactUrlQuery(url) {
29
+ export function redactUrlQuery(url,
30
+ /**
31
+ * The deployment's redactor, so its `redaction.keys` apply to a URL as they
32
+ * do to a log attribute. Without one the built-in rules still apply: masking
33
+ * a URL is not something `redaction.enabled: false` switches off.
34
+ */
35
+ redactor) {
58
36
  const separator = url.indexOf("?");
59
37
  if (separator === -1) {
60
38
  return url;
@@ -75,7 +53,8 @@ export function redactUrlQuery(url) {
75
53
  // iterator walks, so the keys have to be materialised before the loop starts.
76
54
  // oxlint-disable-next-line unicorn/no-useless-spread
77
55
  for (const key of [...params.keys()]) {
78
- if (SENSITIVE_QUERY_KEYS.has(normaliseKey(key))) {
56
+ if (URL_ONLY_SENSITIVE_KEYS.has(normaliseKey(key)) ||
57
+ (redactor ? redactor.isSensitiveKey(key) : isSensitiveKeyByDefault(key))) {
79
58
  params.set(key, REDACTED);
80
59
  redactedAny = true;
81
60
  }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The one definition of "this key names a credential", shared by everything
3
+ * that masks by key - log attributes, captured headers, URL query strings.
4
+ * Two lists that drift apart mean one of the paths quietly stops protecting
5
+ * something the other still does.
6
+ */
7
+ /** Case-insensitive, ignoring `-` and `_`: `api_key`, `apiKey`, `API-KEY` are one key. */
8
+ export declare function normaliseKey(key: string): string;
9
+ export type SensitiveKeyMatcher = (key: string) => boolean;
10
+ /**
11
+ * Builds the matcher, with `extraKeys` - the deployment's own `redaction.keys`
12
+ * - matched exactly (after normalising) on top of the built-in rules.
13
+ */
14
+ export declare function createSensitiveKeyMatcher(extraKeys?: Iterable<string>): SensitiveKeyMatcher;
15
+ export declare const isSensitiveKeyByDefault: SensitiveKeyMatcher;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The one definition of "this key names a credential", shared by everything
3
+ * that masks by key - log attributes, captured headers, URL query strings.
4
+ * Two lists that drift apart mean one of the paths quietly stops protecting
5
+ * something the other still does.
6
+ */
7
+ /**
8
+ * Keys masked only when they are the whole key. Too short or too generic to be
9
+ * matched inside a longer name: `auth` would take `author` with it.
10
+ */
11
+ const EXACT_KEYS = ["pwd", "auth"];
12
+ /**
13
+ * What a credential's name ends in. Real applications do not call the
14
+ * parameter `token`; they call it `resetToken`, `client_secret`,
15
+ * `X-Amz-Signature`, `x-api-key` - so an exact-match list protects the
16
+ * spelling in the documentation and little else.
17
+ *
18
+ * A suffix rather than a substring, which is what keeps this precise: a
19
+ * credential's name ends in the noun, and the keys that merely mention one -
20
+ * `maxTokens`, `tokenCount`, `secretary` - do not.
21
+ */
22
+ const SENSITIVE_SUFFIXES = [
23
+ "password",
24
+ "passwd",
25
+ "secret",
26
+ "token",
27
+ "credential",
28
+ "credentials",
29
+ "signature",
30
+ "jwt",
31
+ "cookie",
32
+ "apikey",
33
+ "privatekey",
34
+ "accesskey",
35
+ "secretkey",
36
+ "sessionid",
37
+ "authorization",
38
+ ];
39
+ /**
40
+ * Words that mark a key as sensitive wherever they sit in it, for the names
41
+ * that put the noun first: `passwordConfirmation`, `secret_value`. `token` is
42
+ * deliberately absent - `tokenCount` and `tokenLimit` are ordinary numbers.
43
+ */
44
+ const SENSITIVE_WORDS = new Set([
45
+ "password",
46
+ "passwd",
47
+ "secret",
48
+ "credential",
49
+ "credentials",
50
+ ]);
51
+ /** Case-insensitive, ignoring `-` and `_`: `api_key`, `apiKey`, `API-KEY` are one key. */
52
+ export function normaliseKey(key) {
53
+ return key.toLowerCase().replace(/[-_]/g, "");
54
+ }
55
+ function wordsOf(key) {
56
+ return key
57
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
58
+ .toLowerCase()
59
+ .split(/[^a-z0-9]+/);
60
+ }
61
+ /**
62
+ * Builds the matcher, with `extraKeys` - the deployment's own `redaction.keys`
63
+ * - matched exactly (after normalising) on top of the built-in rules.
64
+ */
65
+ export function createSensitiveKeyMatcher(extraKeys = []) {
66
+ const exact = new Set([...EXACT_KEYS, ...extraKeys].map(normaliseKey));
67
+ return (key) => {
68
+ const normalised = normaliseKey(key);
69
+ // `password2`, `token_1`: a numbered credential is still one.
70
+ const stem = normalised.replace(/\d+$/, "");
71
+ return (exact.has(normalised) ||
72
+ SENSITIVE_SUFFIXES.some((suffix) => stem.endsWith(suffix)) ||
73
+ wordsOf(key).some((word) => SENSITIVE_WORDS.has(word)));
74
+ };
75
+ }
76
+ export const isSensitiveKeyByDefault = createSensitiveKeyMatcher();
@@ -30,4 +30,10 @@ export declare function collectCodeFrames(stack: string | undefined, options?: {
30
30
  linesOfContext?: number;
31
31
  maxFrames?: number;
32
32
  sourceMaps?: boolean;
33
+ /**
34
+ * The error's own `message`, which is how the frames are told apart from
35
+ * message text that looks like one - see `frameLines`. Always pass it for
36
+ * a stack that came off an error.
37
+ */
38
+ message?: string;
33
39
  }): CodeFrame[] | undefined;