node-server-lens 0.1.2 → 0.1.4

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
@@ -21,38 +21,49 @@
21
21
 
22
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
23
 
24
- Use it two ways:
24
+ Setup is **4 values**. Put the same four in your hub and in every app you want to watch:
25
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 |
26
+ ```bash
27
+ SERVER_LENS_USER=admin # hub login
28
+ SERVER_LENS_PASS=a-strong-password # hub login
29
+ SERVER_LENS_HUB_URL=https://lens.example.com # where your hub runs
30
+ SERVER_LENS_KEY=a-long-random-key # servers must send this to be accepted
31
+ ```
32
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.
33
+ No database, no build step, one dependency (`ws`). Works with **Next.js, Express, Fastify, Koa, NestJS, Hapi, plain Node**, and **any other language** over HTTP.
34
34
 
35
35
  ## ⚡ Quick start
36
36
 
37
- **1. Install**
37
+ **1. Start the hub** in a folder with a `.env` file containing the 4 values. It reads them, signs you in with `SERVER_LENS_USER` and `SERVER_LENS_PASS`, and listens on the port in `SERVER_LENS_HUB_URL`:
38
38
 
39
39
  ```bash
40
- npm install node-server-lens
40
+ npx node-server-lens
41
41
  ```
42
42
 
43
- **2. Add one line before your routes**
43
+ Generate a key with `openssl rand -hex 24`. For hosting it properly, see [Host the hub](#-host-the-hub).
44
44
 
45
- ```js
46
- const serverLens = require('node-server-lens');
45
+ **2. Connect an app.** Install the package:
47
46
 
48
- app.use(serverLens());
47
+ ```bash
48
+ npm install node-server-lens
49
49
  ```
50
50
 
51
- **3. Open** `http://localhost:3000/server-lens` (use your app's port).
51
+ Add the connection code for your framework:
52
+
53
+ | Framework | Connection code |
54
+ | --- | --- |
55
+ | **Next.js** | `instrumentation.ts`: `export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') (await import('node-server-lens')).instrument(); }`<br>and in `next.config`: `serverExternalPackages: ['node-server-lens']` |
56
+ | **Express / NestJS** | `app.use(require('node-server-lens')());` before your routes |
57
+ | **Fastify, Koa, Hapi, any Node** | `require('node-server-lens').instrument();` at the top of your entry file |
58
+ | **Other languages** | [HTTP ingest API](#ingest-schema) |
59
+
60
+ Put the same 4 values in the app's `.env` (`.env.local` for Next.js) and restart it.
52
61
 
53
- That's it. Using Next.js, Fastify or Koa instead? See [Connect your servers](#-connect-your-servers).
62
+ **3. Open your hub URL and sign in.** The app shows up within a few seconds. Repeat step 2 for every server you want to watch.
54
63
 
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.
64
+ > **No hub?** Leave out `SERVER_LENS_HUB_URL` and the app serves its own dashboard at `/server-lens` instead (signed in with `SERVER_LENS_USER` / `SERVER_LENS_PASS`). That's handy for local development.
65
+ >
66
+ > **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.
56
67
 
57
68
  ## 🤖 Set up with an AI coding agent
58
69
 
@@ -63,45 +74,39 @@ Add Server Lens monitoring (npm package "node-server-lens", docs: https://github
63
74
 
64
75
  1. Detect the backend framework and language from the project files.
65
76
  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 });
77
+ 3. Add the connection code. It needs no options: the package reads its settings from environment variables.
78
+ Match the project's module style (ESM import or CommonJS require) and use TypeScript if the project does.
79
+ - Next.js: create instrumentation.ts (in src/ if the project uses src/, otherwise the project root):
80
+ export async function register() {
81
+ if (process.env.NEXT_RUNTIME === 'nodejs') (await import('node-server-lens')).instrument();
74
82
  }
75
- }
83
+ If instrumentation.ts already exists, add that line inside its register() function.
76
84
  Then add 'node-server-lens' to serverExternalPackages in next.config
77
85
  (Next.js 14: experimental.serverComponentsExternalPackages).
86
+ - Express, Connect, or NestJS on the Express adapter: in the file that creates the app, add
87
+ app.use(require('node-server-lens')()) BEFORE any routes.
78
88
  - 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).
89
+ before the server starts, call require('node-server-lens').instrument().
81
90
  - Not Node.js (Python, Go, PHP, Ruby, Java, .NET...): do not install the npm package. Add a small
82
91
  middleware that records method, route pattern, path, status, duration in ms, client IP and timestamp
83
92
  for each request, batches them, and POSTs them every 5 seconds to `${SERVER_LENS_HUB_URL}/api/ingest`
84
93
  with the header "Authorization: Bearer ${SERVER_LENS_KEY}", using the JSON format in the
85
94
  "HTTP ingest API" section of the docs. Only run it when both variables are set, and never let a
86
95
  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.
96
+ 4. Add these 4 variables with empty values to .env.example (create it if missing), and tell me to fill
97
+ them in my real env file (.env.local for Next.js, .env otherwise). Never commit real secrets.
98
+ SERVER_LENS_USER=
99
+ SERVER_LENS_PASS=
100
+ SERVER_LENS_HUB_URL=
101
+ SERVER_LENS_KEY=
102
+ 5. Tell me which files you changed, and remind me to restart the app after setting the values.
97
103
  ```
98
104
 
99
105
  <details>
100
106
  <summary>What the prompt sets up</summary>
101
107
 
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`.
108
+ - The app reports to your hub as soon as the 4 values are set. It appears in the hub's server switcher under its `package.json` name (override with `SERVER_LENS_NAME`).
103
109
  - **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
