Dashboard VPN: per-browser VPN toggle with country picker

- manager/vpn-pool.js: free proxy pool from ProxyScrape JSON (no key),
  live-checked via curl, cached 30 min, grouped by country
- server.js: GET /api/vpn/pool, POST /api/vpn/refresh,
  POST /api/browsers/:id/vpn; vpn state stored in meta.json
- generate.js: 5th arg vpnJson, stored in meta.json
- index.html: VPN section in Settings (toggle + country + refresh),
  VPN badge on cells, manual proxy disabled while VPN is on
- README: VPN section + file list
Verified live on 49.128.189.254: 24 working proxies in 11 countries,
b1 VPN on (PH 180.232.127.250) showed the proxy IP, off restored direct
This commit is contained in:
maspend committed 2026-12-02 14:38:03 +07:00
1 parent df4ae5a17a
commit 26427401db
5 files changed
+426 -13

No files matched your search

+34
View File
@@ -141,6 +141,39 @@ ikut melakukan hal yang sama: gerakan mouse, klik, scroll, dan ketikan.
`:1808N` sebagai fallback untuk pemakaian satu browser, dan laporkan `:1808N` sebagai fallback untuk pemakaian satu browser, dan laporkan
ke Muse untuk diperiksa. ke Muse untuk diperiksa.
## VPN lewat dashboard (per browser)
Tiap browser bisa dinyalakan VPN-nya langsung dari grid, tanpa membuka
ekstensi Browsec di dalam browser. Buka **Settings** di satu cell, di
bagian **VPN** pilih **VPN nyala** + negara (atau Otomatis), lalu
**Simpan & Restart** — browser itu restart dan semua traffic-nya jalan
lewat server VPN di negara yang dipilih (IP-nya berubah). Cell yang VPN-nya
nyala menampilkan badge biru **VPN · XX** dan identitasnya menunjukkan
negara + server VPN-nya. Matikan lagi dari Settings yang sama.
- **Cara kerja.** Saklar VPN di dashboard memilih satu server dari pool
proxy gratis (SOCKS5/HTTP) lalu mengaturnya sebagai `--proxy-server`
Chromium browser itu (mekanisme yang sama dengan proxy manual di
Settings). Status VPN tercatat di `meta.json` (`vpn: {on, country,
countryCode, type, host, port}`) supaya grid bisa menampilkan badge.
Proxy manual diabaikan selama VPN nyala (field-nya di-disable).
- **Pool VPN.** Sumber: ProxyScrape free proxy list (JSON, tanpa key,
tanpa akun). Manager (`manager/vpn-pool.js`) mengambil daftarnya,
menyaring yang `alive` + uptime cukup, lalu mengecek tiap kandidat
dengan request nyata lewat proxy itu (curl ke ifconfig.me) — hanya
yang lolos yang masuk pool. Pool di-cache 30 menit, di-refresh otomatis
di background (saat manager start dan saat cache basi), dan bisa
di-refresh manual dari tombol **Refresh daftar negara VPN** di Settings.
Endpoint: `GET /api/vpn/pool` (negara + jumlah), `POST /api/vpn/refresh`,
`POST /api/browsers/:id/vpn` (`{on, country?, ua?}`).
- **Batasan.** Ini proxy gratis, bukan VPN berbayar: kecepatan dan
kestabilan bervariasi, server bisa mati mendadak, dan negara yang
tersedia tergantung pool saat itu (biasanya ~10–25 server di ~10 negara).
Kalau halaman tidak mau load setelah VPN nyala, matikan lalu nyalakan
lagi (dapat server baru) atau pilih negara lain. Untuk VPN yang stabil,
pakai proxy berbayar dan isi di proxy manual (Settings) — itu tetap
didukung seperti sebelumnya.
## Identitas default (10 browser) ## Identitas default (10 browser)
| ID | Nama | User-Agent | HTTP | UDP | | ID | Nama | User-Agent | HTTP | UDP |
@@ -235,6 +268,7 @@ Installer membuat b1..b10. Untuk browser ke-11 (atau lebih):
browser-farm/ browser-farm/
manager/ manager/
server.js # API + static server (Express, :18080) server.js # API + static server (Express, :18080)
vpn-pool.js # pool VPN gratis (ProxyScrape, cek live, cache 30 mnt)
config.json # 10 browser + 10 preset User-Agent config.json # 10 browser + 10 preset User-Agent
package.json # express ^4.19.2 package.json # express ^4.19.2
public/index.html # grid UI (5x2, dark, Bahasa Indonesia) public/index.html # grid UI (5x2, dark, Bahasa Indonesia)
+127 -4
View File
@@ -38,6 +38,7 @@
.badge.running{background:var(--accent-dark);color:var(--accent)} .badge.running{background:var(--accent-dark);color:var(--accent)}
.badge.stopped{background:#3d1a1a;color:var(--danger)} .badge.stopped{background:#3d1a1a;color:var(--danger)}
.badge.master{background:#3b2f0b;color:var(--warn)} .badge.master{background:#3b2f0b;color:var(--warn)}
.badge.vpn{background:#123a5c;color:#93c5fd}
.cell.is-master{border-color:var(--warn)} .cell.is-master{border-color:var(--warn)}
button.sync-on{background:var(--accent);border-color:var(--accent);color:#06281c;font-weight:600} button.sync-on{background:var(--accent);border-color:var(--accent);color:#06281c;font-weight:600}
.identity{margin-top:4px;color:var(--muted);font-size:12px;word-break:break-word} .identity{margin-top:4px;color:var(--muted);font-size:12px;word-break:break-word}
@@ -78,7 +79,7 @@
<button id="stopAllBtn" type="button">Stop semua</button> <button id="stopAllBtn" type="button">Stop semua</button>
<button id="syncBtn" type="button" title="Saat ON, kendalikan 1 browser dan semua browser lain ikut (klik, scroll, ketik, paste).">Sinkron: OFF</button> <button id="syncBtn" type="button" title="Saat ON, kendalikan 1 browser dan semua browser lain ikut (klik, scroll, ketik, paste).">Sinkron: OFF</button>
</header> </header>
<p class="note"><b>Cara pakai:</b> login sekali dengan password farm &mdash; semua browser langsung terhubung otomatis. Tiap cell adalah browser Chromium sendiri (profil, cookie, dan IP terpisah). Settings mengubah User-Agent &amp; proxy, lalu browser restart otomatis. <b>Sinkron:</b> nyalakan tombol di atas, lalu klik/ketik/paste di satu browser — semua browser lain ikut melakukan hal yang sama. Browser yang terakhir kamu sentuh jadi Master (badge kuning).</p> <p class="note"><b>Cara pakai:</b> login sekali dengan password farm &mdash; semua browser langsung terhubung otomatis. Tiap cell adalah browser Chromium sendiri (profil, cookie, dan IP terpisah). Settings mengubah User-Agent &amp; proxy, lalu browser restart otomatis. <b>VPN:</b> di Settings tiap browser ada saklar VPN — nyalakan, pilih negara, dan browser itu jalan lewat server VPN (IP/nagara berubah) tanpa buka ekstensi Browsec di dalam browser. <b>Sinkron:</b> nyalakan tombol di atas, lalu klik/ketik/paste di satu browser — semua browser lain ikut melakukan hal yang sama. Browser yang terakhir kamu sentuh jadi Master (badge kuning).</p>
<div class="banner" id="banner"></div> <div class="banner" id="banner"></div>
<main class="grid" id="grid"></main> <main class="grid" id="grid"></main>
@@ -204,6 +205,11 @@
} }
function identityLine(b) { function identityLine(b) {
var v = b.vpn || { on: false };
if (v.on) {
return (b.uaLabel || b.uaKey || '-') + ' · VPN ' + (v.country || v.countryCode || '') +
' (' + (v.type || '') + ' ' + (v.host || '') + ':' + (v.port || '') + ')';
}
var p = b.proxy || { type: 'direct' }; var p = b.proxy || { type: 'direct' };
var proxyText = 'Direct'; var proxyText = 'Direct';
if (p.type && p.type !== 'direct') { if (p.type && p.type !== 'direct') {
@@ -228,6 +234,9 @@
title.appendChild(el('strong', null, b.name)); title.appendChild(el('strong', null, b.name));
var badge = el('span', 'badge stopped', 'Stopped'); var badge = el('span', 'badge stopped', 'Stopped');
title.appendChild(badge); title.appendChild(badge);
var vpnBadge = el('span', 'badge vpn', 'VPN');
vpnBadge.style.display = 'none';
title.appendChild(vpnBadge);
var masterBadge = el('span', 'badge master', 'Master'); var masterBadge = el('span', 'badge master', 'Master');
masterBadge.style.display = 'none'; masterBadge.style.display = 'none';
title.appendChild(masterBadge); title.appendChild(masterBadge);
@@ -277,9 +286,23 @@
saveSettings(b.id); saveSettings(b.id);
}); });
form.innerHTML = form.innerHTML =
'<label>VPN (lewat dashboard &mdash; tanpa buka Browsec di browser)</label>' +
'<div class="row">' +
'<div><select name="vpnOn">' +
'<option value="off">VPN mati</option>' +
'<option value="on">VPN nyala</option>' +
'</select></div>' +
'<div><select name="vpnCountry">' +
'<option value="">Otomatis (negara mana saja)</option>' +
'</select></div>' +
'</div>' +
'<div class="msg vpnmsg"></div>' +
'<div class="actions">' +
'<button type="button" class="vpnRefreshBtn">Refresh daftar negara VPN</button>' +
'</div>' +
'<label>User-Agent</label>' + '<label>User-Agent</label>' +
'<select name="ua"></select>' + '<select name="ua"></select>' +
'<label>Proxy</label>' + '<label>Proxy manual (dipakai kalau VPN mati)</label>' +
'<select name="proxyType">' + '<select name="proxyType">' +
'<option value="direct">Direct (tanpa proxy)</option>' + '<option value="direct">Direct (tanpa proxy)</option>' +
'<option value="http">HTTP</option>' + '<option value="http">HTTP</option>' +
@@ -301,11 +324,27 @@
form.querySelector('.cancelBtn').addEventListener('click', function () { form.querySelector('.cancelBtn').addEventListener('click', function () {
form.classList.remove('open'); form.classList.remove('open');
}); });
// VPN on => the manual proxy fields are ignored (the VPN server is
// the proxy), so disable them to avoid confusion.
form.querySelector('select[name="vpnOn"]').addEventListener('change', function () {
var on = form.querySelector('select[name="vpnOn"]').value === 'on';
['proxyType', 'host', 'port', 'user', 'pass'].forEach(function (n) {
var inp = form.querySelector('[name="' + n + '"]');
if (inp) inp.disabled = on;
});
});
form.querySelector('.vpnRefreshBtn').addEventListener('click', function () {
setVpnMsg(b.id, 'Me-refresh daftar negara VPN...', false);
fetch('/api/vpn/refresh', { method: 'POST' })
.then(function () { return loadVpnPool(); })
.then(function () { setVpnMsg(b.id, 'Daftar negara VPN diperbarui.', false); })
.catch(function () { setVpnMsg(b.id, 'Gagal refresh pool VPN.', true); });
});
cell.appendChild(form); cell.appendChild(form);
grid.appendChild(cell); grid.appendChild(cell);
cells[b.id] = { cells[b.id] = {
el: cell, iframe: frame, overlay: overlay, badge: badge, el: cell, iframe: frame, overlay: overlay, badge: badge, vpnBadge: vpnBadge,
identity: identity, form: form, prevStatus: null, iframeLoaded: false, identity: identity, form: form, prevStatus: null, iframeLoaded: false,
tokenLoaded: false, masterBadge: masterBadge, inputEl: null, inputPoll: null, tokenLoaded: false, masterBadge: masterBadge, inputEl: null, inputPoll: null,
}; };
@@ -589,6 +628,46 @@
syncBtn.addEventListener('click', function () { setSync(!syncOn); }); syncBtn.addEventListener('click', function () { setSync(!syncOn); });
renderSyncBtn(); renderSyncBtn();
// ---- Dashboard VPN pool ----
// Countries offered by the VPN toggle come from the manager's pool
// (free proxy servers, verified live). Loaded lazily when a Settings
// form opens; refreshed on demand via the Refresh button.
var vpnPoolCache = null;
function fillVpnCountries() {
var countries = (vpnPoolCache && vpnPoolCache.countries) || [];
Object.keys(cells).forEach(function (id) {
var sel = cells[id].form.querySelector('select[name="vpnCountry"]');
if (!sel) return;
var cur = sel.value;
sel.innerHTML = '<option value="">Otomatis (negara mana saja)</option>';
countries.forEach(function (c) {
var opt = document.createElement('option');
opt.value = c.code;
opt.textContent = c.name + ' (' + c.count + ')';
sel.appendChild(opt);
});
sel.value = cur || '';
});
}
function loadVpnPool() {
return fetch('/api/vpn/pool')
.then(function (r) { return r.json(); })
.then(function (j) {
vpnPoolCache = j;
fillVpnCountries();
return j;
})
.catch(function () { /* pool stays empty; turning VPN on will report it */ });
}
function setVpnMsg(id, text, isErr) {
var c = cells[id];
if (!c) return;
var m = c.form.querySelector('.vpnmsg');
if (!m) return;
m.textContent = text;
m.classList.toggle('err', !!isErr);
}
function fillUaOptions() { function fillUaOptions() {
Object.keys(cells).forEach(function (id) { Object.keys(cells).forEach(function (id) {
var sel = cells[id].form.querySelector('select[name="ua"]'); var sel = cells[id].form.querySelector('select[name="ua"]');
@@ -606,6 +685,18 @@
var c = cells[id]; var c = cells[id];
var sel = c.form.querySelector('select[name="ua"]'); var sel = c.form.querySelector('select[name="ua"]');
sel.value = b.uaKey || ''; sel.value = b.uaKey || '';
var v = b.vpn || { on: false };
var vpnOn = !!v.on;
c.form.querySelector('select[name="vpnOn"]').value = vpnOn ? 'on' : 'off';
c.form.querySelector('select[name="vpnCountry"]').value = v.countryCode || '';
setVpnMsg(id, vpnOn
? ('VPN nyala: ' + (v.country || v.countryCode || '') + ' · ' + (v.type || '') + ' ' + (v.host || '') + ':' + (v.port || ''))
: 'VPN mati — browser pakai koneksi langsung / proxy manual di bawah.', false);
['proxyType', 'host', 'port', 'user', 'pass'].forEach(function (n) {
var inp = c.form.querySelector('[name="' + n + '"]');
if (inp) inp.disabled = vpnOn;
});
loadVpnPool();
var p = b.proxy || { type: 'direct' }; var p = b.proxy || { type: 'direct' };
c.form.querySelector('select[name="proxyType"]').value = p.type || 'direct'; c.form.querySelector('select[name="proxyType"]').value = p.type || 'direct';
c.form.querySelector('input[name="host"]').value = p.host || ''; c.form.querySelector('input[name="host"]').value = p.host || '';
@@ -661,6 +752,33 @@
function saveSettings(id) { function saveSettings(id) {
var c = cells[id]; var c = cells[id];
var f = c.form; var f = c.form;
var ua = f.querySelector('select[name="ua"]').value;
var vpnOn = f.querySelector('select[name="vpnOn"]').value === 'on';
if (vpnOn) {
// VPN on: the dashboard picks a working server from the pool for
// the chosen country (or any country) and restarts the browser
// through it. The manual proxy is ignored while VPN is on.
var country = f.querySelector('select[name="vpnCountry"]').value;
setMsg(id, 'Menyalakan VPN & restart browser...', false);
fetch('/api/browsers/' + encodeURIComponent(id) + '/vpn', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ on: true, country: country, ua: ua }),
})
.then(function (r) { return r.json(); })
.then(function (j) {
if (!j.ok) throw new Error(j.error || 'gagal menyalakan VPN');
var v = j.vpn || {};
setMsg(id, 'VPN nyala: ' + (v.country || '') + ' · ' + (v.type || '') + ' ' + (v.host || '') + ':' + (v.port || ''), false);
return refresh();
})
.catch(function (e) {
setMsg(id, 'Gagal: ' + e.message, true);
});
return;
}
// VPN off: manual proxy / direct, as before (this also clears the
// dashboard VPN state on the server).
var proxyType = f.querySelector('select[name="proxyType"]').value; var proxyType = f.querySelector('select[name="proxyType"]').value;
var proxy = { type: proxyType }; var proxy = { type: proxyType };
if (proxyType !== 'direct') { if (proxyType !== 'direct') {
@@ -670,7 +788,7 @@
proxy.pass = f.querySelector('input[name="pass"]').value; proxy.pass = f.querySelector('input[name="pass"]').value;
} }
var body = { var body = {
ua: f.querySelector('select[name="ua"]').value, ua: ua,
proxy: proxy, proxy: proxy,
}; };
setMsg(id, 'Menyimpan & restart browser...', false); setMsg(id, 'Menyimpan & restart browser...', false);
@@ -697,6 +815,11 @@
var running = b.status === 'running'; var running = b.status === 'running';
c.badge.textContent = running ? 'Running' : 'Stopped'; c.badge.textContent = running ? 'Running' : 'Stopped';
c.badge.className = 'badge ' + (running ? 'running' : 'stopped'); c.badge.className = 'badge ' + (running ? 'running' : 'stopped');
var v = b.vpn || { on: false };
if (c.vpnBadge) {
c.vpnBadge.style.display = v.on ? '' : 'none';
c.vpnBadge.textContent = 'VPN · ' + (v.countryCode || v.country || '');
}
c.identity.textContent = identityLine(b); c.identity.textContent = identityLine(b);
c.overlay.style.display = running ? 'none' : 'flex'; c.overlay.style.display = running ? 'none' : 'flex';
if (running) { if (running) {
+96 -8
View File
@@ -19,6 +19,7 @@ const { promisify } = require('util');
const execFileAsync = promisify(execFile); const execFileAsync = promisify(execFile);
const app = express(); const app = express();
const vpnPool = require('./vpn-pool');
const PORT = Number(process.env.PORT || 18080); const PORT = Number(process.env.PORT || 18080);
const HOST = process.env.HOST || '127.0.0.1'; const HOST = process.env.HOST || '127.0.0.1';
@@ -105,6 +106,7 @@ function loadBrowser(id) {
uaKey: uaKey, uaKey: uaKey,
uaLabel: preset.label || uaKey, uaLabel: preset.label || uaKey,
proxy: meta.proxy || { type: 'direct' }, proxy: meta.proxy || { type: 'direct' },
vpn: meta.vpn && typeof meta.vpn.on === 'boolean' ? meta.vpn : { on: false },
httpPort: base.httpPort, httpPort: base.httpPort,
udpStart: base.udpStart, udpStart: base.udpStart,
udpEnd: base.udpEnd, udpEnd: base.udpEnd,
@@ -336,8 +338,21 @@ app.post('/api/browsers/:id/wipe', async (req, res) => {
} }
}); });
// Regenerate one browser's chromium.conf + meta.json and restart it.
// vpn is the dashboard VPN state stored in meta.json ({on:false} for a
// manual/direct setup; the /vpn endpoint passes the live VPN details).
async function applyBrowserConfig(id, uaKey, proxy, vpn) {
await execFileAsync(
process.execPath,
[GENERATE_SCRIPT, id, uaKey, JSON.stringify(proxy), JSON.stringify(vpn || { on: false })],
{ env: Object.assign({}, process.env, { FARM_ROOT: FARM_ROOT }) }
);
await dockerAction('restart', id);
}
// Change one browser's identity (UA preset + proxy), then restart it so the // Change one browser's identity (UA preset + proxy), then restart it so the
// new Chromium flags take effect. // new Chromium flags take effect. A manual proxy clears the dashboard VPN
// state (the proxy is now manual, not the VPN one).
app.post('/api/browsers/:id/config', async (req, res) => { app.post('/api/browsers/:id/config', async (req, res) => {
const id = req.params.id; const id = req.params.id;
if (!validateId(id)) { if (!validateId(id)) {
@@ -353,13 +368,7 @@ app.post('/api/browsers/:id/config', async (req, res) => {
return res.status(400).json({ ok: false, error: checked.error }); return res.status(400).json({ ok: false, error: checked.error });
} }
try { try {
// Regenerate chromium.conf + meta.json with the shared generator. await applyBrowserConfig(id, body.ua, checked.proxy, { on: false });
await execFileAsync(
process.execPath,
[GENERATE_SCRIPT, id, body.ua, JSON.stringify(checked.proxy)],
{ env: Object.assign({}, process.env, { FARM_ROOT: FARM_ROOT }) }
);
await dockerAction('restart', id);
const info = loadBrowser(id); const info = loadBrowser(id);
const st = await dockerStatus(id); const st = await dockerStatus(id);
res.json({ res.json({
@@ -369,6 +378,7 @@ app.post('/api/browsers/:id/config', async (req, res) => {
uaKey: info.uaKey, uaKey: info.uaKey,
uaLabel: info.uaLabel, uaLabel: info.uaLabel,
proxy: info.proxy, proxy: info.proxy,
vpn: info.vpn,
status: st.status, status: st.status,
}); });
} catch (e) { } catch (e) {
@@ -376,6 +386,79 @@ app.post('/api/browsers/:id/config', async (req, res) => {
} }
}); });
// ---- Dashboard VPN ----
// The VPN toggle routes one browser through a free proxy server from the
// pool (another country), switched from the dashboard instead of the
// Browsec extension inside the browser. The proxy becomes the browser's
// --proxy-server; the vpn field in meta.json records that it came from
// the dashboard VPN, so the grid can show the badge.
app.get('/api/vpn/pool', (req, res) => {
const pool = vpnPool.getPool();
res.json({
ok: true,
updatedAt: pool.updatedAt,
refreshing: pool.refreshing,
total: pool.proxies.length,
countries: vpnPool.countries(),
});
});
app.post('/api/vpn/refresh', (req, res) => {
vpnPool.refreshPool().catch(() => {});
const pool = vpnPool.getPool();
res.json({ ok: true, refreshing: true, total: pool.proxies.length });
});
app.post('/api/browsers/:id/vpn', async (req, res) => {
const id = req.params.id;
if (!validateId(id)) {
return res.status(400).json({ ok: false, error: 'invalid browser id' });
}
const body = req.body || {};
const cfg = loadConfig();
const info = loadBrowser(id);
if (!info) return res.status(404).json({ ok: false, error: 'browser not found' });
const uaKey = body.ua && (cfg.uaPresets || {})[body.ua] ? body.ua : info.uaKey;
try {
if (body.on) {
let pool = vpnPool.getPool();
if (!pool.proxies.length) {
await vpnPool.refreshPool();
pool = vpnPool.getPool();
}
const picked = vpnPool.pickProxy(typeof body.country === 'string' ? body.country : '');
if (!picked) {
return res.status(503).json({
ok: false,
error: 'pool VPN belum siap atau tidak ada proxy untuk negara itu — refresh pool lalu ulangi',
});
}
const vpn = {
on: true,
country: picked.country,
countryCode: picked.countryCode,
type: picked.type,
host: picked.host,
port: picked.port,
};
await applyBrowserConfig(
id,
uaKey,
{ type: picked.type, host: picked.host, port: picked.port, user: '', pass: '' },
vpn
);
const st = await dockerStatus(id);
return res.json({ ok: true, id: id, vpn: vpn, status: st.status });
}
// VPN off: back to a direct connection.
await applyBrowserConfig(id, uaKey, { type: 'direct' }, { on: false });
const st = await dockerStatus(id);
return res.json({ ok: true, id: id, vpn: { on: false }, status: st.status });
} catch (e) {
res.status(500).json({ ok: false, error: String((e && e.message) || e) });
}
});
// Generic start/stop/restart. Defined AFTER the specific :id routes // Generic start/stop/restart. Defined AFTER the specific :id routes
// (/wipe and /config) so Express does not swallow those paths as an "action". // (/wipe and /config) so Express does not swallow those paths as an "action".
app.post('/api/browsers/:id/:action', async (req, res) => { app.post('/api/browsers/:id/:action', async (req, res) => {
@@ -396,6 +479,11 @@ app.post('/api/browsers/:id/:action', async (req, res) => {
} }
}); });
// Warm up the VPN pool in the background so the dashboard toggle has
// servers ready when the user opens it. Refreshes again automatically
// whenever /api/vpn/pool sees a stale cache.
vpnPool.refreshPool().catch(() => {});
app.listen(PORT, HOST, () => { app.listen(PORT, HOST, () => {
console.log('browser-farm manager listening on ' + HOST + ':' + PORT); console.log('browser-farm manager listening on ' + HOST + ':' + PORT);
}); });
+149
View File
@@ -0,0 +1,149 @@
// vpn-pool.js — free VPN/proxy pool for the Browser Farm dashboard.
//
// The dashboard "VPN" toggle routes one browser through a free proxy
// server (SOCKS5/HTTP) in another country — the same idea as the Browsec
// extension, but switched from the dashboard instead of inside the browser.
// Source: ProxyScrape free proxy list (JSON, no key, no account). Every
// entry already carries protocol, country and uptime; the pool only offers
// entries that pass a live check (a real request through the proxy) so a
// dead proxy is never assigned to a browser.
//
// The pool is cached 30 minutes and refreshed in the background. Checks
// run through `curl` (present on the VPS) via execFile with an argument
// array — no user input ever reaches a shell.
'use strict';
const { execFile } = require('child_process');
const POOL_URL =
'https://api.proxyscrape.com/v4/free-proxy-list/get' +
'?request=display_proxies&proxy_format=protocolipport&format=json&timeout=10000';
const CHECK_URL = 'http://ifconfig.me/ip';
const CHECK_TIMEOUT_SEC = 8;
const CHECK_CONCURRENCY = 20;
const SAMPLE_SIZE = 80;
const CACHE_TTL_MS = 30 * 60 * 1000;
const MIN_UPTIME = 10; // percent; skip flaky entries
// Cache: { proxies: [{type, host, port, country, countryCode, city}], updatedAt, refreshing }
let cache = { proxies: [], updatedAt: 0, refreshing: false };
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
return arr;
}
function execCurl(args) {
return new Promise((resolve) => {
execFile('curl', args, { timeout: (CHECK_TIMEOUT_SEC + 2) * 1000 }, (err, stdout) => {
if (err) return resolve(null);
resolve((stdout || '').trim());
});
});
}
// Live-check one proxy: a real request through it must return an IP.
// Returns true when the proxy works.
async function checkProxy(p) {
const target = p.host + ':' + p.port;
let out = null;
if (p.type === 'socks5') {
out = await execCurl(['-s', '--max-time', String(CHECK_TIMEOUT_SEC), '--socks5', target, CHECK_URL]);
} else {
out = await execCurl(['-s', '--max-time', String(CHECK_TIMEOUT_SEC), '--proxy', 'http://' + target, CHECK_URL]);
}
// ifconfig.me/ip answers with a plain IPv4 address.
return out !== null && /^\d{1,3}(\.\d{1,3}){3}$/.test(out);
}
async function fetchList() {
const res = await fetch(POOL_URL, { signal: AbortSignal.timeout(20000) });
if (!res.ok) throw new Error('proxyscrape http ' + res.status);
const j = await res.json();
if (!j || !Array.isArray(j.proxies)) throw new Error('proxyscrape bad json');
return j.proxies;
}
// Refresh the pool. Runs in the background; concurrent callers share one run.
async function refreshPool() {
if (cache.refreshing) return cache;
cache.refreshing = true;
try {
const list = await fetchList();
const candidates = shuffle(
list
.filter((e) => e && e.alive && (e.protocol === 'socks5' || e.protocol === 'http'))
.filter((e) => typeof e.uptime === 'number' && e.uptime >= MIN_UPTIME)
.filter((e) => e.ip && Number.isInteger(e.port))
.map((e) => ({
type: e.protocol,
host: e.ip,
port: e.port,
country: (e.ip_data && e.ip_data.country) || 'Unknown',
countryCode: (e.ip_data && e.ip_data.countryCode) || '??',
city: (e.ip_data && e.ip_data.city) || '',
}))
).slice(0, SAMPLE_SIZE);
// Check the sample with bounded concurrency; keep only working proxies.
const working = [];
let next = 0;
async function worker() {
while (next < candidates.length) {
const p = candidates[next++];
try {
if (await checkProxy(p)) working.push(p);
} catch (e) {
// Dead proxy — skip it.
}
}
}
await Promise.all(Array.from({ length: CHECK_CONCURRENCY }, () => worker()));
// Prefer SOCKS5 (handles all traffic + remote DNS), then HTTP.
working.sort((a, b) => (a.type === b.type ? 0 : a.type === 'socks5' ? -1 : 1));
cache = { proxies: working, updatedAt: Date.now(), refreshing: false };
} catch (e) {
console.error('vpn pool refresh failed: ' + (e && e.message ? e.message : e));
cache.refreshing = false;
}
return cache;
}
// Current pool. Triggers a background refresh when stale; never blocks.
function getPool() {
const stale = Date.now() - cache.updatedAt > CACHE_TTL_MS;
if (stale && !cache.refreshing) {
refreshPool().catch(() => {});
}
return { proxies: cache.proxies, updatedAt: cache.updatedAt, refreshing: cache.refreshing, stale: stale };
}
// Countries in the current pool, with counts, sorted by count desc.
function countries() {
const byCode = new Map();
for (const p of cache.proxies) {
const cur = byCode.get(p.countryCode) || { code: p.countryCode, name: p.country, count: 0 };
cur.count++;
byCode.set(p.countryCode, cur);
}
return Array.from(byCode.values()).sort((a, b) => b.count - a.count);
}
// Pick one working proxy, optionally from a country. SOCKS5 preferred.
function pickProxy(countryCode) {
let list = cache.proxies;
if (countryCode) {
const byCountry = list.filter((p) => p.countryCode === countryCode);
if (byCountry.length) list = byCountry;
}
if (!list.length) return null;
return list[Math.floor(Math.random() * list.length)];
}
module.exports = { refreshPool, getPool, countries, pickProxy };
+20 -1
View File
@@ -1,12 +1,17 @@
#!/usr/bin/env node #!/usr/bin/env node
// generate.js — single source of truth for per-browser Neko files. // generate.js — single source of truth for per-browser Neko files.
// Usage: node generate.js <browserId> [uaKey] [proxyJson] // Usage: node generate.js <browserId> [uaKey] [proxyJson] [vpnJson]
// browserId: b1..b10 (required) // browserId: b1..b10 (required)
// uaKey: one of the keys in manager/config.json uaPresets (optional, // uaKey: one of the keys in manager/config.json uaPresets (optional,
// defaults to the browser's configured uaKey) // defaults to the browser's configured uaKey)
// proxyJson: JSON string, e.g. '{"type":"direct"}' or // proxyJson: JSON string, e.g. '{"type":"direct"}' or
// '{"type":"http","host":"1.2.3.4","port":8080,"user":"","pass":""}' // '{"type":"http","host":"1.2.3.4","port":8080,"user":"","pass":""}'
// (optional, defaults to {"type":"direct"}) // (optional, defaults to {"type":"direct"})
// vpnJson: JSON string describing the dashboard VPN state, e.g.
// '{"on":true,"country":"Netherlands","countryCode":"NL",
// "type":"socks5","host":"1.2.3.4","port":1080}'
// (optional, defaults to {"on":false}). Stored in meta.json
// only — it does not change chromium.conf beyond the proxy.
// Writes: <FARM_ROOT>/<id>/chromium.conf and <FARM_ROOT>/<id>/meta.json // Writes: <FARM_ROOT>/<id>/chromium.conf and <FARM_ROOT>/<id>/meta.json
// FARM_ROOT env var overrides the output root (default /opt/farm). // FARM_ROOT env var overrides the output root (default /opt/farm).
// Only ever called with validated arguments (browser id ^b(10|[1-9])$, ua key from // Only ever called with validated arguments (browser id ^b(10|[1-9])$, ua key from
@@ -31,6 +36,7 @@ function main() {
const id = process.argv[2]; const id = process.argv[2];
const uaKeyArg = process.argv[3] || ''; const uaKeyArg = process.argv[3] || '';
const proxyJson = process.argv[4] || ''; const proxyJson = process.argv[4] || '';
const vpnJson = process.argv[5] || '';
if (!/^b(10|[1-9])$/.test(id || '')) fail('invalid browser id (want b1..b10)'); if (!/^b(10|[1-9])$/.test(id || '')) fail('invalid browser id (want b1..b10)');
@@ -60,6 +66,18 @@ function main() {
fail('invalid proxy type (want direct|http|socks5)'); fail('invalid proxy type (want direct|http|socks5)');
} }
// Dashboard VPN state (stored in meta.json only; the proxy above is what
// actually routes the traffic). Kept as given, default off.
let vpn = { on: false };
if (vpnJson) {
try {
vpn = JSON.parse(vpnJson);
} catch (e) {
fail('invalid vpn JSON');
}
if (!vpn || typeof vpn.on !== 'boolean') fail('invalid vpn state (want {on:boolean,...})');
}
// Build the --proxy-server flag. Direct = no flag at all. // Build the --proxy-server flag. Direct = no flag at all.
// With user/pass the credentials are embedded in the URL (Chromium uses // With user/pass the credentials are embedded in the URL (Chromium uses
// them for proxy auth); they are visible in the container's process list, // them for proxy auth); they are visible in the container's process list,
@@ -105,6 +123,7 @@ function main() {
uaKey: uaKey, uaKey: uaKey,
uaLabel: preset.label, uaLabel: preset.label,
proxy: proxyMeta, proxy: proxyMeta,
vpn: vpn,
httpPort: browser.httpPort, httpPort: browser.httpPort,
udpStart: browser.udpStart, udpStart: browser.udpStart,
udpEnd: browser.udpEnd, udpEnd: browser.udpEnd,