import { describe, it, expect } from "vitest"; import { readdirSync, readFileSync } from "node:fs"; import { join, relative, resolve } from "node:path"; // portal-path-segment-encoding (F38 follow-up): Next.js decodes route params, so a raw `${id}` turns a client's // `%2F` / `%3F` into a real `/` / `?` in the mobile-api path, reaching a sibling endpoint or adding a parameter. // Every value read from `params` is interpolated through encodeURIComponent; a catch-all array is encoded per // segment (`path.map(encodeURIComponent).join("/")`). This file is identical in both portals. const PORTAL_ROOT = resolve(__dirname, "../../.."); const APP_DIR = join(PORTAL_ROOT, "app"); const SCANNED = new Set(["route.ts", "page.tsx", "layout.tsx"]); function sourceFiles(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }).flatMap(e => { const p = join(dir, e.name); if (e.isDirectory()) return e.name === "node_modules" ? [] : sourceFiles(p); return SCANNED.has(e.name) ? [p] : []; }); } const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const PARAMS = String.raw`await\s+(?:ctx\.|context\.|props\.)?params`; /** The names a source binds from its route params. Names already bound to an encoded join are left out. */ function paramNames(src: string): string[] { const names = new Set(); for (const m of src.matchAll(new RegExp(String.raw`(?:const|let)\s*\{([^}]+)\}\s*=\s*\(?${PARAMS}\b`, "g"))) { for (const part of m[1].split(",")) { const name = part.split("=")[0].split(":").pop()?.trim(); if (name) names.add(name); } } // The whole params object bound to a name: any `${p.…}` use of it is a raw param. for (const m of src.matchAll(new RegExp(String.raw`(?:const|let)\s+(\w+)\s*=\s*\(?${PARAMS}\b\)?\s*(?:as\s[^;\n]*)?;`, "g"))) { names.add(m[1]); } for (const m of src.matchAll(new RegExp(String.raw`(?:const|let)\s+(\w+)\s*=\s*\(${PARAMS}\)\.\w+([^;\n]*)`, "g"))) { if (!/\.map\(\s*encodeURIComponent\s*\)/.test(m[2])) names.add(m[1]); } return [...names]; } /** The params values a source interpolates raw (not through encodeURIComponent), or [] when it does not. */ export function rawParamOffences(src: string): string[] { const out = new Set(); for (const name of paramNames(src)) { const raw = new RegExp(String.raw`\$\{\s*${escape(name)}\b(?!\.map\(\s*encodeURIComponent\s*\))`); if (raw.test(src)) out.add(`\${${name}} interpolated raw`); } for (const m of src.matchAll(new RegExp(String.raw`\(${PARAMS}\)\.(\w+)\.join\(`, "g"))) { out.add(`${m[1]}.join() without encoding each segment`); } return [...out]; } describe("portals never interpolate a raw route param (portal-path-segment-encoding)", () => { const files = sourceFiles(APP_DIR).map(f => ({ rel: relative(PORTAL_ROOT, f), src: readFileSync(f, "utf8") })); it("finds the route and page files", () => { expect(files.length).toBeGreaterThan(10); }); it("has no file that interpolates a params value raw", () => { const offenders = files .map(f => ({ file: f.rel, why: rawParamOffences(f.src) })) .filter(o => o.why.length > 0) .map(o => `${o.file}: ${o.why.join(", ")}`); expect(offenders).toEqual([]); }); }); /** Files that fetch mobile-api directly with an interpolated path must apply the dot-segment guard themselves. */ function directFetchFiles(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }).flatMap(e => { const p = join(dir, e.name); if (e.isDirectory()) return e.name === "node_modules" ? [] : directFetchFiles(p); return /\.(ts|tsx)$/.test(e.name) && !/\.test\.tsx?$/.test(e.name) ? [p] : []; }); } /** * True when a server source reads MOBILE_API_BASE_URL, builds a URL from a base (any name containing "base", or the * env var itself) plus an interpolated path, calls fetch, and never calls the guard. The URL may be built inline or in * a variable first. Browser code never reads MOBILE_API_BASE_URL, so its `${BASE}` BFF paths are not matched. */ export function unguardedDirectFetch(src: string): boolean { if (!src.includes("MOBILE_API_BASE_URL")) return false; const built = /`\$\{\s*(?:[\w.]*base[\w.]*|process\.env\.MOBILE_API_BASE_URL)\s*\}[^`]*\$\{/i.test(src); return built && /\bfetch\(/.test(src) && !/\b(?:isTraversalPath|hasDotSegment)\(/.test(src); } describe("direct mobile-api fetches apply the dot-segment guard (portal-path-segment-encoding)", () => { it("has no file that fetches an interpolated upstream path without isTraversalPath", () => { const offenders = directFetchFiles(join(PORTAL_ROOT, "app")) .filter(f => unguardedDirectFetch(readFileSync(f, "utf8"))) .map(f => relative(PORTAL_ROOT, f)); expect(offenders).toEqual([]); }); it("flags an unguarded direct fetch and accepts a guarded one", () => { expect(unguardedDirectFetch("const base = process.env.MOBILE_API_BASE_URL;\nres = await fetch(`${base}/api/x/${id}`);")).toBe(true); expect(unguardedDirectFetch("const base = process.env.MOBILE_API_BASE_URL;\nif (isTraversalPath(path)) return;\nres = await fetch(`${base}${path}`);")).toBe(false); expect(unguardedDirectFetch("const base = process.env.MOBILE_API_BASE_URL;\nres = await fetch(`${base}/api/x/images`);")).toBe(false); expect(unguardedDirectFetch("const base = process.env.MOBILE_API_BASE_URL;\nconst url = `${base}/api/x/${id}/invoice`;\nres = await fetch(url);")).toBe(true); expect(unguardedDirectFetch("const upstream =\n `${process.env.MOBILE_API_BASE_URL}/api/x/${id}`;\nawait fetch(upstream);")).toBe(true); // Browser code builds BFF paths from its own `${BASE}`; it never reads MOBILE_API_BASE_URL. expect(unguardedDirectFetch("const BASE = \"/api/member/messages\";\nawait fetch(`${BASE}/${uuid}/images`);")).toBe(false); expect(unguardedDirectFetch("const base = process.env.MOBILE_API_BASE_URL;\nconst u = `${mobileBaseUrl}/api/x/${id}`;\nawait fetch(u);")).toBe(true); }); }); // --------------------------------------------------------------------------- // forwardedClientIpHeaders coverage (task 7) // --------------------------------------------------------------------------- /** * True when a server source reads MOBILE_API_BASE_URL and never references forwardedClientIpHeaders * or callMobileApi (the central helper that already forwards it). */ export function missingForwardedIpCoverage(src: string): boolean { if (!src.includes("MOBILE_API_BASE_URL")) return false; // Any file that reads the base URL builds its own request (mobileApi.ts included), so it must merge // forwardedClientIpHeaders itself; merely importing callMobileApi does not cover a raw fetch beside it. return !/\bforwardedClientIpHeaders\(/.test(src); } describe("missingForwardedIpCoverage", () => { it("flags a direct mobile-api fetch that does not forward the client IP, even if it also uses callMobileApi", () => { expect(missingForwardedIpCoverage("const base = process.env.MOBILE_API_BASE_URL;\nawait fetch(`${base}/api/x`);")).toBe(true); expect( missingForwardedIpCoverage( "import { callMobileApi } from \"./mobileApi\";\nconst base = process.env.MOBILE_API_BASE_URL;\nawait fetch(`${base}/api/x`);", ), ).toBe(true); expect( missingForwardedIpCoverage("import { clientIp } from \"./x\";\nconst base = process.env.MOBILE_API_BASE_URL;\nawait fetch(`${base}/api/x`);"), ).toBe(true); }); it("accepts a direct fetch that merges forwardedClientIpHeaders, and files that never read the base URL", () => { expect( missingForwardedIpCoverage( "const base = process.env.MOBILE_API_BASE_URL;\nconst h = await forwardedClientIpHeaders();\nawait fetch(`${base}/api/x`, { headers: h });", ), ).toBe(false); expect(missingForwardedIpCoverage("await callMobileApi(\"/api/x\", { token });")).toBe(false); }); }); describe("forwardedClientIpHeaders is used on every mobile-api call path (task 7)", () => { it("every server file that reads MOBILE_API_BASE_URL either calls callMobileApi or imports forwardedClientIpHeaders", () => { const offenders = directFetchFiles(join(PORTAL_ROOT, "app")) .filter(f => missingForwardedIpCoverage(readFileSync(f, "utf8"))) .map(f => relative(PORTAL_ROOT, f)); expect(offenders).toEqual([]); }); }); describe("rawParamOffences", () => { it("flags each raw shape", () => { expect(rawParamOffences("const { id } = await params;\ncall(`/api/admin/roles/${id}`);")).not.toEqual([]); expect(rawParamOffences("const { uuid } = await ctx.params;\ncall(`/api/x/${uuid}/y`);")).not.toEqual([]); expect(rawParamOffences("const { a, b: code } = await props.params;\ncall(`/api/x/${code}`);")).not.toEqual([]); expect(rawParamOffences("const sub = (await ctx.params).path.join(\"/\");\ncall(`/api/x/${sub}`);")).not.toEqual([]); expect(rawParamOffences("const { path } = await params;\ncall(`/api/x/${path.join(\"/\")}`);")).not.toEqual([]); expect(rawParamOffences("const p = await params;\ncall(`/api/x/${p.id}`);")).not.toEqual([]); expect(rawParamOffences("let { id } = await params;\ncall(`/api/x/${id}`);")).not.toEqual([]); expect(rawParamOffences("const { id } = (await params) as { id: string };\ncall(`/api/x/${id}`);")).not.toEqual([]); }); it("accepts encoded values", () => { expect(rawParamOffences("const { id } = await params;\ncall(`/api/admin/roles/${encodeURIComponent(id)}`);")).toEqual([]); expect( rawParamOffences("const sub = (await ctx.params).path.map(encodeURIComponent).join(\"/\");\ncall(`/api/x/${sub}`);"), ).toEqual([]); expect(rawParamOffences("const { id } = await params;\nconst n = Number(id);\ncall(`/api/x/${n}`);")).toEqual([]); expect(rawParamOffences("const { stub } = await params;\nlookup(`/${stub.map(encodeURIComponent).join(\"/\")}`);")).toEqual([]); }); });