Best practices for preventing data leaks
Data Encryption and Transmission Security
When handling sensitive data on the frontend, it is essential to ensure the security of data during transmission and storage. HTTPS is a basic requirement, but relying solely on transport-layer encryption is far from sufficient. Critical data should undergo secondary encryption on the frontend. Common implementation methods include:
- Using the Web Crypto API for client-side encryption
async function encryptData(data, secretKey) {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const keyBuffer = encoder.encode(secretKey);
const cryptoKey = await crypto.subtle.importKey(
'raw',
keyBuffer,
{ name: 'AES-GCM' },
false,
['encrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
cryptoKey,
dataBuffer
);
return { iv, encrypted };
}
- Implementing real-time encryption for sensitive form fields
document.querySelector('#credit-card').addEventListener('input', (e) => {
const encrypted = window.btoa(e.target.value);
e.target.dataset.encryptedValue = encrypted;
e.target.value = ''; // Clear plaintext display
});
Input Validation and Sanitization
Untrusted user input is a major source of data leaks. Strict validation strategies must be implemented:
- Implementing a whitelist validation mechanism
function sanitizeInput(input) {
const allowedChars = /^[a-zA-Z0-9\-_@. ]+$/;
if (!allowedChars.test(input)) {
return input.replace(/[^a-zA-Z0-9\-_@. ]/g, '');
}
return input;
}
- Using dedicated validators for different data types
const emailValidator = (email) =>
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) &&
!/<script|javascript:/i.test(email);
const phoneValidator = (phone) =>
/^[\d\-\+ ]+$/.test(phone) &&
phone.replace(/\D/g, '').length >= 10;
Secure Storage Strategies
Special attention is required when storing sensitive data on the browser side:
- Differentiating storage levels based on importance
// Sensitive data should use sessionStorage with automatic clearing
const storeSessionData = (key, value) => {
const encrypted = CryptoJS.AES.encrypt(value, 'secret').toString();
sessionStorage.setItem(key, encrypted);
window.addEventListener('beforeunload', () => sessionStorage.removeItem(key));
};
- Example of secure cookie settings
document.cookie = `auth_token=${token};
Secure;
HttpOnly;
SameSite=Strict;
Path=/;
Max-Age=${60 * 30}`; // Expires in 30 minutes
XSS Attack Prevention Measures
Cross-site scripting (XSS) attacks are a common pathway for data leaks:
- Safe rendering of dynamic content
function safeRender(content) {
const div = document.createElement('div');
div.textContent = content;
return div.innerHTML
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
- Example of CSP policy implementation
<meta http-equiv="Content-Security-Policy"
content="default-src 'self';
script-src 'self' 'unsafe-inline' cdn.example.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data:;
connect-src 'self' api.example.com;">
Security Management of Third-Party Dependencies
Third-party libraries in frontend projects can become security vulnerabilities:
- Automated dependency checks
// Example package.json configuration
{
"scripts": {
"security-check": "npx audit-ci --moderate",
"dep-check": "npx npm-check-updates -u"
}
}
- Security validation for dynamically loaded resources
function loadExternalScript(url, integrity) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = url;
script.integrity = integrity;
script.crossOrigin = 'anonymous';
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// Usage example
loadExternalScript(
'https://cdn.example.com/library.js',
'sha384-abc123...'
);
Error Handling and Logging
Improper error handling may expose sensitive information:
- Secure error message handling
window.onerror = (msg, url, line) => {
const safeMsg = msg.toString()
.replace(/password=['"][^'"]*['"]/g, 'password=***')
.replace(/token=['"][^'"]*['"]/g, 'token=***');
console.error(`Safe Error: ${safeMsg} at ${url}:${line}`);
return true; // Prevent default error handling
};
- Error log filtering in production environments
function logError(error) {
if (process.env.NODE_ENV === 'production') {
const sanitized = {
message: error.message.replace(/[^\w\s]/g, ''),
stack: error.stack ? error.stack.split('\n')[0] : ''
};
sendToMonitoring(sanitized);
} else {
console.error(error);
}
}
Two-Factor Authentication for Sensitive Operations
Critical operations require additional layers of protection:
- Confirmation process for important actions
function confirmCriticalAction(action) {
const modal = document.createElement('div');
modal.innerHTML = `
<div class="confirm-dialog">
<p>Please verify your identity to proceed</p>
<input type="password" placeholder="Account password">
<button id="confirm">Confirm</button>
<button id="cancel">Cancel</button>
</div>
`;
return new Promise((resolve) => {
modal.querySelector('#confirm').addEventListener('click', () => {
if (validatePassword(modal.querySelector('input').value)) {
action();
resolve(true);
}
});
modal.querySelector('#cancel').addEventListener('click', () => resolve(false));
document.body.appendChild(modal);
});
}
Real-Time Monitoring and Alert Mechanisms
Establishing a frontend security monitoring system:
- Abnormal behavior detection
const activityMonitor = {
normalPatterns: [
/^click:button#submit$/,
/^input:form#login/
],
checkActivity(event) {
const eventId = `${event.type}:${event.target.tagName.toLowerCase()}#${event.target.id}`;
if (!this.normalPatterns.some(p => p.test(eventId))) {
this.reportSuspicious(eventId);
}
},
reportSuspicious(event) {
navigator.sendBeacon('/security-log', JSON.stringify({
event,
timestamp: Date.now(),
userAgent: navigator.userAgent
}));
}
};
document.addEventListener('click', activityMonitor.checkActivity.bind(activityMonitor));
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn