feat(api): Key 改为明文保存可随时复制,新增口令列与一键复制接入信息(地址+使用者+口令)

This commit is contained in:
sgp
2026-11-04 21:25:12 +08:00
parent f7f700d32a
commit d1f1a5db7a
4 changed files with 83 additions and 13 deletions
+3 -1
View File
@@ -287,7 +287,9 @@ sudo systemctl restart drawlogo-api
- 输入管理口令进入(口令 = 服务器 `config.json` 的 `adminToken`)
- 可视化签发 Key:填写**使用者**、**备注**、**每分钟限流**、**每日配额**、**有效期**
- 列表可查看今日用量、最近使用时间,支持**启用/禁用/编辑/删除**
- 明文 Key 只在签发时显示一次,页面提供一键复制
- **内部使用模式**:Key 明文保存在 `data/apikeys.json`(权限 600),后台可随时查看掩码、点「复制」一键复制 **地址 + 使用者 + 口令**,直接发给调用方
- 早期只存哈希的旧 Key 无法查看明文,重新生成一个即可(旧 Key 可删除)
- 若未来商业化,建议改回「仅存哈希 + 明文只显示一次」
> 管理口令与普通 API Key 完全分离;普通 Key 无法访问管理接口。口令为空时后台接口整体关闭。
+2
View File
@@ -73,6 +73,8 @@ function create() {
const rec = {
id: 'key_' + crypto.randomBytes(4).toString('hex'),
name,
// 内部使用:明文保存,便于后台查看/复制;hash 仅作兼容
key: raw,
hash: crypto.createHash('sha256').update(raw).digest('hex'),
enabled: true,
ratePerMin: Number(args.rate || CONFIG.defaultRatePerMin || 60),
+11 -2
View File
@@ -151,8 +151,14 @@ function authenticate(req) {
return { ok: false, status: 401, code: 'UNAUTHORIZED', message: '缺少 API Key(请求头 X-API-Key 或 Authorization: Bearer <key>)' };
}
loadKeys(false);
const hash = sha256(raw.trim());
const rec = keyState.keys.find(k => k.enabled !== false && k.hash && safeEqual(k.hash, hash));
const trimmed = raw.trim();
const hash = sha256(trimmed);
const rec = keyState.keys.find(k => {
if (k.enabled === false) return false;
// 新 Key 存明文,可直接比较;旧 Key 只有 hash,保持兼容
if (k.key) return safeEqual(k.key, trimmed);
return k.hash && safeEqual(k.hash, hash);
});
if (!rec) {
return { ok: false, status: 403, code: 'INVALID_KEY', message: 'API Key 无效或已禁用' };
}
@@ -224,6 +230,8 @@ function publicKey(rec) {
id: rec.id,
name: rec.name,
note: rec.note || '',
// 内部使用:明文保存,后台可随时查看/复制;旧 Key 无 key 字段
key: rec.key || '',
enabled: rec.enabled !== false,
ratePerMin: rec.ratePerMin,
dailyQuota: rec.dailyQuota,
@@ -271,6 +279,7 @@ async function handleAdmin(req, res, pathname) {
id: 'key_' + crypto.randomBytes(4).toString('hex'),
name,
note: String(body.note || '').trim(),
key: raw,
hash: sha256(raw),
enabled: true,
ratePerMin: Math.max(1, Number(body.ratePerMin) || CONFIG.defaultRatePerMin),