Commit 921cdc8d by liimin

feat(security): 重构安全配置和Sentry错误上报功能

- 将sentryDsn和sentryOptions重构为嵌套的sentry配置对象,增加enable开关
- 新增security配置对象,支持白名单功能开关和自定义地址
- 更新相关文档和类型定义
- 修改Request类初始化逻辑,根据配置决定是否启用功能
- 优化白名单检查逻辑,支持自定义地址
1 parent 006694ce
...@@ -336,10 +336,13 @@ const request = new Request({ ...@@ -336,10 +336,13 @@ const request = new Request({
appSecret: 'your_app_secret', appSecret: 'your_app_secret',
// Sentry 配置 // Sentry 配置
sentryDsn: 'https://your-sentry-dsn@sentry.io/project-id', sentry: {
sentryOptions: { enable: true, // 是否启用Sentry错误上报
environment: 'production', dsn: 'https://your-sentry-dsn@sentry.io/project-id',
release: 'v1.0.0' options: {
environment: 'production',
release: 'v1.0.0'
}
} }
}); });
...@@ -380,8 +383,15 @@ const request = new Request({ ...@@ -380,8 +383,15 @@ const request = new Request({
appSecret: '', // 应用密钥(用于签名) appSecret: '', // 应用密钥(用于签名)
headers: {}, // 默认请求头 headers: {}, // 默认请求头
signatureFunc: null, // 自定义签名函数 signatureFunc: null, // 自定义签名函数
sentryDsn: '', // Sentry DSN(用于错误上报) sentry: { // Sentry 错误上报配置
sentryOptions: {}, // Sentry 初始化选项 enable: false, // 是否启用Sentry错误上报,默认为false
dsn: '', // Sentry DSN
options: {} // Sentry 初始化选项
},
security: { // 安全配置
enable: false, // 是否启用白名单功能,默认为false
address: undefined // 自定义白名单地址,默认使用内置地址
},
disableBusinessErrorReport: false // 是否禁用业务错误自动上报 disableBusinessErrorReport: false // 是否禁用业务错误自动上报
}); });
``` ```
...@@ -412,8 +422,15 @@ const request = new Request({ ...@@ -412,8 +422,15 @@ const request = new Request({
appSecret: '', // 应用密钥 appSecret: '', // 应用密钥
signal: AbortSignal, // 用于取消请求的信号 signal: AbortSignal, // 用于取消请求的信号
signatureFunc: Function, // 自定义签名函数 signatureFunc: Function, // 自定义签名函数
sentryDsn: '', // Sentry DSN(用于错误上报) sentry: { // Sentry 错误上报配置
sentryOptions: {}, // Sentry 初始化选项 enable: false, // 是否启用Sentry错误上报
dsn: '', // Sentry DSN
options: {} // Sentry 初始化选项
},
security: { // 安全配置
enable: false, // 是否启用白名单功能,默认为false
address: undefined // 自定义白名单地址,默认使用内置地址
},
disableBusinessErrorReport: false // 是否禁用业务错误自动上报 disableBusinessErrorReport: false // 是否禁用业务错误自动上报
} }
``` ```
......
...@@ -19,15 +19,16 @@ const request = new Request({ ...@@ -19,15 +19,16 @@ const request = new Request({
baseURL: 'https://api.example.com', baseURL: 'https://api.example.com',
// ... 其他配置 // ... 其他配置
// Sentry 配置(必填) // Sentry 配置
sentryDsn: 'https://your-sentry-dsn@sentry.io/project-id', sentry: {
enable: true, // 是否启用Sentry错误上报
// Sentry 初始化选项(可选) dsn: 'https://your-sentry-dsn@sentry.io/project-id',
sentryOptions: { options: { // 可选:Sentry 配置选项
environment: 'production', environment: 'production',
release: 'v1.0.0', release: 'v1.0.0',
debug: false, debug: false,
tracesSampleRate: 0.2 tracesSampleRate: 0.2
}
}, },
// 是否禁用业务逻辑错误自动上报(可选,默认启用) // 是否禁用业务逻辑错误自动上报(可选,默认启用)
...@@ -152,10 +153,13 @@ const request = new Request({ ...@@ -152,10 +153,13 @@ const request = new Request({
timeout: 10000, timeout: 10000,
appId: 'your-app-id', appId: 'your-app-id',
appSecret: 'your-app-secret', appSecret: 'your-app-secret',
sentryDsn: 'https://your-sentry-dsn@sentry.io/project-id', sentry: {
sentryOptions: { enable: true,
environment: 'production', dsn: 'https://your-sentry-dsn@sentry.io/project-id',
release: 'v1.0.0' options: {
environment: 'production',
release: 'v1.0.0'
}
}, },
requestId: `req-${Date.now()}` requestId: `req-${Date.now()}`
}); });
......
...@@ -102,7 +102,14 @@ ...@@ -102,7 +102,14 @@
baseURL: 'http://192.168.1.117:9898/facade', baseURL: 'http://192.168.1.117:9898/facade',
appId: 'dj_zhixin', appId: 'dj_zhixin',
appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b', appSecret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
sentryDsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1', sentry: {
enable: true,
dsn: 'https://be4fb79a912b4c34a5d1c539a1618978@sentry.glsx.com.cn/1'
},
security: {
enable: true,
address: 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=glsx-common' // 自定义地址
}
}); });
// 测试白名单内请求 // 测试白名单内请求
......
...@@ -21,15 +21,23 @@ class Defaults implements RequestConfig { ...@@ -21,15 +21,23 @@ class Defaults implements RequestConfig {
method?: string; method?: string;
url?: string; url?: string;
data?: any; data?: any;
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer'; responseType?: "json" | "text" | "blob" | "arraybuffer";
// 其他可选配置 // 其他可选配置
params?: Record<string, any>; params?: Record<string, any>;
signatureFunc?: typeof generateSignature; signatureFunc?: typeof generateSignature;
httpOptions?: any; httpOptions?: any;
returnAll?: boolean; returnAll?: boolean;
// Sentry 配置 // Sentry 配置
sentryDsn: string; sentry: {
sentryOptions?: Record<string, any>; enable: boolean;
dsn?: string;
options?: Record<string, any>;
};
// 安全配置
security: {
enable: boolean;
address?: string;
};
/** /**
* 创建默认配置实例 * 创建默认配置实例
...@@ -37,37 +45,44 @@ class Defaults implements RequestConfig { ...@@ -37,37 +45,44 @@ class Defaults implements RequestConfig {
*/ */
constructor(config: Partial<RequestConfig> = {}) { constructor(config: Partial<RequestConfig> = {}) {
// 检查必填参数 // 检查必填参数
if (!config.sentryDsn) { if (!config.sentry?.dsn) {
throw new Error('sentryDsn is required for initialization'); throw new Error("sentry.dsn is required for initialization");
} }
// 基础配置 // 基础配置
this.baseURL = config.baseURL || ""; this.baseURL = config.baseURL || "";
this.timeout = config.timeout || 5000; this.timeout = config.timeout || 5000;
this.headers = { this.headers = {
"Content-Type": "application/json;charset=UTF-8", "Content-Type": "application/json;charset=UTF-8",
...config.headers ...config.headers,
}; };
this.appId = config.appId || ""; this.appId = config.appId || "";
this.appSecret = config.appSecret || ""; this.appSecret = config.appSecret || "";
this.sentryDsn = config.sentryDsn; // 设置必填的 sentryDsn this.sentry = {
enable: config.sentry?.enable ?? false,
dsn: config.sentry?.dsn,
options: config.sentry?.options || {},
};
this.security = {
enable: config.security?.enable ?? false,
address: config.security?.address,
};
// 重试配置 // 重试配置
this.retries = config.retries ?? 0; // 默认不重试 this.retries = config.retries ?? 0; // 默认不重试
this.retryDelay = config.retryDelay ?? 300; // 默认重试延迟300ms this.retryDelay = config.retryDelay ?? 300; // 默认重试延迟300ms
this.shouldResetTimeout = config.shouldResetTimeout ?? true; // 默认重试时重置超时 this.shouldResetTimeout = config.shouldResetTimeout ?? true; // 默认重试时重置超时
// 事件订阅配置 // 事件订阅配置
this.events = config.events || {}; this.events = config.events || {};
// 其他可选配置 // 其他可选配置
if (config.params) this.params = { ...config.params }; if (config.params) this.params = { ...config.params };
if (config.signatureFunc) this.signatureFunc = config.signatureFunc; if (config.signatureFunc) this.signatureFunc = config.signatureFunc;
if (config.httpOptions) this.httpOptions = config.httpOptions; if (config.httpOptions) this.httpOptions = config.httpOptions;
if (config.sentryOptions) this.sentryOptions = config.sentryOptions;
// 合并其他用户提供的配置 // 合并其他用户提供的配置
Object.keys(config).forEach(key => { Object.keys(config).forEach((key) => {
if (!(key in this)) { if (!(key in this)) {
(this as any)[key] = (config as any)[key]; (this as any)[key] = (config as any)[key];
} }
...@@ -86,9 +101,9 @@ class Defaults implements RequestConfig { ...@@ -86,9 +101,9 @@ class Defaults implements RequestConfig {
// 确保params正确合并 // 确保params正确合并
params: { ...this.params, ...config.params }, params: { ...this.params, ...config.params },
// 确保headers正确合并 // 确保headers正确合并
headers: { ...this.headers, ...config.headers } headers: { ...this.headers, ...config.headers },
}); });
} }
} }
export default Defaults;
\ No newline at end of file \ No newline at end of file
export default Defaults;
...@@ -70,10 +70,14 @@ class Request { ...@@ -70,10 +70,14 @@ class Request {
// 自动订阅事件 // 自动订阅事件
subscribeEvents(this.defaults.events); subscribeEvents(this.defaults.events);
// 预加载白名单URL列表 // 根据配置决定是否预加载白名单URL列表
preloadWhitelist(); if (this.defaults.security.enable) {
// 初始化 Sentry preloadWhitelist(this.defaults.security.address);
initSentry(this.defaults.sentryDsn, this.defaults.sentryOptions || {}); }
// 根据配置决定是否初始化 Sentry
if (this.defaults.sentry.enable && this.defaults.sentry.dsn) {
initSentry(this.defaults.sentry.dsn, this.defaults.sentry.options || {});
}
} }
/** /**
...@@ -184,12 +188,15 @@ class Request { ...@@ -184,12 +188,15 @@ class Request {
} }
// 获取请求参数 // 获取请求参数
const params = { ...config.params }; const params = { ...config.params };
// 检查当前请求的URL是否在白名单中 // 根据配置决定是否检查白名单
const isInWhitelist = await checkWhitelist(config.url!); if (this.defaults.security.enable) {
// 如果URL在白名单中,将sdctag=true添加到URL和签名参数中 // 检查当前请求的URL是否在白名单中
if (isInWhitelist) { const isInWhitelist = await checkWhitelist(config.url!, this.defaults.security.address);
// 检查URL是否已经包含查询参数 // 如果URL在白名单中,将sdctag=true添加到URL和签名参数中
params.sdctag = "true"; if (isInWhitelist) {
// 检查URL是否已经包含查询参数
params.sdctag = "true";
}
} }
config.params = params; config.params = params;
// 合并URL参数和请求体数据用于签名 // 合并URL参数和请求体数据用于签名
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @Author: limin * @Author: limin
* @Date: 2025-09-09 09:49:02 * @Date: 2025-09-09 09:49:02
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-09-18 00:12:50 * @LastEditTime: 2025-09-18 09:39:49
* @FilePath: \glsk-fetch\src\monitoring\traces.ts * @FilePath: \glsk-fetch\src\monitoring\traces.ts
*/ */
......
...@@ -3,14 +3,19 @@ import Trace from "../monitoring/traces"; ...@@ -3,14 +3,19 @@ import Trace from "../monitoring/traces";
/** /**
* 检查URL是否在白名单中 * 检查URL是否在白名单中
* @param {string} url 当前请求的URL * @param {string} url 当前请求的URL
* @param {string} [customAddress] 自定义白名单地址
* @returns {Promise<boolean>} 是否在白名单中 * @returns {Promise<boolean>} 是否在白名单中
*/ */
export async function checkWhitelist(url: string): Promise<boolean> { export async function checkWhitelist(url: string, customAddress?: string): Promise<boolean> {
// 如果没有URL参数,返回false // 如果没有URL参数,返回false
if (!url) { if (!url) {
return false; return false;
} }
try { try {
// 如果提供了自定义地址,更新TraceManager配置
if (customAddress) {
Trace.updateConfig({ url: customAddress });
}
// 获取白名单URL列表 // 获取白名单URL列表
const whitelistUrls = await Trace.getTraceUrls(); const whitelistUrls = await Trace.getTraceUrls();
// 检查当前请求的URL是否在白名单中 // 检查当前请求的URL是否在白名单中
...@@ -23,10 +28,15 @@ export async function checkWhitelist(url: string): Promise<boolean> { ...@@ -23,10 +28,15 @@ export async function checkWhitelist(url: string): Promise<boolean> {
/** /**
* 预加载白名单URL列表 * 预加载白名单URL列表
* @param {string} [customAddress] 自定义白名单地址
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function preloadWhitelist(): Promise<void> { export async function preloadWhitelist(customAddress?: string): Promise<void> {
try { try {
// 如果提供了自定义地址,更新TraceManager配置
if (customAddress) {
Trace.updateConfig({ url: customAddress });
}
await Trace.preloadTraceUrls(); await Trace.preloadTraceUrls();
console.log('白名单URL预加载完成'); console.log('白名单URL预加载完成');
} catch (error) { } catch (error) {
......
...@@ -7,6 +7,17 @@ export interface RequestHeaders { ...@@ -7,6 +7,17 @@ export interface RequestHeaders {
[key: string]: string | undefined; [key: string]: string | undefined;
} }
export interface SecurityConfig {
enable?: boolean; // 是否启用白名单功能,默认为true
address?: string; // 获取白名单的地址,如果未提供则使用SDK内置默认地址
}
export interface SentryConfig {
enable?: boolean; // 是否启用Sentry错误上报,默认为true
dsn?: string; // Sentry DSN配置
options?: Record<string, any>; // Sentry初始化选项
}
export interface RequestError extends Error { export interface RequestError extends Error {
code: string; code: string;
config: RequestConfig; config: RequestConfig;
...@@ -38,8 +49,8 @@ export interface RequestConfig extends RetryConfig { ...@@ -38,8 +49,8 @@ export interface RequestConfig extends RetryConfig {
events?: Record<string, Function>; // 事件订阅配置 events?: Record<string, Function>; // 事件订阅配置
httpOptions?: any; // HTTP选项 httpOptions?: any; // HTTP选项
returnAll?: boolean; // 是否返回完整响应 returnAll?: boolean; // 是否返回完整响应
sentryDsn?: string; // Sentry DSN 配置(可选,推荐在初始化时设置) sentry?: SentryConfig; // Sentry配置,包含错误上报开关、DSN和选项
sentryOptions?: Record<string, any>; // Sentry 初始化选项 security?: SecurityConfig; // 安全配置,包含白名单功能开关和地址
} }
export interface SignatureOptions { export interface SignatureOptions {
......
...@@ -22,8 +22,8 @@ export class RequestError extends Error { ...@@ -22,8 +22,8 @@ export class RequestError extends Error {
// 确保instanceof正常工作 // 确保instanceof正常工作
Object.setPrototypeOf(this, RequestError.prototype); Object.setPrototypeOf(this, RequestError.prototype);
// 如果配置中包含 sentryDsn,则上报错误到 Sentry // 如果配置中包含 sentry.dsn,则上报错误到 Sentry
if (config && config.sentryDsn) { if (config && config.sentry?.dsn) {
this.reportToSentry(); this.reportToSentry();
} }
} }
......
...@@ -184,4 +184,4 @@ export function processPostSignatureParams(params: Record<string, any>): Record< ...@@ -184,4 +184,4 @@ export function processPostSignatureParams(params: Record<string, any>): Record<
// JSON 模式直接返回对象 // JSON 模式直接返回对象
return processedResult as Record<string, string>; return processedResult as Record<string, string>;
} }
\ No newline at end of file \ 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!