Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(plugin): support authenticated proxy #3175

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@
"semver": "7.7.1",
"serve": "14.2.4",
"simple-youtube-age-restriction-bypass": "github:organization/Simple-YouTube-Age-Restriction-Bypass#v2.5.9",
"socks": "^2.8.4",
"solid-floating-ui": "0.3.1",
"solid-js": "1.9.5",
"solid-styled-components": "0.28.5",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 24 additions & 0 deletions src/i18n/resources/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,30 @@
}
}
}
},
"auth-proxy-adapter": {
"name": "Auth Proxy Adapter",
"description": "Support for the use of authentication proxy services",
"menu": {
"disable": "Disable Proxy Adapter",
"enable": "Enable Proxy Adapter",
"hostname": {
"label": "Hostname"
},
"port": {
"label": "Port"
}
},
"prompt": {
"hostname": {
"title": "Proxy Hostname",
"label": "Enter hostname for local proxy server (requires restart):"
},
"port": {
"title": "Proxy Port",
"label": "Enter port for local proxy server (requires restart):"
}
}
}
}
}
24 changes: 24 additions & 0 deletions src/i18n/resources/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,30 @@
"visualizer-type": "可视化类型"
},
"name": "可视化效果"
},
"auth-proxy-adapter": {
"name": "认证代理适配",
"description": "支持使用需要身份验证的代理",
"menu": {
"disable": "禁用代理适配",
"enable": "启用代理适配",
"hostname": {
"label": "主机名"
},
"port": {
"label": "端口"
}
},
"prompt": {
"hostname": {
"title": "代理主机名",
"label": "请输入本地代理服务器的主机名(需要重启):"
},
"port": {
"title": "代理端口",
"label": "请输入本地代理服务器的端口号(需要重启):"
}
}
}
}
}
21 changes: 20 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ import { loadI18n, setLanguage, t } from '@/i18n';

import ErrorHtmlAsset from '@assets/error.html?asset';

import { defaultAuthProxyConfig } from '@/plugins/auth-proxy-adapter/config';

import type { PluginConfig } from '@/types/plugins';

