Skip to content

Production-ready CSP injector for React, Angular & VITE projects. Smart auto-detection, environment variables, workspace support. Enterprise-grade SPA security.

License

Notifications You must be signed in to change notification settings

sourcefuse/arc-spa-csp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ arc-spa-csp

Content Security Policy (CSP) injector for Single Page Applications (SPAs) - React, Angular, and VITE projects with comprehensive framework support

npm version License: MIT TypeScript Coverage Tests Node.js

✨ Features

  • 🎯 Smart Auto-detection: Automatically finds HTML files for React, Angular, VITE, and workspace projects
  • πŸ“¦ Zero Runtime Dependencies: Pure TypeScript with minimal external dependencies
  • βš™οΈ Intelligent Defaults: Works out-of-the-box with framework-specific CSP policies
  • πŸ”§ Environment Aware: Separate development and production configurations
  • πŸ“„ Maximum Flexibility: Supports custom HTML and config file paths
  • πŸ” Production Ready: Secure CSP policies with cryptographic nonce support
  • 🌍 Template Variables: Dynamic interpolation with {{REACT_APP_}}, {{VITE_}}, and {{NG_*}}
  • πŸš€ Full VITE Support: Complete VITE environment variable integration
  • πŸ—οΈ Angular Workspace: Native support for Angular workspace projects with proper environment isolation

πŸš€ Quick Start

Installation

npm install -g arc-spa-csp
# or
npx arc-spa-csp init  # Create default config

Development Mode (No Build Required)

React Projects

# Inject CSP into public/index.html (used by React dev server)
arc-spa-csp --dev

VITE Projects

# Inject CSP into index.html (used by VITE dev server)
arc-spa-csp --dev

Angular Projects

# Inject CSP into src/index.html (used by ng serve)
arc-spa-csp --dev

Angular Workspaces

# Auto-detects projects/*/src/index.html (e.g., projects/arc/src/index.html)
arc-spa-csp --dev

# Or specify explicitly:
arc-spa-csp --dev --html projects/arc/src/index.html

Production Mode (After Build)

# For React (after npm run build)
npm run build
arc-spa-csp

# For VITE (after npm run build)
npm run build
arc-spa-csp

# For Angular (after ng build)
ng build
arc-spa-csp

# Custom HTML file
arc-spa-csp --html dist/my-app/index.html

πŸ› οΈ CLI Commands

Initialize Configuration

# Create default csp.config.json
arc-spa-csp init

# Interactive configuration wizard (recommended)
arc-spa-csp init --interactive

# Use with npx (no installation)
npx arc-spa-csp init --interactive

πŸ§™β€β™‚οΈ Interactive Configuration Wizard

The interactive mode guides you through creating the perfect CSP configuration for your project:

arc-spa-csp init --interactive

Features

  • πŸš€ Framework Detection: Choose from React CRA, VITE, Angular CLI, or Generic
  • βš™οΈ Configuration Type: Development (permissive) or Production (strict)
  • πŸ” Security Options: Enable nonce support for enhanced security
  • 🌍 Environment Variables: Auto-include framework-specific variable templates
  • πŸ“Š Report Mode: Option for report-only CSP (logs without blocking)

Example Interactive Session

πŸŽ‰ Welcome to arc-spa-csp configuration wizard!
Let's set up your Content Security Policy configuration.

πŸš€ Which framework are you using?
  1. React (Create React App) - Traditional React with Create React App
  2. VITE (React/Vue/Vanilla) - Modern build tool with fast HMR
  3. Angular CLI - Angular framework with CLI
  4. Generic/Other - Other frameworks or custom setup

Select framework (1-4): 2
βœ… Selected: VITE (React/Vue/Vanilla)

βš™οΈ Configuration type:
  1. Development (permissive, good for testing)
  2. Production (strict, secure for deployment)
  3. Custom (configure directives manually)

Select type (1-3): 1
βœ… Configuration type: development

