node-server-lens 0.1.0 → 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 CHANGED
@@ -1,138 +1,150 @@
1
- # Server Lens
2
-
3
- **Self-hosted, real-time monitoring for all your servers, with a dark, grain-textured dashboard.**
4
-
5
- Add one line to your backend and get a live dashboard with server status and IPs, streaming logs, request traffic with week / month / year history, per-endpoint API stats and uptime checks. Run the **hub** anywhere (VPS, Docker, Render, Railway, Fly.io…) to watch many servers from one place: Express, Next.js, Fastify, NestJS, any Node server, or any other language over HTTP.
6
-
7
- - No database. No build step. One dependency (`ws`).
8
- - MIT licensed.
9
-
10
- ---
11
-
12
- ## Contents
13
-
14
- - [Features](#features)
15
- - [How it works](#how-it-works)
16
- - [Quick start (try the demo)](#quick-start-try-the-demo)
17
- - [Option A: embedded dashboard (one server)](#option-a-embedded-dashboard-one-server)
18
- - [Option B: the hub (many servers)](#option-b-the-hub-many-servers)
19
- - [Connecting servers](#connecting-servers)
20
- - [Express / Connect / plain `http`](#express--connect--plain-http)
21
- - [Next.js](#nextjs)
22
- - [Fastify, Koa, NestJS, Hapi (any Node server)](#fastify-koa-nestjs-hapi-any-node-server)
23
- - [Any URL, no code (uptime checks)](#any-url-no-code-uptime-checks)
24
- - [Python, Go, PHP, Java, Ruby… (HTTP ingest API)](#python-go-php-java-ruby-http-ingest-api)
25
- - [Custom loggers (pino, winston)](#custom-loggers-pino-winston)
26
- - [Hosting the hub](#hosting-the-hub)
27
- - [Docker](#docker)
28
- - [VPS with PM2 + Nginx (HTTPS)](#vps-with-pm2--nginx-https)
29
- - [Render / Railway / Fly.io](#render--railway--flyio)
30
- - [Configuration reference](#configuration-reference)
31
- - [HTTP API](#http-api)
32
- - [Security](#security)
33
- - [Limitations](#limitations)
34
- - [Development](#development)
35
- - [License](#license)
1
+ <p align="center">
2
+ <img src="docs/images/banner.svg" alt="Server Lens: real-time monitoring for all your servers" width="100%">
3
+ </p>
4
+
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/node-server-lens"><img src="https://img.shields.io/npm/v/node-server-lens?color=c2ec44&labelColor=1b1b1e&label=npm" alt="npm version"></a>
7
+ <a href="https://www.npmjs.com/package/node-server-lens"><img src="https://img.shields.io/npm/dm/node-server-lens?color=d37ff6&labelColor=1b1b1e" alt="npm downloads"></a>
8
+ <img src="https://img.shields.io/node/v/node-server-lens?color=4fd16b&labelColor=1b1b1e" alt="node version">
9
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-8c8c93?labelColor=1b1b1e" alt="MIT license"></a>
10
+ </p>
11
+
12
+ <p align="center">
13
+ <b><a href="#-quick-start">Quick start</a></b> ·
14
+ <b><a href="#-set-up-with-an-ai-coding-agent">AI agent setup</a></b> ·
15
+ <b><a href="#-connect-your-servers">Connect servers</a></b> ·
16
+ <b><a href="#-host-the-hub">Hosting</a></b> ·
17
+ <b><a href="#-reference">Reference</a></b>
18
+ </p>
36
19
 
37
20
  ---
38
21
 
39
- ## Features
40
-
41
- | Page | What you get |
42
- | --- | --- |
43
- | **Servers** (hub) | Every connected server in one grid: status (online / degraded / offline / down), requests in the last hour, average latency, error rate. Add or remove servers from the UI. |
44
- | **Overview** | KPI cards (total requests, average response, 5xx error rate, uptime) with hour-over-hour change, the traffic chart and the status-code breakdown. |
45
- | **Server Info** | Hostname, IPv4/IPv6 addresses (one-click copy), port, PID, runtime, OS, CPU, memory, environment, process and system uptime, load average. Live sparklines for process CPU, RSS memory, event-loop lag and system memory. |
46
- | **Traffic** | Request volume chart with **1h · 24h · Week · Month · Year** filters. Hover any bar for count, average latency and errors. History is persisted by the hub. |
47
- | **Status Codes** | Share of 2xx/3xx vs 4xx vs 5xx responses, plus recent requests. |
48
- | **Live Logs** | Everything your app writes with `console.log/info/warn/error/debug`, streamed over WebSocket. Search with highlighting, level filters with counts, pause/resume, clear and download. |
49
- | **API Endpoints** | Every route with calls, share of traffic, avg / p95 / max latency, errors and last call. Sorted by **most called** by default; also slowest (avg or p95), most errors, recently called, A–Z. IDs are grouped (`/users/42` → `/users/:id`). |
50
- | **Requests** | The latest requests with method, path, status, duration and client IP. Search and "errors only" filter. |
22
+ **Server Lens** gives any backend a live monitoring dashboard: server status and IPs, streaming logs, request traffic with week / month / year history, per-endpoint API stats and uptime checks.
51
23
 
52
- Also: health endpoint for load balancers, optional basic auth, URL uptime monitors with down/recovery log lines, auto-reconnect, mobile layout.
24
+ Use it two ways:
53
25
 
54
- ## How it works
55
-
56
- ```
57
- ┌──────────────┐ POST /api/ingest (every 5s) ┌──────────────────────┐
58
- │ Express app │ ───────────────────────────────▶│ │
59
- │ + agent │ │ Server Lens hub │◀── you (browser, WebSocket)
60
- ├──────────────┤ │ stores history in │
61
- │ Next.js app │ ───────────────────────────────▶│ a JSON file │
62
- │ + instrument │ │ │
63
- ├──────────────┤ │ │
64
- │ Go / Python │ ── same JSON over HTTP ────────▶│ │
65
- └──────────────┘ └──────────┬───────────┘
66
- │ GET every 30s
67
- ┌─────────▼─────────┐
68
- │ any URL (uptime) │
69
- └───────────────────┘
70
- ```
26
+ | | **Embedded** | **Hub** |
27
+ | --- | --- | --- |
28
+ | What | A dashboard inside your app at `/server-lens` | One dashboard for many servers, hosted anywhere |
29
+ | Setup | `app.use(serverLens())` | `npx node-server-lens` + point servers at it |
30
+ | History | Since the app started | Up to ~13 months, saved to disk |
31
+ | Best for | One app, local dev, quick checks | Teams, production, many services |
71
32
 
72
- - **Agent**: the npm package inside your Node app. It times every request, captures console output and samples CPU / memory / event-loop lag. It can serve its own dashboard at `/server-lens`, report to a hub, or both.
73
- - **Hub**: a small standalone server that receives data from many agents, polls URLs, keeps up to ~13 months of hourly history on disk and serves the multi-server dashboard.
33
+ No database, no build step, one dependency (`ws`). Works with **Express, Next.js, Fastify, Koa, NestJS, Hapi, plain Node**, and **any other language** over HTTP.
74
34
 
75
- ## Quick start (try the demo)
35
+ ## ⚡ Quick start
76
36
 
77
- ```bash
78
- git clone https://github.com/Sathishram2000/Server-Lens.git
79
- cd Server-Lens
80
- npm install
81
- npm run demo
82
- ```
83
-
84
- Open http://localhost:4000. The demo starts a hub, two fake API servers that report to it, and a URL monitor, with a year of generated history so every chart has data. Each demo API also has its own embedded dashboard at http://localhost:3001/server-lens and http://localhost:3002/server-lens.
85
-
86
- ## Option A: embedded dashboard (one server)
37
+ **1. Install**
87
38
 
88
39
  ```bash
89
40
  npm install node-server-lens
90
41
  ```
91
42
 
43
+ **2. Add one line before your routes**
44
+
92
45
  ```js
93
- const express = require('express');
94
46
  const serverLens = require('node-server-lens');
95
47
 
96
- const app = express();
97
- app.use(serverLens()); // add before your routes
48
+ app.use(serverLens());
49
+ ```
98
50
 
99
- app.get('/api/users', (req, res) => res.json([]));
100
- app.listen(3000);
51
+ **3. Open** `http://localhost:3000/server-lens` (use your app's port).
52
+
53
+ That's it. Using Next.js, Fastify or Koa instead? See [Connect your servers](#-connect-your-servers).
54
+
55
+ > **Try it without your own project:** `git clone https://github.com/Sathishram2000/Node-Server-Lens.git && cd Node-Server-Lens && npm install && npm run demo`, then open http://localhost:4000. The demo runs a hub, two sample APIs and an uptime check, with a year of sample history.
56
+
57
+ ## 🤖 Set up with an AI coding agent
58
+
59
+ Using Claude Code, Cursor, Copilot, Windsurf or another coding agent? Copy this prompt into it from your project folder. It detects your framework, installs the package and wires everything up.
60
+
61
+ ```text
62
+ Add Server Lens monitoring (npm package "node-server-lens", docs: https://github.com/Sathishram2000/Node-Server-Lens) to this project.
63
+
64
+ 1. Detect the backend framework and language from the project files.
65
+ 2. If it runs on Node.js, install "node-server-lens" with the package manager that matches the lockfile (npm, pnpm, yarn or bun).
66
+ 3. Wire it up, matching the project's module style (ESM import or CommonJS require) and TypeScript if used:
67
+ - Express, Connect, or NestJS on the Express adapter: in the file that creates the app, add
68
+ app.use(serverLens({ ...options })) BEFORE any routes.
69
+ - Next.js: create instrumentation.ts (in src/ if the project uses src/, otherwise the project root) with
70
+ export async function register() {
71
+ if (process.env.NEXT_RUNTIME === 'nodejs') {
72
+ const { instrument } = await import('node-server-lens');
73
+ instrument({ ...options });
74
+ }
75
+ }
76
+ Then add 'node-server-lens' to serverExternalPackages in next.config
77
+ (Next.js 14: experimental.serverComponentsExternalPackages).
78
+ - Fastify, Koa, Hapi, plain http/https, or any other Node server: at the very top of the entry file,
79
+ before the server starts, call require('node-server-lens').instrument({ ...options })
80
+ (or the ESM import equivalent).
81
+ - Not Node.js (Python, Go, PHP, Ruby, Java, .NET...): do not install the npm package. Add a small
82
+ middleware that records method, route pattern, path, status, duration in ms, client IP and timestamp
83
+ for each request, batches them, and POSTs them every 5 seconds to `${SERVER_LENS_HUB_URL}/api/ingest`
84
+ with the header "Authorization: Bearer ${SERVER_LENS_KEY}", using the JSON format in the
85
+ "HTTP ingest API" section of the docs. Only run it when both variables are set, and never let a
86
+ failed POST break a request.
87
+ 4. Options to pass (Node.js):
88
+ - name: this project's name
89
+ - auth: { username: process.env.SERVER_LENS_USER, password: process.env.SERVER_LENS_PASS },
90
+ only when both variables are set (otherwise leave auth out)
91
+ - hub: { url: process.env.SERVER_LENS_HUB_URL, key: process.env.SERVER_LENS_KEY },
92
+ only when SERVER_LENS_HUB_URL is set
93
+ 5. Add SERVER_LENS_USER, SERVER_LENS_PASS, SERVER_LENS_HUB_URL and SERVER_LENS_KEY with empty values to
94
+ .env.example (create it if missing). Never commit real secrets.
95
+ 6. Start the app, request /server-lens, and confirm it returns HTTP 200. Tell me the dashboard URL and
96
+ which files you changed.
101
97
  ```
102
98
 
103
- Open http://localhost:3000/server-lens. That's it: the WebSocket attaches itself to your HTTP server on the first request.
99
+ <details>
100
+ <summary>What the prompt sets up</summary>
104
101
 
105
- > In production, always protect it: `serverLens({ auth: { username: 'admin', password: process.env.LENS_PASSWORD } })`.
102
+ - **Node.js apps** get the embedded dashboard at `/server-lens`, plus hub reporting once you set `SERVER_LENS_HUB_URL` and `SERVER_LENS_KEY`.
103
+ - **Other languages** get a small reporter that sends data to your hub.
104
+ - Login is enabled as soon as you set `SERVER_LENS_USER` and `SERVER_LENS_PASS`.
105
+ - Nothing secret is written to the code; values come from environment variables.
106
106
 
107
- ## Option B: the hub (many servers)
107
+ Always review the changes before you commit them.
108
+ </details>
108
109
 
109
- Start a hub (needs Node 18+):
110
+ ## 🖥 What you get
110
111
 
111
- ```bash
112
- npx node-server-lens --port 4000 --key "$(openssl rand -hex 24)" --user admin --pass 'change-me'
113
- ```
112
+ | Page | What it shows |
113
+ | --- | --- |
114
+ | **Server switcher** *(hub)* | Click the server name at the top right to see every connected server with its status (online, degraded, offline, down), requests in the last hour, latency and error rate. Pick one to switch; you stay on the page you're on. Add or remove servers from the same menu. |
115
+ | **Overview** | Total requests, average response time, 5xx error rate and uptime, each with hour-over-hour change, plus the traffic chart and status codes. |
116
+ | **Server Info** | Hostname, IPv4/IPv6 addresses with copy buttons, port, PID, runtime, OS, CPU, memory, environment, uptime and load average. Live charts for CPU, memory, event-loop lag and system memory. |
117
+ | **Traffic** | Request volume with **1h · 24h · Week · Month · Year** filters. Hover a bar for its count, average latency and errors. |
118
+ | **Status Codes** | Share of successful (2xx/3xx), client error (4xx) and server error (5xx) responses, plus recent requests. |
119
+ | **Live Logs** | Everything your app prints with `console.log / info / warn / error / debug`, streamed live. Search with highlighting, level filters, pause, clear and download. |
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
+ | **Requests** | The latest requests with method, path, status, duration and client IP. Search and an "errors only" filter. |
114
122
 
115
- or from a clone:
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.
116
124
 
117
- ```bash
118
- SERVER_LENS_KEY=your-secret SERVER_LENS_USER=admin SERVER_LENS_PASS=change-me npm run hub
119
- ```
125
+ ## 🧭 How it works
126
+
127
+ <p align="center">
128
+ <img src="docs/images/architecture.svg" alt="Servers send data to the Server Lens hub; you watch it live in the dashboard" width="100%">
129
+ </p>
120
130
 
121
- Then point your servers at it (next section). Click **+ Add server** in the dashboard at any time to see copy-paste snippets with your hub URL filled in.
131
+ - The **agent** (this npm package) runs inside your Node app. It times every request, captures console output and samples CPU, memory and event-loop lag. It can show its own dashboard, report to a hub, or both.
132
+ - The **hub** is a small standalone server. It receives data from agents and other languages, checks URLs for uptime, saves history to a JSON file and serves the multi-server dashboard.
122
133
 
123
- ## Connecting servers
134
+ ## 🔌 Connect your servers
124
135
 
125
- All agent options are listed in the [configuration reference](#configuration-reference). Keep the key in an environment variable (`SERVER_LENS_KEY`), never in code.
136
+ Keep keys and passwords in environment variables, never in code. Every option is listed in the [reference](#agent-options).
126
137
 
127
- ### Express / Connect / plain `http`
138
+ <details open>
139
+ <summary><b>Express · Connect · NestJS (Express adapter) · plain Node http</b></summary>
128
140
 
129
141
  ```js
130
142
  const serverLens = require('node-server-lens');
131
143
 
132
144
  app.use(serverLens({
133
- name: 'orders-api', // shown in the hub
134
- hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY },
135
- // dashboard: false, // report to the hub only
145
+ name: 'orders-api',
146
+ auth: { username: 'admin', password: process.env.SERVER_LENS_PASS }, // protect /server-lens
147
+ hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY }, // optional: report to a hub
136
148
  }));
137
149
  ```
138
150
 
@@ -143,19 +155,20 @@ const http = require('http');
143
155
  const lens = require('node-server-lens')();
144
156
 
145
157
  http.createServer((req, res) => lens(req, res, () => {
146
- // your handler
147
- res.end('ok');
158
+ res.end('ok'); // your handler
148
159
  })).listen(3000);
149
160
  ```
150
161
 
151
- With Express, routes are grouped by their pattern (`/users/:id`). Elsewhere, numeric, UUID and long hex path segments are replaced with `:id`.
162
+ ESM works too: `import serverLens from 'node-server-lens'`.
163
+ </details>
152
164
 
153
- ### Next.js
165
+ <details>
166
+ <summary><b>Next.js</b></summary>
154
167
 
155
- Works with `next start` and `next dev` (Node runtime, App or Pages router).
168
+ Works with `next start` and `next dev` (Node.js runtime, App or Pages router).
156
169
 
157
170
  1. `npm install node-server-lens`
158
- 2. Create `instrumentation.ts` (or `.js`) at the project root (or in `src/`):
171
+ 2. Create `instrumentation.ts` in the project root (or in `src/` if you use it):
159
172
 
160
173
  ```ts
161
174
  export async function register() {
@@ -163,8 +176,8 @@ export async function register() {
163
176
  const { instrument } = await import('node-server-lens');
164
177
  instrument({
165
178
  name: 'web',
166
- hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY! },
167
- auth: { username: 'admin', password: process.env.LENS_PASSWORD! }, // for the embedded /server-lens page
179
+ auth: { username: 'admin', password: process.env.SERVER_LENS_PASS! },
180
+ hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY! }, // optional
168
181
  });
169
182
  }
170
183
  }
@@ -177,11 +190,13 @@ module.exports = { serverExternalPackages: ['node-server-lens'] };
177
190
  // Next.js 14: module.exports = { experimental: { serverComponentsExternalPackages: ['node-server-lens'] } };
178
191
  ```
179
192
 
180
- Pages and API routes are recorded; `/_next/*` assets are ignored. The embedded dashboard is also served at `/server-lens` on your Next.js app. Edge runtime routes are not captured (they don't run in Node).
193
+ Pages and API routes are recorded and `/_next/*` assets are skipped. The dashboard is served at `/server-lens` on your Next.js app. Routes on the Edge runtime aren't captured, because they don't run in Node.
194
+ </details>
181
195
 
182
- ### Fastify, Koa, NestJS, Hapi (any Node server)
196
+ <details>
197
+ <summary><b>Fastify · Koa · Hapi · any other Node server</b></summary>
183
198
 
184
- `instrument()` hooks into Node's `http`/`https` servers, so it works with any framework without touching your routes. Call it once, before your server starts:
199
+ `instrument()` hooks into Node's own `http`/`https` servers, so it works with any framework without touching your routes. Call it once, before the server starts:
185
200
 
186
201
  ```js
187
202
  require('node-server-lens').instrument({
@@ -189,18 +204,20 @@ require('node-server-lens').instrument({
189
204
  hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY },
190
205
  });
191
206
 
192
- // ...then start Fastify / Koa / Nest as usual
207
+ // ...then start Fastify / Koa / Hapi as usual
193
208
  ```
209
+ </details>
194
210
 
195
- NestJS on the Express adapter can also use `app.use(serverLens())` in `main.ts`.
196
-
197
- ### Any URL, no code (uptime checks)
211
+ <details>
212
+ <summary><b>Any website or API, no code (uptime checks)</b></summary>
198
213
 
199
- In the hub, open **Servers → + Add server → Any URL**, give it a name and a health-check URL. The hub requests it every 30 seconds (configurable with `--check`) and tracks availability %, response time, status codes and down/recovery events. Works for any stack, static sites and third-party APIs.
214
+ In the hub, click the server name at the top right, then **+ Add server → Any URL** and enter a name and a health-check URL. The hub requests it every 30 seconds (change with `--check`) and tracks availability %, response time, status codes, and down/recovery events. Works for any stack, static sites and third-party APIs.
215
+ </details>
200
216
 
201
- ### Python, Go, PHP, Java, Ruby… (HTTP ingest API)
217
+ <details>
218
+ <summary><b>Python · Go · PHP · Ruby · Java (HTTP ingest API)</b></summary>
202
219
 
203
- Send JSON to the hub from any language. Batch it (for example every 5 seconds):
220
+ Send batches of JSON to the hub, for example every 5 seconds:
204
221
 
205
222
  ```bash
206
223
  curl -X POST https://lens.example.com/api/ingest \
@@ -223,7 +240,7 @@ import os, time, threading, requests
223
240
  from flask import Flask, request, g
224
241
 
225
242
  app = Flask(__name__)
226
- HUB, KEY, buf = "https://lens.example.com/api/ingest", os.environ["SERVER_LENS_KEY"], []
243
+ HUB, KEY, buf = os.environ["SERVER_LENS_HUB_URL"] + "/api/ingest", os.environ["SERVER_LENS_KEY"], []
227
244
 
228
245
  @app.before_request
229
246
  def start(): g.t = time.time()
@@ -249,37 +266,47 @@ def flush():
249
266
  threading.Thread(target=flush, daemon=True).start()
250
267
  ```
251
268
 
269
+ <a id="ingest-schema"></a>
270
+
252
271
  | Field | Type | Notes |
253
272
  | --- | --- | --- |
254
- | `id` | string, required | `[A-Za-z0-9_.-]{1,64}`, stable per server |
273
+ | `id` | string, required | `[A-Za-z0-9_.-]{1,64}`, the same on every report |
255
274
  | `name` | string | display name |
256
275
  | `info` | object | `hostname`, `runtime`, `platform`, `arch`, `cpuModel`, `env`, `port`, `pid`, `cpus`, `totalMem`, `startedAt`, `uptime`, `osUptime`, `ips[]` |
257
276
  | `sample` | object | latest stats: `cpu` (%), `sysCpu` (%), `rss`, `heapUsed`, `freeMem` (bytes), `lag` (ms), `load` ([1, 5, 15]) |
258
- | `requests` | array (≤10,000) | `ts` (ms epoch), `method`, `route`, `path`, `status`, `ms`, `ip` |
259
- | `logs` | array (≤2,000) | `ts`, `level` (`debug`/`info`/`warn`/`error`), `msg` |
277
+ | `requests` | array, ≤ 10,000 | `ts` (ms epoch), `method`, `route`, `path`, `status`, `ms`, `ip` |
278
+ | `logs` | array, ≤ 2,000 | `ts`, `level` (`debug` / `info` / `warn` / `error`), `msg` |
260
279
 
261
- A server shows as **offline** if it hasn't reported for 20 seconds.
280
+ A server shows as **offline** when it hasn't reported for 20 seconds.
281
+ </details>
262
282
 
263
- ### Custom loggers (pino, winston)
283
+ <details>
284
+ <summary><b>Other loggers (pino, winston…)</b></summary>
264
285
 
265
- `console.*` is captured automatically. To forward another logger:
286
+ `console.*` is captured automatically. To forward another logger, call `lens.log(level, ...args)`:
266
287
 
267
288
  ```js
268
289
  const lens = serverLens();
269
290
  app.use(lens);
270
291
  lens.log('warn', 'disk usage at', 91, '%');
271
-
272
- // pino: a tiny destination
273
- const logger = require('pino')({}, { write: (line) => { const o = JSON.parse(line); lens.log(o.level >= 50 ? 'error' : o.level >= 40 ? 'warn' : 'info', o.msg); process.stdout.write(line); } });
274
292
  ```
293
+ </details>
275
294
 
276
- ## Hosting the hub
295
+ ## 🚀 Host the hub
277
296
 
278
- The hub is a single Node process that stores history in one JSON file. Give it a persistent disk, a key and a login, and put it behind HTTPS.
297
+ The hub is one Node process that saves history to one JSON file. Give it a **persistent disk**, an **ingest key** and a **login**, and put it behind **HTTPS**.
279
298
 
280
- ### Docker
299
+ ```bash
300
+ npx node-server-lens --port 4000 --key "$(openssl rand -hex 24)" --user admin --pass 'change-me'
301
+ ```
302
+
303
+ Click the server name at the top right, then **+ Add server**, at any time for copy-paste snippets with your hub URL filled in.
304
+
305
+ <details open>
306
+ <summary><b>Docker</b></summary>
281
307
 
282
308
  ```bash
309
+ git clone https://github.com/Sathishram2000/Node-Server-Lens.git && cd Node-Server-Lens
283
310
  docker build -t server-lens .
284
311
  docker run -d --name server-lens -p 4000:4000 \
285
312
  -e SERVER_LENS_KEY=your-long-random-key \
@@ -304,11 +331,13 @@ services:
304
331
  volumes:
305
332
  lens-data:
306
333
  ```
334
+ </details>
307
335
 
308
- ### VPS with PM2 + Nginx (HTTPS)
336
+ <details>
337
+ <summary><b>VPS with PM2 + Nginx (HTTPS)</b></summary>
309
338
 
310
339
  ```bash
311
- git clone https://github.com/Sathishram2000/Server-Lens.git && cd Server-Lens
340
+ git clone https://github.com/Sathishram2000/Node-Server-Lens.git && cd Node-Server-Lens
312
341
  npm ci --omit=dev
313
342
  npm install -g pm2
314
343
  SERVER_LENS_KEY=... SERVER_LENS_USER=admin SERVER_LENS_PASS=... \
@@ -317,7 +346,7 @@ SERVER_LENS_KEY=... SERVER_LENS_USER=admin SERVER_LENS_PASS=... \
317
346
  pm2 save && pm2 startup
318
347
  ```
319
348
 
320
- Nginx (WebSocket upgrade headers are required for live updates):
349
+ Nginx needs the WebSocket upgrade headers for live updates:
321
350
 
322
351
  ```nginx
323
352
  server {
@@ -334,15 +363,17 @@ server {
334
363
  }
335
364
  ```
336
365
 
337
- Then `sudo certbot --nginx -d lens.example.com` for a free TLS certificate. Run only **one** hub process (no PM2 cluster mode): history lives in that process.
366
+ Then run `sudo certbot --nginx -d lens.example.com` for a free TLS certificate. Run only **one** hub process (not PM2 cluster mode), because history lives in that process.
367
+ </details>
338
368
 
339
- ### Render / Railway / Fly.io
369
+ <details>
370
+ <summary><b>Render · Railway · Fly.io · any container platform</b></summary>
340
371
 
341
372
  Any platform that runs a Docker image or a Node process and supports WebSockets works:
342
373
 
343
374
  | Setting | Value |
344
375
  | --- | --- |
345
- | Build | `npm ci --omit=dev` (or use the included `Dockerfile`) |
376
+ | Build | `npm ci --omit=dev`, or use the included `Dockerfile` |
346
377
  | Start | `node bin/server-lens.js` |
347
378
  | Env vars | `SERVER_LENS_KEY`, `SERVER_LENS_USER`, `SERVER_LENS_PASS`, `SERVER_LENS_DATA=/data/server-lens-data.json` |
348
379
  | Disk / volume | mount at `/data` so history survives deploys |
@@ -350,90 +381,98 @@ Any platform that runs a Docker image or a Node process and supports WebSockets
350
381
 
351
382
  `PORT` is read from the environment, which these platforms set for you. Without a persistent disk the hub still works, but history resets on each deploy.
352
383
 
353
- Serverless platforms (Vercel functions, AWS Lambda) are not a good fit for the **hub**, which needs a long-running process and a disk. Apps deployed there can still be watched with a URL monitor or the ingest API.
384
+ Serverless platforms (Vercel functions, AWS Lambda) aren't a good fit for the **hub**, which needs a long-running process and a disk. Apps deployed there can still be watched with an uptime check or the ingest API.
385
+ </details>
354
386
 
355
- ## Configuration reference
387
+ ## 📖 Reference
356
388
 
357
- ### Agent: `serverLens(options)` / `instrument(options)`
389
+ <a id="agent-options"></a>
390
+
391
+ <details>
392
+ <summary><b>Agent options</b>: <code>serverLens(options)</code> and <code>instrument(options)</code></summary>
358
393
 
359
394
  | Option | Default | Description |
360
395
  | --- | --- | --- |
361
396
  | `path` | `'/server-lens'` | Where the embedded dashboard is served |
362
- | `auth` | none | `{ username, password }` for basic auth, or `(req) => boolean` |
363
- | `dashboard` | `true` | `false` to disable the embedded dashboard (hub reporting only) |
364
- | `hub` | none | `{ url, key, id?, name?, interval? }`, report to a hub |
397
+ | `auth` | none | `{ username, password }` shows the sign-in page; or `(req) => boolean` to plug in your own auth |
398
+ | `dashboard` | `true` | `false` turns off the embedded dashboard (hub reporting only) |
399
+ | `hub` | none | `{ url, key, id?, name?, interval? }` to report to a hub |
365
400
  | `name` | hostname | Display name |
366
401
  | `title` | `'Server Lens'` | Dashboard title |
367
402
  | `captureConsole` | `true` | Capture `console.*` into live logs |
368
- | `ignore` | `[]` | Path prefixes or RegExps not to record (`instrument` also ignores `/_next/`, `/favicon.ico`) |
369
- | `interval` | `2000` | Live update interval (ms) |
403
+ | `ignore` | `[]` | Path prefixes or RegExps not to record (`instrument` also skips `/_next/` and `/favicon.ico`) |
404
+ | `interval` | `2000` | Live update interval in ms |
370
405
  | `maxLogs` | `1000` | Log lines kept in memory |
371
- | `maxRoutes` | `500` | Distinct endpoints tracked (extra ones are grouped as `METHOD *`) |
406
+ | `maxRoutes` | `500` | Distinct endpoints tracked; extras are grouped as `METHOD *` |
372
407
  | `maxRecent` | `100` | Recent requests kept |
373
408
 
374
- Returned middleware also has: `attach(server)`, `log(level, ...args)`, `snapshot()`, `close()`.
409
+ The returned middleware also has `attach(server)`, `log(level, ...args)`, `snapshot()` and `close()`. TypeScript types are included.
410
+ </details>
375
411
 
376
- ### Hub: `server-lens` CLI
412
+ <details>
413
+ <summary><b>Hub options</b>: <code>npx node-server-lens</code></summary>
377
414
 
378
- | Flag | Env | Default |
415
+ | Flag | Environment variable | Default |
379
416
  | --- | --- | --- |
380
417
  | `--port` | `PORT` | `4000` |
381
418
  | `--host` | `HOST` | `0.0.0.0` |
382
- | `--key` | `SERVER_LENS_KEY` | random per run (printed) |
419
+ | `--key` | `SERVER_LENS_KEY` | random for each run (printed at start) |
383
420
  | `--user` / `--pass` | `SERVER_LENS_USER` / `SERVER_LENS_PASS` | none (open) |
384
421
  | `--data` | `SERVER_LENS_DATA` | `./server-lens-data.json` |
385
- | `--check` | `SERVER_LENS_CHECK` | `30` (seconds between URL checks) |
422
+ | `--check` | `SERVER_LENS_CHECK` | `30` seconds between uptime checks |
386
423
  | `--title` | `SERVER_LENS_TITLE` | `Server Lens` |
387
424
 
388
- Programmatic: `const { createHub } = require('node-server-lens'); createHub({ key, auth, dataFile }).listen(4000);`
425
+ From code: `const { createHub } = require('node-server-lens'); createHub({ key, auth, dataFile }).listen(4000);`
426
+ </details>
389
427
 
390
- ## HTTP API
428
+ <details>
429
+ <summary><b>HTTP API</b></summary>
391
430
 
392
- Paths are relative to the dashboard (`/server-lens` for the agent, `/` for the hub).
431
+ Paths are relative to the dashboard: `/server-lens` for the agent, `/` for the hub.
393
432
 
394
433
  | Method & path | Auth | Description |
395
434
  | --- | --- | --- |
396
435
  | `GET /health` | none | `{ status, uptime, timestamp }` for load balancers |
397
- | `GET /api/snapshot?server=<id>` | dashboard | Everything the dashboard shows, as JSON |
398
- | `GET /api/servers` | dashboard | Server list with status and last-hour stats |
399
- | `GET /api/logs?server=<id>` | dashboard | Buffered log lines |
400
- | `POST /api/ingest` | `Bearer <key>` | Hub only: push data ([schema](#python-go-php-java-ruby-http-ingest-api)) |
401
- | `POST /api/monitors` | dashboard | Hub only: `{ name, url }` adds a URL monitor |
402
- | `DELETE /api/servers/<id>` | dashboard | Hub only: remove a server and its history |
403
- | `WS /ws?token=…` | page token | Live stream used by the UI |
436
+ | `GET /api/snapshot?server=<id>` | login | Everything the dashboard shows, as JSON |
437
+ | `GET /api/servers` | login | Server list with status and last-hour stats |
438
+ | `GET /api/logs?server=<id>` | login | Buffered log lines |
439
+ | `POST /api/ingest` | `Bearer <key>` | Hub only: push data ([format](#ingest-schema)) |
440
+ | `POST /api/monitors` | login | Hub only: `{ name, url }` adds an uptime check |
441
+ | `DELETE /api/servers/<id>` | login | Hub only: removes a server and its history |
442
+ | `WS /ws?token=…` | page token | The live stream the dashboard uses |
443
+ </details>
404
444
 
405
- ## Security
445
+ ## 🔒 Security
406
446
 
407
- - **Set a login** (`auth` / `SERVER_LENS_USER` + `SERVER_LENS_PASS`). Logs and server details can contain sensitive data. The agent prints a warning when `NODE_ENV=production` and no auth is set.
408
- - **Use HTTPS** in front of the hub; basic auth and the ingest key travel in headers.
409
- - The ingest key is compared in constant time; payloads are size-limited (4 MB), validated and truncated; route cardinality is capped so URL scanners can't exhaust memory.
410
- - The live socket needs a random per-process token that is only embedded in the authenticated page.
411
- - URL monitors make the hub send requests to URLs that logged-in users enter. Only give dashboard access to people you trust, and keep the hub off networks with sensitive internal services if that matters to you.
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
+ - **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.
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.
451
+ - The live connection needs a random per-process token that only appears in the logged-in page.
452
+ - Uptime checks make the hub request URLs that logged-in users enter. Only give dashboard access to people you trust.
412
453
 
413
- ## Limitations
454
+ ## ⚠️ Limitations
414
455
 
415
- - Agent data lives in memory; restart the app and its embedded dashboard starts fresh. Use the hub for long-term history.
416
- - Under Node `cluster` / PM2 cluster mode, each worker is reported separately (give each a distinct `hub.id`, or run a URL monitor).
417
- - The hub stores data in a JSON file: great for tens of servers, not built for thousands.
418
- - p95 latency is computed from the last 200 requests per endpoint.
456
+ - The embedded dashboard keeps data in memory, so it starts fresh when the app restarts. Use the hub for long-term history.
457
+ - In Node `cluster` / PM2 cluster mode, each worker reports separately. Give each one its own `hub.id`, or use an uptime check.
458
+ - The hub stores data in one JSON file: fine for tens of servers, not built for thousands.
459
+ - p95 latency is calculated from the last 200 requests of each endpoint.
419
460
 
420
- ## Development
461
+ ## 🛠 Development
421
462
 
422
463
  ```bash
423
464
  npm install
424
- npm run demo # hub + 2 agents + URL monitor on http://localhost:4000
425
- npm test # node:test suite
465
+ npm run demo # hub + 2 sample APIs + uptime check at http://localhost:4000
466
+ npm test
426
467
  ```
427
468
 
428
- Project layout:
429
-
430
469
  ```
431
- bin/server-lens.js hub CLI
470
+ bin/server-lens.js hub command line
432
471
  src/index.js agent: middleware, instrument(), hub reporter
433
- src/hub.js hub: ingest, URL monitors, persistence
434
- src/dashboard.js UI + JSON API + WebSocket for one or many servers
435
- src/metrics.js counters, minute/hour buckets, ranges
436
- src/source.js local / remote / URL server sources
472
+ src/hub.js hub: ingest, uptime checks, saving history
473
+ src/dashboard.js dashboard page, JSON API and WebSocket
474
+ src/metrics.js counters and minute/hour history
475
+ src/source.js local, remote and URL servers
437
476
  src/logs.js console capture and log buffer
438
477
  public/index.html the whole dashboard UI (no build step)
439
478
  example/ demo scripts
@@ -443,4 +482,4 @@ Issues and pull requests are welcome.
443
482
 
444
483
  ## License
445
484
 
446
- [MIT](LICENSE)
485
+ [MIT](LICENSE) © Sathish Ramasamy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-server-lens",
3
- "version": "0.1.0",
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": {
@@ -37,7 +37,7 @@
37
37
  ],
38
38
  "repository": {
39
39
  "type": "git",
40
- "url": "git+https://github.com/Sathishram2000/Server-Lens.git"
40
+ "url": "git+https://github.com/Sathishram2000/Node-Server-Lens.git"
41
41
  },
42
42
  "license": "MIT",
43
43
  "engines": {
@@ -47,8 +47,8 @@
47
47
  "ws": "^8.18.0"
48
48
  },
49
49
  "author": "Sathish Ramasamy",
50
- "homepage": "https://github.com/Sathishram2000/Server-Lens#readme",
50
+ "homepage": "https://github.com/Sathishram2000/Node-Server-Lens#readme",
51
51
  "bugs": {
52
- "url": "https://github.com/Sathishram2000/Server-Lens/issues"
52
+ "url": "https://github.com/Sathishram2000/Node-Server-Lens/issues"
53
53
  }
54
54
  }
package/public/index.html CHANGED
@@ -247,23 +247,32 @@ td.path{font-family:var(--mono);font-size:14px;max-width:380px;overflow:hidden;t
247
247
  .slow{color:var(--amber)}
248
248
  .tfoot{color:var(--muted);font-size:13px;margin-top:14px}
249
249
 
250
- /* ---------- fleet (hub mode) ---------- */
251
- .fleet{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:14px}
252
- .srvcard{position:relative;text-align:left;padding:18px 20px;border-radius:18px;border:1px solid var(--line);background:rgba(0,0,0,.16);transition:border-color .15s,background .15s;display:flex;flex-direction:column;gap:10px;min-width:0}
253
- .srvcard:hover{border-color:rgba(255,255,255,.2)}
254
- .srvcard.sel{border-color:rgba(211,127,246,.55);background:rgba(211,127,246,.07);box-shadow:0 0 0 1px rgba(211,127,246,.25),0 0 30px -10px rgba(211,127,246,.5)}
255
- .srvcard .nm{display:flex;align-items:center;gap:10px;font-size:17px;padding-right:22px}
256
- .srvcard .nm span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
257
- .srvcard .hs{color:var(--muted);font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
258
- .srvcard .st3{display:flex;gap:16px;font-size:13px;color:var(--muted)}
259
- .srvcard .st3 b{display:block;font-weight:400;font-size:17px;color:var(--text)}
260
- .kind{font-size:11px;letter-spacing:.05em;text-transform:uppercase;padding:2px 8px;border-radius:999px;background:rgba(255,255,255,.06);color:var(--muted);flex:none}
261
- .rm{position:absolute;top:12px;right:12px;color:var(--dim);padding:4px;border-radius:6px;line-height:0}
250
+ /* ---------- server switcher (hub mode) ---------- */
251
+ .switcher{position:relative;min-width:0}
252
+ button.who{cursor:default;text-align:left}
253
+ .hub button.who{cursor:pointer}
254
+ .hub button.who:hover,button.who[aria-expanded="true"]{border-color:rgba(255,255,255,.25);background:rgba(255,255,255,.05)}
255
+ .who .chev{width:14px;height:14px;color:var(--muted);flex:none;transition:transform .2s}
256
+ button.who[aria-expanded="true"] .chev{transform:rotate(180deg)}
257
+ .menu{position:absolute;right:0;top:calc(100% + 10px);z-index:40;width:400px;max-width:calc(100vw - 32px);max-height:min(70vh,560px);overflow:auto;padding:8px;border-radius:22px;border:1px solid var(--line2);background:linear-gradient(180deg,#1c1c1f,#151517);box-shadow:0 30px 60px rgba(0,0,0,.6)}
258
+ .menu-h{display:flex;align-items:center;justify-content:space-between;padding:10px 14px 8px;color:var(--muted);font-size:13px;letter-spacing:.04em;text-transform:uppercase}
259
+ .srvrow{position:relative;display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:4px 12px;align-items:center;padding:12px 14px;border-radius:14px;cursor:pointer;border:1px solid transparent}
260
+ .srvrow:hover,.srvrow:focus-visible{background:rgba(255,255,255,.05)}
261
+ .srvrow.sel{background:rgba(211,127,246,.09);border-color:rgba(211,127,246,.35)}
262
+ .srvrow .nm{display:flex;align-items:center;gap:8px;font-size:15px;min-width:0}
263
+ .srvrow .nm span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
264
+ .srvrow .hs{grid-column:2;color:var(--muted);font-size:12.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
265
+ .srvrow .st{grid-column:3;grid-row:1/3;text-align:right;font-size:12px;color:var(--muted);line-height:1.5;padding:0;background:none;border:0}
266
+ .srvrow .st b{font-weight:400;color:var(--text);font-size:14px}
267
+ .kind{font-size:10.5px;letter-spacing:.05em;text-transform:uppercase;padding:2px 7px;border-radius:999px;background:rgba(255,255,255,.06);color:var(--muted);flex:none;font-style:normal}
268
+ .rm{position:absolute;top:6px;right:6px;color:var(--dim);padding:4px;border-radius:6px;line-height:0;opacity:0}
269
+ .srvrow:hover .rm,.rm:focus-visible{opacity:1}
262
270
  .rm:hover{color:var(--red)}
263
- .srvcard.addnew{align-items:center;justify-content:center;border-style:dashed;color:var(--muted);min-height:130px;font-size:16px;flex-direction:row}
264
- .srvcard.addnew:hover{color:var(--text)}
271
+ .menu-add{display:block;width:100%;margin-top:6px;padding:12px;border-radius:14px;border:1px dashed var(--line2);color:var(--muted);font-size:15px}
272
+ .menu-add:hover{color:var(--text);border-color:rgba(255,255,255,.25)}
265
273
  .dot.down,.dot.offline{background:var(--red)} .dot.pending{background:var(--dim)} .dot.degraded{background:var(--amber)}
266
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}
267
276
  dialog::backdrop{background:rgba(0,0,0,.6);backdrop-filter:blur(4px)}
268
277
  dialog h3{font-weight:300;font-size:28px;letter-spacing:-.02em;margin-bottom:6px}
269
278
  dialog .seg{display:inline-flex;margin:18px 0 20px;flex-wrap:wrap}
@@ -316,7 +325,6 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
316
325
  </div>
317
326
  <nav class="nav">
318
327
  <a href="#/dashboard" data-page="dashboard"><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><path d="M12 3a9 9 0 0 0-9 9v5a3 3 0 0 0 3 3h12a3 3 0 0 0 3-3v-5a9 9 0 0 0-9-9Zm-1 11h2v4h-2z"/></svg>Dashboard</a>
319
- <a href="#/servers" data-page="servers" id="navServers" hidden><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><rect x="3" y="3" width="8" height="8" rx="2.5"/><rect x="13" y="3" width="8" height="8" rx="2.5"/><rect x="3" y="13" width="8" height="8" rx="2.5"/><rect x="13" y="13" width="8" height="8" rx="2.5"/></svg>Servers</a>
320
328
  <a href="#/server" data-page="server"><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><rect x="3" y="4" width="18" height="7" rx="2.5"/><rect x="3" y="13" width="18" height="7" rx="2.5"/><circle cx="7.5" cy="7.5" r="1.2" fill="#0b0b0c"/><circle cx="7.5" cy="16.5" r="1.2" fill="#0b0b0c"/></svg>Server Info</a>
321
329
  <button class="grp" id="grpToggle" aria-expanded="true"><span><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><rect x="3" y="3" width="18" height="18" rx="5"/><path d="M8 16v-5M12 16V8M16 16v-3" stroke="#0b0b0c" stroke-width="2" stroke-linecap="round"/></svg>Analytics</span><svg class="chev" style="transform:rotate(180deg)"><use href="#i-chev"/></svg></button>
322
330
  <div class="sub" id="subNav">
@@ -329,12 +337,13 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
329
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>
330
338
  </nav>
331
339
  <div class="side-bottom">
332
- <nav class="nav"><a href="https://github.com/Sathishram2000/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></nav>
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>
333
342
  <hr>
334
343
  <div class="help">
335
344
  <h4>Like Server Lens?</h4>
336
345
  <p>It's free and open source. A star helps other developers find it.</p>
337
- <a class="btn" href="https://github.com/Sathishram2000/Server-Lens" target="_blank" rel="noopener">Star on GitHub <svg><use href="#i-right"/></svg></a>
346
+ <a class="btn" href="https://github.com/Sathishram2000/Node-Server-Lens" target="_blank" rel="noopener">Star on GitHub <svg><use href="#i-right"/></svg></a>
338
347
  </div>
339
348
  </div>
340
349
  </aside>
@@ -342,18 +351,21 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
342
351
  <main id="top">
343
352
  <header class="top">
344
353
  <h1><button class="iconbtn" id="showSide" aria-label="Show sidebar"><svg width="16" height="16"><use href="#i-right"/></svg></button><span id="pageTitle">Overview</span></h1>
345
- <a class="who" href="#/servers" id="who" title="Switch server">
346
- <span class="avatar" id="avatar">··</span>
347
- <span class="host" id="host">Connecting…</span>
348
- <span class="conn"><span class="dot" id="connDot"></span><span id="connTxt">Offline</span></span>
349
- </a>
354
+ <div class="switcher" id="switcher">
355
+ <button class="who" id="who" aria-haspopup="true" aria-expanded="false" title="Switch server">
356
+ <span class="avatar" id="avatar">··</span>
357
+ <span class="host" id="host">Connecting…</span>
358
+ <span class="conn"><span class="dot" id="connDot"></span><span id="connTxt">Offline</span></span>
359
+ <svg class="chev" id="whoChev" hidden><use href="#i-chev"/></svg>
360
+ </button>
361
+ <div class="menu" id="srvMenu" hidden>
362
+ <div class="menu-h"><span>Servers</span><span class="badge flat" id="fleetCount"></span></div>
363
+ <div id="fleet" role="listbox" aria-label="Servers"></div>
364
+ <button class="menu-add" id="addBtn">+ Add server</button>
365
+ </div>
366
+ </div>
350
367
  </header>
351
368
 
352
- <section class="card pad grid" id="fleetCard" data-pages="servers">
353
- <div class="card-h"><h2>Servers <span class="badge flat" id="fleetCount"></span></h2><button class="pillbtn" id="addBtn">+ Add server</button></div>
354
- <div class="fleet" id="fleet"></div>
355
- </section>
356
-
357
369
  <section class="grid kpis" aria-label="Key metrics" data-pages="dashboard traffic">
358
370
  <div class="card kpi"><div class="lbl">Total Requests</div><div class="val"><span class="num" id="kReq">–</span><span id="kReqB"></span></div></div>
359
371
  <div class="card kpi"><div class="lbl">Avg Response</div><div class="val"><span class="num" id="kAvg">–</span><span id="kAvgB"></span></div></div>
@@ -454,7 +466,7 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
454
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>
455
467
  <div data-p="node">
456
468
  <div class="step">1 · Install the agent</div><pre>npm install node-server-lens</pre>
457
- <div class="step">2 · Add it before your routes (Express, Fastify, Koa, NestJS or plain http)</div>
469
+ <div class="step">2 · Add it before your routes (Express, NestJS or plain http). Fastify, Koa or Hapi: use <span class="mono">instrument()</span> as in the Next.js tab</div>
458
470
  <pre id="snipNode"></pre>
459
471
  </div>
460
472
  <div data-p="next" hidden>
@@ -788,17 +800,17 @@ $('grpToggle').addEventListener('click', () => {
788
800
  $('grpToggle').setAttribute('aria-expanded', String(!open));
789
801
  });
790
802
  /* ---------- pages (hash router) ---------- */
791
- const PAGES = { dashboard: 'Overview', servers: 'Servers', server: 'Server Info', traffic: 'Traffic', status: 'Status Codes', logs: 'Live Logs', apis: 'API Endpoints', requests: 'Requests' };
803
+ const PAGES = { dashboard: 'Overview', server: 'Server Info', traffic: 'Traffic', status: 'Status Codes', logs: 'Live Logs', apis: 'API Endpoints', requests: 'Requests' };
792
804
  let page = 'dashboard';
793
805
  function route() {
794
- let p = location.hash.replace(/^#\/?/, '') || (CFG.hub ? 'servers' : 'dashboard');
795
- if (!PAGES[p] || (p === 'servers' && !CFG.hub)) p = 'dashboard';
806
+ let p = location.hash.replace(/^#\/?/, '') || 'dashboard';
807
+ if (!PAGES[p]) p = 'dashboard';
796
808
  page = p;
797
809
  document.querySelectorAll('[data-pages]').forEach((el) => (el.hidden = !el.dataset.pages.split(' ').includes(p)));
798
810
  $('row2').classList.toggle('single', p !== 'dashboard');
799
811
  $('pageTitle').textContent = PAGES[p];
800
812
  document.title = `${PAGES[p]} · ${CFG.title}`;
801
- document.body.className = 'page-' + p;
813
+ document.body.className = 'page-' + p + (CFG.hub ? ' hub' : '');
802
814
  document.querySelectorAll('[data-page]').forEach((a) => a.classList.toggle('active', a.dataset.page === p));
803
815
  $('app').classList.remove('drawer');
804
816
  scrollTo(0, 0);
@@ -806,27 +818,42 @@ function route() {
806
818
  if (p === 'logs') box.scrollTop = box.scrollHeight;
807
819
  }
808
820
  addEventListener('hashchange', route);
809
- $('navServers').hidden = !CFG.hub;
810
- if (!CFG.hub) $('who').removeAttribute('href');
821
+ if (CFG.signOut) { $('signOut').hidden = false; $('signOut').action = `${CFG.base}/logout`; }
822
+
823
+ /* ---------- server switcher ---------- */
824
+ const menu = $('srvMenu');
825
+ function toggleMenu(open = menu.hidden) {
826
+ if (!CFG.hub) return;
827
+ menu.hidden = !open;
828
+ $('who').setAttribute('aria-expanded', String(open));
829
+ if (open) (menu.querySelector('.srvrow.sel') || menu.querySelector('.srvrow'))?.focus();
830
+ }
831
+ if (CFG.hub) { document.body.classList.add('hub'); $('whoChev').hidden = false; }
832
+ $('who').addEventListener('click', () => toggleMenu());
833
+ document.addEventListener('click', (e) => { if (!menu.hidden && !e.target.closest('#switcher')) toggleMenu(false); });
834
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !menu.hidden) { toggleMenu(false); $('who').focus(); } });
811
835
 
812
836
  /* ---------- data flow ---------- */
813
837
  const snapSeen = (s) => (s.servers || []).find((x) => x.id === s.id)?.lastSeen;
814
838
  function renderFleet(s) {
815
839
  if (!CFG.hub || !s.servers) return;
816
840
  $('fleetCount').textContent = s.servers.length;
817
- $('fleet').innerHTML = s.servers.map((x) => `<div class="srvcard${x.id === s.id ? ' sel' : ''}" role="button" tabindex="0" data-sid="${esc(x.id)}">
818
- ${x.id !== 'hub' ? `<button class="rm" data-rm="${esc(x.id)}" aria-label="Remove ${esc(x.name)}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg></button>` : ''}
819
- <div class="nm"><span class="dot ${x.health === 'healthy' ? 'ok' : esc(x.health)}"></span><span>${esc(x.name)}</span><em class="kind">${x.kind === 'url' ? 'URL' : x.id === 'hub' ? 'Hub' : 'Agent'}</em></div>
841
+ const keep = menu.contains(document.activeElement) && document.activeElement.dataset.sid;
842
+ $('fleet').innerHTML = s.servers.map((x) => `<div class="srvrow${x.id === s.id ? ' sel' : ''}" role="option" aria-selected="${x.id === s.id}" tabindex="0" data-sid="${esc(x.id)}">
843
+ <span class="dot ${x.health === 'healthy' ? 'ok' : esc(x.health)}" title="${esc(x.health)}"></span>
844
+ <div class="nm"><span>${esc(x.name)}</span><em class="kind">${x.kind === 'url' ? 'URL' : x.id === 'hub' ? 'Hub' : 'Agent'}</em></div>
845
+ <div class="st"><b>${compact(x.count)}</b> req/h<br>${x.count ? ms(x.avgMs) : '–'} · <span class="${x.errors ? 'err' : ''}">${x.count ? ((x.errors / x.count) * 100).toFixed(1) + '%' : '–'}</span></div>
820
846
  <div class="hs">${esc(x.url || x.host || '')}</div>
821
- <div class="st3"><div><b>${compact(x.count)}</b>req / 1h</div><div><b>${x.count ? ms(x.avgMs) : '–'}</b>avg</div><div><b class="${x.errors ? 'err' : ''}">${x.count ? ((x.errors / x.count) * 100).toFixed(1) + '%' : '–'}</b>errors</div></div>
822
- </div>`).join('') + `<button class="srvcard addnew" data-add>+ Add server</button>`;
847
+ ${x.id !== 'hub' ? `<button class="rm" data-rm="${esc(x.id)}" aria-label="Remove ${esc(x.name)}"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg></button>` : ''}
848
+ </div>`).join('');
849
+ if (keep) menu.querySelector(`[data-sid="${CSS.escape(keep)}"]`)?.focus();
823
850
  }
824
851
  function select(id) {
825
852
  if (!ws || ws.readyState !== 1) return;
826
- if (snap && snap.id === id) { location.hash = '#/dashboard'; return; }
853
+ toggleMenu(false);
854
+ if (snap && snap.id === id) return;
827
855
  try { localStorage.setItem('sl-server', id); } catch {}
828
856
  ws.send(JSON.stringify({ type: 'subscribe', id }));
829
- location.hash = '#/dashboard';
830
857
  }
831
858
  $('fleet').addEventListener('click', async (e) => {
832
859
  const rm = e.target.closest('[data-rm]');
@@ -837,10 +864,13 @@ $('fleet').addEventListener('click', async (e) => {
837
864
  if (snap && snap.id === rm.dataset.rm) ws.send(JSON.stringify({ type: 'subscribe', id: 'hub' }));
838
865
  return;
839
866
  }
840
- if (e.target.closest('[data-add]')) return openAdd();
841
867
  const c = e.target.closest('[data-sid]'); if (c) select(c.dataset.sid);
842
868
  });
843
- $('fleet').addEventListener('keydown', (e) => { const c = e.target.closest('[data-sid]'); if (c && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); select(c.dataset.sid); } });
869
+ $('fleet').addEventListener('keydown', (e) => {
870
+ const c = e.target.closest('[data-sid]'); if (!c) return;
871
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); select(c.dataset.sid); }
872
+ else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); (e.key === 'ArrowDown' ? c.nextElementSibling : c.previousElementSibling)?.focus(); }
873
+ });
844
874
 
845
875
  /* ---------- connect dialog ---------- */
846
876
  const hubUrl = location.origin + CFG.base;
@@ -870,7 +900,7 @@ $('snipApi').textContent = `curl -X POST ${hubUrl}/api/ingest \\
870
900
  "requests": [{ "ts": 1733040000000, "method": "GET", "route": "/invoices/:id", "status": 200, "ms": 18 }],
871
901
  "logs": [{ "ts": 1733040000000, "level": "info", "msg": "invoice sent" }]
872
902
  }'`;
873
- function openAdd() { $('addDlg').showModal(); }
903
+ function openAdd() { toggleMenu(false); $('addDlg').showModal(); }
874
904
  $('addBtn').addEventListener('click', openAdd);
875
905
  $('addTabs').addEventListener('click', (e) => {
876
906
  const b = e.target.closest('button'); if (!b) return;
@@ -914,7 +944,7 @@ function connect() {
914
944
  setConn(false, 'Reconnecting…');
915
945
  retry++;
916
946
  // server restarted → our token is stale; reload once the server answers again
917
- 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(() => {});
918
948
  setTimeout(connect, Math.min(10000, 500 * 2 ** retry));
919
949
  };
920
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
- const h = req.headers.authorization || '';
35
- if (!h.startsWith('Basic ')) return false;
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
- res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Server Lens"', 'Content-Type': 'text/plain' });
110
- return res.end('Authentication required');
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));