Files
SupplierSystem/server/src/services/mainSystemAuthConsistencyGuard.ts
T
Ubuntu 1735026df0 fix(主系统对接): 授权一致性防护——入站来源校验 + 导入前出站预检 + 出站被拒告警
背景(dev 真机事故 2026-10-22):自贡 BR002 的单被主系统里另一个测试 client
(devcore_race_client)推入,本地库存抵扣完成、批次报告也有,但出站换 token 403
(本系统配置的 erp client 在该供应商上没有带编码授权行)⇒ 报告/回写全部发不出去、
主系统毫无反应,且界面上没有任何痕迹。

三层防护(设计见 docs/design/20261022-主系统对接授权一致性防护.md):
1) 入站来源守卫:webhook 的 payload.client_id / X-Client-Id 必须等于本系统配置的对接
   client;不一致 ⇒ 整条忽略(不建任何数据)+ 失败台账(push_client_mismatch) + 首次通知;
   缺字段(老版本主系统)放行,行为不变;
2) 导入前「出站可用」预检:推送建单前先换一次对接 token;换不到 ⇒ 不建单(503 可重试,
   10 分钟拉取对账继续兜底)+ 台账(outbound_auth_forbidden) + 首次通知;集成开关未启用
   (本地/测试)保持旧行为;
3) 出站授权失败告警:token 层 401/403/404 统一落台账 + 通知,覆盖报告推送/回写/事实刷新。

顺带:导入成功(推送或拉取)后立即触发一次批次报告推送,15 分钟对账只作兜底。

验证:新增 16 个单测全过;typecheck 通过;后端全量 3 failed/574 passed(18 failed/4122
passed,红均为既有 mainSystemReturnCancel/opsGuardHardening/routeLayerBoundary);
dev API 真机验证来源不一致被忽略并落台账/通知、合法来源放行、403 产生「对接授权失效」通知;
设计门禁 6 通过/3 既有红(迁移顺序/env 登记/ai-cost 故意红)/1 未执行(检查器连不上本地库)。
未部署(生产发布需单独命令)。
2026-10-22 09:40:16 +08:00

243 lines
11 KiB
TypeScript

