signature.ts
3.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import CryptoJS from 'crypto-js';
import { processGetSignatureParams, processPostSignatureParams } from './utils';
export interface SignatureOptions {
appId: string;
appSecret: string;
params?: Record<string, any>;
noSignAttr?: string[];
method?: string;
}
export interface SignatureResult {
nonce: string;
timestamp: string;
sign: string;
[key: string]: any;
}
/**
* 生成UUID v4格式的随机字符串
* 使用更高效的实现方式
* @returns {string} UUID v4格式字符串
*/
function generateUUID(): string {
// 使用crypto API如果可用,否则回退到Math.random
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
// 设置版本号 (4) 和变体位
bytes[6] = (bytes[6] & 0x0f) | 0x40; // 版本4
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, 32)}`;
}
// 回退到原有实现
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
/**
* 验证签名参数
* @param options 签名选项
*/
function validateSignatureOptions(options: SignatureOptions): void {
if (!options) {
throw new Error('Signature options are required');
}
const { appId, appSecret, method } = options;
if (!appId || typeof appId !== 'string' || appId.trim() === '') {
throw new Error('Valid appId is required');
}
if (!appSecret || typeof appSecret !== 'string' || appSecret.trim() === '') {
throw new Error('Valid appSecret is required');
}
if (method && typeof method !== 'string') {
throw new Error('Method must be a string');
}
}
/**
* 构建签名字符串
* @param processedParams 处理后的参数
* @param noSignAttr 不参与签名的属性列表
* @returns 签名字符串
*/
function buildSignatureString(processedParams: Record<string, any>, noSignAttr: string[]): string {
return Object.keys(processedParams)
.sort()
.filter(key => !noSignAttr.includes(key))
.map(key => `${key}=${processedParams[key]}`)
.join('&');
}
/**
* 参数处理策略映射
* 避免每次调用generateSignature时都创建新的Map对象
*/
const PARAM_PROCESSORS = new Map([
['GET', processGetSignatureParams],
['DELETE', processGetSignatureParams],
['POST', processPostSignatureParams],
['PUT', processPostSignatureParams],
['PATCH', processPostSignatureParams]
]);
/**
* 生成签名
* @param options 签名参数
* @returns 签名信息
*/
export function generateSignature(options: SignatureOptions): SignatureResult {
// 参数验证
validateSignatureOptions(options);
const {
appId,
appSecret,
params = {},
noSignAttr = [],
method = 'GET'
} = options;
// 生成随机字符串和时间戳
const nonce = generateUUID();
const timestamp = Date.now().toString();
// 准备签名参数,先添加系统参数
const allParams: Record<string, any> = {
'X-App-Id': appId,
'X-Nonce': nonce,
'X-Timestamp': timestamp,
...params
};
// 根据请求方法选择相应的参数处理策略
const normalizedMethod = method.toUpperCase();
const processor = PARAM_PROCESSORS.get(normalizedMethod) || processPostSignatureParams;
const processedParams = processor(allParams);
// 构建签名字符串
const stringToSign = buildSignatureString(processedParams, noSignAttr);
// 生成最终签名
const signString = `${stringToSign}&secret=${appSecret}`;
const sign = CryptoJS.HmacSHA256(signString, appSecret).toString();
return {
nonce,
timestamp,
sign
};
}