Add a read-only ability to screenshot a public URL with public-only browser egress

Abierto
#2,603 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
58/100
Tipo de issue
Nueva funcionalidad
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
node.js, playwright, typescript, wordpress
Área
backend, security

Línea de trabajo

Start with inc/Core/WebScreenshot/public-proxy.cjs, inc/Core/WebScreenshot/capture.cjs, and tests/web-screenshot-browser.test.cjs, then locate the WordPress ability registration and runner integration. Reuse the pinned Playwright Chromium and existing network-policy entry points rather than introducing separate browser binaries or host filters. Done means the ability returns a base64 PNG for public pages and rejects private-address redirects and iframes, disallowed ports, and missing Chromium with the established error.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

enhancement

Problem

Agents that have no shell, such as MCP clients and chat agents limited to WordPress abilities, can read a public page's text but can't see how it looks. Text extraction of JS-heavy or design-led pages often returns almost nothing; one storefront came back as a few hundred characters of cookie-banner text. Seeing a page means running a headless browser. WP Codebox already owns a pinned, checked Playwright Chromium (playwright-browser-provenance) and a browser network policy, so the capability belongs here rather than in a separate per-plugin set of host-binary filters.

Target state

Add a read-only ability, e.g. wp-codebox/capture-url-screenshot, with tests.

  • Input: url (required, http/https, default ports, no credentials). Optional viewport {width,height} (default 1280x800, max 1600 each). Optional full_page (bool, default false, height capped around 3200px).
  • Output (JSON-safe, binding): { "type": "image", "mimeType": "image/png", "image_base64": "<base64>", "url", "final_url", "width", "height" }. Never raw bytes, so it survives the core /wp-abilities/v1 runner and cross-site dispatch. A downstream MCP layer already unwraps exactly this shape into an MCP image content block.
  • Permission: a read-only capability a site editor can hold, such as edit_posts or a filterable equivalent. Set show_in_rest: true and mark it readonly and idempotent.
  • Browser: use the Chromium that WP Codebox already pins and checks. When it's missing, return a clean WP_Error with the existing readiness message (the playwright/cli.js install chromium hint). Don't introduce new host-path filters.
  • Egress safety (the core of this): every connection the browser makes is checked when it's made. That covers the top URL, redirects, subresources, iframes and workers. Only connections to public IPs on ports 80 and 443 are allowed; loopback, private, link-local (169.254.169.254), CGNAT, reserved, multicast, unique-local and non-global IPv6 are all refused. Fold this into the existing browser network policy as a "public internet only" mode if that fits better than a separate path. Disable service workers, QUIC and non-proxied WebRTC UDP. No file output, a fresh context per capture, and a hard deadline of about 30s.
  • Tests: a public page captures; a redirect to a private address is refused; a private-address iframe never reaches the pixels; non-80/443 ports are refused; and the unavailable-browser error.

Prior art (a working candidate written for another plugin, now redirected here)

An implementation was built and passed its own tests before we decided it belonged in WP Codebox. Its egress design is the part worth keeping: Chromium is launched with proxy: socks5://127.0.0.1:<ephemeral>, bypass: '<-loopback>' and --host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1, so all name resolution happens in the proxy. The proxy resolves each host, rejects the connection if any answer is non-public, and dials only the validated numeric IP.

public-proxy.cjs
/* Loopback-only SOCKS5 proxy for Chromium. No UDP, BIND or direct fallback. */
'use strict';

const dns = require('node:dns').promises;
const net = require('node:net');

