sign.uts 1.86 KB
import { get, keys, set } from "../../utils/common.uts";
import { sha1 } from "./sha1.uts";

/**
 * 参数签名方法(从 gl_tape/api/request/sign.js 迁移)
 * - 删除原始参数中的 sign 字段
 * - 按 key 字典序排序
 * - 将 null 转为空字符串,对对象使用 JSON.stringify
 * - 拼接为 key + value 字符串,首尾加密钥后做 SHA1,再转大写
 *
 * @param params 原始参数对象(会被浅拷贝,不直接修改入参)
 * @param secret 签名密钥
 * @param noSignAttr 不参与签名的字段列表
 */
export function sign(params: UTSJSONObject, secret: string, noSignAttr: string[] = []): UTSJSONObject {
	// 使用 UTSJSONObject 做一份浅拷贝,避免直接修改原始对象
	const realObj = {} as UTSJSONObject;

	// 先将入参拷贝到 realObj 中,并清理 sign 字段
	const rawKeys = keys(params);
	for (const key of rawKeys) {
		if (key == "sign") {
			continue;
		}
		const value = get(params, key);
		set(realObj, key, value);
	}

	// 再次获取 key 列表并排序,确保签名字段顺序稳定
	const sortedKeys = keys(realObj);
	sortedKeys.sort((a, b) => a.localeCompare(b));

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

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

		set(realObj, key, obj);
	}

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

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

	return realObj;
}