/**
* 主系统对接「授权一致性」防护(设计:docs/design/20261022-主系统对接授权一致性防护.md)。
*
* 三层保护,全部**只做守卫与可观测性**,绝不改写主业务结果:
* ① 入站来源守卫:webhook 的 `payload.client_id` / `X-Client-Id` 必须等于本系统配置的对接 client,
* 否则整条忽略(不建任何数据)并落失败台账 + 首次通知;
* ② 导入前出站可用预检:推送建单前先换一次对接 token(有缓存),换不到 ⇒ 不建单(503 可重试)
* + 失败台账 + 首次通知;集成开关未启用(本地/测试)保持旧行为;
* ③ 出站授权失败告警:`getMainSystemToken` 401/403/404 时落台账并通知,覆盖报告推送/回写/事实刷新。
*
* 纪律:本模块里的写台账/发通知**全部 try/catch 吞掉** —— 防护链路不得反过来把导入搞挂。
*/
import { config } from '../config';
import { pool } from '../db';
import { isMainSystemIntegrationEnabled } from './mainSystem/config';
import { getMainSystemToken } from './mainSystem/token';
import { findBranchCodeByAccessCode } from './branchAccessCode';
import { recordMainSystemImportFailure } from './mainSystemImportFailureService';
import { formatChinaDate } from './orderDeliveryDate';
import { notifyRoleUsers } from './notificationService';
export type PushClientIdentityCheck =
| { ok: true; pushedClientId: string | null; reason?: 'client_id_absent' | 'not_configured' }
| { ok: false; pushedClientId: string; configuredClientId: string; reason: 'client_mismatch' };
/**
* 判定一条 webhook 推送是否来自**本系统配置的对接 client**。
*
* - 推送方 client 优先取 body `client_id`,再退请求头 `X-Client-Id`(主系统两条都发);
* - 任一侧缺失 ⇒ 放行(老版本主系统 / 本地联调不发该字段;不改变现行为,只记 WARN);
* - 两侧都有且不相等 ⇒ 拒绝。
*/
export function evaluatePushClientIdentity(input: {
bodyClientId?: unknown;
headerClientId?: unknown;
configuredClientId?: string | null;
}): PushClientIdentityCheck {
const configured = String(input.configuredClientId ?? '').trim();
const pushed = String(input.bodyClientId ?? '').trim() || String(input.headerClientId ?? '').trim();
if (!configured) return { ok: true, pushedClientId: pushed || null, reason: 'not_configured' };
if (!pushed) return { ok: true, pushedClientId: null, reason: 'client_id_absent' };
if (pushed === configured) return { ok: true, pushedClientId: pushed };
return { ok: false, pushedClientId: pushed, configuredClientId: configured, reason: 'client_mismatch' };
}
/** 从推送载荷尽力取「配送日」(行内 task_day/delivery_date → 订单号里的日期 → 中国时区今天) */
function pickDeliveryDateFromPayload(payload: Record<string, unknown> | null | undefined): string {
const rows = Array.isArray((payload as any)?.data) ? ((payload as any).data as unknown[]) : [];
for (const raw of rows) {
const row = (raw || {}) as Record<string, unknown>;
const value = row.task_day ?? row.delivery_date ?? row.deliveryDate;
if (value == null) continue;
const day = String(value).slice(0, 10);
if (/^\d{4}-\d{2}-\d{2}$/.test(day)) return day;
}
const fromOrder = String((payload as any)?.order_code || '').match(/_(\d{8})_/);
if (fromOrder) {
const digits = fromOrder[1];
return `${digits.slice(0, 4)}-${digits.slice(4, 6)}-${digits.slice(6, 8)}`;
}
return formatChinaDate(new Date());
}
/** 推送载荷里的 subsystem_code → 我方分公司(定不到返回 UNKNOWN,仅用于台账展示,不参与业务) */
async function resolveBranchFromPushPayload(payload: Record<string, unknown> | null | undefined): Promise<string> {
try {
const subsystemCode = String((payload as any)?.subsystem_code || '').trim();
if (!subsystemCode) return 'UNKNOWN';
const branchCode = await findBranchCodeByAccessCode(subsystemCode);
return branchCode ? String(branchCode).trim() : 'UNKNOWN';
} catch {
return 'UNKNOWN';
}
}
/**
* 记录一次「推送来源 client 与本地配置不一致」:失败台账 + 首次站内通知。
* 调用方应已决定**不处理**该请求;本函数只负责留痕。
*/
export async function recordForeignClientPush(input: {
event: string;
payload: Record<string, unknown> | null | undefined;
pushedClientId: string;
configuredClientId: string;
}): Promise<void> {
try {
const payload = (input.payload || {}) as Record<string, unknown>;
const branchCode = await resolveBranchFromPushPayload(payload);
const mainBranchCode = String((payload as any)?.branch_code || '').trim() || '*';
const mainOrderCode = (payload as any)?.order_code ? String((payload as any).order_code) : null;
const message =
`主系统推送来源 client 与本地配置不一致:push=${input.pushedClientId} ` +
`configured=${input.configuredClientId} event=${input.event} ⇒ 已忽略(未建任何数据)`;
console.warn(`[main-system-webhook] ${message}`);
const recorded = await recordMainSystemImportFailure({
branchCode,
deliveryDate: pickDeliveryDateFromPayload(payload),
mainBranchCode,
mainOrderCode,
message,
errorCode: 'push_client_mismatch',
});
if (!recorded?.isFirst) return;
await notifyRoleUsers({
roles: ['admin', 'super_admin'],
notifyType: 'main_system_import_failed',
title: '主系统推送来源异常',
content:
`收到非本系统对接客户端(${input.pushedClientId})推送的 ${input.event},已忽略、未建任何数据;` +
`本系统配置的对接客户端是 ${input.configuredClientId}。` +
`${mainOrderCode ? `涉及主系统订单 ${mainOrderCode}。` : ''}` +
`请检查主系统对接客户端/接入编码绑定,避免订单与报告落到错误的子系统。`,
// 去重键用「分公司 × 标题」:同一错误 client 连续推多单时只提醒一次(订单号已在正文)
relatedOrderCode: null,
branchCode: branchCode === 'UNKNOWN' ? null : branchCode,
dedupWithinHours: 6,
}).catch(() => undefined);
} catch (error) {
console.error(
'[main-system-auth-guard] 记录推送来源异常失败(不影响主流程):',
(error as Error)?.message || error
);
}
}
/** 按主系统供应商编码反查我方绑定(用于告警台账归位);查不到返回 null */
async function resolveBindingForSupplier(
mainSupplierCode: string
): Promise<{ branchCode: string; mainBranchCode: string } | null> {
try {
const result = await pool.query<{ branch_code: string; main_branch_code: string }>(
`SELECT branch_code, main_branch_code
FROM public.main_supplier_bindings
WHERE main_supplier_code = $1 AND status = 'active'
ORDER BY bound_at DESC
LIMIT 1`,
[mainSupplierCode]
);
const row = result.rows[0];
if (!row) return null;
return {
branchCode: String(row.branch_code || '').trim(),
mainBranchCode: String(row.main_branch_code || '').trim(),
};
} catch {
return null;
}
}
/**
* 出站授权失败(token/回写/报告被主系统拒):落失败台账 + 首次通知。
* 只做留痕,不抛错;同一台账键按天累加 attempts,不会刷屏。
*/
export async function recordOutboundAuthFailure(input: {
supplierCode: string;
reason: string;
branchCode?: string | null;
deliveryDate?: string | null;
mainBranchCode?: string | null;
mainOrderCode?: string | null;
}): Promise<void> {
try {
const supplierCode = String(input.supplierCode || '').trim();
if (!supplierCode) return;
let branchCode = String(input.branchCode || '').trim();
let mainBranchCode = String(input.mainBranchCode || '').trim();
if (!branchCode || !mainBranchCode) {
const binding = await resolveBindingForSupplier(supplierCode);
branchCode = branchCode || binding?.branchCode || '';
mainBranchCode = mainBranchCode || binding?.mainBranchCode || '';
}
const deliveryDate = String(input.deliveryDate || '').trim() || formatChinaDate(new Date());
const reason = String(input.reason || '').slice(0, 500) || '未授权';
const message = `对接授权不可用(供应商 ${supplierCode}):${reason}`;
const recorded = await recordMainSystemImportFailure({
branchCode: branchCode || 'UNKNOWN',
deliveryDate,
mainBranchCode: mainBranchCode || '*',
mainOrderCode: input.mainOrderCode ?? null,
message,
errorCode: 'outbound_auth_forbidden',
});
if (!recorded?.isFirst) return;
await notifyRoleUsers({
roles: ['admin', 'super_admin'],
notifyType: 'main_system_import_failed',
title: '主系统对接授权失效',
content:
`主系统拒绝对供应商 ${supplierCode} 的对接请求:${reason}。` +
`在授权恢复前,该供应商的主系统订单拉取、备货完成回写与批次报告推送都会被拒绝;` +
`请检查主系统对接客户端与「子系统接入编码」绑定是否一致。`,
// 去重键用「分公司 × 标题」:授权失效通常持续存在,不要按单/按供应商刷屏
relatedOrderCode: null,
branchCode: branchCode || null,
dedupWithinHours: 6,
}).catch(() => undefined);
} catch (error) {
console.error(
'[main-system-auth-guard] 记录出站授权失败失败(不影响主流程):',
(error as Error)?.message || error
);
}
}
export type OutboundAuthPreflight = { ok: true } | { ok: false; reason: string };
/**
* 推送建单前的「出站可用」预检:先确认对该主系统供应商能换到对接 token
* (缓存,成本低)。换不到 ⇒ 本轮不建单,由失败台账 + 通知暴露给管理员。
*
* ⚠️ 集成开关未启用(本地/测试/未配置凭据)⇒ 直接放行,保持旧行为,避免把测试环境打挂。
*/
export async function ensureOutboundAuthForImport(input: {
branchCode: string;
supplierCode: string;
deliveryDate?: string | null;
mainBranchCode?: string | null;
mainOrderCode?: string | null;
}): Promise<OutboundAuthPreflight> {
const supplierCode = String(input.supplierCode || '').trim();
if (!supplierCode) return { ok: false, reason: '缺少 supplier_code' };
if (!isMainSystemIntegrationEnabled()) return { ok: true };
const token = await getMainSystemToken(supplierCode);
if (token.kind === 'ok') return { ok: true };
// 缺凭据属「没配」而不是「配错」,旧行为交给各链路自己报 not_configured
if (token.kind === 'not_configured') return { ok: true };
const reason = token.reason || '换取对接 Token 失败';
void recordOutboundAuthFailure({
supplierCode,
reason,
branchCode: input.branchCode,
deliveryDate: input.deliveryDate,
mainBranchCode: input.mainBranchCode,
mainOrderCode: input.mainOrderCode,
});
return { ok: false, reason };
}
/** 供 webhook 路由使用:本系统配置的对接 client_id(空 = 未配置) */
export function configuredPushClientId(): string {
return String(config.mainSystemIntegration?.clientId || '').trim();
}