125 lines · 4.9 KB
import { env } from "cloudflare:workers";
import { MIN_SECRETS_KEY_LENGTH } from "./crypto";
import { bindingNameForShard, configuredShardCount } from "./git/artifacts-shards";
import { userContentOriginProblem } from "./usercontent-policy";

const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);

export type DeploymentVars = {
  GITFOR_LOCAL?: string;
  PUBLIC_URL?: string;
  USERCONTENT_ORIGIN?: string;
  SECRETS_KEY?: string;
  ARTIFACTS_SHARDS?: string;
  SITES_DOMAIN?: string;
  EDITOR_ORIGIN?: string;
};

export function isLoopbackHost(host: string): boolean {
  const lower = host.toLowerCase();
  return LOOPBACK_HOSTS.has(lower) || lower.endsWith(".localhost");
}

/** True when PUBLIC_URL points at this machine; an unparsable value counts as local (never as a deployment). */
export function isLoopbackUrl(raw: string | undefined): boolean {
  try {
    return isLoopbackHost(new URL(raw ?? "").hostname);
  } catch {
    return true;
  }
}

/**
 * `vite dev` and `bun run preview` set GITFOR_LOCAL=true (vite.config.ts); `bun run deploy` never does. Dev-only
 * conveniences (first signup becomes admin, loopback integration sinks) also require a loopback PUBLIC_URL.
 */
export function isLocalDev(vars: DeploymentVars = env): boolean {
  return vars.GITFOR_LOCAL === "true" && isLoopbackUrl(vars.PUBLIC_URL);
}

/**