gscSignature.spec.js 1.23 KB
import { createGscNonce, createGscSignature } from "./gscSignature";

describe("gscSignature", () => {
	it("应按 GSC 规则生成固定签名请求头", () => {
		const headers = createGscSignature({
			appId: "test-app",
			appSecret: "test-secret",
			data: { count: 2, name: "张三" },
			method: "POST",
			nonce: "nonce-1",
			params: { sessionId: "token-1" },
			timestamp: "1700000000000",
		});

		expect(headers).toEqual({
			"X-App-Id": "test-app",
			"X-Nonce": "nonce-1",
			"X-Sign": "f467d9b817628dee7bf819b9a85de443d5f08433d865956b00db4fa5b0e95971",
			"X-Timestamp": "1700000000000",
		});
	});

	it("应忽略空值和 noSignAttr 指定字段", () => {
		const headers = createGscSignature({
			appId: "test-app",
			appSecret: "test-secret",
			data: {
				ignored: "x",
				nullable: null,
				undefinedValue: undefined,
			},
			method: "POST",
			noSignAttr: ["ignored"],
			nonce: "nonce-1",
			params: {},
			timestamp: "1700000000000",
		});

		expect(headers["X-Sign"]).toBe(
			"c63c7a7fc7c0d47ec06d2bae84a41521d74f520501224638c6ce165c37601664",
		);
	});

	it("应生成 UUID v4 格式的随机数", () => {
		expect(createGscNonce()).toMatch(
			/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
		);
	});
});