import { getDomainRoutingConfig, hostMatches, normalizeHost, type DomainRoutingConfig, type DomainRoutingEnv } from "@hivegrid/config"; import { adminPath, apiPath, appPath } from "./CanonicalUrlUtils"; import { canonicalAdminRouteSlugs, disabledPluginRouteSlugs, isPublicWebRoutePath, isWebRoutePath, normalizeRoutePath, pathMatchesRoutePrefix, reservedTenantChildRouteSlugs, reservedTenantRouteSlugs, } from "./PublicRouteSegments"; export type HostRoutingContext = "app" | "admin" | "api" | "root" | "unknown"; type UrlInput = string | URL | Request; export function getHostRoutingContext(host: string | undefined, config: DomainRoutingConfig = getDomainRoutingConfig()): HostRoutingContext { if (hostMatches(host, config.webAppHost)) { return "app"; } if (hostMatches(host, config.adminAppHost)) { return "admin"; } if (hostMatches(host, config.apiHost)) { return "api"; } if (hostMatches(host, config.appBaseDomain)) { return "root"; } return "unknown"; } export function getHostRoutingContextFromRequest(request: Request, env?: DomainRoutingEnv): HostRoutingContext { const config = getDomainRoutingConfig(env); return getHostRoutingContext(getRequestRoutingHost(request, new URL(request.url), config), config); } export function getHostAwareInternalPath(pathname: string, context: HostRoutingContext): string { if (isFrameworkInternalRoute(pathname)) { return pathname.startsWith("/") ? pathname : `/${pathname}`; } if (context === "admin" && isCanonicalAdminHostRoute(pathname)) { return pathname.startsWith("/") ? pathname : `/${pathname}`; } if ((context === "app" || context === "admin") && isPublicWebRoute(pathname)) { return pathname.startsWith("/") ? pathname : `/${pathname}`; } if (context === "app") { const [tenantSlug, ...rest] = trimPath(pathname).split("/").filter(Boolean); if (!tenantSlug) { return "/app"; } return appPath({ tenantSlug, path: rest.join("/"), mode: "host-aware" }); } if (context === "admin") { return adminPath(trimPath(pathname), { mode: "host-aware" }); } if (context === "api") { const normalized = trimPath(pathname); if (normalized === "healthz" || normalized === "readyz") { return `/${normalized}`; } return normalized.startsWith("v1/") || normalized === "v1" ? `/${normalized}` : apiPath(normalized, { mode: "host-aware" }); } return pathname.startsWith("/") ? pathname : `/${pathname}`; } export function getHostAwareInternalUrlPath(input: UrlInput, config: DomainRoutingConfig = getDomainRoutingConfig()): string { const url = toUrl(input); const context = getHostRoutingContext(getHostFromInput(input, url, config), config); const internalPath = getHostAwareInternalPathWithoutDoublePrefix(url.pathname, context); return `${internalPath}${url.search}${url.hash}`; } export function getCanonicalHostRedirectUrl(input: UrlInput, config: DomainRoutingConfig = getDomainRoutingConfig()): string | null { const url = toUrl(input); const currentHost = getHostFromInput(input, url, config); const context = getHostRoutingContext(currentHost, config); // Self-Redirect-Guard: Zeigt der kanonische Redirect auf denselben Host UND denselben Pfad, waere es eine // 308-Endlosschleife (passiert z.B. wenn adminAppHost == webAppHost — Single-Host-Staging/Dev oder eine // Fehlkonfiguration). In dem Fall NICHT umleiten. In getrennten Prod-Hosts (app. != admin.) greift der // Guard nie, das Verhalten bleibt unveraendert. const isSelfRedirect = (origin: string, pathname: string) => { let targetHost: string; try { targetHost = new URL(origin).host; } catch { return false; } return hostMatches(currentHost, targetHost) && pathname === url.pathname; }; const crossHostRedirect = getCrossHostCanonicalRedirect(url.pathname, context, config); if (crossHostRedirect && !isSelfRedirect(crossHostRedirect.origin, crossHostRedirect.pathname)) { return `${crossHostRedirect.origin}${crossHostRedirect.pathname}${url.search}${url.hash}`; } const rootHostRedirect = getRootHostCanonicalRedirect(url.pathname, context, config); if (rootHostRedirect && !isSelfRedirect(rootHostRedirect.origin, rootHostRedirect.pathname)) { return `${rootHostRedirect.origin}${rootHostRedirect.pathname}${url.search}${url.hash}`; } return null; } export function isCanonicalHostForContext( host: string | undefined, context: Exclude, config: DomainRoutingConfig = getDomainRoutingConfig() ) { const normalizedHost = normalizeHost(host); if (!normalizedHost) { return false; } return getHostRoutingContext(normalizedHost, config) === context; } function trimPath(pathname: string) { return pathname.replace(/^\/+|\/+$/g, ""); } function isPublicWebRoute(pathname: string) { return isWebRoutePath(pathname); } function isFrameworkInternalRoute(pathname: string) { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; return normalizedPathname === "/__manifest"; } const activeWebInternalRoutePrefixes = ["/internal/imports/dry-run"] as const; function isActiveWebInternalRoute(pathname: string) { const routePathname = normalizeRoutePath(pathname); return activeWebInternalRoutePrefixes.some((prefix) => pathMatchesRoutePrefix(routePathname, prefix)); } export function isCanonicalAdminHostRoute(pathname: string) { const routePathname = normalizeRoutePath(pathname); if (isActiveWebInternalRoute(routePathname)) { return false; } if (isDisabledAdminHostRoute(routePathname)) { return false; } const firstSegment = trimPath(routePathname).split("/")[0]; return Boolean(firstSegment && (canonicalAdminRouteSlugs as readonly string[]).includes(firstSegment)); } function isCanonicalApiHostRoute(pathname: string) { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; const routePathname = normalizedPathname.replace(/\.data$/, ""); return routePathname === "/v1" || routePathname.startsWith("/v1/"); } function isLegacyApiV1HostRoute(pathname: string) { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; const routePathname = normalizedPathname.replace(/\.data$/, ""); return routePathname === "/api/v1" || routePathname.startsWith("/api/v1/"); } function isLegacyAppHostRoute(pathname: string) { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; const routePathname = normalizedPathname.replace(/\.data$/, ""); return routePathname.startsWith("/app/") && routePathname.split("/").filter(Boolean).length >= 2; } function isRemovedAdminPrefixRoute(pathname: string) { const routePathname = normalizeRoutePath(pathname); return trimPath(routePathname).split("/").filter(Boolean)[0] === "admin"; } function canonicalTenantPathFromLegacyApp(pathname: string) { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; const routePathname = normalizedPathname.replace(/\.data$/, ""); const canonicalPathname = routePathname.replace(/^\/app(?=\/)/, ""); return normalizedPathname.endsWith(".data") ? `${canonicalPathname}.data` : canonicalPathname; } function canonicalApiPathFromLegacyApiV1(pathname: string) { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; const routePathname = normalizedPathname.replace(/\.data$/, ""); const canonicalPathname = routePathname.replace(/^\/api(?=\/v1(?:\/|$))/, ""); return normalizedPathname.endsWith(".data") ? `${canonicalPathname}.data` : canonicalPathname; } function isApiOperationalRoute(pathname: string) { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; const routePathname = normalizedPathname.replace(/\.data$/, ""); return routePathname === "/healthz" || routePathname === "/readyz"; } function getRootHostCanonicalRedirect(pathname: string, context: HostRoutingContext, config: DomainRoutingConfig) { if (context !== "root") { return null; } const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; if (isLegacyApiV1HostRoute(normalizedPathname)) { return { origin: `${config.protocol}://${config.apiHost}`, pathname: canonicalApiPathFromLegacyApiV1(normalizedPathname), }; } if (isLegacyAppHostRoute(normalizedPathname)) { const canonicalPathname = canonicalTenantPathFromLegacyApp(normalizedPathname); if (isDisabledTenantHostRoute(canonicalPathname)) { return null; } return { origin: `${config.protocol}://${config.webAppHost}`, pathname: canonicalPathname, }; } if (isRemovedAdminPrefixRoute(normalizedPathname)) { return null; } if (normalizedPathname === "/" || isPublicWebRoutePath(normalizedPathname) || isFrameworkInternalRoute(normalizedPathname)) { return null; } if (isDisabledPluginHostRoute(normalizedPathname)) { return null; } if (isActiveWebInternalRoute(normalizedPathname)) { return { origin: `${config.protocol}://${config.webAppHost}`, pathname: normalizedPathname, }; } if (isCanonicalAdminHostRoute(normalizedPathname)) { return { origin: `${config.protocol}://${config.adminAppHost}`, pathname: normalizedPathname, }; } if (isCanonicalApiHostRoute(normalizedPathname)) { return { origin: `${config.protocol}://${config.apiHost}`, pathname: normalizedPathname, }; } return { origin: `${config.protocol}://${config.webAppHost}`, pathname: normalizedPathname, }; } function isDisabledPluginHostRoute(pathname: string) { return isDisabledAdminHostRoute(pathname) || isDisabledTenantHostRoute(pathname); } const disabledAdminHostRoutePrefixes = ["/__workflows", "/internal/ai", "/internal/api/__workflows", "/internal/api/workflows", "/workflows"] as const; const disabledTenantHostRouteChildPrefixes = [ "/__portals", "/__widgets", "/__workflows", "/chat", "/crm", "/email-marketing", "/internal/ai", "/portals", "/sites", "/widgets", "/workflow-engine", ] as const; function isDisabledAdminHostRoute(pathname: string) { const routePathname = normalizeRoutePath(pathname); const firstSegment = trimPath(routePathname).split("/")[0]; if (firstSegment && (disabledPluginRouteSlugs as readonly string[]).includes(firstSegment)) { return true; } return disabledAdminHostRoutePrefixes.some((prefix) => pathMatchesRoutePrefix(routePathname, prefix)); } function isDisabledTenantHostRoute(pathname: string) { const routePathname = normalizeRoutePath(pathname); const [, ...childSegments] = trimPath(routePathname).split("/").filter(Boolean); if (childSegments.length === 0) { return false; } const childPathname = `/${childSegments.join("/")}`; return disabledTenantHostRouteChildPrefixes.some((prefix) => pathMatchesRoutePrefix(childPathname, prefix)); } function getCrossHostCanonicalRedirect(pathname: string, context: HostRoutingContext, config: DomainRoutingConfig) { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; if (isLegacyApiV1HostRoute(normalizedPathname)) { return { origin: `${config.protocol}://${config.apiHost}`, pathname: canonicalApiPathFromLegacyApiV1(normalizedPathname), }; } if (isLegacyAppHostRoute(normalizedPathname)) { const canonicalPathname = canonicalTenantPathFromLegacyApp(normalizedPathname); if (isDisabledTenantHostRoute(canonicalPathname)) { return null; } return { origin: `${config.protocol}://${config.webAppHost}`, pathname: canonicalPathname, }; } if (context === "api" && isUnversionedApiHostAlias(normalizedPathname)) { return { origin: `${config.protocol}://${config.apiHost}`, pathname: apiPath(normalizedPathname, { mode: "host-aware" }), }; } if ((normalizedPathname === "/" || isPublicWebRoutePath(normalizedPathname)) && context === "api" && !isApiOperationalRoute(normalizedPathname)) { return { origin: `${config.protocol}://${config.webAppHost}`, pathname: normalizedPathname, }; } if (normalizedPathname === "/" || isPublicWebRoutePath(normalizedPathname) || isFrameworkInternalRoute(normalizedPathname)) { return null; } if (isDisabledPluginHostRoute(normalizedPathname)) { return null; } if (isActiveWebInternalRoute(normalizedPathname)) { return context === "app" ? null : { origin: `${config.protocol}://${config.webAppHost}`, pathname: normalizedPathname, }; } if (isCanonicalApiHostRoute(normalizedPathname) && context !== "api") { return { origin: `${config.protocol}://${config.apiHost}`, pathname: normalizedPathname, }; } if (isCanonicalAdminHostRoute(normalizedPathname) && context !== "admin") { return { origin: `${config.protocol}://${config.adminAppHost}`, pathname: normalizedPathname, }; } if ((context === "admin" || context === "api") && isCanonicalTenantHostRoute(normalizedPathname)) { return { origin: `${config.protocol}://${config.webAppHost}`, pathname: normalizedPathname, }; } return null; } function getHostAwareInternalPathWithoutDoublePrefix(pathname: string, context: HostRoutingContext): string { const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; if (context === "app" && isLegacyAppHostRoute(normalizedPathname)) { return getHostAwareInternalPath(canonicalTenantPathFromLegacyApp(normalizedPathname), context); } return getHostAwareInternalPath(normalizedPathname, context); } function isCanonicalTenantHostRoute(pathname: string) { const routePathname = normalizeRoutePath(pathname); const [, firstSegment, secondSegment] = routePathname.match(/^\/([^/?#]+)(?:\/([^/?#]+))?/) ?? []; if (isDisabledTenantHostRoute(routePathname)) { return false; } if (!firstSegment || isCanonicalAdminHostRoute(routePathname) || isWebRoutePath(routePathname) || firstSegment === "v1") { return false; } if ((reservedTenantRouteSlugs as readonly string[]).includes(firstSegment)) { return false; } if (!secondSegment) { return true; } const canonicalTenantSegments = new Set([ "$entity", "apps", "dashboard", "g", "internal", "notifications", "settings", ]); if ((reservedTenantChildRouteSlugs as readonly string[]).includes(secondSegment) && !canonicalTenantSegments.has(secondSegment)) { return false; } return Boolean(secondSegment && (canonicalTenantSegments.has(secondSegment) || !secondSegment.startsWith("__"))); } function isUnversionedApiHostAlias(pathname: string) { if (isApiOperationalRoute(pathname) || isCanonicalApiHostRoute(pathname) || isFrameworkInternalRoute(pathname)) { return false; } const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`; const firstSegment = trimPath(normalizedPathname).split("/")[0]; if (!firstSegment) { return false; } return [ "accounts", "ai", "analytics", "api-keys", "auth", "billing", "docs", "entities", "events", "exports", "health", "maintenance", "notifications", "openapi.json", "relationships", "session", "usage", "workspaces", ].includes(firstSegment); } function toUrl(input: UrlInput) { if (input instanceof URL) { return input; } if (input instanceof Request) { return new URL(input.url); } return new URL(input); } function getHostFromInput(input: UrlInput, url: URL, config: DomainRoutingConfig) { if (input instanceof Request) { return getRequestRoutingHost(input, url, config); } return url.host; } export function getRequestRoutingHost(request: Request, url: URL = new URL(request.url), config: DomainRoutingConfig = getDomainRoutingConfig()) { const directHost = request.headers.get("host") ?? url.host; const directContext = getHostRoutingContext(directHost, config); if (directContext === "app" || directContext === "admin" || directContext === "api") { return directHost; } const forwardedHost = request.headers .get("x-forwarded-host") ?.split(",") .map((value) => value.trim()) .find(Boolean); if (forwardedHost) { return forwardedHost; } return directHost; }