Skip to content

Commit 3ca9aec

Browse files
authored
Merge pull request #144 from mcode/xss-middleware
impliment middleware to prevent xss attacks
2 parents cb889de + 286a704 commit 3ca9aec

3 files changed

Lines changed: 43 additions & 4 deletions

File tree

frontend/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<meta charset="UTF-8" />
55
<link rel="icon" type="image/png" href="/intermediary.png" />
66
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
7-
<title>Rems Intermediary UI</title>
7+
<title>PIMS Pharmacy</title>
88
</head>
99
<body>
1010
<div id="root"></div>

frontend/vite-xss-middleware.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// vite-xss-fix.ts
2+
import { Plugin } from 'vite';
3+
4+
export function viteXssMiddleware(): Plugin {
5+
const middleware = (req: any, res: any, next: any) => {
6+
const originalEnd = res.end;
7+
const chunks: any[] = [];
8+
9+
res.end = function (chunk?: any) {
10+
if (chunk) chunks.push(Buffer.from(chunk));
11+
12+
const body = Buffer.concat(chunks).toString();
13+
14+
// If Vite's error message is reflecting user input, replace it
15+
if (body.includes('did you mean to visit') && body.includes('<a href=')) {
16+
const safe = `<!DOCTYPE html>
17+
<html>
18+
<head><title>404 Not Found</title></head>
19+
<body><h1>404 - Page Not Found</h1></body>
20+
</html>`;
21+
res.setHeader('Content-Type', 'text/html');
22+
return originalEnd.call(res, safe);
23+
}
24+
25+
return originalEnd.call(res, Buffer.concat(chunks));
26+
};
27+
28+
next();
29+
};
30+
31+
return {
32+
name: 'vite-xss-fix',
33+
configureServer(server) {
34+
server.middlewares.use(middleware);
35+
},
36+
configurePreviewServer(server) {
37+
server.middlewares.use(middleware);
38+
}
39+
};
40+
}

frontend/vite.config.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
import { defineConfig } from 'vite';
22
import react from '@vitejs/plugin-react';
3-
3+
import { viteXssMiddleware } from './vite-xss-middleware';
44
import dotenv from 'dotenv';
55

66
dotenv.config({ path: '.env' }); // load env vars from .env
77
export default defineConfig({
8-
// depending on your application, base can also be "/"
98
base: process.env.REACT_APP_VITE_BASE || '',
10-
plugins: [react()],
9+
plugins: [react(), viteXssMiddleware()],
1110
preview: {
1211
allowedHosts: ['.mitre.org', '.elb.us-east-1.amazonaws.com'],
1312
port: parseInt(process.env.PORT!),

0 commit comments

Comments
 (0)