diff --git a/src/app.js b/src/app.js index 9fca57eb..2f6d09cb 100644 --- a/src/app.js +++ b/src/app.js @@ -141,40 +141,10 @@ class Application { if (buf && buf.length && !buf.toString(encoding || 'utf8').trim()) { throw new Error('Invalid JSON: empty body') } - // 注意:不在这里修改buffer,避免导致JSON解析错误 } }) ) this.app.use(express.urlencoded({ extended: true, limit: '10mb' })) - - // 🧹 JSON 解析错误处理中间件 - this.app.use((err, req, res, next) => { - if (err instanceof SyntaxError && err.status === 400 && 'body' in err) { - // JSON 解析错误统一处理 - logger.warn('🚨 JSON parsing error detected:', err.message) - - // 检查是否是常见的JSON解析错误 - if ( - err.message.includes('Unexpected end of JSON input') || - err.message.includes('Unexpected token') || - err.message.includes('Expected property name') || - err.message.includes('in JSON at position') || - err.message.includes('surrogate') || - err.message.includes('UTF-16') || - err.message.includes('invalid character') - ) { - return res.status(400).json({ - type: 'error', - error: { - type: 'invalid_request_error', - message: 'Invalid JSON format in request body. Please ensure the request contains valid JSON data.' - } - }) - } - } - next(err) - }) - this.app.use(securityMiddleware) // 🎯 信任代理 diff --git a/src/routes/api.js b/src/routes/api.js index 9f66bc6d..3b1c4160 100644 --- a/src/routes/api.js +++ b/src/routes/api.js @@ -12,52 +12,11 @@ const sessionHelper = require('../utils/sessionHelper') const router = express.Router() -// 🧹 Unicode 字符清理函数 -function cleanUnicodeString(str) { - if (typeof str !== 'string') { - return str - } - - // 移除无效的 UTF-16 代理对字符 - // 匹配无效的低代理字符 (0xDC00-0xDFFF) 没有对应的高代理字符 - // 匹配无效的高代理字符 (0xD800-0xDBFF) 没有对应的低代理字符 - return str.replace( - /[\uDC00-\uDFFF](?![\uD800-\uDBFF])|[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, - '\uFFFD' - ) -} - -// 🧹 递归清理对象中的 Unicode 字符 -function cleanUnicodeInObject(obj) { - if (typeof obj === 'string') { - return cleanUnicodeString(obj) - } - - if (Array.isArray(obj)) { - return obj.map((item) => cleanUnicodeInObject(item)) - } - - if (obj && typeof obj === 'object') { - const cleaned = {} - for (const [key, value] of Object.entries(obj)) { - cleaned[cleanUnicodeString(key)] = cleanUnicodeInObject(value) - } - return cleaned - } - - return obj -} - // 🔧 共享的消息处理函数 async function handleMessagesRequest(req, res) { try { const startTime = Date.now() - // Unicode 字符清理 - 在输入验证之前清理请求体 - if (req.body) { - req.body = cleanUnicodeInObject(req.body) - } - // 严格的输入验证 if (!req.body || typeof req.body !== 'object') { return res.status(400).json({