whistle.mock-plugins 1.1.1-beta.2 → 1.1.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -319,7 +319,6 @@ const dataManager = {
319
319
  try {
320
320
  // 读取所有接口数据
321
321
  const data = await this.getInterfaces();
322
- this.log(`读取到接口数据: ${JSON.stringify(data.filter(item => item.enabled === true || item.active === true))}`);
323
322
  // 过滤出启用状态的接口
324
323
  const enabledInterfaces = data.filter(item => item.enabled === true || item.active === true);
325
324
 
@@ -168,22 +168,22 @@ const initRouter = () => {
168
168
  allInterfaces = processedInterfaces;
169
169
  }
170
170
  } else {
171
- // 读取每个功能的接口
172
- features.forEach(feature => {
173
- const interfacesFile = path.join(DATA_DIR, `interfaces-${feature.id}.json`);
174
- if (fs.existsSync(interfacesFile)) {
175
- const interfaces = fs.readJsonSync(interfacesFile);
171
+ // 读取每个功能的接口
172
+ features.forEach(feature => {
173
+ const interfacesFile = path.join(DATA_DIR, `interfaces-${feature.id}.json`);
174
+ if (fs.existsSync(interfacesFile)) {
175
+ const interfaces = fs.readJsonSync(interfacesFile);
176
176
  // 确保每个接口都经过数据处理
177
177
  const processedInterfaces = interfaces.map(item => {
178
178
  const processed = processInterfaceData(item);
179
179
  return {
180
180
  ...processed,
181
- featureName: feature.name
181
+ featureName: feature.name
182
182
  };
183
183
  });
184
184
  allInterfaces = allInterfaces.concat(processedInterfaces);
185
- }
186
- });
185
+ }
186
+ });
187
187
  }
188
188
 
189
189
  console.log(`获取接口列表成功,共 ${allInterfaces.length} 个接口`);
@@ -222,7 +222,7 @@ const ruleManager = {
222
222
  // 收集所有URL匹配的接口
223
223
  const urlMatchedInterfaces = [];
224
224
 
225
- // 先收集所有URL匹配的接口(包括精确匹配和正则匹配)
225
+ // 先收集所有URL匹配的接口(根据proxyType采用不同匹配策略)
226
226
  for (const intf of interfaces) {
227
227
  if (!intf || !intf.urlPattern) {
228
228
  continue;
@@ -240,39 +240,19 @@ const ruleManager = {
240
240
  continue;
241
241
  }
242
242
 
243
- // 检查URL是否匹配
243
+ // 根据proxyType选择匹配策略
244
+ const proxyType = intf.proxyType || 'response';
244
245
  let urlMatches = false;
245
246
 
246
- // 精确匹配
247
- if (intf.urlPattern === requestPath) {
248
- urlMatches = true;
249
- } else {
250
- // 正则表达式匹配
251
- try {
252
- // 从缓存获取或创建正则表达式
253
- if (!this.regexCache) {
254
- this.regexCache = new Map();
255
- }
256
-
257
- let regex;
258
- if (this.regexCache.has(intf.urlPattern)) {
259
- regex = this.regexCache.get(intf.urlPattern);
260
- } else {
261
- // 将通配符转换为正则表达式
262
- const pattern = this.convertPatternToRegex(intf.urlPattern);
263
- regex = new RegExp(pattern);
264
- // 缓存正则表达式,避免重复创建
265
- this.regexCache.set(intf.urlPattern, regex);
266
- }
267
-
268
- urlMatches = regex.test(requestPath);
269
- } catch (err) {
270
- this.log(`[规则处理器] 正则匹配接口 ${intf.name} 时出错: ${err.message}`);
271
- continue;
272
- }
247
+ try {
248
+ urlMatches = this.isUrlMatchByProxyType(requestPath, intf.urlPattern, proxyType, req);
249
+ } catch (err) {
250
+ this.log(`[规则处理器] 匹配接口 ${intf.name} 时出错: ${err.message}`);
251
+ continue;
273
252
  }
274
253
 
275
254
  if (urlMatches) {
255
+ this.log(`[规则处理器] 接口 ${intf.name} URL匹配成功 (${proxyType}模式)`);
276
256
  urlMatchedInterfaces.push(intf);
277
257
  }
278
258
  }
@@ -310,18 +290,109 @@ const ruleManager = {
310
290
  },
311
291
 
312
292
  /**
313
- * 将URL模式中的通配符转换为正则表达式
314
- * @param {string} pattern URL模式
315
- * @returns {string} 正则表达式字符串
293
+ * 根据代理类型进行URL匹配
294
+ * @param {string} requestPath 请求路径
295
+ * @param {string} pattern URL匹配模式
296
+ * @param {string} proxyType 代理类型
297
+ * @param {object} req 请求对象(用于获取完整URL)
298
+ * @returns {boolean} 是否匹配
316
299
  */
317
- convertPatternToRegex(pattern) {
318
- if (pattern.startsWith('/') && pattern.endsWith('/') && pattern.length > 2) {
319
- // 已经是正则表达式格式:/pattern/
320
- return pattern.slice(1, -1);
300
+ isUrlMatchByProxyType(requestPath, pattern, proxyType, req) {
301
+ if (!pattern) return false;
302
+ // 获取完整URL(如果需要)
303
+ const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
304
+
305
+ switch (proxyType) {
306
+ case 'url_redirect':
307
+ // URL重定向:需要完全匹配完整URL
308
+ this.log(`[规则处理器] url_redirect模式 - 完全匹配: ${fullUrl} === ${pattern}`);
309
+ return pattern === fullUrl;
310
+
311
+ case 'redirect':
312
+ // 重定向:前缀匹配
313
+ this.log(`[规则处理器] redirect模式 - 前缀匹配: ${fullUrl}.startsWith(${pattern})`);
314
+ return fullUrl.startsWith(pattern);
315
+
316
+ case 'response':
317
+ case 'file':
318
+ default:
319
+ // 模拟响应和文件代理:支持多种匹配方式
320
+ return this.isUrlMatchForResponse(requestPath, pattern);
321
321
  }
322
-
323
- // 转换通配符 * 为 .*
324
- return pattern.replace(/\*/g, '.*').replace(/\//g, '\\/');
322
+ },
323
+
324
+ /**
325
+ * 响应类型的URL匹配(支持精确匹配、通配符、正则表达式)
326
+ * @param {string} requestPath 请求路径
327
+ * @param {string} pattern URL匹配模式
328
+ * @returns {boolean} 是否匹配
329
+ */
330
+ isUrlMatchForResponse(requestPath, pattern) {
331
+ // 精确匹配
332
+ if (pattern === requestPath) {
333
+ this.log(`[规则处理器] response模式 - 精确匹配成功: ${requestPath}`);
334
+ return true;
335
+ }
336
+
337
+ // 通配符匹配
338
+ if (pattern.includes('*')) {
339
+ try {
340
+ // 从缓存获取或创建正则表达式
341
+ if (!this.regexCache) {
342
+ this.regexCache = new Map();
343
+ }
344
+
345
+ const cacheKey = `wildcard:${pattern}`;
346
+ let regex = this.regexCache.get(cacheKey);
347
+
348
+ if (!regex) {
349
+ // 转换通配符为正则表达式
350
+ const regexPattern = pattern
351
+ .replace(/[-\/\\^$+?.()|[\]{}]/g, '\\$&') // 转义特殊字符
352
+ .replace(/\*/g, '.*'); // 将 * 替换为 .*
353
+
354
+ regex = new RegExp('^' + regexPattern + '$');
355
+ this.regexCache.set(cacheKey, regex);
356
+ }
357
+
358
+ const matches = regex.test(requestPath);
359
+ this.log(`[规则处理器] response模式 - 通配符匹配${matches ? '成功' : '失败'}: ${requestPath} ~ ${pattern}`);
360
+ return matches;
361
+ } catch (err) {
362
+ this.log(`[规则处理器] 通配符匹配错误: ${err.message}`);
363
+ return false;
364
+ }
365
+ }
366
+
367
+ // 正则表达式匹配
368
+ if (pattern.startsWith('/') && pattern.length > 2 && pattern.endsWith('/')) {
369
+ try {
370
+ // 从缓存获取或创建正则表达式
371
+ if (!this.regexCache) {
372
+ this.regexCache = new Map();
373
+ }
374
+
375
+ const cacheKey = `regex:${pattern}`;
376
+ let regex = this.regexCache.get(cacheKey);
377
+
378
+ if (!regex) {
379
+ const regexStr = pattern.slice(1, -1);
380
+ regex = new RegExp(regexStr);
381
+ this.regexCache.set(cacheKey, regex);
382
+ }
383
+
384
+ const matches = regex.test(requestPath);
385
+ this.log(`[规则处理器] response模式 - 正则匹配${matches ? '成功' : '失败'}: ${requestPath} ~ ${pattern}`);
386
+ return matches;
387
+ } catch (err) {
388
+ this.log(`[规则处理器] 正则表达式匹配错误: ${err.message}`);
389
+ return false;
390
+ }
391
+ }
392
+
393
+ // 都不匹配
394
+ this.log(`[规则处理器] response模式 - 所有匹配方式都失败: ${requestPath} != ${pattern}`);
395
+ return false;
325
396
  },
326
397
 
327
398
  /**
@@ -438,38 +509,192 @@ const ruleManager = {
438
509
  const config = interfaceObj.config || interfaceObj;
439
510
  const targetUrl = config.targetUrl || '';
440
511
  const preserveParams = config.preserveParams || false;
441
-
512
+ const proxyType = interfaceObj.proxyType || config.proxyType || '';
513
+
442
514
  if (!targetUrl) {
443
515
  res.end(JSON.stringify({ error: 'No target URL specified' }));
444
516
  return { error: 'No target URL specified' };
445
517
  }
446
-
447
- // 构建重定向URL
518
+
448
519
  let redirectUrl = targetUrl;
520
+
521
+ if (proxyType === 'url_redirect') {
522
+ // url_redirect 只跳转到 targetUrl,不附加原始请求的 query 参数
523
+ redirectUrl = targetUrl;
524
+ } else if (proxyType === 'redirect') {
525
+ // redirect 类型:将 pattern 部分替换为 targetUrl
526
+ const pattern = config.urlPattern || interfaceObj.urlPattern || '';
527
+ const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
528
+ this.log(`[规则处理器] fullUrl : ${fullUrl}`);
529
+ if (pattern && fullUrl && fullUrl.startsWith(pattern)) {
530
+ redirectUrl = targetUrl + fullUrl.slice(pattern.length);
531
+ this.log(`[规则处理器] redirectUrl : ${redirectUrl}`);
532
+ // 保留参数
533
+ if (preserveParams) {
534
+ const parsedReqUrl = url.parse(fullUrl, true);
535
+ const parsedTargetUrl = url.parse(redirectUrl, true);
536
+ const mergedQuery = { ...parsedTargetUrl.query, ...parsedReqUrl.query };
537
+ const redirectUrlObj = new url.URL(redirectUrl);
538
+ Object.entries(mergedQuery).forEach(([key, value]) => {
539
+ redirectUrlObj.searchParams.set(key, value);
540
+ });
541
+ redirectUrl = redirectUrlObj.toString();
542
+ }
543
+ } else {
544
+ // pattern 不匹配,直接跳转到 targetUrl
545
+ redirectUrl = targetUrl;
546
+ }
547
+ } else {
548
+ // 其他类型,默认直接跳转到 targetUrl
549
+ if (preserveParams) {
550
+ const parsedReqUrl = url.parse(req.url, true);
551
+ const parsedTargetUrl = url.parse(targetUrl, true);
552
+ const mergedQuery = { ...parsedTargetUrl.query, ...parsedReqUrl.query };
553
+ const redirectUrlObj = new url.URL(targetUrl);
554
+ Object.entries(mergedQuery).forEach(([key, value]) => {
555
+ redirectUrlObj.searchParams.set(key, value);
556
+ });
557
+ redirectUrl = redirectUrlObj.toString();
558
+ }
559
+ }
560
+
561
+ this.log(`[规则处理器] 准备模拟请求到: ${redirectUrl}`);
562
+
563
+ // 调用模拟请求方法
564
+ await this.simulateRequest(redirectUrl, req, res);
449
565
 
450
- // 如果需要保留参数,则将原请求的查询参数附加到重定向URL
451
- if (preserveParams) {
452
- const parsedUrl = url.parse(req.url, true);
453
- const parsedTargetUrl = url.parse(targetUrl, true);
566
+ return { redirectUrl };
567
+ },
568
+
569
+ /**
570
+ * 模拟请求到目标URL并返回响应数据
571
+ * @param {string} targetUrl 目标URL
572
+ * @param {object} req 原始请求对象
573
+ * @param {object} res 响应对象
574
+ * @returns {Promise<object>} 请求结果
575
+ */
576
+ async simulateRequest(targetUrl, req, res) {
577
+ try {
578
+ const http = require('http');
579
+ const https = require('https');
580
+
581
+ // 解析目标URL
582
+ const urlObj = new URL(targetUrl);
583
+ const isHttps = urlObj.protocol === 'https:';
584
+
585
+ // 准备请求选项
586
+ const options = {
587
+ protocol: urlObj.protocol,
588
+ hostname: urlObj.hostname,
589
+ port: urlObj.port || (isHttps ? 443 : 80),
590
+ path: urlObj.pathname + urlObj.search,
591
+ method: req.method,
592
+ headers: {...req.headers}
593
+ };
594
+
595
+ // 删除可能导致问题的请求头
596
+ delete options.headers.host;
597
+ delete options.headers['x-whistle-real-url'];
598
+ delete options.headers['x-whistle-rule-value'];
599
+ delete options.headers['x-forwarded-url'];
454
600
 
455
- // 合并查询参数
456
- const mergedQuery = { ...parsedTargetUrl.query, ...parsedUrl.query };
601
+ // 设置正确的Host头
602
+ options.headers.host = urlObj.host;
457
603
 
458
- // 重建URL
459
- const redirectUrlObj = new url.URL(targetUrl);
460
- Object.entries(mergedQuery).forEach(([key, value]) => {
461
- redirectUrlObj.searchParams.set(key, value);
604
+ this.log(`[规则处理器] 发送 ${req.method} 请求到: ${targetUrl}`);
605
+
606
+ // 选择http或https模块
607
+ const httpModule = isHttps ? https : http;
608
+
609
+ // 创建请求并返回Promise
610
+ return new Promise((resolve, reject) => {
611
+ const proxyReq = httpModule.request(options, (proxyRes) => {
612
+ this.log(`[规则处理器] 收到响应,状态码: ${proxyRes.statusCode}`);
613
+
614
+ // 复制响应头
615
+ Object.keys(proxyRes.headers).forEach(key => {
616
+ res.setHeader(key, proxyRes.headers[key]);
617
+ });
618
+
619
+ // 设置状态码
620
+ res.statusCode = proxyRes.statusCode;
621
+
622
+ // 传输响应体
623
+ proxyRes.pipe(res);
624
+
625
+ // 收集响应数据用于返回结果
626
+ let responseData = '';
627
+ proxyRes.on('data', chunk => {
628
+ responseData += chunk;
629
+ });
630
+
631
+ proxyRes.on('end', () => {
632
+ this.log(`[规则处理器] 请求完成,响应大小: ${responseData.length} 字节`);
633
+ resolve({
634
+ statusCode: proxyRes.statusCode,
635
+ responseSize: responseData.length,
636
+ contentType: proxyRes.headers['content-type']
637
+ });
638
+ });
639
+ });
640
+
641
+ // 错误处理
642
+ proxyReq.on('error', (error) => {
643
+ this.log(`[规则处理器] 请求 ${targetUrl} 时出错: ${error.message}`);
644
+
645
+ // 如果响应尚未发送,返回错误信息
646
+ if (!res.headersSent) {
647
+ res.statusCode = 502;
648
+ res.end(JSON.stringify({
649
+ error: '转发请求失败',
650
+ message: error.message,
651
+ targetUrl: targetUrl
652
+ }));
653
+ }
654
+
655
+ reject(error);
656
+ });
657
+
658
+ // 处理超时
659
+ proxyReq.setTimeout(30000, () => {
660
+ this.log(`[规则处理器] 请求 ${targetUrl} 超时`);
661
+ const timeoutError = new Error('请求超时');
662
+ proxyReq.destroy(timeoutError);
663
+ reject(timeoutError);
664
+ });
665
+
666
+ // 转发请求体
667
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
668
+ // 如果请求有体,则转发
669
+ if (req.readable) {
670
+ req.pipe(proxyReq);
671
+ } else {
672
+ // 如果请求体已被读取,尝试重建并发送
673
+ if (req.body) {
674
+ const bodyStr = typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
675
+ proxyReq.write(bodyStr);
676
+ proxyReq.end();
677
+ } else {
678
+ proxyReq.end();
679
+ }
680
+ }
681
+ } else {
682
+ // 对于GET和HEAD请求,直接结束请求
683
+ proxyReq.end();
684
+ }
462
685
  });
463
686
 
464
- redirectUrl = redirectUrlObj.toString();
687
+ } catch (error) {
688
+ this.log(`[规则处理器] 准备请求时发生错误: ${error.message}`);
689
+ res.statusCode = 500;
690
+ res.end(JSON.stringify({
691
+ error: '内部服务器错误',
692
+ message: error.message,
693
+ targetUrl: targetUrl
694
+ }));
695
+
696
+ return { error: 'Internal server error', message: error.message };
465
697
  }
466
-
467
- // 执行重定向
468
- res.setHeader('Location', redirectUrl);
469
- res.statusCode = 302;
470
- res.end();
471
-
472
- return { redirectUrl };
473
698
  },
474
699
 
475
700
  /**
@@ -13,7 +13,7 @@ const FEATURES_FILE = path.join(DATA_DIR, 'features.json');
13
13
  // 配置项
14
14
  const CONFIG = {
15
15
  // 日志级别:0=NONE, 1=ERROR, 2=WARN, 3=INFO, 4=DEBUG
16
- LOG_LEVEL: process.env.MOCK_PLUGIN_LOG_LEVEL || 3,
16
+ LOG_LEVEL: process.env.MOCK_PLUGIN_LOG_LEVEL || 4,
17
17
  // 缓存有效期(毫秒),默认 60 秒
18
18
  CACHE_INTERVAL: process.env.MOCK_PLUGIN_CACHE_INTERVAL || 60000,
19
19
  // 是否在控制台输出详细日志
@@ -268,12 +268,7 @@ const generateRandomValue = (pattern) => {
268
268
  // 构建重定向规则
269
269
  const buildRedirectRule = (fullUrl, targetUrl, customHeaders, pattern, isUrlRedirect = 0) => {
270
270
  // 构建目标URL
271
- let finalTargetUrl;
272
- if(!isUrlRedirect){
273
- finalTargetUrl = fullUrl.replace(pattern, targetUrl);
274
- }else{
275
- finalTargetUrl = `redirect://${targetUrl}`;
276
- }
271
+ let finalTargetUrl = fullUrl.replace(pattern, targetUrl);
277
272
 
278
273
  // 定义结果数组,避免多次字符串拼接
279
274
  const rules = [`${fullUrl} ${finalTargetUrl}`];
@@ -507,7 +502,8 @@ module.exports = (server, options) => {
507
502
  // 处理 url_redirect 类型:完全匹配 fullPath 并直接返回目标URL
508
503
  if (proxyType === 'url_redirect') {
509
504
  const targetUrl = matchedInterface.targetUrl.trim();
510
- logDebug(`接口 "${matchedInterface.name}" 使用URL重定向模式,目标URL: ${targetUrl}`);
505
+ const pattern = matchedInterface.urlPattern.trim();
506
+ logDebug(`接口 "${matchedInterface.name}" 使用URL重定向模式,模式: ${pattern}, 目标URL: ${targetUrl}`);
511
507
 
512
508
  // 确保目标URL合法
513
509
  if (!isValidTargetUrl(targetUrl)) {