132 lines
2.8 KiB
JavaScript
132 lines
2.8 KiB
JavaScript
'use strict';
|
|
|
|
const assert = require('node:assert/strict');
|
|
const apiSign = require('../../../app/lib/api_sign');
|
|
|
|
describe('test/app/lib/api_sign.test.js', () => {
|
|
it('同一参数不同顺序时签名应一致', () => {
|
|
const left = apiSign.signRequest({
|
|
query: {
|
|
b: '2',
|
|
a: '1',
|
|
sign: 'ignore-me',
|
|
},
|
|
body: {
|
|
z: 2,
|
|
a: 1,
|
|
},
|
|
selfAppSecret: 'secret-1',
|
|
});
|
|
|
|
const right = apiSign.signRequest({
|
|
query: {
|
|
a: '1',
|
|
b: '2',
|
|
signature: 'ignore-me-too',
|
|
},
|
|
body: {
|
|
a: 1,
|
|
z: 2,
|
|
},
|
|
selfAppSecret: 'secret-1',
|
|
});
|
|
|
|
assert.equal(left.sign, right.sign);
|
|
assert.equal(left.canonicalQuery, 'a=1&b=2');
|
|
});
|
|
|
|
it('body 不同时签名应不同', () => {
|
|
const one = apiSign.signRequest({
|
|
query: {
|
|
app_key: 'ak-1',
|
|
method: 'order.create',
|
|
},
|
|
body: {
|
|
orderNo: 'A001',
|
|
qty: 1,
|
|
},
|
|
selfAppSecret: 'secret-1',
|
|
});
|
|
|
|
const two = apiSign.signRequest({
|
|
query: {
|
|
app_key: 'ak-1',
|
|
method: 'order.create',
|
|
},
|
|
body: {
|
|
orderNo: 'A001',
|
|
qty: 2,
|
|
},
|
|
selfAppSecret: 'secret-1',
|
|
});
|
|
|
|
assert.notEqual(one.bodySign, two.bodySign);
|
|
assert.notEqual(one.sign, two.sign);
|
|
});
|
|
|
|
it('缺少 secret 或 providedSign 时应返回可读错误', () => {
|
|
assert.throws(() => {
|
|
apiSign.signRequest({
|
|
query: {
|
|
a: 1,
|
|
},
|
|
body: {},
|
|
selfAppSecret: '',
|
|
});
|
|
}, /selfAppSecret 不能为空/);
|
|
|
|
const verifyResult = apiSign.verifyRequestSign({
|
|
query: {
|
|
a: 1,
|
|
},
|
|
body: {},
|
|
providedSign: '',
|
|
selfAppSecret: 'secret-1',
|
|
});
|
|
|
|
assert.equal(verifyResult.ok, false);
|
|
assert.equal(verifyResult.message, 'providedSign 不能为空');
|
|
});
|
|
|
|
it('verify 成功和失败分支应正确返回', () => {
|
|
const signResult = apiSign.signRequest({
|
|
query: {
|
|
app_key: 'ak-1',
|
|
timestamp: '1711111111',
|
|
},
|
|
body: {
|
|
orderNo: 'B001',
|
|
},
|
|
selfAppSecret: 'secret-1',
|
|
});
|
|
|
|
const success = apiSign.verifyRequestSign({
|
|
query: {
|
|
timestamp: '1711111111',
|
|
app_key: 'ak-1',
|
|
},
|
|
body: {
|
|
orderNo: 'B001',
|
|
},
|
|
providedSign: signResult.sign,
|
|
selfAppSecret: 'secret-1',
|
|
});
|
|
|
|
const failed = apiSign.verifyRequestSign({
|
|
query: {
|
|
timestamp: '1711111111',
|
|
app_key: 'ak-1',
|
|
},
|
|
body: {
|
|
orderNo: 'B001',
|
|
},
|
|
providedSign: 'deadbeef',
|
|
selfAppSecret: 'secret-1',
|
|
});
|
|
|
|
assert.equal(success.ok, true);
|
|
assert.equal(failed.ok, false);
|
|
assert.equal(failed.message, '签名不匹配');
|
|
});
|
|
});
|