@stacksjs/email 0.72.56 → 0.72.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{mkdir,writeFile}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{log}from"@stacksjs/logging";import{template}from"../template";import{BaseEmailDriver}from"./base";const STORE_LIMIT=100,captured=[];export class LogEmailDriver extends BaseEmailDriver{name="log";resolveDir(){const fromEnv=process.env.LOG_MAIL_DIR;if(fromEnv)return resolve(fromEnv);return resolve(join(import.meta.dir,"..","..","..","..","..","logs","mail"))}async send(message,options){try{this.validateMessage(message);let rendered;if(message.template){const t=await template(message.template,options);if(t)rendered={html:t.html,text:t.text}}const html=rendered?.html??message.html,text=rendered?.text??message.text,stamp=new Date,safeSubject=(message.subject||"no-subject").replace(/[^\w.-]+/g,"-").slice(0,60),filename=`${stamp.toISOString().replace(/[:.]/g,"-")}-${safeSubject}.html`,dir=this.resolveDir();try{await mkdir(dir,{recursive:!0});const filePath=join(dir,filename),body=html?html:text?`<pre>${escapeHtml(text)}</pre>`:"<em>(empty body)</em>",headerBlock=renderHeader({stamp,message});await writeFile(filePath,`${headerBlock}
1
+ import{mkdir,writeFile}from"node:fs/promises";import{join,resolve}from"node:path";import{log}from"@stacksjs/logging";import{template}from"../template";import{BaseEmailDriver}from"./base";const STORE_LIMIT=100,captured=[];export class LogEmailDriver extends BaseEmailDriver{name="log";resolveDir(){const fromEnv=process.env.LOG_MAIL_DIR;if(fromEnv)return resolve(fromEnv);return resolve(join(import.meta.dir,"..","..","..","..","..","logs","mail"))}async send(message,options){try{this.validateMessage(message);let rendered;if(message.template){const t=await template(message.template,options);if(t)rendered={html:t.html,text:t.text}}const html=rendered?.html??message.html,text=rendered?.text??message.text,stamp=new Date,safeSubject=(message.subject||"no-subject").replace(/[^\w.-]+/g,"-").slice(0,60),filename=`${stamp.toISOString().replace(/[:.]/g,"-")}-${safeSubject}.html`,dir=this.resolveDir();try{await mkdir(dir,{recursive:!0});const filePath=join(dir,filename),body=html?html:text?`<pre>${escapeHtml(text)}</pre>`:"<em>(empty body)</em>",headerBlock=renderHeader({stamp,message});await writeFile(filePath,`${headerBlock}
2
2
  ${body}
3
3
  `)}catch(err){log.warn(`[email:log] could not write inspection file: ${err.message}`)}const flatTo=Array.isArray(message.to)?message.to.map((t)=>typeof t==="string"?t:t.address).join(", "):typeof message.to==="string"?message.to:message.to.address;log.info(`[email:log] would send \u2192 ${flatTo} :: ${message.subject}`);captured.push({...message,sentAt:stamp,rendered});if(captured.length>STORE_LIMIT)captured.splice(0,captured.length-STORE_LIMIT);return this.handleSuccess(message,`log-${stamp.getTime()}`)}catch(error){return this.handleError(error,message)}}static captured(){return captured}static reset(){captured.length=0}}function renderHeader({stamp,message}){return["<!--",` Captured by @stacksjs/email log driver at ${stamp.toISOString()}`,` From: ${formatAddr(message.from)}`,` To: ${formatList(message.to)}`,message.cc?` Cc: ${formatList(message.cc)}`:null,message.bcc?` Bcc: ${formatList(message.bcc)}`:null,` Subject: ${message.subject}`,"-->"].filter(Boolean).join(`
4
4
  `)}function formatAddr(v){if(!v)return"";if(typeof v==="string")return v;const o=v;return o.name?`${o.name} <${o.address??""}>`:o.address??""}function formatList(v){if(Array.isArray(v))return v.map(formatAddr).join(", ");return formatAddr(v)}function escapeHtml(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[c])}export default LogEmailDriver;
@@ -1 +1 @@
1
- import{Buffer}from"node:buffer";import{suppress}from"./suppression";import{recordWebhookEventOrSkip}from"./webhook-dedup";import{emitEmailBounceHard,emitEmailBounceSoft,emitEmailComplaint,emitEmailUnsubscribe,suppressionTypeFor}from"./webhook-events";import{verifyMailgunSignature,verifyPostmarkAuth,verifySendgridSignature,verifySesSnsSignature}from"./webhook-signatures";const OK_DUPLICATE={status:200,body:{ok:!0,processed:!1,reason:"duplicate"}};function unauthorized(reason){return{status:401,body:{ok:!1,reason}}}function badRequest(reason){return{status:400,body:{ok:!1,reason}}}async function dispatchClassifiedEvent(classification,payload){const suppressionType=suppressionTypeFor(classification);if(suppressionType)await suppress(payload.email,suppressionType,payload.reason);switch(classification){case"bounce-hard":await emitEmailBounceHard(payload);break;case"bounce-soft":await emitEmailBounceSoft(payload);break;case"complaint":await emitEmailComplaint(payload);break;case"unsubscribe":await emitEmailUnsubscribe(payload);break;case"delivered":break}}export async function handleMailgunWebhook(rawBody,config){let parsed;try{parsed=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const sig=parsed.signature,event=parsed["event-data"];if(!sig||!event)return badRequest("missing-fields");const v=verifyMailgunSignature({timestamp:sig.timestamp,token:sig.token,signature:sig.signature,signingKey:config.signingKey,toleranceSeconds:config.toleranceSeconds});if(!v.ok)return unauthorized(v.reason);if(!await recordWebhookEventOrSkip("mailgun",event.id))return OK_DUPLICATE;const classification=classifyMailgunEvent(event.event,event.severity);if(!classification)return{status:200,body:{ok:!0,processed:!1,reason:"unhandled-event"}};await dispatchClassifiedEvent(classification,{email:event.recipient,provider:"mailgun",reason:event.reason,raw:event});return{status:200,body:{ok:!0,processed:!0,classification}}}function classifyMailgunEvent(event,severity){switch(event){case"failed":return severity==="temporary"?"bounce-soft":"bounce-hard";case"complained":return"complaint";case"unsubscribed":return"unsubscribe";case"delivered":return"delivered";default:return null}}export async function handlePostmarkWebhook(rawBody,authorizationHeader,sourceIp,config){const v=verifyPostmarkAuth({authorizationHeader,expectedUsername:config.username,expectedPassword:config.password,sourceIp,ipAllowlist:config.ipAllowlist});if(!v.ok)return unauthorized(v.reason);let parsed;try{parsed=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const eventId=String(parsed.ID??parsed.MessageID??""),email=String(parsed.Email??parsed.Recipient??"");if(!email)return badRequest("missing-recipient");if(!await recordWebhookEventOrSkip("postmark",eventId))return OK_DUPLICATE;const classification=classifyPostmarkEvent(parsed);if(!classification)return{status:200,body:{ok:!0,processed:!1,reason:"unhandled-event"}};await dispatchClassifiedEvent(classification,{email,provider:"postmark",reason:parsed.Description,raw:parsed});return{status:200,body:{ok:!0,processed:!0,classification}}}function classifyPostmarkEvent(msg){switch(msg.RecordType){case"Bounce":return msg.TypeCode===1?"bounce-hard":"bounce-soft";case"SpamComplaint":return"complaint";case"SubscriptionChange":return msg.SuppressSending?"unsubscribe":null;case"Delivery":return"delivered";default:return null}}export async function handleSesWebhook(rawBody,config={}){let snsMessage;try{snsMessage=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const v=await verifySesSnsSignature({message:snsMessage,certUrlHostAllowlist:config.certUrlHostAllowlist,fetchCert:config.fetchCert});if(!v.ok)return unauthorized(v.reason);if(snsMessage.Type==="SubscriptionConfirmation"){if(config.autoConfirmSubscriptions!==!1&&snsMessage.SubscribeURL)try{await fetch(snsMessage.SubscribeURL)}catch{}return{status:200,body:{ok:!0,processed:!0,reason:"subscription-confirmed"}}}if(snsMessage.Type==="UnsubscribeConfirmation")return{status:200,body:{ok:!0,processed:!0,reason:"subscription-removed"}};let innerMessage;try{innerMessage=JSON.parse(snsMessage.Message)}catch{return badRequest("invalid-inner-json")}if(!await recordWebhookEventOrSkip("ses",snsMessage.MessageId))return OK_DUPLICATE;const dispatched=[];if(innerMessage.notificationType==="Bounce"&&innerMessage.bounce){const classification=innerMessage.bounce.bounceType==="Permanent"?"bounce-hard":"bounce-soft";for(const r of innerMessage.bounce.bouncedRecipients){await dispatchClassifiedEvent(classification,{email:r.emailAddress,provider:"ses",reason:r.diagnosticCode,raw:innerMessage});dispatched.push(classification)}}else if(innerMessage.notificationType==="Complaint"&&innerMessage.complaint)for(const r of innerMessage.complaint.complainedRecipients){await dispatchClassifiedEvent("complaint",{email:r.emailAddress,provider:"ses",reason:innerMessage.complaint.complaintFeedbackType,raw:innerMessage});dispatched.push("complaint")}else if(innerMessage.notificationType==="Delivery"&&innerMessage.delivery)for(const r of innerMessage.delivery.recipients){await dispatchClassifiedEvent("delivered",{email:r,provider:"ses",raw:innerMessage});dispatched.push("delivered")}return{status:200,body:{ok:!0,processed:dispatched.length>0,classification:dispatched[0]}}}export async function handleSendgridWebhook(rawBody,signatureHeader,timestampHeader,config){const v=verifySendgridSignature({body:rawBody,signature:signatureHeader,timestamp:timestampHeader,publicKeyPem:config.publicKeyPem,toleranceSeconds:config.toleranceSeconds});if(!v.ok)return unauthorized(v.reason);let events;try{events=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}if(!Array.isArray(events))return badRequest("expected-array");let processed=0;const classifications=[];for(const ev of events){if(!ev.email)continue;const id=ev.sg_event_id??`${ev.event}:${ev.email}:${Date.now()}`;if(!await recordWebhookEventOrSkip("sendgrid",id))continue;const classification=classifySendgridEvent(ev.event,ev.type);if(!classification)continue;await dispatchClassifiedEvent(classification,{email:ev.email,provider:"sendgrid",reason:ev.reason,raw:ev});processed++;classifications.push(classification)}return{status:200,body:{ok:!0,processed:processed>0,classification:classifications[0]}}}function classifySendgridEvent(event,type){switch(event){case"bounce":return type==="blocked"?"bounce-soft":"bounce-hard";case"dropped":return"bounce-hard";case"spamreport":return"complaint";case"unsubscribe":return"unsubscribe";case"group_unsubscribe":return"unsubscribe";case"delivered":return"delivered";default:return null}}
1
+ import{suppress}from"./suppression";import{recordWebhookEventOrSkip}from"./webhook-dedup";import{emitEmailBounceHard,emitEmailBounceSoft,emitEmailComplaint,emitEmailUnsubscribe,suppressionTypeFor}from"./webhook-events";import{verifyMailgunSignature,verifyPostmarkAuth,verifySendgridSignature,verifySesSnsSignature}from"./webhook-signatures";const OK_DUPLICATE={status:200,body:{ok:!0,processed:!1,reason:"duplicate"}};function unauthorized(reason){return{status:401,body:{ok:!1,reason}}}function badRequest(reason){return{status:400,body:{ok:!1,reason}}}async function dispatchClassifiedEvent(classification,payload){const suppressionType=suppressionTypeFor(classification);if(suppressionType)await suppress(payload.email,suppressionType,payload.reason);switch(classification){case"bounce-hard":await emitEmailBounceHard(payload);break;case"bounce-soft":await emitEmailBounceSoft(payload);break;case"complaint":await emitEmailComplaint(payload);break;case"unsubscribe":await emitEmailUnsubscribe(payload);break;case"delivered":break}}export async function handleMailgunWebhook(rawBody,config){let parsed;try{parsed=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const sig=parsed.signature,event=parsed["event-data"];if(!sig||!event)return badRequest("missing-fields");const v=verifyMailgunSignature({timestamp:sig.timestamp,token:sig.token,signature:sig.signature,signingKey:config.signingKey,toleranceSeconds:config.toleranceSeconds});if(!v.ok)return unauthorized(v.reason);if(!await recordWebhookEventOrSkip("mailgun",event.id))return OK_DUPLICATE;const classification=classifyMailgunEvent(event.event,event.severity);if(!classification)return{status:200,body:{ok:!0,processed:!1,reason:"unhandled-event"}};await dispatchClassifiedEvent(classification,{email:event.recipient,provider:"mailgun",reason:event.reason,raw:event});return{status:200,body:{ok:!0,processed:!0,classification}}}function classifyMailgunEvent(event,severity){switch(event){case"failed":return severity==="temporary"?"bounce-soft":"bounce-hard";case"complained":return"complaint";case"unsubscribed":return"unsubscribe";case"delivered":return"delivered";default:return null}}export async function handlePostmarkWebhook(rawBody,authorizationHeader,sourceIp,config){const v=verifyPostmarkAuth({authorizationHeader,expectedUsername:config.username,expectedPassword:config.password,sourceIp,ipAllowlist:config.ipAllowlist});if(!v.ok)return unauthorized(v.reason);let parsed;try{parsed=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const eventId=String(parsed.ID??parsed.MessageID??""),email=String(parsed.Email??parsed.Recipient??"");if(!email)return badRequest("missing-recipient");if(!await recordWebhookEventOrSkip("postmark",eventId))return OK_DUPLICATE;const classification=classifyPostmarkEvent(parsed);if(!classification)return{status:200,body:{ok:!0,processed:!1,reason:"unhandled-event"}};await dispatchClassifiedEvent(classification,{email,provider:"postmark",reason:parsed.Description,raw:parsed});return{status:200,body:{ok:!0,processed:!0,classification}}}function classifyPostmarkEvent(msg){switch(msg.RecordType){case"Bounce":return msg.TypeCode===1?"bounce-hard":"bounce-soft";case"SpamComplaint":return"complaint";case"SubscriptionChange":return msg.SuppressSending?"unsubscribe":null;case"Delivery":return"delivered";default:return null}}export async function handleSesWebhook(rawBody,config={}){let snsMessage;try{snsMessage=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}const v=await verifySesSnsSignature({message:snsMessage,certUrlHostAllowlist:config.certUrlHostAllowlist,fetchCert:config.fetchCert});if(!v.ok)return unauthorized(v.reason);if(snsMessage.Type==="SubscriptionConfirmation"){if(config.autoConfirmSubscriptions!==!1&&snsMessage.SubscribeURL)try{await fetch(snsMessage.SubscribeURL)}catch{}return{status:200,body:{ok:!0,processed:!0,reason:"subscription-confirmed"}}}if(snsMessage.Type==="UnsubscribeConfirmation")return{status:200,body:{ok:!0,processed:!0,reason:"subscription-removed"}};let innerMessage;try{innerMessage=JSON.parse(snsMessage.Message)}catch{return badRequest("invalid-inner-json")}if(!await recordWebhookEventOrSkip("ses",snsMessage.MessageId))return OK_DUPLICATE;const dispatched=[];if(innerMessage.notificationType==="Bounce"&&innerMessage.bounce){const classification=innerMessage.bounce.bounceType==="Permanent"?"bounce-hard":"bounce-soft";for(const r of innerMessage.bounce.bouncedRecipients){await dispatchClassifiedEvent(classification,{email:r.emailAddress,provider:"ses",reason:r.diagnosticCode,raw:innerMessage});dispatched.push(classification)}}else if(innerMessage.notificationType==="Complaint"&&innerMessage.complaint)for(const r of innerMessage.complaint.complainedRecipients){await dispatchClassifiedEvent("complaint",{email:r.emailAddress,provider:"ses",reason:innerMessage.complaint.complaintFeedbackType,raw:innerMessage});dispatched.push("complaint")}else if(innerMessage.notificationType==="Delivery"&&innerMessage.delivery)for(const r of innerMessage.delivery.recipients){await dispatchClassifiedEvent("delivered",{email:r,provider:"ses",raw:innerMessage});dispatched.push("delivered")}return{status:200,body:{ok:!0,processed:dispatched.length>0,classification:dispatched[0]}}}export async function handleSendgridWebhook(rawBody,signatureHeader,timestampHeader,config){const v=verifySendgridSignature({body:rawBody,signature:signatureHeader,timestamp:timestampHeader,publicKeyPem:config.publicKeyPem,toleranceSeconds:config.toleranceSeconds});if(!v.ok)return unauthorized(v.reason);let events;try{events=JSON.parse(rawBody)}catch{return badRequest("invalid-json")}if(!Array.isArray(events))return badRequest("expected-array");let processed=0;const classifications=[];for(const ev of events){if(!ev.email)continue;const id=ev.sg_event_id??`${ev.event}:${ev.email}:${Date.now()}`;if(!await recordWebhookEventOrSkip("sendgrid",id))continue;const classification=classifySendgridEvent(ev.event,ev.type);if(!classification)continue;await dispatchClassifiedEvent(classification,{email:ev.email,provider:"sendgrid",reason:ev.reason,raw:ev});processed++;classifications.push(classification)}return{status:200,body:{ok:!0,processed:processed>0,classification:classifications[0]}}}function classifySendgridEvent(event,type){switch(event){case"bounce":return type==="blocked"?"bounce-soft":"bounce-hard";case"dropped":return"bounce-hard";case"spamreport":return"complaint";case"unsubscribe":return"unsubscribe";case"group_unsubscribe":return"unsubscribe";case"delivered":return"delivered";default:return null}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/email",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.72.56",
5
+ "version": "0.72.60",
6
6
  "description": "The Stacks Email integration. Painlessly create & manage your inboxes, templates, and send emails.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -64,10 +64,10 @@
64
64
  "postal-mime": "^2.7.6"
65
65
  },
66
66
  "devDependencies": {
67
- "@stacksjs/cli": "0.72.56",
68
- "@stacksjs/config": "0.72.56",
67
+ "@stacksjs/cli": "0.72.60",
68
+ "@stacksjs/config": "0.72.60",
69
69
  "better-dx": "^0.2.24",
70
- "@stacksjs/error-handling": "0.72.56",
71
- "@stacksjs/types": "0.72.56"
70
+ "@stacksjs/error-handling": "0.72.60",
71
+ "@stacksjs/types": "0.72.60"
72
72
  }
73
73
  }