feat: api_key 脱敏展示与还原

模型编辑弹窗(moe-key)显示为 sk-***1234 样式,不改则保存原值;
配置原文编辑器(GET /api/config)对 api_key 行逐行脱敏,
PUT/validate 时按出现顺序从原文件还原未改动的项,用户输入的新 key 原样生效。

- 前端 models.js: maskKey + moeOrigKey,保存时含 *** 视为未改动
- 后端 routes/config.js: maskApiKeys/restoreApiKeys,GET 脱敏,PUT/validate 还原
- PATCH 不变:模型弹窗已在前端还原真实 key 后再请求
This commit is contained in:
2026-09-02 20:12:47 +08:00
parent 8140fe2226
commit 29672f9d33
2 changed files with 71 additions and 7 deletions
+17 -2
View File
@@ -9,6 +9,15 @@ let cfgModels = []; // 配置里的模型数组(下标即 PATCH 下
let runtimeById = {}; // 运行池状态,按 id 关联
let modelsPendingRestart = false;
let moeIdx = -1; // 当前编辑弹窗对应的下标;-1 = 新增
let moeOrigKey = ''; // 打开编辑弹窗时的原始 api_key;未改动(显示仍含***)则保留原值
// api_key 脱敏显示:sk-***1234 样式。含 *** 作为「未改动」哨兵,保存时据此还原原 key。
function maskKey(k) {
k = k || '';
if (k.length > 8) return k.slice(0, 3) + '***' + k.slice(-4);
if (k.length > 0) return '***' + k.slice(-2);
return '';
}
// token 用量紧凑显示:1.2k / 9.1M 这种 human-friendly 量级,一眼看出多少。
// <1000 原样;1k~1M 用 k(1 位小数,去尾零);≥1M 用 M。0 显示为 0。
@@ -81,7 +90,10 @@ function openModelEditor(rawId) {
idIn.value = m.id || '';
idIn.disabled = !add; // 编辑时禁改 id(历史会话按 id 绑定)
$('moe-url').value = m.url || '';
$('moe-key').value = m.api_key || '';
moeOrigKey = m.api_key || '';
const keyIn = $('moe-key');
keyIn.value = maskKey(moeOrigKey);
keyIn.placeholder = add ? 'sk-...' : '不改则保留原 key(清空将保存为空)';
$('moe-vision').checked = !!m.vision;
$('moe-del-btn').classList.toggle('hidden', add);
$('model-edit-modal').classList.remove('hidden');
@@ -94,11 +106,14 @@ async function saveModelEditor() {
const url = $('moe-url').value.trim().replace(/\/+$/, '');
if (!id) return toast('请填写 id');
if (!url) return toast('请填写上游地址');
// 显示值含 *** = 未改动,还原原 key;否则按用户输入(支持改为新 key 或清空)
const keyVal = $('moe-key').value.trim();
const api_key = keyVal.includes('***') ? moeOrigKey : keyVal;
const obj = {
id,
display_name: $('moe-name').value.trim() || id,
url,
api_key: $('moe-key').value.trim(),
api_key,
vision: $('moe-vision').checked,
};
let body;
+54 -5
View File
@@ -1,6 +1,6 @@
// 配置读写 API(2.0 阶段 2):设置页管理 config.yml。
// 语义:写 = 校验 → 覆盖文件(无热重载);POST /api/system/restart 后生效。
// 注意:GET 返回的原文含密钥,接口与设置页同受 auth 中间件保护(自用场景)。
// 注意:GET 返回的原文已对 api_key 脱敏,避免明文外显;PUT/validate 时按顺序还原。
const express = require('express');
const engine = require('../engine');
const { loadConfigFromText, readConfigText, applyEditsToText, writeConfigText } = require('../config');
@@ -35,19 +35,65 @@ function diffTop(oldCfg, newCfg) {
function cfgOf() { return engine.getConfig(); }
// api_key 脱敏:与前端 models.js 的 maskKey 保持一致。
function maskKey(k) {
k = k || '';
if (k.length > 8) return k.slice(0, 3) + '***' + k.slice(-4);
if (k.length > 0) return '***' + k.slice(-2);
return '';
}
// 逐行掩码 config.yml 原文里的 api_key 值(设置页原文编辑器展示用)。
// 行格式如 ` api_key: sk-xxx` 或 ` api_key: "sk-xxx"`(双/单引号)。
// 记录每行是否掩码,便于 restore 时按顺序还原未改动项。
const API_KEY_LINE = /^(\s*api_key:\s*)(["']?)(.+?)\2\s*$/;
function maskApiKeys(text) {
if (!text) return text;
return text.split('\n').map(function (line) {
const m = line.match(API_KEY_LINE);
if (!m) return line;
return m[1] + m[2] + maskKey(m[3]) + m[2];
}).join('\n');
}
// 还原:提交原文中含 *** 的 api_key 行 = 用户未改动,按出现顺序从原文件取回原值。
// 不含 *** 的 = 用户手输的新 key,原样保留。
function restoreApiKeys(submitted, orig) {
if (!submitted) return submitted;
const origKeys = [];
(orig || '').split('\n').forEach(function (line) {
const m = line.match(API_KEY_LINE);
if (m) origKeys.push(m[3]);
});
let i = 0;
return submitted.split('\n').map(function (line) {
const m = line.match(API_KEY_LINE);
if (!m) return line;
if (!m[3].includes('***')) return line; // 用户改过,保留
const origKey = i < origKeys.length ? origKeys[i] : '';
i++;
return m[1] + m[2] + origKey + m[2];
}).join('\n');
}
// 配置原文 + 路径 + 当前生效配置(设置页表单显示当前值;注释原样保留)
// GET 返回的原文对 models[].api_key 脱敏(避免明文外显);PUT/validate 时按顺序还原。
router.get('/', wrap((req, res) => {
const cfg = cfgOf();
const text = readConfigText(cfg);
res.json({ config_path: cfg.config_path || '', exists: text !== null, text: text === null ? '' : text, effective: cfg });
const shown = text === null ? '' : maskApiKeys(text);
res.json({ config_path: cfg.config_path || '', exists: text !== null, text: shown, effective: cfg });
}));
// 干跑校验(编辑器保存前预检):body { text }
// 还原脱敏后的 api_key 再校验,避免 diff 误报 models 段变更。
router.post('/validate', wrap((req, res) => {
const text = req.body && req.body.text;
if (typeof text !== 'string') return badRequest(res, new Error('body.text 必须是字符串'));
const origText = readConfigText(cfgOf());
const restored = restoreApiKeys(text, origText || '');
try {
const next = loadConfigFromText(text, '');
const next = loadConfigFromText(restored, '');
res.json({ ok: true, changed: diffTop(cfgOf(), next) });
} catch (e) {
res.status(400).json({ ok: false, error: String(e && e.message || e) });
@@ -55,13 +101,16 @@ router.post('/validate', wrap((req, res) => {
}));
// 整文件编辑:body { text }
// 还原脱敏后的 api_key 再写入,未改动的项保持原值,用户输入的新 key 原样生效。
router.put('/', wrap((req, res) => {
const cfg = cfgOf();
const text = req.body && req.body.text;
if (typeof text !== 'string') return badRequest(res, new Error('body.text 必须是字符串'));
const origText = readConfigText(cfg);
const restored = restoreApiKeys(text, origText || '');
let next;
try { next = loadConfigFromText(text, cfg.config_path); } catch (e) { return badRequest(res, e); }
writeConfigText(cfg, text);
try { next = loadConfigFromText(restored, cfg.config_path); } catch (e) { return badRequest(res, e); }
writeConfigText(cfg, restored);
log.info('[config] ' + (req.user || '-') + ' 整文件保存配置,变更段:' + (diffTop(cfg, next).join(',') || '无'));
res.json({ ok: true, changed: diffTop(cfg, next), restart_required: true });
}));