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 />;
......
/**
* 数组参数的线上字节钉值:固定 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)}`;
}; };
......
...@@ -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!