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:
co-authored by
Claude Fable 5.2
parent
0ba0014ed5
commit
6003b3d7d7
@@ -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 }
|
||||
}
|
||||
Reference in New Issue
Block a user