httpSign.qs.test.mjs 2.35 KB
/**
 * @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)
	})
})