array-sign-probe.mjs
5.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/**
* 数组参数(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();