-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.js
More file actions
104 lines (92 loc) · 4.1 KB
/
Copy pathstart.js
File metadata and controls
104 lines (92 loc) · 4.1 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
const { spawn, spawnSync } = require('child_process');
const path = require('path');
const readline = require('readline');
const PORT = Number(process.env.PORT || 3000);
const root = __dirname;
function ps(command) {
const r = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', command], {
cwd: root,
encoding: 'utf8',
windowsHide: true
});
return { ok: r.status === 0, out: String(r.stdout || '').trim(), err: String(r.stderr || '').trim() };
}
function findWindowsPrimaryIp() {
if (process.platform !== 'win32') return '';
const cmd = String.raw`
$cfg = Get-NetIPConfiguration -ErrorAction SilentlyContinue |
Where-Object {
$_.IPv4DefaultGateway -and $_.IPv4Address -and $_.NetAdapter.Status -eq 'Up' -and
$_.IPv4Address.IPAddress -match '^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)' -and
$_.InterfaceAlias -notmatch 'vEthernet|WSL|Docker|VirtualBox|VMware|Tailscale|ZeroTier|Hamachi|WireGuard|OpenVPN|Bluetooth|Loopback'
} |
Select-Object -First 1
if ($cfg) { $cfg.IPv4Address.IPAddress }
`;
const r = ps(cmd);
return r.ok ? r.out.split(/\r?\n/).map(s => s.trim()).find(Boolean) || '' : '';
}
function firewallRuleExists() {
if (process.platform !== 'win32') return true;
const name = `DropLink Local Transfer (TCP ${PORT})`;
const safe = name.replace(/'/g, "''");
return ps(`if(Get-NetFirewallRule -DisplayName '${safe}' -ErrorAction SilentlyContinue){exit 0}else{exit 1}`).ok;
}
function ask(question) {
if (!process.stdin.isTTY) return Promise.resolve(true);
return new Promise(resolve => {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
rl.question(question, answer => {
rl.close();
const a = String(answer || '').trim().toLowerCase();
resolve(a === '' || a === 'y' || a === 'yes' || a === 'д' || a === 'да');
});
});
}
async function ensureFirewall() {
if (process.platform !== 'win32' || firewallRuleExists()) return;
console.log('');
console.log('[DropLink] Windows Firewall ещё не настроен для телефона.');
console.log(`[DropLink] Нужно один раз разрешить входящие подключения на TCP ${PORT} из частных LAN-сетей.`);
const yes = await ask('Настроить сейчас? [Y/n]: ');
if (!yes) {
console.log('[DropLink] Пропущено. localhost будет работать, но телефон может не подключиться.');
return;
}
const script = path.join(root, 'FIX_NETWORK_ACCESS.ps1');
const r = spawnSync('powershell.exe', [
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script, '-Port', String(PORT)
], { cwd: root, stdio: 'inherit' });
if (r.status !== 0) console.log('[DropLink] Не удалось создать правило Firewall. Запусти FIX_NETWORK_ACCESS.cmd от администратора.');
}
async function main() {
console.log('');
console.log('========================================');
console.log(' DropLink v0.2.2 — LAN startup check');
console.log('========================================');
await ensureFirewall();
const env = { ...process.env, PORT: String(PORT) };
const primaryIp = findWindowsPrimaryIp();
if (primaryIp) {
env.DROPLINK_PREFERRED_IP = primaryIp;
console.log(`[DropLink] Основной LAN IP Windows: ${primaryIp}`);
} else if (process.platform === 'win32') {
console.log('[DropLink] Не удалось определить основной LAN IP через Windows. Сервер покажет все найденные адреса.');
}
console.log('');
const child = spawn(process.execPath, [path.join(root, 'server.js')], {
cwd: root,
stdio: 'inherit',
env
});
child.on('exit', code => process.exit(code ?? 0));
const forward = signal => {
try { child.kill(signal); } catch {}
};
process.once('SIGINT', () => forward('SIGINT'));
process.once('SIGTERM', () => forward('SIGTERM'));
}
main().catch(err => {
console.error('[DropLink] Ошибка запуска:', err && err.message ? err.message : err);
process.exit(1);
});