universal-screenshot-mcp 1.0.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -112,7 +112,7 @@ Captures a web page (or a specific element) via a headless Puppeteer browser.
112
112
  | `selector` | string | — | CSS selector to capture a specific element |
113
113
  | `waitForSelector` | string | — | Wait for this selector before capturing |
114
114
  | `waitForTimeout` | number | — | Delay in milliseconds (0–30000) |
115
- | `outputPath` | string | — | Output file path (default: `~/Desktop/Screenshots`) |
115
+ | `outputPath` | string | — | Output file path (default: `~/Documents/screenshots`) |
116
116
 
117
117
  **Example prompt:**
118
118
  > Take a screenshot of https://example.com at 1920x1080
@@ -131,7 +131,7 @@ Captures the desktop, a specific application window, or a screen region using na
131
131
  | `includeCursor` | boolean | — | Include the mouse cursor in the capture |
132
132
  | `format` | enum | — | `png` (default) or `jpg` |
133
133
  | `delay` | number | — | Capture delay in seconds (0–10) |
134
- | `outputPath` | string | — | Output file path (default: `~/Desktop/Screenshots`) |
134
+ | `outputPath` | string | — | Output file path (default: `~/Documents/screenshots`) |
135
135
 
136
136
  #### Cross-Platform Feature Support
137
137
 
@@ -148,13 +148,23 @@ Captures the desktop, a specific application window, or a screen region using na
148
148
  **Example prompt:**
149
149
  > Take a system screenshot of the Safari window
150
150
 
151
- ## Output Directories
151
+ ## Configuration
152
152
 
153
- Screenshots are saved to `~/Desktop/Screenshots` by default. Custom output paths must resolve to one of these allowed directories:
153
+ ### Environment Variables
154
+
155
+ | Variable | Default | Description |
156
+ |----------|---------|-------------|
157
+ | `SCREENSHOT_OUTPUT_DIR` | `Documents/screenshots` | Default output directory relative to `~` |
158
+ | `ALLOW_LOCAL` | `false` | Set to `true` to allow screenshotting `localhost`/`127.x.x.x`/`[::1]` (useful for local dev servers) |
159
+
160
+ ### Output Directories
161
+
162
+ Screenshots are saved to `~/Documents/screenshots` by default (configurable via `SCREENSHOT_OUTPUT_DIR`). Custom output paths must resolve to one of these allowed directories:
154
163
 
155
164
  | Directory | Description |
156
165
  |------------------------|--------------------------|
157
- | `~/Desktop/Screenshots`| Default output location |
166
+ | `~/Documents/screenshots` | Default output location (configurable) |
167
+ | `~/Desktop/Screenshots`| Original default location |
158
168
  | `~/Downloads` | User downloads folder |
159
169
  | `~/Documents` | User documents folder |
160
170
  | `/tmp` | System temp directory |
@@ -176,15 +186,19 @@ For full details, see [`docs/security.md`](docs/security.md).
176
186
 
177
187
  ### Scripts
178
188
 
179
- | Command | Description |
180
- |----------------------|-----------------------------------|
181
- | `npm run build` | Compile TypeScript to `build/` |
182
- | `npm run watch` | Recompile on file changes |
183
- | `npm test` | Run tests with Vitest |
184
- | `npm run test:watch` | Run tests in watch mode |
185
- | `npm run test:coverage` | Run tests with coverage report |
186
- | `npm run lint` | Lint source with ESLint |
187
- | `npm run inspector` | Launch MCP Inspector for debugging|
189
+ | Command | Description |
190
+ |----------------------|----------------------------------------|
191
+ | `npm run build` | Compile TypeScript to `build/` |
192
+ | `npm run watch` | Recompile on file changes |
193
+ | `npm test` | Unit tests (fast, fully mocked) |
194
+ | `npm run test:integration` | Integration tests (real DNS/filesystem) |
195
+ | `npm run test:e2e` | E2E tests (real Puppeteer/native tools)|
196
+ | `npm run test:all` | All test tiers together |
197
+ | `npm run test:linux` | Linux e2e via Docker (requires Docker) |
198
+ | `npm run test:watch` | Run tests in watch mode |
199
+ | `npm run test:coverage` | Run tests with coverage report |
200
+ | `npm run lint` | Lint source with ESLint |
201
+ | `npm run inspector` | Launch MCP Inspector for debugging |
188
202
 
