init commit for iPAL-kit plugin

This commit is contained in:
2026-07-18 20:30:23 +02:00
parent 10638127a9
commit 5733a9c8bf
119 changed files with 6892 additions and 411 deletions
+4
View File
@@ -0,0 +1,4 @@
// Server-only exports. sendEmail imports 'server-only' (SMTP password, nodemailer)
// so this must never be imported from a client component.
export { sendEmail } from './sendEmail.js'
export type { SendEmailArgs, SendEmailResult } from './sendEmail.js'
+108
View File
@@ -0,0 +1,108 @@
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
}
export type PanelSmtpAdapterArgs = {
/**
* Used only until the panel is filled in — Payload requires a from-address
* synchronously at boot, before any global can be read. Once SiteIntegrations
* has an address, it wins.
*/
fallbackFromAddress?: string
fallbackFromName?: string
}
/**
* Payload email adapter backed by the SMTP settings in the SiteIntegrations
* global.
*
* Why this exists: Payload builds its email adapter once, at boot, from the
* config — which would normally mean SMTP credentials living in env vars and a
* redeploy to change them. This adapter instead resolves SMTP on every send, so
* an editor can change the mailbox in the admin panel and the next email uses
* it.
*
* Wiring it into the config means `payload.sendEmail` works everywhere — which
* includes the form-builder's own submission emails (the ones an editor
* configures per form under "Emails"). Those go out over the panel's SMTP with
* no extra code.
*
* Boot-time constraints shape two details:
* - `defaultFromAddress` / `defaultFromName` must be returned synchronously, so
* they're placeholders; the real from-address is applied per message below.
* - nodemailer is imported dynamically inside sendEmail, so merely loading the
* Payload config (or running `generate:importmap`) doesn't pull it in.
*/
export const panelSmtpAdapter =
(args: PanelSmtpAdapterArgs = {}): PayloadEmailAdapter =>
({ payload }) => ({
name: 'ipal-panel-smtp',
defaultFromAddress: args.fallbackFromAddress ?? 'noreply@localhost',
defaultFromName: args.fallbackFromName ?? 'Website',
sendEmail: async (message: SendEmailOptions) => {
const smtp = await getSiteIntegrations<SmtpIntegrations>(payload)
const host = smtp.smtpHost
const port = smtp.smtpPort ?? 587
const user = smtp.smtpUser
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 }
}
// The panel is the source of truth for the sender; fall back to whatever
// the caller set (Payload fills in defaultFromAddress when unset).
const fromAddress = smtp.smtpFromAddress
const fromName = smtp.smtpFromName
const from = fromAddress
? fromName
? `${fromName} <${fromAddress}>`
: fromAddress
: message.from
// Defence in depth against header injection. Modern nodemailer already
// 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 { default: nodemailer } = await import('nodemailer')
const transporter = nodemailer.createTransport({
auth: { pass, user },
host,
port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
})
try {
const info = await transporter.sendMail({
...message,
from,
...(message.subject ? { subject: stripCRLF(message.subject) } : {}),
})
return { messageId: info.messageId, sent: true }
} 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 }
}
},
})
+95
View File
@@ -0,0 +1,95 @@
import 'server-only'
import type { BasePayload } from 'payload'
import nodemailer from 'nodemailer'
import { getSiteIntegrations } from '../payload/index.js'
/** SMTP fields the sender reads from SiteIntegrations. */
type SmtpIntegrations = {
smtpFromAddress?: null | string
smtpFromName?: null | string
smtpHost?: null | string
smtpPassword?: null | string
smtpPort?: null | number
smtpUser?: null | string
}
export type SendEmailArgs = {
/** Override the configured from-address for this message. */
from?: string
/** HTML body. */
html: string
/** Payload instance — used to read SMTP config from SiteIntegrations. */
payload: BasePayload
replyTo?: string
subject: string
/** Optional plain-text fallback. */
text?: string
to: string | string[]
}
export type SendEmailResult = { error: string; sent: false } | { messageId: string; sent: true }
/**
* Sends an email using SMTP settings from the SiteIntegrations global.
*
* Reads config at call time (not at boot) so editors can change SMTP in the
* admin panel without a restart — consistent with the plugin's panel-managed
* model. `server-only` keeps the SMTP password out of any client bundle.
*
* Returns a result object rather than throwing, so callers (e.g. form
* submission) can handle failure without a try/catch and never leak SMTP
* details to the client.
*/
export async function sendEmail({
from,
html,
payload,
replyTo,
subject,
text,
to,
}: SendEmailArgs): Promise<SendEmailResult> {
const smtp = await getSiteIntegrations<SmtpIntegrations>(payload)
const host = smtp.smtpHost
const port = smtp.smtpPort ?? 587
const user = smtp.smtpUser
const pass = smtp.smtpPassword
if (!host || !user || !pass) {
return { error: 'SMTP is not configured in Site Integrations.', sent: false }
}
const fromAddress = from ?? smtp.smtpFromAddress
if (!fromAddress) {
return { error: 'No from-address configured.', sent: false }
}
const fromName = smtp.smtpFromName
const fromHeader = fromName ? `${fromName} <${fromAddress}>` : fromAddress
const transporter = nodemailer.createTransport({
auth: { pass, user },
host,
port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
})
try {
const info = await transporter.sendMail({
from: fromHeader,
html,
subject,
to,
...(text ? { text } : {}),
...(replyTo ? { replyTo } : {}),
})
return { messageId: info.messageId, sent: true }
} catch (err) {
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
return { error: 'Failed to send email.', sent: false }
}
}