securenow 8.23.0 → 8.24.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.
@@ -0,0 +1,487 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Request capture shared by every SecureNow HTTP integration: the Node preload
5
+ * (tracing.js), Next.js (nextjs.js) and Nuxt (through the preload). Detection rules
6
+ * read the same attributes whatever the framework: http.request.headers (redacted)
7
+ * and http.request.body (redacted, size-capped, multipart as metadata only).
8
+ *
9
+ * The body is observed, never consumed: the request's own emit('data') is wrapped,
10
+ * so the application reads its body exactly as it would without SecureNow.
11
+ */
12
+
13
+ const { OTP_SENSITIVE_FIELDS, isOtpCodeField, matchesSensitiveField, redactOtpGraphQL, redactOtpQuery } = require('./otp-redaction');
14
+ const { createHeaderNameRedactor } = require('./header-redaction');
15
+
16
+ // Default sensitive fields to redact from request bodies.
17
+ // OTP/code aliases use exact normalized matching; other fields are matched
18
+ // substring-wise against lowercased keys (see redactSensitiveData),
19
+ // so e.g. 'card' also catches 'creditCard' and 'account' also catches
20
+ // 'accountNumber'. Over-redaction here is intentional: a falsely-redacted
21
+ // telemetry value is always safer than a leaked secret. Entries are kept
22
+ // specific enough to avoid nuking broad benign keys (e.g. we use
23
+ // 'firstname'/'lastname'/'fullname', never bare 'name').
24
+ const DEFAULT_SENSITIVE_FIELDS = [
25
+ ...OTP_SENSITIVE_FIELDS,
26
+ // credentials / auth
27
+ 'password', 'passwd', 'pwd', 'secret', 'token', 'api_key', 'apikey',
28
+ 'access_token', 'auth', 'authorization', 'bearer', 'credentials',
29
+ 'mysql_pwd', 'otp', 'mfa', 'totp', 'sessionid', 'session_id',
30
+ 'cookie', 'set-cookie',
31
+ // financial
32
+ 'stripeToken', 'card', 'cardnumber', 'ccv', 'cvc', 'cvv',
33
+ 'iban', 'account', 'accountnumber', 'routing', 'sortcode', 'taxid',
34
+ // PII
35
+ 'ssn', 'pin', 'email', 'e_mail', 'phone', 'mobile', 'dob', 'birthdate',
36
+ 'firstname', 'lastname', 'fullname', 'address', 'postcode', 'zip',
37
+ 'passport', 'license',
38
+ ];
39
+
40
+ // Conservative value-shape redactors. Key-name matching misses secrets that
41
+ // land in free-form string values (GraphQL bodies, message fields, etc.), so
42
+ // as a second layer we scrub string VALUES that *look like* a secret/PII.
43
+ // These are intentionally precise/bounded so they don't garble normal prose,
44
+ // and they only ever transform captured telemetry strings (read-only) — never
45
+ // the actual request/response stream. Compiled once at module load.
46
+ const VALUE_REDACTORS = [
47
+ // JWT: three base64url segments. Anchored to the eyJ header so it won't
48
+ // match arbitrary dotted tokens.
49
+ { name: 'jwt', re: /eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/g },
50
+ // Bearer/Basic auth header value embedded in a body string.
51
+ { name: 'bearer', re: /\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi },
52
+ // Stripe-style / SecureNow live+test API keys.
53
+ { name: 'apikey', re: /\b(?:sk|pk|rk|snk)_(?:live|test)_[A-Za-z0-9]{8,}/g },
54
+ // Email addresses (bounded local/domain parts).
55
+ { name: 'email', re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,24}\b/g },
56
+ // Credit-card-like: 13–19 digit runs that pass a Luhn check, allowing
57
+ // space/dash grouping. Luhn-gated to avoid clobbering ordinary long numbers.
58
+ { name: 'card', re: /\b(?:\d[ -]?){13,19}\b/g, luhn: true },
59
+ ];
60
+
61
+ // Skip the value-shape scan on very large strings to bound per-body cost.
62
+ const MAX_VALUE_SCAN_LENGTH = 16384;
63
+
64
+ function luhnValid(digits) {
65
+ let sum = 0;
66
+ let alt = false;
67
+ for (let i = digits.length - 1; i >= 0; i--) {
68
+ let d = digits.charCodeAt(i) - 48;
69
+ if (d < 0 || d > 9) return false;
70
+ if (alt) { d *= 2; if (d > 9) d -= 9; }
71
+ sum += d;
72
+ alt = !alt;
73
+ }
74
+ return sum % 10 === 0;
75
+ }
76
+
77
+ /**
78
+ * Redact obvious secret/PII shapes inside a captured string VALUE.
79
+ * Returns the input unchanged when nothing matches (cheap common case).
80
+ */
81
+ function redactSensitiveValue(value) {
82
+ if (typeof value !== 'string' || value.length === 0) return value;
83
+ // Credential assignments in GraphQL/query strings need field-aware
84
+ // redaction even though a short numeric OTP has no unique value shape.
85
+ value = redactOtpQuery(redactOtpGraphQL(value));
86
+ if (value.length > MAX_VALUE_SCAN_LENGTH) return value; // bound shape scans
87
+ let out = value;
88
+ for (const r of VALUE_REDACTORS) {
89
+ r.re.lastIndex = 0;
90
+ if (r.luhn) {
91
+ out = out.replace(r.re, (m) => {
92
+ const digits = m.replace(/[ -]/g, '');
93
+ if (digits.length < 13 || digits.length > 19) return m;
94
+ return luhnValid(digits) ? '[REDACTED]' : m;
95
+ });
96
+ } else {
97
+ out = out.replace(r.re, '[REDACTED]');
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+
103
+ function escapeRegex(str) {
104
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
105
+ }
106
+
107
+ /**
108
+ * Redact sensitive fields from an object
109
+ */
110
+ function redactSensitiveData(obj, sensitiveFields = DEFAULT_SENSITIVE_FIELDS) {
111
+ if (!obj || typeof obj !== 'object') return obj;
112
+
113
+ const redacted = Array.isArray(obj) ? [...obj] : { ...obj };
114
+
115
+ for (const key of Object.keys(redacted)) {
116
+
117
+ if (matchesSensitiveField(key, sensitiveFields)) {
118
+ redacted[key] = '[REDACTED]';
119
+ } else if (typeof redacted[key] === 'object' && redacted[key] !== null) {
120
+ redacted[key] = redactSensitiveData(redacted[key], sensitiveFields);
121
+ } else if (typeof redacted[key] === 'string') {
122
+ // Second layer: even if the key name looks benign, scrub values that
123
+ // *look like* a secret/PII (JWT, bearer token, API key, email, card).
124
+ redacted[key] = redactSensitiveValue(redacted[key]);
125
+ }
126
+ }
127
+
128
+ return redacted;
129
+ }
130
+
131
+ /**
132
+ * Redact sensitive data from GraphQL query strings
133
+ */
134
+ function redactGraphQLQuery(query, sensitiveFields = DEFAULT_SENSITIVE_FIELDS) {
135
+ if (!query || typeof query !== 'string') return query;
136
+
137
+ let redacted = query;
138
+
139
+ // Redact sensitive fields in GraphQL arguments and variables
140
+ sensitiveFields.filter(field => field === 'otp' || !isOtpCodeField(field)).forEach(field => {
141
+ const escaped = escapeRegex(field);
142
+ const patterns = [
143
+ // Quoted values: password: "..." keeps its quotes.
144
+ new RegExp(`(${escaped}\\s*:\\s*["'])([^"']+)(["'])`, 'gi'),
145
+ // Unquoted values (variables, numbers). A value starting with a quote was handled above.
146
+ new RegExp(`(${escaped}\\s*:\\s*)([^\\s,})\n"'][^\\s,})\n]*)`, 'gi'),
147
+ ];
148
+
149
+ patterns.forEach(pattern => {
150
+ // With two groups the third callback argument is the match offset, not a suffix: testing
151
+ // it for truthiness appended the offset to the redacted value ("[REDACTED]17").
152
+ redacted = redacted.replace(pattern, (match, prefix, value, suffix) => (
153
+ typeof suffix === 'string' ? `${prefix}[REDACTED]${suffix}` : `${prefix}[REDACTED]`
154
+ ));
155
+ });
156
+ });
157
+
158
+ // Second layer: scrub secret/PII *shapes* anywhere in the (free-form) query
159
+ // body — catches values the key-name pass above can't see.
160
+ redacted = redactOtpGraphQL(redactSensitiveValue(redacted));
161
+
162
+ return redacted;
163
+ }
164
+
165
+ /**
166
+ * Redact a captured body text by content type: the same rules as the HTTP-layer capture,
167
+ * for integrations that only see the body as text (Next.js Request.text()).
168
+ */
169
+ function redactBodyText(bodyText, contentType, sensitiveFields = DEFAULT_SENSITIVE_FIELDS) {
170
+ const ct = String(contentType || '').toLowerCase();
171
+ if (ct.includes('application/graphql')) {
172
+ return { body: redactGraphQLQuery(bodyText, sensitiveFields), type: 'graphql' };
173
+ }
174
+ if (ct.includes('application/json')) {
175
+ return { body: JSON.stringify(redactSensitiveData(JSON.parse(bodyText), sensitiveFields)), type: 'json' };
176
+ }
177
+ if (ct.includes('application/x-www-form-urlencoded')) {
178
+ return { body: JSON.stringify(redactSensitiveData(Object.fromEntries(new URLSearchParams(bodyText)), sensitiveFields)), type: 'form' };
179
+ }
180
+ return null;
181
+ }
182
+
183
+ // -------- Multipart streaming parser --------
184
+ // Streams through the request without buffering file content.
185
+ // Only part headers and text-field values are kept in memory,
186
+ // so memory stays bounded (~few KB) regardless of upload size.
187
+
188
+ function extractBoundary(contentType) {
189
+ const match = contentType.match(/boundary=(?:"([^"]+)"|([^\s;]+))/i);
190
+ return match ? (match[1] || match[2]) : null;
191
+ }
192
+
193
+ function createMultipartMetaCollector(contentType, sensitiveFields, maxTextFieldSize, onComplete) {
194
+ const boundary = extractBoundary(contentType);
195
+ if (!boundary) { onComplete({ error: 'BOUNDARY_NOT_FOUND' }); return null; }
196
+
197
+ const result = { fields: Object.create(null), files: [] };
198
+ let totalSize = 0;
199
+ let buf = Buffer.alloc(0);
200
+
201
+ const MAX_PARTS = 100;
202
+ let partCount = 0;
203
+
204
+ const FIRST_DELIM = Buffer.from('--' + boundary);
205
+ const DELIM = Buffer.from('\r\n--' + boundary);
206
+ const HDR_END = Buffer.from('\r\n\r\n');
207
+
208
+ let initialized = false;
209
+ let inHeaders = true;
210
+ let isFile = false;
211
+ let fldName = '';
212
+ let fName = '';
213
+ let pCT = '';
214
+ let bodyBytes = 0;
215
+ let textVal = '';
216
+
217
+ function flushPart() {
218
+ if (!fldName || fldName === '__proto__' || fldName === 'constructor' || fldName === 'prototype') return;
219
+ if (isFile) {
220
+ result.files.push({ field: fldName, filename: fName, contentType: pCT || 'unknown', size: bodyBytes });
221
+ } else {
222
+ const redact = matchesSensitiveField(fldName, sensitiveFields);
223
+ // Name-match redaction first; otherwise scrub secret/PII *shapes* in the value.
224
+ result.fields[fldName] = redact
225
+ ? '[REDACTED]'
226
+ : redactSensitiveValue(textVal.substring(0, maxTextFieldSize));
227
+ }
228
+ fldName = ''; bodyBytes = 0; textVal = ''; partCount++;
229
+ }
230
+
231
+ function drain() {
232
+ if (!initialized) {
233
+ const i = buf.indexOf(FIRST_DELIM);
234
+ if (i === -1) {
235
+ if (buf.length > FIRST_DELIM.length + 4) buf = buf.slice(buf.length - FIRST_DELIM.length - 4);
236
+ return;
237
+ }
238
+ buf = buf.slice(i + FIRST_DELIM.length);
239
+ initialized = true;
240
+ inHeaders = true;
241
+ }
242
+
243
+ let guard = 200;
244
+ while (buf.length > 0 && guard-- > 0 && partCount < MAX_PARTS) {
245
+ if (inHeaders) {
246
+ if (buf.length >= 2 && buf[0] === 0x2D && buf[1] === 0x2D) { buf = Buffer.alloc(0); return; }
247
+ if (buf.length >= 2 && buf[0] === 0x0D && buf[1] === 0x0A) { buf = buf.slice(2); continue; }
248
+
249
+ const hi = buf.indexOf(HDR_END);
250
+ if (hi === -1) return;
251
+
252
+ const hdr = buf.slice(0, hi).toString('latin1');
253
+ buf = buf.slice(hi + 4);
254
+
255
+ const nm = hdr.match(/name="([^"]+)"/);
256
+ const fn = hdr.match(/filename="([^"]*)"/);
257
+ const ct = hdr.match(/Content-Type:\s*(.+)/i);
258
+ fldName = nm ? nm[1] : '';
259
+ fName = fn ? fn[1] : '';
260
+ pCT = ct ? ct[1].trim() : '';
261
+ isFile = !!fn;
262
+ bodyBytes = 0;
263
+ textVal = '';
264
+ inHeaders = false;
265
+ }
266
+
267
+ const di = buf.indexOf(DELIM);
268
+ if (di === -1) {
269
+ const safe = Math.max(0, buf.length - DELIM.length - 2);
270
+ if (safe > 0) {
271
+ bodyBytes += safe;
272
+ if (!isFile && textVal.length < maxTextFieldSize) {
273
+ textVal += buf.slice(0, safe).toString('utf8').substring(0, maxTextFieldSize - textVal.length);
274
+ }
275
+ buf = buf.slice(safe);
276
+ }
277
+ return;
278
+ }
279
+
280
+ bodyBytes += di;
281
+ if (!isFile && textVal.length < maxTextFieldSize) {
282
+ textVal += buf.slice(0, di).toString('utf8').substring(0, maxTextFieldSize - textVal.length);
283
+ }
284
+ flushPart();
285
+ buf = buf.slice(di + DELIM.length);
286
+ inHeaders = true;
287
+ }
288
+ }
289
+
290
+ function onData(chunk) {
291
+ const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
292
+ totalSize += data.length;
293
+ buf = Buffer.concat([buf, data]);
294
+ drain();
295
+ }
296
+
297
+ function onEnd() {
298
+ try {
299
+ if (!inHeaders && fldName) {
300
+ bodyBytes += buf.length;
301
+ if (!isFile) textVal += buf.toString('utf8').substring(0, maxTextFieldSize - textVal.length);
302
+ flushPart();
303
+ }
304
+ onComplete({ parsed: result, totalSize });
305
+ } catch (e) {
306
+ onComplete({ error: 'PARSE_ERROR' });
307
+ }
308
+ }
309
+
310
+ return { onData, onEnd };
311
+ }
312
+
313
+ const BODY_CAPTURE_PATCH = Symbol.for('securenow.bodyCapture.emitPatch');
314
+
315
+ /**
316
+ * @param {{ captureBody?: boolean, captureMultipart?: boolean, maxBodySize?: number, customSensitiveFields?: string[] }} options
317
+ */
318
+ function createRequestCapture(options = {}) {
319
+ const captureBody = options.captureBody !== false;
320
+ const captureMultipart = options.captureMultipart !== false;
321
+ const maxBodySize = options.maxBodySize || 10240;
322
+ const customSensitiveFields = options.customSensitiveFields || [];
323
+ const allSensitiveFields = [...DEFAULT_SENSITIVE_FIELDS, ...customSensitiveFields];
324
+
325
+ // Credential-bearing request headers (cookies, auth, CSRF/XSRF, session, API keys, and any
326
+ // configured capture.sensitiveFields) are redacted by name before capture.
327
+ const isSensitiveHeaderName = createHeaderNameRedactor(customSensitiveFields);
328
+
329
+ function captureHeaders(span, request) {
330
+ if (!request || !request.headers) return;
331
+ const safe = {};
332
+ for (const [k, v] of Object.entries(request.headers)) {
333
+ if (isSensitiveHeaderName(k)) { safe[k] = '[REDACTED]'; continue; }
334
+ safe[k] = redactSensitiveValue(redactOtpQuery(typeof v === 'string' ? v : String(v))).substring(0, 500);
335
+ }
336
+ const serialized = JSON.stringify(safe);
337
+ if (serialized.length <= 8192) {
338
+ span.setAttribute('http.request.headers', serialized);
339
+ }
340
+ }
341
+
342
+ function installRequestBodyObserver(span, request, contentType) {
343
+ if (!request || request[BODY_CAPTURE_PATCH]) return;
344
+
345
+ const normalizedContentType = String(contentType || '').toLowerCase();
346
+ const isStructuredBody = captureBody && (
347
+ normalizedContentType.includes('application/json') ||
348
+ normalizedContentType.includes('application/graphql') ||
349
+ normalizedContentType.includes('application/x-www-form-urlencoded')
350
+ );
351
+ const isMultipartBody = normalizedContentType.includes('multipart/form-data');
352
+
353
+ if (!isStructuredBody && !isMultipartBody) return;
354
+
355
+ if (isMultipartBody && !captureMultipart) {
356
+ span.setAttribute('http.request.body', '[MULTIPART - NOT CAPTURED]');
357
+ span.setAttribute('http.request.body.type', 'multipart');
358
+ span.setAttribute('http.request.body.note', 'Multipart capture disabled by config.capture.multipart=false');
359
+ return;
360
+ }
361
+
362
+ let chunks = [];
363
+ let size = 0;
364
+ let structuredDone = false;
365
+
366
+ // The boundary is case-sensitive: browsers send mixed-case ones (----WebKitFormBoundaryAbC...),
367
+ // so it is read from the header as sent, not from the lowercased copy (which found no part).
368
+ const multipartCollector = isMultipartBody && captureMultipart
369
+ ? createMultipartMetaCollector(String(contentType || ''), allSensitiveFields, 1000, ({ error, parsed, totalSize }) => {
370
+ try {
371
+ if (error === 'BOUNDARY_NOT_FOUND') {
372
+ span.setAttribute('http.request.body', '[MULTIPART - BOUNDARY NOT FOUND]');
373
+ span.setAttribute('http.request.body.type', 'multipart');
374
+ return;
375
+ }
376
+ if (error) {
377
+ span.setAttribute('http.request.body', '[MULTIPART - PARSE ERROR]');
378
+ span.setAttribute('http.request.body.type', 'multipart');
379
+ span.setAttribute('http.request.body.parse_error', true);
380
+ return;
381
+ }
382
+ span.setAttributes({
383
+ 'http.request.body': JSON.stringify(parsed).substring(0, maxBodySize),
384
+ 'http.request.body.type': 'multipart',
385
+ 'http.request.body.size': totalSize,
386
+ 'http.request.body.fields_count': Object.keys(parsed.fields).length,
387
+ 'http.request.body.files_count': parsed.files.length,
388
+ });
389
+ } catch (e) {
390
+ span.setAttribute('http.request.body', '[MULTIPART - PARSE ERROR]');
391
+ span.setAttribute('http.request.body.type', 'multipart');
392
+ span.setAttribute('http.request.body.parse_error', true);
393
+ }
394
+ })
395
+ : null;
396
+
397
+ if (isMultipartBody && captureMultipart && !multipartCollector) return;
398
+
399
+ function finishStructuredCapture() {
400
+ if (!isStructuredBody || structuredDone) return;
401
+ structuredDone = true;
402
+
403
+ if (size > maxBodySize) {
404
+ span.setAttribute('http.request.body', `[TOO LARGE: ${size} bytes]`);
405
+ span.setAttribute('http.request.body.size', size);
406
+ chunks = [];
407
+ return;
408
+ }
409
+
410
+ if (chunks.length === 0) return;
411
+
412
+ const body = Buffer.concat(chunks).toString('utf8');
413
+ chunks = [];
414
+
415
+ try {
416
+ if (normalizedContentType.includes('application/graphql')) {
417
+ const redacted = redactGraphQLQuery(body, allSensitiveFields);
418
+ span.setAttributes({
419
+ 'http.request.body': redacted.substring(0, maxBodySize),
420
+ 'http.request.body.type': 'graphql',
421
+ 'http.request.body.size': size,
422
+ });
423
+ } else if (normalizedContentType.includes('application/json')) {
424
+ const parsed = JSON.parse(body);
425
+ const redacted = redactSensitiveData(parsed, allSensitiveFields);
426
+ span.setAttributes({
427
+ 'http.request.body': JSON.stringify(redacted).substring(0, maxBodySize),
428
+ 'http.request.body.type': 'json',
429
+ 'http.request.body.size': size,
430
+ });
431
+ } else if (normalizedContentType.includes('application/x-www-form-urlencoded')) {
432
+ const parsed = Object.fromEntries(new URLSearchParams(body));
433
+ const redacted = redactSensitiveData(parsed, allSensitiveFields);
434
+ span.setAttributes({
435
+ 'http.request.body': JSON.stringify(redacted).substring(0, maxBodySize),
436
+ 'http.request.body.type': 'form',
437
+ 'http.request.body.size': size,
438
+ });
439
+ }
440
+ } catch (e) {
441
+ span.setAttribute('http.request.body', '[UNPARSEABLE - REDACTED FOR SAFETY]');
442
+ span.setAttribute('http.request.body.parse_error', true);
443
+ span.setAttribute('http.request.body.size', size);
444
+ }
445
+ }
446
+
447
+ const originalEmit = request.emit;
448
+ request[BODY_CAPTURE_PATCH] = true;
449
+ request.emit = function securenowObservedEmit(event, ...args) {
450
+ try {
451
+ if (event === 'data' && args.length > 0) {
452
+ const chunk = Buffer.isBuffer(args[0]) ? args[0] : Buffer.from(args[0]);
453
+ if (isStructuredBody) {
454
+ size += chunk.length;
455
+ if (size <= maxBodySize) chunks.push(chunk);
456
+ }
457
+ if (multipartCollector) multipartCollector.onData(chunk);
458
+ } else if (event === 'end') {
459
+ finishStructuredCapture();
460
+ if (multipartCollector) multipartCollector.onEnd();
461
+ }
462
+ } catch (_) {
463
+ // Body capture must never interfere with the application request stream.
464
+ }
465
+ return originalEmit.apply(this, [event, ...args]);
466
+ };
467
+ }
468
+
469
+ function observeBody(span, request) {
470
+ if (!(captureBody || captureMultipart) || !request || !request.method) return;
471
+ if (!['POST', 'PUT', 'PATCH'].includes(request.method)) return;
472
+ const contentType = (request.headers && request.headers['content-type']) || '';
473
+ installRequestBodyObserver(span, request, contentType);
474
+ }
475
+
476
+ return { captureBody, captureMultipart, maxBodySize, allSensitiveFields, captureHeaders, observeBody };
477
+ }
478
+
479
+ module.exports = {
480
+ DEFAULT_SENSITIVE_FIELDS,
481
+ redactSensitiveValue,
482
+ redactSensitiveData,
483
+ redactGraphQLQuery,
484
+ redactBodyText,
485
+ createMultipartMetaCollector,
486
+ createRequestCapture,
487
+ };