import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ loadTelephonyContext: vi.fn(), requireTelephonyPermission: vi.fn(), buildAircallInstallUrl: vi.fn(), completeAircallOAuthCallback: vi.fn(), verifyAircallOAuthState: vi.fn(), runAuthenticatedProviderOAuthCallback: vi.fn(), validateCSRFToken: vi.fn(), getUserInfo: vi.fn(), getMyTenants: vi.fn(), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: () => Promise.resolve({ t: (key: string) => key }), })); vi.mock("~/modules/telephony/routes/telephonyAccess.server", () => ({ TELEPHONY_PERMISSIONS: { manage: "telephony.manage" }, loadTelephonyContext: mocks.loadTelephonyContext, requireTelephonyPermission: mocks.requireTelephonyPermission, })); vi.mock("~/modules/telephony/services/AircallConnectionService.server", () => ({ AircallConnectError: class AircallConnectError extends Error { readonly code: string; constructor(code: string) { super(code); this.code = code; } }, buildAircallInstallUrl: mocks.buildAircallInstallUrl, completeAircallOAuthCallback: mocks.completeAircallOAuthCallback, })); vi.mock("~/modules/telephony/services/aircallOAuthState.server", () => ({ verifyAircallOAuthState: mocks.verifyAircallOAuthState, })); vi.mock("~/utils/integrations/providerOAuthCallbackAccess.server", () => ({ ProviderOAuthCallbackAccessError: class ProviderOAuthCallbackAccessError extends Error {}, runAuthenticatedProviderOAuthCallback: mocks.runAuthenticatedProviderOAuthCallback, })); vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken, getUserInfo: mocks.getUserInfo, })); vi.mock("~/utils/db/tenants.db.server", () => ({ getMyTenants: mocks.getMyTenants, })); import { loader as callbackLoader } from "./integrations.aircall.oauth.callback"; import { action as installAction, loader as installLoader } from "./integrations.aircall.oauth.install"; const STATE_PAYLOAD = { tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", connectionId: "connection-1", nonce: "nonce-1", createdAt: Date.now(), } as const; const CONTEXT = { tenantId: "tenant-1", userId: "user-1", tenantUserId: "membership-1", permissions: ["telephony.manage"], hasModule: true, } as const; beforeEach(() => { vi.clearAllMocks(); mocks.loadTelephonyContext.mockResolvedValue(CONTEXT); mocks.requireTelephonyPermission.mockImplementation((ctx: unknown) => ctx); mocks.buildAircallInstallUrl.mockResolvedValue("https://dashboard.aircall.test/oauth/authorize?state=signed"); mocks.completeAircallOAuthCallback.mockResolvedValue({ tenantId: "tenant-1", tenantSlug: "acme", dataConnectionId: "connection-1", telephonyConnectionId: "telephony-1", providerUserCount: 1, autoBoundUserCount: 1, }); mocks.verifyAircallOAuthState.mockReturnValue({ ok: true, payload: STATE_PAYLOAD }); mocks.runAuthenticatedProviderOAuthCallback.mockImplementation(async ({ callback }: { callback: () => Promise }) => callback()); mocks.validateCSRFToken.mockResolvedValue(undefined); mocks.getUserInfo.mockResolvedValue({ userId: "user-1" }); mocks.getMyTenants.mockResolvedValue([ { id: "tenant-1", name: "Acme", slug: "acme" }, { id: "tenant-2", name: "Beta", slug: "beta" }, ]); }); describe("Aircall OAuth public routes", () => { it("starts install only through a CSRF-protected POST for the authenticated active tenant manager", async () => { const request = new Request("https://app.example.test/integrations/aircall/oauth/install?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "csrf-token" }), }); const response = await installAction({ request } as never); expect(response.status).toBe(302); expect(response.headers.get("location")).toBe("https://dashboard.aircall.test/oauth/authorize?state=signed"); expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() }); expect(mocks.loadTelephonyContext).toHaveBeenCalledWith({ request, params: { tenant: "acme" }, requireModule: true, }); expect(mocks.requireTelephonyPermission).toHaveBeenCalledWith(CONTEXT, "telephony.manage"); expect(mocks.runAuthenticatedProviderOAuthCallback).toHaveBeenCalledWith({ request, tenantId: "tenant-1", userId: "user-1", callback: expect.any(Function), }); expect(mocks.buildAircallInstallUrl).toHaveBeenCalledWith({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", }); }); it("does not resolve tenant access when install lacks a tenant", async () => { const request = new Request("https://app.example.test/integrations/aircall/oauth/install", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "csrf-token" }), }); const response = await installAction({ request, } as never).catch((error: unknown) => error); expect(response).toBeInstanceOf(Response); expect((response as Response).status).toBe(404); expect(mocks.loadTelephonyContext).not.toHaveBeenCalled(); }); it("serves a read-only Marketplace GET confirmation without reserving a connection slot", async () => { const request = new Request("https://app.example.test/integrations/aircall/oauth/install?tenant=acme"); const response = await installLoader({ request } as never); expect(response.status).toBe(200); await expect(response.json()).resolves.toMatchObject({ mode: "confirm", tenantSlug: "acme", settingsHref: "/acme/settings/integrations/telephony", }); expect(mocks.loadTelephonyContext).toHaveBeenCalledWith({ request, params: { tenant: "acme" }, requireModule: true, }); expect(mocks.requireTelephonyPermission).toHaveBeenCalledWith(CONTEXT, "telephony.manage"); expect(mocks.validateCSRFToken).not.toHaveBeenCalled(); expect(mocks.buildAircallInstallUrl).not.toHaveBeenCalled(); }); it("continues Marketplace GET through an in-route tenant selection into the protected Aircall authorize POST", async () => { const request = new Request("https://app.example.test/integrations/aircall/oauth/install"); const response = await installLoader({ request } as never); expect(response.status).toBe(200); const data = await response.json(); expect(data).toMatchObject({ mode: "entry", authenticated: true, loginHref: "/login?redirectTo=%2Fintegrations%2Faircall%2Foauth%2Finstall", tenants: [ { id: "tenant-1", name: "Acme", slug: "acme" }, { id: "tenant-2", name: "Beta", slug: "beta" }, ], }); expect(mocks.getUserInfo).toHaveBeenCalledWith(request); expect(mocks.getMyTenants).toHaveBeenCalledWith("user-1"); expect(mocks.loadTelephonyContext).not.toHaveBeenCalled(); expect(mocks.buildAircallInstallUrl).not.toHaveBeenCalled(); const selectedTenant = data.tenants[0] as { slug: string }; const postRequest = new Request("https://app.example.test/integrations/aircall/oauth/install", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "csrf-token", tenant: selectedTenant.slug }), }); const postResponse = await installAction({ request: postRequest } as never); expect(postResponse.status).toBe(302); expect(postResponse.headers.get("location")).toBe("https://dashboard.aircall.test/oauth/authorize?state=signed"); expect(mocks.validateCSRFToken).toHaveBeenCalledWith(postRequest, { formData: expect.anything() }); expect(mocks.loadTelephonyContext).toHaveBeenCalledWith({ request: postRequest, params: { tenant: "acme" }, requireModule: true, }); expect(mocks.requireTelephonyPermission).toHaveBeenCalledWith(CONTEXT, "telephony.manage"); expect(mocks.buildAircallInstallUrl).toHaveBeenCalledWith({ tenantId: "tenant-1", tenantSlug: "acme", userId: "user-1", }); }); it("returns a safe login continuation without listing tenants for an unauthenticated Marketplace GET", async () => { mocks.getUserInfo.mockResolvedValueOnce({}); const request = new Request("https://app.example.test/integrations/aircall/oauth/install"); const response = await installLoader({ request } as never); await expect(response.json()).resolves.toMatchObject({ mode: "entry", authenticated: false, loginHref: "/login?redirectTo=%2Fintegrations%2Faircall%2Foauth%2Finstall", tenants: [], }); expect(mocks.getMyTenants).not.toHaveBeenCalled(); }); it("rejects an invalid install CSRF token before tenant access or slot reservation", async () => { mocks.validateCSRFToken.mockRejectedValueOnce(new Error("invalid csrf")); const request = new Request("https://app.example.test/integrations/aircall/oauth/install?tenant=acme", { method: "POST", body: new URLSearchParams({ intent: "connect", csrf: "invalid" }), }); await expect(installAction({ request } as never)).rejects.toThrow("invalid csrf"); expect(mocks.loadTelephonyContext).not.toHaveBeenCalled(); expect(mocks.buildAircallInstallUrl).not.toHaveBeenCalled(); }); it("rejects invalid state before session, permission and token exchange", async () => { mocks.verifyAircallOAuthState.mockReturnValue({ ok: false, reason: "bad-signature" }); const response = await callbackLoader({ request: new Request("https://app.example.test/integrations/aircall/oauth/callback?code=code&state=tampered"), } as never); expect(response.status).toBe(302); expect(response.headers.get("location")).toBe("/?aircall=error"); expect(mocks.runAuthenticatedProviderOAuthCallback).not.toHaveBeenCalled(); expect(mocks.loadTelephonyContext).not.toHaveBeenCalled(); expect(mocks.completeAircallOAuthCallback).not.toHaveBeenCalled(); }); it("re-checks active session, module and telephony.manage inside the callback", async () => { const request = new Request("https://app.example.test/integrations/aircall/oauth/callback?code=one-time-code&state=signed"); const response = await callbackLoader({ request } as never); expect(response.status).toBe(302); expect(response.headers.get("location")).toBe("/acme/settings/integrations/telephony?aircall=connected"); expect(mocks.runAuthenticatedProviderOAuthCallback).toHaveBeenCalledWith({ request, tenantId: "tenant-1", userId: "user-1", callback: expect.any(Function), }); expect(mocks.loadTelephonyContext).toHaveBeenCalledWith({ request, params: { tenant: "acme" }, requireModule: true, }); expect(mocks.requireTelephonyPermission).toHaveBeenCalledWith(CONTEXT, "telephony.manage"); expect(mocks.completeAircallOAuthCallback).toHaveBeenCalledWith({ code: "one-time-code", state: "signed" }); expect(mocks.requireTelephonyPermission.mock.invocationCallOrder[0]).toBeLessThan(mocks.completeAircallOAuthCallback.mock.invocationCallOrder[0]!); }); it("does not exchange a token when callback permission is no longer present", async () => { mocks.requireTelephonyPermission.mockImplementation(() => { throw new Error("not found"); }); const response = await callbackLoader({ request: new Request("https://app.example.test/integrations/aircall/oauth/callback?code=one-time-code&state=signed"), } as never); expect(response.status).toBe(302); expect(response.headers.get("location")).toBe("/acme/settings/integrations/telephony?aircall=error"); expect(mocks.completeAircallOAuthCallback).not.toHaveBeenCalled(); }); });