@stacksjs/email 0.75.255 → 0.75.257

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 +1 @@
1
- import{config as appConfig}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{assertEnvelopeAddress,assertHeaderSafeSubject}from"../validation";export class BaseEmailDriver{config;constructor(config){this.config={maxRetries:config?.maxRetries||3,retryTimeout:config?.retryTimeout||1000,...config}}configure(config){this.config={...this.config,...config}}validateMessage(message){if(!message.from?.address&&!appConfig.email.from?.address)throw Error("Email sender address is required either in message or config");if(!message.to||Array.isArray(message.to)&&message.to.length===0)throw Error("At least one recipient is required");if(!message.subject)throw Error("Email subject is required");assertHeaderSafeSubject(message.subject);const checkAddress=(raw,role)=>{if(!raw)return;assertEnvelopeAddress(raw,role)},flatten=(v)=>{if(!v)return[];if(typeof v==="string")return[v];if(Array.isArray(v))return v.flatMap((item)=>typeof item==="string"?[item]:item?.address?[item.address]:[]);const obj=v;return obj.address?[obj.address]:[]};if(message.from)checkAddress(message.from.address,"from");for(const addr of flatten(message.to))checkAddress(addr,"to");for(const addr of flatten(message.cc))checkAddress(addr,"cc");for(const addr of flatten(message.bcc))checkAddress(addr,"bcc");return!0}formatAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((_addr)=>{if(typeof _addr==="string")return _addr;if(!_addr.name)return _addr.address;return`${/[",()<>[\]:;@\\]/.test(_addr.name)?`"${_addr.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:_addr.name} <${_addr.address}>`})}formatAddressList(value){if(!value)return[];if(Array.isArray(value))return this.formatAddresses(value);if(typeof value==="string")return this.formatAddresses(value);return this.formatAddresses([value])}async handleError(error,message){const err=error instanceof Error?error:Error(String(error));log.error(`[${this.name}] Email sending failed`,{error:err.message,stack:err.stack,to:message.to,subject:message.subject});let result={message:`Email sending failed: ${err.message}`,success:!1,provider:this.name};if(message.onError){const customResult=message.onError(err),handlerResult=customResult instanceof Promise?await customResult:customResult;result={...result,...handlerResult,success:!1,provider:this.name}}return result}async handleSuccess(message,messageId){let result={message:"Email sent successfully",success:!0,provider:this.name,messageId};try{if(message.handle){const customResult=message.handle(),handlerResult=customResult instanceof Promise?await customResult:customResult;result={...result,...handlerResult,success:!0,provider:this.name,messageId}}if(message.onSuccess){const successResult=message.onSuccess(),handlerResult=successResult instanceof Promise?await successResult:successResult;result={...result,...handlerResult,success:!0,provider:this.name,messageId}}}catch(error){return this.handleError(error,message)}return result}}
1
+ import{config as appConfig}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{assertEnvelopeAddress,assertHeaderSafeSubject,assertHeaderValue}from"../validation";export class BaseEmailDriver{config;constructor(config){this.config={maxRetries:config?.maxRetries||3,retryTimeout:config?.retryTimeout||1000,...config}}configure(config){this.config={...this.config,...config}}validateMessage(message){if(!message.from?.address&&!appConfig.email.from?.address)throw Error("Email sender address is required either in message or config");if(!message.to||Array.isArray(message.to)&&message.to.length===0)throw Error("At least one recipient is required");if(!message.subject)throw Error("Email subject is required");assertHeaderSafeSubject(message.subject);const checkAddresses=(value,role)=>{if(value===void 0||value===null)return;if(Array.isArray(value))for(const item of value)checkAddresses(item,role);else if(typeof value==="string")assertEnvelopeAddress(value,role);else{const address=value;assertEnvelopeAddress(address.address,role);if(address.name!==void 0)assertHeaderValue(address.name,`${role} name`)}};checkAddresses(message.from??appConfig.email.from,"from");checkAddresses(message.to,"to");checkAddresses(message.cc,"cc");checkAddresses(message.bcc,"bcc");checkAddresses(message.replyTo,"replyTo");return!0}formatAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((_addr)=>{if(typeof _addr==="string")return _addr;if(!_addr.name)return _addr.address;return`${/[",()<>[\]:;@\\]/.test(_addr.name)?`"${_addr.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:_addr.name} <${_addr.address}>`})}formatAddressList(value){if(!value)return[];if(Array.isArray(value))return this.formatAddresses(value);if(typeof value==="string")return this.formatAddresses(value);return this.formatAddresses([value])}async handleError(error,message){const err=error instanceof Error?error:Error(String(error));log.error(`[${this.name}] Email sending failed`,{error:err.message,stack:err.stack,to:message.to,subject:message.subject});let result={message:`Email sending failed: ${err.message}`,success:!1,provider:this.name};if(message.onError){const customResult=message.onError(err),handlerResult=customResult instanceof Promise?await customResult:customResult;result={...result,...handlerResult,success:!1,provider:this.name}}return result}async handleSuccess(message,messageId){let result={message:"Email sent successfully",success:!0,provider:this.name,messageId};try{if(message.handle){const customResult=message.handle(),handlerResult=customResult instanceof Promise?await customResult:customResult;result={...result,...handlerResult,success:!0,provider:this.name,messageId}}if(message.onSuccess){const successResult=message.onSuccess(),handlerResult=successResult instanceof Promise?await successResult:successResult;result={...result,...handlerResult,success:!0,provider:this.name,messageId}}}catch(error){return this.handleError(error,message)}return result}}
@@ -1,6 +1,7 @@
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{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 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,env=process.env,host=smtp?.host||env.MAIL_HOST||"127.0.0.1",port=smtp?.port||(env.MAIL_PORT?Number(env.MAIL_PORT):void 0)||587,fromAddress=typeof config.email?.from?.address==="string"?config.email.from.address:"",username=smtp?.username||env.MAIL_USERNAME||fromAddress||"",localPart=(username.includes("@")?username.split("@")[0]:username).toUpperCase().replace(/[^A-Z0-9]/g,"_"),password=smtp?.password||env.MAIL_PASSWORD||(localPart?env[`MAIL_PASSWORD_${localPart}`]:void 0)||"",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 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,fromAddress=message.from?.address||config.email.from?.address||"",fromName=message.from?.name||config.email.from?.name||"",toAddresses=this.formatAddresses(message.to),replyToAddresses=this.formatAddressList(message.replyTo),emailContent=buildMimeMessage({from:fromName?`${fromName} <${fromAddress}>`:fromAddress,to:toAddresses.join(", "),cc:message.cc?this.formatAddresses(message.cc).join(", "):void 0,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):void 0,customHeaders:filterStringHeaders(message.headers),subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain}),messageId=await this.sendViaSMTP(smtpConfig,fromAddress,toAddresses,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(Error(`SMTP connection timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))},SMTPDriver.SMTP_TIMEOUT),originalResolve=resolve,originalReject=reject;resolve=(value)=>{clearTimeout(timeout);originalResolve(value)};reject=(reason)=>{clearTimeout(timeout);originalReject(reason)};let socket,buffer="";const _currentCommand="",commandQueue=[],_isProcessing=!1;let completed=!1;const processResponse=(response)=>{log.debug(`[SMTP] Server: ${response.trim()}`);if(parseInt(response.substring(0,3),10)>=400){const error=Error(`SMTP Error: ${response.trim()}`);if(commandQueue.length>0)commandQueue.shift()?.reject(error);return}if(commandQueue.length>0)commandQueue.shift()?.resolve(response)},sendCommand=(cmd)=>{return new Promise((res,rej)=>{commandQueue.push({cmd,resolve:res,reject:rej});log.debug(`[SMTP] Client: ${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{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 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,env=process.env,host=smtp?.host||env.MAIL_HOST||"127.0.0.1",port=smtp?.port||(env.MAIL_PORT?Number(env.MAIL_PORT):void 0)||587,fromAddress=typeof config.email?.from?.address==="string"?config.email.from.address:"",username=smtp?.username||env.MAIL_USERNAME||fromAddress||"",localPart=(username.includes("@")?username.split("@")[0]:username).toUpperCase().replace(/[^A-Z0-9]/g,"_"),password=smtp?.password||env.MAIL_PASSWORD||(localPart?env[`MAIL_PASSWORD_${localPart}`]:void 0)||"",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 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,fromAddress=message.from?.address||config.email.from?.address||"",fromName=message.from?.name||config.email.from?.name||"",toAddresses=this.formatAddresses(message.to),replyToAddresses=this.formatAddressList(message.replyTo),emailContent=buildMimeMessage({from:fromName?`${fromName} <${fromAddress}>`:fromAddress,to:toAddresses.join(", "),cc:message.cc?this.formatAddresses(message.cc).join(", "):void 0,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):void 0,customHeaders:filterStringHeaders(message.headers),subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain}),recipients=[...new Set([...toAddresses,...this.formatAddresses(message.cc),...this.formatAddresses(message.bcc)])],messageId=await this.sendViaSMTP(smtpConfig,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(Error(`SMTP connection timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))},SMTPDriver.SMTP_TIMEOUT),originalResolve=resolve,originalReject=reject;resolve=(value)=>{clearTimeout(timeout);originalResolve(value)};reject=(reason)=>{clearTimeout(timeout);originalReject(reason)};let socket,buffer="";const _currentCommand="",commandQueue=[],_isProcessing=!1;let completed=!1;const processResponse=(response)=>{log.debug(`[SMTP] Server: ${response.trim()}`);if(parseInt(response.substring(0,3),10)>=400){const error=Error(`SMTP Error: ${response.trim()}`);if(commandQueue.length>0)commandQueue.shift()?.reject(error);return}if(commandQueue.length>0)commandQueue.shift()?.resolve(response)},sendCommand=(cmd,sensitive=!1)=>{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
  `)})},handleData=(data)=>{buffer+=data.toString();const lines=buffer.split(`\r
3
- `);buffer=lines.pop()||"";for(const line of lines)if(line.length>=3){if(line.length===3||line[3]===" ")processResponse(line)}},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)commandQueue.shift()?.reject(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"));await sendCommand(Buffer.from(smtpConfig.password).toString("base64"))}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");socket.write(`${content}\r
3
+ `);buffer=lines.pop()||"";for(const line of lines)if(line.length>=3){if(line.length===3||line[3]===" ")processResponse(line)}},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)commandQueue.shift()?.reject(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"),!0);await sendCommand(Buffer.from(smtpConfig.password).toString("base64"),!0)}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 stuffed=content.replace(/\r\n|\r|\n/g,`\r
4
+ `).replace(/(^|\r\n)\./g,"$1..");socket.write(`${stuffed}\r
4
5
  .\r
5
6
  `);await new Promise((res,rej)=>{commandQueue.push({cmd:"DATA_END",resolve:res,reject:rej})});completed=!0;const messageId=`${Date.now()}.${Math.random().toString(36).substring(2)}@${smtpConfig.host}`;try{socket.write(`QUIT\r
6
7
  `)}catch{}socket.end();resolve(messageId)}catch(error){if(completed){socket.end();return}socket.end();reject(error)}};if(smtpConfig.encryption==="ssl")socket=tls.connect({host:smtpConfig.host,port:smtpConfig.port,servername:smtpConfig.host},()=>{log.debug(`[SMTP] TLS connected to ${smtpConfig.host}:${smtpConfig.port}`);runSmtpSession()});else socket=net.connect({host:smtpConfig.host,port:smtpConfig.port},()=>{log.debug(`[SMTP] Connected to ${smtpConfig.host}:${smtpConfig.port}`);runSmtpSession()});socket.on("data",handleData);socket.setTimeout(SMTPDriver.SMTP_TIMEOUT);socket.on("timeout",()=>{socket.destroy(Error(`SMTP socket timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))});socket.on("error",(error)=>{if(completed)return;log.error(`[SMTP] Connection error to ${smtpConfig.host}:${smtpConfig.port}:`,error);reject(error)});socket.on("close",(hadError)=>{log.debug(`[SMTP] Connection closed (hadError: ${hadError})`);if(completed)return;while(commandQueue.length>0)commandQueue.shift()?.reject(Error("Connection closed unexpectedly"))})})}formatAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((addr)=>{if(typeof addr==="string")return addr;return addr.address})}}export default SMTPDriver;
