From a32c73707306288fcd203ea85b7c9aff496a0003 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 10 Mar 2026 12:06:23 +0000 Subject: [PATCH] feat: upgrade Persona Studio login to support API Key auto-detect model mode - Add backend route POST /api/ps/apikey/detect-models for model auto-detection with 1-hour caching - Add backend route POST /api/ps/apikey/chat for proxying chat through user's own API credentials - Update login page with API Key login section (API Base URL + API Key + model detection + model list) - Update chat.js to support API Key mode with dynamic model usage (selected_model) - Update styles for API Key login UI (detect status, model list, etc.) - Add smoke tests for new endpoints and dev_id login backward compatibility - Security: API Key stored only in sessionStorage, never persisted on backend Co-authored-by: qinfendebingshuo <207279273+qinfendebingshuo@users.noreply.github.com> --- persona-studio/backend/routes/apikey.js | 265 ++++++++++++++++++++++++ persona-studio/backend/server.js | 4 + persona-studio/frontend/chat.js | 72 +++++-- persona-studio/frontend/index.html | 146 ++++++++++--- persona-studio/frontend/style.css | 108 +++++++++- tests/smoke/apikey-detect.test.js | 105 ++++++++++ 6 files changed, 661 insertions(+), 39 deletions(-) create mode 100644 persona-studio/backend/routes/apikey.js create mode 100644 tests/smoke/apikey-detect.test.js diff --git a/persona-studio/backend/routes/apikey.js b/persona-studio/backend/routes/apikey.js new file mode 100644 index 00000000..d37aa650 --- /dev/null +++ b/persona-studio/backend/routes/apikey.js @@ -0,0 +1,265 @@ +/** + * persona-studio · API Key 模型检测路由 + * POST /api/ps/apikey/detect-models 检测可用模型 + * POST /api/ps/apikey/chat 通过用户 API Key 对话 + */ +const express = require('express'); +const router = express.Router(); +const crypto = require('crypto'); +const https = require('https'); +const http = require('http'); + +/* ---- 模型列表缓存(1 小时有效期) ---- */ +const modelCache = new Map(); +const CACHE_TTL_MS = 60 * 60 * 1000; // 1 小时 + +function getCacheKey(apiBase, apiKey) { + const hash = crypto.createHash('sha256').update(apiKey).digest('hex').slice(0, 16); + return apiBase + '::' + hash; +} + +function getCachedModels(apiBase, apiKey) { + const key = getCacheKey(apiBase, apiKey); + const entry = modelCache.get(key); + if (entry && Date.now() - entry.timestamp < CACHE_TTL_MS) { + return entry.models; + } + return null; +} + +function setCachedModels(apiBase, apiKey, models) { + const key = getCacheKey(apiBase, apiKey); + modelCache.set(key, { models, timestamp: Date.now() }); +} + +/** + * 请求第三方 API 的 /v1/models 接口 + */ +function fetchModels(apiBase, apiKey, timeoutMs) { + return new Promise((resolve, reject) => { + // 规范化 apiBase:去除末尾斜杠 + const base = apiBase.replace(/\/+$/, ''); + // 支持 base 已带 /v1 或不带的情况 + const modelsPath = base.endsWith('/v1') ? base + '/models' : base + '/v1/models'; + const url = new URL(modelsPath); + const isHttps = url.protocol === 'https:'; + const mod = isHttps ? https : http; + + const options = { + hostname: url.hostname, + port: url.port || (isHttps ? 443 : 80), + path: url.pathname + (url.search || ''), + method: 'GET', + headers: { + 'Authorization': 'Bearer ' + apiKey, + 'Accept': 'application/json' + }, + timeout: timeoutMs || 15000 + }; + + const req = mod.request(options, (res) => { + let data = ''; + res.on('data', (chunk) => { data += chunk; }); + res.on('end', () => { + if (res.statusCode === 401 || res.statusCode === 403) { + return reject(new Error('API Key 无效')); + } + if (res.statusCode >= 400) { + return reject(new Error('API Base 不可访问 (HTTP ' + res.statusCode + ')')); + } + try { + const json = JSON.parse(data); + const models = json.data || json.models || []; + const modelIds = models + .map(function (m) { return m.id || m.name || null; }) + .filter(Boolean); + resolve(modelIds); + } catch (_e) { + reject(new Error('未检测到可用模型')); + } + }); + }); + + req.on('error', () => { + reject(new Error('API Base 不可访问')); + }); + + req.on('timeout', () => { + req.destroy(); + reject(new Error('API Base 不可访问(请求超时)')); + }); + + req.end(); + }); +} + +/** + * 调用用户 API 的 chat/completions 接口 + */ +function callUserApi({ apiBase, apiKey, model, messages, maxTokens, temperature, timeoutMs }) { + return new Promise((resolve, reject) => { + const base = apiBase.replace(/\/+$/, ''); + const chatPath = base.endsWith('/v1') ? base + '/chat/completions' : base + '/v1/chat/completions'; + const url = new URL(chatPath); + const isHttps = url.protocol === 'https:'; + const mod = isHttps ? https : http; + + const body = JSON.stringify({ + model: model, + messages: messages, + max_tokens: maxTokens || 2000, + temperature: temperature != null ? temperature : 0.8 + }); + + const options = { + hostname: url.hostname, + port: url.port || (isHttps ? 443 : 80), + path: url.pathname, + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer ' + apiKey, + 'Content-Length': Buffer.byteLength(body) + }, + timeout: timeoutMs || 60000 + }; + + const req = mod.request(options, (res) => { + let data = ''; + res.on('data', (chunk) => { data += chunk; }); + res.on('end', () => { + try { + const json = JSON.parse(data); + if (json.choices && json.choices[0] && json.choices[0].message) { + resolve(json.choices[0].message.content); + } else if (json.error) { + reject(new Error(json.error.message || 'API 调用失败')); + } else { + reject(new Error('API 返回格式异常')); + } + } catch (_e) { + reject(new Error('API 返回解析失败')); + } + }); + }); + + req.on('error', (err) => { + reject(new Error('API 请求失败: ' + err.message)); + }); + + req.on('timeout', () => { + req.destroy(); + reject(new Error('API 请求超时')); + }); + + req.write(body); + req.end(); + }); +} + +// POST /api/ps/apikey/detect-models +router.post('/detect-models', async (req, res) => { + const { api_base, api_key } = req.body || {}; + + if (!api_base || typeof api_base !== 'string') { + return res.status(400).json({ + error: true, + code: 'MISSING_API_BASE', + message: '请输入 API Base URL' + }); + } + + if (!api_key || typeof api_key !== 'string') { + return res.status(400).json({ + error: true, + code: 'MISSING_API_KEY', + message: '请输入 API Key' + }); + } + + // 检查缓存 + const cached = getCachedModels(api_base, api_key); + if (cached) { + return res.json({ + error: false, + models: cached, + count: cached.length, + cached: true + }); + } + + try { + const models = await fetchModels(api_base, api_key, 15000); + + if (!models || models.length === 0) { + return res.status(404).json({ + error: true, + code: 'NO_MODELS', + message: '未检测到可用模型' + }); + } + + // 写入缓存 + setCachedModels(api_base, api_key, models); + + res.json({ + error: false, + models: models, + count: models.length, + cached: false + }); + } catch (err) { + res.status(502).json({ + error: true, + code: 'DETECT_FAILED', + message: err.message || '模型检测失败' + }); + } +}); + +// POST /api/ps/apikey/chat +router.post('/chat', async (req, res) => { + const { api_base, api_key, model, messages } = req.body || {}; + + if (!api_base || !api_key || !model) { + return res.status(400).json({ + error: true, + code: 'MISSING_PARAMS', + message: '缺少必要参数 (api_base, api_key, model)' + }); + } + + if (!messages || !Array.isArray(messages) || messages.length === 0) { + return res.status(400).json({ + error: true, + code: 'MISSING_MESSAGES', + message: '缺少消息内容' + }); + } + + try { + const reply = await callUserApi({ + apiBase: api_base, + apiKey: api_key, + model: model, + messages: messages, + maxTokens: 2000, + temperature: 0.8, + timeoutMs: 60000 + }); + + res.json({ + error: false, + reply: reply, + model: model + }); + } catch (err) { + res.status(502).json({ + error: true, + code: 'CHAT_FAILED', + message: err.message || '对话请求失败' + }); + } +}); + +module.exports = router; diff --git a/persona-studio/backend/server.js b/persona-studio/backend/server.js index 8a997b4e..03186e7f 100644 --- a/persona-studio/backend/server.js +++ b/persona-studio/backend/server.js @@ -7,6 +7,7 @@ const authRoutes = require('./routes/auth'); const chatRoutes = require('./routes/chat'); const buildRoutes = require('./routes/build'); const notifyRoutes = require('./routes/notify'); +const apikeyRoutes = require('./routes/apikey'); const app = express(); app.use(cors()); @@ -20,6 +21,7 @@ app.use('/api/ps/auth', authRoutes); app.use('/api/ps/chat', chatRoutes); app.use('/api/ps/build', buildRoutes); app.use('/api/ps/notify', notifyRoutes); +app.use('/api/ps/apikey', apikeyRoutes); // ── 健康检查 ── app.get('/api/ps/health', (_req, res) => { @@ -43,6 +45,8 @@ app.get('/', (_req, res) => { '/api/ps/chat/history', '/api/ps/build/start', '/api/ps/notify/send', + '/api/ps/apikey/detect-models', + '/api/ps/apikey/chat', '/api/ps/health' ] }); diff --git a/persona-studio/frontend/chat.js b/persona-studio/frontend/chat.js index 4fcf88ef..dfa7d159 100644 --- a/persona-studio/frontend/chat.js +++ b/persona-studio/frontend/chat.js @@ -4,6 +4,10 @@ const DEV_ID = sessionStorage.getItem('dev_id'); const SESSION_TOKEN = sessionStorage.getItem('session_token'); +const LOGIN_MODE = sessionStorage.getItem('login_mode'); // 'apikey' or null +const USER_API_BASE = sessionStorage.getItem('user_api_base'); +const USER_API_KEY = sessionStorage.getItem('user_api_key'); +const SELECTED_MODEL = sessionStorage.getItem('selected_model'); const API_BASE = (function () { if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') { @@ -19,8 +23,25 @@ const API_BASE = (function () { return; } - document.getElementById('devIdDisplay').textContent = DEV_ID; - loadHistory(); + // API Key 模式额外校验 + if (LOGIN_MODE === 'apikey' && (!USER_API_BASE || !USER_API_KEY || !SELECTED_MODEL)) { + window.location.href = 'index.html'; + return; + } + + var displayId = DEV_ID; + if (LOGIN_MODE === 'apikey') { + displayId = SELECTED_MODEL; + } + document.getElementById('devIdDisplay').textContent = displayId; + + if (LOGIN_MODE === 'apikey') { + // API Key 模式:显示欢迎信息,不加载历史 + appendMessage('persona', '你好!当前使用模型:' + SELECTED_MODEL + '。有什么我可以帮你的?'); + conversationHistory.push({ role: 'assistant', content: '你好!当前使用模型:' + SELECTED_MODEL + '。有什么我可以帮你的?' }); + } else { + loadHistory(); + } })(); /* ---- State ---- */ @@ -84,17 +105,40 @@ async function sendMessage() { sendBtn.disabled = true; try { - var res = await fetch(API_BASE + '/api/ps/chat/message', { - method: 'POST', - headers: authHeaders({ 'Content-Type': 'application/json' }), - body: JSON.stringify({ - dev_id: DEV_ID, - message: text, - history: conversationHistory.slice(-20) - }) - }); + var data; - var data = await res.json(); + if (LOGIN_MODE === 'apikey') { + // API Key 模式:通过后端代理调用用户的 API + var apiMessages = conversationHistory.slice(-20).map(function (msg) { + return { role: msg.role === 'assistant' ? 'assistant' : 'user', content: msg.content }; + }); + + var res = await fetch(API_BASE + '/api/ps/apikey/chat', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + api_base: USER_API_BASE, + api_key: USER_API_KEY, + model: SELECTED_MODEL, + messages: apiMessages + }) + }); + + data = await res.json(); + } else { + // 开发编号模式:使用原有后端接口 + var res = await fetch(API_BASE + '/api/ps/chat/message', { + method: 'POST', + headers: authHeaders({ 'Content-Type': 'application/json' }), + body: JSON.stringify({ + dev_id: DEV_ID, + message: text, + history: conversationHistory.slice(-20) + }) + }); + + data = await res.json(); + } if (data.reply) { appendMessage('persona', data.reply); @@ -173,6 +217,10 @@ async function confirmBuild() { function handleLogout() { sessionStorage.removeItem('dev_id'); sessionStorage.removeItem('session_token'); + sessionStorage.removeItem('login_mode'); + sessionStorage.removeItem('user_api_base'); + sessionStorage.removeItem('user_api_key'); + sessionStorage.removeItem('selected_model'); window.location.href = 'index.html'; } diff --git a/persona-studio/frontend/index.html b/persona-studio/frontend/index.html index 230df193..211d9e7d 100644 --- a/persona-studio/frontend/index.html +++ b/persona-studio/frontend/index.html @@ -14,6 +14,7 @@
编号由冰朔主控分配,格式:EXP-000 ~ EXP-011
@@ -33,8 +34,36 @@ 或访客模式暂不可用,正式编号用户可正常登录
+ +输入你的第三方 API 信息,自动检测可用模型
+ + + + + + + + +