build.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. const fs = require('fs');
  2. const { promises: fsPromises } = fs;
  3. const pathFn = require('path');
  4. let table;
  5. const PRESET_MITM_HOSTNAMES = [
  6. '*baidu.com',
  7. '*ydstatic.com',
  8. 'bdsp-x.jd.com',
  9. 'dsp-x.jd.com',
  10. '*snssdk.com',
  11. '*musical.com',
  12. '*musical.ly',
  13. '*snssdk.ly',
  14. 'api.chelaile.net.cn',
  15. 'atrace.chelaile.net.cn',
  16. '*.meituan.net',
  17. 'ctrl.playcvn.com',
  18. 'ctrl.playcvn.net',
  19. 'ctrl.zmzapi.com',
  20. 'ctrl.zmzapi.net',
  21. 'api.zhuishushenqi.com',
  22. 'b.zhuishushenqi.com',
  23. '*.music.126.net',
  24. '*.prod.hosts.ooklaserver.net'
  25. ];
  26. try {
  27. table = require('table');
  28. } catch (e) {
  29. console.log('Dependency "table" not found');
  30. console.log('"npm i table" then try again!');
  31. process.exit(1);
  32. }
  33. (async () => {
  34. const folderListPath = pathFn.resolve(__dirname, '../List/');
  35. const rulesets = await listDir(folderListPath);
  36. let urlRegexPaths = [];
  37. urlRegexPaths.push(
  38. ...(await fsPromises.readFile(pathFn.join(__dirname, '../Modules/sukka_url_rewrite.sgmodule'), { encoding: 'utf-8' }))
  39. .split('\n')
  40. .filter(
  41. i => !i.startsWith('#')
  42. && !i.startsWith('[')
  43. )
  44. .map(i => i.split(' ')[0])
  45. .map(i => ({
  46. origin: i,
  47. processed: i
  48. .replaceAll('(www.)?', '{www or not}')
  49. .replaceAll('^https?://', '')
  50. .replaceAll('^https://', '')
  51. .replaceAll('^http://', '')
  52. .replaceAll('\\.', '.')
  53. .replaceAll('.+', '*')
  54. .replace(/(.*)\//, (_, $1) => $1)
  55. }))
  56. );
  57. const bothWwwApexDomains = [];
  58. urlRegexPaths = urlRegexPaths.map(i => {
  59. if (!i.processed.includes('{www or not}')) return i;
  60. const d = i.processed.replace('{www or not}', '');
  61. bothWwwApexDomains.push({
  62. origin: i.origin,
  63. processed: `www.${d}`
  64. });
  65. return {
  66. origin: i.origin,
  67. processed: d
  68. };
  69. });
  70. urlRegexPaths.push(...bothWwwApexDomains);
  71. await Promise.all(rulesets.map(async file => {
  72. const content = (await fsPromises.readFile(pathFn.join(folderListPath, file), { encoding: 'utf-8' })).split('\n');
  73. urlRegexPaths.push(
  74. ...content
  75. .filter(i => i.startsWith('URL-REGEX'))
  76. .map(i => i.split(',')[1])
  77. .map(i => ({
  78. origin: i,
  79. processed: i
  80. .replaceAll('^https?://', '')
  81. .replaceAll('^https://', '')
  82. .replaceAll('^http://', '')
  83. .replaceAll('\\.', '.')
  84. .replaceAll('.+', '*')
  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(mitmDomains.join(', '));
  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. }