Commit b308b9ce by liimin

fix(security): 修复签名参数处理顺序问题并优化参数合并

调整签名生成逻辑,先处理参数再合并系统参数,确保签名正确性
优化请求配置合并逻辑,添加data字段合并支持
更新测试用例中的appId和请求参数
1 parent 9551cfe0
......@@ -86,7 +86,7 @@
// 创建请求实例
const request = new Request({
baseURL: 'http://192.168.3.145:9898/gsc-vcp-web-facade',
appId: 'dj_zhixin',
appId: 'Web_DJia',
appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
timeout:5000,
sentry: {
......@@ -135,6 +135,7 @@
const result = await request.get('/test/param/test', {
params:{
"id":6,
"test":"test",
"objs": ["hehe", "haah"],
"dogs":[{"name":"haogou","age":1},{"name":"拉布拉多","age":2}],
"dogs":{"name":"haogou","age":1},
......@@ -165,10 +166,12 @@
const result = await request.post('/test/param/test',
// 请求体数据
{
"id": 6,
"objs": ["hehe", "haah"],
"dogs": [{"name": "haogou", "age": 1}, {"name": "拉布拉多", "age": 2}],
"dog": {"name": "haogou", "age": 1}
// "id": 6,
// "test": "test",
// "objs": ['hehe', 'haah'],
// "dogs": [{"name": "haogou", "age": 1}, {"name": "拉布拉多", "age": 2}],
// "dog": {"name": "haogou", "age": 1}
}, {
duplicatePrevention: true // 简化配置:直接传入 true
}
......
......@@ -97,6 +97,8 @@ class Defaults implements RequestConfig {
...config,
// 确保params正确合并
params: { ...this.params, ...config.params },
data: { ...this.data, ...config.data },
// 确保headers正确合并
headers: { ...this.headers, ...config.headers },
// 确保response正确合并
......
......@@ -86,22 +86,19 @@ export function generateSignature(options: SignatureOptions): SignatureResult {
// 生成随机字符串和时间戳
const nonce = generateUUID();
const timestamp = Date.now().toString();
// 根据请求方法选择相应的参数处理策略
const normalizedMethod = method.toUpperCase();
const processor = PARAM_PROCESSORS.get(normalizedMethod) || processPostSignatureParams;
const processedParams = processor(params);
// 准备签名参数,先添加系统参数
const allParams: Record<string, any> = {
'X-App-Id': appId,
'X-Nonce': nonce,
'X-Timestamp': timestamp,
...params
...processedParams
};
// 根据请求方法选择相应的参数处理策略
const normalizedMethod = method.toUpperCase();
const processor = PARAM_PROCESSORS.get(normalizedMethod) || processPostSignatureParams;
const processedParams = processor(allParams);
// 构建签名字符串
const stringToSign = buildSignatureString(processedParams, noSignAttr);
const stringToSign = buildSignatureString(allParams, noSignAttr);
// 生成最终签名
const signString = `${stringToSign}&secret=${appSecret}`;
......
......@@ -6,9 +6,9 @@
* 环境类型枚举
*/
export enum EnvironmentType {
WEB = 'web',
MINIPROGRAM = 'miniprogram',
UNIAPP = 'uniapp'
WEB = "web",
MINIPROGRAM = "miniprogram",
UNIAPP = "uniapp",
}
/**
......@@ -18,26 +18,26 @@ export enum EnvironmentType {
export const detectEnvironment = (() => {
// 缓存检测结果
let detectedEnv: EnvironmentType | null = null;
// 返回实际的检测函数
return (): EnvironmentType => {
// 如果已经检测过,直接返回缓存结果
if (detectedEnv !== null) {
return detectedEnv;
}
// 执行环境检测
if (typeof wx !== 'undefined' && wx && 'request' in wx) {
if (typeof wx !== "undefined" && wx && "request" in wx) {
// 小程序环境
detectedEnv = EnvironmentType.MINIPROGRAM;
} else if (typeof uni !== 'undefined' && uni && 'request' in uni) {
} else if (typeof uni !== "undefined" && uni && "request" in uni) {
// uniapp环境
detectedEnv = EnvironmentType.UNIAPP;
} else {
// Web环境
detectedEnv = EnvironmentType.WEB;
}
return detectedEnv;
};
})();
......@@ -47,11 +47,11 @@ export const detectEnvironment = (() => {
*/
export enum ArrayProcessMode {
/** JSON 格式:将数组转换为 JSON 字符串 */
JSON = 'json',
JSON = "json",
/** 索引格式:将数组转换为索引键值对 */
INDEX = 'index',
INDEX = "index",
/** 对象索引格式:将对象数组转换为扁平化的索引键值对,适用于Java后端 */
OBJECT_INDEX = 'object_index'
OBJECT_INDEX = "object_index",
}
/**
......@@ -59,24 +59,22 @@ export enum ArrayProcessMode {
* @param params 原始参数对象
* @returns 处理后的参数对象,数组和对象转换为JSON字符串
*/
export function processParamsAsJson(params: Record<string, any>): Record<string, string> {
export function processParamsAsJson(
params: Record<string, any>
): Record<string, string> {
const result: Record<string, string> = {};
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) {
result[key] = '';
} else if (Array.isArray(value)) {
result[key] = "";
} else if (typeof value === "string" || typeof value === "object") {
// 数组直接转换为 JSON 字符串
result[key] = JSON.stringify(value);
} else if (typeof value === 'object') {
// 对象转换为 JSON 字符串
result[key] = JSON.stringify(value);
} else {
// 基本类型直接使用
result[key] = String(value);
result[key] = value;
}
}
return result;
}
......@@ -85,21 +83,23 @@ export function processParamsAsJson(params: Record<string, any>): Record<string,
* @param params 原始参数对象
* @returns 键值对数组,数组使用索引格式 key[0]=value, key[1]=value
*/
export function processParamsAsIndex(params: Record<string, any>): Array<{key: string, value: string}> {
const result: Array<{key: string, value: string}> = [];
export function processParamsAsIndex(
params: Record<string, any>
): Array<{ key: string; value: string }> {
const result: Array<{ key: string; value: string }> = [];
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) {
result.push({ key, value: '' });
result.push({ key, value: "" });
} else if (Array.isArray(value)) {
// 数组使用索引格式 key[0]=value, key[1]=value
value.forEach((item, index) => {
result.push({
key: `${key}[${index}]`,
value: String(item)
result.push({
key: `${key}[${index}]`,
value: String(item),
});
});
} else if (typeof value === 'object') {
} else if (typeof value === "object") {
// 对象转换为 JSON 字符串
result.push({ key, value: JSON.stringify(value) });
} else {
......@@ -107,7 +107,7 @@ export function processParamsAsIndex(params: Record<string, any>): Array<{key: s
result.push({ key, value: String(value) });
}
}
return result;
}
......@@ -116,37 +116,39 @@ export function processParamsAsIndex(params: Record<string, any>): Array<{key: s
* @param params 原始参数对象
* @returns 键值对数组,对象数组扁平化为 dogs[0].name=value, dogs[0].age=value 格式
*/
export function processParamsAsObjectIndex(params: Record<string, any>): Array<{key: string, value: string}> {
const result: Array<{key: string, value: string}> = [];
export function processParamsAsObjectIndex(
params: Record<string, any>
): Array<{ key: string; value: string }> {
const result: Array<{ key: string; value: string }> = [];
for (const [key, value] of Object.entries(params)) {
if (value === null || value === undefined) {
result.push({ key, value: '' });
result.push({ key, value: "" });
} else if (Array.isArray(value)) {
// 数组中的每个元素
value.forEach((item, index) => {
if (typeof item === 'object' && item !== null) {
if (typeof item === "object" && item !== null) {
// 对象数组:dogs[0].name=value, dogs[0].age=value
for (const [objKey, objValue] of Object.entries(item)) {
result.push({
key: `${key}[${index}].${objKey}`,
value: String(objValue)
result.push({
key: `${key}[${index}].${objKey}`,
value: String(objValue),
});
}
} else {
// 基本类型数组:key[0]=value, key[1]=value
result.push({
key: `${key}[${index}]`,
value: String(item)
result.push({
key: `${key}[${index}]`,
value: String(item),
});
}
});
} else if (typeof value === 'object') {
} else if (typeof value === "object") {
// 单个对象:展开为多个键值对
for (const [objKey, objValue] of Object.entries(value)) {
result.push({
key: `${key}.${objKey}`,
value: String(objValue)
result.push({
key: `${key}.${objKey}`,
value: String(objValue),
});
}
} else {
......@@ -154,7 +156,7 @@ export function processParamsAsObjectIndex(params: Record<string, any>): Array<{
result.push({ key, value: String(value) });
}
}
return result;
}
......@@ -163,12 +165,14 @@ export function processParamsAsObjectIndex(params: Record<string, any>): Array<{
* @param params 原始参数对象
* @returns 处理后的参数对象
*/
export function processGetSignatureParams(params: Record<string, any>): Record<string, string> {
export function processGetSignatureParams(
params: Record<string, any>
): Record<string, string> {
const processedResult = processParamsAsObjectIndex(params);
// OBJECT_INDEX 模式返回的是数组,需要转换为对象
const result: Record<string, string> = {};
(processedResult as Array<{key: string, value: string}>).forEach(item => {
(processedResult as Array<{ key: string; value: string }>).forEach((item) => {
result[item.key] = item.value;
});
return result;
......@@ -179,9 +183,11 @@ export function processGetSignatureParams(params: Record<string, any>): Record<s
* @param params 原始参数对象
* @returns 处理后的参数对象
*/
export function processPostSignatureParams(params: Record<string, any>): Record<string, string> {
export function processPostSignatureParams(
params: Record<string, any>
): Record<string, string> {
const processedResult = processParamsAsJson(params);
// JSON 模式直接返回对象
return processedResult as Record<string, string>;
}
......@@ -193,22 +199,27 @@ export function processPostSignatureParams(params: Record<string, any>): Record<
*/
export function generateUUID(): string {
// 使用crypto API如果可用,否则回退到Math.random
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
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)}`;
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 "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);
});
}
\ No newline at end of file
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!