Commit 6aa55dea by liimin

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

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