@ruyalab/webmonitor-nextjs 0.0.0-stage → 1.0.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 +53 -2
- package/bin/webmonitor-nextjs.js +107 -0
- package/index.d.ts +15 -0
- package/package.json +49 -4
- package/src/app-router.js +16 -0
- package/src/core.js +371 -0
- package/src/index.js +3 -0
- package/src/pages-router.js +19 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ruyalab
|
|
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,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ruyalab/webmonitor-nextjs
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Connect a Next.js site to **[Web Monitor](https://webmonitor.ruyalab.com)** — uptime, response time,
|
|
4
|
+
performance, SEO and security checks every minute.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install @ruyalab/webmonitor-nextjs
|
|
10
|
+
npx webmonitor-nextjs init
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`init` creates the API route (`app/api/webmonitor/[...slug]/route` for the App Router, or
|
|
14
|
+
`pages/api/webmonitor/[...slug]` for the Pages Router) and saves a new `WEBMONITOR_API_KEY` in `.env.local`.
|
|
15
|
+
|
|
16
|
+
Then:
|
|
17
|
+
|
|
18
|
+
1. Add the same `WEBMONITOR_API_KEY` to your hosting environment variables and deploy.
|
|
19
|
+
2. In the Web Monitor dashboard click **Add site**, choose **Next.js**, and paste the key.
|
|
20
|
+
|
|
21
|
+
Optional: `WEBMONITOR_SITE_URL=https://your-site.com` sets the public URL used for SEO/security checks
|
|
22
|
+
(defaults to the URL the request came in on). `WEBMONITOR_LOG_FILE` shows an error log in the dashboard.
|
|
23
|
+
|
|
24
|
+
## What it reports
|
|
25
|
+
|
|
26
|
+
All values are measured on your server at request time:
|
|
27
|
+
|
|
28
|
+
| Endpoint | Data |
|
|
29
|
+
|---|---|
|
|
30
|
+
| `health` | status, Node and Next.js versions, memory, load |
|
|
31
|
+
| `performance` | memory, CPU load per core, disk space, production build |
|
|
32
|
+
| `seo` | homepage title, meta description, H1, image alt text, `lang`, canonical, links |
|
|
33
|
+
| `security` | HTTPS, supported Node version, production mode, security headers, `X-Powered-By` |
|
|
34
|
+
| `libraries` | dependencies with installed versions |
|
|
35
|
+
| `analytics` | `null` — visitor analytics need an analytics provider |
|
|
36
|
+
|
|
37
|
+
Requests must send `Authorization: Bearer <WEBMONITOR_API_KEY>`. Without a key (or with a short key) the
|
|
38
|
+
endpoint refuses to run.
|
|
39
|
+
|
|
40
|
+
## Manual setup
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// app/api/webmonitor/[...slug]/route.ts
|
|
44
|
+
export { GET } from '@ruyalab/webmonitor-nextjs/app-router';
|
|
45
|
+
export const dynamic = 'force-dynamic';
|
|
46
|
+
export const runtime = 'nodejs';
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
// pages/api/webmonitor/[...slug].ts
|
|
51
|
+
export { default } from '@ruyalab/webmonitor-nextjs/pages-router';
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
MIT License · © Ruyalab
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// npx webmonitor-nextjs init [--new] [--force]
|
|
3
|
+
// Creates the Web Monitor API route in your Next.js project and saves WEBMONITOR_API_KEY in .env.local.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
|
|
8
|
+
const args = process.argv.slice(2);
|
|
9
|
+
const command = args.find((a) => !a.startsWith('-')) || 'help';
|
|
10
|
+
const flag = (name) => args.includes(`--${name}`);
|
|
11
|
+
const root = process.cwd();
|
|
12
|
+
|
|
13
|
+
const color = (code) => (text) => (process.stdout.isTTY ? `\x1b[${code}m${text}\x1b[0m` : text);
|
|
14
|
+
const green = color(32);
|
|
15
|
+
const yellow = color(33);
|
|
16
|
+
const red = color(31);
|
|
17
|
+
|
|
18
|
+
function fail(message) {
|
|
19
|
+
console.error(red(`✖ ${message}`));
|
|
20
|
+
process.exit(1);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function findRouterDir() {
|
|
24
|
+
for (const dir of ['app', 'src/app']) {
|
|
25
|
+
if (fs.existsSync(path.join(root, dir))) return { type: 'app', dir };
|
|
26
|
+
}
|
|
27
|
+
for (const dir of ['pages', 'src/pages']) {
|
|
28
|
+
if (fs.existsSync(path.join(root, dir))) return { type: 'pages', dir };
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function writeRoute() {
|
|
34
|
+
const router = findRouterDir();
|
|
35
|
+
if (!router) fail('No app/ or pages/ folder found. Run this in the root of your Next.js project.');
|
|
36
|
+
const ext = fs.existsSync(path.join(root, 'tsconfig.json')) ? 'ts' : 'js';
|
|
37
|
+
const file = router.type === 'app'
|
|
38
|
+
? path.join(router.dir, 'api', 'webmonitor', '[...slug]', `route.${ext}`)
|
|
39
|
+
: path.join(router.dir, 'api', 'webmonitor', `[...slug].${ext}`);
|
|
40
|
+
const contents = router.type === 'app'
|
|
41
|
+
? [
|
|
42
|
+
'// Web Monitor endpoint (created by `npx webmonitor-nextjs init`)',
|
|
43
|
+
"export { GET } from '@ruyalab/webmonitor-nextjs/app-router';",
|
|
44
|
+
"export const dynamic = 'force-dynamic';",
|
|
45
|
+
"export const runtime = 'nodejs';",
|
|
46
|
+
'',
|
|
47
|
+
].join('\n')
|
|
48
|
+
: [
|
|
49
|
+
'// Web Monitor endpoint (created by `npx webmonitor-nextjs init`)',
|
|
50
|
+
"export { default } from '@ruyalab/webmonitor-nextjs/pages-router';",
|
|
51
|
+
'',
|
|
52
|
+
].join('\n');
|
|
53
|
+
|
|
54
|
+
const fullPath = path.join(root, file);
|
|
55
|
+
if (fs.existsSync(fullPath) && !flag('force')) {
|
|
56
|
+
console.log(green(`✔ Route already exists: ${file}`));
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
|
60
|
+
fs.writeFileSync(fullPath, contents);
|
|
61
|
+
console.log(green(`✔ Created ${file}`));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function ensureKey() {
|
|
65
|
+
const envFile = path.join(root, '.env.local');
|
|
66
|
+
let env = fs.existsSync(envFile) ? fs.readFileSync(envFile, 'utf8') : '';
|
|
67
|
+
const existing = env.match(/^WEBMONITOR_API_KEY=(.*)$/m)?.[1]?.trim().replace(/^["']|["']$/g, '');
|
|
68
|
+
if (existing && !flag('new')) {
|
|
69
|
+
console.log(green('✔ WEBMONITOR_API_KEY already set in .env.local (use --new to replace it)'));
|
|
70
|
+
return existing;
|
|
71
|
+
}
|
|
72
|
+
const key = randomBytes(32).toString('hex');
|
|
73
|
+
const line = `WEBMONITOR_API_KEY=${key}`;
|
|
74
|
+
env = /^WEBMONITOR_API_KEY=/m.test(env)
|
|
75
|
+
? env.replace(/^WEBMONITOR_API_KEY=.*$/m, line)
|
|
76
|
+
: `${env.replace(/\n*$/, '')}${env ? '\n\n' : ''}${line}\n`;
|
|
77
|
+
fs.writeFileSync(envFile, env);
|
|
78
|
+
console.log(green('✔ Saved WEBMONITOR_API_KEY in .env.local'));
|
|
79
|
+
return key;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (command === 'init') {
|
|
83
|
+
const pkgFile = path.join(root, 'package.json');
|
|
84
|
+
if (!fs.existsSync(pkgFile)) fail('No package.json here. Run this in the root of your Next.js project.');
|
|
85
|
+
const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
|
|
86
|
+
if (!pkg.dependencies?.next && !pkg.devDependencies?.next) {
|
|
87
|
+
console.log(yellow('! "next" is not in package.json — make sure you are in your Next.js project root.'));
|
|
88
|
+
}
|
|
89
|
+
writeRoute();
|
|
90
|
+
const key = ensureKey();
|
|
91
|
+
console.log(`
|
|
92
|
+
Next steps
|
|
93
|
+
1. Add the same variable to your hosting provider (e.g. Vercel → Settings → Environment Variables):
|
|
94
|
+
${yellow('WEBMONITOR_API_KEY')}=${key}
|
|
95
|
+
2. Deploy, then add the site in your Web Monitor dashboard:
|
|
96
|
+
Platform: ${yellow('Next.js')} API key: ${key}
|
|
97
|
+
3. Test: curl -H "Authorization: Bearer ${key}" https://your-site.com/api/webmonitor/health
|
|
98
|
+
`);
|
|
99
|
+
} else {
|
|
100
|
+
console.log(`Web Monitor for Next.js
|
|
101
|
+
|
|
102
|
+
Usage:
|
|
103
|
+
npx webmonitor-nextjs init Create the API route and WEBMONITOR_API_KEY
|
|
104
|
+
npx webmonitor-nextjs init --new Replace the API key with a new one
|
|
105
|
+
npx webmonitor-nextjs init --force Re-create the route file
|
|
106
|
+
`);
|
|
107
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare const VERSION: string;
|
|
2
|
+
export declare const ENDPOINTS: string[];
|
|
3
|
+
|
|
4
|
+
export declare function handleWebMonitorRequest(
|
|
5
|
+
endpoint: string,
|
|
6
|
+
request: { authorization?: string | null; origin: string; forwardedProto?: string | null },
|
|
7
|
+
): Promise<{ status: number; body: Record<string, unknown> }>;
|
|
8
|
+
|
|
9
|
+
/** App Router route handler (app/api/webmonitor/[...slug]/route.ts) */
|
|
10
|
+
export declare function GET(request: Request): Promise<Response>;
|
|
11
|
+
|
|
12
|
+
/** Pages Router API handler (pages/api/webmonitor/[...slug].ts) */
|
|
13
|
+
declare function pagesHandler(req: unknown, res: unknown): Promise<void>;
|
|
14
|
+
export { pagesHandler };
|
|
15
|
+
export default pagesHandler;
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ruyalab/webmonitor-nextjs",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Connect a Next.js site to Web Monitor (webmonitor.ruyalab.com): uptime, performance, SEO and security checks.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"nextjs",
|
|
7
|
+
"monitoring",
|
|
8
|
+
"uptime",
|
|
9
|
+
"health-check",
|
|
10
|
+
"webmonitor"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://webmonitor.ruyalab.com/integrations#nextjs",
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Ruyalab",
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./src/index.js",
|
|
17
|
+
"types": "./index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./index.d.ts",
|
|
21
|
+
"default": "./src/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./app-router": {
|
|
24
|
+
"types": "./index.d.ts",
|
|
25
|
+
"default": "./src/app-router.js"
|
|
26
|
+
},
|
|
27
|
+
"./pages-router": {
|
|
28
|
+
"types": "./index.d.ts",
|
|
29
|
+
"default": "./src/pages-router.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"bin": {
|
|
33
|
+
"webmonitor-nextjs": "bin/webmonitor-nextjs.js"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"src",
|
|
37
|
+
"bin",
|
|
38
|
+
"index.d.ts",
|
|
39
|
+
"README.md",
|
|
40
|
+
"LICENSE"
|
|
41
|
+
],
|
|
42
|
+
"peerDependencies": {
|
|
43
|
+
"next": ">=13.4"
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=18.17"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// App Router route handler: app/api/webmonitor/[...slug]/route.(js|ts)
|
|
2
|
+
// export { GET } from '@ruyalab/webmonitor-nextjs/app-router';
|
|
3
|
+
// export const dynamic = 'force-dynamic';
|
|
4
|
+
// export const runtime = 'nodejs';
|
|
5
|
+
import { handleWebMonitorRequest } from './core.js';
|
|
6
|
+
|
|
7
|
+
export async function GET(request) {
|
|
8
|
+
const url = new URL(request.url);
|
|
9
|
+
const endpoint = url.pathname.split('/').filter(Boolean).pop();
|
|
10
|
+
const { status, body } = await handleWebMonitorRequest(endpoint, {
|
|
11
|
+
authorization: request.headers.get('authorization'),
|
|
12
|
+
origin: url.origin,
|
|
13
|
+
forwardedProto: request.headers.get('x-forwarded-proto'),
|
|
14
|
+
});
|
|
15
|
+
return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
|
|
16
|
+
}
|
package/src/core.js
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// Web Monitor integration core for Next.js (Node.js runtime).
|
|
2
|
+
// Every value is measured at request time; what can't be measured (visitor analytics, malware scans)
|
|
3
|
+
// is reported as null / "not_available", never guessed.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
8
|
+
|
|
9
|
+
export const VERSION = '1.0.0';
|
|
10
|
+
export const ENDPOINTS = ['health', 'analytics', 'performance', 'seo', 'security', 'libraries', 'logs', 'recommendations'];
|
|
11
|
+
|
|
12
|
+
const projectRoot = () => process.cwd();
|
|
13
|
+
|
|
14
|
+
function readJson(file) {
|
|
15
|
+
try {
|
|
16
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
17
|
+
} catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const installedVersion = (name) => readJson(path.join(projectRoot(), 'node_modules', name, 'package.json'))?.version ?? null;
|
|
23
|
+
|
|
24
|
+
function safeEqual(a, b) {
|
|
25
|
+
const left = Buffer.from(String(a));
|
|
26
|
+
const right = Buffer.from(String(b));
|
|
27
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const round = (value, digits = 2) => (value == null ? null : Number(value.toFixed(digits)));
|
|
31
|
+
|
|
32
|
+
function systemMemoryPercent() {
|
|
33
|
+
return round(((os.totalmem() - os.freemem()) / os.totalmem()) * 100);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// 1-minute load average per CPU core, as a percentage (null on Windows, where it isn't available)
|
|
37
|
+
function cpuUsagePercent() {
|
|
38
|
+
if (process.platform === 'win32') return null;
|
|
39
|
+
const cores = os.cpus().length || 1;
|
|
40
|
+
return round(Math.min(100, (os.loadavg()[0] / cores) * 100));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function trafficStats() {
|
|
44
|
+
try {
|
|
45
|
+
const lines = fs.readFileSync('/proc/net/dev', 'utf8').split('\n');
|
|
46
|
+
let tx = 0;
|
|
47
|
+
let rx = 0;
|
|
48
|
+
let found = false;
|
|
49
|
+
for (const line of lines) {
|
|
50
|
+
const split = line.split(':');
|
|
51
|
+
if (split.length < 2) continue;
|
|
52
|
+
const iface = split[0].trim();
|
|
53
|
+
if (!iface || iface === 'lo') continue;
|
|
54
|
+
const cols = split.slice(1).join(':').trim().split(/\s+/);
|
|
55
|
+
if (cols.length < 9) continue;
|
|
56
|
+
rx += Number(cols[0]);
|
|
57
|
+
tx += Number(cols[8]);
|
|
58
|
+
found = true;
|
|
59
|
+
}
|
|
60
|
+
if (!found) return { txBytes: null, rxBytes: null };
|
|
61
|
+
return { txBytes: tx, rxBytes: rx };
|
|
62
|
+
} catch {
|
|
63
|
+
return { txBytes: null, rxBytes: null };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function diskStats() {
|
|
68
|
+
try {
|
|
69
|
+
const stats = fs.statfsSync(projectRoot());
|
|
70
|
+
const free = stats.bavail * stats.bsize;
|
|
71
|
+
const total = stats.blocks * stats.bsize;
|
|
72
|
+
if (!total) return { freeBytes: null, totalBytes: null, freePercent: null };
|
|
73
|
+
return {
|
|
74
|
+
freeBytes: free,
|
|
75
|
+
totalBytes: total,
|
|
76
|
+
freePercent: round((stats.bavail / stats.blocks) * 100, 1),
|
|
77
|
+
};
|
|
78
|
+
} catch {
|
|
79
|
+
return { freeBytes: null, totalBytes: null, freePercent: null };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ---- endpoints ------------------------------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
function getHealth() {
|
|
86
|
+
const start = performance.now();
|
|
87
|
+
const memory = systemMemoryPercent();
|
|
88
|
+
const status = memory >= 95 ? 'warning' : 'healthy';
|
|
89
|
+
return {
|
|
90
|
+
status,
|
|
91
|
+
message: status === 'healthy' ? 'Site is healthy' : 'Server memory usage is above 95%',
|
|
92
|
+
timestamp: new Date().toISOString(),
|
|
93
|
+
response_time: round(performance.now() - start),
|
|
94
|
+
node_version: process.version,
|
|
95
|
+
nextjs_version: installedVersion('next'),
|
|
96
|
+
framework: 'Next.js',
|
|
97
|
+
integration_version: VERSION,
|
|
98
|
+
uptime_seconds: Math.round(os.uptime()),
|
|
99
|
+
checks: {
|
|
100
|
+
memory_usage: `${memory}%`,
|
|
101
|
+
load_average: process.platform === 'win32' ? null : round(os.loadavg()[0]),
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function getAnalytics() {
|
|
107
|
+
// Visitors, page views, bounce rate and sessions need an analytics source (Vercel Analytics, GA4...).
|
|
108
|
+
return {
|
|
109
|
+
totalVisitors: null,
|
|
110
|
+
pageViews: null,
|
|
111
|
+
bounceRate: null,
|
|
112
|
+
avgSessionDuration: null,
|
|
113
|
+
analytics_source: 'unavailable',
|
|
114
|
+
analytics_note: 'Connect an analytics provider for visitor data. The server cannot measure visits on its own.',
|
|
115
|
+
top_pages: [],
|
|
116
|
+
content_stats: {},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function getPerformance() {
|
|
121
|
+
const start = performance.now();
|
|
122
|
+
const memory = systemMemoryPercent();
|
|
123
|
+
const cpu = cpuUsagePercent();
|
|
124
|
+
const disk = diskStats();
|
|
125
|
+
const traffic = trafficStats();
|
|
126
|
+
const processMemory = process.memoryUsage();
|
|
127
|
+
const elapsed = round(performance.now() - start);
|
|
128
|
+
|
|
129
|
+
let score = 100;
|
|
130
|
+
const recommendations = [];
|
|
131
|
+
if (memory > 80) { score -= 15; recommendations.push('Server memory usage is high — add memory or reduce usage'); }
|
|
132
|
+
if (cpu != null && cpu > 80) { score -= 20; recommendations.push('Server CPU load is high — optimize heavy work or add capacity'); }
|
|
133
|
+
if (disk.freePercent != null && disk.freePercent < 10) { score -= 15; recommendations.push('Less than 10% disk space left on the server'); }
|
|
134
|
+
if (process.env.NODE_ENV !== 'production') { score -= 10; recommendations.push('Run the site with a production build (next build && next start)'); }
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
load_time: elapsed,
|
|
138
|
+
server_response_time: elapsed,
|
|
139
|
+
database_query_time: null,
|
|
140
|
+
memory_usage: memory,
|
|
141
|
+
memory_peak: round(processMemory.rss / 1048576),
|
|
142
|
+
heap_used_mb: round(processMemory.heapUsed / 1048576),
|
|
143
|
+
cpu_usage: cpu,
|
|
144
|
+
disk_free_percent: disk.freePercent,
|
|
145
|
+
disk_free_bytes: disk.freeBytes,
|
|
146
|
+
disk_total_bytes: disk.totalBytes,
|
|
147
|
+
bandwidth_tx_bytes: traffic.txBytes,
|
|
148
|
+
bandwidth_rx_bytes: traffic.rxBytes,
|
|
149
|
+
performance_score: Math.max(0, score),
|
|
150
|
+
active_plugins: null,
|
|
151
|
+
recommendations,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async function fetchHomepage(ctx) {
|
|
156
|
+
if (ctx.homepage) return ctx.homepage;
|
|
157
|
+
const url = `${ctx.siteUrl}/`;
|
|
158
|
+
try {
|
|
159
|
+
const response = await fetch(url, { headers: { 'User-Agent': `WebMonitor/${VERSION}` }, signal: AbortSignal.timeout(5000) });
|
|
160
|
+
const html = await response.text();
|
|
161
|
+
ctx.homepage = { url, html, headers: Object.fromEntries([...response.headers].map(([k, v]) => [k.toLowerCase(), v])) };
|
|
162
|
+
} catch (error) {
|
|
163
|
+
ctx.homepage = { url, html: null, headers: null, error: error.message };
|
|
164
|
+
}
|
|
165
|
+
return ctx.homepage;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function countLinks(html, siteUrl) {
|
|
169
|
+
const host = new URL(siteUrl).host;
|
|
170
|
+
let internal = 0;
|
|
171
|
+
let external = 0;
|
|
172
|
+
for (const [, href] of html.matchAll(/<a\b[^>]*href=["']([^"'#]+)["']/gi)) {
|
|
173
|
+
try {
|
|
174
|
+
const target = new URL(href, siteUrl);
|
|
175
|
+
if (target.host === host) internal += 1;
|
|
176
|
+
else if (/^https?:$/.test(target.protocol)) external += 1;
|
|
177
|
+
} catch {
|
|
178
|
+
// ignore malformed links
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return [internal, external];
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function getSeo(ctx) {
|
|
185
|
+
const page = await fetchHomepage(ctx);
|
|
186
|
+
if (page.html == null) {
|
|
187
|
+
return { score: null, ssl_enabled: ctx.https, seo_issues: [], recommendations: [], note: `Homepage could not be read for analysis: ${page.error}` };
|
|
188
|
+
}
|
|
189
|
+
const { html } = page;
|
|
190
|
+
const issues = [];
|
|
191
|
+
const recommendations = [];
|
|
192
|
+
let score = 100;
|
|
193
|
+
|
|
194
|
+
const title = (html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] || '').replace(/<[^>]+>/g, '').trim();
|
|
195
|
+
const description = (html.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["']/i)
|
|
196
|
+
|| html.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["']/i))?.[1]?.trim() || '';
|
|
197
|
+
const h1Count = (html.match(/<h1[\s>]/gi) || []).length;
|
|
198
|
+
const images = html.match(/<img\b[^>]*>/gi) || [];
|
|
199
|
+
const imagesWithAlt = images.filter((tag) => /\balt=["'][^"']+["']/i.test(tag)).length;
|
|
200
|
+
const hasLang = /<html[^>]+\blang=["'][^"']+["']/i.test(html);
|
|
201
|
+
const hasCanonical = /<link[^>]+rel=["']canonical["']/i.test(html);
|
|
202
|
+
const [internal, external] = countLinks(html, ctx.siteUrl);
|
|
203
|
+
|
|
204
|
+
if (!title) { score -= 20; issues.push('Homepage has no <title>'); recommendations.push('Add a descriptive page title (metadata.title)'); }
|
|
205
|
+
else if (title.length > 65) { score -= 5; issues.push('Title is longer than 65 characters'); }
|
|
206
|
+
if (!description) { score -= 15; issues.push('Homepage has no meta description'); recommendations.push('Add a meta description (metadata.description)'); }
|
|
207
|
+
if (h1Count === 0) { score -= 10; issues.push('Homepage has no <h1> heading'); recommendations.push('Add one <h1> heading'); }
|
|
208
|
+
else if (h1Count > 1) { score -= 5; issues.push(`Homepage has ${h1Count} <h1> headings`); }
|
|
209
|
+
if (images.length > imagesWithAlt) { score -= 10; issues.push(`${images.length - imagesWithAlt} of ${images.length} images have no alt text`); recommendations.push('Add alt text to images'); }
|
|
210
|
+
if (!hasLang) { score -= 5; issues.push('<html> has no lang attribute'); }
|
|
211
|
+
if (!hasCanonical) { score -= 5; issues.push('No canonical link'); }
|
|
212
|
+
if (!ctx.https) { score -= 10; issues.push('Site is not served over HTTPS'); recommendations.push('Enable SSL certificate'); }
|
|
213
|
+
|
|
214
|
+
return {
|
|
215
|
+
score: Math.max(0, score),
|
|
216
|
+
meta_tags: title && description ? 'complete' : 'incomplete',
|
|
217
|
+
alt_tags: images.length ? Math.round((imagesWithAlt / images.length) * 100) : null,
|
|
218
|
+
heading_structure: h1Count === 1 ? 'good' : 'needs_improvement',
|
|
219
|
+
internal_links: internal,
|
|
220
|
+
external_links: external,
|
|
221
|
+
ssl_enabled: ctx.https,
|
|
222
|
+
site_title: title,
|
|
223
|
+
site_description: description,
|
|
224
|
+
total_content: null,
|
|
225
|
+
seo_issues: issues,
|
|
226
|
+
recommendations,
|
|
227
|
+
analyzed_url: page.url,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function getSecurity(ctx) {
|
|
232
|
+
const checks = {};
|
|
233
|
+
const recommendations = [];
|
|
234
|
+
const add = (name, passed, advice) => {
|
|
235
|
+
checks[name] = passed;
|
|
236
|
+
if (passed === false) recommendations.push(advice);
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
add('https', ctx.https, 'Enable SSL certificate (serve the site over HTTPS)');
|
|
240
|
+
add('supported_node', Number(process.versions.node.split('.')[0]) >= 20, 'Upgrade Node.js to a supported LTS version (20 or newer)');
|
|
241
|
+
add('production_mode', process.env.NODE_ENV === 'production', 'Run a production build (NODE_ENV=production)');
|
|
242
|
+
|
|
243
|
+
const { headers } = await fetchHomepage(ctx);
|
|
244
|
+
if (headers) {
|
|
245
|
+
add('no_powered_by_header', !headers['x-powered-by'], 'Hide the X-Powered-By header (poweredByHeader: false in next.config)');
|
|
246
|
+
add('hsts_header', Boolean(headers['strict-transport-security']), 'Send a Strict-Transport-Security header');
|
|
247
|
+
add('nosniff_header', Boolean(headers['x-content-type-options']), 'Send X-Content-Type-Options: nosniff');
|
|
248
|
+
add('frame_protection', Boolean(headers['x-frame-options'] || headers['content-security-policy']), 'Protect against clickjacking (X-Frame-Options or CSP)');
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const known = Object.values(checks).filter((v) => v !== null && v !== undefined);
|
|
252
|
+
return {
|
|
253
|
+
ssl_status: ctx.https ? 'enabled' : 'disabled',
|
|
254
|
+
firewall: 'unknown',
|
|
255
|
+
malware_scan: 'not_available',
|
|
256
|
+
vulnerability_scan: 'not_available',
|
|
257
|
+
security_score: known.length ? Math.round((known.filter(Boolean).length / known.length) * 100) : null,
|
|
258
|
+
security_checks: checks,
|
|
259
|
+
security_plugins: null,
|
|
260
|
+
total_plugins: null,
|
|
261
|
+
outdated_plugins: null,
|
|
262
|
+
node_version: process.version,
|
|
263
|
+
nextjs_version: installedVersion('next'),
|
|
264
|
+
recommendations,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function getLibraries() {
|
|
269
|
+
const pkg = readJson(path.join(projectRoot(), 'package.json'));
|
|
270
|
+
if (!pkg) return { total_libraries: 0, all_libraries: [], message: 'package.json not found' };
|
|
271
|
+
const format = (deps = {}, isDev) => Object.entries(deps).map(([name, range]) => ({
|
|
272
|
+
name,
|
|
273
|
+
version: installedVersion(name),
|
|
274
|
+
rawVersion: range,
|
|
275
|
+
isDev,
|
|
276
|
+
type: isDev ? 'devDependency' : 'dependency',
|
|
277
|
+
outdated: null,
|
|
278
|
+
}));
|
|
279
|
+
const dependencies = format(pkg.dependencies, false);
|
|
280
|
+
const devDependencies = format(pkg.devDependencies, true);
|
|
281
|
+
return {
|
|
282
|
+
total_libraries: dependencies.length + devDependencies.length,
|
|
283
|
+
dependencies_count: dependencies.length,
|
|
284
|
+
devDependencies_count: devDependencies.length,
|
|
285
|
+
dependencies,
|
|
286
|
+
devDependencies,
|
|
287
|
+
all_libraries: [...dependencies, ...devDependencies],
|
|
288
|
+
outdated_count: null,
|
|
289
|
+
node_version: process.version,
|
|
290
|
+
nextjs_version: installedVersion('next'),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function getLogs() {
|
|
295
|
+
const candidates = [process.env.WEBMONITOR_LOG_FILE, path.join(projectRoot(), 'logs', 'error.log')].filter(Boolean);
|
|
296
|
+
for (const file of candidates) {
|
|
297
|
+
try {
|
|
298
|
+
const lines = fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).slice(-100);
|
|
299
|
+
return {
|
|
300
|
+
error_log: {
|
|
301
|
+
enabled: true,
|
|
302
|
+
message: '',
|
|
303
|
+
lines: lines.map((raw) => ({ raw, time: raw.slice(0, 40).match(/\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/)?.[0] ?? '' })),
|
|
304
|
+
count: lines.length,
|
|
305
|
+
},
|
|
306
|
+
access_summary: {},
|
|
307
|
+
};
|
|
308
|
+
} catch {
|
|
309
|
+
// try the next location
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
error_log: { enabled: false, message: 'No log file found. Set WEBMONITOR_LOG_FILE to show your error log here.', lines: [], count: 0 },
|
|
314
|
+
access_summary: {},
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function getRecommendations(ctx) {
|
|
319
|
+
const sections = { performance: getPerformance(), seo: await getSeo(ctx), security: await getSecurity(ctx) };
|
|
320
|
+
const recommendations = Object.entries(sections).flatMap(([source, data]) => (data.recommendations || []).map((text) => ({ text, source })));
|
|
321
|
+
return { recommendations, count: recommendations.length };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const HANDLERS = {
|
|
325
|
+
health: getHealth,
|
|
326
|
+
analytics: getAnalytics,
|
|
327
|
+
performance: getPerformance,
|
|
328
|
+
seo: getSeo,
|
|
329
|
+
security: getSecurity,
|
|
330
|
+
libraries: getLibraries,
|
|
331
|
+
plugins: getLibraries,
|
|
332
|
+
logs: getLogs,
|
|
333
|
+
recommendations: getRecommendations,
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Framework-neutral request handler.
|
|
338
|
+
* @param {string} endpoint last path segment, e.g. "health"
|
|
339
|
+
* @param {{ authorization?: string|null, origin: string, forwardedProto?: string|null }} request
|
|
340
|
+
* @returns {Promise<{ status: number, body: object }>}
|
|
341
|
+
*/
|
|
342
|
+
export async function handleWebMonitorRequest(endpoint, request) {
|
|
343
|
+
const apiKey = process.env.WEBMONITOR_API_KEY || '';
|
|
344
|
+
if (!apiKey) {
|
|
345
|
+
return { status: 503, body: { error: 'WEBMONITOR_API_KEY is not set on this site. Run: npx webmonitor-nextjs init' } };
|
|
346
|
+
}
|
|
347
|
+
// A short or placeholder key would be guessable: refuse to run with it
|
|
348
|
+
if (apiKey.length < 16 || /^paste-/i.test(apiKey)) {
|
|
349
|
+
return { status: 503, body: { error: 'WEBMONITOR_API_KEY is too short or still the placeholder. Use a long random key.' } };
|
|
350
|
+
}
|
|
351
|
+
const token = /^Bearer\s+(.+)$/i.exec(request.authorization || '')?.[1]?.trim() || '';
|
|
352
|
+
if (!safeEqual(token, apiKey)) {
|
|
353
|
+
return { status: 401, body: { error: 'Invalid API key. Please check your authorization header.' } };
|
|
354
|
+
}
|
|
355
|
+
const handler = HANDLERS[endpoint];
|
|
356
|
+
if (!handler) {
|
|
357
|
+
return { status: 404, body: { error: `Unknown endpoint. Available: ${ENDPOINTS.join(', ')}` } };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const siteUrl = (process.env.WEBMONITOR_SITE_URL || request.origin).replace(/\/$/, '');
|
|
361
|
+
const ctx = {
|
|
362
|
+
siteUrl,
|
|
363
|
+
https: siteUrl.startsWith('https://') || request.forwardedProto === 'https',
|
|
364
|
+
homepage: null,
|
|
365
|
+
};
|
|
366
|
+
try {
|
|
367
|
+
return { status: 200, body: await handler(ctx) };
|
|
368
|
+
} catch (error) {
|
|
369
|
+
return { status: 500, body: { error: `Web Monitor check failed: ${error.message}` } };
|
|
370
|
+
}
|
|
371
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Pages Router API route: pages/api/webmonitor/[...slug].(js|ts)
|
|
2
|
+
// export { default } from '@ruyalab/webmonitor-nextjs/pages-router';
|
|
3
|
+
import { handleWebMonitorRequest } from './core.js';
|
|
4
|
+
|
|
5
|
+
export default async function webMonitorHandler(req, res) {
|
|
6
|
+
if (req.method !== 'GET') {
|
|
7
|
+
res.setHeader('Allow', 'GET');
|
|
8
|
+
return res.status(405).json({ error: 'Method not allowed' });
|
|
9
|
+
}
|
|
10
|
+
const slug = [].concat(req.query.slug || []);
|
|
11
|
+
const proto = req.headers['x-forwarded-proto'] || (req.socket?.encrypted ? 'https' : 'http');
|
|
12
|
+
const { status, body } = await handleWebMonitorRequest(slug[slug.length - 1], {
|
|
13
|
+
authorization: req.headers.authorization,
|
|
14
|
+
origin: `${proto}://${req.headers.host}`,
|
|
15
|
+
forwardedProto: req.headers['x-forwarded-proto'],
|
|
16
|
+
});
|
|
17
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
18
|
+
return res.status(status).json(body);
|
|
19
|
+
}
|