const privateV4 = new net.BlockList();
for (const [address, bits] of [
	['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8],
	['169.254.0.0', 16], ['172.16.0.0', 12], ['192.0.0.0', 24],
	['192.0.2.0', 24], ['192.88.99.0', 24], ['192.168.0.0', 16],
	['198.18.0.0', 15], ['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 3],
]) {
	privateV4.addSubnet(address, bits);
}
const globalV6 = new net.BlockList();
globalV6.addSubnet('2000::', 3, 'ipv6');
const specialV6 = new net.BlockList();
for (const [address, bits] of [
	['2001::', 23], ['2001:db8::', 32], ['2002::', 16], ['3ffe::', 16], ['3fff::', 20],
]) {
	specialV6.addSubnet(address, bits, 'ipv6');
}

function isPublicAddress(address) {
	if (net.isIPv4(address)) {
		return !privateV4.check(address);
	}
	return net.isIPv6(address) && !address.includes('%') &&
		globalV6.check(address, 'ipv6') && !specialV6.check(address, 'ipv6');
}

async function publicAddress(host, resolve) {
	const name = host.toLowerCase().replace(/\.$/, '');
	const family = net.isIP(name);
	if (!family && (!/^[a-z0-9_-]+(\.[a-z0-9_-]+)+$/.test(name) || /\.(localhost|local|internal|home\.arpa)$/.test(name))) {
		throw new Error('Not a public hostname');
	}
	// Query an absolute name, without OS DNS search suffixes. Check every answer.
	const addresses = family ? [{ address: name }] : await resolve(`${name}.`);
	if (!addresses.length || addresses.some(({ address }) => !isPublicAddress(address))) {
		throw new Error('Not a public address');
	}
	return addresses[0].address;
}

function createPublicProxy({ resolve = (host) => dns.lookup(host, { all: true }), connect = net.connect } = {}) {
	const server = net.createServer((client) => {
		let buffer = Buffer.alloc(0);
		let greeted = false;
		let upstream;
		client.setTimeout(10000, () => client.destroy());
		client.on('error', () => client.destroy());
		client.on('close', () => upstream?.destroy());

		function deny() {
			client.end(Buffer.from([5, 2, 0, 1, 0, 0, 0, 0, 0, 0]));
		}

		async function establish(host, port) {
			try {
				const address = await publicAddress(host, resolve);
				if (client.destroyed) {
					return;
				}
				// The socket gets only the validated numeric IP, never the hostname.
				upstream = connect({ host: address, port, family: net.isIP(address) });
				upstream.once('connect', () => {
					client.write(Buffer.from([5, 0, 0, 1, 0, 0, 0, 0, 0, 0]));
					client.pipe(upstream).pipe(client);
				});
				upstream.on('error', () => client.destroy());
				upstream.on('close', () => client.destroy());
			} catch {
				deny();
			}
		}

		function readHandshake(chunk) {
			if (buffer.length + chunk.length > 520) {
				client.destroy();
				return;
			}
			buffer = Buffer.concat([buffer, chunk]);
			if (!greeted) {
				if (buffer.length < 2 || buffer.length < 2 + buffer[1]) {
					return;
				}
				const end = 2 + buffer[1];
				if (buffer[0] !== 5 || !buffer.subarray(2, end).includes(0)) {
					client.end(Buffer.from([5, 255]));
					return;
				}
				greeted = true;
				client.write(Buffer.from([5, 0]));
				buffer = buffer.subarray(end);
			}
			if (buffer.length < 5) {
				return;
			}
			const type = buffer[3];
			const end = type === 1 ? 8 : type === 4 ? 20 : type === 3 ? 5 + buffer[4] : 0;
			if (buffer[0] !== 5 || buffer[1] !== 1 || buffer[2] !== 0 || !end) {
				deny();
				return;
			}
			if (buffer.length < end + 2) {
				return;
			}
			client.removeListener('data', readHandshake);
			client.pause();
			const port = buffer.readUInt16BE(end);
			if (buffer.length !== end + 2 || (port !== 80 && port !== 443)) {
				deny();
				return;
			}
			let host;
			if (type === 1) {
				host = [...buffer.subarray(4, end)].join('.');
			} else if (type === 4) {
				host = Array.from({ length: 8 }, (_, i) => buffer.readUInt16BE(4 + i * 2).toString(16)).join(':');
			} else {
				host = buffer.toString('latin1', 5, end).replace(/^\[([^\]]+)\]$/, '$1');
			}
			void establish(host, port);
		}

		client.on('data', readHandshake);
	});
	server.maxConnections = 128;
	return server;
}

module.exports = { createPublicProxy, isPublicAddress };
capture.cjs
'use strict';

const { once } = require('node:events');
const { createPublicProxy } = require('./public-proxy.cjs');

async function capture(chromium, chrome, job, proxy) {
	proxy.listen(0, '127.0.0.1');
	await once(proxy, 'listening');
	let browser;
	try {
		browser = await chromium.launch({
			executablePath: chrome,
			chromiumSandbox: true,
			timeout: 10000,
			proxy: { server: `socks5://127.0.0.1:${proxy.address().port}`, bypass: '<-loopback>' },
			args: [
				'--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1',
				'--disable-quic',
				'--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
			],
		});
		const context = await browser.newContext({
			viewport: job.viewport,
			deviceScaleFactor: 1,
			serviceWorkers: 'block',
			acceptDownloads: false,
		});
		const page = await context.newPage();
		const response = await page.goto(job.url, { waitUntil: 'load', timeout: 18000 });
		if (!response || !response.ok()) {
			throw new Error('Navigation failed');
		}

		// Bound the screenshot before allocating pixels, even for very tall pages.
		const session = await context.newCDPSession(page);
		const { cssContentSize } = await session.send('Page.getLayoutMetrics');
		const height = Math.max(job.viewport.height, Math.min(job.max_height, Math.ceil(cssContentSize.height)));
		const { data } = await session.send('Page.captureScreenshot', {
			format: 'png',
			captureBeyondViewport: height > job.viewport.height,
			clip: { x: 0, y: 0, width: job.viewport.width, height, scale: 1 },
		});
		return { image_base64: data, final_url: page.url() };
	} finally {
		try {
			await browser?.close();
		} finally {
			proxy.close();
		}
	}
}

if (require.main === module) {
	const [playwright, chrome, input] = process.argv.slice(2);
	// Playwright's exit hook kills its Chromium process group. PHP holds stdin
	// open, so a terminated PHP worker also triggers cleanup via EOF.
	const stop = () => process.exit(1);
	setTimeout(stop, 28000);
	process.stdin.on('end', stop);
	process.stdin.resume();
	capture(require(playwright).chromium, chrome, JSON.parse(input), createPublicProxy())
		.then((result) => {
			process.stdout.write(JSON.stringify(result), () => process.exit(0));
		})
		.catch(stop);
}

module.exports = { capture };
browser tests
/* Run with Node 20+: node --test tests/web-screenshot-browser.test.cjs
 * Set DATAMACHINE_TEST_CHROME and DATAMACHINE_TEST_PLAYWRIGHT to also run Chromium.
 */
'use strict';

const assert = require('node:assert/strict');
const { once } = require('node:events');
const http = require('node:http');
const net = require('node:net');
const { test } = require('node:test');
const { capture } = require('../inc/Core/WebScreenshot/capture.cjs');
const { createPublicProxy, isPublicAddress } = require('../inc/Core/WebScreenshot/public-proxy.cjs');

async function listen(server) {
	server.listen(0, '127.0.0.1');
	await once(server, 'listening');
	return server.address().port;
}

test('rejects special-use addresses and accepts public IPv4/IPv6', () => {
	for (const ip of ['127.0.0.1', '169.254.169.254', '100.64.0.1', '192.0.2.1', '240.0.0.1', '::1', '::ffff:8.8.8.8', 'fc00::1', '64:ff9b::a00:1', '2001:db8::1', '2002:a00:1::1', 'fe80::1%lo']) {
		assert.equal(isPublicAddress(ip), false, ip);
	}
	assert.equal(isPublicAddress('8.8.8.8'), true);
	assert.equal(isPublicAddress('2606:4700::1111'), true);
});

test('SOCKS checks DNS again for each connection and pins the numeric address', { timeout: 5000 }, async (t) => {
	const fixture = net.createServer();
	const port = await listen(fixture);
	t.after(() => fixture.close());
	let queries = 0;
	const dials = [];
	const proxy = createPublicProxy({
		resolve: async (host) => {
			assert.equal(host, 'public.example.');
			return ++queries === 1 ? [{ address: '8.8.8.8' }] : [{ address: '8.8.8.8' }, { address: '10.0.0.1' }];
		},
		connect: (options) => {
			dials.push(options);
			return net.connect(port, '127.0.0.1');
		},
	});
	const proxyPort = await listen(proxy);
	t.after(() => proxy.close());
	async function request(host) {
		const socket = net.connect(proxyPort, '127.0.0.1');
		try {
			await once(socket, 'connect');
			socket.write(Buffer.from([5, 1, 0]));
			assert.deepEqual((await once(socket, 'data'))[0], Buffer.from([5, 0]));
			socket.write(Buffer.concat([Buffer.from([5, 1, 0, 3, host.length]), Buffer.from(host), Buffer.from([0, 80])]));
			return (await once(socket, 'data'))[0][1];
		} finally {
			socket.destroy();
		}
	}
	assert.equal(await request('public.example'), 0);
	assert.equal(await request('public.example'), 2);
	assert.equal(await request('127.0.0.1'), 2);
	assert.deepEqual(dials, [{ host: '8.8.8.8', port: 80, family: 4 }]);
});

const chrome = process.env.DATAMACHINE_TEST_CHROME;
const playwright = process.env.DATAMACHINE_TEST_PLAYWRIGHT;
test('Chromium cannot follow a private redirect or load a private iframe', { skip: !chrome || !playwright, timeout: 40000 }, async (t) => {
	let privateHits = 0;
	const privateSite = http.createServer((req, res) => {
		++privateHits;
		res.end('private fixture');
	});
	const privatePort = await listen(privateSite);
	t.after(() => privateSite.close());
	const loopbackUrl = `http://127.0.0.1:${privatePort}/`;
	const privateUrl = 'http://private.example/';
	const privateLookups = [];
	const publicSite = http.createServer((req, res) => {
		if (req.url === '/redirect') {
			res.writeHead(302, { Location: privateUrl });
			res.end();
			return;
		}
		res.setHeader('Content-Type', 'text/html');
		res.end(`<body style="height:20000px"><iframe src="${privateUrl}"></iframe><iframe src="${loopbackUrl}"></iframe></body>`);
	});
	const publicPort = await listen(publicSite);
	t.after(() => publicSite.close());
	const proxy = () => createPublicProxy({
		resolve: async (host) => {
			if (host === 'private.example.') {
				privateLookups.push(host);
				return [{ address: '127.0.0.1' }];
			}
			return host === 'public.example.' ? [{ address: '8.8.8.8' }] : [];
		},
		connect: ({ host, port }) => {
			assert.deepEqual([host, port], ['8.8.8.8', 80]);
			return net.connect(publicPort, '127.0.0.1');
		},
	});
	const chromium = require(playwright).chromium;
	const job = { viewport: { width: 320, height: 240 }, max_height: 1000 };
	await assert.rejects(capture(chromium, chrome, { ...job, url: 'http://public.example/redirect' }, proxy()), /ERR_SOCKS_CONNECTION_FAILED/);
	assert.ok(privateLookups.length > 0, 'redirect reached the proxy DNS policy');
	privateLookups.length = 0;
	const result = await capture(chromium, chrome, { ...job, url: 'http://public.example/iframe' }, proxy());
	assert.ok(privateLookups.length > 0, 'iframe reached the proxy DNS policy');
	assert.equal(result.final_url, 'http://public.example/iframe');
	const png = Buffer.from(result.image_base64, 'base64');
	assert.equal(png.readUInt32BE(16), 320);
	assert.equal(png.readUInt32BE(20), 1000);
	assert.equal(privateHits, 0);
});
Lenguaje dominante
TypeScript
Estrellas
19
Forks
4
Merge medio
35 min
PR fusionados (30 d)
11

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de Automattic/wp-codebox

Todos los issues de Automattic/wp-codebox

Issues similares

Más issues de TypeScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.