ShowerLoop-cc/csp-hash-calculator.js

38 lines
1.0 KiB
JavaScript
Executable File

#!/usr/bin/env node
/**
* CSP Hash Calculator
*
* This script calculates SHA-256 hashes for inline scripts and styles
* to be used in Content Security Policy headers.
*
* Usage:
* node csp-hash-calculator.js "<inline-code>"
*
* Example:
* node csp-hash-calculator.js "document.addEventListener('DOMContentLoaded', function() { console.log('Hello'); });"
*/
const crypto = require('crypto');
// Function to calculate CSP hash
function calculateHash(content) {
const hash = crypto.createHash('sha256').update(content, 'utf8').digest('base64');
return `'sha256-${hash}'`;
}
// Get content from command line argument or stdin
const content = process.argv[2] || '';
if (!content) {
console.error('Error: No content provided. Please provide content as a command line argument.');
process.exit(1);
}
// Calculate and display the hash
const hash = calculateHash(content);
console.log('CSP Hash:');
console.log(hash);
console.log('\nAdd to your CSP header:');
console.log('For script: script-src ' + hash);
console.log('For style: style-src ' + hash);