build-telegram-cidr.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. // @ts-check
  2. import { createReadlineInterfaceFromResponse } from './lib/fetch-text-by-line';
  3. import { task } from './trace';
  4. import { SHARED_DESCRIPTION } from './constants/description';
  5. import { once } from 'foxts/once';
  6. import { RulesetOutput } from './lib/rules/ruleset';
  7. import { $$fetch } from './lib/fetch-retry';
  8. import { fastIpVersion } from 'foxts/fast-ip-version';
  9. import DNS2 from 'dns2';
  10. import { getTelegramBackupIPFromBase64 } from './lib/get-telegram-backup-ip';
  11. import picocolors from 'picocolors';
  12. export const getTelegramCIDRPromise = once(async () => {
  13. const resp = await $$fetch('https://core.telegram.org/resources/cidr.txt');
  14. const lastModified = resp.headers.get('last-modified');
  15. const date = lastModified ? new Date(lastModified) : new Date();
  16. const ipcidr: string[] = [
  17. // Unused secret Telegram backup CIDR, announced by AS62041
  18. '95.161.64.0/20'
  19. ];
  20. const ipcidr6: string[] = [];
  21. for await (const cidr of createReadlineInterfaceFromResponse(resp, true)) {
  22. const v = fastIpVersion(cidr);
  23. if (v === 4) {
  24. ipcidr.push(cidr);
  25. } else if (v === 6) {
  26. ipcidr6.push(cidr);
  27. }
  28. }
  29. const backupIPs = new Set<string>();
  30. // https://github.com/tdlib/td/blob/master/td/telegram/ConfigManager.cpp
  31. // Backup IP Source 1 (DoH)
  32. await Promise.all([
  33. DNS2.DOHClient({ dns: '8.8.8.8' }),
  34. DNS2.DOHClient({ dns: '1.0.0.1' })
  35. ].flatMap(
  36. (client) => [
  37. 'apv3.stel.com', // prod
  38. 'tapv3.stel.com' // test
  39. ].map(async (domain) => {
  40. try {
  41. // tapv3.stel.com was for testing server
  42. const resp = await client(domain, 'TXT');
  43. const strings = resp.answers.map(i => i.data);
  44. const str = strings[0]!.length > strings[1]!.length
  45. ? strings[0]! + strings[1]!
  46. : strings[1]! + strings[0]!;
  47. const ips = getTelegramBackupIPFromBase64(str);
  48. ips.forEach(i => backupIPs.add(i.ip));
  49. console.log('[telegram backup ip]', picocolors.green('DoH TXT'), { domain, ips });
  50. } catch (e) {
  51. console.error('[telegram backup ip]', picocolors.red('DoH TXT error'), { domain }, e);
  52. }
  53. })
  54. ));
  55. // Backup IP Source 2: Firebase Realtime Database (test server not supported)
  56. try {
  57. const text = await (await $$fetch('https://reserve-5a846.firebaseio.com/ipconfigv3.json')).json();
  58. if (typeof text === 'string' && text.length === 344) {
  59. const ips = getTelegramBackupIPFromBase64(text);
  60. ips.forEach(i => backupIPs.add(i.ip));
  61. console.log('[telegram backup ip]', picocolors.green('Firebase Realtime DB'), { ips });
  62. }
  63. } catch (e) {
  64. console.error('[telegram backup ip]', picocolors.red('Firebase Realtime DB error'), e);
  65. // ignore all errors
  66. }
  67. // Backup IP Source 3: Firebase Value Store (test server not supported)
  68. try {
  69. const json = await (await fetch('https://firestore.googleapis.com/v1/projects/reserve-5a846/databases/(default)/documents/ipconfig/v3', {
  70. headers: {
  71. Accept: '*/*',
  72. Origin: undefined // Without this line, Google API will return "Bad request: Origin doesn't match Host for XD3.". Probably have something to do with sqlite cache store
  73. }
  74. })).json();
  75. // const json = await resp.json();
  76. if (
  77. json && typeof json === 'object'
  78. && 'fields' in json && typeof json.fields === 'object' && json.fields
  79. && 'data' in json.fields && typeof json.fields.data === 'object' && json.fields.data
  80. && 'stringValue' in json.fields.data && typeof json.fields.data.stringValue === 'string' && json.fields.data.stringValue.length === 344
  81. ) {
  82. const ips = getTelegramBackupIPFromBase64(json.fields.data.stringValue);
  83. ips.forEach(i => backupIPs.add(i.ip));
  84. console.log('[telegram backup ip]', picocolors.green('Firebase Value Store'), { ips });
  85. } else {
  86. console.error('[telegram backup ip]', picocolors.red('Firebase Value Store data format invalid'), { json });
  87. }
  88. } catch (e) {
  89. console.error('[telegram backup ip]', picocolors.red('Firebase Value Store error'), e);
  90. }
  91. // Backup IP Source 4: Google App Engine
  92. await Promise.all([
  93. 'https://dns-telegram.appspot.com',
  94. 'https://dns-telegram.appspot.com/test'
  95. ].map(async (url) => {
  96. try {
  97. const text = await (await $$fetch(url)).text();
  98. if (text.length === 344) {
  99. const ips = getTelegramBackupIPFromBase64(text);
  100. ips.forEach(i => backupIPs.add(i.ip));
  101. console.log('[telegram backup ip]', picocolors.green('Google App Engine'), { url, ips });
  102. }
  103. } catch (e) {
  104. console.error('[telegram backup ip]', picocolors.red('Google App Engine error'), { url }, e);
  105. }
  106. }));
  107. // tcdnb.azureedge.net no longer works
  108. console.log('[telegram backup ip]', `Found ${backupIPs.size} backup IPs:`, backupIPs);
  109. ipcidr.push(...Array.from(backupIPs).map(i => i + '/32'));
  110. return { date, ipcidr, ipcidr6 };
  111. });
  112. export const buildTelegramCIDR = task(require.main === module, __filename)(async (span) => {
  113. const { date, ipcidr, ipcidr6 } = await span.traceChildAsync('get telegram cidr', getTelegramCIDRPromise);
  114. if (ipcidr.length + ipcidr6.length === 0) {
  115. throw new Error('Failed to fetch data!');
  116. }
  117. const description = [
  118. ...SHARED_DESCRIPTION,
  119. 'Data from:',
  120. ' - https://core.telegram.org/resources/cidr.txt'
  121. ];
  122. return new RulesetOutput(span, 'telegram', 'ip')
  123. .withTitle('Sukka\'s Ruleset - Telegram IP CIDR')
  124. .withDescription(description)
  125. // .withDate(date) // With extra data source, we no longer use last-modified for file date
  126. .appendDataSource(
  127. 'https://core.telegram.org/resources/cidr.txt (last updated: ' + date.toISOString() + ')'
  128. )
  129. .bulkAddCIDR4NoResolve(ipcidr)
  130. .bulkAddCIDR6NoResolve(ipcidr6)
  131. .write();
  132. });