suing / tg-net-fix.cjs
Subsequently's picture
Rename tg-net-fix to tg-net-fix.cjs
7e626dc verified
Raw History Blame Contribute Delete
7.95 kB
'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();
}