build-telegram-cidr.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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', {
  76. headers: {
  77. Accept: '*/*',
  78. 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
  79. }
  80. })).json();
  81. // const json = await resp.json();
  82. if (
  83. json && typeof json === 'object'
  84. && 'fields' in json && typeof json.fields === 'object' && json.fields
  85. && 'data' in json.fields && typeof json.fields.data === 'object' && json.fields.data
  86. && 'stringValue' in json.fields.data && typeof json.fields.data.stringValue === 'string' && json.fields.data.stringValue.length === 344
  87. ) {
  88. const ips = getTelegramBackupIPFromBase64(json.fields.data.stringValue);
  89. ips.forEach(i => backupIPs.add(i.ip));
  90. console.log('[telegram backup ip]', picocolors.green('Firebase Value Store'), { ips });
  91. } else {
  92. console.error('[telegram backup ip]', picocolors.red('Firebase Value Store data format invalid'), { json });
  93. }
  94. } catch (e) {
  95. console.error('[telegram backup ip]', picocolors.red('Firebase Value Store error'), e);
  96. }
  97. // Backup IP Source 4: Google App Engine
  98. await Promise.all([
  99. 'https://dns-telegram.appspot.com',
  100. 'https://dns-telegram.appspot.com/test'
  101. ].map(async (url) => {
  102. try {
  103. const text = await (await $$fetch(url)).text();
  104. if (text.length === 344) {
  105. const ips = getTelegramBackupIPFromBase64(text);
  106. ips.forEach(i => backupIPs.add(i.ip));
  107. console.log('[telegram backup ip]', picocolors.green('Google App Engine'), { url, ips });
  108. }
  109. } catch (e) {
  110. console.error('[telegram backup ip]', picocolors.red('Google App Engine error'), { url }, e);
  111. }
  112. }));
  113. // tcdnb.azureedge.net no longer works
  114. console.log('[telegram backup ip]', `Found ${backupIPs.size} backup IPs:`, backupIPs);
  115. ipcidr.push(...Array.from(backupIPs).map(i => i + '/32'));
  116. return { date, ipcidr, ipcidr6 };
  117. });
  118. export const buildTelegramCIDR = task(require.main === module, __filename)(async (span) => {
  119. const { date, ipcidr, ipcidr6 } = await span.traceChildAsync('get telegram cidr', getTelegramCIDRPromise);
  120. if (ipcidr.length + ipcidr6.length === 0) {
  121. throw new Error('Failed to fetch data!');
  122. }
  123. const description = [
  124. ...SHARED_DESCRIPTION,
  125. 'Data from:',
  126. ' - https://core.telegram.org/resources/cidr.txt'
  127. ];
  128. return new RulesetOutput(span, 'telegram', 'ip')
  129. .withTitle('Sukka\'s Ruleset - Telegram IP CIDR')
  130. .withDescription(description)
  131. // .withDate(date) // With extra data source, we no longer use last-modified for file date
  132. .appendDataSource(
  133. 'https://core.telegram.org/resources/cidr.txt (last updated: ' + date.toISOString() + ')'
  134. )
  135. .bulkAddCIDR4NoResolve(ipcidr)
  136. .bulkAddCIDR6NoResolve(ipcidr6)
  137. .write();
  138. });