signature.ts 3.82 KB
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
  };
}