smartproxy/ts/smartproxy.portproxy.ts

185 lines
6.4 KiB
TypeScript

import * as plugins from './smartproxy.plugins.js';
export interface DomainConfig {
domain: string; // glob pattern for domain
allowedIPs: string[]; // glob patterns for IPs allowed to access this domain
targetIP?: string; // Optional target IP for this domain
}
export interface ProxySettings extends plugins.tls.TlsOptions {
// Port configuration
fromPort: number;
toPort: number;
toHost?: string; // Target host to proxy to, defaults to 'localhost'
// Domain and security settings
domains: DomainConfig[];
sniEnabled?: boolean;
defaultAllowedIPs?: string[]; // Optional default IP patterns if no matching domain found
preserveSourceIP?: boolean; // Whether to preserve the client's source IP when proxying
}
export class PortProxy {
netServer: plugins.net.Server | plugins.tls.Server;
settings: ProxySettings;
constructor(settings: ProxySettings) {
this.settings = {
...settings,
toHost: settings.toHost || 'localhost'
};
}
public async start() {
const cleanUpSockets = (from: plugins.net.Socket, to: plugins.net.Socket) => {
from.end();
to.end();
from.removeAllListeners();
to.removeAllListeners();
from.unpipe();
to.unpipe();
from.destroy();
to.destroy();
};
const normalizeIP = (ip: string): string[] => {
// Handle IPv4-mapped IPv6 addresses
if (ip.startsWith('::ffff:')) {
const ipv4 = ip.slice(7); // Remove '::ffff:' prefix
return [ip, ipv4];
}
// Handle IPv4 addresses by adding IPv4-mapped IPv6 variant
if (ip.match(/^\d{1,3}(\.\d{1,3}){3}$/)) {
return [ip, `::ffff:${ip}`];
}
return [ip];
};
const isAllowed = (value: string, patterns: string[]): boolean => {
// Expand patterns to include both IPv4 and IPv6 variants
const expandedPatterns = patterns.flatMap(normalizeIP);
// Check if any variant of the IP matches any expanded pattern
return normalizeIP(value).some(ip =>
expandedPatterns.some(pattern => plugins.minimatch(ip, pattern))
);
};
const findMatchingDomain = (serverName: string): DomainConfig | undefined => {
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
};
const server = this.settings.sniEnabled
? plugins.tls.createServer({
...this.settings,
SNICallback: (serverName: string, cb: (err: Error | null, ctx?: plugins.tls.SecureContext) => void) => {
console.log(`SNI request for domain: ${serverName}`);
// For SNI passthrough, we don't need to create a context
// Just acknowledge the SNI request and continue
cb(null);
}
})
: plugins.net.createServer();
const handleConnection = (from: plugins.net.Socket | plugins.tls.TLSSocket) => {
const remoteIP = from.remoteAddress || '';
let serverName = '';
// First check if this IP is in the default allowed list
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
if (this.settings.sniEnabled && from instanceof plugins.tls.TLSSocket) {
serverName = (from as any).servername || '';
console.log(`TLS Connection from ${remoteIP} for domain: ${serverName}`);
}
// If IP is in defaultAllowedIPs, allow the connection regardless of SNI
if (isDefaultAllowed) {
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
} else if (this.settings.sniEnabled && serverName) {
// For SNI connections that aren't in default list, check domain-specific rules
const domainConfig = findMatchingDomain(serverName);
if (!domainConfig) {
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`);
from.end();
return;
}
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
from.end();
return;
}
} else {
// Non-SNI connection and not in default list
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
from.end();
return;
}
// Determine target host - use domain-specific targetIP if available
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
// Create connection, optionally preserving the client's source IP
const connectionOptions: plugins.net.NetConnectOpts = {
host: targetHost,
port: this.settings.toPort,
};
// Only set localAddress if preserveSourceIP is enabled
if (this.settings.preserveSourceIP) {
connectionOptions.localAddress = remoteIP.replace('::ffff:', ''); // Remove IPv6 mapping if present
}
const to = plugins.net.createConnection(connectionOptions);
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
from.setTimeout(120000);
from.pipe(to);
to.pipe(from);
from.on('error', () => {
cleanUpSockets(from, to);
});
to.on('error', () => {
cleanUpSockets(from, to);
});
from.on('close', () => {
cleanUpSockets(from, to);
});
to.on('close', () => {
cleanUpSockets(from, to);
});
from.on('timeout', () => {
cleanUpSockets(from, to);
});
to.on('timeout', () => {
cleanUpSockets(from, to);
});
from.on('end', () => {
cleanUpSockets(from, to);
});
to.on('end', () => {
cleanUpSockets(from, to);
});
};
this.netServer = server
.on('connection', handleConnection)
.on('secureConnection', handleConnection)
.on('tlsClientError', (err, tlsSocket) => {
console.log(`TLS Client Error: ${err.message}`);
})
.on('error', (err) => {
console.log(`Server Error: ${err.message}`);
})
.listen(this.settings.fromPort);
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI enabled)' : ''}`);
}
public async stop() {
const done = plugins.smartpromise.defer();
this.netServer.close(() => {
done.resolve();
});
await done.promise;
}
}