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
339 lines
13 KiB
TypeScript
339 lines
13 KiB
TypeScript
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
|
import { readFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { callMobileApi } from "./mobileApi";
|
|
|
|
const BASE = "https://mobile.example.test";
|
|
const KEY = "test-api-key";
|
|
|
|
function makeRes(body: string, init: { ok?: boolean; status?: number } = {}) {
|
|
return {
|
|
ok: init.ok ?? true,
|
|
status: init.status ?? 200,
|
|
text: async () => body,
|
|
} as Response;
|
|
}
|
|
|
|
let fetchMock: ReturnType<typeof vi.fn>;
|
|
|
|
beforeEach(() => {
|
|
vi.stubEnv("MOBILE_API_BASE_URL", BASE);
|
|
vi.stubEnv("MOBILE_API_KEY", KEY);
|
|
fetchMock = vi.fn();
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
vi.unstubAllEnvs();
|
|
});
|
|
|
|
describe("callMobileApi", () => {
|
|
it("targets the base URL and injects the api-key header", async () => {
|
|
fetchMock.mockResolvedValue(makeRes(JSON.stringify({ value: 1 })));
|
|
await callMobileApi("/api/admin/me");
|
|
|
|
const [url, init] = fetchMock.mock.calls[0];
|
|
expect(url).toBe(`${BASE}/api/admin/me`);
|
|
const headers = new Headers(init.headers);
|
|
expect(headers.get("api-key")).toBe(KEY);
|
|
expect(headers.get("authorization")).toBeNull();
|
|
});
|
|
|
|
it("forwards the bearer token when provided", async () => {
|
|
fetchMock.mockResolvedValue(makeRes("{}"));
|
|
await callMobileApi("/api/admin/me", { token: "jwt-123" });
|
|
|
|
const [, init] = fetchMock.mock.calls[0];
|
|
const headers = new Headers(init.headers);
|
|
expect(headers.get("authorization")).toBe("Bearer jwt-123");
|
|
});
|
|
|
|
it('normalizes {result:"false", errorMessage} to an error', async () => {
|
|
fetchMock.mockResolvedValue(
|
|
makeRes(JSON.stringify({ result: "false", errorMessage: "Invalid username or password. " })),
|
|
);
|
|
const r = await callMobileApi("/api/admin/auth/login", { method: "POST", body: {} });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.error).toContain("Invalid username or password");
|
|
});
|
|
|
|
it("extracts RFC-7807 problem+json 'detail' as the error, not the raw JSON body", async () => {
|
|
// solvway-mobile-api throws ResponseStatusException, which Spring renders as an
|
|
// application/problem+json body: {type,title,status,detail,instance}. The page shows
|
|
// r.error inline, so it must be the human 'detail', never the serialized document.
|
|
fetchMock.mockResolvedValue(
|
|
makeRes(
|
|
JSON.stringify({
|
|
type: "about:blank",
|
|
title: "Conflict",
|
|
status: 409,
|
|
detail: "already exists: MEMBER",
|
|
instance: "/api/admin/catalog/priceType",
|
|
}),
|
|
{ ok: false, status: 409 },
|
|
),
|
|
);
|
|
const r = await callMobileApi("/api/admin/catalog/priceType", { method: "POST", body: {} });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) {
|
|
expect(r.error).toBe("already exists: MEMBER");
|
|
expect(r.status).toBe(409);
|
|
}
|
|
});
|
|
|
|
it("extracts the admin endpoints' {error} body as the error, not the raw JSON (babyboo-42)", async () => {
|
|
// AdminMemberController (register, profile edit, sponsor change, rank correction) answers
|
|
// 400/500 with {"error": "<message>"}; the form must show the message, never the JSON.
|
|
fetchMock.mockResolvedValue(
|
|
makeRes(JSON.stringify({ error: "This email is already registered. " }), { ok: false, status: 400 }),
|
|
);
|
|
const r = await callMobileApi("/api/admin/members", { method: "POST", body: {} });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) {
|
|
expect(r.error).toBe("This email is already registered. ");
|
|
expect(r.status).toBe(400);
|
|
}
|
|
});
|
|
|
|
it("falls back to problem+json 'title' when 'detail' is absent", async () => {
|
|
fetchMock.mockResolvedValue(
|
|
makeRes(
|
|
JSON.stringify({ type: "about:blank", title: "Unprocessable Entity", status: 422 }),
|
|
{ ok: false, status: 422 },
|
|
),
|
|
);
|
|
const r = await callMobileApi("/api/admin/catalog/priceType", { method: "POST", body: {} });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.error).toBe("Unprocessable Entity");
|
|
});
|
|
|
|
it("carries the machine-readable code of a 403 PASSWORD_RESET_REQUIRED", async () => {
|
|
fetchMock.mockResolvedValue(
|
|
makeRes(JSON.stringify({ message: "PASSWORD_RESET_REQUIRED", code: "PASSWORD_RESET_REQUIRED" }), {
|
|
ok: false,
|
|
status: 403,
|
|
}),
|
|
);
|
|
const r = await callMobileApi("/api/admin/members");
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.code).toBe("PASSWORD_RESET_REQUIRED");
|
|
});
|
|
|
|
it("surfaces extra fields via extra", async () => {
|
|
fetchMock.mockResolvedValue(
|
|
makeRes(JSON.stringify({ success: false, someFlag: true })),
|
|
);
|
|
const r = await callMobileApi("/api/admin/auth/login", { method: "POST", body: {} });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.extra?.someFlag).toBe(true);
|
|
});
|
|
|
|
it("flags an expired token (HTTP 500 Expired Token)", async () => {
|
|
fetchMock.mockResolvedValue(makeRes("Expired Token", { ok: false, status: 500 }));
|
|
const r = await callMobileApi("/api/admin/me", { token: "old" });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.expired).toBe(true);
|
|
});
|
|
|
|
it("returns parsed JSON on success", async () => {
|
|
fetchMock.mockResolvedValue(makeRes(JSON.stringify({ name: "Admin User" })));
|
|
const r = await callMobileApi<{ name: string }>("/api/admin/me", { token: "jwt" });
|
|
expect(r.ok).toBe(true);
|
|
if (r.ok) expect(r.data.name).toBe("Admin User");
|
|
});
|
|
|
|
it("passes an abort signal to fetch so requests cannot hang forever", async () => {
|
|
fetchMock.mockResolvedValue(makeRes("{}"));
|
|
await callMobileApi("/api/admin/me", { timeoutMs: 5000 });
|
|
const [, init] = fetchMock.mock.calls[0];
|
|
expect(init.signal).toBeInstanceOf(AbortSignal);
|
|
});
|
|
|
|
it("returns a timeout error (timedOut flag) when the upstream call aborts", async () => {
|
|
fetchMock.mockRejectedValue(new DOMException("The operation timed out.", "TimeoutError"));
|
|
const r = await callMobileApi("/api/admin/auth/login", { method: "POST", body: {} });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) {
|
|
expect(r.timedOut).toBe(true);
|
|
expect(r.error).toContain("taking too long");
|
|
}
|
|
});
|
|
|
|
describe("missing configuration", () => {
|
|
it("returns a not-configured error and attempts no fetch when MOBILE_API_KEY is unset", async () => {
|
|
vi.stubEnv("MOBILE_API_KEY", "");
|
|
const r = await callMobileApi("/api/admin/me");
|
|
expect(r).toEqual({ ok: false, error: "Mobile API is not configured" });
|
|
expect(fetchMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns a not-configured error and attempts no fetch when MOBILE_API_BASE_URL is unset", async () => {
|
|
vi.stubEnv("MOBILE_API_BASE_URL", "");
|
|
const r = await callMobileApi("/api/admin/me");
|
|
expect(r).toEqual({ ok: false, error: "Mobile API is not configured" });
|
|
expect(fetchMock).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
});
|
|
|
|
// Static source checks: the api-key must never be readable from a client
|
|
// bundle. These guard the module itself; task 6.5 later greps the whole
|
|
// portal to confirm no other module has grown a second reference.
|
|
describe("module source (server-only guarantees)", () => {
|
|
const src = readFileSync(join(__dirname, "mobileApi.ts"), "utf8");
|
|
|
|
it("imports server-only", () => {
|
|
expect(src).toMatch(/^import "server-only";/m);
|
|
});
|
|
|
|
it("never references NEXT_PUBLIC_MOBILE", () => {
|
|
expect(src).not.toMatch(/NEXT_PUBLIC_MOBILE/);
|
|
});
|
|
|
|
it("is the module that reads MOBILE_API_KEY, and apiRoute.ts does not", () => {
|
|
expect(src).toMatch(/MOBILE_API_KEY/);
|
|
const apiRouteSrc = readFileSync(join(__dirname, "apiRoute.ts"), "utf8");
|
|
expect(apiRouteSrc).not.toMatch(/MOBILE_API_KEY/);
|
|
});
|
|
});
|
|
|
|
describe("callMobileApi — error list (add-shipping-rates)", () => {
|
|
it("keeps an upstream 'errors' string list on a 4xx", async () => {
|
|
fetchMock.mockResolvedValue(new Response(JSON.stringify({ message: "Rates not saved", errors: ["Row 3: gap after 1 kg"] }), { status: 400 }));
|
|
const r = await callMobileApi("/api/admin/shipping/rate-cards/3/rates", { method: "PUT", body: {}, token: "t" });
|
|
expect(r).toMatchObject({ ok: false, status: 400, error: "Rates not saved", errors: ["Row 3: gap after 1 kg"] });
|
|
});
|
|
|
|
it("adds no errors key when the upstream sends none", async () => {
|
|
fetchMock.mockResolvedValue(new Response(JSON.stringify({ message: "nope" }), { status: 409 }));
|
|
const r = await callMobileApi("/api/admin/shipping/zones", { method: "POST", body: {}, token: "t" });
|
|
expect(r).not.toHaveProperty("errors");
|
|
});
|
|
});
|
|
|
|
describe("callMobileApi — coded error details (BABYBOO-39)", () => {
|
|
it("keeps an upstream 'details' object of scalars with its code on a 4xx", async () => {
|
|
fetchMock.mockResolvedValue(
|
|
new Response(
|
|
JSON.stringify({
|
|
message: "Insufficient stock for sku_variation 50: available 0, requested 10, shortfall 10",
|
|
code: "INSUFFICIENT_STOCK",
|
|
details: { skuVariationId: 50, available: 0, requested: 10 },
|
|
}),
|
|
{ status: 400 },
|
|
),
|
|
);
|
|
const r = await callMobileApi("/api/admin/stock/transfer", { method: "POST", body: {}, token: "t" });
|
|
expect(r).toMatchObject({
|
|
ok: false,
|
|
status: 400,
|
|
code: "INSUFFICIENT_STOCK",
|
|
details: { skuVariationId: 50, available: 0, requested: 10 },
|
|
});
|
|
});
|
|
|
|
it("accepts string and boolean detail values", async () => {
|
|
fetchMock.mockResolvedValue(
|
|
new Response(JSON.stringify({ message: "x", details: { a: "s", b: true } }), { status: 400 }),
|
|
);
|
|
const r = await callMobileApi("/x", { token: "t" });
|
|
expect(r).toMatchObject({ details: { a: "s", b: true } });
|
|
});
|
|
|
|
it.each([
|
|
["an array", [1, 2]],
|
|
["a nested object", { a: { b: 1 } }],
|
|
["a null value", { a: null }],
|
|
["a string", "nope"],
|
|
["null", null],
|
|
])("ignores details that is %s", async (_label, details) => {
|
|
fetchMock.mockResolvedValue(new Response(JSON.stringify({ message: "x", details }), { status: 400 }));
|
|
const r = await callMobileApi("/x", { token: "t" });
|
|
expect(r).not.toHaveProperty("details");
|
|
});
|
|
|
|
it("adds no details key when the upstream sends none", async () => {
|
|
fetchMock.mockResolvedValue(new Response(JSON.stringify({ message: "nope" }), { status: 409 }));
|
|
const r = await callMobileApi("/x", { token: "t" });
|
|
expect(r).not.toHaveProperty("details");
|
|
});
|
|
});
|
|
|
|
describe("callMobileApi dot-segment guard (F01)", () => {
|
|
const refused = [
|
|
"/api/member/orders/../../admin/members",
|
|
"/api/member/orders/./x",
|
|
"/api/member/orders/%2E%2E/profile",
|
|
"/api/member/orders/%2e%2e/profile",
|
|
"/api/member/orders/%2e/x",
|
|
"/api/member/orders/..\\profile",
|
|
"/api/member/orders/%5C/profile",
|
|
"/api/member/orders/%5c/profile",
|
|
"/api/member/orders/..?x=1",
|
|
"/api/member/orders/..#frag",
|
|
"/api/member/orders/..;/..;/admin/members",
|
|
"/api/member/orders/..;x/profile",
|
|
"/api/member/orders/%2e%2e;x/profile",
|
|
"/api/member/orders/.;/x",
|
|
"/api/member/orders/..%3B/profile",
|
|
];
|
|
|
|
it.each(refused)("refuses %s without calling upstream", async path => {
|
|
const r = await callMobileApi(path, { token: "jwt" });
|
|
expect(fetchMock).not.toHaveBeenCalled();
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) {
|
|
expect(r.status).toBe(400);
|
|
expect(typeof r.error).toBe("string");
|
|
expect(r.error.length).toBeGreaterThan(0);
|
|
}
|
|
});
|
|
|
|
it("allows dots inside a normal segment or the query string, sent unchanged", async () => {
|
|
fetchMock.mockResolvedValue(makeRes("{}"));
|
|
const path = "/api/member/orders/abc.def?next=../x&v=1.2";
|
|
await callMobileApi(path);
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
expect(fetchMock.mock.calls[0][0]).toBe(`${BASE}${path}`);
|
|
});
|
|
|
|
it("allows a path parameter on a non-dot segment, sent unchanged", async () => {
|
|
fetchMock.mockResolvedValue(makeRes("{}"));
|
|
const path = "/api/member/orders/abc;v=1";
|
|
await callMobileApi(path);
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
expect(fetchMock.mock.calls[0][0]).toBe(`${BASE}${path}`);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// X-Client-Ip forwarding (task 7a)
|
|
// ---------------------------------------------------------------------------
|
|
let headersMockFn: { get: (k: string) => string | null };
|
|
vi.mock("next/headers", () => ({
|
|
headers: () => headersMockFn,
|
|
}));
|
|
|
|
describe("callMobileApi — X-Client-Ip forwarding", () => {
|
|
beforeEach(() => {
|
|
headersMockFn = { get: () => null };
|
|
});
|
|
|
|
it("adds X-Client-Ip when the incoming request has X-Forwarded-For", async () => {
|
|
headersMockFn = { get: (k: string) => k === "x-forwarded-for" ? "198.51.100.1, 203.0.113.7" : null };
|
|
fetchMock.mockResolvedValue(makeRes("{}"));
|
|
await callMobileApi("/api/admin/me");
|
|
const headers = new Headers((fetchMock.mock.calls[0][1] as { headers: Record<string, string> }).headers);
|
|
expect(headers.get("X-Client-Ip")).toBe("203.0.113.7");
|
|
});
|
|
|
|
it("does not add X-Client-Ip when there is no X-Forwarded-For", async () => {
|
|
headersMockFn = { get: () => null };
|
|
fetchMock.mockResolvedValue(makeRes("{}"));
|
|
await callMobileApi("/api/admin/me");
|
|
const headers = new Headers((fetchMock.mock.calls[0][1] as { headers: Record<string, string> }).headers);
|
|
expect(headers.get("X-Client-Ip")).toBeNull();
|
|
});
|
|
});
|