110
  - Nothing secret is written to the code; values come from environment variables.
106
111
 
107
112
  Always review the changes before you commit them.
@@ -120,7 +125,7 @@ Always review the changes before you commit them.
120
125
  | **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
126
  | **Requests** | The latest requests with method, path, status, duration and client IP. Search and an "errors only" filter. |
122
127
 
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.
128
+ Also included: a styled sign-in page with 7-day sessions and a sign-out button, a `/health` endpoint for load balancers, uptime checks with down/recovery alerts in the logs, auto-reconnect, and a mobile layout.
124
129
 
125
130
  ## 🧭 How it works
126
131
 
@@ -133,78 +138,57 @@ Also included: a `/health` endpoint for load balancers, optional login, uptime c
133
138
 
134
139
  ## 🔌 Connect your servers
135
140
 
136
- Keep keys and passwords in environment variables, never in code. Every option is listed in the [reference](#agent-options).
141
+ Every app needs the package, one piece of connection code, and the 4 values in its environment (see [Quick start](#-quick-start)). Optional extras are in the [reference](#agent-options).
137
142
 
138
143
  <details open>
139
- <summary><b>Express · Connect · NestJS (Express adapter) · plain Node http</b></summary>
144
+ <summary><b>Next.js</b></summary>
140
145
 
141
- ```js
142
- const serverLens = require('node-server-lens');
146
+ Works with `next dev`, `next start` and custom servers (Node.js runtime, App or Pages router).
143
147
 
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
- }));
148
+ `instrumentation.ts` in the project root (or `src/`):
149
+
150
+ ```ts
151
+ export async function register() {
152
+ if (process.env.NEXT_RUNTIME === 'nodejs') (await import('node-server-lens')).instrument();
153
+ }
149
154
  ```
150
155
 
151
- Plain Node `http`:
156
+ `next.config.js` / `next.config.ts`:
152
157
 
153
158
  ```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);
159
+ module.exports = { serverExternalPackages: ['node-server-lens'] };
160
+ // Next.js 14: module.exports = { experimental: { serverComponentsExternalPackages: ['node-server-lens'] } };
160
161
  ```
161
162
 
162
- ESM works too: `import serverLens from 'node-server-lens'`.
163
+ `.env.local`: the 4 values. Restart the dev server after changing them.
164
+
165
+ Pages and API routes are recorded and `/_next/*` assets are skipped. Edge runtime routes aren't captured, because they don't run in Node.
163
166
  </details>
164
167
 
165
168
  <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):
169
+ <summary><b>Express · Connect · NestJS (Express adapter) · plain Node http</b></summary>
172
170
 
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
- }
171
+ ```js
172
+ app.use(require('node-server-lens')()); // before your routes
184
173
  ```
185
174
 
186
- 3. Keep the package out of the bundle in `next.config.js`:
175
+ Plain Node `http`:
187
176
 
188
177
  ```js
189
- module.exports = { serverExternalPackages: ['node-server-lens'] };
190
- // Next.js 14: module.exports = { experimental: { serverComponentsExternalPackages: ['node-server-lens'] } };
178
+ const lens = require('node-server-lens')();
179
+ http.createServer((req, res) => lens(req, res, () => res.end('ok'))).listen(3000);
191
180
  ```
192
181
 
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.
182
+ ESM: `import serverLens from 'node-server-lens'; app.use(serverLens());`
194
183
  </details>
195
184
 
196
185
  <details>
197
186
  <summary><b>Fastify · Koa · Hapi · any other Node server</b></summary>
198
187
 
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:
188
+ `instrument()` hooks into Node's own `http`/`https` servers, so it works with any framework without touching your routes. Put it at the top of your entry file, before the server starts:
200
189
 
201
190
  ```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
191
+ require('node-server-lens').instrument();
208
192
  ```
209
193
  </details>
210
194
 
@@ -297,6 +281,8 @@ lens.log('warn', 'disk usage at', 91, '%');
297
281
  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
282
 
299
283
  ```bash
284
+ npx node-server-lens # reads ./.env (the 4 values)
285
+ # or pass them directly:
300
286
  npx node-server-lens --port 4000 --key "$(openssl rand -hex 24)" --user admin --pass 'change-me'
301
287
  ```
302
288
 
@@ -394,10 +380,10 @@ Serverless platforms (Vercel functions, AWS Lambda) aren't a good fit for the **
394
380
  | Option | Default | Description |
395
381
  | --- | --- | --- |
396
382
  | `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 |
383
+ | `hub` | from `SERVER_LENS_HUB_URL` + `SERVER_LENS_KEY` | `{ url, key, id?, name?, interval? }`; `false` turns reporting off |
384
+ | `auth` | from `SERVER_LENS_USER` + `SERVER_LENS_PASS` | Login for the in-app dashboard: `{ username, password }`, or `(req) => boolean` for your own auth |
385
+ | `dashboard` | on only when no hub is set | `true` serves `/server-lens` inside the app even when reporting to a hub |
386
+ | `name` | `SERVER_LENS_NAME`, else `package.json` name, else hostname | Name shown in the hub |
401
387
  | `title` | `'Server Lens'` | Dashboard title |
402
388
  | `captureConsole` | `true` | Capture `console.*` into live logs |
403
389
  | `ignore` | `[]` | Path prefixes or RegExps not to record (`instrument` also skips `/_next/` and `/favicon.ico`) |
@@ -414,7 +400,8 @@ The returned middleware also has `attach(server)`, `log(level, ...args)`, `snaps
414
400
 
415
401
  | Flag | Environment variable | Default |
416
402
  | --- | --- | --- |
417
- | `--port` | `PORT` | `4000` |
403
+ | `--env` | | `./.env` if it exists (loads the `SERVER_LENS_*` values; Node 20.12+) |
404
+ | `--port` | `PORT` | the port in `SERVER_LENS_HUB_URL`, else `4000` |
418
405
  | `--host` | `HOST` | `0.0.0.0` |
419
406
  | `--key` | `SERVER_LENS_KEY` | random for each run (printed at start) |
420
407
  | `--user` / `--pass` | `SERVER_LENS_USER` / `SERVER_LENS_PASS` | none (open) |
@@ -445,7 +432,8 @@ Paths are relative to the dashboard: `/server-lens` for the agent, `/` for the h
445
432
  ## 🔒 Security
446
433
 
447
434
  - **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.
435
+ - **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.
436
+ - **Use HTTPS** in front of the hub, because the session cookie and the ingest key travel in request headers.
449
437
  - 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
438
  - The live connection needs a random per-process token that only appears in the logged-in page.
451
439
  - Uptime checks make the hub request URLs that logged-in users enter. Only give dashboard access to people you trust.
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
+ const fs = require('fs');
3
4
  const crypto = require('crypto');
4
5
  const { createHub } = require('../src/hub');
5
6
 
@@ -9,16 +10,28 @@ if (argv.includes('-h') || argv.includes('--help')) {
9
10
 
10
11
  Usage: server-lens [hub] [options]
11
12
 
12
- --port <n> Port to listen on (env PORT, default 4000)
13
+ --env <file> Load settings from this file (default: ./.env if present)
14
+ --port <n> Port to listen on (env PORT, else the port in SERVER_LENS_HUB_URL, else 4000)
13
15
  --host <addr> Interface to bind (env HOST, default 0.0.0.0)
14
16
  --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
+ --user <name> Dashboard login username (env SERVER_LENS_USER)
18
+ --pass <pass> Dashboard login password (env SERVER_LENS_PASS)
17
19
  --data <file> Where history is stored (env SERVER_LENS_DATA, default ./server-lens-data.json)
18
20
  --check <sec> URL monitor interval (env SERVER_LENS_CHECK, default 30)
19
21
  --title <text> Dashboard title`);
20
22
  process.exit(0);
21
23
  }
24
+ // Load the same SERVER_LENS_* values the apps use, from --env <file> or ./.env
25
+ const envIdx = argv.indexOf('--env');
26
+ const envFile = envIdx >= 0 ? argv[envIdx + 1] : fs.existsSync('.env') ? '.env' : null;
27
+ if (envFile) {
28
+ try {
29
+ if (!process.loadEnvFile) throw new Error('needs Node.js 20.12 or newer (or pass the values as env vars / flags)');
30
+ process.loadEnvFile(envFile); console.log(`Loaded settings from ${envFile}`);
31
+ }
32
+ catch (e) { console.error(`Could not load ${envFile}: ${e.message}`); if (envIdx >= 0) process.exit(1); }
33
+ }
34
+
22
35
  const arg = (name, env, def) => {
23
36
  const i = argv.indexOf(`--${name}`);
24
37
  return i >= 0 && argv[i + 1] ? argv[i + 1] : process.env[env] || def;
@@ -32,7 +45,9 @@ if (!key) {
32
45
  const user = arg('user', 'SERVER_LENS_USER'), pass = arg('pass', 'SERVER_LENS_PASS');
33
46
  if (!user) console.warn('Warning: the dashboard has no login. Set SERVER_LENS_USER and SERVER_LENS_PASS before exposing it publicly.');
34
47
 
35
- const port = Number(arg('port', 'PORT', 4000));
48
+ let urlPort;
49
+ try { urlPort = new URL(process.env.SERVER_LENS_HUB_URL).port; } catch { /* not set */ }
50
+ const port = Number(arg('port', 'PORT', urlPort || 4000));
36
51
  const host = arg('host', 'HOST', '0.0.0.0');
37
52
  const hub = createHub({
38
53
  key,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-server-lens",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Self-hosted, real-time monitoring for all your servers: live logs over WebSocket, request traffic with week/month/year history, API stats, uptime checks. Express, Next.js, any Node server, or any language over HTTP.",
5
5
  "main": "src/index.js",
6
6
  "bin": {
package/public/index.html CHANGED
@@ -272,6 +272,7 @@ button.who[aria-expanded="true"] .chev{transform:rotate(180deg)}
272
272
  .menu-add:hover{color:var(--text);border-color:rgba(255,255,255,.25)}
273
273
  .dot.down,.dot.offline{background:var(--red)} .dot.pending{background:var(--dim)} .dot.degraded{background:var(--amber)}
274
274
  dialog{margin:auto;width:min(680px,calc(100% - 32px));max-height:calc(100% - 32px);border-radius:24px;border:1px solid var(--line2);background:linear-gradient(180deg,#1b1b1e,#151517);color:var(--text);padding:30px 32px;box-shadow:0 40px 80px rgba(0,0,0,.6)}
275
+ dialog:focus,dialog:focus-visible{outline:none}
275
276
  dialog::backdrop{background:rgba(0,0,0,.6);backdrop-filter:blur(4px)}
276
277
  dialog h3{font-weight:300;font-size:28px;letter-spacing:-.02em;margin-bottom:6px}
277
278
  dialog .seg{display:inline-flex;margin:18px 0 20px;flex-wrap:wrap}
@@ -282,14 +283,6 @@ dialog input.in{width:100%;padding:12px 16px;border-radius:14px;border:1px solid
282
283
  dialog input.in:focus{border-color:rgba(211,127,246,.6)}
283
284
  .btn.primary{background:linear-gradient(180deg,#e09cff,#b866e6);color:#160a1c;border:0;font-weight:500}
284
285
  .dlg-foot{display:flex;justify-content:flex-end;gap:10px;margin-top:22px}
285
- .onboard-only{display:none}
286
- #addDlg.onboard .onboard-only{display:flex}
287
- #addDlg.onboard [data-close]{display:none}
288
- .welcome{align-items:center;gap:8px;color:var(--green);font-size:14px;margin-bottom:10px}
289
- .onboard-foot{align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-top:24px;padding-top:20px;border-top:1px solid var(--line)}
290
- .onboard-foot .muted{display:flex;align-items:center;gap:10px;font-size:14px}
291
- .dot.wait{animation:blink 1.4s ease-in-out infinite}
292
- @keyframes blink{50%{opacity:.25}}
293
286
  .formerr{color:var(--red);font-size:14px;margin-top:10px;min-height:1em}
294
287
  @media (max-width:1280px){.kpis{grid-template-columns:repeat(2,minmax(0,1fr))}.row2,.srv{grid-template-columns:minmax(0,1fr)}}
295
288
  @media (max-width:900px){
@@ -344,7 +337,8 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
344
337
  <a href="#/requests" data-page="requests"><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><path d="M21 3 3 10.5l7 2.5 2.5 7z"/></svg>Requests</a>
345
338
  </nav>
346
339
  <div class="side-bottom">
347
- <nav class="nav"><a href="https://github.com/Sathishram2000/Node-Server-Lens#readme" target="_blank" rel="noopener"><svg viewBox="0 0 24 24" fill="currentColor" opacity=".8"><path d="M6 3h9l4 4v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z"/><path d="M8 12h8M8 16h5" stroke="#0b0b0c" stroke-width="1.8" stroke-linecap="round"/></svg>Documentation</a></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>
348
342
  <hr>
349
343
  <div class="help">
350
344
  <h4>Like Server Lens?</h4>
@@ -467,20 +461,26 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
467
461
  </div>
468
462
 
469
463
  <dialog id="addDlg">
470
- <div class="onboard-only welcome"><span class="dot ok"></span>Your hub is running</div>
471
- <h3 id="dlgTitle">Connect a server</h3>
472
- <p class="muted" id="dlgSub">Pick how this server should report to the hub.</p>
464
+ <h3>Connect a server</h3>
465
+ <p class="muted">Pick how this server should report to the hub.</p>
473
466
  <div class="seg" id="addTabs"><button data-t="node" class="on">Node.js / Express</button><button data-t="next">Next.js</button><button data-t="url">Any URL</button><button data-t="api">Other languages</button></div>
474
467
  <div data-p="node">
475
- <div class="step">1 · Install the agent</div><pre>npm install node-server-lens</pre>
476
- <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>
477
- <pre id="snipNode"></pre>
468
+ <div class="step">1 · Install</div><pre>npm install node-server-lens</pre>
469
+ <div class="step">2 · Add one line before your routes (Express, NestJS, plain http)</div>
470
+ <pre>app.use(require('node-server-lens')());</pre>
471
+ <div class="step">Fastify, Koa, Hapi or anything else: put this at the top of your entry file instead</div>
472
+ <pre>require('node-server-lens').instrument();</pre>
473
+ <div class="step">3 · Add these values to the app's <span class="mono">.env</span> and restart it</div>
474
+ <pre class="snipEnv"></pre>
478
475
  </div>
479
476
  <div data-p="next" hidden>
480
- <div class="step">1 · <span class="mono">npm install node-server-lens</span>, then add <span class="mono">instrumentation.ts</span> at the project root</div>
477
+ <div class="step">1 · Install</div><pre>npm install node-server-lens</pre>
478
+ <div class="step">2 · Create <span class="mono">instrumentation.ts</span> in the project root (or <span class="mono">src/</span>)</div>
481
479
  <pre id="snipNext"></pre>
482
- <div class="step">2 · Keep it out of the bundle in <span class="mono">next.config.js</span></div>
483
- <pre>module.exports = { serverExternalPackages: ['node-server-lens'] };</pre>
480
+ <div class="step">3 · In <span class="mono">next.config</span>, keep it out of the bundle</div>
481
+ <pre>serverExternalPackages: ['node-server-lens'],</pre>
482
+ <div class="step">4 · Add these values to <span class="mono">.env.local</span> and restart</div>
483
+ <pre class="snipEnv"></pre>
484
484
  </div>
485
485
  <form data-p="url" hidden id="urlForm">
486
486
  <p class="muted">No code needed. The hub checks the URL every 30 seconds and tracks uptime and response time: works for Python, Go, PHP, Java, Rails, static sites, anything with HTTP.</p>
@@ -494,10 +494,6 @@ dialog input.in:focus{border-color:rgba(211,127,246,.6)}
494
494
  <pre id="snipApi"></pre>
495
495
  </div>
496
496
  <div class="dlg-foot" id="dlgFoot"><button class="btn" data-close>Done</button></div>
497
- <div class="onboard-only onboard-foot">
498
- <span class="muted"><span class="dot pending wait"></span>Waiting for your first server… this closes by itself once it reports in.</span>
499
- <a class="btn primary" href="https://github.com/Sathishram2000/Node-Server-Lens#-connect-your-servers" target="_blank" rel="noopener">Open setup guide <svg><use href="#i-right"/></svg></a>
500
- </div>
501
497
  </dialog>
502
498
 
503
499
  <script>
@@ -829,6 +825,8 @@ function route() {
829
825
  if (p === 'logs') box.scrollTop = box.scrollHeight;
830
826
  }
831
827
  addEventListener('hashchange', route);
828
+ if (CFG.signOut) { $('signOut').hidden = false; $('signOut').action = `${CFG.base}/logout`; }
829
+
832
830
  /* ---------- server switcher ---------- */
833
831
  const menu = $('srvMenu');
834
832
  function toggleMenu(open = menu.hidden) {
@@ -883,20 +881,13 @@ $('fleet').addEventListener('keydown', (e) => {
883
881
 
884
882
  /* ---------- connect dialog ---------- */
885
883
  const hubUrl = location.origin + CFG.base;
886
- $('snipNode').textContent = `const serverLens = require('node-server-lens');
887
-
888
- app.use(serverLens({
889
- name: 'orders-api',
890
- hub: { url: '${hubUrl}', key: process.env.SERVER_LENS_KEY },
891
- }));`;
884
+ const envVals = `SERVER_LENS_USER=your-hub-username
885
+ SERVER_LENS_PASS=your-hub-password
886
+ SERVER_LENS_HUB_URL=${hubUrl}
887
+ SERVER_LENS_KEY=your-hub-key`;
888
+ document.querySelectorAll('.snipEnv').forEach((el) => (el.textContent = envVals));
892
889
  $('snipNext').textContent = `export async function register() {
893
- if (process.env.NEXT_RUNTIME === 'nodejs') {
894
- const { instrument } = await import('node-server-lens');
895
- instrument({
896
- name: 'web',
897
- hub: { url: '${hubUrl}', key: process.env.SERVER_LENS_KEY },
898
- });
899
- }
890
+ if (process.env.NEXT_RUNTIME === 'nodejs') (await import('node-server-lens')).instrument();
900
891
  }`;
901
892
  $('snipApi').textContent = `curl -X POST ${hubUrl}/api/ingest \\
902
893
  -H "Authorization: Bearer $SERVER_LENS_KEY" \\
@@ -917,22 +908,7 @@ $('addTabs').addEventListener('click', (e) => {
917
908
  $('addDlg').querySelectorAll('[data-p]').forEach((p) => (p.hidden = p.dataset.p !== b.dataset.t));
918
909
  $('dlgFoot').hidden = b.dataset.t === 'url';
919
910
  });
920
- $('addDlg').addEventListener('click', (e) => { if (!onboarding && (e.target.closest('[data-close]') || e.target === $('addDlg'))) $('addDlg').close(); });
921
- $('addDlg').addEventListener('cancel', (e) => { if (onboarding) e.preventDefault(); }); // Escape can't dismiss first-run setup
922
-
923
- /* ---------- first run: nothing connected yet ---------- */
924
- let onboarding = false;
925
- function checkOnboarding(s) {
926
- const none = CFG.hub && s.servers && s.servers.every((x) => x.id === 'hub');
927
- if (none === onboarding) return;
928
- onboarding = none;
929
- const d = $('addDlg');
930
- d.classList.toggle('onboard', none);
931
- $('dlgTitle').textContent = none ? 'Connect your first server' : 'Connect a server';
932
- $('dlgSub').textContent = none ? 'Nothing is reporting to this hub yet. Pick your stack below, or open the setup guide for every option.' : 'Pick how this server should report to the hub.';
933
- if (none) { toggleMenu(false); if (!d.open) d.showModal(); }
934
- else { if (d.open) d.close(); const first = s.servers.find((x) => x.id !== 'hub'); if (first && s.id === 'hub') select(first.id); } // jump to the server that just connected
935
- }
911
+ $('addDlg').addEventListener('click', (e) => { if (e.target.closest('[data-close]') || e.target === $('addDlg')) $('addDlg').close(); });
936
912
  $('urlForm').addEventListener('submit', async (e) => {
937
913
  e.preventDefault();
938
914
  $('mErr').textContent = '';
@@ -947,7 +923,6 @@ function apply(s) {
947
923
  if (snap && snap.id !== s.id) { ipsKey = ''; hoverIdx = null; }
948
924
  snap = s;
949
925
  renderFleet(s);
950
- checkOnboarding(s);
951
926
  renderHeader(s); renderTraffic(); renderDonut(s); renderServer(s); renderApis(); renderRecent();
952
927
  }
953
928
  function setConn(on, txt) {
@@ -969,7 +944,7 @@ function connect() {
969
944
  setConn(false, 'Reconnecting…');
970
945
  retry++;
971
946
  // server restarted → our token is stale; reload once the server answers again
972
- if (retry > 2) fetch(API, { cache: 'no-store' }).then((r) => { if (r.ok) location.reload(); }).catch(() => {});
947
+ if (retry > 2) fetch(API, { cache: 'no-store' }).then((r) => { if (r.ok || r.status === 401) location.reload(); }) // 401: session expired → login page.catch(() => {});
973
948
  setTimeout(connect, Math.min(10000, 500 * 2 ** retry));
974
949
  };
975
950
  }
@@ -0,0 +1,113 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>Sign in · Server Lens</title>
7
+ <link rel="preconnect" href="https://fonts.googleapis.com">
8
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
9
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap" rel="stylesheet">
10
+ <style>
11
+ :root{
12
+ --line:rgba(255,255,255,.075);--line2:rgba(255,255,255,.12);--text:#f2f2f4;--muted:#8c8c93;
13
+ --purple:#d37ff6;--lime:#c2ec44;--red:#ff5d72;--redbg:rgba(255,80,100,.13);
14
+ --noise:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='3' stitchTiles='stitch'/%3E%3CfeColorMatrix type='saturate' values='0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
15
+ }
16
+ *{box-sizing:border-box;margin:0;padding:0}
17
+ body{
18
+ min-height:100vh;display:grid;place-items:center;padding:24px 16px;
19
+ font-family:'Inter',ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;font-weight:300;color:var(--text);-webkit-font-smoothing:antialiased;
20
+ background:radial-gradient(1100px 700px at 90% 110%,#262629 0%,transparent 60%),radial-gradient(800px 500px at 10% -10%,#1a1a1d 0%,transparent 60%),#0b0b0c;
21
+ }
22
+ body::after{content:"";position:fixed;inset:0;background:var(--noise);opacity:.07;pointer-events:none;mix-blend-mode:overlay}
23
+ .card{
24
+ position:relative;width:min(420px,100%);padding:40px 36px 34px;border-radius:28px;border:1px solid var(--line);
25
+ background:linear-gradient(180deg,rgba(255,255,255,.045),rgba(255,255,255,.012));
26
+ box-shadow:inset 0 1px 0 rgba(255,255,255,.05),0 40px 80px -30px rgba(0,0,0,.8);
27
+ }
28
+ .card::after{content:"";position:absolute;inset:0;border-radius:inherit;background:var(--noise);opacity:.09;mix-blend-mode:overlay;pointer-events:none}
29
+ .logo{display:flex;align-items:center;gap:12px;font-size:22px;font-weight:400;letter-spacing:-.02em;margin-bottom:34px}
30
+ .logo svg{width:30px;height:30px}
31
+ h1{font-weight:300;font-size:32px;letter-spacing:-.025em;margin-bottom:8px}
32
+ .sub{color:var(--muted);font-size:15px;margin-bottom:28px}
33
+ label{display:block;color:var(--muted);font-size:14px;margin:0 0 8px}
34
+ .field{position:relative;margin-bottom:18px}
35
+ input{
36
+ width:100%;padding:14px 18px;border-radius:16px;border:1px solid var(--line2);background:rgba(0,0,0,.28);
37
+ color:var(--text);font:inherit;font-size:16px;font-weight:400;outline:0;transition:border-color .15s,box-shadow .15s;
38
+ }
39
+ input:focus{border-color:rgba(211,127,246,.65);box-shadow:0 0 0 4px rgba(211,127,246,.12)}
40
+ .field input[type=password],.field input.pw{padding-right:72px}
41
+ .show{position:absolute;right:10px;bottom:9px;padding:6px 10px;border-radius:10px;border:0;background:rgba(255,255,255,.06);color:var(--muted);font:inherit;font-size:13px;cursor:pointer}
42
+ .show:hover{color:var(--text)}
43
+ .err{display:none;align-items:center;gap:8px;padding:11px 14px;border-radius:12px;background:var(--redbg);color:var(--red);font-size:14px;margin:4px 0 16px}
44
+ .err.on{display:flex}
45
+ button.go{
46
+ width:100%;margin-top:8px;padding:14px;border:0;border-radius:999px;cursor:pointer;
47
+ background:linear-gradient(180deg,#e9aaff,#b866e6);color:#160a1c;font:inherit;font-size:16px;font-weight:500;
48
+ box-shadow:0 10px 30px -10px rgba(214,128,250,.7);transition:filter .15s,transform .1s;
49
+ }
50
+ button.go:hover{filter:brightness(1.06)}
51
+ button.go:active{transform:translateY(1px)}
52
+ button.go[disabled]{opacity:.6;cursor:wait}
53
+ .foot{display:flex;align-items:center;gap:8px;justify-content:center;color:var(--muted);font-size:13px;margin-top:22px}
54
+ .dot{width:7px;height:7px;border-radius:50%;background:#4fd16b}
55
+ :focus-visible{outline:2px solid var(--purple);outline-offset:2px}
56
+ @media (prefers-reduced-motion:reduce){*{transition:none!important}}
57
+ </style>
58
+ </head>
59
+ <body>
60
+ <main class="card">
61
+ <div class="logo">
62
+ <svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="12.5" fill="none" stroke="#c2ec44" stroke-width="5"/><circle cx="16" cy="16" r="4.5" fill="#f2f2f4"/></svg>
63
+ <span id="title">Server Lens</span>
64
+ </div>
65
+ <h1>Welcome back</h1>
66
+ <p class="sub">Sign in to view your servers.</p>
67
+ <form id="f" method="post" action="__SL_LOGIN__" novalidate>
68
+ <div class="err" id="err" role="alert"></div>
69
+ <div class="field">
70
+ <label for="u">Username</label>
71
+ <input id="u" name="username" autocomplete="username" autocapitalize="off" spellcheck="false" required autofocus>
72
+ </div>
73
+ <div class="field">
74
+ <label for="p">Password</label>
75
+ <input id="p" name="password" type="password" class="pw" autocomplete="current-password" required>
76
+ <button type="button" class="show" id="show" aria-label="Show password">Show</button>
77
+ </div>
78
+ <button class="go" id="go">Sign in</button>
79
+ </form>
80
+ <div class="foot"><span class="dot"></span>Secure session · stays signed in for 7 days</div>
81
+ </main>
82
+ <script>
83
+ (() => {
84
+ const CFG = __SL_CONFIG__;
85
+ document.getElementById('title').textContent = CFG.title;
86
+ document.title = 'Sign in · ' + CFG.title;
87
+ const f = document.getElementById('f'), err = document.getElementById('err'), go = document.getElementById('go'), p = document.getElementById('p');
88
+ const fail = (m) => { err.textContent = m; err.classList.add('on'); };
89
+ if (CFG.error) fail(CFG.error);
90
+ document.getElementById('show').addEventListener('click', (e) => {
91
+ const on = p.type === 'password';
92
+ p.type = on ? 'text' : 'password';
93
+ e.currentTarget.textContent = on ? 'Hide' : 'Show';
94
+ e.currentTarget.setAttribute('aria-label', on ? 'Hide password' : 'Show password');
95
+ });
96
+ f.addEventListener('submit', async (e) => {
97
+ e.preventDefault();
98
+ err.classList.remove('on');
99
+ if (!f.username.value || !p.value) return fail('Enter your username and password.');
100
+ go.disabled = true; go.textContent = 'Signing in…';
101
+ try {
102
+ const r = await fetch(CFG.login, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: f.username.value, password: p.value }), credentials: 'same-origin' });
103
+ if (r.ok) return location.replace(CFG.next);
104
+ const out = await r.json().catch(() => ({}));
105
+ fail(out.error || 'Sign in failed.');
106
+ p.select();
107
+ } catch { fail('Cannot reach the server. Try again.'); }
108
+ go.disabled = false; go.textContent = 'Sign in';
109
+ });
110
+ })();
111
+ </script>
112
+ </body>
113
+ </html>
package/src/dashboard.js CHANGED
@@ -6,6 +6,9 @@ const crypto = require('crypto');
6
6
  const { WebSocketServer } = require('ws');
7
7
 
8
8
  const HTML = fs.readFileSync(path.join(__dirname, '..', 'public', 'index.html'), 'utf8');
9
+ const LOGIN = fs.readFileSync(path.join(__dirname, '..', 'public', 'login.html'), 'utf8');
10
+ const SESSION_DAYS = 7;
11
+ const MAX_FAILS = 10, FAIL_WINDOW = 15 * 60 * 1000;
9
12
  const hash = (s) => crypto.createHash('sha256').update(String(s)).digest();
10
13
  const safeEqual = (a, b) => crypto.timingSafeEqual(hash(a), hash(b));
11
14
 
@@ -28,12 +31,66 @@ function createDashboard({ base, title = 'Server Lens', auth, interval = 2000, h
28
31
 
29
32
  const send = (ws, msg) => { try { ws.send(JSON.stringify(msg)); } catch { /* socket gone */ } };
30
33
 
34
+ // Sessions: a signed "expiry.signature" cookie. The key comes from the credentials, so sessions
35
+ // survive restarts and changing the password signs everyone out.
36
+ const login = auth && typeof auth === 'object';
37
+ const key = login ? hash(`server-lens-session:${base}:${auth.username}:${auth.password}`) : null;
38
+ const sign = (v) => crypto.createHmac('sha256', key).update(String(v)).digest('base64url');
39
+ const cookieName = login ? 'sl_' + sign('cookie-name').slice(0, 10) : '';
40
+ const fails = new Map(); // ip -> { n, first }
41
+
42
+ function validSession(req) {
43
+ const m = (req.headers.cookie || '').match(new RegExp(`(?:^|;\\s*)${cookieName}=([^;]+)`));
44
+ if (!m) return false;
45
+ const [exp, sig] = decodeURIComponent(m[1]).split('.');
46
+ return Number(exp) > Date.now() && !!sig && safeEqual(sig, sign(exp));
47
+ }
48
+
31
49
  function authorized(req) {
32
50
  if (!auth) return true;
33
51
  if (typeof auth === 'function') return !!auth(req);
34
- 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));
package/src/hub.js CHANGED
@@ -22,7 +22,8 @@ function createHub(opts = {}) {
22
22
  const self = localSource({ id: 'hub', name: opts.name || 'Server Lens Hub', captureConsole: opts.captureConsole !== false });
23
23
  const sources = new Map([[self.id, self]]);
24
24
  // hub itself is listed last so the first real server is the default view
25
- const list = () => [...sources.values()].filter((s) => s !== self).concat(self);
25
+ const rank = (s) => (s.health() === 'offline' || s.health() === 'down' ? 1 : 0);
26
+ const list = () => [...sources.values()].filter((s) => s !== self).sort((a, b) => rank(a) - rank(b)).concat(self); // live servers first
26
27
  const dash = createDashboard({ base, title: opts.title || 'Server Lens', auth: opts.auth, interval: opts.interval, hub: true, sources: { list, get: (id) => sources.get(id) } });
27
28
  dash.watch(self);
28
29
 
package/src/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export interface HubTarget {
10
10
  id?: string;
11
11
  /** Display name in the hub. Default: `name` option or hostname */
12
12
  name?: string;
13
- /** Push interval in ms. Default 5000 */
13
+ /** Push interval in ms. Default 2000 */
14
14
  interval?: number;
15
15
  }
16
16
 
@@ -21,10 +21,10 @@ export interface ServerLensOptions {
21
21
  name?: string;
22
22
  /** Protect the dashboard with basic auth or a custom check */
23
23
  auth?: { username: string; password: string } | ((req: IncomingMessage) => boolean);
24
- /** Set false to only report to a hub (no embedded dashboard) */
24
+ /** In-app dashboard at `path`. Default: on only when no hub is configured */
25
25
  dashboard?: boolean;
26
- /** Report this server to a Server Lens hub */
27
- hub?: HubTarget;
26
+ /** Report to a hub. Default: from SERVER_LENS_HUB_URL + SERVER_LENS_KEY; false to disable */
27
+ hub?: HubTarget | false;
28
28
  /** Capture console.log/info/warn/error/debug into live logs. Default true */
29
29
  captureConsole?: boolean;
30
30
  /** Paths (prefix string or RegExp) not to record */
package/src/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  'use strict';
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
2
5
  const http = require('http');
3
6
  const https = require('https');
4
7
  const { normalizePath } = require('./metrics');
@@ -6,6 +9,29 @@ const { localSource } = require('./source');
6
9
  const { createDashboard, normBase } = require('./dashboard');
7
10
  const { createHub } = require('./hub');
8
11
 
12
+ /**
13
+ * Options not passed in code come from the environment:
14
+ * SERVER_LENS_HUB_URL + SERVER_LENS_KEY → report to that hub (and no dashboard inside the app)
15
+ * SERVER_LENS_USER + SERVER_LENS_PASS → login for the in-app dashboard, when it is on
16
+ * SERVER_LENS_NAME → display name (default: package.json name, then hostname)
17
+ */
18
+ function resolveOptions(opts) {
19
+ const env = process.env;
20
+ const hub = opts.hub !== undefined ? opts.hub || null
21
+ : env.SERVER_LENS_HUB_URL ? { url: env.SERVER_LENS_HUB_URL, key: env.SERVER_LENS_KEY || '' } : null;
22
+ const auth = opts.auth !== undefined ? opts.auth
23
+ : env.SERVER_LENS_USER && env.SERVER_LENS_PASS ? { username: env.SERVER_LENS_USER, password: env.SERVER_LENS_PASS } : undefined;
24
+ return {
25
+ ...opts, hub, auth,
26
+ name: opts.name || env.SERVER_LENS_NAME || packageName() || os.hostname(),
27
+ dashboard: opts.dashboard !== undefined ? opts.dashboard : !hub, // with a hub, watch it there
28
+ };
29
+ }
30
+
31
+ function packageName() {
32
+ try { return JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8')).name || ''; } catch { return ''; }
33
+ }
34
+
9
35
  /**
10
36
  * Create a Server Lens agent. It is an Express/Connect-style middleware:
11
37
  * app.use(serverLens())
@@ -13,7 +39,9 @@ const { createHub } = require('./hub');
13
39
  * http.createServer((req, res) => lens(req, res, () => handler(req, res)))
14
40
  * or, for any Node server (Next.js, Fastify, Koa, NestJS…), use serverLens.instrument().
15
41
  */
16
- function serverLens(opts = {}) {
42
+ function serverLens(options = {}) {
43
+ const opts = resolveOptions(options);
44
+ if (opts.hub && !opts.hub.key) process.emitWarning('server-lens: SERVER_LENS_KEY is not set; the hub will reject this server.');
17
45
  const base = normBase(opts.path);
18
46
  const ignore = opts.ignore || [];
19
47
  const src = localSource({ name: opts.name, captureConsole: opts.captureConsole !== false, maxLogs: opts.maxLogs, maxRoutes: opts.maxRoutes, maxRecent: opts.maxRecent });
@@ -87,6 +115,7 @@ function instrument(opts = {}) {
87
115
  S.prototype.emit = function (ev, a, b, c) {
88
116
  if (ev === 'request') { lens.bind(this); lens(a, b, () => orig.call(this, ev, a, b)); return true; }
89
117
  if (ev === 'upgrade' && lens.isWs(a)) { lens.bind(this); lens.handleUpgrade(a, b, c); return true; }
118
+ if (ev === 'listening') lens.bind(this); // know the port before the first request arrives
90
119
  return orig.apply(this, arguments);
91
120
  };
92
121
  }
@@ -95,18 +124,25 @@ function instrument(opts = {}) {
95
124
  }
96
125
 
97
126
  /** Batches requests, logs and system samples and pushes them to a Server Lens hub. */
98
- function createReporter({ url, key, id, name, interval = 5000 }, src) {
127
+ function createReporter({ url, key, id, name, interval = 2000 }, src) {
99
128
  if (!url) throw new Error('server-lens: hub.url is required');
100
129
  const endpoint = `${String(url).replace(/\/+$/, '')}/api/ingest`;
101
- let requests = [], logs = [], warned = false, busy = false;
130
+ let requests = [], logs = [], warned = false, busy = false, serverId = id;
131
+ const started = Date.now();
102
132
  src.logs.on('log', (e) => { logs.push({ ts: e.ts, level: e.level, msg: e.msg }); if (logs.length > 1000) logs.shift(); });
103
133
 
104
134
  async function flush() {
105
135
  if (busy) return;
106
- busy = true;
107
136
  const info = src.info();
137
+ // The id must not change once chosen, or the hub shows the server twice. Wait (up to 60s) for the
138
+ // HTTP server to start listening so the id can include the port.
139
+ if (!serverId) {
140
+ if (!info.port && Date.now() - started < 60000) return;
141
+ serverId = `${info.hostname}-${info.port || 'app'}`.toLowerCase().replace(/[^\w.-]+/g, '-');
142
+ }
143
+ busy = true;
108
144
  const body = {
109
- id: id || `${info.hostname}-${info.port || 'app'}`.toLowerCase().replace(/[^\w.-]+/g, '-'),
145
+ id: serverId,
110
146
  name: name || src.name, info,
111
147
  sample: src.metrics.samples[src.metrics.samples.length - 1],
112
148
  requests: requests.slice(0, 5000), logs: logs.slice(0, 1000),