Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(security): bound public ingress bodies
Abdurrahman Fakhrulf0b782c40a83
diff --git a/app/api/auth/login/route.test.ts b/app/api/auth/login/route.test.tsindex 9a21ddf2..9d0904a1 100644--- a/app/api/auth/login/route.test.ts+++ b/app/api/auth/login/route.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { NextRequest } from "next/server";+import { NextRequest } from "next/server";import { clientIp } from "./route";// clientIp() is the rate-limit key. Behind multi-hop proxies (Cloudflare →@@ -72,7 +72,7 @@ describe("clientIp — XFF trusted-proxy hops", () => {// incremented BEFORE the per-IP gate and unconditionally, so a single flooding IP// burned the process-wide budget and locked every other caller out of the cockpit —// unauthenticated, from the internet, for as long as the flood ran.-describe("rate limiting cannot be turned into a lockout of everyone else", () => {+describe("login admission budgets", () => {const SECRET = "s".repeat(48);const PASSWORD = "correct-horse-battery";const device = "d".repeat(32);@@ -94,11 +94,10 @@ describe("rate limiting cannot be turned into a lockout of everyone else", () =>return (await import("./route")).POST;}- const post = (ip: string, password: string) =>- ({- headers: { get: (k: string) => (k.toLowerCase() === "x-forwarded-for" ? ip : null) },- json: async () => ({ password, deviceId: device, deviceLabel: "test" }),- }) as unknown as NextRequest;+ const post = (ip: string, password: string) => new NextRequest("https://mso.example/api/auth/login", {+ method: "POST", headers: {"x-forwarded-for": ip, "content-type": "application/json"},+ body: JSON.stringify({password, deviceId: device, deviceLabel: "test"}),+ });it("keeps serving a different IP after one IP exhausts its own budget", async () => {const POST = await loadRoute();@@ -116,19 +115,15 @@ describe("rate limiting cannot be turned into a lockout of everyone else", () =>expect(owner.status).toBe(403);});- it("keeps serving the owner after a DISTRIBUTED flood fills the process-wide budget", async () => {+ it("exhausts the distributed budget before parsing or testing another password", async () => {const POST = await loadRoute();- // The variant the single-IP reorder did NOT fix: six fresh addresses, each- // staying inside its own 5/min allowance, together spend the whole 30/min- // process-wide budget. No per-IP gate ever fires, so under the old code every- // one of those 30 charged the global counter and the owner's CORRECT password- // from a seventh address came back 429 — an unauthenticated lockout of prod.for (let ip = 0; ip < 6; ip++) {- for (let i = 0; i < 5; i++) await POST(post(`198.51.100.${ip}`, "wrong"));+ for (let i = 0; i < 5; i++) expect((await POST(post(`198.51.100.${ip}`, "wrong"))).status).toBe(401);}- const owner = await POST(post("203.0.113.7", PASSWORD));- expect(owner.status).not.toBe(429);- expect(owner.status).toBe(403); // device_pending = the password was accepted+ const request = post("203.0.113.7", PASSWORD);+ const reader = vi.spyOn(request.body!, "getReader");+ expect((await POST(request)).status).toBe(429);+ expect(reader).not.toHaveBeenCalled();});it("still blocks a single IP past its own allowance", async () => {diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.tsindex 9a6af801..7029c221 100644--- a/app/api/auth/login/route.ts+++ b/app/api/auth/login/route.ts@@ -1,3 +1,4 @@+import { readRequestJson, RequestBodyError } from "@/lib/security/request-body";import { NextRequest, NextResponse } from "next/server";import { constantTimeEq, MAX_COMPARE_BYTES, MIN_SECRET_LEN, signSession, type SessionPayload } from "@/lib/auth/session";import { SESSION_COOKIE } from "@/lib/auth/require-session";@@ -50,24 +51,10 @@ export function clientIp(req: NextRequest): string {return req.headers.get("x-real-ip") ?? "127.0.0.1";}-// ORDER MATTERS, and getting it wrong was an unauthenticated lockout of the owner.-// The global counter used to increment FIRST and unconditionally — including for-// requests the per-IP limiter was already rejecting. So one IP, past its 5/min, kept-// burning the process-wide 30/min budget, and every OTHER caller — the owner, from a-// different address, with the correct password — got 429 for as long as the flood-// continued. No credential required, from the public internet, indefinitely.-//-// Now the per-IP gate runs first and an already-blocked IP returns without touching-// the global budget, so the process-wide cap only ever counts attempts that were-// actually going to reach the password compare.-//-// That reorder killed the single-IP variant but not the distributed one: six fresh-// IPs spending 5 attempts each still filled the 30/min process-wide budget here, and-// the owner's CORRECT password from a seventh address then got 429. So the global-// budget is no longer charged on the way in at all — it is charged below, only by an-// attempt that actually failed the password compare. A correct password can never be-// rejected by it, while the distributed brute-force cap is unchanged (30 wrong-// passwords per minute process-wide, on top of the per-IP 5/min).+// Per-IP rejection never charges the global budget. Admission is reserved before+// body reads/password comparison so distributed requests cannot keep testing guesses.+// Exhaustion temporarily rejects all unauthenticated attempts; an already-approved+// session or the local CLI remains the recovery path, not a password oracle.function rateLimited(ip: string): boolean {const now = Date.now();if (now - globalWindowStart > WINDOW_MS) {@@ -83,6 +70,9 @@ function rateLimited(ip: string): boolean {const live = entry && now <= entry.reset_at;if (live && entry.count >= MAX_ATTEMPTS) return true;+ if (globalAttempts >= GLOBAL_MAX_ATTEMPTS) return true;+ globalAttempts += 1;+if (!live) {rateLimitMap.set(ip, { count: 1, reset_at: now + WINDOW_MS });return false;@@ -114,11 +104,11 @@ export async function POST(req: NextRequest) {return NextResponse.json({ error: "Too many attempts, try again later" }, { status: 429 });}- let body: { password?: string; deviceId?: string; deviceLabel?: string };+ let body: Record<string, unknown>;try {- body = await req.json();- } catch {- return NextResponse.json({ error: "Invalid request body" }, { status: 400 });+ body = await readRequestJson(req, 16 * 1024);+ } catch (error) {+ return NextResponse.json({ error: "Invalid request body" }, { status: error instanceof RequestBodyError ? error.status : 400 });}const { password: provided, deviceId } = body;@@ -137,12 +127,6 @@ export async function POST(req: NextRequest) {// Length-safe fixed-width comparison; no reusable password hash is created.if (!constantTimeEq(password, provided)) {audit({ action: "auth.denied", actor: deviceId, ip, ok: false, detail: "bad password" });- // Charge the process-wide budget HERE, not in rateLimited(), so only a genuinely- // wrong password can exhaust it. See the note above rateLimited().- if (++globalAttempts > GLOBAL_MAX_ATTEMPTS) {- audit({ action: "auth.ratelimited", ip, ok: false, detail: "global" });- return NextResponse.json({ error: "Too many attempts, try again later" }, { status: 429 });- }return NextResponse.json({ error: "bad_password" }, { status: 401 });}diff --git a/app/api/v1/channels/discord/[id]/route.ts b/app/api/v1/channels/discord/[id]/route.tsindex aefa5562..6527cf2f 100644--- a/app/api/v1/channels/discord/[id]/route.ts+++ b/app/api/v1/channels/discord/[id]/route.ts@@ -1,3 +1,4 @@+import { readRequestText, RequestBodyError } from "@/lib/security/request-body";import { NextRequest, NextResponse } from "next/server";import { ChannelError, dispatchChannelInbound, receiveDiscord } from "@/lib/channels";import { rateLimitedUntrusted } from "@/lib/host/rate-limit";@@ -10,17 +11,14 @@ export async function POST(req: NextRequest, context: { params: Promise<{ id: sttry {const { id } = await context.params;if (rateLimitedUntrusted(`channel-discord:${id}`, 120, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429 });- const length = Number(req.headers.get("content-length"));- if (Number.isFinite(length) && length > 1024 * 1024) throw new ChannelError("request_too_large", 413);- const body = await req.text();- if (Buffer.byteLength(body) > 1024 * 1024) throw new ChannelError("request_too_large", 413);+ const body = await readRequestText(req, 1024 * 1024);const result = await receiveDiscord(id, body, req.headers.get("x-signature-timestamp"), req.headers.get("x-signature-ed25519"));if (result.ping) return NextResponse.json({ type: 1 });if (!result.event) throw new ChannelError("invalid_discord_interaction");const dispatched = await dispatchChannelInbound(id, result.event, channelWorkflowRuntime());return NextResponse.json({ type: 4, data: { content: dispatched.workflow ? "Workflow started." : "Received by MSO Channels.", flags: 64 } });} catch (error) {- const value = error instanceof ChannelError ? error : new ChannelError("invalid_channel_interaction");+ const value = error instanceof ChannelError ? error : error instanceof RequestBodyError ? new ChannelError(error.message, error.status) : new ChannelError("invalid_channel_interaction");return NextResponse.json({ error: value.code }, { status: value.status });}}diff --git a/app/oauth/register/route.ts b/app/oauth/register/route.tsindex 1a400fef..91c37141 100644--- a/app/oauth/register/route.ts+++ b/app/oauth/register/route.ts@@ -1,3 +1,4 @@+import { readRequestJson, RequestBodyError } from "@/lib/security/request-body";import { registerClient } from "@/lib/mcp/store";import { isAllowedRedirect } from "@/lib/mcp/pkce";import { mcpEnabled } from "@/lib/mcp/scope";@@ -32,9 +33,9 @@ export async function POST(req: Request) {let body: { redirect_uris?: unknown; client_name?: unknown };try {- body = await req.json();- } catch {- return bad("invalid_request", "body must be JSON");+ body = await readRequestJson(req, 16 * 1024);+ } catch (error) {+ return bad("invalid_request", "body must be bounded JSON", error instanceof RequestBodyError ? error.status : 400);}if (!Array.isArray(body.redirect_uris) || body.redirect_uris.length === 0) {diff --git a/app/oauth/token/route.ts b/app/oauth/token/route.tsindex c5669e42..9bad2a94 100644--- a/app/oauth/token/route.ts+++ b/app/oauth/token/route.ts@@ -1,3 +1,4 @@+import { readRequestJson, readRequestText, RequestBodyError } from "@/lib/security/request-body";import { TenantDenied } from "@/lib/tenancy/authority";import { consumeCode, OAUTH_ACCESS_TOKEN_TTL_MS, rotateOAuthGrant, storeOAuthGrant } from "@/lib/mcp/store";import { verifyPkce, randomToken } from "@/lib/mcp/pkce";@@ -10,16 +11,22 @@ export const dynamic = "force-dynamic";const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store", Pragma: "no-cache" } });async function params(req: Request): Promise<Record<string, string>> {- const p: Record<string, string> = {}, ct = req.headers.get("content-type") ?? "";- if (ct.includes("application/json")) Object.assign(p, await req.json().catch(() => ({})));- else { const form = await req.formData().catch(() => null); if (form) for (const [k, v] of form.entries()) p[k] = String(v); }- return p;+ const ct = req.headers.get("content-type")?.split(";")[0].trim();+ if (ct === "application/json") {+ const body = await readRequestJson(req, 16 * 1024);+ if (Object.values(body).some(value => typeof value !== "string")) throw new RequestBodyError(400, "invalid_request");+ return body as Record<string, string>;+ }+ if (ct !== "application/x-www-form-urlencoded") throw new RequestBodyError(415, "unsupported_content_type");+ return Object.fromEntries(new URLSearchParams(await readRequestText(req, 16 * 1024)));}export async function POST(req: Request) {if (!mcpEnabled()) return new Response("Not Found", { status: 404 });if (rateLimitedUntrusted(`mcp:token:${clientIp(req)}`, 30, 60_000)) return json({ error: "rate_limited" }, 429);- const p = await params(req), expectedResource = `${publicOrigin(req)}/mcp`;+ let p: Record<string, string>;+ try { p = await params(req); } catch (error) { return json({ error: "invalid_request" }, error instanceof RequestBodyError ? error.status : 400); }+ const expectedResource = `${publicOrigin(req)}/mcp`;if (p.grant_type === "refresh_token") {if (!p.refresh_token || !p.client_id) return json({ error: "invalid_request" }, 400);diff --git a/lib/infra/setup-http.ts b/lib/infra/setup-http.tsindex 9b15e2f5..f55d1625 100644--- a/lib/infra/setup-http.ts+++ b/lib/infra/setup-http.ts@@ -1,25 +1,8 @@+import { readRequestJson, RequestBodyError } from "@/lib/security/request-body";import { SetupError, SETUP_MAX_BODY } from "./setup-capability";export async function readSetupJson(req: Request, maxBytes = SETUP_MAX_BODY): Promise<Record<string, unknown>> {if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 2 * 1024 * 1024) throw new SetupError("invalid_body_limit", 400);if (req.headers.get("content-type")?.split(";")[0].trim() !== "application/json") throw new SetupError("json_required", 415);- if (Number(req.headers.get("content-length")) > maxBytes) throw new SetupError("request_too_large", 413);- const reader = req.body?.getReader(); if (!reader) throw new SetupError("invalid_request", 400);- let text = "", bytes = 0;- const decoder = new TextDecoder();- try {- for (;;) {- let timer: ReturnType<typeof setTimeout> | undefined;- const part = await Promise.race([reader.read(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new SetupError("request_timeout", 408)), 5000); })]).finally(() => clearTimeout(timer));- if (part.done) break;- bytes += part.value.byteLength; if (bytes > maxBytes) throw new SetupError("request_too_large", 413);- text += decoder.decode(part.value, { stream: true });- }- text += decoder.decode();- const value: unknown = JSON.parse(text);- if (!value || typeof value !== "object" || Array.isArray(value)) throw new SetupError("invalid_request", 400);- return value as Record<string, unknown>;- } catch (error) {- await reader.cancel().catch(() => undefined);- throw error instanceof SetupError ? error : new SetupError("invalid_request", 400);- } finally { reader.releaseLock(); }+ try { return await readRequestJson(req, maxBytes); }+ catch (error) { throw new SetupError(error instanceof RequestBodyError ? error.message : "invalid_request", error instanceof RequestBodyError ? error.status : 400); }}diff --git a/lib/managed-apps/project-ingress-proxy.test.ts b/lib/managed-apps/project-ingress-proxy.test.tsindex 7c97ff2d..8c1681d7 100644--- a/lib/managed-apps/project-ingress-proxy.test.ts+++ b/lib/managed-apps/project-ingress-proxy.test.ts@@ -21,6 +21,7 @@ function req(path: string, signature = "a".repeat(64)) {host: "hermes.mso.example.com","sec-fetch-site": "cross-site","content-type": "application/json",+ "content-length": "2","x-webhook-timestamp": String(Math.floor(Date.now() / 1000)),"x-webhook-signature-v2": signature,},diff --git a/lib/managed-apps/project-ingress.test.ts b/lib/managed-apps/project-ingress.test.tsindex e11296cb..11a2fbe6 100644--- a/lib/managed-apps/project-ingress.test.ts+++ b/lib/managed-apps/project-ingress.test.ts@@ -15,6 +15,7 @@ function request(path: string, headers: Record<string, string> = {}) {method: "POST",headers: {"content-type": "application/json",+ "content-length": "2","x-webhook-timestamp": String(Math.floor(Date.now() / 1000)),"x-webhook-signature-v2": "a".repeat(64),...headers,diff --git a/lib/managed-apps/project-ingress.ts b/lib/managed-apps/project-ingress.tsindex 449d4b7e..a5d5fd7e 100644--- a/lib/managed-apps/project-ingress.ts+++ b/lib/managed-apps/project-ingress.ts@@ -64,10 +64,11 @@ function plausibleHmacV2Json(request: Request, route: ProjectIngressRoute): boolif (!Number.isInteger(seconds) || Math.abs(Math.floor(Date.now() / 1000) - seconds) > 300) return false;if (!/^[0-9a-f]{64}$/i.test(request.headers.get("x-webhook-signature-v2") ?? "")) return false;const lengthHeader = request.headers.get("content-length");- if (lengthHeader) {- const length = Number(lengthHeader);- if (!Number.isFinite(length) || length < 0 || length > route.maxBodyBytes) return false;- }+ // The rewrite cannot replace a streaming body. Require a bounded HTTP framing+ // contract; chunked or missing-length requests must use a bounded route instead.+ if (!lengthHeader || !/^\d{1,10}$/.test(lengthHeader) || request.headers.has("transfer-encoding")) return false;+ const length = Number(lengthHeader);+ if (!Number.isSafeInteger(length) || length < 1 || length > route.maxBodyBytes) return false;return true;}@@ -84,3 +85,13 @@ export function projectIngressDecision(if (!route) return { matched: false };return plausibleHmacV2Json(request, route) ? { matched: true, target: route.target } : { matched: true };}++/** Machine callbacks receive only their own protocol headers, never cockpit credentials. */+export function projectIngressHeaders(incoming: Headers): Headers {+ const out = new Headers();+ for (const name of ["content-type", "content-length", "x-webhook-timestamp", "x-webhook-signature-v2", "x-request-id"]) {+ const value = incoming.get(name);+ if (value !== null) out.set(name, value);+ }+ return out;+}diff --git a/lib/security/request-body.test.ts b/lib/security/request-body.test.tsnew file mode 100644index 00000000..1c2451b1--- /dev/null+++ b/lib/security/request-body.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from "vitest";+import { readRequestJson, readRequestText } from "./request-body";+function streamRequest(chunks: string[], headers: Record<string, string> = {}, cancelled = () => {}) {+ let index = 0;+ return new Request("https://fixture.invalid", {method: "POST", headers, duplex: "half", body: new ReadableStream({+ pull(controller) { if (index < chunks.length) controller.enqueue(new TextEncoder().encode(chunks[index++])); else controller.close(); }, cancel: cancelled,+ })} as RequestInit);+}+describe("bounded public request bodies", () => {+ it("counts actual bytes when length is absent or falsely small", async () => {+ for (const headers of [{}, {"content-length":"1"}]) await expect(readRequestText(streamRequest(["12", "345"], headers), 4)).rejects.toMatchObject({status: 413});+ });+ it("rejects declared oversized bodies before reading", async () => {+ await expect(readRequestText(streamRequest([], {"content-length":"9999"}), 16)).rejects.toMatchObject({status: 413});+ });+ it("bounds bytes rather than UTF-16 character count", async () => {+ await expect(readRequestText(streamRequest(["ééé"]), 4)).rejects.toMatchObject({status: 413});+ });+ it("preserves raw text and accepts bounded JSON objects", async () => {+ expect(await readRequestText(streamRequest(["hello", " world"]), 64)).toBe("hello world");+ expect(await readRequestJson(streamRequest(['{"ok":', 'true}']), 64)).toEqual({ok:true});+ await expect(readRequestJson(streamRequest(["null"]), 64)).rejects.toMatchObject({status: 400});+ });+ it("uses a total deadline and never hangs on stream cancellation", async () => {+ const req = new Request("https://fixture.invalid", {method:"POST", duplex:"half", body:new ReadableStream({pull() { return new Promise(() => {}); }, cancel() { return new Promise(() => {}); }})} as RequestInit);+ await expect(readRequestText(req, 32, 20)).rejects.toMatchObject({status:408});+ });+});diff --git a/lib/security/request-body.ts b/lib/security/request-body.tsnew file mode 100644index 00000000..f22f9d93--- /dev/null+++ b/lib/security/request-body.ts@@ -0,0 +1,35 @@+/** Bounded readers for public ingress. Count actual bytes before decoding/parsing. */+export class RequestBodyError extends Error {+ constructor(public readonly status: number, message: string) { super(message); this.name = "RequestBodyError"; }+}+export async function readRequestText(req: Request, maxBytes: number, timeoutMs = 5_000): Promise<string> {+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 2 * 1024 * 1024) throw new Error("invalid request body limit");+ const length = req.headers.get("content-length");+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes)) throw new RequestBodyError(413, "request_too_large");+ if (!req.body) return "";+ const reader = req.body.getReader();+ const decoder = new TextDecoder("utf-8", { fatal: true });+ let bytes = 0, text = "", timer: ReturnType<typeof setTimeout> | undefined;+ const deadline = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new RequestBodyError(408, "request_timeout")), timeoutMs); });+ try {+ for (;;) {+ const part = await Promise.race([reader.read(), deadline]);+ if (part.done) break;+ bytes += part.value.byteLength;+ if (bytes > maxBytes) throw new RequestBodyError(413, "request_too_large");+ text += decoder.decode(part.value, { stream: true });+ }+ return text + decoder.decode();+ } catch (error) {+ void reader.cancel().catch(() => undefined);+ throw error instanceof RequestBodyError ? error : new RequestBodyError(400, "invalid_request");+ } finally { clearTimeout(timer); reader.releaseLock(); }+}+export async function readRequestJson(req: Request, maxBytes: number): Promise<Record<string, unknown>> {+ const text = await readRequestText(req, maxBytes);+ try {+ const value: unknown = JSON.parse(text);+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("object required");+ return value as Record<string, unknown>;+ } catch { throw new RequestBodyError(400, "invalid_request"); }+}diff --git a/lib/security/scan-boundaries.test.ts b/lib/security/scan-boundaries.test.tsnew file mode 100644index 00000000..5eb82c63--- /dev/null+++ b/lib/security/scan-boundaries.test.ts@@ -0,0 +1,29 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { isCredentialPath, looseCredentialExcludes } from "@/lib/host/path-credentials";+import { assertA2AUrl } from "@/lib/a2a/network";+import { projectIngressDecision } from "@/lib/managed-apps/project-ingress";++afterEach(() => vi.unstubAllEnvs());+describe("security scan boundary regressions", () => {+ it.each([".env", ".env.local", ".env.production", ".env.backup"])("denies project %s independently of the running checkout", (name) => {+ expect(isCredentialPath(`/srv/projects/fixture/${name}`)).toBe(true);+ });+ it("keeps the public environment example readable", () => {+ expect(isCredentialPath("/srv/projects/fixture/.env.example")).toBe(false);+ });+ it("enforces the dotenv boundary in recursive archives too", () => {+ expect(looseCredentialExcludes()).toEqual(expect.arrayContaining([".env*", "*/.env*"]));+ });+ it("requires explicit owner opt-in for loopback A2A discovery", () => {+ vi.stubEnv("OS_A2A_ALLOW_LOOPBACK", "");+ expect(() => assertA2AUrl("http://127.0.0.1:4555/card")).toThrow(/disabled/);+ });+ it.each([{}, { "transfer-encoding": "chunked", "content-length": "2" }])("does not forward unbounded project ingress", (extra) => {+ const routes = JSON.stringify([{app: "hermes", method: "POST", path: "/webhook", target: "http://127.0.0.1:8644/webhook", auth: "hmac-v2-json"}]);+ const req = new Request("https://hermes.example/webhook", {method: "POST", body: "{}", headers: {+ "content-type": "application/json", "x-webhook-timestamp": String(Math.floor(Date.now()/1000)),+ "x-webhook-signature-v2": "a".repeat(64), ...extra,+ }});+ expect(projectIngressDecision(req, "hermes", "/webhook", routes)).toEqual({matched: true});+ });+});diff --git a/proxy.ts b/proxy.tsindex 6a9c1dbb..2cba760f 100644--- a/proxy.ts+++ b/proxy.ts@@ -27,7 +27,7 @@ import {upstreamSocketHeaders,} from "@/lib/managed-apps/proxy-headers";import { getManagedAppDefinition } from "@/lib/managed-apps/catalog";-import { projectIngressDecision } from "@/lib/managed-apps/project-ingress";+import { projectIngressDecision, projectIngressHeaders } from "@/lib/managed-apps/project-ingress";import { verifySession } from "@/lib/auth/session";import { configuredSessionCookieScope } from "@/lib/auth/session-cookie";import { currentSessionPolicy, getApprovedDevice } from "@/lib/auth/device-store";@@ -232,7 +232,7 @@ export async function proxy(request: NextRequest) {const ingress = projectIngressDecision(request, managedApp, pathname);if (ingress.matched) {if (!ingress.target) return blocked();- return NextResponse.rewrite(new URL(ingress.target));+ return NextResponse.rewrite(new URL(ingress.target), { request: { headers: projectIngressHeaders(request.headers) } });}// A host inside the app namespace that is NOT an app (a new `X.mso.example.com`