import "server-only"; import type { NextRequest } from "next/server"; // Client-context propagation for the admin auth path (openspec/changes/add-admin-login-security): // the real client's IP and user-agent are visible only at this BFF, so the login/logout handlers // capture them and forward them to mobile-api as X-Client-Ip / X-Client-User-Agent. mobile-api // propagates them downstream so services-auth / services-system can stamp the login_audit row // with the true client instead of the BFF. export const CLIENT_IP_HEADER = "X-Client-Ip"; export const CLIENT_USER_AGENT_HEADER = "X-Client-User-Agent"; /** Headers carrying the real client IP + user-agent, empty when not derivable. */ export function clientContextHeaders(req: NextRequest): Record { const headers: Record = {}; const ip = clientIp(req); if (ip) headers[CLIENT_IP_HEADER] = ip; const ua = req.headers.get("user-agent"); if (ua) headers[CLIENT_USER_AGENT_HEADER] = ua; return headers; } /** * The client address as the ingress saw it: the LAST x-forwarded-for entry (the hop the ingress adds), else * x-real-ip. Earlier entries are written by the client and ignored (trust-ingress-client-ip, F33; the storefront rate * limiter uses the same rule). Correct whether the ingress overwrites the header or appends to it. */ export function clientIp(req: NextRequest): string { const forwarded = req.headers.get("x-forwarded-for"); if (forwarded) { const hops = forwarded.split(",").map(hop => hop.trim()).filter(Boolean); if (hops.length > 0) return hops[hops.length - 1]; } return req.headers.get("x-real-ip")?.trim() ?? ""; } /** * Read the incoming request's X-Forwarded-For header from the server-side request context * and return an object with X-Client-Ip set to the last entry (or {} when absent / no request). * Never throws — returns {} on error so callers can spread it into fetch headers safely. */ export async function forwardedClientIpHeaders(): Promise> { try { const { headers } = await import("next/headers"); const h = await headers(); const xff = h.get("x-forwarded-for"); if (xff) { const hops = xff.split(",").map((hop: string) => hop.trim()).filter(Boolean); if (hops.length > 0) return { [CLIENT_IP_HEADER]: hops[hops.length - 1] }; } return {}; } catch { // No request context (e.g. build time) — return empty headers. return {}; } }