feat: Node.js 域名解析支持 TCP/UDP DNS

This commit is contained in:
xream committed 2026-06-19 12:16:26 +08:00
1 parent e6cb6c9b21
commit 649412df6f
4 files changed
+458 -24

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.25.0",
"version": "2.26.0",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"packageManager": "pnpm@11.0.9",
@@ -3,7 +3,7 @@ import scriptResourceCache from '@/utils/script-resource-cache';
import { isIPv4, isIPv6, ipAddress, isPlainObject } from '@/utils';
import { FULL } from '@/utils/logical';
import { getFlag, removeFlag } from '@/utils/geo';
import { doh } from '@/utils/dns';
import { resolveDns } from '@/utils/dns';
import lodash from 'lodash';
import $ from '@/core/app';
import { hex_md5 } from '@/vendor/md5';
@@ -597,7 +597,7 @@ const DOMAIN_RESOLVERS = {
const cached = resourceCache.get(id);
if (!noCache && cached) return cached;
const answerType = type === 'IPv6' ? 'AAAA' : 'A';
const res = await doh({
const res = await resolveDns({
url,
domain,
type: answerType,
@@ -624,7 +624,7 @@ const DOMAIN_RESOLVERS = {
const cached = resourceCache.get(id);
if (!noCache && cached) return cached;
const answerType = type === 'IPv6' ? 'AAAA' : 'A';
const res = await doh({
const res = await resolveDns({
url: 'https://8.8.4.4/dns-query',
domain,
type: answerType,
@@ -678,7 +678,7 @@ const DOMAIN_RESOLVERS = {
const cached = resourceCache.get(id);
if (!noCache && cached) return cached;
const answerType = type === 'IPv6' ? 'AAAA' : 'A';
const res = await doh({
const res = await resolveDns({
url: 'https://1.0.0.1/dns-query',
domain,
type: answerType,
@@ -1,18 +1,104 @@
import { expect } from 'chai';
import { describe, it, beforeEach, afterEach } from 'mocha';
import dnsPacket from 'dns-packet';
import $ from '@/core/app';
import PROCESSORS, { ApplyProcessor } from '@/core/proxy-utils/processors';
import { SETTINGS_KEY } from '@/constants';
import resourceCache from '@/utils/resource-cache';
import { parseDnsResolver } from '@/utils/dns';
import { hex_md5 } from '@/vendor/md5';
const ResolveDomainOperator = PROCESSORS['Resolve Domain Operator'];
const dgram = eval("require('dgram')");
const net = eval("require('net')");
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function createDnsResponse(query, data = '192.0.2.55') {
const question = query.questions[0];
return dnsPacket.encode({
type: 'response',
id: query.id,
flags: dnsPacket.RECURSION_DESIRED,
questions: query.questions,
answers: [
{
type: question.type,
class: 'IN',
name: question.name,
ttl: 60,
data,
},
],
});
}
function getEdnsClientSubnet(query) {
return query.additionals
?.find((item) => item.type === 'OPT')
?.options?.find(
(option) =>
option.code === 'CLIENT_SUBNET' || option.code === 8,
)?.ip;
}
function startUdpDnsServer(onQuery) {
return new Promise((resolve, reject) => {
const server = dgram.createSocket('udp4');
server.once('error', reject);
server.on('message', (message, rinfo) => {
const query = dnsPacket.decode(message);
onQuery(query);
server.send(createDnsResponse(query), rinfo.port, rinfo.address);
});
server.bind(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve({
host: '127.0.0.1',
port: server.address().port,
close: () =>
new Promise((resolveClose) => server.close(resolveClose)),
});
});
});
}
function startTcpDnsServer(onQuery) {
return new Promise((resolve, reject) => {
const server = net.createServer((socket) => {
let request = Buffer.alloc(0);
socket.on('data', (chunk) => {
request = Buffer.concat([request, chunk]);
if (request.length < 2) return;
const requestLength = request.readUInt16BE(0);
if (request.length < requestLength + 2) return;
const query = dnsPacket.decode(
request.slice(2, 2 + requestLength),
);
onQuery(query);
const response = createDnsResponse(query, '192.0.2.56');
const responseLength = Buffer.alloc(2);
responseLength.writeUInt16BE(response.length, 0);
socket.end(Buffer.concat([responseLength, response]));
});
});
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve({
host: '127.0.0.1',
port: server.address().port,
close: () =>
new Promise((resolveClose) => server.close(resolveClose)),
});
});
});
}
describe('Resolve Domain Operator', function () {
let originalGoogleResolver;
let originalRead;
@@ -248,4 +334,96 @@ describe('Resolve Domain Operator', function () {
$.warn = originalWarn;
}
});
it('parses Custom DNS resolver formats', function () {
expect(parseDnsResolver('https://1.1.1.1/dns-query')).to.deep.equal({
protocol: 'doh',
url: 'https://1.1.1.1/dns-query',
});
expect(parseDnsResolver('1.1.1.1:5353')).to.deep.equal({
protocol: 'udp',
host: '1.1.1.1',
port: 5353,
});
expect(parseDnsResolver('1.1.1.1')).to.deep.equal({
protocol: 'udp',
host: '1.1.1.1',
port: 53,
});
expect(parseDnsResolver('udp://1.1.1.1')).to.deep.equal({
protocol: 'udp',
host: '1.1.1.1',
port: 53,
});
expect(parseDnsResolver('tcp://1.1.1.1')).to.deep.equal({
protocol: 'tcp',
host: '1.1.1.1',
port: 53,
});
expect(parseDnsResolver('tcp://1.1.1.1:5353')).to.deep.equal({
protocol: 'tcp',
host: '1.1.1.1',
port: 5353,
});
});
it('resolves Custom UDP DNS and sends EDNS', async function () {
const queries = [];
const server = await startUdpDnsServer((query) => queries.push(query));
const url = `${server.host}:${server.port}`;
cacheKeys.push(hex_md5(`CUSTOM:${url}:udp.example.com:IPv4`));
try {
const processor = ResolveDomainOperator({
provider: 'Custom',
type: 'IPv4',
url,
edns: '198.51.100.1',
cache: 'disabled',
});
const output = await ApplyProcessor(processor, [
{ name: 'UDP Custom', server: 'udp.example.com', port: 443 },
]);
expect(output[0].server).to.equal('192.0.2.55');
expect(queries).to.have.length(1);
expect(queries[0].questions[0]).to.include({
type: 'A',
name: 'udp.example.com',
});
expect(getEdnsClientSubnet(queries[0])).to.equal('198.51.100.0');
} finally {
await server.close();
}
});
it('resolves Custom TCP DNS and sends EDNS', async function () {
const queries = [];
const server = await startTcpDnsServer((query) => queries.push(query));
const url = `tcp://${server.host}:${server.port}`;
cacheKeys.push(hex_md5(`CUSTOM:${url}:tcp.example.com:IPv4`));
try {
const processor = ResolveDomainOperator({
provider: 'Custom',
type: 'IPv4',
url,
edns: '198.51.101.2',
cache: 'disabled',
});
const output = await ApplyProcessor(processor, [
{ name: 'TCP Custom', server: 'tcp.example.com', port: 443 },
]);
expect(output[0].server).to.equal('192.0.2.56');
expect(queries).to.have.length(1);
expect(queries[0].questions[0]).to.include({
type: 'A',
name: 'tcp.example.com',
});
expect(getEdnsClientSubnet(queries[0])).to.equal('198.51.101.0');
} finally {
await server.close();
}
});
});
+275 -19
View File
@@ -1,10 +1,31 @@
import $ from '@/core/app';
import dnsPacket from 'dns-packet';
import { Buffer } from 'buffer';
import { isIPv4 } from '@/utils';
import { isIPv4, isIPv6 } from '@/utils';
export async function doh({ url, domain, type = 'A', timeout, edns }) {
const buf = dnsPacket.encode({
const DNS_DEFAULT_PORT = 53;
const DNS_TCP_LENGTH_BYTES = 2;
function buildDnsQuery({ domain, type = 'A', edns }) {
const additionals = [];
if (edns) {
additionals.push({
type: 'OPT',
name: '.',
udpPayloadSize: 4096,
flags: 0,
options: [
{
code: 'CLIENT_SUBNET',
ip: edns,
sourcePrefixLength: isIPv4(edns) ? 24 : 56,
scopePrefixLength: 0,
},
],
});
}
return dnsPacket.encode({
type: 'query',
id: 0,
flags: dnsPacket.RECURSION_DESIRED,
@@ -14,22 +35,83 @@ export async function doh({ url, domain, type = 'A', timeout, edns }) {
name: domain,
},
],
additionals: [
{
type: 'OPT',
name: '.',
udpPayloadSize: 4096,
flags: 0,
options: [
{
code: 'CLIENT_SUBNET',
ip: edns,
sourcePrefixLength: isIPv4(edns) ? 24 : 56,
scopePrefixLength: 0,
},
],
},
],
additionals,
});
}
function normalizeDnsTimeout(timeout) {
return timeout || 8000;
}
function normalizeDnsHost(host) {
return host?.replace(/^\[(.*)\]$/, '$1');
}
function parseDnsPort(port) {
if (!port) return DNS_DEFAULT_PORT;
const parsed = Number(port);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
throw new Error('自定义 DNS 端口号应为 1-65535 的整数');
}
return parsed;
}
function assertNoDnsServerUrlExtraParts(parsed, raw) {
if (
parsed.username ||
parsed.password ||
(parsed.pathname && parsed.pathname !== '/') ||
parsed.search ||
parsed.hash
) {
throw new Error(`自定义 DNS 地址格式无效: ${raw}`);
}
}
function parseDnsServerUrl(raw, protocol) {
try {
const value = protocol
? raw
: `udp://${isIPv6(raw) ? `[${raw}]` : raw}`;
const parsed = new URL(value);
assertNoDnsServerUrlExtraParts(parsed, raw);
const host = normalizeDnsHost(parsed.hostname);
if (!host) throw new Error(`自定义 DNS 地址格式无效: ${raw}`);
return {
protocol: protocol || 'udp',
host,
port: parseDnsPort(parsed.port),
};
} catch (e) {
if (e?.message?.includes('自定义 DNS')) throw e;
throw new Error(`自定义 DNS 地址格式无效: ${raw}`);
}
}
export function parseDnsResolver(url) {
const raw = `${url || ''}`.trim();
if (!raw) throw new Error('自定义 DNS 不能为空');
if (/^https?:\/\//i.test(raw)) {
return {
protocol: 'doh',
url: raw,
};
}
const protocol = raw.match(/^([a-z][a-z\d+.-]*):\/\//i)?.[1];
const normalizedProtocol = protocol?.toLowerCase();
if (normalizedProtocol && !['udp', 'tcp'].includes(normalizedProtocol)) {
throw new Error(`自定义 DNS 不支持 ${protocol} 协议`);
}
return parseDnsServerUrl(raw, normalizedProtocol);
}
export async function doh({ url, domain, type = 'A', timeout, edns }) {
const buf = buildDnsQuery({
domain,
type,
edns,
});
const b64 = Buffer.from(buf).toString('base64');
@@ -52,3 +134,177 @@ export async function doh({ url, domain, type = 'A', timeout, edns }) {
return dnsPacket.decode(Buffer.from($.env.isQX ? res.bodyBytes : res.body));
}
async function queryDnsOverUdp({ server, domain, type = 'A', timeout, edns }) {
const dgram = eval("require('dgram')");
const buf = buildDnsQuery({
domain,
type,
edns,
});
return new Promise((resolve, reject) => {
let settled = false;
const socket = dgram.createSocket(isIPv6(server.host) ? 'udp6' : 'udp4');
const timer = setTimeout(() => {
finish(new Error('DNS UDP query timeout'));
}, normalizeDnsTimeout(timeout));
function cleanup() {
clearTimeout(timer);
socket.removeAllListeners();
try {
socket.close();
} catch (e) {
// Socket may already be closed by the time cleanup runs.
}
}
function finish(error, result) {
if (settled) return;
settled = true;
cleanup();
if (error) {
reject(error);
} else {
resolve(result);
}
}
socket.on('error', (error) => finish(error));
socket.on('message', (message) => {
try {
finish(null, dnsPacket.decode(message));
} catch (e) {
finish(e);
}
});
socket.send(buf, server.port, server.host, (error) => {
if (error) finish(error);
});
});
}
async function queryDnsOverTcp({ server, domain, type = 'A', timeout, edns }) {
const net = eval("require('net')");
const payload = buildDnsQuery({
domain,
type,
edns,
});
const length = Buffer.alloc(DNS_TCP_LENGTH_BYTES);
length.writeUInt16BE(payload.length, 0);
const request = Buffer.concat([length, payload]);
return new Promise((resolve, reject) => {
let settled = false;
let response = Buffer.alloc(0);
let responseLength;
const socket = net.createConnection({
host: server.host,
port: server.port,
});
function cleanup() {
socket.removeAllListeners();
socket.destroy();
}
function finish(error, result) {
if (settled) return;
settled = true;
cleanup();
if (error) {
reject(error);
} else {
resolve(result);
}
}
socket.setTimeout(normalizeDnsTimeout(timeout), () => {
finish(new Error('DNS TCP query timeout'));
});
socket.on('connect', () => {
socket.write(request);
});
socket.on('error', (error) => finish(error));
socket.on('end', () => {
finish(new Error('DNS TCP connection ended before response'));
});
socket.on('data', (chunk) => {
try {
response = Buffer.concat([response, chunk]);
if (
responseLength == null &&
response.length >= DNS_TCP_LENGTH_BYTES
) {
responseLength = response.readUInt16BE(0);
}
if (
responseLength != null &&
response.length >= responseLength + DNS_TCP_LENGTH_BYTES
) {
const message = response.slice(
DNS_TCP_LENGTH_BYTES,
responseLength + DNS_TCP_LENGTH_BYTES,
);
finish(null, dnsPacket.decode(message));
}
} catch (e) {
finish(e);
}
});
});
}
export async function resolveDns({
url,
domain,
type = 'A',
timeout,
edns,
}) {
const raw = `${url || ''}`.trim();
const protocol = raw.match(/^([a-z][a-z\d+.-]*):\/\//i)?.[1];
if (
raw &&
!$.env.isNode &&
!/^https?:\/\//i.test(raw) &&
(!protocol || ['udp', 'tcp'].includes(protocol.toLowerCase()))
) {
throw new Error('TCP/UDP DNS 仅支持 Node.js 环境');
}
const resolver = parseDnsResolver(url);
if (resolver.protocol === 'doh') {
return doh({
url: resolver.url,
domain,
type,
timeout,
edns,
});
}
if (!$.env.isNode) {
throw new Error('TCP/UDP DNS 仅支持 Node.js 环境');
}
if (resolver.protocol === 'tcp') {
return queryDnsOverTcp({
server: resolver,
domain,
type,
timeout,
edns,
});
}
return queryDnsOverUdp({
server: resolver,
domain,
type,
timeout,
edns,
});
}