Recommended security learning path
Fundamental Concepts of Frontend Security
The core of frontend security lies in understanding common threat models in the browser environment. The Same-Origin Policy (SOP) is the most basic security mechanism, which restricts documents or scripts from one origin from reading or modifying documents from another origin. Modern web applications often need to relax this restriction, which introduces the Cross-Origin Resource Sharing (CORS) mechanism:
// Server-side CORS header example
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://trusted-site.com');
res.header('Access-Control-Allow-Methods', 'GET,POST');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
Content Security Policy (CSP) is another critical defense layer, controlling resource loading through a whitelist mechanism:
<!-- CSP policy example -->
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self' https://apis.google.com;
img-src 'self' data:;
style-src 'self' 'unsafe-inline'">
Common Attack Types and Defenses
XSS Attack Protection
Cross-Site Scripting (XSS) attacks are divided into three categories:
- Stored XSS: Malicious scripts are permanently stored on the target server.
- Reflected XSS: Malicious scripts come from the current HTTP request.
- DOM-based XSS: The vulnerability exists in client-side code.
Defensive measures include input and output encoding:
// HTML entity encoding function
function encodeHTML(str) {
return str.replace(/[&<>'"]/g,
tag => ({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag]));
}
Modern frameworks like React/Vue have built-in XSS protection, but special cases like dangerouslySetInnerHTML
require attention.
CSRF Protection
Defense measures against Cross-Site Request Forgery (CSRF) include:
- SameSite cookies (SameSite attribute)
- CSRF tokens
- Double-submit cookies
// CSRF token middleware example in Express
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });
app.get('/form', csrfProtection, (req, res) => {
res.render('send', { csrfToken: req.csrfToken() });
});
app.post('/process', csrfProtection, (req, res) => {
// Processing logic
});
Modern Frontend Security Practices
Frontend Dependency Security
Use npm audit
to regularly check for dependency vulnerabilities:
npm audit
npm audit fix
Consider using Snyk or Dependabot for automated dependency updates.
Security Headers Configuration
Key HTTP security headers include:
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY
- Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
Nginx configuration example:
add_header X-Frame-Options "DENY";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "strict-origin-when-cross-origin";
Client-Side Data Security
Principles for handling sensitive data:
- Avoid storing tokens in
localStorage
- Use HttpOnly and Secure cookies
- Consider using the Web Crypto API for client-side encryption
// Web Crypto API example - generating SHA-256 hash
async function hashMessage(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
Advanced Security Topics
Web Workers Security
Security considerations for dedicated Worker communication:
// Main thread
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
if (e.origin !== expectedOrigin) return;
// Process message
};
// Worker thread
self.addEventListener('message', (e) => {
// Verify message source
if (!isValidSource(e.source)) return;
// Processing logic
});
WASM Security Considerations
Security boundaries for WebAssembly modules:
// Memory limits when instantiating WASM
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100,
shared: false
});
// Strict import object
const importObject = {
env: {
memory,
abort: () => {}
}
};
Third-Party Script Management
Secure patterns for loading third-party resources:
<!-- Use integrity attribute to ensure resource integrity -->
<script src="https://example.com/library.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script>
<!-- Sandboxed iframe -->
<iframe src="https://third-party.com"
sandbox="allow-scripts allow-same-origin"
allow="geolocation 'src'"></iframe>
Security Toolchain
Static Analysis Tools
- ESLint security rules:
{
"extends": ["plugin:security/recommended"],
"rules": {
"security/detect-object-injection": "error",
"security/detect-eval-with-expression": "error"
}
}
- Use Snyk CLI to detect vulnerabilities:
snyk test
snyk monitor
Dynamic Analysis Tools
OWASP ZAP basic scanning process:
- Set up proxy
- Crawl website
- Active scan
- Analyze report
Browser developer tools security-related features:
- Application panel for storage inspection
- Network panel for security headers
- Security panel for certificates and mixed content
Secure Coding Standards
Input Validation Patterns
// Strict whitelist validation
function validateInput(input) {
const pattern = /^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z]{2,6}$/;
if (!pattern.test(input)) {
throw new Error('Invalid input format');
}
return input;
}
// Strong type checking
function processData(data) {
if (typeof data !== 'object' || data === null) {
throw new TypeError('Expected object');
}
// ...
}
Security Design Patterns
- Principle of least privilege implementation:
// API permission encapsulation
const createRestrictedAPI = (user) => {
return {
getData: user.canRead ? API.getData : () => Promise.reject('Forbidden'),
updateData: user.canWrite ? API.updateData : () => Promise.reject('Forbidden')
};
};
- Immutable data pattern:
// Using Object.freeze
const config = Object.freeze({
apiUrl: 'https://api.example.com',
maxRetries: 3
});
// Using immer for safe updates
import produce from 'immer';
const nextState = produce(currentState, draft => {
draft.user.permissions.push('new-permission');
});
Continuous Security Practices
Security Code Review Checklist
Frontend code reviews should check:
- Whether all dynamic content is properly encoded
- Whether all API calls have error handling
- Whether unsafe functions (eval, innerHTML, etc.) are used
- Whether sensitive operations have secondary verification
- Whether third-party resources are controlled
Threat Modeling Example
Threat model for an e-commerce payment process:
- Attack surface:
- Payment form DOM manipulation
- Payment API calls
- Payment result page
- Potential threats:
- Form hijacking
- API parameter tampering
- Payment result spoofing
- Control measures:
- Form input monitoring
- Request signing
- Server-side payment result validation
Security Test Automation
Jest security test example:
describe('Security Tests', () => {
test('XSS protection test', () => {
const input = '<script>alert(1)</script>';
const output = sanitize(input);
expect(output).not.toContain('<script>');
});
test('CSRF token validation', async () => {
const res = await request(app)
.post('/transfer')
.send({ amount: 100 });
expect(res.status).toBe(403);
});
});
Browser Security Feature Evolution
Trusted Types API
New specification to prevent DOM XSS:
// Policy definition
if (window.trustedTypes && trustedTypes.createPolicy) {
const escapePolicy = trustedTypes.createPolicy('escapePolicy', {
createHTML: str => str.replace(/</g, '<').replace(/>/g, '>')
});
}
// Usage
document.getElementById('output').innerHTML =
escapePolicy.createHTML(userInput);
COOP/COEP Isolation
Cross-Origin Isolation configuration:
Cross-Origin-Embedder-Policy: require-corp
Cross-Origin-Opener-Policy: same-origin
WebAuthn Integration
Biometric authentication implementation example:
navigator.credentials.create({
publicKey: {
challenge: new Uint8Array(32),
rp: { name: "Example Site" },
user: {
id: new Uint8Array(16),
name: "user@example.com",
displayName: "User"
},
pubKeyCredParams: [{ type: "public-key", alg: -7 }],
timeout: 60000,
attestation: "direct"
}
}).then(credential => {
// Handle credential
});
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn