Skip to content

Commit

Permalink
fix: better options handling for public host (#112)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Aug 27, 2023
1 parent e15fc57 commit bff03a1
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
9 changes: 7 additions & 2 deletions pnpm-lock.yaml

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

10 changes: 10 additions & 0 deletions src/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ export function formatURL(url: string) {
);
}

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

const anyhostRegex = /^$|^0\.0\.0\.0$|^::$/;
export function isAnyhost(hostname: string | undefined) {
return hostname === undefined ? false : anyhostRegex.test(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 bff03a1

Please sign in to comment.