/** * src/adapters/graph-mailbox-adapter.ts * ====================================== * Tenant-agnostic Microsoft Graph mailbox poller (app-only client-credentials). * * Generalized from v0-datahub/lib/invoice-inbox/poll.ts: there the mailbox * (invoice@protosell.se), the Entra app, and the folder were all hardcoded * module constants. Here every one of those is a CALLER-SUPPLIED parameter — * any SIAX customer can register any mailbox (invoices, HR forms, contracts, * receipts, ...) and poll it through this adapter. Nothing about invoices, * vendors, or Protosell is baked in here — that logic (vendor-kb matching, * dup-hash, DQ scoring, invoice classification) was intentionally left * behind; it does not belong in a generic capture adapter. */ const GRAPH_BASE = "https://graph.microsoft.com/v1.0"; export interface GraphMailboxConfig { /** Entra (Azure AD) tenant id the app registration lives in. */ tenantId: string; /** Entra app (client) id — app-only, client-credentials grant. */ clientId: string; /** Entra app client secret. Never logged, never persisted by this adapter. */ clientSecret: string; /** Mailbox address to poll, e.g. "invoices@customer.com". */ mailboxAddress: string; /** Mail folder to poll. Default: "inbox". */ folder?: string; } export interface GraphMessage { id: string; internetMessageId: string | null; conversationId: string | null; receivedAt: string | null; senderName: string | null; senderEmail: string | null; toRecipients: string[]; subject: string | null; bodyPreview: string | null; /** HTML body stripped to plain text. Falls back to bodyPreview when body is absent. */ bodyText: string | null; hasAttachments: boolean; webLink: string | null; } export interface GraphAttachment { id: string; name: string | null; contentType: string | null; sizeBytes: number | null; isPdf: boolean; contentBytes: Buffer; } export interface PollMessagesOptions { /** Only return messages received at/after this ISO timestamp (incremental polling). */ sinceISO?: string; /** Page size per Graph request. Default 50. */ top?: number; /** Max number of pages to walk. Default 2 (raise for backfills). */ maxPages?: number; } /** Strip HTML to plain text. Generic — no document-type-specific parsing. */ function stripHtml(html: string): string { return (html || "") .replace(//gi, " ") .replace(//gi, " ") .replace(/<[^>]+>/g, " ") .replace(/ /gi, " ") .replace(/&/gi, "&") .replace(/</gi, "<") .replace(/>/gi, ">") .replace(/\s+/g, " ") .trim(); } export class GraphMailboxAdapter { private cachedToken: { token: string; expiresAt: number } | null = null; constructor(private config: GraphMailboxConfig) {} static isConfigured(config: Partial): boolean { return !!(config.tenantId && config.clientId && config.clientSecret && config.mailboxAddress); } private async getToken(): Promise { if (this.cachedToken && this.cachedToken.expiresAt > Date.now() + 30_000) { return this.cachedToken.token; } const { tenantId, clientId, clientSecret } = this.config; if (!tenantId || !clientId || !clientSecret) { throw new Error("GraphMailboxAdapter: missing tenantId/clientId/clientSecret"); } const body = new URLSearchParams({ client_id: clientId, client_secret: clientSecret, grant_type: "client_credentials", scope: "https://graph.microsoft.com/.default", }); const res = await fetch(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body, }); const json: Record = await res.json(); if (!res.ok) { throw new Error(`Graph token request failed: ${json.error || res.status} ${json.error_description || ""}`); } const expiresInMs = (typeof json.expires_in === "number" ? json.expires_in : 3600) * 1000; this.cachedToken = { token: json.access_token as string, expiresAt: Date.now() + expiresInMs }; return this.cachedToken.token; } // Graph-API:t är genuint ostrukturerat JSON (value-array med fri form); // full typning av hela Graph-ytan är egen insats — any här är medveten // och avgränsad till denna adapter (eslint-undantag med skäl, DoD §13). // eslint-disable-next-line @typescript-eslint/no-explicit-any private async get(path: string): Promise { const token = await this.getToken(); const url = path.startsWith("http") ? path : `${GRAPH_BASE}${path}`; const res = await fetch(url, { headers: { authorization: `Bearer ${token}` } }); // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Graph-JSON är genuint ostrukturerat; full Graph-typning är egen insats const json: any = await res.json(); if (!res.ok) { throw new Error(`Graph GET ${path} -> ${json.error?.code || res.status}: ${json.error?.message || ""}`); } return json; } /** List messages in the configured mailbox/folder, newest first, optionally incremental. */ async pollMessages(opts: PollMessagesOptions = {}): Promise { const folder = this.config.folder || "inbox"; const top = opts.top ?? 50; const maxPages = opts.maxPages ?? 2; const select = "$select=id,internetMessageId,conversationId,receivedDateTime,from,toRecipients,subject,bodyPreview,hasAttachments,webLink,body"; let sinceFilter = ""; if (opts.sinceISO) { sinceFilter = `&$filter=receivedDateTime ge ${new Date(opts.sinceISO).toISOString()}`; } let url = `${GRAPH_BASE}/users/${encodeURIComponent(this.config.mailboxAddress)}/mailFolders/${encodeURIComponent(folder)}` + `/messages?$top=${top}&$orderby=receivedDateTime desc&${select}${sinceFilter}`; const out: GraphMessage[] = []; for (let page = 0; page < maxPages && url; page++) { const data = await this.get(url); for (const m of data.value || []) { out.push({ id: m.id, internetMessageId: m.internetMessageId || null, conversationId: m.conversationId || null, receivedAt: m.receivedDateTime || null, senderName: m.from?.emailAddress?.name || null, senderEmail: m.from?.emailAddress?.address || null, toRecipients: (m.toRecipients || []).map((r: { emailAddress?: { address?: string } }) => r.emailAddress?.address).filter(Boolean), subject: m.subject || null, bodyPreview: m.bodyPreview || null, bodyText: m.body?.content ? stripHtml(m.body.content) : m.bodyPreview || null, hasAttachments: !!m.hasAttachments, webLink: m.webLink || null, }); } url = data["@odata.nextLink"] || ""; } return out; } /** List and download every file attachment on a message. */ async listAttachments(messageId: string): Promise { const data = await this.get( `/users/${encodeURIComponent(this.config.mailboxAddress)}/messages/${messageId}/attachments`, ); const out: GraphAttachment[] = []; for (const a of data.value || []) { if (a["@odata.type"] !== "#microsoft.graph.fileAttachment" || !a.contentBytes) continue; const contentType: string | null = a.contentType || null; const name: string | null = a.name || null; const isPdf = (contentType || "").includes("pdf") || /\.pdf$/i.test(name || ""); out.push({ id: a.id, name, contentType, sizeBytes: typeof a.size === "number" ? a.size : null, isPdf, contentBytes: Buffer.from(a.contentBytes, "base64"), }); } return out; } }