@stacksjs/email 0.75.612 → 0.75.614

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,6 +1,17 @@
1
1
  import { BaseEmailDriver } from './base';
2
2
  import type { EmailAddress, EmailMessage, EmailResult } from '@stacksjs/types';
3
3
  import type { TemplateOptions } from '../template';
4
+ /**
5
+ * The mail host of an app that runs its own mail (`email.server.enabled`),
6
+ * for when no host is named: `mail.<domain>`, which its deploy publishes and
7
+ * holds a certificate for.
8
+ *
9
+ * Without it an app that declared a mailbox and deployed still had to be told
10
+ * where its own mail server was, and until then tried the machine it ran on.
11
+ * Only where mail really goes out: a developer's machine keeps the loopback
12
+ * default, and must name a host to reach a real server.
13
+ */
14
+ export declare function ownMailHost(email: { domain?: unknown, server?: { enabled?: unknown, subdomain?: unknown } } | null | undefined, environment?: string | undefined): string | undefined;
4
15
  /**
5
16
  * SMTP Driver for email sending
6
17
  * Works with any SMTP server: Mailtrap, Mailgun, SendGrid, SES, etc.
@@ -1,4 +1,4 @@
1
- import{Buffer}from"node:buffer";import process from"node:process";import*as tls from"node:tls";import*as net from"node:net";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{signDkim}from"../dkim";import{buildMimeMessage}from"../mime";import{ENVELOPE_ADDRESS,filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr)){throw new Error(`[smtp] Refusing to send: ${role} envelope address contains forbidden characters or is malformed: ${JSON.stringify(addr)}`)}}export class SMTPDriver extends BaseEmailDriver{static SMTP_TIMEOUT=30000;name="smtp";getConfig(){const smtp=config.services?.smtp;const env=process.env;const host=smtp?.host||env.MAIL_HOST||"127.0.0.1";const port=smtp?.port||(env.MAIL_PORT?Number(env.MAIL_PORT):undefined)||587;const fromAddress=typeof config.email?.from?.address==="string"?config.email.from.address:"";const username=smtp?.username||env.MAIL_USERNAME||fromAddress||"";const localPart=(username.includes("@")?username.split("@")[0]:username).toUpperCase().replace(/[^A-Z0-9]/g,"_");const password=smtp?.password||env.MAIL_PASSWORD||(localPart?env[`MAIL_PASSWORD_${localPart}`]:undefined)||"";const rawEncryption=smtp?.encryption??env.MAIL_ENCRYPTION??null;return{host,port,username,password,encryption:rawEncryption==="tls"?"starttls":rawEncryption||null}}async send(message,options){const smtpConfig=this.getConfig();if(!smtpConfig.host||smtpConfig.host===""){throw new Error("[SMTP] Host is not configured. Set MAIL_HOST in your .env file.")}const logContext={provider:this.name,to:message.to,subject:message.subject,host:smtpConfig.host,port:smtpConfig.port};log.info("Sending email via SMTP...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ){htmlContent=templ.html}}const finalHtml=htmlContent||message.html;const fromAddress=message.from?.address||config.email.from?.address||"";const fromName=message.from?.name||config.email.from?.name||"";const toAddresses=this.formatAddresses(message.to);const replyToAddresses=this.formatAddressList(message.replyTo);const built=buildMimeMessage({from:fromName?`${fromName} <${fromAddress}>`:fromAddress,to:toAddresses.join(", "),cc:message.cc?this.formatAddresses(message.cc).join(", "):undefined,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):undefined,customHeaders:filterStringHeaders(message.headers),subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain});const emailContent=message.dkim?signDkim(built,message.dkim):built;const recipients=[...new Set([...toAddresses,...this.formatAddresses(message.cc),...this.formatAddresses(message.bcc)])];const messageId=await this.sendViaSMTP(smtpConfig,message.envelopeFrom||fromAddress,recipients,emailContent);return this.handleSuccess(message,messageId)}catch(error){return this.handleError(error,message)}}async sendViaSMTP(smtpConfig,from,to,content){return new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{reject(new Error(`SMTP connection timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))},SMTPDriver.SMTP_TIMEOUT);const originalResolve=resolve;const originalReject=reject;resolve=(value)=>{clearTimeout(timeout);originalResolve(value)};reject=(reason)=>{clearTimeout(timeout);originalReject(reason)};let socket;let buffer="";const _currentCommand="";const commandQueue=[];const _isProcessing=false;let completed=false;const processResponse=(response)=>{log.debug(`[SMTP] Server: ${response.trim()}`);const code=parseInt(response.substring(0,3),10);if(code>=400){const error=new Error(`SMTP Error: ${response.trim()}`);if(commandQueue.length>0){const current=commandQueue.shift();current?.reject(error)}return}if(commandQueue.length>0){const current=commandQueue.shift();current?.resolve(response)}};const sendCommand=(cmd,sensitive=false)=>{return new Promise((res,rej)=>{commandQueue.push({cmd:sensitive?"[redacted authentication]":cmd,resolve:res,reject:rej});log.debug(`[SMTP] Client: ${sensitive?"[redacted authentication]":cmd}`);socket.write(`${cmd}\r
1
+ import{Buffer}from"node:buffer";import process from"node:process";import*as tls from"node:tls";import*as net from"node:net";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{signDkim}from"../dkim";export function ownMailHost(email,environment=process.env.APP_ENV){if(!["production","staging"].includes(String(environment||"")))return;if(email?.server?.enabled!==true)return;const domain=typeof email.domain==="string"?email.domain.trim().toLowerCase():"";if(!domain||!domain.includes(".")||domain==="example.com")return;const subdomain=typeof email.server.subdomain==="string"&&email.server.subdomain.trim()?email.server.subdomain.trim():"mail";return`${subdomain}.${domain}`}import{buildMimeMessage}from"../mime";import{ENVELOPE_ADDRESS,filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr)){throw new Error(`[smtp] Refusing to send: ${role} envelope address contains forbidden characters or is malformed: ${JSON.stringify(addr)}`)}}export class SMTPDriver extends BaseEmailDriver{static SMTP_TIMEOUT=30000;name="smtp";getConfig(){const smtp=config.services?.smtp;const env=process.env;const host=smtp?.host||env.MAIL_HOST||ownMailHost(config.email)||"127.0.0.1";const port=smtp?.port||(env.MAIL_PORT?Number(env.MAIL_PORT):undefined)||587;const fromAddress=typeof config.email?.from?.address==="string"?config.email.from.address:"";const username=smtp?.username||env.MAIL_USERNAME||fromAddress||"";const localPart=(username.includes("@")?username.split("@")[0]:username).toUpperCase().replace(/[^A-Z0-9]/g,"_");const password=smtp?.password||env.MAIL_PASSWORD||(localPart?env[`MAIL_PASSWORD_${localPart}`]:undefined)||"";const rawEncryption=smtp?.encryption??env.MAIL_ENCRYPTION??(!smtp?.host&&!env.MAIL_HOST&&host!=="127.0.0.1"?"tls":null);return{host,port,username,password,encryption:rawEncryption==="tls"?"starttls":rawEncryption||null}}async send(message,options){const smtpConfig=this.getConfig();if(!smtpConfig.host||smtpConfig.host===""){throw new Error("[SMTP] Host is not configured. Set MAIL_HOST in your .env file.")}const logContext={provider:this.name,to:message.to,subject:message.subject,host:smtpConfig.host,port:smtpConfig.port};log.info("Sending email via SMTP...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await templateByName(message.template,options);if(templ&&"html"in templ){htmlContent=templ.html}}const finalHtml=htmlContent||message.html;const fromAddress=message.from?.address||config.email.from?.address||"";const fromName=message.from?.name||config.email.from?.name||"";const toAddresses=this.formatAddresses(message.to);const replyToAddresses=this.formatAddressList(message.replyTo);const built=buildMimeMessage({from:fromName?`${fromName} <${fromAddress}>`:fromAddress,to:toAddresses.join(", "),cc:message.cc?this.formatAddresses(message.cc).join(", "):undefined,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):undefined,customHeaders:filterStringHeaders(message.headers),subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain});const emailContent=message.dkim?signDkim(built,message.dkim):built;const recipients=[...new Set([...toAddresses,...this.formatAddresses(message.cc),...this.formatAddresses(message.bcc)])];const messageId=await this.sendViaSMTP(smtpConfig,message.envelopeFrom||fromAddress,recipients,emailContent);return this.handleSuccess(message,messageId)}catch(error){return this.handleError(error,message)}}async sendViaSMTP(smtpConfig,from,to,content){return new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{reject(new Error(`SMTP connection timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))},SMTPDriver.SMTP_TIMEOUT);const originalResolve=resolve;const originalReject=reject;resolve=(value)=>{clearTimeout(timeout);originalResolve(value)};reject=(reason)=>{clearTimeout(timeout);originalReject(reason)};let socket;let buffer="";const _currentCommand="";const commandQueue=[];const _isProcessing=false;let completed=false;const processResponse=(response)=>{log.debug(`[SMTP] Server: ${response.trim()}`);const code=parseInt(response.substring(0,3),10);if(code>=400){const error=new Error(`SMTP Error: ${response.trim()}`);if(commandQueue.length>0){const current=commandQueue.shift();current?.reject(error)}return}if(commandQueue.length>0){const current=commandQueue.shift();current?.resolve(response)}};const sendCommand=(cmd,sensitive=false)=>{return new Promise((res,rej)=>{commandQueue.push({cmd:sensitive?"[redacted authentication]":cmd,resolve:res,reject:rej});log.debug(`[SMTP] Client: ${sensitive?"[redacted authentication]":cmd}`);socket.write(`${cmd}\r
2
2
  `)})};const handleData=(data)=>{buffer+=data.toString();const lines=buffer.split(`\r
3
3
  `);buffer=lines.pop()||"";for(const line of lines){if(line.length>=3){const isLastLine=line.length===3||line[3]===" ";if(isLastLine){processResponse(line)}}}};const runSmtpSession=async()=>{try{await new Promise((res,rej)=>{commandQueue.push({cmd:"GREETING",resolve:res,reject:rej})});const _ehloResponse=await sendCommand(`EHLO ${config.email.domain||"localhost"}`);if(smtpConfig.encryption==="starttls"&&!(socket instanceof tls.TLSSocket)){await sendCommand("STARTTLS");const plainSocket=socket;plainSocket.removeAllListeners("data");socket=await new Promise((res,rej)=>{const tlsSocket=tls.connect({socket:plainSocket,host:smtpConfig.host,servername:smtpConfig.host},()=>{log.debug("[SMTP] TLS connection established");res(tlsSocket)});tlsSocket.on("error",(err)=>{log.error("[SMTP] TLS socket error:",err);rej(err)});tlsSocket.on("data",handleData);tlsSocket.on("close",(hadError)=>{log.debug(`[SMTP] TLS socket closed (hadError: ${hadError})`);while(commandQueue.length>0){const pending=commandQueue.shift();pending?.reject(new Error("TLS connection closed unexpectedly"))}})});await sendCommand(`EHLO ${config.email.domain||"localhost"}`)}if(smtpConfig.username&&smtpConfig.password){await sendCommand("AUTH LOGIN");await sendCommand(Buffer.from(smtpConfig.username).toString("base64"),true);await sendCommand(Buffer.from(smtpConfig.password).toString("base64"),true)}assertEnvelopeAddress(from,"MAIL FROM");for(const recipient of to)assertEnvelopeAddress(recipient,"RCPT TO");await sendCommand(`MAIL FROM:<${from}>`);for(const recipient of to){await sendCommand(`RCPT TO:<${recipient}>`)}await sendCommand("DATA");const normalized=content.replace(/\r\n|\r|\n/g,`\r
4
4
  `);const stuffed=normalized.replace(/(^|\r\n)\./g,"$1..");socket.write(`${stuffed}\r
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/email",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.612",
5
+ "version": "0.75.614",
6
6
  "description": "The Stacks Email integration. Painlessly create & manage your inboxes, templates, and send emails.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -61,26 +61,26 @@
61
61
  "prepublishOnly": "bun run build"
62
62
  },
63
63
  "dependencies": {
64
- "@stacksjs/config": "0.75.612",
65
- "@stacksjs/database": "0.75.612",
66
- "@stacksjs/events": "0.75.612",
67
- "@stacksjs/logging": "0.75.612",
64
+ "@stacksjs/config": "0.75.614",
65
+ "@stacksjs/database": "0.75.614",
66
+ "@stacksjs/events": "0.75.614",
67
+ "@stacksjs/logging": "0.75.614",
68
68
  "@stacksjs/mail": "^0.3.11",
69
- "@stacksjs/path": "0.75.612",
70
- "@stacksjs/storage": "0.75.612",
71
- "@stacksjs/strings": "0.75.612",
69
+ "@stacksjs/path": "0.75.614",
70
+ "@stacksjs/storage": "0.75.614",
71
+ "@stacksjs/strings": "0.75.614",
72
72
  "@stacksjs/stx": "^0.2.889",
73
73
  "@stacksjs/ts-cloud": "^0.16.137",
74
- "@stacksjs/utils": "0.75.612"
74
+ "@stacksjs/utils": "0.75.614"
75
75
  },
76
76
  "devDependencies": {
77
- "@stacksjs/cli": "0.75.612",
78
- "@stacksjs/error-handling": "0.75.612",
79
- "@stacksjs/types": "0.75.612",
77
+ "@stacksjs/cli": "0.75.614",
78
+ "@stacksjs/error-handling": "0.75.614",
79
+ "@stacksjs/types": "0.75.614",
80
80
  "better-dx": "^0.2.39"
81
81
  },
82
82
  "peerDependencies": {
83
- "@stacksjs/queue": "0.75.612"
83
+ "@stacksjs/queue": "0.75.614"
84
84
  },
85
85
  "peerDependenciesMeta": {
86
86
  "@stacksjs/queue": {