πŸ” Enable nonce for inline scripts/styles? (recommended for production) [y/N]: n

❓ Use report-only mode? (logs violations without blocking) [y/N]: n

🌍 Include VITE_* environment variable templates? [Y/n]: y

βš™οΈ Configuration summary:
  Framework: vite
  Type: development
  Nonce: disabled
  Report-only: disabled
  Environment variables: included

βš™οΈ Created config file: csp.config.json

Inject CSP

USAGE:
  arc-spa-csp [options]

COMMANDS:
  init                         Create default csp.config.json file
  (no command)                 Inject CSP into HTML file

OPTIONS:
  --html, -h <path>     Path to HTML file (auto-detected if not specified)
  --config, -c <path>   Path to config file (uses defaults if not specified)
  --dev, -d            Development mode (injects into source files)
  --dry-run            Show what would be done without making changes
  --help               Show this help
  --version, -v        Show version

EXAMPLES:
  arc-spa-csp                              # Auto-detect and inject CSP
  arc-spa-csp --dev                        # Development mode (no build required)
  arc-spa-csp --html build/index.html      # Specific HTML file
  arc-spa-csp --config custom.json         # Custom config
  arc-spa-csp --dry-run                    # Preview changes
  arc-spa-csp init                         # Create default config file

πŸ”„ Development Workflow

Working with Dev Servers

The --dev flag is designed for development workflows where you want to test CSP policies without building your project:

React Development

  1. Run arc-spa-csp --dev - modifies public/index.html
  2. Start your dev server: npm start or yarn start
  3. The React dev server serves the modified HTML with CSP headers
  4. Test your application and iterate on CSP policies

VITE Development

  1. Run arc-spa-csp --dev - modifies index.html
  2. Start VITE dev server: npm run dev or yarn dev
  3. The VITE dev server serves the modified HTML with CSP headers
  4. Test your application with real CSP policies

Angular Development

  1. Run arc-spa-csp --dev - modifies src/index.html
  2. Start Angular dev server: ng serve
  3. The Angular dev server serves the modified HTML with CSP headers
  4. Test your application and iterate on CSP policies

Key Benefits

  • βœ… No build required - Test CSP policies immediately
  • βœ… Hot reload friendly - CSP persists through dev server reloads
  • βœ… Source control safe - Changes are in source files
  • βœ… Environment aware - Automatic resolution of development env vars

Production Deployment

For production, run CSP injection after your build process:

# React
npm run build
arc-spa-csp

# VITE
npm run build
arc-spa-csp

# Angular
ng build
arc-spa-csp

πŸ“ Framework Auto-Detection

βš›οΈ React Projects

React Development Mode (--dev)

  • βœ… public/index.html (Create React App default)

React Production Mode (default)

  • βœ… build/index.html (Create React App build output)
  • βœ… dist/index.html (Vite, Webpack builds)

⚑ VITE Projects

VITE Development Mode (--dev)

  • βœ… index.html (VITE project root)

VITE Production Mode (default)

  • βœ… dist/index.html (VITE build output)

πŸ…°οΈ Angular Projects

Angular Development Mode (--dev)

  • βœ… src/index.html (Standard Angular project)
  • βœ… projects/*/src/index.html (Angular workspace projects)

Angular Production Mode (default)

  • βœ… dist/project-name/index.html (Angular CLI default)
  • βœ… dist/index.html (Simple builds)
  • πŸ” Smart Detection: Reads angular.json to find exact build output path

πŸ—οΈ Angular Workspace Support

Full support for Angular workspace projects with proper environment isolation.

How it works:

# Workspace root - uses workspace environment
arc-spa-csp --dev --html src/index.html

# Specific project - uses project-specific environment
arc-spa-csp --dev --html projects/my-app/src/index.html

Environment Variable Loading:

  • Workspace Root: src/environments/environment.ts β†’ NG_* variables
  • Workspace Project: projects/my-app/src/environments/environment.ts β†’ NG_* variables
  • Automatic Detection: Detects correct project root from HTML path
  • Environment Isolation: Each project can have different environment variables

Example Workspace Structure:

my-workspace/
β”œβ”€β”€ angular.json
β”œβ”€β”€ src/environments/environment.ts          # Workspace root env
└── projects/
    β”œβ”€β”€ app1/src/environments/environment.ts # App1 specific env
    └── app2/src/environments/environment.ts # App2 specific env

Usage Examples:

# Target specific workspace project
arc-spa-csp --dev --html projects/app1/src/index.html

# Auto-detection finds workspace projects
arc-spa-csp --dev  # Searches projects/*/src/index.html automatically

