Browser Farm: grid of 8 isolated Neko browsers with per-browser identity, single login, and sync control

This commit is contained in:
Muse committed 2026-12-01 21:20:41 +07:00
commit 32ac658c70
11 files changed
+2564

No files matched your search

+705
View File
@@ -0,0 +1,705 @@
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Browser Farm</title>
<style>
:root{
--bg:#0b1220; --panel:#111c2e; --panel2:#0e1726; --border:#1e2c44;
--text:#e6edf7; --muted:#8fa3bf; --accent:#34d399; --accent-dark:#0f3d2e;
--danger:#f87171; --warn:#fbbf24;
}
*{box-sizing:border-box}
html,body{margin:0;padding:0}
body{background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif}
.topbar{display:flex;align-items:center;gap:12px;padding:10px 16px;background:var(--panel);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:20;flex-wrap:wrap}
.topbar h1{font-size:18px;margin:0;letter-spacing:.3px}
.topbar h1 span{color:var(--accent)}
.topbar .sub{color:var(--muted);font-size:13px}
.spacer{flex:1}
.note{margin:0;padding:8px 16px;color:var(--muted);font-size:13px;background:var(--panel2);border-bottom:1px solid var(--border)}
.note b{color:var(--text)}
button{cursor:pointer;border:1px solid var(--border);background:var(--panel2);color:var(--text);border-radius:7px;padding:6px 11px;font-size:13px}
button:hover{border-color:var(--accent)}
button.primary{background:var(--accent);border-color:var(--accent);color:#06281c;font-weight:600}
button.danger{border-color:#5b2323;color:var(--danger)}
button.danger:hover{border-color:var(--danger)}
button:disabled{opacity:.45;cursor:default}
.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;padding:12px}
@media (max-width:1500px){.grid{grid-template-columns:repeat(2,1fr)}}
@media (max-width:820px){.grid{grid-template-columns:1fr}}
.cell{background:var(--panel);border:1px solid var(--border);border-radius:10px;overflow:hidden;display:flex;flex-direction:column;min-height:430px}
.cell.expanded{position:fixed;inset:0;z-index:60;border-radius:0;min-height:0}
.cell-head{padding:9px 12px;border-bottom:1px solid var(--border)}
.cell-title{display:flex;align-items:center;gap:8px;font-size:14px}
.cell-title strong{font-weight:650}
.badge{font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px;letter-spacing:.3px}
.badge.running{background:var(--accent-dark);color:var(--accent)}
.badge.stopped{background:#3d1a1a;color:var(--danger)}
.badge.master{background:#3b2f0b;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}
.identity{margin-top:4px;color:var(--muted);font-size:12px;word-break:break-word}
.cell-view{position:relative;flex:1;min-height:330px;background:#000}
.cell-view iframe{position:absolute;inset:0;width:100%;height:100%;border:0;display:block;background:#000}
.overlay{position:absolute;inset:0;background:rgba(4,9,18,.93);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;color:var(--muted);font-size:14px;text-align:center;padding:16px}
.overlay strong{color:var(--text);font-size:16px}
.toolbar{display:flex;gap:6px;padding:8px 10px;border-top:1px solid var(--border);flex-wrap:wrap}
.settings{display:none;padding:10px 12px;border-top:1px solid var(--border);background:var(--panel2)}
.settings.open{display:block}
.settings label{display:block;font-size:12px;color:var(--muted);margin:8px 0 3px}
.settings input,.settings select{width:100%;padding:7px 9px;border-radius:7px;border:1px solid var(--border);background:var(--bg);color:var(--text);font-size:13px}
.settings .row{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.settings .actions{display:flex;gap:8px;margin-top:12px}
.settings .msg{margin-top:8px;font-size:12px;color:var(--muted)}
.settings .msg.err{color:var(--danger)}
.banner{display:none;margin:10px 12px 0;padding:10px 12px;border:1px solid #5b2323;background:#2a1212;color:#fca5a5;border-radius:8px;font-size:13px}
.banner.show{display:block}
.login-overlay{position:fixed;inset:0;z-index:100;background:rgba(4,9,18,.97);display:flex;align-items:center;justify-content:center;padding:16px}
.login-overlay.hidden{display:none}
.login-card{width:100%;max-width:360px;background:var(--panel);border:1px solid var(--border);border-radius:12px;padding:26px 24px}
.login-card h2{margin:0 0 4px;font-size:20px}
.login-card h2 span{color:var(--accent)}
.login-card p{margin:0 0 16px;color:var(--muted);font-size:13px}
.login-card label{display:block;font-size:12px;color:var(--muted);margin:0 0 4px}
.login-card input{width:100%;padding:10px 12px;border-radius:7px;border:1px solid var(--border);background:var(--bg);color:var(--text);font-size:15px}
.login-card button{width:100%;margin-top:14px;padding:10px;font-size:15px}
.login-card .err{margin-top:10px;font-size:13px;color:var(--danger);min-height:18px}
</style>
</head>
<body>
<header class="topbar">
<h1>Browser <span>Farm</span></h1>
<span class="sub">8 browser terisolasi &middot; tiap browser identitas berbeda</span>
<div class="spacer"></div>
<button id="refreshBtn" type="button">Refresh</button>
<button id="startAllBtn" type="button" class="primary">Start 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).">Sinkron: OFF</button>
</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 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>
<div class="login-overlay hidden" id="loginOverlay">
<form class="login-card" id="loginForm">
<h2>Browser <span>Farm</span></h2>
<p>Masukkan password farm untuk membuka grid.</p>
<label for="loginPass">Password</label>
<input id="loginPass" type="password" autocomplete="current-password" placeholder="Password farm">
<button type="submit" class="primary">Masuk</button>
<div class="err" id="loginErr"></div>
</form>
</div>
<script>
(function () {
'use strict';
var grid = document.getElementById('grid');
var banner = document.getElementById('banner');
var loginOverlay = document.getElementById('loginOverlay');
var loginForm = document.getElementById('loginForm');
var loginPass = document.getElementById('loginPass');
var loginErr = document.getElementById('loginErr');
var cells = {}; // id -> { el, iframe, overlay, badge, identity, settingsForm, prevStatus, iframeLoaded, tokenLoaded, masterBadge, inputEl, inputPoll }
var presets = {}; // uaKey -> { label, ua }
var busy = {};
var gridStarted = false;
var pollTimer = null;
// ---- Sync control: one master drives all browsers ----
// Toggle state lives in localStorage only (per browser, not shared
// across devices). Default OFF.
var SYNC_KEY = 'farm_sync';
var syncOn = false;
try { syncOn = window.localStorage.getItem(SYNC_KEY) === 'on'; } catch (e) { syncOn = false; }
var masterId = null; // id of the cell the user last interacted with
var lastMoveMirror = 0;
var MOVE_MIRROR_MIN_MS = 16; // throttle mousemove mirroring (~60fps)
function showBanner(msg) {
banner.textContent = msg;
banner.classList.add('show');
}
function hideBanner() {
banner.classList.remove('show');
}
function showLogin(msg) {
if (msg) loginErr.textContent = msg;
loginOverlay.classList.remove('hidden');
setTimeout(function () { loginPass.focus(); }, 50);
}
function hideLogin() {
loginOverlay.classList.add('hidden');
loginErr.textContent = '';
loginPass.value = '';
}
// One farm login, then the grid starts. Called on page load and after
// every successful login (e.g. after the session expired mid-use).
function startGrid() {
if (!gridStarted) {
gridStarted = true;
loadPresets().then(function () { return refresh(); });
pollTimer = setInterval(refresh, 10000);
} else {
refresh();
}
}
function checkAuth() {
fetch('/api/me')
.then(function (r) { return r.json(); })
.then(function (j) {
if (j && j.authenticated) {
hideLogin();
startGrid();
} else {
showLogin();
}
})
.catch(function () { showLogin('Manager tidak bisa dihubungi.'); });
}
loginForm.addEventListener('submit', function (ev) {
ev.preventDefault();
var pw = loginPass.value;
if (!pw) return;
loginErr.textContent = '';
fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: pw }),
})
.then(function (r) {
if (!r.ok) throw new Error('salah');
return r.json();
})
.then(function (j) {
if (!j.ok) throw new Error('salah');
hideLogin();
startGrid();
})
.catch(function () {
loginErr.textContent = 'Password salah, coba lagi.';
loginPass.select();
});
});
function iframeUrl(b) {
// Same-origin path through the nginx /bN/ proxy (see install.sh):
// the grid must script into the Neko iframes for Sync, which needs
// same-origin. A relative path always matches the grid's origin
// (IP or domain). The token mechanism is unchanged.
var base = '/' + b.id + '/';
// The manager hands us a fresh Neko session token per browser; the
// Neko client auto-connects with ?token=... and never shows its
// login form. Without a token we fall back to the plain URL (that
// cell will show Neko's login form instead of a broken cell).
if (b.token) return base + '?token=' + encodeURIComponent(b.token);
return base;
}
function identityLine(b) {
var p = b.proxy || { type: 'direct' };
var proxyText = 'Direct';
if (p.type && p.type !== 'direct') {
proxyText = (p.type === 'socks5' ? 'SOCKS5 ' : 'HTTP ') + (p.host || '') + ':' + (p.port || '');
}
return (b.uaLabel || b.uaKey || '-') + ' · ' + proxyText;
}
function el(tag, cls, text) {
var n = document.createElement(tag);
if (cls) n.className = cls;
if (text !== undefined && text !== null) n.textContent = text;
return n;
}
function buildCell(b) {
var cell = el('section', 'cell');
cell.id = 'cell-' + b.id;
var head = el('div', 'cell-head');
var title = el('div', 'cell-title');
title.appendChild(el('strong', null, b.name));
var badge = el('span', 'badge stopped', 'Stopped');
title.appendChild(badge);
var masterBadge = el('span', 'badge master', 'Master');
masterBadge.style.display = 'none';
title.appendChild(masterBadge);
head.appendChild(title);
var identity = el('div', 'identity', identityLine(b));
head.appendChild(identity);
cell.appendChild(head);
var view = el('div', 'cell-view');
var frame = document.createElement('iframe');
frame.setAttribute('title', b.name);
frame.setAttribute('allow', 'autoplay; clipboard-read; clipboard-write; fullscreen');
frame.addEventListener('load', function () { pollForInput(b.id); });
view.appendChild(frame);
var overlay = el('div', 'overlay');
overlay.appendChild(el('strong', null, 'Browser berhenti'));
overlay.appendChild(el('span', null, 'Klik Start untuk menyalakan browser ini.'));
var ovStart = el('button', 'primary', 'Start');
ovStart.type = 'button';
ovStart.addEventListener('click', function () { doAction(b.id, 'start'); });
overlay.appendChild(ovStart);
view.appendChild(overlay);
cell.appendChild(view);
var toolbar = el('div', 'toolbar');
var acts = [
['start', 'Start', ''],
['stop', 'Stop', ''],
['restart', 'Restart', ''],
['wipe', 'Wipe', 'danger'],
['fullscreen', 'Fullscreen', ''],
['settings', 'Settings', ''],
];
acts.forEach(function (a) {
var btn = el('button', a[2], a[1]);
btn.type = 'button';
btn.dataset.act = a[0];
btn.addEventListener('click', function () { onToolbar(b.id, a[0]); });
toolbar.appendChild(btn);
});
cell.appendChild(toolbar);
var form = document.createElement('form');
form.className = 'settings';
form.addEventListener('submit', function (ev) {
ev.preventDefault();
saveSettings(b.id);
});
form.innerHTML =
'<label>User-Agent</label>' +
'<select name="ua"></select>' +
'<label>Proxy</label>' +
'<select name="proxyType">' +
'<option value="direct">Direct (tanpa proxy)</option>' +
'<option value="http">HTTP</option>' +
'<option value="socks5">SOCKS5</option>' +
'</select>' +
'<div class="row">' +
'<div><label>Host proxy</label><input name="host" type="text" placeholder="1.2.3.4" autocomplete="off"></div>' +
'<div><label>Port proxy</label><input name="port" type="number" min="1" max="65535" placeholder="8080"></div>' +
'</div>' +
'<div class="row">' +
'<div><label>Username (opsional)</label><input name="user" type="text" autocomplete="off"></div>' +
'<div><label>Password (opsional)</label><input name="pass" type="password" autocomplete="off"></div>' +
'</div>' +
'<div class="actions">' +
'<button type="submit" class="primary">Simpan &amp; Restart</button>' +
'<button type="button" class="cancelBtn">Batal</button>' +
'</div>' +
'<div class="msg"></div>';
form.querySelector('.cancelBtn').addEventListener('click', function () {
form.classList.remove('open');
});
cell.appendChild(form);
grid.appendChild(cell);
cells[b.id] = {
el: cell, iframe: frame, overlay: overlay, badge: badge,
identity: identity, form: form, prevStatus: null, iframeLoaded: false,
tokenLoaded: false, masterBadge: masterBadge, inputEl: null, inputPoll: null,
};
}
// ---- Sync control: find + watch the Neko input element ----
// The Neko Overlay (client/core/src/overlay.ts) is a wrap div holding
// a <canvas> (cursor layer) and a transparent <textarea> (the input
// layer). Every mouse/wheel/keyboard listener lives on that textarea.
// We find it by structure — a textarea whose parent also holds a
// canvas — not by class name: the Overlay sets no class names.
function findNekoInput(doc) {
try {
if (!doc) return null;
var tas = doc.querySelectorAll('textarea');
for (var i = 0; i < tas.length; i++) {
var p = tas[i].parentElement;
if (p && p.querySelector('canvas')) return tas[i];
}
return null;
} catch (e) {
return null; // cross-origin or not ready yet
}
}
// Poll for the Neko input element after an iframe (re)loads. The Neko
// client renders its overlay asynchronously, so we wait up to ~10s.
// A cell whose input never appears is simply left unmirrored.
function pollForInput(id) {
var c = cells[id];
if (!c) return;
if (c.inputPoll) { clearInterval(c.inputPoll); c.inputPoll = null; }
c.inputEl = null;
var tries = 0;
c.inputPoll = setInterval(function () {
tries++;
var input = null;
try {
if (c.iframe && c.iframe.contentDocument) input = findNekoInput(c.iframe.contentDocument);
} catch (e) { input = null; }
if (input) {
clearInterval(c.inputPoll); c.inputPoll = null;
attachSyncListeners(id, input);
return;
}
if (tries >= 20) { clearInterval(c.inputPoll); c.inputPoll = null; }
}, 500);
}
// Attach the Sync capture listeners to one cell's Neko input element.
// Listeners go on the textarea itself (same target as the Overlay's
// own listeners): the Overlay calls stopPropagation(), which blocks
// ancestors but never other listeners on the same element.
function attachSyncListeners(id, input) {
var c = cells[id];
if (!c || c.inputEl === input) return;
c.inputEl = input;
var win = input.ownerDocument.defaultView;
function handler(e) { onCellInput(id, e); }
// Mouse + wheel + keyboard: exactly the events the Overlay listens
// to. (The Overlay uses mouse events, not pointer events, so we
// mirror mouse events — a PointerEvent would be ignored by it.)
['mousemove', 'mousedown', 'wheel', 'keydown', 'keyup'].forEach(function (type) {
input.addEventListener(type, handler, false);
});
// mouseup can happen outside the textarea (the Overlay itself
// listens on window, capture). Catch every mouseup via the iframe
// window so a press that started on the video is always released.
// (Only window, not the textarea too — otherwise one release would
// mirror twice.)
if (win) win.addEventListener('mouseup', handler, true);
}
function setMaster(id) {
if (masterId === id) return;
masterId = id;
Object.keys(cells).forEach(function (k) {
var c = cells[k];
if (c.masterBadge) c.masterBadge.style.display = (k === id) ? '' : 'none';
if (c.el) c.el.classList.toggle('is-master', k === id);
});
}
function clearMaster() {
masterId = null;
Object.keys(cells).forEach(function (k) {
var c = cells[k];
if (c.masterBadge) c.masterBadge.style.display = 'none';
if (c.el) c.el.classList.remove('is-master');
});
}
// One real user interaction on a cell makes it the master and mirrors
// that input to every other cell.
function onCellInput(id, e) {
if (!syncOn) return;
// Only real user input drives Sync. Synthetic events dispatched into
// followers have isTrusted=false — ignoring them prevents feedback
// loops and stops a follower from becoming the master. (Neither the
// Neko Overlay nor its Guacamole keyboard checks isTrusted, so the
// synthetic events still reach the remote desktop.)
if (!e.isTrusted) return;
setMaster(id);
mirrorInput(id, e);
}
function mirrorInput(masterId, e) {
var master = cells[masterId];
if (!master || !master.inputEl) return;
var type = e.type;
if (type !== 'mousemove' && type !== 'mousedown' && type !== 'mouseup' &&
type !== 'wheel' && type !== 'keydown' && type !== 'keyup') return;
// Throttle mousemove mirroring (~60fps) so a fast drag does not
// flood the followers with synthetic events. Clicks, wheel and keys
// are never throttled.
if (type === 'mousemove') {
var now = Date.now();
if (now - lastMoveMirror < MOVE_MIRROR_MIN_MS) return;
lastMoveMirror = now;
}
// Relative position inside the master's input area. The Overlay maps
// clientX/clientY against its canvas rect, which equals the textarea
// rect (both fill the same box), so fractions of the textarea map
// exactly onto each follower's remote screen — even if cells render
// at slightly different sizes.
var r;
try { r = master.inputEl.getBoundingClientRect(); } catch (err) { return; }
var fx = r.width ? (e.clientX - r.left) / r.width : 0;
var fy = r.height ? (e.clientY - r.top) / r.height : 0;
fx = Math.max(0, Math.min(1, fx));
fy = Math.max(0, Math.min(1, fy));
Object.keys(cells).forEach(function (fid) {
if (fid === masterId) return;
var f = cells[fid];
if (!f || !f.inputEl) return;
if (!f._browser || f._browser.status !== 'running') return;
try {
var fwin = f.inputEl.ownerDocument.defaultView;
if (!fwin) return;
var fr = f.inputEl.getBoundingClientRect();
var cx = fr.left + fx * fr.width;
var cy = fr.top + fy * fr.height;
var mods = {
ctrlKey: !!e.ctrlKey, shiftKey: !!e.shiftKey,
altKey: !!e.altKey, metaKey: !!e.metaKey,
};
var ev = null;
if (type === 'wheel') {
ev = new fwin.WheelEvent('wheel', {
bubbles: true, cancelable: true,
clientX: cx, clientY: cy,
deltaX: e.deltaX || 0, deltaY: e.deltaY || 0, deltaMode: e.deltaMode || 0,
ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey,
altKey: mods.altKey, metaKey: mods.metaKey,
});
} else if (type === 'keydown' || type === 'keyup') {
ev = new fwin.KeyboardEvent(type, {
bubbles: true, cancelable: true,
key: e.key, code: e.code, location: e.location || 0,
ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey,
altKey: mods.altKey, metaKey: mods.metaKey,
repeat: !!e.repeat,
});
// The Neko Guacamole keyboard resolves keys from keyCode/which
// (and from key). The KeyboardEvent constructor cannot set
// keyCode/which, so shadow them so the follower maps the
// same key.
try {
Object.defineProperty(ev, 'keyCode', { value: e.keyCode || 0 });
Object.defineProperty(ev, 'which', { value: e.which || e.keyCode || 0 });
} catch (err) { /* ignore */ }
} else {
// mousemove / mousedown / mouseup
ev = new fwin.MouseEvent(type, {
bubbles: true, cancelable: true,
clientX: cx, clientY: cy,
button: (typeof e.button === 'number') ? e.button : 0,
buttons: (typeof e.buttons === 'number') ? e.buttons : 0,
ctrlKey: mods.ctrlKey, shiftKey: mods.shiftKey,
altKey: mods.altKey, metaKey: mods.metaKey,
});
}
if (ev) f.inputEl.dispatchEvent(ev);
} catch (err) {
// A follower that is not ready must never break the grid.
}
});
}
// Sync toggle: on/off, remembered in localStorage (per browser).
var syncBtn = document.getElementById('syncBtn');
function renderSyncBtn() {
syncBtn.textContent = syncOn ? 'Sinkron: ON' : 'Sinkron: OFF';
syncBtn.classList.toggle('sync-on', syncOn);
}
function setSync(on) {
syncOn = !!on;
try { window.localStorage.setItem(SYNC_KEY, syncOn ? 'on' : 'off'); } catch (e) {}
renderSyncBtn();
if (!syncOn) clearMaster();
}
syncBtn.addEventListener('click', function () { setSync(!syncOn); });
renderSyncBtn();
function fillUaOptions() {
Object.keys(cells).forEach(function (id) {
var sel = cells[id].form.querySelector('select[name="ua"]');
sel.innerHTML = '';
Object.keys(presets).forEach(function (key) {
var opt = document.createElement('option');
opt.value = key;
opt.textContent = presets[key].label || key;
sel.appendChild(opt);
});
});
}
function openSettings(id, b) {
var c = cells[id];
var sel = c.form.querySelector('select[name="ua"]');
sel.value = b.uaKey || '';
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 || '';
c.form.querySelector('input[name="port"]').value = p.port || '';
c.form.querySelector('input[name="user"]').value = p.user || '';
c.form.querySelector('input[name="pass"]').value = p.pass || '';
c.form.querySelector('.msg').textContent = '';
c.form.classList.add('open');
}
function setMsg(id, text, isErr) {
var m = cells[id].form.querySelector('.msg');
m.textContent = text;
m.classList.toggle('err', !!isErr);
}
function onToolbar(id, act) {
if (act === 'fullscreen') {
var c = cells[id];
var willExpand = !c.el.classList.contains('expanded');
Object.keys(cells).forEach(function (k) { cells[k].el.classList.remove('expanded'); });
if (willExpand) c.el.classList.add('expanded');
return;
}
if (act === 'settings') {
var b = cells[id]._browser;
if (b) openSettings(id, b);
return;
}
if (act === 'wipe') {
var name = (cells[id]._browser && cells[id]._browser.name) || id;
if (!window.confirm('Hapus semua data ' + name + ' (cookies, history, login)?\nHanya browser ini yang dihapus, browser lain tidak disentuh.')) return;
}
doAction(id, act);
}
function doAction(id, action) {
if (busy[id]) return;
busy[id] = true;
fetch('/api/browsers/' + encodeURIComponent(id) + '/' + encodeURIComponent(action), { method: 'POST' })
.then(function (r) { return r.json(); })
.then(function (j) {
busy[id] = false;
if (!j.ok) throw new Error(j.error || 'gagal');
return refresh();
})
.catch(function (e) {
busy[id] = false;
showBanner('Gagal ' + action + ' ' + id + ': ' + e.message);
});
}
function saveSettings(id) {
var c = cells[id];
var f = c.form;
var proxyType = f.querySelector('select[name="proxyType"]').value;
var proxy = { type: proxyType };
if (proxyType !== 'direct') {
proxy.host = f.querySelector('input[name="host"]').value.trim();
proxy.port = Number(f.querySelector('input[name="port"]').value);
proxy.user = f.querySelector('input[name="user"]').value;
proxy.pass = f.querySelector('input[name="pass"]').value;
}
var body = {
ua: f.querySelector('select[name="ua"]').value,
proxy: proxy,
};
setMsg(id, 'Menyimpan & restart browser...', false);
fetch('/api/browsers/' + encodeURIComponent(id) + '/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
.then(function (r) { return r.json(); })
.then(function (j) {
if (!j.ok) throw new Error(j.error || 'gagal menyimpan');
setMsg(id, 'Tersimpan. Identitas baru: ' + (j.uaLabel || '') + ' · ' + ((j.proxy && j.proxy.type) || ''), false);
return refresh();
})
.catch(function (e) {
setMsg(id, 'Gagal: ' + e.message, true);
});
}
function updateCell(b) {
var c = cells[b.id];
if (!c) return;
c._browser = b;
var running = b.status === 'running';
c.badge.textContent = running ? 'Running' : 'Stopped';
c.badge.className = 'badge ' + (running ? 'running' : 'stopped');
c.identity.textContent = identityLine(b);
c.overlay.style.display = running ? 'none' : 'flex';
if (running) {
if (!c.iframeLoaded || c.prevStatus === 'stopped') {
// First load, or the browser came back after a stop/restart:
// (re)set the src, with the fresh token when we have one.
c.iframe.src = iframeUrl(b);
c.iframeLoaded = true;
c.tokenLoaded = !!b.token;
c.inputEl = null; // new page — the old textarea is gone; the iframe load handler re-polls for the new one
} else if (!c.tokenLoaded && b.token) {
// The token arrived after the iframe was first loaded (Neko was
// still starting). Upgrade the src once so the cell auto-connects.
// Normal polls never touch src, so a token refresh never kicks
// the user out of a running browser.
c.iframe.src = iframeUrl(b);
c.tokenLoaded = true;
c.inputEl = null;
}
}
c.prevStatus = b.status;
}
function refresh() {
return fetch('/api/browsers')
.then(function (r) {
if (r.status === 401) {
// Session expired — ask for the farm password again.
showLogin('Sesi habis, login lagi.');
throw new Error('unauthorized');
}
return r.json();
})
.then(function (j) {
hideBanner();
var list = j.browsers || [];
list.forEach(function (b) {
if (!cells[b.id]) buildCell(b);
updateCell(b);
});
})
.catch(function (e) {
if (e.message !== 'unauthorized') {
showBanner('Manager tidak bisa dihubungi: ' + e.message);
}
});
}
function loadPresets() {
return fetch('/api/ua-presets')
.then(function (r) { return r.json(); })
.then(function (j) {
presets = j.presets || {};
fillUaOptions();
})
.catch(function () { /* presets stay empty; settings still works with server validation */ });
}
document.getElementById('refreshBtn').addEventListener('click', function () { refresh(); });
document.getElementById('startAllBtn').addEventListener('click', function () {
fetch('/api/browsers/start-all', { method: 'POST' })
.then(function () { return refresh(); })
.catch(function (e) { showBanner('Gagal start semua: ' + e.message); });
});
document.getElementById('stopAllBtn').addEventListener('click', function () {
fetch('/api/browsers/stop-all', { method: 'POST' })
.then(function () { return refresh(); })
.catch(function (e) { showBanner('Gagal stop semua: ' + e.message); });
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
Object.keys(cells).forEach(function (k) { cells[k].el.classList.remove('expanded'); });
}
});
checkAuth();
})();
</script>
</body>
</html>