/** * 服务端路由烟雾测试(不依赖 funjia-server / cuid / lodash)。 * * 用 vm 在内存中加载路由源码,把外部依赖替换成桩,再配一个内存版 db, * 直接调用真实 handler 做断言。重点回归「整库被清空」这个致命缺陷。 * * node smoke-test.mjs * * 退出码 0 = 全部通过,1 = 有用例失败。 */ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { dirname, join } from "node:path"; import vm from "node:vm"; const here = dirname(fileURLToPath(import.meta.url)); // ── 沙箱内可用的桩 ──────────────────────────────────────────────────── const sandbox = { console, Math, Date, JSON, Object, Array, String, Number, Boolean, Promise, Error, TypeError, setTimeout, __cuid: () => "id-" + Math.random().toString(36).slice(2, 10), __lodashMerge: (target, source) => Object.assign(target, source), __db: null, }; sandbox.globalThis = sandbox; vm.createContext(sandbox); /** 把路由源码的 import 改写成沙箱内的全局引用 */ const rewrite = (src) => { let out = src; // default 导入的第三方包 out = out.replace( /import\s+cuid\s+from\s+["'][^"']*cuid["'];?/g, "const cuid = globalThis.__cuid;" ); out = out.replace( /import\s+_\s+from\s+["'][^"']*lodash["'];?/g, "const _ = { merge: (t, s) => globalThis.__lodashMerge(t, s) };" ); // funjia-server 的具名导入(支持 `X as Y` 别名) out = out.replace( /import\s*\{([^}]*)\}\s*from\s*["']funjia-server[^"']*["'];?/g, (m, names) => names .split(",") .map((n) => n.trim()) .filter(Boolean) .map((n) => { const [orig, alias] = n.split(/\s+as\s+/).map((s) => s.trim()); return `const ${alias || orig} = globalThis.__${orig};`; }) .join("\n") ); // 相对导入 helpers.mjs(支持 `getTable as getTableRaw` 别名) out = out.replace( /import\s*\{([^}]*)\}\s*from\s*["'][^"']*helpers\.mjs["'];?/g, (m, names) => names .split(",") .map((n) => n.trim()) .filter(Boolean) .map((n) => { const [orig, alias] = n.split(/\s+as\s+/).map((s) => s.trim()); return `const ${alias || orig} = globalThis.__helpers.${orig};`; }) .join("\n") ); // export default Foo → 挂到 __mod out = out.replace(/export\s+default\s+([A-Za-z_$][\w$]*)\s*;?/g, "globalThis.__mod = $1;"); return out; }; const loadModule = (relPath) => { sandbox.__mod = undefined; const src = rewrite(readFileSync(join(here, relPath), "utf8")); // 每个模块包一层 IIFE,避免不同文件的顶层 const 在共享沙箱里冲突 vm.runInContext(`(function () {\n${src}\n})();`, sandbox, { filename: relPath }); return sandbox.__mod; }; // ── 先加载 helpers.mjs ──────────────────────────────────────────────── { let src = readFileSync(join(here, "routers/helpers.mjs"), "utf8"); src = src.replace(/export\s+const\s+([A-Za-z_$][\w$]*)\s*=/g, "const $1 ="); src += "\nglobalThis.__helpers = { getTable, pickFilters, matchRow, paginate, listResponse, omitSensitive };"; vm.runInContext(src, sandbox, { filename: "routers/helpers.mjs" }); } // ── getDb 桩:读 sandbox.__db ───────────────────────────────────────── sandbox.__getDb = async () => sandbox.__db; // ── 载入被测路由 ────────────────────────────────────────────────────── const getEmployee = loadModule("routers/anki/employee.mjs"); const getNotice = loadModule("routers/anki/notice.mjs"); const getDynamic = loadModule("routers/dynamic.mjs"); // ── 假 router:收集路由表 ───────────────────────────────────────────── const routes = []; const router = {}; for (const m of ["get", "post", "put", "delete"]) { router[m] = (path, handler) => routes.push({ method: m, path, handler }); } getEmployee(router); getNotice(router); getDynamic(router); const find = (method, path) => { const r = routes.find((x) => x.method === method && x.path === path); if (!r) throw new Error(`路由未注册: ${method.toUpperCase()} ${path}`); return r.handler; }; // ── 测试工具 ────────────────────────────────────────────────────────── const makeDb = (seed) => ({ data: JSON.parse(JSON.stringify(seed)), write: async () => {}, }); const makeCtx = ({ params = {}, query = {}, body = {} } = {}) => ({ type: "", body: undefined, params, request: { query, body }, }); let passed = 0; let failed = 0; const test = async (name, fn) => { try { await fn(); passed++; console.log(` PASS ${name}`); } catch (err) { failed++; console.log(` FAIL ${name}`); console.log(` ${err.message}`); } }; /** * 断言是「空数组」。 * 不能直接用 assert.deepEqual(x, []):沙箱里创建的数组与主 realm 的 `[]` * 原型不同,Node 会判定为「结构相同但非同一引用」。这里只校验实质语义。 */ const assertEmptyArray = (value, label = "值") => { assert.ok(Array.isArray(value), `${label} 不是数组: ${JSON.stringify(value)}`); assert.equal(value.length, 0, `${label} 应为空数组,实际长度 ${value.length}`); }; const seed = { employee: [ { id: "e1", userName: "admin", pwd: "123456", realName: "管理员" }, { id: "e2", userName: "staff", pwd: "654321", realName: "员工甲" }, ], Notice: [{ id: "n1", title: "公告一", sort: 1 }], leaseRecords: [{ id: "l1", name: "租赁单" }], }; // ══ 用例 ══════════════════════════════════════════════════════════════ console.log("\n=== 服务端路由烟雾测试 ===\n"); console.log("[员工路由]"); await test("list 不泄漏 pwd 明文", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ body: {} }); await find("post", "/api/employee/list")(ctx); assert.equal(ctx.body.code, 0); assert.equal(ctx.body.total, 2); for (const row of ctx.body.data) { assert.ok(!("pwd" in row), `pwd 泄漏: ${JSON.stringify(row)}`); } }); await test("list 在空表时不抛 500", async () => { sandbox.__db = makeDb({}); const ctx = makeCtx({ body: {} }); await find("post", "/api/employee/list")(ctx); assert.equal(ctx.body.code, 0); assert.equal(ctx.body.total, 0); assertEmptyArray(ctx.body.data, "列表数据"); }); await test("login 成功返回用户但不含 pwd", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ body: { userName: "admin", pwd: "123456" } }); await find("post", "/api/employee/login")(ctx); assert.equal(ctx.body.code, 0); assert.equal(ctx.body.data.userName, "admin"); assert.ok(!("pwd" in ctx.body.data)); }); await test("login 失败不区分账号/密码错误(防枚举)", async () => { sandbox.__db = makeDb(seed); const a = makeCtx({ body: { userName: "nobody", pwd: "x" } }); const b = makeCtx({ body: { userName: "admin", pwd: "wrong" } }); await find("post", "/api/employee/login")(a); await find("post", "/api/employee/login")(b); assert.equal(a.body.code, 1); assert.equal(b.body.code, 1); assert.equal(a.body.msg, b.body.msg); }); await test("add 拒绝重复用户名", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ body: { userName: "admin", pwd: "x" } }); await find("post", "/api/employee/add")(ctx); assert.equal(ctx.body.code, 1); assert.equal(sandbox.__db.data.employee.length, 2); }); await test("add 忽略请求体传入的 id / createTime", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ body: { userName: "newbie", id: "HACKED", createTime: "1970-01-01" } }); await find("post", "/api/employee/add")(ctx); const added = sandbox.__db.data.employee.find((x) => x.userName === "newbie"); assert.ok(added, "新员工未写入"); assert.notEqual(added.id, "HACKED"); assert.notEqual(added.createTime, "1970-01-01"); }); await test("upd 不能覆盖主键 id,且能改动业务字段", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ body: { id: "e1", realName: "改名了", pwd: "newpwd" } }); await find("post", "/api/employee/upd")(ctx); const row = sandbox.__db.data.employee.find((x) => x.id === "e1"); assert.ok(row, "e1 丢失"); assert.equal(row.id, "e1"); assert.equal(row.realName, "改名了"); }); await test("upd 目标不存在时返回业务错误而非 500", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ body: { id: "not-exist", realName: "x" } }); await find("post", "/api/employee/upd")(ctx); assert.equal(ctx.body.code, 1); }); await test("delete 只删指定记录并返回条数", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ body: { ids: ["e1", "ghost"] } }); await find("post", "/api/employee/delete")(ctx); assert.equal(ctx.body.code, 0); assert.equal(ctx.body.data.deleted, 1); assert.equal(sandbox.__db.data.employee.length, 1); }); await test("delete 空 ids 被拒绝", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ body: { ids: [] } }); await find("post", "/api/employee/delete")(ctx); assert.equal(ctx.body.code, 1); }); console.log("\n[通知路由]"); await test("Notice list 不因空表崩溃", async () => { sandbox.__db = makeDb({}); const ctx = makeCtx({ body: {} }); await find("post", "/api/Notice/list")(ctx); assert.equal(ctx.body.code, 0); assertEmptyArray(ctx.body.data, "列表数据"); }); console.log("\n[★ 致命缺陷回归:整库清空]"); await test("dynamic.upd 目标表缺失时不清空整库", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ params: { tableName: "brandNewTable" }, body: { id: "x", name: "y" } }); await find("post", "/api/dynamic/upd/:tableName")(ctx); assert.ok(Array.isArray(sandbox.__db.data.employee), "employee 表被清空了!"); assert.equal(sandbox.__db.data.employee.length, 2); assert.ok(Array.isArray(sandbox.__db.data.Notice), "Notice 表被清空了!"); assert.equal(sandbox.__db.data.Notice.length, 1); assert.ok(Array.isArray(sandbox.__db.data.leaseRecords), "leaseRecords 表被清空了!"); assertEmptyArray(sandbox.__db.data.brandNewTable, "缺失的新表"); }); await test("dynamic.delete 目标表缺失时不清空整库", async () => { sandbox.__db = makeDb(seed); const ctx = makeCtx({ params: { tableName: "anotherNewTable" }, body: { ids: ["a"] } }); await find("post", "/api/dynamic/delete/:tableName")(ctx); assert.equal(sandbox.__db.data.employee.length, 2, "employee 表被清空了!"); assert.equal(sandbox.__db.data.Notice.length, 1, "Notice 表被清空了!"); }); await test("dynamic.list 空表返回空数组而非 500", async () => { sandbox.__db = makeDb({}); const ctx = makeCtx({ params: { tableName: "whatever" }, body: {} }); await find("post", "/api/dynamic/list/:tableName")(ctx); assert.equal(ctx.body.code, 0); assertEmptyArray(ctx.body.data, "列表数据"); assert.equal(ctx.body.total, 0); }); await test("dynamic.add 忽略请求体 id / createTime", async () => { sandbox.__db = makeDb({ whatever: [] }); const ctx = makeCtx({ params: { tableName: "whatever" }, body: { id: "HACK", createTime: "0" } }); await find("post", "/api/dynamic/add/:tableName")(ctx); const row = sandbox.__db.data.whatever[0]; assert.ok(row, "未写入"); assert.notEqual(row.id, "HACK"); assert.notEqual(row.createTime, "0"); }); await test("dynamic 分页参数生效", async () => { sandbox.__db = makeDb({ big: Array.from({ length: 25 }, (_, i) => ({ id: `b${i}`, n: i })) }); const ctx = makeCtx({ params: { tableName: "big" }, body: { page: 2, pageSize: 10 } }); await find("post", "/api/dynamic/list/:tableName")(ctx); assert.equal(ctx.body.total, 25); assert.equal(ctx.body.data.length, 10); assert.equal(ctx.body.data[0].id, "b10"); }); // ── 汇总 ────────────────────────────────────────────────────────────── console.log(`\n=== 结果: ${passed} 通过 / ${failed} 失败 ===\n`); process.exit(failed === 0 ? 0 : 1);