fix: address code review - const/let scoping, header injection guard, error messages

- Use const/let instead of var for block-scoped variables in frontend
- Add header injection validation for API Key (reject newline chars)
- Include original error message in fetchModels error callback
- Use more reliable hostname for unreachable API base test

Co-authored-by: qinfendebingshuo <207279273+qinfendebingshuo@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot] 2026-03-10 12:08:37 +00:00
parent a32c737073
commit 62ec0fcfae
4 changed files with 38 additions and 22 deletions

View File

@ -80,8 +80,8 @@ function fetchModels(apiBase, apiKey, timeoutMs) {
}); });
}); });
req.on('error', () => { req.on('error', (err) => {
reject(new Error('API Base 不可访问')); reject(new Error('API Base 不可访问: ' + err.message));
}); });
req.on('timeout', () => { req.on('timeout', () => {
@ -177,7 +177,14 @@ router.post('/detect-models', async (req, res) => {
}); });
} }
// 检查缓存 // 防止 header injectionAPI Key 不得包含换行符
if (/[\r\n]/.test(api_key)) {
return res.status(400).json({
error: true,
code: 'INVALID_API_KEY',
message: 'API Key 格式无效'
});
}
const cached = getCachedModels(api_base, api_key); const cached = getCachedModels(api_base, api_key);
if (cached) { if (cached) {
return res.json({ return res.json({
@ -229,6 +236,15 @@ router.post('/chat', async (req, res) => {
}); });
} }
// 防止 header injection
if (/[\r\n]/.test(api_key)) {
return res.status(400).json({
error: true,
code: 'INVALID_API_KEY',
message: 'API Key 格式无效'
});
}
if (!messages || !Array.isArray(messages) || messages.length === 0) { if (!messages || !Array.isArray(messages) || messages.length === 0) {
return res.status(400).json({ return res.status(400).json({
error: true, error: true,

View File

@ -105,15 +105,15 @@ async function sendMessage() {
sendBtn.disabled = true; sendBtn.disabled = true;
try { try {
var data; let data;
if (LOGIN_MODE === 'apikey') { if (LOGIN_MODE === 'apikey') {
// API Key 模式:通过后端代理调用用户的 API // API Key 模式:通过后端代理调用用户的 API
var apiMessages = conversationHistory.slice(-20).map(function (msg) { const apiMessages = conversationHistory.slice(-20).map(function (msg) {
return { role: msg.role === 'assistant' ? 'assistant' : 'user', content: msg.content }; return { role: msg.role === 'assistant' ? 'assistant' : 'user', content: msg.content };
}); });
var res = await fetch(API_BASE + '/api/ps/apikey/chat', { const res = await fetch(API_BASE + '/api/ps/apikey/chat', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
@ -127,7 +127,7 @@ async function sendMessage() {
data = await res.json(); data = await res.json();
} else { } else {
// 开发编号模式:使用原有后端接口 // 开发编号模式:使用原有后端接口
var res = await fetch(API_BASE + '/api/ps/chat/message', { const res = await fetch(API_BASE + '/api/ps/chat/message', {
method: 'POST', method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }), headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ body: JSON.stringify({

View File

@ -87,9 +87,9 @@
/* ---- 开发编号登录 ---- */ /* ---- 开发编号登录 ---- */
async function handleLogin(e) { async function handleLogin(e) {
e.preventDefault(); e.preventDefault();
var devId = document.getElementById('devIdInput').value.trim().toUpperCase(); const devId = document.getElementById('devIdInput').value.trim().toUpperCase();
var errorEl = document.getElementById('errorMsg'); const errorEl = document.getElementById('errorMsg');
var btn = document.getElementById('loginBtn'); const btn = document.getElementById('loginBtn');
errorEl.style.display = 'none'; errorEl.style.display = 'none';
@ -103,13 +103,13 @@
btn.textContent = '验证中…'; btn.textContent = '验证中…';
try { try {
var res = await fetch(API_BASE + '/api/ps/auth/login', { const res = await fetch(API_BASE + '/api/ps/auth/login', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ dev_id: devId }) body: JSON.stringify({ dev_id: devId })
}); });
var data = await res.json(); const data = await res.json();
if (!res.ok || data.error) { if (!res.ok || data.error) {
errorEl.textContent = data.message || '登录失败,请检查编号'; errorEl.textContent = data.message || '登录失败,请检查编号';
@ -138,12 +138,12 @@
/* ---- API Key 模型检测 ---- */ /* ---- API Key 模型检测 ---- */
async function handleDetectModels() { async function handleDetectModels() {
var apiBase = document.getElementById('apiBaseInput').value.trim(); const apiBase = document.getElementById('apiBaseInput').value.trim();
var apiKey = document.getElementById('apiKeyInput').value.trim(); const apiKey = document.getElementById('apiKeyInput').value.trim();
var errorEl = document.getElementById('errorMsg'); const errorEl = document.getElementById('errorMsg');
var statusEl = document.getElementById('detectStatus'); const statusEl = document.getElementById('detectStatus');
var modelContainer = document.getElementById('modelListContainer'); const modelContainer = document.getElementById('modelListContainer');
var btn = document.getElementById('detectBtn'); const btn = document.getElementById('detectBtn');
errorEl.style.display = 'none'; errorEl.style.display = 'none';
modelContainer.style.display = 'none'; modelContainer.style.display = 'none';
@ -167,13 +167,13 @@
statusEl.style.display = 'block'; statusEl.style.display = 'block';
try { try {
var res = await fetch(API_BASE + '/api/ps/apikey/detect-models', { const res = await fetch(API_BASE + '/api/ps/apikey/detect-models', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ api_base: apiBase, api_key: apiKey }) body: JSON.stringify({ api_base: apiBase, api_key: apiKey })
}); });
var data = await res.json(); const data = await res.json();
if (!res.ok || data.error) { if (!res.ok || data.error) {
statusEl.textContent = data.message || '未检测到模型,请检查 API Key'; statusEl.textContent = data.message || '未检测到模型,请检查 API Key';
@ -183,7 +183,7 @@
return; return;
} }
var models = data.models || []; const models = data.models || [];
if (models.length === 0) { if (models.length === 0) {
statusEl.textContent = '未检测到可用模型'; statusEl.textContent = '未检测到可用模型';
statusEl.className = 'detect-status detect-error'; statusEl.className = 'detect-status detect-error';

View File

@ -59,7 +59,7 @@ describe('POST /api/ps/apikey/detect-models', () => {
test('returns error for unreachable API base', async () => { test('returns error for unreachable API base', async () => {
const res = await post('/api/ps/apikey/detect-models', { const res = await post('/api/ps/apikey/detect-models', {
api_base: 'http://127.0.0.1:19999', api_base: 'http://invalid.test.local',
api_key: 'sk-test-invalid' api_key: 'sk-test-invalid'
}); });
expect(res.status).toBe(502); expect(res.status).toBe(502);