189
203
  ### Project Structure
190
204
 
@@ -215,10 +229,16 @@ src/
215
229
 
216
230
  ### Testing
217
231
 
218
- Tests use [Vitest](https://vitest.dev/) with full dependency injection — no real network calls, filesystem access, or subprocess execution in tests.
232
+ Tests use [Vitest](https://vitest.dev/) in three tiers:
233
+
234
+ - **Unit** (`npm test`) — Full dependency injection, no real I/O. Fast feedback loop.
235
+ - **Integration** (`npm run test:integration`) — Real DNS resolution, real filesystem with temp directories, real Puppeteer against a local HTTP server.
236
+ - **E2E** (`npm run test:e2e`) — Real native screenshot tools. macOS tests run natively; Linux tests run in Docker via `npm run test:linux`.
219
237
 
220
238
  ```bash
221
- npm test
239
+ npm test # Unit tests (~300ms)
240
+ npm run test:linux # Linux provider tests in Docker
241
+ npm run test:all # Everything
222
242
  ```
223
243
 
224
244
  ### Debugging with MCP Inspector
@@ -2,21 +2,36 @@
2
2
  // Configuration Constants
3
3
  // ============================================================================
4
4
  import { join } from 'path';
5
+ import { homedir, tmpdir } from 'os';
5
6
  /**
6
7
  * Maximum number of concurrent Puppeteer browser instances.
7
8
  * Each instance spawns a Chromium process consuming 100-500MB of memory.
8
9
  * SEC-005: Prevents resource exhaustion / DoS attacks.
9
10
  */
10
11
  export const MAX_CONCURRENT_SCREENSHOTS = 3;
12
+ /**
13
+ * When true, allows loopback addresses (127.x.x.x, ::1, localhost) in URL validation.
14
+ * All other private/reserved ranges remain blocked regardless of this setting.
15
+ * Useful for screenshotting local dev servers. Off by default for SSRF safety.
16
+ */
17
+ export const ALLOW_LOCAL = process.env.ALLOW_LOCAL === 'true';
11
18
  /**
12
19
  * Resolved allowed output directories for screenshots.
13
20
  * Only these directories (and their subdirectories) are permitted for file output.
14
- * Uses process.env.HOME at module load time (pure computation, no I/O side effects).
21
+ * os.homedir() works cross-platform (USERPROFILE on Windows, HOME on Unix).
22
+ */
23
+ export const homeDir = process.env.HOME || homedir();
24
+ /**
25
+ * Resolved default output directory for screenshots.
26
+ * Priority: 1) SCREENSHOT_OUTPUT_DIR env var 2) ~/Documents/screenshots 3) ~/Desktop/Screenshots
15
27
  */
16
- export const homeDir = process.env.HOME || '/tmp';
28
+ export const configuredOutDir = process.env.SCREENSHOT_OUTPUT_DIR
29
+ ? join(homeDir, process.env.SCREENSHOT_OUTPUT_DIR.replace(/^~\/?/, ''))
30
+ : join(homeDir, 'Documents', 'screenshots');
17
31
  export const ALLOWED_OUTPUT_DIRS = [
18
- join(homeDir, 'Desktop', 'Screenshots'), // ~/Desktop/Screenshots (default output)
19
- '/tmp', // System temp directory
32
+ join(homeDir, 'Desktop', 'Screenshots'), // ~/Desktop/Screenshots (original default)
33
+ configuredOutDir, // Configured default output directory
34
+ tmpdir(), // System temp directory (cross-platform)
20
35
  join(homeDir, 'Downloads'), // ~/Downloads
21
36
  join(homeDir, 'Documents'), // ~/Documents
22
37
  ];
@@ -1,9 +1,13 @@
1
1
  import { Semaphore } from '../utils/semaphore.js';
2
- import { MAX_CONCURRENT_SCREENSHOTS, homeDir } from './index.js';
2
+ import { MAX_CONCURRENT_SCREENSHOTS, homeDir, configuredOutDir } from './index.js';
3
3
  import { mkdirSync } from 'fs';
4
- import { join } from 'path';
5
4
  export { homeDir };
6
- export const defaultOutDir = join(homeDir, 'Desktop', 'Screenshots');
5
+ /**
6
+ * Default output directory for screenshots.
7
+ * Configurable via SCREENSHOT_OUTPUT_DIR environment variable.
8
+ * Falls back to ~/Documents/screenshots, then ~/Desktop/Screenshots.
9
+ */
10
+ export const defaultOutDir = configuredOutDir;
7
11
  // SINGLETON — the only Semaphore instance in the entire codebase
8
12
  export const puppeteerSemaphore = new Semaphore(MAX_CONCURRENT_SCREENSHOTS);
9
13
  // Lazy directory creation — called by tools on first use, not at import
@@ -1,14 +1,14 @@
1
1
  import { z } from 'zod';
2
2
  import puppeteer from 'puppeteer';
3
3
  import { puppeteerSemaphore, defaultOutDir, ensureDefaultDirectory } from '../config/runtime.js';
4
- import { ALLOWED_OUTPUT_DIRS, MAX_CONCURRENT_SCREENSHOTS } from '../config/index.js';
4
+ import { ALLOWED_OUTPUT_DIRS, MAX_CONCURRENT_SCREENSHOTS, ALLOW_LOCAL } from '../config/index.js';
5
5
  import { validateUrl } from '../validators/url.js';
6
6
  import { validateOutputPath } from '../validators/path.js';
7
7
  import { ok, err, timestamp, ensureDir } from '../utils/helpers.js';
8
8
  // Semaphore protects expensive Puppeteer operations
9
9
  export function registerTakeScreenshot(server) {
10
10
  server.registerTool('take_screenshot', {
11
- description: 'Capture web page or element via headless browser. Saves to ~/Desktop/Screenshots by default.',
11
+ description: 'Capture web page or element via headless browser. Saves to ~/Documents/screenshots by default (configurable via SCREENSHOT_OUTPUT_DIR env var).',
12
12
  inputSchema: {
13
13
  url: z.string().describe('URL to capture'),
14
14
  width: z.number().min(1).max(3840).optional().describe('Viewport width'),
@@ -23,7 +23,7 @@ export function registerTakeScreenshot(server) {
23
23
  ensureDefaultDirectory(); // Ensure the default directory exists
24
24
  // Security: Validate URL before making request (SSRF prevention)
25
25
  // Now async to support DNS resolution for DNS rebinding protection (SEC-001)
26
- const urlValidation = await validateUrl(url);
26
+ const urlValidation = await validateUrl(url, { allowLocal: ALLOW_LOCAL });
27
27
  if (!urlValidation.valid) {
28
28
  return err(`URL validation failed: ${urlValidation.error}`);
29
29
  }
@@ -51,7 +51,11 @@ export function registerTakeScreenshot(server) {
51
51
  '--disable-setuid-sandbox',
52
52
  ];
53
53
  if (urlValidation.resolvedIp && urlValidation.hostname) {
54
- browserArgs.push(`--host-resolver-rules=MAP ${urlValidation.hostname} ${urlValidation.resolvedIp}`);
54
+ // Chromium requires bracket notation for IPv6 addresses in host-resolver-rules
55
+ const pinnedIp = urlValidation.resolvedIp.includes(':')
56
+ ? `[${urlValidation.resolvedIp}]`
57
+ : urlValidation.resolvedIp;
58
+ browserArgs.push(`--host-resolver-rules=MAP ${urlValidation.hostname} ${pinnedIp}`);
55
59
  }
56
60
  browser = await puppeteer.launch({ headless: true, args: browserArgs });
57
61
  const page = await browser.newPage();
@@ -75,7 +79,7 @@ export function registerTakeScreenshot(server) {
75
79
  return;
76
80
  }
77
81
  // Validate redirect target against SSRF rules
78
- const redirectValidation = await validateUrl(reqUrl);
82
+ const redirectValidation = await validateUrl(reqUrl, { allowLocal: ALLOW_LOCAL });
79
83
  if (!redirectValidation.valid) {
80
84
  req.abort('blockedbyclient');
81
85
  return;
@@ -8,7 +8,7 @@ import { getScreenshotProvider } from '../utils/screenshot-provider.js';
8
8
  // No semaphore — system screenshot tools are lightweight (< 100ms, < 10MB)
9
9
  export function registerTakeSystemScreenshot(server) {
10
10
  server.registerTool('take_system_screenshot', {
11
- description: 'Capture desktop, window, or region screenshot. Cross-platform: macOS (screencapture), Linux (maim/scrot/gnome-screenshot/etc.), Windows (PowerShell+.NET). Saves to ~/Desktop/Screenshots by default. For window mode, provide windowName (app name like "Safari") or windowId.',
11
+ description: 'Capture desktop, window, or region screenshot. Cross-platform: macOS (screencapture), Linux (maim/scrot/gnome-screenshot/etc.), Windows (PowerShell+.NET). Saves to ~/Documents/screenshots by default (configurable via SCREENSHOT_OUTPUT_DIR env var). For window mode, provide windowName (app name like "Safari") or windowId.',
12
12
  inputSchema: {
13
13
  mode: z
14
14
  .enum(['fullscreen', 'window', 'region'])
@@ -27,7 +27,7 @@ export function registerTakeSystemScreenshot(server) {
27
27
  })
28
28
  .optional()
29
29
  .describe('Region {x,y,width,height}'),
30
- display: z.number().min(1).optional().describe('Display number'),
30
+ display: z.number().int().min(1).optional().describe('Display number'),
31
31
  includeCursor: z.boolean().optional().describe('Include cursor'),
32
32
  format: z.enum(['png', 'jpg']).optional().describe('Image format (png or jpg)'),
33
33
  delay: z.number().min(0).max(10).optional().describe('Delay seconds'),
@@ -16,6 +16,7 @@ export class LinuxProvider {
16
16
  }
17
17
  async captureFullscreen(opts) {
18
18
  const backend = await this.getBackend();
19
+ this.assertSupportedOptions(opts);
19
20
  if (opts.delay && opts.delay > 0)
20
21
  await sleep(opts.delay);
21
22
  switch (backend) {
@@ -41,6 +42,7 @@ export class LinuxProvider {
41
42
  }
42
43
  async captureWindow(opts) {
43
44
  const backend = await this.getBackend();
45
+ this.assertSupportedOptions(opts);
44
46
  if (opts.delay && opts.delay > 0)
45
47
  await sleep(opts.delay);
46
48
  // Try to resolve window ID from name using xdotool (X11 only)
@@ -92,6 +94,7 @@ export class LinuxProvider {
92
94
  }
93
95
  async captureRegion(opts) {
94
96
  const backend = await this.getBackend();
97
+ this.assertSupportedOptions(opts);
95
98
  if (opts.delay && opts.delay > 0)
96
99
  await sleep(opts.delay);
97
100
  const geometry = `${opts.width}x${opts.height}+${opts.x}+${opts.y}`;
@@ -121,6 +124,13 @@ export class LinuxProvider {
121
124
  }
122
125
  }
123
126
  // ── Private helpers ────────────────────────────────────────────────────
127
+ assertSupportedOptions(opts) {
128
+ if (opts.includeCursor) {
129
+ throw new Error('Linux provider does not support includeCursor — none of the supported backends ' +
130
+ '(maim, scrot, gnome-screenshot, spectacle, grim, import) expose a cursor flag in our argv. ' +
131
+ 'Use macOS or Windows for cursor capture.');
132
+ }
133
+ }
124
134
  async detectBackend() {
125
135
  if (this._detected)
126
136
  return;
@@ -2,26 +2,65 @@
2
2
  // Windows screenshot provider — PowerShell + .NET System.Drawing
3
3
  // ============================================================================
4
4
  import { execFileAsync, commandExists, sleep } from './screenshot-provider.js';
5
+ const POWERSHELL_FALLBACK_PATHS = [
6
+ 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',
7
+ 'C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe',
8
+ ];
9
+ async function resolvePowerShell() {
10
+ if (await commandExists('powershell'))
11
+ return 'powershell';
12
+ for (const p of POWERSHELL_FALLBACK_PATHS) {
13
+ try {
14
+ await execFileAsync(p, ['-Command', 'echo ok']);
15
+ return p;
16
+ }
17
+ catch { /* try next */ }
18
+ }
19
+ return null;
20
+ }
5
21
  /**
6
22
  * Windows screenshot provider using PowerShell with .NET System.Drawing.
7
23
  * Zero external dependencies — PowerShell and .NET are built into all modern Windows.
8
24
  */
9
25
  export class WindowsProvider {
10
26
  platform = 'Windows';
27
+ powershellPath = null;
28
+ static DPI_AWARE_SNIPPET = `
29
+ Add-Type -TypeDefinition @"
30
+ using System;
31
+ using System.Runtime.InteropServices;
32
+ public class DpiAwareness {
33
+ [DllImport("user32.dll")]
34
+ public static extern bool SetProcessDPIAware();
35
+ [DllImport("user32.dll", SetLastError = true)]
36
+ public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
37
+ }
38
+ "@
39
+ try { [DpiAwareness]::SetProcessDpiAwarenessContext([IntPtr]::new(-4)) | Out-Null } catch { [DpiAwareness]::SetProcessDPIAware() | Out-Null }`.trim();
11
40
  async isAvailable() {
12
- return commandExists('powershell');
41
+ this.powershellPath = await resolvePowerShell();
42
+ return this.powershellPath !== null;
13
43
  }
14
44
  async captureFullscreen(opts) {
15
45
  if (opts.delay && opts.delay > 0)
16
46
  await sleep(opts.delay);
17
47
  const format = this.dotNetFormat(opts.format);
18
- const displayIndex = (opts.display ?? 1) - 1; // Convert 1-based to 0-based
48
+ // No display specified → capture entire virtual screen (all monitors combined)
49
+ // display specified → capture that specific monitor
50
+ const captureAllDisplays = opts.display === undefined || opts.display === null;
51
+ const displayIndex = captureAllDisplays ? 0 : (opts.display - 1);
52
+ const boundsScript = captureAllDisplays
53
+ ? `
54
+ $bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen`
55
+ : `
56
+ $screens = [System.Windows.Forms.Screen]::AllScreens
57
+ $screen = if (${displayIndex} -lt $screens.Length) { $screens[${displayIndex}] } else { [System.Windows.Forms.Screen]::PrimaryScreen }
58
+ $bounds = $screen.Bounds`;
19
59
  const script = `
60
+ ${WindowsProvider.DPI_AWARE_SNIPPET}
20
61
  Add-Type -AssemblyName System.Windows.Forms
21
62
  Add-Type -AssemblyName System.Drawing
22
- $screens = [System.Windows.Forms.Screen]::AllScreens
23
- $screen = if (${displayIndex} -lt $screens.Length) { $screens[${displayIndex}] } else { [System.Windows.Forms.Screen]::PrimaryScreen }
24
- $bounds = $screen.Bounds
63
+ ${boundsScript}
25
64
  $bitmap = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)
26
65
  $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
27
66
  ${opts.includeCursor ? '$cursorPos = [System.Windows.Forms.Cursor]::Position\n' : ''}
@@ -49,6 +88,7 @@ $hwnd = $proc.MainWindowHandle
49
88
  `
50
89
  : `$hwnd = [IntPtr]::new(${opts.windowId})`;
51
90
  const script = `
91
+ ${WindowsProvider.DPI_AWARE_SNIPPET}
52
92
  Add-Type -AssemblyName System.Drawing
53
93
  Add-Type @"
54
94
  using System;
@@ -86,6 +126,7 @@ $bitmap.Dispose()
86
126
  await sleep(opts.delay);
87
127
  const format = this.dotNetFormat(opts.format);
88
128
  const script = `
129
+ ${WindowsProvider.DPI_AWARE_SNIPPET}
89
130
  Add-Type -AssemblyName System.Drawing
90
131
  $bitmap = New-Object System.Drawing.Bitmap(${opts.width}, ${opts.height})
91
132
  $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
@@ -98,11 +139,13 @@ $bitmap.Dispose()
98
139
  }
99
140
  // ── Private helpers ────────────────────────────────────────────────────
100
141
  async runPowerShell(script) {
101
- await execFileAsync('powershell', [
142
+ const cmd = this.powershellPath ?? 'powershell';
143
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
144
+ await execFileAsync(cmd, [
102
145
  '-ExecutionPolicy', 'Bypass',
103
146
  '-NoProfile',
104
147
  '-NonInteractive',
105
- '-Command', script,
148
+ '-EncodedCommand', encoded,
106
149
  ]);
107
150
  }
108
151
  dotNetFormat(format) {
@@ -1,5 +1,5 @@
1
1
  import { promises as fsPromises } from 'fs';
2
- import { dirname, join, resolve, relative } from 'path';
2
+ import { dirname, join, resolve, relative, isAbsolute } from 'path';
3
3
  const defaultFileSystem = {
4
4
  realpath: (path) => fsPromises.realpath(path),
5
5
  };
@@ -59,14 +59,15 @@ export async function validateOutputPath(customPath, defaultName, config, fileSy
59
59
  realAllowedDir = resolve(allowedDir);
60
60
  }
61
61
  const relativePath = relative(realAllowedDir, realPath);
62
- // If relative path doesn't start with '..' and isn't absolute, it's within the allowed dir
63
- if (!relativePath.startsWith('..') && !relativePath.startsWith('/')) {
62
+ // isAbsolute() catches the cross-drive case on Windows, where relative() returns
63
+ // an absolute path like 'D:\\foo' that doesn't start with '/' or '..'.
64
+ if (!relativePath.startsWith('..') && !isAbsolute(relativePath)) {
64
65
  return { valid: true, path: realPath };
65
66
  }
66
67
  }
67
68
  // Path is outside all allowed directories (after symlink resolution)
68
69
  return {
69
70
  valid: false,
70
- error: 'Output path must be within allowed directories (~/Desktop/Screenshots, ~/Downloads, ~/Documents, or /tmp). Symlinks to other locations are not permitted.',
71
+ error: 'Output path must be within allowed directories (~/Desktop/Screenshots, ~/Documents, ~/Downloads, or the system temp directory). Symlinks to other locations are not permitted.',
71
72
  };
72
73
  }
@@ -3,6 +3,34 @@ import { URL } from 'url';
3
3
  const defaultDnsResolver = {
4
4
  lookup: (hostname, options) => dns.lookup(hostname, options),
5
5
  };
6
+ /** Check if an IP is a loopback address. */
7
+ function isLoopback(ip, family) {
8
+ if (family === 4) {
9
+ return /^127\./.test(ip);
10
+ }
11
+ const normalized = ip.toLowerCase();
12
+ if (normalized === '::1')
13
+ return true;
14
+ // ::ffff:127.x.x.x (dotted form)
15
+ if (/^::ffff:127\./.test(normalized))
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;
25
+ }
26
+ /** Wrapper that applies the allowLocal policy over isBlockedIPv4/isBlockedIPv6. */
27
+ function shouldBlockIp(ip, family, allowLocal) {
28
+ const result = family === 4 ? isBlockedIPv4(ip) : isBlockedIPv6(ip);
29
+ if (result.blocked && allowLocal && isLoopback(ip, family)) {
30
+ return { blocked: false };
31
+ }
32
+ return result;
33
+ }
6
34
  /** Check if an IPv4 address is in a blocked range. */
7
35
  export function isBlockedIPv4(ip) {
8
36
  const ipv4Match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
@@ -100,7 +128,9 @@ export function isBlockedIPv6(ip) {
100
128
  * Validate a URL for SSRF prevention with DNS rebinding protection (SEC-001).
101
129
  * Returns resolvedIp and hostname on success to enable IP pinning.
102
130
  */
103
- export async function validateUrl(urlString, dnsResolver = defaultDnsResolver) {
131
+ export async function validateUrl(urlString, options) {
132
+ const allowLocal = options?.allowLocal ?? false;
133
+ const dnsResolver = options?.dnsResolver ?? defaultDnsResolver;
104
134
  let parsed;
105
135
  try {
106
136
  parsed = new URL(urlString);
@@ -113,20 +143,21 @@ export async function validateUrl(urlString, dnsResolver = defaultDnsResolver) {
113
143
  return { valid: false, error: 'Only http and https protocols are allowed' };
114
144
  }
115
145
  const hostname = parsed.hostname.toLowerCase();
116
- // Block localhost by name
117
- if (hostname === 'localhost' || hostname === 'localhost.localdomain') {
118
- return { valid: false, error: 'Access to localhost is not allowed' };
119
- }
120
- // Block IPv6 localhost in bracket notation
121
- if (hostname === '[::1]') {
122
- return { valid: false, error: 'Access to IPv6 localhost is not allowed' };
146
+ // Block localhost by name (unless allowLocal is enabled)
147
+ if (!allowLocal) {
148
+ if (hostname === 'localhost' || hostname === 'localhost.localdomain') {
149
+ return { valid: false, error: 'Access to localhost is not allowed' };
150
+ }
151
+ if (hostname === '[::1]') {
152
+ return { valid: false, error: 'Access to IPv6 localhost is not allowed' };
153
+ }
123
154
  }
124
155
  // Check if hostname is a literal IP address
125
156
  const isLiteralIPv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.test(hostname);
126
157
  const isLiteralIPv6 = hostname.startsWith('[') && hostname.endsWith(']');
127
158
  if (isLiteralIPv4) {
128
159
  // Direct IPv4 - validate immediately
129
- const ipCheck = isBlockedIPv4(hostname);
160
+ const ipCheck = shouldBlockIp(hostname, 4, allowLocal);
130
161
  if (ipCheck.blocked) {
131
162
  return { valid: false, error: ipCheck.reason };
132
163
  }
@@ -135,7 +166,7 @@ export async function validateUrl(urlString, dnsResolver = defaultDnsResolver) {
135
166
  if (isLiteralIPv6) {
136
167
  // Direct IPv6 - validate immediately (strip brackets)
137
168
  const ipv6 = hostname.slice(1, -1);
138
- const ipCheck = isBlockedIPv6(ipv6);
169
+ const ipCheck = shouldBlockIp(ipv6, 6, allowLocal);
139
170
  if (ipCheck.blocked) {
140
171
  return { valid: false, error: ipCheck.reason };
141
172
  }
@@ -152,16 +183,8 @@ export async function validateUrl(urlString, dnsResolver = defaultDnsResolver) {
152
183
  // Check ALL resolved IPs - if any is blocked, reject the entire request
153
184
  let firstNonBlockedIp;
154
185
  for (const addr of addresses) {
155
- if (addr.family === 4) {
156
- const ipCheck = isBlockedIPv4(addr.address);
157
- if (ipCheck.blocked) {
158
- return { valid: false, error: `DNS resolved to blocked IP: ${ipCheck.reason}` };
159
- }
160
- if (!firstNonBlockedIp)
161
- firstNonBlockedIp = addr.address;
162
- }
163
- else if (addr.family === 6) {
164
- const ipCheck = isBlockedIPv6(addr.address);
186
+ if (addr.family === 4 || addr.family === 6) {
187
+ const ipCheck = shouldBlockIp(addr.address, addr.family, allowLocal);
165
188
  if (ipCheck.blocked) {
166
189
  return { valid: false, error: `DNS resolved to blocked IP: ${ipCheck.reason}` };
167
190
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "universal-screenshot-mcp",
3
- "version": "1.0.0",
3
+ "version": "1.1.2",
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",
@@ -43,6 +43,10 @@
43
43
  "watch": "tsc --watch",
44
44
  "inspector": "npx @modelcontextprotocol/inspector build/index.js",
45
45
  "test": "vitest run",
46
+ "test:integration": "vitest run --config vitest.integration.config.ts",
47
+ "test:e2e": "vitest run --config vitest.e2e.config.ts",
48
+ "test:linux": "bash scripts/run-linux-tests.sh",
49
+ "test:all": "vitest run --config vitest.all.config.ts",
46
50
  "test:watch": "vitest",
47
51
  "test:coverage": "vitest run --coverage",
48
52
  "lint": "eslint src/"