import "server-only"; import { publicError } from "@/app/lib/server/publicError"; import type { ApiResult } from "@/app/lib/types"; import { isTraversalPath } from "./upstreamPathGuard"; import { forwardedClientIpHeaders } from "./clientContext"; // Server-only client for solvway-mobile-api. Injects the secret `api-key`, // optionally forwards the admin JWT as a bearer, and normalizes the various // upstream response shapes into a single ApiResult. export interface MobileCallOptions { method?: "GET" | "POST" | "PUT" | "DELETE"; body?: unknown; token?: string; headers?: Record; /** Upstream timeout; the mobile-api can block indefinitely (e.g. registerNewMember's * account-creation wait loop), and the UI must never hang on it. */ timeoutMs?: number; } const DEFAULT_TIMEOUT_MS = 30_000; /** The mobile-api signals an expired/invalid JWT with these specific responses. */ function isExpiredSignal(status: number, raw: string): boolean { const t = raw.toLowerCase(); return ( (status === 500 && (t.includes("expired token") || t.includes("invalid token"))) || (status === 400 && t.includes("missing header 'authorization'")) ); } /** An upstream `details` object, kept only when it is a flat object of string/number/boolean values. */ function extractDetails(parsed: unknown): Record | undefined { if (!parsed || typeof parsed !== "object") return undefined; const details = (parsed as { details?: unknown }).details; if (!details || typeof details !== "object" || Array.isArray(details)) return undefined; const values = Object.values(details as Record); const scalar = values.every(v => typeof v === "string" || typeof v === "number" || typeof v === "boolean"); return scalar ? (details as Record) : undefined; } function extractError(parsed: unknown): string | undefined { if (parsed && typeof parsed === "object") { const o = parsed as Record; // Legacy mobile-api shapes carry errorMessage/message; ResponseStatusException is // rendered by Spring as RFC-7807 problem+json ({type,title,status,detail,instance}), // whose human text is `detail` (with `title` as the coarse fallback). The admin member // endpoints answer {error} (AdminMemberController). Without these the whole problem // document would leak into the UI as the "message". return ( (typeof o.error === "string" && o.error) || (o.errorMessage as string) || (o.message as string) || (o.detail as string) || (o.title as string) || undefined ); } if (typeof parsed === "string" && parsed.trim()) return parsed; return undefined; } type Failure = Extract, { ok: false }>; /** The ApiResult failure for a non-2xx upstream response; `raw` is the response body text. */ function upstreamFailure(status: number, raw: string): Failure { let parsed: unknown = undefined; if (raw) { try { parsed = JSON.parse(raw); } catch { parsed = raw; } } if (isExpiredSignal(status, raw)) { return { ok: false, error: "Your session has expired. Please sign in again.", status, expired: true }; } const details = extractDetails(parsed); return { ok: false, // public-error-text (F39): only a business message reaches the browser; a non-JSON body (an HTML error page, // a stack trace) never does. error: publicError(typeof parsed === "object" ? extractError(parsed) : undefined), status, ...(parsed && typeof parsed === "object" && typeof (parsed as { code?: unknown }).code === "string" ? { code: (parsed as { code: string }).code } : {}), ...(parsed && typeof parsed === "object" && Array.isArray((parsed as { errors?: unknown }).errors) && (parsed as { errors: string[] }).errors.every(v => typeof v === "string") ? { errors: (parsed as { errors: string[] }).errors } : {}), ...(details ? { details } : {}), }; } /** Sends the upstream request (guard, config, headers, timeout); a Response or the failure to report. */ async function upstreamFetch(path: string, opts: MobileCallOptions): Promise<{ res: Response } | { fail: Failure }> { if (isTraversalPath(path)) { return { fail: { ok: false, error: "Invalid request path", status: 400 } }; } const base = process.env.MOBILE_API_BASE_URL; const key = process.env.MOBILE_API_KEY; if (!base || !key) { return { fail: { ok: false, error: "Mobile API is not configured" } }; } const forwardedIp = await forwardedClientIpHeaders(); const headers: Record = { "api-key": key, ...opts.headers ?? {}, ...forwardedIp, }; // X-Client-Ip is always the value computed from this request's X-Forwarded-For (spread last), so no caller // header can replace it; login/logout pass the same computed value through clientContextHeaders. if (opts.token) headers["Authorization"] = `Bearer ${opts.token}`; if (opts.body !== undefined) headers["Content-Type"] = "application/json"; try { return { res: await fetch(`${base}${path}`, { method: opts.method ?? "GET", headers, body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, cache: "no-store", signal: AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS), }) }; } catch (err) { if (err instanceof DOMException && (err.name === "TimeoutError" || err.name === "AbortError")) { return { fail: { ok: false, error: "The server is taking too long to respond. Please try again.", timedOut: true } }; } return { fail: { ok: false, error: "Unable to reach the server. Please try again." } }; } } export async function callMobileApi( path: string, opts: MobileCallOptions = {}, ): Promise> { const up = await upstreamFetch(path, opts); if ("fail" in up) return up.fail; const { res } = up; const raw = await res.text(); if (!res.ok) return upstreamFailure(res.status, raw); let parsed: unknown = undefined; if (raw) { try { parsed = JSON.parse(raw); } catch { parsed = raw; } } // 2xx, but the body may still encode a logical failure. if (parsed && typeof parsed === "object") { const obj = parsed as Record; if (obj.result === "false") { return { ok: false, error: publicError((obj.errorMessage as string) || (obj.message as string) || "Request failed"), extra: obj, }; } if (obj.success === false) { return { ok: false, error: publicError((obj.message as string) || "Request failed"), extra: obj, }; } } return { ok: true, data: parsed as T }; } export interface BinaryPayload { body: ArrayBuffer; contentType: string | null; contentDisposition: string | null; } /** GET a binary upstream response (e.g. an xlsx export); failures use the same shape as callMobileApi. */ export async function callMobileApiBinary( path: string, opts: Pick = {}, ): Promise> { const up = await upstreamFetch(path, opts); if ("fail" in up) return up.fail; const { res } = up; if (!res.ok) return upstreamFailure(res.status, await res.text()); return { ok: true, data: { body: await res.arrayBuffer(), contentType: res.headers.get("Content-Type"), contentDisposition: res.headers.get("Content-Disposition"), }, }; }