Files
TailScan/templates/index.html
T

898 lines
36 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TailScan</title>
<style>
/* ── Default theme: Dark Slate ─────────────────────────────── */
:root {
--bg: #0f1117;
--surface: #1a1d27;
--surface2: #222636;
--border: #2d3148;
--text: #e2e8f0;
--muted: #7c85a2;
--accent: #5b6ee8;
--accent-hover: #4a5cd6;
--green: #22c55e;
--red: #ef4444;
--yellow: #f59e0b;
--exit-badge: #7c3aed;
--guac-green: #22c55e;
}
/* ── Rose Pine theme ────────────────────────────────────────── */
body.theme-rosepine {
--bg: #191724;
--surface: #1f1d2e;
--surface2: #26233a;
--border: #403d52;
--text: #e0def4;
--muted: #6e6a86;
--accent: #c4a7e7;
--accent-hover: #ebbcba;
--green: #9ccfd8;
--red: #eb6f92;
--yellow: #f6c177;
--exit-badge: #c4a7e7;
--guac-green: #9ccfd8;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); height: 100vh; display: flex; flex-direction: column; }
/* Top bar */
.topbar {
display: flex; align-items: center; gap: 12px;
padding: 0 20px; height: 52px;
background: var(--surface); border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.topbar .logo { font-weight: 700; font-size: 16px; color: var(--accent); letter-spacing: 0.5px; cursor: pointer; user-select: none; transition: opacity 0.15s; }
.topbar .logo:hover { opacity: 0.75; }
.topbar .spacer { flex: 1; }
.topbar .exit-status {
display: flex; align-items: center; gap: 8px;
font-size: 13px; color: var(--muted);
}
.topbar .exit-status .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--red); }
.topbar .exit-status .dot.connected { background: var(--green); }
.topbar .exit-name { color: var(--text); font-weight: 500; }
.btn {
padding: 6px 14px; border-radius: 6px; border: none; cursor: pointer;
font-size: 13px; font-weight: 500; transition: background 0.15s;
}
.btn-primary { background: var(--accent); color: white; }
.btn-primary:hover { background: var(--accent-hover); }
.btn-ghost { background: transparent; color: var(--muted); border: 1px solid var(--border); }
.btn-ghost:hover { color: var(--text); border-color: var(--muted); }
.btn-danger { background: transparent; color: var(--red); border: 1px solid var(--border); }
.btn-danger:hover { background: rgba(239,68,68,0.1); }
/* Layout */
.layout { display: flex; flex: 1; overflow: hidden; }
/* Sidebar */
.sidebar {
width: 280px; flex-shrink: 0;
background: var(--surface); border-right: 1px solid var(--border);
display: flex; flex-direction: column; overflow: hidden;
}
.sidebar-header {
padding: 14px 16px 10px;
border-bottom: 1px solid var(--border);
display: flex; align-items: center; justify-content: space-between;
}
.sidebar-header h2 { font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; color: var(--muted); }
.sidebar-list { overflow-y: auto; flex: 1; padding: 8px; }
.peer-item {
display: flex; align-items: center; gap: 10px;
padding: 8px 10px; border-radius: 8px; cursor: pointer;
transition: background 0.12s; margin-bottom: 2px;
}
.peer-item:hover { background: var(--surface2); }
.peer-item.active-exit { background: rgba(91,110,232,0.15); border: 1px solid rgba(91,110,232,0.3); }
.peer-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; background: var(--red); }
.peer-dot.online { background: var(--green); }
.peer-info { flex: 1; min-width: 0; }
.peer-name { font-size: 13px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.peer-ip { font-size: 11px; color: var(--muted); font-family: monospace; }
.peer-badges { display: flex; gap: 4px; margin-top: 2px; flex-wrap: wrap; }
.badge {
font-size: 10px; padding: 1px 6px; border-radius: 10px; font-weight: 600;
}
.badge-exit { background: rgba(124,58,237,0.2); color: #a78bfa; border: 1px solid rgba(124,58,237,0.3); }
.badge-self { background: rgba(34,197,94,0.15); color: #4ade80; border: 1px solid rgba(34,197,94,0.3); }
.badge-os { background: var(--surface2); color: var(--muted); border: 1px solid var(--border); }
.section-label {
font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.7px;
color: var(--muted); padding: 8px 10px 4px; margin-top: 4px;
}
/* Main content */
.main { flex: 1; overflow-y: auto; padding: 24px; display: flex; flex-direction: column; gap: 20px; }
/* Cards */
.card {
background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
padding: 20px;
}
.card-title { font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.7px; color: var(--muted); margin-bottom: 16px; }
/* Geo info */
.geo-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 12px; }
.geo-item label { font-size: 11px; color: var(--muted); display: block; margin-bottom: 3px; }
.geo-item .value { font-size: 14px; font-weight: 500; }
.geo-item .value.ip { font-family: monospace; font-size: 15px; color: var(--accent); }
/* Device table */
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th {
text-align: left; padding: 8px 12px;
font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.7px;
color: var(--muted); border-bottom: 1px solid var(--border);
}
td { padding: 8px 12px; border-bottom: 1px solid rgba(45,49,72,0.5); vertical-align: middle; }
tr:last-child td { border-bottom: none; }
tr.device-row:hover td { background: var(--surface2); }
.status-up { color: var(--green); font-weight: 600; }
.ip-cell { font-family: monospace; color: var(--accent); white-space: nowrap; }
/* Hide empty rows (default on) — only after port scan has completed */
tr.no-ports:not(.scanning) { display: none; }
body.show-empty tr.no-ports { display: table-row; }
tr.cached-row td { color: #c4a7e7; }
tr.cached-row .port-chip { border-color: #c4a7e7; color: #c4a7e7; }
tr.cached-row a.port-chip { color: #c4a7e7; }
/* Port chips */
.port-chips { display: flex; flex-wrap: wrap; gap: 4px; }
.port-chip {
position: relative;
font-size: 11px; font-family: monospace; font-weight: 600;
padding: 2px 7px; border-radius: 4px;
background: rgba(91,110,232,0.15); color: #a5b4fc;
border: 1px solid rgba(91,110,232,0.25);
cursor: pointer; white-space: nowrap; user-select: none;
text-decoration: none; display: inline-block;
}
.port-chip:hover { background: rgba(91,110,232,0.35); border-color: rgba(91,110,232,0.5); color: #c7d2fe; }
.port-chip.no-browse { cursor: default; }
.port-chip.no-browse:hover { background: rgba(91,110,232,0.15); border-color: rgba(91,110,232,0.25); color: #a5b4fc; }
/* Guacamole-connectable ports (green) */
.port-chip.guac-chip {
background: rgba(34,197,94,0.12); color: #4ade80;
border: 1px solid rgba(34,197,94,0.3);
}
.port-chip.guac-chip:hover { background: rgba(34,197,94,0.28); border-color: rgba(34,197,94,0.55); color: #86efac; }
body.theme-rosepine .port-chip.guac-chip {
background: rgba(156,207,216,0.12); color: #9ccfd8;
border: 1px solid rgba(156,207,216,0.3);
}
body.theme-rosepine .port-chip.guac-chip:hover { background: rgba(156,207,216,0.28); border-color: rgba(156,207,216,0.55); color: #c8e8ec; }
/* Copyparty / file transfer ports (orange) */
.port-chip.copyparty-chip {
background: rgba(249,115,22,0.13); color: #fb923c;
border: 1px solid rgba(249,115,22,0.3);
}
.port-chip.copyparty-chip:hover { background: rgba(249,115,22,0.28); border-color: rgba(249,115,22,0.55); color: #fdba74; }
body.theme-rosepine .port-chip.copyparty-chip {
background: rgba(246,193,119,0.13); color: #f6c177;
border: 1px solid rgba(246,193,119,0.3);
}
body.theme-rosepine .port-chip.copyparty-chip:hover { background: rgba(246,193,119,0.28); border-color: rgba(246,193,119,0.55); color: #f9d89a; }
/* Custom tooltip */
.port-chip .chip-tip {
display: none;
position: absolute; bottom: calc(100% + 6px); left: 50%; transform: translateX(-50%);
background: #2a2d3e; color: #e2e8f0; font-size: 11px; font-family: -apple-system, sans-serif;
font-weight: 500; white-space: nowrap; padding: 5px 9px; border-radius: 6px;
border: 1px solid #3d4166; pointer-events: none; z-index: 100;
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
}
.port-chip .chip-tip::after {
content: ''; position: absolute; top: 100%; left: 50%; transform: translateX(-50%);
border: 5px solid transparent; border-top-color: #3d4166;
}
.port-chip:hover .chip-tip { display: block; }
.ports-scanning {
font-size: 11px; color: var(--muted);
display: flex; align-items: center; gap: 6px;
}
.spinner-sm {
display: inline-block; width: 10px; height: 10px;
border: 1.5px solid var(--border); border-top-color: var(--accent);
border-radius: 50%; animation: spin 0.7s linear infinite; flex-shrink: 0;
}
/* Empty / loading states */
.empty-state {
text-align: center; padding: 48px 24px; color: var(--muted);
}
.empty-state .icon { font-size: 48px; margin-bottom: 12px; }
.empty-state p { font-size: 14px; }
.spinner {
display: inline-block; width: 20px; height: 20px;
border: 2px solid var(--border); border-top-color: var(--accent);
border-radius: 50%; animation: spin 0.7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* Refresh bar */
.refresh-bar {
display: flex; align-items: center; gap: 10px;
font-size: 12px; color: var(--muted);
}
.refresh-bar .countdown { font-weight: 600; color: var(--text); min-width: 20px; }
/* Disconnect prompt */
#no-exit-msg {
display: flex; flex-direction: column; align-items: center; justify-content: center;
flex: 1; text-align: center; gap: 12px; color: var(--muted);
}
#no-exit-msg h2 { font-size: 18px; color: var(--text); }
#no-exit-msg p { font-size: 14px; max-width: 320px; }
</style>
</head>
<body>
<!-- Top bar -->
<div class="topbar">
<span class="logo" onclick="cycleTheme()" title="Click to change theme">🔍 TailScan</span>
<div class="exit-status">
<div class="dot" id="exit-dot"></div>
<span id="exit-label">Not connected to exit node</span>
</div>
<div class="spacer"></div>
<button class="btn btn-danger" id="disconnect-btn" style="display:none" onclick="disconnectExit()">Disconnect</button>
<button class="btn btn-ghost" id="toggle-empty-btn" onclick="toggleEmpty()" style="display:none">Show all</button>
<a href="/logout"><button class="btn btn-ghost">Logout</button></a>
</div>
<!-- Layout -->
<div class="layout">
<!-- Sidebar -->
<div class="sidebar">
<div class="sidebar-header">
<h2>Tailnet Devices</h2>
<button class="btn btn-ghost" onclick="loadPeers()" style="padding:4px 8px; font-size:11px;">↺</button>
</div>
<div class="sidebar-list" id="peer-list">
<div style="padding:20px; text-align:center; color:var(--muted);"><div class="spinner"></div></div>
</div>
<div id="version-badge" style="padding:10px 14px; font-size:10px; color:var(--muted); border-top:1px solid var(--border); text-align:center;">
TailScan <span id="version-str">...</span>
</div>
</div>
<!-- Main -->
<div class="main" id="main-content">
<div id="no-exit-msg">
<div style="font-size:56px;">🛰️</div>
<h2>Select an Exit Node</h2>
<p>Click an exit node on the left to connect and scan its LAN.</p>
</div>
</div>
</div>
<script>
let currentExitNode = null;
let refreshInterval = null;
let countdownInterval = null;
let countdown = 60;
let portRescanTimer = null;
// ── Peers ────────────────────────────────────────────────────────────────────
async function loadPeers() {
const list = document.getElementById('peer-list');
list.innerHTML = '<div style="padding:20px;text-align:center;color:var(--muted)"><div class="spinner"></div></div>';
try {
const r = await fetch('/api/peers');
const d = await r.json();
currentExitNode = d.current_exit_node;
updateTopbar(currentExitNode, d.peers);
renderPeers(d.peers, d.current_exit_node);
} catch(e) {
list.innerHTML = '<div style="padding:16px;color:var(--red);font-size:13px;">Failed to load peers</div>';
}
}
function renderPeers(peers, activeExit) {
const list = document.getElementById('peer-list');
const exitNodes = peers.filter(p => p.exit_node_option && !p.self);
const others = peers.filter(p => !p.exit_node_option || p.self);
let html = '';
if (exitNodes.length) {
html += '<div class="section-label">Exit Nodes</div>';
for (const p of exitNodes) {
const isActive = p.exit_node || p.ip === activeExit;
html += peerHTML(p, isActive, true);
}
}
if (others.length) {
html += '<div class="section-label">Devices</div>';
for (const p of others) {
html += peerHTML(p, false, false);
}
}
list.innerHTML = html || '<div style="padding:16px;color:var(--muted);font-size:13px;">No devices found</div>';
}
function peerHTML(p, isActive, isExitNode) {
const onclick = isExitNode && !p.self ? `onclick="connectExit('${p.ip}', '${p.hostname}')"` : '';
const cursor = isExitNode && !p.self ? '' : 'cursor:default;';
return `
<div class="peer-item ${isActive ? 'active-exit' : ''}" ${onclick} style="${cursor}">
<div class="peer-dot ${p.online ? 'online' : ''}"></div>
<div class="peer-info">
<div class="peer-name">${escHtml(p.hostname)}</div>
<div class="peer-ip">${p.ip}</div>
<div class="peer-badges">
${p.self ? '<span class="badge badge-self">this device</span>' : ''}
${isExitNode ? '<span class="badge badge-exit">exit node</span>' : ''}
${p.os ? `<span class="badge badge-os">${escHtml(p.os)}</span>` : ''}
</div>
</div>
</div>`;
}
// ── Exit node control ────────────────────────────────────────────────────────
async function connectExit(ip, hostname) {
showLoading(`Connecting to ${hostname}...`);
try {
await fetch('/api/exit-node/set', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ip})
});
currentExitNode = ip;
updateTopbar(ip, null, hostname);
await loadPeers();
startAutoRefresh();
await runScan();
} catch(e) {
showError('Failed to connect to exit node.');
}
}
async function disconnectExit() {
stopAutoRefresh();
await fetch('/api/exit-node/disconnect', {method: 'POST'});
currentExitNode = null;
updateTopbar(null);
await loadPeers();
document.getElementById('main-content').innerHTML = `
<div id="no-exit-msg">
<div style="font-size:56px;">🛰️</div>
<h2>Select an Exit Node</h2>
<p>Click an exit node on the left to connect and scan its LAN.</p>
</div>`;
}
// ── Scan ─────────────────────────────────────────────────────────────────────
let activeScanSource = null;
let knownDevices = {}; // ip -> device data
let portScanQueue = []; // IPs queued for auto port scan
let portScanRunning = false; // only one at a time
function isFirstScan() {
return Object.keys(knownDevices).length === 0;
}
function ensureScanUI() {
// Build scaffold once; on subsequent scans just update status
if (!document.getElementById('scan-wrap')) {
document.getElementById('main-content').innerHTML = `
<div id="scan-wrap">
<div class="refresh-bar" style="margin-bottom:12px;" id="scan-bar">
<div class="spinner"></div>
<span id="scan-status">Connecting...</span>
<span style="flex:1"></span>
<button class="btn btn-ghost" onclick="runScan()" style="padding:4px 10px;font-size:12px;">Restart</button>
</div>
<div id="geo-card"></div>
<div id="device-card" class="card" style="display:none">
<div class="card-title" id="device-card-title">LAN Devices</div>
<div class="table-wrap"><table>
<thead><tr>
<th>IP</th><th>Status</th><th>Open Ports</th>
</tr></thead>
<tbody id="device-tbody"></tbody>
</table></div>
</div>
</div>`;
} else {
// Just reset the status bar
const bar = document.getElementById('scan-bar');
if (bar) bar.innerHTML = `
<div class="spinner"></div>
<span id="scan-status">Refreshing...</span>
<span style="flex:1"></span>
<button class="btn btn-ghost" onclick="runScan()" style="padding:4px 10px;font-size:12px;">Restart</button>`;
}
}
function runScan() {
if (activeScanSource) { activeScanSource.close(); activeScanSource = null; }
if (portRescanTimer) { clearTimeout(portRescanTimer); portRescanTimer = null; }
stopAutoRefresh();
ensureScanUI();
let seenIPs = new Set(); // IPs found in this scan cycle
const src = new EventSource('/api/scan');
activeScanSource = src;
src.onmessage = (e) => {
const d = JSON.parse(e.data);
if (d.type === 'meta') {
if (!d.connected) {
document.getElementById('main-content').innerHTML = `
<div id="no-exit-msg"><div style="font-size:56px;">🛰️</div><h2>Not Connected</h2>
<p>Select an exit node from the sidebar.</p></div>`;
knownDevices = {};
src.close(); return;
}
const geo = d.geo || {};
document.getElementById('geo-card').innerHTML = `
<div class="card" style="margin-bottom:20px;">
<div class="card-title">WAN & Location</div>
<div class="geo-grid">
<div class="geo-item"><label>WAN IP</label><div class="value ip">${escHtml(geo.ip||'—')}</div></div>
<div class="geo-item"><label>City</label><div class="value">${escHtml(geo.city||'—')}</div></div>
<div class="geo-item"><label>Region</label><div class="value">${escHtml(geo.region||'—')}</div></div>
<div class="geo-item"><label>Country</label><div class="value">${escHtml(geo.country||'—')}</div></div>
<div class="geo-item"><label>ISP</label><div class="value">${escHtml(geo.isp||'—')}</div></div>
<div class="geo-item"><label>Timezone</label><div class="value">${escHtml(geo.timezone||'—')}</div></div>
</div>
</div>`;
const status = document.getElementById('scan-status');
if (status) status.textContent = `Scanning ${d.subnet}...`;
document.getElementById('device-card').style.display = '';
document.getElementById('device-card-title').textContent =
`LAN Devices — ${d.subnet} (scanning...)`;
}
else if (d.type === 'cached') {
// Cached device from a previous scan — show immediately with cached port data
const isNew = !knownDevices[d.ip];
knownDevices[d.ip] = d;
const key = d.ip.replace(/\./g, '-');
const tbody = document.getElementById('device-tbody');
if (isNew) {
const row = document.createElement('tr');
row.id = `row-${key}`;
row.className = 'device-row scanning cached-row';
row.innerHTML = deviceRowHTML(d);
const rows = tbody.querySelectorAll('tr[id^="row-"]');
let inserted = false;
for (const r of rows) {
const rip = r.id.replace('row-','').replace(/-/g,'.');
if (ipNum(d.ip) < ipNum(rip)) { tbody.insertBefore(row, r); inserted = true; break; }
}
if (!inserted) tbody.appendChild(row);
}
// If cached device has port data, render it now instead of spinning
if (d.open_ports) {
renderPortsFromCache(d.ip, d.open_ports);
} else {
portScanQueue.push(d.ip);
drainPortScanQueue();
}
const title = document.getElementById('device-card-title');
if (title) title.textContent = `LAN Devices — ${Object.keys(knownDevices).length} (cached)`;
}
else if (d.type === 'cache_done') {
const ago = d.scanned_at ? Math.round((Date.now()/1000 - d.scanned_at) / 60) : null;
const agoStr = ago !== null ? ` · cached ${ago}m ago` : '';
const bar = document.getElementById('scan-bar');
if (bar) bar.innerHTML = `
<span style="color:var(--muted);">📦 Showing cached results${agoStr} · live scan in progress...</span>`;
}
else if (d.type === 'device') {
seenIPs.add(d.ip);
const isNew = !knownDevices[d.ip];
// Clear cached marker on this row if present
const key = d.ip.replace(/\./g, '-');
const existingRow = document.getElementById(`row-${key}`);
if (existingRow) existingRow.classList.remove('cached-row');
knownDevices[d.ip] = d;
const tbody = document.getElementById('device-tbody');
if (isNew) {
const row = document.createElement('tr');
row.id = `row-${key}`;
row.className = 'device-row scanning';
row.innerHTML = deviceRowHTML(d);
const rows = tbody.querySelectorAll('tr[id^="row-"]');
let inserted = false;
for (const r of rows) {
const rip = r.id.replace('row-','').replace(/-/g,'.');
if (ipNum(d.ip) < ipNum(rip)) { tbody.insertBefore(row, r); inserted = true; break; }
}
if (!inserted) tbody.appendChild(row);
portScanQueue.push(d.ip);
drainPortScanQueue();
}
const title = document.getElementById('device-card-title');
if (title) title.textContent =
`LAN Devices — scanning... (${Object.keys(knownDevices).length} found)`;
}
else if (d.type === 'error') {
const status = document.getElementById('scan-status');
if (status) status.innerHTML = `<span style="color:var(--red)">⚠ ${escHtml(d.message)}</span>`;
src.close();
}
else if (d.type === 'done') {
src.close();
activeScanSource = null;
// Remove rows for IPs that disappeared since last scan
for (const ip of Object.keys(knownDevices)) {
if (!seenIPs.has(ip)) {
const key = ip.replace(/\./g, '-');
document.getElementById(`row-${key}`)?.remove();
delete knownDevices[ip];
}
}
const bar = document.getElementById('scan-bar');
if (bar) bar.innerHTML = `
<span style="color:var(--green);">✓ Scan complete</span>
<span style="color:var(--muted);margin-left:8px;">Next in <span id="countdown">60</span>s</span>
<span style="flex:1"></span>
<button class="btn btn-ghost" onclick="runScan()" style="padding:4px 10px;font-size:12px;">Scan now</button>`;
const title = document.getElementById('device-card-title');
if (title) title.textContent = `LAN Devices — ${d.count} found`;
resetCountdown();
schedulePortRescan();
}
};
src.onerror = () => {
src.close();
activeScanSource = null;
const status = document.getElementById('scan-status');
if (status) status.innerHTML = `<span style="color:var(--red)">Connection lost</span>`;
};
}
function deviceRowHTML(d) {
const key = d.ip.replace(/\./g, '-');
return `
<td class="ip-cell">${escHtml(d.ip)}</td>
<td class="status-up">●&nbsp;up</td>
<td id="ports-inline-${key}">
<div class="ports-scanning"><div class="spinner-sm"></div><span>queued</span></div>
</td>`;
}
function renderPortsFromCache(ip, open_ports) {
const key = ip.replace(/\./g, '-');
const cell = document.getElementById(`ports-inline-${key}`);
const row = document.getElementById(`row-${key}`);
if (!cell) return;
if (!row) return;
row.classList.remove('scanning');
if (!open_ports || open_ports.length === 0) {
cell.innerHTML = `<span style="color:var(--muted);font-size:11px;">—</span>`;
row.classList.add('no-ports');
document.getElementById('toggle-empty-btn').style.display = '';
} else {
row.classList.remove('no-ports');
cell.innerHTML = `<div class="port-chips">${buildChips(ip, open_ports)}</div>`;
}
}
const BROWSABLE_PORTS = new Set([
80, 443, 8080, 8081, 8082, 8090, 8443, 8006, 8007,
8123, 8888, 5000, 5001, 8001, 32400, 10000, 9090, 9091,
3000, 3001, 4000, 4200, 7000, 7001, 8096, 8097, 8920,
7878, 8989, 8686, 9696, 8787, 5055, 5299, 9117, 9443,
1880, 9000, 9393, 9999, 4040, 8200
]);
// Copyparty file server ports (orange + browsable)
const COPYPARTY_PORTS = new Set([3923, 30266]);
// File transfer protocol ports — shown in orange (not web-browsable)
const FILE_PROTO_PORTS = new Set([21, 873, 2049, 445, 548]);
const FILE_PROTO_LABELS = {
21: 'FTP', 873: 'rsync', 2049: 'NFS', 445: 'SMB', 548: 'AFP'
};
// Ports that open in Guacamole (green chips)
const GUAC_PORTS = new Set([22, 3389, 5900, 5901, 5902, 5903]);
const GUAC_PROTOCOLS = {22: 'ssh', 3389: 'rdp', 5900: 'vnc', 5901: 'vnc', 5902: 'vnc', 5903: 'vnc'};
// Guacamole is running on the same host as TailScan
const GUAC_URL = 'http://100.99.195.16:8085/guacamole';
function buildChips(ip, ports) {
return ports.map(p => {
const isGuac = GUAC_PORTS.has(p.port);
const isCopyparty = COPYPARTY_PORTS.has(p.port);
const isFileProt = FILE_PROTO_PORTS.has(p.port);
const isBrowsable = BROWSABLE_PORTS.has(p.port);
if (isGuac) {
const proto = GUAC_PROTOCOLS[p.port];
const tip = `${escHtml(p.service)} — open in Guacamole (${proto.toUpperCase()})`;
return `<span class="port-chip guac-chip" onclick="openGuac('${ip}', ${p.port}, '${proto}')" title="${tip}">${p.port}<span class="chip-tip">${tip}</span></span>`;
} else if (isCopyparty) {
const tUrl = encodeURIComponent(`http://${ip}:${p.port}/`);
const tip = `Copyparty file server — click to browse`;
return `<a class="port-chip copyparty-chip" href="/proxy?t=${tUrl}" target="_blank">${p.port}<span class="chip-tip">${tip}</span></a>`;
} else if (isFileProt) {
const label = FILE_PROTO_LABELS[p.port] || escHtml(p.service);
const tip = `${label} — file transfer protocol`;
return `<span class="port-chip copyparty-chip no-browse">${p.port}<span class="chip-tip">${tip}</span></span>`;
} else if (isBrowsable) {
const scheme = [443, 8443, 8006].includes(p.port) ? 'https' : 'http';
const tUrl = encodeURIComponent(`${scheme}://${ip}:${p.port}/`);
const tip = `${escHtml(p.service)} — click to browse`;
return `<a class="port-chip" href="/proxy?t=${tUrl}" target="_blank">${p.port}<span class="chip-tip">${tip}</span></a>`;
} else {
return `<span class="port-chip no-browse">${p.port}<span class="chip-tip">${escHtml(p.service)}</span></span>`;
}
}).join('');
}
function ipNum(ip) {
return ip.split('.').reduce((a, b) => a * 256 + parseInt(b), 0);
}
// ── Port scan ────────────────────────────────────────────────────────────────
function portScanManual(ip) {
portScanQueue = portScanQueue.filter(q => q !== ip);
portScan(ip);
}
async function drainPortScanQueue() {
if (portScanRunning || portScanQueue.length === 0) return;
portScanRunning = true;
while (portScanQueue.length > 0) {
const ip = portScanQueue.shift();
if (!document.getElementById(`row-${ip.replace(/\./g,'-')}`)) continue;
await portScan(ip);
}
portScanRunning = false;
}
async function portScan(ip) {
const key = ip.replace(/\./g, '-');
const cell = document.getElementById(`ports-inline-${key}`);
if (!cell) return;
// Don't re-show spinner on rows that already have cached port data (live scan refreshing)
const row = document.getElementById(`row-${key}`);
if (!row || row.classList.contains('cached-row')) {
// Keep existing display while refreshing silently
} else {
cell.innerHTML = `<div class="ports-scanning"><div class="spinner-sm"></div><span style="font-size:11px;">scanning...</span></div>`;
}
try {
const r = await fetch(`/api/port-scan?ip=${encodeURIComponent(ip)}`);
const d = await r.json();
if (row) row.classList.remove('scanning', 'cached-row');
if (d.error) {
cell.innerHTML = `<span style="color:var(--red);font-size:11px;">⚠ ${escHtml(d.error)}</span>`;
} else {
const ports = d.open_ports || [];
if (ports.length === 0) {
cell.innerHTML = `<span style="color:var(--muted);font-size:11px;">—</span>`;
if (row) row.classList.add('no-ports');
document.getElementById('toggle-empty-btn').style.display = '';
} else {
if (row) row.classList.remove('no-ports');
cell.innerHTML = `<div class="port-chips">${buildChips(ip, ports)}</div>`;
}
// Push port results to server cache
fetch('/api/cache/ports', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({[ip]: {open_ports: ports, os_guess: d.os_guess}})
}).catch(() => {});
}
} catch(e) {
cell.innerHTML = `<span style="color:var(--red);font-size:11px;">failed</span>`;
if (row) row.classList.remove('scanning');
}
}
// ── Silent port rescan ───────────────────────────────────────────────────────
function schedulePortRescan() {
if (portRescanTimer) clearTimeout(portRescanTimer);
portRescanTimer = setTimeout(async () => {
portRescanTimer = null;
const ips = Object.keys(knownDevices);
if (!ips.length) return;
// Queue all known IPs for a silent rescan (don't show spinner — just update chips in place)
for (const ip of ips) {
portScanQueue.push(ip);
}
await drainPortScanQueue();
// Schedule next rescan
schedulePortRescan();
}, 300_000);
}
// ── Toggle empty rows ────────────────────────────────────────────────────────
function toggleEmpty() {
const showing = document.body.classList.toggle('show-empty');
document.getElementById('toggle-empty-btn').textContent = showing ? 'Hide empty' : 'Show all';
}
// ── Auto-refresh ─────────────────────────────────────────────────────────────
function startAutoRefresh() {
stopAutoRefresh();
countdown = 60;
countdownInterval = setInterval(() => {
countdown--;
const el = document.getElementById('countdown');
if (el) el.textContent = countdown;
if (countdown <= 0) runScan();
}, 1000);
}
function stopAutoRefresh() {
if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
}
function resetCountdown() {
countdown = 60;
const el = document.getElementById('countdown');
if (el) el.textContent = 60;
startAutoRefresh();
}
// ── Top bar ──────────────────────────────────────────────────────────────────
function updateTopbar(exitIp, peers, hostname) {
const dot = document.getElementById('exit-dot');
const label = document.getElementById('exit-label');
const btn = document.getElementById('disconnect-btn');
if (exitIp) {
dot.classList.add('connected');
// Try to find hostname from peers
let name = hostname;
if (!name && peers) {
const match = peers.find(p => p.ip === exitIp);
if (match) name = match.hostname;
}
label.textContent = `Exit: ${name || exitIp}`;
btn.style.display = '';
} else {
dot.classList.remove('connected');
label.textContent = 'Not connected to exit node';
btn.style.display = 'none';
}
}
// ── Helpers ──────────────────────────────────────────────────────────────────
function escHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function showLoading(msg) {
document.getElementById('main-content').innerHTML = `
<div style="text-align:center;padding:60px;color:var(--muted)">
<div class="spinner" style="width:32px;height:32px;margin:0 auto 16px"></div>
<p>${escHtml(msg)}</p>
</div>`;
}
function showError(msg) {
document.getElementById('main-content').innerHTML = `
<div style="text-align:center;padding:60px;color:var(--red)">
<div style="font-size:40px;margin-bottom:12px;">⚠️</div>
<p>${escHtml(msg)}</p>
</div>`;
}
// ── Guacamole ─────────────────────────────────────────────────────────────────
async function openGuac(ip, port, proto) {
// Show loading cursor
document.body.style.cursor = 'wait';
try {
const r = await fetch(`/api/guac-connect?ip=${encodeURIComponent(ip)}&port=${port}&proto=${proto}`);
if (!r.ok) {
const err = await r.json().catch(() => ({detail: r.statusText}));
alert(`Guacamole error: ${err.detail || r.statusText}`);
return;
}
const d = await r.json();
window.open(d.url, '_blank');
} catch(e) {
alert(`Failed to connect to Guacamole: ${e}`);
} finally {
document.body.style.cursor = '';
}
}
// ── Theme ─────────────────────────────────────────────────────────────────────
const THEMES = ['default', 'rosepine'];
const THEME_LABELS = {default: 'Dark Slate', rosepine: 'Rosé Pine'};
function applyTheme(name) {
document.body.classList.remove(...THEMES.map(t => `theme-${t}`));
if (name !== 'default') document.body.classList.add(`theme-${name}`);
localStorage.setItem('tailscan-theme', name);
// Update version badge subtitle
const vbadge = document.getElementById('version-badge');
if (vbadge) {
const span = document.getElementById('version-str');
const cur = span ? span.textContent : '';
vbadge.title = `Theme: ${THEME_LABELS[name] || name}`;
}
}
function cycleTheme() {
const cur = localStorage.getItem('tailscan-theme') || 'default';
const idx = THEMES.indexOf(cur);
const next = THEMES[(idx + 1) % THEMES.length];
applyTheme(next);
// Brief flash on logo to confirm
const logo = document.querySelector('.logo');
if (logo) {
logo.style.opacity = '0.3';
setTimeout(() => logo.style.opacity = '', 150);
}
}
// Apply saved theme on load
applyTheme(localStorage.getItem('tailscan-theme') || 'default');
// ── Version ───────────────────────────────────────────────────────────────────
fetch('/api/version').then(r=>r.json()).then(d=>{
const el = document.getElementById('version-str');
if (el) el.textContent = 'v' + d.version;
}).catch(()=>{});
// ── Init ─────────────────────────────────────────────────────────────────────
(async () => {
await loadPeers();
if (currentExitNode) {
startAutoRefresh();
await runScan();
}
})();
</script>
</body>
</html>