Files
browser-farm/manager/server.js
T

402 lines
14 KiB
JavaScript

// Browser Farm manager — serves the grid UI and controls 8 isolated Neko
// browsers (farm-b1..farm-b8) via docker. Listens on 127.0.0.1:18080;
// nginx proxies port 80 to it. No database: per-browser runtime state lives
// in /opt/farm/<id>/meta.json, static identity in manager/config.json.
// Security: browser ids are validated strictly (^b[1-8]$) and every docker
// call uses execFile with an argument array — no user input ever reaches a
// shell. One password (FARM_PASSWORD) gates the whole grid (httpOnly
// farm_auth cookie, 7 days); the manager logs in to each Neko instance
// itself and hands the grid a ?token= URL per cell, so the user never sees
// a per-cell Neko login form.
'use strict';
const express = require('express');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { execFile } = require('child_process');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);
const app = express();
const PORT = Number(process.env.PORT || 18080);
const HOST = process.env.HOST || '127.0.0.1';
const FARM_ROOT = process.env.FARM_ROOT || '/opt/farm';
const CONFIG_PATH = path.join(__dirname, 'config.json');
const GENERATE_SCRIPT = path.join(__dirname, '..', 'scripts', 'generate.js');
// Single password for the whole farm: the grid login AND every Neko
// instance's password. Must match FARM_PASSWORD in scripts/install.sh.
const FARM_PASSWORD = process.env.FARM_PASSWORD || 'pendol1722';
const NEKO_LOGIN_USER = 'pend';
const TOKEN_TTL_MS = 55 * 60 * 1000; // Neko tokens are re-fetched every 55 min
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; // farm login lasts 7 days
// In-memory farm sessions: sessionId -> expiresAt (ms). No DB.
const sessions = new Map();
// In-memory Neko tokens: browserId -> { token, expiresAt, startedAt }.
const tokenCache = new Map();
app.use(express.json({ limit: '64kb' }));
app.use(express.static(path.join(__dirname, 'public')));
function parseCookies(req) {
const out = {};
const header = req.headers && req.headers.cookie;
if (!header) return out;
header.split(';').forEach(function (part) {
const idx = part.indexOf('=');
if (idx > 0) {
try {
out[part.slice(0, idx).trim()] = decodeURIComponent(part.slice(idx + 1).trim());
} catch (e) {
out[part.slice(0, idx).trim()] = part.slice(idx + 1).trim();
}
}
});
return out;
}
function isAuthenticated(req) {
const sid = parseCookies(req).farm_auth;
if (!sid) return false;
const exp = sessions.get(sid);
if (!exp) return false;
if (exp < Date.now()) {
sessions.delete(sid);
return false;
}
return true;
}
// Grid-level password gate for /api/*. Public: POST /api/login, GET /api/me.
// GET /health is not under /api, so it is never gated. The grid page itself
// (/) is served without auth; it calls /api/me and shows a login overlay
// when the session is missing or expired.
function requireFarmAuth(req, res, next) {
if (req.method === 'POST' && req.path === '/login') return next();
if (req.method === 'GET' && req.path === '/me') return next();
if (isAuthenticated(req)) return next();
return res.status(401).json({ ok: false, error: 'unauthorized' });
}
app.use('/api', requireFarmAuth);
function loadConfig() {
return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
}
// Merge config defaults with the runtime meta.json (if it exists).
function loadBrowser(id) {
const cfg = loadConfig();
const base = (cfg.browsers || []).find((b) => b.id === id);
if (!base) return null;
let meta = {};
try {
meta = JSON.parse(fs.readFileSync(path.join(FARM_ROOT, id, 'meta.json'), 'utf8'));
} catch (e) {
// No meta yet (fresh install) — fall back to config defaults.
}
const uaKey = meta.uaKey || base.uaKey;
const preset = (cfg.uaPresets || {})[uaKey] || (cfg.uaPresets || {})[base.uaKey] || {};
return {
id: base.id,
name: meta.name || base.name,
uaKey: uaKey,
uaLabel: preset.label || uaKey,
proxy: meta.proxy || { type: 'direct' },
httpPort: base.httpPort,
udpStart: base.udpStart,
udpEnd: base.udpEnd,
};
}
function validateId(id) {
return /^b[1-8]$/.test(id || '');
}
async function dockerStatus(id) {
const name = 'farm-' + id;
try {
const { stdout } = await execFileAsync('docker', [
'inspect',
'-f',
'{{.State.Status}}|{{.State.StartedAt}}',
name,
]);
const parts = stdout.trim().split('|');
const status = parts[0] || 'stopped';
let uptime = null;
if (status === 'running' && parts[1]) {
const started = new Date(parts[1]).getTime();
if (!Number.isNaN(started)) {
uptime = Math.max(0, Math.floor((Date.now() - started) / 1000));
}
}
return { status: status, uptime: uptime, startedAt: parts[1] || null };
} catch (e) {
// Container missing, or docker unavailable — treat as stopped.
return { status: 'stopped', uptime: null, startedAt: null };
}
}
// Log in to one Neko instance and return its session token (or null).
// The Neko web client accepts ?token=... in the iframe URL and then
// auto-connects, so the user never sees a per-cell login form.
async function fetchNekoToken(httpPort) {
try {
const res = await fetch('http://127.0.0.1:' + httpPort + '/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: NEKO_LOGIN_USER, password: FARM_PASSWORD }),
signal: AbortSignal.timeout(5000),
});
if (!res.ok) return null;
const j = await res.json();
return j && typeof j.token === 'string' && j.token ? j.token : null;
} catch (e) {
console.error(
'neko login failed (port ' + httpPort + '): ' + (e && e.message ? e.message : e)
);
return null;
}
}
// Cached Neko token for one browser. Re-fetched when missing, expired, or
// when the container restarted (startedAt changed — a restart invalidates
// the old token). Returns null when Neko is not reachable yet.
async function getBrowserToken(id, httpPort, startedAt) {
const now = Date.now();
const cached = tokenCache.get(id);
if (
cached &&
cached.token &&
cached.expiresAt > now &&
cached.startedAt === startedAt
) {
return cached.token;
}
const token = await fetchNekoToken(httpPort);
if (token) {
tokenCache.set(id, { token: token, expiresAt: now + TOKEN_TTL_MS, startedAt: startedAt });
} else {
tokenCache.delete(id);
}
return token;
}
async function dockerAction(action, id) {
await execFileAsync('docker', [action, 'farm-' + id]);
}
function validateProxy(p) {
const proxy = p || { type: 'direct' };
if (!['direct', 'http', 'socks5'].includes(proxy.type)) {
return { error: 'invalid proxy type (want direct|http|socks5)' };
}
if (proxy.type === 'direct') return { proxy: { type: 'direct' } };
const host = typeof proxy.host === 'string' ? proxy.host.trim() : '';
const port = Number(proxy.port);
if (!host) return { error: 'proxy host required' };
if (!Number.isInteger(port) || port < 1 || port > 65535) {
return { error: 'proxy port invalid (want 1-65535)' };
}
return {
proxy: {
type: proxy.type,
host: host,
port: port,
user: typeof proxy.user === 'string' ? proxy.user : '',
pass: typeof proxy.pass === 'string' ? proxy.pass : '',
},
};
}
app.get('/health', (req, res) => {
res.json({ ok: true });
});
// Single grid-level login. On success sets an httpOnly farm_auth cookie
// (7 days). One password for the whole farm — no per-cell login.
app.post('/api/login', (req, res) => {
const pw = req.body && typeof req.body.password === 'string' ? req.body.password : '';
const expected = Buffer.from(FARM_PASSWORD, 'utf8');
const given = Buffer.from(pw, 'utf8');
const ok = given.length === expected.length && crypto.timingSafeEqual(given, expected);
if (!ok) {
return res.status(401).json({ ok: false, error: 'password salah' });
}
const sid = crypto.randomBytes(32).toString('hex');
sessions.set(sid, Date.now() + SESSION_TTL_MS);
res.setHeader(
'Set-Cookie',
'farm_auth=' + sid + '; HttpOnly; Path=/; Max-Age=' + Math.floor(SESSION_TTL_MS / 1000) + '; SameSite=Lax'
);
res.json({ ok: true });
});
app.get('/api/me', (req, res) => {
res.json({ authenticated: isAuthenticated(req) });
});
// UA preset list, used by the Settings dropdown in the grid UI.
app.get('/api/ua-presets', (req, res) => {
try {
const cfg = loadConfig();
res.json({ presets: cfg.uaPresets || {} });
} catch (e) {
res.status(500).json({ ok: false, error: String((e && e.message) || e) });
}
});
app.get('/api/browsers', async (req, res) => {
try {
const cfg = loadConfig();
const list = await Promise.all(
(cfg.browsers || []).map(async (b) => {
const info = loadBrowser(b.id);
const st = await dockerStatus(b.id);
// Token is only fetched when the cache is stale (missing, expired,
// or the container restarted) — never on every 10s poll.
let token = null;
if (st.status === 'running') {
token = await getBrowserToken(b.id, info.httpPort, st.startedAt);
}
return Object.assign({}, info, { status: st.status, uptime: st.uptime, token: token });
})
);
res.json({ browsers: list });
} catch (e) {
res.status(500).json({ ok: false, error: String((e && e.message) || e) });
}
});
// Start all / stop all (defined before the :id routes).
app.post('/api/browsers/start-all', async (req, res) => {
const cfg = loadConfig();
const results = [];
for (const b of cfg.browsers || []) {
try {
await dockerAction('start', b.id);
results.push({ id: b.id, ok: true });
} catch (e) {
results.push({ id: b.id, ok: false, error: String((e && e.message) || e) });
}
}
res.json({ ok: true, results: results });
});
app.post('/api/browsers/stop-all', async (req, res) => {
const cfg = loadConfig();
const results = [];
for (const b of cfg.browsers || []) {
try {
await dockerAction('stop', b.id);
results.push({ id: b.id, ok: true });
} catch (e) {
results.push({ id: b.id, ok: false, error: String((e && e.message) || e) });
}
}
res.json({ ok: true, results: results });
});
// Wipe one browser's profile (cookies, history, logins). Scope is exactly
// that browser's bind-mounted profile dir — nothing else is touched.
app.post('/api/browsers/:id/wipe', async (req, res) => {
const id = req.params.id;
if (!validateId(id)) {
return res.status(400).json({ ok: false, error: 'invalid browser id' });
}
const profileDir = path.resolve(path.join(FARM_ROOT, id, 'profile'));
const root = path.resolve(FARM_ROOT) + path.sep;
if (!profileDir.startsWith(root)) {
return res.status(400).json({ ok: false, error: 'invalid profile path' });
}
try {
try {
await dockerAction('stop', id);
} catch (e) {
// Already stopped or missing — wiping the profile is still safe.
}
await execFileAsync('rm', ['-rf', profileDir]);
await execFileAsync('mkdir', ['-p', profileDir]);
await dockerAction('start', id);
const st = await dockerStatus(id);
res.json({
ok: true,
id: id,
wiped: 'profile of farm-' + id + ' only',
scope:
'Only this browser (farm-' + id + ') profile was deleted. ' +
'Other browsers were not touched.',
status: st.status,
});
} catch (e) {
res.status(500).json({ ok: false, error: String((e && e.message) || e) });
}
});
// Change one browser's identity (UA preset + proxy), then restart it so the
// new Chromium flags take effect.
app.post('/api/browsers/:id/config', 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();
if (!body.ua || !(cfg.uaPresets || {})[body.ua]) {
return res.status(400).json({ ok: false, error: 'invalid ua preset' });
}
const checked = validateProxy(body.proxy);
if (checked.error) {
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);
const info = loadBrowser(id);
const st = await dockerStatus(id);
res.json({
ok: true,
id: id,
name: info.name,
uaKey: info.uaKey,
uaLabel: info.uaLabel,
proxy: info.proxy,
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) => {
const id = req.params.id;
const action = req.params.action;
if (!validateId(id)) {
return res.status(400).json({ ok: false, error: 'invalid browser id' });
}
if (action !== 'start' && action !== 'stop' && action !== 'restart') {
return res.status(400).json({ ok: false, error: 'invalid action' });
}
try {
await dockerAction(action, id);
const st = await dockerStatus(id);
res.json({ ok: true, id: id, action: action, status: st.status });
} catch (e) {
res.status(500).json({ ok: false, error: String((e && e.message) || e) });
}
});
app.listen(PORT, HOST, () => {
console.log('browser-farm manager listening on ' + HOST + ':' + PORT);
});