Files
cypress/packages/server/lib/util/socket_allowed.ts
Lachlan Miller ab401ecd35 chore: use import type syntax (#17864)
* chore: use import type across repo

* chore: use import type across repo

* chore: use import type across repo

* chore: use import type across repo

* update exports

* update test

* update import type

* update types

* use import type in driver

* correctly export function

* revert test

* remove unrelated code

* revert code

* improve type imports

* override for reporter
2021-08-25 09:11:56 +10:00

47 lines
1.2 KiB
TypeScript

import _ from 'lodash'
import Debug from 'debug'
import type net from 'net'
import type { Request } from 'express'
const debug = Debug('cypress:server:util:socket_allowed')
/**
* Utility to validate incoming, local socket connections against a list of
* expected client TCP ports.
*/
export class SocketAllowed {
allowedLocalPorts: number[] = []
/**
* Add a socket to the allowed list.
*/
add = (socket: net.Socket) => {
const { localPort } = socket
debug('allowing socket %o', { localPort })
this.allowedLocalPorts.push(localPort)
socket.once('close', () => {
debug('allowed socket closed, removing %o', { localPort })
this._remove(socket)
})
}
_remove (socket: net.Socket) {
_.pull(this.allowedLocalPorts, socket.localPort)
}
/**
* Is this socket that this request originated allowed?
*/
isRequestAllowed (req: Request) {
const { remotePort, remoteAddress } = req.socket
const isAllowed = this.allowedLocalPorts.includes(remotePort!)
&& ['127.0.0.1', '::1'].includes(remoteAddress!)
debug('is incoming request allowed? %o', { isAllowed, reqUrl: req.url, remotePort, remoteAddress })
return isAllowed
}
}