node-server-lens 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/package.json +1 -1
- package/public/index.html +9 -34
- package/public/login.html +113 -0
- package/src/dashboard.js +86 -6
package/README.md
CHANGED
|
@@ -120,7 +120,7 @@ Always review the changes before you commit them.
|
|
|
120
120
|
| **API Endpoints** | Every route with calls, share of traffic, avg / p95 / max latency, errors and last call. Sorted by **most called**; also by slowest, most errors, recently called or name. `/users/42` and `/users/43` are grouped as `/users/:id`. |
|
|
121
121
|
| **Requests** | The latest requests with method, path, status, duration and client IP. Search and an "errors only" filter. |
|
|
122
122
|
|
|
123
|
-
Also included: a `/health` endpoint for load balancers,
|
|
123
|
+
Also included: a styled sign-in page with 7-day sessions and a sign-out button, a `/health` endpoint for load balancers, uptime checks with down/recovery alerts in the logs, auto-reconnect, and a mobile layout.
|
|
124
124
|
|
|
125
125
|
## 🧭 How it works
|
|
126
126
|
|
|
@@ -394,7 +394,7 @@ Serverless platforms (Vercel functions, AWS Lambda) aren't a good fit for the **
|
|
|
394
394
|
| Option | Default | Description |
|
|
395
395
|
| --- | --- | --- |
|
|
396
396
|
| `path` | `'/server-lens'` | Where the embedded dashboard is served |
|
|
397
|
-
| `auth` | none | `{ username, password }`
|
|
397
|
+
| `auth` | none | `{ username, password }` shows the sign-in page; or `(req) => boolean` to plug in your own auth |
|
|
398
398
|
| `dashboard` | `true` | `false` turns off the embedded dashboard (hub reporting only) |
|
|
399
399
|
| `hub` | none | `{ url, key, id?, name?, interval? }` to report to a hub |
|
|
400
400
|
| `name` | hostname | Display name |
|
|
@@ -445,7 +445,8 @@ Paths are relative to the dashboard: `/server-lens` for the agent, `/` for the h
|
|
|
445
445
|
## 🔒 Security
|
|
446
446
|
|
|
447
447
|
- **Turn on the login** (`auth`, or `SERVER_LENS_USER` + `SERVER_LENS_PASS` on the hub). Logs and server details can contain sensitive data. The agent prints a warning when `NODE_ENV=production` and no login is set.
|
|
448
|
-
- **
|
|
448
|
+
- **How sign-in works:** a sign-in page (not the browser's pop-up) creates a signed, `HttpOnly`, `SameSite=Strict` session cookie that lasts 7 days (`Secure` on HTTPS). Sessions survive restarts; changing the password signs everyone out. After 10 wrong attempts from one IP, sign-in is paused for 15 minutes. Scripts and `curl` can still use HTTP Basic auth.
|
|
449
|
+
- **Use HTTPS** in front of the hub, because the session cookie and the ingest key travel in request headers.
|
|
449
450
|
- The ingest key is checked in constant time. Payloads are size-limited (4 MB), validated and truncated, and the number of tracked routes is capped so URL scanners can't use up memory.
|
|
450
451
|
- The live connection needs a random per-process token that only appears in the logged-in page.
|
|
451
452
|
- Uptime checks make the hub request URLs that logged-in users enter. Only give dashboard access to people you trust.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "node-server-lens",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Self-hosted, real-time monitoring for all your servers: live logs over WebSocket, request traffic with week/month/year history, API stats, uptime checks. Express, Next.js, any Node server, or any language over HTTP.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"bin": {
|
package/public/index.html
CHANGED
|
@@ -272,6 +272,7 @@ button.who[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
272
272
|
.menu-add:hover{color:var(--text);border-color:rgba(255,255,255,.25)}
|
|
273
273
|
.dot.down,.dot.offline{background:var(--red)} .dot.pending{background:var(--dim)} .dot.degraded{background:var(--amber)}
|
|
274
274
|
dialog{margin:auto;width:min(680px,calc(100% - 32px));max-height:calc(100% - 32px);border-radius:24px;border:1px solid var(--line2);background:linear-gradient(180deg,#1b1b1e,#151517);color:var(--text);padding:30px 32px;box-shadow:0 40px 80px rgba(0,0,0,.6)}
|
|
275
|
+
dialog:focus,dialog:focus-visible{outline:none}
|
|
275
276
|
dialog::backdrop{background:rgba(0,0,0,.6);backdrop-filter:blur(4px)}
|
|
276
277
|
dialog h3{font-weight:300;font-size:28px;letter-spacing:-.02em;margin-bottom:6px}
|
|
277
278
|
dialog .seg{display:inline-flex;margin:18px 0 20px;flex-wrap:wrap}
|
|
@@ -282,14 +283,6 @@ dialog input.in{width:100%;padding:12px 16px;border-radius:14px;border:1px solid
|
|
|
282
283
|
dialog input.in:focus{border-color:rgba(211,127,246,.6)}
|
|
283
284
|
.btn.primary{background:linear-gradient(180deg,#e09cff,#b866e6);color:#160a1c;border:0;font-weight:500}
|
|
284
285
|
.dlg-foot{display:flex;justify-content:flex-end;gap:10px;margin-top:22px}
|
|
285
|
-
.onboard-only{display:none}
|
|
286
|
-
#addDlg.onboard .onboard-only{display:flex}
|
|
287
|
-
#addDlg.onboard [data-close]{display:none}
|
|
288
|
-
.welcome{align-items:center;gap:8px;color:var(--green);font-size:14px;margin-bottom:10px}
|
|
289
|
-
.onboard-foot{align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-top:24px;padding-top:20px;border-top:1px solid var(--line)}
|
|
290
|
-
.onboard-foot .muted{display:flex;align-items:center;gap:10px;font-size:14px}
|
|
291
|
-
.dot.wait{animation:blink 1.4s ease-in-out infinite}
|
|
292
|
-
@keyframes blink{50%{opacity:.25}}
|
|
293
286
|
.formerr{color:var(--red);font-size:14px;margin-top:10px;min-height:1em}
|
|
294
287
|
@media (max-width:1280px){.kpis{grid-template-columns:repeat(2,minmax(0,1fr))}.row2,.srv{grid-template-columns:minmax(0,1fr)}}
|
|
295
288
|
@media (max-width:900px){
|
|
@@ -344,7 +337,8 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
|
|
|
344
337
|
<a href="#/requests" data-page="requests"><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><path d="M21 3 3 10.5l7 2.5 2.5 7z"/></svg>Requests</a>
|
|
345
338
|
</nav>
|
|
346
339
|
<div class="side-bottom">
|
|
347
|
-
<nav class="nav"><a href="https://github.com/Sathishram2000/Node-Server-Lens#readme" target="_blank" rel="noopener"><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><path d="M6 3h9l4 4v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z"/><path d="M8 12h8M8 16h5" stroke="#0b0b0c" stroke-width="1.8" stroke-linecap="round"/></svg>Documentation</a
|
|
340
|
+
<nav class="nav"><a href="https://github.com/Sathishram2000/Node-Server-Lens#readme" target="_blank" rel="noopener"><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><path d="M6 3h9l4 4v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z"/><path d="M8 12h8M8 16h5" stroke="#0b0b0c" stroke-width="1.8" stroke-linecap="round"/></svg>Documentation</a>
|
|
341
|
+
<form id="signOut" method="post" hidden><button class="grp" type="submit"><span><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" opacity=".85"><path d="M15 4h3a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-3M10 16l-4-4 4-4M6 12h10"/></svg>Sign out</span></button></form></nav>
|
|
348
342
|
<hr>
|
|
349
343
|
<div class="help">
|
|
350
344
|
<h4>Like Server Lens?</h4>
|
|
@@ -467,9 +461,8 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
|
|
|
467
461
|
</div>
|
|
468
462
|
|
|
469
463
|
<dialog id="addDlg">
|
|
470
|
-
<
|
|
471
|
-
<
|
|
472
|
-
<p class="muted" id="dlgSub">Pick how this server should report to the hub.</p>
|
|
464
|
+
<h3>Connect a server</h3>
|
|
465
|
+
<p class="muted">Pick how this server should report to the hub.</p>
|
|
473
466
|
<div class="seg" id="addTabs"><button data-t="node" class="on">Node.js / Express</button><button data-t="next">Next.js</button><button data-t="url">Any URL</button><button data-t="api">Other languages</button></div>
|
|
474
467
|
<div data-p="node">
|
|
475
468
|
<div class="step">1 · Install the agent</div><pre>npm install node-server-lens</pre>
|
|
@@ -494,10 +487,6 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
|
|
|
494
487
|
<pre id="snipApi"></pre>
|
|
495
488
|
</div>
|
|
496
489
|
<div class="dlg-foot" id="dlgFoot"><button class="btn" data-close>Done</button></div>
|
|
497
|
-
<div class="onboard-only onboard-foot">
|
|
498
|
-
<span class="muted"><span class="dot pending wait"></span>Waiting for your first server… this closes by itself once it reports in.</span>
|
|
499
|
-
<a class="btn primary" href="https://github.com/Sathishram2000/Node-Server-Lens#-connect-your-servers" target="_blank" rel="noopener">Open setup guide <svg><use href="#i-right"/></svg></a>
|
|
500
|
-
</div>
|
|
501
490
|
</dialog>
|
|
502
491
|
|
|
503
492
|
<script>
|
|
@@ -829,6 +818,8 @@ function route() {
|
|
|
829
818
|
if (p === 'logs') box.scrollTop = box.scrollHeight;
|
|
830
819
|
}
|
|
831
820
|
addEventListener('hashchange', route);
|
|
821
|
+
if (CFG.signOut) { $('signOut').hidden = false; $('signOut').action = `${CFG.base}/logout`; }
|
|
822
|
+
|
|
832
823
|
/* ---------- server switcher ---------- */
|
|
833
824
|
const menu = $('srvMenu');
|
|
834
825
|
function toggleMenu(open = menu.hidden) {
|
|
@@ -917,22 +908,7 @@ $('addTabs').addEventListener('click', (e) => {
|
|
|
917
908
|
$('addDlg').querySelectorAll('[data-p]').forEach((p) => (p.hidden = p.dataset.p !== b.dataset.t));
|
|
918
909
|
$('dlgFoot').hidden = b.dataset.t === 'url';
|
|
919
910
|
});
|
|
920
|
-
$('addDlg').addEventListener('click', (e) => { if (
|
|
921
|
-
$('addDlg').addEventListener('cancel', (e) => { if (onboarding) e.preventDefault(); }); // Escape can't dismiss first-run setup
|
|
922
|
-
|
|
923
|
-
/* ---------- first run: nothing connected yet ---------- */
|
|
924
|
-
let onboarding = false;
|
|
925
|
-
function checkOnboarding(s) {
|
|
926
|
-
const none = CFG.hub && s.servers && s.servers.every((x) => x.id === 'hub');
|
|
927
|
-
if (none === onboarding) return;
|
|
928
|
-
onboarding = none;
|
|
929
|
-
const d = $('addDlg');
|
|
930
|
-
d.classList.toggle('onboard', none);
|
|
931
|
-
$('dlgTitle').textContent = none ? 'Connect your first server' : 'Connect a server';
|
|
932
|
-
$('dlgSub').textContent = none ? 'Nothing is reporting to this hub yet. Pick your stack below, or open the setup guide for every option.' : 'Pick how this server should report to the hub.';
|
|
933
|
-
if (none) { toggleMenu(false); if (!d.open) d.showModal(); }
|
|
934
|
-
else { if (d.open) d.close(); const first = s.servers.find((x) => x.id !== 'hub'); if (first && s.id === 'hub') select(first.id); } // jump to the server that just connected
|
|
935
|
-
}
|
|
911
|
+
$('addDlg').addEventListener('click', (e) => { if (e.target.closest('[data-close]') || e.target === $('addDlg')) $('addDlg').close(); });
|
|
936
912
|
$('urlForm').addEventListener('submit', async (e) => {
|
|
937
913
|
e.preventDefault();
|
|
938
914
|
$('mErr').textContent = '';
|
|
@@ -947,7 +923,6 @@ function apply(s) {
|
|
|
947
923
|
if (snap && snap.id !== s.id) { ipsKey = ''; hoverIdx = null; }
|
|
948
924
|
snap = s;
|
|
949
925
|
renderFleet(s);
|
|
950
|
-
checkOnboarding(s);
|
|
951
926
|
renderHeader(s); renderTraffic(); renderDonut(s); renderServer(s); renderApis(); renderRecent();
|
|
952
927
|
}
|
|
953
928
|
function setConn(on, txt) {
|
|
@@ -969,7 +944,7 @@ function connect() {
|
|
|
969
944
|
setConn(false, 'Reconnecting…');
|
|
970
945
|
retry++;
|
|
971
946
|
// server restarted → our token is stale; reload once the server answers again
|
|
972
|
-
if (retry > 2) fetch(API, { cache: 'no-store' }).then((r) => { if (r.ok) location.reload(); }).catch(() => {});
|
|
947
|
+
if (retry > 2) fetch(API, { cache: 'no-store' }).then((r) => { if (r.ok || r.status === 401) location.reload(); }) // 401: session expired → login page.catch(() => {});
|
|
973
948
|
setTimeout(connect, Math.min(10000, 500 * 2 ** retry));
|
|
974
949
|
};
|
|
975
950
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
6
|
+
<title>Sign in · Server Lens</title>
|
|
7
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
8
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
9
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap" rel="stylesheet">
|
|
10
|
+
<style>
|
|
11
|
+
:root{
|
|
12
|
+
--line:rgba(255,255,255,.075);--line2:rgba(255,255,255,.12);--text:#f2f2f4;--muted:#8c8c93;
|
|
13
|
+
--purple:#d37ff6;--lime:#c2ec44;--red:#ff5d72;--redbg:rgba(255,80,100,.13);
|
|
14
|
+
--noise:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='3' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
|
|
15
|
+
}
|
|
16
|
+
*{box-sizing:border-box;margin:0;padding:0}
|
|
17
|
+
body{
|
|
18
|
+
min-height:100vh;display:grid;place-items:center;padding:24px 16px;
|
|
19
|
+
font-family:'Inter',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;font-weight:300;color:var(--text);-webkit-font-smoothing:antialiased;
|
|
20
|
+
background:radial-gradient(1100px 700px at 90% 110%,#262629 0%,transparent 60%),radial-gradient(800px 500px at 10% -10%,#1a1a1d 0%,transparent 60%),#0b0b0c;
|
|
21
|
+
}
|
|
22
|
+
body::after{content:"";position:fixed;inset:0;background:var(--noise);opacity:.07;pointer-events:none;mix-blend-mode:overlay}
|
|
23
|
+
.card{
|
|
24
|
+
position:relative;width:min(420px,100%);padding:40px 36px 34px;border-radius:28px;border:1px solid var(--line);
|
|
25
|
+
background:linear-gradient(180deg,rgba(255,255,255,.045),rgba(255,255,255,.012));
|
|
26
|
+
box-shadow:inset 0 1px 0 rgba(255,255,255,.05),0 40px 80px -30px rgba(0,0,0,.8);
|
|
27
|
+
}
|
|
28
|
+
.card::after{content:"";position:absolute;inset:0;border-radius:inherit;background:var(--noise);opacity:.09;mix-blend-mode:overlay;pointer-events:none}
|
|
29
|
+
.logo{display:flex;align-items:center;gap:12px;font-size:22px;font-weight:400;letter-spacing:-.02em;margin-bottom:34px}
|
|
30
|
+
.logo svg{width:30px;height:30px}
|
|
31
|
+
h1{font-weight:300;font-size:32px;letter-spacing:-.025em;margin-bottom:8px}
|
|
32
|
+
.sub{color:var(--muted);font-size:15px;margin-bottom:28px}
|
|
33
|
+
label{display:block;color:var(--muted);font-size:14px;margin:0 0 8px}
|
|
34
|
+
.field{position:relative;margin-bottom:18px}
|
|
35
|
+
input{
|
|
36
|
+
width:100%;padding:14px 18px;border-radius:16px;border:1px solid var(--line2);background:rgba(0,0,0,.28);
|
|
37
|
+
color:var(--text);font:inherit;font-size:16px;font-weight:400;outline:0;transition:border-color .15s,box-shadow .15s;
|
|
38
|
+
}
|
|
39
|
+
input:focus{border-color:rgba(211,127,246,.65);box-shadow:0 0 0 4px rgba(211,127,246,.12)}
|
|
40
|
+
.field input[type=password],.field input.pw{padding-right:72px}
|
|
41
|
+
.show{position:absolute;right:10px;bottom:9px;padding:6px 10px;border-radius:10px;border:0;background:rgba(255,255,255,.06);color:var(--muted);font:inherit;font-size:13px;cursor:pointer}
|
|
42
|
+
.show:hover{color:var(--text)}
|
|
43
|
+
.err{display:none;align-items:center;gap:8px;padding:11px 14px;border-radius:12px;background:var(--redbg);color:var(--red);font-size:14px;margin:4px 0 16px}
|
|
44
|
+
.err.on{display:flex}
|
|
45
|
+
button.go{
|
|
46
|
+
width:100%;margin-top:8px;padding:14px;border:0;border-radius:999px;cursor:pointer;
|
|
47
|
+
background:linear-gradient(180deg,#e9aaff,#b866e6);color:#160a1c;font:inherit;font-size:16px;font-weight:500;
|
|
48
|
+
box-shadow:0 10px 30px -10px rgba(214,128,250,.7);transition:filter .15s,transform .1s;
|
|
49
|
+
}
|
|
50
|
+
button.go:hover{filter:brightness(1.06)}
|
|
51
|
+
button.go:active{transform:translateY(1px)}
|
|
52
|
+
button.go[disabled]{opacity:.6;cursor:wait}
|
|
53
|
+
.foot{display:flex;align-items:center;gap:8px;justify-content:center;color:var(--muted);font-size:13px;margin-top:22px}
|
|
54
|
+
.dot{width:7px;height:7px;border-radius:50%;background:#4fd16b}
|
|
55
|
+
:focus-visible{outline:2px solid var(--purple);outline-offset:2px}
|
|
56
|
+
@media (prefers-reduced-motion:reduce){*{transition:none!important}}
|
|
57
|
+
</style>
|
|
58
|
+
</head>
|
|
59
|
+
<body>
|
|
60
|
+
<main class="card">
|
|
61
|
+
<div class="logo">
|
|
62
|
+
<svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="12.5" fill="none" stroke="#c2ec44" stroke-width="5"/><circle cx="16" cy="16" r="4.5" fill="#f2f2f4"/></svg>
|
|
63
|
+
<span id="title">Server Lens</span>
|
|
64
|
+
</div>
|
|
65
|
+
<h1>Welcome back</h1>
|
|
66
|
+
<p class="sub">Sign in to view your servers.</p>
|
|
67
|
+
<form id="f" method="post" action="__SL_LOGIN__" novalidate>
|
|
68
|
+
<div class="err" id="err" role="alert"></div>
|
|
69
|
+
<div class="field">
|
|
70
|
+
<label for="u">Username</label>
|
|
71
|
+
<input id="u" name="username" autocomplete="username" autocapitalize="off" spellcheck="false" required autofocus>
|
|
72
|
+
</div>
|
|
73
|
+
<div class="field">
|
|
74
|
+
<label for="p">Password</label>
|
|
75
|
+
<input id="p" name="password" type="password" class="pw" autocomplete="current-password" required>
|
|
76
|
+
<button type="button" class="show" id="show" aria-label="Show password">Show</button>
|
|
77
|
+
</div>
|
|
78
|
+
<button class="go" id="go">Sign in</button>
|
|
79
|
+
</form>
|
|
80
|
+
<div class="foot"><span class="dot"></span>Secure session · stays signed in for 7 days</div>
|
|
81
|
+
</main>
|
|
82
|
+
<script>
|
|
83
|
+
(() => {
|
|
84
|
+
const CFG = __SL_CONFIG__;
|
|
85
|
+
document.getElementById('title').textContent = CFG.title;
|
|
86
|
+
document.title = 'Sign in · ' + CFG.title;
|
|
87
|
+
const f = document.getElementById('f'), err = document.getElementById('err'), go = document.getElementById('go'), p = document.getElementById('p');
|
|
88
|
+
const fail = (m) => { err.textContent = m; err.classList.add('on'); };
|
|
89
|
+
if (CFG.error) fail(CFG.error);
|
|
90
|
+
document.getElementById('show').addEventListener('click', (e) => {
|
|
91
|
+
const on = p.type === 'password';
|
|
92
|
+
p.type = on ? 'text' : 'password';
|
|
93
|
+
e.currentTarget.textContent = on ? 'Hide' : 'Show';
|
|
94
|
+
e.currentTarget.setAttribute('aria-label', on ? 'Hide password' : 'Show password');
|
|
95
|
+
});
|
|
96
|
+
f.addEventListener('submit', async (e) => {
|
|
97
|
+
e.preventDefault();
|
|
98
|
+
err.classList.remove('on');
|
|
99
|
+
if (!f.username.value || !p.value) return fail('Enter your username and password.');
|
|
100
|
+
go.disabled = true; go.textContent = 'Signing in…';
|
|
101
|
+
try {
|
|
102
|
+
const r = await fetch(CFG.login, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: f.username.value, password: p.value }), credentials: 'same-origin' });
|
|
103
|
+
if (r.ok) return location.replace(CFG.next);
|
|
104
|
+
const out = await r.json().catch(() => ({}));
|
|
105
|
+
fail(out.error || 'Sign in failed.');
|
|
106
|
+
p.select();
|
|
107
|
+
} catch { fail('Cannot reach the server. Try again.'); }
|
|
108
|
+
go.disabled = false; go.textContent = 'Sign in';
|
|
109
|
+
});
|
|
110
|
+
})();
|
|
111
|
+
</script>
|
|
112
|
+
</body>
|
|
113
|
+
</html>
|
package/src/dashboard.js
CHANGED
|
@@ -6,6 +6,9 @@ const crypto = require('crypto');
|
|
|
6
6
|
const { WebSocketServer } = require('ws');
|
|
7
7
|
|
|
8
8
|
const HTML = fs.readFileSync(path.join(__dirname, '..', 'public', 'index.html'), 'utf8');
|
|
9
|
+
const LOGIN = fs.readFileSync(path.join(__dirname, '..', 'public', 'login.html'), 'utf8');
|
|
10
|
+
const SESSION_DAYS = 7;
|
|
11
|
+
const MAX_FAILS = 10, FAIL_WINDOW = 15 * 60 * 1000;
|
|
9
12
|
const hash = (s) => crypto.createHash('sha256').update(String(s)).digest();
|
|
10
13
|
const safeEqual = (a, b) => crypto.timingSafeEqual(hash(a), hash(b));
|
|
11
14
|
|
|
@@ -28,12 +31,66 @@ function createDashboard({ base, title = 'Server Lens', auth, interval = 2000, h
|
|
|
28
31
|
|
|
29
32
|
const send = (ws, msg) => { try { ws.send(JSON.stringify(msg)); } catch { /* socket gone */ } };
|
|
30
33
|
|
|
34
|
+
// Sessions: a signed "expiry.signature" cookie. The key comes from the credentials, so sessions
|
|
35
|
+
// survive restarts and changing the password signs everyone out.
|
|
36
|
+
const login = auth && typeof auth === 'object';
|
|
37
|
+
const key = login ? hash(`server-lens-session:${base}:${auth.username}:${auth.password}`) : null;
|
|
38
|
+
const sign = (v) => crypto.createHmac('sha256', key).update(String(v)).digest('base64url');
|
|
39
|
+
const cookieName = login ? 'sl_' + sign('cookie-name').slice(0, 10) : '';
|
|
40
|
+
const fails = new Map(); // ip -> { n, first }
|
|
41
|
+
|
|
42
|
+
function validSession(req) {
|
|
43
|
+
const m = (req.headers.cookie || '').match(new RegExp(`(?:^|;\\s*)${cookieName}=([^;]+)`));
|
|
44
|
+
if (!m) return false;
|
|
45
|
+
const [exp, sig] = decodeURIComponent(m[1]).split('.');
|
|
46
|
+
return Number(exp) > Date.now() && !!sig && safeEqual(sig, sign(exp));
|
|
47
|
+
}
|
|
48
|
+
|
|
31
49
|
function authorized(req) {
|
|
32
50
|
if (!auth) return true;
|
|
33
51
|
if (typeof auth === 'function') return !!auth(req);
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
return safeEqual(Buffer.from(h.slice(6), 'base64').toString(), `${auth.username}:${auth.password}`);
|
|
52
|
+
if (validSession(req)) return true;
|
|
53
|
+
const h = req.headers.authorization || ''; // Basic auth still works for curl / scripts
|
|
54
|
+
return h.startsWith('Basic ') && safeEqual(Buffer.from(h.slice(6), 'base64').toString(), `${auth.username}:${auth.password}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function cookie(req, value, maxAge) {
|
|
58
|
+
const secure = req.socket.encrypted || String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim() === 'https';
|
|
59
|
+
return `${cookieName}=${value}; Path=${base || '/'}; Max-Age=${maxAge}; HttpOnly; SameSite=Strict${secure ? '; Secure' : ''}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function loginPage(res, code, error) {
|
|
63
|
+
const cfg = JSON.stringify({ title, login: `${base}/login`, next: `${base}/`, error: error || '' }).replace(/</g, '\\u003c');
|
|
64
|
+
res.writeHead(code, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff' });
|
|
65
|
+
res.end(LOGIN.replace('__SL_CONFIG__', cfg).replace('__SL_LOGIN__', `${base}/login`));
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function handleLogin(req, res) {
|
|
70
|
+
const ip = req.socket.remoteAddress || '';
|
|
71
|
+
const now = Date.now();
|
|
72
|
+
const f = fails.get(ip);
|
|
73
|
+
if (f && now - f.first > FAIL_WINDOW) fails.delete(ip);
|
|
74
|
+
const wantsHtml = !String(req.headers['content-type'] || '').includes('json');
|
|
75
|
+
const reply = (code, error) => (wantsHtml ? loginPage(res, code, error) : json(res, code, { error }));
|
|
76
|
+
if ((fails.get(ip) || {}).n >= MAX_FAILS) {
|
|
77
|
+
res.setHeader('Retry-After', String(Math.ceil(FAIL_WINDOW / 1000)));
|
|
78
|
+
return reply(429, 'Too many attempts. Try again in 15 minutes.');
|
|
79
|
+
}
|
|
80
|
+
let body;
|
|
81
|
+
try { body = await readForm(req); } catch { return reply(400, 'Invalid request.'); }
|
|
82
|
+
const ok = safeEqual(String(body.username || ''), auth.username) & safeEqual(String(body.password || ''), auth.password); // no short-circuit
|
|
83
|
+
if (!ok) {
|
|
84
|
+
const e = fails.get(ip) || { n: 0, first: now };
|
|
85
|
+
e.n++; fails.set(ip, e);
|
|
86
|
+
if (fails.size > 10000) fails.clear(); // memory guard
|
|
87
|
+
return reply(401, 'Wrong username or password.');
|
|
88
|
+
}
|
|
89
|
+
fails.delete(ip);
|
|
90
|
+
const exp = now + SESSION_DAYS * 864e5;
|
|
91
|
+
res.setHeader('Set-Cookie', cookie(req, `${exp}.${sign(exp)}`, SESSION_DAYS * 86400));
|
|
92
|
+
if (wantsHtml) { res.writeHead(303, { Location: `${base}/` }); res.end(); return true; }
|
|
93
|
+
return json(res, 200, { ok: true });
|
|
37
94
|
}
|
|
38
95
|
|
|
39
96
|
function summary(src) {
|
|
@@ -105,12 +162,19 @@ function createDashboard({ base, title = 'Server Lens', auth, interval = 2000, h
|
|
|
105
162
|
const src = sources.list()[0];
|
|
106
163
|
return json(res, 200, { status: src ? src.health() : 'unknown', uptime: process.uptime(), timestamp: Date.now() });
|
|
107
164
|
}
|
|
165
|
+
if (login && sub === '/login' && req.method === 'POST') { handleLogin(req, res); return true; }
|
|
166
|
+
if (login && sub === '/logout' && req.method === 'POST') {
|
|
167
|
+
res.writeHead(303, { 'Set-Cookie': cookie(req, '', 0), Location: `${base}/` });
|
|
168
|
+
res.end();
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
108
171
|
if (!authorized(req)) {
|
|
109
|
-
|
|
110
|
-
return res
|
|
172
|
+
if (login && req.method === 'GET' && (sub === '/' || sub === '/login')) return loginPage(res, 401);
|
|
173
|
+
return json(res, 401, { error: 'Sign in required' });
|
|
111
174
|
}
|
|
175
|
+
if (sub === '/login' && req.method === 'GET') { res.writeHead(303, { Location: `${base}/` }); res.end(); return true; }
|
|
112
176
|
if (sub === '/' && req.method === 'GET') {
|
|
113
|
-
const cfg = JSON.stringify({ base, ws: `${base}/ws`, token, title, interval, hub }).replace(/</g, '\\u003c');
|
|
177
|
+
const cfg = JSON.stringify({ base, ws: `${base}/ws`, token, title, interval, hub, signOut: !!login && validSession(req) }).replace(/</g, '\\u003c');
|
|
114
178
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff' });
|
|
115
179
|
return res.end(HTML.replace('__SL_CONFIG__', cfg));
|
|
116
180
|
}
|
|
@@ -134,6 +198,22 @@ function createDashboard({ base, title = 'Server Lens', auth, interval = 2000, h
|
|
|
134
198
|
return { handle, handleUpgrade, isWs, authorized, watch, snapshot, close, base };
|
|
135
199
|
}
|
|
136
200
|
|
|
201
|
+
/** Reads a small JSON or urlencoded body (or uses one a body parser already read). */
|
|
202
|
+
function readForm(req, limit = 8 * 1024) {
|
|
203
|
+
if (req.body && typeof req.body === 'object') return Promise.resolve(req.body);
|
|
204
|
+
return new Promise((resolve, reject) => {
|
|
205
|
+
let size = 0; const chunks = [];
|
|
206
|
+
req.on('data', (c) => { size += c.length; if (size > limit) { req.destroy(); reject(new Error('too large')); } else chunks.push(c); });
|
|
207
|
+
req.on('end', () => {
|
|
208
|
+
const raw = Buffer.concat(chunks).toString();
|
|
209
|
+
try {
|
|
210
|
+
resolve(String(req.headers['content-type'] || '').includes('json') ? JSON.parse(raw || '{}') : Object.fromEntries(new URLSearchParams(raw)));
|
|
211
|
+
} catch (e) { reject(e); }
|
|
212
|
+
});
|
|
213
|
+
req.on('error', reject);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
137
217
|
function json(res, code, body) {
|
|
138
218
|
res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
139
219
|
res.end(JSON.stringify(body));
|