universal-screenshot-mcp 1.4.0 → 1.5.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/README.md +3 -2
- package/build/config/index.js +11 -0
- package/build/tools/take-screenshot.js +102 -10
- package/build/utils/windows-provider.js +22 -18
- package/build/validators/url.js +170 -100
- package/package.json +2 -3
package/README.md
CHANGED
|
@@ -204,7 +204,8 @@ This server implements multiple layers of security hardening:
|
|
|
204
204
|
| SEC-001 | SSRF / DNS rebinding | URLs validated against blocked IP ranges; DNS resolved pre-request with IP pinning via `--host-resolver-rules`; navigation redirects re-validated |
|
|
205
205
|
| SEC-003 | Command injection | All subprocesses use `execFile` (no shell); app names validated against `SAFE_APP_NAME_PATTERN` |
|
|
206
206
|
| SEC-004 | Path traversal | Output paths validated with `fs.realpath()` symlink resolution; restricted to allowed directories |
|
|
207
|
-
| SEC-005 | Denial of service | Concurrent Puppeteer instances limited to 3 via semaphore
|
|
207
|
+
| SEC-005 | Denial of service | Concurrent Puppeteer instances limited to 3 via semaphore; 120 s hard deadline per call, after which the browser is killed and the slot freed |
|
|
208
|
+
| SEC-006 | Popup SSRF bypass | Chromium's popup blocker kept on (Puppeteer disables it by default); any popup that still opens is closed |
|
|
208
209
|
|
|
209
210
|
For full details, see [`docs/security.md`](docs/security.md).
|
|
210
211
|
|
|
@@ -259,7 +260,7 @@ Tests use [Vitest](https://vitest.dev/) in three tiers:
|
|
|
259
260
|
|
|
260
261
|
- **Unit** (`npm test`) — Full dependency injection, no real I/O. Fast feedback loop.
|
|
261
262
|
- **Integration** (`npm run test:integration`) — Real DNS resolution, real filesystem with temp directories, real Puppeteer against a local HTTP server.
|
|
262
|
-
- **E2E** (`npm run test:e2e`) — Real native screenshot tools. macOS tests run natively; Linux tests run in Docker via `npm run test:linux
|
|
263
|
+
- **E2E** (`npm run test:e2e`) — Real native screenshot tools. macOS tests run natively; Linux tests run in Docker via `npm run test:linux`; Windows tests run on the `windows-latest` CI runner.
|
|
263
264
|
|
|
264
265
|
```bash
|
|
265
266
|
npm test # Unit tests (~300ms)
|
package/build/config/index.js
CHANGED
|
@@ -9,6 +9,17 @@ import { homedir, tmpdir } from 'os';
|
|
|
9
9
|
* SEC-005: Prevents resource exhaustion / DoS attacks.
|
|
10
10
|
*/
|
|
11
11
|
export const MAX_CONCURRENT_SCREENSHOTS = 3;
|
|
12
|
+
/**
|
|
13
|
+
* Hard ceiling on a single take_screenshot call, covering launch, navigation,
|
|
14
|
+
* waits and capture. When it fires the browser is force-killed so the
|
|
15
|
+
* semaphore permit is always returned. SEC-005: a page that wedges Chromium
|
|
16
|
+
* (e.g. via window.open()) must not hold a permit forever.
|
|
17
|
+
*
|
|
18
|
+
* Must stay above the sum of the per-step budgets in take-screenshot.ts —
|
|
19
|
+
* goto (30s) + waitForSelector (30s) + waitForTimeout (schema max 30s) — plus
|
|
20
|
+
* launch and capture time, or a legitimate slow page is killed mid-capture.
|
|
21
|
+
*/
|
|
22
|
+
export const SCREENSHOT_DEADLINE_MS = 120_000;
|
|
12
23
|
/**
|
|
13
24
|
* When true, allows loopback addresses (127.x.x.x, ::1, localhost) in URL validation.
|
|
14
25
|
* All other private/reserved ranges remain blocked regardless of this setting.
|
|
@@ -1,11 +1,40 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
+
import { unlink } from 'node:fs/promises';
|
|
2
3
|
import puppeteer from 'puppeteer';
|
|
3
4
|
import { puppeteerSemaphore, defaultOutDir, ensureDefaultDirectory } from '../config/runtime.js';
|
|
4
|
-
import { ALLOWED_OUTPUT_DIRS, MAX_CONCURRENT_SCREENSHOTS, ALLOW_LOCAL } from '../config/index.js';
|
|
5
|
-
import { validateUrl } from '../validators/url.js';
|
|
5
|
+
import { ALLOWED_OUTPUT_DIRS, MAX_CONCURRENT_SCREENSHOTS, ALLOW_LOCAL, SCREENSHOT_DEADLINE_MS } from '../config/index.js';
|
|
6
|
+
import { validateUrl, isBlockedIp } from '../validators/url.js';
|
|
6
7
|
import { validateOutputPath } from '../validators/path.js';
|
|
7
8
|
import { ok, err, timestamp, ensureDir } from '../utils/helpers.js';
|
|
8
9
|
// Semaphore protects expensive Puppeteer operations
|
|
10
|
+
/** How long a graceful browser.close() may take before the process is killed. */
|
|
11
|
+
const BROWSER_CLOSE_GRACE_MS = 5_000;
|
|
12
|
+
/**
|
|
13
|
+
* Close the browser, falling back to SIGKILL if close() hangs or fails.
|
|
14
|
+
* A wedged Chromium must never keep the caller (and its semaphore permit) waiting.
|
|
15
|
+
*/
|
|
16
|
+
async function shutdownBrowser(browser, force) {
|
|
17
|
+
const proc = browser.process();
|
|
18
|
+
if (!force) {
|
|
19
|
+
let timer;
|
|
20
|
+
try {
|
|
21
|
+
await Promise.race([
|
|
22
|
+
browser.close(),
|
|
23
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('close timed out')), BROWSER_CLOSE_GRACE_MS); }),
|
|
24
|
+
]);
|
|
25
|
+
}
|
|
26
|
+
catch { /* browser may already be dead, or close() hung — kill below */ }
|
|
27
|
+
finally {
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (proc && proc.exitCode === null && proc.signalCode === null) {
|
|
32
|
+
try {
|
|
33
|
+
proc.kill('SIGKILL');
|
|
34
|
+
}
|
|
35
|
+
catch { /* already gone */ }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
9
38
|
export function registerTakeScreenshot(server) {
|
|
10
39
|
server.registerTool('take_screenshot', {
|
|
11
40
|
description: 'Capture web page or element via headless browser. Saves to ~/Documents/screenshots by default (configurable via SCREENSHOT_OUTPUT_DIR env var).',
|
|
@@ -44,7 +73,9 @@ export function registerTakeScreenshot(server) {
|
|
|
44
73
|
}
|
|
45
74
|
// Declare browser outside try block to ensure cleanup in finally
|
|
46
75
|
let browser;
|
|
47
|
-
|
|
76
|
+
let timedOut = false;
|
|
77
|
+
let deadlineTimer;
|
|
78
|
+
const capture = async () => {
|
|
48
79
|
// SEC-001: IP pinning to protect against DNS rebinding attacks
|
|
49
80
|
const browserArgs = [
|
|
50
81
|
'--no-sandbox',
|
|
@@ -57,8 +88,30 @@ export function registerTakeScreenshot(server) {
|
|
|
57
88
|
: urlValidation.resolvedIp;
|
|
58
89
|
browserArgs.push(`--host-resolver-rules=MAP ${urlValidation.hostname} ${pinnedIp}`);
|
|
59
90
|
}
|
|
60
|
-
|
|
61
|
-
|
|
91
|
+
const launched = await puppeteer.launch({
|
|
92
|
+
headless: true,
|
|
93
|
+
args: browserArgs,
|
|
94
|
+
// SEC-006: Puppeteer disables Chromium's popup blocker by default. Keep it
|
|
95
|
+
// on: a popup's navigation never passes through the page's request
|
|
96
|
+
// interceptor (an unvalidated, SSRF-capable request), and popups can wedge
|
|
97
|
+
// page.screenshot() indefinitely. Nothing here supplies a user gesture,
|
|
98
|
+
// so the blocker stops every window.open() / target=_blank.
|
|
99
|
+
ignoreDefaultArgs: ['--disable-popup-blocking'],
|
|
100
|
+
});
|
|
101
|
+
browser = launched;
|
|
102
|
+
// The deadline may have fired while launch() was pending; finally{} has
|
|
103
|
+
// already run, so this browser is ours to kill.
|
|
104
|
+
if (timedOut) {
|
|
105
|
+
await shutdownBrowser(launched, true);
|
|
106
|
+
throw new Error('deadline exceeded during launch');
|
|
107
|
+
}
|
|
108
|
+
// SEC-006: Defense in depth — close any popup that slips past the blocker.
|
|
109
|
+
launched.on('targetcreated', (target) => {
|
|
110
|
+
if (target.opener()) {
|
|
111
|
+
target.page().then(p => p?.close()).catch(() => { });
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
const page = await launched.newPage();
|
|
62
115
|
if (width && height)
|
|
63
116
|
await page.setViewport({ width, height });
|
|
64
117
|
// SEC-001: Intercept requests to prevent SSRF via HTTP redirects.
|
|
@@ -99,11 +152,32 @@ export function registerTakeScreenshot(server) {
|
|
|
99
152
|
catch { /* request may already be handled */ }
|
|
100
153
|
}
|
|
101
154
|
});
|
|
155
|
+
// SEC-001: --host-resolver-rules pins only the original hostname, so
|
|
156
|
+
// Chromium re-resolves redirect and iframe hostnames itself after the
|
|
157
|
+
// Node-side check above. A rebinding DNS server can answer that second
|
|
158
|
+
// lookup with an internal address. Check the address Chromium actually
|
|
159
|
+
// connected to for every navigation response (redirect hops included)
|
|
160
|
+
// and refuse to return a screenshot if any of them is blocked.
|
|
161
|
+
let blockedNavigation;
|
|
162
|
+
page.on('response', (res) => {
|
|
163
|
+
if (blockedNavigation || !res.request().isNavigationRequest())
|
|
164
|
+
return;
|
|
165
|
+
const { ip } = res.remoteAddress();
|
|
166
|
+
if (!ip)
|
|
167
|
+
return; // no network connection (e.g. data:, about:blank)
|
|
168
|
+
const ipCheck = isBlockedIp(ip, { allowLocal: ALLOW_LOCAL });
|
|
169
|
+
if (ipCheck.blocked) {
|
|
170
|
+
blockedNavigation = `navigation to ${res.url()} connected to ${ip}: ${ipCheck.reason}`;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
102
173
|
await page.goto(url, { waitUntil: 'networkidle0', timeout: 30000 });
|
|
103
174
|
if (waitForSelector)
|
|
104
175
|
await page.waitForSelector(waitForSelector, { timeout: 30000 });
|
|
105
176
|
if (waitForTimeout)
|
|
106
177
|
await new Promise(r => setTimeout(r, waitForTimeout));
|
|
178
|
+
if (blockedNavigation) {
|
|
179
|
+
return err(`URL validation failed: ${blockedNavigation}`);
|
|
180
|
+
}
|
|
107
181
|
ensureDir(dest);
|
|
108
182
|
if (selector) {
|
|
109
183
|
const el = await page.$(selector);
|
|
@@ -115,19 +189,37 @@ export function registerTakeScreenshot(server) {
|
|
|
115
189
|
else {
|
|
116
190
|
await page.screenshot({ path: dest, fullPage: fullPage || false });
|
|
117
191
|
}
|
|
192
|
+
// A navigation may have completed while the capture was in progress
|
|
193
|
+
if (blockedNavigation) {
|
|
194
|
+
await unlink(dest).catch(() => { });
|
|
195
|
+
return err(`URL validation failed: ${blockedNavigation}`);
|
|
196
|
+
}
|
|
118
197
|
return ok(`Screenshot saved: ${dest}`);
|
|
198
|
+
};
|
|
199
|
+
try {
|
|
200
|
+
const work = capture();
|
|
201
|
+
// Once the deadline wins, work's eventual rejection has no listener
|
|
202
|
+
work.catch(() => { });
|
|
203
|
+
// SEC-005: Overall deadline. Individual Puppeteer calls (notably
|
|
204
|
+
// screenshot()) have no timeout of their own and can hang forever.
|
|
205
|
+
const deadline = new Promise((_, reject) => {
|
|
206
|
+
deadlineTimer = setTimeout(() => {
|
|
207
|
+
timedOut = true;
|
|
208
|
+
reject(new Error(`timed out after ${SCREENSHOT_DEADLINE_MS}ms`));
|
|
209
|
+
}, SCREENSHOT_DEADLINE_MS);
|
|
210
|
+
});
|
|
211
|
+
return await Promise.race([work, deadline]);
|
|
119
212
|
}
|
|
120
213
|
catch (e) {
|
|
121
214
|
return err(`Screenshot error: ${e instanceof Error ? e.message : e}`);
|
|
122
215
|
}
|
|
123
216
|
finally {
|
|
217
|
+
clearTimeout(deadlineTimer);
|
|
124
218
|
// Ensure browser is always closed to prevent resource leaks
|
|
125
|
-
// Close browser BEFORE releasing semaphore to avoid briefly exceeding concurrency limit
|
|
219
|
+
// Close browser BEFORE releasing semaphore to avoid briefly exceeding concurrency limit.
|
|
220
|
+
// On timeout, skip the graceful close (it would likely hang too) and kill outright.
|
|
126
221
|
if (browser) {
|
|
127
|
-
|
|
128
|
-
await browser.close();
|
|
129
|
-
}
|
|
130
|
-
catch { /* browser may already be dead */ }
|
|
222
|
+
await shutdownBrowser(browser, timedOut);
|
|
131
223
|
}
|
|
132
224
|
// SEC-005: Always release permit to prevent deadlock, even on error
|
|
133
225
|
puppeteerSemaphore.release();
|
|
@@ -66,11 +66,11 @@ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
|
|
66
66
|
${opts.includeCursor ? '$cursorPos = [System.Windows.Forms.Cursor]::Position\n' : ''}
|
|
67
67
|
$graphics.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)
|
|
68
68
|
${opts.includeCursor ? this.cursorDrawScript() : ''}
|
|
69
|
-
$bitmap.Save(
|
|
69
|
+
$bitmap.Save($env:SS_OUTPUT_PATH, [System.Drawing.Imaging.ImageFormat]::${format})
|
|
70
70
|
$graphics.Dispose()
|
|
71
71
|
$bitmap.Dispose()
|
|
72
72
|
`.trim();
|
|
73
|
-
await this.runPowerShell(script);
|
|
73
|
+
await this.runPowerShell(script, { SS_OUTPUT_PATH: opts.outputPath });
|
|
74
74
|
}
|
|
75
75
|
async captureWindow(opts) {
|
|
76
76
|
if (opts.delay && opts.delay > 0)
|
|
@@ -82,8 +82,9 @@ $bitmap.Dispose()
|
|
|
82
82
|
// Use windowName to find the process, or windowId as HWND
|
|
83
83
|
const findWindowScript = opts.windowName
|
|
84
84
|
? `
|
|
85
|
-
$
|
|
86
|
-
|
|
85
|
+
$windowName = $env:SS_WINDOW_NAME
|
|
86
|
+
$proc = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and $_.MainWindowTitle.IndexOf($windowName, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 } | Select-Object -First 1
|
|
87
|
+
if (-not $proc) { throw "Window not found: $windowName" }
|
|
87
88
|
$hwnd = $proc.MainWindowHandle
|
|
88
89
|
`
|
|
89
90
|
: `$hwnd = [IntPtr]::new(${opts.windowId})`;
|
|
@@ -115,11 +116,14 @@ if ($width -le 0 -or $height -le 0) { throw "Invalid window dimensions" }
|
|
|
115
116
|
$bitmap = New-Object System.Drawing.Bitmap($width, $height)
|
|
116
117
|
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
|
117
118
|
$graphics.CopyFromScreen($rect.Left, $rect.Top, 0, 0, (New-Object System.Drawing.Size($width, $height)))
|
|
118
|
-
$bitmap.Save(
|
|
119
|
+
$bitmap.Save($env:SS_OUTPUT_PATH, [System.Drawing.Imaging.ImageFormat]::${format})
|
|
119
120
|
$graphics.Dispose()
|
|
120
121
|
$bitmap.Dispose()
|
|
121
122
|
`.trim();
|
|
122
|
-
await this.runPowerShell(script
|
|
123
|
+
await this.runPowerShell(script, {
|
|
124
|
+
SS_OUTPUT_PATH: opts.outputPath,
|
|
125
|
+
...(opts.windowName ? { SS_WINDOW_NAME: opts.windowName } : {}),
|
|
126
|
+
});
|
|
123
127
|
}
|
|
124
128
|
async captureRegion(opts) {
|
|
125
129
|
if (opts.delay && opts.delay > 0)
|
|
@@ -131,14 +135,22 @@ Add-Type -AssemblyName System.Drawing
|
|
|
131
135
|
$bitmap = New-Object System.Drawing.Bitmap(${opts.width}, ${opts.height})
|
|
132
136
|
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
|
133
137
|
$graphics.CopyFromScreen(${opts.x}, ${opts.y}, 0, 0, (New-Object System.Drawing.Size(${opts.width}, ${opts.height})))
|
|
134
|
-
$bitmap.Save(
|
|
138
|
+
$bitmap.Save($env:SS_OUTPUT_PATH, [System.Drawing.Imaging.ImageFormat]::${format})
|
|
135
139
|
$graphics.Dispose()
|
|
136
140
|
$bitmap.Dispose()
|
|
137
141
|
`.trim();
|
|
138
|
-
await this.runPowerShell(script);
|
|
142
|
+
await this.runPowerShell(script, { SS_OUTPUT_PATH: opts.outputPath });
|
|
139
143
|
}
|
|
140
144
|
// ── Private helpers ────────────────────────────────────────────────────
|
|
141
|
-
|
|
145
|
+
/**
|
|
146
|
+
* Run a static PowerShell script. Untrusted values (paths, window names) are
|
|
147
|
+
* never interpolated into the script text: PowerShell's tokenizer treats
|
|
148
|
+
* U+2018–U+201B as single quotes and U+201C–U+201E as double quotes, so
|
|
149
|
+
* escaping ASCII quotes alone cannot keep them inside a string literal.
|
|
150
|
+
* Instead they are passed as environment variables and read via `$env:NAME`,
|
|
151
|
+
* which PowerShell never re-parses as code (SEC-003).
|
|
152
|
+
*/
|
|
153
|
+
async runPowerShell(script, vars) {
|
|
142
154
|
const cmd = this.powershellPath ?? 'powershell';
|
|
143
155
|
const encoded = Buffer.from(script, 'utf16le').toString('base64');
|
|
144
156
|
await execFileAsync(cmd, [
|
|
@@ -146,7 +158,7 @@ $bitmap.Dispose()
|
|
|
146
158
|
'-NoProfile',
|
|
147
159
|
'-NonInteractive',
|
|
148
160
|
'-EncodedCommand', encoded,
|
|
149
|
-
]);
|
|
161
|
+
], { env: { ...process.env, ...vars } });
|
|
150
162
|
}
|
|
151
163
|
dotNetFormat(format) {
|
|
152
164
|
switch (format) {
|
|
@@ -154,14 +166,6 @@ $bitmap.Dispose()
|
|
|
154
166
|
default: return 'Png';
|
|
155
167
|
}
|
|
156
168
|
}
|
|
157
|
-
escapePath(p) {
|
|
158
|
-
// Escape single quotes for PowerShell string literals
|
|
159
|
-
return p.replace(/'/g, "''");
|
|
160
|
-
}
|
|
161
|
-
escapeString(s) {
|
|
162
|
-
// Escape characters that could break PowerShell string interpolation
|
|
163
|
-
return s.replace(/'/g, "''").replace(/[`$"]/g, '');
|
|
164
|
-
}
|
|
165
169
|
cursorDrawScript() {
|
|
166
170
|
return `
|
|
167
171
|
try {
|
package/build/validators/url.js
CHANGED
|
@@ -1,126 +1,192 @@
|
|
|
1
1
|
import { promises as dns } from 'dns';
|
|
2
|
+
import { isIP, isIPv4, isIPv6 } from 'net';
|
|
2
3
|
import { URL } from 'url';
|
|
3
4
|
const defaultDnsResolver = {
|
|
4
5
|
lookup: (hostname, options) => dns.lookup(hostname, options),
|
|
5
6
|
};
|
|
6
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Every IPv4 block that is not globally reachable unicast (IANA special-purpose
|
|
9
|
+
* registry, plus multicast and reserved space). Anything outside these ranges
|
|
10
|
+
* is ordinary public unicast.
|
|
11
|
+
*/
|
|
12
|
+
const BLOCKED_IPV4_RANGES = [
|
|
13
|
+
{ base: '0.0.0.0', prefix: 8, reason: 'Access to 0.x.x.x addresses is not allowed' },
|
|
14
|
+
{ base: '10.0.0.0', prefix: 8, reason: 'Access to private network (10.x.x.x) is not allowed' },
|
|
15
|
+
{ base: '100.64.0.0', prefix: 10, reason: 'Access to shared/CGNAT addresses (100.64-127.x.x) is not allowed' },
|
|
16
|
+
{ base: '127.0.0.0', prefix: 8, reason: 'Access to loopback addresses is not allowed' },
|
|
17
|
+
{ base: '169.254.0.0', prefix: 16, reason: 'Access to link-local/metadata addresses (169.254.x.x) is not allowed' },
|
|
18
|
+
{ base: '172.16.0.0', prefix: 12, reason: 'Access to private network (172.16-31.x.x) is not allowed' },
|
|
19
|
+
{ base: '192.0.0.0', prefix: 24, reason: 'Access to IETF protocol assignment addresses (192.0.0.x) is not allowed' },
|
|
20
|
+
{ base: '192.0.2.0', prefix: 24, reason: 'Access to documentation addresses (TEST-NET-1, 192.0.2.x) is not allowed' },
|
|
21
|
+
{ base: '192.88.99.0', prefix: 24, reason: 'Access to 6to4 relay anycast addresses (192.88.99.x) is not allowed' },
|
|
22
|
+
{ base: '192.168.0.0', prefix: 16, reason: 'Access to private network (192.168.x.x) is not allowed' },
|
|
23
|
+
{ base: '198.18.0.0', prefix: 15, reason: 'Access to benchmark addresses (198.18-19.x.x) is not allowed' },
|
|
24
|
+
{ base: '198.51.100.0', prefix: 24, reason: 'Access to documentation addresses (TEST-NET-2, 198.51.100.x) is not allowed' },
|
|
25
|
+
{ base: '203.0.113.0', prefix: 24, reason: 'Access to documentation addresses (TEST-NET-3, 203.0.113.x) is not allowed' },
|
|
26
|
+
{ base: '224.0.0.0', prefix: 4, reason: 'Access to multicast addresses (224-239.x.x.x) is not allowed' },
|
|
27
|
+
{ base: '240.0.0.0', prefix: 4, reason: 'Access to reserved/broadcast addresses (240-255.x.x.x) is not allowed' },
|
|
28
|
+
];
|
|
29
|
+
/** Parse a dotted-quad IPv4 address to an unsigned 32-bit integer. */
|
|
30
|
+
function ipv4ToInt(ip) {
|
|
31
|
+
return ip.split('.').reduce((acc, octet) => ((acc << 8) | Number(octet)) >>> 0, 0);
|
|
32
|
+
}
|
|
33
|
+
function intToIpv4(n) {
|
|
34
|
+
return [n >>> 24, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff].join('.');
|
|
35
|
+
}
|
|
36
|
+
function inIpv4Range(ip, base, prefix) {
|
|
37
|
+
const mask = prefix === 0 ? 0 : (~0 << (32 - prefix)) >>> 0;
|
|
38
|
+
return ((ip & mask) >>> 0) === ((ipv4ToInt(base) & mask) >>> 0);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Parse an IPv6 address (any textual form, including an embedded dotted IPv4
|
|
42
|
+
* tail or a zone index) into its eight 16-bit groups. Returns null if invalid.
|
|
43
|
+
*/
|
|
44
|
+
function parseIPv6(ip) {
|
|
45
|
+
let addr = ip.toLowerCase();
|
|
46
|
+
const zone = addr.indexOf('%');
|
|
47
|
+
if (zone !== -1)
|
|
48
|
+
addr = addr.slice(0, zone);
|
|
49
|
+
if (!isIPv6(addr))
|
|
50
|
+
return null;
|
|
51
|
+
// Rewrite a dotted IPv4 tail (::ffff:1.2.3.4) as two hex groups.
|
|
52
|
+
const lastColon = addr.lastIndexOf(':');
|
|
53
|
+
const tail = addr.slice(lastColon + 1);
|
|
54
|
+
if (tail.includes('.')) {
|
|
55
|
+
const v4 = ipv4ToInt(tail);
|
|
56
|
+
addr = `${addr.slice(0, lastColon + 1)}${(v4 >>> 16).toString(16)}:${(v4 & 0xffff).toString(16)}`;
|
|
57
|
+
}
|
|
58
|
+
const [head, rest] = addr.split('::');
|
|
59
|
+
const headGroups = head ? head.split(':') : [];
|
|
60
|
+
const restGroups = rest ? rest.split(':') : [];
|
|
61
|
+
const fill = rest === undefined ? 0 : 8 - headGroups.length - restGroups.length;
|
|
62
|
+
const groups = [...headGroups, ...Array(fill).fill('0'), ...restGroups].map((g) => parseInt(g, 16));
|
|
63
|
+
return groups.length === 8 ? groups : null;
|
|
64
|
+
}
|
|
65
|
+
/** Extract the IPv4 address carried in two 16-bit groups. */
|
|
66
|
+
function embeddedIpv4(high, low) {
|
|
67
|
+
return intToIpv4(((high << 16) | low) >>> 0);
|
|
68
|
+
}
|
|
69
|
+
/** Check if an IP is a loopback address (the only range `allowLocal` re-opens). */
|
|
7
70
|
function isLoopback(ip, family) {
|
|
8
71
|
if (family === 4) {
|
|
9
|
-
return
|
|
72
|
+
return isIPv4(ip) && ip.startsWith('127.');
|
|
10
73
|
}
|
|
11
|
-
const
|
|
12
|
-
if (
|
|
74
|
+
const g = parseIPv6(ip);
|
|
75
|
+
if (!g)
|
|
76
|
+
return false;
|
|
77
|
+
const upperZero = g.slice(0, 5).every((x) => x === 0);
|
|
78
|
+
// ::1
|
|
79
|
+
if (upperZero && g[5] === 0 && g[6] === 0 && g[7] === 1)
|
|
13
80
|
return true;
|
|
14
|
-
// ::ffff:127.
|
|
15
|
-
|
|
16
|
-
return true;
|
|
17
|
-
// ::ffff:7f00:0 through ::ffff:7fff:ffff (hex form for 127.0.0.0/8)
|
|
18
|
-
const hexMatch = normalized.match(/^::ffff:([0-9a-f]{1,4}):[0-9a-f]{1,4}$/);
|
|
19
|
-
if (hexMatch) {
|
|
20
|
-
const high = parseInt(hexMatch[1], 16);
|
|
21
|
-
if ((high >> 8) === 127)
|
|
22
|
-
return true;
|
|
23
|
-
}
|
|
24
|
-
return false;
|
|
81
|
+
// ::ffff:127.0.0.0/104 — IPv4-mapped loopback connects to the real 127.x host
|
|
82
|
+
return upperZero && g[5] === 0xffff && (g[6] >> 8) === 127;
|
|
25
83
|
}
|
|
26
|
-
/**
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
84
|
+
/**
|
|
85
|
+
* Check any IP address (IPv4 or IPv6) against the SSRF policy, applying the
|
|
86
|
+
* `allowLocal` loopback exception. Fails closed on anything that is not a
|
|
87
|
+
* valid IP address of the expected family.
|
|
88
|
+
*/
|
|
89
|
+
export function isBlockedIp(ip, options) {
|
|
90
|
+
const address = ip.startsWith('[') && ip.endsWith(']') ? ip.slice(1, -1) : ip;
|
|
91
|
+
const detected = isIP(address.split('%')[0]);
|
|
92
|
+
if (detected === 0 || (options?.family !== undefined && options.family !== detected)) {
|
|
93
|
+
return { blocked: true, reason: `Not a valid IP address: ${ip}` };
|
|
94
|
+
}
|
|
95
|
+
const family = detected;
|
|
96
|
+
const result = family === 4 ? isBlockedIPv4(address) : isBlockedIPv6(address);
|
|
97
|
+
if (result.blocked && options?.allowLocal && isLoopback(address, family)) {
|
|
30
98
|
return { blocked: false };
|
|
31
99
|
}
|
|
32
100
|
return result;
|
|
33
101
|
}
|
|
34
|
-
/**
|
|
102
|
+
/**
|
|
103
|
+
* Check if an IPv4 address is outside public unicast space.
|
|
104
|
+
* Returns not-blocked for strings that are not IPv4 addresses; use
|
|
105
|
+
* {@link isBlockedIp} for a fail-closed check of arbitrary input.
|
|
106
|
+
*/
|
|
35
107
|
export function isBlockedIPv4(ip) {
|
|
36
|
-
|
|
37
|
-
if (!ipv4Match) {
|
|
108
|
+
if (!isIPv4(ip)) {
|
|
38
109
|
return { blocked: false }; // Not an IPv4 address, check elsewhere
|
|
39
110
|
}
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
if (a === 172 && b >= 16 && b <= 31) {
|
|
51
|
-
return { blocked: true, reason: 'Access to private network (172.16-31.x.x) is not allowed' };
|
|
52
|
-
}
|
|
53
|
-
// Block private: 192.168.0.0/16
|
|
54
|
-
if (a === 192 && b === 168) {
|
|
55
|
-
return { blocked: true, reason: 'Access to private network (192.168.x.x) is not allowed' };
|
|
56
|
-
}
|
|
57
|
-
// Block link-local and cloud metadata: 169.254.0.0/16
|
|
58
|
-
if (a === 169 && b === 254) {
|
|
59
|
-
return { blocked: true, reason: 'Access to link-local/metadata addresses (169.254.x.x) is not allowed' };
|
|
60
|
-
}
|
|
61
|
-
// Block 0.0.0.0/8
|
|
62
|
-
if (a === 0) {
|
|
63
|
-
return { blocked: true, reason: 'Access to 0.x.x.x addresses is not allowed' };
|
|
64
|
-
}
|
|
65
|
-
// Block CGNAT / Shared Address Space: 100.64.0.0/10 (100.64.x.x - 100.127.x.x)
|
|
66
|
-
// Used by AWS VPC, Tailscale, carrier-grade NAT
|
|
67
|
-
if (a === 100 && b >= 64 && b <= 127) {
|
|
68
|
-
return { blocked: true, reason: 'Access to shared/CGNAT addresses (100.64-127.x.x) is not allowed' };
|
|
69
|
-
}
|
|
70
|
-
// Block benchmark testing: 198.18.0.0/15 (198.18.x.x - 198.19.x.x)
|
|
71
|
-
if (a === 198 && (b === 18 || b === 19)) {
|
|
72
|
-
return { blocked: true, reason: 'Access to benchmark addresses (198.18-19.x.x) is not allowed' };
|
|
73
|
-
}
|
|
74
|
-
// Block broadcast: 255.255.255.255
|
|
75
|
-
if (a === 255 && b === 255 && c === 255 && d === 255) {
|
|
76
|
-
return { blocked: true, reason: 'Access to broadcast address is not allowed' };
|
|
111
|
+
const n = ipv4ToInt(ip);
|
|
112
|
+
const match = BLOCKED_IPV4_RANGES.find((r) => inIpv4Range(n, r.base, r.prefix));
|
|
113
|
+
return match ? { blocked: true, reason: match.reason } : { blocked: false };
|
|
114
|
+
}
|
|
115
|
+
/** Re-check an IPv4 address embedded in an IPv6 address. */
|
|
116
|
+
function checkEmbeddedIpv4(kind, high, low) {
|
|
117
|
+
const v4 = embeddedIpv4(high, low);
|
|
118
|
+
const check = isBlockedIPv4(v4);
|
|
119
|
+
if (check.blocked) {
|
|
120
|
+
return { blocked: true, reason: `Access to ${kind} blocked address (${v4}): ${check.reason}` };
|
|
77
121
|
}
|
|
78
122
|
return { blocked: false };
|
|
79
123
|
}
|
|
80
|
-
/**
|
|
124
|
+
/**
|
|
125
|
+
* Check if an IPv6 address is outside global unicast space.
|
|
126
|
+
*
|
|
127
|
+
* This is an allow-list: only 2000::/3 is accepted, minus its special-purpose
|
|
128
|
+
* blocks. Formats that wrap an IPv4 address and are routed to it (IPv4-mapped,
|
|
129
|
+
* NAT64 well-known prefix, 6to4) are unwrapped and the embedded address is
|
|
130
|
+
* re-checked against the IPv4 policy.
|
|
131
|
+
*
|
|
132
|
+
* Returns not-blocked for strings that are not IPv6 addresses; use
|
|
133
|
+
* {@link isBlockedIp} for a fail-closed check of arbitrary input.
|
|
134
|
+
*/
|
|
81
135
|
export function isBlockedIPv6(ip) {
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
136
|
+
const g = parseIPv6(ip);
|
|
137
|
+
if (!g) {
|
|
138
|
+
return { blocked: false }; // Not an IPv6 address, check elsewhere
|
|
139
|
+
}
|
|
140
|
+
// ::/96 family: unspecified, loopback, IPv4-compatible, IPv4-mapped
|
|
141
|
+
if (g.slice(0, 5).every((x) => x === 0)) {
|
|
142
|
+
if (g[5] === 0xffff) {
|
|
143
|
+
return checkEmbeddedIpv4('IPv4-mapped', g[6], g[7]);
|
|
144
|
+
}
|
|
145
|
+
if (g[5] === 0) {
|
|
146
|
+
if (g[6] === 0 && g[7] === 0) {
|
|
147
|
+
return { blocked: true, reason: 'Access to the IPv6 unspecified address (::) is not allowed' };
|
|
148
|
+
}
|
|
149
|
+
if (g[6] === 0 && g[7] === 1) {
|
|
150
|
+
return { blocked: true, reason: 'Access to IPv6 localhost is not allowed' };
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
blocked: true,
|
|
154
|
+
reason: `Access to deprecated IPv4-compatible IPv6 addresses (::${embeddedIpv4(g[6], g[7])}) is not allowed`,
|
|
155
|
+
};
|
|
95
156
|
}
|
|
96
157
|
}
|
|
97
|
-
//
|
|
98
|
-
if (
|
|
99
|
-
return
|
|
158
|
+
// 64:ff9b::/96 — NAT64 well-known prefix (RFC 6052); routed to the embedded IPv4
|
|
159
|
+
if (g[0] === 0x64 && g[1] === 0xff9b && g.slice(2, 6).every((x) => x === 0)) {
|
|
160
|
+
return checkEmbeddedIpv4('NAT64', g[6], g[7]);
|
|
100
161
|
}
|
|
101
|
-
//
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
if (ipv4Check.blocked) {
|
|
106
|
-
return { blocked: true, reason: `Access to IPv4-mapped blocked address: ${ipv4Check.reason}` };
|
|
162
|
+
// Allow-list: anything outside 2000::/3 is not global unicast
|
|
163
|
+
if ((g[0] & 0xe000) !== 0x2000) {
|
|
164
|
+
if ((g[0] & 0xffc0) === 0xfe80) {
|
|
165
|
+
return { blocked: true, reason: 'Access to IPv6 link-local addresses is not allowed' };
|
|
107
166
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const high = parseInt(ipv4MappedHexMatch[1], 16);
|
|
114
|
-
const low = parseInt(ipv4MappedHexMatch[2], 16);
|
|
115
|
-
const a = (high >> 8) & 0xff;
|
|
116
|
-
const b = high & 0xff;
|
|
117
|
-
const c = (low >> 8) & 0xff;
|
|
118
|
-
const d = low & 0xff;
|
|
119
|
-
const ipv4 = `${a}.${b}.${c}.${d}`;
|
|
120
|
-
const ipv4Check = isBlockedIPv4(ipv4);
|
|
121
|
-
if (ipv4Check.blocked) {
|
|
122
|
-
return { blocked: true, reason: `Access to IPv4-mapped blocked address: ${ipv4Check.reason}` };
|
|
167
|
+
if ((g[0] & 0xfe00) === 0xfc00) {
|
|
168
|
+
return { blocked: true, reason: 'Access to IPv6 private addresses is not allowed' };
|
|
169
|
+
}
|
|
170
|
+
if ((g[0] & 0xff00) === 0xff00) {
|
|
171
|
+
return { blocked: true, reason: 'Access to IPv6 multicast addresses is not allowed' };
|
|
123
172
|
}
|
|
173
|
+
return { blocked: true, reason: 'Access to non-global-unicast IPv6 addresses is not allowed' };
|
|
174
|
+
}
|
|
175
|
+
// 2002::/16 — 6to4 (RFC 3056); routed to the embedded IPv4
|
|
176
|
+
if (g[0] === 0x2002) {
|
|
177
|
+
return checkEmbeddedIpv4('6to4', g[1], g[2]);
|
|
178
|
+
}
|
|
179
|
+
// 2001::/23 — IETF protocol assignments (Teredo, benchmarking, ORCHID, ...)
|
|
180
|
+
if (g[0] === 0x2001 && g[1] < 0x0200) {
|
|
181
|
+
return { blocked: true, reason: 'Access to IPv6 IETF protocol assignment addresses (2001::/23) is not allowed' };
|
|
182
|
+
}
|
|
183
|
+
// 2001:db8::/32 and 3fff::/20 — documentation (RFC 3849, RFC 9637)
|
|
184
|
+
if ((g[0] === 0x2001 && g[1] === 0x0db8) || (g[0] === 0x3fff && g[1] < 0x1000)) {
|
|
185
|
+
return { blocked: true, reason: 'Access to IPv6 documentation addresses is not allowed' };
|
|
186
|
+
}
|
|
187
|
+
// 5f00::/16 — SRv6 SIDs (RFC 9602), not globally reachable
|
|
188
|
+
if (g[0] === 0x5f00) {
|
|
189
|
+
return { blocked: true, reason: 'Access to IPv6 SRv6 SID addresses is not allowed' };
|
|
124
190
|
}
|
|
125
191
|
return { blocked: false };
|
|
126
192
|
}
|
|
@@ -157,7 +223,7 @@ export async function validateUrl(urlString, options) {
|
|
|
157
223
|
const isLiteralIPv6 = hostname.startsWith('[') && hostname.endsWith(']');
|
|
158
224
|
if (isLiteralIPv4) {
|
|
159
225
|
// Direct IPv4 - validate immediately
|
|
160
|
-
const ipCheck =
|
|
226
|
+
const ipCheck = isBlockedIp(hostname, { allowLocal, family: 4 });
|
|
161
227
|
if (ipCheck.blocked) {
|
|
162
228
|
return { valid: false, error: ipCheck.reason };
|
|
163
229
|
}
|
|
@@ -166,7 +232,7 @@ export async function validateUrl(urlString, options) {
|
|
|
166
232
|
if (isLiteralIPv6) {
|
|
167
233
|
// Direct IPv6 - validate immediately (strip brackets)
|
|
168
234
|
const ipv6 = hostname.slice(1, -1);
|
|
169
|
-
const ipCheck =
|
|
235
|
+
const ipCheck = isBlockedIp(ipv6, { allowLocal, family: 6 });
|
|
170
236
|
if (ipCheck.blocked) {
|
|
171
237
|
return { valid: false, error: ipCheck.reason };
|
|
172
238
|
}
|
|
@@ -184,7 +250,7 @@ export async function validateUrl(urlString, options) {
|
|
|
184
250
|
let firstNonBlockedIp;
|
|
185
251
|
for (const addr of addresses) {
|
|
186
252
|
if (addr.family === 4 || addr.family === 6) {
|
|
187
|
-
const ipCheck =
|
|
253
|
+
const ipCheck = isBlockedIp(addr.address, { allowLocal, family: addr.family });
|
|
188
254
|
if (ipCheck.blocked) {
|
|
189
255
|
return { valid: false, error: `DNS resolved to blocked IP: ${ipCheck.reason}` };
|
|
190
256
|
}
|
|
@@ -192,6 +258,10 @@ export async function validateUrl(urlString, options) {
|
|
|
192
258
|
firstNonBlockedIp = addr.address;
|
|
193
259
|
}
|
|
194
260
|
}
|
|
261
|
+
if (!firstNonBlockedIp) {
|
|
262
|
+
// Nothing to pin Chromium to — fail closed rather than let it resolve freely
|
|
263
|
+
return { valid: false, error: 'DNS resolution returned no usable IPv4/IPv6 addresses' };
|
|
264
|
+
}
|
|
195
265
|
return { valid: true, resolvedIp: firstNonBlockedIp, hostname };
|
|
196
266
|
}
|
|
197
267
|
catch (dnsError) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "universal-screenshot-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "An MCP server for capturing web page screenshots via Puppeteer and cross-platform system screenshots via native OS tools",
|
|
5
5
|
"author": "Seth Bang",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -59,12 +59,11 @@
|
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@modelcontextprotocol/client": "^2.0.0",
|
|
61
61
|
"@types/node": "^22.0.0",
|
|
62
|
-
"@typescript-eslint/eslint-plugin": "^8.59.0",
|
|
63
62
|
"@typescript-eslint/parser": "^8.59.0",
|
|
64
63
|
"@vitest/coverage-v8": "^4.0.18",
|
|
65
64
|
"eslint": "^10.2.1",
|
|
66
65
|
"jiti": "^2.4.0",
|
|
67
|
-
"typescript": "
|
|
66
|
+
"typescript": "~6.0.0",
|
|
68
67
|
"vitest": "^4.0.18"
|
|
69
68
|
}
|
|
70
69
|
}
|