Skip to content

Commit

Permalink
fix: validate input hostname and warn
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Sep 6, 2023
1 parent aee15da commit bfc8149
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
17 changes: 17 additions & 0 deletions src/_utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { networkInterfaces } from "node:os";
import { relative } from "pathe";
import { colors } from "consola/utils";
import { consola } from "consola";
import { ListenOptions } from "./types";
import { isWsl } from "./lib/wsl";

Expand Down Expand Up @@ -129,3 +130,19 @@ function detectStackblitzURL(entry?: string) {
console.error(error);
}
}

const HOSTNAME_RE = /^(?!-)[\d.A-Za-z-]{1,63}(?<!-)$/;

export function validateHostname(
hostname: string | undefined,
_public: boolean,
) {
if (hostname && !HOSTNAME_RE.test(hostname)) {
const fallbackHost = _public ? "0.0.0.0" : "127.0.0.1";
consola.warn(
`[listhen] Invalid hostname: \`${hostname}\`. Using \`${fallbackHost}\` as fallback.`,
);
return fallbackHost;
}
return hostname;
}
11 changes: 8 additions & 3 deletions src/listen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
getPublicURL,
generateURL,
getDefaultHost,
validateHostname,
} from "./_utils";
import { resolveCertificate } from "./_cert";

Expand All @@ -38,13 +39,17 @@ export async function listen(
// --- Resolve Options ---
const _isProd = _options.isProd ?? process.env.NODE_ENV === "production";
const _isTest = _options.isTest ?? process.env.NODE_ENV === "test";
const _hostname = process.env.HOST ?? _options.hostname;
const __public =
(process.argv.includes("--host") ? true : undefined) ?? _isProd;
const _hostname = validateHostname(
process.env.HOST ?? _options.hostname,
__public,
);
const _public =
_options.public ??
(isLocalhost(_hostname) ? false : undefined) ??
(isAnyhost(_hostname) ? true : undefined) ??
(process.argv.includes("--host") ? true : undefined) ??
_isProd;
__public;

const listhenOptions = defu<ListenOptions, ListenOptions[]>(_options, {
name: "",
Expand Down

0 comments on commit bfc8149

Please sign in to comment.