@nestjs/observe 0.3.25 → 0.3.26

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 (94) hide show
  1. package/README.md +17 -0
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +41 -17
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +158 -96
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.js +7 -3
  34. package/dist/otlp/otlp-trace-exporter.service.js +63 -5
  35. package/dist/outgoing/http.integration.d.ts +8 -4
  36. package/dist/outgoing/http.integration.js +13 -6
  37. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  38. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  39. package/dist/outgoing/llm/llm-providers.js +72 -22
  40. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  41. package/dist/outgoing/llm/llm-usage.js +72 -25
  42. package/dist/outgoing/mssql.integration.js +16 -2
  43. package/dist/outgoing/mysql2.integration.js +17 -1
  44. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  45. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  46. package/dist/outgoing/pg.integration.d.ts +3 -2
  47. package/dist/outgoing/pg.integration.js +39 -11
  48. package/dist/outgoing/sql-statement.util.js +106 -14
  49. package/dist/outgoing/undici.integration.d.ts +13 -0
  50. package/dist/outgoing/undici.integration.js +68 -0
  51. package/dist/protocols/bull-observe-agent.service.js +2 -12
  52. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  53. package/dist/protocols/deferred-trace-completion.js +36 -6
  54. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  55. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  56. package/dist/protocols/graphql-operation-parser.js +72 -18
  57. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  58. package/dist/protocols/http-observe-agent.service.js +177 -59
  59. package/dist/protocols/job-trace-runner.d.ts +35 -3
  60. package/dist/protocols/job-trace-runner.js +126 -29
  61. package/dist/protocols/queue-observe-agent.service.js +44 -20
  62. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  63. package/dist/protocols/rpc-observe-agent.service.js +187 -47
  64. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  65. package/dist/protocols/ws-observe-agent.service.js +226 -20
  66. package/dist/services/index.d.ts +1 -1
  67. package/dist/services/index.js +1 -1
  68. package/dist/services/logger-patcher.service.js +3 -4
  69. package/dist/services/operation-trace.registry.d.ts +45 -1
  70. package/dist/services/operation-trace.registry.js +418 -35
  71. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  72. package/dist/services/stdout-forwarder.service.js +288 -51
  73. package/dist/services/tracer.service.d.ts +23 -0
  74. package/dist/services/tracer.service.js +91 -5
  75. package/dist/utils/capture-request.util.d.ts +3 -1
  76. package/dist/utils/capture-request.util.js +100 -12
  77. package/dist/utils/fit-to-length.util.js +33 -10
  78. package/dist/utils/log-line.parser.d.ts +14 -0
  79. package/dist/utils/log-line.parser.js +7 -3
  80. package/dist/utils/log-redactor.d.ts +14 -0
  81. package/dist/utils/log-redactor.js +512 -61
  82. package/dist/utils/operation-state.util.d.ts +39 -0
  83. package/dist/utils/operation-state.util.js +50 -0
  84. package/dist/utils/redact-url-query.d.ts +26 -4
  85. package/dist/utils/redact-url-query.js +184 -32
  86. package/dist/utils/sensitive-keys.d.ts +4 -1
  87. package/dist/utils/sensitive-keys.js +48 -10
  88. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  89. package/dist/utils/shared-hook-slot.util.js +103 -0
  90. package/dist/utils/source-context.util.d.ts +8 -0
  91. package/dist/utils/source-context.util.js +88 -24
  92. package/dist/utils/source-map-resolver.util.js +8 -2
  93. package/dist/utils/trace-context.util.js +21 -6
  94. package/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import { stripAnsi } from "./log-line.parser.js";
1
2
  import { createSensitiveKeyMatcher, } from "./sensitive-keys.js";
2
3
  /**
3
4
  * Strips secrets out of log lines before they leave the process.
@@ -20,77 +21,417 @@ import { createSensitiveKeyMatcher, } from "./sensitive-keys.js";
20
21
  */
21
22
  const DEFAULT_REPLACEMENT = "[REDACTED]";
22
23
  /**
23
- * Key names recognised inside free text, as `key=value` or `"key": "value"`.
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.
24
+ * Where a bare token may start: not inside a word, but also right after a
25
+ * percent escape (`%2FeyJ...`, a URL-encoded path) or a JSON escape
26
+ * (`\neyJ...`, `\u0022eyJ...`), whose last character would otherwise read as
27
+ * the token's own.
27
28
  */
