@cosmstack/blackshield
Version:
A developer-first security toolkit for React/Next.js applications
813 lines (614 loc) โข 20.1 kB
Markdown
# @cosmstack/blackshield
> A developer-first security toolkit for React/Next.js applications. Prevent common security vulnerabilities with minimal setup and intuitive APIs.
[](https://badge.fury.io/js/@cosmstack%2Fblackshield)
[](https://opensource.org/licenses/MIT)
## ๐ก๏ธ What is Blackshield?
Blackshield is a comprehensive security toolkit designed specifically for React and Next.js applications. It provides multiple layers of protection against common web vulnerabilities while maintaining excellent developer experience.
### Key Features
- **๐ Environment Variable Protection** - Detect and prevent sensitive data exposure through `NEXT_PUBLIC_*` variables
- **๐ก๏ธ CSRF Protection** - Complete Cross-Site Request Forgery protection with automatic token management
- **๐ซ XSS Protection** - Safe HTML rendering with automatic sanitization
- **๐ Route Guards** - Declarative authentication and authorization for pages and components
- **โก Server Security** - Protect API routes and server actions with middleware
- **๐ง Static Analysis** - ESLint rules to catch security issues during development
- **๐ CLI Tools** - Command-line security analysis and project scanning
- **๐๏ธ Build Integration** - Next.js and Vite plugins for build-time security checks
## ๐ Quick Start
### Installation
```bash
npm install @cosmstack/blackshield zod
```
### Initialize Configuration
```bash
npx @cosmstack/blackshield init
```
This creates `.blackshieldrc.json` and example ESLint configuration.
### Basic Setup
```tsx
// app/layout.tsx
import { SecureProvider } from '@cosmstack/blackshield'
export default function RootLayout({ children }) {
return (
<html>
<body>
<SecureProvider config={{ dev: true }}>
{children}
</SecureProvider>
</body>
</html>
)
}
```
### Run Security Analysis
```bash
npx @cosmstack/blackshield check
npx @cosmstack/blackshield scan-env
```
## ๐ Core Concepts
### Security Layers
Blackshield provides protection at multiple levels:
1. **Development Time** - ESLint rules catch issues as you code
2. **Build Time** - Plugins validate security during builds
3. **Runtime** - Components and hooks provide active protection
### Zero-Config Security
Most features work out of the box with sensible defaults, but everything is customizable for your specific needs.
## ๐ก๏ธ Security Checks Overview
Blackshield provides comprehensive protection against common web vulnerabilities through multiple detection and prevention mechanisms:
| Security Check | Type | When It Runs | What It Protects Against |
|---|---|---|---|
| **Environment Variable Leak Detection** | Static Analysis + CLI | Build/Dev/Manual | Sensitive data exposed via `NEXT_PUBLIC_*` variables |
| **CSRF Protection** | Runtime + Middleware | Request Time | Cross-site request forgery attacks |
| **XSS Protection** | Runtime + Static | Render Time + Dev | Malicious script injection via HTML content |
| **Route Guards** | Runtime | Navigation | Unauthorized access to protected pages |
| **Server Security** | Middleware | Request Time | Unprotected API routes and server actions |
| **Input Validation** | Runtime | Request Time | Invalid or malicious data processing |
### ๐ Environment Variable Protection
**Protects Against:**
- API keys, secrets, and tokens exposed to client-side code
- Database URLs and credentials accessible in browser
- Private configuration leaked through `NEXT_PUBLIC_*` variables
**Detection Methods:**
- โ
CLI command: `npx @cosmstack/blackshield scan-env`
- โ
ESLint rule: `@cosmstack/blackshield/no-public-sensitive-env`
- โ
Build-time validation via Next.js/Vite plugins
- โ
Manual audit: `envAudit()` function
**When to Use:** Always run during development and CI/CD pipelines.
### ๐ก๏ธ CSRF Protection
**Protects Against:**
- Unauthorized actions performed on behalf of authenticated users
- State-changing operations without proper verification
- Cross-site request attacks targeting your API endpoints
**Implementation:**
- โ
Client hook: `useCsrfProtection()` with automatic token injection
- โ
Server middleware: `csrfMiddleware()` and `protect()` with `csrf: true`
- โ
Manual token management: `generateCsrfToken()`, `validateCsrfToken()`
**When to Use:** For all state-changing operations (POST, PUT, DELETE) in authenticated applications.
### ๐ซ XSS Protection
**Protects Against:**
- Cross-Site Scripting attacks through malicious HTML injection
- Execution of untrusted JavaScript code
- Data theft and session hijacking via script injection
**Implementation:**
- โ
Safe component: `<SafeHTML>` for rendering user content
- โ
Manual sanitization: `sanitizeHTML()` function
- โ
React hook: `useSanitizedHTML()` for dynamic content
- โ
ESLint rule: `@cosmstack/blackshield/no-unsafe-html` detects `dangerouslySetInnerHTML`
**When to Use:** Whenever rendering user-generated content, markdown, or HTML from external sources.
### ๐ Server Security
**Protects Against:**
- Unprotected API routes accessible without authentication
- Missing authorization checks for sensitive operations
- Rate limiting bypass and DoS attacks
- Invalid input processing leading to security vulnerabilities
**Implementation:**
- โ
Middleware: `protect()` for API routes with auth, roles, rate limiting
- โ
Server actions: `protectServerAction()` for form submissions
- โ
Input validation: Zod schema validation with `schemaValidation` option
- โ
Rate limiting: Built-in rate limiting with configurable windows
**When to Use:** For all API endpoints and server actions that handle sensitive data or operations.
## ๐ง Features & Usage
### ๐ Environment Variable Protection
Prevent accidental exposure of sensitive data through `NEXT_PUBLIC_*` variables.
#### What it protects against:
- API keys, secrets, and tokens exposed to client-side code
- Database URLs and credentials in browser
- Private configuration leaked through environment variables
#### Usage:
```bash
# Scan your project for sensitive variables
npx @cosmstack/blackshield scan-env
```
```typescript
// Manual validation
import { envAudit } from '@cosmstack/blackshield'
const result = await envAudit({
allowedPublicVars: ['NEXT_PUBLIC_APP_URL']
})
if (!result.isValid) {
console.error('Sensitive variables found:', result.sensitiveVars)
}
```
#### Configuration:
```json
// .blackshieldrc.json
{
"envValidation": {
"allowedPublicVars": [
"NEXT_PUBLIC_APP_URL",
"NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY"
]
}
}
```
### ๐ก๏ธ CSRF Protection
Complete Cross-Site Request Forgery protection with JWT-based tokens.
#### What it protects against:
- Unauthorized actions performed on behalf of authenticated users
- State-changing operations without proper verification
- Cross-site request attacks
#### Client-side Usage:
```tsx
import { useCsrfProtection } from '@cosmstack/blackshield'
function MyComponent() {
const { protectedFetch, token, isLoading } = useCsrfProtection()
const handleSubmit = async (data) => {
// CSRF token automatically injected
const response = await protectedFetch('/api/sensitive-action', {
method: 'POST',
credentials: 'include',
body: JSON.stringify(data)
})
}
return <form onSubmit={handleSubmit}>...</form>
}
```
#### Server-side Usage:
```typescript
import { protect } from '@cosmstack/blackshield/server'
// Protect API route with CSRF validation
export default protect(async (req, { user }) => {
// Handler logic here
return Response.json({ success: true })
}, {
requireAuth: true,
csrf: true
})
```
### ๐ซ XSS Protection
Safe HTML rendering with automatic sanitization.
#### What it protects against:
- Cross-Site Scripting attacks through malicious HTML injection
- Execution of untrusted JavaScript code
- Data theft and session hijacking
#### Usage:
```tsx
import { SafeHTML, sanitizeHTML } from '@cosmstack/blackshield'
// Safe component rendering
function BlogPost({ content }) {
return (
<article>
<SafeHTML
html={content}
allowedTags={['p', 'strong', 'em', 'ul', 'ol', 'li']}
/>
</article>
)
}
// Manual sanitization
const result = sanitizeHTML(userInput, {
allowedTags: ['p', 'strong'],
allowedAttributes: ['class']
})
console.log(result.sanitized) // Clean HTML
console.log(result.removedTags) // ['script', 'iframe']
```
### ๐ Authentication & Route Guards
Declarative authentication and authorization for your application.
#### User Management:
```tsx
import { useSecureUser } from '@cosmstack/blackshield'
function Dashboard() {
const {
user,
isAuthenticated,
login,
logout,
hasRole,
hasPermission
} = useSecureUser()
if (!isAuthenticated) {
return <LoginForm onLogin={login} />
}
return (
<div>
<h1>Welcome, {user.email}</h1>
{hasRole('admin') && <AdminPanel />}
{hasPermission('write') && <CreateButton />}
</div>
)
}
```
#### Route Protection:
```tsx
import { useGuardedRoute } from '@cosmstack/blackshield'
function AdminPage() {
const { isAuthorized, isLoading } = useGuardedRoute({
requiredRoles: ['admin'],
redirectTo: '/unauthorized'
})
if (isLoading) return <Loading />
if (!isAuthorized) return null // Automatic redirect
return <AdminDashboard />
}
```
### โก Server Security
Comprehensive protection for API routes and server actions.
#### API Route Protection:
```typescript
import { protect } from '@cosmstack/blackshield/server'
import { z } from 'zod'
const createPostSchema = z.object({
title: z.string().min(1).max(200),
content: z.string().min(1),
tags: z.array(z.string()).max(5)
})
export const POST = protect(async (req, { user, validatedInput }) => {
const post = await createPost({
...validatedInput,
authorId: user.id
})
return Response.json({ post })
}, {
requireAuth: true,
roles: ['user'],
csrf: true,
rateLimit: {
max: 10, // 10 requests per minute
windowSeconds: 60
},
schemaValidation: createPostSchema
})
```
#### Server Action Protection:
```typescript
import { protectServerAction } from '@cosmstack/blackshield/server'
export const updateProfile = protectServerAction(async (data) => {
return await updateUserProfile(data)
}, {
requireAuth: true,
schemaValidation: profileSchema
})
```
### ๐ง Static Analysis
ESLint rules to catch security issues during development.
#### Setup:
```json
// .eslintrc.json
{
"extends": ["next/core-web-vitals"],
"plugins": ["@cosmstack/blackshield/eslint-plugin"],
"rules": {
"@cosmstack/blackshield/no-public-sensitive-env": "error",
"@cosmstack/blackshield/no-unsafe-html": "error"
}
}
```
#### What it catches:
```javascript
// โ Will trigger error
const apiKey = process.env.NEXT_PUBLIC_API_SECRET
<div dangerouslySetInnerHTML={{ __html: userContent }} />
// โ
Safe alternatives
const apiKey = process.env.API_SECRET // Server-side only
<SafeHTML html={userContent} />
```
### ๐๏ธ Build Integration
Catch security issues during your build process.
#### Next.js Plugin:
```javascript
// next.config.js
import { withBlackshield } from '@cosmstack/blackshield/build/next'
const nextConfig = {
// Your Next.js config
}
export default withBlackshield(nextConfig, {
failOnEnvErrors: true,
config: {
envValidation: {
allowedPublicVars: ['NEXT_PUBLIC_APP_URL']
}
}
})
```
#### Vite Plugin:
```javascript
// vite.config.js
import { blackshieldVite } from '@cosmstack/blackshield/build/vite'
export default defineConfig({
plugins: [
blackshieldVite({
failOnEnvErrors: process.env.NODE_ENV === 'production'
})
]
})
```
## ๐ CLI Commands
### Project Analysis
```bash
# Comprehensive security analysis
npx @cosmstack/blackshield check
# Analyze specific directory
npx @cosmstack/blackshield check --path ./src
# Output as JSON
npx @cosmstack/blackshield check --format json
# Use custom config
npx @cosmstack/blackshield check --config ./custom-config.json
```
### Environment Scanning
```bash
# Scan for sensitive environment variables
npx @cosmstack/blackshield scan-env
# Scan specific directory
npx @cosmstack/blackshield scan-env --path ./
```
### Configuration
```bash
# Initialize configuration files
npx @cosmstack/blackshield init
# Force overwrite existing config
npx @cosmstack/blackshield init --force
```
## โ๏ธ Configuration
### Main Configuration File
```json
// .blackshieldrc.json
{
"envValidation": {
"allowedPublicVars": [
"NEXT_PUBLIC_APP_URL",
"NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY"
]
},
"xssProtection": {
"autoSanitize": true,
"allowedTags": ["p", "strong", "em", "ul", "ol", "li"],
"allowedAttributes": ["class", "id"]
},
"csrfProtection": {
"enabled": true,
"tokenHeader": "x-csrf-token",
"tokenCookie": "csrf-token",
"tokenExpiry": 3600
},
"boundaryProtection": {
"validateServerProps": true
}
}
```
### Environment Setup
```bash
# Required for CSRF protection
JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters
# Optional: Alternative secret for NextAuth.js compatibility
NEXTAUTH_SECRET=your-nextauth-secret
```
โ ๏ธ **Security Warnings:**
- **JWT_SECRET**: Must be at least 32 characters long and cryptographically secure
- **Never commit secrets**: Add `.env*` to your `.gitignore` file
- **Rotate secrets regularly**: Change JWT secrets periodically in production
- **Use different secrets**: Never reuse the same secret across environments
**Example .env.local template:**
```bash
# Security Configuration
JWT_SECRET=your-super-secret-jwt-key-minimum-32-characters-long
NEXTAUTH_SECRET=your-nextauth-secret-for-compatibility
# Database (Server-side only - NO NEXT_PUBLIC_ prefix)
DATABASE_URL=postgresql://user:password@localhost:5432/myapp
REDIS_URL=redis://localhost:6379
# API Keys (Server-side only - NO NEXT_PUBLIC_ prefix)
STRIPE_SECRET_KEY=sk_test_...
SENDGRID_API_KEY=SG...
# Safe Public Variables (Explicitly allowed)
NEXT_PUBLIC_APP_URL=http://localhost:3000
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
NEXT_PUBLIC_GOOGLE_ANALYTICS_ID=G-...
```
## ๐ฆ Package Structure
### Client-side Imports
```typescript
import {
// Core providers and hooks
SecureProvider,
useBlackshield,
useSecureUser,
useGuardedRoute,
// CSRF protection
useCsrfProtection,
getCsrfToken,
// XSS protection
SafeHTML,
sanitizeHTML,
useSanitizedHTML,
// Environment validation
validateEnvironmentVariables,
envAudit,
scanEnvFiles,
// Configuration
DEFAULT_CONFIG
} from '@cosmstack/blackshield'
```
### Server-side Imports
```typescript
import {
// Input validation
validateServerInput,
commonSchemas,
// Secure cookies
createSignedCookie,
readSecureCookie,
deleteSecureCookie,
// CSRF protection
generateCsrfToken,
verifyCsrfToken,
setCsrfTokenCookie,
validateCsrfToken,
csrfMiddleware,
// Middleware protection
protect,
protectServerAction
} from '@cosmstack/blackshield/server'
```
### Build Plugins
```typescript
// Next.js
import { withBlackshield } from '@cosmstack/blackshield/build/next'
// Vite
import { blackshieldVite } from '@cosmstack/blackshield/build/vite'
```
### ESLint Plugin
```json
{
"plugins": ["@cosmstack/blackshield/eslint-plugin"]
}
```
## ๐ TypeScript Support
Full TypeScript support with comprehensive type definitions:
```typescript
import type {
// Core types
BlackshieldConfig,
SecureUser,
AuthContext,
// Route protection
RouteGuardConfig,
// Server types
ServerInputValidation,
ProtectOptions,
// Environment types
EnvValidationResult,
EnvAuditResult,
// CSRF types
CsrfToken,
CsrfConfig,
// XSS types
XSSProtectionResult,
// Analysis types
SecurityIssue,
AnalysisResult
} from '@cosmstack/blackshield'
```
## ๐ก๏ธ Security Best Practices
### Environment Variables
```bash
# โ Dangerous - exposes secrets to client
NEXT_PUBLIC_API_SECRET=secret123
NEXT_PUBLIC_DATABASE_URL=postgres://...
# โ
Safe - server-side only
API_SECRET=secret123
DATABASE_URL=postgres://...
# โ
Safe - explicitly allowed public variables
NEXT_PUBLIC_APP_URL=https://myapp.com
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
```
### Content Rendering
```tsx
// โ Dangerous - can execute malicious scripts
<div dangerouslySetInnerHTML={{ __html: userContent }} />
// โ
Safe - automatically sanitized
<SafeHTML html={userContent} />
// โ
Safe - manual sanitization with control
const { sanitized } = sanitizeHTML(userContent, {
allowedTags: ['p', 'strong', 'em']
})
```
### API Protection
```typescript
// โ Unprotected API route
export async function POST(req: Request) {
const data = await req.json()
return Response.json(await createPost(data))
}
// โ
Protected with authentication, validation, and rate limiting
export const POST = protect(async (req, { user, validatedInput }) => {
return Response.json(await createPost({
...validatedInput,
authorId: user.id
}))
}, {
requireAuth: true,
schemaValidation: postSchema,
rateLimit: { max: 10, windowSeconds: 60 }
})
```
## ๐บ๏ธ Roadmap
### โ
v0.1.0 - Current Release (MVP)
**Core Security Features:**
- โ
Environment Variable Leak Detection with CLI scanning
- โ
CSRF Protection with JWT-based tokens
- โ
XSS Protection with safe HTML rendering
- โ
Route Guards for authentication and authorization
- โ
Server Security middleware for API routes and server actions
- โ
Input Validation with Zod schema support
- โ
Rate Limiting with configurable windows
- โ
ESLint Rules for static analysis
- โ
CLI Tools for project analysis
- โ
Build Integration for Next.js and Vite
**Developer Experience:**
- โ
Zero-config setup with sensible defaults
- โ
Full TypeScript support
- โ
Comprehensive documentation
- โ
Test coverage for all core features
### ๐ง v0.2.0 - Planned Features
**Enhanced Security:**
- ๐ Content Security Policy (CSP) management
- ๐ SQL Injection detection for database queries
- ๐ File upload security validation
- ๐ Session management improvements
**Developer Tools:**
- ๐ Security dashboard for issue visualization
- ๐ VS Code extension for real-time security hints
- ๐ GitHub Actions integration
- ๐ Automated security reports
**Integrations:**
- ๐ Auth.js/NextAuth.js connector
- ๐ Clerk authentication integration
- ๐ Firebase Auth support
- ๐ Supabase Auth integration
### ๐ฎ Future Vision
- ๐ฎ AI-powered security analysis
- ๐ฎ Real-time threat detection
- ๐ฎ Security compliance reporting (SOC 2, GDPR)
- ๐ฎ Multi-framework support (Remix, SvelteKit)
## ๐งช Test Coverage
Blackshield maintains comprehensive test coverage for all security features:
```bash
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run specific test suites
npm run test:env-audit
npm run test:csrf
npm run test:xss
npm run test:middleware
```
**Current Coverage:**
- โ
Environment audit and scanning
- โ
CSRF token generation and validation
- โ
XSS protection and sanitization
- โ
Route guards and authentication
- โ
Server middleware protection
- โ
ESLint rules validation
- โ
CLI commands functionality
All tests include both unit tests and integration scenarios to ensure reliability in production environments.
## ๐ค Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
## ๐ License
MIT ยฉ [CosmStack](https://github.com/cosmstack)
## ๐ Links
- [GitHub Repository](https://github.com/cosmstack/blackshield)
- [npm Package](https://www.npmjs.com/package/@cosmstack/blackshield)
- [Documentation](https://github.com/cosmstack/blackshield#readme)
- [Issues](https://github.com/cosmstack/blackshield/issues)
---
**Built with โค๏ธ by the CosmStack team**