smoke.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #!/usr/bin/env node
  2. 'use strict';
  3. // 零依赖冒烟测试:拉起真实服务(随机端口),全量核对端点行为后关停。
  4. // 安全边界:只做只读请求 + 无副作用 POST(校验失败类、空操作);
  5. // 绝不触碰 DELETE /api/reports/data、/api/crawl/start、/api/open-folder、
  6. // /api/image/test、/api/chat/test,也不在数据湖有主体时调用 /api/reports/ask。
  7. // 用法:node scripts/smoke.js
  8. const { spawn } = require('child_process');
  9. const net = require('net');
  10. const http = require('http');
  11. const path = require('path');
  12. const ROOT = path.resolve(__dirname, '..');
  13. function pickPort() {
  14. return new Promise((resolve, reject) => {
  15. const srv = net.createServer();
  16. srv.unref();
  17. srv.on('error', reject);
  18. srv.listen(0, '127.0.0.1', () => {
  19. const port = srv.address().port;
  20. srv.close(() => resolve(port));
  21. });
  22. });
  23. }
  24. function request(port, method, urlPath, body) {
  25. return new Promise((resolve, reject) => {
  26. const req = http.request({
  27. host: '127.0.0.1', port, method, path: urlPath, timeout: 15000,
  28. headers: body !== undefined ? { 'Content-Type': 'application/json' } : {},
  29. }, (res) => {
  30. const chunks = [];
  31. res.on('data', (c) => chunks.push(c));
  32. res.on('end', () => resolve({
  33. status: res.statusCode,
  34. headers: res.headers,
  35. text: Buffer.concat(chunks).toString('utf8'),
  36. json: () => JSON.parse(Buffer.concat(chunks).toString('utf8')),
  37. }));
  38. });
  39. req.on('error', reject);
  40. req.on('timeout', () => req.destroy(new Error('timeout')));
  41. if (body !== undefined) req.write(JSON.stringify(body));
  42. req.end();
  43. });
  44. }
  45. const results = [];
  46. async function check(name, fn) {
  47. try {
  48. await fn();
  49. results.push({ name, ok: true });
  50. } catch (e) {
  51. results.push({ name, ok: false, error: e.message });
  52. }
  53. }
  54. function expect(cond, msg) {
  55. if (!cond) throw new Error(msg);
  56. }
  57. async function waitForHealth(port, timeoutMs = 20000) {
  58. const start = Date.now();
  59. for (;;) {
  60. try {
  61. const res = await request(port, 'GET', '/healthz');
  62. if (res.status === 200) return;
  63. } catch { /* not up yet */ }
  64. if (Date.now() - start > timeoutMs) throw new Error('服务未在超时内启动');
  65. await new Promise((r) => setTimeout(r, 300));
  66. }
  67. }
  68. function enc(s) { return encodeURIComponent(s); }
  69. async function main() {
  70. const port = await pickPort();
  71. const child = spawn(process.execPath, [path.join(ROOT, 'server.js')], {
  72. env: { ...process.env, PORT: String(port), HOST: '127.0.0.1' },
  73. stdio: ['ignore', 'pipe', 'pipe'],
  74. });
  75. let bootLog = '';
  76. child.stdout.on('data', (c) => { bootLog += c; });
  77. child.stderr.on('data', (c) => { bootLog += c; });
  78. try {
  79. await waitForHealth(port);
  80. let workspaceRoot = '';
  81. {
  82. const res = await request(port, 'GET', '/api/default-root');
  83. workspaceRoot = res.json().root;
  84. }
  85. const encRoot = enc(workspaceRoot);
  86. const b64Root = Buffer.from(workspaceRoot, 'utf8').toString('base64url');
  87. // ---- 基础与健康 ----
  88. await check('GET /healthz', async () => {
  89. const r = await request(port, 'GET', '/healthz');
  90. expect(r.status === 200 && r.json().ok === true, `status=${r.status}`);
  91. });
  92. await check('GET /readyz', async () => {
  93. const r = await request(port, 'GET', '/readyz');
  94. const j = r.json();
  95. expect(r.status === 200 && typeof j.ok === 'boolean' && typeof j.workspaceReady === 'boolean', `status=${r.status}`);
  96. });
  97. await check('GET /api/default-root', async () => {
  98. const r = await request(port, 'GET', '/api/default-root');
  99. expect(r.status === 200 && !!r.json().root, `status=${r.status}`);
  100. });
  101. // ---- 设置域 ----
  102. await check('GET /api/models', async () => {
  103. const r = await request(port, 'GET', '/api/models');
  104. const j = r.json();
  105. expect(r.status === 200 && Array.isArray(j.models) && j.models.length >= 5 && !!j.default, `status=${r.status}`);
  106. });
  107. await check('GET /api/settings(脱敏)', async () => {
  108. const r = await request(port, 'GET', '/api/settings');
  109. const j = r.json();
  110. expect(r.status === 200 && typeof j.rootDir === 'string' && typeof j.port === 'number', `status=${r.status}`);
  111. expect(!j.apiKey || j.apiKey.includes('••••'), 'apiKey 未脱敏');
  112. });
  113. await check('POST /api/settings 非法 pageSize → 400', async () => {
  114. const r = await request(port, 'POST', '/api/settings', { pageSize: 9999 });
  115. expect(r.status === 400, `status=${r.status}`);
  116. });
  117. await check('POST /api/settings 非法 delayMs → 400', async () => {
  118. const r = await request(port, 'POST', '/api/settings', { delayMs: -5 });
  119. expect(r.status === 400, `status=${r.status}`);
  120. });
  121. // ---- 采集域 ----
  122. await check('GET /api/session', async () => {
  123. const r = await request(port, 'GET', '/api/session');
  124. expect(r.status === 200 && typeof r.json().cookieConfigured === 'boolean', `status=${r.status}`);
  125. });
  126. await check('GET /api/shops(base64url root)', async () => {
  127. const r = await request(port, 'GET', `/api/shops?root=${b64Root}`);
  128. expect(r.status === 200 && Array.isArray(r.json().shops), `status=${r.status}`);
  129. });
  130. await check('GET /api/shops 非法 root → 403', async () => {
  131. const bad = Buffer.from('/tmp/elsewhere', 'utf8').toString('base64url');
  132. const r = await request(port, 'GET', `/api/shops?root=${bad}`);
  133. expect(r.status === 403, `status=${r.status}`);
  134. });
  135. await check('GET /api/scan', async () => {
  136. const r = await request(port, 'GET', `/api/scan?root=${encRoot}`);
  137. const j = r.json();
  138. expect(r.status === 200 && Array.isArray(j.shops), `status=${r.status}`);
  139. });
  140. await check('GET /api/crawl/status', async () => {
  141. const r = await request(port, 'GET', '/api/crawl/status');
  142. expect(r.status === 200 && typeof r.json().status === 'string', `status=${r.status}`);
  143. });
  144. await check('POST /api/crawl/stop(空操作)', async () => {
  145. const r = await request(port, 'POST', '/api/crawl/stop');
  146. expect(r.status === 200 && r.json().ok === true, `status=${r.status}`);
  147. });
  148. // ---- 生成/任务/历史域 ----
  149. await check('GET /api/tasks', async () => {
  150. const r = await request(port, 'GET', '/api/tasks');
  151. const j = r.json();
  152. expect(r.status === 200 && j.summary && Array.isArray(j.tasks), `status=${r.status}`);
  153. });
  154. await check('GET /api/job/未知ID → 404', async () => {
  155. const r = await request(port, 'GET', '/api/job/00000000-0000-0000-0000-000000000000');
  156. expect(r.status === 404, `status=${r.status}`);
  157. });
  158. await check('GET /api/creations', async () => {
  159. const r = await request(port, 'GET', `/api/creations?root=${encRoot}&limit=5`);
  160. const j = r.json();
  161. expect(r.status === 200 && typeof j.total === 'number' && Array.isArray(j.items), `status=${r.status}`);
  162. });
  163. await check('GET /files 越界 → 403', async () => {
  164. const r = await request(port, 'GET', `/files?path=${enc('/etc/passwd')}`);
  165. expect(r.status === 403, `status=${r.status}`);
  166. });
  167. await check('GET /files 缺参 → 400', async () => {
  168. const r = await request(port, 'GET', '/files');
  169. expect(r.status === 400, `status=${r.status}`);
  170. });
  171. // ---- 日志 ----
  172. await check('GET /api/logs', async () => {
  173. const r = await request(port, 'GET', '/api/logs');
  174. expect(r.status === 200 && Array.isArray(r.json().logs), `status=${r.status}`);
  175. });
  176. await check('POST /api/logs/clear', async () => {
  177. const r = await request(port, 'POST', '/api/logs/clear');
  178. expect(r.status === 200 && r.json().ok === true, `status=${r.status}`);
  179. });
  180. // ---- 数据报表域 ----
  181. await check('GET /api/reports/status(不限方法 GET)', async () => {
  182. const r = await request(port, 'GET', '/api/reports/status');
  183. expect(r.status === 200 && r.json().napos, `status=${r.status}`);
  184. });
  185. await check('POST /api/reports/status(不限方法 POST)', async () => {
  186. const r = await request(port, 'POST', '/api/reports/status');
  187. expect(r.status === 200, `status=${r.status}`);
  188. });
  189. await check('GET /api/reports/columns', async () => {
  190. const r = await request(port, 'GET', '/api/reports/columns');
  191. expect(r.status === 200 && Array.isArray(r.json().columns) && r.json().columns.length >= 10, `status=${r.status}`);
  192. });
  193. await check('GET /api/reports/entities', async () => {
  194. const r = await request(port, 'GET', '/api/reports/entities');
  195. expect(r.status === 200 && Array.isArray(r.json().entities), `status=${r.status}`);
  196. });
  197. await check('GET /api/reports/sync/status', async () => {
  198. const r = await request(port, 'GET', '/api/reports/sync/status');
  199. expect(r.status === 200 && typeof r.json().running === 'boolean', `status=${r.status}`);
  200. });
  201. await check('GET /api/reports/syncs', async () => {
  202. const r = await request(port, 'GET', '/api/reports/syncs');
  203. expect(r.status === 200 && Array.isArray(r.json().runs), `status=${r.status}`);
  204. });
  205. await check('GET /api/reports/daily', async () => {
  206. const r = await request(port, 'GET', '/api/reports/daily');
  207. expect(r.status === 200, `status=${r.status}`);
  208. });
  209. await check('GET /api/reports/aggregate', async () => {
  210. const r = await request(port, 'GET', '/api/reports/aggregate');
  211. expect(r.status === 200, `status=${r.status}`);
  212. });
  213. await check('GET /api/reports/export → CSV', async () => {
  214. const r = await request(port, 'GET', '/api/reports/export');
  215. expect(r.status === 200 && /text\/csv/.test(r.headers['content-type'] || ''), `status=${r.status}`);
  216. });
  217. await check('GET /api/reports/report-html → HTML', async () => {
  218. const r = await request(port, 'GET', '/api/reports/report-html');
  219. expect(r.status === 200 && /text\/html/.test(r.headers['content-type'] || ''), `status=${r.status}`);
  220. });
  221. await check('POST /api/reports/ask(有主体时跳过)', async () => {
  222. const ent = await request(port, 'GET', '/api/reports/entities');
  223. if (ent.json().entities.length > 0) return; // 有主体会真调对话模型,跳过
  224. const r = await request(port, 'POST', '/api/reports/ask', { q: 'test' });
  225. expect(r.status === 400 && r.json().code === 'ASK_NO_ENTITY', `status=${r.status}`);
  226. });
  227. // ---- 静态与路由行为 ----
  228. for (const p of ['/', '/index.html', '/app.js', '/crawl.js', '/gen.js', '/history.js', '/tasks.js', '/reports.js', '/style.css', '/vendor/echarts.min.js']) {
  229. await check(`静态 ${p}`, async () => {
  230. const r = await request(port, 'GET', p);
  231. expect(r.status === 200, `status=${r.status}`);
  232. });
  233. }
  234. await check('GET /no-such-path → 404', async () => {
  235. const r = await request(port, 'GET', '/no-such-path');
  236. expect(r.status === 404, `status=${r.status}`);
  237. });
  238. await check('DELETE /api/settings → 405', async () => {
  239. const r = await request(port, 'DELETE', '/api/settings');
  240. expect(r.status === 405, `status=${r.status}`);
  241. });
  242. // ---- 优雅停机(SIGTERM 后应自行退出) ----
  243. await check('SIGTERM 优雅停机', async () => {
  244. process.kill(child.pid, 'SIGTERM');
  245. const exited = await new Promise((resolve) => {
  246. const t = setTimeout(() => resolve(false), 8000);
  247. child.on('exit', () => { clearTimeout(t); resolve(true); });
  248. });
  249. expect(exited, 'SIGTERM 后 8 秒内未退出');
  250. });
  251. } catch (e) {
  252. results.push({ name: '(测试执行中断)', ok: false, error: e.message });
  253. } finally {
  254. try { child.kill('SIGKILL'); } catch { /* already dead */ }
  255. }
  256. const failed = results.filter((r) => !r.ok);
  257. console.log('\n========== 冒烟测试结果 ==========');
  258. for (const r of results) {
  259. console.log(`${r.ok ? '✓' : '✗'} ${r.name}${r.ok ? '' : ' ← ' + r.error}`);
  260. }
  261. console.log(`\n通过 ${results.length - failed.length}/${results.length}`);
  262. if (failed.length) {
  263. console.log('\n服务启动日志(末尾 500 字):');
  264. console.log(bootLog.slice(-500));
  265. process.exit(1);
  266. }
  267. }
  268. main().catch((e) => {
  269. console.error('冒烟脚本自身异常:', e);
  270. process.exit(1);
  271. });