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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // @ts-check
  2. import path from 'node:path';
  3. import { DOMESTICS, DOH_BOOTSTRAP, AdGuardHomeDNSMapping } from '../Source/non_ip/domestic';
  4. import { DIRECTS, HOSTS, 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 './constants/description';
  10. import { once } from 'foxts/once';
  11. import * as yaml from 'yaml';
  12. import { appendArrayInPlace } from 'foxts/append-array-in-place';
  13. import { OUTPUT_INTERNAL_DIR, OUTPUT_MODULES_DIR, OUTPUT_MODULES_RULES_DIR, SOURCE_DIR } from './constants/dir';
  14. import { RulesetOutput } from './lib/rules/ruleset';
  15. import { SurgeOnlyRulesetOutput } from './lib/rules/ruleset';
  16. export function createGetDnsMappingRule(allowWildcard: boolean) {
  17. const hasWildcard = (domain: string) => {
  18. if (domain.includes('*') || domain.includes('?')) {
  19. if (!allowWildcard) {
  20. throw new TypeError(`Wildcard domain is not supported: ${domain}`);
  21. }
  22. return true;
  23. }
  24. return false;
  25. };
  26. return (domain: string): string[] => {
  27. const results: string[] = [];
  28. if (domain[0] === '$') {
  29. const d = domain.slice(1);
  30. if (hasWildcard(domain)) {
  31. results.push(`DOMAIN-WILDCARD,${d}`);
  32. } else {
  33. results.push(`DOMAIN,${d}`);
  34. }
  35. } else if (domain[0] === '+') {
  36. const d = domain.slice(1);
  37. if (hasWildcard(domain)) {
  38. results.push(`DOMAIN-WILDCARD,*.${d}`);
  39. } else {
  40. results.push(`DOMAIN-SUFFIX,${d}`);
  41. }
  42. } else if (hasWildcard(domain)) {
  43. results.push(`DOMAIN-WILDCARD,${domain}`, `DOMAIN-WILDCARD,*.${domain}`);
  44. } else {
  45. results.push(`DOMAIN-SUFFIX,${domain}`);
  46. }
  47. return results;
  48. };
  49. }
  50. export const getDomesticAndDirectDomainsRulesetPromise = once(async () => {
  51. const domestics = await readFileIntoProcessedArray(path.join(SOURCE_DIR, 'non_ip/domestic.conf'));
  52. const directs = await readFileIntoProcessedArray(path.resolve(SOURCE_DIR, 'non_ip/direct.conf'));
  53. const lans: string[] = [];
  54. const getDnsMappingRuleWithWildcard = createGetDnsMappingRule(true);
  55. [DOH_BOOTSTRAP, DOMESTICS].forEach((item) => {
  56. Object.values(item).forEach(({ domains }) => {
  57. appendArrayInPlace(domestics, domains.flatMap(getDnsMappingRuleWithWildcard));
  58. });
  59. });
  60. Object.values(DIRECTS).forEach(({ domains }) => {
  61. appendArrayInPlace(directs, domains.flatMap(getDnsMappingRuleWithWildcard));
  62. });
  63. Object.values(LAN).forEach(({ domains }) => {
  64. appendArrayInPlace(directs, domains.flatMap(getDnsMappingRuleWithWildcard));
  65. });
  66. // backward compatible, add lan.conf
  67. Object.values(LAN).forEach(({ domains }) => {
  68. appendArrayInPlace(lans, domains.flatMap(getDnsMappingRuleWithWildcard));
  69. });
  70. return [domestics, directs, lans] as const;
  71. });
  72. export const buildDomesticRuleset = task(require.main === module, __filename)(async (span) => {
  73. const [domestics, directs, lans] = await getDomesticAndDirectDomainsRulesetPromise();
  74. const dataset: Array<[name: string, DNSMapping]> = ([DOH_BOOTSTRAP, DOMESTICS, DIRECTS, LAN, HOSTS] as const).flatMap(Object.entries);
  75. return Promise.all([
  76. new RulesetOutput(span, 'domestic', 'non_ip')
  77. .withTitle('Sukka\'s Ruleset - Domestic Domains')
  78. .withDescription([
  79. ...SHARED_DESCRIPTION,
  80. '',
  81. 'This file contains known addresses that are avaliable in the Mainland China.'
  82. ])
  83. .addFromRuleset(domestics)
  84. .write(),
  85. new RulesetOutput(span, 'direct', 'non_ip')
  86. .withTitle('Sukka\'s Ruleset - Direct Rules')
  87. .withDescription([
  88. ...SHARED_DESCRIPTION,
  89. '',
  90. 'This file contains domains and process that should not be proxied.'
  91. ])
  92. .addFromRuleset(directs)
  93. .write(),
  94. new RulesetOutput(span, 'lan', 'non_ip')
  95. .withTitle('Sukka\'s Ruleset - LAN')
  96. .withDescription([
  97. ...SHARED_DESCRIPTION,
  98. '',
  99. 'This file includes rules for LAN DOMAIN and reserved TLDs.'
  100. ])
  101. .addFromRuleset(lans)
  102. .write(),
  103. ...dataset.map(([name, { ruleset, domains }]) => {
  104. if (!ruleset) {
  105. return;
  106. }
  107. const output = new SurgeOnlyRulesetOutput(span, name.toLowerCase(), 'sukka_local_dns_mapping', OUTPUT_MODULES_RULES_DIR)
  108. .withTitle(`Sukka's Ruleset - Local DNS Mapping (${name})`)
  109. .withDescription([
  110. ...SHARED_DESCRIPTION,
  111. '',
  112. 'This is an internal rule that is only referenced by sukka_local_dns_mapping.sgmodule',
  113. 'Do not use this file in your Rule section, all rules are included in non_ip/domestic.conf already.'
  114. ]);
  115. domains.forEach((domain) => {
  116. switch (domain[0]) {
  117. case '$':
  118. output.addDomain(domain.slice(1));
  119. break;
  120. case '+':
  121. output.addDomainSuffix(domain.slice(1));
  122. break;
  123. default:
  124. output.addDomainSuffix(domain);
  125. break;
  126. }
  127. });
  128. return output.write();
  129. }),
  130. compareAndWriteFile(
  131. span,
  132. [
  133. '#!name=[Sukka] Local DNS Mapping',
  134. `#!desc=Last Updated: ${new Date().toISOString()}`,
  135. '',
  136. '[Host]',
  137. ...Object.entries(
  138. // I use an object to deduplicate the domains
  139. // Otherwise I could just construct an array directly
  140. dataset.reduce<Record<string, string>>((acc, cur) => {
  141. const ruleset_name = cur[0].toLowerCase();
  142. const { domains, dns, hosts, ruleset } = cur[1];
  143. Object.entries(hosts).forEach(([dns, ips]) => {
  144. acc[dns] ||= ips.join(', ');
  145. });
  146. if (ruleset) {
  147. acc[`RULE-SET:https://ruleset.skk.moe/Modules/Rules/sukka_local_dns_mapping/${ruleset_name}.conf`] ||= `server:${dns}`;
  148. } else {
  149. domains.forEach((domain) => {
  150. switch (domain[0]) {
  151. case '$':
  152. acc[domain.slice(1)] ||= `server:${dns}`;
  153. break;
  154. case '+':
  155. acc[`*.${domain.slice(1)}`] ||= `server:${dns}`;
  156. break;
  157. default:
  158. acc[domain] ||= `server:${dns}`;
  159. acc[`*.${domain}`] ||= `server:${dns}`;
  160. break;
  161. }
  162. });
  163. }
  164. return acc;
  165. }, {})
  166. ).map(([dns, ips]) => `${dns} = ${ips}`)
  167. ],
  168. path.resolve(OUTPUT_MODULES_DIR, 'sukka_local_dns_mapping.sgmodule')
  169. ),
  170. compareAndWriteFile(
  171. span,
  172. yaml.stringify(
  173. dataset.reduce<{
  174. dns: { 'nameserver-policy': Record<string, string | string[]> },
  175. hosts: Record<string, string | string[]>
  176. }>((acc, cur) => {
  177. const { domains, dns, ...rest } = cur[1];
  178. domains.forEach((domain) => {
  179. switch (domain[0]) {
  180. case '$':
  181. domain = domain.slice(1);
  182. break;
  183. case '+':
  184. domain = `*.${domain.slice(1)}`;
  185. break;
  186. default:
  187. domain = `+.${domain}`;
  188. break;
  189. }
  190. acc.dns['nameserver-policy'][domain] = dns;
  191. });
  192. if ('hosts' in rest) {
  193. // eslint-disable-next-line guard-for-in -- known plain object
  194. for (const domain in rest.hosts) {
  195. const dest = rest.hosts[domain];
  196. if (domain in acc.hosts) {
  197. if (typeof acc.hosts[domain] === 'string') {
  198. acc.hosts[domain] = [acc.hosts[domain]];
  199. }
  200. acc.hosts[domain].push(...dest);
  201. } else if (dest.length === 1) {
  202. acc.hosts[domain] = dest[0];
  203. } else {
  204. acc.hosts[domain] = dest;
  205. }
  206. }
  207. }
  208. return acc;
  209. }, {
  210. dns: { 'nameserver-policy': {} },
  211. hosts: {}
  212. }),
  213. { version: '1.1' }
  214. ).split('\n'),
  215. path.join(OUTPUT_INTERNAL_DIR, 'clash_nameserver_policy.yaml')
  216. ),
  217. compareAndWriteFile(
  218. span,
  219. [
  220. '# Local DNS Mapping for AdGuard Home',
  221. 'tls://1.12.12.12',
  222. 'tls://120.53.53.53',
  223. 'https://1.12.12.12/dns-query',
  224. 'https://120.53.53.53/dns-query',
  225. '[//]udp://10.10.1.1:53',
  226. ...(([DOMESTICS, DIRECTS, LAN, HOSTS] as const).flatMap(Object.values) as DNSMapping[]).flatMap(({ domains, dns: _dns }) => domains.flatMap((domain) => {
  227. let dns;
  228. if (_dns in AdGuardHomeDNSMapping) {
  229. dns = AdGuardHomeDNSMapping[_dns as keyof typeof AdGuardHomeDNSMapping].join(' ');
  230. } else {
  231. console.warn(`Unknown DNS "${_dns}" not in AdGuardHomeDNSMapping`);
  232. dns = _dns;
  233. }
  234. // if (
  235. // // AdGuard Home has built-in AS112 / private PTR handling
  236. // domain.endsWith('.arpa')
  237. // // Ignore simple hostname
  238. // || !domain.includes('.')
  239. // ) {
  240. // return [];
  241. // }
  242. if (domain[0] === '$') {
  243. return [
  244. `[/${domain.slice(1)}/]${dns}`
  245. ];
  246. }
  247. if (domain[0] === '+') {
  248. return [
  249. `[/${domain.slice(1)}/]${dns}`
  250. ];
  251. }
  252. return [
  253. `[/${domain}/]${dns}`
  254. ];
  255. }))
  256. ],
  257. path.resolve(OUTPUT_INTERNAL_DIR, 'dns_mapping_adguardhome.conf')
  258. )
  259. ]);
  260. });