'use strict'; // tg-net-fix.cjs // node tg-net-fix.cjs probe [quiet] -> 并发探测 api.telegram.org 的候选 IP, 写缓存并给出分层诊断 // node --require tg-net-fix.cjs ... -> 让对 api.telegram.org 的解析指向缓存里"已验证可用"的 IP // 证书校验与 SNI/Host 始终是真实的 api.telegram.org, 不会连到假服务器。 const fs = require('fs'); const dns = require('dns'); const net = require('net'); const tls = require('tls'); const https = require('https'); const util = require('util'); const HOST = 'api.telegram.org'; const CACHE = process.env.TG_IP_CACHE || '/tmp/tg-ips.json'; const PORT = parseInt(process.env.TG_PORT || '443', 10); const PROBE_MS = parseInt(process.env.TG_PROBE_MS || '7000', 10); const STATIC_IPS = ['149.154.167.220', '149.154.166.110', '149.154.167.99', '149.154.167.51', '91.108.56.130', '149.154.175.50', '91.108.4.1']; function readCache() { try { return JSON.parse(fs.readFileSync(CACHE, 'utf8')); } catch (e) { return null; } } // ───────────────────────── probe ───────────────────────── function guard(p, ms) { return Promise.race([Promise.resolve(p).catch(() => []), new Promise(r => setTimeout(() => r([]), ms))]); } async function sysDns() { return dns.promises.resolve4(HOST); } async function udpDns(server) { const r = new dns.promises.Resolver({ timeout: 3000, tries: 1 }); r.setServers([server]); return r.resolve4(HOST); } function getJson(opts) { return new Promise(res => { const req = https.get(opts, r => { let b = ''; r.on('data', c => b += c); r.on('end', () => { try { res(JSON.parse(b)); } catch (e) { res(null); } }); }); req.on('error', () => res(null)); req.setTimeout(4000, () => { req.destroy(); res(null); }); }); } async function doh(ip, sni, p) { const j = await getJson({ host: ip, port: 443, servername: sni, path: p, headers: { Host: sni, Accept: 'application/dns-json' } }); return ((j && j.Answer) || []).filter(a => a.type === 1).map(a => a.data); } function tryIp(ip, ms) { return new Promise(resolve => { const t0 = Date.now(); let stage = 'tcp', done = false, timer, s; const fin = (ok, reason) => { if (done) return; done = true; clearTimeout(timer); try { s && s.destroy(); } catch (e) { /* ignore */ } resolve({ ip, ok, stage, reason, ms: Date.now() - t0 }); }; timer = setTimeout(() => fin(false, 'timeout'), ms); s = tls.connect({ host: ip, port: PORT, servername: HOST, rejectUnauthorized: true }); s.once('connect', () => { stage = 'tls'; }); s.once('secureConnect', () => { stage = 'http'; s.write('GET / HTTP/1.1\r\nHost: ' + HOST + '\r\nConnection: close\r\nUser-Agent: tg-probe\r\n\r\n'); }); s.on('data', d => { if (/^HTTP\/1\./.test(String(d))) fin(true); }); s.once('error', e => fin(false, e.code || e.message)); s.once('close', () => fin(false, 'closed')); }); } async function probe(quiet) { const prev = readCache(); const lists = await Promise.all([ guard(sysDns(), 5000), ...['1.1.1.1', '8.8.8.8', '9.9.9.9', '223.5.5.5'].map(s => guard(udpDns(s), 5000)), guard(doh('8.8.8.8', 'dns.google', '/resolve?name=' + HOST + '&type=A'), 6000), guard(doh('1.1.1.1', 'cloudflare-dns.com', '/dns-query?name=' + HOST + '&type=A'), 6000), ]); const dyn = new Set(lists.flat().filter(net.isIPv4)); const extra = (process.env.TG_EXTRA_IPS || '').split(',').map(s => s.trim()).filter(net.isIPv4); const cands = [...new Set([...dyn, ...extra, ...STATIC_IPS])]; const res = await Promise.all(cands.map(ip => tryIp(ip, PROBE_MS))); const okList = res.filter(r => r.ok).sort((a, b) => a.ms - b.ms); const fails = { tcp: 0, tls: 0, http: 0 }; res.filter(r => !r.ok).forEach(r => { fails[r.stage] = (fails[r.stage] || 0) + 1; }); let ips = okList.map(r => ({ ip: r.ip, ms: r.ms })), stale = false; if (!ips.length && prev && prev.ips && prev.ips.length && Date.now() - prev.at < 30 * 60 * 1000) { ips = prev.ips; stale = true; // 短暂失败不丢弃上一次的好 IP } const out = { at: Date.now(), ips, stale, tried: cands.length, dnsFound: dyn.size, fails }; try { fs.writeFileSync(CACHE + '.tmp', JSON.stringify(out)); fs.renameSync(CACHE + '.tmp', CACHE); } catch (e) { console.error('[tg-probe] cache write failed: ' + e.message); } const sig = ips.map(x => x.ip).join(',') + (okList.length ? '' : '|none'); const prevSig = prev ? (prev.ips || []).map(x => x.ip).join(',') + (prev.stale || !(prev.ips || []).length ? '|none' : '') : null; if (quiet && sig === prevSig && okList.length) return out; if (okList.length) { console.log('[tg-probe] OK ' + okList.length + '/' + cands.length + ' 可用: ' + okList.slice(0, 4).map(r => r.ip + '(' + r.ms + 'ms)').join(' ') + ' | DNS解析到 ' + dyn.size + ' 个'); } else { let why; if (fails.http > 0) why = 'TLS 能握手但 HTTP 无响应 → 应用层过滤'; else if (fails.tls > 0) why = 'TCP 通但 TLS 握手被掐 → SNI/TLS 层过滤, 换 IP 无效'; else why = 'TCP 连接全部超时/被拒 → IP 层被丢包, 换 IP/换 SNI 都无效'; console.log('[tg-probe] FAIL 0/' + cands.length + ' | tcp=' + fails.tcp + ' tls=' + fails.tls + ' http=' + fails.http + ' | DNS解析到 ' + dyn.size + ' 个' + (stale ? ' | 沿用旧缓存' : '')); console.log('[tg-probe] 结论: ' + why + '. 探测无法解决时, 请设置 TELEGRAM_PROXY(走自己的 VPS) 或把网关搬到 VPS.'); const sample = res.slice(0, 4).map(r => r.ip + ':' + r.stage + '/' + r.reason).join(' '); console.log('[tg-probe] 样例: ' + sample); } return out; } // ───────────────────────── preload ───────────────────────── function install() { let memo = [], memoAt = 0, lastSig = ''; const getIps = () => { const now = Date.now(); if (now - memoAt > 3000) { memoAt = now; const c = readCache(); memo = ((c && c.ips) || []).map(x => x.ip).filter(net.isIPv4); const sig = memo.join(','); if (sig && sig !== lastSig) { lastSig = sig; console.error('[tg-net-fix] ' + HOST + ' -> ' + sig); } } return memo; }; const v4ok = f => !f || f === 4 || f === 'IPv4'; const origLookup = dns.lookup; const patched = function (hostname, options, cb) { if (typeof options === 'function') { cb = options; options = {}; } if (typeof options === 'number') options = { family: options }; options = options || {}; if (hostname === HOST && v4ok(options.family)) { const ips = getIps(); if (ips.length) { if (options.all) return process.nextTick(cb, null, ips.map(a => ({ address: a, family: 4 }))); return process.nextTick(cb, null, ips[0], 4); } } return origLookup.call(dns, hostname, options, cb); }; patched[util.promisify.custom] = (h, o) => new Promise((res, rej) => patched(h, o || {}, (e, a, f) => e ? rej(e) : res(Array.isArray(a) ? a : { address: a, family: f }))); dns.lookup = patched; const origP = dns.promises.lookup; dns.promises.lookup = function (h, o) { if (h === HOST && v4ok(o && typeof o === 'object' ? o.family : o)) { const ips = getIps(); if (ips.length) return Promise.resolve(o && o.all ? ips.map(a => ({ address: a, family: 4 })) : { address: ips[0], family: 4 }); } return origP.apply(this, arguments); }; try { require('module').syncBuiltinESMExports(); } catch (e) { /* ignore */ } } if (require.main === module) { const mode = process.argv[2] || 'probe'; if (mode === 'status') { console.log(JSON.stringify(readCache())); process.exit(0); } probe(process.argv[3] === 'quiet').then(() => process.exit(0), e => { console.error(e); process.exit(0); }); } else { install(); }