钉钉 AI 客服:安全加固完全指南
安全是 AI 客服的生命线。
一、安全威胁
| 威胁 | 风险 | 等级 |
|---|---|---|
| SQL 注入 | 数据泄露 | 高 |
| XSS 攻击 | 信息窃取 | 高 |
| API 滥用 | 服务中断 | 中 |
| 数据泄露 | 隐私问题 | 高 |
二、输入验证
2.1 SQL 注入防护
// ❌ 不安全的查询
const sql = `SELECT * FROM users WHERE id = ${id}`;
// ✅ 安全的查询
const sql = 'SELECT * FROM users WHERE id = ?';
await db.query(sql, [id]);
2.2 XSS 防护
const validator = require('validator');
function sanitize(input) {
return validator.escape(input);
}
// 使用
const safeMessage = sanitize(userMessage);
三、API 安全
3.1 速率限制
const rateLimit = require('express-rate-limit');
app.use('/api/', rateLimit({
windowMs: 60 * 1000,
max: 100,
message: '请求过于频繁'
}));
3.2 API Key 验证
app.use((req, res, next) => {
const key = req.headers['x-api-key'];
if (!key || !validateKey(key)) {
return res.status(401).json({ error: '无效 API Key' });
}
next();
});
四、数据加密
4.1 传输加密
// 强制 HTTPS
app.use((req, res, next) => {
if (!req.secure) {
return res.redirect(`https://${req.headers.host}${req.url}`);
}
next();
});
4.2 存储加密
const crypto = require('crypto');
function encrypt(text) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', SECRET_KEY, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
function decrypt(text) {
const [ivHex, encrypted] = text.split(':');
const iv = Buffer.from(ivHex, 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', SECRET_KEY, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
五、访问控制
5.1 RBAC 权限
const roles = {
admin: ['read', 'write', 'delete'],
editor: ['read', 'write'],
viewer: ['read']
};
function checkPermission(user, action) {
return roles[user.role].includes(action);
}
5.2 IP 白名单
const ALLOWED_IPS = ['192.168.1.0/24', '10.0.0.0/8'];
app.use((req, res, next) => {
const ip = req.ip;
if (!isAllowedIP(ip)) {
return res.status(403).json({ error: '访问被拒绝' });
}
next();
});
六、安全头
const helmet = require('helmet');
app.use(helmet());
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"]
}
}));
七、日志审计
function audit(action, user, details) {
console.log(JSON.stringify({
timestamp: new Date().toISOString(),
action,
user: user.id,
details
}));
}
// 使用
audit('DELETE_FAQ', req.user, { faqId: id });
八、安全检查清单
- 输入验证
- SQL 参数化
- XSS 过滤
- HTTPS 强制
- API 限流
- 权限控制
- 日志审计
- 定期安全扫描
项目地址:GitHub - dingtalk-connector-pro 有问题欢迎 Issue 或评论区交流