node-server-lens 0.0.0-stage → 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sathish Ramasamy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,484 @@
1
- # Temporary Holding Version
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>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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>
19
+
20
+ ---
21
+
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.
23
+
24
+ Use it two ways:
25
+
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 |
32
+
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.
34
+
35
+ ## ⚡ Quick start
36
+
37
+ **1. Install**
38
+
39
+ ```bash
40
+ npm install node-server-lens
41
+ ```
42
+
43
+ **2. Add one line before your routes**
44
+
45
+ ```js
46
+ const serverLens = require('node-server-lens');
47
+
48
+ app.use(serverLens());
49
+ ```
50
+
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.
97
+ ```
98
+
99
+ <details>
100
+ <summary>What the prompt sets up</summary>
101
+
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
+
107
+ Always review the changes before you commit them.
108
+ </details>
109
+
110
+ ## 🖥 What you get
111
+
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. |
122
+
123
+ Also included: a `/health` endpoint for load balancers, optional login, uptime checks with down/recovery alerts in the logs, auto-reconnect, and a mobile layout.
124
+
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>
130
+
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.
133
+
134
+ ## 🔌 Connect your servers
135
+
136
+ Keep keys and passwords in environment variables, never in code. Every option is listed in the [reference](#agent-options).
137
+
138
+ <details open>
139
+ <summary><b>Express · Connect · NestJS (Express adapter) · plain Node http</b></summary>
140
+
141
+ ```js
142
+ const serverLens = require('node-server-lens');
143
+
144
+ app.use(serverLens({
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
148
+ }));
149
+ ```
150
+
151
+ Plain Node `http`:
152
+
153
+ ```js
154
+ const http = require('http');
155
+ const lens = require('node-server-lens')();
156
+
157
+ http.createServer((req, res) => lens(req, res, () => {
158
+ res.end('ok'); // your handler
159
+ })).listen(3000);
160
+ ```
161
+
162
+ ESM works too: `import serverLens from 'node-server-lens'`.
163
+ </details>
164
+
165
+ <details>
166
+ <summary><b>Next.js</b></summary>
167
+
168
+ Works with `next start` and `next dev` (Node.js runtime, App or Pages router).
169
+
170
+ 1. `npm install node-server-lens`
171
+ 2. Create `instrumentation.ts` in the project root (or in `src/` if you use it):
172
+
173
+ ```ts
174
+ export async function register() {
175
+ if (process.env.NEXT_RUNTIME === 'nodejs') {
176
+ const { instrument } = await import('node-server-lens');
177
+ instrument({
178
+ name: 'web',
179
+ auth: { username: 'admin', password: process.env.SERVER_LENS_PASS! },
180
+ hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY! }, // optional
181
+ });
182
+ }
183
+ }
184
+ ```
185
+
186
+ 3. Keep the package out of the bundle in `next.config.js`:
187
+
188
+ ```js
189
+ module.exports = { serverExternalPackages: ['node-server-lens'] };
190
+ // Next.js 14: module.exports = { experimental: { serverComponentsExternalPackages: ['node-server-lens'] } };
191
+ ```
192
+
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>
195
+
196
+ <details>
197
+ <summary><b>Fastify · Koa · Hapi · any other Node server</b></summary>
198
+
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:
200
+
201
+ ```js
202
+ require('node-server-lens').instrument({
203
+ name: 'billing',
204
+ hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY },
205
+ });
206
+
207
+ // ...then start Fastify / Koa / Hapi as usual
208
+ ```
209
+ </details>
210
+
211
+ <details>
212
+ <summary><b>Any website or API, no code (uptime checks)</b></summary>
213
+
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>
216
+
217
+ <details>
218
+ <summary><b>Python · Go · PHP · Ruby · Java (HTTP ingest API)</b></summary>
219
+
220
+ Send batches of JSON to the hub, for example every 5 seconds:
221
+
222
+ ```bash
223
+ curl -X POST https://lens.example.com/api/ingest \
224
+ -H "Authorization: Bearer $SERVER_LENS_KEY" \
225
+ -H "Content-Type: application/json" \
226
+ -d '{
227
+ "id": "billing-go-1",
228
+ "name": "Billing (Go)",
229
+ "info": { "hostname": "billing-1", "runtime": "Go 1.23", "port": 8080 },
230
+ "sample": { "cpu": 12.5, "rss": 73400320, "lag": 0 },
231
+ "requests": [{ "ts": 1764590000000, "method": "GET", "route": "/invoices/:id", "path": "/invoices/91", "status": 200, "ms": 18, "ip": "10.0.0.4" }],
232
+ "logs": [{ "ts": 1764590000000, "level": "info", "msg": "invoice sent" }]
233
+ }'
234
+ ```
235
+
236
+ Python (Flask) example:
237
+
238
+ ```python
239
+ import os, time, threading, requests
240
+ from flask import Flask, request, g
241
+
242
+ app = Flask(__name__)
243
+ HUB, KEY, buf = os.environ["SERVER_LENS_HUB_URL"] + "/api/ingest", os.environ["SERVER_LENS_KEY"], []
244
+
245
+ @app.before_request
246
+ def start(): g.t = time.time()
247
+
248
+ @app.after_request
249
+ def record(resp):
250
+ buf.append({"ts": int(time.time() * 1000), "method": request.method,
251
+ "route": request.url_rule.rule if request.url_rule else request.path,
252
+ "path": request.path, "status": resp.status_code,
253
+ "ms": (time.time() - g.t) * 1000, "ip": request.remote_addr})
254
+ return resp
255
+
256
+ def flush():
257
+ while True:
258
+ time.sleep(5)
259
+ batch = buf[:]; del buf[:len(batch)]
260
+ try:
261
+ requests.post(HUB, json={"id": "flask-api", "name": "Flask API", "requests": batch},
262
+ headers={"Authorization": f"Bearer {KEY}"}, timeout=5)
263
+ except Exception:
264
+ buf[:0] = batch # retry next round
265
+
266
+ threading.Thread(target=flush, daemon=True).start()
267
+ ```
268
+
269
+ <a id="ingest-schema"></a>
270
+
271
+ | Field | Type | Notes |
272
+ | --- | --- | --- |
273
+ | `id` | string, required | `[A-Za-z0-9_.-]{1,64}`, the same on every report |
274
+ | `name` | string | display name |
275
+ | `info` | object | `hostname`, `runtime`, `platform`, `arch`, `cpuModel`, `env`, `port`, `pid`, `cpus`, `totalMem`, `startedAt`, `uptime`, `osUptime`, `ips[]` |
276
+ | `sample` | object | latest stats: `cpu` (%), `sysCpu` (%), `rss`, `heapUsed`, `freeMem` (bytes), `lag` (ms), `load` ([1, 5, 15]) |
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` |
279
+
280
+ A server shows as **offline** when it hasn't reported for 20 seconds.
281
+ </details>
282
+
283
+ <details>
284
+ <summary><b>Other loggers (pino, winston…)</b></summary>
285
+
286
+ `console.*` is captured automatically. To forward another logger, call `lens.log(level, ...args)`:
287
+
288
+ ```js
289
+ const lens = serverLens();
290
+ app.use(lens);
291
+ lens.log('warn', 'disk usage at', 91, '%');
292
+ ```
293
+ </details>
294
+
295
+ ## 🚀 Host the hub
296
+
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**.
298
+
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>
307
+
308
+ ```bash
309
+ git clone https://github.com/Sathishram2000/Node-Server-Lens.git && cd Node-Server-Lens
310
+ docker build -t server-lens .
311
+ docker run -d --name server-lens -p 4000:4000 \
312
+ -e SERVER_LENS_KEY=your-long-random-key \
313
+ -e SERVER_LENS_USER=admin -e SERVER_LENS_PASS=change-me \
314
+ -v server-lens-data:/data \
315
+ --restart unless-stopped server-lens
316
+ ```
317
+
318
+ `docker-compose.yml`:
319
+
320
+ ```yaml
321
+ services:
322
+ server-lens:
323
+ build: .
324
+ ports: ["4000:4000"]
325
+ environment:
326
+ SERVER_LENS_KEY: ${SERVER_LENS_KEY}
327
+ SERVER_LENS_USER: admin
328
+ SERVER_LENS_PASS: ${SERVER_LENS_PASS}
329
+ volumes: ["lens-data:/data"]
330
+ restart: unless-stopped
331
+ volumes:
332
+ lens-data:
333
+ ```
334
+ </details>
335
+
336
+ <details>
337
+ <summary><b>VPS with PM2 + Nginx (HTTPS)</b></summary>
338
+
339
+ ```bash
340
+ git clone https://github.com/Sathishram2000/Node-Server-Lens.git && cd Node-Server-Lens
341
+ npm ci --omit=dev
342
+ npm install -g pm2
343
+ SERVER_LENS_KEY=... SERVER_LENS_USER=admin SERVER_LENS_PASS=... \
344
+ SERVER_LENS_DATA=/var/lib/server-lens/data.json \
345
+ pm2 start bin/server-lens.js --name server-lens
346
+ pm2 save && pm2 startup
347
+ ```
348
+
349
+ Nginx needs the WebSocket upgrade headers for live updates:
350
+
351
+ ```nginx
352
+ server {
353
+ server_name lens.example.com;
354
+ location / {
355
+ proxy_pass http://127.0.0.1:4000;
356
+ proxy_http_version 1.1;
357
+ proxy_set_header Upgrade $http_upgrade;
358
+ proxy_set_header Connection "upgrade";
359
+ proxy_set_header Host $host;
360
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
361
+ proxy_read_timeout 1h;
362
+ }
363
+ }
364
+ ```
365
+
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>
368
+
369
+ <details>
370
+ <summary><b>Render · Railway · Fly.io · any container platform</b></summary>
371
+
372
+ Any platform that runs a Docker image or a Node process and supports WebSockets works:
373
+
374
+ | Setting | Value |
375
+ | --- | --- |
376
+ | Build | `npm ci --omit=dev`, or use the included `Dockerfile` |
377
+ | Start | `node bin/server-lens.js` |
378
+ | Env vars | `SERVER_LENS_KEY`, `SERVER_LENS_USER`, `SERVER_LENS_PASS`, `SERVER_LENS_DATA=/data/server-lens-data.json` |
379
+ | Disk / volume | mount at `/data` so history survives deploys |
380
+ | Instances | exactly 1 |
381
+
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.
383
+
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>
386
+
387
+ ## 📖 Reference
388
+
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>
393
+
394
+ | Option | Default | Description |
395
+ | --- | --- | --- |
396
+ | `path` | `'/server-lens'` | Where the embedded dashboard is served |
397
+ | `auth` | none | `{ username, password }` for a login, or `(req) => boolean` |
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 |
400
+ | `name` | hostname | Display name |
401
+ | `title` | `'Server Lens'` | Dashboard title |
402
+ | `captureConsole` | `true` | Capture `console.*` into live logs |
403
+ | `ignore` | `[]` | Path prefixes or RegExps not to record (`instrument` also skips `/_next/` and `/favicon.ico`) |
404
+ | `interval` | `2000` | Live update interval in ms |
405
+ | `maxLogs` | `1000` | Log lines kept in memory |
406
+ | `maxRoutes` | `500` | Distinct endpoints tracked; extras are grouped as `METHOD *` |
407
+ | `maxRecent` | `100` | Recent requests kept |
408
+
409
+ The returned middleware also has `attach(server)`, `log(level, ...args)`, `snapshot()` and `close()`. TypeScript types are included.
410
+ </details>
411
+
412
+ <details>
413
+ <summary><b>Hub options</b>: <code>npx node-server-lens</code></summary>
414
+
415
+ | Flag | Environment variable | Default |
416
+ | --- | --- | --- |
417
+ | `--port` | `PORT` | `4000` |
418
+ | `--host` | `HOST` | `0.0.0.0` |
419
+ | `--key` | `SERVER_LENS_KEY` | random for each run (printed at start) |
420
+ | `--user` / `--pass` | `SERVER_LENS_USER` / `SERVER_LENS_PASS` | none (open) |
421
+ | `--data` | `SERVER_LENS_DATA` | `./server-lens-data.json` |
422
+ | `--check` | `SERVER_LENS_CHECK` | `30` seconds between uptime checks |
423
+ | `--title` | `SERVER_LENS_TITLE` | `Server Lens` |
424
+
425
+ From code: `const { createHub } = require('node-server-lens'); createHub({ key, auth, dataFile }).listen(4000);`
426
+ </details>
427
+
428
+ <details>
429
+ <summary><b>HTTP API</b></summary>
430
+
431
+ Paths are relative to the dashboard: `/server-lens` for the agent, `/` for the hub.
432
+
433
+ | Method & path | Auth | Description |
434
+ | --- | --- | --- |
435
+ | `GET /health` | none | `{ status, uptime, timestamp }` for load balancers |
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>
444
+
445
+ ## 🔒 Security
446
+
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
+ - **Use HTTPS** in front of the hub, because the login and the ingest key travel in request headers.
449
+ - 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
+ - The live connection needs a random per-process token that only appears in the logged-in page.
451
+ - Uptime checks make the hub request URLs that logged-in users enter. Only give dashboard access to people you trust.
452
+
453
+ ## ⚠️ Limitations
454
+
455
+ - The embedded dashboard keeps data in memory, so it starts fresh when the app restarts. Use the hub for long-term history.
456
+ - In Node `cluster` / PM2 cluster mode, each worker reports separately. Give each one its own `hub.id`, or use an uptime check.
457
+ - The hub stores data in one JSON file: fine for tens of servers, not built for thousands.
458
+ - p95 latency is calculated from the last 200 requests of each endpoint.
459
+
460
+ ## 🛠 Development
461
+
462
+ ```bash
463
+ npm install
464
+ npm run demo # hub + 2 sample APIs + uptime check at http://localhost:4000
465
+ npm test
466
+ ```
467
+
468
+ ```
469
+ bin/server-lens.js hub command line
470
+ src/index.js agent: middleware, instrument(), hub reporter
471
+ src/hub.js hub: ingest, uptime checks, saving history
472
+ src/dashboard.js dashboard page, JSON API and WebSocket
473
+ src/metrics.js counters and minute/hour history
474
+ src/source.js local, remote and URL servers
475
+ src/logs.js console capture and log buffer
476
+ public/index.html the whole dashboard UI (no build step)
477
+ example/ demo scripts
478
+ ```
479
+
480
+ Issues and pull requests are welcome.
481
+
482
+ ## License
483
+
484
+ [MIT](LICENSE) © Sathish Ramasamy
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ const crypto = require('crypto');
4
+ const { createHub } = require('../src/hub');
5
+
6
+ const argv = process.argv.slice(2);
7
+ if (argv.includes('-h') || argv.includes('--help')) {
8
+ console.log(`Server Lens hub: one dashboard for all your servers.
9
+
10
+ Usage: server-lens [hub] [options]
11
+
12
+ --port <n> Port to listen on (env PORT, default 4000)
13
+ --host <addr> Interface to bind (env HOST, default 0.0.0.0)
14
+ --key <secret> Ingest key agents must send (env SERVER_LENS_KEY, generated if empty)
15
+ --user <name> Dashboard basic-auth user (env SERVER_LENS_USER)
16
+ --pass <pass> Dashboard basic-auth pass (env SERVER_LENS_PASS)
17
+ --data <file> Where history is stored (env SERVER_LENS_DATA, default ./server-lens-data.json)
18
+ --check <sec> URL monitor interval (env SERVER_LENS_CHECK, default 30)
19
+ --title <text> Dashboard title`);
20
+ process.exit(0);
21
+ }
22
+ const arg = (name, env, def) => {
23
+ const i = argv.indexOf(`--${name}`);
24
+ return i >= 0 && argv[i + 1] ? argv[i + 1] : process.env[env] || def;
25
+ };
26
+
27
+ let key = arg('key', 'SERVER_LENS_KEY');
28
+ if (!key) {
29
+ key = crypto.randomBytes(18).toString('base64url');
30
+ console.log(`No ingest key set; generated one for this run: ${key}\nSet SERVER_LENS_KEY to keep it stable across restarts.`);
31
+ }
32
+ const user = arg('user', 'SERVER_LENS_USER'), pass = arg('pass', 'SERVER_LENS_PASS');
33
+ if (!user) console.warn('Warning: the dashboard has no login. Set SERVER_LENS_USER and SERVER_LENS_PASS before exposing it publicly.');
34
+
35
+ const port = Number(arg('port', 'PORT', 4000));
36
+ const host = arg('host', 'HOST', '0.0.0.0');
37
+ const hub = createHub({
38
+ key,
39
+ auth: user ? { username: user, password: pass || '' } : undefined,
40
+ dataFile: arg('data', 'SERVER_LENS_DATA'),
41
+ checkInterval: Number(arg('check', 'SERVER_LENS_CHECK', 30)),
42
+ title: arg('title', 'SERVER_LENS_TITLE', 'Server Lens'),
43
+ });
44
+ hub.listen(port, host, () => console.log(`Server Lens hub running at http://localhost:${port}`));
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "node-server-lens",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
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
+ "main": "src/index.js",
6
+ "bin": {
7
+ "server-lens": "bin/server-lens.js"
8
+ },
9
+ "types": "src/index.d.ts",
10
+ "files": [
11
+ "src",
12
+ "public",
13
+ "bin",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "scripts": {
18
+ "demo": "node example/demo.js",
19
+ "hub": "node bin/server-lens.js",
20
+ "test": "node --test",
21
+ "prepublishOnly": "npm test"
22
+ },
23
+ "keywords": [
24
+ "nextjs",
25
+ "uptime",
26
+ "hub",
27
+ "self-hosted",
28
+ "monitoring",
29
+ "dashboard",
30
+ "express",
31
+ "middleware",
32
+ "logs",
33
+ "metrics",
34
+ "websocket",
35
+ "status",
36
+ "apm"
37
+ ],
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/Sathishram2000/Node-Server-Lens.git"
41
+ },
42
+ "license": "MIT",
43
+ "engines": {
44
+ "node": ">=18"
45
+ },
46
+ "dependencies": {
47
+ "ws": "^8.18.0"
48
+ },
49
+ "author": "Sathish Ramasamy",
50
+ "homepage": "https://github.com/Sathishram2000/Node-Server-Lens#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/Sathishram2000/Node-Server-Lens/issues"
53
+ }
54
+ }