- 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 超长修复
312 lines
15 KiB
TypeScript
312 lines
15 KiB
TypeScript
import express from 'express';
|
||
import cors from 'cors';
|
||
import helmet from 'helmet';
|
||
import rateLimit, { ipKeyGenerator } from 'express-rate-limit';
|
||
import { authMiddleware, AuthRequest } from './middleware/auth';
|
||
import { getDistributedLockStats } from './services/distributedLock';
|
||
import fs from 'fs';
|
||
import path from 'path';
|
||
import { config } from './config';
|
||
import { isArkConfigured } from './env';
|
||
import { isVoiceTranscriptionConfigured } from './services/speechService';
|
||
import authRoutes from './routes/auth';
|
||
import dataRoutes from './routes/data';
|
||
import storageRoutes from './routes/storage';
|
||
import functionRoutes from './routes/functions';
|
||
import mobileRoutes from './routes/mobile';
|
||
import purchaserRoutes from './routes/purchasers';
|
||
import supplierRoutes from './routes/suppliers';
|
||
import supplierApiRoutes from './routes/supplier/supplierApiRoutes';
|
||
import accountRoutes from './routes/accounts';
|
||
import dashboardRoutes from './routes/dashboard';
|
||
import workflowRoutes from './routes/workflow';
|
||
import { warmRlsRoleCache } from './db';
|
||
import { assertTenantRlsReady } from './services/tenantRlsGuard';
|
||
import modulesRoutes from './routes/modules';
|
||
import catalogRoutes from './routes/catalog';
|
||
import rolesRoutes from './routes/roles';
|
||
import skuImageRoutes from './routes/skuImage';
|
||
import menuGroupIconRoutes from './routes/menuGroupIcon';
|
||
import mainSystemIntegrationRoutes from './routes/mainSystemIntegration';
|
||
import publicTraceRoutes from './routes/publicTrace';
|
||
import publicDeliveryNoteRoutes from './routes/publicDeliveryNote';
|
||
import orderEntryAgentRoutes from './routes/orderEntryAgent';
|
||
import { tenantDbMiddleware } from './middleware/tenantDbMiddleware';
|
||
import { operationAuditMiddleware } from './middleware/operationAuditMiddleware';
|
||
import { startScheduledJobs } from './services/scheduledJobs';
|
||
import { ensureRoleDefinitionsSchema } from './services/roleDefinitionService';
|
||
import { loadTenantContext } from './services/tenantScope';
|
||
import { syncPermissionCatalog } from './services/permissionCatalogService';
|
||
import { initRedisConnection, isRedisConfigured, pingRedis } from './services/redisClient';
|
||
import { listHotCacheTables } from './services/queryCacheService';
|
||
import { initNotificationStreamBridge, getNotificationStreamStats } from './services/notificationStreamService';
|
||
import { getStorageProviderInfo } from './services/storageProvider';
|
||
import { ensureInspectionResultFolders } from './services/storageUploadService';
|
||
import { INSPECTION_PHOTO_BUCKETS } from './services/storageBucketConfig';
|
||
|
||
if (config.storage.provider === 'local') {
|
||
fs.mkdirSync(config.storageDir, { recursive: true });
|
||
}
|
||
|
||
export function createApp() {
|
||
const app = express();
|
||
/**
|
||
* SEC-3(2026-10-19):不再无条件 `trust proxy = 1`。
|
||
* 取值由 `TRUST_PROXY` 决定(默认 `loopback`,只信同机代理);无条件信任会让直连请求
|
||
* 用 `X-Forwarded-For` 伪造 `req.ip` ⇒ 登录限流/审计 IP 可被绕过。
|
||
* 限流键 `loginKeyGenerator` 本身仍只用 `req.ip`(由 `loginAuditIpHardening.test.ts` 钉住,勿回退)。
|
||
*/
|
||
app.set('trust proxy', config.trustProxy);
|
||
// 开发环境放宽 CSP,生产环境严格限制
|
||
const isDev = process.env.NODE_ENV !== 'production';
|
||
app.use(
|
||
helmet({
|
||
contentSecurityPolicy: {
|
||
directives: {
|
||
defaultSrc: ["'self'"],
|
||
scriptSrc: isDev ? ["'self'", "'unsafe-inline'", "'unsafe-eval'"] : ["'self'"],
|
||
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://cdn.tailwindcss.com"],
|
||
fontSrc: ["'self'", "https://fonts.gstatic.com", "data:"],
|
||
imgSrc: ["'self'", "data:", "blob:", "https:"],
|
||
connectSrc: ["'self'", "ws:", "wss:", "https:"],
|
||
frameAncestors: ["'none'"],
|
||
},
|
||
},
|
||
crossOriginResourcePolicy: { policy: 'cross-origin' },
|
||
})
|
||
);
|
||
app.use(cors({ origin: config.corsOrigins, credentials: true }));
|
||
// A11: 普通 JSON 收紧;文件/语音走 multer 独立上限
|
||
// webhook 验签必须基于**原始 body 字节**,所以该路径先挂 raw 解析(放在 json 之前)
|
||
app.use('/api/integration/main-system/webhook', express.raw({ type: '*/*', limit: '2mb' }));
|
||
// 库存入库·多商品识别:一次可上传多张图片(base64),仅这两个路由放宽 body 上限;其余仍 2mb
|
||
app.use('/api/workflow/inventory/recognize-lines', express.json({ limit: '20mb' }));
|
||
app.use('/api/mobile/inventory/recognize-lines', express.json({ limit: '20mb' }));
|
||
app.use(express.json({ limit: '2mb' }));
|
||
|
||
function loginKeyGenerator(req: {
|
||
ip?: string;
|
||
body?: Record<string, unknown>;
|
||
}) {
|
||
// 限流维度只取 Express 解析后的 req.ip(其取值由上方 app.set('trust proxy', …) 决定)。
|
||
// ⚠️ 不得回退读原始 `x-forwarded-for`:nginx/CLB 用 `$proxy_add_x_forwarded_for` 是
|
||
// **追加**语义,第一段永远是客户端自填的 → 伪造该头即可每次换一个新桶,限流形同虚设
|
||
// (2026-09-24 实测:本地直连时换 XFF 即 remaining 重置为 29)。
|
||
// 注:若被**直连**(绕过代理),trust proxy 会把直连对端当可信代理,req.ip 仍可由
|
||
// 请求头决定 —— 那要靠收窄 trust proxy(只信已知代理)+ 安全组只放行代理来源来解决,
|
||
// 不在本函数职责内。
|
||
const rawIp = String(req.ip || '').trim();
|
||
const ip = rawIp ? ipKeyGenerator(rawIp) : 'unknown';
|
||
const login = String(
|
||
req.body?.username || req.body?.login_name || req.body?.email || ''
|
||
)
|
||
.trim()
|
||
.toLowerCase();
|
||
return login ? `${ip}|${login}` : ip;
|
||
}
|
||
|
||
// A9: 登录限速按 IP + 登录名;另保留纯 IP 兜底
|
||
const loginLimiter = rateLimit({
|
||
windowMs: 10 * 60 * 1000,
|
||
limit: 30,
|
||
standardHeaders: true,
|
||
legacyHeaders: false,
|
||
keyGenerator: loginKeyGenerator as any,
|
||
message: { error: 'too_many_requests', error_description: '尝试次数过多,请稍后再试' },
|
||
});
|
||
const loginIpLimiter = rateLimit({
|
||
windowMs: 10 * 60 * 1000,
|
||
limit: 80,
|
||
standardHeaders: true,
|
||
legacyHeaders: false,
|
||
message: { error: 'too_many_requests', error_description: '尝试次数过多,请稍后再试' },
|
||
});
|
||
app.use('/api/auth/token', loginIpLimiter, loginLimiter);
|
||
app.use('/api/auth/unified-login', loginIpLimiter, loginLimiter);
|
||
app.use('/api/mobile/login', loginIpLimiter, loginLimiter);
|
||
app.use('/api/supplier/login', loginIpLimiter, loginLimiter);
|
||
app.use('/api/supplier/oauth/token', loginIpLimiter, loginLimiter);
|
||
|
||
// AI/函数接口限速:防滥用刷成本
|
||
const functionLimiter = rateLimit({
|
||
windowMs: 60 * 1000,
|
||
limit: 60,
|
||
standardHeaders: true,
|
||
legacyHeaders: false,
|
||
message: { data: null, error: { message: '请求过于频繁,请稍后再试' } },
|
||
});
|
||
app.use('/api/functions', functionLimiter);
|
||
|
||
// M3:公开健康检查只回**最小信息**。
|
||
// 原实现(未鉴权)把 queryCacheTables(热点表名列表)、storage(provider + **桶名** + endpoint)、
|
||
// redis/ark/语音状态、notificationStream(在线连接数)全部公开 —— 等于对外报内部拓扑。
|
||
// 全仓核查:前端 / 小程序 / 安卓**零调用**;运维与部署脚本一律 `curl -sf` 只看 HTTP 码,
|
||
// 仅 deploy-prod.ps1 读 `status` 字段(保留)。故公开面只留 status + time。
|
||
app.get('/api/health', (_req, res) => {
|
||
res.json({ status: 'ok', time: new Date().toISOString() });
|
||
});
|
||
|
||
// M3:完整诊断(原 /api/health 载荷)挪到**需登录令牌 + 超管/运维**的端点。
|
||
// SEC-6(2026-10-19 T9):普通登录用户不得读内部拓扑(桶名/endpoint/热点表/在线连接数/锁统计)。
|
||
app.get('/api/health/details', authMiddleware, async (req: AuthRequest, res) => {
|
||
// SEC-6:mobile/受限 token 即使角色是 super_admin/ops 也不得读完整拓扑
|
||
if (req.tokenScope === 'mobile') {
|
||
return res.status(403).json({ error: 'forbidden', error_description: '移动端受限令牌不可访问完整诊断' });
|
||
}
|
||
const ctx = await loadTenantContext(req.userId);
|
||
const allowed =
|
||
Boolean(ctx?.isSuperAdmin) ||
|
||
Boolean(ctx?.roles?.includes('super_admin')) ||
|
||
Boolean(ctx?.roles?.includes('ops'));
|
||
if (!ctx || !allowed) {
|
||
return res.status(403).json({ error: 'forbidden', error_description: '仅超管/运维可查看完整诊断' });
|
||
}
|
||
res.json({
|
||
status: 'ok',
|
||
time: new Date().toISOString(),
|
||
arkConfigured: isArkConfigured(),
|
||
speechConfigured: await isVoiceTranscriptionConfigured(),
|
||
redisConfigured: isRedisConfigured(),
|
||
redisConnected: await pingRedis(),
|
||
queryCacheTables: listHotCacheTables(),
|
||
notificationStream: getNotificationStreamStats(),
|
||
storage: getStorageProviderInfo(),
|
||
// M11 可观测性:分布式锁统计(进程内;含回退次数与「持有超过 ttlSec」次数)
|
||
locks: getDistributedLockStats(),
|
||
});
|
||
});
|
||
|
||
// 变更类 API 结束后写操作日志(依赖后续路由内 auth 设置 userId)
|
||
app.use(operationAuditMiddleware);
|
||
|
||
app.use('/api/auth', tenantDbMiddleware, authRoutes);
|
||
app.use('/api/data', dataRoutes);
|
||
app.use('/api/storage', storageRoutes);
|
||
app.use('/api/sku-image', tenantDbMiddleware, skuImageRoutes);
|
||
app.use('/api/menu-group-icon', tenantDbMiddleware, menuGroupIconRoutes);
|
||
app.use('/api/functions', tenantDbMiddleware, functionRoutes);
|
||
app.use('/api/mobile', tenantDbMiddleware, mobileRoutes);
|
||
app.use('/api/purchasers', tenantDbMiddleware, purchaserRoutes);
|
||
/** 供应商开放 API(singular);管理端开户仍为 /api/suppliers */
|
||
app.use('/api/supplier', tenantDbMiddleware, supplierApiRoutes);
|
||
app.use('/api/suppliers', tenantDbMiddleware, supplierRoutes);
|
||
app.use('/api/accounts', tenantDbMiddleware, accountRoutes);
|
||
app.use('/api/dashboard', tenantDbMiddleware, dashboardRoutes);
|
||
app.use('/api/workflow', workflowRoutes);
|
||
app.use('/api/mcp/order-entry', tenantDbMiddleware, orderEntryAgentRoutes);
|
||
app.use('/api/integration', tenantDbMiddleware, mainSystemIntegrationRoutes);
|
||
app.use('/api/public', publicTraceRoutes);
|
||
app.use('/api/public', publicDeliveryNoteRoutes);
|
||
app.use('/api/modules', modulesRoutes);
|
||
app.use('/api/catalog', tenantDbMiddleware, catalogRoutes);
|
||
app.use('/api/roles', rolesRoutes);
|
||
|
||
// SEC-8(2026-10-19 T9):/api 未命中路由统一 JSON 404(不再回 Express 默认 HTML)
|
||
app.use('/api', (_req, res) => {
|
||
res.status(404).json({ data: null, error: { message: '接口不存在', code: 'not_found' } });
|
||
});
|
||
|
||
// SEC-8(2026-10-19 T9):全局错误兜底 —— 统一 JSON,不把堆栈/内部细节返回客户端。
|
||
// 放在所有路由之后、静态资源/监听之前;4xx 业务错误仍由各路由自行返回。
|
||
app.use((err: any, req: express.Request, res: express.Response, _next: express.NextFunction) => {
|
||
const status = Number(err?.status || err?.statusCode || 500);
|
||
const code = status >= 500 ? 'internal_error' : String(err?.code || 'request_failed');
|
||
const message =
|
||
status >= 500 ? '服务器内部错误,请稍后重试' : String(err?.message || '请求失败');
|
||
console.error(`[express-error] ${req.method} ${req.originalUrl} status=${status}`, err);
|
||
// 已开始输出(SSE/流式):直接返回会让连接悬挂;销毁连接让客户端立即感知失败
|
||
if (res.headersSent) {
|
||
try {
|
||
res.destroy();
|
||
} catch {
|
||
// ignore
|
||
}
|
||
return;
|
||
}
|
||
res.status(status).json({ data: null, error: { message, code } });
|
||
});
|
||
|
||
const isProduction = process.env.NODE_ENV === 'production';
|
||
if (isProduction && config.serveStatic) {
|
||
const staticDir = path.join(__dirname, '..', '..', 'dist');
|
||
if (fs.existsSync(staticDir)) {
|
||
app.use(express.static(staticDir));
|
||
app.get('*', (req, res, next) => {
|
||
if (req.path.startsWith('/api')) {
|
||
next();
|
||
return;
|
||
}
|
||
res.sendFile(path.join(staticDir, 'index.html'));
|
||
});
|
||
console.log(`Serving frontend from ${staticDir}`);
|
||
} else {
|
||
console.warn(`Frontend dist not found at ${staticDir}`);
|
||
}
|
||
}
|
||
return app;
|
||
}
|
||
|
||
export const app = createApp();
|
||
|
||
if (require.main === module) {
|
||
void (async () => {
|
||
try {
|
||
await warmRlsRoleCache();
|
||
await assertTenantRlsReady();
|
||
} catch (err: any) {
|
||
console.error(err?.message || err);
|
||
if (String(process.env.RLS_REQUIRED ?? '1').trim() !== '0') {
|
||
console.error('[rls] RLS_REQUIRED=1,拒绝启动(请先 npm run db:migrate)');
|
||
process.exit(1);
|
||
}
|
||
}
|
||
|
||
app.listen(config.port, config.host, () => {
|
||
const isProduction = process.env.NODE_ENV === 'production';
|
||
const mode = isProduction
|
||
? config.serveStatic
|
||
? 'production(all-in-one)'
|
||
: 'production(api-only)'
|
||
: 'development';
|
||
// SEC-3:打印**实际**监听地址(默认 127.0.0.1,容器用 HOST=0.0.0.0 覆盖)
|
||
console.log(`API server running on ${config.host}:${config.port} (${mode})`);
|
||
// 显眼地打出去连的是哪个主系统:本地开发是 127.0.0.1:3001,上线后是线上地址。
|
||
// 这一行是为了防「以为在连本地、其实指着生产」——看到不像本地的地址就停下来确认。
|
||
// 注意:登录已与主系统解耦(一律本地账号),这里只影响拉取/回写,与能否登录无关。
|
||
if (config.mainSystem.baseUrl) {
|
||
const looksLocal = /^https?:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/.test(config.mainSystem.baseUrl);
|
||
console.log(
|
||
`[main-system] 主系统对接地址:${config.mainSystem.baseUrl}` +
|
||
`(${looksLocal ? '本地' : '⚠️ 非本地,请确认是预期环境'};超时 ${config.mainSystem.timeoutMs}ms)`
|
||
);
|
||
} else {
|
||
console.warn('[main-system] 未配置 MAIN_SYSTEM_BASE_URL:不会拉取主系统的货(不影响本地登录)');
|
||
}
|
||
void ensureRoleDefinitionsSchema().catch((err) => {
|
||
console.warn('role_definitions schema ensure skipped:', err?.message || err);
|
||
});
|
||
void syncPermissionCatalog().catch((err) => {
|
||
console.warn('permission catalog sync skipped:', err?.message || err);
|
||
});
|
||
void initRedisConnection().then(async (ok) => {
|
||
if (isRedisConfigured()) {
|
||
console.log(
|
||
ok ? 'Redis connected (query cache enabled)' : 'Redis unavailable (query cache disabled)'
|
||
);
|
||
}
|
||
await initNotificationStreamBridge();
|
||
});
|
||
// 环境隔离自检:MAIN_SYSTEM_BASE_URL 指向非本机 + 开着自动拉单/回写 ⇒ 醒目告警(2026-10-13)
|
||
void import('./services/mainSystem/config')
|
||
.then(({ warnIfRemoteMainSystemWithWriteback }) => warnIfRemoteMainSystemWithWriteback())
|
||
.catch(() => undefined);
|
||
startScheduledJobs();
|
||
void Promise.all(
|
||
INSPECTION_PHOTO_BUCKETS.map((bucket) => ensureInspectionResultFolders(bucket))
|
||
).catch((err) => {
|
||
console.warn('inspection result folders ensure skipped:', err?.message || err);
|
||
});
|
||
});
|
||
})();
|
||
}
|