fix: 移除Unicode清理逻辑,恢复与main分支一致的转发流程

- 移除app.js中的JSON解析错误处理中间件
- 移除api.js中的cleanUnicodeString和cleanUnicodeInObject函数
- 移除handleMessagesRequest中的Unicode清理调用
- 确保转发逻辑与main远程分支完全一致

问题原因:
- Unicode清理逻辑会修改请求体,可能导致某些情况下的JSON解析错误
- Claude API本身能够处理Unicode问题,不需要在中转服务中预处理

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
shaw
2025-08-21 09:29:27 +08:00
parent 39a72e3e72
commit bd10032857
2 changed files with 0 additions and 71 deletions

View File

@@ -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)
// 🎯 信任代理

View File

@@ -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({