-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
320 lines (285 loc) · 11.6 KB
/
main.js
File metadata and controls
320 lines (285 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
const { app, BrowserWindow, ipcMain, Tray, Menu, nativeImage, dialog } = require('electron');
const path = require('path');
const { spawn, execSync } = require('child_process');
const fs = require('fs');
let mainWindow;
let tray = null;
let xrayProcess = null;
let isQuitting = false;
// Функции для управления системным прокси Windows
function enableSystemProxy(proxyAddress) {
try {
execSync(`reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1 /f`, { windowsHide: true });
execSync(`reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer /t REG_SZ /d "${proxyAddress}" /f`, { windowsHide: true });
execSync(`netsh winhttp set proxy "${proxyAddress}"`, { windowsHide: true });
return true;
} catch (err) {
return false;
}
}
function disableSystemProxy() {
try {
execSync(`reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f`, { windowsHide: true });
execSync(`netsh winhttp reset proxy`, { windowsHide: true });
return true;
} catch (err) {
return false;
}
}
function setProxyEnvironment(proxyAddress) {
try {
const httpProxy = `http://${proxyAddress}`;
execSync(`setx HTTP_PROXY "${httpProxy}"`, { windowsHide: true });
execSync(`setx HTTPS_PROXY "${httpProxy}"`, { windowsHide: true });
execSync(`setx ALL_PROXY "${httpProxy}"`, { windowsHide: true });
process.env.HTTP_PROXY = httpProxy;
process.env.HTTPS_PROXY = httpProxy;
process.env.ALL_PROXY = httpProxy;
return true;
} catch (err) {
return false;
}
}
function clearProxyEnvironment() {
try {
execSync(`setx HTTP_PROXY ""`, { windowsHide: true });
execSync(`setx HTTPS_PROXY ""`, { windowsHide: true });
execSync(`setx ALL_PROXY ""`, { windowsHide: true });
delete process.env.HTTP_PROXY;
delete process.env.HTTPS_PROXY;
delete process.env.ALL_PROXY;
return true;
} catch (err) {
return false;
}
}
// Полная очистка при выходе
function cleanupAndQuit() {
writeLog('Application closing, cleaning up...');
if (xrayProcess) {
xrayProcess.kill();
xrayProcess = null;
}
disableSystemProxy();
clearProxyEnvironment();
writeLog('Cleanup complete');
}
const logFile = path.join(__dirname, 'xray', 'vpn.log');
function writeLog(message) {
const timestamp = new Date().toISOString();
const logLine = `[${timestamp}] ${message}\n`;
fs.appendFileSync(logFile, logLine);
}
function createTray() {
const iconPath = path.join(__dirname, 'icon.ico');
let trayIcon;
if (fs.existsSync(iconPath)) {
trayIcon = nativeImage.createFromPath(iconPath);
} else {
const size = 16;
const buffer = Buffer.alloc(size * size * 4);
for (let i = 0; i < size * size; i++) {
buffer[i * 4] = 96;
buffer[i * 4 + 1] = 75;
buffer[i * 4 + 2] = 162;
buffer[i * 4 + 3] = 255;
}
trayIcon = nativeImage.createFromBuffer(buffer, { width: size, height: size });
}
tray = new Tray(trayIcon);
updateTrayMenu();
tray.setToolTip('MyVPN - Отключен');
tray.on('double-click', () => {
if (mainWindow) mainWindow.show();
});
}
function updateTrayMenu() {
const isConnected = xrayProcess !== null;
const contextMenu = Menu.buildFromTemplate([
{ label: 'MyVPN', enabled: false },
{ type: 'separator' },
{ label: isConnected ? '● Подключен' : '○ Отключен', enabled: false },
{ type: 'separator' },
{ label: 'Открыть', click: () => { if (mainWindow) mainWindow.show(); } },
{
label: isConnected ? 'Отключить VPN' : 'Подключить VPN',
click: async () => {
if (isConnected) await disconnectVPN();
else await connectVPN();
updateTrayMenu();
}
},
{ type: 'separator' },
{ label: 'Выход', click: () => { isQuitting = true; cleanupAndQuit(); app.quit(); } }
]);
tray.setContextMenu(contextMenu);
tray.setToolTip(isConnected ? 'MyVPN - Подключен' : 'MyVPN - Отключен');
}
function createWindow() {
fs.writeFileSync(logFile, '');
mainWindow = new BrowserWindow({
width: 600, height: 700, minWidth: 400, minHeight: 500, resizable: true,
webPreferences: { nodeIntegration: true, contextIsolation: false }
});
mainWindow.loadFile('index.html');
mainWindow.setMenuBarVisibility(false);
mainWindow.on('close', (event) => { if (!isQuitting) { event.preventDefault(); mainWindow.hide(); } });
mainWindow.on('minimize', (event) => { event.preventDefault(); mainWindow.hide(); });
}
app.whenReady().then(() => { createWindow(); createTray(); });
app.on('window-all-closed', () => { });
app.on('before-quit', () => { isQuitting = true; cleanupAndQuit(); });
// Генерация XRay конфига
function generateXrayConfig(config) {
return {
log: { loglevel: 'warning' },
inbounds: [
{ port: 10808, protocol: 'socks', settings: { udp: true }, sniffing: { enabled: true, destOverride: ['http', 'tls'] } },
{ port: 10809, protocol: 'http' }
],
outbounds: [
{
protocol: 'vless',
settings: {
vnext: [{
address: config.address,
port: config.port,
users: [{ id: config.uuid, encryption: 'none', flow: config.flow || 'xtls-rprx-vision' }]
}]
},
streamSettings: {
network: config.type || 'tcp',
security: config.security || 'reality',
realitySettings: config.security === 'reality' ? {
serverName: config.sni,
fingerprint: config.fingerprint,
publicKey: config.publicKey,
shortId: config.shortId
} : undefined
},
tag: 'proxy'
},
{ protocol: 'freedom', tag: 'direct' }
],
routing: { rules: [{ type: 'field', ip: ['geoip:private'], outboundTag: 'direct' }] }
};
}
// Подключение VPN через XRay
async function connectVPN() {
try {
const xrayPath = path.join(__dirname, 'xray', 'xray.exe');
const configPath = path.join(__dirname, 'xray', 'config.json');
if (!fs.existsSync(xrayPath)) {
writeLog('ERROR: xray.exe not found');
return { success: false, error: 'xray.exe не найден' };
}
const userConfig = loadUserConfig();
if (userConfig) {
const xrayConfig = generateXrayConfig(userConfig);
fs.writeFileSync(configPath, JSON.stringify(xrayConfig, null, 2));
}
writeLog('Starting XRay...');
if (mainWindow) mainWindow.webContents.send('vpn-log', '🔄 Запуск XRay...');
xrayProcess = spawn(xrayPath, ['run', '-config', configPath], { cwd: path.join(__dirname, 'xray') });
xrayProcess.stdout.on('data', (data) => {
const msg = data.toString();
writeLog(msg);
if (mainWindow) mainWindow.webContents.send('vpn-log', msg);
});
xrayProcess.stderr.on('data', (data) => {
const msg = data.toString();
writeLog('STDERR: ' + msg);
if (mainWindow) mainWindow.webContents.send('vpn-log', msg);
});
xrayProcess.on('close', (code) => {
writeLog(`XRay exited with code: ${code}`);
if (mainWindow) mainWindow.webContents.send('vpn-disconnected');
xrayProcess = null;
updateTrayMenu();
});
await new Promise(resolve => setTimeout(resolve, 1500));
if (xrayProcess && !xrayProcess.killed) {
const proxyAddress = '127.0.0.1:10809';
enableSystemProxy(proxyAddress);
setProxyEnvironment(proxyAddress);
writeLog('VPN connected (proxy mode)');
if (mainWindow) mainWindow.webContents.send('vpn-log', '✅ VPN включен (режим прокси)');
}
updateTrayMenu();
return { success: true };
} catch (error) {
writeLog('Connect error: ' + error.message);
return { success: false, error: error.message };
}
}
async function disconnectVPN() {
writeLog('VPN disconnecting...');
if (xrayProcess) { xrayProcess.kill(); xrayProcess = null; }
disableSystemProxy();
clearProxyEnvironment();
writeLog('VPN disconnected');
updateTrayMenu();
return { success: true };
}
// Config paths
const userConfigPath = path.join(__dirname, 'xray', 'user-config.json');
const xrayConfigPath = path.join(__dirname, 'xray', 'config.json');
// Parse VLESS URL
function parseVlessUrl(url) {
try {
if (!url.startsWith('vless://')) return { error: 'Ссылка должна начинаться с vless://' };
const withoutProtocol = url.substring(8);
const [mainPart, name] = withoutProtocol.split('#');
const [userServer, queryString] = mainPart.split('?');
const [uuid, serverPort] = userServer.split('@');
const [address, port] = serverPort.split(':');
const params = {};
if (queryString) {
queryString.split('&').forEach(p => {
const [key, value] = p.split('=');
params[key] = decodeURIComponent(value || '');
});
}
return {
uuid, address, port: parseInt(port),
name: name ? decodeURIComponent(name) : address,
security: params.security || 'reality',
type: params.type || 'tcp',
sni: params.sni || params.serverName || 'www.google.com',
fingerprint: params.fp || 'chrome',
publicKey: params.pbk || '',
shortId: params.sid || '',
flow: params.flow || 'xtls-rprx-vision'
};
} catch (e) {
return { error: 'Неверный формат ссылки: ' + e.message };
}
}
function saveUserConfig(config) { fs.writeFileSync(userConfigPath, JSON.stringify(config, null, 2)); }
function loadUserConfig() {
try {
if (fs.existsSync(userConfigPath)) return JSON.parse(fs.readFileSync(userConfigPath, 'utf8'));
} catch (e) { writeLog('Error loading user config: ' + e.message); }
return null;
}
// IPC handlers
ipcMain.handle('connect-vpn', connectVPN);
ipcMain.handle('disconnect-vpn', disconnectVPN);
ipcMain.handle('get-status', async () => ({ connected: xrayProcess !== null }));
ipcMain.handle('get-config', async () => loadUserConfig());
ipcMain.handle('save-config', async (event, vlessUrl) => {
const parsed = parseVlessUrl(vlessUrl);
if (parsed.error) return { success: false, error: parsed.error };
saveUserConfig(parsed);
const xrayConfig = generateXrayConfig(parsed);
fs.writeFileSync(xrayConfigPath, JSON.stringify(xrayConfig, null, 2));
writeLog('Config saved: ' + parsed.address + ':' + parsed.port);
return { success: true, config: parsed };
});
ipcMain.handle('reset-config', async () => {
try {
if (fs.existsSync(userConfigPath)) fs.unlinkSync(userConfigPath);
writeLog('Config reset');
return { success: true };
} catch (e) { return { success: false, error: e.message }; }
});