WireGuard monitor dashboard (Dashboard 2) – peers, traffic, history, Telegram alerts
A single-tab flow that monitors the WireGuard peers on your router (Teltonika RutOS, OpenWrt or any Linux box) and shows them on a Node-RED Dashboard 2 page.
Features
- Live peers table: tunnel / endpoint IP, current rate, 24 h traffic graph, totals, last handshake, online time today
- 7-day online heatmap, event log (connect / disconnect / endpoint change / router outage)
- Fast dashboard, quiet log: disconnects are logged and notified only after a configurable wait, so sleeping phones don't spam you
- Telegram notifications (or ntfy / e-mail via output 2), CSV export, multiple routers, English / Hungarian UI
- Demo mode: works right after import, without a router
- No extra packages besides Dashboard 2: uses the built-in exec node and a read-only SSH key (
command="wg show all dump")
Quick start
- Import, Deploy, open
/dashboard/wireguard. Demo mode shows sample data. - Double-click the tab and set
WG_ROUTERSandWG_PEER_NAMES. - Press "1. Create SSH key", add the line from the Debug panel to the router, press "2. Test connection", then set
WG_DEMOtofalse.
Full documentation, screenshots and a demo video: https://github.com/juhasz-zoltan/node-red-wireguard-monitor
MIT license, provided as is. Developed with AI assistance.
[{"id":"wgpubtab00000001","type":"tab","label":"WireGuard","disabled":false,"info":"WireGuard VPN monitor for Node-RED Dashboard 2.\nPolls \"wg show all dump\" on one or more routers (SSH key, or locally) and shows peers, live traffic, a 24 h graph per peer, a 7-day online heatmap, an event log, CSV export and notifications.\n\nSETTINGS: double-click this tab → Environment Variables\n- WG_ROUTERS: JSON list of routers, e.g. [{\"id\":\"home\",\"name\":\"Home router\",\"host\":\"192.168.1.1\",\"user\":\"root\",\"port\":22,\"mode\":\"ssh\"}]. mode \"local\" = Node-RED runs on the WireGuard host itself\n- WG_PEER_NAMES: JSON object, public key → friendly name\n- WG_DATA_DIR: folder for logs and state (ending with /)\n- WG_SSH_KEY: private key path (empty = WG_DATA_DIR/ssh/wg_monitor)\n- WG_LANG: en / hu (default language; switchable on the dashboard)\n- WG_TZ: time zone for day boundaries, e.g. Europe/Budapest (empty = server time zone)\n- WG_ONLINE_WINDOW: handshake within this many seconds = online\n- WG_CONFIRM: a disconnect is logged and notified only after this many seconds of continuous offline (the dashboard shows it right away)\n- WG_CONFIRM_PEERS: per-device override (JSON), e.g. {\"Office router\": 120}\n- WG_NOTIFY: comma separated: offline, online, endpoint, router\n- WG_NOTIFY_MUTE: JSON list of peer names without notifications\n- WG_TELEGRAM_CHATID: chat ID for the \"Telegram formatter\" node\n- WG_EXPORT_TOKEN: if set, required for CSV download (?token=...)\n- WG_DEMO: true = generated demo data (separate wgdemo_* files). Set to false after configuring WG_ROUTERS.\n\nSSH KEY: press \"1. Create SSH key\", add the line shown in the Debug panel to /etc/dropbear/authorized_keys (OpenWrt / RutOS) or ~/.ssh/authorized_keys on the router, then press \"2. Test connection\".\n\nLOGS: WG_DATA_DIR/wg_YYYY-MM-DD.ndjson (kept 62 days), state: wg_state.json. CSV: /wireguard/export?type=events|daily&days=1..62&lang=en|hu\n\nLicense: MIT. Provided \"as is\", without warranty.","env":[{"name":"WG_ROUTERS","value":"[{\"id\": \"home\", \"name\": \"Home router\", \"host\": \"192.168.1.1\", \"user\": \"root\", \"port\": 22, \"mode\": \"ssh\"}]","type":"json"},{"name":"WG_PEER_NAMES","value":"{\"PUBLIC_KEY_OF_PEER_1_44_CHARACTERS_ENDING_WITH=\": \"Laptop\"}","type":"json"},{"name":"WG_DATA_DIR","value":"/data/wireguard/","type":"str"},{"name":"WG_SSH_KEY","value":"","type":"str"},{"name":"WG_LANG","value":"en","type":"str"},{"name":"WG_TZ","value":"","type":"str"},{"name":"WG_ONLINE_WINDOW","value":"180","type":"num"},{"name":"WG_CONFIRM","value":"600","type":"num"},{"name":"WG_CONFIRM_PEERS","value":"{}","type":"json"},{"name":"WG_NOTIFY","value":"offline,online,router","type":"str"},{"name":"WG_NOTIFY_MUTE","value":"[]","type":"json"},{"name":"WG_TELEGRAM_CHATID","value":"","type":"str"},{"name":"WG_EXPORT_TOKEN","value":"","type":"str"},{"name":"WG_DEMO","value":"true","type":"bool"}]},{"id":"wgpubcmt00000001","type":"comment","z":"wgpubtab00000001","name":"① Settings: double-click the tab → Environment Variables (WG_DEMO=true shows demo data)","info":"WireGuard VPN monitor for Node-RED Dashboard 2.\nPolls \"wg show all dump\" on one or more routers (SSH key, or locally) and shows peers, live traffic, a 24 h graph per peer, a 7-day online heatmap, an event log, CSV export and notifications.\n\nSETTINGS: double-click this tab → Environment Variables\n- WG_ROUTERS: JSON list of routers, e.g. [{\"id\":\"home\",\"name\":\"Home router\",\"host\":\"192.168.1.1\",\"user\":\"root\",\"port\":22,\"mode\":\"ssh\"}]. mode \"local\" = Node-RED runs on the WireGuard host itself\n- WG_PEER_NAMES: JSON object, public key → friendly name\n- WG_DATA_DIR: folder for logs and state (ending with /)\n- WG_SSH_KEY: private key path (empty = WG_DATA_DIR/ssh/wg_monitor)\n- WG_LANG: en / hu (default language; switchable on the dashboard)\n- WG_TZ: time zone for day boundaries, e.g. Europe/Budapest (empty = server time zone)\n- WG_ONLINE_WINDOW: handshake within this many seconds = online\n- WG_CONFIRM: a disconnect is logged and notified only after this many seconds of continuous offline (the dashboard shows it right away)\n- WG_CONFIRM_PEERS: per-device override (JSON), e.g. {\"Office router\": 120}\n- WG_NOTIFY: comma separated: offline, online, endpoint, router\n- WG_NOTIFY_MUTE: JSON list of peer names without notifications\n- WG_TELEGRAM_CHATID: chat ID for the \"Telegram formatter\" node\n- WG_EXPORT_TOKEN: if set, required for CSV download (?token=...)\n- WG_DEMO: true = generated demo data (separate wgdemo_* files). Set to false after configuring WG_ROUTERS.\n\nSSH KEY: press \"1. Create SSH key\", add the line shown in the Debug panel to /etc/dropbear/authorized_keys (OpenWrt / RutOS) or ~/.ssh/authorized_keys on the router, then press \"2. Test connection\".\n\nLOGS: WG_DATA_DIR/wg_YYYY-MM-DD.ndjson (kept 62 days), state: wg_state.json. CSV: /wireguard/export?type=events|daily&days=1..62&lang=en|hu\n\nLicense: MIT. Provided \"as is\", without warranty.","x":330,"y":40,"wires":[]},{"id":"wgpubinj00000001","type":"inject","z":"wgpubtab00000001","name":"Poll (30 s)","props":[{"p":"topic","vt":"str"}],"repeat":"30","crontab":"","once":true,"onceDelay":"2","topic":"wg_poll","x":140,"y":100,"wires":[["wgpubpoll0000001"]]},{"id":"wgpubpoll0000001","type":"function","z":"wgpubtab00000001","name":"Poll (SSH / local / demo)","func":"// @ts-nocheck\n// ===== Poll =====\n// On every tick: output 1 -> exec node (one command per router: SSH or local \"wg show all dump\")\n// output 2 -> WireGuard logic (clock tick + generated data in demo mode)\nfunction envJson(name, def) {\n let v = env.get(name);\n if (v === undefined || v === null || v === \"\") return def;\n if (typeof v === \"string\") { try { v = JSON.parse(v); } catch (e) { node.warn(name + \": invalid JSON\"); return def; } }\n return v;\n}\nconst q = (s) => \"'\" + String(s).replace(/'/g, \"'\\\\''\") + \"'\";\nconst DEMO = env.get(\"WG_DEMO\") === true || env.get(\"WG_DEMO\") === \"true\";\n\nif (DEMO) {\n // ---- demo: made-up peers with documentation IP ranges (for trying it out, screenshots, videos) ----\n const now = Date.now(), nowS = Math.floor(now / 1000);\n const key = (i) => Buffer.alloc(32, i * 37 + 11).toString(\"base64\");\n let D = context.get(\"demo\");\n if (!D) {\n D = { peers: [\n { i: 1, n: \"Branch Router\", ip: \"10.8.0.2/32\", ep: \"198.51.100.24\", base: 350, p: 0.0, ka: 25 },\n { i: 2, n: \"Laptop\", ip: \"10.8.0.3/32\", ep: \"203.0.113.57\", base: 120, p: 0.04, ka: 25 },\n { i: 3, n: \"Phone\", ip: \"10.8.0.4/32\", ep: \"192.0.2.180\", base: 30, p: 0.08, ka: 0 },\n { i: 4, n: \"NAS Backup\", ip: \"10.8.0.5/32\", ep: \"198.51.100.77\", base: 900, p: 0.01, ka: 25 },\n { i: 5, n: \"Camera Gateway\", ip: \"10.8.0.6/32\", ep: \"203.0.113.9\", base: 1600, p: 0.0, ka: 25 },\n { i: 6, n: \"Old Tablet\", ip: \"(none)\", ep: \"\", base: 0, p: 0, ka: 0 }\n ] };\n D.peers.forEach(p => { p.on = p.ip !== \"(none)\" && p.i !== 2; p.rx = Math.floor(Math.random() * 5e9); p.tx = Math.floor(Math.random() * 2e9); p.hs = p.on ? nowS - 20 : nowS - 7200; });\n }\n const lines = [\"wg0\\t(hidden)\\t\" + key(99) + \"\\t51820\\toff\"], names = {};\n D.peers.forEach(p => {\n names[key(p.i)] = p.n;\n if (p.ip !== \"(none)\") {\n if (Math.random() < p.p) p.on = !p.on;\n if (p.on) {\n const kb = p.base * (0.4 + Math.random() * 1.2) * 60 / 8 * 1000; // kbit/s -> bytes per minute\n p.rx += Math.floor(kb); p.tx += Math.floor(kb * (0.15 + Math.random() * 0.3));\n p.hs = nowS - Math.floor(5 + Math.random() * 100);\n if (p.i === 3 && Math.random() < 0.05) p.ep = \"192.0.2.\" + Math.floor(10 + Math.random() * 240);\n }\n }\n lines.push([\"wg0\", key(p.i), \"(none)\", p.ep ? p.ep + \":\" + (40000 + p.i) : \"(none)\", p.ip, p.ip === \"(none)\" ? 0 : p.hs, p.rx, p.tx, p.ka || \"off\"].join(\"\\t\"));\n });\n context.set(\"demo\", D);\n return [null, [{ topic: \"wg_tick\" }, { topic: \"wg_poll\", router: \"demo\", payload: lines.join(\"\\n\"), names: names }]];\n}\n\nlet DIR = String(env.get(\"WG_DATA_DIR\") || \"/data/wireguard/\"); if (!DIR.endsWith(\"/\")) DIR += \"/\";\nconst KEY = String(env.get(\"WG_SSH_KEY\") || (DIR + \"ssh/wg_monitor\"));\nconst KNOWN = DIR + \"ssh/known_hosts\";\nconst TMPKEY = \"/tmp/wg_monitor_key\"; // a 600-mode copy of the key (shared folders often have loose permissions, which ssh refuses)\nconst routers = envJson(\"WG_ROUTERS\", []);\nconst out = [];\n(Array.isArray(routers) ? routers : []).forEach((r, i) => {\n const id = String(r.id || (\"r\" + (i + 1)));\n if (r.mode === \"local\") { out.push({ topic: \"wg_poll\", router: id, payload: \"wg show all dump\" }); return; }\n const host = String(r.host || \"\"), user = String(r.user || \"root\"), port = parseInt(r.port, 10) || 22;\n if (!/^[A-Za-z0-9.\\-:\\[\\]]+$/.test(host) || !/^[A-Za-z0-9._-]+$/.test(user)) { node.warn(\"Invalid router entry in WG_ROUTERS: \" + JSON.stringify(r)); return; }\n out.push({ topic: \"wg_poll\", router: id, payload:\n \"cmp -s \" + q(KEY) + \" \" + TMPKEY + \" 2>/dev/null || { cp \" + q(KEY) + \" \" + TMPKEY + \" && chmod 600 \" + TMPKEY + \"; }; \" +\n \"ssh -i \" + TMPKEY + \" -p \" + port + \" -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=5 -o LogLevel=ERROR\" +\n \" -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=\" + q(KNOWN) + \" \" + q(user + \"@\" + host) + \" 'wg show all dump'\" });\n});\nreturn [out, { topic: \"wg_tick\" }];\n","outputs":2,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[],"x":370,"y":100,"wires":[["wgpubexec0000001"],["wgpublogic000001"]]},{"id":"wgpubexec0000001","type":"exec","z":"wgpubtab00000001","command":"env","addpay":"payload","append":"","useSpawn":"false","timer":"25","winHide":false,"oldrc":false,"name":"wg show (SSH or local)","x":620,"y":80,"wires":[["wgpublogic000001"],[],["wgpublogic000001"]]},{"id":"wgpublogic000001","type":"function","z":"wgpubtab00000001","name":"WireGuard logic","func":"// @ts-nocheck\n// ===== WireGuard logic (v2) =====\n// Inputs: \"Poll\" node (wg_tick + demo data) | exec node (stdout = text, return code = object) | \"cleanup\" | the dashboard (\"wg_get\")\n// Output 1: dashboard Output 2: notifications (to Telegram / ntfy / e-mail)\n// All settings are environment variables of this tab (double-click the tab → Environment Variables).\n\nfunction envJson(name, def) {\n let v = env.get(name);\n if (v === undefined || v === null || v === \"\") return def;\n if (typeof v === \"string\") { try { v = JSON.parse(v); } catch (e) { node.warn(name + \": invalid JSON\"); return def; } }\n return v;\n}\nconst DEMO = env.get(\"WG_DEMO\") === true || env.get(\"WG_DEMO\") === \"true\";\nconst LANG = String(env.get(\"WG_LANG\") || \"en\").toLowerCase().startsWith(\"en\") ? \"en\" : \"hu\";\nconst ROUTERS = DEMO ? [{ id: \"demo\", name: \"Demo router\" }]\n : (Array.isArray(envJson(\"WG_ROUTERS\", [])) ? envJson(\"WG_ROUTERS\", []) : [])\n .map((r, i) => ({ id: String(r.id || (\"r\" + (i + 1))), name: String(r.name || r.host || (\"Router \" + (i + 1))) }));\nconst ONLINE_WINDOW = Number(env.get(\"WG_ONLINE_WINDOW\")) || 180; // handshake within this many seconds = online\nconst ROUTER_STALE_MS = 180000; // no valid data for this long -> \"not responding\"\nlet DIR = String(env.get(\"WG_DATA_DIR\") || \"/data/wireguard/\"); if (!DIR.endsWith(\"/\")) DIR += \"/\";\nconst PFX = DEMO ? \"wgdemo_\" : \"wg_\";\nconst STATE_FILE = DIR + PFX + \"state.json\";\nconst OLD_STATE_FILE = DIR + PFX + \"allapot.json\"; // file name used by earlier versions\nconst NOTIFY = String(env.get(\"WG_NOTIFY\") ?? \"offline,online,router\").split(\",\").map(s => s.trim()).filter(Boolean);\nconst MUTE = envJson(\"WG_NOTIFY_MUTE\", []);\nconst CONFIRM = Number(env.get(\"WG_CONFIRM\") ?? 600) || 0; // a disconnect is logged and notified only after this many seconds of continuous offline (short sleeps of a phone are ignored)\nconst CONFIRM_PEERS = envJson(\"WG_CONFIRM_PEERS\", {}); // per-device override, e.g. {\"Office router\": 120}\nconst LOG_DAYS = 62, DAY_MS = 86400000, BUCKET_MS = 300000, BUCKETS = 288; // 24 hours in 5-minute buckets\nconst CTX = DEMO ? \"wg_S_demo\" : \"wg_S\";\nconst TZ = String(env.get(\"WG_TZ\") || Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\"); // day boundaries and log timestamps\nconst LOCALE = LANG === \"en\" ? \"en-GB\" : \"hu-HU\";\n\nfunction mget(k) { try { return context.get(k, \"memory\"); } catch (e) { return context.get(k); } }\nfunction mset(k, v) { try { context.set(k, v, \"memory\"); } catch (e) { context.set(k, v); } }\nfunction fget(k) { try { return flow.get(k, \"memory\"); } catch (e) { return flow.get(k); } }\nfunction fset(k, v) { try { flow.set(k, v, \"memory\"); } catch (e) { flow.set(k, v); } }\nfunction parts(ts) {\n const o = {};\n new Intl.DateTimeFormat(\"en-GB\", { timeZone: TZ, year: \"numeric\", month: \"2-digit\", day: \"2-digit\",\n hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\", hourCycle: \"h23\" }).formatToParts(new Date(ts)).forEach(x => o[x.type] = x.value);\n return o;\n}\nfunction dayKey(ts) { const o = parts(ts); return o.year + \"-\" + o.month + \"-\" + o.day; }\nfunction dur(ms) {\n const s = Math.max(0, Math.round(ms / 1000)), en = LANG === \"en\";\n if (s < 60) return s + (en ? \" s\" : \" mp\");\n const m = Math.floor(s / 60); if (m < 60) return m + (en ? \" min\" : \" perc\");\n const h = Math.floor(m / 60); if (h < 48) return h + (en ? \" h \" : \" ó \") + (m % 60) + (en ? \" m\" : \" p\");\n return Math.floor(h / 24) + (en ? \" d\" : \" nap\");\n}\n\n// ---------- state ----------\nlet R = mget(\"R\");\nif (!R || R.v !== 2 || R.demo !== DEMO) { R = { v: 2, demo: DEMO, started: Date.now(), rt: {}, prev: {}, live: {}, saveTs: 0, warned: false, dirOk: false }; mset(\"R\", R); }\nif (!R.dirOk) { try { fs.mkdirSync(DIR, { recursive: true }); } catch (e) { } R.dirOk = true; }\nR.live = R.live || {};\nlet S = fget(CTX);\nif (!S || S.v !== 1) {\n try { S = JSON.parse(fs.readFileSync(STATE_FILE, \"utf8\")); } catch (e) { S = null; }\n if (!S) { try { S = JSON.parse(fs.readFileSync(OLD_STATE_FILE, \"utf8\")); } catch (e) { S = null; } }\n if (!S || S.v !== 1) S = { v: 1 };\n S.peers = S.peers || {}; S.days = S.days || {}; S.ev = Array.isArray(S.ev) ? S.ev : [];\n S.hist = S.hist || {}; S.routers = S.routers || {};\n fset(CTX, S);\n}\nfunction rstate(id) { return R.rt[id] || (R.rt[id] = { lastOk: 0, lastPoll: 0, lastErr: 0, err: \"\", out: [] }); }\n\nfunction save(force) {\n const now = Date.now();\n if (!force && now - R.saveTs < 60000) return;\n R.saveTs = now;\n try { fs.writeFileSync(STATE_FILE + \".tmp\", JSON.stringify(S)); fs.renameSync(STATE_FILE + \".tmp\", STATE_FILE); }\n catch (e) { if (!R.warned) { R.warned = true; node.warn(\"Cannot write state file (\" + STATE_FILE + \"): \" + e.message); } }\n}\nfunction dayObj(ts) {\n const k = dayKey(ts);\n const d = S.days[k] || (S.days[k] = { on: {}, up: 0, down: 0 });\n const keys = Object.keys(S.days).sort();\n while (keys.length > LOG_DAYS) delete S.days[keys.shift()];\n return d;\n}\nfunction addEvent(e) {\n S.ev.unshift(e);\n if (S.ev.length > 300) S.ev.length = 300;\n try { fs.appendFileSync(DIR + PFX + dayKey(e.t) + \".ndjson\", JSON.stringify(Object.assign({ ts: new Date(e.t).toISOString() }, e)) + \"\\n\"); }\n catch (err) { if (!R.warned) { R.warned = true; node.warn(\"Cannot write log file: \" + err.message); } }\n}\nfunction notify(kind, peer, text) {\n if (!NOTIFY.includes(kind)) return;\n if (peer && Array.isArray(MUTE) && MUTE.includes(peer)) return;\n node.send([null, { topic: \"WireGuard\", kind: kind, peer: peer || \"\", payload: text }]);\n}\n\n// ---------- 24-hour traffic history (5-minute buckets) ----------\nfunction histAdd(key, now, drx, dtx) {\n const b = Math.floor(now / BUCKET_MS);\n let h = S.hist[key];\n if (!h || !Array.isArray(h.rx) || h.rx.length !== BUCKETS) h = S.hist[key] = { b: b, rx: new Array(BUCKETS).fill(0), tx: new Array(BUCKETS).fill(0) };\n const shift = Math.min(BUCKETS, b - h.b);\n if (shift > 0) {\n h.rx.splice(0, shift); h.tx.splice(0, shift);\n for (let i = 0; i < shift; i++) { h.rx.push(0); h.tx.push(0); }\n h.b = b;\n }\n h.rx[BUCKETS - 1] += drx; h.tx[BUCKETS - 1] += dtx;\n}\nfunction spark(key, now) {\n // 96 points (15-minute average, kbit/s), oldest first\n const h = S.hist[key], b = Math.floor(now / BUCKET_MS);\n const rx = new Array(96).fill(0), tx = new Array(96).fill(0);\n if (!h) return { rx: rx, tx: tx };\n const shift = b - h.b;\n for (let i = 0; i < BUCKETS; i++) {\n const j = i - shift; if (j < 0) continue;\n const k = Math.floor(j / 3);\n rx[k] += h.rx[i]; tx[k] += h.tx[i];\n }\n const f = 8 / 1000 / 900;\n return { rx: rx.map(v => Math.round(v * f * 10) / 10), tx: tx.map(v => Math.round(v * f * 10) / 10) };\n}\n\n// ---------- router reachability ----------\nfunction checkRouters(now) {\n for (const r of ROUTERS) {\n const rr = rstate(r.id);\n const st = S.routers[r.id] || (S.routers[r.id] = { down: false, since: now });\n const stale = now - (rr.lastOk || R.started) > ROUTER_STALE_MS;\n if (stale && !st.down) {\n st.down = true; st.since = rr.lastOk || now;\n addEvent({ t: now, k: \"router_down\", peer: r.name, err: rr.err || \"\" });\n notify(\"router\", \"\", LANG === \"en\" ? \"⚠️ \" + r.name + \" is not responding\" + (rr.err ? \": \" + rr.err.slice(0, 120) : \"\")\n : \"⚠️ \" + r.name + \" nem válaszol\" + (rr.err ? \": \" + rr.err.slice(0, 120) : \"\"));\n save(true);\n } else if (!stale && st.down) {\n addEvent({ t: now, k: \"router_up\", peer: r.name, dur: now - st.since });\n notify(\"router\", \"\", LANG === \"en\" ? \"✅ \" + r.name + \" is reachable again (down for \" + dur(now - st.since) + \")\"\n : \"✅ \" + r.name + \" újra elérhető (\" + dur(now - st.since) + \" kiesés után)\");\n st.down = false; st.since = now;\n save(true);\n }\n }\n}\n\n// ---------- output ----------\nfunction allPeers() { let a = []; ROUTERS.forEach(r => { a = a.concat(rstate(r.id).out || []); }); return a; }\nfunction build(now) {\n const peers = allPeers().map(p => Object.assign({}, p, { spark: spark(p.key, now) }));\n const order = { online: 0, idle: 1, offline: 2, disabled: 3 };\n peers.sort((a, b) => order[a.status] - order[b.status] || a.name.localeCompare(b.name, LOCALE));\n const stats = { total: peers.length, online: 0, idle: 0, offline: 0, disabled: 0 };\n peers.forEach(p => stats[p.status]++);\n const routers = ROUTERS.map(r => { const rr = rstate(r.id);\n return { id: r.id, name: r.name, lastOk: rr.lastOk, err: rr.err, stale: now - (rr.lastOk || R.started) > ROUTER_STALE_MS }; });\n const days = [];\n for (let i = 6; i >= 0; i--) { const k = dayKey(now - i * DAY_MS); days.push({ day: k, n: S.days[k] || { on: {}, up: 0, down: 0 } }); }\n const lastOk = Math.max(0, ...routers.map(r => r.lastOk || 0));\n return { wg: 2, now: now, lang: LANG, tz: TZ, demo: DEMO, multi: ROUTERS.length > 1, token: env.get(\"WG_EXPORT_TOKEN\") || \"\",\n window: ONLINE_WINDOW, routers: routers, lastOk: lastOk, stale: routers.some(r => r.stale), noConfig: !ROUTERS.length,\n peers: peers, stats: stats, today: days[6].n, days: days, ev: S.ev.slice(0, 150) };\n}\nfunction sendUi() { node.send([{ topic: \"wg_update\", payload: build(Date.now()) }, null]); }\n\n// ---------- processing ----------\nfunction processDump(rid, text, names) {\n const router = ROUTERS.find(r => r.id === rid);\n if (!router) return;\n const rr = rstate(rid), now = Date.now();\n const rows = text.split(\"\\n\").map(l => l.trim()).filter(Boolean).map(l => l.split(/[\\t|]/));\n // \"wg show all dump\": interface line = 5 fields (listen-port is the 4th), peer line = 9 fields\n if (!rows.some(p => p.length === 5 && /^\\d+$/.test(p[3]))) {\n rr.bad = text.trim().slice(0, 200); // the error text comes with the return code message (the exec node sends it next)\n return false;\n }\n rr.bad = \"\";\n const dt = rr.lastPoll ? Math.min(now - rr.lastPoll, 180000) : 0; // for \"online today\" (long gaps are not counted)\n rr.lastPoll = now; rr.lastOk = now; rr.err = \"\";\n const nowS = Math.floor(now / 1000), multi = ROUTERS.length > 1;\n const peers = [], seen = {}, day = dayObj(now);\n for (const p of rows) {\n if (p.length < 8) continue;\n const key = p[1].trim();\n if (key.length !== 44 || !key.endsWith(\"=\")) continue; // e.g. login banner lines\n if (seen[key]) continue;\n seen[key] = true;\n const off = p[4] === \"(none)\";\n const hs = parseInt(p[5], 10) || 0, ago = hs > 0 ? nowS - hs : null;\n const rx = parseInt(p[6], 10) || 0, tx = parseInt(p[7], 10) || 0;\n const ka = (p[8] || \"off\").trim();\n const kaSec = ka === \"off\" ? 0 : (parseInt(ka, 10) || 0);\n // live status (for the dashboard): handshake within the window, and for keepalive peers the received byte counter keeps growing\n const pv0 = R.prev[key];\n const lastGrow = (!pv0 || rx !== pv0.rx) ? now : (pv0.g || now);\n const kaLost = kaSec > 0 && now - lastGrow > Math.max(kaSec * 3, (dt || 60000) / 1000 * 1.5) * 1000;\n const live = off ? \"disabled\" : (hs > 0 && ago < ONLINE_WINDOW && !kaLost ? \"online\" : \"offline\");\n const lv = R.live[key];\n if (!lv || lv.s !== live) R.live[key] = { s: live, t: now };\n const name = names[key] || key.substring(0, 6) + \"…\";\n const endpoint = p[3] === \"(none)\" ? \"-\" : p[3];\n const epIp = endpoint === \"-\" ? \"\" : endpoint.replace(/:\\d+$/, \"\").replace(/^\\[|\\]$/g, \"\");\n\n // current rate and 24 h history from the previous poll (0 if the counter was reset)\n const pv = R.prev[key];\n let rxRate = 0, txRate = 0;\n if (pv && now > pv.t && rx >= pv.rx && tx >= pv.tx) {\n const sec = (now - pv.t) / 1000;\n rxRate = Math.round((rx - pv.rx) * 8 / 1000 / sec * 10) / 10;\n txRate = Math.round((tx - pv.tx) * 8 / 1000 / sec * 10) / 10;\n histAdd(key, now, rx - pv.rx, tx - pv.tx);\n }\n R.prev[key] = { rx: rx, tx: tx, t: now, g: lastGrow };\n\n // confirmed status (log, notifications, online time): a disconnect only counts after CONFIRM seconds of continuous offline\n const rname = multi ? router.name : \"\", where = rname ? \" (\" + rname + \")\" : \"\";\n const confirmMs = (Number(CONFIRM_PEERS[name] ?? CONFIRM) || 0) * 1000;\n let st = S.peers[key];\n if (!st) st = S.peers[key] = { name: name, status: live, since: now, ep: epIp, offAt: 0 };\n else {\n st.name = name;\n if (live === \"online\") {\n st.offAt = 0;\n if (st.status !== \"online\") {\n const d = now - st.since;\n addEvent({ t: now, k: \"online\", peer: name, from: st.status, dur: d, r: rname || undefined });\n day.up++;\n notify(\"online\", name, LANG === \"en\" ? \"🟢 \" + name + \" connected\" + where + \" – offline for \" + dur(d)\n : \"🟢 \" + name + \" csatlakozott\" + where + \" – előtte \" + dur(d) + \" offline\");\n st.status = \"online\"; st.since = now;\n }\n } else if (live === \"disabled\") {\n st.offAt = 0;\n if (st.status !== \"disabled\") {\n addEvent({ t: now, k: \"disabled\", peer: name, from: st.status, dur: now - st.since, r: rname || undefined });\n if (st.status === \"online\") day.down++;\n st.status = \"disabled\"; st.since = now;\n }\n } else if (st.status === \"online\") {\n if (!st.offAt) st.offAt = now;\n if (now - st.offAt >= confirmMs) {\n const t0 = st.offAt, d = t0 - st.since;\n addEvent({ t: t0, k: \"offline\", peer: name, from: \"online\", dur: d, r: rname || undefined });\n day.down++;\n notify(\"offline\", name, LANG === \"en\" ? \"🔴 \" + name + \" disconnected\" + where + \" – was online for \" + dur(d)\n : \"🔴 \" + name + \" lecsatlakozott\" + where + \" – előtte \" + dur(d) + \" online\");\n st.status = \"offline\"; st.since = t0; st.offAt = 0;\n }\n } else if (st.status !== \"offline\") {\n addEvent({ t: now, k: \"offline\", peer: name, from: st.status, dur: now - st.since, r: rname || undefined });\n st.status = \"offline\"; st.since = now;\n }\n if (epIp && st.ep && st.ep !== epIp) {\n addEvent({ t: now, k: \"endpoint\", peer: name, from: st.ep, to: epIp, r: rname || undefined });\n notify(\"endpoint\", name, LANG === \"en\" ? \"🌐 \" + name + \" new endpoint: \" + epIp + \" (was \" + st.ep + \")\" : \"🌐 \" + name + \" új címről: \" + epIp + \" (előtte \" + st.ep + \")\");\n }\n if (epIp) st.ep = epIp;\n }\n if (st.status === \"online\" && dt) day.on[name] = (day.on[name] || 0) + dt;\n\n peers.push({\n key: key, name: name, iface: p[0], router: rname, ip: off ? \"-\" : p[4], endpoint: endpoint,\n ago: ago, rx: rx, tx: tx, rxRate: rxRate, txRate: txRate, status: live, ka: kaSec,\n since: R.live[key].t, onToday: day.on[name] || 0\n });\n }\n rr.out = peers;\n // drop traffic history of peers not seen for 2 days\n Object.keys(S.hist).forEach(k => { if (S.hist[k].b < Math.floor(now / BUCKET_MS) - 2 * BUCKETS) delete S.hist[k]; });\n save(false);\n}\n\nfunction statusLine() {\n const now = Date.now(), b = build(now);\n const en = LANG === \"en\", time = new Date().toLocaleTimeString(LOCALE, { timeZone: TZ });\n if (b.noConfig) { node.status({ fill: \"red\", shape: \"ring\", text: en ? \"WG_ROUTERS is not set\" : \"WG_ROUTERS nincs beállítva\" }); return; }\n if (b.stale) {\n const bad = b.routers.filter(r => r.stale).map(r => r.name).join(\", \");\n node.status({ fill: \"red\", shape: \"ring\", text: (en ? \"Not responding: \" : \"Nem válaszol: \") + bad + \" • \" + time });\n } else node.status({ fill: b.stats.online ? \"green\" : \"yellow\", shape: \"dot\", text: (DEMO ? (en ? \"DEMO • \" : \"DEMÓ • \") : \"\") + (b.stats.online + b.stats.idle) + \"/\" + b.stats.total + \" online • \" + time });\n}\n\nfunction cleanup(now) {\n const cut = dayKey(now - LOG_DAYS * DAY_MS);\n const re = new RegExp(\"^\" + PFX + \"\\\\d{4}-\\\\d{2}-\\\\d{2}\\\\.ndjson$\");\n try {\n fs.readdirSync(DIR).filter(f => re.test(f))\n .forEach(f => { if (f.slice(PFX.length, PFX.length + 10) < cut) { try { fs.unlinkSync(DIR + f); } catch (e) { } } });\n } catch (e) { }\n save(true);\n}\n\n// ===================== entry point =====================\nif (msg.topic === \"wg_get\") { sendUi(); return null; }\nif (msg.topic === \"cleanup\") { cleanup(Date.now()); sendUi(); return null; }\nif (msg.topic === \"wg_tick\") { checkRouters(Date.now()); statusLine(); sendUi(); return null; }\n\nconst rid = String(msg.router || (ROUTERS[0] && ROUTERS[0].id) || \"\");\nif (msg.payload && typeof msg.payload === \"object\" && !Buffer.isBuffer(msg.payload)) {\n // 3rd output of the exec node: return code\n const rr0 = rstate(rid);\n if (msg.payload.code === 0 && Date.now() - rr0.lastOk > 5000) {\n // command succeeded but returned nothing usable\n rr0.err = rr0.bad || (LANG === \"en\" ? \"empty response (no WireGuard interface?)\" : \"üres válasz (nincs WireGuard interfész?)\");\n rr0.lastErr = Date.now();\n checkRouters(Date.now()); statusLine(); sendUi();\n }\n if (msg.payload.code !== 0 && msg.payload.code !== undefined) {\n const rr = rstate(rid);\n rr.err = String(msg.payload.message || \"\").replace(/^Command failed:[^\\n]*\\n?/, \"\").trim().slice(0, 300) || ((LANG === \"en\" ? \"exit code \" : \"hibakód \") + msg.payload.code);\n rr.lastErr = Date.now();\n checkRouters(Date.now()); statusLine(); sendUi();\n }\n return null;\n}\nconst text = Buffer.isBuffer(msg.payload) ? msg.payload.toString(\"utf8\") : String(msg.payload ?? \"\");\nconst names = Object.assign({}, DEMO ? {} : envJson(\"WG_PEER_NAMES\", {}), msg.names || {});\nlet ok = false;\ntry { ok = processDump(rid, text, names) !== false; } catch (e) { node.error(\"WireGuard processing error: \" + e.message, msg); }\nif (!ok) return null;\ncheckRouters(Date.now());\nstatusLine();\nsendUi();\nreturn null;\n","outputs":2,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[{"var":"fs","module":"fs"}],"x":860,"y":140,"wires":[["wgpubtmpl0000001"],["wgpubtg000000001","wgpubdbg00000001"]]},{"id":"wgpubtmpl0000001","type":"ui-template","z":"wgpubtab00000001","group":"wgpubgroup000001","page":"","ui":"","name":"WireGuard dashboard","order":1,"width":"12","height":"0","head":"","format":"<template>\n <div class=\"wg-wrap\">\n <div v-if=\"!G\" class=\"wg-card wg-empty\">\n <v-progress-circular indeterminate color=\"#00e5ff\" size=\"24\" class=\"mr-3\"></v-progress-circular>\n {{ t('loading') }}\n </div>\n\n <div v-else class=\"wg-view\">\n <div class=\"wg-top\">\n <div class=\"wg-row\">\n <v-icon color=\"#00e5ff\">mdi-vpn</v-icon>\n <h2 class=\"wg-title\">WireGuard VPN</h2>\n <v-chip v-if=\"G.demo\" size=\"small\" variant=\"flat\" color=\"purple\" class=\"font-weight-bold\"><v-icon start size=\"small\">mdi-flask-outline</v-icon>{{ t('demo') }}</v-chip>\n <v-chip size=\"small\" variant=\"flat\" color=\"success\" class=\"font-weight-bold\"><v-icon start size=\"small\">mdi-check-network</v-icon>{{ G.stats.online }} ONLINE</v-chip>\n <v-chip v-if=\"G.stats.idle\" size=\"small\" variant=\"flat\" color=\"amber-darken-2\" class=\"font-weight-bold\"><v-icon start size=\"small\">mdi-sleep</v-icon>{{ G.stats.idle }} {{ t('idleUp') }}</v-chip>\n <v-chip v-if=\"G.stats.offline\" size=\"small\" variant=\"flat\" color=\"error\" class=\"font-weight-bold\"><v-icon start size=\"small\">mdi-close-network</v-icon>{{ G.stats.offline }} OFFLINE</v-chip>\n <v-chip v-if=\"G.stats.disabled\" size=\"small\" variant=\"flat\" color=\"grey-darken-2\" class=\"font-weight-bold\"><v-icon start size=\"small\">mdi-cancel</v-icon>{{ G.stats.disabled }} {{ t('disabledUp') }}</v-chip>\n <v-chip v-if=\"G.noConfig\" size=\"small\" variant=\"flat\" color=\"warning\" class=\"font-weight-bold\">{{ t('noConfig') }}</v-chip>\n <template v-for=\"r in G.routers\" :key=\"r.id\">\n <v-chip v-if=\"r.stale\" size=\"small\" variant=\"flat\" color=\"warning\" class=\"font-weight-bold wg-blink\" :title=\"r.err || ''\">\n <v-icon start size=\"small\">mdi-router-network-wireless</v-icon>{{ G.multi ? r.name + ': ' : '' }}{{ t('routerDown') }}{{ r.lastOk ? ', ' + since(srvNow - r.lastOk) : '' }}\n </v-chip>\n <v-chip v-else-if=\"G.multi\" size=\"small\" variant=\"tonal\" color=\"#00e5ff\" class=\"font-weight-bold\"><v-icon start size=\"small\">mdi-router-wireless</v-icon>{{ r.name }}</v-chip>\n </template>\n </div>\n <div class=\"wg-row\">\n <div class=\"wg-seg\" role=\"group\" :aria-label=\"t('language')\">\n <button type=\"button\" :aria-pressed=\"lang === 'hu'\" @click=\"setLang('hu')\">HU</button>\n <button type=\"button\" :aria-pressed=\"lang === 'en'\" @click=\"setLang('en')\">EN</button>\n </div>\n <button type=\"button\" class=\"wg-btn\" @click=\"exp.open = true\"><v-icon size=\"small\" class=\"mr-1\">mdi-download</v-icon>{{ t('download') }}</button>\n </div>\n </div>\n <div v-if=\"staleErr\" class=\"wg-err\"><v-icon size=\"small\" color=\"warning\" class=\"mr-1\">mdi-alert</v-icon>{{ staleErr }}</div>\n\n <div class=\"wg-grid wg-fill\">\n <div class=\"wg-col\">\n <!-- Peers -->\n <section class=\"wg-card wg-a-peers\">\n <div class=\"wg-card-head\">\n <span class=\"wg-h\"><v-icon size=\"small\" color=\"#00e5ff\" class=\"mr-1\">mdi-lan-connect</v-icon>{{ t('peers') }}</span>\n <span class=\"wg-muted\">{{ t('updated') }} {{ G.lastOk ? ago(G.lastOk) : '--' }}</span>\n </div>\n <div class=\"wg-table\">\n <div class=\"wg-tr wg-th\">\n <span>{{ t('cDevice') }}</span><span>{{ t('cIp') }}</span><span>{{ t('cNow') }}</span><span>{{ t('c24') }}</span><span>{{ t('cTotal') }}</span><span>{{ t('cHs') }}</span><span>{{ t('cToday') }}</span><span>{{ t('cStatus') }}</span>\n </div>\n <div v-if=\"!G.peers.length\" class=\"wg-muted wg-center wg-pad\">{{ t('noData') }}</div>\n <div v-for=\"p in G.peers\" :key=\"p.key\" class=\"wg-tr\" :class=\"'st-' + p.status\">\n <span class=\"wg-name\">\n <v-icon size=\"26\" :color=\"stColor(p.status)\" :class=\"{ 'wg-glow': p.status === 'online' }\">{{ icon(p.name) }}</v-icon>\n <span><b :title=\"p.name\">{{ p.name }}</b><small>{{ p.router ? p.router + ' · ' : '' }}{{ p.iface }}</small></span>\n </span>\n <span class=\"wg-mono\"><b class=\"wg-cyan\">{{ p.ip.replace(/,/g, ', ') }}</b><small :title=\"p.endpoint\">{{ p.endpoint }}</small></span>\n <span class=\"wg-mono wg-rate\">\n <span :class=\"{ dim: !p.rxRate }\"><v-icon size=\"x-small\" color=\"#00e676\">mdi-arrow-down-thick</v-icon>{{ rate(p.rxRate) }}</span>\n <span :class=\"{ dim: !p.txRate }\"><v-icon size=\"x-small\" color=\"#ff6e40\">mdi-arrow-up-thick</v-icon>{{ rate(p.txRate) }}</span>\n </span>\n <span class=\"wg-spark\" :title=\"sparkTitle(p)\">\n <svg viewBox=\"0 0 96 26\" preserveAspectRatio=\"none\" width=\"100%\" height=\"26\" aria-hidden=\"true\">\n <polyline :points=\"sparkPts(p, 'rx', true)\" fill=\"rgba(0, 230, 118, 0.18)\" stroke=\"none\"></polyline>\n <polyline :points=\"sparkPts(p, 'rx')\" fill=\"none\" stroke=\"#00e676\" stroke-width=\"1.3\" vector-effect=\"non-scaling-stroke\"></polyline>\n <polyline :points=\"sparkPts(p, 'tx')\" fill=\"none\" stroke=\"#ff6e40\" stroke-width=\"1.1\" vector-effect=\"non-scaling-stroke\"></polyline>\n </svg>\n <small>{{ t('peak') }} {{ rate(sparkMax(p)) }}</small>\n </span>\n <span class=\"wg-mono wg-rate\">\n <span>↓ {{ bytes(p.rx) }}</span><span>↑ {{ bytes(p.tx) }}</span>\n </span>\n <span class=\"wg-sm\">{{ p.ago === null ? t('never') : (p.ago < 5 ? t('now') : agoTxt(p.ago * 1000)) }}\n <small v-if=\"p.status === 'offline' && !p.ka\" class=\"wg-ka\" :title=\"t('kaHint')\"><v-icon size=\"x-small\" color=\"#ffb74d\">mdi-information-outline</v-icon>{{ t('noKa') }}</small>\n </span>\n <span class=\"wg-sm\">{{ p.onToday ? dur(p.onToday) : '--' }}</span>\n <span><v-chip size=\"small\" variant=\"flat\" :color=\"stChip(p.status)\" class=\"font-weight-bold wg-chip\">{{ stText(p.status) }}</v-chip>\n <small class=\"wg-since\">{{ p.since ? since(srvNow - p.since) : '' }}</small></span>\n </div>\n </div>\n </section>\n\n <!-- Event log / 7 days -->\n <section class=\"wg-card wg-a-log\">\n <div class=\"wg-card-head\">\n <div class=\"wg-seg wg-tabs\" role=\"tablist\">\n <button type=\"button\" role=\"tab\" :aria-selected=\"tab === 'ev'\" :aria-pressed=\"tab === 'ev'\" @click=\"tab = 'ev'\"><v-icon size=\"small\" class=\"mr-1\">mdi-history</v-icon>{{ t('events') }}</button>\n <button type=\"button\" role=\"tab\" :aria-selected=\"tab === 'week'\" :aria-pressed=\"tab === 'week'\" @click=\"tab = 'week'\"><v-icon size=\"small\" class=\"mr-1\">mdi-calendar-week</v-icon>{{ t('week') }}</button>\n </div>\n <span class=\"wg-muted\">{{ t('today') }}: {{ G.today.up || 0 }} {{ t('connCount') }} · {{ G.today.down || 0 }} {{ t('discCount') }}</span>\n </div>\n <div v-if=\"tab === 'ev'\" class=\"wg-log\">\n <div v-if=\"!G.ev.length\" class=\"wg-muted wg-center wg-pad\">{{ t('noEvents') }}</div>\n <div v-for=\"(e, i) in G.ev\" :key=\"e.t + e.peer + e.k + i\" class=\"wg-ev\">\n <v-icon size=\"small\" :color=\"evColor(e)\">{{ evIcon(e) }}</v-icon>\n <div class=\"wg-ev-main\">\n <div class=\"wg-ev-title\"><b :style=\"{ color: evColor(e) }\">{{ e.peer }}</b> {{ evText(e) }}<span v-if=\"e.r\" class=\"wg-muted\"> · {{ e.r }}</span></div>\n <div class=\"wg-muted\">{{ when(e.t) }}<template v-if=\"evDetail(e)\"> · {{ evDetail(e) }}</template></div>\n </div>\n <span class=\"wg-muted wg-ago\">{{ ago(e.t) }}</span>\n </div>\n </div>\n <div v-else class=\"wg-week\">\n <div class=\"wg-wk\" :style=\"{ gridTemplateColumns: 'minmax(110px, 1.3fr) repeat(7, minmax(46px, 1fr))' }\">\n <span></span>\n <span v-for=\"d in G.days\" :key=\"'h' + d.day\" class=\"wg-wk-h\" :class=\"{ today: d.day === G.days[6].day }\">{{ dayLabel(d.day) }}</span>\n <template v-for=\"n in weekNames\" :key=\"'r' + n\">\n <span class=\"wg-wk-name\"><v-icon size=\"x-small\" class=\"mr-1\">{{ icon(n) }}</v-icon>{{ n }}</span>\n <span v-for=\"d in G.days\" :key=\"n + d.day\" class=\"wg-wk-c\" :style=\"cellStyle(d, n)\" :title=\"n + ' · ' + d.day + ': ' + (onMs(d, n) ? dur(onMs(d, n)) : '0')\">{{ cellTxt(d, n) }}</span>\n </template>\n <span class=\"wg-wk-name wg-muted\">{{ t('connCountCap') }}</span>\n <span v-for=\"d in G.days\" :key=\"'u' + d.day\" class=\"wg-wk-s up\">{{ d.n.up || '' }}</span>\n <span class=\"wg-wk-name wg-muted\">{{ t('discCountCap') }}</span>\n <span v-for=\"d in G.days\" :key=\"'d' + d.day\" class=\"wg-wk-s down\">{{ d.n.down || '' }}</span>\n </div>\n <div v-if=\"!weekNames.length\" class=\"wg-muted wg-center wg-pad\">{{ t('noData') }}</div>\n <div class=\"wg-muted wg-wk-note\">{{ t('weekNote') }}</div>\n </div>\n </section>\n </div>\n\n <!-- Live topology -->\n <section class=\"wg-card wg-a-topo\">\n <div class=\"wg-card-head\">\n <span class=\"wg-h\"><v-icon size=\"small\" color=\"#00e5ff\" class=\"mr-1\">mdi-satellite-uplink</v-icon>{{ t('topo') }}</span>\n <span class=\"wg-muted\">{{ onlinePeers.length }} {{ t('tunnels') }}</span>\n </div>\n <div ref=\"topo\" class=\"wg-topo\">\n <div class=\"wg-core\">\n <v-icon size=\"58\" color=\"#00e5ff\" class=\"wg-logo\">mdi-shield-lock</v-icon>\n <div class=\"wg-core-pulse\"></div>\n </div>\n <div v-for=\"(p, i) in onlinePeers\" :key=\"p.key\" class=\"wg-orbit\" :style=\"orbitStyle(i)\">\n <div class=\"wg-sat\" :style=\"spinStyle(i)\">\n <v-icon size=\"26\" :color=\"stColor(p.status)\" class=\"wg-sat-ic wg-glow\">{{ icon(p.name) }}</v-icon>\n <span class=\"wg-sat-label\">{{ p.name }}<em v-if=\"p.rxRate || p.txRate\"> · {{ rate(p.rxRate + p.txRate) }}</em></span>\n </div>\n </div>\n <div v-if=\"!onlinePeers.length\" class=\"wg-none\"><v-icon size=\"small\" color=\"error\" class=\"mr-1\">mdi-alert-circle-outline</v-icon>{{ t('noActive') }}</div>\n </div>\n <div v-if=\"restPeers.length\" class=\"wg-rest\">\n <span v-for=\"p in restPeers\" :key=\"p.key\" :style=\"{ '--c': stColor(p.status) }\"><v-icon size=\"x-small\">{{ icon(p.name) }}</v-icon>{{ p.name }}</span>\n </div>\n </section>\n </div>\n </div>\n\n <!-- LOG DOWNLOAD -->\n <div v-if=\"exp.open\" class=\"wg-overlay\" @click.self=\"exp.open = false\">\n <div class=\"wg-modal\" role=\"dialog\" aria-modal=\"true\" aria-labelledby=\"wg-exp-title\">\n <div class=\"wg-modal-head\">\n <h2 id=\"wg-exp-title\" class=\"wg-modal-title\">{{ t('download') }}</h2>\n <button type=\"button\" class=\"wg-icon-btn\" :aria-label=\"t('close')\" @click=\"exp.open = false\"><v-icon>mdi-close</v-icon></button>\n </div>\n <div class=\"wg-field\">{{ t('content') }}\n <div class=\"wg-seg\">\n <button type=\"button\" :aria-pressed=\"exp.type === 'events'\" @click=\"exp.type = 'events'\">{{ t('events') }}</button>\n <button type=\"button\" :aria-pressed=\"exp.type === 'daily'\" @click=\"exp.type = 'daily'\">{{ t('daily') }}</button>\n </div>\n <div class=\"wg-muted\">{{ exp.type === 'daily' ? t('dailyHelp') : t('eventsHelp') }}</div>\n </div>\n <div class=\"wg-field\">{{ t('period') }}\n <div class=\"wg-seg\">\n <button v-for=\"d in [1, 7, 30, 62]\" :key=\"d\" type=\"button\" :aria-pressed=\"exp.days === d\" @click=\"exp.days = d\">{{ d === 1 ? t('todayCap') : d + ' ' + t('days') }}</button>\n </div>\n </div>\n <a class=\"wg-btn wg-btn-primary wg-link\" :href=\"exportHref\" download>{{ t('downloadCsv') }}</a>\n </div>\n </div>\n </div>\n</template>\n\n<script>\n // @ts-nocheck\n export default {\n data() {\n const TXT = {\n hu: {\n loading: 'Adatok betöltése… Ha egy percen belül sem jön semmi, nézd meg, hogy a „WireGuard logic” node fut-e.',\n demo: 'DEMÓ', disabledUp: 'LETILTVA', noConfig: 'Nincs router beállítva (WG_ROUTERS)', routerDown: 'A router nem válaszol', language: 'Nyelv',\n download: 'Napló letöltése', peers: 'Kapcsolatok', updated: 'frissítve', cDevice: 'Eszköz', cIp: 'Belső / külső IP', cNow: 'Most', c24: '24 óra',\n cTotal: 'Összesen', cHs: 'Kézfogás', cToday: 'Ma online', cStatus: 'Állapot', noData: 'Még nincs adat a routertől.', peak: 'csúcs',\n never: 'soha', now: 'most', noKa: 'nincs keepalive', kaHint: 'A routeren ennél az eszköznél nincs PersistentKeepalive beállítva, ezért forgalom nélkül a kézfogás elévülhet, és offline-nak látszik. Állítsd 25 mp-re a routeren vagy a kliensen.',\n events: 'Eseménynapló', week: '7 nap', today: 'ma', todayCap: 'Ma', connCount: 'csatlakozás', discCount: 'lecsatlakozás', connCountCap: 'Csatlakozás', discCountCap: 'Lecsatlakozás',\n noEvents: 'Még nem volt esemény.', weekNote: 'A cellákban: online órák száma az adott napon.', topo: 'Élő topológia', tunnels: 'aktív alagút', noActive: 'Nincs aktív kapcsolat',\n close: 'Bezárás', content: 'Tartalom', daily: 'Napi összesítő', dailyHelp: 'Naponta: csatlakozások, lecsatlakozások, és eszközönként hány percet volt online.',\n eventsHelp: 'Minden esemény: mikor csatlakozott / csatlakozott le egy eszköz (és előtte mennyi ideig), címváltások, router-kiesések.',\n period: 'Időszak', days: 'nap', downloadCsv: 'Letöltés (CSV, Excelben megnyitható)',\n evOnline: 'csatlakozott', evOffline: 'lecsatlakozott', evDisabled: 'letiltva', evEndpoint: 'új címről jelentkezett', evRDown: 'nem válaszol', evRUp: 'újra elérhető',\n before: 'előtte', downFor: 'kiesés hossza', online: 'Online', idle: 'Tétlen', idleUp: 'TÉTLEN', offline: 'Offline', disabled: 'Letiltva', todayW: 'ma', yesterday: 'tegnap',\n u: { s: 'mp', m: 'perc', h: 'ó', mm: 'p', d: 'nap' }, ago: (x) => x + ' ezelőtt', since: (x) => x + ' óta',\n wd: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo']\n },\n en: {\n loading: 'Loading… If nothing arrives within a minute, check that the \"WireGuard logic\" node is running.',\n demo: 'DEMO', disabledUp: 'DISABLED', noConfig: 'No router configured (WG_ROUTERS)', routerDown: 'Router not responding', language: 'Language',\n download: 'Download log', peers: 'Peers', updated: 'updated', cDevice: 'Device', cIp: 'Tunnel / endpoint IP', cNow: 'Now', c24: '24 hours',\n cTotal: 'Total', cHs: 'Handshake', cToday: 'Online today', cStatus: 'Status', noData: 'No data from the router yet.', peak: 'peak',\n never: 'never', now: 'now', noKa: 'no keepalive', kaHint: 'The router has no PersistentKeepalive for this peer, so without traffic the handshake can expire and it shows as offline. Set it to 25 s on the router or the client.',\n events: 'Event log', week: '7 days', today: 'today', todayCap: 'Today', connCount: 'connections', discCount: 'disconnections', connCountCap: 'Connections', discCountCap: 'Disconnections',\n noEvents: 'No events yet.', weekNote: 'Cells show hours online on that day.', topo: 'Live topology', tunnels: 'active tunnels', noActive: 'No active peers',\n close: 'Close', content: 'Content', daily: 'Daily summary', dailyHelp: 'Per day: connections, disconnections and minutes online per peer.',\n eventsHelp: 'Every event: when a peer connected / disconnected (and for how long before), endpoint changes, router outages.',\n period: 'Period', days: 'days', downloadCsv: 'Download (CSV, opens in Excel)',\n evOnline: 'connected', evOffline: 'disconnected', evDisabled: 'disabled', evEndpoint: 'new endpoint', evRDown: 'not responding', evRUp: 'reachable again',\n before: 'previously', downFor: 'outage', online: 'Online', idle: 'Idle', idleUp: 'IDLE', offline: 'Offline', disabled: 'Disabled', todayW: 'today', yesterday: 'yesterday',\n u: { s: 's', m: 'min', h: 'h', mm: 'm', d: 'd' }, ago: (x) => x + ' ago', since: (x) => 'for ' + x,\n wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n }\n };\n return {\n TXT: TXT,\n exportBase: '/wireguard/export', // URL of the \"Log download\" http in node (adjust if your httpNodeRoot is not \"/\")\n nowMs: Date.now(), offset: 0, ticker: null,\n box: 360, ro: null, tab: 'ev', userLang: null,\n exp: { open: false, type: 'events', days: 7 }\n }\n },\n computed: {\n G() { const p = this.msg && this.msg.payload; return (p && p.wg === 2 && Array.isArray(p.peers)) ? p : null; },\n lang() { return this.userLang || (this.G && this.G.lang) || 'en'; },\n L() { return this.TXT[this.lang] || this.TXT.en; },\n srvNow() { return this.nowMs + this.offset; },\n onlinePeers() { return this.G.peers.filter(p => p.status === 'online' || p.status === 'idle').slice(0, 8); },\n restPeers() { return this.G.peers.filter(p => p.status !== 'online' && p.status !== 'idle'); },\n staleErr() { const r = this.G && this.G.routers.find(x => x.stale && x.err); return r ? (this.G.multi ? r.name + ': ' : '') + r.err : ''; },\n weekNames() {\n const s = {};\n this.G.peers.forEach(p => { if (p.status !== 'disabled') s[p.name] = true; });\n this.G.days.forEach(d => Object.keys(d.n.on || {}).forEach(n => { s[n] = true; }));\n return Object.keys(s).sort((a, b) => a.localeCompare(b, this.lang));\n },\n exportHref() {\n return this.exportBase + '?type=' + this.exp.type + '&days=' + this.exp.days + '&lang=' + this.lang + (this.G && this.G.token ? '&token=' + encodeURIComponent(this.G.token) : '');\n }\n },\n watch: {\n msg: { immediate: true, handler() { const p = this.msg && this.msg.payload; if (p && p.now) this.offset = p.now - Date.now(); } },\n G(n, o) { if (n && !o) this.$nextTick(() => this.observe()); }\n },\n mounted() {\n try { const l = window.localStorage.getItem('wg_lang'); if (l === 'hu' || l === 'en') this.userLang = l; } catch (e) { }\n this.ticker = setInterval(() => { this.nowMs = Date.now(); }, 5000);\n this.send({ topic: 'wg_get' });\n this.$nextTick(() => this.observe());\n this._esc = (ev) => { if (ev.key === 'Escape') this.exp.open = false; };\n window.addEventListener('keydown', this._esc);\n },\n unmounted() {\n clearInterval(this.ticker);\n if (this.ro) this.ro.disconnect();\n window.removeEventListener('keydown', this._esc);\n },\n methods: {\n t(k) { return this.L[k] !== undefined ? this.L[k] : k; },\n setLang(l) { this.userLang = l; try { window.localStorage.setItem('wg_lang', l); } catch (e) { } },\n observe() {\n const el = this.$refs.topo;\n if (this.ro || !el || !window.ResizeObserver) return;\n this.ro = new ResizeObserver(() => { this.box = Math.max(200, Math.min(el.clientWidth, el.clientHeight)); });\n this.ro.observe(el);\n },\n // orbits scale with the box so the outermost one (and its labels) always fits\n orbitStyle(i) {\n const n = this.onlinePeers.length, inner = Math.min(220, this.box * 0.42), outer = Math.max(inner, this.box - 150);\n const step = n > 1 ? Math.min(70, (outer - inner) / (n - 1)) : 0;\n const size = Math.round(inner + i * step), speed = 18 + i * 5;\n return { width: size + 'px', height: size + 'px', animationDuration: speed + 's', animationDelay: -(i * 17.3) + 's', zIndex: 20 - i };\n },\n spinStyle(i) { const speed = 18 + i * 5; return { animationDuration: speed + 's', animationDelay: -(i * 17.3) + 's' }; },\n icon(name) {\n const n = (name || '').toLowerCase();\n if (/iphone|phone|telefon|mobil|ipad|tablet|android/.test(n)) return 'mdi-cellphone';\n if (/windows|pc|laptop|mac|desktop|notebook/.test(n)) return 'mdi-laptop';\n if (/router|teltonika|rut|gateway|branch|iroda|office/.test(n)) return 'mdi-router-wireless';\n if (/nas|synology|ds118|ds225|backup|server|szerver/.test(n)) return 'mdi-nas';\n if (/kamera|camera|techson|ipc|cam|nvr/.test(n)) return 'mdi-cctv';\n return 'mdi-network-outline';\n },\n stColor(s) { return s === 'online' ? '#00e676' : s === 'idle' ? '#ffb74d' : s === 'offline' ? '#ff5252' : '#8a979c'; },\n stChip(s) { return s === 'online' ? 'success' : s === 'idle' ? 'amber-darken-2' : s === 'offline' ? 'error' : 'grey-darken-2'; },\n stText(s) { return s === 'online' || s === 'idle' || s === 'offline' || s === 'disabled' ? this.t(s) : (s || ''); },\n evColor(e) { return e.k === 'endpoint' ? '#40c4ff' : e.k === 'router_down' ? '#ffb74d' : e.k === 'router_up' ? '#00e676' : this.stColor(e.k); },\n evIcon(e) {\n return { online: 'mdi-lan-connect', offline: 'mdi-lan-disconnect', disabled: 'mdi-cancel', endpoint: 'mdi-map-marker-path',\n router_down: 'mdi-router-network-wireless', router_up: 'mdi-router-wireless' }[e.k] || 'mdi-information-outline';\n },\n evText(e) { return this.t({ online: 'evOnline', offline: 'evOffline', disabled: 'evDisabled', endpoint: 'evEndpoint', router_down: 'evRDown', router_up: 'evRUp' }[e.k] || e.k); },\n evDetail(e) {\n if (e.k === 'endpoint') return e.from + ' → ' + e.to;\n if (e.k === 'router_up') return e.dur ? this.t('downFor') + ' ' + this.dur(e.dur) : '';\n if (e.k === 'router_down') return e.err ? e.err.slice(0, 120) : '';\n return e.dur ? this.t('before') + ' ' + this.dur(e.dur) + ' ' + this.stText(e.from).toLowerCase() : '';\n },\n rate(k) { return !k ? '0' : k >= 1000 ? (k / 1000).toFixed(1) + ' Mbit/s' : Math.round(k) + ' kbit/s'; },\n bytes(b) { return b >= 1073741824 ? (b / 1073741824).toFixed(2) + ' GB' : (b / 1048576).toFixed(1) + ' MB'; },\n sparkMax(p) { const s = p.spark; if (!s) return 0; let m = 0; for (let i = 0; i < s.rx.length; i++) m = Math.max(m, s.rx[i], s.tx[i]); return m; },\n sparkPts(p, k, area) {\n const s = p.spark; if (!s) return '';\n const m = this.sparkMax(p) || 1, a = s[k], n = a.length;\n const pts = a.map((v, i) => (i * 96 / (n - 1)).toFixed(1) + ',' + (25 - (v / m) * 23).toFixed(1));\n return area ? '0,26 ' + pts.join(' ') + ' 96,26' : pts.join(' ');\n },\n sparkTitle(p) {\n const s = p.spark; if (!s) return '';\n const sum = (a) => a.reduce((x, y) => x + y, 0) * 900 * 1000 / 8; // 15-minute kbit/s averages -> bytes\n return '24 h: ↓ ' + this.bytes(sum(s.rx)) + ' ↑ ' + this.bytes(sum(s.tx));\n },\n onMs(d, n) { return (d.n.on && d.n.on[n]) || 0; },\n cellTxt(d, n) { const h = this.onMs(d, n) / 3600000; return h <= 0 ? '' : h < 0.1 ? '<0.1' : (h >= 10 ? Math.round(h) : h.toFixed(1)); },\n cellStyle(d, n) {\n const f = Math.min(1, this.onMs(d, n) / 86400000);\n return f > 0 ? { background: 'rgba(0, 230, 118, ' + (0.12 + f * 0.7).toFixed(2) + ')', color: f > 0.55 ? '#06120a' : '#e8f1f2' } : {};\n },\n dayLabel(day) {\n const dt = new Date(day + 'T12:00:00Z');\n return this.L.wd[dt.getUTCDay()] + ' ' + day.slice(8, 10) + '.';\n },\n parts(ts) {\n const o = {};\n new Intl.DateTimeFormat('en-GB', { timeZone: (this.G && this.G.tz) || undefined, year: 'numeric', month: '2-digit', day: '2-digit',\n hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).formatToParts(new Date(ts)).forEach(x => { o[x.type] = x.value; });\n return o;\n },\n when(ts) {\n const o = this.parts(ts), n = this.parts(this.srvNow), y = this.parts(this.srvNow - 86400000);\n const time = o.hour + ':' + o.minute;\n if (o.year === n.year && o.month === n.month && o.day === n.day) return this.t('todayW') + ' ' + time;\n if (o.year === y.year && o.month === y.month && o.day === y.day) return this.t('yesterday') + ' ' + time;\n return o.month + '.' + o.day + '. ' + time;\n },\n dur(ms) {\n const u = this.L.u, s = Math.max(0, Math.round(ms / 1000));\n if (s < 60) return s + ' ' + u.s;\n const m = Math.floor(s / 60);\n if (m < 60) return m + ' ' + u.m;\n const h = Math.floor(m / 60);\n if (h < 48) return h + ' ' + u.h + ' ' + (m % 60) + ' ' + u.mm;\n return Math.floor(h / 24) + ' ' + u.d;\n },\n agoTxt(ms) { return this.L.ago(this.dur(ms)); },\n since(ms) { return this.L.since(this.dur(ms)); },\n ago(ts) { const d = this.srvNow - ts; return d < 5000 ? this.t('now') : this.agoTxt(d); }\n }\n}\n</script>\n\n<style>\n .wg-wrap { color: #e8f1f2; font-variant-numeric: tabular-nums; font-size: 14px; position: relative;\n /* one screen without scrolling on Full HD and 4K */\n height: calc(100vh - 160px); min-height: 460px; display: flex; flex-direction: column; overflow: hidden; }\n .wg-view { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }\n .wg-fill { flex: 1 1 auto; min-height: 0; }\n .wg-wrap h2 { margin: 0; }\n .wg-card { background: linear-gradient(180deg, rgba(0, 229, 255, 0.05), transparent 70px), #15181a; border: 1px solid rgba(0, 229, 255, 0.35);\n border-radius: 10px; padding: 12px 14px; min-width: 0; }\n .wg-empty { display: flex; align-items: center; }\n .wg-muted { color: #8a979c; font-size: 12.5px; line-height: 1.4; }\n .wg-center { text-align: center; } .wg-pad { padding: 20px 0; }\n .wg-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }\n .wg-top { display: flex; justify-content: space-between; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; }\n .wg-title { font-size: 19px; font-weight: 700; }\n .wg-h { font-size: 15px; font-weight: 600; display: inline-flex; align-items: center; }\n .wg-card-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; flex-shrink: 0; }\n .wg-err { margin: -4px 0 10px; padding: 6px 10px; border-radius: 6px; background: rgba(255, 183, 77, 0.1); border: 1px solid rgba(255, 183, 77, 0.4);\n color: #ffcc80; font-size: 12.5px; font-family: 'JetBrains Mono', ui-monospace, Consolas, monospace; word-break: break-word; flex-shrink: 0; }\n\n /* two independent columns: peers + log on the left, topology on the right */\n .wg-grid { display: grid; gap: 10px; grid-template-columns: minmax(0, 2.5fr) minmax(300px, 1fr); grid-template-rows: minmax(0, 1fr); }\n .wg-col { display: flex; flex-direction: column; gap: 10px; min-height: 0; }\n .wg-a-peers { flex: 0 0 auto; display: flex; flex-direction: column; min-height: 0; max-height: 62%; }\n .wg-a-log { flex: 1 1 0; display: flex; flex-direction: column; min-height: 140px; }\n .wg-a-topo { display: flex; flex-direction: column; min-height: 0; }\n @media (max-width: 1150px) {\n .wg-wrap { height: auto; overflow: visible; }\n .wg-view, .wg-fill { flex: none; }\n .wg-grid { display: flex; flex-direction: column; }\n .wg-col { display: contents; }\n .wg-a-peers { order: 1; max-height: none; } .wg-a-topo { order: 2; } .wg-a-log { order: 3; flex: none; }\n .wg-topo { flex: none !important; height: 360px; }\n .wg-log, .wg-week { max-height: 70vh; }\n }\n\n /* peers table */\n .wg-table { overflow: auto; min-height: 0; scrollbar-width: thin; scrollbar-color: rgba(0, 229, 255, 0.35) transparent; }\n .wg-tr { display: grid; grid-template-columns: minmax(150px, 1.4fr) minmax(130px, 1.2fr) 110px 112px 100px 100px 85px 110px; gap: 10px; align-items: center;\n padding: 7px 6px; border-top: 1px solid rgba(255, 255, 255, 0.05); min-width: 950px; transition: background 0.2s; }\n .wg-tr:not(.wg-th):hover { background: rgba(0, 229, 255, 0.07); }\n .wg-th { position: sticky; top: 0; z-index: 2; background: #121618; border-top: 0; border-bottom: 2px solid rgba(0, 229, 255, 0.35);\n color: #00e5ff; font-size: 11.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; }\n .wg-tr.st-offline { background: rgba(255, 82, 82, 0.05); }\n .wg-tr.st-disabled { opacity: 0.55; }\n .wg-tr.st-idle { background: rgba(255, 183, 77, 0.05); }\n .wg-name { display: flex; align-items: center; gap: 10px; min-width: 0; }\n .wg-name > span, .wg-mono { display: flex; flex-direction: column; min-width: 0; }\n .wg-name b { font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .wg-name small, .wg-mono small { color: #6f7c82; font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .wg-mono { font-family: 'JetBrains Mono', ui-monospace, Consolas, monospace; font-size: 12.5px; }\n .wg-cyan { color: #00e5ff; }\n .wg-rate span { display: flex; align-items: center; gap: 2px; white-space: nowrap; font-weight: 600; }\n .wg-rate span.dim { opacity: 0.4; }\n .wg-spark { display: flex; flex-direction: column; min-width: 0; }\n .wg-spark svg { display: block; background: rgba(255, 255, 255, 0.03); border-radius: 3px; }\n .wg-spark small { color: #6f7c82; font-size: 10.5px; white-space: nowrap; }\n .wg-sm { font-size: 12.5px; color: #b6c2c6; font-weight: 600; white-space: nowrap; }\n .wg-ka { display: flex; align-items: center; gap: 2px; color: #ffb74d; font-size: 10.5px; font-weight: 500; cursor: help; }\n .wg-chip { min-width: 78px; justify-content: center; }\n .wg-since { display: block; color: #6f7c82; font-size: 10.5px; margin-top: 2px; white-space: nowrap; }\n .wg-glow { filter: drop-shadow(0 0 6px currentColor); }\n\n /* event log */\n .wg-log { flex: 1 1 auto; min-height: 0; overflow-y: auto; padding-right: 2px; scrollbar-width: thin; scrollbar-color: rgba(0, 229, 255, 0.35) transparent; }\n .wg-ev { display: flex; align-items: center; gap: 10px; padding: 5px 4px; border-top: 1px solid rgba(255, 255, 255, 0.05); }\n .wg-ev-main { min-width: 0; flex: 1; }\n .wg-ev-title { font-size: 13.5px; }\n .wg-ago { white-space: nowrap; }\n .wg-tabs button { display: inline-flex; align-items: center; font-weight: 600; font-size: 13px; padding: 4px 12px; }\n\n /* 7 days */\n .wg-week { flex: 1 1 auto; min-height: 0; overflow: auto; scrollbar-width: thin; scrollbar-color: rgba(0, 229, 255, 0.35) transparent; }\n .wg-wk { display: grid; gap: 4px; align-items: center; min-width: 470px; }\n .wg-wk-h { text-align: center; color: #00e5ff; font-size: 11.5px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; padding-bottom: 2px; }\n .wg-wk-h.today { color: #fff; text-shadow: 0 0 8px #00e5ff; }\n .wg-wk-name { font-size: 12.5px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; }\n .wg-wk-c { height: 26px; border-radius: 5px; background: rgba(255, 255, 255, 0.04); display: flex; align-items: center; justify-content: center;\n font-size: 12px; font-weight: 700; transition: transform 0.15s; }\n .wg-wk-c:hover { transform: scale(1.08); }\n .wg-wk-s { text-align: center; font-size: 12px; font-weight: 700; }\n .wg-wk-s.up { color: #00e676; } .wg-wk-s.down { color: #ff5252; }\n .wg-wk-note { margin-top: 8px; }\n\n /* topology: orbiting satellites */\n .wg-topo { flex: 1 1 auto; min-height: 220px; position: relative; display: flex; align-items: center; justify-content: center; overflow: hidden;\n border-radius: 8px; background: radial-gradient(circle, rgba(0, 229, 255, 0.09) 0%, transparent 65%); }\n .wg-core { position: absolute; z-index: 5; width: 100px; height: 100px; display: flex; align-items: center; justify-content: center; }\n .wg-logo { z-index: 101; filter: drop-shadow(0 0 14px rgba(0, 229, 255, 0.95)); animation: wg-float 4s ease-in-out infinite; }\n .wg-core-pulse { position: absolute; inset: 0; border-radius: 50%; box-shadow: 0 0 25px rgba(0, 229, 255, 0.8); animation: wg-pulse 2s infinite alternate ease-in-out; }\n .wg-orbit { position: absolute; border: 1px dashed rgba(0, 229, 255, 0.28); border-radius: 50%; animation-name: wg-spin; animation-timing-function: linear;\n animation-iteration-count: infinite; box-shadow: inset 0 0 15px rgba(0, 229, 255, 0.03); }\n .wg-sat { position: absolute; top: -24px; left: calc(50% - 24px); width: 48px; height: 48px; display: flex; align-items: center; justify-content: center;\n animation-name: wg-antispin; animation-timing-function: linear; animation-iteration-count: infinite; }\n .wg-sat-ic { background: #0a0a0a; border-radius: 50%; padding: 4px; border: 1px solid rgba(255, 255, 255, 0.12); }\n .wg-sat-label { position: absolute; top: 38px; font-size: 10.5px; font-weight: 800; color: #fff; background: rgba(0, 0, 0, 0.82); padding: 2px 6px; border-radius: 4px;\n white-space: nowrap; border: 1px solid rgba(0, 229, 255, 0.35); box-shadow: 0 2px 5px rgba(0, 0, 0, 0.8); }\n .wg-sat-label em { font-style: normal; color: #00e676; font-weight: 600; }\n .wg-none { position: absolute; bottom: 16px; color: #ff5252; font-size: 12px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; }\n .wg-rest { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: 8px; font-size: 12px; flex-shrink: 0; }\n .wg-rest span { --c: #8a979c; color: var(--c); display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; }\n .wg-rest .v-icon { color: var(--c); }\n\n .wg-blink { animation: wg-blink 1.2s infinite; }\n .wg-seg { display: inline-flex; border: 1px solid #3a4347; border-radius: 6px; overflow: hidden; align-self: flex-start; }\n .wg-seg button { background: transparent; color: #b6c2c6; border: 0; padding: 4px 10px; font-size: 12.5px; cursor: pointer; }\n .wg-seg button + button { border-left: 1px solid #3a4347; }\n .wg-seg button[aria-pressed=\"true\"] { background: #00e5ff; color: #0a0a0a; font-weight: 600; }\n .wg-btn { display: inline-flex; align-items: center; background: transparent; color: #e8f1f2; border: 1px solid #3a4347; border-radius: 6px; padding: 6px 12px;\n font-size: 13px; cursor: pointer; white-space: nowrap; text-decoration: none; }\n .wg-btn:hover { border-color: #8a979c; }\n .wg-btn-primary { background: #00e5ff; border-color: #00e5ff; color: #0a0a0a; font-weight: 600; }\n .wg-link { justify-content: center; margin-top: 4px; }\n .wg-wrap button:focus-visible, .wg-wrap a:focus-visible { outline: 2px solid #fff; outline-offset: 1px; }\n .wg-icon-btn { background: transparent; border: 0; color: #8a979c; cursor: pointer; padding: 4px; border-radius: 6px; line-height: 0; }\n .wg-icon-btn:hover { color: #e8f1f2; background: rgba(255, 255, 255, 0.08); }\n .wg-overlay { position: absolute; inset: 0; z-index: 200; background: rgba(8, 10, 11, 0.9); display: flex; align-items: flex-start; justify-content: center; padding: 12px; overflow-y: auto; border-radius: 6px; }\n .wg-modal { width: min(480px, 100%); background: #121516; border: 1px solid #3a4347; border-radius: 12px; padding: 14px 18px; margin: auto 0; display: flex; flex-direction: column; }\n .wg-modal-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 10px; }\n .wg-modal-title { font-size: 19px; font-weight: 700; }\n .wg-field { display: flex; flex-direction: column; gap: 6px; margin-bottom: 12px; font-size: 13.5px; font-weight: 600; }\n .wg-field .wg-muted { font-weight: 400; }\n\n @keyframes wg-float { 0%, 100% { transform: translateY(0) scale(1); } 50% { transform: translateY(-6px) scale(1.05); filter: drop-shadow(0 0 30px rgba(0, 229, 255, 1)); } }\n @keyframes wg-pulse { 0% { transform: scale(0.95); opacity: 0.6; } 100% { transform: scale(1.15); opacity: 1; box-shadow: 0 0 55px rgba(0, 229, 255, 0.9); } }\n @keyframes wg-spin { to { transform: rotate(360deg); } }\n @keyframes wg-antispin { from { transform: rotate(360deg); } to { transform: rotate(0deg); } }\n @keyframes wg-blink { 50% { opacity: 0.5; } }\n @media (prefers-reduced-motion: reduce) { .wg-orbit, .wg-sat, .wg-logo, .wg-core-pulse, .wg-blink { animation: none; } }\n</style>\n","storeOutMessages":true,"passthru":false,"resendOnRefresh":true,"templateScope":"local","className":"","x":1120,"y":120,"wires":[["wgpublogic000001"]]},{"id":"wgpubtg000000001","type":"function","z":"wgpubtab00000001","name":"Telegram formatter → wire to your Telegram sender","func":"// @ts-nocheck\n// Telegram formatter: converts the notification to the format of the node-red-contrib-telegrambot \"sender\" node.\n// Wire its output to your own Telegram sender node. Chat ID: WG_TELEGRAM_CHATID (tab environment variable).\nconst chat = env.get(\"WG_TELEGRAM_CHATID\");\nif (!chat) { node.status({ fill: \"grey\", shape: \"ring\", text: \"WG_TELEGRAM_CHATID is not set\" }); return null; }\nnode.status({ fill: \"green\", shape: \"dot\", text: \"last: \" + new Date().toLocaleTimeString() });\nmsg.payload = { chatId: chat, type: \"message\", content: msg.payload };\nreturn msg;\n","outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1200,"y":200,"wires":[[]]},{"id":"wgpubdbg00000001","type":"debug","z":"wgpubtab00000001","name":"Notifications","active":true,"tosidebar":true,"console":false,"tostatus":true,"complete":"payload","targetType":"msg","statusVal":"payload","statusType":"auto","x":1120,"y":240,"wires":[]},{"id":"wgpubinj00000002","type":"inject","z":"wgpubtab00000001","name":"Start + hourly (cleanup)","props":[{"p":"topic","vt":"str"}],"repeat":"3600","crontab":"","once":true,"onceDelay":"8","topic":"cleanup","x":170,"y":180,"wires":[["wgpublogic000001"]]},{"id":"wgpubhttp0000001","type":"http in","z":"wgpubtab00000001","name":"Log download (GET /wireguard/export)","url":"/wireguard/export","method":"get","upload":false,"swaggerDoc":"","x":200,"y":280,"wires":[["wgpubcsv00000001"]]},{"id":"wgpubcsv00000001","type":"function","z":"wgpubtab00000001","name":"Log CSV","func":"// @ts-nocheck\n// Log download: GET /wireguard/export?type=events|daily&days=1..62&lang=en|hu[&token=...]\n// Returns CSV (semicolon separated, UTF-8 BOM) so Excel opens it directly in most locales.\nconst DEMO = env.get(\"WG_DEMO\") === true || env.get(\"WG_DEMO\") === \"true\";\nlet DIR = String(env.get(\"WG_DATA_DIR\") || \"/data/wireguard/\"); if (!DIR.endsWith(\"/\")) DIR += \"/\";\nconst PFX = DEMO ? \"wgdemo_\" : \"wg_\";\nconst STATE_FILE = DIR + PFX + \"state.json\", OLD_STATE_FILE = DIR + PFX + \"allapot.json\";\nconst TZ = String(env.get(\"WG_TZ\") || Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\");\nconst TOKEN = env.get(\"WG_EXPORT_TOKEN\") || \"\";\nconst q = msg.req.query || {};\nconst EN = q.lang ? q.lang === \"en\" : String(env.get(\"WG_LANG\") || \"en\").toLowerCase().startsWith(\"en\");\nfunction plain(code, text) { msg.statusCode = code; msg.headers = { \"Content-Type\": \"text/plain; charset=utf-8\" }; msg.payload = text; return msg; }\nif (TOKEN && q.token !== TOKEN) return plain(403, EN ? \"Invalid or missing token.\" : \"Hibás vagy hiányzó token.\");\nfunction fget(k) { try { return flow.get(k, \"memory\"); } catch (e) { return flow.get(k); } }\nlet S = fget(DEMO ? \"wg_S_demo\" : \"wg_S\");\nif (!S) { for (const f of [STATE_FILE, OLD_STATE_FILE]) { try { S = JSON.parse(fs.readFileSync(f, \"utf8\")); break; } catch (e) { S = null; } } }\nif (!S || S.v !== 1) return plain(503, EN ? \"The WireGuard logic has not started yet.\" : \"A WireGuard logika még nem indult el.\");\n\nconst T = EN ? {\n online: \"Online\", offline: \"Offline\", disabled: \"Disabled\", endpoint: \"Endpoint change\", router_down: \"Router not responding\", router_up: \"Router reachable again\",\n date: \"Date\", conn: \"Connections\", disc: \"Disconnections\", onmin: \" online (min)\", time: \"Time\", peer: \"Peer\", event: \"Event\", prev: \"Previous state\",\n prevLen: \"Previous state duration (min)\", detail: \"Details\", router: \"Router\", file: \"wireguard_\" } : {\n online: \"Online\", offline: \"Offline\", disabled: \"Letiltva\", endpoint: \"Címváltás\", router_down: \"A router nem válaszol\", router_up: \"A router újra elérhető\",\n date: \"Dátum\", conn: \"Csatlakozás\", disc: \"Lecsatlakozás\", onmin: \" online (perc)\", time: \"Időpont\", peer: \"Kapcsolat\", event: \"Esemény\", prev: \"Előző állapot\",\n prevLen: \"Előző állapot hossza (perc)\", detail: \"Részletek\", router: \"Router\", file: \"wireguard_\" };\nconst type = (q.type === \"daily\" || q.type === \"napi\") ? \"daily\" : \"events\";\nconst days = Math.min(62, Math.max(1, parseInt(q.days, 10) || 7));\nfunction parts(ts) {\n const o = {};\n new Intl.DateTimeFormat(\"en-GB\", { timeZone: TZ, year: \"numeric\", month: \"2-digit\", day: \"2-digit\",\n hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\", hourCycle: \"h23\" }).formatToParts(new Date(ts)).forEach(x => o[x.type] = x.value);\n return o;\n}\nconst dayKey = (ts) => { const o = parts(ts); return o.year + \"-\" + o.month + \"-\" + o.day; };\nconst stamp = (ts) => { const o = parts(ts); return EN ? o.year + \"-\" + o.month + \"-\" + o.day + \" \" + o.hour + \":\" + o.minute + \":\" + o.second\n : o.year + \".\" + o.month + \".\" + o.day + \". \" + o.hour + \":\" + o.minute + \":\" + o.second; };\nconst cell = (v) => { const s = v === null || v === undefined ? \"\" : String(v); return /[\";\\n]/.test(s) ? '\"' + s.replace(/\"/g, '\"\"') + '\"' : s; };\nconst now = Date.now(), dayList = [];\nfor (let i = days - 1; i >= 0; i--) dayList.push(dayKey(now - i * 86400000));\n\nconst rows = [];\nif (type === \"daily\") {\n const names = {};\n dayList.forEach(k => { const d = S.days[k]; if (d) Object.keys(d.on || {}).forEach(n => { names[n] = true; }); });\n Object.values(S.peers || {}).forEach(p => { names[p.name] = true; });\n const list = Object.keys(names).sort((a, b) => a.localeCompare(b, EN ? \"en\" : \"hu\"));\n rows.push([T.date, T.conn, T.disc].concat(list.map(n => n + T.onmin)));\n dayList.forEach(k => {\n const d = S.days[k];\n if (d) rows.push([EN ? k : k.replace(/-/g, \".\"), d.up || 0, d.down || 0].concat(list.map(n => Math.round(((d.on || {})[n] || 0) / 60000))));\n });\n} else {\n rows.push([T.time, T.peer, T.event, T.prev, T.prevLen, T.detail, T.router]);\n const ev = [];\n dayList.forEach(k => {\n let txt = \"\";\n try { txt = fs.readFileSync(DIR + PFX + k + \".ndjson\", \"utf8\"); } catch (e) { return; }\n txt.split(\"\\n\").forEach(l => { if (l.trim()) { try { ev.push(JSON.parse(l)); } catch (err) { } } });\n });\n ev.sort((a, b) => a.t - b.t).forEach(e => {\n const detail = e.k === \"endpoint\" ? (e.from + \" → \" + e.to) : (e.err || \"\");\n const isState = e.k === \"online\" || e.k === \"offline\" || e.k === \"disabled\";\n rows.push([stamp(e.t), e.peer, T[e.k] || e.k, isState ? (T[e.from] || e.from || \"\") : \"\", e.dur ? Math.round(e.dur / 60000) : \"\", detail, e.r || \"\"]);\n });\n}\nmsg.statusCode = 200;\nmsg.headers = { \"Content-Type\": \"text/csv; charset=utf-8\", \"Content-Disposition\": 'attachment; filename=\"' + T.file + (DEMO ? \"demo_\" : \"\") + type + \"_\" + dayKey(now) + '.csv\"', \"Cache-Control\": \"no-store\" };\nmsg.payload = \"\" + rows.map(r => r.map(cell).join(\";\")).join(\"\\r\\n\") + \"\\r\\n\";\nreturn msg;\n","outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[{"var":"fs","module":"fs"}],"x":470,"y":280,"wires":[["wgpubresp0000001"]]},{"id":"wgpubresp0000001","type":"http response","z":"wgpubtab00000001","name":"","statusCode":"","headers":{},"x":650,"y":280,"wires":[]},{"id":"wgpubcmt00000002","type":"comment","z":"wgpubtab00000001","name":"② SSH key: press 1, add the Debug line to the router, then press 2","info":"See the tab description and README for the router side.","x":260,"y":360,"wires":[]},{"id":"wgpubinj00000003","type":"inject","z":"wgpubtab00000001","name":"1. Create SSH key","props":[{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"keygen","x":150,"y":410,"wires":[["wgpubssh00000001"]]},{"id":"wgpubinj00000004","type":"inject","z":"wgpubtab00000001","name":"2. Test connection","props":[{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"test","x":150,"y":450,"wires":[["wgpubssh00000001"]]},{"id":"wgpubssh00000001","type":"function","z":"wgpubtab00000001","name":"SSH key helper","func":"// @ts-nocheck\n// ===== SSH key helper =====\n// topic \"keygen\": creates the key pair (if it does not exist yet) and prints the line to add to the router in the Debug panel\n// topic \"test\": tries the connection to every router\nfunction envJson(name, def) {\n let v = env.get(name);\n if (v === undefined || v === null || v === \"\") return def;\n if (typeof v === \"string\") { try { v = JSON.parse(v); } catch (e) { return def; } }\n return v;\n}\nconst HU = String(env.get(\"WG_LANG\") || \"en\").toLowerCase().startsWith(\"hu\");\nconst q = (s) => \"'\" + String(s).replace(/'/g, \"'\\\\''\") + \"'\";\nlet DIR = String(env.get(\"WG_DATA_DIR\") || \"/data/wireguard/\"); if (!DIR.endsWith(\"/\")) DIR += \"/\";\nconst KEY = String(env.get(\"WG_SSH_KEY\") || (DIR + \"ssh/wg_monitor\"));\nconst KEYDIR = KEY.replace(/\\/[^/]*$/, \"\") || \"/\";\nconst KNOWN = DIR + \"ssh/known_hosts\";\nconst TMPKEY = \"/tmp/wg_monitor_key\";\n\nif (msg.topic === \"keygen\") {\n msg.payload = \"mkdir -p \" + q(KEYDIR) + \" \" + q(DIR + \"ssh\") + \" && \" +\n \"( [ -f \" + q(KEY) + \" ] && echo \" + q(HU ? \"A kulcs már létezik, nem írom felül.\" : \"The key already exists, not overwriting it.\") + \" || ssh-keygen -q -t ed25519 -N '' -C wg-monitor -f \" + q(KEY) + \" ) && \" +\n \"chmod 600 \" + q(KEY) + \" 2>/dev/null; rm -f \" + TMPKEY + \"; echo; echo \" + q(HU ? \"=== Ezt a sort másold a routerbe ===\" : \"=== Add this line to the router ===\") + \"; \" +\n \"echo \\\"command=\\\\\\\"wg show all dump\\\\\\\",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty $(cat \" + q(KEY + \".pub\") + \")\\\"\";\n return msg;\n}\nif (msg.topic === \"test\") {\n const out = [];\n (envJson(\"WG_ROUTERS\", []) || []).forEach((r, i) => {\n if (r.mode === \"local\") { out.push({ topic: \"test\", payload: \"echo 'Local mode:'; wg show interfaces && echo OK\" }); return; }\n const host = String(r.host || \"\"), user = String(r.user || \"root\"), port = parseInt(r.port, 10) || 22;\n out.push({ topic: \"test\", payload:\n \"echo \" + q(\"--- \" + (r.name || host) + \" (\" + user + \"@\" + host + \") ---\") + \"; \" +\n \"cp \" + q(KEY) + \" \" + TMPKEY + \" && chmod 600 \" + TMPKEY + \" && \" +\n \"ssh -i \" + TMPKEY + \" -p \" + port + \" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new\" +\n \" -o UserKnownHostsFile=\" + q(KNOWN) + \" \" + q(user + \"@\" + host) + \" 'wg show all dump' > /tmp/wg_test.txt && \" +\n \"awk -F'\\\\t' 'NF==5{print \\\"\" + (HU ? \"Interfész: \" : \"Interface: \") + \"\\\" $1} NF>=8{n++} END{print \\\"\" + (HU ? \"Peerek száma: \" : \"Peers: \") + \"\\\" n+0}' /tmp/wg_test.txt && rm -f /tmp/wg_test.txt && echo \" + q(HU ? \"RENDBEN: a kapcsolat működik.\" : \"OK: the connection works.\") });\n });\n if (!out.length) { node.warn(HU ? \"Nincs router a WG_ROUTERS változóban.\" : \"No router in WG_ROUTERS.\"); return null; }\n return [out];\n}\nreturn null;\n","outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[],"x":360,"y":430,"wires":[["wgpubexec0000002"]]},{"id":"wgpubexec0000002","type":"exec","z":"wgpubtab00000001","command":"env","addpay":"payload","append":"","useSpawn":"false","timer":"30","winHide":false,"oldrc":false,"name":"run command","x":550,"y":430,"wires":[["wgpubdbg00000002"],["wgpubdbg00000002"],["wgpubdbg00000003"]]},{"id":"wgpubdbg00000002","type":"debug","z":"wgpubtab00000001","name":"SSH helper output","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":770,"y":410,"wires":[]},{"id":"wgpubdbg00000003","type":"debug","z":"wgpubtab00000001","name":"SSH helper exit code","active":true,"tosidebar":true,"console":false,"tostatus":true,"complete":"payload","targetType":"msg","statusVal":"payload.code","statusType":"msg","x":780,"y":450,"wires":[]},{"id":"wgpubgroup000001","type":"ui-group","name":"WireGuard","page":"wgpubpage0000001","width":12,"height":1,"order":1,"showTitle":false,"className":"","visible":"true","disabled":"false","groupType":"default"},{"id":"wgpubpage0000001","type":"ui-page","name":"WireGuard","ui":"wgpubbase0000001","path":"/wireguard","icon":"vpn","layout":"grid","theme":"wgpubtheme000001","breakpoints":[{"name":"Default","px":"0","cols":"3"},{"name":"Tablet","px":"576","cols":"6"},{"name":"Small Desktop","px":"768","cols":"9"},{"name":"Desktop","px":"1024","cols":"12"}],"order":1,"className":"","visible":"true","disabled":"false"},{"id":"wgpubbase0000001","type":"ui-base","name":"Dashboard","path":"/dashboard","appIcon":"","includeClientData":true,"acceptsClientConfig":["ui-notification","ui-control"],"showPathInSidebar":false,"headerContent":"page","navigationStyle":"default","titleBarStyle":"default","showReconnectNotification":true,"notificationDisplayTime":1,"showDisconnectNotification":true,"allowInstall":false},{"id":"wgpubtheme000001","type":"ui-theme","name":"WireGuard dark","colors":{"surface":"#1a1a1a","primary":"#00e5ff","bgPage":"#0a0a0a","groupBg":"#141414","groupOutline":"#00e5ff"},"sizes":{"density":"default","pagePadding":"12px","groupGap":"12px","groupBorderRadius":"4px","widgetGap":"12px"}}]