gscSignature.js 1.96 KB
import CryptoJS from "crypto-js";

function collectSignatureParams(data = {}, params = {}) {
	const result = {};
	const keys = new Set([...Object.keys(data), ...Object.keys(params)]);
	keys.forEach((key) => {
		const fromParams = Object.prototype.hasOwnProperty.call(params, key);
		const value = fromParams ? params[key] : data[key];
		if (value === null || value === undefined) {
			return;
		}
		if (typeof value === "string") {
			result[key] = fromParams ? value : JSON.stringify(value);
		} else if (typeof value === "object") {
			result[key] = JSON.stringify(value);
		} else {
			result[key] = String(value);
		}
	});
	return result;
}

export function createGscNonce() {
	if (typeof crypto !== "undefined" && crypto.getRandomValues) {
		const bytes = new Uint8Array(16);
		crypto.getRandomValues(bytes);
		bytes[6] = (bytes[6] & 0x0F) | 0x40;
		bytes[8] = (bytes[8] & 0x3F) | 0x80;
		const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
		return [
			hex.slice(0, 8),
			hex.slice(8, 12),
			hex.slice(12, 16),
			hex.slice(16, 20),
			hex.slice(20),
		].join("-");
	}
	return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (character) => {
		const random = Math.floor(Math.random() * 16);
		const value = character === "x" ? random : (random & 0x3) | 0x8;
		return value.toString(16);
	});
}

export function createGscSignature(options) {
	const systemHeaders = {
		"X-App-Id": options.appId,
		"X-Nonce": options.nonce || createGscNonce(),
		"X-Timestamp": String(options.timestamp || Date.now()),
	};
	const signParams = {
		...systemHeaders,
		...collectSignatureParams(options.data, options.params),
	};
	const noSignAttr = options.noSignAttr || [];
	const source = Object.keys(signParams)
		.sort()
		.filter(key => !noSignAttr.includes(key))
		.map(key => `${key}=${signParams[key]}`)
		.join("&");

	return {
		...systemHeaders,
		"X-Sign": CryptoJS.HmacSHA256(
			`${source}&secret=${options.appSecret}`,
			options.appSecret,
		).toString(),
	};
}