feat: whatsapp portal proxy, client service and polling hook

Part of tasks 5.1/5.2 (not ticked): one catch-all proxy at /api/whatsapp (media
served with nosniff and a sandbox CSP), typed client calls, and usePolling that
pauses while the tab is hidden.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-02 11:03:56 +08:00
1 parent 13b692748c
commit 1d5e792e3d
5 files changed
+305

No files matched your search

@@ -0,0 +1,72 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), callMobileApiBinary: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi, callMobileApiBinary: mocks.callMobileApiBinary }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET, POST } from "./route";
type Req = Parameters<typeof GET>[0];
const ctx = (...path: string[]) => ({ params: Promise.resolve({ path: path.length ? path : undefined }) });
const req = (url: string, init?: RequestInit) => new Request(`http://localhost${url}`, init) as unknown as Req;
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.callMobileApiBinary.mockReset();
mocks.getToken.mockReset();
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } });
});
describe("/api/whatsapp/[[...path]]", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET(req("/api/whatsapp/conversations"), ctx("conversations"))).status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards GETs with the query string", async () => {
await GET(req("/api/whatsapp/conversations?tab=mine&q=ais"), ctx("conversations"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/whatsapp/conversations?tab=mine&q=ais", { token: "jwt-abc" });
});
it("forwards POST bodies", async () => {
await POST(req("/api/whatsapp/conversations/c1/messages", { method: "POST", body: JSON.stringify({ text: "hi" }) }), ctx("conversations", "c1", "messages"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/whatsapp/conversations/c1/messages", { method: "POST", body: { text: "hi" }, token: "jwt-abc" });
});
it("answers an empty upstream body as JSON null", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: true, data: undefined });
const res = await POST(req("/api/whatsapp/conversations/c1/read", { method: "POST" }), ctx("conversations", "c1", "read"));
expect(res.status).toBe(200);
expect(await res.json()).toBeNull();
});
it("rejects dot segments", async () => {
expect((await GET(req("/api/whatsapp/x"), ctx("..", "users"))).status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("passes upstream errors with their code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "The 24-hour window has closed. Send a template.", status: 409, code: "WINDOW_CLOSED" });
const res = await POST(req("/api/whatsapp/conversations/c1/messages", { method: "POST", body: "{}" }), ctx("conversations", "c1", "messages"));
expect(res.status).toBe(409);
expect(((await res.json()) as Record<string, unknown>).code).toBe("WINDOW_CLOSED");
});
it("serves media as bytes that cannot run as a page", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: true, data: { body: new Uint8Array([1, 2]).buffer, contentType: "text/html", contentDisposition: "attachment" } });
const res = await GET(req("/api/whatsapp/media/m1"), ctx("media", "m1"));
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/whatsapp/media/m1", { token: "jwt-abc" });
expect(res.headers.get("Content-Type")).toBe("text/html");
expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff");
expect(res.headers.get("Content-Security-Policy")).toBe("sandbox");
expect(res.headers.get("Content-Disposition")).toBe("attachment");
expect(res.headers.get("Cache-Control")).toBe("private, no-store");
});
it("passes a media 410 through", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: false, error: "Media expired", status: 410, code: "MEDIA_EXPIRED" });
expect((await GET(req("/api/whatsapp/media/m1"), ctx("media", "m1"))).status).toBe(410);
});
});
@@ -0,0 +1,41 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi, callMobileApiBinary } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// One proxy for every /api/admin/whatsapp endpoint; mobile-api owns validation and the BO_WHATSAPP guards.
type Ctx = { params: Promise<{ path?: string[] }> };
async function forward(req: NextRequest, { params }: Ctx, method?: "POST") {
const token = await getToken();
if (!token) return unauthorized();
const { path = [] } = await params;
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
const target = `/api/admin/whatsapp${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
if (!method && path[0] === "media") {
// ponytail: buffers the file (mobile-api caps it at 100 MB); stream the upstream body if large documents become common.
const media = await callMobileApiBinary(target, { token });
if (!media.ok) return errorResponse(media);
const { body, contentType, contentDisposition } = media.data;
return new NextResponse(body, {
headers: {
"Content-Type": contentType ?? "application/octet-stream",
...(contentDisposition ? { "Content-Disposition": contentDisposition } : {}),
// The type is whatever the sender declared: never let it run as a page on this origin.
"X-Content-Type-Options": "nosniff",
"Content-Security-Policy": "sandbox",
"Cache-Control": "private, no-store",
},
});
}
const result = method
? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token })
: await callMobileApi<unknown>(target, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data ?? null);
}
export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx);
export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST");
@@ -0,0 +1,51 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderHook } from "@testing-library/react";
import { act } from "react";
import { usePolling } from "./usePolling";
let hidden = false;
beforeEach(() => {
vi.useFakeTimers();
hidden = false;
Object.defineProperty(document, "hidden", { configurable: true, get: () => hidden });
});
afterEach(() => vi.useRealTimers());
describe("usePolling", () => {
it("runs now and then every interval", () => {
const fn = vi.fn();
renderHook(() => usePolling(fn, 1000));
expect(fn).toHaveBeenCalledTimes(1);
act(() => { vi.advanceTimersByTime(3000); });
expect(fn).toHaveBeenCalledTimes(4);
});
it("skips ticks while the tab is hidden and catches up when it shows", () => {
const fn = vi.fn();
renderHook(() => usePolling(fn, 1000));
hidden = true;
act(() => { vi.advanceTimersByTime(3000); });
expect(fn).toHaveBeenCalledTimes(1);
hidden = false;
act(() => { document.dispatchEvent(new Event("visibilitychange")); });
expect(fn).toHaveBeenCalledTimes(2);
});
it("stops after unmount and runs when the named window event fires", () => {
const fn = vi.fn();
const { unmount } = renderHook(() => usePolling(fn, 1000, "whatsapp-unread-changed"));
act(() => { window.dispatchEvent(new Event("whatsapp-unread-changed")); });
expect(fn).toHaveBeenCalledTimes(2);
unmount();
act(() => { vi.advanceTimersByTime(3000); window.dispatchEvent(new Event("whatsapp-unread-changed")); });
expect(fn).toHaveBeenCalledTimes(2);
});
it("does nothing when disabled", () => {
const fn = vi.fn();
renderHook(() => usePolling(fn, 1000, undefined, false));
act(() => { vi.advanceTimersByTime(3000); });
expect(fn).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,28 @@
import { useEffect, useRef } from "react";
/**
* Calls `fn` now, then every `ms` while the tab is visible, again when the tab shows, and whenever the
* optional window event fires. The latest `fn` is used without restarting the timer.
*/
// ponytail: polling (30 s list, 10 s thread); server-sent events if the delay ever matters.
export function usePolling(fn: () => void, ms: number, refreshEvent?: string, enabled = true) {
const latest = useRef(fn);
useEffect(() => {
latest.current = fn;
});
useEffect(() => {
if (!enabled) return;
const run = () => {
if (!document.hidden) latest.current();
};
run();
const id = window.setInterval(run, ms);
document.addEventListener("visibilitychange", run);
if (refreshEvent) window.addEventListener(refreshEvent, run);
return () => {
window.clearInterval(id);
document.removeEventListener("visibilitychange", run);
if (refreshEvent) window.removeEventListener(refreshEvent, run);
};
}, [ms, refreshEvent, enabled]);
}
@@ -0,0 +1,113 @@
import { apiGet, apiPost } from "@/app/lib/clientApi";
export type WhatsAppTab = "mine" | "unassigned" | "all";
export interface WhatsAppConversation {
uuid: string;
companyId: number;
contactWaId: string;
contactName: string | null;
leadUuid: string | null;
leadName: string | null;
ownerUserId: number | null;
ownerName: string | null;
ownerManual: boolean;
lastInboundAt: string | null;
lastMessageAt: string | null;
lastMessagePreview: string | null;
windowOpen: boolean;
unreadCount: number;
}
export interface WhatsAppMessage {
uuid: string;
direction: "IN" | "OUT";
type: string;
body: string | null;
templateName: string | null;
mediaMime: string | null;
mediaFilename: string | null;
locationLat: number | null;
locationLng: number | null;
locationName: string | null;
status: "pending" | "sent" | "delivered" | "read" | "failed" | null;
errorCode: string | null;
errorTitle: string | null;
sentByUserId: number | null;
createdAt: string;
statusAt: string | null;
}
export interface WhatsAppTemplate {
name: string;
language: string;
category: string;
bodyText: string;
paramCount: number;
supported: boolean;
}
export interface WhatsAppPage {
items: WhatsAppConversation[];
total: number;
page: number;
size: number;
}
export interface WhatsAppThread {
conversation: WhatsAppConversation;
messages: WhatsAppMessage[];
hasOlder: boolean;
}
const q = (params: Record<string, string | number | undefined | null>) => {
const s = new URLSearchParams();
for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null && v !== "") s.set(k, String(v));
const out = s.toString();
return out ? `?${out}` : "";
};
const c = (uuid: string) => encodeURIComponent(uuid);
export const listConversations = (tab: WhatsAppTab, search: string, page: number, companyId?: number | null) =>
apiGet<WhatsAppPage>(`/api/whatsapp/conversations${q({ tab, q: search, page, companyId })}`);
export const getThread = (uuid: string, before?: string, companyId?: number | null) =>
apiGet<WhatsAppThread>(`/api/whatsapp/conversations/${c(uuid)}${q({ before, companyId })}`);
export const sendText = (uuid: string, text: string, companyId?: number | null) =>
apiPost<WhatsAppMessage>(`/api/whatsapp/conversations/${c(uuid)}/messages${q({ companyId })}`, { text });
export const sendTemplate = (uuid: string, template: WhatsAppTemplate, params: string[], companyId?: number | null) =>
apiPost<WhatsAppMessage>(`/api/whatsapp/conversations/${c(uuid)}/messages${q({ companyId })}`, {
template: template.name,
language: template.language,
params,
});
export const markRead = (uuid: string, companyId?: number | null) =>
apiPost<null>(`/api/whatsapp/conversations/${c(uuid)}/read${q({ companyId })}`);
export const assignConversation = (uuid: string, userId: number | null, companyId?: number | null) =>
apiPost<WhatsAppConversation>(
`/api/whatsapp/conversations/${c(uuid)}/assign${q({ companyId })}`,
userId === null ? { automatic: true } : { userId },
);
/** Exactly one of leadUuid or eventLeadUuid. */
export const startChat = (target: { leadUuid: string } | { eventLeadUuid: string }) =>
apiPost<WhatsAppConversation>("/api/whatsapp/start", target);
export const listTemplates = (companyId?: number | null) =>
apiGet<WhatsAppTemplate[]>(`/api/whatsapp/templates${q({ companyId })}`);
export const syncTemplates = (companyId?: number | null) =>
apiPost<WhatsAppTemplate[]>(`/api/whatsapp/templates/sync${q({ companyId })}`);
export const unreadCount = () => apiGet<{ count: number }>("/api/whatsapp/unread-count");
export const listAssignees = (companyId?: number | null) =>
apiGet<{ id: number; name: string | null }[]>(`/api/whatsapp/assignees${q({ companyId })}`);
export const mediaUrl = (messageUuid: string, companyId?: number | null) =>
`/api/whatsapp/media/${c(messageUuid)}${q({ companyId })}`;