Fix turnstile
This commit is contained in:
@@ -1,28 +1,34 @@
|
||||
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
|
||||
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
|
||||
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
||||
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
|
||||
|
||||
type TransportIntegrations = {
|
||||
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
emailTransport?: 'smtp' | 'graph' | null
|
||||
emailStatus?: IntegrationStatus | null
|
||||
}
|
||||
|
||||
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) =>
|
||||
(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200)
|
||||
|
||||
export type MailAdapterArgs = {
|
||||
smtp?: PanelSmtpAdapterArgs
|
||||
graph?: GraphAdapterArgs
|
||||
fallbackFromAddress?: string
|
||||
fallbackFromName?: string
|
||||
graph?: GraphAdapterArgs
|
||||
smtp?: PanelSmtpAdapterArgs
|
||||
}
|
||||
|
||||
/** True when the agency Graph credentials are present in the environment. */
|
||||
function graphAvailable(): boolean {
|
||||
return Boolean(
|
||||
process.env.GRAPH_TENANT_ID &&
|
||||
process.env.GRAPH_CLIENT_ID &&
|
||||
process.env.GRAPH_CLIENT_SECRET &&
|
||||
process.env.GRAPH_SENDER,
|
||||
process.env.GRAPH_CLIENT_ID &&
|
||||
process.env.GRAPH_CLIENT_SECRET &&
|
||||
process.env.GRAPH_SENDER,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -69,20 +75,58 @@ export const mailAdapter =
|
||||
sendEmail: async (message: SendEmailOptions) => {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const choice = settings.emailTransport ?? 'smtp'
|
||||
const previous = settings[STATUS_FIELD]
|
||||
const useGraph = choice === 'graph' && graphAvailable()
|
||||
const graphFallback = choice === 'graph' && !useGraph
|
||||
|
||||
if (choice === 'graph') {
|
||||
if (graphAvailable()) {
|
||||
return graph.sendEmail(message)
|
||||
}
|
||||
if (graphFallback) {
|
||||
// Panel asked for Graph but the agency creds aren't configured for
|
||||
// this project. Fall back to SMTP rather than silently dropping mail.
|
||||
payload.logger.warn(
|
||||
'[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
|
||||
)
|
||||
return smtp.sendEmail(message)
|
||||
}
|
||||
|
||||
return smtp.sendEmail(message)
|
||||
const transport = useGraph ? 'Microsoft Graph' : 'SMTP'
|
||||
const code = useGraph ? 'graph-error' : 'smtp-error'
|
||||
let result: unknown
|
||||
try {
|
||||
result = await (useGraph ? graph : smtp).sendEmail(message)
|
||||
} catch (err) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
||||
state: 'degraded',
|
||||
code,
|
||||
message: `${transport}: ${describe(err)}`,
|
||||
})
|
||||
throw err // callers (form-builder, Send test) still see the failure
|
||||
}
|
||||
|
||||
// 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 { sent?: boolean; error?: string; detail?: string } | null
|
||||
if (failed && typeof failed === 'object' && failed.sent === false) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
||||
state: 'degraded',
|
||||
code,
|
||||
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`,
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// Graph selected but unavailable is a configuration problem even if SMTP delivered.
|
||||
await recordIntegrationStatus(
|
||||
payload,
|
||||
STATUS_FIELD,
|
||||
previous,
|
||||
graphFallback
|
||||
? {
|
||||
state: 'degraded',
|
||||
code: 'graph-unavailable',
|
||||
message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.',
|
||||
}
|
||||
: { state: 'ok' },
|
||||
)
|
||||
return result
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
|
||||
/** SMTP fields the adapter reads from SiteIntegrations. */
|
||||
type SmtpIntegrations = {
|
||||
smtpFromAddress?: null | string
|
||||
smtpFromName?: null | string
|
||||
smtpHost?: null | string
|
||||
smtpPassword?: null | string
|
||||
smtpPort?: null | number
|
||||
smtpUser?: null | string
|
||||
smtpHost?: string | null
|
||||
smtpPort?: number | null
|
||||
smtpUser?: string | null
|
||||
smtpPassword?: string | null
|
||||
smtpFromAddress?: string | null
|
||||
smtpFromName?: string | null
|
||||
}
|
||||
|
||||
export type PanelSmtpAdapterArgs = {
|
||||
@@ -59,8 +58,10 @@ export const panelSmtpAdapter =
|
||||
const pass = smtp.smtpPassword
|
||||
|
||||
if (!host || !user || !pass) {
|
||||
payload.logger.error('[ipal] Email not sent: SMTP is not configured in Site Integrations.')
|
||||
return { error: 'SMTP is not configured in Site Integrations.', sent: false }
|
||||
payload.logger.error(
|
||||
'[ipal] Email not sent: SMTP is not configured in Site Integrations.',
|
||||
)
|
||||
return { sent: false, error: 'SMTP is not configured in Site Integrations.' }
|
||||
}
|
||||
|
||||
// The panel is the source of truth for the sender; fall back to whatever
|
||||
@@ -77,18 +78,15 @@ export const panelSmtpAdapter =
|
||||
// normalises CRLF in standard headers, but the form-builder interpolates
|
||||
// user data into the subject via {{field}} placeholders, so strip any
|
||||
// newlines from header-bound values before they reach the transport.
|
||||
const stripCRLF = (v: unknown): string =>
|
||||
String(v ?? '')
|
||||
.replace(/[\r\n]+/g, ' ')
|
||||
.trim()
|
||||
const stripCRLF = (v: unknown): string => String(v ?? '').replace(/[\r\n]+/g, ' ').trim()
|
||||
|
||||
const { default: nodemailer } = await import('nodemailer')
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
auth: { pass, user },
|
||||
host,
|
||||
port,
|
||||
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
|
||||
auth: { user, pass },
|
||||
})
|
||||
|
||||
try {
|
||||
@@ -97,12 +95,13 @@ export const panelSmtpAdapter =
|
||||
from,
|
||||
...(message.subject ? { subject: stripCRLF(message.subject) } : {}),
|
||||
})
|
||||
return { messageId: info.messageId, sent: true }
|
||||
return { sent: true, messageId: info.messageId }
|
||||
} catch (err) {
|
||||
// Never surface SMTP internals to the caller — a form submission
|
||||
// shouldn't fail loudly because the mailbox is misconfigured.
|
||||
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
|
||||
return { error: 'Failed to send email.', sent: false }
|
||||
// `detail` is for the panel status (mailAdapter), not for end users.
|
||||
return { sent: false, error: 'Failed to send email.', detail: (err as Error).message }
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user