build-mitm-hostname.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 !== '*baidu.com' && i.endsWith('baidu.com')) // Special Case
  104. && !(i !== '*.meituan.net' && i.endsWith('.meituan.net'))
  105. && !i.startsWith('.')
  106. && !i.endsWith('.')
  107. && !i.endsWith('*')
  108. });
  109. const mitmDomainsRegExpArray = mitmDomains.map(i => {
  110. return new RegExp(
  111. escapeRegExp(i)
  112. .replaceAll('{www or not}', '(www.)?')
  113. .replaceAll('\\*', '(.*)')
  114. )
  115. });
  116. const parsedDomainsData = [];
  117. dedupedUrlRegexPaths.forEach(i => {
  118. const result = parseDomain(i.processed);
  119. if (result.success) {
  120. if (matchWithRegExpArray(result.hostname.trim(), mitmDomainsRegExpArray)) {
  121. parsedDomainsData.push([green(result.hostname), i.origin]);
  122. } else {
  123. parsedDomainsData.push([yellow(result.hostname), i.origin]);
  124. }
  125. }
  126. });
  127. console.log('Mitm Hostnames:');
  128. console.log('hostname = %APPEND% ' + mitmDomains.join(', '));
  129. console.log('--------------------');
  130. console.log('Parsed Sucessed:');
  131. console.log(table.table(parsedDomainsData, {
  132. border: table.getBorderCharacters('void'),
  133. columnDefault: {
  134. paddingLeft: 0,
  135. paddingRight: 3
  136. },
  137. drawHorizontalLine: () => false
  138. }));
  139. console.log('--------------------');
  140. console.log('Parsed Failed');
  141. console.log([...parsedFailures].join('\n'));
  142. })();
  143. /** Util function */
  144. function parseDomain(input) {
  145. try {
  146. const url = new URL(`https://${input}`);
  147. return {
  148. success: true,
  149. hostname: url.hostname
  150. }
  151. } catch {
  152. return {
  153. success: false
  154. }
  155. }
  156. }
  157. function matchWithRegExpArray(input, regexps = []) {
  158. for (const r of regexps) {
  159. if (r.test(input)) return true;
  160. }
  161. return false;
  162. }
  163. function escapeRegExp(string = '') {
  164. const reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  165. const reHasRegExpChar = RegExp(reRegExpChar.source);
  166. return string && reHasRegExpChar.test(string)
  167. ? string.replace(reRegExpChar, '\\$&')
  168. : string;
  169. }