import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { GRAPH_MAIL_SUBSCRIPTION_LIFETIME_MS, GraphMailError, MICROSOFT_MAIL_SCOPES, buildInitialDeltaUrl, buildMicrosoftAuthorizationUrl, createMailSubscription, deleteMailSubscription, exchangeMicrosoftCodeForTokens, fetchDeltaPage, fetchGraphUserProfile, refreshMicrosoftAccessToken, renewMailSubscription, resolveMicrosoftMailOAuthConfig, sendGraphMail, setGraphMessageRead, } from "./graphMailApi.js"; // VA-P23 — Graph mail client unit tests. All network I/O is mocked; these pin // the request shapes (endpoints, params, bodies) and the Klartext error mapping. const CONFIG = { clientId: "cid", clientSecret: "csecret", redirectUri: "https://app.hivegrid.de/integrations/email/microsoft/oauth/callback", tenant: "common", }; function jsonResponse(status: number, body: unknown): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); } let fetchMock: ReturnType; beforeEach(() => { fetchMock = vi.fn(); vi.stubGlobal("fetch", fetchMock); }); afterEach(() => { vi.unstubAllGlobals(); }); describe("resolveMicrosoftMailOAuthConfig", () => { it("returns null when any env key is missing", () => { expect(resolveMicrosoftMailOAuthConfig({})).toBeNull(); }); it("defaults the AAD tenant to common", () => { const config = resolveMicrosoftMailOAuthConfig({ MICROSOFT_MAIL_CLIENT_ID: "cid", MICROSOFT_MAIL_CLIENT_SECRET: "cs", MICROSOFT_MAIL_REDIRECT_URI: "https://app.hivegrid.de/cb", }); expect(config?.tenant).toBe("common"); }); }); describe("buildMicrosoftAuthorizationUrl", () => { it("targets the v2 authorize endpoint with the mail scopes", () => { const url = new URL(buildMicrosoftAuthorizationUrl(CONFIG, "signed-state")); expect(url.origin + url.pathname).toBe("https://login.microsoftonline.com/common/oauth2/v2.0/authorize"); expect(url.searchParams.get("scope")).toBe(MICROSOFT_MAIL_SCOPES.join(" ")); expect(url.searchParams.get("state")).toBe("signed-state"); }); }); describe("token exchange + refresh", () => { it("exchanges the code against the tenant token endpoint", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, { access_token: "at", refresh_token: "rt", expires_in: 3600 })); const tokens = await exchangeMicrosoftCodeForTokens(CONFIG, "the-code"); expect(tokens.accessToken).toBe("at"); expect(String(fetchMock.mock.calls[0][0])).toBe("https://login.microsoftonline.com/common/oauth2/v2.0/token"); }); it("persists the ROTATED refresh token from a refresh response", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, { access_token: "at2", refresh_token: "rt-rotated", expires_in: 3600 })); const tokens = await refreshMicrosoftAccessToken(CONFIG, "rt-old"); expect(tokens.refreshToken).toBe("rt-rotated"); }); it("maps invalid_grant to auth_token_expired", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(400, { error: "invalid_grant" })); await expect(refreshMicrosoftAccessToken(CONFIG, "dead")).rejects.toMatchObject({ name: "GraphMailError", code: "auth_token_expired", }); }); }); describe("subscriptions", () => { it("creates the /me/messages subscription with clientState and ~3d lifetime", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(201, { id: "sub1", expirationDateTime: "2026-07-05T00:00:00Z" })); const before = Date.now(); const sub = await createMailSubscription("at", "https://app.hivegrid.de/webhooks/email/microsoft", "cs-secret"); expect(sub.id).toBe("sub1"); const body = JSON.parse(String(fetchMock.mock.calls[0][1].body)); expect(body).toMatchObject({ resource: "/me/messages", clientState: "cs-secret", changeType: "created,updated" }); const requestedExpiry = new Date(body.expirationDateTime).getTime(); expect(requestedExpiry).toBeGreaterThan(before); expect(requestedExpiry).toBeLessThanOrEqual(before + GRAPH_MAIL_SUBSCRIPTION_LIFETIME_MS + 5000); }); it("signals an expired subscription on renew (404) so the caller re-creates", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(404, {})); await expect(renewMailSubscription("at", "sub-gone")).rejects.toMatchObject({ code: "subscription_failed" }); }); it("deletes idempotently (404 = already gone)", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(404, {})); await expect(deleteMailSubscription("at", "sub1")).resolves.toBeUndefined(); }); }); describe("delta sync", () => { it("builds the initial per-folder delta URL with a receivedDateTime bound", () => { const url = buildInitialDeltaUrl("inbox", "2026-04-03T00:00:00Z"); expect(url).toContain("/me/mailFolders/inbox/messages/delta"); expect(url).toContain("receivedDateTime+ge+2026-04-03T00%3A00%3A00Z"); }); it("follows links verbatim and surfaces next/delta links", async () => { fetchMock.mockResolvedValueOnce( jsonResponse(200, { value: [{ id: "g1", conversationId: "c1" }], "@odata.deltaLink": "https://graph.microsoft.com/v1.0/next-delta", }), ); const page = await fetchDeltaPage("at", "https://graph.microsoft.com/v1.0/whatever"); expect(page.messages).toHaveLength(1); expect(page.deltaLink).toBe("https://graph.microsoft.com/v1.0/next-delta"); expect(fetchMock.mock.calls[0][0]).toBe("https://graph.microsoft.com/v1.0/whatever"); }); it("marks an invalid delta token (410) as fullResyncRequired", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(410, {})); const error = await fetchDeltaPage("at", "https://graph.microsoft.com/v1.0/x").catch((e: unknown) => e); expect(error).toBeInstanceOf(GraphMailError); expect((error as GraphMailError).fullResyncRequired).toBe(true); }); }); describe("profile, send, read state", () => { it("falls back to userPrincipalName when mail is empty", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, { id: "u1", userPrincipalName: "u@x.de" })); const profile = await fetchGraphUserProfile("at"); expect(profile.email).toBe("u@x.de"); }); it("accepts sendMail's 202-without-id contract", async () => { fetchMock.mockResolvedValueOnce(new Response(null, { status: 202 })); await expect( sendGraphMail("at", { subject: "s", bodyHtml: "

x

", to: [{ address: "a@b.de" }] }), ).resolves.toBeUndefined(); const body = JSON.parse(String(fetchMock.mock.calls[0][1].body)); expect(body.saveToSentItems).toBe(true); expect(body.message.toRecipients).toEqual([{ emailAddress: { address: "a@b.de" } }]); }); it("patches the isRead flag", async () => { fetchMock.mockResolvedValueOnce(jsonResponse(200, {})); await setGraphMessageRead("at", "m1", true); expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ isRead: true }); }); });