Skip to content
Open
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
1 change: 1 addition & 0 deletions client-src/overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,7 @@ const createOverlay = (options: CreateOverlayOptions): StateMachine => {
typeElement.addEventListener('click', () => {
fetch(
`/rspack-dev-server/open-editor?fileName=${message.moduleIdentifier}`,
{ headers: { 'X-Rspack-Dev-Server': '1' } },
);
});
}
Expand Down
2 changes: 2 additions & 0 deletions docs/migrate-v1-to-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,3 +272,5 @@ http://localhost:8080/?rspack-dev-server-hot=false&rspack-dev-server-live-reload
GET /rspack-dev-server/invalidate
GET /rspack-dev-server/open-editor?fileName=...
```

When calling these two routes from a script, send the `X-Rspack-Dev-Server: 1` request header. The built-in error overlay sends it automatically.
29 changes: 29 additions & 0 deletions src/isTrustedActionRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { IncomingHttpHeaders } from 'node:http';

export function isTrustedActionRequest(
headers: IncomingHttpHeaders,
isTlsServer: boolean,
): boolean {
const site = headers['sec-fetch-site'];
if (site !== undefined) {
// "none" is a user-initiated navigation, e.g. from the address bar.
return site === 'same-origin' || site === 'none';
}

if (headers.origin !== undefined) {
const authority = headers[':authority'] ?? headers.host;
if (typeof authority !== 'string') {
return false;
}
try {
const protocol = isTlsServer ? 'https' : 'http';
return headers.origin === new URL(`${protocol}://${authority}`).origin;
} catch {
return false;
}
}

// Without browser-provided origin information, require an explicit request.
// A cross-origin page cannot set this header in a simple request.
return headers['x-rspack-dev-server'] === '1';
}
13 changes: 13 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import ipaddr from 'ipaddr.js';
import type { App } from 'open';
import type { IPv6 } from 'ipaddr.js';
import { getPort } from './getPort.js';
import { isTrustedActionRequest } from './isTrustedActionRequest.js';
import { WebsocketServer } from './servers/WebsocketServer.js';
import type {
AddressInfo,
Expand Down Expand Up @@ -1594,6 +1595,12 @@ class Server<
return;
}

if (!isTrustedActionRequest(req.headers, this.isTlsServer)) {
res.statusCode = 403;
res.end('Cross-Origin request blocked');
return;
}

this.invalidate();

res.end();
Expand All @@ -1614,6 +1621,12 @@ class Server<
return;
}

if (!isTrustedActionRequest(req.headers, this.isTlsServer)) {
res.statusCode = 403;
res.end('Cross-Origin request blocked');
return;
}

const resolveUrl = new URL(req.url, `http://${req.headers.host}`);
const params = new URLSearchParams(resolveUrl.search);
const fileName = params.get('fileName');
Expand Down
20 changes: 20 additions & 0 deletions tests/e2e/built-in-routes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,26 @@ describe('Built in routes', () => {
expect(pageErrors).toMatchSnapshot('page errors');
});

it('requires scripts to opt in to built-in actions', async () => {
const invalidate = rs
.spyOn(server, 'invalidate')
.mockImplementation(() => {});
const base = `http://127.0.0.1:${port}/rspack-dev-server`;
for (const route of ['invalidate', 'open-editor']) {
for (const method of ['GET', 'HEAD']) {
const response = await fetch(`${base}/${route}`, { method });
expect(response.status).toBe(403);
}
}
expect(invalidate).not.toHaveBeenCalled();

const response = await fetch(`${base}/invalidate`, {
headers: { 'X-Rspack-Dev-Server': '1' },
});
expect(response.status).toBe(200);
expect(invalidate).toHaveBeenCalledTimes(1);
});

it('should handle GET request to directory index and list all middleware directories', async () => {
page
.on('console', (message) => {
Expand Down
3 changes: 3 additions & 0 deletions tests/e2e/overlay.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,9 @@ describe('overlay', () => {

const openEditorResponse = await openEditorResponsePromise;

expect(
openEditorResponse.request().headers()['x-rspack-dev-server'],
).toBe('1');
expect(openEditorResponse.status()).toBe(200);
} finally {
fs.writeFileSync(pathToFile, originalCode);
Expand Down
60 changes: 60 additions & 0 deletions tests/isTrustedActionRequest.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { isTrustedActionRequest } from '../src/isTrustedActionRequest.js';

describe('isTrustedActionRequest', () => {
it.each([
['same-origin', true],
['none', true],
['same-site', false],
['cross-site', false],
['unknown', false],
])('checks the browser-provided site %s first', (site, expected) => {
expect(
isTrustedActionRequest(
{ 'sec-fetch-site': site, 'x-rspack-dev-server': '1' },
false,
),
).toBe(expected);
});

it.each([
['http://localhost:8080', true],
['https://localhost:8080', false],
['http://localhost:8081', false],
['http://example.com:8080', false],
['null', false],
])(
'checks the complete origin %s without Fetch Metadata',
(origin, expected) => {
expect(
isTrustedActionRequest(
{ host: 'localhost:8080', origin, 'x-rspack-dev-server': '1' },
false,
),
).toBe(expected);
},
);

it('uses the HTTP/2 authority and normalizes the default port', () => {
expect(
isTrustedActionRequest(
{ ':authority': '[::1]:443', origin: 'https://[::1]' },
true,
),
).toBe(true);
});

it('rejects an origin without a valid request authority', () => {
for (const host of [undefined, 'localhost:invalid']) {
expect(
isTrustedActionRequest({ host, origin: 'http://localhost' }, false),
).toBe(false);
}
});

it('requires an explicit header when the source is unknown', () => {
expect(isTrustedActionRequest({}, false)).toBe(false);
expect(isTrustedActionRequest({ 'x-rspack-dev-server': '1' }, false)).toBe(
true,
);
});
});