Static Asset Hardening Strategy
This plan outlines a comprehensive strategy to harden static assets (e.g., JavaScript, CSS, fonts, images) against tampering, supply-chain attacks, and XSS via Subresource Integrity (SRI), Content Security Policy (CSP) with nonces, and automated regression detection. The goal is to ensure integrity, restrict execution, and prevent regressions during development/deployments.
The strategy assumes a modern web stack (e.g., Node.js/Express, Next.js, Vite/Webpack for builds, CI/CD with GitHub Actions/Jenkins). It's phased for minimal disruption: Audit → Implement → Automate → Monitor.
Key Principles
- Defense-in-Depth: SRI verifies fetched resources; CSP nonces allow controlled inline content; regression detection catches breaks.
- Strict Mode: Start permissive, tighten over phases (e.g.,
report-only CSP first).
- Automation-First: Integrate into build/CI pipelines to avoid manual toil.
- Browser Support: Targets modern browsers (Chrome 50+, Firefox 40+); polyfill if needed.
- Static Assets Scope: Third-party CDNs, self-hosted bundles; excludes dynamic user content.
Phase 1: Audit & Preparation (1-2 days)
-
Inventory Assets:
- Crawl site with tools like
wget --mirror or Lighthouse to list all <script>, <link>, <img>, etc.
- Identify inline vs. external; third-party (e.g., Google Fonts, analytics).
-
Baseline Security:
- Check current CSP via browser devtools/Headers.
- Scan for vulnerabilities:
npm audit, Snyk, or Retire.js for deps.
- Test SRI feasibility: Use
openssl dgst -sha384 -binary file.js | openssl base64 -A for manual hashes.
-
Build Pipeline Setup:
- Ensure assets are versioned/hashed (e.g.,
app.abc123.js via Webpack).
- Tools: Install
sri-hash, @rollup/plugin-sri, html-webpack-srihash-plugin.
Phase 2: Implement SRI (2-3 days)
SRI adds integrity attributes to prevent loading tampered resources.
Steps
-
Generate Hashes:
- Use SHA-384 (balanced security/performance):
sha384-ABC123....
- Automate in build:
# Webpack example with html-webpack-srihash-plugin
npm i html-webpack-srihash-plugin
// webpack.config.js
new HtmlWebpackSrihashPlugin({
algorithms: ['sha384'],
source: 'sha384',
crossorigin: 'anonymous' // Required for cross-origin
})
- Output:
<script src="/app.js" integrity="sha384-ABC..." crossorigin="anonymous"></script>
-
Apply to Assets:
| Asset Type | Priority | Example |
|---|
| Third-party JS/CSS (CDNs) | High | jQuery, Bootstrap from unpkg.com |
| Self-hosted bundles | High | Main app.js/css |
| Fonts/Images | Medium | Via <link rel="preload"> or img (SRI support varies) |
| Workers | Low | <script type="moduleworker"> (experimental) |
-
Edge Cases:
- Dynamic imports: Hash at build-time; re-hash on content change.
- CDNs: Pin to specific versions (e.g.,
unpkg.com/lodash@4.17.21).
Phase 3: Implement CSP with Nonces (3-5 days)
CSP blocks unauthorized resources; nonces enable safe inline scripts/styles (e.g., analytics snippets).
Steps
-
CSP Policy Design:
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-{NONCE}' https://trusted.cdn.com 'unsafe-eval' (phased out);
style-src 'self' 'nonce-{NONCE}' https://fonts.googleapis.com;
img-src 'self' data: https:;
font-src 'self' data: https://fonts.gstatic.com;
object-src 'none';
base-uri 'self';
report-uri /csp-report;
- Use
strict-dynamic for modern nonce+SRI combo (CSP3).
-
Nonce Generation:
- Server-Side Rendering (SSR): Generate per-request (crypto.randomBytes(16).toString('base64')).
// Express/Helmet example
app.use((req, res, next) => {
res.locals.nonce = crypto.randomBytes(16).toString('base64');
res.setHeader('Content-Security-Policy', `script-src 'nonce-${res.locals.nonce}' 'strict-dynamic';`);
next();
});
// In template: <script nonce="<%= nonce %>">...</script>
- Static Sites: Avoid inline (use external); or use service workers/Cloudflare Workers for dynamic nonces.
- Client-Side: Inject nonce into inline via
document.currentScript.nonce.
-
Integration:
- Server: Helmet.js (
npm i helmet).
- Meta tag fallback:
<meta http-equiv="Content-Security-Policy" content="...">.
- Combine with SRI: CSP
require-sri-for 'script' (CSP3, Chrome-only).
Phase 4: Automated Regression Detection (Ongoing Setup, 2-4 days)
Prevent deploys that break SRI/CSP (e.g., unhashed assets, CSP blocks).
CI/CD Pipeline Integration
Use GitHub Actions/Jenkins:
# .github/workflows/security.yml
name: Asset Hardening Checks
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run build # Generates SRI-hashed assets
- name: SRI Validation
uses: fendouai/sri-action@v1 # Or custom: curl assets, verify integrity
- name: E2E CSP/SRI Tests
uses: microsoft/playwright-github-action@v1
with:
playwright-version: '1.40'
- run: npx playwright test security.spec.js # See below
Test Suite (Playwright/Puppeteer)
// security.spec.js
test('No CSP/SRI violations', async ({ page }) => {
// Intercept CSP reports
page.route('**/csp-report', route => route.fulfill({ status: 204 }));
page.on('console', msg => {
if (msg.type() === 'error' && msg.text().includes('CSP') || msg.text().includes('SRI')) {
throw new Error(`Violation: ${msg.text()}`);
}
});
// Load page with strict CSP header mocked
await page.setExtraHTTPHeaders({ 'Content-Security-Policy': strictCSP });
await page.goto('/');
await expect(page.locator('#critical-feature')).toBeVisible(); // Business logic check
});
Additional Tools
| Tool | Purpose | Command/Example |
|---|
| csp-scan | Audit CSP | npx csp-scan https://example.com |
| Lighthouse CI | Performance + Security | lhci autorun (flags CSP/SRI issues) |
| Sentry/ELK | Prod Monitoring | Capture securitypolicyviolation events |
| webpack-bundle-analyzer | Detect bloat/changes | Auto-regression on bundle size/hash diffs |
Phase 5: Rollout & Monitoring (Ongoing)
-
Phased Deploy:
- Week 1:
Content-Security-Policy-Report-Only + third-party SRI.
- Week 2: Full CSP/SRI on staging.
- Week 3: Prod with feature flags.
-
Monitoring:
- CSP reports: Endpoint logs violations to Datadog/Splunk.
- Alerts: >5 violations/hour → Slack/ PagerDuty.
- Quarterly audits: Re-run Phase 1.
-
Maintenance:
- Hook SRI hash gen to asset changes (watch mode).
- Rotate nonces: Per-request by design.
- Update on deps change:
npm outdated → rebuild.
Expected Outcomes & Metrics
- Security: Blocks 100% tampered assets; reduces XSS surface.
- Performance: Minimal overhead (<1% load time); CDNs still cacheable.
- Reliability: 0 regressions via CI gate.
- Cost: ~$50/month (tools/monitoring); free OSS alternatives.
| Metric | Target | Measurement |
|---|
| CSP Violations | <1/day | Report endpoint |
| SRI Coverage | 100% critical assets | CI scan |
| Load Failures | 0% | Playwright + Sentry |
This strategy is production-ready and scalable. Customize for your stack (e.g., React/Vue specifics). If you provide your tech stack or site URL, I can refine with code snippets!