Commit 12ee1475 by liimin

fix(mp,web): 微信系统信息接口适配新 API,修复签名摊平与跨 realm 错误文案

- mp/sales、mp/store: getSystemInfo 改为合并 getWindowInfo/getAppBaseInfo/getDeviceInfo 等新接口,兼容对象与函数两种调用约定,规避 wx.getSystemInfo 废弃
- web/shell: 菜单图标注册表补充二手车管理所需图标
- api-core/points: 数组与嵌套对象在请求出口摊平,保证签名原文与请求体同一份字节,修复批量操作 code 25 无效签名
- points: errorMessage 不再依赖 instanceof Error,跨 realm 错误保留后端原话与网关码
- points: 渠道参数 source 改为 uj-web-points,wire-check 扩充至 17 组断言并同步文档
1 parent 76a1a341
Pipeline #391 for 12ee1475 failed in 0 seconds
import $router from '../router/index' import $router from '../router/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/** /**
* 微信校验通知类工具封装 * 微信校验通知类工具封装
...@@ -97,16 +96,30 @@ const wxShowToast = (name, params) => { ...@@ -97,16 +96,30 @@ const wxShowToast = (name, params) => {
} }
} }
/**获取设备信息 */ /**获取设备信息
const getSystemInfo = callBack => { * 兼容两种调用约定,对齐原生 wx.getSystemInfo:
getSystemInfo({ * - 对象形式 getSystemInfo({ success, fail, complete })
success(res) { * - 函数形式 getSystemInfo(callBack) —— 成功/失败以同一 callBack 回调
callBack(res) * 基础库 2.20.1+ 起 wx.getSystemInfo 已废弃,内部改用新接口合并返回。
}, */
fail(err) { const getSystemInfo = options => {
callBack(err) const callBack = typeof options === 'function' ? options : null
} const onSuccess = callBack || (options && options.success)
}) const onFail = callBack || (options && options.fail)
const onComplete = options && options.complete
try {
const windowInfo = wx.getWindowInfo() || {}
const appBaseInfo = wx.getAppBaseInfo() || {}
const deviceInfo = wx.getDeviceInfo() || {}
const systemSetting = wx.getSystemSetting() || {}
const appAuthorizeSetting = wx.getAppAuthorizeSetting() || {}
const res = { ...deviceInfo, ...appBaseInfo, ...windowInfo, ...systemSetting, ...appAuthorizeSetting }
onSuccess && onSuccess(res)
} catch (err) {
onFail && onFail(err)
} finally {
onComplete && onComplete()
}
} }
/**拨打电话 */ /**拨打电话 */
......
import wxqrcode from '~/utils/lib/wxqrcode.js' import wxqrcode from '~/utils/lib/wxqrcode.js'
import $router from '../router/index' import $router from '../router/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/** /**
* 微信校验通知类工具封装 * 微信校验通知类工具封装
*/ */
...@@ -93,16 +93,30 @@ const wxShowToast = (name, params) => { ...@@ -93,16 +93,30 @@ const wxShowToast = (name, params) => {
} }
} }
/**获取设备信息 */ /**获取设备信息
const getSystemInfo = callBack => { * 兼容两种调用约定,对齐原生 wx.getSystemInfo:
getSystemInfo({ * - 对象形式 getSystemInfo({ success, fail, complete })
success(res) { * - 函数形式 getSystemInfo(callBack) —— 成功/失败以同一 callBack 回调
callBack(res) * 基础库 2.20.1+ 起 wx.getSystemInfo 已废弃,内部改用新接口合并返回。
}, */
fail(err) { const getSystemInfo = options => {
callBack(err) const callBack = typeof options === 'function' ? options : null
} const onSuccess = callBack || (options && options.success)
}) const onFail = callBack || (options && options.fail)
const onComplete = options && options.complete
try {
const windowInfo = wx.getWindowInfo() || {}
const appBaseInfo = wx.getAppBaseInfo() || {}
const deviceInfo = wx.getDeviceInfo() || {}
const systemSetting = wx.getSystemSetting() || {}
const appAuthorizeSetting = wx.getAppAuthorizeSetting() || {}
const res = { ...deviceInfo, ...appBaseInfo, ...windowInfo, ...systemSetting, ...appAuthorizeSetting }
onSuccess && onSuccess(res)
} catch (err) {
onFail && onFail(err)
} finally {
onComplete && onComplete()
}
} }
/**拨打电话 */ /**拨打电话 */
......
...@@ -22,6 +22,19 @@ import { ...@@ -22,6 +22,19 @@ import {
SolutionOutlined, SolutionOutlined,
HomeOutlined, HomeOutlined,
SettingOutlined, SettingOutlined,
CarOutlined,
FundProjectionScreenOutlined,
AimOutlined,
ExperimentOutlined,
ControlOutlined,
ToolOutlined,
SendOutlined,
ReconciliationOutlined,
UserSwitchOutlined,
FileTextOutlined,
SafetyCertificateOutlined,
WechatOutlined,
PayCircleOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { useAccess, buildMenus, type MenuGroupDef } from '@/access'; import { useAccess, buildMenus, type MenuGroupDef } from '@/access';
import { useAppStore } from '@/store/useAppStore'; import { useAppStore } from '@/store/useAppStore';
...@@ -59,7 +72,9 @@ const EXTRA_TITLES: Record<string, string> = { ...@@ -59,7 +72,9 @@ const EXTRA_TITLES: Record<string, string> = {
'/profile': '个人资料', '/profile': '个人资料',
}; };
// 图标注册表:菜单数据只存图标名,渲染时查表(新增图标在这里登记即可) // 图标注册表:菜单数据(后端 sys_menu.icon / 兜底 menu.json)只存图标名,渲染时查表。
// 这里刻意用字面量而不是 `import * as antdIcons` 动态取:后者会把 894 个图标全打进首屏。
// 代价是后端新增菜单图标必须在这里同步登记一行,漏了会在 dev 控制台点名(见 resolveIcon)。
const iconMap: Record<string, React.ReactNode> = { const iconMap: Record<string, React.ReactNode> = {
DashboardOutlined: <DashboardOutlined />, DashboardOutlined: <DashboardOutlined />,
ShopOutlined: <ShopOutlined />, ShopOutlined: <ShopOutlined />,
...@@ -74,6 +89,20 @@ const iconMap: Record<string, React.ReactNode> = { ...@@ -74,6 +89,20 @@ const iconMap: Record<string, React.ReactNode> = {
SolutionOutlined: <SolutionOutlined />, SolutionOutlined: <SolutionOutlined />,
HomeOutlined: <HomeOutlined />, HomeOutlined: <HomeOutlined />,
SettingOutlined: <SettingOutlined />, SettingOutlined: <SettingOutlined />,
// 二手车管理(scripts/usedcar-menu-complete.sql)
CarOutlined: <CarOutlined />,
FundProjectionScreenOutlined: <FundProjectionScreenOutlined />,
AimOutlined: <AimOutlined />,
ExperimentOutlined: <ExperimentOutlined />,
ControlOutlined: <ControlOutlined />,
ToolOutlined: <ToolOutlined />,
SendOutlined: <SendOutlined />,
ReconciliationOutlined: <ReconciliationOutlined />,
UserSwitchOutlined: <UserSwitchOutlined />,
FileTextOutlined: <FileTextOutlined />,
SafetyCertificateOutlined: <SafetyCertificateOutlined />,
WechatOutlined: <WechatOutlined />,
PayCircleOutlined: <PayCircleOutlined />,
}; };
/** 后端未下发图标(icon 为 null)或图标名未登记时的兜底图标 */ /** 后端未下发图标(icon 为 null)或图标名未登记时的兜底图标 */
const DEFAULT_MENU_ICON: React.ReactNode = <AppstoreOutlined />; const DEFAULT_MENU_ICON: React.ReactNode = <AppstoreOutlined />;
......
...@@ -6,17 +6,18 @@ ...@@ -6,17 +6,18 @@
--- ---
## 1. 静态闸门(本机实测,2026-11-06) ## 1. 静态闸门(本机实测,2026-11-06 首测 / 2026-11-10 复测)
| 闸门 | 命令 | 结果 | | 闸门 | 命令 | 结果 |
| ------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | ------ | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 类型 | `npx tsc --noEmit` | 0 错 | | 类型 | `npx tsc --noEmit` | 0 错 |
| Lint | `npx eslint . --max-warnings=0` | 0 错 0 警 | | Lint | `npx eslint . --max-warnings=0` | 0 错 0 警 |
| 格式 | `npx prettier --check`(本子应用全量) | 通过 | | 格式 | `npx prettier --check`(本子应用全量) | 通过 |
| 构建 | `npx vite build` | 通过,3310 模块 / 1505.86 kB(gzip 480.88 kB) | | 构建 | `npx vite build` | 通过,3332 模块 / 1546.60 kB(gzip 495.51 kB)(2026-11-10 复测) |
| 边界 | `node scripts/check-boundaries.mjs` | 错误 0,告警 1(store 既有 CSS,与本次无关);扫描 3 个子应用,points 在内 | | 边界 | `node scripts/check-boundaries.mjs` | 错误 0,告警 1:`src/features/shared/page.css` 含裸 `.ant-*` 选择器(既有视觉收口,非本次新增;确认没覆盖组件内部几何属性即可);扫描 3 个子应用、5 个小程序,points 在内 |
| 一致性 | `node scripts/reconcile.mjs` | 问题 0 —— 但它不检查 points,见第 6.1 | | 一致性 | `node scripts/reconcile.mjs` | 问题 0 —— 但它不检查 points,见第 6.1 |
| 签名 | `pnpm --filter @uj/api-core test`(`test/glsxSign.test.mjs`) | 真实抓包 11 字段复算 → `689F62277A050D6285B1E38BB2C3DA8D8E518EC9` 精确命中;MD5(32 位)明确不符,已固化成防回归闸门 | | 签名 | `pnpm --filter @uj/api-core test`(`test/glsxSign.test.mjs`) | 真实抓包 11 字段复算 → `689F62277A050D6285B1E38BB2C3DA8D8E518EC9` 精确命中;MD5(32 位)明确不符,已固化成防回归闸门。整套 111 个(2026-11-10 新增 005/006 钉出口摊平、FT-REALM-001 钉跨 realm 文案) |
| 出口 | `node out/.temp/wire-check.mjs` | 17 组全离线断言,逐条见 §4;2026-11-10 起 ⑯ 管摊平、⑰ 管错误文案 |
浏览器里逐个页面的验收没做 —— 按约定静态闸门到此为止,视觉与交互由你点。第 9 节是可以照着点的清单。 浏览器里逐个页面的验收没做 —— 按约定静态闸门到此为止,视觉与交互由你点。第 9 节是可以照着点的清单。
...@@ -109,7 +110,7 @@ ...@@ -109,7 +110,7 @@
1. **一个系统一套策略。** `GatewayId = 'scrm-shopmall' | 'scrm-carlife' | 'dj-smartcarlife'`,各自带 `router` 路径、令牌放哪个头(前两个 `token`,dj 是 `TGT`)、用哪个签名器。第三个系统再接进来时新增一个 `GatewayStrategy`,页面与业务模块不需要知道对方是谁。 1. **一个系统一套策略。** `GatewayId = 'scrm-shopmall' | 'scrm-carlife' | 'dj-smartcarlife'`,各自带 `router` 路径、令牌放哪个头(前两个 `token`,dj 是 `TGT`)、用哪个签名器。第三个系统再接进来时新增一个 `GatewayStrategy`,页面与业务模块不需要知道对方是谁。
方法名里的 `dj.` / `scrm.` 前缀**不**代表落点域名:老系统里只有 `dj.smartcarlife.api.shopMerchant.list` 与 `dj.api.smartcarlife.merchant.score.deduct.order.page` 真打 dj 路由,`dj.api.shopmall.staff.score.*` 走的是 scrm-shopmall router。这条对照从 `temp/scrm-micro-points` 现读,不靠人记(见下文 ⑬)。 方法名里的 `dj.` / `scrm.` 前缀**不**代表落点域名:老系统里只有 `dj.smartcarlife.api.shopMerchant.list` 与 `dj.api.smartcarlife.merchant.score.deduct.order.page` 真打 dj 路由,`dj.api.shopmall.staff.score.*` 走的是 scrm-shopmall router。这条对照从 `temp/scrm-micro-points` 现读,不靠人记(见下文 ⑬)。
2. **签名是可替换的策略,不是散在页面里的代码。** glsx 系用 **SHA1**:`secret + 按 key 升序拼接的 k+v + secret` 取 SHA1,**40 位大写**(不是 MD5,MD5 只有 32 位,曾误用导致验签必挂);timestamp 进签名原文,非字符串参数按 JSON 原文参与拼接。唯一实现是 api-core 的 `createSigner()` 不传参默认值(`gateways/glsx.ts` 只声明它),依据是 `glsx-common/src/util.js#createSign` 的默认 `way='sha1'`;真实抓包 golden 值固化在 `packages/api-core/test/glsxSign.test.mjs`。老系统的 `noSignAttr` 换成 `unsignedKeys`。 2. **签名是可替换的策略,不是散在页面里的代码。** glsx 系用 **SHA1**:`secret + 按 key 升序拼接的 k+v + secret` 取 SHA1,**40 位大写**(不是 MD5,MD5 只有 32 位,曾误用导致验签必挂);timestamp 进签名原文;数组与嵌套对象在加签**之前**摊平成 `ids[0]` / `a.b` 这样的标量键(第 6 条),不存在「非字符串参数按 JSON 原文拼接」这种形态。唯一实现是 api-core 的 `createSigner()` 不传参默认值(`gateways/glsx.ts` 只声明它),依据是 `glsx-common/src/util.js#createSign` 的默认 `way='sha1'`;真实抓包 golden 值固化在 `packages/api-core/test/glsxSign.test.mjs`。老系统的 `noSignAttr` 换成 `unsignedKeys`。
3. **返回值归一挂在 `transformResponse` 上。** 老网关 `code:'0'` → 主壳的 `{ data }`,`code:'21'` → `10002` 走统一登出,其他码 → 带人话文案的失败。函数随 props 引用传给主壳,序列化不了它,所以主壳代码一行不用改。 3. **返回值归一挂在 `transformResponse` 上。** 老网关 `code:'0'` → 主壳的 `{ data }`,`code:'21'` → `10002` 走统一登出,其他码 → 带人话文案的失败。函数随 props 引用传给主壳,序列化不了它,所以主壳代码一行不用改。
4. **请求体一律 `application/x-www-form-urlencoded`。** 这个头写在 `@uj/api-core` 的 `prepareRpcCall`(web 与小程序共用同一份组装),不在子应用装配层重复声明,也不由传输层默认值决定。少了它,axios 会把同一个对象按 JSON 发出去,而 glsx rop 网关只按 form 解析请求体,于是返回 HTTP 200 + `<error code="22">缺少appKey参数</error>`:状态正常、响应里没数据,看不出是编码问题。 4. **请求体一律 `application/x-www-form-urlencoded`。** 这个头写在 `@uj/api-core` 的 `prepareRpcCall`(web 与小程序共用同一份组装),不在子应用装配层重复声明,也不由传输层默认值决定。少了它,axios 会把同一个对象按 JSON 发出去,而 glsx rop 网关只按 form 解析请求体,于是返回 HTTP 200 + `<error code="22">缺少appKey参数</error>`:状态正常、响应里没数据,看不出是编码问题。
5. **`usedCarFlag=1` 是这个系统的数据身份,不是筛选条件。** 后端把它加在 13 个接口的请求体上(`StaffScoreRopRequest` / `IntegralOrderPageRequest` / `IntegralTransferOutPageRequest` 三组,同组的导出、金额合计、一键操作校验各自复用),传 `1` = 只返回二手车展业门店数据、不传 = 原逻辑查全部。本系统只服务二手车,所以口径定成**一律传 1**:字段名与取值只在 [api/core/usedCarScope.ts](file:///D:/work/uj-admin/apps/web/subapps/points/src/api/core/usedCarScope.ts) 定义一次,由唯一的请求出口 [api/core/rpc-client.ts](file:///D:/work/uj-admin/apps/web/subapps/points/src/api/core/rpc-client.ts) 在 `rpc()` 里注入并覆盖。带来的三个后果都是刻意的: 5. **`usedCarFlag=1` 是这个系统的数据身份,不是筛选条件。** 后端把它加在 13 个接口的请求体上(`StaffScoreRopRequest` / `IntegralOrderPageRequest` / `IntegralTransferOutPageRequest` 三组,同组的导出、金额合计、一键操作校验各自复用),传 `1` = 只返回二手车展业门店数据、不传 = 原逻辑查全部。本系统只服务二手车,所以口径定成**一律传 1**:字段名与取值只在 [api/core/usedCarScope.ts](file:///D:/work/uj-admin/apps/web/subapps/points/src/api/core/usedCarScope.ts) 定义一次,由唯一的请求出口 [api/core/rpc-client.ts](file:///D:/work/uj-admin/apps/web/subapps/points/src/api/core/rpc-client.ts) 在 `rpc()` 里注入并覆盖。带来的三个后果都是刻意的:
...@@ -117,10 +118,14 @@ ...@@ -117,10 +118,14 @@
- 详情地址少一段:`/points/user/<channelSource>/<staffId>` 与 `/points/user/<channelSource>/<merchantId>/<phone>`。范围不再随地址流动,因为它不随任何人变。 - 详情地址少一段:`/points/user/<channelSource>/<staffId>` 与 `/points/user/<channelSource>/<merchantId>/<phone>`。范围不再随地址流动,因为它不随任何人变。
- 覆盖范围按出口算,不按清单算:`wire-check.mjs` ⑩ 逐个复算 **53 个已登记方法**(需求点名的 13 个只是其中的子集),新接一个接口不需要登记条件就一定带 —— 漏不掉,也不需要谁记得。 - 覆盖范围按出口算,不按清单算:`wire-check.mjs` ⑩ 逐个复算 **53 个已登记方法**(需求点名的 13 个只是其中的子集),新接一个接口不需要登记条件就一定带 —— 漏不掉,也不需要谁记得。
将来若真要同域共存第二套部署(非二手车),改的是这个常量与注入点,而不是往页面里加回控件。 将来若真要同域共存第二套部署(非二手车),改的是这个常量与注入点,而不是往页面里加回控件。
6. **数组与嵌套对象在请求出口摊平,签名原文与请求体是同一份字节。** `ids: [214, 213, 212]` → `ids[0]=214&ids[1]=213&ids[2]=212`,嵌套对象 → `a.b`,`null` → 空串,`undefined` 和空数组连键都不出现。规则逐字对齐老系统 `glsx-common/src/util.js#createSign` 里的 `qs.stringify({ arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true })`,实现只有一处:`packages/api-core/src/gateway/dispatcher.ts` 的 `flattenFormParams`,在 `prepareRpcCall` 合并完 `fixedParams` / 业务参数 / 会话号之后、加签之前跑一次。web 与小程序共用这条组装,所以 points、mp/points、mp/sales 的数组入参一起被修正。
为什么值得单独一条:摊平如果交给传输层决定,axios 默认按 `ids[]=214&ids[]=213` 发出去,而签名原文里拼的是 JSON 数组本体,两边字节不同,网关回 `code 25 无效签名`。2026-11-10 提现批量付款的抓包正是这个形态(`source / ids[0..2] / canApprove / usedCarFlag / sessionId / method / appKey / format / timestamp / v / sign`),现象是一句文案正确的 `25` 落在所有带 `ids` 的批量操作上(审核、驳回、付款、打标、生成批次、金额合计)—— 一次签名错,六个入口一起红。
判据两道:`wire-check.mjs` ⑯ 对 53 个出口逐个复算摊平结果,并用 `node:crypto` 独立重算一遍签名(不 import 生产签名器,防止两处一起错);`glsxSign.test.mjs` IT-GLSX-SIGN-005 用一次线上真实应答(固定 timestamp,`code 0`,`payAmount: 1200`)钉住键序与 golden。
请求仍然全部经 `requestViaHost()` → `window.$wujie.props.request(config)`,铁律「请求层绝不下放」没有被破坏([ARCHITECTURE.md §2](file:///D:/work/uj-admin/ARCHITECTURE.md))。 请求仍然全部经 `requestViaHost()` → `window.$wujie.props.request(config)`,铁律「请求层绝不下放」没有被破坏([ARCHITECTURE.md §2](file:///D:/work/uj-admin/ARCHITECTURE.md))。
- **这个网关没有免签接口。** 老系统里那 5 个方法(`checkTransferType`、`sumAllPayAmount`、`settleAmount`、`payChannels`、`balance`)看着像「不签」,实测逐个打过去只证明了三件事:不带 appKey → `code 22 缺少appKey参数`;带 appKey 不带 sign → `code 24 缺少签名参数`;两者齐全 → `code 0 调用服务成功`。早先按「免签」登记时,`signed:false` 把整个身份信封一起跳过了,于是累计结算金额那条永远是一排 `—`。现在接口层不允许 `signed:false`(`wire-check.mjs` ⑮ 直接把它判红);`importXlsx` 提交文件但签名原文里排除 `file`,这是唯一的例外,走 `unsignedKeys`。 - **这个网关没有免签接口。** 老系统里那 5 个方法(`checkTransferType`、`sumAllPayAmount`、`settleAmount`、`payChannels`、`balance`)看着像「不签」,实测逐个打过去只证明了三件事:不带 appKey → `code 22 缺少appKey参数`;带 appKey 不带 sign → `code 24 缺少签名参数`;两者齐全 → `code 0 调用服务成功`。早先按「免签」登记时,`signed:false` 把整个身份信封一起跳过了,于是累计结算金额那条永远是一排 `—`。现在接口层不允许 `signed:false`(`wire-check.mjs` ⑮ 直接把它判红);`importXlsx` 提交文件但签名原文里排除 `file`,这是唯一的例外,走 `unsignedKeys`。
- **后端的原话必须落到页面上。** 网关已经回了 `code 25` 和一句「签名无效,请按正确的算法…」,页面却仍旧显示「操作失败,请稍后重试」,原因是 realm:子应用的代码在 wujie 的 iframe realm 里,请求由主壳的 `props.request` 抛出,那个 Error 在子应用侧 `instanceof Error` 与 `instanceof RequestError` 全是 false,于是 message 和 `code` 一起被丢掉,业务失败被当成传输失败 —— 文案变笼统、多弹一个 toast、还白重试一次。修法是两处:api-core 用 `isRequestError()`(认对象自己写上去的标记,不认原型链)配合 `wrapError()` 原样保留文案与码(`core/errors.ts`、`core/facade.ts`),points 侧 `features/shared/format.ts#errorMessage` 只按字段取值、拿到纯数字码就缀上「(网关码 25)」,取不到任何文字才用兜底句。判据:`facade.test.mjs` FT-REALM-001 用 `node:vm` 造一个真·另一个 realm 的 Error,断言只发一次请求、不多弹 toast;`wire-check.mjs` ⑰ 核文案矩阵(有码 / 无码 / 字符串 / undefined 四种输入)。
- 超时对齐老系统 180 s(导入/导出这类慢接口不会被前端提前掐断)。 - 超时对齐老系统 180 s(导入/导出这类慢接口不会被前端提前掐断)。
- 唯一一处「老系统没有的出口」:`scrm.api.shopmall.integralorder.page` / `.export`(门店版,不带 `all.`,见 `api/modules/points.ts` 的 `pageStoreOrders` / `exportStoreOrders`)。后端让它与运营版共用同一份 `IntegralOrderPageRequest`,`usedCarFlag` 同样生效;老系统只登记了 `all.*`,这两个是给门店端复用而在此登记的,**当前没有 UI 调用点,别当死代码删**(删前确认门店端没在用它)。 - 唯一一处「老系统没有的出口」:`scrm.api.shopmall.integralorder.page` / `.export`(门店版,不带 `all.`,见 `api/modules/points.ts` 的 `pageStoreOrders` / `exportStoreOrders`)。后端让它与运营版共用同一份 `IntegralOrderPageRequest`,`usedCarFlag` 同样生效;老系统只登记了 `all.*`,这两个是给门店端复用而在此登记的,**当前没有 UI 调用点,别当死代码删**(删前确认门店端没在用它)。
...@@ -134,7 +139,7 @@ origin 与请求体有四处容易踩的坑,都固化成了 `wire-check.mjs` ...@@ -134,7 +139,7 @@ origin 与请求体有四处容易踩的坑,都固化成了 `wire-check.mjs`
- **会话分环境**:`sessionId`(主壳 `loginToken`)是**某个环境签发的会话**,不是全局通行证。实测同一个 `scrm-base-*-rop` 在 `scrm.dev.glsx.com.cn` 回 `code:'0'` 出数据,在 `scrm.test.glsx.com.cn` 回 `code:'21' 无效的sessionId`。所以 scrm 与 dj 两个 origin 必须取自环境表的**同一行**,换环境一起换 —— ⑭ 就是把 `.env` 的两行拿去和小程序环境表逐行对齐。 - **会话分环境**:`sessionId`(主壳 `loginToken`)是**某个环境签发的会话**,不是全局通行证。实测同一个 `scrm-base-*-rop` 在 `scrm.dev.glsx.com.cn` 回 `code:'0'` 出数据,在 `scrm.test.glsx.com.cn` 回 `code:'21' 无效的sessionId`。所以 scrm 与 dj 两个 origin 必须取自环境表的**同一行**,换环境一起换 —— ⑭ 就是把 `.env` 的两行拿去和小程序环境表逐行对齐。
这条的连锁现象要认得:`21` 归一成 `10002` 触发统一登出、清掉 `loginToken`,同一屏里后发的那条请求因此连 `sessionId` 都带不上,网关回 `code:'20' 缺少sessionId参数`。两条错误码是同一个配置错的两次呼吸,不是两个 bug。 这条的连锁现象要认得:`21` 归一成 `10002` 触发统一登出、清掉 `loginToken`,同一屏里后发的那条请求因此连 `sessionId` 都带不上,网关回 `code:'20' 缺少sessionId参数`。两条错误码是同一个配置错的两次呼吸,不是两个 bug。
联调前跑 `node out/.temp/wire-check.mjs`(15 组,全离线,不需要登录态)。 联调前跑 `node out/.temp/wire-check.mjs`(17 组,全离线,不需要登录态)。
--- ---
......
/**
* 数组参数的线上字节钉值:固定 timestamp 后发一次真实请求,让网关自己认证这份 sign。
* 用法:node out/.temp/array-golden.mjs <sessionId>
* 只读金额合计接口,不写任何数据。
*/
import { readFileSync } from 'node:fs';
import { createServer, loadConfigFromFile } from 'vite';
const SID = process.argv[2];
if (!SID) {
console.log('用法:node out/.temp/array-golden.mjs <sessionId>');
process.exit(1);
}
const lines = readFileSync('.env', 'utf8')
.split('\n')
.filter((line) => /^[A-Z_]+=/.test(line))
.map((line) => line.split('='));
const val = (k) => lines.find(([key]) => key === k)?.[1]?.trim() ?? '';
const credential = {
origin: val('VITE_POINTS_GATEWAY_ORIGIN'),
appKey: val('VITE_POINTS_GATEWAY_APP_KEY'),
secret: val('VITE_POINTS_GATEWAY_SECRET'),
version: '1.0.0',
format: 'json',
};
const TIMESTAMP = 1794300000000;
const realNow = Date.now;
Date.now = () => TIMESTAMP;
const cfg = await loadConfigFromFile({ command: 'serve', mode: 'development' }, 'vite.config.ts');
const server = await createServer({
...cfg.config,
appType: 'custom',
optimizeDeps: { noDiscovery: true, include: [] },
server: { ...cfg.config.server, middlewareMode: true },
logLevel: 'error',
});
const apiCore = await server.ssrLoadModule('@uj/api-core');
await server.ssrLoadModule('/src/adapter/gateways/index.ts');
const raw = await apiCore.prepareRpcCall(
{
gateway: 'scrm-shopmall',
method: 'scrm.api.shopmall.integral.transfer.out.pay.amount',
params: { ids: ['214', '213', '212'], canApprove: false, usedCarFlag: '1' },
},
{
resolveCredential: () => credential,
resolveToken: () => SID,
session: { name: 'sessionId', value: SID },
timeout: 60000,
},
);
Date.now = realNow;
const body = raw.data;
const form = new URLSearchParams(
Object.entries(body).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)]),
).toString();
const reply = await fetch(raw.url, {
method: 'POST',
headers: { ...raw.headers, 'content-type': 'application/x-www-form-urlencoded' },
body: form,
}).then(async (r) => ({ http: r.status, t: await r.text() }));
console.log('url :', raw.url);
console.log('timestamp :', TIMESTAMP);
console.log('keys :', JSON.stringify(Object.keys(body)));
console.log('body :', form.replace(/(appKey=)[^&]+/, '$1…').replace(/(sign=)[^&]+/, '$1…'));
console.log('sign :', body.sign);
console.log('reply :', `HTTP ${reply.http}`, reply.t.slice(0, 220));
console.log('appKey :', credential.appKey);
await server.close();
/**
* 数组参数(ids[])为什么回 code 25:三种发法逐字节对比。
* 用法:node out/.temp/array-sign-probe.mjs <sessionId> [origin]
* 只读金额合计接口,不写任何数据。
*/
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { createServer, loadConfigFromFile } from 'vite';
const SID = process.argv[2];
if (!SID) {
console.log('用法:node out/.temp/array-sign-probe.mjs <sessionId> [origin]');
process.exit(1);
}
const lines = readFileSync('.env', 'utf8')
.split('\n')
.filter((line) => /^[A-Z_]+=/.test(line))
.map((line) => line.split('='));
const val = (k) => lines.find(([key]) => key === k)?.[1]?.trim() ?? '';
const credential = {
origin: process.argv[3] || val('VITE_POINTS_GATEWAY_ORIGIN'),
appKey: val('VITE_POINTS_GATEWAY_APP_KEY'),
secret: val('VITE_POINTS_GATEWAY_SECRET'),
version: '1.0.0',
format: 'json',
};
const cfg = await loadConfigFromFile({ command: 'serve', mode: 'development' }, 'vite.config.ts');
const server = await createServer({
...cfg.config,
appType: 'custom',
optimizeDeps: { noDiscovery: true, include: [] },
server: { ...cfg.config.server, middlewareMode: true },
logLevel: 'error',
});
const apiCore = await server.ssrLoadModule('@uj/api-core');
await server.ssrLoadModule('/src/adapter/gateways/index.ts');
const deps = {
resolveCredential: () => credential,
resolveToken: () => SID,
session: { name: 'sessionId', value: SID },
timeout: 60000,
};
const METHOD = 'scrm.api.shopmall.integral.transfer.out.pay.amount';
const IDS = [214, 213, 212];
const PARAMS = { ids: IDS, canApprove: false };
const send = async (url, headers, fields, label) => {
const body = new URLSearchParams(
Object.entries(fields).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)]),
).toString();
const reply = await fetch(url, {
method: 'POST',
headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' },
body,
})
.then((r) => r.text().then((t) => ({ http: r.status, t })))
.catch((e) => ({ http: 0, t: String(e) }));
const code =
(reply.t.match(/"code"\s*:\s*"(\d+)"/) ?? reply.t.match(/code="(\d+)"/) ?? [])[1] ?? '?';
const message =
(reply.t.match(/"message"\s*:\s*"([^"]*)"/) ?? reply.t.match(/<message>([^<]*)</) ?? [])[1] ??
'';
const solution = (reply.t.match(/"solution"\s*:\s*"([^"]*)"/) ?? [])[1] ?? '';
console.log(`\n【${label}】`);
console.log(
` body : ${body.replace(/&sign=[^&]*/, '&sign=…').replace(/(appKey=)[^&]*/, '$1…')}`,
);
console.log(
` 回话 : HTTP ${reply.http} code=${code} ${message}${solution ? ` / ${solution.slice(0, 40)}` : ''}`,
);
};
// ① 现状:api-core 直接发嵌套数组,body 由传输层决定怎么编码(浏览器里是 ids[]=…)。
const asIs = await apiCore.prepareRpcCall(
{ gateway: 'scrm-shopmall', method: METHOD, params: { ...PARAMS, usedCarFlag: '1' } },
deps,
);
await send(asIs.url, asIs.headers, asIs.data, '① 现状:params 里放数组');
// ② 老系统:glsx-common/createSign 用 qs(arrayFormat:indices, allowDots) 摊平后再签名,
// body 也发摊平后的键(ids[0]=…)。这是网关认的那份字节。
const legacyRequire = createRequire('D:/work/npm/glsx-common/package.json');
const qs = legacyRequire('qs');
const sha1 = legacyRequire('sha1');
const legacyParams = {
...PARAMS,
usedCarFlag: '1',
source: 'uj-web-points',
sessionId: SID,
method: METHOD,
appKey: credential.appKey,
format: credential.format,
v: credential.version,
};
// 逐字照抄 glsx-common/src/util.js#createSign(先塞 timestamp,再 qs 摊平,摊平后的键名才拿去排序)
legacyParams.timestamp = Date.now();
const strQs = qs.stringify(legacyParams, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true,
});
const collect = strQs.split('&').reduce((acc, item) => {
const [key, value] = item.split('=');
acc[key] = decodeURIComponent(value ?? '');
return acc;
}, {});
const keys = Object.keys(collect).sort();
const str = keys.reduce(
(col, key) => (key === 'sign' ? col : (col.push(key, collect[key] ?? ''), col)),
[],
);
collect.sign = sha1(`${credential.secret}${str.join('')}${credential.secret}`).toUpperCase();
await send(asIs.url, { token: SID }, collect, '② 老系统:qs 摊平 ids[0]/ids[1]/ids[2] 后加签');
// ③ 修复预演:出口先把数组摊平成 ids[0]/ids[1]/ids[2] 再交给 prepareRpcCall,
// 签名与 body 因此同源,仍然全部走 api-core。
const flattened = {};
strQs.split('&').forEach((item) => {
const [key, value] = item.split('=');
if (key !== 'ids[0]' && key !== 'ids[1]' && key !== 'ids[2]') return;
flattened[key] = decodeURIComponent(value);
});
console.log(
`\n(摊平对照:qs 给出的键名 = ${Object.keys(collect)
.filter((k) => k.startsWith('ids'))
.join(', ')})`,
);
const simulated = await apiCore.prepareRpcCall(
{
gateway: 'scrm-shopmall',
method: METHOD,
params: { ...flattened, canApprove: false },
},
deps,
);
await send(
simulated.url,
simulated.headers,
simulated.data,
'③ 修复预演:出口先摊平,再签名、再发',
);
await server.close();
...@@ -51,7 +51,9 @@ const send = async (label, { bodySid, headerSid }) => { ...@@ -51,7 +51,9 @@ const send = async (label, { bodySid, headerSid }) => {
}); });
const text = (await res.text()).replace(/\s+/g, ' ').slice(0, 160); const text = (await res.text()).replace(/\s+/g, ' ').slice(0, 160);
const sentSid = raw.data.sessionId ? '有' : '无'; const sentSid = raw.data.sessionId ? '有' : '无';
console.log(`${label} body.sessionId=${sentSid} token头=${headerSid ? '有' : '无'}\n → ${text}\n`); console.log(
`${label} body.sessionId=${sentSid} token头=${headerSid ? '有' : '无'}\n → ${text}\n`,
);
}; };
try { try {
......
...@@ -69,8 +69,11 @@ const ask = async (method, mode) => { ...@@ -69,8 +69,11 @@ const ask = async (method, mode) => {
}) })
.then((r) => r.text().then((t) => ({ http: r.status, t }))) .then((r) => r.text().then((t) => ({ http: r.status, t })))
.catch((e) => ({ http: 0, t: String(e) })); .catch((e) => ({ http: 0, t: String(e) }));
const code = (reply.t.match(/"code"\s*:\s*"(\d+)"/) ?? reply.t.match(/code="(\d+)"/) ?? [])[1] ?? '?'; const code =
const message = (reply.t.match(/"message"\s*:\s*"([^"]*)"/) ?? reply.t.match(/<message>([^<]*)</) ?? [])[1] ?? ''; (reply.t.match(/"code"\s*:\s*"(\d+)"/) ?? reply.t.match(/code="(\d+)"/) ?? [])[1] ?? '?';
const message =
(reply.t.match(/"message"\s*:\s*"([^"]*)"/) ?? reply.t.match(/<message>([^<]*)</) ?? [])[1] ??
'';
return `HTTP ${reply.http} code=${code} ${message.slice(0, 26)}`; return `HTTP ${reply.http} code=${code} ${message.slice(0, 26)}`;
}; };
......
...@@ -9,9 +9,13 @@ ...@@ -9,9 +9,13 @@
* ③ 逐个复算登记的每一个出口(53 个),确认组装层不会把它丢掉。 * ③ 逐个复算登记的每一个出口(53 个),确认组装层不会把它丢掉。
* ④ - ⑧ 核地址:范围段已从路由里删掉,旧地址只会「接不住」,不会静默查错人。 * ④ - ⑧ 核地址:范围段已从路由里删掉,旧地址只会「接不住」,不会静默查错人。
* ⑨ - ⑭ 核落点与联调配置:方法→router→域名、origin 协议、form 请求体、两个网关同环境。 * ⑨ - ⑭ 核落点与联调配置:方法→router→域名、origin 协议、form 请求体、两个网关同环境。
* ⑮ - ⑰ 核线上字节的三条硬规则:没有免签接口(少 sign 就是 code 24)、
* 数组与嵌套对象必须在出口摊平(否则签名原文与请求体两套字节,网关回 code 25)、
* 后端给的失败原因必须原样出现在页面上(跨 realm 的错误不是本域 Error 实例)。
*/ */
import { createServer, loadConfigFromFile } from 'vite'; import { createServer, loadConfigFromFile } from 'vite';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFileSync, readdirSync } from 'node:fs'; import { readFileSync, readdirSync } from 'node:fs';
import { createRequire } from 'node:module'; import { createRequire } from 'node:module';
import { join } from 'node:path'; import { join } from 'node:path';
...@@ -58,7 +62,10 @@ try { ...@@ -58,7 +62,10 @@ try {
await check('① 契约只有一个值:字段名 usedCarFlag、取值 1,并覆盖调用方传进来的任何东西', () => { await check('① 契约只有一个值:字段名 usedCarFlag、取值 1,并覆盖调用方传进来的任何东西', () => {
assert.equal(scope.USED_CAR_FIELD_NAME, 'usedCarFlag'); assert.equal(scope.USED_CAR_FIELD_NAME, 'usedCarFlag');
assert.equal(scope.USED_CAR_FLAG, '1'); assert.equal(scope.USED_CAR_FLAG, '1');
assert.deepEqual(scope.withUsedCarScope({ currentPage: 1 }), { currentPage: 1, usedCarFlag: '1' }); assert.deepEqual(scope.withUsedCarScope({ currentPage: 1 }), {
currentPage: 1,
usedCarFlag: '1',
});
// 表单草稿、旧地址段、别处传来的 0/空串一律无效:口径不接受第二处定义。 // 表单草稿、旧地址段、别处传来的 0/空串一律无效:口径不接受第二处定义。
for (const draft of ['', '0', 'all', undefined, null]) { for (const draft of ['', '0', 'all', undefined, null]) {
assert.equal(scope.withUsedCarScope({ usedCarFlag: draft }).usedCarFlag, '1'); assert.equal(scope.withUsedCarScope({ usedCarFlag: draft }).usedCarFlag, '1');
...@@ -219,31 +226,38 @@ try { ...@@ -219,31 +226,38 @@ try {
timeout: 180000, timeout: 180000,
}; };
await check('⑩ 逐个复算请求体:登记的每个出口都带 usedCarFlag=1,签名与落点不受影响', async () => { await check(
const seen = new Set(); '⑩ 逐个复算请求体:登记的每个出口都带 usedCarFlag=1,签名与落点不受影响',
for (const { gateway, method } of endpoints) { async () => {
if (seen.has(method)) continue; const seen = new Set();
seen.add(method); for (const { gateway, method } of endpoints) {
// 页面只会交来表单与分页参数;范围由请求出口注入后到这里。 if (seen.has(method)) continue;
// 这一跳验的是「组装层既不会丢掉它,也不会把它当成多余字段处理掉」。 seen.add(method);
const raw = await apiCore.prepareRpcCall( // 页面只会交来表单与分页参数;范围由请求出口注入后到这里。
{ gateway, method, params: scope.withUsedCarScope({ currentPage: 1, pageSize: 10 }) }, // 这一跳验的是「组装层既不会丢掉它,也不会把它当成多余字段处理掉」。
deps, const raw = await apiCore.prepareRpcCall(
); { gateway, method, params: scope.withUsedCarScope({ currentPage: 1, pageSize: 10 }) },
assert.equal(raw.data.usedCarFlag, '1', `${method} 的 body 丢了 usedCarFlag`); deps,
assert.equal(raw.data.method, method, `${method} 的落点方法名不对`); );
assert.equal(raw.data.source, 'scrm-home', `${method} 丢了网关固定渠道参数`); assert.equal(raw.data.usedCarFlag, '1', `${method} 的 body 丢了 usedCarFlag`);
assert.match(raw.url, /\/rop-[\w-]+\/router$/, `${method} 落点算错:${raw.url}`); assert.equal(raw.data.method, method, `${method} 的落点方法名不对`);
if (DOCUMENTED.includes(method)) { // 渠道名 2026-11-10 起由本域自报 'uj-web-points'(老抓包里是老系统的 'scrm-home');
assert.equal(typeof raw.data.sign, 'string', `${method} 没产生签名字段`); // 它进签名原文但不参与身份校验,线上实测 code 0。换名要连同 api-core 的钉值一起重取。
assert.equal(raw.data.sign.length, 40, `${method} 的签名不是 SHA1 40 位`); assert.equal(raw.data.source, 'uj-web-points', `${method} 丢了网关固定渠道参数`);
assert.match(raw.url, /\/rop-[\w-]+\/router$/, `${method} 落点算错:${raw.url}`);
if (DOCUMENTED.includes(method)) {
assert.equal(typeof raw.data.sign, 'string', `${method} 没产生签名字段`);
assert.equal(raw.data.sign.length, 40, `${method} 的签名不是 SHA1 40 位`);
}
} }
} for (const method of DOCUMENTED) {
for (const method of DOCUMENTED) { assert.ok(seen.has(method), `${method} 没进逐个复算:接口层登记与需求清单脱节了`);
assert.ok(seen.has(method), `${method} 没进逐个复算:接口层登记与需求清单脱节了`); }
} console.log(
console.log(` · 逐个复算覆盖 ${seen.size} 个出口,需求点名的 ${DOCUMENTED.length} 个全在其中`); ` · 逐个复算覆盖 ${seen.size} 个出口,需求点名的 ${DOCUMENTED.length} 个全在其中`,
}); );
},
);
await check('⑪ .env 里的网关 origin 协议:公网必须 https(http 会被 301 掉请求体)', () => { await check('⑪ .env 里的网关 origin 协议:公网必须 https(http 会被 301 掉请求体)', () => {
// 公网 http 会被 nginx 301 到 https,浏览器跟随 301 时把 POST 降成 GET 并丢掉 body: // 公网 http 会被 nginx 301 到 https,浏览器跟随 301 时把 POST 降成 GET 并丢掉 body:
...@@ -260,7 +274,14 @@ try { ...@@ -260,7 +274,14 @@ try {
.split('\n') .split('\n')
.filter((line) => /^#?\s*VITE_POINTS_\w*GATEWAY_ORIGIN=\S/.test(line)), .filter((line) => /^#?\s*VITE_POINTS_\w*GATEWAY_ORIGIN=\S/.test(line)),
) )
.map((line) => line.replace(/^\s*#\s*/, '').split('=').slice(1).join('=').trim()); .map((line) =>
line
.replace(/^\s*#\s*/, '')
.split('=')
.slice(1)
.join('=')
.trim(),
);
assert.ok(origins.length >= 2, `.env / .env.example 里没读到网关 origin`); assert.ok(origins.length >= 2, `.env / .env.example 里没读到网关 origin`);
for (const raw of origins) { for (const raw of origins) {
const { protocol, hostname } = new URL(raw); const { protocol, hostname } = new URL(raw);
...@@ -282,8 +303,16 @@ try { ...@@ -282,8 +303,16 @@ try {
const ax = axios.create({ const ax = axios.create({
adapter: (config) => { adapter: (config) => {
const h = config.headers; const h = config.headers;
wire = { data: config.data, ct: (h && h.get && h.get('content-type')) || h?.['content-type'] }; wire = {
return Promise.resolve({ data: '{"code":"0","data":[]}', status: 200, headers: {}, config }); data: config.data,
ct: (h && h.get && h.get('content-type')) || h?.['content-type'],
};
return Promise.resolve({
data: '{"code":"0","data":[]}',
status: 200,
headers: {},
config,
});
}, },
}); });
const shell = apiCore.createClient({ const shell = apiCore.createClient({
...@@ -305,7 +334,11 @@ try { ...@@ -305,7 +334,11 @@ try {
'dj.api.shopmall.staff.score.page', 'dj.api.shopmall.staff.score.page',
]) { ]) {
const raw = await apiCore.prepareRpcCall( const raw = await apiCore.prepareRpcCall(
{ gateway: 'scrm-shopmall', method, params: fmt.compactParams({ currentPage: 1, usedCarFlag: '1' }) }, {
gateway: 'scrm-shopmall',
method,
params: fmt.compactParams({ currentPage: 1, usedCarFlag: '1' }),
},
deps, deps,
); );
await shell await shell
...@@ -347,7 +380,10 @@ try { ...@@ -347,7 +380,10 @@ try {
// 我们的 gateway id → 登记的 router(glsx.ts 一处真源) // 我们的 gateway id → 登记的 router(glsx.ts 一处真源)
const glsx = readFileSync('src/adapter/gateways/glsx.ts', 'utf8'); const glsx = readFileSync('src/adapter/gateways/glsx.ts', 'utf8');
const routerOf = new Map( const routerOf = new Map(
[...glsx.matchAll(/id: '([\w-]+)',\s*router: '(rop-[\w-]+)\/router'/g)].map(([, id, r]) => [id, r]), [...glsx.matchAll(/id: '([\w-]+)',\s*router: '(rop-[\w-]+)\/router'/g)].map(([, id, r]) => [
id,
r,
]),
); );
// 老系统没有的出口(门店版 2 个)必须在这里点名,不能靠「查不到就跳过」蒙过去 // 老系统没有的出口(门店版 2 个)必须在这里点名,不能靠「查不到就跳过」蒙过去
...@@ -379,9 +415,14 @@ try { ...@@ -379,9 +415,14 @@ try {
envTable envTable
.split('\n') .split('\n')
.filter((line) => !/^\s*\/\//.test(line)) .filter((line) => !/^\s*\/\//.test(line))
.flatMap((line) => [...line.matchAll(new RegExp(`\\b${kind}: '(https?://[^']+)'`, 'g'))].map((m) => host(m[1]))); .flatMap((line) =>
[...line.matchAll(new RegExp(`\\b${kind}: '(https?://[^']+)'`, 'g'))].map((m) =>
host(m[1]),
),
);
const env = readFileSync('.env', 'utf8'); const env = readFileSync('.env', 'utf8');
const originOf = (key) => (env.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? '').replace(/\/+$/, ''); const originOf = (key) =>
(env.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? '').replace(/\/+$/, '');
const pairs = [ const pairs = [
['rop-scrm-shopmall', originOf('VITE_POINTS_GATEWAY_ORIGIN'), hostsOf('scrm')], ['rop-scrm-shopmall', originOf('VITE_POINTS_GATEWAY_ORIGIN'), hostsOf('scrm')],
['rop-dj-smartcarlife', originOf('VITE_POINTS_DJ_GATEWAY_ORIGIN'), hostsOf('dj')], ['rop-dj-smartcarlife', originOf('VITE_POINTS_DJ_GATEWAY_ORIGIN'), hostsOf('dj')],
...@@ -397,7 +438,11 @@ try { ...@@ -397,7 +438,11 @@ try {
// 那种行由表自己解释,不用我们的配置去背这个锅。 // 那种行由表自己解释,不用我们的配置去背这个锅。
const sharedHosts = new Set(hostsOf('scrm').filter((h) => hostsOf('dj').includes(h))); const sharedHosts = new Set(hostsOf('scrm').filter((h) => hostsOf('dj').includes(h)));
if (!sharedHosts.has(host(pairs[0][1]))) { if (!sharedHosts.has(host(pairs[0][1]))) {
assert.notEqual(host(pairs[0][1]), host(pairs[1][1]), 'scrm 与 dj 配成了同一个域名:dj 路由会被 nginx 挡成 405'); assert.notEqual(
host(pairs[0][1]),
host(pairs[1][1]),
'scrm 与 dj 配成了同一个域名:dj 路由会被 nginx 挡成 405',
);
} }
}); });
...@@ -422,17 +467,23 @@ try { ...@@ -422,17 +467,23 @@ try {
} }
const env = readFileSync('.env', 'utf8'); const env = readFileSync('.env', 'utf8');
const originOf = (key) => (env.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? '').replace(/\/+$/, ''); const originOf = (key) =>
(env.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? '').replace(/\/+$/, '');
const scrmOrigin = originOf('VITE_POINTS_GATEWAY_ORIGIN'); const scrmOrigin = originOf('VITE_POINTS_GATEWAY_ORIGIN');
const djOrigin = originOf('VITE_POINTS_DJ_GATEWAY_ORIGIN'); const djOrigin = originOf('VITE_POINTS_DJ_GATEWAY_ORIGIN');
assert.ok(scrmOrigin && djOrigin, '⑭ 需要 .env 里两个网关 origin 都配上,先看 ⑬ 的报错'); assert.ok(scrmOrigin && djOrigin, '⑭ 需要 .env 里两个网关 origin 都配上,先看 ⑬ 的报错');
const scrm = host(scrmOrigin); const scrm = host(scrmOrigin);
const dj = host(djOrigin); const dj = host(djOrigin);
const matched = [...rows].filter(([, row]) => row.scrm === scrm && row.dj === dj && row.scrm && row.dj); const matched = [...rows].filter(
([, row]) => row.scrm === scrm && row.dj === dj && row.scrm && row.dj,
);
assert.ok( assert.ok(
matched.length > 0, matched.length > 0,
`scrm=${scrm} 与 dj=${dj} 不在环境表的同一行里:会话是分环境的,混用必回 code 21 无效的sessionId。` + `scrm=${scrm} 与 dj=${dj} 不在环境表的同一行里:会话是分环境的,混用必回 code 21 无效的sessionId。` +
`可选行:${[...rows].filter(([, r]) => r.scrm && r.dj).map(([k, r]) => `${k}(${r.scrm} + ${r.dj})`).join(' / ')}`, `可选行:${[...rows]
.filter(([, r]) => r.scrm && r.dj)
.map(([k, r]) => `${k}(${r.scrm} + ${r.dj})`)
.join(' / ')}`,
); );
console.log(` · 两个网关同属环境「${matched[0][0]}」`); console.log(` · 两个网关同属环境「${matched[0][0]}」`);
}); });
...@@ -456,7 +507,11 @@ try { ...@@ -456,7 +507,11 @@ try {
{ gateway, method, params: scope.withUsedCarScope({}) }, { gateway, method, params: scope.withUsedCarScope({}) },
deps, deps,
); );
assert.equal(raw.data.appKey, 'ak', `${method} 没带 appKey:网关回 code 22,请求根本不会被执行`); assert.equal(
raw.data.appKey,
'ak',
`${method} 没带 appKey:网关回 code 22,请求根本不会被执行`,
);
assert.equal( assert.equal(
typeof raw.data.sign === 'string' && raw.data.sign.length === 40, typeof raw.data.sign === 'string' && raw.data.sign.length === 40,
true, true,
...@@ -466,6 +521,78 @@ try { ...@@ -466,6 +521,78 @@ try {
console.log(` · ${seen.size} 个出口逐个核过身份信封与签名`); console.log(` · ${seen.size} 个出口逐个核过身份信封与签名`);
}); });
await check('⑯ 数组与嵌套对象在出口摊平:签名原文与请求体是同一份字节', async () => {
// 线上症状:勾选 3 条做批量操作,全部回 code 25 无效签名。原因是签名原文里写的是
// `ids[214,213,212]`(JSON 串),而请求体里 `ids` 怎么摊开由传输层决定(浏览器发 ids[]=…);
// 网关只会按它真正收到的键名重算。老系统与二手车小程序都先摊平再加签,摊平点现在在请求出口。
const nested = {
ids: ['214', '213'],
tag: { path: { id: 7 } },
nil: null,
empty: [],
drop: undefined,
};
const seen = new Set();
for (const { gateway, method } of endpoints) {
if (seen.has(method)) continue;
seen.add(method);
const { data: body } = await apiCore.prepareRpcCall(
{ gateway, method, params: nested },
deps,
);
assert.ok(!('ids' in body), `${method} 还在发数组本体:编码规则一旦交给传输层就是两套字节`);
assert.equal(body['ids[0]'], '214', `${method} 的 ids 没摊平成 ids[0]`);
assert.equal(body['ids[1]'], '213', `${method} 的 ids 没摊平成 ids[1]`);
assert.equal(body['tag.path.id'], '7', `${method} 的嵌套对象没摊平成 a.b`);
assert.equal(body.nil, '', `${method} 的 null 应摊成空串键(与 qs 同规则)`);
assert.ok(!('empty' in body), `${method} 的空数组该整个键消失`);
assert.ok(!('drop' in body), `${method} 的 undefined 该整个键消失`);
for (const [key, value] of Object.entries(body)) {
assert.ok(
typeof value === 'string' || typeof value === 'number',
`${method} 的 ${key} 不是标量:${JSON.stringify(value)}`,
);
}
// 独立复算一遍:就用网关 solution 里那句算法(SHA1(<secret> 升序 k+v <secret>)),
// 只喂它收到后会看到的键值对,不借 api-core 的签名器。
const plain = Object.keys(body)
.filter((key) => key !== 'sign')
.sort()
.map((key) => `${key}${body[key]}`)
.join('');
assert.equal(
body.sign,
createHash('sha1').update(`sk${plain}sk`).digest('hex').toUpperCase(),
`${method} 的签名与「按请求体字节重算」的结果不一致:网关按请求体验签,不看我们心里怎么想`,
);
}
console.log(` · ${seen.size} 个出口逐个复算了摊平后的签名`);
});
await check('⑰ 后端的原话必须落到页面上:跨 realm 的错误不降级成笼统提示', () => {
// 请求由主壳代理,错误对象属于主壳那个 realm,在子应用里 `instanceof Error === false`。
// 判断写成 instanceof 时,「无效签名」这种明确原因会被吞成「操作失败,请稍后重试」——
// 这一组断言在修复前是红的,它就是防回归的地方。
assert.equal(fmt.errorMessage({ message: '无效签名', code: '25' }), '无效签名(网关码 25)');
assert.equal(
fmt.errorMessage(Object.assign(new Error('无效签名'), { code: 25 })),
'无效签名(网关码 25)',
'本域 Error 与跨 realm 的普通对象要走同一条判断',
);
assert.equal(
fmt.errorMessage({ message: '提现记录不存在' }),
'提现记录不存在',
'没有码就别硬凑括注',
);
assert.equal(fmt.errorMessage('网关无响应'), '网关无响应');
// 只有「什么都没说」时才允许那句兜底话。
assert.equal(fmt.errorMessage(undefined), '操作失败,请稍后重试');
assert.ok(
!fmt.errorMessage({ message: '无效签名', code: '25' }).includes('操作失败'),
'后端已经说了原因,页面不许再用兜底话盖掉',
);
});
console.log(`wire-check 通过:${groups.length} 组断言`); console.log(`wire-check 通过:${groups.length} 组断言`);
groups.forEach((g) => console.log(` ${g}`)); groups.forEach((g) => console.log(` ${g}`));
} finally { } finally {
......
...@@ -81,8 +81,9 @@ export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy { ...@@ -81,8 +81,9 @@ export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy {
...def, ...def,
signer: glsxSha1Signer, signer: glsxSha1Signer,
normalize: normalizeGlsxEnvelope, normalize: normalizeGlsxEnvelope,
// 老网关每次请求固定携带、且参与加签的渠道参数:与老系统 / 真实抓包一致用 'scrm-home'。 // 老网关每次请求固定携带、且参与加签的渠道参数。本域自报 'uj-web-points'(2026-11-10 起,
// 改这个值会直接改变签名原文,联调前不要随意换渠道名。 // 不再是抓包里的老系统渠道 'scrm-home'):网关不拿它校验身份,线上实测照常 code 0,
// 钉值见 packages/api-core/test/glsxSign.test.mjs 的 IT-GLSX-SIGN-005。
fixedParams: { source: 'uj-web-points' }, fixedParams: { source: 'uj-web-points' },
}; };
} }
......
...@@ -95,9 +95,23 @@ export function compactParams(values: Record<string, unknown>): Record<string, u ...@@ -95,9 +95,23 @@ export function compactParams(values: Record<string, unknown>): Record<string, u
return params; return params;
} }
/** 错误提示取后端 message;适配层抛出的 Error 已带人话文案。 */ /**
* 错误提示取后端信封里的原话。
*
* 判断不能写成 `error instanceof Error`:请求由主壳代理,抛出的错误属于主壳那个 realm,
* 在子应用里 instanceof 一律为 false,于是「无效签名」这种明确原因会被吞成
* 「操作失败,请稍后重试」——后端说了什么,页面就该说什么。
* 数字网关码一并带上,报障时可以直接对着网关日志,不用再猜是哪一层失败。
*/
export function errorMessage(error: unknown): string { export function errorMessage(error: unknown): string {
if (error instanceof Error && error.message) return error.message; const e = error as { message?: unknown; code?: unknown } | undefined;
if (typeof error === 'string' && error) return error; const text =
return '操作失败,请稍后重试'; typeof error === 'string'
? error.trim()
: typeof e?.message === 'string'
? e.message.trim()
: '';
if (!text) return '操作失败,请稍后重试';
const code = typeof e?.code === 'number' || typeof e?.code === 'string' ? String(e.code) : '';
return /^\d+$/.test(code) ? `${text}(网关码 ${code})` : text;
} }
...@@ -193,7 +193,11 @@ export default function OrderList() { ...@@ -193,7 +193,11 @@ export default function OrderList() {
/> />
</UCard> </UCard>
{settle.modal} {settle.modal}
<OrderDetailDrawer open={!!detailId} id={detailId ?? ''} onClose={() => setDetailId(undefined)} /> <OrderDetailDrawer
open={!!detailId}
id={detailId ?? ''}
onClose={() => setDetailId(undefined)}
/>
</PageShell> </PageShell>
); );
} }
...@@ -26,3 +26,15 @@ export class RequestError extends Error { ...@@ -26,3 +26,15 @@ export class RequestError extends Error {
if (init.cause !== undefined) this.cause = init.cause; if (init.cause !== undefined) this.cause = init.cause;
} }
} }
/**
* 「是不是 RequestError」只能靠标记字段,不能靠 instanceof。
*
* wujie 子应用跑在自己的 iframe realm 里:主壳 props.request 抛出的错误在子应用侧
* `instanceof Error === false`。用 instanceof 判定会把一条带了人话文案与业务码的失败
* 降级成 `String(err)`,顺带丢掉 code —— 于是业务错误被当成传输错误(多 toast、多重试),
* 页面提示退化成「操作失败,请稍后重试」。`isRequestError` 是实例自有字段,跨 realm 仍在。
*/
export function isRequestError(error: unknown): error is RequestError {
return Boolean(error) && (error as { isRequestError?: unknown }).isRequestError === true;
}
import { createAutoSender, createWxSender, createUniSender, createFetchSender, createHostSender } from '../transport/senders'; import { createAutoSender, createWxSender, createUniSender, createFetchSender, createHostSender } from '../transport/senders';
import { RequestError } from './errors'; import { RequestError, isRequestError } from './errors';
import './polyfill';
import { resolveRequestStrategy } from '../gateway/strategies'; import { resolveRequestStrategy } from '../gateway/strategies';
import type { PreparedRequest, RequestStrategy, SignatureStrategy } from '../gateway/strategies'; import type { PreparedRequest, RequestStrategy, SignatureStrategy } from '../gateway/strategies';
import type { import type {
...@@ -20,7 +21,7 @@ import { ...@@ -20,7 +21,7 @@ import {
requestKey, requestKey,
} from './cancellation'; } from './cancellation';
export { RequestError } from './errors'; export { RequestError, isRequestError } from './errors';
export { export {
cancelRequests, cancelRequests,
setActiveScope, setActiveScope,
...@@ -426,6 +427,37 @@ function buildError(message: string, init: Partial<RequestError> = {}): RequestE ...@@ -426,6 +427,37 @@ function buildError(message: string, init: Partial<RequestError> = {}): RequestE
return new RequestError(message, init); return new RequestError(message, init);
} }
/** 取错误文案:跨 realm 抛来的错误不是本 realm 的 Error 实例,只能认 message 字段。 */
function messageOf(error: unknown): string {
const message = (error as { message?: unknown } | undefined)?.message;
if (typeof message === 'string' && message) return message;
return typeof error === 'string' ? error : String(error);
}
/** 外部(主壳 / 第三方)错误上已有的语义字段,包装时原样带过来,别让 code 在转换里丢掉。 */
function foreignInit(error: unknown): Partial<RequestError> {
const e = error as { code?: string | number; data?: unknown; response?: unknown } | undefined;
const init: Partial<RequestError> = {};
if (e && typeof e.code !== 'undefined' && typeof e.code !== 'object') init.code = e.code;
if (e && typeof e.data !== 'undefined') init.data = e.data;
if (e && typeof e.response !== 'undefined') init.response = e.response;
return init;
}
/**
* 把任意来源的失败归成一份 RequestError。
* 判定用 isRequestError 标记而非 instanceof(见 errors.ts),否则会连带丢掉 code ——
* code 没了,业务失败会被当成传输失败去 toast、去重试。
*/
function wrapError(error: unknown, config?: RequestConfig): RequestError {
if (isRequestError(error)) return error;
return buildError(messageOf(error), {
...foreignInit(error),
cause: error,
...(config ? { config } : {}),
});
}
// PreparedRequest 由 ./strategies 定义并以 import type 引入。 // PreparedRequest 由 ./strategies 定义并以 import type 引入。
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
...@@ -483,7 +515,7 @@ export class Request { ...@@ -483,7 +515,7 @@ export class Request {
promise = promise.then(chain.shift(), chain.shift()); promise = promise.then(chain.shift(), chain.shift());
} }
return promise.catch((error: unknown) => { return promise.catch((error: unknown) => {
const err = error instanceof RequestError ? error : buildError(error instanceof Error ? error.message : String(error), { cause: error }); const err = wrapError(error);
safeEvent(() => merged.events?.error?.(err, merged)); safeEvent(() => merged.events?.error?.(err, merged));
if (merged.errorHandler) return merged.errorHandler(err, merged); if (merged.errorHandler) return merged.errorHandler(err, merged);
throw err; throw err;
...@@ -608,9 +640,7 @@ export class Request { ...@@ -608,9 +640,7 @@ export class Request {
throw buildError('请求已取消', { config, code: 'CANCELLED', cause: error }); throw buildError('请求已取消', { config, code: 'CANCELLED', cause: error });
} }
lastError = error; lastError = error;
const wrapped = error instanceof RequestError const wrapped = wrapError(error, config);
? error
: buildError(error instanceof Error ? error.message : String(error), { cause: error, config });
const isBusiness = wrapped.code !== undefined; const isBusiness = wrapped.code !== undefined;
const shouldRetry = Boolean(retry && attempt < maxAttempts - 1 && (retry.condition ? retry.condition(wrapped) : !isBusiness)); const shouldRetry = Boolean(retry && attempt < maxAttempts - 1 && (retry.condition ? retry.condition(wrapped) : !isBusiness));
if (!shouldRetry) { if (!shouldRetry) {
......
/**
* 环境能力补齐:原生小程序(微信 appservice / 老 webview)运行时没有全局
* `AbortController` / `AbortSignal`,而 api-core 的取消链路(facade 每次 dispatch、
* senders 的超时 / 合并)依赖它们。缺失会直接导致 `AbortController is not defined`,
* 每个请求都崩。这里仅在全局确实不存在时安装最小实现;web / 现代浏览器已有原生
* 实现时本模块为 no-op,绝不覆盖原生。
*
* 最小实现足以支撑 api-core 的全部用法:
* - new AbortController() / controller.signal / controller.abort(reason)
* - signal.aborted / signal.addEventListener('abort', cb) / signal.onabort
* - AbortSignal.timeout(ms)(setTimeout 到点自动 abort)
* - AbortSignal.any(list)(任一输入 abort 即 abort)
* 真·底层中断(fetch / wx.request abort)由各自传输层负责,这里只管 api-core
* 内部的取消状态机,不越界。
*/
function installAbortPolyfill(): void {
const g = globalThis as Record<string, unknown>;
const hasController = typeof g.AbortController !== 'undefined';
const hasSignal = typeof g.AbortSignal !== 'undefined';
if (hasController && hasSignal) return; // 原生齐全,不碰
type AbortListener = (event: unknown) => void;
class PolyAbortSignal {
aborted = false;
reason: unknown = undefined;
onabort: AbortListener | null = null;
private listeners: AbortListener[] = [];
addEventListener(type: 'abort', listener: AbortListener): void {
if (type === 'abort') this.listeners.push(listener);
}
removeEventListener(type: 'abort', listener: AbortListener): void {
if (type === 'abort') {
const i = this.listeners.indexOf(listener);
if (i >= 0) this.listeners.splice(i, 1);
}
}
dispatchEvent(): boolean {
return false;
}
throwIfAborted(): void {
if (this.aborted) {
const e = new Error('AbortError');
(e as Error).name = 'AbortError';
throw e;
}
}
/** @internal 仅由 controller 调用 */
_fire(reason?: unknown): void {
if (this.aborted) return;
this.aborted = true;
this.reason = reason;
const cb = this.onabort;
if (cb) cb({ type: 'abort' });
const list = this.listeners.slice();
this.listeners.length = 0;
for (const l of list) l({ type: 'abort' });
}
}
class PolyAbortController {
readonly signal: PolyAbortSignal;
constructor() {
this.signal = new PolyAbortSignal();
}
abort(reason?: unknown): void {
this.signal._fire(reason);
}
}
const SignalCtor = PolyAbortSignal as unknown as typeof AbortSignal;
// AbortSignal.timeout:到点自动 abort(小程序里 wx.request 自带超时,这里仅补状态机)。
const timeoutFn = function timeout(ms: number): AbortSignal {
const ctrl = new PolyAbortController();
setTimeout(
() => ctrl.abort({ name: 'TimeoutError', message: `signal timed out after ${ms}ms` }),
ms,
);
return ctrl.signal;
} as unknown as typeof AbortSignal.timeout;
// AbortSignal.any:任一输入 abort 即 abort。
const anyFn = function any(signals: AbortSignal[]): AbortSignal {
const ctrl = new PolyAbortController();
for (const s of signals) {
if (s.aborted) {
ctrl.abort(s.reason);
break;
}
s.addEventListener('abort', () => ctrl.abort(s.reason), { once: true } as EventListenerOptions);
}
return ctrl.signal;
} as unknown as typeof AbortSignal.any;
if (!hasController) g.AbortController = PolyAbortController;
if (!hasSignal) {
const S = SignalCtor as unknown as Record<string, unknown>;
S.timeout = timeoutFn;
S.any = anyFn;
g.AbortSignal = SignalCtor;
}
}
installAbortPolyfill();
...@@ -42,6 +42,40 @@ export interface RpcDispatcherDeps extends Omit<RpcPrepareDeps, 'resolveToken'> ...@@ -42,6 +42,40 @@ export interface RpcDispatcherDeps extends Omit<RpcPrepareDeps, 'resolveToken'>
} }
/** /**
* glsx 系网关只认「摊平后的 form 键值对」:数组是 `ids[0]`/`ids[1]`,嵌套对象是 `a.b`,值一律是字符串。
* 老系统、二手车小程序与本域三条链路在这一步同源(`glsx-common/src/util.js#createSign` 与
* `apps/mp/usedcar/utils/request/http.js#flatten` 都先摊平再加签)。
*
* 不摊平会同时错两处:签名原文里是 `ids[214,213,212]`(JSON 串),而请求体里的键名由传输层决定
* (浏览器 axios 发 `ids[]=…`)——网关按它真正收到的键名重算签名,于是 HTTP 200 + `code 25 无效签名`。
* 规则逐条对齐 qs 的 `{arrayFormat:'indices', allowDots:true, encodeValuesOnly:true}`:
* null 留空串键,undefined 与空数组整个键消失。
*/
export function flattenFormParams(params: Record<string, unknown>): Record<string, string> {
const out: Record<string, string> = {};
const walk = (value: unknown, key: string) => {
if (value === undefined) return;
if (value === null) {
out[key] = '';
return;
}
if (Array.isArray(value)) {
value.forEach((item, index) => walk(item, `${key}[${index}]`));
return;
}
if (typeof value === 'object') {
for (const [name, nested] of Object.entries(value as Record<string, unknown>)) {
walk(nested, key ? `${key}.${name}` : name);
}
return;
}
out[key] = String(value);
};
for (const [key, value] of Object.entries(params)) walk(value, key);
return out;
}
/**
* 把一次「业务语义」调用组装成原始传输请求(只组装,不发送)。 * 把一次「业务语义」调用组装成原始传输请求(只组装,不发送)。
* *
* `createRpcDispatcher`(小程序直连)与 `strategies.rpcGateway`(统一 Request 门面) * `createRpcDispatcher`(小程序直连)与 `strategies.rpcGateway`(统一 Request 门面)
...@@ -54,14 +88,14 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi ...@@ -54,14 +88,14 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi
const needsSign = call.signed !== false; const needsSign = call.signed !== false;
// 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;会话标识同样并入并参与签名。 // 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;会话标识同样并入并参与签名。
// effectiveParams 同时驱动请求体与加签原文(与 rop 策略一致:sessionId 既进 body 也进签名)。 // 摊平发生在签名之前:effectiveParams 同时驱动加签原文与请求体,二者因此不可能分叉。
const effectiveParams: Record<string, unknown> = { const effectiveParams = flattenFormParams({
...strategy.fixedParams, ...strategy.fixedParams,
...call.params, ...call.params,
...(deps.session && !call.params[deps.session.name] ...(deps.session && !call.params[deps.session.name]
? { [deps.session.name]: deps.session.value } ? { [deps.session.name]: deps.session.value }
: {}), : {}),
}; });
const body: Record<string, unknown> = { ...effectiveParams, method: call.method }; const body: Record<string, unknown> = { ...effectiveParams, method: call.method };
if (needsSign && !credential.secret) { if (needsSign && !credential.secret) {
throw new Error(`网关 ${call.gateway} 的接口需要加签,但未配置 appKey / secret。`); throw new Error(`网关 ${call.gateway} 的接口需要加签,但未配置 appKey / secret。`);
......
/** /**
* 环境能力补齐必须在任何业务代码前执行:原生小程序运行时没有全局 AbortController /
* AbortSignal,缺失会令每次请求抛 `AbortController is not defined`。仅在全局确实缺失时
* 安装最小实现,web / 现代浏览器有原生实现时本模块为 no-op。
*/
import './core/polyfill';
/**
* @uj/api-core 主入口 —— 对外只有三个统一门面: * @uj/api-core 主入口 —— 对外只有三个统一门面:
* *
* createSigner(options?) 签名器,选型靠 kind / algorithm,不传即最新 glsx SHA1 * createSigner(options?) 签名器,选型靠 kind / algorithm,不传即最新 glsx SHA1
...@@ -24,7 +31,13 @@ export type { ...@@ -24,7 +31,13 @@ export type {
} from './core/types'; } from './core/types';
export { registerGateway, resolveGateway } from './gateway/registry'; export { registerGateway, resolveGateway } from './gateway/registry';
export { createRpcDispatcher, prepareRpcCall, unwrapEnvelope, RpcError } from './gateway/dispatcher'; export {
createRpcDispatcher,
flattenFormParams,
prepareRpcCall,
unwrapEnvelope,
RpcError,
} from './gateway/dispatcher';
export type { RpcDispatcherDeps, RpcPrepareDeps } from './gateway/dispatcher'; export type { RpcDispatcherDeps, RpcPrepareDeps } from './gateway/dispatcher';
// 传输层适配:每种 transport 一个 RequestSender 构造器,由 dispatcher 的 sender 注入。 // 传输层适配:每种 transport 一个 RequestSender 构造器,由 dispatcher 的 sender 注入。
...@@ -112,6 +125,7 @@ export { ...@@ -112,6 +125,7 @@ export {
Defaults, Defaults,
InterceptorManager, InterceptorManager,
RequestError, RequestError,
isRequestError,
cancelRequests, cancelRequests,
setActiveScope, setActiveScope,
getActiveScope, getActiveScope,
......
import type { HttpMethod } from '@uj/contracts'; import type { HttpMethod } from '@uj/contracts';
import type { RawRequest, RawResponse, RequestSender } from '../core/types'; import type { RawRequest, RawResponse, RequestSender } from '../core/types';
import '../core/polyfill';
/** /**
* 主壳请求函数的入参形状(props.request / requestViaHost 的 RemoteRequest 子集)。 * 主壳请求函数的入参形状(props.request / requestViaHost 的 RemoteRequest 子集)。
......
...@@ -74,10 +74,21 @@ test('FT-FAC-001 主入口只暴露三个统一入口,旧具名 API 只在 leg ...@@ -74,10 +74,21 @@ test('FT-FAC-001 主入口只暴露三个统一入口,旧具名 API 只在 leg
assert.equal(typeof core[name], 'function', `主入口应导出 ${name}`); assert.equal(typeof core[name], 'function', `主入口应导出 ${name}`);
} }
const oldNames = [ const oldNames = [
'createMd5Signer', 'createGlsxSha1Signer', 'createSha1Signer', 'createSdkSigner', 'createMd5Signer',
'createHmacSigner', 'createNoneSigner', 'strategies', 'ropPreset', 'rpcGatewayPreset', 'createGlsxSha1Signer',
'createRopClient', 'createWebHostClient', 'createRpcGatewayClient', 'createRestClient', 'createSha1Signer',
'createGscRestClient', 'defineSignatureStrategy', 'createSdkSigner',
'createHmacSigner',
'createNoneSigner',
'strategies',
'ropPreset',
'rpcGatewayPreset',
'createRopClient',
'createWebHostClient',
'createRpcGatewayClient',
'createRestClient',
'createGscRestClient',
'defineSignatureStrategy',
]; ];
for (const name of oldNames) { for (const name of oldNames) {
assert.ok(!(name in core), `主入口不应再导出旧名 ${name}`); assert.ok(!(name in core), `主入口不应再导出旧名 ${name}`);
...@@ -114,7 +125,10 @@ test('FT-FAC-002 createSigner() 不传参即最新 glsx SHA1,与旧预设逐 ...@@ -114,7 +125,10 @@ test('FT-FAC-002 createSigner() 不传参即最新 glsx SHA1,与旧预设逐
test('FT-FAC-003 显式传 algorithm 保留通用工厂语义(老代码不炸)', async () => { test('FT-FAC-003 显式传 algorithm 保留通用工厂语义(老代码不炸)', async () => {
const custom = createSigner({ algorithm: 'md5', secretWrap: 'both', uppercase: true }); const custom = createSigner({ algorithm: 'md5', secretWrap: 'both', uppercase: true });
assert.deepEqual(await custom.fields(SIGN_INPUT), await legacy.createMd5Signer().fields(SIGN_INPUT)); assert.deepEqual(
await custom.fields(SIGN_INPUT),
await legacy.createMd5Signer().fields(SIGN_INPUT),
);
assert.throws(() => createSigner({ kind: 'custom' }), /algorithm/); assert.throws(() => createSigner({ kind: 'custom' }), /algorithm/);
}); });
...@@ -127,7 +141,10 @@ test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind ...@@ -127,7 +141,10 @@ test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind
assert.equal(createStrategy().strategy, legacy.strategies.rpcGateway({}).strategy); assert.equal(createStrategy().strategy, legacy.strategies.rpcGateway({}).strategy);
assert.throws(() => createStrategy({ kind: 'nope' }), /未知的策略 kind/); assert.throws(() => createStrategy({ kind: 'nope' }), /未知的策略 kind/);
const client = createClient({ kind: 'rest', sender: { send: async () => ({ status: 200, data: {} }) } }); const client = createClient({
kind: 'rest',
sender: { send: async () => ({ status: 200, data: {} }) },
});
assert.equal(typeof client.post, 'function'); assert.equal(typeof client.post, 'function');
assert.equal(client.defaults.config.strategy, 'plain'); assert.equal(client.defaults.config.strategy, 'plain');
assert.equal(createClient().defaults.config.strategy, 'rpc-gateway'); assert.equal(createClient().defaults.config.strategy, 'rpc-gateway');
...@@ -143,7 +160,9 @@ test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind ...@@ -143,7 +160,9 @@ test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind
test('FT-CANCEL-001 相同请求 abort 前一个在途请求(后一个成功)', async () => { test('FT-CANCEL-001 相同请求 abort 前一个在途请求(后一个成功)', async () => {
const calls = []; const calls = [];
let markFirstStarted; let markFirstStarted;
const firstStarted = new Promise((resolve) => { markFirstStarted = resolve; }); const firstStarted = new Promise((resolve) => {
markFirstStarted = resolve;
});
const sender = { const sender = {
send(req) { send(req) {
calls.push(req); calls.push(req);
...@@ -251,7 +270,9 @@ test('FT-CANCEL-005 cancelRequests() 不传 scope 取消当前 realm 全部在 ...@@ -251,7 +270,9 @@ test('FT-CANCEL-005 cancelRequests() 不传 scope 取消当前 realm 全部在
test('FT-CANCEL-006 外部 signal(react-query queryFn)abort 会取消请求且不重试', async () => { test('FT-CANCEL-006 外部 signal(react-query queryFn)abort 会取消请求且不重试', async () => {
let attempts = 0; let attempts = 0;
let markStarted; let markStarted;
const started = new Promise((resolve) => { markStarted = resolve; }); const started = new Promise((resolve) => {
markStarted = resolve;
});
const sender = { const sender = {
send(req) { send(req) {
attempts += 1; attempts += 1;
...@@ -299,22 +320,25 @@ test('FT-SIGNAL-001 transport=host 时 signal 透到 props.request(主壳 axio ...@@ -299,22 +320,25 @@ test('FT-SIGNAL-001 transport=host 时 signal 透到 props.request(主壳 axio
test('FT-SIGNAL-002 host 链路取消时,主壳拿到的 signal 真的被 abort', async () => { test('FT-SIGNAL-002 host 链路取消时,主壳拿到的 signal 真的被 abort', async () => {
let hostSignal; let hostSignal;
let markStarted; let markStarted;
const started = new Promise((resolve) => { markStarted = resolve; }); const started = new Promise((resolve) => {
markStarted = resolve;
});
setActiveScope('host-page'); setActiveScope('host-page');
const client = createClient({ const client = createClient({
kind: 'rest', kind: 'rest',
transport: 'host', transport: 'host',
raw: true, raw: true,
baseURL: 'https://api.test', baseURL: 'https://api.test',
hostSend: (req) => new Promise((_resolve, reject) => { hostSend: (req) =>
hostSignal = req.signal; new Promise((_resolve, reject) => {
markStarted(); hostSignal = req.signal;
req.signal?.addEventListener( markStarted();
'abort', req.signal?.addEventListener(
() => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })), 'abort',
{ once: true }, () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
); { once: true },
}), );
}),
}); });
const p = client.post('/host-abort', { a: 1 }); const p = client.post('/host-abort', { a: 1 });
try { try {
...@@ -334,14 +358,21 @@ test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', asy ...@@ -334,14 +358,21 @@ test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', asy
let captured; let captured;
globalThis.fetch = async (_url, init) => { globalThis.fetch = async (_url, init) => {
captured = init; captured = init;
return { status: 200, headers: { get: () => 'application/json' }, json: async () => ({ ok: 1 }) }; return {
status: 200,
headers: { get: () => 'application/json' },
json: async () => ({ ok: 1 }),
};
}; };
try { try {
const sender = createFetchSender(); const sender = createFetchSender();
const ac = new AbortController(); const ac = new AbortController();
await sender.send({ await sender.send({
method: 'POST', url: 'https://api.test/x', data: { a: 1 }, method: 'POST',
signal: ac.signal, timeout: 5000, url: 'https://api.test/x',
data: { a: 1 },
signal: ac.signal,
timeout: 5000,
}); });
assert.ok(captured.signal, 'fetch 应收到合并后的 signal'); assert.ok(captured.signal, 'fetch 应收到合并后的 signal');
ac.abort(); ac.abort();
...@@ -350,3 +381,44 @@ test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', asy ...@@ -350,3 +381,44 @@ test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', asy
globalThis.fetch = originalFetch; globalThis.fetch = originalFetch;
} }
}); });
/**
* wujie 子应用里,主壳 props.request 抛来的错误属于**另一个 realm**:
* `instanceof Error` / `instanceof RequestError` 在本域一律为 false。
* 判定一旦写成 instanceof,错误文案会变成 `String(err)`、code 整个丢失,
* 于是业务失败被当成传输失败(多一次 toast、还会重试),页面提示退化成「操作失败,请稍后重试」。
* 这里用 vm 造一个真·跨 realm 的 Error 来钉住这条。
*/
test('FT-REALM-001 跨 realm 抛来的错误仍保留 message 与 code,且不当成传输错误重试', async () => {
const vm = await import('node:vm');
const foreign = vm.runInNewContext(
`(() => { const e = new Error('无效签名'); e.name = 'RequestError'; e.isRequestError = true; e.code = 25; return e; })()`,
);
assert.equal(foreign instanceof Error, false, '前提:跨 realm 的错误不是本域 Error 实例');
let sends = 0;
const toasts = [];
const api = new core.Request({
strategy: 'plain',
baseURL: 'https://x.test',
retry: 2,
sender: {
async send() {
sends += 1;
throw foreign;
},
},
ui: { toast: (text) => toasts.push(text) },
});
await assert.rejects(
() => api.request({ url: '/a', method: 'GET' }),
(error) => {
assert.equal(error.message, '无效签名', '后端原话必须原样带回来');
assert.equal(error.code, 25, '业务码不能在本域包装里丢掉');
return true;
},
);
assert.equal(sends, 1, '带业务码的失败不是传输错误,不该重试');
assert.deepEqual(toasts, [], '业务失败的提示由调用方决定,门面不重复 toast');
});
...@@ -22,6 +22,7 @@ const { ...@@ -22,6 +22,7 @@ const {
createSigner, createSigner,
registerGateway, registerGateway,
prepareRpcCall, prepareRpcCall,
flattenFormParams,
} = require('../dist/index.cjs'); } = require('../dist/index.cjs');
const HERE = path.dirname(fileURLToPath(import.meta.url)); const HERE = path.dirname(fileURLToPath(import.meta.url));
...@@ -99,15 +100,14 @@ test('IT-GLSX-SIGN-002 MD5 预设与 ROP SHA1 预设都不得命中(防误用 ...@@ -99,15 +100,14 @@ test('IT-GLSX-SIGN-002 MD5 预设与 ROP SHA1 预设都不得命中(防误用
}); });
test('IT-GLSX-SIGN-003 端到端 prepareRpcCall 请求体 = 抓包 11 字段(含 sign)', async () => { test('IT-GLSX-SIGN-003 端到端 prepareRpcCall 请求体 = 抓包 11 字段(含 sign)', async () => {
// source 参与签名,生产渠道值必须与抓包一致,否则整条 golden 就不成立 // 这一条复算的是 2026-11-09 那次抓包的字节,所以按抓包里的渠道名登记网关;
const source = productionSource(); // 生产渠道名另有钉值(见 004 与 005),它同样进签名原文,换名就要重新取一份 golden。
assert.equal(source, CAPTURE.source, '生产网关 fixedParams.source 应与抓包一致');
registerGateway({ registerGateway({
id: 'golden-shopmall', id: 'golden-shopmall',
router: 'rop-scrm-shopmall/router', router: 'rop-scrm-shopmall/router',
tokenHeader: 'token', tokenHeader: 'token',
signer: createSigner({ id: 'golden-shopmall-sha1' }), signer: createSigner({ id: 'golden-shopmall-sha1' }),
fixedParams: { source }, fixedParams: { source: CAPTURE.source },
normalize: (raw) => ({ data: raw }), normalize: (raw) => ({ data: raw }),
}); });
...@@ -158,9 +158,109 @@ test('IT-GLSX-SIGN-004 points 网关源码不得回退到 MD5 预设或改动渠 ...@@ -158,9 +158,109 @@ test('IT-GLSX-SIGN-004 points 网关源码不得回退到 MD5 预设或改动渠
const file = path.join(ROOT, rel); const file = path.join(ROOT, rel);
assert.ok(existsSync(file), `${rel} 应存在`); assert.ok(existsSync(file), `${rel} 应存在`);
const src = readFileSync(file, 'utf8'); const src = readFileSync(file, 'utf8');
assert.ok(/createSigner\(\s*\)/.test(src), `${rel} 必须用新版统一签名器且不传参(默认 glsx SHA1)`); assert.ok(
assert.equal(productionSource(), CAPTURE.source, '渠道值改动会让签名与老网关不一致'); /createSigner\(\s*\)/.test(src),
`${rel} 必须用新版统一签名器且不传参(默认 glsx SHA1)`,
);
// 渠道名是本域自报的(2026-11-10 从老系统的 'scrm-home' 换成 'uj-web-points')。
// 它进签名原文、但不参与身份校验,线上实测 code 0;换名要连同 005 的钉值一起重取。
assert.equal(productionSource(), 'uj-web-points', '渠道值改动会让签名与线上钉值不一致');
assert.ok(!src.includes('createMd5Signer'), `${rel} 不得再用 MD5 旧预设`); assert.ok(!src.includes('createMd5Signer'), `${rel} 不得再用 MD5 旧预设`);
assert.ok(!src.includes("kind: 'md5'"), `${rel} 不得把签名器配成 MD5`); assert.ok(!src.includes("kind: 'md5'"), `${rel} 不得把签名器配成 MD5`);
assert.ok(!src.includes('glxsrMd5Signer'), `${rel} 不得残留旧导出名`); assert.ok(!src.includes('glxsrMd5Signer'), `${rel} 不得残留旧导出名`);
}); });
/**
* 2026-11-10 线上取的一份「数组参数」字节,网关当场认证通过(HTTP 200、code:'0'、data.payAmount=1200)。
* 抓它是因为页面上的批量操作全部回 code 25 无效签名:签名原文里写的是 `ids[214,213,212]`
* (JSON 串),而请求体里 `ids` 这个键怎么摊开由传输层决定,网关按它收到的键名重算必然对不上。
* 老系统与二手车小程序都先摊平成 `ids[0]` 再加签,本域同一份实现见 dispatcher.flattenFormParams。
*/
const LIVE = {
method: 'scrm.api.shopmall.integral.transfer.out.pay.amount',
timestamp: 1794300000000,
sessionId: 'scrm-base-1c3b0d4d-366a-4bf2-b8f7-0572f25aa715-rop',
sign: 'CE6C23DEC362B3E3FBA0BF2793CA3128D80FA9A3',
};
test('IT-GLSX-SIGN-005 数组参数在出口摊平成 ids[0]/ids[1]/ids[2]:签名与请求体同一份字节(线上认证)', async () => {
registerGateway({
id: 'live-shopmall',
router: 'rop-scrm-shopmall/router',
tokenHeader: 'token',
signer: createSigner({ id: 'live-shopmall-sha1' }),
fixedParams: { source: productionSource() },
normalize: (raw) => ({ data: raw }),
});
const realNow = Date.now;
Date.now = () => LIVE.timestamp;
let raw;
try {
raw = await prepareRpcCall(
{
gateway: 'live-shopmall',
method: LIVE.method,
params: { ids: ['214', '213', '212'], canApprove: false, usedCarFlag: '1' },
},
{
resolveCredential: () => ({
origin: 'https://scrm.dev.glsx.com.cn',
appKey: APP_KEY,
secret: SECRET,
version: '1.0.0',
format: 'json',
}),
session: { name: 'sessionId', value: LIVE.sessionId },
},
);
} finally {
Date.now = realNow;
}
const body = raw.data;
assert.deepEqual(Object.keys(body), [
'source',
'ids[0]',
'ids[1]',
'ids[2]',
'canApprove',
'usedCarFlag',
'sessionId',
'method',
'appKey',
'format',
'timestamp',
'v',
'sign',
]);
assert.ok(!('ids' in body), '原始数组键必须已经被摊平掉,否则线上发的就是 ids[]');
assert.equal(body['ids[0]'], '214');
assert.equal(body.canApprove, 'false', '布尔摊平成字符串,与老系统 qs 的产物一致');
// 线上发出去的就是 form 串,值只能是标量;一旦还留着数组或对象,编码方式就归传输层说了算,
// 签名原文与请求体从此两套字节(就是这次 code 25 的成因)。
for (const [key, value] of Object.entries(body)) {
assert.ok(
typeof value === 'string' || typeof value === 'number',
`字段 ${key} 没摊平成标量:${JSON.stringify(value)}`,
);
}
// 这一串不是本地复算出来的:同一份字段集在线上跑通过,网关回 code 0 并给了 payAmount。
assert.equal(body.sign, LIVE.sign, '摊平顺序或值形态一变,网关重算的签名就对不上(code 25)');
});
test('IT-GLSX-SIGN-006 嵌套对象摊平成 a.b,null 留空键、undefined 与空数组整个键消失', () => {
const flat = flattenFormParams({
ids: [],
tag: { path: { id: 7 }, name: null },
drop: undefined,
list: [1, [2, 3]],
});
assert.deepEqual(flat, {
'tag.path.id': '7',
'tag.name': '',
'list[0]': '1',
'list[1][0]': '2',
'list[1][1]': '3',
});
});
...@@ -412,10 +412,11 @@ test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/ ...@@ -412,10 +412,11 @@ test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/
const req = calls[0]; const req = calls[0];
assert.equal(req.url, 'https://rpc.test/rop-st/router'); assert.equal(req.url, 'https://rpc.test/rop-st/router');
assert.equal(req.method, 'POST'); assert.equal(req.method, 'POST');
// 值一律标量字符串:网关只按 form 解析请求体,编码细节不能留给传输层决定(见 dispatcher 摊平)。
assert.deepEqual(req.data, { assert.deepEqual(req.data, {
locale: 'zh_CN', locale: 'zh_CN',
source: 'st', source: 'st',
pageNo: 1, pageNo: '1',
method: 'scrm.api.st.order.page', method: 'scrm.api.st.order.page',
appKey: 'k', appKey: 'k',
sign: 'scrm.api.st.order.page#s', sign: 'scrm.api.st.order.page#s',
...@@ -428,7 +429,7 @@ test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/ ...@@ -428,7 +429,7 @@ test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/
assert.equal(rpcSignInputs.length, 1); assert.equal(rpcSignInputs.length, 1);
assert.equal(rpcSignInputs[0].appKey, 'k'); assert.equal(rpcSignInputs[0].appKey, 'k');
assert.equal(rpcSignInputs[0].secret, 's'); assert.equal(rpcSignInputs[0].secret, 's');
assert.deepEqual(rpcSignInputs[0].params, { locale: 'zh_CN', source: 'st', pageNo: 1 }); assert.deepEqual(rpcSignInputs[0].params, { locale: 'zh_CN', source: 'st', pageNo: '1' });
}); });
test('ST-RPC-003 signed:false 只摘 sign、身份信封照发;unsignedKeys 透传 exclude;业务参数可覆盖 fixedParams', async () => { test('ST-RPC-003 signed:false 只摘 sign、身份信封照发;unsignedKeys 透传 exclude;业务参数可覆盖 fixedParams', async () => {
......
...@@ -731,6 +731,9 @@ importers: ...@@ -731,6 +731,9 @@ importers:
'@tanstack/react-query': '@tanstack/react-query':
specifier: 'catalog:' specifier: 'catalog:'
version: 5.106.1(@types/react@19.3.0)(react@19.3.1) version: 5.106.1(@types/react@19.3.0)(react@19.3.1)
'@uj/api-core':
specifier: workspace:^0.0.0
version: link:../api-core
'@uj/contracts': '@uj/contracts':
specifier: workspace:* specifier: workspace:*
version: link:../contracts version: link:../contracts
......
-- =====================================================================
-- 二手车管理(usedcar)完整重建脚本的回滚
-- 对应 usedcar-menu-complete.sql:删除整棵「二手车管理」子树(menu_code 前缀 10026)。
--
-- 说明:
-- - 先用 dry-run 数一遍要删的行(判据:目录 1 / 页面 12 / 按钮 43 = 56),确认无误再 DELETE。
-- - 10026* 只属于二手车管理模块(门店/系统 10000~10024、积分 10025),不会误删其它模块。
-- - sys_role_menu 按 menu_id 记录关联:外键开启的库必须先清关联,否则删除报错。
-- 清理语句见下方注释,menu_code 前缀对齐后再执行。
-- =====================================================================
USE `yj_service`;
-- 1) dry-run:要删什么,先看数与清单
SELECT `menu_type`, COUNT(*) AS cnt
FROM `sys_menu`
WHERE `menu_code` LIKE '10026%'
GROUP BY `menu_type`;
SELECT `menu_id`, `menu_code`, `parent_code`, `menu_name`, `menu_type`, `perm_code`
FROM `sys_menu`
WHERE `menu_code` LIKE '10026%'
ORDER BY `menu_code`;
-- 2) 先解角色关联(按你库里的表名/字段确认后再放开注释执行)
-- DELETE rm FROM `sys_role_menu` rm
-- JOIN `sys_menu` m ON m.`menu_id` = rm.`menu_id`
-- WHERE m.`menu_code` LIKE '10026%';
-- 3) 删除整棵子树(幂等:跑第二次影响 0 行)
DELETE FROM `sys_menu` WHERE `menu_code` LIKE '10026%';
-- 4) 回查:判据 0 行
SELECT COUNT(*) AS remaining FROM `sys_menu` WHERE `menu_code` LIKE '10026%';
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!