#!/usr/bin/env node
/**
* CSP Violation Auto-Remediation Script
*
* Analyzes CSP violations and provides fix recommendations.
* Can optionally attempt automatic fixes for simple cases.
*
* Usage:
* node scripts/fix-csp-violations.js [--auto] [file]
*
* Options:
* --auto Attempt automatic fixes (USE WITH CAUTION)
* --dry-run Show what would be fixed without making changes
* [file] Specific file to fix (default: scan all)
*
* Copyright 2025 Tractatus Project
* Licensed under Apache License 2.0
*/
const fs = require('fs');
const path = require('path');
const { scanForViolations, scanFile } = require('./check-csp-violations');
const colors = {
reset: '\x1b[0m',
green: '\x1b[32m',
yellow: '\x1b[33m',
red: '\x1b[31m',
cyan: '\x1b[36m',
bold: '\x1b[1m'
};
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
/**
* Parse command-line arguments
*/
function parseArgs() {
const args = process.argv.slice(2);
return {
auto: args.includes('--auto'),
dryRun: args.includes('--dry-run'),
file: args.find(arg => !arg.startsWith('--'))
};
}
/**
* Generate fix recommendations for a violation
*/
function generateFixRecommendation(violation) {
const recommendations = {
inline_event_handlers: {
priority: 'HIGH',
approach: 'Move to external JavaScript',
steps: [
`1. Create event listener in external JS file:`,
` document.getElementById('element-id').addEventListener('click', function() {`,
` // Handler code here`,
` });`,
``,
`2. Remove ${violation.matched.split('=')[0]}= attribute from HTML`,
``,
`3. Add unique ID to element if needed for selection`
],
example: 'See public/js/components/*.js for examples'
},
inline_styles: {
priority: 'HIGH',
approach: 'Move to Tailwind CSS classes or external CSS',
steps: [
`1. For dynamic styles: Use CSS classes with JavaScript`,
` element.classList.add('custom-style');`,
``,
`2. For static styles: Add Tailwind classes to HTML`,
` Replace style="${violation.matched}" with Tailwind utilities`,
``,
`3. For complex styles: Add to public/css/custom.css`
],
example: 'Project uses Tailwind CSS - prefer utility classes'
},
inline_scripts: {
priority: 'CRITICAL',
approach: 'Extract to external JavaScript file',
steps: [
`1. Create or identify appropriate JS file in public/js/`,
``,
`2. Move script content to external file`,
``,
`3. Replace inline script with:`,
` `,
``,
`4. Ensure script loads at appropriate time (defer/async if needed)`
],
example: 'See public/js/*.js for existing patterns'
},
javascript_urls: {
priority: 'CRITICAL',
approach: 'Replace with proper event handlers',
steps: [
`1. Remove href="javascript:..." attribute`,
``,
`2. Add event listener in external JS:`,
` document.getElementById('link-id').addEventListener('click', function(e) {`,
` e.preventDefault();`,
` // Action code here`,
` });`,
``,
`3. For links that don't navigate, consider using