build-telegram-cidr.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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({
  34. dns: '8.8.8.8',
  35. http: false
  36. }),
  37. DNS2.DOHClient({
  38. dns: '1.0.0.1',
  39. http: false
  40. })
  41. ].flatMap(
  42. (client) => [
  43. 'apv3.stel.com', // prod
  44. 'tapv3.stel.com' // test
  45. ].map(async (domain) => {
  46. try {
  47. // tapv3.stel.com was for testing server
  48. const resp = await client(domain, 'TXT');
  49. const strings = resp.answers.map(i => i.data);
  50. const str = strings[0]!.length > strings[1]!.length
  51. ? strings[0]! + strings[1]!
  52. : strings[1]! + strings[0]!;
  53. const ips = getTelegramBackupIPFromBase64(str);
  54. ips.forEach(i => backupIPs.add(i.ip));
  55. console.log('[telegram backup ip]', picocolors.green('DoH TXT'), { domain, ips });
  56. } catch (e) {
  57. console.error('[telegram backup ip]', picocolors.red('DoH TXT error'), { domain }, e);
  58. }
  59. })
  60. ));
  61. // Backup IP Source 2: Firebase Realtime Database (test server not supported)
  62. try {
  63. const text = await (await $$fetch('https://reserve-5a846.firebaseio.com/ipconfigv3.json')).json();
  64. if (typeof text === 'string' && text.length === 344) {
  65. const ips = getTelegramBackupIPFromBase64(text);
  66. ips.forEach(i => backupIPs.add(i.ip));
  67. console.log('[telegram backup ip]', picocolors.green('Firebase Realtime DB'), { ips });
  68. }
  69. } catch (e) {
  70. console.error('[telegram backup ip]', picocolors.red('Firebase Realtime DB error'), e);
  71. // ignore all errors
  72. }
  73. // Backup IP Source 3: Firebase Value Store (test server not supported)
  74. try {
  75. const json = await (await $$fetch('https://firestore.googleapis.com/v1/projects/reserve-5a846/databases/(default)/documents/ipconfig/v3')).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)
  126. .bulkAddCIDR4NoResolve(ipcidr)
  127. .bulkAddCIDR6NoResolve(ipcidr6)
  128. .write();
  129. });