Validate Origin header for WebSocket requests

This commit is contained in:
Max Goodhart
2020-07-02 13:54:50 -07:00
parent c9c84d7530
commit aaac169a58

View File

@@ -15,6 +15,7 @@ import websocket from 'koa-easy-ws'
const webDistPath = path.join(app.getAppPath(), 'web') const webDistPath = path.join(app.getAppPath(), 'web')
function initApp({ username, password, baseURL, getInitialState, onMessage }) { function initApp({ username, password, baseURL, getInitialState, onMessage }) {
const expectedOrigin = new URL(baseURL).origin
const sockets = new Set() const sockets = new Set()
const app = new Koa() const app = new Koa()
@@ -38,6 +39,11 @@ function initApp({ username, password, baseURL, getInitialState, onMessage }) {
app.use( app.use(
route.get('/ws', async (ctx) => { route.get('/ws', async (ctx) => {
if (ctx.ws) { if (ctx.ws) {
if (ctx.headers.origin !== expectedOrigin) {
ctx.status = 403
return
}
const ws = await ctx.ws() const ws = await ctx.ws()
sockets.add(ws) sockets.add(ws)