export const DADA_LOOPBACK_HOST = "127.0.0.1";
export const DADA_LOOPBACK_PORT = 43121;

export interface NetworkBoundaryOptions {
  allowTestPort?: boolean;
}

interface NetworkRequest {
  host: string | undefined;
  method: string;
  origin: string | undefined;
}

export function isAllowedNetworkRequest(
  request: NetworkRequest,
  options: NetworkBoundaryOptions = {},
) {
  if (request.method === "OPTIONS" || !request.host) return false;
  const allowedHost = options.allowTestPort
    ? /^127\.0\.0\.1:[1-9][0-9]{0,4}$/.test(request.host)
    : request.host === `${DADA_LOOPBACK_HOST}:${DADA_LOOPBACK_PORT}`;
  if (!allowedHost) return false;

  if (request.origin !== undefined && request.origin !== `http://${request.host}`) return false;
  if (!["GET", "HEAD"].includes(request.method) && request.origin === undefined) return false;
  return true;
}