# Different environments for different projects
# app1 uses: NG_APIURL=https://app1-api.com
# app2 uses: NG_APIURL=https://app2-api.com

🌐 Other Frameworks

While optimized for React, VITE, and Angular, the tool can work with other frameworks that use similar HTML file structures:

  • βœ… Ionic: www/index.html
  • βœ… Vue.js: dist/index.html, public/index.html (generic HTML detection)
  • βœ… Generic HTML: index.html (root directory)

Note: Environment variable support ({{VARIABLE}}) is specific to React, VITE, and Angular projects.

βš™οΈ Configuration

Quick Setup

# Create default configuration
arc-spa-csp init

# This creates csp.config.json with sensible defaults

Manual Configuration

Create a csp.config.json file in your project root:

{
  "directives": {
    "default-src": ["'self'"],
    "script-src": ["'self'", "'unsafe-inline'"],
    "style-src": ["'self'", "'unsafe-inline'"],
    "img-src": ["'self'", "data:", "blob:"],
    "font-src": ["'self'", "data:"],
    "connect-src": ["'self'"],
    "worker-src": ["'self'", "blob:"],
    "manifest-src": ["'self'"]
  },
  "useNonce": false,
  "reportOnly": false
}

Environment Variable Support

Create dynamic configurations with template variables:

{
  "directives": {
    "script-src": ["'self'", "{{REACT_APP_API_URL}}", "{{VITE_API_URL}}", "{{NG_APIURL}}"],
    "img-src": ["'self'", "data:", "{{REACT_APP_CDN_URL}}", "{{VITE_CDN_URL}}"],
    "connect-src": ["'self'", "{{REACT_APP_API_URL}}", "{{VITE_API_URL}}", "{{NG_APIURL}}"]
  },
  "useNonce": true
}

React Environment Variables

  • βœ… .env files (all variants)
  • βœ… REACT_APP_* prefixed variables
  • βœ… Runtime environment variables

VITE Environment Variables

  • βœ… .env files (all variants)
  • βœ… VITE_* prefixed variables
  • βœ… Mixed REACT_APP_* and VITE_* support in same project
  • βœ… Runtime environment variables

Angular Environment Variables

  • βœ… src/environments/environment.ts
  • βœ… src/environments/environment.prod.ts
  • βœ… Automatic NG_* prefixed variables

Built-in Configurations

Development (default)

  • Permissive CSP with 'unsafe-inline'
  • No nonce required
  • Environment variable resolution

Production (NODE_ENV=production)

  • Stricter CSP policies
  • Nonce support enabled
  • Enforced (blocking) mode

πŸ”§ API Usage

import { CSPInjector } from 'arc-spa-csp';

// Simple injection with auto-detection
const result = CSPInjector.inject();

// With custom options
const result = CSPInjector.inject({
  htmlPath: 'dist/index.html',
  configPath: 'custom-csp.json',
  devMode: false,
});

// With custom config and environment variables
const result = CSPInjector.inject({
  config: {
    directives: {
      'default-src': ["'self'"],
      'script-src': ["'self'", "'unsafe-inline'"],
    },
    useNonce: true,
  },
  envVars: {
    REACT_APP_API_URL: 'https://api.example.com',
    VITE_API_URL: 'https://api.example.com',
  },
});

