build-mitm-hostname.ts 5.3 KB

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