sign.uts 2.37 KB
import { stringify as qsStringify, StringifyOptions } from "./qs.uts";
import { sha1 } from "./sha1.uts";

/**
 * 参数签名方法(完全对齐 gl_tape/api/request/sign.js)
 * - 先用 qs.stringify 序列化参数
 * - split('&') 拆开后 decodeURIComponent 解码
 * - 按 key 字典序排序
 * - 拼接为 key + value 字符串,首尾加密钥后做 SHA1,再转大写
 * - 最后把 sign 挂到原始参数对象上(保留原始类型)
 *
 * @param params 原始参数对象(会被修改,添加 sign 字段)
 * @param secret 签名密钥
 * @param noSignAttr 不参与签名的字段列表
 */
export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] = []): UTSJSONObject {

	// 1. 用 qs.stringify 序列化(encodeValuesOnly: true)
	const options = {
		// arrayFormat: 'indices', // UTS qs implementation doesn't support arrayFormat yet, default is indices-like
		allowDots: true,
		encodeValuesOnly: true
	} as StringifyOptions;

	const objStr = qsStringify(params, options);
	// 2. split('&') 拆开
	const objVal = objStr.split("&");

	// 3. 解码并重建对象(用于签名计算)
	const realObj: UTSJSONObject = {};
	for (const item of objVal) {
		const idx = item.indexOf("=");
		if (idx == -1) {
			continue;
		}
		const key = item.slice(0, Math.max(0, idx));
		const val = decodeURIComponent(item.slice(Math.max(0, idx + 1)));
		realObj[key] = val;
	}

	// 4. 获取 key 列表并排序
	const sortedKeys: string[] = [];
	for (const key in realObj) {
		if (key === "sign") {
			continue;
		}
		sortedKeys.push(key);
	}
	sortedKeys.sort();

	// 5. 归一化 value:null -> "",对象 -> JSON 字符串
	for (const key of sortedKeys) {
		let obj: any | null = realObj[key];

		if (obj === null) {
			obj = "";
		} else if (typeof obj === "object") {
			obj = JSON.stringify(obj);
		}

		realObj[key] = obj;
	}

	// 6. 组装待签名字符串(排除 noSignAttr 指定的字段)
	const segments: string[] = [];
	for (const key of sortedKeys) {
		if (noSignAttr.indexOf(key) >= 0) {
			continue;
		}
		const val = realObj[key];
		segments.push(key + val);
	}

	// 7. 计算签名:secret + 拼接字符串 + secret
	const signSrc = secret + segments.join("") + secret;
	const signVal = sha1(signSrc).toUpperCase();

	// 8. 把 sign 挂到 realObj 上,返回全字符串的对象(和老项目保持一致)
	realObj.sign = signVal;

	return realObj;
}