gsc.test.mjs
8.93 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/**
* @file GSC / glsk 网关适配的钉值对照:头部 HMAC-SHA256 签名、参数摊平、URL/body 组装、
* returnAll / 业务失败 / 登出 / 去重的可观察语义。签名期望值先用 node:crypto 独立复算再钉死,
* 防止「自己对自己」的循环验证。
*/
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { createRequire } from 'node:module';
import test from 'node:test';
const require = createRequire(import.meta.url);
const {
buildGscQuery,
createGscClient,
createGscHeaderSigner,
hmacSha256Sync,
processGscSignParams,
sha256,
} = require('../dist/index.cjs');
const TS = 1700000000000;
const NONCE = '00000000-0000-4000-8000-000000000000';
const SECRET = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b';
const APP_ID = 'App_PromoteBusiness';
const nodeHmac = (message) => createHmac('sha256', SECRET).update(message).digest('hex');
const sign = (method, params, data, exclude = []) =>
createGscHeaderSigner({ now: () => TS, nonce: () => NONCE }).headers({
method,
params,
data,
appKey: APP_ID,
secret: SECRET,
exclude,
});
const verifyHeaderSign = (headers, params, data, method, exclude = []) => {
const processed = processGscSignParams(method, params, data ?? {});
const all = {
'X-App-Id': APP_ID,
'X-Nonce': headers['X-Nonce'],
'X-Timestamp': headers['X-Timestamp'],
...processed,
};
const stringToSign = Object.keys(all)
.sort()
.filter((key) => !exclude.includes(key))
.map((key) => `${key}=${all[key]}`)
.join('&');
assert.equal(headers['X-Sign'], nodeHmac(`${stringToSign}&secret=${SECRET}`));
};
test('IT-GSC-CRYPTO-001 SHA-256 / HMAC-SHA256 与标准向量一致', () => {
assert.equal(sha256('abc'), 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
assert.equal(sha256(''), 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
assert.equal(
hmacSha256Sync('what do ya want for nothing?', 'Jefe'),
'5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843',
);
assert.equal(
hmacSha256Sync('中文签名原文', SECRET),
createHmac('sha256', SECRET).update('中文签名原文').digest('hex'),
);
});
test('IT-GSC-SIGN-002 钉值:POST 合并 data/params,GET 摊平,noSignAttr 剔除', () => {
const post = sign(
'POST',
{ sessionId: 's1' },
{ name: '张三', age: 0, active: false, tags: ['a', 'b'], nested: { x: 1 }, empty: null },
);
assert.equal(post['X-Sign'], 'e7f6be2e6893378a4f8c5b5631ad8c8714c9523d2a173309ccc31142a975f3de');
const get = sign('GET', { a: 1, arr: [1, 2], objs: [{ x: 'y' }], obj: { k: 'v' }, nil: null });
assert.equal(get['X-Sign'], 'ec9e20894365a4b63db4a1d3e6106ad79861dea63a389cb2e5604e21625f22f6');
const excluded = sign('POST', { sessionId: 's1', sign: 'stale' }, { file: 'abc', keep: 'y' }, [
'file',
]);
assert.equal(
excluded['X-Sign'],
'bfcfb70204add786920965f6e467255c0d3696d13a8fa19d5a5fc8fcbe873da7',
);
assert.deepEqual(Object.keys(post).sort(), ['X-App-Id', 'X-Nonce', 'X-Sign', 'X-Timestamp']);
assert.equal(post['X-App-Id'], APP_ID);
assert.equal(post['X-Timestamp'], String(TS));
});
test('IT-GSC-PARAMS-003 GET 签名原文带 params. 前缀,查询串不带', () => {
assert.deepEqual(
processGscSignParams('GET', {
a: 1,
arr: [1, 2],
objs: [{ x: 'y' }],
obj: { k: 'v' },
nil: null,
}),
{
'params.a': '1',
'params.arr': '1,2',
'params.objs': '[object Object]',
'params.obj': '[object Object]',
'params.nil': 'null',
},
);
assert.equal(
buildGscQuery({ a: 1, arr: [1, 2], objs: [{ x: 'y' }], obj: { k: 'v' }, nil: null }),
'a=1&arr%5B0%5D=1&arr%5B1%5D=2&objs%5B0%5D.x=y&obj.k=v&nil=',
);
});
const createMockSender = (respond) => {
const calls = [];
return {
calls,
async send(req) {
calls.push(req);
return { status: 200, data: respond(req) };
},
};
};
const createClient = (respond, extra = {}) => {
const sender = createMockSender(respond);
const events = { success: [], error: [], logout: [], duplicate: [], request: [], response: [] };
const client = createGscClient({
baseURL: 'https://gsc.test.glsx.com.cn/gsc-vcp-pad-facade',
appId: APP_ID,
appSecret: SECRET,
session: { requiresSession: true, sessionParamName: 'sessionId', sessionId: () => 'sid-1' },
response: {
codeKey: 'code',
successCode: '0',
dataKey: 'data',
errId: 'errId',
logoutValue: '21',
},
events: {
success: (body, config) => events.success.push([body, config]),
error: (body) => events.error.push(body),
logout: (body) => events.logout.push(body),
duplicate: (url) => events.duplicate.push(url),
request: (url) => events.request.push(url),
response: (res) => events.response.push(res),
},
signer: createGscHeaderSigner({ now: () => TS, nonce: () => NONCE }),
sender,
...extra,
});
return { client, sender, events };
};
test('IT-GSC-CLIENT-004 POST:sessionId 进 query、body 原样、签名头可独立复算', async () => {
const { client, sender } = createClient(() => ({ code: '0', data: { ok: true } }));
const data = { page: 1, tags: ['a'], nested: { x: 1 } };
await client.post('/minicarManage/findAllSoldPage', data, { params: { pageSize: 10 } });
assert.equal(sender.calls.length, 1);
const req = sender.calls[0];
assert.equal(
req.url,
'https://gsc.test.glsx.com.cn/gsc-vcp-pad-facade/minicarManage/findAllSoldPage?pageSize=10&sessionId=sid-1',
);
assert.deepEqual(req.data, data);
assert.equal(req.method, 'POST');
assert.equal(req.timeout, 15_000);
assert.equal(req.headers['Content-Type'], 'application/json;charset=UTF-8');
verifyHeaderSign(req.headers, { pageSize: 10, sessionId: 'sid-1' }, data, 'POST');
});
test('IT-GSC-CLIENT-005 returnAll 返回 { ...传输响应, data: 响应体 }', async () => {
const body = { code: '1', msg: '业务失败', data: { rows: [] } };
const { client, events } = createClient(() => body);
const res = await client.post('/x', {}, { returnAll: true });
assert.equal(res.status, 200);
assert.deepEqual(res.data, body);
// returnAll 在成功/失败判定之前返回,故不触发 success / error(与旧适配器一致)。
assert.equal(events.success.length, 0);
assert.equal(events.error.length, 0);
});
test('IT-GSC-CLIENT-006 成功码取 dataKey,业务失败返回信封并触发 error', async () => {
const ok = createClient(() => ({ code: '0', data: { id: 7 } }));
assert.deepEqual(await ok.client.post('/x'), { id: 7 });
assert.equal(ok.events.success.length, 1);
const failed = createClient(() => ({ code: 4001, msg: '参数错误', data: null }));
assert.deepEqual(await failed.client.post('/x'), { status: 200, data: null });
assert.equal(failed.events.error.length, 1);
assert.equal(failed.events.error[0].msg, '参数错误');
});
test('IT-GSC-CLIENT-007 登出:code 或 errId 命中 21 都触发 logout', async () => {
const byCode = createClient(() => ({ code: '21', data: { reason: 'expired' } }));
assert.deepEqual(await byCode.client.post('/x'), { status: 200, data: { reason: 'expired' } });
assert.equal(byCode.events.logout.length, 1);
const byErrId = createClient(() => ({ code: '0', errId: 21, data: null }));
assert.deepEqual(await byErrId.client.post('/x'), {
status: 200,
data: { code: '0', errId: 21, data: null },
});
assert.equal(byErrId.events.logout.length, 1);
});
test('IT-GSC-CLIENT-008 duplicatePrevention 拦截进行中的同 URL 请求', async () => {
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
const sender = {
calls: 0,
async send() {
this.calls += 1;
await gate;
return { status: 200, data: { code: '0', data: null } };
},
};
const duplicateEvents = [];
const { client } = createClient(() => ({ code: '0' }), {
sender,
events: { duplicate: (url) => duplicateEvents.push(url) },
});
const first = client.post('/evalOrder/create', { a: 1 }, { duplicatePrevention: true });
await assert.rejects(
client.post('/evalOrder/create', { a: 2 }, { duplicatePrevention: true }),
(err) => err.name === 'DuplicateRequestError',
);
release();
await first;
assert.equal(sender.calls, 1);
assert.deepEqual(duplicateEvents, ['/evalOrder/create']);
});
test('IT-GSC-CLIENT-009 requiresSession 但 sessionId 为空时拒绝', async () => {
const { client, sender } = createClient(() => ({ code: '0' }), {
session: { requiresSession: true, sessionId: () => '' },
});
await assert.rejects(client.post('/x'), /获取到的sessionId无效/);
assert.equal(sender.calls.length, 0);
});
test('IT-GSC-CLIENT-010 未配置 codeKey 时原样返回传输响应', async () => {
const { client } = createClient(() => ({ anything: 1 }), {
response: undefined,
session: {},
});
assert.deepEqual(await client.get('/raw'), { status: 200, data: { anything: 1 } });
});