fix(docker): honor OMNIROUTE_BASE_PATH behind reverse-proxy subpaths (#8615)

* fix(docker): honor OMNIROUTE_BASE_PATH behind reverse-proxy subpaths

Next.js basePath is compile-time state; Docker now records the baked value,
forwards the env var as a build-arg, patches root-path images at container
start when needed, and probes health under the active subpath.

Hard Rule #13: scripts/docker/patch-basepath.sh and the entrypoint invoke Node
with a fixed argv; OMNIROUTE_BASE_PATH is read from process.env only — never
interpolated into sed/awk.

Closes #8600

* fix(docs): unblock CI for Docker basePath guide

Describe the build-time basePath marker as a sentinel file instead of a
fabricated env var, and replace the unsupported ```env fence with bash so
fumadocs/Shiki can compile DOCKER_GUIDE.md during DAST smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(docker): add changelog fragment for #8615 basePath bundle patch

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
This commit is contained in:
AmirHossein Rezaei
2026-07-28 01:37:58 +03:30
committed by GitHub
parent 7ac42d6df6
commit bb5cb51f3e
22 changed files with 679 additions and 7 deletions

View File

@@ -177,6 +177,21 @@ const EXTRA_MODULE_ENTRIES = [
src: ["scripts", "build", "bootstrap-env.mjs"],
dest: ["build", "bootstrap-env.mjs"],
},
{
label: "normalizeBasePath helper",
src: ["scripts", "build", "normalizeBasePath.mjs"],
dest: ["build", "normalizeBasePath.mjs"],
},
{
label: "docker basePath entrypoint",
src: ["scripts", "docker", "ensure-docker-base-path.mjs"],
dest: ["docker", "ensure-docker-base-path.mjs"],
},
{
label: "docker basePath patcher",
src: ["scripts", "docker", "patch-standalone-base-path.mjs"],
dest: ["docker", "patch-standalone-base-path.mjs"],
},
{
label: "healthcheck script",
src: ["scripts", "dev", "healthcheck.mjs"],

View File

@@ -329,6 +329,17 @@ export async function main() {
projectRoot,
copyNatives: true,
});
const { spawnSync } = await import("node:child_process");
const basePathWrite = spawnSync(
process.execPath,
[path.join(projectRoot, "scripts", "build", "write-build-base-path.mjs")],
{ cwd: projectRoot, env: process.env, stdio: "inherit" }
);
if (basePathWrite.status !== 0) {
console.warn(
"[build-next-isolated] Non-fatal error writing BUILD_OMNIROUTE_BASE_PATH sentinel"
);
}
} catch (assembleErr) {
console.warn("[build-next-isolated] Non-fatal error assembling standalone:", assembleErr);
}

View File

@@ -0,0 +1,31 @@
/**
* Normalize OMNIROUTE_BASE_PATH for Next.js `basePath` and Docker sentinels.
*
* Rules mirror src/shared/services/modelSyncScheduler.ts::normalizeInternalBasePath
* so runtime self-fetches and the compiled bundle agree on the subpath shape.
*
* @param {string | undefined | null} value
* @returns {string} "" for root, otherwise "/segment" without trailing slash
*/
export function normalizeBasePath(value) {
const trimmed = typeof value === "string" ? value.trim() : "";
if (!trimmed || trimmed === "/") return "";
if (!trimmed.startsWith("/") || /[?#\\]/.test(trimmed)) return "";
const segments = trimmed.split("/").filter(Boolean);
if (segments.some((segment) => segment === "." || segment === "..")) return "";
return `/${segments.join("/")}`;
}
/**
* Prefix an application path with a normalized base path.
*
* @param {string} basePath normalized via normalizeBasePath
* @param {string} pathname must start with "/"
*/
export function joinBasePath(basePath, pathname) {
const pathPart = pathname.startsWith("/") ? pathname : `/${pathname}`;
if (!basePath) return pathPart;
if (pathPart === "/") return `${basePath}/`;
return `${basePath}${pathPart}`;
}

View File

@@ -0,0 +1,42 @@
#!/usr/bin/env node
/**
* Writes BUILD_OMNIROUTE_BASE_PATH into the standalone bundle so container start
* can compare the baked Next.js basePath against OMNIROUTE_BASE_PATH.
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { normalizeBasePath } from "./normalizeBasePath.mjs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, "..", "..");
const NEXT_DIST = process.env.NEXT_DIST_DIR || ".build/next";
function writeSentinel(targetDir) {
const basePath = normalizeBasePath(process.env.OMNIROUTE_BASE_PATH);
const sentinel = path.join(targetDir, "BUILD_OMNIROUTE_BASE_PATH");
fs.writeFileSync(sentinel, `${basePath}\n`);
return { basePath, sentinel };
}
const standaloneDir = path.join(ROOT, NEXT_DIST, "standalone");
if (!fs.existsSync(standaloneDir)) {
console.error(
`[write-build-base-path] FATAL: standalone dir not found: ${standaloneDir}\n` +
" Run `npm run build` first."
);
process.exit(1);
}
const { basePath, sentinel } = writeSentinel(standaloneDir);
console.log(
`[write-build-base-path] Recorded basePath ${basePath || "(root)"} -> ${path.relative(ROOT, sentinel)}`
);
const distDir = path.join(ROOT, "dist");
if (fs.existsSync(distDir)) {
const distSentinel = writeSentinel(distDir).sentinel;
console.log(`[write-build-base-path] Recorded basePath -> ${path.relative(ROOT, distSentinel)}`);
}

View File

@@ -8,6 +8,13 @@ if [ -n "$OMNIROUTE_MEMORY_MB" ]; then
export NODE_OPTIONS="${NODE_OPTIONS:-} --max-old-space-size=${OMNIROUTE_MEMORY_MB}"
fi
# Hard Rule #13: never interpolate OMNIROUTE_BASE_PATH (or any runtime path)
# into sed/awk/shell. The Node guard reads process.env itself — invoke with a
# fixed argv only; do not pass the subpath as a CLI argument or script body.
if [ -f docker/ensure-docker-base-path.mjs ]; then
node docker/ensure-docker-base-path.mjs || exit 1
fi
DATA_PATH="${DATA_DIR:-/app/data}"
if [ -d "$DATA_PATH" ] && [ ! -w "$DATA_PATH" ]; then
echo "WARNING: $DATA_PATH is not writable by the current user (UID $(id -u))."

View File

@@ -21,6 +21,22 @@ import { networkInterfaces } from "node:os";
const DEFAULT_HOSTS = ["127.0.0.1", "localhost", "::1"];
const DEFAULT_TIMEOUT_MS = 4000;
const DEFAULT_HEALTH_PATH = "/api/monitoring/health";
function normalizeBasePath(value) {
const trimmed = typeof value === "string" ? value.trim() : "";
if (!trimmed || trimmed === "/") return "";
if (!trimmed.startsWith("/") || /[?#\\]/.test(trimmed)) return "";
const segments = trimmed.split("/").filter(Boolean);
if (segments.some((segment) => segment === "." || segment === "..")) return "";
return `/${segments.join("/")}`;
}
/** Prefixes the health route with the configured Next.js basePath. */
export function resolveHealthPath(basePathValue) {
const basePath = normalizeBasePath(basePathValue);
return basePath ? `${basePath}${DEFAULT_HEALTH_PATH}` : DEFAULT_HEALTH_PATH;
}
/**
* Get the primary non-loopback IPv4 address (container internal IP).
@@ -45,10 +61,11 @@ function getContainerInternalIP() {
* Build the health URL for a host, bracketing IPv6 literals (e.g. `::1`).
* @param {string} host
* @param {string|number} port
* @param {string} healthPath path to probe, including any basePath prefix
*/
function healthUrl(host, port) {
function healthUrl(host, port, healthPath = DEFAULT_HEALTH_PATH) {
const hostPart = host.includes(":") ? `[${host}]` : host;
return `http://${hostPart}:${port}/api/monitoring/health`;
return `http://${hostPart}:${port}${healthPath}`;
}
/**
@@ -62,6 +79,7 @@ function healthUrl(host, port) {
* @param {string[]} [opts.hosts]
* @param {typeof fetch} [opts.fetchImpl]
* @param {number} [opts.timeoutMs]
* @param {string} [opts.healthPath]
* @returns {Promise<string>} the host that succeeded
*/
export async function probeHealth({
@@ -69,11 +87,12 @@ export async function probeHealth({
hosts = DEFAULT_HOSTS,
fetchImpl = fetch,
timeoutMs = DEFAULT_TIMEOUT_MS,
healthPath = DEFAULT_HEALTH_PATH,
} = {}) {
let lastError = new Error("no hosts to probe");
for (const host of hosts) {
try {
const res = await fetchImpl(healthUrl(host, port), {
const res = await fetchImpl(healthUrl(host, port, healthPath), {
signal: AbortSignal.timeout(timeoutMs),
});
if (res.ok) return host;
@@ -96,7 +115,8 @@ async function main() {
}
try {
await probeHealth({ port, hosts });
const healthPath = resolveHealthPath(process.env.OMNIROUTE_BASE_PATH);
await probeHealth({ port, hosts, healthPath });
process.exit(0);
} catch (err) {
// Surface the failure so `docker inspect ... .State.Health[].Output` is

View File

@@ -0,0 +1,86 @@
#!/usr/bin/env node
/**
* Compares OMNIROUTE_BASE_PATH at container start against BUILD_OMNIROUTE_BASE_PATH
* recorded during the image build. When they differ and the image was built for the
* domain root, rewrites the standalone bundle before Next.js starts.
*
* Hard Rule #13: the subpath is read only from process.env (or an injected env
* object in tests). Never accept it as a CLI argument or interpolate it into a
* shell sed/awk invocation — see scripts/docker/patch-basepath.sh.
*/
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { normalizeBasePath } from "../build/normalizeBasePath.mjs";
import { patchStandaloneBasePath } from "./patch-standalone-base-path.mjs";
const SENTINEL = "BUILD_OMNIROUTE_BASE_PATH";
function readBakedBasePath(appRoot) {
const sentinelPath = path.join(appRoot, SENTINEL);
if (!fs.existsSync(sentinelPath)) return "";
return normalizeBasePath(fs.readFileSync(sentinelPath, "utf8"));
}
function writeBakedBasePath(appRoot, basePath) {
fs.writeFileSync(path.join(appRoot, SENTINEL), `${basePath}\n`);
}
/**
* @param {object} [opts]
* @param {string} [opts.appRoot]
* @param {NodeJS.ProcessEnv} [opts.env]
*/
export function ensureDockerBasePath(opts = {}) {
const appRoot = opts.appRoot || process.cwd();
const runtime = normalizeBasePath(opts.env?.OMNIROUTE_BASE_PATH ?? process.env.OMNIROUTE_BASE_PATH);
const baked = readBakedBasePath(appRoot);
if (runtime === baked) {
return { action: "noop", runtime, baked };
}
if (!runtime && baked) {
throw new Error(
`This OmniRoute image was built for subpath ${baked}, but OMNIROUTE_BASE_PATH is unset. ` +
`Set OMNIROUTE_BASE_PATH=${baked} or rebuild without the build-arg.`
);
}
const patchResult = patchStandaloneBasePath({
appRoot,
fromBasePath: baked,
toBasePath: runtime,
});
writeBakedBasePath(appRoot, runtime);
return { action: "patched", runtime, baked, patchResult };
}
function main() {
try {
const result = ensureDockerBasePath();
if (result.action === "patched") {
const { patchResult, runtime } = result;
console.log(
`[ensure-docker-base-path] Applied runtime subpath ${runtime} ` +
`(manifests=${patchResult.patchedManifests}, textFiles=${patchResult.patchedTextFiles})`
);
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error(`[ensure-docker-base-path] ${message}`);
console.error(
"[ensure-docker-base-path] Rebuild the image with the same subpath, e.g.\n" +
" docker compose build --build-arg OMNIROUTE_BASE_PATH=/omniroute"
);
process.exit(1);
}
}
const isEntrypoint =
Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isEntrypoint) {
main();
}

View File

@@ -0,0 +1,8 @@
#!/bin/sh
# Hard Rule #13 — OMNIROUTE_BASE_PATH must travel via the process environment.
# This wrapper never expands the subpath into sed/awk/shell script text; Node
# reads OMNIROUTE_BASE_PATH from env inside ensure-docker-base-path.mjs.
set -eu
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
exec node "${SCRIPT_DIR}/ensure-docker-base-path.mjs"

View File

@@ -0,0 +1,168 @@
/**
* Rewrites Next.js standalone manifests and embedded basePath literals so a bundle
* built for the domain root can serve under OMNIROUTE_BASE_PATH at container start.
*/
import fs from "node:fs";
import path from "node:path";
import { normalizeBasePath } from "../build/normalizeBasePath.mjs";
const JSON_MANIFEST_NAMES = new Set([
"routes-manifest.json",
"prerender-manifest.json",
"required-server-files.json",
"images-manifest.json",
"app-path-routes-manifest.json",
]);
/**
* @param {string} appRoot
* @returns {string[]}
*/
export function discoverNextDistRoots(appRoot) {
const candidates = [".build/next", ".next", path.join(".build", "next")];
const found = [];
for (const rel of candidates) {
const abs = path.join(appRoot, rel);
if (fs.existsSync(path.join(abs, "routes-manifest.json"))) {
found.push(abs);
}
}
return found;
}
/**
* @param {unknown} node
* @param {string} basePath
*/
function patchJsonNode(node, basePath) {
if (!node || typeof node !== "object") return;
if (Array.isArray(node)) {
for (const entry of node) patchJsonNode(entry, basePath);
return;
}
for (const [key, value] of Object.entries(node)) {
if (key === "basePath" && typeof value === "string") {
node[key] = basePath;
continue;
}
patchJsonNode(value, basePath);
}
}
/**
* @param {string} filePath
* @param {string} basePath
*/
export function patchJsonManifestFile(filePath, basePath) {
const raw = fs.readFileSync(filePath, "utf8");
const parsed = JSON.parse(raw);
patchJsonNode(parsed, basePath);
const next = `${JSON.stringify(parsed, null, 2)}\n`;
if (next !== raw) {
fs.writeFileSync(filePath, next);
return true;
}
return false;
}
const BASE_PATH_LITERAL_RE =
/basePath\s*:\s*(?:""|''|`{2})|basePath\s*:\s*void 0|"basePath"\s*:\s*""/g;
/**
* @param {string} content
* @param {string} basePath
*/
export function patchBasePathLiterals(content, basePath) {
const escaped = basePath.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
return content.replace(BASE_PATH_LITERAL_RE, (match) => {
if (match.startsWith('"basePath"')) return `"basePath":"${escaped}"`;
if (match.includes("void 0")) return `basePath:"${escaped}"`;
return `basePath:"${escaped}"`;
});
}
/**
* @param {string} rootDir
* @param {string} basePath
*/
function walkAndPatchTextFiles(rootDir, basePath) {
let patchedFiles = 0;
const stack = [rootDir];
while (stack.length > 0) {
const current = stack.pop();
if (!current) continue;
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) {
stack.push(full);
continue;
}
if (!/\.(?:js|json|cjs|mjs)$/.test(entry.name)) continue;
const before = fs.readFileSync(full, "utf8");
const after = patchBasePathLiterals(before, basePath);
if (after !== before) {
fs.writeFileSync(full, after);
patchedFiles += 1;
}
}
}
return patchedFiles;
}
/**
* @param {object} opts
* @param {string} opts.appRoot standalone bundle root (cwd in Docker)
* @param {string} opts.fromBasePath normalized baked base path
* @param {string} opts.toBasePath normalized runtime base path
*/
export function patchStandaloneBasePath({ appRoot, fromBasePath, toBasePath }) {
const from = normalizeBasePath(fromBasePath);
const to = normalizeBasePath(toBasePath);
if (from === to) {
return { changed: false, patchedManifests: 0, patchedTextFiles: 0, distRoots: [] };
}
if (from) {
throw new Error(
`runtime OMNIROUTE_BASE_PATH (${to || "(root)"}) does not match the image build ` +
`(${from}). Rebuild with --build-arg OMNIROUTE_BASE_PATH=${to || '""'}.`
);
}
if (!to) {
throw new Error("patchStandaloneBasePath requires a non-empty target base path");
}
const distRoots = discoverNextDistRoots(appRoot);
if (distRoots.length === 0) {
throw new Error(
"could not locate routes-manifest.json under .build/next or .next in the standalone bundle"
);
}
let patchedManifests = 0;
let patchedTextFiles = 0;
for (const distRoot of distRoots) {
for (const name of JSON_MANIFEST_NAMES) {
const manifestPath = path.join(distRoot, name);
if (!fs.existsSync(manifestPath)) continue;
if (patchJsonManifestFile(manifestPath, to)) patchedManifests += 1;
}
const serverDir = path.join(distRoot, "server");
if (fs.existsSync(serverDir)) patchedTextFiles += walkAndPatchTextFiles(serverDir, to);
const staticDir = path.join(distRoot, "static");
if (fs.existsSync(staticDir)) patchedTextFiles += walkAndPatchTextFiles(staticDir, to);
}
for (const entry of ["server.js", "server-ws.mjs"]) {
const serverEntry = path.join(appRoot, entry);
if (!fs.existsSync(serverEntry)) continue;
const before = fs.readFileSync(serverEntry, "utf8");
const after = patchBasePathLiterals(before, to);
if (after !== before) {
fs.writeFileSync(serverEntry, after);
patchedTextFiles += 1;
}
}
return { changed: true, patchedManifests, patchedTextFiles, distRoots, toBasePath: to };
}