fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
This commit is contained in:
Ubuntu
2026-10-19 16:16:51 +08:00
parent 601a207b1e
commit 5fa2bbfd55
252 changed files with 18656 additions and 721 deletions
+13 -2
View File
@@ -31,8 +31,19 @@ NODE
export SKIP_DEMO_SEED="${SKIP_DEMO_SEED:-1}"
export SKIP_E2E_SEED="${SKIP_E2E_SEED:-1}"
echo "[entrypoint] running migrations..."
node dist/migrate.js
# OPS-6:迁移可开关(默认 1 保持现状);0 = 跳过(多副本部署时只让一个实例跑迁移)
RUN_MIGRATIONS="${RUN_MIGRATIONS:-1}"
if [ "$RUN_MIGRATIONS" = "1" ]; then
echo "[entrypoint] running migrations..."
if ! node dist/migrate.js; then
echo "[entrypoint] ERROR: 数据库迁移失败,API 不会启动。" >&2
echo "[entrypoint] 请先备份数据库(pg_dump)并检查 migrations/ 与 schema_migrations 后重试;" >&2
echo "[entrypoint] 本脚本不自动备份/自动回滚(避免给出假的安全感)。" >&2
exit 1
fi
else
echo "[entrypoint] skip migrations (RUN_MIGRATIONS=$RUN_MIGRATIONS)"
fi
echo "[entrypoint] starting API..."
exec "$@"
+8 -1
View File
@@ -8,7 +8,14 @@ import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { currentCycleCode } = require('./test-helpers.js');
const BASE = (process.env.API_BASE || 'https://www.xdjchuanhui.com/api').replace(/\/$/, '');
const { guardTestTarget } = require('./test-target-guard.js');
const explicitApiBase = String(process.env.API_BASE || '').trim();
if (!explicitApiBase) {
console.error('未设置 API_BASE:本机请用 http://127.0.0.1:3022/api;远程需同时设置 ALLOW_REMOTE=1');
process.exit(1);
}
// OPS-2:无默认远程地址;非本机必须 ALLOW_REMOTE=1 且 TTY 确认
const BASE = guardTestTarget({ base: explicitApiBase, explicit: true, label: 'API_BASE' });
const OPERATING_BRANCH = process.env.OPERATING_BRANCH || 'BR002';
const ADMIN_PASSWORDS = ['Superadmin@123', 'SuperAdmin@123', 'E2eTest@123'];
@@ -0,0 +1,112 @@
/**
* **订单头金额一次性对账**(2026-10-19 BIZ-16)。
*
* 背景:`orders.total_amount` 是冗余汇总,行被删/退货红冲后本应重算,但历史上只有
* 缺货删行 / 退货跟随 / 售后取消履约三条路径调 `recalcOrderHeaderTotals`;
* 其余路径会留下"头与明细不一致"的存量行
* (审计样本 `ORD_API_20261018_BR002_0001`:头 253.00 / 未退货明细 249.00,差 ¥4)。
*
* 口径:**完全复用**既有重算口径(金额 = 未退货行 `amount` 之和;重量 = `sumWeightInJin`),
* 明细金额一律不动 ⇒ 不改财务口径。
*
* 用法(在 `SupplierSystem/server` 下):
* npm run reconcile:order-header-totals -- --branch BR002 # dry-run:只报告
* npm run reconcile:order-header-totals -- --branch BR002 --apply # 写回
* npm run reconcile:order-header-totals -- --branch BR002 --limit 1000
*
* 退出码:0 = 完成(dry-run 发现不一致也算完成);1 = apply 后仍不一致。
*
* ⚠️ **写操作只允许本地库**(仓库硬规则:本地脚本不得写线上);脚本会对
* `DATABASE_URL` 做主机白名单校验。
*/
import { reconcileOrderHeaderTotals } from '../src/services/orderHeaderReconcileService';
import { pool } from '../src/db';
type Args = { branch: string; apply: boolean; limit: number };
function parseArgs(argv: string[]): Args {
const out: Args = { branch: '', apply: false, limit: 500 };
for (let i = 0; i < argv.length; i += 1) {
const arg = String(argv[i] || '');
if (arg === '--branch' && argv[i + 1]) out.branch = String(argv[(i += 1)]).toUpperCase();
else if (arg.startsWith('--branch=')) out.branch = arg.slice('--branch='.length).toUpperCase();
else if (arg === '--apply') out.apply = true;
else if (arg === '--limit' && argv[i + 1]) out.limit = Number(argv[(i += 1)]);
else if (arg.startsWith('--limit=')) out.limit = Number(arg.slice('--limit='.length));
}
return out;
}
/** 硬闸门:绝不连非本地库(本脚本 `--apply` 会写库) */
function assertLocalDatabase(url: string) {
const host = (() => {
try {
return new URL(url).hostname;
} catch {
return '';
}
})();
if (!['127.0.0.1', 'localhost', '::1'].includes(host)) {
throw new Error(`拒绝运行:DATABASE_URL 指向非本地库 (${host || 'unknown'})`);
}
}
const money = (n: number) => (Math.round((Number(n) || 0) * 100) / 100).toFixed(2);
async function main() {
const url = String(process.env.DATABASE_URL || '');
if (!url) {
throw new Error('缺少 DATABASE_URL(用 `npm run reconcile:order-header-totals` 会带 --env-file=.env)');
}
assertLocalDatabase(url);
const args = parseArgs(process.argv.slice(2));
if (!args.branch) {
console.error(
'用法:npm run reconcile:order-header-totals -- --branch BR002 [--apply] [--limit 500]'
);
process.exitCode = 2;
return;
}
const result = await reconcileOrderHeaderTotals({
branchCode: args.branch,
apply: args.apply,
limit: Number.isFinite(args.limit) ? args.limit : 500,
});
console.log(
`[reconcile] 分公司 ${result.branchCode}(${result.apply ? 'APPLY 写回' : 'DRY-RUN 只报告'},` +
`扫描上限 ${result.limit}):发现不一致 ${result.mismatchCount} 单,修后仍不一致 ${result.remaining} 单`
);
for (const mismatch of result.mismatches) {
console.log(
` · ${mismatch.orderCode}:头 ${money(mismatch.headerAmount)} / 明细 ${money(mismatch.itemAmount)}` +
`(差 ${mismatch.diff > 0 ? '+' : ''}${money(mismatch.diff)})`
);
}
for (const fixed of result.fixed) {
console.log(
` ✔ ${fixed.orderCode}:头 ${money(fixed.beforeAmount)} → ${money(fixed.afterAmount)},` +
`重量 → ${fixed.afterWeight} 斤`
);
}
if (!args.apply && result.mismatchCount > 0) {
console.log('[reconcile] dry-run 未改库;确认后用 `--apply` 写回。');
}
console.log(`[reconcile] JSON:${JSON.stringify(result)}`);
if (args.apply && result.remaining > 0) {
process.exitCode = 1;
}
}
main()
.catch((error) => {
console.error('[reconcile] 失败:', error instanceof Error ? error.message : error);
process.exitCode = 1;
})
.finally(async () => {
// 只用到一个连接池(src/db):脚本跑完主动收口,避免 tsx 挂住
await pool.end().catch(() => undefined);
});
+10 -1
View File
@@ -5,7 +5,16 @@
const { currentCycleCode } = require('./test-helpers.js');
const BASE = process.env.API_BASE || 'http://127.0.0.1:3001/api';
const { guardTestTarget } = require('./test-target-guard.js');
// OPS-2:默认打本系统 API(3022),且非本机目标必须 API_BASE + ALLOW_REMOTE=1(TTY 确认)
const DEFAULT_TEST_API_BASE = 'http://127.0.0.1:3022/api';
const explicitApiBase = String(process.env.API_BASE || '').trim();
const BASE = guardTestTarget({
base: explicitApiBase || DEFAULT_TEST_API_BASE,
explicit: Boolean(explicitApiBase),
label: 'API_BASE',
});
const isLocalApi = BASE.includes('127.0.0.1') || BASE.includes('localhost');
const OPERATING_BRANCH = process.env.E2E_TEST_BRANCH || process.env.OPERATING_BRANCH || 'BR002';
+13 -4
View File
@@ -1,10 +1,19 @@
#!/usr/bin/env node
/**
* 小程序全流程 API 探针(生产/本地均可)
* 用法: node server/scripts/test-miniprogram-flow.mjs
* 环境: API_BASE 默认 https://www.xdjchuanhui.com/api
* 小程序全流程 API 探针(**无默认目标**,必须显式指定)
* 用法: API_BASE=http://127.0.0.1:3022/api node server/scripts/test-miniprogram-flow.mjs
* 远程: API_BASE=https://... ALLOW_REMOTE=1(非 TTY 拒绝)
*/
const BASE = (process.env.API_BASE || 'https://www.xdjchuanhui.com/api').replace(/\/$/, '');
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { guardTestTarget } = require('./test-target-guard.js');
const explicitApiBase = String(process.env.API_BASE || '').trim();
if (!explicitApiBase) {
console.error('未设置 API_BASE:本机请用 http://127.0.0.1:3022/api;远程需同时设置 ALLOW_REMOTE=1');
process.exit(1);
}
const BASE = guardTestTarget({ base: explicitApiBase, explicit: true, label: 'API_BASE' });
const PASSWORDS = [
process.env.MP_TEST_PASSWORD,
+10 -1
View File
@@ -5,7 +5,16 @@
const { currentCycleCode } = require('./test-helpers.js');
const BASE = process.env.API_BASE || 'http://127.0.0.1:3001/api';
const { guardTestTarget } = require('./test-target-guard.js');
// OPS-2:默认打本系统 API(3022);非本机目标必须 API_BASE + ALLOW_REMOTE=1(TTY 确认)
const DEFAULT_TEST_API_BASE = 'http://127.0.0.1:3022/api';
const explicitApiBase = String(process.env.API_BASE || '').trim();
const BASE = guardTestTarget({
base: explicitApiBase || DEFAULT_TEST_API_BASE,
explicit: Boolean(explicitApiBase),
label: 'API_BASE',
});
const results = [];
function pass(name, detail = '') {
+74
View File
@@ -0,0 +1,74 @@
'use strict';
/**
* 测试脚本目标环境硬守卫(OPS-2,2026-10-19)。
*
* 背景:`test-functionality.js` / `test-page-flows.js` 旧默认 `http://127.0.0.1:3001/api`
* (主系统 API),两个小程序探针默认 `https://www.xdjchuanhui.com/api`(生产)——
* 本机跑一次测试就可能把生产数据打一遍。
*
* 规则:
* · 默认只允许本机(127.0.0.1 / localhost / ::1),默认端口 3022;
* · 目标非本机时必须 **显式** API_BASE + ALLOW_REMOTE=1,否则 exit 1;
* · ALLOW_REMOTE=1 也要 3 秒倒计时确认;非交互(stdin 非 TTY)直接硬失败。
*/
function isLoopbackTarget(base) {
try {
const host = new URL(base).hostname.replace(/^\[|\]$/g, '').toLowerCase();
return host === '127.0.0.1' || host === 'localhost' || host === '::1';
} catch {
return false;
}
}
function sleepBlocking(ms) {
// 无依赖阻塞等待(用于 TTY 下 3 秒倒计时);非 TTY 不会走到这里
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
/**
* @param {{ base: string, explicit?: boolean, label?: string }} options
* @returns {string} 归一后的 base(无尾斜杠)
*/
function guardTestTarget(options) {
const raw = String(options.base || '').trim();
const base = raw.replace(/\/+$/, '');
console.log(`[test] target: ${base}`);
if (!base) {
console.error('[test] 未设置目标地址:本机默认 http://127.0.0.1:3022/api');
process.exit(1);
}
if (isLoopbackTarget(base)) {
/**
* O-12.10:本机 3001 是**主系统** API(AI 生鲜配送),不是本系统 3022。
* 旧守卫把任何 127.0.0.1 都当"安全本地" ⇒ 默认就可能把主系统数据打一遍。
* 需要显式 ALLOW_MAIN_SYSTEM=1 才放行(并在 TTY 下提示)。
*/
let port = '';
try {
const parsed = new URL(base);
port = parsed.port || (parsed.protocol === 'https:' ? '443' : '80');
} catch {
/* isLoopbackTarget 已解析过,理论上不会到这里 */
}
if (port === '3001' && process.env.ALLOW_MAIN_SYSTEM !== '1') {
console.error('检测到目标为本机 3001(主系统 API),已拒绝;如确需测试主系统请设置 ALLOW_MAIN_SYSTEM=1');
process.exit(1);
}
return base;
}
if (!options.explicit || process.env.ALLOW_REMOTE !== '1') {
console.error('拒绝访问非本地目标,如确需请设置 ALLOW_REMOTE=1');
process.exit(1);
}
if (!process.stdin.isTTY) {
console.error('[test] 非交互环境禁止访问非本地目标(即使 ALLOW_REMOTE=1)');
process.exit(1);
}
console.log(`[test] 目标非本地(${options.label || 'remote'}):${base};3 秒后继续,Ctrl+C 取消...`);
sleepBlocking(3000);
return base;
}
module.exports = { guardTestTarget, isLoopbackTarget };