@beignet/core
Version:
Core framework primitives for Beignet
62 lines (54 loc) • 1.59 kB
text/typescript
import type { TrustedProxyConfig } from "./trusted-proxy.js";
export class InvalidRequestUrlError extends Error {
constructor() {
super("req.url must be an absolute HTTP or HTTPS URL.");
this.name = "InvalidRequestUrlError";
}
}
export function parseHttpRequestUrl(value: string): URL {
try {
const url = new URL(value);
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new InvalidRequestUrlError();
}
return url;
} catch (error) {
if (error instanceof InvalidRequestUrlError) throw error;
throw new InvalidRequestUrlError();
}
}
export function requireTrustedProxyHeaderName(
name: string,
optionName: string,
): string {
const header = name.trim();
if (!header) {
throw new Error(`${optionName} must be a non-empty header name.`);
}
try {
new Headers().get(header);
} catch {
throw new Error(`${optionName} must be a valid HTTP header name.`);
}
return header;
}
export function assertValidTrustedProxyConfig(
config: TrustedProxyConfig,
): void {
if (!config) return;
if (config.hostHeader !== undefined && config.hostHeader !== false) {
requireTrustedProxyHeaderName(config.hostHeader, "trustedProxy.hostHeader");
}
if (config.protocolHeader !== undefined && config.protocolHeader !== false) {
requireTrustedProxyHeaderName(
config.protocolHeader,
"trustedProxy.protocolHeader",
);
}
if (typeof config.clientIp === "object") {
requireTrustedProxyHeaderName(
config.clientIp.header,
"trustedProxy.clientIp.header",
);
}
}