WIP: form attachments (e-mail only) — core, endpoint, Graph large upload

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-13 16:20:02 +01:00
co-authored by Claude Fable 5.2
parent 0ba0014ed5
commit 6003b3d7d7
36 changed files with 2399 additions and 97 deletions
+17
View File
@@ -0,0 +1,17 @@
import type { BasePayload } from 'payload'
/**
* The largest total attachment size (bytes) the site's e-mail adapter says it
* can carry, or null when it names no ceiling. mailAdapter and graphAdapter
* report one; any other adapter is taken to have none. Never throws.
*/
export async function mailAttachmentLimit(payload: BasePayload): Promise<null | number> {
const limit = (payload.email as { attachmentLimit?: () => null | number | Promise<null | number> } | undefined)?.attachmentLimit
if (typeof limit !== 'function') {return null}
try {
const value = await limit()
return typeof value === 'number' && value >= 0 ? value : null
} catch {
return null
}
}
+96 -8
View File
@@ -1,6 +1,15 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { getSiteIntegrations } from '../payload/index.js'
import {
attachmentBytes,
GRAPH_INLINE_MAX_BYTES,
GRAPH_LARGE_PERMISSION,
inlineGraphAttachments,
sendLargeGraphMail,
toGraphAttachments,
tokenRoles,
} from './graphAttachments.js'
/**
* From/To settings the adapter reads from SiteIntegrations (panel). The Graph
@@ -19,8 +28,42 @@ type GraphIntegrations = {
}
export type GraphAdapterArgs = {
/** Waits before the sent copy of a large-attachment message is deleted from the mailbox (ms). Default 2 s, 5 s, 15 s, 60 s. */
cleanupDelaysMs?: number[]
fallbackFromAddress?: string
fallbackFromName?: string
/** For tests: the `fetch` to call Microsoft with. */
fetchImpl?: typeof fetch
/**
* Attachments of 3 MB and more (in total): the message goes through a draft
* in the sender mailbox and an upload session, and the mailbox copy is deleted
* afterwards. Needs the `Mail.ReadWrite` application permission. Default true;
* `false` keeps Graph to small attachments (larger ones go over SMTP when the
* panel has SMTP settings — see mailAdapter).
*/
largeAttachments?: boolean
}
/**
* Can this Graph setup send attachments of 3 MB and more?
* - 'ok' — yes
* - 'off' — `largeAttachments: false`
* - 'no-permission' — the app's token lacks Mail.ReadWrite
* - 'unavailable' — Graph is not configured, or no token could be fetched
*/
export type GraphLargeSupport = 'no-permission' | 'off' | 'ok' | 'unavailable'
export async function graphLargeAttachmentSupport(args: Pick<GraphAdapterArgs, 'fetchImpl' | 'largeAttachments'> = {}): Promise<GraphLargeSupport> {
if (args.largeAttachments === false) {return 'off'}
const env = readGraphEnv()
if (!env) {return 'unavailable'}
try {
const roles = tokenRoles(await getAccessToken(env, args.fetchImpl))
// A token we cannot read says nothing — let the send try and report.
return !roles || roles.includes(GRAPH_LARGE_PERMISSION) ? 'ok' : 'no-permission'
} catch {
return 'unavailable'
}
}
type GraphEnv = {
@@ -43,11 +86,15 @@ function readGraphEnv(): GraphEnv | null {
/**
* Fetches an app-only access token via the OAuth2 client-credentials flow.
* Scope MUST be '.../.default' — passing 'Mail.Send' directly is rejected
* (AADSTS1002012). Tokens last ~1h; we fetch per send for simplicity and to
* avoid holding state in a possibly multi-instance deployment. If you send at
* high volume, cache by expiry.
* (AADSTS1002012). Tokens last ~1h and are cached per process until a minute
* before they expire.
*/
async function getAccessToken(env: GraphEnv): Promise<string> {
const tokenCache = new Map<string, { expiresAt: number; token: string }>()
async function getAccessToken(env: GraphEnv, fetchImpl: typeof fetch = fetch): Promise<string> {
const cacheKey = `${env.tenantId}:${env.clientId}`
const cached = tokenCache.get(cacheKey)
if (cached && cached.expiresAt > Date.now()) {return cached.token}
const url = `https://login.microsoftonline.com/${env.tenantId}/oauth2/v2.0/token`
const body = new URLSearchParams({
client_id: env.clientId,
@@ -56,7 +103,7 @@ async function getAccessToken(env: GraphEnv): Promise<string> {
scope: 'https://graph.microsoft.com/.default',
})
const res = await fetch(url, {
const res = await fetchImpl(url, {
body,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
method: 'POST',
@@ -65,8 +112,10 @@ async function getAccessToken(env: GraphEnv): Promise<string> {
const detail = await res.text()
throw new Error(`Graph token request failed (${res.status}): ${detail}`)
}
const data = (await res.json()) as { access_token?: string }
const data = (await res.json()) as { access_token?: string; expires_in?: number }
if (!data.access_token) {throw new Error('Graph token response had no access_token')}
// Kept until a minute before it expires (tokens last about an hour).
tokenCache.set(cacheKey, { expiresAt: Date.now() + Math.max(0, (data.expires_in ?? 0) - 60) * 1000, token: data.access_token })
return data.access_token
}
@@ -103,6 +152,11 @@ export const graphAdapter =
(args: GraphAdapterArgs = {}): PayloadEmailAdapter =>
({ payload }) => ({
name: 'ipal-graph',
/** Total attachment bytes this adapter can carry; null = no ceiling of its own (see mailAdapter). */
attachmentLimit: async (): Promise<null | number> => {
const support = await graphLargeAttachmentSupport(args)
return support === 'ok' || support === 'unavailable' ? null : GRAPH_INLINE_MAX_BYTES - 1
},
defaultFromAddress: args.fallbackFromAddress ?? 'noreply@localhost',
defaultFromName: args.fallbackFromName ?? 'Website',
@@ -166,10 +220,44 @@ export const graphAdapter =
...(replyTo.length > 0 ? { replyTo } : {}),
}
// Attachments: small ones ride in the same call; larger ones need a draft and an upload session.
const attachments = toGraphAttachments(message)
if (!attachments) {
payload.logger.error('[ipal] Graph: an attachment is not in memory (a path or a stream) — pass its content as a Buffer.')
return { detail: 'Attachment content must be a Buffer or a string.', error: 'The e-mail was not sent.', sent: false }
}
const fetchImpl = args.fetchImpl ?? fetch
try {
const token = await getAccessToken(env)
const token = await getAccessToken(env, fetchImpl)
if (attachments.length > 0 && attachmentBytes(attachments) >= GRAPH_INLINE_MAX_BYTES) {
if (args.largeAttachments === false) {
return {
code: 'graph-large-off',
detail: 'Attachments of 3 MB and more are switched off for Microsoft Graph (largeAttachments: false).',
error: 'The e-mail was not sent.',
sent: false,
}
}
const roles = tokenRoles(token)
if (roles && !roles.includes(GRAPH_LARGE_PERMISSION)) {
const detail = `The Microsoft Graph app lacks the ${GRAPH_LARGE_PERMISSION} application permission, so it cannot send attachments of 3 MB and more.`
payload.logger.error(`[ipal] ${detail}`)
return { code: 'graph-permission', detail, error: 'The e-mail was not sent.', sent: false }
}
const large = await sendLargeGraphMail(attachments, {
cleanupDelaysMs: args.cleanupDelaysMs,
fetchImpl,
log: payload.logger,
message: graphMessage,
sender: env.sender,
token,
})
return large.sent ? large : { ...large, error: 'The e-mail was not sent.' }
}
if (attachments.length > 0) {graphMessage.attachments = inlineGraphAttachments(attachments)}
// App-only: MUST target /users/{sender}, never /me.
const res = await fetch(
const res = await fetchImpl(
`https://graph.microsoft.com/v1.0/users/${encodeURIComponent(env.sender)}/sendMail`,
{
body: JSON.stringify({ message: graphMessage, saveToSentItems: false }),
+197
View File
@@ -0,0 +1,197 @@
import type { SendEmailOptions } from 'payload'
/**
* Attachments over Microsoft Graph.
*
* - Small (all attachments together under GRAPH_INLINE_MAX_BYTES): inside the
* one `sendMail` call. Needs only `Mail.Send`; nothing is left in the mailbox.
* - Large: Graph has no single call for it. The message is created as a DRAFT
* in the sender mailbox, each file is added (an upload session for files of
* 3 MiB and more), the draft is sent, and the copy the mailbox keeps in Sent
* Items is deleted afterwards. Needs the `Mail.ReadWrite` application
* permission — limit it to the sender mailbox with an application access
* policy (docs/email.md).
*/
/**
* Microsoft documents inline attachments "under 3 MB"; the request also has to
* fit base64 (+33 %) and the message body, so the plugin switches at 3,000,000 bytes.
*/
export const GRAPH_INLINE_MAX_BYTES = 3_000_000
/** Files of this size and more need an upload session; smaller ones are refused by it. */
const UPLOAD_SESSION_MIN_BYTES = 3 * 1024 * 1024
/** Bytes per PUT — Microsoft: keep it under 4 MB. A multiple of 320 KiB. */
const CHUNK_BYTES = 10 * 320 * 1024
export const GRAPH_LARGE_PERMISSION = 'Mail.ReadWrite'
export type GraphAttachment = { content: Buffer; contentType: string; name: string }
/** nodemailer-style attachments → buffers. `null` when one cannot be read into memory (a path or a stream). */
export function toGraphAttachments(message: SendEmailOptions): GraphAttachment[] | null {
const list = (message as { attachments?: unknown }).attachments
if (!Array.isArray(list) || list.length === 0) {return []}
const out: GraphAttachment[] = []
for (const raw of list as { content?: unknown; contentType?: unknown; filename?: unknown }[]) {
const content =
Buffer.isBuffer(raw.content) ? raw.content
: raw.content instanceof Uint8Array ? Buffer.from(raw.content.buffer, raw.content.byteOffset, raw.content.byteLength)
: typeof raw.content === 'string' ? Buffer.from(raw.content, 'utf8')
: null
if (!content) {return null}
out.push({
name: typeof raw.filename === 'string' && raw.filename ? raw.filename : 'attachment',
content,
contentType: typeof raw.contentType === 'string' && raw.contentType ? raw.contentType : 'application/octet-stream',
})
}
return out
}
export const attachmentBytes = (attachments: GraphAttachment[]) => attachments.reduce((sum, a) => sum + a.content.length, 0)
/** The attachments as `fileAttachment` objects for an inline `sendMail`. */
export const inlineGraphAttachments = (attachments: GraphAttachment[]) =>
attachments.map((a) => ({
name: a.name,
'@odata.type': '#microsoft.graph.fileAttachment',
contentBytes: a.content.toString('base64'),
contentType: a.contentType,
}))
/** Application permissions (`roles`) of an app-only access token; `null` when the token is not a readable JWT. */
export function tokenRoles(token: string): null | string[] {
try {
const payload = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf8')) as { roles?: unknown }
return Array.isArray(payload.roles) ? payload.roles.filter((r): r is string => typeof r === 'string') : null
} catch {
return null
}
}
export type GraphLargeResult =
| { cleanup: Promise<GraphCleanup>; sent: true }
| { code: 'graph-error' | 'graph-permission'; detail: string; sent: false }
/** What happened to the copy in the sender mailbox. */
export type GraphCleanup = 'deleted' | 'left'
type LargeArgs = {
/** Waits between looks at the sent message before deleting it. Default 2 s, 5 s, 15 s, 60 s. */
cleanupDelaysMs?: number[]
fetchImpl: typeof fetch
log: { error: (msg: string) => void; warn: (msg: string) => void }
message: Record<string, unknown>
sender: string
token: string
}
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
const permissionDetail =
`Microsoft Graph refused to create the message: the app needs the ${GRAPH_LARGE_PERMISSION} application permission ` +
'for the sender mailbox to send attachments of 3 MB and more.'
/**
* Sends a message with large attachments: draft → attachments → send → delete
* the mailbox copy. Any failure before the send deletes the draft, so no file
* is left in the mailbox. Never throws.
*/
export async function sendLargeGraphMail(attachments: GraphAttachment[], { cleanupDelaysMs = [2000, 5000, 15_000, 60_000], fetchImpl, log, message, sender, token }: LargeArgs): Promise<GraphLargeResult> {
const base = `https://graph.microsoft.com/v1.0/users/${encodeURIComponent(sender)}`
const auth = { Authorization: `Bearer ${token}` }
const json = { ...auth, 'Content-Type': 'application/json' }
const describe = async (res: Response) => `${res.status} ${(await res.text().catch(() => '')).slice(0, 300)}`
/** Removes a message from the mailbox for good; falls back to a plain delete. */
const remove = async (id: string): Promise<boolean> => {
try {
const purge = await fetchImpl(`${base}/messages/${encodeURIComponent(id)}/permanentDelete`, { headers: auth, method: 'POST' })
if (purge.status === 204 || purge.status === 200) {return true}
const res = await fetchImpl(`${base}/messages/${encodeURIComponent(id)}`, { headers: auth, method: 'DELETE' })
return res.status === 204 || res.status === 200 || res.status === 404
} catch {
return false
}
}
let draftId: string | undefined
try {
// An immutable id stays the same when the draft moves to Sent Items — that is how the copy is found again.
const created = await fetchImpl(`${base}/messages`, {
body: JSON.stringify(message),
headers: { ...json, Prefer: 'IdType="ImmutableId"' },
method: 'POST',
})
if (created.status === 401 || created.status === 403) {
log.error(`[ipal] ${permissionDetail} (${await describe(created)})`)
return { code: 'graph-permission', detail: permissionDetail, sent: false }
}
if (created.status !== 201 && created.status !== 200) {
throw new Error(`create draft failed (${await describe(created)})`)
}
draftId = ((await created.json()) as { id?: string }).id
if (!draftId) {throw new Error('create draft returned no id')}
const item = `${base}/messages/${encodeURIComponent(draftId)}`
for (const attachment of attachments) {
if (attachment.content.length < UPLOAD_SESSION_MIN_BYTES) {
const added = await fetchImpl(`${item}/attachments`, { body: JSON.stringify(inlineGraphAttachments([attachment])[0]), headers: json, method: 'POST' })
if (added.status !== 201 && added.status !== 200) {throw new Error(`add attachment failed (${await describe(added)})`)}
continue
}
const session = await fetchImpl(`${item}/attachments/createUploadSession`, {
body: JSON.stringify({ AttachmentItem: { name: attachment.name, attachmentType: 'file', contentType: attachment.contentType, size: attachment.content.length } }),
headers: json,
method: 'POST',
})
if (session.status !== 201 && session.status !== 200) {throw new Error(`create upload session failed (${await describe(session)})`)}
const { uploadUrl } = (await session.json()) as { uploadUrl?: string }
if (!uploadUrl) {throw new Error('upload session returned no uploadUrl')}
const total = attachment.content.length
for (let start = 0; start < total; start += CHUNK_BYTES) {
const end = Math.min(start + CHUNK_BYTES, total)
// The upload URL is pre-authenticated: no Authorization header (Microsoft's rule).
const put = await fetchImpl(uploadUrl, {
body: new Uint8Array(attachment.content.buffer, attachment.content.byteOffset + start, end - start) as unknown as BodyInit,
headers: { 'Content-Length': String(end - start), 'Content-Range': `bytes ${start}-${end - 1}/${total}`, 'Content-Type': 'application/octet-stream' },
method: 'PUT',
})
if (put.status !== 200 && put.status !== 201) {throw new Error(`upload failed at byte ${start} (${await describe(put)})`)}
}
}
const sent = await fetchImpl(`${item}/send`, { headers: { ...auth, 'Content-Length': '0' }, method: 'POST' })
if (sent.status !== 202) {throw new Error(`send failed (${await describe(sent)})`)}
} catch (err) {
const detail = err instanceof Error ? err.message : String(err)
log.error(`[ipal] Graph send with a large attachment failed: ${detail}`)
// Nothing went out: take the draft (and the file in it) out of the mailbox.
if (draftId && !(await remove(draftId))) {
log.error(`[ipal] Graph: could not delete the draft ${draftId} from ${sender} — delete it by hand (it holds a form file).`)
}
return { code: 'graph-error', detail, sent: false }
}
// Sent. Exchange keeps a copy in Sent Items; delete it once the message has left Drafts.
const sentId = draftId
const cleanup = (async (): Promise<GraphCleanup> => {
for (const delay of cleanupDelaysMs) {
await sleep(delay)
try {
const look = await fetchImpl(`${base}/messages/${encodeURIComponent(sentId)}?$select=isDraft`, { headers: { ...auth, Prefer: 'IdType="ImmutableId"' } })
if (look.status === 404) {return 'deleted'}
if (look.ok && ((await look.json()) as { isDraft?: boolean }).isDraft === false) {
if (await remove(sentId)) {return 'deleted'}
}
} catch {
/* try again after the next delay */
}
}
log.warn(`[ipal] Graph: the sent copy ${sentId} is still in the mailbox ${sender} — delete it by hand (it holds a form file).`)
return 'left'
})()
cleanup.catch(() => undefined)
return { cleanup, sent: true }
}
+47 -7
View File
@@ -2,15 +2,24 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js'
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
type TransportIntegrations = {
emailStatus?: IntegrationStatus | null
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
emailTransport?: 'graph' | 'smtp' | null
smtpHost?: null | string
smtpPassword?: null | string
smtpUser?: null | string
}
const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword)
/** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */
const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission'])
const STATUS_FIELD = 'emailStatus'
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
const describe = (err: unknown) =>
@@ -68,8 +77,24 @@ export const mailAdapter =
const { payload } = deps
/**
* The largest total attachment size (bytes) the current transport can
* carry, or null when the plugin knows no ceiling (the mail server's own
* limit still applies). Read by the forms module, so a File field never
* promises more than can be sent: on Graph without the large-file path and
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
*/
const attachmentLimit = async (): Promise<null | number> => {
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
if ((settings.emailTransport ?? 'smtp') !== 'graph' || !graphAvailable()) {return null}
const support = await graphLargeAttachmentSupport(args.graph)
if (support === 'ok' || support === 'unavailable' || smtpConfigured(settings)) {return null}
return GRAPH_INLINE_MAX_BYTES - 1
}
return {
name: 'ipal-mail-dispatcher',
attachmentLimit,
defaultFromAddress: smtp.defaultFromAddress,
defaultFromName: smtp.defaultFromName,
@@ -88,11 +113,24 @@ export const mailAdapter =
)
}
const transport = useGraph ? 'Microsoft Graph' : 'SMTP'
const code = useGraph ? 'graph-error' : 'smtp-error'
// A large attachment Graph cannot carry (switched off, or the app lacks
// Mail.ReadWrite) goes over SMTP when the panel has SMTP settings.
const attachments = useGraph ? toGraphAttachments(message) : []
const large = Boolean(attachments?.length) && attachmentBytes(attachments ?? []) >= GRAPH_INLINE_MAX_BYTES
const support = large ? await graphLargeAttachmentSupport(args.graph) : 'ok'
const largeOverSmtp = large && support !== 'ok' && support !== 'unavailable' && smtpConfigured(settings)
const viaGraph = useGraph && !largeOverSmtp
const transport = viaGraph ? 'Microsoft Graph' : 'SMTP'
const code = viaGraph ? 'graph-error' : 'smtp-error'
let result: unknown
try {
result = await (useGraph ? graph : smtp).sendEmail(message)
result = await (viaGraph ? graph : smtp).sendEmail(message)
// Graph found out only while sending (a token it could not read): one try over SMTP. Graph sent nothing.
const refused = result as { code?: string; sent?: boolean } | null
if (viaGraph && refused?.sent === false && GRAPH_TOO_LARGE.has(refused.code ?? '') && smtpConfigured(settings)) {
result = await smtp.sendEmail(message)
}
} catch (err) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
code,
@@ -104,10 +142,10 @@ export const mailAdapter =
// The delegates report failure as { sent: false, error, detail? } instead
// of throwing (a broken mailbox must not crash a form submission).
const failed = result as { detail?: string; error?: string; sent?: boolean } | null
const failed = result as { code?: string; detail?: string; error?: string; sent?: boolean } | null
if (failed && typeof failed === 'object' && failed.sent === false) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
code,
code: GRAPH_TOO_LARGE.has(failed.code ?? '') ? 'graph-large-files' : code,
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`,
state: 'degraded',
})
@@ -119,7 +157,9 @@ export const mailAdapter =
payload,
STATUS_FIELD,
previous,
graphFallback
large && support === 'no-permission'
? { code: 'graph-large-files', state: 'degraded' }
: graphFallback
? {
code: 'graph-unavailable',
message: