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