build-mitm-hostname.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. const fsPromises = require('fs').promises;
  2. const pathFn = require('path');
  3. const table = require('table');
  4. const listDir = require('@sukka/listdir');
  5. const { green, yellow } = require('picocolors');
  6. const PRESET_MITM_HOSTNAMES = [
  7. // '*baidu.com',
  8. '*ydstatic.com',
  9. // '*snssdk.com',
  10. '*musical.com',
  11. // '*musical.ly',
  12. // '*snssdk.ly',
  13. 'api.chelaile.net.cn',
  14. 'atrace.chelaile.net.cn',
  15. '*.meituan.net',
  16. 'ctrl.playcvn.com',
  17. 'ctrl.playcvn.net',
  18. 'ctrl.zmzapi.com',
  19. 'ctrl.zmzapi.net',
  20. 'api.zhuishushenqi.com',
  21. 'b.zhuishushenqi.com',
  22. '*.music.126.net',
  23. '*.prod.hosts.ooklaserver.net'
  24. ];
  25. (async () => {
  26. const folderListPath = pathFn.resolve(__dirname, '../List/');
  27. const rulesets = await listDir(folderListPath);
  28. let urlRegexPaths = [];
  29. urlRegexPaths.push(
  30. ...(await fsPromises.readFile(pathFn.join(__dirname, '../Modules/sukka_url_rewrite.sgmodule'), { encoding: 'utf-8' }))
  31. .split('\n')
  32. .filter(
  33. i => !i.startsWith('#')
  34. && !i.startsWith('[')
  35. )
  36. .map(i => i.split(' ')[0])
  37. .map(i => ({
  38. origin: i,
  39. processed: i
  40. .replaceAll('(www.)?', '{www or not}')
  41. .replaceAll('^https?://', '')
  42. .replaceAll('^https://', '')
  43. .replaceAll('^http://', '')
  44. .split('/')[0]
  45. .replaceAll('\\.', '.')
  46. .replaceAll('.+', '*')
  47. .replaceAll('(.*)', '*')
  48. }))
  49. );
  50. const bothWwwApexDomains = [];
  51. urlRegexPaths = urlRegexPaths.map(i => {
  52. if (!i.processed.includes('{www or not}')) return i;
  53. const d = i.processed.replace('{www or not}', '');
  54. bothWwwApexDomains.push({
  55. origin: i.origin,
  56. processed: `www.${d}`
  57. });
  58. return {
  59. origin: i.origin,
  60. processed: d
  61. };
  62. });
  63. urlRegexPaths.push(...bothWwwApexDomains);
  64. await Promise.all(rulesets.map(async file => {
  65. const content = (await fsPromises.readFile(pathFn.join(folderListPath, file), { encoding: 'utf-8' })).split('\n');
  66. urlRegexPaths.push(
  67. ...content
  68. .filter(i => i.startsWith('URL-REGEX'))
  69. .map(i => i.split(',')[1])
  70. .map(i => ({
  71. origin: i,
  72. processed: i
  73. .replaceAll('^https?://', '')
  74. .replaceAll('^https://', '')
  75. .replaceAll('^http://', '')
  76. .replaceAll('\\.', '.')
  77. .replaceAll('.+', '*')
  78. .replaceAll('\\d', '*')
  79. .replaceAll('([a-z])', '*')
  80. .replaceAll('[a-z]', '*')
  81. .replaceAll('([0-9])', '*')
  82. .replaceAll('[0-9]', '*')
  83. .replaceAll(/{.+?}/g, '')
  84. .replaceAll(/\*+/g, '*')
  85. }))
  86. );
  87. }));
  88. let mitmDomains = new Set(PRESET_MITM_HOSTNAMES); // Special case for parsed failed
  89. const parsedFailures = new Set();
  90. const dedupedUrlRegexPaths = [...new Set(urlRegexPaths)];
  91. dedupedUrlRegexPaths.forEach(i => {
  92. const result = parseDomain(i.processed);
  93. if (result.success) {
  94. mitmDomains.add(result.hostname.trim());
  95. } else {
  96. parsedFailures.add(i.origin);
  97. }
  98. });
  99. mitmDomains = [...mitmDomains].filter(i => {
  100. return i.length > 3
  101. && !i.includes('.mp4') // Special Case
  102. && i !== '(www.)' // Special Case
  103. && !(i !== '*.meituan.net' && i.endsWith('.meituan.net'))
  104. && !i.startsWith('.')
  105. && !i.endsWith('.')
  106. && !i.endsWith('*');
  107. });
  108. const mitmDomainsRegExpArray = mitmDomains.map(i => {
  109. return new RegExp(
  110. escapeRegExp(i)
  111. .replaceAll('{www or not}', '(www.)?')
  112. .replaceAll('\\*', '(.*)')
  113. );
  114. });
  115. const parsedDomainsData = [];
  116. dedupedUrlRegexPaths.forEach(i => {
  117. const result = parseDomain(i.processed);
  118. if (result.success) {
  119. if (matchWithRegExpArray(result.hostname.trim(), mitmDomainsRegExpArray)) {
  120. parsedDomainsData.push([green(result.hostname), i.origin]);
  121. } else {
  122. parsedDomainsData.push([yellow(result.hostname), i.origin]);
  123. }
  124. }
  125. });
  126. console.log('Mitm Hostnames:');
  127. console.log(`hostname = %APPEND% ${mitmDomains.join(', ')}`);
  128. console.log('--------------------');
  129. console.log('Parsed Sucessed:');
  130. console.log(table.table(parsedDomainsData, {
  131. border: table.getBorderCharacters('void'),
  132. columnDefault: {
  133. paddingLeft: 0,
  134. paddingRight: 3
  135. },
  136. drawHorizontalLine: () => false
  137. }));
  138. console.log('--------------------');
  139. console.log('Parsed Failed');
  140. console.log([...parsedFailures].join('\n'));
  141. })();
  142. /** Util function */
  143. function parseDomain(input) {
  144. try {
  145. const url = new URL(`https://${input}`);
  146. return {
  147. success: true,
  148. hostname: url.hostname
  149. };
  150. } catch {
  151. return {
  152. success: false
  153. };
  154. }
  155. }
  156. function matchWithRegExpArray(input, regexps = []) {
  157. for (const r of regexps) {
  158. if (r.test(input)) return true;
  159. }
  160. return false;
  161. }
  162. function escapeRegExp(string = '') {
  163. const reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  164. const reHasRegExpChar = RegExp(reRegExpChar.source);
  165. return string && reHasRegExpChar.test(string)
  166. ? string.replace(reRegExpChar, '\\$&')
  167. : string;
  168. }