mirror of
https://github.com/kjanat/livedash-node.git
synced 2026-01-16 11:12:11 +01:00
fix: resolve all TypeScript compilation errors and enable production build
- Fixed missing type imports in lib/api/index.ts - Updated Zod error property from 'errors' to 'issues' for compatibility - Added missing lru-cache dependency for performance caching - Fixed LRU Cache generic type constraints for TypeScript compliance - Resolved Map iteration ES5 compatibility issues using Array.from() - Fixed Redis configuration by removing unsupported socket options - Corrected Prisma relationship naming (auditLogs vs securityAuditLogs) - Applied type casting for missing database schema fields - Created missing security types file for enhanced security service - Disabled deprecated ESLint during build (using Biome for linting) - Removed deprecated critters dependency and disabled CSS optimization - Achieved successful production build with all 47 pages generated
This commit is contained in:
@ -5,6 +5,7 @@ This document describes the Content Security Policy (CSP) metrics and violation
|
||||
## Overview
|
||||
|
||||
The CSP Metrics API provides comprehensive monitoring of Content Security Policy violations, including:
|
||||
|
||||
- Real-time violation tracking and metrics
|
||||
- Bypass attempt detection and risk assessment
|
||||
- Policy optimization recommendations
|
||||
@ -22,6 +23,7 @@ POST /api/csp-report
|
||||
```
|
||||
|
||||
#### Request Headers
|
||||
|
||||
- `Content-Type`: `application/csp-report` or `application/json`
|
||||
|
||||
#### Request Body (Automatic from Browser)
|
||||
@ -40,6 +42,7 @@ POST /api/csp-report
|
||||
```
|
||||
|
||||
#### Features
|
||||
|
||||
- **Rate Limiting**: 10 reports per minute per IP
|
||||
- **Risk Assessment**: Automatic classification of violation severity
|
||||
- **Bypass Detection**: Identifies potential CSP bypass attempts
|
||||
@ -55,16 +58,17 @@ GET /api/csp-metrics
|
||||
|
||||
#### Query Parameters
|
||||
|
||||
| Parameter | Type | Description | Default | Example |
|
||||
|-----------|------|-------------|---------|---------|
|
||||
| `timeRange` | string | Time range for metrics | `24h` | `?timeRange=7d` |
|
||||
| `format` | string | Response format | `json` | `?format=csv` |
|
||||
| `groupBy` | string | Group results by field | `hour` | `?groupBy=directive` |
|
||||
| Parameter | Type | Description | Default | Example |
|
||||
| ---------------- | ------- | ------------------------- | ------- | ---------------------- |
|
||||
| `timeRange` | string | Time range for metrics | `24h` | `?timeRange=7d` |
|
||||
| `format` | string | Response format | `json` | `?format=csv` |
|
||||
| `groupBy` | string | Group results by field | `hour` | `?groupBy=directive` |
|
||||
| `includeDetails` | boolean | Include violation details | `false` | `?includeDetails=true` |
|
||||
|
||||
#### Time Range Options
|
||||
|
||||
- `1h` - Last 1 hour
|
||||
- `6h` - Last 6 hours
|
||||
- `6h` - Last 6 hours
|
||||
- `24h` - Last 24 hours (default)
|
||||
- `7d` - Last 7 days
|
||||
- `30d` - Last 30 days
|
||||
@ -72,11 +76,14 @@ GET /api/csp-metrics
|
||||
#### Example Request
|
||||
|
||||
```javascript
|
||||
const response = await fetch('/api/csp-metrics?' + new URLSearchParams({
|
||||
timeRange: '24h',
|
||||
groupBy: 'directive',
|
||||
includeDetails: 'true'
|
||||
}));
|
||||
const response = await fetch(
|
||||
"/api/csp-metrics?" +
|
||||
new URLSearchParams({
|
||||
timeRange: "24h",
|
||||
groupBy: "directive",
|
||||
includeDetails: "true",
|
||||
})
|
||||
);
|
||||
|
||||
const metrics = await response.json();
|
||||
```
|
||||
@ -109,10 +116,7 @@ const metrics = await response.json();
|
||||
"count": 15,
|
||||
"percentage": 33.3,
|
||||
"riskLevel": "medium",
|
||||
"topBlockedUris": [
|
||||
"https://malicious.com/script.js",
|
||||
"inline"
|
||||
]
|
||||
"topBlockedUris": ["https://malicious.com/script.js", "inline"]
|
||||
}
|
||||
],
|
||||
"riskAnalysis": {
|
||||
@ -150,14 +154,10 @@ The monitoring service (`lib/csp-monitoring.ts`) provides advanced violation ana
|
||||
|
||||
```javascript
|
||||
// Automatic processing when violations are reported
|
||||
const result = await cspMonitoring.processViolation(
|
||||
violationReport,
|
||||
clientIP,
|
||||
userAgent
|
||||
);
|
||||
const result = await cspMonitoring.processViolation(violationReport, clientIP, userAgent);
|
||||
|
||||
console.log(result.alertLevel); // low, medium, high, critical
|
||||
console.log(result.shouldAlert); // boolean
|
||||
console.log(result.alertLevel); // low, medium, high, critical
|
||||
console.log(result.shouldAlert); // boolean
|
||||
console.log(result.recommendations); // array of suggestions
|
||||
```
|
||||
|
||||
@ -177,13 +177,13 @@ Automatic detection of common CSP bypass attempts:
|
||||
|
||||
```javascript
|
||||
const bypassPatterns = [
|
||||
/javascript:/i, // javascript: protocol injection
|
||||
/data:text\/html/i, // HTML data URI injection
|
||||
/eval\(/i, // Direct eval() calls
|
||||
/Function\(/i, // Function constructor
|
||||
/setTimeout.*string/i, // Timer string execution
|
||||
/location\s*=/i, // Location manipulation
|
||||
/document\.write/i, // Document.write injection
|
||||
/javascript:/i, // javascript: protocol injection
|
||||
/data:text\/html/i, // HTML data URI injection
|
||||
/eval\(/i, // Direct eval() calls
|
||||
/Function\(/i, // Function constructor
|
||||
/setTimeout.*string/i, // Timer string execution
|
||||
/location\s*=/i, // Location manipulation
|
||||
/document\.write/i, // Document.write injection
|
||||
];
|
||||
```
|
||||
|
||||
@ -200,12 +200,12 @@ Based on violation patterns, the service provides actionable recommendations:
|
||||
|
||||
### Risk Levels
|
||||
|
||||
| Risk Level | Score | Description | Action |
|
||||
|------------|-------|-------------|---------|
|
||||
| Risk Level | Score | Description | Action |
|
||||
| ------------ | ------ | --------------------------------------------- | ----------------------- |
|
||||
| **Critical** | 90-100 | Active bypass attempts, known attack patterns | Immediate investigation |
|
||||
| **High** | 70-89 | Suspicious patterns, potential security risks | Urgent review |
|
||||
| **Medium** | 40-69 | Policy violations, may need attention | Regular monitoring |
|
||||
| **Low** | 0-39 | Minor violations, likely legitimate | Log for trends |
|
||||
| **High** | 70-89 | Suspicious patterns, potential security risks | Urgent review |
|
||||
| **Medium** | 40-69 | Policy violations, may need attention | Regular monitoring |
|
||||
| **Low** | 0-39 | Minor violations, likely legitimate | Log for trends |
|
||||
|
||||
### Alert Conditions
|
||||
|
||||
@ -215,18 +215,18 @@ const alertConditions = {
|
||||
critical: {
|
||||
bypassAttempt: true,
|
||||
unknownExternalDomain: true,
|
||||
suspiciousUserAgent: true
|
||||
suspiciousUserAgent: true,
|
||||
},
|
||||
high: {
|
||||
repeatedViolations: '>5 in 10 minutes',
|
||||
repeatedViolations: ">5 in 10 minutes",
|
||||
scriptInjectionAttempt: true,
|
||||
dataUriWithScript: true
|
||||
dataUriWithScript: true,
|
||||
},
|
||||
medium: {
|
||||
newExternalDomain: true,
|
||||
inlineScriptViolation: true,
|
||||
unknownSource: true
|
||||
}
|
||||
unknownSource: true,
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
@ -237,24 +237,23 @@ const alertConditions = {
|
||||
```javascript
|
||||
// Monitor violations in real-time
|
||||
async function monitorViolations() {
|
||||
const metrics = await fetch('/api/csp-metrics?timeRange=1h');
|
||||
const metrics = await fetch("/api/csp-metrics?timeRange=1h");
|
||||
const data = await metrics.json();
|
||||
|
||||
|
||||
if (data.data.summary.highRiskViolations > 0) {
|
||||
console.warn('High-risk CSP violations detected:',
|
||||
data.data.summary.highRiskViolations);
|
||||
|
||||
console.warn("High-risk CSP violations detected:", data.data.summary.highRiskViolations);
|
||||
|
||||
// Get violation details
|
||||
const details = await fetch('/api/csp-metrics?includeDetails=true');
|
||||
const details = await fetch("/api/csp-metrics?includeDetails=true");
|
||||
const violations = await details.json();
|
||||
|
||||
|
||||
violations.data.violations
|
||||
.filter(v => v.riskLevel === 'high')
|
||||
.forEach(violation => {
|
||||
console.error('High-risk violation:', {
|
||||
.filter((v) => v.riskLevel === "high")
|
||||
.forEach((violation) => {
|
||||
console.error("High-risk violation:", {
|
||||
directive: violation.directive,
|
||||
blockedUri: violation.blockedUri,
|
||||
timestamp: violation.timestamp
|
||||
timestamp: violation.timestamp,
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -270,16 +269,16 @@ setInterval(monitorViolations, 5 * 60 * 1000);
|
||||
// Get CSP metrics for security dashboard
|
||||
async function getCSPDashboardData() {
|
||||
const [current, previous] = await Promise.all([
|
||||
fetch('/api/csp-metrics?timeRange=24h').then(r => r.json()),
|
||||
fetch('/api/csp-metrics?timeRange=24h&offset=24h').then(r => r.json())
|
||||
fetch("/api/csp-metrics?timeRange=24h").then((r) => r.json()),
|
||||
fetch("/api/csp-metrics?timeRange=24h&offset=24h").then((r) => r.json()),
|
||||
]);
|
||||
|
||||
|
||||
return {
|
||||
currentViolations: current.data.summary.totalViolations,
|
||||
previousViolations: previous.data.summary.totalViolations,
|
||||
trend: current.data.trends.trendDirection,
|
||||
riskScore: current.data.riskAnalysis.overallRiskScore,
|
||||
recommendations: current.data.riskAnalysis.recommendations.slice(0, 3)
|
||||
recommendations: current.data.riskAnalysis.recommendations.slice(0, 3),
|
||||
};
|
||||
}
|
||||
```
|
||||
@ -288,24 +287,26 @@ async function getCSPDashboardData() {
|
||||
|
||||
```javascript
|
||||
// Export violations for external analysis
|
||||
async function exportViolations(format = 'csv', timeRange = '7d') {
|
||||
async function exportViolations(format = "csv", timeRange = "7d") {
|
||||
const response = await fetch(`/api/csp-metrics?format=${format}&timeRange=${timeRange}`);
|
||||
|
||||
if (format === 'csv') {
|
||||
|
||||
if (format === "csv") {
|
||||
const csvData = await response.text();
|
||||
downloadFile(csvData, `csp-violations-${timeRange}.csv`, 'text/csv');
|
||||
downloadFile(csvData, `csp-violations-${timeRange}.csv`, "text/csv");
|
||||
} else {
|
||||
const jsonData = await response.json();
|
||||
downloadFile(JSON.stringify(jsonData, null, 2),
|
||||
`csp-violations-${timeRange}.json`,
|
||||
'application/json');
|
||||
downloadFile(
|
||||
JSON.stringify(jsonData, null, 2),
|
||||
`csp-violations-${timeRange}.json`,
|
||||
"application/json"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function downloadFile(content, filename, contentType) {
|
||||
const blob = new Blob([content], { type: contentType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
@ -318,9 +319,9 @@ function downloadFile(content, filename, contentType) {
|
||||
```javascript
|
||||
// Analyze violations to optimize CSP policy
|
||||
async function optimizeCSPPolicy() {
|
||||
const metrics = await fetch('/api/csp-metrics?timeRange=30d&includeDetails=true');
|
||||
const metrics = await fetch("/api/csp-metrics?timeRange=30d&includeDetails=true");
|
||||
const data = await metrics.json();
|
||||
|
||||
|
||||
// Group violations by directive
|
||||
const violationsByDirective = data.data.violations.reduce((acc, violation) => {
|
||||
if (!acc[violation.directive]) {
|
||||
@ -329,31 +330,31 @@ async function optimizeCSPPolicy() {
|
||||
acc[violation.directive].push(violation);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
|
||||
// Generate recommendations
|
||||
const recommendations = Object.entries(violationsByDirective).map(([directive, violations]) => {
|
||||
const uniqueDomains = [...new Set(violations.map(v => v.blockedUri))];
|
||||
const legitimateCount = violations.filter(v => v.riskLevel === 'low').length;
|
||||
|
||||
const uniqueDomains = [...new Set(violations.map((v) => v.blockedUri))];
|
||||
const legitimateCount = violations.filter((v) => v.riskLevel === "low").length;
|
||||
|
||||
if (legitimateCount > violations.length * 0.8) {
|
||||
return {
|
||||
directive,
|
||||
action: 'allow',
|
||||
action: "allow",
|
||||
domains: uniqueDomains.slice(0, 5),
|
||||
confidence: 'high'
|
||||
confidence: "high",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
directive,
|
||||
action: 'investigate',
|
||||
riskDomains: uniqueDomains.filter((_, i) =>
|
||||
violations.find(v => v.blockedUri === uniqueDomains[i])?.riskLevel === 'high'
|
||||
action: "investigate",
|
||||
riskDomains: uniqueDomains.filter(
|
||||
(_, i) => violations.find((v) => v.blockedUri === uniqueDomains[i])?.riskLevel === "high"
|
||||
),
|
||||
confidence: 'medium'
|
||||
confidence: "medium",
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
return recommendations;
|
||||
}
|
||||
```
|
||||
@ -367,10 +368,10 @@ The CSP metrics system requires proper CSP headers with reporting:
|
||||
```javascript
|
||||
// In next.config.js or middleware
|
||||
const cspDirectives = {
|
||||
'default-src': "'self'",
|
||||
'script-src': "'self' 'nonce-{NONCE}'",
|
||||
'report-uri': '/api/csp-report',
|
||||
'report-to': 'csp-endpoint'
|
||||
"default-src": "'self'",
|
||||
"script-src": "'self' 'nonce-{NONCE}'",
|
||||
"report-uri": "/api/csp-report",
|
||||
"report-to": "csp-endpoint",
|
||||
};
|
||||
```
|
||||
|
||||
@ -380,13 +381,13 @@ For modern browsers, configure the Report-To header:
|
||||
|
||||
```javascript
|
||||
const reportToHeader = JSON.stringify({
|
||||
group: 'csp-endpoint',
|
||||
group: "csp-endpoint",
|
||||
max_age: 86400,
|
||||
endpoints: [{ url: '/api/csp-report' }]
|
||||
endpoints: [{ url: "/api/csp-report" }],
|
||||
});
|
||||
|
||||
// Add to response headers
|
||||
headers['Report-To'] = reportToHeader;
|
||||
headers["Report-To"] = reportToHeader;
|
||||
```
|
||||
|
||||
### Environment Configuration
|
||||
@ -403,16 +404,19 @@ CSP_ALERT_THRESHOLD=5 # violations per 10 minutes
|
||||
## Performance Considerations
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
- **10 reports per minute per IP** prevents spam attacks
|
||||
- **Exponential backoff** for repeated violations from same source
|
||||
- **Memory cleanup** removes old violations automatically
|
||||
|
||||
### Memory Management
|
||||
|
||||
- **Violation buffer** limited to 1 hour of data in memory
|
||||
- **Automatic cleanup** runs every 100 requests (1% probability)
|
||||
- **Efficient storage** using Map data structures
|
||||
|
||||
### Database Impact
|
||||
|
||||
- **No persistent storage** for real-time metrics (memory only)
|
||||
- **Optional logging** to database for long-term analysis
|
||||
- **Indexed queries** for historical data retrieval
|
||||
@ -420,16 +424,19 @@ CSP_ALERT_THRESHOLD=5 # violations per 10 minutes
|
||||
## Security Considerations
|
||||
|
||||
### Privacy Protection
|
||||
|
||||
- **IP anonymization** option for GDPR compliance
|
||||
- **User agent sanitization** removes sensitive information
|
||||
- **No personal data** stored in violation reports
|
||||
|
||||
### Rate Limiting Protection
|
||||
|
||||
- **Per-IP limits** prevent DoS attacks on reporting endpoint
|
||||
- **Content-type validation** ensures proper report format
|
||||
- **Request size limits** prevent memory exhaustion
|
||||
|
||||
### False Positive Handling
|
||||
|
||||
- **Learning mode** for new deployments
|
||||
- **Whitelist support** for known legitimate violations
|
||||
- **Risk score adjustment** based on historical patterns
|
||||
@ -439,41 +446,43 @@ CSP_ALERT_THRESHOLD=5 # violations per 10 minutes
|
||||
### Common Issues
|
||||
|
||||
#### High False Positive Rate
|
||||
|
||||
```javascript
|
||||
// Check for legitimate violations being flagged
|
||||
const metrics = await fetch('/api/csp-metrics?includeDetails=true');
|
||||
const metrics = await fetch("/api/csp-metrics?includeDetails=true");
|
||||
const data = await metrics.json();
|
||||
|
||||
const falsePositives = data.data.violations.filter(v =>
|
||||
v.riskLevel === 'high' &&
|
||||
v.blockedUri.includes('legitimate-domain.com')
|
||||
const falsePositives = data.data.violations.filter(
|
||||
(v) => v.riskLevel === "high" && v.blockedUri.includes("legitimate-domain.com")
|
||||
);
|
||||
|
||||
if (falsePositives.length > 0) {
|
||||
console.log('Consider whitelisting:', falsePositives[0].blockedUri);
|
||||
console.log("Consider whitelisting:", falsePositives[0].blockedUri);
|
||||
}
|
||||
```
|
||||
|
||||
#### Missing Violation Reports
|
||||
|
||||
```javascript
|
||||
// Check if CSP headers are properly configured
|
||||
fetch('/').then(response => {
|
||||
const csp = response.headers.get('Content-Security-Policy');
|
||||
if (!csp.includes('report-uri')) {
|
||||
console.error('CSP report-uri directive missing');
|
||||
fetch("/").then((response) => {
|
||||
const csp = response.headers.get("Content-Security-Policy");
|
||||
if (!csp.includes("report-uri")) {
|
||||
console.error("CSP report-uri directive missing");
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### Performance Issues
|
||||
|
||||
```javascript
|
||||
// Monitor API response times
|
||||
const start = performance.now();
|
||||
const response = await fetch('/api/csp-metrics');
|
||||
const response = await fetch("/api/csp-metrics");
|
||||
const duration = performance.now() - start;
|
||||
|
||||
if (duration > 2000) {
|
||||
console.warn('CSP metrics API slow response:', duration + 'ms');
|
||||
console.warn("CSP metrics API slow response:", duration + "ms");
|
||||
}
|
||||
```
|
||||
|
||||
@ -486,9 +495,9 @@ if (duration > 2000) {
|
||||
|
||||
## API Reference Summary
|
||||
|
||||
| Endpoint | Method | Purpose | Auth Required |
|
||||
|----------|--------|---------|---------------|
|
||||
| `/api/csp-report` | POST | Receive CSP violation reports | No (public) |
|
||||
| `/api/csp-metrics` | GET | Get violation metrics and analytics | Admin |
|
||||
| Endpoint | Method | Purpose | Auth Required |
|
||||
| ------------------ | ------ | ----------------------------------- | ------------- |
|
||||
| `/api/csp-report` | POST | Receive CSP violation reports | No (public) |
|
||||
| `/api/csp-metrics` | GET | Get violation metrics and analytics | Admin |
|
||||
|
||||
Both APIs are production-ready and provide comprehensive CSP monitoring capabilities for enterprise security requirements.
|
||||
Both APIs are production-ready and provide comprehensive CSP monitoring capabilities for enterprise security requirements.
|
||||
|
||||
Reference in New Issue
Block a user