build-domestic-direct-lan-ruleset-dns-mapping-module.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // @ts-check
  2. import path from 'node:path';
  3. import { DOMESTICS, DOH_BOOTSTRAP } from '../Source/non_ip/domestic';
  4. import { DIRECTS, LAN } from '../Source/non_ip/direct';
  5. import type { DNSMapping } from '../Source/non_ip/direct';
  6. import { readFileIntoProcessedArray } from './lib/fetch-text-by-line';
  7. import { compareAndWriteFile } from './lib/create-file';
  8. import { task } from './trace';
  9. import { SHARED_DESCRIPTION } from './lib/constants';
  10. import { createMemoizedPromise } from './lib/memo-promise';
  11. import * as yaml from 'yaml';
  12. import { appendArrayInPlace } from './lib/append-array-in-place';
  13. import { OUTPUT_INTERNAL_DIR, OUTPUT_MODULES_DIR, SOURCE_DIR } from './constants/dir';
  14. import { RulesetOutput } from './lib/create-file';
  15. export function createGetDnsMappingRule(allowWildcard: boolean) {
  16. const hasWildcard = (domain: string) => {
  17. if (domain.includes('*') || domain.includes('?')) {
  18. if (!allowWildcard) {
  19. throw new TypeError(`Wildcard domain is not supported: ${domain}`);
  20. }
  21. return true;
  22. }
  23. return false;
  24. };
  25. return (domain: string): string[] => {
  26. const results: string[] = [];
  27. if (domain[0] === '$') {
  28. const d = domain.slice(1);
  29. if (hasWildcard(domain)) {
  30. results.push(`DOMAIN-WILDCARD,${d}`);
  31. } else {
  32. results.push(`DOMAIN,${d}`);
  33. }
  34. } else if (domain[0] === '+') {
  35. const d = domain.slice(1);
  36. if (hasWildcard(domain)) {
  37. results.push(`DOMAIN-WILDCARD,*.${d}`);
  38. } else {
  39. results.push(`DOMAIN-SUFFIX,${d}`);
  40. }
  41. } else if (hasWildcard(domain)) {
  42. results.push(`DOMAIN-WILDCARD,${domain}`, `DOMAIN-WILDCARD,*.${domain}`);
  43. } else {
  44. results.push(`DOMAIN-SUFFIX,${domain}`);
  45. }
  46. return results;
  47. };
  48. }
  49. export const getDomesticAndDirectDomainsRulesetPromise = createMemoizedPromise(async () => {
  50. const domestics = await readFileIntoProcessedArray(path.join(SOURCE_DIR, 'non_ip/domestic.conf'));
  51. const directs = await readFileIntoProcessedArray(path.resolve(SOURCE_DIR, 'non_ip/direct.conf'));
  52. const lans: string[] = [];
  53. const getDnsMappingRuleWithWildcard = createGetDnsMappingRule(true);
  54. [DOH_BOOTSTRAP, DOMESTICS].forEach((item) => {
  55. Object.values(item).forEach(({ domains }) => {
  56. appendArrayInPlace(domestics, domains.flatMap(getDnsMappingRuleWithWildcard));
  57. });
  58. });
  59. Object.values(DIRECTS).forEach(({ domains }) => {
  60. appendArrayInPlace(directs, domains.flatMap(getDnsMappingRuleWithWildcard));
  61. });
  62. Object.values(LAN).forEach(({ domains }) => {
  63. appendArrayInPlace(directs, domains.flatMap(getDnsMappingRuleWithWildcard));
  64. });
  65. return [domestics, directs, lans] as const;
  66. });
  67. export const buildDomesticRuleset = task(require.main === module, __filename)(async (span) => {
  68. const [domestics, directs, lans] = await getDomesticAndDirectDomainsRulesetPromise();
  69. const dataset: DNSMapping[] = ([DOH_BOOTSTRAP, DOMESTICS, DIRECTS] as const).flatMap(Object.values);
  70. return Promise.all([
  71. new RulesetOutput(span, 'domestic', 'non_ip')
  72. .withTitle('Sukka\'s Ruleset - Domestic Domains')
  73. .withDescription([
  74. ...SHARED_DESCRIPTION,
  75. '',
  76. 'This file contains known addresses that are avaliable in the Mainland China.'
  77. ])
  78. .addFromRuleset(domestics)
  79. .write(),
  80. new RulesetOutput(span, 'direct', 'non_ip')
  81. .withTitle('Sukka\'s Ruleset - Direct Rules')
  82. .withDescription([
  83. ...SHARED_DESCRIPTION,
  84. '',
  85. 'This file contains domains and process that should not be proxied.'
  86. ])
  87. .addFromRuleset(directs)
  88. .write(),
  89. new RulesetOutput(span, 'lan', 'non_ip')
  90. .withTitle('Sukka\'s Ruleset - LAN')
  91. .withDescription([
  92. ...SHARED_DESCRIPTION,
  93. '',
  94. 'This file includes rules for LAN DOMAIN and reserved TLDs.'
  95. ])
  96. .addFromRuleset(lans)
  97. .write(),
  98. compareAndWriteFile(
  99. span,
  100. [
  101. '#!name=[Sukka] Local DNS Mapping',
  102. `#!desc=Last Updated: ${new Date().toISOString()}`,
  103. '',
  104. '[Host]',
  105. ...Object.entries(
  106. // I use an object to deduplicate the domains
  107. // Otherwise I could just construct an array directly
  108. dataset.reduce<Record<string, string>>((acc, cur) => {
  109. const { domains, dns, hosts } = cur;
  110. Object.entries(hosts).forEach(([dns, ips]) => {
  111. acc[dns] ||= ips.join(', ');
  112. });
  113. domains.forEach((domain) => {
  114. switch (domain[0]) {
  115. case '$':
  116. acc[domain.slice(1)] ||= `server:${dns}`;
  117. break;
  118. case '+':
  119. acc[`*.${domain.slice(1)}`] ||= `server:${dns}`;
  120. break;
  121. default:
  122. acc[domain] ||= `server:${dns}`;
  123. acc[`*.${domain}`] ||= `server:${dns}`;
  124. break;
  125. }
  126. });
  127. return acc;
  128. }, {})
  129. ).map(([dns, ips]) => `${dns} = ${ips}`)
  130. ],
  131. path.resolve(OUTPUT_MODULES_DIR, 'sukka_local_dns_mapping.sgmodule')
  132. ),
  133. compareAndWriteFile(
  134. span,
  135. yaml.stringify(
  136. dataset.reduce<{
  137. dns: { 'nameserver-policy': Record<string, string | string[]> },
  138. hosts: Record<string, string>
  139. }>((acc, cur) => {
  140. const { domains, dns, ...rest } = cur;
  141. domains.forEach((domain) => {
  142. let domainWildcard = domain;
  143. if (domain[0] === '$') {
  144. domainWildcard = domain.slice(1);
  145. } else if (domain[0] === '+') {
  146. domainWildcard = `*.${domain.slice(1)}`;
  147. } else {
  148. domainWildcard = `+.${domain}`;
  149. }
  150. acc.dns['nameserver-policy'][domainWildcard] = dns === 'system'
  151. ? ['system://', 'system', 'dhcp://system']
  152. : dns;
  153. });
  154. if ('hosts' in rest) {
  155. Object.assign(acc.hosts, rest.hosts);
  156. }
  157. return acc;
  158. }, {
  159. dns: { 'nameserver-policy': {} },
  160. hosts: {}
  161. }),
  162. { version: '1.1' }
  163. ).split('\n'),
  164. path.join(OUTPUT_INTERNAL_DIR, 'clash_nameserver_policy.yaml')
  165. ),
  166. compareAndWriteFile(
  167. span,
  168. [
  169. '# Local DNS Mapping for AdGuard Home',
  170. '',
  171. '[//]udp://10.10.1.1:53',
  172. ...dataset.flatMap(({ domains, dns: _dns }) => domains.flatMap((domain) => {
  173. const dns = _dns === 'system'
  174. ? 'udp://10.10.1.1:53'
  175. : _dns;
  176. if (
  177. // AdGuard Home has built-in AS112 / private PTR handling
  178. domain.endsWith('.arpa')
  179. // Ignore simple hostname
  180. || !domain.includes('.')
  181. ) {
  182. return [];
  183. }
  184. if (domain[0] === '$') {
  185. return [
  186. `[/${domain.slice(1)}/]${dns}`
  187. ];
  188. }
  189. if (domain[0] === '+') {
  190. return [
  191. `[/${domain.slice(1)}/]${dns}`
  192. ];
  193. }
  194. return [
  195. `[/${domain}/]${dns}`
  196. ];
  197. }))
  198. ],
  199. path.resolve(OUTPUT_INTERNAL_DIR, 'dns_mapping_adguardhome.conf')
  200. )
  201. ]);
  202. });