Skip to content

Commit

Permalink
fix: better public host inference
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 27, 2023
1 parent e15fc57 commit 43061f2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ export function formatURL(url: string) {
);
}

const localhostRegex = /^127(\.\d{1,3}){3}$|^localhost$|^::1$/;
export function isLocalhost(hostname = "") {
return localhostRegex.test(hostname)
}

export function isAnyhost(hostname = "") {
return hostname === "" || hostname === "0.0.0.0" || hostname === "::";
}

export function getPublicURL(
urls: ListenURL[],
listhenOptions: ListenOptions,
Expand Down
23 changes: 22 additions & 1 deletion src/listen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
formatAddress,
formatURL,
getNetworkInterfaces,
isLocalhost,
isAnyhost,
getPublicURL,
} from "./_utils";
import { resolveCertificate } from "./_cert";
Expand All @@ -36,8 +38,10 @@ export async function listen(
const _hostname = process.env.HOST ?? _options.hostname;
const _public =
_options.public ??
(isLocalhost(_hostname) ? false : undefined) ??
(isAnyhost(_hostname) ? true : undefined) ??
(process.argv.includes("--host") ? true : undefined) ??
(_hostname === "localhost" ? false : _isProd);
_isProd;

const listhenOptions = defu<ListenOptions, ListenOptions[]>(_options, {
name: "",
Expand All @@ -54,6 +58,23 @@ export async function listen(
autoClose: true,
});

if (listhenOptions.public && isLocalhost(listhenOptions.hostname)) {
console.warn(
`[listhen] Trying to listhen on private host ${JSON.stringify(
listhenOptions.hostname,
)} with public option disabled.`,
);
listhenOptions.public = false;
} else if (!listhenOptions.public && isAnyhost(listhenOptions.hostname)) {
console.warn(
`[listhen] Trying to listhen on public host ${JSON.stringify(
listhenOptions.hostname,
)} with public option disabled. Using "localhost".`,
);
listhenOptions.public = false;
listhenOptions.hostname = "localhost";
}

if (listhenOptions.isTest) {
listhenOptions.showURL = false;
}
Expand Down

0 comments on commit 43061f2

Please sign in to comment.