Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@ interface DevToolsJSON {

const ENDPOINT = '/.well-known/appspecific/com.chrome.devtools.json';

const IPV4_LOOPBACK_RE = /^127(?:\.\d{1,3}){3}$/;

function isLocalhost(hostHeader: string | undefined): boolean {
if (!hostHeader) {
return false;
}
try {
const url = new URL(`http://${hostHeader}`);
if (url.host !== hostHeader.toLowerCase()) {
return false;
}
const {hostname} = url;
return (
hostname === 'localhost' ||
hostname.endsWith('.localhost') ||
hostname === '[::1]' ||
IPV4_LOOPBACK_RE.test(hostname)
);
} catch {
return false;
}
}

const plugin = (options: DevToolsJsonOptions = {}): Plugin => ({
name: 'devtools-json',
enforce: 'post',
Expand Down Expand Up @@ -96,7 +119,12 @@ const plugin = (options: DevToolsJsonOptions = {}): Plugin => ({
);
}

server.middlewares.use(ENDPOINT, async (_req, res) => {
server.middlewares.use(ENDPOINT, async (req, res) => {
if (!isLocalhost(req.headers.host)) {
res.writeHead(403);
res.end();
return;
}
// Determine the project root that will be reported to DevTools.
const resolveProjectRoot = (): string => {
if (options.projectRoot) {
Expand Down
25 changes: 25 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,5 +138,30 @@ describe('#VitePluginDevToolsJson', () => {
await server.close();
delete process.env.DOCKER_DESKTOP;
});

it('should reject non-localhost Host headers (DNS rebinding protection)', async () => {
const server = await createServer({
plugins: [VitePluginDevToolsJson()],
server: {
port,
host: true,
},
});

await server.listen();

const blockedResponse = await request(server.httpServer!)
.get('/.well-known/appspecific/com.chrome.devtools.json')
.set('Host', `attacker.example:${port}`);
expect(blockedResponse.status).to.equal(403);
expect(blockedResponse.text).to.equal('');

const allowedResponse = await request(server.httpServer!)
.get('/.well-known/appspecific/com.chrome.devtools.json')
.set('Host', `localhost:${port}`);
expect(allowedResponse.status).to.equal(200);

await server.close();
});
});
});
Loading