Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support "CONNECT", socket-based interception #483

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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 package.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@
"follow-redirects": "^1.15.1",
"got": "^11.8.3",
"happy-dom": "^12.10.3",
"hpagent": "^1.2.0",
"jest": "^27.4.3",
"node-fetch": "2.6.7",
"rimraf": "^3.0.2",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 64 additions & 0 deletions proxy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const http = require('node:http')
const net = require('node:net')
const { URL } = require('node:url')

// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('okay')
})
proxy.on('connect', (req, clientSocket, head) => {
console.log('\n\nproxy.on(connect)', req.method, req.url, {
clientSocket,
head: head.toString('utf8'),
})

// Connect to an origin server
const { port, hostname } = new URL(`http://${req.url}`)
const serverSocket = net.connect(port || 80, hostname, () => {
clientSocket.write(
'HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n'
)
serverSocket.write(head)
serverSocket.pipe(clientSocket)
clientSocket.pipe(serverSocket)
})
})

// Now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {
// Make a request to a tunneling proxy
const options = {
port: 1337,
host: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80',
}

const req = http.request(options)
console.log('req.end()')
req.end()

req.on('connect', (res, socket, head) => {
console.log('============='.repeat(10))
console.log('\n\n req.on(connect)')
console.group({ res, socket, head: head.toString('utf8') })
console.log(res.statusCode, res.statusMessage)

// Make a request over an HTTP tunnel
socket.write(
'GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n'
)
socket.on('data', (chunk) => {
console.log('incoming chunk...')
})
socket.on('end', () => {
proxy.close()
})
})
})
20 changes: 20 additions & 0 deletions src/interceptors/ClientRequest/NodeClientRequest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ClientRequest, IncomingMessage } from 'http'
import { Duplex } from 'stream'
import type { Logger } from '@open-draft/logger'
import { until } from '@open-draft/until'
import { DeferredPromise } from '@open-draft/deferred-promise'
Expand Down Expand Up @@ -577,6 +578,25 @@ export class NodeClientRequest extends ClientRequest {
this.terminate()

this.logger.info('request complete!')

if (this.method === 'CONNECT') {
console.warn('SHOULD EMIT CONNECT', typeof this.response)

const head = Buffer.from('')

const socket = new Duplex({
read() {},
write(chunk, encoding, callback) {
console.log(
'CONNECT event Duplex write:\n',
`== START ==\n${chunk.toString('utf8')}== END ==`
)
callback()
},
})

this.emit('connect', this.response, socket, head)
}
})
}

Expand Down
24 changes: 17 additions & 7 deletions src/interceptors/ClientRequest/utils/createRequest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { NodeClientRequest } from '../NodeClientRequest'
import { FORBIDDEN_REQUEST_METHODS } from '../../../utils/fetchUtils'

/**
* Creates a Fetch API `Request` instance from the given `http.ClientRequest`.
Expand Down Expand Up @@ -26,7 +27,9 @@ export function createRequest(clientRequest: NodeClientRequest): Request {
* @see https://github.com/mswjs/interceptors/issues/438
*/
if (clientRequest.url.username || clientRequest.url.password) {
const auth = `${clientRequest.url.username || ''}:${clientRequest.url.password || ''}`
const auth = `${clientRequest.url.username || ''}:${
clientRequest.url.password || ''
}`
headers.set('Authorization', `Basic ${btoa(auth)}`)

// Remove the credentials from the URL since you cannot
Expand All @@ -37,13 +40,20 @@ export function createRequest(clientRequest: NodeClientRequest): Request {

const method = clientRequest.method || 'GET'

return new Request(clientRequest.url, {
method,
const fetchRequest = new Request(clientRequest.url, {
method: FORBIDDEN_REQUEST_METHODS.includes(method)
? `UNSAFE-${method}`
: method,
headers,
credentials: 'same-origin',
body:
method === 'HEAD' || method === 'GET'
? null
: clientRequest.requestBuffer,
body: ['HEAD', 'GET'].includes(method) ? null : clientRequest.requestBuffer,
})

if (fetchRequest.method.startsWith('UNSAFE-')) {
Object.defineProperty(fetchRequest, 'method', {
value: fetchRequest.method.replace('UNSAFE-', ''),
})
}

return fetchRequest
}
4 changes: 2 additions & 2 deletions src/interceptors/ClientRequest/utils/createResponse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { it, expect } from 'vitest'
import { Socket } from 'net'
import * as http from 'http'
import { createResponse } from './createResponse'
import { responseStatusCodesWithoutBody } from '../../../utils/responseUtils'
import { RESPONSE_STATUS_CODES_WITHOUT_BODY } from '../../../utils/fetchUtils'

it('creates a fetch api response from http incoming message', async () => {
const message = new http.IncomingMessage(new Socket())
Expand All @@ -22,7 +22,7 @@ it('creates a fetch api response from http incoming message', async () => {
expect(await response.json()).toEqual({ firstName: 'John' })
})

it.each(responseStatusCodesWithoutBody)(
it.each(RESPONSE_STATUS_CODES_WITHOUT_BODY)(
'ignores message body for %i response status',
(responseStatus) => {
const message = new http.IncomingMessage(new Socket())
Expand Down
4 changes: 2 additions & 2 deletions src/interceptors/ClientRequest/utils/createResponse.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { IncomingHttpHeaders, IncomingMessage } from 'http'
import { responseStatusCodesWithoutBody } from '../../../utils/responseUtils'
import { RESPONSE_STATUS_CODES_WITHOUT_BODY } from '../../../utils/fetchUtils'

/**
* Creates a Fetch API `Response` instance from the given
* `http.IncomingMessage` instance.
*/
export function createResponse(message: IncomingMessage): Response {
const responseBodyOrNull = responseStatusCodesWithoutBody.includes(
const responseBodyOrNull = RESPONSE_STATUS_CODES_WITHOUT_BODY.includes(
message.statusCode || 200
)
? null
Expand Down
Loading
Loading