build-mitm-hostname.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. const fs = require('fs');
  2. const { promises: fsPromises } = fs;
  3. const pathFn = require('path');
  4. const table = require('table');
  5. const PRESET_MITM_HOSTNAMES = [
  6. '*baidu.com',
  7. '*ydstatic.com',
  8. '*snssdk.com',
  9. '*musical.com',
  10. '*musical.ly',
  11. '*snssdk.ly',
  12. 'api.chelaile.net.cn',
  13. 'atrace.chelaile.net.cn',
  14. '*.meituan.net',
  15. 'ctrl.playcvn.com',
  16. 'ctrl.playcvn.net',
  17. 'ctrl.zmzapi.com',
  18. 'ctrl.zmzapi.net',
  19. 'api.zhuishushenqi.com',
  20. 'b.zhuishushenqi.com',
  21. '*.music.126.net',
  22. '*.prod.hosts.ooklaserver.net'
  23. ];
  24. (async () => {
  25. const folderListPath = pathFn.resolve(__dirname, '../List/');
  26. const rulesets = await listDir(folderListPath);
  27. let urlRegexPaths = [];
  28. urlRegexPaths.push(
  29. ...(await fsPromises.readFile(pathFn.join(__dirname, '../Modules/sukka_url_rewrite.sgmodule'), { encoding: 'utf-8' }))
  30. .split('\n')
  31. .filter(
  32. i => !i.startsWith('#')
  33. && !i.startsWith('[')
  34. )
  35. .map(i => i.split(' ')[0])
  36. .map(i => ({
  37. origin: i,
  38. processed: i
  39. .replaceAll('(www.)?', '{www or not}')
  40. .replaceAll('^https?://', '')
  41. .replaceAll('^https://', '')
  42. .replaceAll('^http://', '')
  43. .split('/')[0]
  44. .replaceAll('\\.', '.')
  45. .replaceAll('.+', '*')
  46. .replaceAll('(.*)', '*')
  47. }))
  48. );
  49. const bothWwwApexDomains = [];
  50. urlRegexPaths = urlRegexPaths.map(i => {
  51. if (!i.processed.includes('{www or not}')) return i;
  52. const d = i.processed.replace('{www or not}', '');
  53. bothWwwApexDomains.push({
  54. origin: i.origin,
  55. processed: `www.${d}`
  56. });
  57. return {
  58. origin: i.origin,
  59. processed: d
  60. };
  61. });
  62. urlRegexPaths.push(...bothWwwApexDomains);
  63. await Promise.all(rulesets.map(async file => {
  64. const content = (await fsPromises.readFile(pathFn.join(folderListPath, file), { encoding: 'utf-8' })).split('\n');
  65. urlRegexPaths.push(
  66. ...content
  67. .filter(i => i.startsWith('URL-REGEX'))
  68. .map(i => i.split(',')[1])
  69. .map(i => ({
  70. origin: i,
  71. processed: i
  72. .replaceAll('^https?://', '')
  73. .replaceAll('^https://', '')
  74. .replaceAll('^http://', '')
  75. .replaceAll('\\.', '.')
  76. .replaceAll('.+', '*')
  77. .replaceAll('\\d', '*')
  78. .replaceAll('([a-z])', '*')
  79. .replaceAll('[a-z]', '*')
  80. .replaceAll('([0-9])', '*')
  81. .replaceAll('[0-9]', '*')
  82. .replaceAll(/{.+?}/g, '')
  83. .replaceAll(/\*+/g, '*')
  84. }))
  85. );
  86. }));
  87. let mitmDomains = new Set(PRESET_MITM_HOSTNAMES); // Special case for parsed failed
  88. const parsedFailures = new Set();
  89. const dedupedUrlRegexPaths = [...new Set(urlRegexPaths)];
  90. dedupedUrlRegexPaths.forEach(i => {
  91. const result = parseDomain(i.processed);
  92. if (result.success) {
  93. mitmDomains.add(result.hostname.trim());
  94. } else {
  95. parsedFailures.add(i.origin);
  96. }
  97. });
  98. mitmDomains = [...mitmDomains].filter(i => {
  99. return i.length > 3
  100. && !i.includes('.mp4') // Special Case
  101. && i !== '(www.)' // Special Case
  102. && !(i !== '*baidu.com' && i.endsWith('baidu.com')) // 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 green(...args) {
  144. return `\u001b[32m${args.join(' ')}\u001b[0m`;
  145. }
  146. function yellow(...args) {
  147. return `\u001b[33m${args.join(' ')}\u001b[0m`;
  148. }
  149. function parseDomain(input) {
  150. try {
  151. const url = new URL(`https://${input}`);
  152. return {
  153. success: true,
  154. hostname: url.hostname
  155. }
  156. } catch {
  157. return {
  158. success: false
  159. }
  160. }
  161. }
  162. function matchWithRegExpArray(input, regexps = []) {
  163. for (const r of regexps) {
  164. if (r.test(input)) return true;
  165. }
  166. return false;
  167. }
  168. function escapeRegExp(string = '') {
  169. const reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  170. const reHasRegExpChar = RegExp(reRegExpChar.source);
  171. return string && reHasRegExpChar.test(string)
  172. ? string.replace(reRegExpChar, '\\$&')
  173. : string;
  174. }
  175. function listDir(path, options) {
  176. const results = [];
  177. options = Object.assign({ ignoreHidden: true, ignorePattern: null }, options);
  178. return listDirWalker(path, results, '', options).then(() => results);
  179. }
  180. function listDirWalker(path, results, parent, options) {
  181. const promises = [];
  182. return readAndFilterDir(path, options).then(items => {
  183. items.forEach(item => {
  184. const currentPath = pathFn.join(parent, item.name);
  185. if (item.isDirectory()) {
  186. promises.push(listDirWalker(pathFn.join(path, item.name), results, currentPath, options));
  187. }
  188. else {
  189. results.push(currentPath);
  190. }
  191. });
  192. }).then(() => Promise.all(promises));
  193. }
  194. function readAndFilterDir(path, options) {
  195. const { ignoreHidden = true, ignorePattern } = options;
  196. return fs.promises.readdir(path, Object.assign(Object.assign({}, options), { withFileTypes: true }))
  197. .then(results => {
  198. if (ignoreHidden) {
  199. results = results.filter(({ name }) => !name.startsWith('.'));
  200. }
  201. if (ignorePattern) {
  202. results = results.filter(({ name }) => !ignorePattern.test(name));
  203. }
  204. return results;
  205. });
  206. }