build-chn-cidr.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { fetchRemoteTextByLine } from './lib/fetch-text-by-line';
  2. import { task } from './trace';
  3. import { contains as containsCidr, exclude as excludeCidr } from 'fast-cidr-tools';
  4. import { createMemoizedPromise } from './lib/memo-promise';
  5. import { CN_CIDR_MISSING_IN_CHNROUTE, NON_CN_CIDR_INCLUDED_IN_CHNROUTE } from './constants/cidr';
  6. import { appendArrayInPlace } from './lib/append-array-in-place';
  7. import { IPListOutput } from './lib/create-file';
  8. import { cachedOnlyFail } from './lib/fs-memo';
  9. const PROBE_CHN_CIDR_V4 = [
  10. // NetEase Hangzhou
  11. '223.252.196.38',
  12. // Aliyun ShenZhen
  13. '120.78.92.171'
  14. ];
  15. export const getChnCidrPromise = createMemoizedPromise(cachedOnlyFail(
  16. async function getChnCidr() {
  17. const [_cidr4, cidr6] = await Promise.all([
  18. fetchRemoteTextByLine('https://raw.githubusercontent.com/misakaio/chnroutes2/master/chnroutes.txt', true).then(Array.fromAsync<string>),
  19. fetchRemoteTextByLine('https://gaoyifan.github.io/china-operator-ip/china6.txt', true).then(Array.fromAsync<string>)
  20. ]);
  21. const cidr4 = excludeCidr(
  22. appendArrayInPlace(_cidr4, CN_CIDR_MISSING_IN_CHNROUTE),
  23. NON_CN_CIDR_INCLUDED_IN_CHNROUTE,
  24. true
  25. );
  26. for (const probeIp of PROBE_CHN_CIDR_V4) {
  27. if (!containsCidr(cidr4, PROBE_CHN_CIDR_V4)) {
  28. const err = new TypeError('chnroutes missing probe IP');
  29. err.cause = probeIp;
  30. throw err;
  31. }
  32. }
  33. return [cidr4, cidr6] as const;
  34. },
  35. {
  36. serializer: JSON.stringify,
  37. deserializer: JSON.parse
  38. }
  39. ));
  40. export const buildChnCidr = task(require.main === module, __filename)(async (span) => {
  41. const [filteredCidr4, cidr6] = await span.traceChildAsync('download chnroutes2', getChnCidrPromise);
  42. // Can not use SHARED_DESCRIPTION here as different license
  43. const description = [
  44. 'License: CC BY-SA 2.0',
  45. 'Homepage: https://ruleset.skk.moe',
  46. 'GitHub: https://github.com/SukkaW/Surge',
  47. ''
  48. ];
  49. return Promise.all([
  50. new IPListOutput(span, 'china_ip', false)
  51. .withTitle('Sukka\'s Ruleset - Mainland China IPv4 CIDR')
  52. .withDescription([
  53. ...description,
  54. 'Data from https://misaka.io (misakaio @ GitHub)'
  55. ])
  56. .bulkAddCIDR4(filteredCidr4)
  57. .write(),
  58. new IPListOutput(span, 'china_ip_ipv6', false)
  59. .withTitle('Sukka\'s Ruleset - Mainland China IPv6 CIDR')
  60. .withDescription([
  61. ...description,
  62. 'Data from https://github.com/gaoyifan/china-operator-ip'
  63. ])
  64. .bulkAddCIDR6(cidr6)
  65. .write()
  66. ]);
  67. });