Skip to content

Commit 9dcd3a5

Browse files
committed
fix(rpc): gracefully reject invalid ws upgrades to prevent ECONNRESET
1 parent 7032307 commit 9dcd3a5

2 files changed

Lines changed: 10 additions & 1 deletion

File tree

packages/devframe/src/rpc/transports/ws-server.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,19 +157,27 @@ function routeUpgrades(
157157
allowedOrigins: readonly string[] | false | undefined,
158158
): () => void {
159159
const listener = (req: IncomingMessage, socket: Duplex, head: Buffer) => {
160+
socket.on('error', () => {
161+
// Prevent unhandled ECONNRESET crashes when destroying the socket
162+
// or when the client abruptly disconnects.
163+
})
164+
160165
if (path) {
161166
let pathname = req.url ?? '/'
162167
try {
163168
pathname = new URL(req.url ?? '/', 'http://localhost').pathname
164169
}
165170
catch {}
166171
if (!pathMatches(pathname, path)) {
167-
if (destroyUnmatched)
172+
if (destroyUnmatched) {
173+
socket.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n')
168174
socket.destroy()
175+
}
169176
return
170177
}
171178
}
172179
if (allowedOrigins !== false && !isAllowedOrigin(req.headers.origin, allowedOrigins ?? [])) {
180+
socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n')
173181
socket.destroy()
174182
return
175183
}

packages/devframe/src/rpc/transports/ws.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ describe('ws origin check', () => {
187187
})
188188
ws.on('error', () => resolve('closed'))
189189
ws.on('unexpected-response', () => resolve('closed'))
190+
ws.on('close', () => resolve('closed'))
190191
})
191192
}
192193

0 commit comments

Comments
 (0)