node-server-lens 0.0.0-stage → 0.1.0
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 +21 -0
- package/README.md +445 -2
- package/bin/server-lens.js +44 -0
- package/package.json +52 -4
- package/public/index.html +929 -0
- package/src/dashboard.js +143 -0
- package/src/hub.js +153 -0
- package/src/index.d.ts +80 -0
- package/src/index.js +145 -0
- package/src/logs.js +46 -0
- package/src/metrics.js +212 -0
- package/src/source.js +112 -0
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,446 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Server Lens
|
|
2
2
|
|
|
3
|
-
|
|
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)
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
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. |
|
|
51
|
+
|
|
52
|
+
Also: health endpoint for load balancers, optional basic auth, URL uptime monitors with down/recovery log lines, auto-reconnect, mobile layout.
|
|
53
|
+
|
|
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
|
+
```
|
|
71
|
+
|
|
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.
|
|
74
|
+
|
|
75
|
+
## Quick start (try the demo)
|
|
76
|
+
|
|
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)
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
npm install node-server-lens
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
const express = require('express');
|
|
94
|
+
const serverLens = require('node-server-lens');
|
|
95
|
+
|
|
96
|
+
const app = express();
|
|
97
|
+
app.use(serverLens()); // add before your routes
|
|
98
|
+
|
|
99
|
+
app.get('/api/users', (req, res) => res.json([]));
|
|
100
|
+
app.listen(3000);
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Open http://localhost:3000/server-lens. That's it: the WebSocket attaches itself to your HTTP server on the first request.
|
|
104
|
+
|
|
105
|
+
> In production, always protect it: `serverLens({ auth: { username: 'admin', password: process.env.LENS_PASSWORD } })`.
|
|
106
|
+
|
|
107
|
+
## Option B: the hub (many servers)
|
|
108
|
+
|
|
109
|
+
Start a hub (needs Node 18+):
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
npx node-server-lens --port 4000 --key "$(openssl rand -hex 24)" --user admin --pass 'change-me'
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
or from a clone:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
SERVER_LENS_KEY=your-secret SERVER_LENS_USER=admin SERVER_LENS_PASS=change-me npm run hub
|
|
119
|
+
```
|
|
120
|
+
|
|
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.
|
|
122
|
+
|
|
123
|
+
## Connecting servers
|
|
124
|
+
|
|
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.
|
|
126
|
+
|
|
127
|
+
### Express / Connect / plain `http`
|
|
128
|
+
|
|
129
|
+
```js
|
|
130
|
+
const serverLens = require('node-server-lens');
|
|
131
|
+
|
|
132
|
+
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
|
|
136
|
+
}));
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Plain Node `http`:
|
|
140
|
+
|
|
141
|
+
```js
|
|
142
|
+
const http = require('http');
|
|
143
|
+
const lens = require('node-server-lens')();
|
|
144
|
+
|
|
145
|
+
http.createServer((req, res) => lens(req, res, () => {
|
|
146
|
+
// your handler
|
|
147
|
+
res.end('ok');
|
|
148
|
+
})).listen(3000);
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
With Express, routes are grouped by their pattern (`/users/:id`). Elsewhere, numeric, UUID and long hex path segments are replaced with `:id`.
|
|
152
|
+
|
|
153
|
+
### Next.js
|
|
154
|
+
|
|
155
|
+
Works with `next start` and `next dev` (Node runtime, App or Pages router).
|
|
156
|
+
|
|
157
|
+
1. `npm install node-server-lens`
|
|
158
|
+
2. Create `instrumentation.ts` (or `.js`) at the project root (or in `src/`):
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
export async function register() {
|
|
162
|
+
if (process.env.NEXT_RUNTIME === 'nodejs') {
|
|
163
|
+
const { instrument } = await import('node-server-lens');
|
|
164
|
+
instrument({
|
|
165
|
+
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
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
3. Keep the package out of the bundle in `next.config.js`:
|
|
174
|
+
|
|
175
|
+
```js
|
|
176
|
+
module.exports = { serverExternalPackages: ['node-server-lens'] };
|
|
177
|
+
// Next.js 14: module.exports = { experimental: { serverComponentsExternalPackages: ['node-server-lens'] } };
|
|
178
|
+
```
|
|
179
|
+
|
|
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).
|
|
181
|
+
|
|
182
|
+
### Fastify, Koa, NestJS, Hapi (any Node server)
|
|
183
|
+
|
|
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:
|
|
185
|
+
|
|
186
|
+
```js
|
|
187
|
+
require('node-server-lens').instrument({
|
|
188
|
+
name: 'billing',
|
|
189
|
+
hub: { url: 'https://lens.example.com', key: process.env.SERVER_LENS_KEY },
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
// ...then start Fastify / Koa / Nest as usual
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
NestJS on the Express adapter can also use `app.use(serverLens())` in `main.ts`.
|
|
196
|
+
|
|
197
|
+
### Any URL, no code (uptime checks)
|
|
198
|
+
|
|
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.
|
|
200
|
+
|
|
201
|
+
### Python, Go, PHP, Java, Ruby… (HTTP ingest API)
|
|
202
|
+
|
|
203
|
+
Send JSON to the hub from any language. Batch it (for example every 5 seconds):
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
curl -X POST https://lens.example.com/api/ingest \
|
|
207
|
+
-H "Authorization: Bearer $SERVER_LENS_KEY" \
|
|
208
|
+
-H "Content-Type: application/json" \
|
|
209
|
+
-d '{
|
|
210
|
+
"id": "billing-go-1",
|
|
211
|
+
"name": "Billing (Go)",
|
|
212
|
+
"info": { "hostname": "billing-1", "runtime": "Go 1.23", "port": 8080 },
|
|
213
|
+
"sample": { "cpu": 12.5, "rss": 73400320, "lag": 0 },
|
|
214
|
+
"requests": [{ "ts": 1764590000000, "method": "GET", "route": "/invoices/:id", "path": "/invoices/91", "status": 200, "ms": 18, "ip": "10.0.0.4" }],
|
|
215
|
+
"logs": [{ "ts": 1764590000000, "level": "info", "msg": "invoice sent" }]
|
|
216
|
+
}'
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Python (Flask) example:
|
|
220
|
+
|
|
221
|
+
```python
|
|
222
|
+
import os, time, threading, requests
|
|
223
|
+
from flask import Flask, request, g
|
|
224
|
+
|
|
225
|
+
app = Flask(__name__)
|
|
226
|
+
HUB, KEY, buf = "https://lens.example.com/api/ingest", os.environ["SERVER_LENS_KEY"], []
|
|
227
|
+
|
|
228
|
+
@app.before_request
|
|
229
|
+
def start(): g.t = time.time()
|
|
230
|
+
|
|
231
|
+
@app.after_request
|
|
232
|
+
def record(resp):
|
|
233
|
+
buf.append({"ts": int(time.time() * 1000), "method": request.method,
|
|
234
|
+
"route": request.url_rule.rule if request.url_rule else request.path,
|
|
235
|
+
"path": request.path, "status": resp.status_code,
|
|
236
|
+
"ms": (time.time() - g.t) * 1000, "ip": request.remote_addr})
|
|
237
|
+
return resp
|
|
238
|
+
|
|
239
|
+
def flush():
|
|
240
|
+
while True:
|
|
241
|
+
time.sleep(5)
|
|
242
|
+
batch = buf[:]; del buf[:len(batch)]
|
|
243
|
+
try:
|
|
244
|
+
requests.post(HUB, json={"id": "flask-api", "name": "Flask API", "requests": batch},
|
|
245
|
+
headers={"Authorization": f"Bearer {KEY}"}, timeout=5)
|
|
246
|
+
except Exception:
|
|
247
|
+
buf[:0] = batch # retry next round
|
|
248
|
+
|
|
249
|
+
threading.Thread(target=flush, daemon=True).start()
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
| Field | Type | Notes |
|
|
253
|
+
| --- | --- | --- |
|
|
254
|
+
| `id` | string, required | `[A-Za-z0-9_.-]{1,64}`, stable per server |
|
|
255
|
+
| `name` | string | display name |
|
|
256
|
+
| `info` | object | `hostname`, `runtime`, `platform`, `arch`, `cpuModel`, `env`, `port`, `pid`, `cpus`, `totalMem`, `startedAt`, `uptime`, `osUptime`, `ips[]` |
|
|
257
|
+
| `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` |
|
|
260
|
+
|
|
261
|
+
A server shows as **offline** if it hasn't reported for 20 seconds.
|
|
262
|
+
|
|
263
|
+
### Custom loggers (pino, winston)
|
|
264
|
+
|
|
265
|
+
`console.*` is captured automatically. To forward another logger:
|
|
266
|
+
|
|
267
|
+
```js
|
|
268
|
+
const lens = serverLens();
|
|
269
|
+
app.use(lens);
|
|
270
|
+
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
|
+
```
|
|
275
|
+
|
|
276
|
+
## Hosting the hub
|
|
277
|
+
|
|
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.
|
|
279
|
+
|
|
280
|
+
### Docker
|
|
281
|
+
|
|
282
|
+
```bash
|
|
283
|
+
docker build -t server-lens .
|
|
284
|
+
docker run -d --name server-lens -p 4000:4000 \
|
|
285
|
+
-e SERVER_LENS_KEY=your-long-random-key \
|
|
286
|
+
-e SERVER_LENS_USER=admin -e SERVER_LENS_PASS=change-me \
|
|
287
|
+
-v server-lens-data:/data \
|
|
288
|
+
--restart unless-stopped server-lens
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
`docker-compose.yml`:
|
|
292
|
+
|
|
293
|
+
```yaml
|
|
294
|
+
services:
|
|
295
|
+
server-lens:
|
|
296
|
+
build: .
|
|
297
|
+
ports: ["4000:4000"]
|
|
298
|
+
environment:
|
|
299
|
+
SERVER_LENS_KEY: ${SERVER_LENS_KEY}
|
|
300
|
+
SERVER_LENS_USER: admin
|
|
301
|
+
SERVER_LENS_PASS: ${SERVER_LENS_PASS}
|
|
302
|
+
volumes: ["lens-data:/data"]
|
|
303
|
+
restart: unless-stopped
|
|
304
|
+
volumes:
|
|
305
|
+
lens-data:
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
### VPS with PM2 + Nginx (HTTPS)
|
|
309
|
+
|
|
310
|
+
```bash
|
|
311
|
+
git clone https://github.com/Sathishram2000/Server-Lens.git && cd Server-Lens
|
|
312
|
+
npm ci --omit=dev
|
|
313
|
+
npm install -g pm2
|
|
314
|
+
SERVER_LENS_KEY=... SERVER_LENS_USER=admin SERVER_LENS_PASS=... \
|
|
315
|
+
SERVER_LENS_DATA=/var/lib/server-lens/data.json \
|
|
316
|
+
pm2 start bin/server-lens.js --name server-lens
|
|
317
|
+
pm2 save && pm2 startup
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
Nginx (WebSocket upgrade headers are required for live updates):
|
|
321
|
+
|
|
322
|
+
```nginx
|
|
323
|
+
server {
|
|
324
|
+
server_name lens.example.com;
|
|
325
|
+
location / {
|
|
326
|
+
proxy_pass http://127.0.0.1:4000;
|
|
327
|
+
proxy_http_version 1.1;
|
|
328
|
+
proxy_set_header Upgrade $http_upgrade;
|
|
329
|
+
proxy_set_header Connection "upgrade";
|
|
330
|
+
proxy_set_header Host $host;
|
|
331
|
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
332
|
+
proxy_read_timeout 1h;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
```
|
|
336
|
+
|
|
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.
|
|
338
|
+
|
|
339
|
+
### Render / Railway / Fly.io
|
|
340
|
+
|
|
341
|
+
Any platform that runs a Docker image or a Node process and supports WebSockets works:
|
|
342
|
+
|
|
343
|
+
| Setting | Value |
|
|
344
|
+
| --- | --- |
|
|
345
|
+
| Build | `npm ci --omit=dev` (or use the included `Dockerfile`) |
|
|
346
|
+
| Start | `node bin/server-lens.js` |
|
|
347
|
+
| Env vars | `SERVER_LENS_KEY`, `SERVER_LENS_USER`, `SERVER_LENS_PASS`, `SERVER_LENS_DATA=/data/server-lens-data.json` |
|
|
348
|
+
| Disk / volume | mount at `/data` so history survives deploys |
|
|
349
|
+
| Instances | exactly 1 |
|
|
350
|
+
|
|
351
|
+
`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
|
+
|
|
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.
|
|
354
|
+
|
|
355
|
+
## Configuration reference
|
|
356
|
+
|
|
357
|
+
### Agent: `serverLens(options)` / `instrument(options)`
|
|
358
|
+
|
|
359
|
+
| Option | Default | Description |
|
|
360
|
+
| --- | --- | --- |
|
|
361
|
+
| `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 |
|
|
365
|
+
| `name` | hostname | Display name |
|
|
366
|
+
| `title` | `'Server Lens'` | Dashboard title |
|
|
367
|
+
| `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) |
|
|
370
|
+
| `maxLogs` | `1000` | Log lines kept in memory |
|
|
371
|
+
| `maxRoutes` | `500` | Distinct endpoints tracked (extra ones are grouped as `METHOD *`) |
|
|
372
|
+
| `maxRecent` | `100` | Recent requests kept |
|
|
373
|
+
|
|
374
|
+
Returned middleware also has: `attach(server)`, `log(level, ...args)`, `snapshot()`, `close()`.
|
|
375
|
+
|
|
376
|
+
### Hub: `server-lens` CLI
|
|
377
|
+
|
|
378
|
+
| Flag | Env | Default |
|
|
379
|
+
| --- | --- | --- |
|
|
380
|
+
| `--port` | `PORT` | `4000` |
|
|
381
|
+
| `--host` | `HOST` | `0.0.0.0` |
|
|
382
|
+
| `--key` | `SERVER_LENS_KEY` | random per run (printed) |
|
|
383
|
+
| `--user` / `--pass` | `SERVER_LENS_USER` / `SERVER_LENS_PASS` | none (open) |
|
|
384
|
+
| `--data` | `SERVER_LENS_DATA` | `./server-lens-data.json` |
|
|
385
|
+
| `--check` | `SERVER_LENS_CHECK` | `30` (seconds between URL checks) |
|
|
386
|
+
| `--title` | `SERVER_LENS_TITLE` | `Server Lens` |
|
|
387
|
+
|
|
388
|
+
Programmatic: `const { createHub } = require('node-server-lens'); createHub({ key, auth, dataFile }).listen(4000);`
|
|
389
|
+
|
|
390
|
+
## HTTP API
|
|
391
|
+
|
|
392
|
+
Paths are relative to the dashboard (`/server-lens` for the agent, `/` for the hub).
|
|
393
|
+
|
|
394
|
+
| Method & path | Auth | Description |
|
|
395
|
+
| --- | --- | --- |
|
|
396
|
+
| `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 |
|
|
404
|
+
|
|
405
|
+
## Security
|
|
406
|
+
|
|
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.
|
|
412
|
+
|
|
413
|
+
## Limitations
|
|
414
|
+
|
|
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.
|
|
419
|
+
|
|
420
|
+
## Development
|
|
421
|
+
|
|
422
|
+
```bash
|
|
423
|
+
npm install
|
|
424
|
+
npm run demo # hub + 2 agents + URL monitor on http://localhost:4000
|
|
425
|
+
npm test # node:test suite
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
Project layout:
|
|
429
|
+
|
|
430
|
+
```
|
|
431
|
+
bin/server-lens.js hub CLI
|
|
432
|
+
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
|
|
437
|
+
src/logs.js console capture and log buffer
|
|
438
|
+
public/index.html the whole dashboard UI (no build step)
|
|
439
|
+
example/ demo scripts
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
Issues and pull requests are welcome.
|
|
443
|
+
|
|
444
|
+
## License
|
|
445
|
+
|
|
446
|
+
[MIT](LICENSE)
|
|
@@ -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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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/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/Server-Lens#readme",
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "https://github.com/Sathishram2000/Server-Lens/issues"
|
|
53
|
+
}
|
|
54
|
+
}
|