Considering data security
Basic Concepts of Data Security
Data security is crucial in ECharts applications, involving three core aspects: data transmission, storage, and presentation. Unprotected sensitive data may lead to information leaks and even legal risks. For example, when a healthcare platform uses ECharts to display patient age distribution, sending raw data containing ID numbers directly to the frontend violates the relevant provisions of the Personal Information Protection Law.
Data Transmission Security
HTTPS Encryption
All API requests containing chart data must be encrypted via HTTPS:
// Bad practice: Using unencrypted HTTP
fetch('http://api.example.com/chart-data')
// Correct approach: Enforce HTTPS
fetch('https://api.example.com/chart-data', {
headers: {
'Authorization': `Bearer ${token}`
}
})
Data Desensitization
Sensitive fields should be desensitized before the server returns data:
interface PatientData {
id: number;
name: string; // Needs desensitization
diagnosis: string;
}
// Desensitization function example
function desensitize(data: PatientData[]): PatientData[] {
return data.map(item => ({
...item,
name: item.name.charAt(0) + '**'
}));
}
Frontend Data Storage Security
Avoid Storing Sensitive Data Locally
A common mistake is storing authentication information in localStorage:
// High-risk practice
localStorage.setItem('auth_token', 'eyJhbGci...');
// Recommended solution
sessionStorage.setItem('temp_chart_config', JSON.stringify(config));
Web Worker for Confidential Computations
For sensitive data requiring frontend calculations, use Web Workers to isolate the execution environment:
// worker.js
self.onmessage = function(e) {
const sensitiveData = decrypt(e.data.payload);
const chartOption = processData(sensitiveData);
postMessage(chartOption);
}
// Main thread
const worker = new Worker('worker.js');
worker.postMessage({ payload: encryptedData });
ECharts Configuration Security Practices
Disable Unnecessary Features
Deactivate potentially risky features in system configurations:
option = {
toolbox: {
show: false // Disable toolbox features that may export data
},
tooltip: {
formatter: (params) => {
// Filter sensitive information
return `${params.seriesName}: ${params.value.replace(/\d{4}$/, '****')}`
}
}
}
Dynamic Permission Control
Generate chart configurations dynamically based on user roles:
function generateChartOptions(userRole) {
const baseOption = {
xAxis: { type: 'category' },
series: [{ type: 'bar' }]
};
if (userRole === 'admin') {
baseOption.toolbox = {
show: true,
feature: {
dataView: { readOnly: false },
saveAsImage: {}
}
};
}
return baseOption;
}
Third-Party Dependency Security
Regularly Update ECharts Versions
Keep dependencies up-to-date with secure versions:
# Check for known vulnerabilities
npm audit
# Update to a secure version
npm update echarts@5.4.3
Content Security Policy (CSP) Configuration
Strictly restrict resource loading in HTTP headers:
Content-Security-Policy:
default-src 'self';
script-src 'self' 'unsafe-eval' cdn.jsdelivr.net;
style-src 'self' 'unsafe-inline';
img-src data:;
Data Rendering Protection Measures
XSS Prevention
Escape dynamically generated HTML content:
function safeTooltipFormatter(params) {
const div = document.createElement('div');
div.textContent = params.name;
return `${div.innerHTML}: ${params.value}`;
}
Large-Number Handling
Process large datasets that may cause memory leaks:
option = {
dataset: {
source: largeData.map(item => ({
...item,
// Precision control to prevent floating-point attacks
value: Number(item.value.toFixed(4))
}))
},
progressive: 1e6, // Enable progressive rendering
progressiveThreshold: 1e6
}
Audit and Monitoring Mechanisms
User Behavior Logging
Record critical operation events:
chart.on('click', (params) => {
if (params.componentType === 'series') {
logAnalytics({
event: 'chart_click',
data: {
// Record non-sensitive metadata
seriesIndex: params.seriesIndex,
dataIndex: params.dataIndex
}
});
}
});
Performance Monitoring
Detect performance issues caused by abnormal data volumes:
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
if (entries.some(entry => entry.duration > 1000)) {
alert('Chart rendering timeout');
}
});
observer.observe({ entryTypes: ['measure'] });
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn