Files
frost-network-proxy/src/resolver.js
T

42 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
/**
* 目标地址解析 + 白名单校验。
* 所有协议在真正建立连接前都会走这里,保证“允许代理的目标 IP”规则统一生效。
*/
const net = require('node:net');
const dns = require('node:dns');
/**
* 解析目标主机并在白名单中挑选可用 IP。
* @param {string} host 目标主机(域名或 IP)
* @param {import('./ipFilter').IpFilter} filter IP 过滤器
* @returns {Promise<string>} 可用的目标 IP
* @throws {Error} 带 code 的错误:EBLOCKED(被白名单拒绝)/ ENOTFOUND(解析失败)
*/
async function resolveAllowed(host, filter) {
const literal = net.isIP(host);
let addresses;
if (literal) {
addresses = [{ address: host, family: literal }];
} else {
addresses = await dns.promises.lookup(host, { all: true, verbatim: true });
if (!Array.isArray(addresses) || addresses.length === 0) {
const err = new Error(`无法解析目标域名:${host}`);
err.code = 'ENOTFOUND';
throw err;
}
}
const allowed = addresses.find((item) => filter.allows(item.address));
if (!allowed) {
const err = new Error(`目标 IP 不在允许列表:${addresses.map((item) => item.address).join(', ')}`);
err.code = 'EBLOCKED';
throw err;
}
return allowed.address;
}
module.exports = { resolveAllowed };