httpSign.qs.test.mjs
2.35 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
/**
* @file http 签名对 qs.stringify 的依赖契约(防误删 lib/qs.js)
* 运行:node --test tests/httpSign.qs.test.mjs
*/
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
const require = createRequire(import.meta.url)
const rootDir = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..')
const qs = require(path.join(rootDir, 'utils/lib/qs.js'))
const sha1 = require(path.join(rootDir, 'utils/lib/sha1.js'))
/** 与 utils/request/http.js sign 保持一致,供单测与 qs 替换评估 */
function sign(params, secret, noSignAttr = []) {
delete params.sign
const objStr = qs.stringify(params, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true
})
const objVal = objStr.split('&')
const realObj = {}
objVal.forEach(item => {
const idx = item.indexOf('=')
realObj[item.split('=')[0]] = decodeURIComponent(item.slice(idx + 1))
})
const keys = Object.keys(realObj).sort()
const str = []
let obj = null
for (const key in realObj) {
obj = realObj[key]
if (obj === null) {
obj = ''
} else if (typeof obj === 'object') {
obj = JSON.stringify(obj)
}
realObj[key] = obj
}
keys.forEach(e => {
if (!noSignAttr.includes(e)) str.push(e + realObj[e])
})
realObj.sign = sha1(secret + str.join('') + secret).toUpperCase()
return realObj
}
describe('http sign qs dependency', () => {
it('IT-SIGN-QS-001: sign produces uppercase sha1 sign for flat params', () => {
const secret = 'test-secret'
const params = {
appKey: 'ak',
method: 'dj.api.test',
v: '1.0.0',
format: 'json',
locale: 'zh_CN',
source: 'dj-wechat',
foo: 'bar'
}
const signed = sign({ ...params }, secret, [])
assert.equal(typeof signed.sign, 'string')
assert.match(signed.sign, /^[0-9A-F]{40}$/)
assert.equal(signed.foo, 'bar')
})
it('IT-SIGN-QS-002: noSignAttr excludes keys from sign string', () => {
const secret = 'test-secret'
const base = {
appKey: 'ak',
method: 'dj.api.test',
v: '1.0.0',
format: 'json',
locale: 'zh_CN',
source: 'dj-wechat',
foo: 'bar'
}
const withExclude = sign({ ...base, skip: 'x' }, secret, ['skip'])
const withoutExclude = sign({ ...base, skip: 'x' }, secret, [])
assert.notEqual(withExclude.sign, withoutExclude.sign)
})
})