Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,167 @@
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<typeof vi.fn>;
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: "<p>x</p>", 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 });
});
});
@@ -0,0 +1,460 @@
// VA-P23 · Microsoft Graph Mail REST/OAuth client (shared web + worker).
//
// Plain `fetch` against the Microsoft identity platform + Graph REST endpoints —
// NO Microsoft SDK (same EU-stack boundary as gmailApi.ts/googleCalendarApi.ts).
// Provider-typed, pure of any app/Prisma import so apps/web (connect/send) and
// apps/worker (delta drain / subscription renewal) share it.
//
// Graph specifics that shape this client (M09 Block D):
// - Subscriptions on /me/messages live at most ~4230 minutes (~3 days) → the
// renewal cron PATCHes the expiration daily.
// - `clientState` is the ONLY auth mechanism on notifications: generated per
// mailbox, stored, and compared on every push.
// - Delta queries are PER FOLDER (inbox, sentitems, …) — the caller keeps one
// cursor per folder and follows @odata.nextLink/@odata.deltaLink verbatim.
// - sendMail returns 202 WITHOUT a message id → the sent-items delta re-ingest
// dedupes onto the local outbound mirror via internetMessageId.
const GRAPH_API_BASE = "https://graph.microsoft.com/v1.0";
/** Stable Klartext error codes (mapped to i18n keys at the module boundary). */
export type GraphMailErrorCode =
| "auth_token_expired"
| "auth_scope_missing"
| "rate_limit_exceeded"
| "message_not_found"
| "delta_token_invalid"
| "subscription_failed"
| "provider_outage"
| "not_configured"
| "unknown";
export class GraphMailError extends Error {
readonly code: GraphMailErrorCode;
readonly httpStatus?: number;
/** True when Graph invalidated the delta cursor (410 Gone) → full resync. */
readonly fullResyncRequired: boolean;
constructor(code: GraphMailErrorCode, httpStatus?: number, message?: string) {
super(message ?? code);
this.name = "GraphMailError";
this.code = code;
this.httpStatus = httpStatus;
this.fullResyncRequired = code === "delta_token_invalid";
}
}
/** OAuth client config read from env (Azure app registration, VEXT-5 §bridge). */
export interface MicrosoftMailOAuthConfig {
readonly clientId: string;
readonly clientSecret: string;
/** Must match an Azure-registered redirect URI exactly. */
readonly redirectUri: string;
/** AAD tenant segment; `common` = any Microsoft account (default). */
readonly tenant: string;
}
export function resolveMicrosoftMailOAuthConfig(env: NodeJS.ProcessEnv = process.env): MicrosoftMailOAuthConfig | null {
const clientId = env.MICROSOFT_MAIL_CLIENT_ID;
const clientSecret = env.MICROSOFT_MAIL_CLIENT_SECRET;
const redirectUri = env.MICROSOFT_MAIL_REDIRECT_URI;
if (!clientId || !clientSecret || !redirectUri) {
return null;
}
return { clientId, clientSecret, redirectUri, tenant: env.MICROSOFT_MAIL_TENANT || "common" };
}
/** Graph mail scopes (M09 Block B). `offline_access` yields the refresh token. */
export const MICROSOFT_MAIL_SCOPES = ["offline_access", "Mail.ReadWrite", "Mail.Send", "User.Read"] as const;
function oauthBase(tenant: string): string {
return `https://login.microsoftonline.com/${encodeURIComponent(tenant)}/oauth2/v2.0`;
}
/** Build the consent-screen URL. `state` carries a signed tenant+user token. */
export function buildMicrosoftAuthorizationUrl(config: MicrosoftMailOAuthConfig, state: string): string {
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: "code",
response_mode: "query",
scope: MICROSOFT_MAIL_SCOPES.join(" "),
prompt: "select_account",
state,
});
return `${oauthBase(config.tenant)}/authorize?${params.toString()}`;
}
export interface GraphTokenSet {
readonly accessToken: string;
/** Graph rotates the refresh token on every grant — persist the new one. */
readonly refreshToken?: string;
readonly expiresAt: Date;
readonly scopes: readonly string[];
}
interface GraphTokenResponse {
access_token: string;
refresh_token?: string;
expires_in: number;
scope?: string;
error?: string;
error_description?: string;
}
function tokenSetFromResponse(body: GraphTokenResponse, now: number): GraphTokenSet {
return {
accessToken: body.access_token,
refreshToken: body.refresh_token,
expiresAt: new Date(now + body.expires_in * 1000),
scopes: body.scope ? body.scope.split(" ") : [],
};
}
/** Exchange the authorization `code` for a token set (initial connect). */
export async function exchangeMicrosoftCodeForTokens(config: MicrosoftMailOAuthConfig, code: string): Promise<GraphTokenSet> {
const res = await fetch(`${oauthBase(config.tenant)}/token`, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
redirect_uri: config.redirectUri,
grant_type: "authorization_code",
scope: MICROSOFT_MAIL_SCOPES.join(" "),
code,
}),
});
const body = (await res.json()) as GraphTokenResponse;
if (!res.ok || !body.access_token) {
throw mapOAuthError(res.status, body);
}
return tokenSetFromResponse(body, Date.now());
}
/** Refresh an access token. Graph returns a ROTATED refresh token — persist it. */
export async function refreshMicrosoftAccessToken(config: MicrosoftMailOAuthConfig, refreshToken: string): Promise<GraphTokenSet> {
const res = await fetch(`${oauthBase(config.tenant)}/token`, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: "refresh_token",
scope: MICROSOFT_MAIL_SCOPES.join(" "),
refresh_token: refreshToken,
}),
});
const body = (await res.json()) as GraphTokenResponse;
if (!res.ok || !body.access_token) {
throw mapOAuthError(res.status, body);
}
return tokenSetFromResponse({ ...body, refresh_token: body.refresh_token ?? refreshToken }, Date.now());
}
// NOTE: the Microsoft identity platform has no simple app-side token-revoke
// endpoint for delegated tokens. Disconnect = delete the Graph subscription +
// drop the ciphertexts; the refresh token dies with the user's own revocation
// or its natural expiry. Documented in MailboxConnectionService.disconnect.
function mapOAuthError(status: number, body: { error?: string }): GraphMailError {
if (body.error === "invalid_grant") {
return new GraphMailError("auth_token_expired", status, body.error);
}
if (status === 429) {
return new GraphMailError("rate_limit_exceeded", status);
}
if (status >= 500) {
return new GraphMailError("provider_outage", status);
}
return new GraphMailError("unknown", status, body.error);
}
/** Minimal identity used to fill `emailAddress` / `externalAccountId`. */
export interface GraphUserProfile {
readonly id: string;
readonly email: string;
readonly displayName?: string;
}
export async function fetchGraphUserProfile(accessToken: string): Promise<GraphUserProfile> {
const res = await fetch(`${GRAPH_API_BASE}/me?$select=id,mail,userPrincipalName,displayName`, {
headers: { authorization: `Bearer ${accessToken}` },
});
if (!res.ok) {
throw mapApiError(res.status);
}
const body = (await res.json()) as { id?: string; mail?: string; userPrincipalName?: string; displayName?: string };
return { id: body.id ?? "", email: body.mail || body.userPrincipalName || "", displayName: body.displayName };
}
export interface GraphSubscription {
readonly id: string;
readonly expiresAt: Date;
}
/** Max subscription lifetime for /me/messages (~4230 minutes ≈ 3 days). */
export const GRAPH_MAIL_SUBSCRIPTION_LIFETIME_MS = 4230 * 60 * 1000;
/**
* Create the push subscription on /me/messages. `clientState` is generated per
* mailbox, stored on the mailbox row, and verified on every notification.
*/
export async function createMailSubscription(
accessToken: string,
notificationUrl: string,
clientState: string,
): Promise<GraphSubscription> {
const res = await fetch(`${GRAPH_API_BASE}/subscriptions`, {
method: "POST",
headers: { authorization: `Bearer ${accessToken}`, "content-type": "application/json" },
body: JSON.stringify({
changeType: "created,updated",
notificationUrl,
resource: "/me/messages",
expirationDateTime: new Date(Date.now() + GRAPH_MAIL_SUBSCRIPTION_LIFETIME_MS).toISOString(),
clientState,
}),
});
if (!res.ok) {
throw new GraphMailError("subscription_failed", res.status);
}
const body = (await res.json()) as { id: string; expirationDateTime: string };
return { id: body.id, expiresAt: new Date(body.expirationDateTime) };
}
/** Renew (PATCH) an existing subscription's expiration (daily renewal cron). */
export async function renewMailSubscription(accessToken: string, subscriptionId: string): Promise<GraphSubscription> {
const res = await fetch(`${GRAPH_API_BASE}/subscriptions/${encodeURIComponent(subscriptionId)}`, {
method: "PATCH",
headers: { authorization: `Bearer ${accessToken}`, "content-type": "application/json" },
body: JSON.stringify({ expirationDateTime: new Date(Date.now() + GRAPH_MAIL_SUBSCRIPTION_LIFETIME_MS).toISOString() }),
});
if (res.status === 404) {
// Subscription already expired at Microsoft → caller re-creates it.
throw new GraphMailError("subscription_failed", res.status, "subscription_expired");
}
if (!res.ok) {
throw mapApiError(res.status);
}
const body = (await res.json()) as { id: string; expirationDateTime: string };
return { id: body.id, expiresAt: new Date(body.expirationDateTime) };
}
/** Delete the subscription (disconnect). Idempotent. */
export async function deleteMailSubscription(accessToken: string, subscriptionId: string): Promise<void> {
const res = await fetch(`${GRAPH_API_BASE}/subscriptions/${encodeURIComponent(subscriptionId)}`, {
method: "DELETE",
headers: { authorization: `Bearer ${accessToken}` },
});
if (res.ok || res.status === 404) {
return;
}
throw mapApiError(res.status);
}
/** The Graph message projection this module maps into EmailIntegrationMessage. */
export interface GraphMessage {
readonly id: string;
readonly conversationId?: string;
readonly internetMessageId?: string;
readonly subject?: string;
readonly bodyPreview?: string;
readonly body?: { contentType?: string; content?: string };
readonly from?: { emailAddress?: { address?: string; name?: string } };
readonly toRecipients?: ReadonlyArray<{ emailAddress?: { address?: string; name?: string } }>;
readonly ccRecipients?: ReadonlyArray<{ emailAddress?: { address?: string; name?: string } }>;
readonly bccRecipients?: ReadonlyArray<{ emailAddress?: { address?: string; name?: string } }>;
readonly sentDateTime?: string;
readonly receivedDateTime?: string;
readonly isRead?: boolean;
readonly hasAttachments?: boolean;
readonly internetMessageHeaders?: ReadonlyArray<{ name?: string; value?: string }>;
/** Present in delta responses for removed items. */
readonly "@removed"?: { reason?: string };
}
const MESSAGE_SELECT = [
"id",
"conversationId",
"internetMessageId",
"subject",
"bodyPreview",
"body",
"from",
"toRecipients",
"ccRecipients",
"bccRecipients",
"sentDateTime",
"receivedDateTime",
"isRead",
"hasAttachments",
].join(",");
export interface GraphDeltaPage {
readonly messages: readonly GraphMessage[];
/** Follow verbatim until absent. */
readonly nextLink?: string;
/** Persist as the folder cursor once the page set is fully processed. */
readonly deltaLink?: string;
}
/** Build the INITIAL delta URL for a folder, bounded for the 90-day initial sync. */
export function buildInitialDeltaUrl(folderId: string, receivedAfterIso?: string): string {
const params = new URLSearchParams({ $select: MESSAGE_SELECT });
if (receivedAfterIso) {
params.set("$filter", `receivedDateTime ge ${receivedAfterIso}`);
}
return `${GRAPH_API_BASE}/me/mailFolders/${encodeURIComponent(folderId)}/messages/delta?${params.toString()}`;
}
/**
* Fetch one delta page. `url` is either the initial folder delta URL or a stored
* @odata.nextLink/@odata.deltaLink — Graph links are followed VERBATIM. A 410
* means the delta token expired → full resync for that folder.
*/
export async function fetchDeltaPage(accessToken: string, url: string): Promise<GraphDeltaPage> {
const res = await fetch(url, { headers: { authorization: `Bearer ${accessToken}` } });
if (res.status === 410) {
throw new GraphMailError("delta_token_invalid", res.status);
}
if (!res.ok) {
throw mapApiError(res.status);
}
const body = (await res.json()) as {
value?: GraphMessage[];
"@odata.nextLink"?: string;
"@odata.deltaLink"?: string;
};
return { messages: body.value ?? [], nextLink: body["@odata.nextLink"], deltaLink: body["@odata.deltaLink"] };
}
export async function getGraphMessage(accessToken: string, messageId: string): Promise<GraphMessage> {
const res = await fetch(
`${GRAPH_API_BASE}/me/messages/${encodeURIComponent(messageId)}?$select=${MESSAGE_SELECT}&$expand=internetMessageHeaders`,
{ headers: { authorization: `Bearer ${accessToken}` } },
);
if (!res.ok) {
throw mapApiError(res.status);
}
return (await res.json()) as GraphMessage;
}
export interface GraphSendRecipient {
readonly address: string;
readonly name?: string;
}
export interface GraphSendInput {
readonly subject: string;
readonly bodyHtml: string;
readonly to: readonly GraphSendRecipient[];
readonly cc?: readonly GraphSendRecipient[];
readonly bcc?: readonly GraphSendRecipient[];
/** fileAttachment content as base64 (v1 cap: ≤3 MB per attachment). */
readonly attachments?: ReadonlyArray<{ name: string; contentType: string; contentBase64: string }>;
/** Internet-message-id being replied to (threads the message client-side). */
readonly inReplyToInternetMessageId?: string;
}
function graphRecipients(list: readonly GraphSendRecipient[] | undefined) {
return (list ?? []).map((r) => ({ emailAddress: { address: r.address, ...(r.name ? { name: r.name } : {}) } }));
}
/**
* Send a message (/me/sendMail, saveToSentItems). Graph answers 202 with NO
* message id — the caller mirrors the outbound locally and the sent-items delta
* later dedupes via internetMessageId.
*/
export async function sendGraphMail(accessToken: string, input: GraphSendInput): Promise<void> {
const message: Record<string, unknown> = {
subject: input.subject,
body: { contentType: "HTML", content: input.bodyHtml },
toRecipients: graphRecipients(input.to),
ccRecipients: graphRecipients(input.cc),
bccRecipients: graphRecipients(input.bcc),
};
if (input.attachments?.length) {
message.attachments = input.attachments.map((a) => ({
"@odata.type": "#microsoft.graph.fileAttachment",
name: a.name,
contentType: a.contentType,
contentBytes: a.contentBase64,
}));
}
const res = await fetch(`${GRAPH_API_BASE}/me/sendMail`, {
method: "POST",
headers: { authorization: `Bearer ${accessToken}`, "content-type": "application/json" },
body: JSON.stringify({ message, saveToSentItems: true }),
});
if (!res.ok && res.status !== 202) {
throw mapApiError(res.status);
}
}
/** Mirror a read/unread toggle back to the provider (M09 Block F bulk actions). */
export async function setGraphMessageRead(accessToken: string, messageId: string, isRead: boolean): Promise<void> {
const res = await fetch(`${GRAPH_API_BASE}/me/messages/${encodeURIComponent(messageId)}`, {
method: "PATCH",
headers: { authorization: `Bearer ${accessToken}`, "content-type": "application/json" },
body: JSON.stringify({ isRead }),
});
if (!res.ok) {
throw mapApiError(res.status);
}
}
export interface GraphAttachment {
readonly id: string;
readonly name: string;
readonly contentType?: string;
readonly sizeBytes: number;
/** Present for fileAttachment when fetched individually (≤3 MB inline). */
readonly contentBase64?: string;
}
export async function listGraphAttachments(accessToken: string, messageId: string): Promise<GraphAttachment[]> {
const res = await fetch(`${GRAPH_API_BASE}/me/messages/${encodeURIComponent(messageId)}/attachments?$select=id,name,contentType,size`, {
headers: { authorization: `Bearer ${accessToken}` },
});
if (!res.ok) {
throw mapApiError(res.status);
}
const body = (await res.json()) as { value?: Array<{ id: string; name?: string; contentType?: string; size?: number }> };
return (body.value ?? []).map((a) => ({ id: a.id, name: a.name ?? "attachment", contentType: a.contentType, sizeBytes: a.size ?? 0 }));
}
/** Fetch one attachment (fileAttachment → contentBytes inline; >3 MB via $value stream is v2). */
export async function getGraphAttachment(accessToken: string, messageId: string, attachmentId: string): Promise<GraphAttachment> {
const res = await fetch(
`${GRAPH_API_BASE}/me/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`,
{ headers: { authorization: `Bearer ${accessToken}` } },
);
if (!res.ok) {
throw mapApiError(res.status);
}
const body = (await res.json()) as { id: string; name?: string; contentType?: string; size?: number; contentBytes?: string };
return {
id: body.id,
name: body.name ?? "attachment",
contentType: body.contentType,
sizeBytes: body.size ?? 0,
contentBase64: body.contentBytes,
};
}
function mapApiError(status: number): GraphMailError {
switch (status) {
case 401:
return new GraphMailError("auth_token_expired", status);
case 403:
return new GraphMailError("auth_scope_missing", status);
case 404:
return new GraphMailError("message_not_found", status);
case 410:
return new GraphMailError("delta_token_invalid", status);
case 429:
return new GraphMailError("rate_limit_exceeded", status);
default:
return status >= 500 ? new GraphMailError("provider_outage", status) : new GraphMailError("unknown", status);
}
}