feat(api): 新增素材检索 API 服务(图标/海报检索 + SVG 直链 + Key 鉴权 + 中文语义检索)

This commit is contained in:
sgp
2026-11-04 16:42:02 +08:00
parent 9e222877ea
commit dce05d6516
15 changed files with 1848 additions and 0 deletions
+540
View File
@@ -0,0 +1,540 @@
#!/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 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
};
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`);
}
/** 按字节偏移读取单条素材 */
function readItem(src, i) {
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);
try { return JSON.parse(buf.toString('utf8')); } catch (e) { return null; }
}
/* ============================ 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 hash = sha256(raw.trim());
const rec = keyState.keys.find(k => k.enabled !== false && k.hash && safeEqual(k.hash, hash));
if (!rec) {
return { ok: false, status: 403, code: 'INVALID_KEY', 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 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;
/** 主流通用图标库优先(同分时排序用,越小越优先) */
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;
}
/**
* 在指定集合中搜索(支持英文名 / 中文分类 / 中文语义别名)
* @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 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 { n, c, t, k, kws, cats, types } = src.idx;
for (let i = 0; i < n.length; i++) {
if (opts.type && types[t[i]] !== opts.type) continue;
if (!includeNegative && NEGATIVE_RE.test(n[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 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();
const n = src.idx.n;
for (let i = 0; i < n.length; i++) {
if (n[i] === target) return i;
}
return -1;
}
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;
}
/** 构造可直接嵌入的 SVG */
function toSvg(item) {
const body = String(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 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',
'X-Content-Type-Options': 'nosniff',
...(headers || {})
};
const payload = typeof body === 'string' ? body : JSON.stringify(body);
res.writeHead(status, h);
res.end(payload);
}
function ok(res, data, meta, extraHeaders) {
send(res, 200, { ok: true, data, ...(meta ? { meta } : {}) }, extraHeaders);
}
function fail(res, status, code, message, extraHeaders) {
send(res, status, { ok: false, error: { 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();
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, '');
}
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/health') {
return ok(res, { status: 'up', version: '1.0.0', builtAt: store.catalog.builtAt, uptime: Math.round(process.uptime()) });
}
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()) }
});
}
if (pathname === '/api/v1/sources') {
const kind = q.get('kind');
const pick = s => ({
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
});
const data = {};
if (!kind || kind === 'icons') data.icons = store.icons.map(pick);
if (!kind || kind === 'posters') data.posters = store.posters.map(pick);
return ok(res, data);
}
/* ---------- 图标 ---------- */
if (pathname === '/api/v1/icons/search') {
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'
});
return ok(res, r.items, { 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);
}
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 内容');
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'
});
return res.end(svg);
}
return ok(res, { ...item, source: sourceId, sourceNameCn: src.nameCn || sourceId, license: src.license, commercial: src.commercial }, null, rateHeaders);
}
/* ---------- 海报 ---------- */
if (pathname === '/api/v1/posters/search') {
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'
});
return ok(res, r.items, { total: r.total, limit: r.limit, offset: r.offset }, 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, 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');
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);
const limit = parseLimit(q.get('limit'));
const offset = parseOffset(q.get('offset'));
return ok(res, list.slice(offset, offset + limit), { 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();
try {
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`);
});
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();