securenow 5.10.2 → 5.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/nextjs-wrapper.js CHANGED
@@ -1,158 +1,158 @@
1
- /**
2
- * SecureNow Next.js API Route Wrapper for Body Capture
3
- *
4
- * This approach is NON-INVASIVE and runs INSIDE your handler,
5
- * so it never blocks or interferes with middleware or routing.
6
- *
7
- * Usage:
8
- *
9
- * import { withSecureNow } from 'securenow/nextjs-wrapper';
10
- *
11
- * export const POST = withSecureNow(async (request) => {
12
- * // Your handler code - request.body is available as parsed JSON
13
- * const data = await request.json();
14
- * return Response.json({ success: true });
15
- * });
16
- */
17
-
18
- const { trace } = require('@opentelemetry/api');
19
-
20
- // Default sensitive fields to redact
21
- const DEFAULT_SENSITIVE_FIELDS = [
22
- 'password', 'passwd', 'pwd', 'secret', 'token', 'api_key', 'apikey',
23
- 'access_token', 'auth', 'credentials', 'mysql_pwd', 'stripeToken',
24
- 'card', 'cardnumber', 'ccv', 'cvc', 'cvv', 'ssn', 'pin',
25
- ];
26
-
27
- /**
28
- * Redact sensitive fields from an object
29
- */
30
- function redactSensitiveData(obj, sensitiveFields = DEFAULT_SENSITIVE_FIELDS) {
31
- if (!obj || typeof obj !== 'object') return obj;
32
-
33
- const redacted = Array.isArray(obj) ? [...obj] : { ...obj };
34
-
35
- for (const key of Object.keys(redacted)) {
36
- const lowerKey = key.toLowerCase();
37
-
38
- if (sensitiveFields.some(field => lowerKey.includes(field.toLowerCase()))) {
39
- redacted[key] = '[REDACTED]';
40
- } else if (typeof redacted[key] === 'object' && redacted[key] !== null) {
41
- redacted[key] = redactSensitiveData(redacted[key], sensitiveFields);
42
- }
43
- }
44
-
45
- return redacted;
46
- }
47
-
48
- /**
49
- * Capture body from Request object (clone to avoid consuming)
50
- */
51
- async function captureRequestBody(request) {
52
- const captureBody = String(process.env.SECURENOW_CAPTURE_BODY) === '1' ||
53
- String(process.env.SECURENOW_CAPTURE_BODY).toLowerCase() === 'true';
54
-
55
- if (!captureBody) return;
56
- if (!['POST', 'PUT', 'PATCH'].includes(request.method)) return;
57
-
58
- const span = trace.getActiveSpan();
59
- if (!span) return;
60
-
61
- try {
62
- const contentType = request.headers.get('content-type') || '';
63
- const maxBodySize = Math.max(1024, parseInt(process.env.SECURENOW_MAX_BODY_SIZE, 10) || 10240);
64
- const customSensitiveFields = (process.env.SECURENOW_SENSITIVE_FIELDS || '').split(',').map(s => s.trim()).filter(Boolean);
65
- const allSensitiveFields = [...DEFAULT_SENSITIVE_FIELDS, ...customSensitiveFields];
66
-
67
- // Only for supported types
68
- if (!contentType.includes('application/json') &&
69
- !contentType.includes('application/graphql') &&
70
- !contentType.includes('application/x-www-form-urlencoded')) {
71
- return;
72
- }
73
-
74
- // Clone to avoid consuming the original
75
- const cloned = request.clone();
76
- const bodyText = await cloned.text();
77
-
78
- if (bodyText.length > maxBodySize) {
79
- span.setAttribute('http.request.body', `[TOO LARGE: ${bodyText.length} bytes]`);
80
- span.setAttribute('http.request.body.size', bodyText.length);
81
- return;
82
- }
83
-
84
- // Parse and redact based on type
85
- let redacted;
86
- if (contentType.includes('application/json') || contentType.includes('application/graphql')) {
87
- try {
88
- const parsed = JSON.parse(bodyText);
89
- redacted = redactSensitiveData(parsed, allSensitiveFields);
90
- span.setAttributes({
91
- 'http.request.body': JSON.stringify(redacted).substring(0, maxBodySize),
92
- 'http.request.body.type': contentType.includes('graphql') ? 'graphql' : 'json',
93
- 'http.request.body.size': bodyText.length,
94
- });
95
- } catch (e) {
96
- span.setAttribute('http.request.body', '[INVALID JSON]');
97
- }
98
- } else if (contentType.includes('application/x-www-form-urlencoded')) {
99
- const params = new URLSearchParams(bodyText);
100
- const parsed = Object.fromEntries(params);
101
- redacted = redactSensitiveData(parsed, allSensitiveFields);
102
- span.setAttributes({
103
- 'http.request.body': JSON.stringify(redacted).substring(0, maxBodySize),
104
- 'http.request.body.type': 'form',
105
- 'http.request.body.size': bodyText.length,
106
- });
107
- }
108
- } catch (error) {
109
- // Silently fail - never block the request
110
- }
111
- }
112
-
113
- /**
114
- * Wrap a Next.js API route handler to capture body
115
- * This is OPTIONAL and NON-INVASIVE - only use on routes where you want body capture
116
- */
117
- function withSecureNow(handler) {
118
- return async function wrappedHandler(request, context) {
119
- // Capture body asynchronously (doesn't block handler)
120
- captureRequestBody(request).catch(() => {
121
- // Ignore errors silently
122
- });
123
-
124
- // Call original handler immediately - no blocking!
125
- return handler(request, context);
126
- };
127
- }
128
-
129
- /**
130
- * Alternative: Auto-capture wrapper that tries to capture AFTER handler runs
131
- * This is even safer as it never interferes with the handler logic
132
- */
133
- function withSecureNowAsync(handler) {
134
- return async function wrappedHandler(request, context) {
135
- // Try to capture body in background (non-blocking)
136
- const capturePromise = captureRequestBody(request);
137
-
138
- // Run handler
139
- const response = await handler(request, context);
140
-
141
- // Wait for capture to finish (but don't fail if it doesn't)
142
- await capturePromise.catch(() => {});
143
-
144
- return response;
145
- };
146
- }
147
-
148
- module.exports = {
149
- withSecureNow,
150
- withSecureNowAsync,
151
- captureRequestBody,
152
- redactSensitiveData,
153
- DEFAULT_SENSITIVE_FIELDS,
154
- };
155
-
156
-
157
-
158
-
1
+ /**
2
+ * SecureNow Next.js API Route Wrapper for Body Capture
3
+ *
4
+ * This approach is NON-INVASIVE and runs INSIDE your handler,
5
+ * so it never blocks or interferes with middleware or routing.
6
+ *
7
+ * Usage:
8
+ *
9
+ * import { withSecureNow } from 'securenow/nextjs-wrapper';
10
+ *
11
+ * export const POST = withSecureNow(async (request) => {
12
+ * // Your handler code - request.body is available as parsed JSON
13
+ * const data = await request.json();
14
+ * return Response.json({ success: true });
15
+ * });
16
+ */
17
+
18
+ const { trace } = require('@opentelemetry/api');
19
+
20
+ // Default sensitive fields to redact
21
+ const DEFAULT_SENSITIVE_FIELDS = [
22
+ 'password', 'passwd', 'pwd', 'secret', 'token', 'api_key', 'apikey',
23
+ 'access_token', 'auth', 'credentials', 'mysql_pwd', 'stripeToken',
24
+ 'card', 'cardnumber', 'ccv', 'cvc', 'cvv', 'ssn', 'pin',
25
+ ];
26
+
27
+ /**
28
+ * Redact sensitive fields from an object
29
+ */
30
+ function redactSensitiveData(obj, sensitiveFields = DEFAULT_SENSITIVE_FIELDS) {
31
+ if (!obj || typeof obj !== 'object') return obj;
32
+
33
+ const redacted = Array.isArray(obj) ? [...obj] : { ...obj };
34
+
35
+ for (const key of Object.keys(redacted)) {
36
+ const lowerKey = key.toLowerCase();
37
+
38
+ if (sensitiveFields.some(field => lowerKey.includes(field.toLowerCase()))) {
39
+ redacted[key] = '[REDACTED]';
40
+ } else if (typeof redacted[key] === 'object' && redacted[key] !== null) {
41
+ redacted[key] = redactSensitiveData(redacted[key], sensitiveFields);
42
+ }
43
+ }
44
+
45
+ return redacted;
46
+ }
47
+
48
+ /**
49
+ * Capture body from Request object (clone to avoid consuming)
50
+ */
51
+ async function captureRequestBody(request) {
52
+ const captureBody = String(process.env.SECURENOW_CAPTURE_BODY) === '1' ||
53
+ String(process.env.SECURENOW_CAPTURE_BODY).toLowerCase() === 'true';
54
+
55
+ if (!captureBody) return;
56
+ if (!['POST', 'PUT', 'PATCH'].includes(request.method)) return;
57
+
58
+ const span = trace.getActiveSpan();
59
+ if (!span) return;
60
+
61
+ try {
62
+ const contentType = request.headers.get('content-type') || '';
63
+ const maxBodySize = Math.max(1024, parseInt(process.env.SECURENOW_MAX_BODY_SIZE, 10) || 10240);
64
+ const customSensitiveFields = (process.env.SECURENOW_SENSITIVE_FIELDS || '').split(',').map(s => s.trim()).filter(Boolean);
65
+ const allSensitiveFields = [...DEFAULT_SENSITIVE_FIELDS, ...customSensitiveFields];
66
+
67
+ // Only for supported types
68
+ if (!contentType.includes('application/json') &&
69
+ !contentType.includes('application/graphql') &&
70
+ !contentType.includes('application/x-www-form-urlencoded')) {
71
+ return;
72
+ }
73
+
74
+ // Clone to avoid consuming the original
75
+ const cloned = request.clone();
76
+ const bodyText = await cloned.text();
77
+
78
+ if (bodyText.length > maxBodySize) {
79
+ span.setAttribute('http.request.body', `[TOO LARGE: ${bodyText.length} bytes]`);
80
+ span.setAttribute('http.request.body.size', bodyText.length);
81
+ return;
82
+ }
83
+
84
+ // Parse and redact based on type
85
+ let redacted;
86
+ if (contentType.includes('application/json') || contentType.includes('application/graphql')) {
87
+ try {
88
+ const parsed = JSON.parse(bodyText);
89
+ redacted = redactSensitiveData(parsed, allSensitiveFields);
90
+ span.setAttributes({
91
+ 'http.request.body': JSON.stringify(redacted).substring(0, maxBodySize),
92
+ 'http.request.body.type': contentType.includes('graphql') ? 'graphql' : 'json',
93
+ 'http.request.body.size': bodyText.length,
94
+ });
95
+ } catch (e) {
96
+ span.setAttribute('http.request.body', '[INVALID JSON]');
97
+ }
98
+ } else if (contentType.includes('application/x-www-form-urlencoded')) {
99
+ const params = new URLSearchParams(bodyText);
100
+ const parsed = Object.fromEntries(params);
101
+ redacted = redactSensitiveData(parsed, allSensitiveFields);
102
+ span.setAttributes({
103
+ 'http.request.body': JSON.stringify(redacted).substring(0, maxBodySize),
104
+ 'http.request.body.type': 'form',
105
+ 'http.request.body.size': bodyText.length,
106
+ });
107
+ }
108
+ } catch (error) {
109
+ // Silently fail - never block the request
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Wrap a Next.js API route handler to capture body
115
+ * This is OPTIONAL and NON-INVASIVE - only use on routes where you want body capture
116
+ */
117
+ function withSecureNow(handler) {
118
+ return async function wrappedHandler(request, context) {
119
+ // Capture body asynchronously (doesn't block handler)
120
+ captureRequestBody(request).catch(() => {
121
+ // Ignore errors silently
122
+ });
123
+
124
+ // Call original handler immediately - no blocking!
125
+ return handler(request, context);
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Alternative: Auto-capture wrapper that tries to capture AFTER handler runs
131
+ * This is even safer as it never interferes with the handler logic
132
+ */
133
+ function withSecureNowAsync(handler) {
134
+ return async function wrappedHandler(request, context) {
135
+ // Try to capture body in background (non-blocking)
136
+ const capturePromise = captureRequestBody(request);
137
+
138
+ // Run handler
139
+ const response = await handler(request, context);
140
+
141
+ // Wait for capture to finish (but don't fail if it doesn't)
142
+ await capturePromise.catch(() => {});
143
+
144
+ return response;
145
+ };
146
+ }
147
+
148
+ module.exports = {
149
+ withSecureNow,
150
+ withSecureNowAsync,
151
+ captureRequestBody,
152
+ redactSensitiveData,
153
+ DEFAULT_SENSITIVE_FIELDS,
154
+ };
155
+
156
+
157
+
158
+
package/nextjs.js CHANGED
@@ -521,8 +521,8 @@ function registerSecureNow(options = {}) {
521
521
  } catch (_) {}
522
522
 
523
523
  // Graceful shutdown for logs
524
- process.on('SIGTERM', async () => { try { await loggerProvider.shutdown(); } catch (_) {} });
525
- process.on('SIGINT', async () => { try { await loggerProvider.shutdown(); } catch (_) {} });
524
+ process.on('SIGTERM', async () => { try { await loggerProvider.shutdown(); } catch (_) {} try { require('./firewall').shutdown(); } catch (_) {} });
525
+ process.on('SIGINT', async () => { try { await loggerProvider.shutdown(); } catch (_) {} try { require('./firewall').shutdown(); } catch (_) {} });
526
526
  } catch (e) {
527
527
  console.warn('[securenow] ⚠️ Logging setup failed (missing @opentelemetry/exporter-logs-otlp-http or @opentelemetry/sdk-logs):', e.message);
528
528
  }
@@ -541,6 +541,26 @@ function registerSecureNow(options = {}) {
541
541
  }
542
542
  } catch (_) {}
543
543
 
544
+ // Firewall — auto-activates when SECURENOW_API_KEY is set
545
+ const firewallApiKey = env('SECURENOW_API_KEY');
546
+ if (firewallApiKey && env('SECURENOW_FIREWALL_ENABLED') !== '0') {
547
+ try {
548
+ require('./firewall').init({
549
+ apiKey: firewallApiKey,
550
+ apiUrl: env('SECURENOW_API_URL') || 'https://api.securenow.ai',
551
+ syncInterval: parseInt(env('SECURENOW_FIREWALL_SYNC_INTERVAL'), 10) || 60,
552
+ failMode: env('SECURENOW_FIREWALL_FAIL_MODE') || 'open',
553
+ statusCode: parseInt(env('SECURENOW_FIREWALL_STATUS_CODE'), 10) || 403,
554
+ log: env('SECURENOW_FIREWALL_LOG') !== '0',
555
+ tcp: env('SECURENOW_FIREWALL_TCP') === '1',
556
+ iptables: env('SECURENOW_FIREWALL_IPTABLES') === '1',
557
+ cloud: env('SECURENOW_FIREWALL_CLOUD') || null,
558
+ });
559
+ } catch (e) {
560
+ console.warn('[securenow] Firewall init failed:', e.message);
561
+ }
562
+ }
563
+
544
564
  console.log('[securenow] ✅ OpenTelemetry started for Next.js → %s', tracesUrl);
545
565
  console.log('[securenow] 📊 Auto-capturing comprehensive request metadata:');
546
566
  console.log('[securenow] • IP addresses (x-forwarded-for, x-real-ip, socket)');