Commit 6aa55dea by liimin

feat: 添加自定义字符串序列化函数并优化签名逻辑

- 新增 stringify 模块替代 qs 库,支持多种数组格式序列化
- 优化签名生成和验证逻辑,支持不参与签名的属性配置
- 更新签名相关类型定义,使字段变为可选
- 调整示例中的测试参数
- 降级 @sentry/browser 版本以解决兼容性问题
1 parent 19ae5ac2
...@@ -116,8 +116,8 @@ ...@@ -116,8 +116,8 @@
// 使用params包裹GET请求参数 // 使用params包裹GET请求参数
const result = await request.get('/dict/sign/test', { const result = await request.get('/dict/sign/test', {
params:{ params:{
id: 10, "id":6,
"objs":["cc","dd","sss"] // 白名单[内的method "objs": ["hehe", "haah"]
} }
}); });
...@@ -136,8 +136,8 @@ ...@@ -136,8 +136,8 @@
// 我们只需要在请求参数中添加method参数 // 我们只需要在请求参数中添加method参数
console.log('发送请求,SDK将自动检查白名单并添加sdctag参数'); console.log('发送请求,SDK将自动检查白名单并添加sdctag参数');
const result = await request.post('/dict/sign/test2', { const result = await request.post('/dict/sign/test2', {
id: 10, "id":6,
"objs":["cc","dd","sss"] // 白名单[外的method "objs": ["hehe", "haah"]
}); });
resultElement.textContent = resultElement.textContent =
`请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`; `请求成功:\n请求参数: ${JSON.stringify(result.config.params, null, 2)}\n\n响应数据: ${JSON.stringify(result.data, null, 2)}`;
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
"version": "1.0.0", "version": "1.0.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@sentry/browser": "^10.11.0", "@sentry/browser": "^7.101.1",
"@types/qs": "^6.14.0", "@types/qs": "^6.14.0",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"qs": "^6.14.0" "qs": "^6.14.0"
...@@ -2499,73 +2499,121 @@ ...@@ -2499,73 +2499,121 @@
"win32" "win32"
] ]
}, },
"node_modules/@sentry-internal/browser-utils": { "node_modules/@sentry-internal/feedback": {
"version": "10.11.0", "version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry-internal/browser-utils/-/browser-utils-10.11.0.tgz", "resolved": "https://registry.npmmirror.com/@sentry-internal/feedback/-/feedback-7.120.4.tgz",
"integrity": "sha512-fnMlz5ntap6x4vRsLOHwPqXh7t82StgAiRt+EaqcMX0t9l8C0w0df8qwrONKXvE5GdHWTNFJj5qR15FERSkg3Q==", "integrity": "sha512-eSwgvTdrh03zYYaI6UVOjI9p4VmKg6+c2+CBQfRZX++6wwnCVsNv7XF7WUIpVGBAkJ0N2oapjQmCzJKGKBRWQg==",
"dependencies": { "dependencies": {
"@sentry/core": "10.11.0" "@sentry/core": "7.120.4",
"@sentry/types": "7.120.4",
"@sentry/utils": "7.120.4"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=12"
} }
}, },
"node_modules/@sentry-internal/feedback": { "node_modules/@sentry-internal/replay-canvas": {
"version": "10.11.0", "version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry-internal/feedback/-/feedback-10.11.0.tgz", "resolved": "https://registry.npmmirror.com/@sentry-internal/replay-canvas/-/replay-canvas-7.120.4.tgz",
"integrity": "sha512-ADey51IIaa29kepb8B7aSgSGSrcyT7QZdRsN1rhitefzrruHzpSUci5c2EPIvmWfKJq8Wnvukm9BHXZXAAIOzA==", "integrity": "sha512-2+W4CgUL1VzrPjArbTid4WhKh7HH21vREVilZdvffQPVwOEpgNTPAb69loQuTlhJVveh9hWTj2nE5UXLbLP+AA==",
"dependencies": { "dependencies": {
"@sentry/core": "10.11.0" "@sentry/core": "7.120.4",
"@sentry/replay": "7.120.4",
"@sentry/types": "7.120.4",
"@sentry/utils": "7.120.4"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=12"
} }
}, },
"node_modules/@sentry-internal/replay": { "node_modules/@sentry-internal/tracing": {
"version": "10.11.0", "version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry-internal/replay/-/replay-10.11.0.tgz", "resolved": "https://registry.npmmirror.com/@sentry-internal/tracing/-/tracing-7.120.4.tgz",
"integrity": "sha512-t4M2bxMp2rKGK/l7bkVWjN+xVw9H9V12jAeXmO/Fskz2RcG1ZNLQnKSx/W/zCRMk8k7xOQFsfiApq+zDN+ziKA==", "integrity": "sha512-Fz5+4XCg3akeoFK+K7g+d7HqGMjmnLoY2eJlpONJmaeT9pXY7yfUyXKZMmMajdE2LxxKJgQ2YKvSCaGVamTjHw==",
"dependencies": { "dependencies": {
"@sentry-internal/browser-utils": "10.11.0", "@sentry/core": "7.120.4",
"@sentry/core": "10.11.0" "@sentry/types": "7.120.4",
"@sentry/utils": "7.120.4"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=8"
} }
}, },
"node_modules/@sentry-internal/replay-canvas": { "node_modules/@sentry/browser": {
"version": "10.11.0", "version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry-internal/replay-canvas/-/replay-canvas-10.11.0.tgz", "resolved": "https://registry.npmmirror.com/@sentry/browser/-/browser-7.120.4.tgz",
"integrity": "sha512-brWQ90IYQyZr44IpTprlmvbtz4l2ABzLdpP94Egh12Onf/q6n4CjLKaA25N5kX0uggHqX1Rs7dNaG0mP3ETHhA==", "integrity": "sha512-ymlNtIPG6HAKzM/JXpWVGCzCNufZNADfy+O/olZuVJW5Be1DtOFyRnBvz0LeKbmxJbXb2lX/XMhuen6PXPdoQw==",
"dependencies": { "dependencies": {
"@sentry-internal/replay": "10.11.0", "@sentry-internal/feedback": "7.120.4",
"@sentry/core": "10.11.0" "@sentry-internal/replay-canvas": "7.120.4",
"@sentry-internal/tracing": "7.120.4",
"@sentry/core": "7.120.4",
"@sentry/integrations": "7.120.4",
"@sentry/replay": "7.120.4",
"@sentry/types": "7.120.4",
"@sentry/utils": "7.120.4"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=8"
} }
}, },
"node_modules/@sentry/browser": { "node_modules/@sentry/core": {
"version": "10.11.0", "version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry/browser/-/browser-10.11.0.tgz", "resolved": "https://registry.npmmirror.com/@sentry/core/-/core-7.120.4.tgz",
"integrity": "sha512-qemaKCJKJHHCyGBpdLq23xL5u9Xvir20XN7YFTnHcEq4Jvj0GoWsslxKi5cQB2JvpYn62WxTiDgVLeQlleZhSg==", "integrity": "sha512-TXu3Q5kKiq8db9OXGkWyXUbIxMMuttB5vJ031yolOl5T/B69JRyAoKuojLBjRv1XX583gS1rSSoX8YXX7ATFGA==",
"dependencies": { "dependencies": {
"@sentry-internal/browser-utils": "10.11.0", "@sentry/types": "7.120.4",
"@sentry-internal/feedback": "10.11.0", "@sentry/utils": "7.120.4"
"@sentry-internal/replay": "10.11.0",
"@sentry-internal/replay-canvas": "10.11.0",
"@sentry/core": "10.11.0"
}, },
"engines": { "engines": {
"node": ">=18" "node": ">=8"
} }
}, },
"node_modules/@sentry/core": { "node_modules/@sentry/integrations": {
"version": "10.11.0", "version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry/core/-/core-10.11.0.tgz", "resolved": "https://registry.npmmirror.com/@sentry/integrations/-/integrations-7.120.4.tgz",
"integrity": "sha512-39Rxn8cDXConx3+SKOCAhW+/hklM7UDaz+U1OFzFMDlT59vXSpfI6bcXtNiFDrbOxlQ2hX8yAqx8YRltgSftoA==", "integrity": "sha512-kkBTLk053XlhDCg7OkBQTIMF4puqFibeRO3E3YiVc4PGLnocXMaVpOSCkMqAc1k1kZ09UgGi8DxfQhnFEjUkpA==",
"dependencies": {
"@sentry/core": "7.120.4",
"@sentry/types": "7.120.4",
"@sentry/utils": "7.120.4",
"localforage": "^1.8.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/@sentry/replay": {
"version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry/replay/-/replay-7.120.4.tgz",
"integrity": "sha512-FW8sPenNFfnO/K7sncsSTX4rIVak9j7VUiLIagJrcqZIC7d1dInFNjy8CdVJUlyz3Y3TOgIl3L3+ZpjfyMnaZg==",
"dependencies": {
"@sentry-internal/tracing": "7.120.4",
"@sentry/core": "7.120.4",
"@sentry/types": "7.120.4",
"@sentry/utils": "7.120.4"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@sentry/types": {
"version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry/types/-/types-7.120.4.tgz",
"integrity": "sha512-cUq2hSSe6/qrU6oZsEP4InMI5VVdD86aypE+ENrQ6eZEVLTCYm1w6XhW1NvIu3UuWh7gZec4a9J7AFpYxki88Q==",
"engines": {
"node": ">=8"
}
},
"node_modules/@sentry/utils": {
"version": "7.120.4",
"resolved": "https://registry.npmmirror.com/@sentry/utils/-/utils-7.120.4.tgz",
"integrity": "sha512-zCKpyDIWKHwtervNK2ZlaK8mMV7gVUijAgFeJStH+CU/imcdquizV3pFLlSQYRswG+Lbyd6CT/LGRh3IbtkCFw==",
"dependencies": {
"@sentry/types": "7.120.4"
},
"engines": { "engines": {
"node": ">=18" "node": ">=8"
} }
}, },
"node_modules/@sinclair/typebox": { "node_modules/@sinclair/typebox": {
...@@ -3713,6 +3761,11 @@ ...@@ -3713,6 +3761,11 @@
"node": ">=10.17.0" "node": ">=10.17.0"
} }
}, },
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmmirror.com/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="
},
"node_modules/import-local": { "node_modules/import-local": {
"version": "3.2.0", "version": "3.2.0",
"resolved": "https://registry.npmmirror.com/import-local/-/import-local-3.2.0.tgz", "resolved": "https://registry.npmmirror.com/import-local/-/import-local-3.2.0.tgz",
...@@ -4649,12 +4702,28 @@ ...@@ -4649,12 +4702,28 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/lie": {
"version": "3.1.1",
"resolved": "https://registry.npmmirror.com/lie/-/lie-3.1.1.tgz",
"integrity": "sha512-RiNhHysUjhrDQntfYSfY4MU24coXXdEOgw9WGcKHNeEwffDYbF//u87M1EWaMGzuFoSbqW0C9C6lEEhDOAswfw==",
"dependencies": {
"immediate": "~3.0.5"
}
},
"node_modules/lines-and-columns": { "node_modules/lines-and-columns": {
"version": "1.2.4", "version": "1.2.4",
"resolved": "https://registry.npmmirror.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz", "resolved": "https://registry.npmmirror.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
"integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
"dev": true "dev": true
}, },
"node_modules/localforage": {
"version": "1.10.0",
"resolved": "https://registry.npmmirror.com/localforage/-/localforage-1.10.0.tgz",
"integrity": "sha512-14/H1aX7hzBBmmh7sGPd+AOMkkIrHM3Z1PAyGgZigA1H1p5O5ANnMyWzvpAETtG68/dC4pC0ncy3+PPGzXZHPg==",
"dependencies": {
"lie": "3.1.1"
}
},
"node_modules/locate-path": { "node_modules/locate-path": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz", "resolved": "https://registry.npmmirror.com/locate-path/-/locate-path-5.0.0.tgz",
......
...@@ -2,7 +2,8 @@ import type { RequestConfig, ResponseData } from '../../types'; ...@@ -2,7 +2,8 @@ import type { RequestConfig, ResponseData } from '../../types';
import { parseHeaders } from '../utils'; import { parseHeaders } from '../utils';
import type { Adapter } from '../types'; import type { Adapter } from '../types';
import { BaseAdapter } from './base'; import { BaseAdapter } from './base';
// import qs from "qs"
import { stringify } from '../../libs';
/** /**
* Web环境适配器实现 * Web环境适配器实现
*/ */
......
import Request from './request'; import Request from './request';
import Defaults from './defaults'; import Defaults from './defaults';
import * as Sentry from './sentry'; import * as Sentry from './sentry';
import { generateSignature, verifySignature } from './signature';
// 导出主类 // 导出主类
export default Request; export default Request;
...@@ -8,6 +9,10 @@ export default Request; ...@@ -8,6 +9,10 @@ export default Request;
// 导出 Defaults 类,方便用户直接使用 // 导出 Defaults 类,方便用户直接使用
export { Defaults, Sentry }; export { Defaults, Sentry };
// 导出签名函数
export { generateSignature, verifySignature };
// 导出类型定义 // 导出类型定义
export type { RequestConfig, ResponseData, RequestHeaders } from './types'; export type { RequestConfig, ResponseData, RequestHeaders } from './types';
export type { SentryOptions, ErrorReportOptions } from './sentry'; export type { SentryOptions, ErrorReportOptions } from './sentry';
export type { SignatureOptions, SignatureResult } from './signature';
\ No newline at end of file \ No newline at end of file
import * as Sentry from './sentry-miniapp' import * as Sentry from './sentry-miniapp'
import { stringify } from './stringify'
// 仅使用ES模块导出 // 仅使用ES模块导出
export { Sentry }
\ No newline at end of file \ No newline at end of file
export { Sentry, stringify }
\ No newline at end of file \ No newline at end of file
/**
* 自建的查询字符串序列化函数,替代 qs.stringify
* 支持类似 qs 的配置选项
*/
export interface StringifyOptions {
arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma';
allowDots?: boolean;
encodeValuesOnly?: boolean;
encode?: boolean;
delimiter?: string;
}
/**
* 将对象序列化为查询字符串
* @param obj 要序列化的对象
* @param options 序列化选项
* @returns 查询字符串
*/
export function stringify(obj: any, options: StringifyOptions = {}): string {
const {
arrayFormat = 'indices',
allowDots = false,
encodeValuesOnly = false,
encode = true,
delimiter = '&'
} = options;
const pairs: string[] = [];
function addPair(key: string, value: any, keyPrefix?: string) {
const finalKey = keyPrefix ? `${keyPrefix}${allowDots ? '.' : '['}${key}${allowDots ? '' : ']'}` : key;
if (value === null) {
pairs.push(encode ? `${encodeURIComponent(finalKey)}=null` : `${finalKey}=null`);
} else if (value === undefined) {
pairs.push(encode ? `${encodeURIComponent(finalKey)}=undefined` : `${finalKey}=undefined`);
} else if (typeof value === 'boolean') {
pairs.push(encode ? `${encodeURIComponent(finalKey)}=${value}` : `${finalKey}=${value}`);
} else if (typeof value === 'number') {
pairs.push(encode ? `${encodeURIComponent(finalKey)}=${value}` : `${finalKey}=${value}`);
} else if (Array.isArray(value)) {
value.forEach((item, index) => {
let arrayKey: string;
switch (arrayFormat) {
case 'indices':
arrayKey = `${finalKey}[${index}]`;
break;
case 'brackets':
arrayKey = `${finalKey}[]`;
break;
case 'repeat':
arrayKey = finalKey;
break;
case 'comma':
// 对于 comma 格式,我们将在最后处理
return;
default:
arrayKey = `${finalKey}[${index}]`;
}
if (typeof item === 'object' && item !== null) {
serializeObject(item, arrayKey);
} else {
const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(arrayKey) : arrayKey;
const encodedValue = encode ? encodeURIComponent(String(item)) : String(item);
pairs.push(`${encodedKey}=${encodedValue}`);
}
});
// 处理 comma 格式
if (arrayFormat === 'comma' && value.length > 0) {
const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(finalKey) : finalKey;
const encodedValues = value.map(item => encode ? encodeURIComponent(String(item)) : String(item));
pairs.push(`${encodedKey}=${encodedValues.join(',')}`);
}
} else if (typeof value === 'object' && value !== null) {
serializeObject(value, finalKey);
} else {
const encodedKey = encode && !encodeValuesOnly ? encodeURIComponent(finalKey) : finalKey;
const encodedValue = encode ? encodeURIComponent(String(value)) : String(value);
pairs.push(`${encodedKey}=${encodedValue}`);
}
}
function serializeObject(obj: any, prefix?: string) {
Object.keys(obj).forEach(key => {
const value = obj[key];
addPair(key, value, prefix);
});
}
serializeObject(obj);
return pairs.join(delimiter);
}
\ No newline at end of file \ No newline at end of file
...@@ -190,18 +190,24 @@ class Request { ...@@ -190,18 +190,24 @@ class Request {
config.params = updatedParams; config.params = updatedParams;
} }
// 合并URL参数和请求体数据用于签名
const signatureParams = { ...config.params };
if (config.data && typeof config.data === 'object') {
Object.assign(signatureParams, config.data);
}
// 使用预先确定的签名函数 // 使用预先确定的签名函数
const signature = this.signFunc({ const signature = this.signFunc({
appId, appId,
appSecret, appSecret,
params: config.params, params: signatureParams,
}); });
// 添加签名到请求头 // 添加签名到请求头
config.headers = { config.headers = {
...config.headers, ...config.headers,
"X-App-Id": appId, "X-App-Id": appId,
"X-Nonce": signature.nonce, ...(signature.nonce && { "X-Nonce": signature.nonce }),
"X-Timestamp": signature.timestamp, ...(signature.timestamp && { "X-Timestamp": signature.timestamp }),
"X-Sign": signature.sign, "X-Sign": signature.sign,
}; };
return config; return config;
......
import CryptoJS from 'crypto-js'; import CryptoJS from 'crypto-js';
import { stringify } from './libs';
export interface SignatureOptions { export interface SignatureOptions {
appId: string; appId: string;
appSecret: string; appSecret: string;
params?: Record<string, any>; params?: Record<string, any>;
noSignAttr?: string[];
} }
export interface SignatureResult { export interface SignatureResult {
nonce: string; nonce?: string;
timestamp: string; timestamp?: string;
sign: string; sign: string;
[key: string]: any;
} }
/** /**
...@@ -32,34 +35,76 @@ function generateUUID(): string { ...@@ -32,34 +35,76 @@ function generateUUID(): string {
* @param {Object} options.params 请求参数 * @param {Object} options.params 请求参数
* @returns {Object} 签名信息 * @returns {Object} 签名信息
*/ */
export function generateSignature({ appId, appSecret, params = {} }: SignatureOptions): SignatureResult { export function generateSignature(options: SignatureOptions): SignatureResult {
const {
appId,
appSecret,
params = {},
noSignAttr = []
} = options;
if (!appId || !appSecret) {
throw new Error('appId and appSecret are required');
}
// 生成随机字符串 // 生成随机字符串
const nonce = generateUUID(); const nonce = generateUUID();
// 生成时间戳 // 生成时间戳
const timestamp = Date.now().toString(); const timestamp =Date.now().toString();
// 准备签名参数 // 准备签名参数,先添加系统参数
const signParams: Record<string, string> = { const allParams = {
'X-App-Id': appId, 'X-App-Id': appId,
'X-Nonce': nonce, 'X-Nonce': nonce,
'X-Timestamp': timestamp, 'X-Timestamp': timestamp,
...params ...params
}; };
// 1. 将所有参数(除sign外)按参数名ASCII码从小到大排序 // 1. 使用 stringify 序列化参数
const sortedKeys = Object.keys(signParams).sort(); const objStr = stringify(allParams, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true
});
// 2. 使用URL键值对格式拼接成字符串 // 2. 解析查询字符串
const stringToSign = sortedKeys const objVal = objStr.split('&');
// .filter(key => key !== 'X-Sign' && signParams[key] !== '' && signParams[key] != null) const realObj: Record<string, any> = {};
.map(key => `${key}=${signParams[key]}`)
.join('&'); objVal.forEach(item => {
const idx = item.indexOf('=');
if (idx !== -1) {
const key = item.split('=')[0];
const value = decodeURIComponent(item.slice(idx + 1));
realObj[key] = value;
}
});
// 3. 拼接应用密钥 // 3. 处理特殊值和对象类型
const signString = `${stringToSign}&secret=${appSecret}`; const keys = Object.keys(realObj).sort();
for (const key in realObj) {
let obj = realObj[key];
if (obj === null) {
obj = '';
} else if (typeof obj === 'object') {
obj = JSON.stringify(obj);
}
realObj[key] = obj;
}
// 4. 排除不参与签名的属性,并拼接签名字符串
const str: string[] = [];
keys.forEach(e => {
if (!noSignAttr.includes(e)) {
str.push(`${e}=${realObj[e]}`);
}
});
// 4. 使用HMAC-SHA256算法计算签名 // 5. 拼接应用密钥并生成签名
const stringToSign = str.join('&');
const signString = `${stringToSign}&secret=${appSecret}`;
const sign = CryptoJS.HmacSHA256(signString, appSecret).toString(); const sign = CryptoJS.HmacSHA256(signString, appSecret).toString();
return { return {
...@@ -71,46 +116,78 @@ export function generateSignature({ appId, appSecret, params = {} }: SignatureOp ...@@ -71,46 +116,78 @@ export function generateSignature({ appId, appSecret, params = {} }: SignatureOp
/** /**
* 验证签名 * 验证签名
* @param {Object} options 签名参数
* @param {string} options.appId 应用ID * @param {string} options.appId 应用ID
* @param {string} options.appSecret 应用密钥 * @param {string} options.appSecret 应用密钥
* @param {string} options.sign 待验证的签名
* @param {string} options.nonce 随机字符串
* @param {string} options.timestamp 时间戳
* @param {Object} options.params 请求参数 * @param {Object} options.params 请求参数
* @returns {boolean} 验证结果 * @returns {boolean} 验证结果
*/ */
export function verifySignature({ export function verifySignature(options: SignatureOptions): boolean {
const {
appId, appId,
appSecret, appSecret,
sign, params = {},
nonce, noSignAttr = []
timestamp, } = options;
params = {}
}: SignatureOptions & { sign: string, nonce: string, timestamp: string }): boolean { if (!appId || !appSecret) {
// 准备签名参数 throw new Error('appId and appSecret are required');
const signParams: Record<string, string> = { }
'X-App-Id': appId,
'X-Nonce': nonce, // 获取传入的签名
'X-Timestamp': timestamp, const receivedSign = params.sign;
...params if (!receivedSign) {
}; return false;
}
// 创建用于验证的参数副本(排除 sign 参数)
const verifyParams = { ...params };
delete verifyParams.sign;
// 1. 使用 stringify 序列化参数
const objStr = stringify(verifyParams, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true
});
// 1. 将所有参数(除sign外)按参数名ASCII码从小到大排序 // 2. 解析查询字符串
const sortedKeys = Object.keys(signParams).sort(); const objVal = objStr.split('&');
const realObj: Record<string, any> = {};
objVal.forEach(item => {
const idx = item.indexOf('=');
if (idx !== -1) {
const key = item.split('=')[0];
const value = decodeURIComponent(item.slice(idx + 1));
realObj[key] = value;
}
});
// 2. 使用URL键值对格式拼接成字符串 // 3. 处理特殊值和对象类型
const stringToSign = sortedKeys const keys = Object.keys(realObj).sort();
// .filter(key => key !== 'X-Sign' && signParams[key] !== '' && signParams[key] != null)
.map(key => `${key}=${signParams[key]}`) for (const key in realObj) {
.join('&'); let obj = realObj[key];
if (obj === null) {
obj = '';
} else if (typeof obj === 'object') {
obj = JSON.stringify(obj);
}
realObj[key] = obj;
}
// 4. 排除不参与签名的属性,并拼接签名字符串
const str: string[] = [];
keys.forEach(e => {
if (!noSignAttr.includes(e)) {
str.push(`${e}=${realObj[e]}`);
}
});
// 3. 拼接应用密钥 // 5. 拼接应用密钥并生成签名
const stringToSign = str.join('&');
const signString = `${stringToSign}&secret=${appSecret}`; const signString = `${stringToSign}&secret=${appSecret}`;
const expectedSign = CryptoJS.HmacSHA256(signString, appSecret).toString();
// 4. 使用HMAC-SHA256算法计算签名 return receivedSign === expectedSign;
const calculatedSign = CryptoJS.HmacSHA256(signString, appSecret).toString();
// 5. 比较签名
return calculatedSign === sign;
} }
\ No newline at end of file \ No newline at end of file
...@@ -46,12 +46,14 @@ export interface SignatureOptions { ...@@ -46,12 +46,14 @@ export interface SignatureOptions {
appId: string; appId: string;
appSecret: string; appSecret: string;
params?: Record<string, any>; params?: Record<string, any>;
noSignAttr?: string[];
} }
export interface SignatureResult { export interface SignatureResult {
nonce: string; nonce?: string;
timestamp: string; timestamp?: string;
sign: string; sign: string;
[key: string]: any;
} }
export interface ResponseData<T = any> { export interface ResponseData<T = any> {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!