if (!is.macOS()) {
Expand Down Expand Up @@ -141,7 +143,24 @@ if (is.linux()) {
}

if (config.get('options.proxy')) {
app.commandLine.appendSwitch('proxy-server', config.get('options.proxy'));
const authProxyEnabled = config.plugins.isEnabled('auth-proxy-adapter');

let proxyToUse = '';
if (authProxyEnabled) {
// Use proxy from Auth-Proxy-Adapter plugin
const authProxyConfig = deepmerge(
defaultAuthProxyConfig,
config.get('plugins.auth-proxy-adapter') ?? {},
) as typeof defaultAuthProxyConfig;

const { hostname, port } = authProxyConfig;
proxyToUse = `socks5://${hostname}:${port}`;
} else if (config.get('options.proxy')) {
// Use global proxy settings
proxyToUse = config.get('options.proxy');
}
console.log(LoggerPrefix, `Using proxy: ${proxyToUse}`);
app.commandLine.appendSwitch('proxy-server', proxyToUse);
}

// Adds debug features like hotkeys for triggering dev tools and reload
Expand Down
1 change: 1 addition & 0 deletions src/plugins/auth-proxy-adapter/backend/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './main';
246 changes: 246 additions & 0 deletions src/plugins/auth-proxy-adapter/backend/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
import net from 'net';

import { SocksClient, SocksClientOptions } from 'socks';

import is from 'electron-is';

import { createBackend, LoggerPrefix } from '@/utils';

import { BackendType } from './types';

import config from '@/config';

import { AuthProxyConfig, defaultAuthProxyConfig } from '../config';

import type { BackendContext } from '@/types/contexts';

// Parsing the upstream authentication SOCK proxy URL
const parseSocksUrl = (socksUrl: string) => {
// Format: socks5://username:password@your_server_ip:port

const url = new URL(socksUrl);
return {
host: url.hostname,
port: parseInt(url.port, 10),
type: url.protocol === 'socks5:' ? 5 : 4,
username: url.username,
password: url.password,
};
};

export const backend = createBackend<BackendType, AuthProxyConfig>({
async start(ctx: BackendContext<AuthProxyConfig>) {
const pluginConfig = await ctx.getConfig();
this.startServer(pluginConfig);
},
stop() {
this.stopServer();
},
onConfigChange(config: AuthProxyConfig) {
if (
this.oldConfig?.hostname === config.hostname &&
this.oldConfig?.port === config.port
) {
this.oldConfig = config;
return;
}
this.stopServer();
this.startServer(config);

this.oldConfig = config;
},

// Custom
// Start proxy server - SOCKS5
startServer(serverConfig: AuthProxyConfig) {
if (this.server) {
this.stopServer();
}

const { port, hostname } = serverConfig;
// Upstream proxy from system settings
const upstreamProxyUrl = config.get('options.proxy');
// Create SOCKS proxy server
const socksServer = net.createServer((socket) => {
socket.once('data', (chunk) => {
if (chunk[0] === 0x05) {
// SOCKS5
this.handleSocks5(socket, chunk, upstreamProxyUrl);
} else {
socket.end();
}
});

socket.on('error', (err) => {
console.error(LoggerPrefix, '[SOCKS] Socket error:', err.message);
});
});

// Listen for errors
socksServer.on('error', (err) => {
console.error(LoggerPrefix, '[SOCKS Server Error]', err.message);
});

// Start server
socksServer.listen(port, hostname, () => {
console.log(LoggerPrefix, '===========================================');
console.log(
LoggerPrefix,
`[Auth-Proxy-Adapter] Enable SOCKS proxy at socks5://${hostname}:${port}`,
);
console.log(
LoggerPrefix,
`[Auth-Proxy-Adapter] Using upstream proxy: ${upstreamProxyUrl}`,
);
console.log(LoggerPrefix, '===========================================');
});

this.server = socksServer;
},

// Handle SOCKS5 request
handleSocks5(
clientSocket: net.Socket,
chunk: Buffer,
upstreamProxyUrl: string,
) {
// Handshake phase
const numMethods = chunk[1];
const methods = chunk.subarray(2, 2 + numMethods);

// Check if client supports no authentication method (0x00)
if (methods.includes(0x00)) {
// Reply to client, choose no authentication method
clientSocket.write(Buffer.from([0x05, 0x00]));

// Wait for client's connection request
clientSocket.once('data', (data) => {
this.processSocks5Request(clientSocket, data, upstreamProxyUrl);
});
} else {
// Authentication methods not supported by the client
clientSocket.write(Buffer.from([0x05, 0xff]));
clientSocket.end();
}
},

// Handle SOCKS5 connection request
processSocks5Request(
clientSocket: net.Socket,
data: Buffer,
upstreamProxyUrl: string,
) {
// Parse target address and port
let targetHost, targetPort;
const cmd = data[1]; // Command: 0x01=CONNECT, 0x02=BIND, 0x03=UDP
const atyp = data[3]; // Address type: 0x01=IPv4, 0x03=Domain, 0x04=IPv6

if (cmd !== 0x01) {
// Currently only support CONNECT command
clientSocket.write(
Buffer.from([0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),
);
clientSocket.end();
return;
}

if (atyp === 0x01) {
// IPv4
targetHost = `${data[4]}.${data[5]}.${data[6]}.${data[7]}`;
targetPort = data.readUInt16BE(8);
} else if (atyp === 0x03) {
// Domain
const hostLen = data[4];
targetHost = data.subarray(5, 5 + hostLen).toString();
targetPort = data.readUInt16BE(5 + hostLen);
} else if (atyp === 0x04) {
// IPv6
const ipv6Buffer = data.subarray(4, 20);
targetHost = Array.from(new Array(8), (_, i) =>
ipv6Buffer.readUInt16BE(i * 2).toString(16),
).join(':');
targetPort = data.readUInt16BE(20);
}
if (is.dev()) {
console.debug(
LoggerPrefix,
`[SOCKS5] Request to connect to ${targetHost}:${targetPort}`,
);
}

const socksProxy = parseSocksUrl(upstreamProxyUrl);

if (!socksProxy) {
// Failed to parse proxy URL
clientSocket.write(
Buffer.from([0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),
);
clientSocket.end();
return;
}

const options: SocksClientOptions = {
proxy: {
host: socksProxy.host,
port: socksProxy.port,
type: socksProxy.type as 4 | 5,
userId: socksProxy.username,
password: socksProxy.password,
},
command: 'connect',
destination: {
host: targetHost || defaultAuthProxyConfig.hostname,
port: targetPort || defaultAuthProxyConfig.port,
},
};
SocksClient.createConnection(options)
.then((info) => {
const { socket: proxySocket } = info;

// Connection successful, send success response to client
const responseBuffer = Buffer.from([
0x05, // VER: SOCKS5
0x00, // REP: Success
0x00, // RSV: Reserved field
0x01, // ATYP: IPv4
0,
0,
0,
0, // BND.ADDR: 0.0.0.0 (Bound address, usually not important)
0,
0, // BND.PORT: 0 (Bound port, usually not important)
]);
clientSocket.write(responseBuffer);

// Establish bidirectional data stream
proxySocket.pipe(clientSocket);
clientSocket.pipe(proxySocket);

proxySocket.on('error', (error) => {
console.error(LoggerPrefix, '[SOCKS5] Proxy socket error:', error);
if (clientSocket.writable) clientSocket.end();
});

clientSocket.on('error', (error) => {
console.error(LoggerPrefix, '[SOCKS5] Client socket error:', error);
if (proxySocket.writable) proxySocket.end();
});
})
.catch((error) => {
console.error(LoggerPrefix, '[SOCKS5] Connection error:', error);
// Send failure response to client
clientSocket.write(
Buffer.from([0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),
);
clientSocket.end();
});
},

// Stop proxy server
stopServer() {
if (this.server) {
this.server.close();
this.server = undefined;
}
},
});
21 changes: 21 additions & 0 deletions src/plugins/auth-proxy-adapter/backend/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import net from 'net';

import type { AuthProxyConfig } from '../config';
import type { Server } from 'http';

export type BackendType = {
server?: Server | net.Server;
oldConfig?: AuthProxyConfig;
startServer: (serverConfig: AuthProxyConfig) => void;
stopServer: () => void;
handleSocks5: (
clientSocket: net.Socket,
chunk: Buffer,
upstreamProxyUrl: string,
) => void;
processSocks5Request: (
clientSocket: net.Socket,
data: Buffer,
upstreamProxyUrl: string,
) => void;
};
11 changes: 11 additions & 0 deletions src/plugins/auth-proxy-adapter/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export interface AuthProxyConfig {
enabled: boolean;
hostname: string;
port: number;
}

export const defaultAuthProxyConfig: AuthProxyConfig = {
enabled: false,
hostname: '127.0.0.1',
port: 4545,
};
Loading