28
- const TEXT_KEY_ALTERNATION = [
29
- "password",
30
- "passwd",
31
- "pwd",
32
- "secret",
33
- "token",
34
- "access[_-]?token",
35
- "refresh[_-]?token",
36
- "id[_-]?token",
37
- "api[_-]?key",
38
- "authorization",
39
- "auth",
40
- "credentials?",
41
- "private[_-]?key",
42
- "access[_-]?key",
43
- "secret[_-]?key",
44
- "session[_-]?id",
45
- "set-cookie",
46
- "cookie",
47
- ].join("|");
29
+ const TOKEN_START = String.raw `(?:(?<![A-Za-z0-9_-])|(?<=%[0-9A-Fa-f]{2})|(?<=\\[nrtbf])|(?<=\\u[0-9A-Fa-f]{4}))`;
48
30
  /**
31
+ * A run of base64url characters at least `min` long. Written as `{min}` and
32
+ * then `*` rather than `{min,}`: V8 keeps a backtrack entry per character of a
33
+ * counted quantifier, and a run of ~5.6 MB exhausted its stack, so recording
34
+ * the error replaced it with a RangeError.
35
+ */
36
+ const tokenRun = (min) => min === 0 ? "[A-Za-z0-9_-]*" : `[A-Za-z0-9_-]{${min}}[A-Za-z0-9_-]*`;
37
+ const PEM_BEGIN = /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----/g;
38
+ const PEM_END = /-----END (?:[A-Z ]+ )?PRIVATE KEY-----/g;
39
+ /** The shortest line of base64 taken for the body of a key with no END line. */
40
+ const MIN_PEM_BODY_LINE = 16;
41
+ /**
42
+ * PEM private keys, BEGIN through END.
43
+ *
44
+ * A scan rather than `BEGIN[\s\S]*?END`: on a BEGIN marker with no END after
45
+ * it that lazy run read to the end of the text before failing, and every
46
+ * later marker read it again - quadratic, on an error message a client can
47
+ * fill. Here the END markers are found once, and each BEGIN is paired with the
48
+ * first one after it, as the lazy run did.
49
+ *
50
+ * A BEGIN with no END after it is a key cut off - by a truncated message, the
51
+ * edge of a code frame - and its body is masked as far as it still reads as
52
+ * one: lines of base64, the first at least `MIN_PEM_BODY_LINE` long. A marker
53
+ * that heads no such line (quoted in prose, or in code that checks for one) is
54
+ * left as it was.
55
+ */
56
+ function scanPemBlocks(text, mask) {
57
+ if (!text.includes("PRIVATE KEY-----")) {
58
+ return text;
59
+ }
60
+ const ends = [];
61
+ for (const match of text.matchAll(PEM_END)) {
62
+ ends.push([match.index, match.index + match[0].length]);
63
+ }
64
+ let output = "";
65
+ let copiedTo = 0;
66
+ let nextEnd = 0;
67
+ const begin = new RegExp(PEM_BEGIN.source, "g");
68
+ let match;
69
+ while ((match = begin.exec(text))) {
70
+ const bodyFrom = match.index + match[0].length;
71
+ while (nextEnd < ends.length && ends[nextEnd][0] < bodyFrom) {
72
+ nextEnd++;
73
+ }
74
+ const blockEnd = nextEnd < ends.length ? ends[nextEnd++][1] : pemBodyEnd(text, bodyFrom);
75
+ if (blockEnd === undefined) {
76
+ continue;
77
+ }
78
+ output +=
79
+ text.slice(copiedTo, match.index) +
80
+ mask(text.slice(match.index, blockEnd));
81
+ copiedTo = blockEnd;
82
+ begin.lastIndex = blockEnd;
83
+ }
84
+ return copiedTo === 0 ? text : output + text.slice(copiedTo);
85
+ }
86
+ /**
87
+ * Where the base64 lines after a BEGIN marker stop, or `undefined` when none
88
+ * follows it. A line break may be written raw or JSON-escaped.
89
+ */
90
+ function pemBodyEnd(text, from) {
91
+ let end;
92
+ let at = from;
93
+ for (let line = 0;; line++) {
94
+ const breakLength = lineBreakAt(text, at);
95
+ if (breakLength === 0) {
96
+ return end;
97
+ }
98
+ let runEnd = at + breakLength;
99
+ while (runEnd < text.length &&
100
+ (text[runEnd] === " " || text[runEnd] === "\t")) {
101
+ runEnd++;
102
+ }
103
+ const runStart = runEnd;
104
+ while (runEnd < text.length && isBase64Char(text.charCodeAt(runEnd))) {
105
+ runEnd++;
106
+ }
107
+ const length = runEnd - runStart;
108
+ if (length === 0 || (line === 0 && length < MIN_PEM_BODY_LINE)) {
109
+ return end;
110
+ }
111
+ end = runEnd;
112
+ at = runEnd;
113
+ }
114
+ }
115
+ function lineBreakAt(text, at) {
116
+ if (text[at] === "\n") {
117
+ return 1;
118
+ }
119
+ if (text[at] === "\r") {
120
+ return text[at + 1] === "\n" ? 2 : 1;
121
+ }
122
+ if (text[at] === "\\") {
123
+ if (text[at + 1] === "n") {
124
+ return 2;
125
+ }
126
+ if (text[at + 1] === "r" && text[at + 2] === "\\" && text[at + 3] === "n") {
127
+ return 4;
128
+ }
129
+ }
130
+ return 0;
131
+ }
132
+ function isBase64Char(code) {
133
+ return ((code >= 65 && code <= 90) ||
134
+ (code >= 97 && code <= 122) ||
135
+ (code >= 48 && code <= 57) ||
136
+ code === 43 ||
137
+ code === 47 ||
138
+ code === 61);
139
+ }
140
+ /**
141
+ * A name followed by `:`, `=`, `:=` or `=>`, as free text writes a pair:
142
+ * `password=x`, `"token": "x"`, `\"secret\":\"x\"` (JSON inside a string),
143
+ * `'password' => 'x'` (util.inspect of a Map), `api.key: x`, `auth[token]=x`.
144
+ * Not `==`, which compares rather than assigns, and `=>` only after a quoted
145
+ * name, as util.inspect writes one - otherwise it is an arrow function. Must
146
+ * not start inside a name,
147
+ * so each name is tried once, from its first character; a bracket is not part
148
+ * of the name's own run, so `[token=x]` is a name after a bracket.
149
+ */
150
+ const KEY_CANDIDATE = /(?<![\w$.-])((?:\\?["'])?)([A-Za-z_$][\w$.-]*(?:\[[\w$.-]*\])*)((?:\\?["'])?)[ \t]*(:=|=>|:|=(?!=))[ \t]*/g;
151
+ /**
152
+ * What every name the shared matcher calls sensitive contains, written
153
+ * without separators. Tested first so the matcher - which splits a name into
154
+ * words - runs only for the few names that could be one.
155
+ */
156
+ const KEY_STEMS = /pass|pwd|secret|token|auth|cred|key|sig|jwt|cookie|session/i;
157
+ /**
158
+ * Names whose value is a whole header: a scheme and a credential
159
+ * (`Authorization: ApiKey sk_...`), or every cookie of a `Cookie` line.
160
+ */
161
+ const HEADER_KEY = /(?:authorization|cookie)$/;
162
+ /** Where a bare value ends: what the old rule's `[^\s,;&}"']` stopped at. */
163
+ const BARE_VALUE_END = /[\s,;&}"']/;
164
+ /**
165
+ * Where a header value ends: the line, a quote, or the object it sits in. Not
166
+ * a comma - a Digest credential is a list of them.
167
+ */
168
+ const HEADER_VALUE_END = /[\r\n"'\\}]/;
169
+ const SCHEME_WORD = /^(?:bearer|basic|token)$/i;
170
+ /**
171
+ * `key=value` / `"key": "value"`, the value masked and the key kept - a log
172
+ * reading `password=[REDACTED]` is far more useful than one where the whole
173
+ * pair vanished.
174
+ *
175
+ * A scan rather than a regex, for what a regex could not read: a quoted value
176
+ * past the quotes it escapes, JSON inside a string (`\"password\":\"x\"`), a
177
+ * value cut off before its closing quote, an object or array under a
178
+ * sensitive name, a header that runs past its first space. Every character is
179
+ * read a bounded number of times: a value is read once, and the scan resumes
180
+ * after it.
181
+ *
182
+ * The name is held to the same matcher as an attribute's key - the
183
+ * deployment's `redaction.keys` included - so free text and structured data
184
+ * cannot drift apart.
185
+ *
49
186
  * `literalValuesOnly` is the variant for source code, where the text either
50
187
  * side of a `:` or `=` is mostly identifiers: `const token = await sign(user)`
51
188
  * assigns no secret, and masking `await` would shred every frame that mentions
52
189
  * a credential by name. In source a secret is a literal, so only a quoted
53
190
  * value is masked there.
54
191
  */
55
- function buildDefaultRules(literalValuesOnly = false) {
56
- const value = literalValuesOnly
57
- ? "(?:\"[^\"\\n]*\"|'[^'\\n]*'|`[^`]*`)"
58
- : "(?:\"[^\"]*\"|'[^']*'|(?:Bearer|Basic|Token)\\s+\\S+|[^\\s,;&}\"']+)";
192
+ function keyValueRule(isSensitiveKey, checkEveryKey, literalValuesOnly) {
193
+ const isSensitive = (key) => {
194
+ const bare = key.replace(/[-_. [\]]/g, "");
195
+ return (checkEveryKey || KEY_STEMS.test(bare)) && isSensitiveKey(key);
196
+ };
197
+ return {
198
+ scan: (text, mask) => {
199
+ // Most lines name no credential at all; they are passed over whole.
200
+ if (!checkEveryKey && !KEY_STEMS.test(text)) {
201
+ return text;
202
+ }
203
+ const candidate = new RegExp(KEY_CANDIDATE.source, "g");
204
+ let output = "";
205
+ let copiedTo = 0;
206
+ let match;
207
+ while ((match = candidate.exec(text))) {
208
+ const key = match[2];
209
+ if ((match[4] === "=>" && !match[3]) || !isSensitive(key)) {
210
+ continue;
211
+ }
212
+ const valueStart = match.index + match[0].length;
213
+ // `"token=" + token`: a quote opened before the name and not closed
214
+ // after it means the pair is inside a string, and a value starting
215
+ // with that quote is the string ending, not a value.
216
+ const enclosing = match[3] ? "" : match[1].replace("\\", "");
217
+ if (enclosing &&
218
+ (text[valueStart] === enclosing ||
219
+ (text[valueStart] === "\\" && text[valueStart + 1] === enclosing))) {
220
+ continue;
221
+ }
222
+ const header = HEADER_KEY.test(key.toLowerCase().replace(/[-_]/g, ""));
223
+ const valueEnd = readValue(text, valueStart, literalValuesOnly, header);
224
+ if (valueEnd === -1) {
225
+ continue;
226
+ }
227
+ output += text.slice(copiedTo, valueStart);
228
+ output += mask(text.slice(valueStart, valueEnd));
229
+ copiedTo = valueEnd;
230
+ candidate.lastIndex = valueEnd;
231
+ }
232
+ return copiedTo === 0 ? text : output + text.slice(copiedTo);
233
+ },
234
+ };
235
+ }
236
+ /** Where the value starting at `at` ends, or -1 when there is none to mask. */
237
+ function readValue(text, at, literalValuesOnly, header) {
238
+ const first = text[at];
239
+ if (first === undefined) {
240
+ return -1;
241
+ }
242
+ let end;
243
+ if (first === "\\" && (text[at + 1] === '"' || text[at + 1] === "'")) {
244
+ end = readEscapedQuoted(text, at);
245
+ }
246
+ else if (first === '"' || first === "'" || first === "`") {
247
+ end = readQuoted(text, at, literalValuesOnly);
248
+ }
249
+ else if (literalValuesOnly) {
250
+ return -1;
251
+ }
252
+ else if (header) {
253
+ end = runUntil(text, at, HEADER_VALUE_END);
254
+ return end === at ? -1 : end;
255
+ }
256
+ else if (first === "{" || first === "[") {
257
+ end = readBracketed(text, at);
258
+ }
259
+ else {
260
+ end = runUntil(text, at, BARE_VALUE_END);
261
+ if (end === at || text[end - 1] === ":") {
262
+ // Nothing, or the next pair's key: `currentPassword: newPassword: x`.
263
+ return -1;
264
+ }
265
+ if (SCHEME_WORD.test(text.slice(at, end)) && /[ \t]/.test(text[end])) {
266
+ // `token: Bearer eyJ...` - the credential, not just its scheme.
267
+ const credential = skipBlanks(text, end);
268
+ const credentialEnd = runUntil(text, credential, /\s/);
269
+ return credentialEnd > credential ? credentialEnd : end;
270
+ }
271
+ return end;
272
+ }
273
+ if (literalValuesOnly) {
274
+ return end;
275
+ }
276
+ // A quoted name rather than a value: `"currentPassword": "newPassword": x`.
277
+ const after = skipBlanks(text, end);
278
+ if (text[after] === ":" &&
279
+ end < text.length &&
280
+ first !== "{" &&
281
+ first !== "[") {
282
+ return -1;
283
+ }
284
+ // Text run on behind a closing quote or bracket is the value's too:
285
+ // `token=[abc]def`.
286
+ while (end < text.length && /\w/.test(text[end])) {
287
+ end++;
288
+ }
289
+ return end;
290
+ }
291
+ function runUntil(text, at, stop) {
292
+ let end = at;
293
+ while (end < text.length && !stop.test(text[end])) {
294
+ end++;
295
+ }
296
+ return end;
297
+ }
298
+ function skipBlanks(text, at) {
299
+ let end = at;
300
+ while (text[end] === " " || text[end] === "\t") {
301
+ end++;
302
+ }
303
+ return end;
304
+ }
305
+ /**
306
+ * A quoted value through its closing quote, past the quotes it escapes.
307
+ *
308
+ * In a message the value runs on through line breaks to its closing quote:
309
+ * a multi-line secret, or a key the forwarder joined with its continuation
310
+ * lines, is masked whole rather than its first line only. One never closed -
311
+ * a message cut short - runs to the end of the line it started on, so what it
312
+ * held is masked rather than the head of it kept, and the rest of the text is
313
+ * not. In source only a template literal spans lines, and one never closed
314
+ * runs to the end of the text.
315
+ *
316
+ * Linear over a whole text: a scan that finds no closing quote proves there is
317
+ * no later quote of its kind, so no later value opening with one can scan
318
+ * again - at most one fruitless scan per kind of quote.
319
+ */
320
+ function readQuoted(text, at, inSource = false) {
321
+ const quote = text[at];
322
+ const spansLines = !inSource || quote === "`";
323
+ let lineEnd = -1;
324
+ for (let i = at + 1; i < text.length; i++) {
325
+ const char = text[i];
326
+ if (char === "\\") {
327
+ i++;
328
+ }
329
+ else if (char === quote) {
330
+ return i + 1;
331
+ }
332
+ else if (char === "\n") {
333
+ if (!spansLines) {
334
+ return i;
335
+ }
336
+ if (lineEnd === -1) {
337
+ lineEnd = i;
338
+ }
339
+ }
340
+ }
341
+ return inSource || lineEnd === -1 ? text.length : lineEnd;
342
+ }
343
+ /**
344
+ * A value quoted with escaped quotes - `\"x\"`, JSON inside a JSON string -
345
+ * through its closing `\"`. Inside it, a quote of its own is `\\\"`; a quote
346
+ * behind an even run of backslashes is the enclosing string's, and ends the
347
+ * value before it.
348
+ */
349
+ function readEscapedQuoted(text, at) {
350
+ const quote = text[at + 1];
351
+ for (let i = at + 2; i < text.length; i++) {
352
+ if (text[i] === "\n") {
353
+ return i;
354
+ }
355
+ if (text[i] !== "\\") {
356
+ continue;
357
+ }
358
+ let runEnd = i;
359
+ while (runEnd < text.length && text[runEnd] === "\\") {
360
+ runEnd++;
361
+ }
362
+ const run = runEnd - i;
363
+ if (text[runEnd] === quote) {
364
+ if (run % 2 === 0) {
365
+ return runEnd;
366
+ }
367
+ if (run % 4 === 1) {
368
+ return runEnd + 1;
369
+ }
370
+ }
371
+ i = runEnd - 1;
372
+ }
373
+ return text.length;
374
+ }
375
+ /**
376
+ * An object or array through the bracket that closes it, its strings read as
377
+ * strings. One never closed runs to the end of the text.
378
+ */
379
+ function readBracketed(text, at) {
380
+ let depth = 0;
381
+ for (let i = at; i < text.length; i++) {
382
+ const char = text[i];
383
+ if (char === "{" || char === "[") {
384
+ depth++;
385
+ }
386
+ else if (char === "}" || char === "]") {
387
+ depth--;
388
+ if (depth === 0) {
389
+ return i + 1;
390
+ }
391
+ }
392
+ else if (char === '"') {
393
+ i = readQuoted(text, i) - 1;
394
+ }
395
+ else if (char === "\\") {
396
+ i++;
397
+ }
398
+ }
399
+ return text.length;
400
+ }
401
+ function buildDefaultRules(isSensitiveKey, checkEveryKey, literalValuesOnly = false) {
59
402
  return [
60
403
  // PEM blocks first: they span lines and would otherwise be partially eaten
61
404
  // by the narrower rules below.
62
- {
63
- pattern: /-----BEGIN (?:[A-Z ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z ]+ )?PRIVATE KEY-----/g,
64
- replace: (replacement) => replacement,
65
- },
405
+ { scan: scanPemBlocks },
406
+ // Card numbers before any key: a key's bare value stops at a space, so
407
+ // `token: 4000 0566 5566 5556` would lose only its first group.
408
+ { scan: scanCardNumbers },
66
409
  // Authorization schemes: `Bearer eyJ...`, `Basic dXNlcjpwYXNz`.
67
410
  //
68
411
  // Must precede the key=value rule. That rule's value stops at whitespace, so
69
412
  // on `Authorization: Basic dXNlcjpwYXNz` it would consume only the word
70
- // "Basic" and leave the credential itself sitting in the line.
413
+ // "Basic" and leave the credential itself sitting in the line. Not a word
414
+ // followed by `:` - `Invalid Basic credentials: dXNl...` names a key, whose
415
+ // value the key=value rule masks.
71
416
  {
72
- pattern: /\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=-]{8,}/gi,
417
+ pattern: /\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=%-]{8}[A-Za-z0-9._~+/=%-]*(?![A-Za-z0-9._~+/=%-]|[ \t]*:)/gi,
73
418
  replace: (replacement, scheme) => `${scheme} ${replacement}`,
74
419
  },
75
- // key=value / "key": "value". Keeps the key so the line still says what was
76
- // removed - a log reading `password=[REDACTED]` is far more useful than one
77
- // where the whole pair vanished.
78
- //
79
- // The value alternation matches a scheme-prefixed credential before the bare
80
- // form, so an already-masked `Authorization: Bearer [REDACTED]` collapses to
81
- // a single `[REDACTED]` rather than stacking two.
82
- {
83
- pattern: new RegExp(`((?:${TEXT_KEY_ALTERNATION})["']?\\s*[:=]\\s*)${value}`, "gi"),
84
- replace: (replacement, prefix) => `${prefix}${replacement}`,
85
- },
420
+ // The scheme-prefixed form already masked above collapses here into one
421
+ // `[REDACTED]` under an `Authorization` key, rather than two stacked.
422
+ keyValueRule(isSensitiveKey, checkEveryKey, literalValuesOnly),
86
423
  // Bare JWTs - they show up outside any header often enough to matter.
424
+ // A signed one has three parts; an encrypted one (JWE) five, the second
425
+ // of them empty under `alg: dir`.
87
426
  //
88
427
  // Must not follow a token character, rather than `\b`: a hyphen is a word
89
428
  // boundary but also a token character, so under `\b` every `eyJ` in a run
90
429
  // like `eyJ-eyJ-eyJ-...` started a match that rescanned the rest of the
91
430
  // run - quadratic, on a line a caller can fill.
92
431
  {
93
- pattern: /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g,
432
+ pattern: new RegExp(`${TOKEN_START}eyJ${tokenRun(4)}\\.` +
433
+ `(?:${tokenRun(0)}\\.${tokenRun(4)}\\.${tokenRun(4)}\\.${tokenRun(0)}` +
434
+ `|${tokenRun(4)}\\.${tokenRun(0)})`, "g"),
94
435
  replace: (replacement) => replacement,
95
436
  },
96
437
  // AWS access key ids. Distinctive enough to match on sight; the matching
@@ -108,8 +449,90 @@ function buildDefaultRules(literalValuesOnly = false) {
108
449
  * ids, timestamps concatenated together - so the digits are Luhn-checked before
109
450
  * anything is masked. That turns a rule which would otherwise shred numeric log
110
451
  * data into one that only fires on something genuinely card-shaped.
452
+ *
453
+ * Read as runs of digit groups, so a card beside other numbers - an expiry
454
+ * date, a CVV, a timestamp in front - is still found: a card is one group of
455
+ * 13-19 digits, or groups in a card's own layout (4-4-4-4 and its shorter and
456
+ * longer forms, 4-6-5, 4-6-4). Only those windows are Luhn-checked, so the
457
+ * odds of masking an ordinary run of numbers stay what they were.
111
458
  */
112
- const CARD_CANDIDATE = /\b\d(?:[ -]?\d){12,18}\b/g;
459
+ const DIGIT_RUN = /(?:\b|(?<=\\[nrtbf]))\d+(?:[ -]\d+)*/g;
460
+ const CARD_LAYOUTS = [
461
+ [4, 4, 4, 4, 3],
462
+ [4, 4, 4, 4, 2],
463
+ [4, 4, 4, 4, 1],
464
+ [4, 4, 4, 4],
465
+ [4, 6, 5],
466
+ [4, 6, 4],
467
+ [4, 4, 4, 3],
468
+ [4, 4, 4, 2],
469
+ [4, 4, 4, 1],
470
+ ];
471
+ /** Thirteen digits at least, however grouped: what any card has. */
472
+ const MAY_HOLD_CARD = /\d(?:[ -]?\d){12}/;
473
+ function scanCardNumbers(text, mask) {
474
+ if (!MAY_HOLD_CARD.test(text)) {
475
+ return text;
476
+ }
477
+ let output = "";
478
+ let copiedTo = 0;
479
+ for (const run of text.matchAll(DIGIT_RUN)) {
480
+ const runEnd = run.index + run[0].length;
481
+ // A run that goes on into a word (`4111...abc`) is an identifier.
482
+ const usable = /\w/.test(text[runEnd] ?? "")
483
+ ? run[0].slice(0, Math.max(0, run[0].search(/[ -]\d+$/)))
484
+ : run[0];
485
+ if (usable.length < 13) {
486
+ continue;
487
+ }
488
+ const groups = [];
489
+ for (const group of usable.matchAll(/\d+/g)) {
490
+ groups.push([
491
+ run.index + group.index,
492
+ run.index + group.index + group[0].length,
493
+ ]);
494
+ }
495
+ for (let i = 0; i < groups.length;) {
496
+ const end = cardEndingAt(text, groups, i);
497
+ if (end === undefined) {
498
+ i++;
499
+ continue;
500
+ }
501
+ output +=
502
+ text.slice(copiedTo, groups[i][0]) +
503
+ mask(text.slice(groups[i][0], groups[end][1]));
504
+ copiedTo = groups[end][1];
505
+ i = end + 1;
506
+ }
507
+ }
508
+ return copiedTo === 0 ? text : output + text.slice(copiedTo);
509
+ }
510
+ /** The last group of a Luhn-valid card starting at group `first`, if any. */
511
+ function cardEndingAt(text, groups, first) {
512
+ const length = (i) => groups[i][1] - groups[i][0];
513
+ const digitsOf = (from, to) => {
514
+ let digits = "";
515
+ for (let i = from; i <= to; i++) {
516
+ digits += text.slice(groups[i][0], groups[i][1]);
517
+ }
518
+ return digits;
519
+ };
520
+ if (length(first) >= 13 && length(first) <= 19) {
521
+ return isLuhnValid(digitsOf(first, first)) ? first : undefined;
522
+ }
523
+ for (const layout of CARD_LAYOUTS) {
524
+ if (first + layout.length > groups.length) {
525
+ continue;
526
+ }
527
+ if (layout.every((size, offset) => length(first + offset) === size)) {
528
+ const last = first + layout.length - 1;
529
+ if (isLuhnValid(digitsOf(first, last))) {
530
+ return last;
531
+ }
532
+ }
533
+ }
534
+ return undefined;
535
+ }
113
536
  function isLuhnValid(digits) {
114
537
  let sum = 0;
115
538
  let double = false;
@@ -142,7 +565,13 @@ export class LogRedactor {
142
565
  constructor(options = {}) {
143
566
  this.replacement = options.replacement ?? DEFAULT_REPLACEMENT;
144
567
  this.redactCards = options.useDefaultPatterns !== false;
145
- const defaults = options.useDefaultPatterns === false ? [] : buildDefaultRules();
568
+ this.matchesSensitiveKey = createSensitiveKeyMatcher(options.keys);
569
+ // Configured keys are matched exactly and can be anything, so the cheap
570
+ // stem test in front of the matcher cannot stand in for them.
571
+ const checkEveryKey = (options.keys ? [...options.keys].length : 0) > 0;
572
+ const defaults = options.useDefaultPatterns === false
573
+ ? []
574
+ : buildDefaultRules(this.matchesSensitiveKey, checkEveryKey);
146
575
  const extra = (options.patterns ?? []).map((pattern) => ({
147
576
  // Rebuilt with the global flag: a caller-supplied pattern without /g would
148
577
  // silently redact only the first occurrence in a line.
@@ -153,10 +582,11 @@ export class LogRedactor {
153
582
  }));
154
583
  this.rules = [...defaults, ...extra];
155
584
  this.sourceRules = [
156
- ...(options.useDefaultPatterns === false ? [] : buildDefaultRules(true)),
585
+ ...(options.useDefaultPatterns === false
586
+ ? []
587
+ : buildDefaultRules(this.matchesSensitiveKey, checkEveryKey, true)),
157
588
  ...extra,
158
589
  ];
159
- this.matchesSensitiveKey = createSensitiveKeyMatcher(options.keys);
160
590
  }
161
591
  /**
162
592
  * Whether a key names a credential - the built-in rules plus the configured
@@ -166,8 +596,14 @@ export class LogRedactor {
166
596
  isSensitiveKey(key) {
167
597
  return this.matchesSensitiveKey(key);
168
598
  }
599
+ /**
600
+ * Colour codes are taken out first. The forwarder strips them off a raw
601
+ * line, but a JSON logger writes the escape as `\u001b`, so they only come
602
+ * back once the line is decoded - and between a key and its value, or in
603
+ * front of a card number, they stop every rule matching.
604
+ */
169
605
  redactMessage(message) {
170
- return this.apply(message, this.rules, false);
606
+ return this.apply(message.includes("\x1b") ? stripAnsi(message) : message, this.rules, false);
171
607
  }
172
608
  /**
173
609
  * Redacts lines of source code read for a code frame.
@@ -188,20 +624,16 @@ export class LogRedactor {
188
624
  ? masked + "\n".repeat(match.split("\n").length - 1)
189
625
  : masked;
190
626
  for (const rule of rules) {
627
+ if ("scan" in rule) {
628
+ output = rule.scan(output, (secret) => keep(secret, this.replacement));
629
+ continue;
630
+ }
191
631
  output = output.replace(rule.pattern, (...args) => {
192
632
  // String.replace passes offset and the whole string after the groups.
193
633
  const groups = args.slice(1, -2).map((group) => group ?? "");
194
634
  return keep(args[0], rule.replace(this.replacement, ...groups));
195
635
  });
196
636
  }
197
- if (this.redactCards) {
198
- output = output.replace(CARD_CANDIDATE, (match) => {
199
- const digits = match.replace(/[ -]/g, "");
200
- return digits.length >= 13 && isLuhnValid(digits)
201
- ? this.replacement
202
- : match;
203
- });
204
- }
205
637
  return output;
206
638
  }
207
639
  redactAttributes(attributes) {
@@ -217,20 +649,39 @@ export class LogRedactor {
217
649
  if (typeof value === "string") {
218
650
  return this.redactMessage(value);
219
651
  }
652
+ if (typeof value === "number") {
653
+ return this.isCardNumber(value) ? this.replacement : value;
654
+ }
220
655
  if (Array.isArray(value)) {
221
656
  return value.map((item) => this.redactValue(item, depth + 1));
222
657
  }
223
658
  if (value && typeof value === "object") {
224
659
  return Object.fromEntries(Object.entries(value).map(([key, item]) => [
225
- key,
660
+ this.redactKey(key),
226
661
  // A sensitive key masks its value whatever the shape - an object under
227
662
  // `credentials` is exactly what must not be walked into and partially
228
663
  // preserved.
229
- this.matchesSensitiveKey(key)
664
+ this.matchesSensitiveKey(key.includes("\x1b") ? stripAnsi(key) : key)
230
665
  ? this.replacement
231
666
  : this.redactValue(item, depth + 1),
232
667
  ]));
233
668
  }
234
669
  return value;
235
670
  }
671
+ /**
672
+ * A key is a name, but not always: a JSON body parsed as a form is one key
673
+ * holding the whole document. Only a key long enough to hold a secret, or
674
+ * holding a pair, is read - the rest are the ordinary names they look like.
675
+ */
676
+ redactKey(key) {
677
+ return key.length > 12 || /[:=]/.test(key) ? this.redactMessage(key) : key;
678
+ }
679
+ /** A card number written as a JSON number: `{"number": 4111111111111111}`. */
680
+ isCardNumber(value) {
681
+ if (!this.redactCards || !Number.isInteger(value) || value < 1e12) {
682
+ return false;
683
+ }
684
+ const digits = String(value);
685
+ return digits.length <= 19 && /^\d+$/.test(digits) && isLuhnValid(digits);
686
+ }
236
687
  }