package/dist/mime.js CHANGED
@@ -1,3 +1,3 @@
1
- import{Buffer}from"node:buffer";export function encodeRfc2047IfNeeded(value){if(/^[\x00-\x7F]*$/.test(value))return value;return`=?UTF-8?B?${Buffer.from(value,"utf-8").toString("base64")}?=`}export function buildMimeMessage(options){const{from,to,cc,replyTo,subject,text,html,attachments,messageIdDomain,customHeaders}=options,lines=[],hasAttachments=!!(attachments&&attachments.length>0),boundary=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`;lines.push(`From: ${from}`);lines.push(`To: ${to}`);if(cc)lines.push(`Cc: ${cc}`);if(replyTo)lines.push(`Reply-To: ${replyTo}`);lines.push(`Subject: ${encodeRfc2047IfNeeded(subject)}`);lines.push("MIME-Version: 1.0");lines.push(`Date: ${new Date().toUTCString()}`);lines.push(`Message-ID: <${Date.now()}.${Math.random().toString(36).substring(2)}@${messageIdDomain||"localhost"}>`);if(customHeaders)for(const[k,v]of Object.entries(customHeaders))lines.push(`${k}: ${v}`);if(hasAttachments){const mixedBoundary=boundary,altBoundary=`${boundary}_alt`;lines.push(`Content-Type: multipart/mixed; boundary="${mixedBoundary}"`);lines.push("");lines.push(`--${mixedBoundary}`);pushBodyParts(lines,{text,html,altBoundary});for(const attachment of attachments){lines.push(`--${mixedBoundary}`);pushAttachmentPart(lines,attachment)}lines.push(`--${mixedBoundary}--`)}else pushBodyParts(lines,{text,html,altBoundary:boundary});return lines.join(`\r
2
- `)}function pushBodyParts(lines,options){const{text,html,altBoundary}=options;if(html&&text){lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);lines.push("");lines.push(`--${altBoundary}`);lines.push("Content-Type: text/plain; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(text);lines.push("");lines.push(`--${altBoundary}`);lines.push("Content-Type: text/html; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(html);lines.push("");lines.push(`--${altBoundary}--`)}else if(html){lines.push("Content-Type: text/html; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(html)}else if(text){lines.push("Content-Type: text/plain; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(text)}}function pushAttachmentPart(lines,attachment){const contentType=attachment.contentType||"application/octet-stream",safeFilename=encodeRfc2047IfNeeded(attachment.filename.replace(/\\/g,"\\\\").replace(/"/g,"\\\""));lines.push(`Content-Type: ${contentType}; name="${safeFilename}"`);lines.push(`Content-Disposition: attachment; filename="${safeFilename}"`);lines.push("Content-Transfer-Encoding: base64");lines.push("");const raw=typeof attachment.content==="string"?Buffer.from(attachment.content,"utf-8").toString("base64"):Buffer.from(attachment.content).toString("base64"),wrapped=raw.match(/.{1,76}/g)?.join(`\r
1
+ import{Buffer}from"node:buffer";import{assertHeaderValue,isHeaderName}from"./validation";export function encodeRfc2047IfNeeded(value){assertHeaderValue(value,"encoded header");if(/^[\x00-\x7F]*$/.test(value))return value;return`=?UTF-8?B?${Buffer.from(value,"utf-8").toString("base64")}?=`}export function buildMimeMessage(options){const{from,to,cc,replyTo,subject,text,html,attachments,messageIdDomain,customHeaders}=options;for(const[role,value]of Object.entries({from,to,cc,replyTo,subject,messageIdDomain}))if(value!==void 0)assertHeaderValue(value,role);for(const[name,value]of Object.entries(customHeaders??{})){if(!isHeaderName(name))throw Error("Email custom header name contains forbidden characters");assertHeaderValue(value,name)}const lines=[],hasAttachments=!!(attachments&&attachments.length>0),boundary=`----=_Part_${Date.now()}_${Math.random().toString(36).substring(2)}`;lines.push(`From: ${from}`);lines.push(`To: ${to}`);if(cc)lines.push(`Cc: ${cc}`);if(replyTo)lines.push(`Reply-To: ${replyTo}`);lines.push(`Subject: ${encodeRfc2047IfNeeded(subject)}`);lines.push("MIME-Version: 1.0");lines.push(`Date: ${new Date().toUTCString()}`);lines.push(`Message-ID: <${Date.now()}.${Math.random().toString(36).substring(2)}@${messageIdDomain||"localhost"}>`);if(customHeaders)for(const[k,v]of Object.entries(customHeaders))lines.push(`${k}: ${v}`);if(hasAttachments){const mixedBoundary=boundary,altBoundary=`${boundary}_alt`;lines.push(`Content-Type: multipart/mixed; boundary="${mixedBoundary}"`);lines.push("");lines.push(`--${mixedBoundary}`);pushBodyParts(lines,{text,html,altBoundary});for(const attachment of attachments){lines.push(`--${mixedBoundary}`);pushAttachmentPart(lines,attachment)}lines.push(`--${mixedBoundary}--`)}else pushBodyParts(lines,{text,html,altBoundary:boundary});return lines.join(`\r
2
+ `)}function pushBodyParts(lines,options){const{text,html,altBoundary}=options;if(html&&text){lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);lines.push("");lines.push(`--${altBoundary}`);lines.push("Content-Type: text/plain; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(text);lines.push("");lines.push(`--${altBoundary}`);lines.push("Content-Type: text/html; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(html);lines.push("");lines.push(`--${altBoundary}--`)}else if(html){lines.push("Content-Type: text/html; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(html)}else if(text){lines.push("Content-Type: text/plain; charset=UTF-8");lines.push("Content-Transfer-Encoding: 7bit");lines.push("");lines.push(text)}}function pushAttachmentPart(lines,attachment){assertHeaderValue(attachment.filename,"attachment filename");if(attachment.contentType)assertHeaderValue(attachment.contentType,"attachment content type");const contentType=attachment.contentType||"application/octet-stream",safeFilename=encodeRfc2047IfNeeded(attachment.filename.replace(/\\/g,"\\\\").replace(/"/g,"\\\""));lines.push(`Content-Type: ${contentType}; name="${safeFilename}"`);lines.push(`Content-Disposition: attachment; filename="${safeFilename}"`);lines.push("Content-Transfer-Encoding: base64");lines.push("");const raw=typeof attachment.content==="string"?Buffer.from(attachment.content,"utf-8").toString("base64"):Buffer.from(attachment.content).toString("base64"),wrapped=raw.match(/.{1,76}/g)?.join(`\r
3
3
  `)??raw;lines.push(wrapped);lines.push("")}
@@ -26,6 +26,10 @@ export declare function assertHeaderSafeSubject(subject: string): void;
26
26
  * Mailtrap `headers` map all reject the same injection-shaped values.
27
27
  */
28
28
  export declare function filterStringHeaders(headers: Record<string, string> | undefined): Record<string, string> | undefined;
29
+ /** Validate one unfolded header value before any RFC 2047 encoding. */
30
+ export declare function assertHeaderValue(value: string, role: string): void;
31
+ /** RFC 5322 field names cannot contain whitespace or a colon. */
32
+ export declare function isHeaderName(name: string): boolean;
29
33
  /**
30
34
  * Email validation primitives shared by every driver + the base
31
35
  * driver class. Pulled into a module so the `ENVELOPE_ADDRESS` regex
@@ -1 +1 @@
1
- export const ENVELOPE_ADDRESS=/^[^\s<>"\\\r\n\t]+@[^\s<>"\\\r\n\t]+$/;export function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr))throw Error(`Email ${role} address is malformed or contains forbidden characters: ${JSON.stringify(addr)}`)}export function assertHeaderSafeSubject(subject){if(/[\r\n]/.test(subject))throw Error("Email subject contains forbidden line break characters (CR/LF)")}export function filterStringHeaders(headers){if(!headers)return;const out={};for(const[k,v]of Object.entries(headers)){if(typeof v!=="string")continue;if(/[\r\n]/.test(k)||/[\r\n]/.test(v))continue;out[k]=v}return Object.keys(out).length>0?out:void 0}
1
+ export const ENVELOPE_ADDRESS=/^[^\s<>"\\\r\n\t]+@[^\s<>"\\\r\n\t]+$/;export function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr))throw Error(`Email ${role} address is malformed or contains forbidden characters: ${JSON.stringify(addr)}`)}export function assertHeaderSafeSubject(subject){if(/[\r\n]/.test(subject))throw Error("Email subject contains forbidden line break characters (CR/LF)")}export function filterStringHeaders(headers){if(!headers)return;const out={};for(const[k,v]of Object.entries(headers)){if(typeof v!=="string")continue;if(!isHeaderName(k)||/[\r\n\0]/.test(v))continue;out[k]=v}return Object.keys(out).length>0?out:void 0}export function assertHeaderValue(value,role){if(typeof value!=="string"||/[\r\n\0]/.test(value))throw Error(`Email ${role} contains forbidden header characters`)}export function isHeaderName(name){return/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)}
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.255",
5
+ "version": "0.75.257",
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.255",
65
- "@stacksjs/database": "0.75.255",
66
- "@stacksjs/events": "0.75.255",
67
- "@stacksjs/logging": "0.75.255",
64
+ "@stacksjs/config": "0.75.257",
65
+ "@stacksjs/database": "0.75.257",
66
+ "@stacksjs/events": "0.75.257",
67
+ "@stacksjs/logging": "0.75.257",
68
68
  "@stacksjs/mail": "^0.3.11",
69
- "@stacksjs/path": "0.75.255",
70
- "@stacksjs/storage": "0.75.255",
71
- "@stacksjs/strings": "0.75.255",
72
- "@stacksjs/stx": "^0.2.631",
69
+ "@stacksjs/path": "0.75.257",
70
+ "@stacksjs/storage": "0.75.257",
71
+ "@stacksjs/strings": "0.75.257",
72
+ "@stacksjs/stx": "0.2.644",
73
73
  "@stacksjs/ts-cloud": "^0.16.58",
74
- "@stacksjs/utils": "0.75.255"
74
+ "@stacksjs/utils": "0.75.257"
75
75
  },
76
76
  "devDependencies": {
77
- "@stacksjs/cli": "0.75.255",
78
- "@stacksjs/error-handling": "0.75.255",
79
- "@stacksjs/types": "0.75.255",
77
+ "@stacksjs/cli": "0.75.257",
78
+ "@stacksjs/error-handling": "0.75.257",
79
+ "@stacksjs/types": "0.75.257",
80
80
  "better-dx": "^0.2.24"
81
81
  },
82
82
  "peerDependencies": {
83
- "@stacksjs/queue": "0.75.255"
83
+ "@stacksjs/queue": "0.75.257"
84
84
  },
85
85
  "peerDependenciesMeta": {
86
86
  "@stacksjs/queue": {