Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(erp): stop the server entry swallowing routed .well-known paths (#1460)

Brad Barbine404cc89adc7
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 730c43fcdf..ded866c8d9 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1121,3 +1121,13 @@ canvas hosting Radix popovers/selects.
**Rule:** Card lists (BoM, BoP, and anything similar) render at natural height; the page-level container is the only scroll surface. Don't add `max-h` + `overflow-y-auto` to a card's content to tame its length — if a long list is a problem, solve it with collapse/pagination/virtualization, never a nested scroll region.
**Applies to:** `BillOfMaterial.tsx` / `BillOfProcess.tsx` (items), `JobBillOfMaterial.tsx` / `JobBillOfProcess.tsx`, `QuoteBillOfMaterial.tsx` / `QuoteBillOfProcess.tsx`, and any new card-embedded list in `apps/erp`.
+
+## A prefix short-circuit in the server entry outranks every route under it
+
+**Context:** `/.well-known/oauth-protected-resource` and `/.well-known/oauth-authorization-server` each have a route, and each returned an empty **204** in production instead of its JSON. The MCP endpoint hands clients the first of those URLs in its 401 `WWW-Authenticate` header (`api+/mcp+/_index.ts:63`), so OAuth discovery for the remote connector was dead.
+
+**Problem:** `apps/erp/server/app.ts` wrapped `createRequestHandler` with `if (pathname.startsWith("/.well-known/")) return new Response(null, { status: 204 })` — added to keep browser probes out of the dev logs, with the comment "no app route". That was true when it was written; three `.well-known` routes were added later and every one of them became unreachable, because the short-circuit runs BEFORE the router.
+
+**Rule:** A path check in the server entry silently outranks routing for everything under it. If you short-circuit a prefix, derive the exemptions from the build manifest (`build.routes`) rather than assuming the prefix stays route-free — a comment asserting "no app route" is a claim that rots the moment somebody adds one. Three false leads to skip next time this shape appears: it reproduces identically on Vercel AND `react-router-serve` (so it is not the platform); `/.foo` and `/.env` return normal 404s (so it is not dotfile handling); and `matchRoutes` against the full route table picks the RIGHT route and passes WITH the bug present (so a matcher test proves nothing). The tell was that percent-encoding the dot (`/%2Ewell-known/...`) returned `200 application/json` — `new URL().pathname` leaves the escape undecoded so `startsWith` missed, while the router decodes and matched.
+
+**Applies to:** `apps/erp/server/app.ts`, `apps/mes/server/*`, and any request-handler wrapper that inspects `pathname` before delegating.
diff --git a/apps/erp/app/utils/well-known.test.ts b/apps/erp/app/utils/well-known.test.ts
new file mode 100644
index 0000000000..ec5c37649a
--- /dev/null
+++ b/apps/erp/app/utils/well-known.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vitest";
+import routeConfig from "../routes";
+import { isUnroutedWellKnownPath, wellKnownRoutePaths } from "./well-known";
+
+/** Every route path in the generated config, absolute. */
+async function configuredPaths(): Promise<string[]> {
+ const out: string[] = [];
+
+ const walk = (entries: any[], prefix = "") => {
+ for (const entry of entries ?? []) {
+ const path = [prefix, entry.path ?? ""].filter(Boolean).join("/");
+ if (entry.path !== undefined) out.push(`/${path}`);
+ if (entry.children) walk(entry.children, path);
+ }
+ };
+
+ walk((await (routeConfig as any)) as any[]);
+ return out;
+}
+
+describe("wellKnownRoutePaths", () => {
+ it("reads .well-known routes out of the build manifest", () => {
+ const paths = wellKnownRoutePaths({
+ "routes/[.]well-known.oauth-protected-resource": {
+ path: ".well-known/oauth-protected-resource"
+ },
+ "routes/[.]well-known.mcp[.]json": { path: ".well-known/mcp.json" },
+ "routes/_public+/login": { path: "login" },
+ root: { path: undefined }
+ });
+
+ expect([...paths].sort()).toEqual([
+ "/.well-known/mcp.json",
+ "/.well-known/oauth-protected-resource"
+ ]);
+ });
+
+ it("survives a missing or empty manifest", () => {
+ expect(wellKnownRoutePaths(undefined).size).toBe(0);
+ expect(wellKnownRoutePaths({}).size).toBe(0);
+ });
+});
+
+describe("isUnroutedWellKnownPath", () => {
+ const routed = new Set(["/.well-known/oauth-protected-resource"]);
+
+ it("short-circuits probes with no route", () => {
+ for (const path of [
+ "/.well-known/security.txt",
+ "/.well-known/apple-app-site-association",
+ "/.well-known/appspecific/com.chrome.devtools.json"
+ ]) {
+ expect(isUnroutedWellKnownPath(path, routed), path).toBe(true);
+ }
+ });
+
+ it("lets a routed path through to the router", () => {
+ // The regression: this returned an empty 204 in production, so the MCP
+ // endpoint's 401 pointed clients at a URL that answered with nothing.
+ expect(
+ isUnroutedWellKnownPath("/.well-known/oauth-protected-resource", routed)
+ ).toBe(false);
+ });
+
+ it("leaves every other path alone", () => {
+ for (const path of ["/login", "/api/mcp", "/.env", "/x/.well-known/foo"]) {
+ expect(isUnroutedWellKnownPath(path, routed), path).toBe(false);
+ }
+ });
+
+ it("does not swallow any .well-known route this app actually has", async () => {
+ // Derived from the real route config, so a route added later is covered
+ // without editing this test.
+ const wellKnown = (await configuredPaths()).filter((p) =>
+ p.startsWith("/.well-known/")
+ );
+ const routedPaths = new Set(wellKnown);
+
+ expect(wellKnown.length).toBeGreaterThan(0);
+ for (const path of wellKnown) {
+ expect(isUnroutedWellKnownPath(path, routedPaths), path).toBe(false);
+ }
+ });
+});
diff --git a/apps/erp/app/utils/well-known.ts b/apps/erp/app/utils/well-known.ts
new file mode 100644
index 0000000000..954db5b94d
--- /dev/null
+++ b/apps/erp/app/utils/well-known.ts
@@ -0,0 +1,51 @@
+/**
+ * Which `/.well-known/...` requests the server entry answers itself.
+ *
+ * Browsers and scanners probe this prefix constantly (`security.txt`,
+ * `apple-app-site-association`, Chrome devtools' `appspecific` path), and none
+ * of those have routes. `server/app.ts` answers them with an empty 204 before
+ * `createRequestHandler` runs, which keeps "No route matches" out of the logs.
+ *
+ * That check used to be an unconditional `pathname.startsWith("/.well-known/")`,
+ * which silently made every REAL `.well-known` route unreachable — including
+ * `/.well-known/oauth-protected-resource`, the URL the MCP endpoint hands
+ * clients in its 401 `WWW-Authenticate` header. It returned an empty 204 in
+ * production instead of its JSON, so OAuth discovery for the remote connector
+ * could not complete. Routed paths must reach the router; only unrouted ones are
+ * short-circuited.
+ */
+
+export const WELL_KNOWN_PREFIX = "/.well-known/";
+
+type RouteManifestEntry = { path?: string } | undefined;
+
+/**
+ * The `/.well-known/...` paths the router actually serves, read from the build
+ * manifest. Derived rather than listed, so adding a `.well-known` route serves
+ * it without anyone remembering to update the server entry.
+ */
+export function wellKnownRoutePaths(
+ routes: Record<string, RouteManifestEntry> | undefined
+): Set<string> {
+ const paths = new Set<string>();
+
+ for (const route of Object.values(routes ?? {})) {
+ const path = route?.path;
+ if (!path) continue;
+
+ // Manifest paths are root-relative without a leading slash
+ // (`.well-known/oauth-protected-resource`).
+ const absolute = path.startsWith("/") ? path : `/${path}`;
+ if (absolute.startsWith(WELL_KNOWN_PREFIX)) paths.add(absolute);
+ }
+
+ return paths;
+}
+
+/** True when this is a `.well-known` probe with no route behind it. */
+export function isUnroutedWellKnownPath(
+ pathname: string,
+ routedPaths: ReadonlySet<string>
+): boolean {
+ return pathname.startsWith(WELL_KNOWN_PREFIX) && !routedPaths.has(pathname);
+}
diff --git a/apps/erp/server/app.ts b/apps/erp/server/app.ts
index f27a074a0e..c47af34731 100644
--- a/apps/erp/server/app.ts
+++ b/apps/erp/server/app.ts
@@ -1,16 +1,27 @@
import { createRequestHandler, RouterContextProvider } from "react-router";
// @ts-expect-error
import * as build from "virtual:react-router/server-build";
+import {
+ isUnroutedWellKnownPath,
+ wellKnownRoutePaths
+} from "../app/utils/well-known";
const handler = createRequestHandler(build);
const isVercel = !!process.env.VERCEL_DEPLOYMENT_ID;
-// Browsers probe `/.well-known/...` — no app route; avoid noisy "No route
-// matches" errors in dev logs.
+// Browsers probe `/.well-known/...` — answer the ones with no route directly, to
+// avoid noisy "No route matches" errors in dev logs. Computed once from the
+// build manifest so a real `.well-known` route is never swallowed: this check
+// used to be an unconditional prefix match, which made every such route return
+// an empty 204 instead of its body.
+const routedWellKnownPaths = wellKnownRoutePaths(
+ (build as { routes?: Record<string, { path?: string }> }).routes
+);
+
const fn = (req: Request) => {
try {
const pathname = new URL(req.url).pathname;
- if (pathname.startsWith("/.well-known/")) {
+ if (isUnroutedWellKnownPath(pathname, routedWellKnownPaths)) {
return Promise.resolve(new Response(null, { status: 204 }));
}
} catch {
@@ -23,7 +34,7 @@ const fn = (req: Request) => {
const wrapper = isVercel
? fn
: {
- fetch: fn,
+ fetch: fn
};
export default wrapper;