Files
drawlogo/api/server.js
T
sgp 884ea332a2 feat(api): 新增免鉴权在线接口说明 /api/v1/docs,并让错误响应自带文档入口
- GET /api/v1/docs:返回 README 的调用方章节(text/markdown + gzip,mtime 缓存,截断运维/架构章节)
- 401/403/404/429 等所有错误体新增 error.docs,新接入方首次调用即可自助查阅
- /health、/stats 新增 docs 字段
- README 补充入口说明与在线版调用示例
2026-11-08 18:02:23 +08:00

1116 lines
42 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* 画个标 · 素材 API 服务
*
* 纯 Node 原生实现(零第三方依赖),对外提供素材检索 / SVG 直链 / 技能元数据。
* 设计:
* - 索引常驻内存,素材正文按字节偏移 seek 读取(不整体加载大源文件)
* - API Key 鉴权(X-API-Key / Authorization: Bearer),Key 以 SHA-256 存储
* - 每 Key 分钟级限流 + 每日配额
* - 公网部署时由 nginx 反代,服务本身只监听 127.0.0.1
*
* 启动:node server.js
*/
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const ROOT = __dirname;
const DEFAULT_CONFIG = {
port: 7891,
host: '127.0.0.1',
dataDir: './data',
keyFile: './data/apikeys.json',
defaultRatePerMin: 60,
defaultDailyQuota: 20000,
maxLimit: 100,
corsOrigin: '*',
trustProxy: true,
// 管理后台口令;为空则管理接口关闭
adminToken: '',
// 站点登录(nginx auth_request 子请求校验);为空则登录功能关闭
auth: {
username: '',
passwordHash: '',
secret: '',
maxAgeDays: 7
}
};
function loadConfig() {
const file = path.join(ROOT, 'config.json');
if (!fs.existsSync(file)) return { ...DEFAULT_CONFIG };
return { ...DEFAULT_CONFIG, ...JSON.parse(fs.readFileSync(file, 'utf8')) };
}
const CONFIG = loadConfig();
const DATA_DIR = path.resolve(ROOT, CONFIG.dataDir);
const KEY_FILE = path.resolve(ROOT, CONFIG.keyFile);
/* ============================ 索引加载 ============================ */
const store = {
catalog: null,
icons: [],
posters: [],
skills: null,
byId: new Map() // source id -> source record
};
function openIndex(kind, meta) {
const idxPath = path.join(DATA_DIR, meta.index);
const dataPath = path.join(DATA_DIR, meta.data);
if (!fs.existsSync(idxPath) || !fs.existsSync(dataPath)) {
throw new Error(`索引缺失: ${kind}/${meta.id}(请先执行 node build-index.js)`);
}
const idx = JSON.parse(fs.readFileSync(idxPath, 'utf8'));
const fd = fs.openSync(dataPath, 'r');
return { ...meta, kind, idx, fd };
}
function loadStore() {
const catalogPath = path.join(DATA_DIR, 'sources.json');
if (!fs.existsSync(catalogPath)) {
throw new Error('未找到 data/sources.json,请先执行 node build-index.js');
}
store.catalog = JSON.parse(fs.readFileSync(catalogPath, 'utf8'));
store.icons = store.catalog.icons.sources.map(s => openIndex('icons', s));
store.posters = store.catalog.posters.sources.map(s => openIndex('posters', s));
for (const s of store.icons) store.byId.set('icons/' + s.id, s);
for (const s of store.posters) store.byId.set('posters/' + s.id, s);
const skillsPath = path.join(DATA_DIR, 'skills.json');
store.skills = fs.existsSync(skillsPath) ? JSON.parse(fs.readFileSync(skillsPath, 'utf8')) : null;
const mem = process.memoryUsage();
console.log(`[索引] 图标 ${store.icons.length} 源 / ${store.catalog.icons.total} 个`);
console.log(`[索引] 海报 ${store.posters.length} 源 / ${store.catalog.posters.total} 个`);
console.log(`[索引] RSS ${(mem.rss / 1048576).toFixed(0)} MB`);
}
/** 按字节偏移读取单条素材(带 LRU:详情/随机接口高频重复访问同一批素材) */
const ITEM_CACHE = new Map();
const ITEM_CACHE_MAX = 3000;
function readItem(src, i) {
const key = src.kind + '/' + src.id + '#' + i;
const hit = ITEM_CACHE.get(key);
if (hit) {
ITEM_CACHE.delete(key);
ITEM_CACHE.set(key, hit);
return hit;
}
const off = src.idx.o[i * 2];
const len = src.idx.o[i * 2 + 1];
if (typeof off !== 'number' || typeof len !== 'number') return null;
const buf = Buffer.allocUnsafe(len);
fs.readSync(src.fd, buf, 0, len, off);
let item = null;
try { item = JSON.parse(buf.toString('utf8')); } catch (e) { return null; }
if (item) {
ITEM_CACHE.set(key, item);
if (ITEM_CACHE.size > ITEM_CACHE_MAX) ITEM_CACHE.delete(ITEM_CACHE.keys().next().value);
}
return item;
}
/* ============================ API Key ============================ */
const keyState = {
keys: [],
mtime: 0,
buckets: new Map() // keyId -> { window, count, day, dayCount }
};
function sha256(s) {
return crypto.createHash('sha256').update(String(s)).digest('hex');
}
function safeEqual(a, b) {
const ba = Buffer.from(String(a));
const bb = Buffer.from(String(b));
if (ba.length !== bb.length) return false;
return crypto.timingSafeEqual(ba, bb);
}
function loadKeys(force) {
if (!fs.existsSync(KEY_FILE)) {
if (force) keyState.keys = [];
return;
}
const stat = fs.statSync(KEY_FILE);
if (!force && stat.mtimeMs === keyState.mtime) return;
try {
const list = JSON.parse(fs.readFileSync(KEY_FILE, 'utf8'));
keyState.keys = Array.isArray(list) ? list : [];
keyState.mtime = stat.mtimeMs;
} catch (e) {
console.error('[Key] 解析失败:' + e.message);
}
}
function today() {
const d = new Date();
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
}
/**
* 校验 Key,并做分钟限流 + 日配额
* @returns {{ok:true, key:object, remaining:number}|{ok:false, status:number, code:string, message:string}}
*/
function authenticate(req) {
const raw = req.headers['x-api-key'] || String(req.headers.authorization || '').replace(/^Bearer\s+/i, '');
if (!raw) {
return { ok: false, status: 401, code: 'UNAUTHORIZED', message: '缺少 API Key(请求头 X-API-Key 或 Authorization: Bearer <key>)' };
}
loadKeys(false);
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 无效或已禁用' };
}
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();
let b = keyState.buckets.get(rec.id);
if (!b) { b = { window: now, count: 0, day, dayCount: 0 }; keyState.buckets.set(rec.id, b); }
if (now - b.window >= 60000) { b.window = now; b.count = 0; }
if (b.day !== day) { b.day = day; b.dayCount = 0; }
const rate = Number(rec.ratePerMin || CONFIG.defaultRatePerMin);
const quota = Number(rec.dailyQuota || CONFIG.defaultDailyQuota);
b.count += 1;
b.dayCount += 1;
rec.lastUsedAt = new Date().toISOString();
if (b.dayCount > quota) {
return { ok: false, status: 429, code: 'DAILY_QUOTA_EXCEEDED', message: `超出每日配额(${quota} 次)` };
}
if (b.count > rate) {
return { ok: false, status: 429, code: 'RATE_LIMITED', message: `请求过于频繁(${rate} 次/分钟)`, retryAfter: 60 };
}
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 || '',
// 内部使用:明文保存,后台可随时查看/复制;旧 Key 无 key 字段
key: rec.key || '',
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(),
key: raw,
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', '不支持的方法');
}
/* ============================ 站点登录 ============================ */
const COOKIE_NAME = 'hgb_session';
const loginBuckets = new Map();
/** scrypt 密码哈希:scrypt$salt$hash */
function hashPassword(pw) {
const salt = crypto.randomBytes(16).toString('hex');
const hash = crypto.scryptSync(String(pw), salt, 64).toString('hex');
return 'scrypt$' + salt + '$' + hash;
}
function verifyPassword(pw, stored) {
const parts = String(stored || '').split('$');
if (parts.length !== 3 || parts[0] !== 'scrypt') return false;
const calc = crypto.scryptSync(String(pw), parts[1], 64).toString('hex');
return safeEqual(calc, parts[2]);
}
function authReady() {
const a = CONFIG.auth || {};
return !!(a.username && a.passwordHash && a.secret);
}
function signSession(payload) {
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const sig = crypto.createHmac('sha256', CONFIG.auth.secret).update(body).digest('base64url');
return body + '.' + sig;
}
function verifySession(token) {
const parts = String(token || '').split('.');
if (parts.length !== 2) return null;
const expect = crypto.createHmac('sha256', CONFIG.auth.secret).update(parts[0]).digest('base64url');
if (!safeEqual(parts[1], expect)) return null;
try {
const p = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
if (!p.exp || p.exp < Date.now()) return null;
if (p.u !== CONFIG.auth.username) return null;
return p;
} catch (e) { return null; }
}
function parseCookies(req) {
const out = {};
String(req.headers.cookie || '').split(';').forEach(function (s) {
const i = s.indexOf('=');
if (i > 0) {
try { out[s.slice(0, i).trim()] = decodeURIComponent(s.slice(i + 1).trim()); }
catch (e) { /* ignore */ }
}
});
return out;
}
function currentSession(req) {
return verifySession(parseCookies(req)[COOKIE_NAME]);
}
function clientIp(req) {
return String(req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
}
function loginRateLimit(ip) {
const now = Date.now();
let b = loginBuckets.get(ip);
if (!b || now - b.window >= 60000) { b = { window: now, count: 0 }; loginBuckets.set(ip, b); }
b.count += 1;
return b.count <= 8;
}
function sessionCookie(req, token, maxAge) {
const proto = String(req.headers['x-forwarded-proto'] || '').toLowerCase();
const secure = proto === 'https';
return COOKIE_NAME + '=' + token + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + maxAge + (secure ? '; Secure' : '');
}
async function handleAuth(req, res, pathname) {
const method = req.method;
// 登录
if (pathname === '/api/v1/auth/login' && method === 'POST') {
if (!authReady()) return fail(res, 503, 'AUTH_DISABLED', '登录功能未启用');
const ip = clientIp(req);
if (!loginRateLimit(ip)) return fail(res, 429, 'TOO_MANY_ATTEMPTS', '尝试过于频繁,请 1 分钟后再试');
let body;
try { body = await readJsonBody(req); }
catch (e) { return fail(res, 400, e.code || 'BAD_REQUEST', '请求体格式错误'); }
const username = String(body.username || '').trim();
const password = String(body.password || '');
if (!username || !password) return fail(res, 400, 'BAD_REQUEST', '请输入帐号与密码');
const okUser = safeEqual(username, CONFIG.auth.username);
const okPass = verifyPassword(password, CONFIG.auth.passwordHash);
if (!okUser || !okPass) return fail(res, 401, 'BAD_CREDENTIALS', '帐号或密码错误');
const days = Number(CONFIG.auth.maxAgeDays) || 7;
const maxAge = days * 24 * 3600;
const token = signSession({ u: CONFIG.auth.username, exp: Date.now() + maxAge * 1000 });
return send(res, 200, { ok: true, data: { username: CONFIG.auth.username } }, {
'Set-Cookie': sessionCookie(req, token, maxAge)
});
}
// 退出
if (pathname === '/api/v1/auth/logout' && method === 'POST') {
return send(res, 200, { ok: true, data: { ok: true } }, {
'Set-Cookie': sessionCookie(req, '', 0)
});
}
// 当前登录态(未登录返回 loggedIn:false,避免前端控制台出现 401 噪音)
if (pathname === '/api/v1/auth/me' && method === 'GET') {
const s = currentSession(req);
if (!s) return ok(res, { loggedIn: false });
return ok(res, { loggedIn: true, username: s.u, expiresAt: new Date(s.exp).toISOString() });
}
// nginx auth_request 子请求:200 = 放行,401 = 跳登录
if (pathname === '/api/v1/auth/verify' && method === 'GET') {
if (!authReady()) return fail(res, 503, 'AUTH_DISABLED', '登录功能未启用');
if (!currentSession(req)) return fail(res, 401, 'UNAUTHORIZED', '未登录');
return send(res, 200, '', { 'Content-Type': 'text/plain; charset=utf-8' });
}
return fail(res, 404, 'NOT_FOUND', '未知认证端点');
}
/* ============================ 检索 ============================ */
function parseLimit(v) {
const n = parseInt(v, 10);
if (!Number.isFinite(n) || n <= 0) return 20;
return Math.min(n, CONFIG.maxLimit);
}
function parseOffset(v) {
const n = parseInt(v, 10);
return Number.isFinite(n) && n > 0 ? n : 0;
}
const SAFE_ID = /^[A-Za-z0-9._-]+$/;
/** 负面变体(-off / -alert / -error …),搜索默认排除 */
const NEGATIVE_RE = /-(off|alert|error|forbidden|ban|block|close|cancel|delete|remove|slash|times|prohibited)$/;
const MAX_CANDIDATES = 5000;
/** 负面变体标记(懒计算后缓存在源对象上:避免每次搜索对 50 万名字逐个跑正则) */
function negFlags(src) {
if (!src._neg) {
const n = src.idx.n;
const flags = new Uint8Array(n.length);
for (let i = 0; i < n.length; i++) flags[i] = NEGATIVE_RE.test(n[i]) ? 1 : 0;
src._neg = flags;
}
return src._neg;
}
/** 主流通用图标库优先(同分时排序用,越小越优先) */
const SOURCE_RANK = {
lucide: 0, tabler: 1, heroicons: 2, feather: 3, phosphor: 4, remix: 5,
'material-symbols': 6, 'material-symbols-light': 7, ionicons: 8, mdi: 9,
bootstrap: 10, fontawesome: 11, 'simple-icons': 12, fluent: 13, 'fluent-emoji': 14
};
function sourceRank(id) {
return SOURCE_RANK[id] !== undefined ? SOURCE_RANK[id] : 50;
}
/** 每个源的可搜索文本(懒构建):ASCII 查询走 name+别名,中文查询走分类/中文别名/源中文信息 */
function searchText(src) {
if (!src._st) {
const n = src.idx.n;
const kws = src.idx.kws || [];
src._st = {
ascii: n.join('\u0001').toLowerCase() + '\u0001' + kws.join(' ').toLowerCase(),
cn: ((src.idx.cats || []).join(' ') + ' ' + kws.join(' ') + ' ' +
(src.nameCn || '') + ' ' + (src.name || '') + ' ' + (src.desc || '')).toLowerCase(),
// 源级匹配文本(与 search() 里的 srcText 保持一致,否则源名命中会被剪枝误杀)
src: [(src.name || ''), (src.nameCn || ''), (src.desc || '')].join(' ').toLowerCase()
};
}
return src._st;
}
/**
* 在指定集合中搜索(支持英文名 / 中文分类 / 中文语义别名)
* @param {Array} sources 源记录
* @param {object} opts { q, source, type, commercial, limit, offset, dedupe, includeNegative }
*/
function search(sources, opts) {
const q = String(opts.q || '').trim().toLowerCase();
const limit = parseLimit(opts.limit);
const offset = parseOffset(opts.offset);
const dedupe = opts.dedupe === true;
const includeNegative = opts.includeNegative === true;
const isCJK = /[\u4e00-\u9fff]/.test(q);
const hits = [];
const seen = new Set();
let total = 0;
for (const src of sources) {
if (opts.source && src.id !== opts.source) continue;
if (opts.commercial === true && !src.commercial) continue;
// 源级中文匹配:图标/字体等素材名可能是英文,中文名在源上
const srcText = (opts.includeSourceName || opts.includeSourceText)
? [src.name, src.nameCn, opts.includeSourceText ? src.desc : ''].join(' ').toLowerCase()
: '';
const srcHit = srcText && srcText.indexOf(q) !== -1;
// 「无衬线」包含「衬线」:否定前缀命中降权,避免压过真正的衬线字体
const srcWeak = srcHit && srcText.indexOf('无' + q) !== -1;
const { n, c, t, k, kws, cats, types } = src.idx;
// 快速剪枝:查询词在该源任何可搜索文本中都不存在 → 整源跳过(结果等价,省掉逐条扫描)
// 注意:源名/源中文名命中(srcHit 打分 6/8)也必须算作可命中来源
if (q) {
const st = searchText(src);
const itemText = isCJK ? st.cn : st.ascii;
const srcMatch = (opts.includeSourceName || opts.includeSourceText) && st.src.indexOf(q) !== -1;
if (itemText.indexOf(q) === -1 && !srcMatch) continue;
}
// 中文查询:命中可能来自分类名,也可能来自中文语义别名(kws),逐条评分时判定,
// 源级已由上面的 cn 文本剪枝保证「该源确有中文命中」。
const neg = includeNegative ? null : negFlags(src);
for (let i = 0; i < n.length; i++) {
if (opts.type && types[t[i]] !== opts.type) continue;
if (neg && neg[i]) continue;
let score = 0;
let aliasRank = 99;
if (q) {
const name = n[i];
if (name === q) score = 0;
else if (name.startsWith(q)) score = 1;
else if (name.indexOf(q) !== -1) score = 2;
else {
// 中文语义别名:精确匹配优先于分类,分类优先于别名包含
const codes = k[i] || [];
const ranks = (src.idx.r && src.idx.r[i]) || [];
let exact = false;
let partial = false;
for (let j = 0; j < codes.length; j++) {
const kw = kws[codes[j]] || '';
if (kw === q) {
exact = true;
aliasRank = Math.min(aliasRank, ranks[j] === undefined ? 99 : ranks[j]);
} else if (kw.indexOf(q) !== -1) {
partial = true;
aliasRank = Math.min(aliasRank, ranks[j] === undefined ? 99 : ranks[j]);
}
}
if (exact) score = 3;
else if ((cats[c[i]] || '').toLowerCase().indexOf(q) !== -1) score = 4;
else if (partial) score = 5;
else if (srcHit) score = srcWeak ? 8 : 6;
else continue;
}
}
if (dedupe) {
if (seen.has(n[i])) continue;
seen.add(n[i]);
}
total++;
if (hits.length < MAX_CANDIDATES) {
hits.push({
_sort: score * 100000 + aliasRank * 500 + sourceRank(src.id) * 10 + Math.min(n[i].length, 60),
id: n[i],
name: n[i],
categoryCn: cats[c[i]] || '',
type: types[t[i]] || '',
source: src.id,
sourceNameCn: src.nameCn || src.name || src.id,
license: src.license,
commercial: src.commercial,
index: i
});
}
}
}
hits.sort((a, b) => a._sort - b._sort);
const page = hits.slice(offset, offset + limit).map(({ _sort, ...rest }) => rest);
return { total, items: page, limit, offset };
}
function findByName(src, name) {
const target = String(name || '').toLowerCase();
if (!src._nameMap) {
const n = src.idx.n;
const m = new Map();
for (let i = 0; i < n.length; i++) if (!m.has(n[i])) m.set(n[i], i);
src._nameMap = m;
}
const i = src._nameMap.get(target);
return i === undefined ? -1 : i;
}
function pickRandom(sources, opts) {
const count = Math.min(parseLimit(opts.count || 10), 50);
const pool = sources.filter(s => !opts.source || s.id === opts.source);
if (!pool.length) return [];
const out = [];
for (let k = 0; k < count; k++) {
const src = pool[Math.floor(Math.random() * pool.length)];
const i = Math.floor(Math.random() * src.idx.count);
const item = readItem(src, i);
if (item) out.push({ ...item, source: src.id, sourceNameCn: src.nameCn || src.id, license: src.license });
}
return out;
}
/** 静态站根目录(位图图标原图在此读取后内联为 data URI) */
const STATIC_ROOT = (() => {
const env = process.env.DRAWLOGO_ROOT;
if (env) return path.resolve(env);
const sibling = path.resolve(ROOT, '..', 'drawlogo');
if (fs.existsSync(path.join(sibling, 'js', 'data', 'sources'))) return sibling;
return path.resolve(ROOT, '..');
})();
/** 位图图标原图 → data URI(按相对路径缓存,限制条目数防内存膨胀) */
const rasterCache = new Map();
function readRasterDataURI(rel) {
if (rasterCache.has(rel)) return rasterCache.get(rel);
const abs = path.join(STATIC_ROOT, rel);
const buf = fs.readFileSync(abs);
const uri = 'data:image/png;base64,' + buf.toString('base64');
if (rasterCache.size > 300) rasterCache.clear();
rasterCache.set(rel, uri);
return uri;
}
/** 把 <image href="js/data/sources/...png"> 内联为 data URI(外部调用方无需再取静态资源) */
function inlineRasterSvg(body) {
const s = String(body || '');
if (s.indexOf('js/data/sources/') === -1) return s;
return s.replace(/href="(js\/data\/sources\/[^"]+\.png)"/g, (m, rel) => {
try { return 'href="' + readRasterDataURI(rel) + '"'; } catch (e) { return m; }
});
}
/** 构造可直接嵌入的 SVG */
function toSvg(item) {
const body = inlineRasterSvg(item.svg);
if (!body) return null;
const multiColor = item.type === 'emoji' || item.type === 'brand';
const fill = multiColor ? '' : ' fill="currentColor"';
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"${fill}>${body}</svg>`;
}
/* ============================ HTTP ============================ */
function baseHeaders(extra) {
return {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': CONFIG.corsOrigin,
'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',
// 索引只在重建时变化:允许客户端/CDN 短暂缓存,配合 ETag 做 304 复用
'Cache-Control': 'public, max-age=30, stale-while-revalidate=60',
...(extra || {})
};
}
function send(res, status, body, headers) {
const h = baseHeaders(headers);
const payload = typeof body === 'string' ? body : JSON.stringify(body);
const buf = Buffer.from(payload, 'utf8');
const req = res.req;
const etag = 'W/"' + crypto.createHash('sha1').update(buf).digest('base64').slice(0, 22) + '"';
h.ETag = etag;
if (status === 200 && req && req.headers['if-none-match'] === etag) {
res.writeHead(304, h);
return res.end();
}
const ae = String((req && req.headers['accept-encoding']) || '');
// 小响应不压缩(压缩头开销 > 收益);仅对 JSON 文本启用
if (buf.length > 1024 && /\bgzip\b/.test(ae) && !h['Content-Encoding']) {
const gz = zlib.gzipSync(buf, { level: 6 });
h['Content-Encoding'] = 'gzip';
h.Vary = 'Accept-Encoding';
h['Content-Length'] = gz.length;
res.writeHead(status, h);
return res.end(gz);
}
h['Content-Length'] = buf.length;
res.writeHead(status, h);
res.end(buf);
}
/**
* 静态端点响应缓存:一次性序列化 + 预压缩 + ETag,之后整段复用。
* 适用于「索引重建前内容恒定」的端点(sources / skills / 全量列举)。
*/
const STATE_CACHE = new Map();
const STATE_CACHE_MAX = 400;
const STATE_CACHE_ITEM_MAX = 256 * 1024; // 单条超过 256KB 不缓存(避免大结果集撑内存)
function cachedPayload(res, status, key, build, headers) {
let entry = STATE_CACHE.get(key);
if (!entry) {
const buf = Buffer.from(JSON.stringify(build()), 'utf8');
entry = {
buf,
gz: buf.length > 1024 ? zlib.gzipSync(buf, { level: 6 }) : null,
etag: 'W/"' + crypto.createHash('sha1').update(buf).digest('base64').slice(0, 22) + '"',
cacheable: buf.length <= STATE_CACHE_ITEM_MAX
};
if (entry.cacheable) {
STATE_CACHE.set(key, entry);
if (STATE_CACHE.size > STATE_CACHE_MAX) STATE_CACHE.delete(STATE_CACHE.keys().next().value);
}
}
const h = baseHeaders({ ...(headers || {}), ETag: entry.etag });
const req = res.req;
if (status === 200 && req && req.headers['if-none-match'] === entry.etag) {
res.writeHead(304, h);
return res.end();
}
const ae = String((req && req.headers['accept-encoding']) || '');
if (entry.gz && /\bgzip\b/.test(ae)) {
h['Content-Encoding'] = 'gzip';
h.Vary = 'Accept-Encoding';
h['Content-Length'] = entry.gz.length;
res.writeHead(status, h);
return res.end(entry.gz);
}
h['Content-Length'] = entry.buf.length;
res.writeHead(status, h);
res.end(entry.buf);
}
function ok(res, data, meta, extraHeaders) {
send(res, 200, { ok: true, data, ...(meta ? { meta } : {}) }, extraHeaders);
}
/* ---------- 对接文档(自动可发现:无 Key 也能读,错误响应里也带入口) ---------- */
const DOCS_URL = 'https://drawlogo.zhuig.com/api/v1/docs';
const DOCS_FILE = path.join(ROOT, 'README.md');
const DOCS_CUT = '\n## 八、运维'; // 运维/架构章节含服务器路径与部署命令,不对外公开
let docsCache = { mtime: -1, buf: null, gz: null };
/** 只公开「一~七」章(接口、检索、限流、最佳实践、示例、协议合规) */
function buildDocs() {
let md;
try {
md = fs.readFileSync(DOCS_FILE, 'utf8');
} catch (e) {
return Buffer.from('# 接口说明暂不可用\n\n请联系管理员获取 api/README.md。\n', 'utf8');
}
const cut = md.indexOf(DOCS_CUT);
if (cut > 0) md = md.slice(0, cut) + '\n> 运维与架构章节不对外公开。\n';
return Buffer.from(md, 'utf8');
}
function sendDocs(res) {
let mtime = 0;
try { mtime = fs.statSync(DOCS_FILE).mtimeMs; } catch (e) { /* 缺失时按空文档处理 */ }
if (!docsCache.buf || docsCache.mtime !== mtime) {
const buf = buildDocs();
docsCache = { mtime, buf, gz: buf.length > 1024 ? zlib.gzipSync(buf, { level: 6 }) : null };
}
const h = {
'Content-Type': 'text/markdown; charset=utf-8',
'Access-Control-Allow-Origin': CONFIG.corsOrigin,
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'public, max-age=300'
};
const ae = String((res.req && res.req.headers['accept-encoding']) || '');
if (docsCache.gz && /\bgzip\b/.test(ae)) {
res.writeHead(200, { ...h, 'Content-Encoding': 'gzip', Vary: 'Accept-Encoding', 'Content-Length': docsCache.gz.length });
return res.end(docsCache.gz);
}
res.writeHead(200, { ...h, 'Content-Length': docsCache.buf.length });
return res.end(docsCache.buf);
}
function fail(res, status, code, message, extraHeaders) {
// 错误响应统一带文档入口:新接入方第一次调用(401)就能读到对接说明
send(res, status, { ok: false, error: { code, message, docs: DOCS_URL } }, { 'Cache-Control': 'no-store', ...(extraHeaders || {}) });
}
const PUBLIC_PATHS = new Set(['/api/v1/health', '/api/v1/stats', '/api/v1/sources', '/api/v1/docs']);
async function handle(req, res) {
const u = new URL(req.url, 'http://localhost');
const pathname = decodeURIComponent(u.pathname);
const q = u.searchParams;
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);
}
// 站点登录:登录/退出/登录态/nginx 子请求(免 API Key)
if (pathname.indexOf('/api/v1/auth/') === 0) {
return handleAuth(req, res, pathname);
}
if (req.method !== 'GET') {
return fail(res, 405, 'METHOD_NOT_ALLOWED', '仅支持 GET');
}
// 鉴权(公开端点除外)
let authInfo = null;
if (!PUBLIC_PATHS.has(pathname)) {
const a = authenticate(req);
if (!a.ok) {
const headers = a.retryAfter ? { 'Retry-After': String(a.retryAfter) } : undefined;
return fail(res, a.status, a.code, a.message, headers);
}
authInfo = a;
}
const rateHeaders = authInfo
? { 'X-RateLimit-Limit': String(authInfo.limit), 'X-RateLimit-Remaining': String(authInfo.remaining) }
: undefined;
/* ---------- 基础 ---------- */
if (pathname === '/api/v1/docs') {
return sendDocs(res);
}
if (pathname === '/api/v1/health') {
return ok(res, { status: 'up', version: '1.0.0', builtAt: store.catalog.builtAt, uptime: Math.round(process.uptime()), docs: DOCS_URL });
}
if (pathname === '/api/v1/stats') {
const mem = process.memoryUsage();
return ok(res, {
builtAt: store.catalog.builtAt,
icons: { total: store.catalog.icons.total, sources: store.icons.length },
posters: { total: store.catalog.posters.total, sources: store.posters.length },
skills: store.skills
? { shared: store.skills.shared.total, poster: store.skills.poster.total, sticker: store.skills.sticker.total }
: null,
runtime: { rssMB: Math.round(mem.rss / 1048576), uptime: Math.round(process.uptime()) },
docs: DOCS_URL
});
}
if (pathname === '/api/v1/sources') {
const kind = q.get('kind') || 'all';
const compact = q.get('compact') === '1';
const pick = s => compact
? { id: s.id, name: s.name, nameCn: s.nameCn, type: s.type, license: s.license, commercial: s.commercial, count: s.count }
: {
id: s.id, name: s.name, nameCn: s.nameCn, desc: s.desc, style: s.style, type: s.type,
license: s.license, licenseNote: s.licenseNote, commercial: s.commercial,
count: s.count, workspaces: s.workspaces
};
// 全量源清单恒定(仅索引重建才变):预序列化 + 预压缩 + ETag 复用
return cachedPayload(res, 200, 'sources|' + kind + '|' + (compact ? 1 : 0), () => {
const data = {};
if (kind === 'all' || kind === 'icons') data.icons = store.icons.map(pick);
if (kind === 'all' || kind === 'posters') data.posters = store.posters.map(pick);
return { ok: true, data };
}, rateHeaders);
}
/* ---------- 图标 ---------- */
if (pathname === '/api/v1/icons/search') {
return cachedPayload(res, 200, 'icons/search?' + q.toString(), () => {
const r = search(store.icons, {
q: q.get('q'), source: q.get('source'), type: q.get('type'),
commercial: q.get('commercial') === '1', limit: q.get('limit'), offset: q.get('offset'),
dedupe: q.get('dedupe') === '1', includeNegative: q.get('include_negative') === '1',
includeSourceName: true
});
return { ok: true, data: r.items, meta: { total: r.total, limit: r.limit, offset: r.offset } };
}, rateHeaders);
}
if (pathname === '/api/v1/icons/random') {
const items = pickRandom(store.icons, { count: q.get('count'), source: q.get('source') });
return ok(res, items, { count: items.length }, rateHeaders);
}
// 批量取图(合并多次详情请求,降低 RTT 与鉴权/限流开销);items=源:名称,源:名称
if (pathname === '/api/v1/icons/batch') {
const refs = String(q.get('items') || '').split(',').map(s => s.trim()).filter(Boolean).slice(0, 50);
const out = [];
for (const ref of refs) {
const cut = ref.indexOf(':');
const sid = cut > 0 ? ref.slice(0, cut) : '';
const nm = cut > 0 ? ref.slice(cut + 1) : ref;
const src = store.byId.get('icons/' + sid);
if (!src) { out.push({ ref, error: 'source_not_found' }); continue; }
const i = findByName(src, nm);
if (i < 0) { out.push({ ref, error: 'not_found' }); continue; }
const item = readItem(src, i);
if (!item) { out.push({ ref, error: 'read_failed' }); continue; }
out.push({ ref, item: { ...item, svg: inlineRasterSvg(item.svg), source: sid, license: src.license, commercial: src.commercial } });
}
return ok(res, out, { count: out.length }, rateHeaders);
}
const iconMatch = pathname.match(/^\/api\/v1\/icons\/([^/]+)\/(.+?)(\.svg|\.json)?$/);
if (iconMatch) {
const [, sourceId, rawName, ext] = iconMatch;
if (!SAFE_ID.test(sourceId)) return fail(res, 400, 'BAD_REQUEST', 'source 参数非法');
const src = store.byId.get('icons/' + sourceId);
if (!src) return fail(res, 404, 'NOT_FOUND', `图标源不存在: ${sourceId}`);
const name = rawName.replace(/\.(svg|json)$/i, '');
const i = findByName(src, name);
if (i < 0) return fail(res, 404, 'NOT_FOUND', `图标不存在: ${sourceId}/${name}`);
const item = readItem(src, i);
if (!item) return fail(res, 500, 'INTERNAL', '读取素材失败');
if (ext === '.svg') {
const svg = toSvg(item);
if (!svg) return fail(res, 404, 'NOT_FOUND', '该素材无 SVG 内容');
const ae = String(req.headers['accept-encoding'] || '');
const buf = Buffer.from(svg, 'utf8');
const gz = buf.length > 1024 && /\bgzip\b/.test(ae);
res.writeHead(200, {
'Content-Type': 'image/svg+xml; charset=utf-8',
'Cache-Control': 'public, max-age=86400',
'Access-Control-Allow-Origin': CONFIG.corsOrigin,
'X-Content-Type-Options': 'nosniff',
...(gz ? { 'Content-Encoding': 'gzip', Vary: 'Accept-Encoding' } : { 'Content-Length': buf.length })
});
return res.end(gz ? zlib.gzipSync(buf, { level: 6 }) : buf);
}
return ok(res, { ...item, svg: inlineRasterSvg(item.svg), source: sourceId, sourceNameCn: src.nameCn || sourceId, license: src.license, commercial: src.commercial }, null, rateHeaders);
}
/* ---------- 海报 ---------- */
if (pathname === '/api/v1/posters/search') {
return cachedPayload(res, 200, 'posters/search?' + q.toString(), () => {
const r = search(store.posters, {
q: q.get('q'), source: q.get('source'), type: q.get('type'),
commercial: q.get('commercial') === '1', limit: q.get('limit'), offset: q.get('offset'),
dedupe: q.get('dedupe') === '1', includeNegative: q.get('include_negative') === '1',
includeSourceText: true
});
return { ok: true, data: r.items, meta: { total: r.total, limit: r.limit, offset: r.offset } };
}, rateHeaders);
}
// 批量取海报素材(同 icons/batch)
if (pathname === '/api/v1/posters/batch') {
const refs = String(q.get('items') || '').split(',').map(s => s.trim()).filter(Boolean).slice(0, 50);
const out = [];
for (const ref of refs) {
const cut = ref.indexOf(':');
const sid = cut > 0 ? ref.slice(0, cut) : '';
const nm = cut > 0 ? ref.slice(cut + 1) : ref;
const src = store.byId.get('posters/' + sid);
if (!src) { out.push({ ref, error: 'source_not_found' }); continue; }
const i = findByName(src, nm);
if (i < 0) { out.push({ ref, error: 'not_found' }); continue; }
const item = readItem(src, i);
if (!item) { out.push({ ref, error: 'read_failed' }); continue; }
out.push({ ref, item: { ...item, svg: inlineRasterSvg(item.svg), source: sid, license: src.license, commercial: src.commercial } });
}
return ok(res, out, { count: out.length }, rateHeaders);
}
const posterMatch = pathname.match(/^\/api\/v1\/posters\/([^/]+)\/(.+)$/);
if (posterMatch) {
const [, sourceId, rawName] = posterMatch;
if (!SAFE_ID.test(sourceId)) return fail(res, 400, 'BAD_REQUEST', 'source 参数非法');
const src = store.byId.get('posters/' + sourceId);
if (!src) return fail(res, 404, 'NOT_FOUND', `海报源不存在: ${sourceId}`);
const i = findByName(src, rawName);
if (i < 0) return fail(res, 404, 'NOT_FOUND', `素材不存在: ${sourceId}/${rawName}`);
const item = readItem(src, i);
if (!item) return fail(res, 500, 'INTERNAL', '读取素材失败');
return ok(res, { ...item, svg: inlineRasterSvg(item.svg), source: sourceId, sourceNameCn: src.nameCn || sourceId, license: src.license, commercial: src.commercial }, null, rateHeaders);
}
/* ---------- 技能(元数据) ---------- */
if (pathname === '/api/v1/skills') {
if (!store.skills) return fail(res, 503, 'NOT_READY', '技能索引未构建');
const workspace = q.get('workspace');
const step = q.get('step');
const category = q.get('category');
const limit = parseLimit(q.get('limit'));
const offset = parseOffset(q.get('offset'));
// 技能元数据恒定:按查询条件缓存整段响应
return cachedPayload(res, 200, 'skills|' + q.toString(), () => {
let list = [];
for (const [lib, obj] of Object.entries(store.skills)) {
if (lib === 'kind') continue;
for (const s of (obj.skills || [])) list.push({ ...s, library: lib });
}
if (workspace) list = list.filter(s => !s.workspaces || s.workspaces.includes(workspace));
if (step) list = list.filter(s => String(s.step) === String(step));
if (category) list = list.filter(s => s.category === category);
return { ok: true, data: list.slice(offset, offset + limit), meta: { total: list.length, limit, offset } };
}, rateHeaders);
}
const skillMatch = pathname.match(/^\/api\/v1\/skills\/([A-Za-z0-9._-]+)$/);
if (skillMatch) {
if (!store.skills) return fail(res, 503, 'NOT_READY', '技能索引未构建');
const id = skillMatch[1];
for (const [lib, obj] of Object.entries(store.skills)) {
if (lib === 'kind') continue;
const hit = (obj.skills || []).find(s => s.id === id);
if (hit) return ok(res, { ...hit, library: lib }, null, rateHeaders);
}
return fail(res, 404, 'NOT_FOUND', `技能不存在: ${id}`);
}
return fail(res, 404, 'NOT_FOUND', `未知端点: ${pathname}`);
}
/* ============================ 启动 ============================ */
function main() {
loadStore();
loadKeys(true);
// Key 文件热加载(改 Key 无需重启)
setInterval(() => loadKeys(false), 5000).unref();
const server = http.createServer((req, res) => {
const t0 = Date.now();
handle(req, res).catch(e => {
console.error('[ERROR]', e);
if (!res.headersSent) fail(res, 500, 'INTERNAL', '服务内部错误');
}).then(() => {
const cost = Date.now() - t0;
if (cost > 300) console.warn(`[SLOW] ${req.method} ${req.url} ${cost}ms`);
});
});
server.listen(CONFIG.port, CONFIG.host, () => {
console.log(`[启动] http://${CONFIG.host}:${CONFIG.port} (Key: ${keyState.keys.length} 把)`);
});
const shutdown = () => {
console.log('[退出] 关闭中…');
server.close(() => {
for (const s of store.icons.concat(store.posters)) {
try { fs.closeSync(s.fd); } catch (e) { /* ignore */ }
}
process.exit(0);
});
setTimeout(() => process.exit(0), 3000).unref();
};
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
}
main();