httpSign.qs.test.mjs 5.35 KB
/**
 * @file http 签名对 qs.stringify 的依赖契约(防误删 lib/qs.js),并钉住迁移到
 * @uj/api-core 之后的签名结果,防止摘要 / 拼接口径被改动。
 * 运行: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'))
const { createSigner } = require('@uj/api-core')

/** 与 utils/request/http.js flatten 保持一致:qs 摊平成实际发送体(嵌套 a.b / 数组 a[0]) */
function flatten(params) {
	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))
	})
	return realObj
}

/** 迁移前 utils/request/http.js 的 sign 实现,保留作等价基准 */
function legacySign(params, secret, noSignAttr = []) {
	delete params.sign
	const realObj = flatten(params)
	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
}

const signer = createSigner({ kind: 'rop', id: 'usedcar-sha1' })

/** 迁移后的加签路径:与 utils/request/http.js sign 同源 */
async function sign(params, secret, noSignAttr = []) {
	delete params.sign
	const flat = flatten(params)
	const signed = await signer.fields({
		method: flat.method,
		appKey: flat.appKey,
		secret,
		version: flat.v,
		format: flat.format,
		params: flat,
		exclude: noSignAttr
	})
	return { ...flat, sign: signed.sign }
}

const SECRET = 'test-secret'
const baseParams = () => ({
	appKey: 'ak',
	method: 'dj.api.test',
	v: '1.0.0',
	format: 'json',
	locale: 'zh_CN',
	source: 'dj-wechat',
	foo: 'bar'
})

/** 迁移当天用 node:crypto 独立复算并核对过的向量;api-core 改动必须仍然命中这些值 */
const pinnedVectors = [
	{ name: '扁平', params: baseParams(), exclude: [], sign: '4158D2F1109BA30B1097C4682CBDA9429B159BEF' },
	{
		name: '中文与数字(merchants 形状)',
		params: { ...baseParams(), merchantId: 44209565, keyword: '联诚' },
		exclude: [],
		sign: '6B10AD24D7C66399F61B061367A944B38EA92FE2'
	},
	{
		name: '嵌套对象',
		params: { ...baseParams(), filter: { status: 2, stage: { code: 'A' } } },
		exclude: [],
		sign: '07C855DFD98DE2D69CC349F2DED94199CC51CB1A'
	},
	{
		name: '数组与数组套对象',
		params: { ...baseParams(), ids: [1, 2], items: [{ sku: 'A1', num: 2 }] },
		exclude: [],
		sign: '34FFE152286DF031EA1E8DEA9B47FDCC90D79625'
	}
]

describe('http sign qs dependency', () => {
	it('IT-SIGN-QS-001: sign produces uppercase sha1 sign for flat params', async () => {
		const signed = await sign({ ...baseParams() }, 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', async () => {
		const withExclude = await sign({ ...baseParams(), skip: 'x' }, SECRET, ['skip'])
		const withoutExclude = await sign({ ...baseParams(), skip: 'x' }, SECRET, [])
		assert.notEqual(withExclude.sign, withoutExclude.sign)
	})

	it('IT-SIGN-QS-003: noSignAttr 的键进 body 但不进签名原文', async () => {
		const excluded = await sign({ ...baseParams(), skip: 'x' }, SECRET, ['skip'])
		const absent = await sign(baseParams(), SECRET, [])
		assert.equal(excluded.skip, 'x', '被排除的字段仍要发出去')
		assert.equal(excluded.sign, absent.sign, '不进原文即等同于原文里没有它')
	})

	it('IT-SIGN-QS-004: 摊平 + api-core 的结果与迁移前 sign 逐字节一致', async () => {
		const shapes = [
			{ params: baseParams(), exclude: [] },
			{ params: { ...baseParams(), skip: 'x', file: 'a=b&c 中文' }, exclude: ['skip'] },
			{ params: { ...baseParams(), filter: { status: 2, stage: { code: 'A' } } }, exclude: [] },
			{ params: { ...baseParams(), ids: [1, 2], items: [{ sku: 'A1', num: 2 }] }, exclude: [] },
			{ params: { ...baseParams(), nil: null, zero: 0, off: false }, exclude: [] }
		]
		for (const shape of shapes) {
			const legacy = legacySign(structuredClone(shape.params), SECRET, shape.exclude)
			const migrated = await sign(structuredClone(shape.params), SECRET, shape.exclude)
			assert.deepEqual(
				Object.keys(migrated).sort(),
				Object.keys(legacy).sort(),
				`实际发送体键集变了:${JSON.stringify(shape.params)}`
			)
			assert.equal(migrated.sign, legacy.sign, `签名变了:${JSON.stringify(shape.params)}`)
		}
	})

	for (const vector of pinnedVectors) {
		it(`IT-SIGN-QS-005: 钉住向量 ${vector.name}`, async () => {
			const signed = await sign(structuredClone(vector.params), SECRET, vector.exclude)
			assert.equal(signed.sign, vector.sign)
		})
	}
})