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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. .appendDescription(
  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. .appendDescription(
  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. .appendDescription(
  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 surgeOutput = new SurgeOnlyRulesetOutput(
  108. span,
  109. name.toLowerCase(),
  110. 'sukka_local_dns_mapping',
  111. OUTPUT_MODULES_RULES_DIR
  112. )
  113. .withTitle(`Sukka's Ruleset - Local DNS Mapping (${name})`)
  114. .appendDescription(
  115. SHARED_DESCRIPTION,
  116. '',
  117. 'This is an internal rule that is only referenced by sukka_local_dns_mapping.sgmodule',
  118. 'Do not use this file in your Rule section, all entries are included in non_ip/domestic.conf already.'
  119. );
  120. const mihomoOutput = new SurgeOnlyRulesetOutput(
  121. span,
  122. name.toLowerCase(),
  123. 'mihomo_nameserver_policy',
  124. OUTPUT_INTERNAL_DIR
  125. )
  126. .withTitle(`Sukka's Ruleset - Local DNS Mapping for Mihomo NameServer Policy (${name})`)
  127. .appendDescription(
  128. SHARED_DESCRIPTION,
  129. '',
  130. 'This ruleset is only used for mihomo\'s nameserver-policy feature, which',
  131. 'is similar to the RULE-SET referenced by sukka_local_dns_mapping.sgmodule.',
  132. 'Do not use this file in your Rule section, all entries are included in non_ip/domestic.conf already.'
  133. );
  134. domains.forEach((domain) => {
  135. switch (domain[0]) {
  136. case '$':
  137. surgeOutput.addDomain(domain.slice(1));
  138. mihomoOutput.addDomain(domain.slice(1));
  139. break;
  140. case '+':
  141. surgeOutput.addDomainSuffix(domain.slice(1));
  142. mihomoOutput.addDomainSuffix(domain.slice(1));
  143. break;
  144. default:
  145. surgeOutput.addDomainSuffix(domain);
  146. mihomoOutput.addDomainSuffix(domain);
  147. break;
  148. }
  149. });
  150. return Promise.all([
  151. surgeOutput.write(),
  152. mihomoOutput.write()
  153. ]);
  154. }),
  155. compareAndWriteFile(
  156. span,
  157. [
  158. '#!name=[Sukka] Local DNS Mapping',
  159. `#!desc=Last Updated: ${new Date().toISOString()}`,
  160. '',
  161. '[Host]',
  162. ...Object.entries(
  163. // I use an object to deduplicate the domains
  164. // Otherwise I could just construct an array directly
  165. dataset.reduce<Record<string, string>>((acc, cur) => {
  166. const ruleset_name = cur[0].toLowerCase();
  167. const { domains, dns, hosts, ruleset } = cur[1];
  168. Object.entries(hosts).forEach(([dns, ips]) => {
  169. acc[dns] ||= ips.join(', ');
  170. });
  171. if (ruleset) {
  172. acc[`RULE-SET:https://ruleset.skk.moe/Modules/Rules/sukka_local_dns_mapping/${ruleset_name}.conf`] ||= `server:${dns}`;
  173. } else {
  174. domains.forEach((domain) => {
  175. switch (domain[0]) {
  176. case '$':
  177. acc[domain.slice(1)] ||= `server:${dns}`;
  178. break;
  179. case '+':
  180. acc[`*.${domain.slice(1)}`] ||= `server:${dns}`;
  181. break;
  182. default:
  183. acc[domain] ||= `server:${dns}`;
  184. acc[`*.${domain}`] ||= `server:${dns}`;
  185. break;
  186. }
  187. });
  188. }
  189. return acc;
  190. }, {})
  191. ).map(([dns, ips]) => `${dns} = ${ips}`)
  192. ],
  193. path.resolve(OUTPUT_MODULES_DIR, 'sukka_local_dns_mapping.sgmodule')
  194. ),
  195. compareAndWriteFile(
  196. span,
  197. yaml.stringify(
  198. dataset.reduce<{
  199. dns: { 'nameserver-policy': Record<string, string | string[]> },
  200. hosts: Record<string, string | string[]>,
  201. 'rule-providers': Record<string, {
  202. type: 'http',
  203. path: `./sukkaw_ruleset/${string}`,
  204. url: string,
  205. behavior: 'classical',
  206. format: 'text',
  207. interval: number
  208. }>
  209. }>((acc, cur) => {
  210. const { domains, dns, ruleset, ...rest } = cur[1];
  211. if (ruleset) {
  212. const ruleset_name = cur[0].toLowerCase();
  213. const mihomo_ruleset_id = `mihomo_nameserver_policy_${ruleset_name}`;
  214. acc.dns['nameserver-policy'][`rule-set:${mihomo_ruleset_id}`] = dns;
  215. acc['rule-providers'][mihomo_ruleset_id] = {
  216. type: 'http',
  217. path: `./sukkaw_ruleset/${mihomo_ruleset_id}.txt`,
  218. url: `https://ruleset.skk.moe/Internal/mihomo_nameserver_policy/${ruleset_name}.txt`,
  219. behavior: 'classical',
  220. format: 'text',
  221. interval: 43200
  222. };
  223. } else {
  224. domains.forEach((domain) => {
  225. switch (domain[0]) {
  226. case '$':
  227. domain = domain.slice(1);
  228. break;
  229. case '+':
  230. domain = `*.${domain.slice(1)}`;
  231. break;
  232. default:
  233. domain = `+.${domain}`;
  234. break;
  235. }
  236. acc.dns['nameserver-policy'][domain] = dns;
  237. });
  238. }
  239. if ('hosts' in rest) {
  240. // eslint-disable-next-line guard-for-in -- known plain object
  241. for (const domain in rest.hosts) {
  242. const dest = rest.hosts[domain];
  243. if (domain in acc.hosts) {
  244. if (typeof acc.hosts[domain] === 'string') {
  245. acc.hosts[domain] = [acc.hosts[domain]];
  246. }
  247. acc.hosts[domain].push(...dest);
  248. } else if (dest.length === 1) {
  249. acc.hosts[domain] = dest[0];
  250. } else {
  251. acc.hosts[domain] = dest;
  252. }
  253. }
  254. }
  255. return acc;
  256. }, {
  257. dns: { 'nameserver-policy': {} },
  258. 'rule-providers': {},
  259. hosts: {}
  260. }),
  261. { version: '1.1' }
  262. ).split('\n'),
  263. path.join(OUTPUT_INTERNAL_DIR, 'clash_nameserver_policy.yaml')
  264. ),
  265. compareAndWriteFile(
  266. span,
  267. [
  268. '# Local DNS Mapping for AdGuard Home',
  269. 'tls://dot.pub',
  270. 'https://doh.pub/dns-query',
  271. '[//]udp://10.10.1.1:53',
  272. ...(([DOMESTICS, DIRECTS, LAN, HOSTS] as const).flatMap(Object.values) as DNSMapping[]).flatMap(({ domains, dns: _dns }) => domains.flatMap((domain) => {
  273. let dns;
  274. if (_dns in AdGuardHomeDNSMapping) {
  275. dns = AdGuardHomeDNSMapping[_dns as keyof typeof AdGuardHomeDNSMapping].join(' ');
  276. } else {
  277. console.warn(`Unknown DNS "${_dns}" not in AdGuardHomeDNSMapping`);
  278. dns = _dns;
  279. }
  280. // if (
  281. // // AdGuard Home has built-in AS112 / private PTR handling
  282. // domain.endsWith('.arpa')
  283. // // Ignore simple hostname
  284. // || !domain.includes('.')
  285. // ) {
  286. // return [];
  287. // }
  288. if (domain[0] === '$') {
  289. return [
  290. `[/${domain.slice(1)}/]${dns}`
  291. ];
  292. }
  293. if (domain[0] === '+') {
  294. return [
  295. `[/${domain.slice(1)}/]${dns}`
  296. ];
  297. }
  298. return [
  299. `[/${domain}/]${dns}`
  300. ];
  301. }))
  302. ],
  303. path.resolve(OUTPUT_INTERNAL_DIR, 'dns_mapping_adguardhome.conf')
  304. )
  305. ]);
  306. });