console.log(`CSP injected into ${result.htmlPath}`);
console.log(`Nonce: ${result.nonce}`);

πŸ› οΈ Build Integration

npm scripts

{
  "scripts": {
    "build": "vite build",
    "build:csp": "npm run build && arc-spa-csp",
    "dev:csp": "arc-spa-csp --dev",
    "csp:init": "arc-spa-csp init --interactive",
    "csp:preview": "arc-spa-csp --dry-run"
  }
}

CI/CD

- name: Build and inject CSP
  run: |
    npm run build
    arc-spa-csp

πŸ§ͺ Examples

Getting Started

# 1. Initialize configuration with interactive wizard (recommended)
arc-spa-csp init --interactive

# 2. Follow the guided setup for your framework
# 3. Test your configuration
arc-spa-csp --dry-run

# 4. Apply CSP to your project
arc-spa-csp --dev  # for development
arc-spa-csp        # for production builds

Why use the interactive wizard?

  • βœ… Framework-Specific: Optimized configurations for React, VITE, Angular
  • βœ… Best Practices: Built-in security recommendations
  • βœ… Environment Ready: Auto-configures variable templates
  • βœ… No Guesswork: Guided setup with explanations

React with Create React App

# During development
npm start  # serves from public/
arc-spa-csp --dev  # injects CSP into public/index.html

# For production
npm run build  # creates build/
arc-spa-csp  # injects CSP into build/index.html

VITE Projects

# During development
npm run dev  # serves from root/index.html
arc-spa-csp --dev  # injects CSP into index.html

# For production
npm run build  # creates dist/
arc-spa-csp  # injects CSP into dist/index.html

Angular with CLI

# During development
ng serve  # serves from src/
arc-spa-csp --dev  # injects CSP into src/index.html

# For production
ng build  # creates dist/my-app/
arc-spa-csp  # auto-detects and injects CSP

Environment-Driven Configuration

# React project with environment variables
echo "REACT_APP_API_URL=https://api.example.com" > .env.local
arc-spa-csp --config csp-template.json

# VITE project with environment variables
echo "VITE_API_URL=https://api.example.com" > .env.local
arc-spa-csp --config csp-template.json

# Angular project with environment files
NODE_ENV=production arc-spa-csp

πŸ”§ Troubleshooting

HTML File Not Found

If auto-detection fails, specify the path explicitly:

# For React
arc-spa-csp --html build/index.html

# For VITE
arc-spa-csp --html dist/index.html

# For Angular
arc-spa-csp --html dist/my-project/index.html

# For Angular workspace
arc-spa-csp --html projects/my-app/src/index.html

Environment Variables Not Working

  1. React: Ensure variables have REACT_APP_ prefix
  2. VITE: Ensure variables have VITE_ prefix
  3. Angular: Check that environment.ts files exist in src/environments/
  4. Templates: Verify {{VARIABLE_NAME}} syntax in config files

Supported Environments

  • Node.js: 16.x, 18.x, 20.x, 21.x
  • npm: 8.x+
  • Frameworks: React, Angular, VITE

Development Setup

git clone https://github.com/sourcefuse/arc-spa-csp.git
cd arc-spa-csp
npm install
npm run build
npm test

πŸ“ License

MIT Β© SourceFuse


🎯 About SPA (Single Page Applications)

SPA stands for Single Page Application - a web application that loads a single HTML document and dynamically updates content as the user interacts with the app, without requiring full page reloads. SPAs are commonly built with frameworks like React, Angular, Vue.js, and built with tools like VITE.

This package specializes in securing SPAs by injecting Content Security Policy (CSP) headers that prevent common web vulnerabilities like XSS attacks, ensuring your single-page applications meet enterprise security standards.

About

Production-ready CSP injector for React, Angular & VITE projects. Smart auto-detection, environment variables, workspace support. Enterprise-grade SPA security.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published