sdkSign.test.mjs
2.44 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
/**
* @file createSigner 与 glsx-common-sdk `request/helper.js#createSign` 的钉值对照。
* 输入是已摊平参数(SDK 内部用 qs 摊平,摊平发生在签名前),timestamp 固定以便复算。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import test from 'node:test';
const require = createRequire(import.meta.url);
const { createSigner } = require('../dist/index.cjs');
const TS = 1700000000000;
const SECRET = 'test-secret';
const input = (params, exclude = []) => ({
method: 'x',
params,
timestamp: TS,
appKey: '',
secret: SECRET,
version: '1.0.0',
format: 'json',
exclude,
});
const vectors = [
['扁平参数', [], { method: 'x', appKey: 'k', v: '1.0.0', format: 'json', sessionId: 's1' }],
['嵌套摊平', [], { method: 'x', 'query.page': '1', 'query.tag.a': 'b' }],
['noSignAttr', ['file'], { method: 'x', appKey: 'k', file: 'Zm9v', keep: 'y' }],
['空串/0/false', [], { method: 'x', a: '', c: '0', d: 'false' }],
];
const expected = {
sha1: [
'BC27B5462982BD1DA40289689132CD70CDEABDFF',
'F85D5F9CF7B5CBE3FBCFFA78C6AD365B0906F49E',
'CAF82208DD4E99496A79FFF43A56AB594E8BE412',
'1834B142BD53A74E57929E2DB6C43854A0C65E16',
],
md5: [
'6C6BD58E66A3018802EE140B8C571720',
'D40979D31F4DD5E6CD04E4C1437FEBBC',
'5EB6CA1369334FA6B215A29283A704B8',
'9B068B534E6A2856706D3AE5F4907AC6',
],
};
for (const way of ['sha1', 'md5']) {
test(`IT-SDK-SIGN-${way.toUpperCase()} 与 SDK createSign 逐字节一致`, () => {
const signer = createSigner({ kind: 'sdk', way });
vectors.forEach(([name, exclude, params], i) => {
const fields = signer.fields(input(params, exclude));
assert.equal(fields.timestamp, String(TS), `${name}: timestamp 进请求体且为字符串`);
assert.equal(fields.sign, expected[way][i], name);
});
});
}
test('IT-SDK-SIGN-003 sign 键被剔除,timestamp 不参与 noSignAttr', () => {
const signer = createSigner({ kind: 'sdk' });
const withSign = signer.fields(input({ method: 'x', sign: 'stale', appKey: 'k' }));
const withoutSign = signer.fields(input({ method: 'x', appKey: 'k' }));
assert.equal(withSign.sign, withoutSign.sign);
});
test('IT-SDK-SIGN-004 输出仅含 timestamp 与 sign(其余参数由请求体自带)', () => {
const fields = createSigner({ kind: 'sdk' }).fields(input({ method: 'x', appKey: 'k' }));
assert.deepEqual(Object.keys(fields).sort(), ['sign', 'timestamp']);
});