Files
browser-farm/manager/vpn-pool.js
T
maspend 26427401db 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
2026-12-02 14:38:03 +07:00

150 lines
5.4 KiB
JavaScript

// 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 };