graph + mail dispatcher, test-email endpoint, notifications global
This commit is contained in:
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
import type { PayloadEmailAdapter } from 'payload';
|
||||
export type GraphAdapterArgs = {
|
||||
fallbackFromAddress?: string;
|
||||
fallbackFromName?: string;
|
||||
};
|
||||
/**
|
||||
* Payload email adapter that sends through Microsoft Graph (our Exchange),
|
||||
* using app-only client-credentials auth. Drop-in alternative to
|
||||
* panelSmtpAdapter — same PayloadEmailAdapter contract, so payload.sendEmail
|
||||
* and the form-builder's submission emails work unchanged.
|
||||
*
|
||||
* Split of configuration (deliberate):
|
||||
* - Graph credentials (tenant/client/secret/sender) = AGENCY secrets, from env.
|
||||
* The client never sees or sets them — it's our Exchange, one mailbox
|
||||
* (GRAPH_SENDER, e.g. [email protected]) for every project.
|
||||
* - From-display + recipient = per-project, from the panel (SiteIntegrations),
|
||||
* so an editor controls how the mail is labelled and where it lands.
|
||||
*
|
||||
* Wiring: email: process.env.GRAPH_CLIENT_ID ? graphAdapter() : panelSmtpAdapter()
|
||||
*
|
||||
* Azure setup (one-time, our side): App registration → Mail.Send APPLICATION
|
||||
* permission → admin consent → in Exchange, grant the app "Send As" on the
|
||||
* shared mailbox GRAPH_SENDER.
|
||||
*/
|
||||
export declare const graphAdapter: (args?: GraphAdapterArgs) => PayloadEmailAdapter;
|
||||
Vendored
+174
@@ -0,0 +1,174 @@
|
||||
import { getSiteIntegrations } from '../payload/index.js';
|
||||
/** Reads + validates the agency Graph credentials from env. */ function readGraphEnv() {
|
||||
const tenantId = process.env.GRAPH_TENANT_ID;
|
||||
const clientId = process.env.GRAPH_CLIENT_ID;
|
||||
const clientSecret = process.env.GRAPH_CLIENT_SECRET;
|
||||
const sender = process.env.GRAPH_SENDER;
|
||||
if (!tenantId || !clientId || !clientSecret || !sender) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
clientId,
|
||||
clientSecret,
|
||||
sender,
|
||||
tenantId
|
||||
};
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
*/ async function getAccessToken(env) {
|
||||
const url = `https://login.microsoftonline.com/${env.tenantId}/oauth2/v2.0/token`;
|
||||
const body = new URLSearchParams({
|
||||
client_id: env.clientId,
|
||||
client_secret: env.clientSecret,
|
||||
grant_type: 'client_credentials',
|
||||
scope: 'https://graph.microsoft.com/.default'
|
||||
});
|
||||
const res = await fetch(url, {
|
||||
body,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
method: 'POST'
|
||||
});
|
||||
if (!res.ok) {
|
||||
const detail = await res.text();
|
||||
throw new Error(`Graph token request failed (${res.status}): ${detail}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
if (!data.access_token) {
|
||||
throw new Error('Graph token response had no access_token');
|
||||
}
|
||||
return data.access_token;
|
||||
}
|
||||
/** Normalizes Payload's to/cc (string | string[] | Address[]) into Graph recipients. */ function toRecipients(value) {
|
||||
if (!value) {
|
||||
return [];
|
||||
}
|
||||
const list = Array.isArray(value) ? value : [
|
||||
value
|
||||
];
|
||||
return list.map((v)=>typeof v === 'string' ? v : v.address).filter((a)=>typeof a === 'string' && a.length > 0).map((address)=>({
|
||||
emailAddress: {
|
||||
address
|
||||
}
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* Payload email adapter that sends through Microsoft Graph (our Exchange),
|
||||
* using app-only client-credentials auth. Drop-in alternative to
|
||||
* panelSmtpAdapter — same PayloadEmailAdapter contract, so payload.sendEmail
|
||||
* and the form-builder's submission emails work unchanged.
|
||||
*
|
||||
* Split of configuration (deliberate):
|
||||
* - Graph credentials (tenant/client/secret/sender) = AGENCY secrets, from env.
|
||||
* The client never sees or sets them — it's our Exchange, one mailbox
|
||||
* (GRAPH_SENDER, e.g. [email protected]) for every project.
|
||||
* - From-display + recipient = per-project, from the panel (SiteIntegrations),
|
||||
* so an editor controls how the mail is labelled and where it lands.
|
||||
*
|
||||
* Wiring: email: process.env.GRAPH_CLIENT_ID ? graphAdapter() : panelSmtpAdapter()
|
||||
*
|
||||
* Azure setup (one-time, our side): App registration → Mail.Send APPLICATION
|
||||
* permission → admin consent → in Exchange, grant the app "Send As" on the
|
||||
* shared mailbox GRAPH_SENDER.
|
||||
*/ export const graphAdapter = (args = {})=>({ payload })=>({
|
||||
name: 'ipal-graph',
|
||||
defaultFromAddress: args.fallbackFromAddress ?? 'noreply@localhost',
|
||||
defaultFromName: args.fallbackFromName ?? 'Website',
|
||||
sendEmail: async (message)=>{
|
||||
const env = readGraphEnv();
|
||||
if (!env) {
|
||||
payload.logger.error('[ipal] Email not sent: Graph is not configured. Set GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER.');
|
||||
return {
|
||||
error: 'Graph is not configured (missing env vars).',
|
||||
sent: false
|
||||
};
|
||||
}
|
||||
// From-display comes from the panel; falls back to the caller's from.
|
||||
const panel = await getSiteIntegrations(payload);
|
||||
const fromAddress = panel.smtpFromAddress || undefined;
|
||||
const fromName = panel.smtpFromName || undefined;
|
||||
const to = toRecipients(message.to);
|
||||
if (to.length === 0) {
|
||||
payload.logger.error('[ipal] Email not sent: no valid recipient.');
|
||||
return {
|
||||
error: 'No valid recipient.',
|
||||
sent: false
|
||||
};
|
||||
}
|
||||
// Graph accepts either HTML or Text; Payload gives us html and/or text.
|
||||
const isHtml = typeof message.html === 'string' && message.html.length > 0;
|
||||
const content = isHtml ? String(message.html) : String(message.text ?? '');
|
||||
const graphMessage = {
|
||||
body: {
|
||||
content,
|
||||
contentType: isHtml ? 'HTML' : 'Text'
|
||||
},
|
||||
subject: message.subject ?? '',
|
||||
toRecipients: to,
|
||||
...message.cc ? {
|
||||
ccRecipients: toRecipients(message.cc)
|
||||
} : {},
|
||||
...message.bcc ? {
|
||||
bccRecipients: toRecipients(message.bcc)
|
||||
} : {},
|
||||
// from is only honoured if the app has Send-As for that address; when
|
||||
// it's the shared mailbox itself, omit it and Graph uses the sender.
|
||||
...fromAddress ? {
|
||||
from: {
|
||||
emailAddress: {
|
||||
address: fromAddress,
|
||||
...fromName ? {
|
||||
name: fromName
|
||||
} : {}
|
||||
}
|
||||
}
|
||||
} : {},
|
||||
// replyTo lets the recipient reply to the real submitter if the caller set it.
|
||||
...message.replyTo ? {
|
||||
replyTo: toRecipients(message.replyTo)
|
||||
} : {}
|
||||
};
|
||||
try {
|
||||
const token = await getAccessToken(env);
|
||||
// App-only: MUST target /users/{sender}, never /me.
|
||||
const res = await fetch(`https://graph.microsoft.com/v1.0/users/${encodeURIComponent(env.sender)}/sendMail`, {
|
||||
body: JSON.stringify({
|
||||
message: graphMessage,
|
||||
saveToSentItems: false
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
method: 'POST'
|
||||
});
|
||||
// sendMail returns 202 Accepted with an empty body on success.
|
||||
if (res.status === 202) {
|
||||
return {
|
||||
sent: true
|
||||
};
|
||||
}
|
||||
const detail = await res.text();
|
||||
payload.logger.error(`[ipal] Graph sendMail failed (${res.status}): ${detail}`);
|
||||
return {
|
||||
error: `Graph sendMail failed (${res.status}).`,
|
||||
sent: false
|
||||
};
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
payload.logger.error(`[ipal] Graph send error: ${msg}`);
|
||||
return {
|
||||
error: 'Graph send error.',
|
||||
sent: false
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//# sourceMappingURL=graphAdapter.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+4
@@ -1,2 +1,6 @@
|
||||
export { graphAdapter } from './graphAdapter.js';
|
||||
export type { GraphAdapterArgs } from './graphAdapter.js';
|
||||
export { mailAdapter } from './mailAdapter.js';
|
||||
export type { MailAdapterArgs } from './mailAdapter.js';
|
||||
export { sendEmail } from './sendEmail.js';
|
||||
export type { SendEmailArgs, SendEmailResult } from './sendEmail.js';
|
||||
|
||||
Vendored
+2
@@ -1,3 +1,5 @@
|
||||
export { graphAdapter } from './graphAdapter.js';
|
||||
export { mailAdapter } from './mailAdapter.js';
|
||||
// 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';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/email/index.ts"],"sourcesContent":["// Server-only exports. sendEmail imports 'server-only' (SMTP password, nodemailer)\n// so this must never be imported from a client component.\nexport { sendEmail } from './sendEmail.js'\nexport type { SendEmailArgs, SendEmailResult } from './sendEmail.js'\n"],"names":["sendEmail"],"mappings":"AAAA,mFAAmF;AACnF,0DAA0D;AAC1D,SAASA,SAAS,QAAQ,iBAAgB"}
|
||||
{"version":3,"sources":["../../../src/modules/email/index.ts"],"sourcesContent":["export { graphAdapter } from './graphAdapter.js'\nexport type { GraphAdapterArgs } from './graphAdapter.js'\nexport { mailAdapter } from './mailAdapter.js'\nexport type { MailAdapterArgs } from './mailAdapter.js'\n// Server-only exports. sendEmail imports 'server-only' (SMTP password, nodemailer)\n// so this must never be imported from a client component.\nexport { sendEmail } from './sendEmail.js'\nexport type { SendEmailArgs, SendEmailResult } from './sendEmail.js'\n"],"names":["graphAdapter","mailAdapter","sendEmail"],"mappings":"AAAA,SAASA,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,mFAAmF;AACnF,0DAA0D;AAC1D,SAASC,SAAS,QAAQ,iBAAgB"}
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
import type { PayloadEmailAdapter } from 'payload';
|
||||
import { type GraphAdapterArgs } from './graphAdapter.js';
|
||||
import { type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js';
|
||||
export type MailAdapterArgs = {
|
||||
fallbackFromAddress?: string;
|
||||
fallbackFromName?: string;
|
||||
graph?: GraphAdapterArgs;
|
||||
smtp?: PanelSmtpAdapterArgs;
|
||||
};
|
||||
/**
|
||||
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
|
||||
* (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations.
|
||||
* This is what makes the choice switchable in the panel — Payload builds the
|
||||
* email adapter at boot and can't swap it at runtime, so instead of choosing
|
||||
* between two adapters at boot we install one that delegates on every send.
|
||||
*
|
||||
* Availability guard: Graph only runs if its agency credentials exist in env
|
||||
* (this is *our* Exchange). If the panel says 'graph' but env isn't set up,
|
||||
* we DON'T silently fail — we log clearly and fall back to SMTP, so a client
|
||||
* flipping the switch without the backing config still gets mail out (over SMTP)
|
||||
* rather than silent nothing. If neither is usable, the send reports an error.
|
||||
*
|
||||
* @example
|
||||
* // payload.config.ts
|
||||
* import { mailAdapter } from '@intecion/ipal-kit'
|
||||
* email: mailAdapter()
|
||||
*/
|
||||
export declare const mailAdapter: (args?: MailAdapterArgs) => PayloadEmailAdapter;
|
||||
Vendored
+58
@@ -0,0 +1,58 @@
|
||||
import { getSiteIntegrations } from '../payload/index.js';
|
||||
import { graphAdapter } from './graphAdapter.js';
|
||||
import { panelSmtpAdapter } from './panelSmtpAdapter.js';
|
||||
/** True when the agency Graph credentials are present in the environment. */ function graphAvailable() {
|
||||
return Boolean(process.env.GRAPH_TENANT_ID && process.env.GRAPH_CLIENT_ID && process.env.GRAPH_CLIENT_SECRET && process.env.GRAPH_SENDER);
|
||||
}
|
||||
/**
|
||||
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
|
||||
* (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations.
|
||||
* This is what makes the choice switchable in the panel — Payload builds the
|
||||
* email adapter at boot and can't swap it at runtime, so instead of choosing
|
||||
* between two adapters at boot we install one that delegates on every send.
|
||||
*
|
||||
* Availability guard: Graph only runs if its agency credentials exist in env
|
||||
* (this is *our* Exchange). If the panel says 'graph' but env isn't set up,
|
||||
* we DON'T silently fail — we log clearly and fall back to SMTP, so a client
|
||||
* flipping the switch without the backing config still gets mail out (over SMTP)
|
||||
* rather than silent nothing. If neither is usable, the send reports an error.
|
||||
*
|
||||
* @example
|
||||
* // payload.config.ts
|
||||
* import { mailAdapter } from '@intecion/ipal-kit'
|
||||
* email: mailAdapter()
|
||||
*/ export const mailAdapter = (args = {})=>(deps)=>{
|
||||
// Build both delegates once; each still resolves its own config per send.
|
||||
const smtp = panelSmtpAdapter({
|
||||
fallbackFromAddress: args.fallbackFromAddress,
|
||||
fallbackFromName: args.fallbackFromName,
|
||||
...args.smtp
|
||||
})(deps);
|
||||
const graph = graphAdapter({
|
||||
fallbackFromAddress: args.fallbackFromAddress,
|
||||
fallbackFromName: args.fallbackFromName,
|
||||
...args.graph
|
||||
})(deps);
|
||||
const { payload } = deps;
|
||||
return {
|
||||
name: 'ipal-mail-dispatcher',
|
||||
defaultFromAddress: smtp.defaultFromAddress,
|
||||
defaultFromName: smtp.defaultFromName,
|
||||
sendEmail: async (message)=>{
|
||||
const settings = await getSiteIntegrations(payload);
|
||||
const choice = settings.emailTransport ?? 'smtp';
|
||||
if (choice === 'graph') {
|
||||
if (graphAvailable()) {
|
||||
return graph.sendEmail(message);
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
//# sourceMappingURL=mailAdapter.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/email/mailAdapter.ts"],"sourcesContent":["import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'\n\nimport { getSiteIntegrations } from '../payload/index.js'\nimport { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'\nimport { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'\n\ntype TransportIntegrations = {\n /** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */\n emailTransport?: 'graph' | 'smtp' | null\n}\n\nexport type MailAdapterArgs = {\n fallbackFromAddress?: string\n fallbackFromName?: string\n graph?: GraphAdapterArgs\n smtp?: PanelSmtpAdapterArgs\n}\n\n/** True when the agency Graph credentials are present in the environment. */\nfunction graphAvailable(): boolean {\n return Boolean(\n process.env.GRAPH_TENANT_ID &&\n process.env.GRAPH_CLIENT_ID &&\n process.env.GRAPH_CLIENT_SECRET &&\n process.env.GRAPH_SENDER,\n )\n}\n\n/**\n * Dispatcher email adapter: wired into the config ONCE, but picks the transport\n * (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations.\n * This is what makes the choice switchable in the panel — Payload builds the\n * email adapter at boot and can't swap it at runtime, so instead of choosing\n * between two adapters at boot we install one that delegates on every send.\n *\n * Availability guard: Graph only runs if its agency credentials exist in env\n * (this is *our* Exchange). If the panel says 'graph' but env isn't set up,\n * we DON'T silently fail — we log clearly and fall back to SMTP, so a client\n * flipping the switch without the backing config still gets mail out (over SMTP)\n * rather than silent nothing. If neither is usable, the send reports an error.\n *\n * @example\n * // payload.config.ts\n * import { mailAdapter } from '@intecion/ipal-kit'\n * email: mailAdapter()\n */\nexport const mailAdapter =\n (args: MailAdapterArgs = {}): PayloadEmailAdapter =>\n (deps) => {\n // Build both delegates once; each still resolves its own config per send.\n const smtp = panelSmtpAdapter({\n fallbackFromAddress: args.fallbackFromAddress,\n fallbackFromName: args.fallbackFromName,\n ...args.smtp,\n })(deps)\n const graph = graphAdapter({\n fallbackFromAddress: args.fallbackFromAddress,\n fallbackFromName: args.fallbackFromName,\n ...args.graph,\n })(deps)\n\n const { payload } = deps\n\n return {\n name: 'ipal-mail-dispatcher',\n defaultFromAddress: smtp.defaultFromAddress,\n defaultFromName: smtp.defaultFromName,\n\n sendEmail: async (message: SendEmailOptions) => {\n const settings = await getSiteIntegrations<TransportIntegrations>(payload)\n const choice = settings.emailTransport ?? 'smtp'\n\n if (choice === 'graph') {\n if (graphAvailable()) {\n return graph.sendEmail(message)\n }\n // Panel asked for Graph but the agency creds aren't configured for\n // this project. Fall back to SMTP rather than silently dropping mail.\n payload.logger.warn(\n '[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',\n )\n return smtp.sendEmail(message)\n }\n\n return smtp.sendEmail(message)\n },\n }\n }\n"],"names":["getSiteIntegrations","graphAdapter","panelSmtpAdapter","graphAvailable","Boolean","process","env","GRAPH_TENANT_ID","GRAPH_CLIENT_ID","GRAPH_CLIENT_SECRET","GRAPH_SENDER","mailAdapter","args","deps","smtp","fallbackFromAddress","fallbackFromName","graph","payload","name","defaultFromAddress","defaultFromName","sendEmail","message","settings","choice","emailTransport","logger","warn"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,sBAAqB;AACzD,SAASC,YAAY,QAA+B,oBAAmB;AACvE,SAASC,gBAAgB,QAAmC,wBAAuB;AAcnF,2EAA2E,GAC3E,SAASC;IACP,OAAOC,QACLC,QAAQC,GAAG,CAACC,eAAe,IAC3BF,QAAQC,GAAG,CAACE,eAAe,IAC3BH,QAAQC,GAAG,CAACG,mBAAmB,IAC/BJ,QAAQC,GAAG,CAACI,YAAY;AAE5B;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC,cACX,CAACC,OAAwB,CAAC,CAAC,GAC3B,CAACC;QACC,0EAA0E;QAC1E,MAAMC,OAAOZ,iBAAiB;YAC5Ba,qBAAqBH,KAAKG,mBAAmB;YAC7CC,kBAAkBJ,KAAKI,gBAAgB;YACvC,GAAGJ,KAAKE,IAAI;QACd,GAAGD;QACH,MAAMI,QAAQhB,aAAa;YACzBc,qBAAqBH,KAAKG,mBAAmB;YAC7CC,kBAAkBJ,KAAKI,gBAAgB;YACvC,GAAGJ,KAAKK,KAAK;QACf,GAAGJ;QAEH,MAAM,EAAEK,OAAO,EAAE,GAAGL;QAEpB,OAAO;YACLM,MAAM;YACNC,oBAAoBN,KAAKM,kBAAkB;YAC3CC,iBAAiBP,KAAKO,eAAe;YAErCC,WAAW,OAAOC;gBAChB,MAAMC,WAAW,MAAMxB,oBAA2CkB;gBAClE,MAAMO,SAASD,SAASE,cAAc,IAAI;gBAE1C,IAAID,WAAW,SAAS;oBACtB,IAAItB,kBAAkB;wBACpB,OAAOc,MAAMK,SAAS,CAACC;oBACzB;oBACA,mEAAmE;oBACnE,sEAAsE;oBACtEL,QAAQS,MAAM,CAACC,IAAI,CACjB;oBAEF,OAAOd,KAAKQ,SAAS,CAACC;gBACxB;gBAEA,OAAOT,KAAKQ,SAAS,CAACC;YACxB;QACF;IACF,EAAC"}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import type { Endpoint } from 'payload';
|
||||
/**
|
||||
* Custom endpoint: send a test email to a given address through whatever
|
||||
* transport is currently active (SMTP or Graph — mailAdapter reads the panel
|
||||
* setting per send, so the test exercises the REAL path a form email would
|
||||
* take). Mounted at POST /api/ipal/test-email.
|
||||
*
|
||||
* Admin-only: uses payload.sendEmail (server-side), and requires an
|
||||
* authenticated admin user — a test-send button must never be open to the
|
||||
* public (it would be an open relay / spam vector).
|
||||
*
|
||||
* Returns the adapter's own result so the panel can show exactly what happened,
|
||||
* including the transport-specific error (SMTP auth failure, Graph 401, etc.).
|
||||
*/
|
||||
export declare const testEmailEndpoint: Endpoint;
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import { addDataAndFileToRequest } from 'payload';
|
||||
/**
|
||||
* Custom endpoint: send a test email to a given address through whatever
|
||||
* transport is currently active (SMTP or Graph — mailAdapter reads the panel
|
||||
* setting per send, so the test exercises the REAL path a form email would
|
||||
* take). Mounted at POST /api/ipal/test-email.
|
||||
*
|
||||
* Admin-only: uses payload.sendEmail (server-side), and requires an
|
||||
* authenticated admin user — a test-send button must never be open to the
|
||||
* public (it would be an open relay / spam vector).
|
||||
*
|
||||
* Returns the adapter's own result so the panel can show exactly what happened,
|
||||
* including the transport-specific error (SMTP auth failure, Graph 401, etc.).
|
||||
*/ export const testEmailEndpoint = {
|
||||
handler: async (req)=>{
|
||||
// Auth: only signed-in admins may trigger a send.
|
||||
if (!req.user) {
|
||||
return Response.json({
|
||||
error: 'Unauthorized',
|
||||
ok: false
|
||||
}, {
|
||||
status: 401
|
||||
});
|
||||
}
|
||||
await addDataAndFileToRequest(req);
|
||||
const to = req.data?.to?.trim();
|
||||
if (!to || !/^[^@\s]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(to)) {
|
||||
return Response.json({
|
||||
error: 'Provide a valid recipient address.',
|
||||
ok: false
|
||||
}, {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
try {
|
||||
const info = await req.payload.sendEmail({
|
||||
html: '<p>This is a test message from <strong>ipal-kit</strong>. If you received it, outbound email is configured correctly.</p>',
|
||||
subject: 'ipal-kit — test email',
|
||||
text: 'This is a test message from ipal-kit. If you received it, outbound email is configured correctly.',
|
||||
to
|
||||
});
|
||||
// Payload's sendEmail resolves with the adapter's result. Our adapters
|
||||
// return { sent: boolean, error?: string }; nodemailer returns info with
|
||||
// messageId. Normalize to a simple ok/message for the panel.
|
||||
const sent = info && typeof info === 'object' && 'sent' in info ? info.sent !== false : true;
|
||||
if (!sent) {
|
||||
const error = info?.error ?? 'Send failed (see server logs).';
|
||||
return Response.json({
|
||||
error,
|
||||
ok: false
|
||||
}, {
|
||||
status: 502
|
||||
});
|
||||
}
|
||||
return Response.json({
|
||||
message: `Test email sent to ${to}.`,
|
||||
ok: true
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
req.payload.logger.error(`[ipal] Test email failed: ${message}`);
|
||||
return Response.json({
|
||||
error: 'Send failed. Check transport settings and server logs.',
|
||||
ok: false
|
||||
}, {
|
||||
status: 502
|
||||
});
|
||||
}
|
||||
},
|
||||
method: 'post',
|
||||
path: '/ipal/test-email'
|
||||
};
|
||||
|
||||
//# sourceMappingURL=testEmailEndpoint.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/modules/email/test/testEmailEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload'\n\nimport { addDataAndFileToRequest } from 'payload'\n\n/**\n * Custom endpoint: send a test email to a given address through whatever\n * transport is currently active (SMTP or Graph — mailAdapter reads the panel\n * setting per send, so the test exercises the REAL path a form email would\n * take). Mounted at POST /api/ipal/test-email.\n *\n * Admin-only: uses payload.sendEmail (server-side), and requires an\n * authenticated admin user — a test-send button must never be open to the\n * public (it would be an open relay / spam vector).\n *\n * Returns the adapter's own result so the panel can show exactly what happened,\n * including the transport-specific error (SMTP auth failure, Graph 401, etc.).\n */\nexport const testEmailEndpoint: Endpoint = {\n handler: async (req: PayloadRequest) => {\n // Auth: only signed-in admins may trigger a send.\n if (!req.user) {\n return Response.json({ error: 'Unauthorized', ok: false }, { status: 401 })\n }\n\n await addDataAndFileToRequest(req)\n const to = (req.data?.to as string | undefined)?.trim()\n\n if (!to || !/^[^@\\s]+@[^\\s@][^\\s.@]*\\.[^\\s@]+$/.test(to)) {\n return Response.json(\n { error: 'Provide a valid recipient address.', ok: false },\n { status: 400 },\n )\n }\n\n try {\n const info = await req.payload.sendEmail({\n html: '<p>This is a test message from <strong>ipal-kit</strong>. If you received it, outbound email is configured correctly.</p>',\n subject: 'ipal-kit — test email',\n text: 'This is a test message from ipal-kit. If you received it, outbound email is configured correctly.',\n to,\n })\n\n // Payload's sendEmail resolves with the adapter's result. Our adapters\n // return { sent: boolean, error?: string }; nodemailer returns info with\n // messageId. Normalize to a simple ok/message for the panel.\n const sent =\n info && typeof info === 'object' && 'sent' in info\n ? (info as { sent?: boolean }).sent !== false\n : true\n\n if (!sent) {\n const error = (info as { error?: string })?.error ?? 'Send failed (see server logs).'\n return Response.json({ error, ok: false }, { status: 502 })\n }\n\n return Response.json({ message: `Test email sent to ${to}.`, ok: true })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n req.payload.logger.error(`[ipal] Test email failed: ${message}`)\n return Response.json(\n { error: 'Send failed. Check transport settings and server logs.', ok: false },\n { status: 502 },\n )\n }\n },\n method: 'post',\n path: '/ipal/test-email',\n}\n"],"names":["addDataAndFileToRequest","testEmailEndpoint","handler","req","user","Response","json","error","ok","status","to","data","trim","test","info","payload","sendEmail","html","subject","text","sent","message","err","Error","String","logger","method","path"],"mappings":"AAEA,SAASA,uBAAuB,QAAQ,UAAS;AAEjD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,oBAA8B;IACzCC,SAAS,OAAOC;QACd,kDAAkD;QAClD,IAAI,CAACA,IAAIC,IAAI,EAAE;YACb,OAAOC,SAASC,IAAI,CAAC;gBAAEC,OAAO;gBAAgBC,IAAI;YAAM,GAAG;gBAAEC,QAAQ;YAAI;QAC3E;QAEA,MAAMT,wBAAwBG;QAC9B,MAAMO,KAAMP,IAAIQ,IAAI,EAAED,IAA2BE;QAEjD,IAAI,CAACF,MAAM,CAAC,oCAAoCG,IAAI,CAACH,KAAK;YACxD,OAAOL,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAsCC,IAAI;YAAM,GACzD;gBAAEC,QAAQ;YAAI;QAElB;QAEA,IAAI;YACF,MAAMK,OAAO,MAAMX,IAAIY,OAAO,CAACC,SAAS,CAAC;gBACvCC,MAAM;gBACNC,SAAS;gBACTC,MAAM;gBACNT;YACF;YAEA,uEAAuE;YACvE,yEAAyE;YACzE,6DAA6D;YAC7D,MAAMU,OACJN,QAAQ,OAAOA,SAAS,YAAY,UAAUA,OAC1C,AAACA,KAA4BM,IAAI,KAAK,QACtC;YAEN,IAAI,CAACA,MAAM;gBACT,MAAMb,QAAQ,AAACO,MAA6BP,SAAS;gBACrD,OAAOF,SAASC,IAAI,CAAC;oBAAEC;oBAAOC,IAAI;gBAAM,GAAG;oBAAEC,QAAQ;gBAAI;YAC3D;YAEA,OAAOJ,SAASC,IAAI,CAAC;gBAAEe,SAAS,CAAC,mBAAmB,EAAEX,GAAG,CAAC,CAAC;gBAAEF,IAAI;YAAK;QACxE,EAAE,OAAOc,KAAK;YACZ,MAAMD,UAAUC,eAAeC,QAAQD,IAAID,OAAO,GAAGG,OAAOF;YAC5DnB,IAAIY,OAAO,CAACU,MAAM,CAAClB,KAAK,CAAC,CAAC,0BAA0B,EAAEc,SAAS;YAC/D,OAAOhB,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAA0DC,IAAI;YAAM,GAC7E;gBAAEC,QAAQ;YAAI;QAElB;IACF;IACAiB,QAAQ;IACRC,MAAM;AACR,EAAC"}
|
||||
Reference in New Issue
Block a user