Files
moyu-qile/tests/auth_meta.test.js

107 lines
4.8 KiB
JavaScript

// auth_meta.test.js — 授权接入回归:/api/meta 形状、安装登记去重、fail-open
const http = require('http');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { spawn } = require('child_process');
const ROOT = path.join(__dirname, '..');
const MOCK_PORT = 17901;
const SRV_PORT = 17902;
let mockHits = { check: 0, notice: 0 };
// ── mock CardAuth ──
const mock = http.createServer((req, res) => {
const send = (o) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(o)); };
let b = ''; req.on('data', d => b += d); req.on('end', () => {
const u = req.url.split('?')[0];
if (u === '/api/public/installations/check-update') {
mockHits.check++;
const body = JSON.parse(b || '{}');
if (req.headers['x-api-key'] !== 'ak_test') return send({ code: 403, message: 'API密钥无效或项目已禁用', data: null });
if (!/^\d{10,16}$/.test(body.machine_id || '')) return send({ code: 400, message: '机器码非法', data: null });
return send({ code: 200, message: 'ok', data: {
install_id: 77, update_available: body.client_version !== '9.9.9',
latest_version: '9.9.9', download_url: 'https://example.com/dl',
changelog: '第一行更新\n第二行更新', is_force: false } });
}
if (u === '/api/public/announcements') {
mockHits.notice++;
const one = { id: 901, title: '公告测试', content: '内容A', type: 'notice', target: 'all', project_id: 8, is_top: 1, is_popup: 1, link_url: '' };
const other = { id: 902, title: '别家项目', content: '不该出现', project_id: 6, is_top: 0, is_popup: 0, link_url: '' };
return send({ code: 200, data: { list: [one, other], popup: [one] } });
}
send({ code: 404, message: '接口不存在', data: null });
});
});
function get(port, p) {
return new Promise((resolve, reject) => {
http.get({ host: '127.0.0.1', port, path: p }, r => {
let b = ''; r.on('data', d => b += d);
r.on('end', () => { try { resolve(JSON.parse(b)); } catch (e) { reject(new Error('非JSON: ' + b.slice(0, 100))); } });
}).on('error', reject);
});
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
(async () => {
// 独立数据目录
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'authmeta-'));
fs.writeFileSync(path.join(dir, 'auth.json'), JSON.stringify({
baseUrl: 'http://127.0.0.1:' + MOCK_PORT, apiKey: 'ak_test', projectId: 8, version: '1.1.0'
}));
await new Promise(r => mock.listen(MOCK_PORT, '127.0.0.1', r));
const srv = spawn('node', ['server.js'], {
cwd: ROOT,
env: { ...process.env, PORT: String(SRV_PORT), DATA_DIR: dir },
stdio: ['ignore', 'pipe', 'pipe']
});
let boot = '';
srv.stdout.on('data', d => boot += d);
srv.stderr.on('data', d => boot += d);
try {
await sleep(1500);
// 1) /api/meta:版本、更新提示、公告过滤
const m = await get(SRV_PORT, '/api/meta');
console.assert(m.version === '1.1.0', '版本错误: ' + m.version);
console.assert(m.configured === true, 'configured 应为 true');
console.assert(m.update && m.update.available === true, '应提示有更新');
console.assert(m.update.latest === '9.9.9', 'latest 错误');
console.assert(/第二行更新/.test(m.update.changelog), 'changelog 丢失');
console.assert(m.notices.length === 1 && m.notices[0].id === 901, '公告过滤错误: ' + JSON.stringify(m.notices.map(n => n.id)));
console.assert(/^\d{10,16}$/.test(m.machine), '机器码格式错误');
console.log('✓ meta形状 + 公告按项目过滤 + 有更新');
// 2) 机器码去重:重启服务端后 install_id 不变、machine_id 不变
const m1 = await get(SRV_PORT, '/api/meta');
console.assert(m1.machine === m.machine, '机器码跨请求应稳定');
console.log('✓ 机器码稳定(安装量去重前提)');
// 3) 心跳真的打到 mock(安装登记)
await sleep(300);
console.assert(mockHits.check >= 1, 'mock 未收到 check-update');
console.log('✓ 安装登记/心跳命中 mock (' + mockHits.check + '次)');
// 4) fail-open:杀掉 mock 后 meta 仍可用
await new Promise(r => { mock.close(r); });
await sleep(6200); // 等5分钟缓存过期? 不行——metaAt 未过期时不会重打,直接改走:杀mock后再请求(notices缓存也未过期)
const m2 = await get(SRV_PORT, '/api/meta');
console.assert(m2.version === '1.1.0', 'fail-open 版本仍应返回');
console.log('✓ 授权服务器宕机不影响 /api/meta(fail-open)');
console.log('AUTH_META_ALL_PASS');
} catch (e) {
console.error('FAIL:', e.message);
console.error('server log:', boot.slice(-400));
process.exitCode = 1;
} finally {
srv.kill('SIGKILL');
try { mock.close(); } catch (e) {}
fs.rmSync(dir, { recursive: true, force: true });
}
})();