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:
1 parent
df4ae5a17a
commit
26427401db
5 files changed
+426
-13
No files matched your search
+127
-4
@@ -38,6 +38,7 @@
|
||||
.badge.running{background:var(--accent-dark);color:var(--accent)}
|
||||
.badge.stopped{background:#3d1a1a;color:var(--danger)}
|
||||
.badge.master{background:#3b2f0b;color:var(--warn)}
|
||||
.badge.vpn{background:#123a5c;color:#93c5fd}
|
||||
.cell.is-master{border-color:var(--warn)}
|
||||
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}
|
||||
@@ -78,7 +79,7 @@
|
||||
<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>
|
||||
</header>
|
||||
<p class="note"><b>Cara pakai:</b> login sekali dengan password farm — semua browser langsung terhubung otomatis. Tiap cell adalah browser Chromium sendiri (profil, cookie, dan IP terpisah). Settings mengubah User-Agent & 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 — semua browser langsung terhubung otomatis. Tiap cell adalah browser Chromium sendiri (profil, cookie, dan IP terpisah). Settings mengubah User-Agent & 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>
|
||||
<main class="grid" id="grid"></main>
|
||||
|
||||
@@ -204,6 +205,11 @@
|
||||
}
|
||||
|
||||
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 proxyText = 'Direct';
|
||||
if (p.type && p.type !== 'direct') {
|
||||
@@ -228,6 +234,9 @@
|
||||
title.appendChild(el('strong', null, b.name));
|
||||
var badge = el('span', 'badge stopped', 'Stopped');
|
||||
title.appendChild(badge);
|
||||
var vpnBadge = el('span', 'badge vpn', 'VPN');
|
||||
vpnBadge.style.display = 'none';
|
||||
title.appendChild(vpnBadge);
|
||||
var masterBadge = el('span', 'badge master', 'Master');
|
||||
masterBadge.style.display = 'none';
|
||||
title.appendChild(masterBadge);
|
||||
@@ -277,9 +286,23 @@
|
||||
saveSettings(b.id);
|
||||
});
|
||||
form.innerHTML =
|
||||
'<label>VPN (lewat dashboard — 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>' +
|
||||
'<select name="ua"></select>' +
|
||||
'<label>Proxy</label>' +
|
||||
'<label>Proxy manual (dipakai kalau VPN mati)</label>' +
|
||||
'<select name="proxyType">' +
|
||||
'<option value="direct">Direct (tanpa proxy)</option>' +
|
||||
'<option value="http">HTTP</option>' +
|
||||
@@ -301,11 +324,27 @@
|
||||
form.querySelector('.cancelBtn').addEventListener('click', function () {
|
||||
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);
|
||||
|
||||
grid.appendChild(cell);
|
||||
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,
|
||||
tokenLoaded: false, masterBadge: masterBadge, inputEl: null, inputPoll: null,
|
||||
};
|
||||
@@ -589,6 +628,46 @@
|
||||
syncBtn.addEventListener('click', function () { setSync(!syncOn); });
|
||||
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() {
|
||||
Object.keys(cells).forEach(function (id) {
|
||||
var sel = cells[id].form.querySelector('select[name="ua"]');
|
||||
@@ -606,6 +685,18 @@
|
||||
var c = cells[id];
|
||||
var sel = c.form.querySelector('select[name="ua"]');
|
||||
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' };
|
||||
c.form.querySelector('select[name="proxyType"]').value = p.type || 'direct';
|
||||
c.form.querySelector('input[name="host"]').value = p.host || '';
|
||||
@@ -661,6 +752,33 @@
|
||||
function saveSettings(id) {
|
||||
var c = cells[id];
|
||||
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 proxy = { type: proxyType };
|
||||
if (proxyType !== 'direct') {
|
||||
@@ -670,7 +788,7 @@
|
||||
proxy.pass = f.querySelector('input[name="pass"]').value;
|
||||
}
|
||||
var body = {
|
||||
ua: f.querySelector('select[name="ua"]').value,
|
||||
ua: ua,
|
||||
proxy: proxy,
|
||||
};
|
||||
setMsg(id, 'Menyimpan & restart browser...', false);
|
||||
@@ -697,6 +815,11 @@
|
||||
var running = b.status === 'running';
|
||||
c.badge.textContent = 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.overlay.style.display = running ? 'none' : 'flex';
|
||||
if (running) {
|
||||
|
||||
+96
-8
@@ -19,6 +19,7 @@ const { promisify } = require('util');
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const app = express();
|
||||
const vpnPool = require('./vpn-pool');
|
||||
|
||||
const PORT = Number(process.env.PORT || 18080);
|
||||
const HOST = process.env.HOST || '127.0.0.1';
|
||||
@@ -105,6 +106,7 @@ function loadBrowser(id) {
|
||||
uaKey: uaKey,
|
||||
uaLabel: preset.label || uaKey,
|
||||
proxy: meta.proxy || { type: 'direct' },
|
||||
vpn: meta.vpn && typeof meta.vpn.on === 'boolean' ? meta.vpn : { on: false },
|
||||
httpPort: base.httpPort,
|
||||
udpStart: base.udpStart,
|
||||
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
|
||||
// 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) => {
|
||||
const id = req.params.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 });
|
||||
}
|
||||
try {
|
||||
// Regenerate chromium.conf + meta.json with the shared generator.
|
||||
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);
|
||||
await applyBrowserConfig(id, body.ua, checked.proxy, { on: false });
|
||||
const info = loadBrowser(id);
|
||||
const st = await dockerStatus(id);
|
||||
res.json({
|
||||
@@ -369,6 +378,7 @@ app.post('/api/browsers/:id/config', async (req, res) => {
|
||||
uaKey: info.uaKey,
|
||||
uaLabel: info.uaLabel,
|
||||
proxy: info.proxy,
|
||||
vpn: info.vpn,
|
||||
status: st.status,
|
||||
});
|
||||
} 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
|
||||
// (/wipe and /config) so Express does not swallow those paths as an "action".
|
||||
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, () => {
|
||||
console.log('browser-farm manager listening on ' + HOST + ':' + PORT);
|
||||
});
|
||||
@@ -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 };
|
||||
Reference in new issue
Block a user