Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
166 lines
6.0 KiB
TypeScript
166 lines
6.0 KiB
TypeScript
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<string, string>;
|
|
/** 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<string, string | number | boolean> | 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<string, unknown>);
|
|
const scalar = values.every(v => typeof v === "string" || typeof v === "number" || typeof v === "boolean");
|
|
return scalar ? (details as Record<string, string | number | boolean>) : undefined;
|
|
}
|
|
|
|
function extractError(parsed: unknown): string | undefined {
|
|
if (parsed && typeof parsed === "object") {
|
|
const o = parsed as Record<string, unknown>;
|
|
// 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;
|
|
}
|
|
|
|
export async function callMobileApi<T>(
|
|
path: string,
|
|
opts: MobileCallOptions = {},
|
|
): Promise<ApiResult<T>> {
|
|
if (isTraversalPath(path)) {
|
|
return { 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 { ok: false, error: "Mobile API is not configured" };
|
|
}
|
|
|
|
const forwardedIp = await forwardedClientIpHeaders();
|
|
|
|
const headers: Record<string, string> = {
|
|
"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";
|
|
|
|
let res: Response;
|
|
try {
|
|
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 {
|
|
ok: false,
|
|
error: "The server is taking too long to respond. Please try again.",
|
|
timedOut: true,
|
|
};
|
|
}
|
|
return { ok: false, error: "Unable to reach the server. Please try again." };
|
|
}
|
|
|
|
const raw = await res.text();
|
|
let parsed: unknown = undefined;
|
|
if (raw) {
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch {
|
|
parsed = raw;
|
|
}
|
|
}
|
|
|
|
if (!res.ok) {
|
|
if (isExpiredSignal(res.status, raw)) {
|
|
return {
|
|
ok: false,
|
|
error: "Your session has expired. Please sign in again.",
|
|
status: res.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: res.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 } : {}),
|
|
};
|
|
}
|
|
|
|
// 2xx, but the body may still encode a logical failure.
|
|
if (parsed && typeof parsed === "object") {
|
|
const obj = parsed as Record<string, unknown>;
|
|
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 };
|
|
}
|