Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
12 changes: 8 additions & 4 deletions ext/http/http_next.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1440,16 +1440,20 @@ impl UpgradeStream {
Ok(buf.len())
}
Ok(httparse::Status::Complete(n)) => {
if response.code != Some(StatusCode::SWITCHING_PROTOCOLS.as_u16())
let status_code = response.code.unwrap_or(0);
// Accept 101 (WebSocket upgrade) and 200 (CONNECT tunnel)
if status_code != StatusCode::SWITCHING_PROTOCOLS.as_u16()
&& status_code != StatusCode::OK.as_u16()
{
return Err(std::io::Error::other(
HttpNextError::InvalidHttpStatusLine,
));
}

http
.otel_info_set_status(StatusCode::SWITCHING_PROTOCOLS.as_u16());
http.response_parts().status = StatusCode::SWITCHING_PROTOCOLS;
let status = StatusCode::from_u16(status_code)
.unwrap_or(StatusCode::SWITCHING_PROTOCOLS);
http.otel_info_set_status(status.as_u16());
http.response_parts().status = status;

for header in response.headers {
http.response_parts().headers.append(
Expand Down
22 changes: 21 additions & 1 deletion ext/node/polyfills/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2274,9 +2274,29 @@ export class ServerImpl extends EventEmitter {
});

const req = new IncomingMessageForServer(socket);
req.method = request.method;

if (request.method === "CONNECT") {
// For CONNECT, the URL should be in authority form (host:port).
// Deno's server adds an "http://" prefix, so strip it.
req.url = request.url.replace(/^https?:\/\//, "");
req[kRawHeaders] = request.headers;

if (this.listenerCount("connect") > 0) {
const { conn, response } = upgradeHttpRaw(request);
const socket = new Socket({
handle: new TCP(constants.SERVER, conn),
});
req.socket = socket;
this.emit("connect", req, socket, Buffer.from([]));
return response;
} else {
return new Response(null, { status: 405 });
}
}

// Slice off the origin so that we only have pathname + search
req.url = request.url?.slice(request.url.indexOf("/", 8));
req.method = request.method;
req.upgrade =
request.headers.get("connection")?.toLowerCase().includes("upgrade") &&
request.headers.get("upgrade");
Expand Down
13 changes: 9 additions & 4 deletions ext/node/polyfills/internal/util/debuglog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@
// TODO(petamoriken): enable prefer-primordials for node polyfills
// deno-lint-ignore-file prefer-primordials

// `debugImpls` and `testEnabled` are deliberately not initialized so any call
// to `debuglog()` before `initializeDebugEnv()` is called will throw.
let debugImpls: Record<string, (...args: unknown[]) => void>;
let testEnabled: (str: string) => boolean;
// `debugImpls` and `testEnabled` are initialized with safe defaults so that
// calls to `debuglog()` before `initializeDebugEnv()` do not crash. This can
// happen when internal stream code triggers debug logging during bootstrap
// before the Node process is fully initialized (e.g. when stdin is unavailable
// in compiled binaries run as Windows services or detached processes).
let debugImpls: Record<string, (...args: unknown[]) => void> = Object.create(
null,
);
let testEnabled: (str: string) => boolean = () => false;

// `debugEnv` is initial value of process.env.NODE_DEBUG
export function initializeDebugEnv(debugEnv: string) {
Expand Down
4 changes: 4 additions & 0 deletions tests/specs/node/http_server_connect_event/__test__.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"args": "run -A main.ts",
"output": "main.out"
}
3 changes: 3 additions & 0 deletions tests/specs/node/http_server_connect_event/main.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
CONNECT event received: CONNECT 127.0.0.1:[WILDCARD]
Client received status: HTTP/1.1 200 OK
Tunnel data received successfully
66 changes: 66 additions & 0 deletions tests/specs/node/http_server_connect_event/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import * as http from "node:http";
import * as net from "node:net";

// Test that http.Server emits the "connect" event for CONNECT requests.
// This is essential for HTTP proxy servers (e.g., proxy-chain used by Crawlee).

// Start a simple TCP echo server to act as the "target"
const target = net.createServer((socket) => {
socket.write("hello from target");
socket.end();
});

target.listen(0, () => {
const targetPort = (target.address() as net.AddressInfo).port;

const server = http.createServer((_req, res) => {
res.writeHead(200);
res.end("ok");
});

server.on("connect", (req, clientSocket, _head) => {
console.log(`CONNECT event received: ${req.method} ${req.url}`);

// Connect to the target
const [hostname, port] = req.url!.split(":");
const targetSocket = net.connect(Number(port), hostname, () => {
clientSocket.write(
"HTTP/1.1 200 Connection Established\r\n\r\n",
);
targetSocket.pipe(clientSocket);
clientSocket.pipe(targetSocket);
});

targetSocket.on("error", (err) => {
clientSocket.end(`HTTP/1.1 502 Bad Gateway\r\n\r\n`);
});
});

server.listen(0, () => {
const proxyPort = (server.address() as net.AddressInfo).port;

// Send a CONNECT request to the proxy
const client = net.connect(proxyPort, "127.0.0.1", () => {
client.write(
`CONNECT 127.0.0.1:${targetPort} HTTP/1.1\r\nHost: 127.0.0.1:${targetPort}\r\n\r\n`,
);
});

let data = "";
client.on("data", (chunk) => {
data += chunk.toString();
});

client.on("end", () => {
// Should have received the 200 Connection Established + target data
const lines = data.split("\r\n");
console.log(`Client received status: ${lines[0]}`);
if (data.includes("hello from target")) {
console.log("Tunnel data received successfully");
}
client.end();
server.close();
target.close();
});
});
});