Skip to content

Commit

Permalink
turbopack: bind to IPv6 loopback address
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell committed Apr 6, 2023
1 parent fc1d8c0 commit fd4c496
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 17 deletions.
2 changes: 1 addition & 1 deletion packages/next-swc/crates/next-core/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ async fn route_internal(
JsonValueVc::cell(request),
JsonValueVc::cell(dir.to_string_lossy().into()),
JsonValueVc::cell(json!({
"hostname": server_addr.ip(),
"hostname": server_addr.hostname(),
"port": server_addr.port(),
})),
],
Expand Down
12 changes: 3 additions & 9 deletions packages/next-swc/crates/next-dev-tests/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,6 @@ fn test_skipped_fails(resource: PathBuf) {
async fn run_test(resource: PathBuf) -> JestRunResult {
register();

let is_debug_start = *DEBUG_START;

let resource = canonicalize(resource).unwrap();
assert!(resource.exists(), "{} does not exist", resource.display());
assert!(
Expand All @@ -195,11 +193,7 @@ async fn run_test(resource: PathBuf) -> JestRunResult {
let test_dir = resource.to_path_buf();
let workspace_root = cargo_workspace_root.parent().unwrap().parent().unwrap();
let project_dir = test_dir.join("input");
let requested_addr = if is_debug_start {
"127.0.0.1:3000".parse().unwrap()
} else {
get_free_local_addr().unwrap()
};
let requested_addr = get_free_local_addr().unwrap();

let mock_dir = resource.join("__httpmock__");
let mock_server_future = get_mock_server_future(&mock_dir);
Expand Down Expand Up @@ -475,8 +469,8 @@ async fn run_browser(addr: SocketAddr) -> Result<JestRunResult> {
}

fn get_free_local_addr() -> Result<SocketAddr, std::io::Error> {
let socket = TcpSocket::new_v4()?;
socket.bind("127.0.0.1:0".parse().unwrap())?;
let socket = TcpSocket::new_v6()?;
socket.bind("[::]:0".parse().unwrap())?;
socket.local_addr()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,15 @@ import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export async function middleware(req: NextRequest) {
const origin = new URL(req.url).origin;
const res = await fetch(`${origin}/api/endpoint`);
const json = await res.json();
return NextResponse.json(json);
const url = new URL(req.url)
const { searchParams } = url
const origin = searchParams.get('origin')
? `http://${searchParams.get('origin')}`
: url.origin

const res = await fetch(`${origin}/api/endpoint`)
const json = await res.json()
return NextResponse.json({ ...json, origin })
}

export const config = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,35 @@ export default function Foo() {
}

function runTests() {
it('should include custom env fields in middleware process', async () => {
it('router has correct host when not specified', async () => {
// Without a host query param, the router will use the request's origin
// to fetch from the API endpoint.
const res = await fetch('/fetch-endpoint')
const env = await res.json()
expect(env).toHaveProperty('name', 'John Doe')
})

it('router can fetch localhost', async () => {
const res = await fetch(`/fetch-endpoint?host=localhost:${location.port}`)
const env = await res.json()
expect(env).toHaveProperty('name', 'John Doe')
})

it('router can fetch 127.0.0.1', async () => {
const res = await fetch(`/fetch-endpoint?host=127.0.0.1:${location.port}`)
const env = await res.json()
expect(env).toHaveProperty('name', 'John Doe')
})

it('router can fetch 0.0.0.0', async () => {
const res = await fetch(`/fetch-endpoint?host=0.0.0.0:${location.port}`)
const env = await res.json()
expect(env).toHaveProperty('name', 'John Doe')
})

it('router can fetch IPv6', async () => {
const res = await fetch(`/fetch-endpoint?host=[::1]:${location.port}`)
const env = await res.json()
expect(env).toHaveProperty('name', 'John Doe')
})
}
6 changes: 4 additions & 2 deletions packages/next-swc/crates/next-dev/src/devserver_options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub struct DevServerOptions {
/// Hostname on which to start the application
#[cfg_attr(
feature = "cli",
clap(short = 'H', long, value_parser, default_value = "0.0.0.0")
clap(short = 'H', long, value_parser, default_value = "::")
)]
#[cfg_attr(feature = "serializable", serde(default = "default_host"))]
pub hostname: IpAddr,
Expand Down Expand Up @@ -114,5 +114,7 @@ fn default_port() -> u16 {

#[cfg(feature = "serializable")]
fn default_host() -> IpAddr {
IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0))
// IPv6 address can accept both IPv4 and v6 requests.
// https://nodejs.org/api/net.html#serverlistenport-host-backlog-callback
IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED)
}

0 comments on commit fd4c496

Please sign in to comment.