@nestjs/observe 0.3.25 → 0.3.27

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