Some checks failed
🚀 Build & Deploy Image / Determine Build Necessity (push) Failing after 10m14s
🚀 Build & Deploy Image / Build Runtime Base Image (push) Has been skipped
🚀 Build & Deploy Image / Build Docker Image (push) Has been skipped
🚀 Build & Deploy Image / Run Tests & Quality Checks (push) Has been skipped
🚀 Build & Deploy Image / Auto-deploy to Staging (push) Has been skipped
🚀 Build & Deploy Image / Auto-deploy to Production (push) Has been skipped
Security Vulnerability Scan / Check for Dependency Changes (push) Failing after 11m25s
Security Vulnerability Scan / Composer Security Audit (push) Has been cancelled
- Remove middleware reference from Gitea Traefik labels (caused routing issues) - Optimize Gitea connection pool settings (MAX_IDLE_CONNS=30, authentication_timeout=180s) - Add explicit service reference in Traefik labels - Fix intermittent 504 timeouts by improving PostgreSQL connection handling Fixes Gitea unreachability via git.michaelschiemer.de
383 lines
7.2 KiB
Markdown
383 lines
7.2 KiB
Markdown
# Security Module
|
|
|
|
**Security Utilities: CSRF, XSS Protection, and CSP Helpers**
|
|
|
|
The Security Module provides comprehensive security utilities for client-side security management.
|
|
|
|
---
|
|
|
|
## Features
|
|
|
|
- **CSRF Token Management** - Automatic token refresh and management
|
|
- **XSS Protection** - HTML sanitization and input validation
|
|
- **Content Security Policy** - CSP validation and helpers
|
|
- **Security Headers Validation** - Client-side security header checks
|
|
|
|
---
|
|
|
|
## Quick Start
|
|
|
|
### Basic Usage
|
|
|
|
```javascript
|
|
import { SecurityManager } from './modules/security/index.js';
|
|
|
|
// Create security manager
|
|
const security = SecurityManager.create({
|
|
csrf: {
|
|
autoRefresh: true,
|
|
refreshInterval: 30 * 60 * 1000 // 30 minutes
|
|
},
|
|
xss: {
|
|
enabled: true,
|
|
sanitizeOnInput: false
|
|
}
|
|
});
|
|
|
|
// Get CSRF token
|
|
const token = security.getCsrfToken();
|
|
|
|
// Use in fetch request
|
|
const response = await fetch('/api/endpoint', {
|
|
method: 'POST',
|
|
headers: {
|
|
...security.getCsrfTokenHeader(),
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(data)
|
|
});
|
|
```
|
|
|
|
### Module System Integration
|
|
|
|
```html
|
|
<!-- Enable global security manager -->
|
|
<script type="module">
|
|
import { init } from './modules/security/index.js';
|
|
|
|
init({
|
|
csrf: {
|
|
autoRefresh: true
|
|
}
|
|
});
|
|
</script>
|
|
|
|
<!-- Access globally -->
|
|
<script>
|
|
// Get CSRF token
|
|
const token = window.SecurityManager.getCsrfToken();
|
|
|
|
// Refresh token
|
|
await window.SecurityManager.refreshCsrfToken();
|
|
</script>
|
|
```
|
|
|
|
---
|
|
|
|
## API Reference
|
|
|
|
### SecurityManager.create(config)
|
|
|
|
Create a new SecurityManager instance.
|
|
|
|
**Parameters**:
|
|
- `config.csrf` - CSRF manager configuration
|
|
- `config.xss` - XSS protection configuration
|
|
- `config.csp` - CSP configuration
|
|
|
|
**Example**:
|
|
```javascript
|
|
const security = SecurityManager.create({
|
|
csrf: {
|
|
tokenName: '_token',
|
|
headerName: 'X-CSRF-TOKEN',
|
|
autoRefresh: true,
|
|
refreshInterval: 30 * 60 * 1000
|
|
},
|
|
xss: {
|
|
enabled: true,
|
|
sanitizeOnInput: false
|
|
}
|
|
});
|
|
```
|
|
|
|
### security.getCsrfToken()
|
|
|
|
Get current CSRF token.
|
|
|
|
**Returns**: `string | null`
|
|
|
|
### security.getCsrfTokenHeader()
|
|
|
|
Get CSRF token header object for use in fetch requests.
|
|
|
|
**Returns**: `Record<string, string>`
|
|
|
|
**Example**:
|
|
```javascript
|
|
const headers = {
|
|
...security.getCsrfTokenHeader(),
|
|
'Content-Type': 'application/json'
|
|
};
|
|
```
|
|
|
|
### security.refreshCsrfToken()
|
|
|
|
Manually refresh CSRF token.
|
|
|
|
**Returns**: `Promise<void>`
|
|
|
|
### security.escapeHtml(text)
|
|
|
|
Escape HTML to prevent XSS.
|
|
|
|
**Parameters**:
|
|
- `text` - Text to escape
|
|
|
|
**Returns**: `string`
|
|
|
|
**Example**:
|
|
```javascript
|
|
const safe = security.escapeHtml('<script>alert("xss")</script>');
|
|
// Returns: <script>alert("xss")</script>
|
|
```
|
|
|
|
### security.validateUrl(url)
|
|
|
|
Validate URL to prevent XSS.
|
|
|
|
**Parameters**:
|
|
- `url` - URL to validate
|
|
|
|
**Returns**: `boolean`
|
|
|
|
**Example**:
|
|
```javascript
|
|
if (security.validateUrl(userInput)) {
|
|
// Safe to use
|
|
} else {
|
|
// Potentially dangerous
|
|
}
|
|
```
|
|
|
|
### security.validateSecurityHeaders()
|
|
|
|
Validate security headers.
|
|
|
|
**Returns**: `SecurityHeadersValidation`
|
|
|
|
**Example**:
|
|
```javascript
|
|
const validation = security.validateSecurityHeaders();
|
|
if (!validation.valid) {
|
|
console.warn('Security issues:', validation.issues);
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## CSRF Token Management
|
|
|
|
### Automatic Token Refresh
|
|
|
|
```javascript
|
|
const security = SecurityManager.create({
|
|
csrf: {
|
|
autoRefresh: true,
|
|
refreshInterval: 30 * 60 * 1000 // Refresh every 30 minutes
|
|
}
|
|
});
|
|
```
|
|
|
|
### Manual Token Refresh
|
|
|
|
```javascript
|
|
await security.refreshCsrfToken();
|
|
```
|
|
|
|
### Using Token in Requests
|
|
|
|
```javascript
|
|
// Get token header
|
|
const headers = security.getCsrfTokenHeader();
|
|
|
|
// Use in fetch
|
|
const response = await fetch('/api/endpoint', {
|
|
method: 'POST',
|
|
headers: {
|
|
...headers,
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(data)
|
|
});
|
|
```
|
|
|
|
---
|
|
|
|
## XSS Protection
|
|
|
|
### HTML Sanitization
|
|
|
|
```javascript
|
|
const security = SecurityManager.create({
|
|
xss: {
|
|
enabled: true,
|
|
sanitizeOnInput: true // Auto-sanitize on input
|
|
}
|
|
});
|
|
|
|
// Manual sanitization
|
|
const safe = security.sanitizeHtml(userInput);
|
|
```
|
|
|
|
### HTML Escaping
|
|
|
|
```javascript
|
|
const escaped = security.escapeHtml('<script>alert("xss")</script>');
|
|
```
|
|
|
|
### URL Validation
|
|
|
|
```javascript
|
|
if (security.validateUrl(userInput)) {
|
|
// Safe URL
|
|
window.location.href = userInput;
|
|
} else {
|
|
// Potentially dangerous
|
|
console.error('Invalid URL');
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Content Security Policy
|
|
|
|
### CSP Validation
|
|
|
|
```javascript
|
|
const security = SecurityManager.create({
|
|
csp: {
|
|
enabled: true
|
|
}
|
|
});
|
|
|
|
// CSP is automatically validated on init
|
|
// Check validation results
|
|
const validation = security.validateSecurityHeaders();
|
|
```
|
|
|
|
---
|
|
|
|
## Integration with LiveComponents
|
|
|
|
```javascript
|
|
import { SecurityManager } from './modules/security/index.js';
|
|
import { LiveComponentManager } from './modules/livecomponent/index.js';
|
|
|
|
const security = SecurityManager.create();
|
|
|
|
// LiveComponents automatically use CSRF tokens
|
|
// But you can also manually update tokens
|
|
security.csrfManager.updateAllTokens();
|
|
```
|
|
|
|
---
|
|
|
|
## Integration with Forms
|
|
|
|
```javascript
|
|
import { SecurityManager } from './modules/security/index.js';
|
|
|
|
const security = SecurityManager.create();
|
|
|
|
// Forms automatically get updated CSRF tokens
|
|
// Listen for token refresh events
|
|
window.addEventListener('csrf:token-refreshed', (event) => {
|
|
console.log('CSRF token refreshed:', event.detail.token);
|
|
});
|
|
```
|
|
|
|
---
|
|
|
|
## Use Cases
|
|
|
|
### API Requests with CSRF
|
|
|
|
```javascript
|
|
const security = SecurityManager.create();
|
|
|
|
async function apiCall(url, data) {
|
|
const response = await fetch(url, {
|
|
method: 'POST',
|
|
headers: {
|
|
...security.getCsrfTokenHeader(),
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify(data)
|
|
});
|
|
|
|
return response.json();
|
|
}
|
|
```
|
|
|
|
### User Input Sanitization
|
|
|
|
```javascript
|
|
const security = SecurityManager.create();
|
|
|
|
function handleUserInput(input) {
|
|
// Sanitize HTML
|
|
const sanitized = security.sanitizeHtml(input);
|
|
|
|
// Escape for display
|
|
const escaped = security.escapeHtml(input);
|
|
|
|
// Validate URL
|
|
if (security.validateUrl(input)) {
|
|
// Safe to use as URL
|
|
}
|
|
}
|
|
```
|
|
|
|
### Security Headers Check
|
|
|
|
```javascript
|
|
const security = SecurityManager.create();
|
|
|
|
// Validate security headers
|
|
const validation = security.validateSecurityHeaders();
|
|
if (!validation.valid) {
|
|
console.warn('Security issues detected:', validation.issues);
|
|
// Report to backend or show warning
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Best Practices
|
|
|
|
1. **Always Use CSRF Tokens** - Include CSRF tokens in all state-changing requests
|
|
2. **Sanitize User Input** - Sanitize HTML before displaying user content
|
|
3. **Validate URLs** - Always validate URLs before using them
|
|
4. **Enable Auto-Refresh** - Keep CSRF tokens fresh with auto-refresh
|
|
5. **Check Security Headers** - Validate security headers in development
|
|
|
|
---
|
|
|
|
## Browser Support
|
|
|
|
- **Chrome/Edge**: 90+
|
|
- **Firefox**: 88+
|
|
- **Safari**: 14+
|
|
- **Mobile**: iOS 14+, Android Chrome 90+
|
|
|
|
**Required Features**:
|
|
- ES2020 JavaScript
|
|
- Fetch API
|
|
- CustomEvent support
|
|
|
|
---
|
|
|
|
**Next**: [Cache Manager Module](cache-manager.md) →
|
|
|