fix(pi): bypass stale Fake-IP DNS and dead local proxy for domestic model APIs

This commit is contained in:
Sycun 2026-11-30 17:10:52 +08:00
parent 12b4bf638e
commit 8e893960a3
2 changed files with 244 additions and 2 deletions

View File

@ -1,4 +1,6 @@
import { execFileSync } from "node:child_process"; import { execFileSync } from "node:child_process";
import { lookup as defaultDnsLookup } from "node:dns";
import { Resolver } from "node:dns/promises";
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import { isIP } from "node:net"; import { isIP } from "node:net";
import { Client, EnvHttpProxyAgent, Pool, install, setGlobalDispatcher, type Dispatcher } from "undici"; import { Client, EnvHttpProxyAgent, Pool, install, setGlobalDispatcher, type Dispatcher } from "undici";
@ -10,6 +12,7 @@ const redirects = new Set([301, 302, 303, 307, 308]);
const PRE_TLS_RETRY_DELAYS_MS = [150, 350, 600]; const PRE_TLS_RETRY_DELAYS_MS = [150, 350, 600];
const AUTO_SELECT_FAMILY_TIMEOUT_MS = 2_000; const AUTO_SELECT_FAMILY_TIMEOUT_MS = 2_000;
const CONNECT_TIMEOUT_MS = 20_000; const CONNECT_TIMEOUT_MS = 20_000;
const DEFAULT_PUBLIC_DNS_SERVERS = ["223.5.5.5", "119.29.29.29", "1.1.1.1"];
// OpenSSL 3.5+/4.x sends a >1.6KB post-quantum (X25519MLKEM768) TLS 1.3 ClientHello // OpenSSL 3.5+/4.x sends a >1.6KB post-quantum (X25519MLKEM768) TLS 1.3 ClientHello
// that fragments across TCP segments and triggers deterministic ECONNRESET on many // that fragments across TCP segments and triggers deterministic ECONNRESET on many
// middleboxes, SNI routers, SLBs, and proxy tunnels. Classic ECDH curves keep the // middleboxes, SNI routers, SLBs, and proxy tunnels. Classic ECDH curves keep the
@ -24,12 +27,13 @@ interface ProxySettings {
} }
interface TransportProfile { interface TransportProfile {
id: "default" | "ipv4-h2" | "ipv4-tls12" | "os-proxy"; id: "default" | "ipv4-h2" | "ipv4-tls12" | "direct-clean-dns" | "os-proxy";
allowH2: boolean; allowH2: boolean;
ipv4Only: boolean; ipv4Only: boolean;
tls12Compat: boolean; tls12Compat: boolean;
disableSessionReuse: boolean; disableSessionReuse: boolean;
useOsProxy?: boolean; useOsProxy?: boolean;
useCleanPublicDns?: boolean;
} }
const BASE_PROFILES: readonly TransportProfile[] = [ const BASE_PROFILES: readonly TransportProfile[] = [
@ -38,6 +42,20 @@ const BASE_PROFILES: readonly TransportProfile[] = [
{ id: "ipv4-tls12", allowH2: false, ipv4Only: true, tls12Compat: true, disableSessionReuse: true }, { id: "ipv4-tls12", allowH2: false, ipv4Only: true, tls12Compat: true, disableSessionReuse: true },
]; ];
const DIRECT_CLEAN_DNS_PROFILE: TransportProfile = {
id: "direct-clean-dns",
allowH2: false,
ipv4Only: true,
tls12Compat: false,
disableSessionReuse: true,
useCleanPublicDns: true,
};
const DIRECT_PROXY_SETTINGS: ProxySettings = {
noProxy: "*",
source: "none",
};
const OS_PROXY_PROFILE: TransportProfile = { const OS_PROXY_PROFILE: TransportProfile = {
id: "os-proxy", id: "os-proxy",
allowH2: false, allowH2: false,
@ -49,6 +67,7 @@ const OS_PROXY_PROFILE: TransportProfile = {
const dispatcherCache = new Map<string, Dispatcher>(); const dispatcherCache = new Map<string, Dispatcher>();
const preferredProfileByOrigin = new Map<string, TransportProfile["id"]>(); const preferredProfileByOrigin = new Map<string, TransportProfile["id"]>();
const cleanDnsCache = new Map<string, { expiresAt: number; addresses: string[] }>();
let cachedOsProxy: { expiresAt: number; value: ProxySettings | undefined } | undefined; let cachedOsProxy: { expiresAt: number; value: ProxySettings | undefined } | undefined;
function blocked(message: string): Response { function blocked(message: string): Response {
@ -108,6 +127,122 @@ export function isLoopbackOrPrivateHost(rawHostname: string): boolean {
return false; return false;
} }
// RFC 2544 benchmark range (198.18.0.0/15) and ULA (fc00::/7) are used as TUN Fake-IPs
// by Clash, Mihomo, Surge, and sing-box. When those tools are turned off, stale Fake-IP
// entries cached in OS or VMware NAT DNS fail with ECONNRESET until real DNS is queried.
export function isFakeIpAddress(rawAddress: string): boolean {
const addr = rawAddress.replace(/^\[(.+)\]$/, "$1").toLowerCase();
const family = isIP(addr);
if (family === 4) {
const parts = addr.split(".").map(Number);
return parts[0] === 198 && (parts[1] === 18 || parts[1] === 19);
}
if (family === 6) {
return addr.startsWith("fc") || addr.startsWith("fd");
}
return false;
}
const DOMESTIC_MODEL_HOST_SUFFIXES = [
".cn",
".deepseek.com",
".aliyuncs.com",
".volces.com",
".baidubce.com",
".tencentcloudapi.com",
".myqcloud.com",
".minimaxi.com",
".minimax.chat",
".stepfun.com",
".lingyiwanwu.com",
".xf-yun.com",
];
const DOMESTIC_MODEL_EXACT_HOSTS = new Set([
"api.deepseek.com",
"dashscope.aliyuncs.com",
"api.lkeap.cloud.tencent.com",
"api.minimaxi.com",
"api.minimax.chat",
"api.stepfun.com",
"api.lingyiwanwu.com",
"spark-api-open.xf-yun.com",
]);
export function isDomesticModelHost(rawHostname: string): boolean {
const host = rawHostname.replace(/^\[(.+)\]$/, "$1").replace(/\.$/, "").toLowerCase();
if (!host || isIP(host) !== 0 || isLoopbackOrPrivateHost(host)) return false;
if (DOMESTIC_MODEL_EXACT_HOSTS.has(host)) return true;
return DOMESTIC_MODEL_HOST_SUFFIXES.some(suffix => host.endsWith(suffix));
}
export function isLocalClientProxy(proxy: ProxySettings): boolean {
const urls = [proxy.httpProxy, proxy.httpsProxy].filter((v): v is string => Boolean(v));
if (urls.length === 0) return false;
return urls.every(raw => {
if (!URL.canParse(raw)) return false;
return isLoopbackOrPrivateHost(new URL(raw).hostname);
});
}
async function resolveCleanPublicIpv4(hostname: string): Promise<string[]> {
const now = Date.now();
const cached = cleanDnsCache.get(hostname);
if (cached && now < cached.expiresAt) return cached.addresses;
const customServers = process.env.CYBERSTRIKE_CLEAN_DNS_SERVERS
?.split(/[,\s]+/)
.map(s => s.trim())
.filter(Boolean);
const resolver = new Resolver();
resolver.setServers(customServers?.length ? customServers : DEFAULT_PUBLIC_DNS_SERVERS);
let timer: NodeJS.Timeout | undefined;
try {
const resolved = await Promise.race([
resolver.resolve4(hostname),
new Promise<never>((_, reject) => {
timer = setTimeout(() => {
resolver.cancel();
reject(new Error("Clean DNS resolution timed out"));
}, 2_500);
}),
]);
const valid = resolved.filter(ip => isIP(ip) === 4 && !isFakeIpAddress(ip));
if (valid.length > 0) {
cleanDnsCache.set(hostname, { expiresAt: now + 60_000, addresses: valid });
return valid;
}
} catch {
// Fall back to system DNS lookup below if UDP 53 to public resolvers is blocked.
} finally {
if (timer) clearTimeout(timer);
}
return [];
}
function cleanPublicDnsLookup(
hostname: string,
options: { all?: boolean },
callback: (err: NodeJS.ErrnoException | null, address: string | { address: string; family: number }[], family?: number) => void,
): void {
if (isIP(hostname) !== 0 || isLoopbackOrPrivateHost(hostname)) {
defaultDnsLookup(hostname, options as any, callback as any);
return;
}
void resolveCleanPublicIpv4(hostname).then(addresses => {
if (addresses.length > 0) {
if (options?.all) {
callback(null, addresses.map(address => ({ address, family: 4 })));
} else {
callback(null, addresses[0], 4);
}
return;
}
defaultDnsLookup(hostname, options as any, callback as any);
});
}
export function parseDarwinScutilProxy(output: string): ProxySettings | undefined { export function parseDarwinScutilProxy(output: string): ProxySettings | undefined {
const field = (name: string): string | undefined => { const field = (name: string): string | undefined => {
const match = output.match(new RegExp(`^\\s*${name}\\s*:\\s*(.+?)\\s*$`, "m")); const match = output.match(new RegExp(`^\\s*${name}\\s*:\\s*(.+?)\\s*$`, "m"));
@ -284,6 +419,7 @@ function getDispatcherForProfile(profile: TransportProfile, proxy: ProxySettings
...(profile.allowH2 ? { preferH2: true } : {}), ...(profile.allowH2 ? { preferH2: true } : {}),
...(profile.tls12Compat ? { maxVersion: "TLSv1.2" as const, ciphers: "DEFAULT:@SECLEVEL=1" } : {}), ...(profile.tls12Compat ? { maxVersion: "TLSv1.2" as const, ciphers: "DEFAULT:@SECLEVEL=1" } : {}),
...(profile.disableSessionReuse ? { maxCachedSessions: 0 } : {}), ...(profile.disableSessionReuse ? { maxCachedSessions: 0 } : {}),
...(profile.useCleanPublicDns ? { lookup: cleanPublicDnsLookup } : {}),
}; };
// Used by ProxyAgent / Socks5ProxyAgent when upgrading a tunnel socket to TLS. // Used by ProxyAgent / Socks5ProxyAgent when upgrading a tunnel socket to TLS.
@ -372,10 +508,23 @@ function annotateConnectError(error: unknown, target: URL, proxy: ProxySettings)
function candidateStages(url: URL, envProxy: ProxySettings): { profile: TransportProfile; proxy: ProxySettings }[] { function candidateStages(url: URL, envProxy: ProxySettings): { profile: TransportProfile; proxy: ProxySettings }[] {
const stages: { profile: TransportProfile; proxy: ProxySettings }[] = BASE_PROFILES.map(profile => ({ profile, proxy: envProxy })); const stages: { profile: TransportProfile; proxy: ProxySettings }[] = BASE_PROFILES.map(profile => ({ profile, proxy: envProxy }));
if (envProxy.source === "none" && !isLoopbackOrPrivateHost(url.hostname)) { if (envProxy.source === "none" && !isLoopbackOrPrivateHost(url.hostname)) {
// Bypass stale Clash/Mihomo TUN Fake-IP (198.18.0.0/15) cached in OS or VMware NAT DNS
// after the user turns off their proxy client.
stages.push({ profile: DIRECT_CLEAN_DNS_PROFILE, proxy: DIRECT_PROXY_SETTINGS });
const osProxy = readOsSystemProxy(); const osProxy = readOsSystemProxy();
if (osProxy) { if (osProxy) {
stages.push({ profile: OS_PROXY_PROFILE, proxy: osProxy }); stages.push({ profile: OS_PROXY_PROFILE, proxy: osProxy });
} }
} else if (
envProxy.source === "env" &&
isLocalClientProxy(envProxy) &&
isDomesticModelHost(url.hostname) &&
!matchesNoProxy(url.hostname, Number(url.port) || (url.protocol === "https:" ? 443 : 80), envProxy.noProxy)
) {
// When a local/LAN proxy client (e.g. Clash on 127.0.0.1 or VMware host 192.168.x.1)
// is turned off while HTTP_PROXY/HTTPS_PROXY remains in the shell environment, fall back
// to direct connection for official domestic model APIs such as DeepSeek.
stages.push({ profile: DIRECT_CLEAN_DNS_PROFILE, proxy: DIRECT_PROXY_SETTINGS });
} }
const preferred = preferredProfileByOrigin.get(url.origin); const preferred = preferredProfileByOrigin.get(url.origin);
if (!preferred) return stages; if (!preferred) return stages;
@ -418,7 +567,8 @@ async function fetchHop(
throw error; throw error;
} }
if (attempt >= stages.length - 1) { if (attempt >= stages.length - 1) {
throw annotateConnectError(error, url, lastProxy); const diagnosticProxy = envProxy.source === "env" ? envProxy : lastProxy;
throw annotateConnectError(error, url, diagnosticProxy);
} }
const delay = PRE_TLS_RETRY_DELAYS_MS[Math.min(attempt, PRE_TLS_RETRY_DELAYS_MS.length - 1)]; const delay = PRE_TLS_RETRY_DELAYS_MS[Math.min(attempt, PRE_TLS_RETRY_DELAYS_MS.length - 1)];
await abortableDelay(delay, signal); await abortableDelay(delay, signal);

View File

@ -1,5 +1,6 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { test } from "node:test"; import { test } from "node:test";
import dgram from "node:dgram";
import { createServer } from "node:http"; import { createServer } from "node:http";
import { createServer as createHttpsServer } from "node:https"; import { createServer as createHttpsServer } from "node:https";
import { connect, createServer as createTcpServer } from "node:net"; import { connect, createServer as createTcpServer } from "node:net";
@ -11,6 +12,9 @@ import { basename, join } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { SessionManager } from "@earendil-works/pi-coding-agent"; import { SessionManager } from "@earendil-works/pi-coding-agent";
import { import {
isDomesticModelHost,
isFakeIpAddress,
isLocalClientProxy,
isLoopbackOrPrivateHost, isLoopbackOrPrivateHost,
isPreResponseConnectError, isPreResponseConnectError,
normalizeProxyUrl, normalizeProxyUrl,
@ -951,3 +955,91 @@ test("TLS handshake keeps single-packet ClientHello, falls back to IPv4 on IPv6
assert.equal(socksRun.result.response, "tls-verified"); assert.equal(socksRun.result.response, "tls-verified");
assert.ok(socksConnections >= 1); assert.ok(socksConnections >= 1);
}); });
test("domestic DeepSeek endpoint recovers via clean DNS + direct fallback when local proxy is closed", { timeout: 45000 }, async t => {
assert.equal(isFakeIpAddress("198.18.0.45"), true);
assert.equal(isFakeIpAddress("198.19.255.1"), true);
assert.equal(isFakeIpAddress("8.8.8.8"), false);
assert.equal(isDomesticModelHost("api.deepseek.com"), true);
assert.equal(isDomesticModelHost("open.bigmodel.cn"), true);
assert.equal(isDomesticModelHost("api.openai.com"), false);
assert.equal(isLocalClientProxy({ httpsProxy: "http://192.168.33.1:7890", source: "env" }), true);
assert.equal(isLocalClientProxy({ httpsProxy: "http://proxy.corp.example.com:8080", source: "env" }), false);
const certDir = await mkdtemp(join(tmpdir(), "csai-pi-deepseek-cert-"));
t.after(() => rm(certDir, { recursive: true, force: true }));
const keyPath = join(certDir, "key.pem");
const certPath = join(certDir, "cert.pem");
execFileSync("openssl", [
"req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
"-keyout", keyPath, "-out", certPath, "-days", "1", "-nodes",
"-subj", "/CN=api.deepseek.com",
"-addext", "subjectAltName=DNS:api.deepseek.com,IP:127.0.0.1",
], { stdio: "ignore" });
const key = await readFile(keyPath);
const cert = await readFile(certPath);
const deepseekOrigin = createHttpsServer({ key, cert }, (_req, res) => sse(res, { role: "assistant", content: "deepseek-direct-ok" }, "stop"));
deepseekOrigin.listen(0, "127.0.0.1");
await once(deepseekOrigin, "listening");
t.after(() => { deepseekOrigin.closeAllConnections(); deepseekOrigin.close(); });
// Local UDP DNS server answering A queries with 127.0.0.1.
let dnsQueries = 0;
const udpDns = dgram.createSocket("udp4");
udpDns.on("message", (msg, rinfo) => {
dnsQueries++;
const id = msg.subarray(0, 2);
let qEnd = 12;
while (qEnd < msg.length && msg[qEnd] !== 0) qEnd += 1 + msg[qEnd];
qEnd += 5; // null label + QTYPE(2) + QCLASS(2)
const question = msg.subarray(12, qEnd);
const header = Buffer.from([
id[0], id[1],
0x81, 0x80, // QR=1, RD=1, RA=1, NOERROR
0x00, 0x01, // QDCOUNT=1
0x00, 0x01, // ANCOUNT=1
0x00, 0x00, 0x00, 0x00,
]);
const answer = Buffer.from([
0xc0, 0x0c, // pointer to QNAME
0x00, 0x01, // TYPE A
0x00, 0x01, // CLASS IN
0x00, 0x00, 0x00, 0x3c, // TTL 60s
0x00, 0x04, // RDLENGTH 4
127, 0, 0, 1,
]);
udpDns.send(Buffer.concat([header, question, answer]), rinfo.port, rinfo.address);
});
udpDns.bind(0, "127.0.0.1");
await once(udpDns, "listening");
t.after(() => udpDns.close());
// Closed local proxy port (bind then immediately close so connect gets ECONNREFUSED).
const closedProxyProbe = createTcpServer();
closedProxyProbe.listen(0, "127.0.0.1");
await once(closedProxyProbe, "listening");
const deadProxyPort = closedProxyProbe.address().port;
await new Promise(r => closedProxyProbe.close(r));
const env = {
...process.env,
NODE_EXTRA_CA_CERTS: certPath,
HTTP_PROXY: `http://127.0.0.1:${deadProxyPort}`,
http_proxy: `http://127.0.0.1:${deadProxyPort}`,
HTTPS_PROXY: `http://127.0.0.1:${deadProxyPort}`,
https_proxy: `http://127.0.0.1:${deadProxyPort}`,
NO_PROXY: "",
no_proxy: "",
CYBERSTRIKE_CLEAN_DNS_SERVERS: `127.0.0.1:${udpDns.address().port}`,
};
const { result } = await invoke(
t,
{ ...request(`https://api.deepseek.com:${deepseekOrigin.address().port}/v1`), generateOnly: true, tools: [] },
undefined,
env,
);
assert.equal(result.status, "completed", result.error);
assert.equal(result.response, "deepseek-direct-ok");
assert.ok(dnsQueries >= 1);
});