feat(api): 新增 API Key Web 管理后台(使用者/备注/限流/配额/有效期/启停/删除),管理接口与普通 Key 隔离

This commit is contained in:
sgp
2026-11-04 18:26:39 +08:00
parent a14670e65a
commit ca75da8589
5 changed files with 811 additions and 12 deletions
+11
View File
@@ -282,6 +282,17 @@ sudo systemctl restart drawlogo-api
### Key 管理
**Web 管理后台**(推荐):`https://drawlogo.zhuig.com/api-admin.html`
- 输入管理口令进入(口令 = 服务器 `config.json` 的 `adminToken`)
- 可视化签发 Key:填写**使用者**、**备注**、**每分钟限流**、**每日配额**、**有效期**
- 列表可查看今日用量、最近使用时间,支持**启用/禁用/编辑/删除**
- 明文 Key 只在签发时显示一次,页面提供一键复制
> 管理口令与普通 API Key 完全分离;普通 Key 无法访问管理接口。口令为空时后台接口整体关闭。
**命令行**(服务器 `/opt/drawlogo-api`):
```bash
cd /opt/drawlogo-api
node admin.js create --name "项目A" --rate 120 --quota 30000
+2 -1
View File
@@ -7,5 +7,6 @@
"defaultDailyQuota": 20000,
"maxLimit": 100,
"corsOrigin": "*",
"trustProxy": true
"trustProxy": true,
"adminToken": ""
}
+166 -11
View File
@@ -28,7 +28,9 @@ const DEFAULT_CONFIG = {
defaultDailyQuota: 20000,
maxLimit: 100,
corsOrigin: '*',
trustProxy: true
trustProxy: true,
// 管理后台口令;为空则管理接口关闭
adminToken: ''
};
function loadConfig() {
@@ -147,6 +149,9 @@ function authenticate(req) {
if (!rec) {
return { ok: false, status: 403, code: 'INVALID_KEY', message: 'API Key 无效或已禁用' };
}
if (rec.expiresAt && Date.parse(rec.expiresAt) < Date.now()) {
return { ok: false, status: 403, code: 'KEY_EXPIRED', message: 'API Key 已过期' };
}
const now = Date.now();
const day = today();
@@ -171,6 +176,142 @@ function authenticate(req) {
return { ok: true, key: rec, remaining: Math.max(0, rate - b.count), limit: rate };
}
/* ============================ 管理后台 ============================ */
function saveKeys(list) {
keyState.keys = list;
fs.mkdirSync(path.dirname(KEY_FILE), { recursive: true });
fs.writeFileSync(KEY_FILE, JSON.stringify(list, null, 2));
try { fs.chmodSync(KEY_FILE, 0o600); } catch (e) { /* Windows 忽略 */ }
try { keyState.mtime = fs.statSync(KEY_FILE).mtimeMs; } catch (e) { /* ignore */ }
}
function readJsonBody(req, limit) {
const max = limit || 8192;
return new Promise((resolve, reject) => {
let size = 0;
const chunks = [];
req.on('data', c => {
size += c.length;
if (size > max) {
reject(Object.assign(new Error('BODY_TOO_LARGE'), { code: 'BODY_TOO_LARGE' }));
req.destroy();
return;
}
chunks.push(c);
});
req.on('end', () => {
if (!chunks.length) return resolve({});
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }
catch (e) { reject(Object.assign(new Error('BAD_JSON'), { code: 'BAD_JSON' })); }
});
req.on('error', reject);
});
}
/** 对外返回的 Key 视图(绝不返回 hash) */
function publicKey(rec) {
const b = keyState.buckets.get(rec.id);
const now = Date.now();
return {
id: rec.id,
name: rec.name,
note: rec.note || '',
enabled: rec.enabled !== false,
ratePerMin: rec.ratePerMin,
dailyQuota: rec.dailyQuota,
createdAt: rec.createdAt,
lastUsedAt: rec.lastUsedAt || null,
expiresAt: rec.expiresAt || null,
todayCount: b && b.day === today() ? b.dayCount : 0,
minuteCount: b && (now - b.window < 60000) ? b.count : 0
};
}
async function handleAdmin(req, res, pathname) {
const method = req.method;
const m = pathname.match(/^\/api\/v1\/admin\/keys(?:\/([A-Za-z0-9_]+))?$/);
if (!m) return fail(res, 404, 'NOT_FOUND', '未知管理端点');
const id = m[1];
// 列表 + 概览
if (!id && method === 'GET') {
loadKeys(false);
const keys = keyState.keys.map(publicKey);
return ok(res, {
keys,
stats: {
total: keys.length,
enabled: keys.filter(k => k.enabled).length,
todayCalls: keys.reduce((a, b) => a + b.todayCount, 0)
}
});
}
// 新建 Key:明文只返回这一次
if (!id && method === 'POST') {
let body;
try { body = await readJsonBody(req); }
catch (e) { return fail(res, 400, e.code || 'BAD_REQUEST', '请求体格式错误'); }
const name = String(body.name || '').trim();
if (!name) return fail(res, 400, 'BAD_REQUEST', '请填写使用者名称');
loadKeys(false);
const raw = 'dl_' + crypto.randomBytes(20).toString('hex');
const rec = {
id: 'key_' + crypto.randomBytes(4).toString('hex'),
name,
note: String(body.note || '').trim(),
hash: sha256(raw),
enabled: true,
ratePerMin: Math.max(1, Number(body.ratePerMin) || CONFIG.defaultRatePerMin),
dailyQuota: Math.max(1, Number(body.dailyQuota) || CONFIG.defaultDailyQuota),
expiresAt: body.expiresAt || null,
createdAt: new Date().toISOString(),
lastUsedAt: null
};
const list = keyState.keys.slice();
list.push(rec);
saveKeys(list);
return ok(res, { record: publicKey(rec), key: raw });
}
if (id) {
loadKeys(false);
const rec = keyState.keys.find(k => k.id === id);
if (!rec) return fail(res, 404, 'NOT_FOUND', 'Key 不存在');
if (method === 'PATCH' || method === 'PUT') {
let body;
try { body = await readJsonBody(req); }
catch (e) { return fail(res, 400, e.code || 'BAD_REQUEST', '请求体格式错误'); }
if (body.name !== undefined) {
const n = String(body.name).trim();
if (!n) return fail(res, 400, 'BAD_REQUEST', '使用者名称不能为空');
rec.name = n;
}
if (body.note !== undefined) rec.note = String(body.note).trim();
if (body.ratePerMin !== undefined) rec.ratePerMin = Math.max(1, Number(body.ratePerMin) || rec.ratePerMin);
if (body.dailyQuota !== undefined) rec.dailyQuota = Math.max(1, Number(body.dailyQuota) || rec.dailyQuota);
if (body.enabled !== undefined) rec.enabled = !!body.enabled;
if (body.expiresAt !== undefined) rec.expiresAt = body.expiresAt || null;
saveKeys(keyState.keys.slice());
return ok(res, { record: publicKey(rec) });
}
if (method === 'DELETE') {
saveKeys(keyState.keys.filter(k => k.id !== id));
return ok(res, { deleted: id });
}
}
return fail(res, 405, 'METHOD_NOT_ALLOWED', '不支持的方法');
}
/* ============================ 检索 ============================ */
function parseLimit(v) {
@@ -321,8 +462,8 @@ function send(res, status, body, headers) {
const h = {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': CONFIG.corsOrigin,
'Access-Control-Allow-Headers': 'Content-Type, X-API-Key, Authorization',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, X-API-Key, Authorization, X-Admin-Token',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
'X-Content-Type-Options': 'nosniff',
...(headers || {})
};
@@ -341,8 +482,7 @@ function fail(res, status, code, message, extraHeaders) {
const PUBLIC_PATHS = new Set(['/api/v1/health', '/api/v1/stats', '/api/v1/sources']);
function handle(req, res) {
const t0 = Date.now();
async function handle(req, res) {
const u = new URL(req.url, 'http://localhost');
const pathname = decodeURIComponent(u.pathname);
const q = u.searchParams;
@@ -350,6 +490,22 @@ function handle(req, res) {
if (req.method === 'OPTIONS') {
return send(res, 204, '');
}
// 管理后台:独立口令,不走普通 API Key
if (pathname.indexOf('/api/v1/admin/') === 0) {
if (!CONFIG.adminToken) {
return fail(res, 503, 'ADMIN_DISABLED', '管理后台未启用(未配置 adminToken)');
}
const t = req.headers['x-admin-token'];
if (!t || !safeEqual(String(t), String(CONFIG.adminToken))) {
return fail(res, 401, 'ADMIN_UNAUTHORIZED', '管理口令错误');
}
if (['GET', 'POST', 'PATCH', 'PUT', 'DELETE'].indexOf(req.method) === -1) {
return fail(res, 405, 'METHOD_NOT_ALLOWED', '不支持的方法');
}
return handleAdmin(req, res, pathname);
}
if (req.method !== 'GET') {
return fail(res, 405, 'METHOD_NOT_ALLOWED', '仅支持 GET');
}
@@ -509,14 +665,13 @@ function main() {
const server = http.createServer((req, res) => {
const t0 = Date.now();
try {
handle(req, res);
} catch (e) {
handle(req, res).catch(e => {
console.error('[ERROR]', e);
if (!res.headersSent) fail(res, 500, 'INTERNAL', '服务内部错误');
}
const cost = Date.now() - t0;
if (cost > 300) console.warn(`[SLOW] ${req.method} ${req.url} ${cost}ms`);
}).then(() => {
const cost = Date.now() - t0;
if (cost > 300) console.warn(`[SLOW] ${req.method} ${req.url} ${cost}ms`);
});
});
server.listen(CONFIG.port, CONFIG.host, () => {