@stacksjs/email 0.75.609 → 0.75.611
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.
- package/dist/dkim.d.ts +42 -0
- package/dist/dkim.js +15 -0
- package/dist/drivers/commshq.d.ts +45 -0
- package/dist/drivers/commshq.js +1 -0
- package/dist/drivers/index.d.ts +2 -0
- package/dist/drivers/index.js +1 -1
- package/dist/drivers/smtp.js +1 -1
- package/dist/email.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +13 -13
package/dist/dkim.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign a raw message, answering it with a `DKIM-Signature` field in front.
|
|
3
|
+
*
|
|
4
|
+
* The message is otherwise returned as it was given, byte for byte after its
|
|
5
|
+
* line endings are made CRLF: a signature is over what is sent, so anything
|
|
6
|
+
* that rewrites the message afterwards breaks it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function signDkim(raw: string, options: DkimSigningOptions): string;
|
|
9
|
+
/**
|
|
10
|
+
* Check a message's first DKIM signature against a public key.
|
|
11
|
+
*
|
|
12
|
+
* For tests and for a service checking its own signing before it trusts it
|
|
13
|
+
* with real mail. A receiver looks the key up in DNS; this is given it.
|
|
14
|
+
*/
|
|
15
|
+
export declare function verifyDkim(raw: string, publicKey: string): DkimVerification;
|
|
16
|
+
/** The TXT value that publishes a public key: `v=DKIM1; k=rsa; p=…`. */
|
|
17
|
+
export declare function dkimRecord(publicKey: string): string;
|
|
18
|
+
/** A new 2048-bit RSA key pair for a signing domain. */
|
|
19
|
+
export declare function generateDkimKeyPair(): DkimKeyPair;
|
|
20
|
+
/** Where a domain's key is published. */
|
|
21
|
+
export declare function dkimRecordName(domain: string, selector: string): string;
|
|
22
|
+
/** A TXT answer's `p=` value, with the white space DNS splits it by removed. */
|
|
23
|
+
export declare function dkimRecordKey(record: string): string;
|
|
24
|
+
/** Signed when present. `from` is signed even when a caller's list leaves it out. */
|
|
25
|
+
export declare const DEFAULT_SIGNED_HEADERS: readonly string[];
|
|
26
|
+
export declare interface DkimSigningOptions {
|
|
27
|
+
domain: string
|
|
28
|
+
selector: string
|
|
29
|
+
privateKey: string
|
|
30
|
+
headers?: readonly string[]
|
|
31
|
+
}
|
|
32
|
+
export declare interface DkimVerification {
|
|
33
|
+
ok: boolean
|
|
34
|
+
reason?: string
|
|
35
|
+
domain?: string
|
|
36
|
+
selector?: string
|
|
37
|
+
}
|
|
38
|
+
export declare interface DkimKeyPair {
|
|
39
|
+
privateKey: string
|
|
40
|
+
publicKey: string
|
|
41
|
+
record: string
|
|
42
|
+
}
|
package/dist/dkim.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{Buffer}from"node:buffer";import{createHash,createPublicKey,createSign,createVerify,generateKeyPairSync}from"node:crypto";export const DEFAULT_SIGNED_HEADERS=["from","to","cc","subject","date","message-id","reply-to","mime-version","content-type","content-transfer-encoding","list-unsubscribe","list-unsubscribe-post"];function parse(raw){const text=raw.replace(/\r?\n/g,`\r
|
|
2
|
+
`);const split=text.indexOf(`\r
|
|
3
|
+
\r
|
|
4
|
+
`);const head=split===-1?text:text.slice(0,split);const body=split===-1?"":text.slice(split+4);const headers=[];for(const line of head.split(`\r
|
|
5
|
+
`)){if(/^[ \t]/.test(line)&&headers.length>0){headers[headers.length-1].raw+=`\r
|
|
6
|
+
${line}`;continue}const colon=line.indexOf(":");if(colon<1)continue;headers.push({name:line.slice(0,colon).trim().toLowerCase(),raw:line})}return{headers,body}}function canonicalHeader(raw){const colon=raw.indexOf(":");const name=raw.slice(0,colon).trim().toLowerCase();const value=raw.slice(colon+1).replace(/\r\n/g,"").replace(/[ \t]+/g," ").trim();return`${name}:${value}`}function canonicalBody(body){const lines=body.split(`\r
|
|
7
|
+
`).map((line)=>line.replace(/[ \t]+/g," ").replace(/ +$/,""));while(lines.length>0&&lines[lines.length-1]==="")lines.pop();return lines.length===0?`\r
|
|
8
|
+
`:`${lines.join(`\r
|
|
9
|
+
`)}\r
|
|
10
|
+
`}function bodyHash(body){return createHash("sha256").update(canonicalBody(body)).digest("base64")}function pick(headers,names){const used=new Set;const picked=[];for(const name of names){for(let i=headers.length-1;i>=0;i--){if(used.has(i)||headers[i].name!==name)continue;used.add(i);picked.push(canonicalHeader(headers[i].raw));break}}return picked}function cleanDomain(value){return value.trim().toLowerCase().replace(/\.$/,"")}export function signDkim(raw,options){const domain=cleanDomain(options.domain);const selector=options.selector.trim().toLowerCase();if(!/^[a-z0-9.-]+$/.test(domain)||!/^[a-z0-9._-]+$/.test(selector))throw new Error("[dkim] The signing domain and selector must be plain DNS names.");const message=parse(raw);const present=new Set(message.headers.map((header)=>header.name));const wanted=[...new Set(["from",...(options.headers??DEFAULT_SIGNED_HEADERS).map((name)=>name.toLowerCase())])];const names=wanted.filter((name)=>present.has(name));if(!present.has("from"))throw new Error("[dkim] A message with no From field cannot be signed.");const unsigned=["v=1","a=rsa-sha256","c=relaxed/relaxed",`d=${domain}`,`s=${selector}`,`t=${Math.floor(Date.now()/1000)}`,`h=${names.join(":")}`,`bh=${bodyHash(message.body)}`,"b="].join("; ");const signed=`${pick(message.headers,names).map((header)=>`${header}\r
|
|
11
|
+
`).join("")}${canonicalHeader(`DKIM-Signature: ${unsigned}`)}`;const signature=createSign("RSA-SHA256").update(signed).sign(options.privateKey,"base64");const folded=signature.match(/.{1,72}/g)?.join(`\r
|
|
12
|
+
`)??signature;const normalised=raw.replace(/\r?\n/g,`\r
|
|
13
|
+
`);return`DKIM-Signature: ${unsigned}${folded}\r
|
|
14
|
+
${normalised}`}export function verifyDkim(raw,publicKey){const message=parse(raw);const field=message.headers.find((header)=>header.name==="dkim-signature");if(!field)return{ok:false,reason:"no signature"};const value=field.raw.slice(field.raw.indexOf(":")+1).replace(/\r\n/g,"");const tags=new Map;for(const part of value.split(";")){const eq=part.indexOf("=");if(eq>0)tags.set(part.slice(0,eq).trim(),part.slice(eq+1).trim())}const domain=tags.get("d");const selector=tags.get("s");const signature=(tags.get("b")??"").replace(/\s+/g,"");if(tags.get("bh")!==bodyHash(message.body))return{ok:false,reason:"the body was changed",domain,selector};const names=(tags.get("h")??"").split(":").map((name)=>name.trim().toLowerCase()).filter(Boolean);const others=message.headers.filter((header)=>header!==field);const emptied=field.raw.replace(/([;\s]b=)[^;]*/,"$1");const signed=`${pick(others,names).map((header)=>`${header}\r
|
|
15
|
+
`).join("")}${canonicalHeader(emptied)}`;const ok=createVerify("RSA-SHA256").update(signed).verify(publicKey,signature,"base64");return ok?{ok,domain,selector}:{ok,reason:"the signature does not match",domain,selector}}export function dkimRecord(publicKey){const der=createPublicKey(publicKey).export({type:"spki",format:"der"});return`v=DKIM1; k=rsa; p=${Buffer.from(der).toString("base64")}`}export function generateDkimKeyPair(){const{privateKey,publicKey}=generateKeyPairSync("rsa",{modulusLength:2048,privateKeyEncoding:{type:"pkcs8",format:"pem"},publicKeyEncoding:{type:"spki",format:"pem"}});return{privateKey,publicKey,record:dkimRecord(publicKey)}}export function dkimRecordName(domain,selector){return`${selector.trim().toLowerCase()}._domainkey.${cleanDomain(domain)}`}export function dkimRecordKey(record){return(/(?:^|;)\s*p=([^;]*)/.exec(record.replace(/"\s*"/g,"").replace(/"/g,""))?.[1]??"").replace(/\s+/g,"")}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { BaseEmailDriver } from './base';
|
|
2
|
+
import type { EmailMessage, EmailResult } from '@stacksjs/types';
|
|
3
|
+
import type { TemplateOptions } from '../template';
|
|
4
|
+
/**
|
|
5
|
+
* Send through CommsHQ, with the key `buddy hq:connect commshq` wrote.
|
|
6
|
+
*
|
|
7
|
+
* CommsHQ sends the message from the app's own domain once that domain is
|
|
8
|
+
* verified, signed with the domain's DKIM key, and from an address of its own
|
|
9
|
+
* until then. The app says who the mail is from; whether that address may be
|
|
10
|
+
* used yet is the service's decision, and its answer says which was used.
|
|
11
|
+
*
|
|
12
|
+
* The key and the origin are `config.services.commshq`, where every HQ
|
|
13
|
+
* service's are. Nothing here reads SMTP settings: an app connected to
|
|
14
|
+
* CommsHQ needs no mail server of its own.
|
|
15
|
+
*/
|
|
16
|
+
/** Which mail driver an app sends with when nothing more specific was said. */
|
|
17
|
+
export declare function resolveDefaultMailDriver(input: {
|
|
18
|
+
|
|
19
|
+
configured?: string
|
|
20
|
+
|
|
21
|
+
explicit: boolean
|
|
22
|
+
|
|
23
|
+
commshqKey?: string
|
|
24
|
+
environment?: string
|
|
25
|
+
}): string;
|
|
26
|
+
declare interface CommsHqSendBody {
|
|
27
|
+
from?: { name?: string, address: string }
|
|
28
|
+
to: string[]
|
|
29
|
+
cc?: string[]
|
|
30
|
+
bcc?: string[]
|
|
31
|
+
replyTo?: string[]
|
|
32
|
+
subject: string
|
|
33
|
+
html?: string
|
|
34
|
+
text?: string
|
|
35
|
+
headers?: Record<string, string>
|
|
36
|
+
idempotencyKey?: string
|
|
37
|
+
}
|
|
38
|
+
export declare class CommsHqDriver extends BaseEmailDriver {
|
|
39
|
+
/** @defaultValue 'commshq' */
|
|
40
|
+
name: string;
|
|
41
|
+
private settings;
|
|
42
|
+
body(message: EmailMessage, html: string | undefined): CommsHqSendBody;
|
|
43
|
+
send(message: EmailMessage, options?: TemplateOptions): Promise<EmailResult>;
|
|
44
|
+
}
|
|
45
|
+
export default CommsHqDriver;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{templateByName}from"../template";import{BaseEmailDriver}from"./base";export function resolveDefaultMailDriver(input){if(input.explicit&&input.configured)return input.configured;if(input.commshqKey&&["production","staging"].includes(String(input.environment||"")))return"commshq";return input.configured||"ses"}export class CommsHqDriver extends BaseEmailDriver{name="commshq";settings(){const service=config.services?.commshq;return{url:String(service?.url||process.env.COMMSHQ_URL||"https://commshq.org").replace(/\/+$/,""),key:String(service?.key||process.env.COMMSHQ_KEY||"")}}body(message,html){const from=message.from??(config.email?.from?.address?{name:config.email.from.name,address:config.email.from.address}:undefined);const replyTo=this.formatAddressList(message.replyTo);const cc=this.formatAddresses(message.cc);const bcc=this.formatAddresses(message.bcc);return{...from?{from:{name:from.name,address:from.address}}:{},to:this.formatAddresses(message.to),...cc.length?{cc}:{},...bcc.length?{bcc}:{},...replyTo.length?{replyTo}:{},subject:message.subject,...html?{html}:{},...message.text?{text:message.text}:{},...message.headers&&Object.keys(message.headers).length?{headers:message.headers}:{},...message.idempotencyKey?{idempotencyKey:message.idempotencyKey}:{}}}async send(message,options){const{url,key}=this.settings();log.info("Sending email via CommsHQ...",{provider:this.name,to:message.to,subject:message.subject});try{this.validateMessage(message);if(!key)throw new Error("[commshq] No key is configured. Run `buddy hq:connect commshq`, which writes COMMSHQ_KEY.");if(message.attachments?.length)throw new Error("[commshq] Attachments are not supported by the CommsHQ send endpoint yet. Send this message with the smtp driver: mail.use('smtp').");let html=message.html;if(message.template){const rendered=await templateByName(message.template,options);if(rendered&&"html"in rendered)html=rendered.html}const response=await fetch(`${url}/api/v1/send`,{method:"POST",headers:{Authorization:`Bearer ${key}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(this.body(message,html)),signal:AbortSignal.timeout(20000)});const answer=await response.json().catch(()=>null);if(!response.ok)throw new Error(`[commshq] ${answer?.error||`The service answered ${response.status}`}`);return this.handleSuccess(message,answer?.id)}catch(error){return this.handleError(error,message)}}}export default CommsHqDriver;
|
package/dist/drivers/index.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export * as capture from './capture';
|
|
|
6
6
|
// graphs, two capture stores, so a test asserting on one saw nothing the app
|
|
7
7
|
// wrote to the other (stacksjs/stacks#2581).
|
|
8
8
|
export { CaptureEmailDriver } from './capture';
|
|
9
|
+
export * as commshq from './commshq';
|
|
10
|
+
export { CommsHqDriver, resolveDefaultMailDriver } from './commshq';
|
|
9
11
|
export * as log from './log';
|
|
10
12
|
export * as mailgun from './mailgun';
|
|
11
13
|
export * as mailtrap from './mailtrap';
|
package/dist/drivers/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export* as capture from"./capture";export{CaptureEmailDriver}from"./capture";export* as log from"./log";export* as mailgun from"./mailgun";export* as mailtrap from"./mailtrap";export* as sendgrid from"./sendgrid";export* as ses from"./ses";
|
|
1
|
+
export* as capture from"./capture";export{CaptureEmailDriver}from"./capture";export* as commshq from"./commshq";export{CommsHqDriver,resolveDefaultMailDriver}from"./commshq";export* as log from"./log";export* as mailgun from"./mailgun";export* as mailtrap from"./mailtrap";export* as sendgrid from"./sendgrid";export* as ses from"./ses";
|
package/dist/drivers/smtp.js
CHANGED
|
@@ -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{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
|
|
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
|
|
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/dist/email.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{CaptureEmailDriver}from"./drivers/capture";import{LogEmailDriver}from"./drivers/log";import{MailgunDriver}from"./drivers/mailgun";import{MailtrapDriver}from"./drivers/mailtrap";import{SendGridDriver}from"./drivers/sendgrid";import{SESDriver}from"./drivers/ses";import{SMTPDriver}from"./drivers/smtp";import{findEmailByIdempotencyKey,recordEmailIdempotency}from"./idempotency";import{checkSuppressionFor}from"./suppression";export class EmailDeliveryError extends Error{result;constructor(result){super(result.message||`Email delivery failed through ${result.provider||"the configured provider"}.`);this.name="EmailDeliveryError";this.result=result}}export class Email{name;subject;to;from;template;handle;onError;onSuccess;constructor(options){this.name=options.name;this.subject=options.subject;this.to=options.to;this.from=options.from;this.template=options.template;this.handle=options.handle;this.onError=options.onError;this.onSuccess=options.onSuccess}async renderTemplate(){if(!this.template)return"";try{const{path:p}=await import("@stacksjs/path");const templatePath=p.resourcesPath(`views/emails/${this.template}.html`);const file=Bun.file(templatePath);if(await file.exists()){return await file.text()}}catch{}if(this.template.includes("<")){return this.template}return`<p>${this.template}</p>`}async send(to){const target=to??this.to;const recipients=Array.isArray(target)?target:target?[target]:[];if(recipients.length===0){throw new Error("No recipient specified for email")}try{await mail.sendOrFail({to:recipients,from:this.from||{name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"},subject:this.subject,html:await this.renderTemplate()});if(this.onSuccess){this.onSuccess()}if(this.handle){return this.handle()}return{message:"Email sent"}}catch(error){if(this.onError){return this.onError(error instanceof Error?error:new Error(String(error)))}throw error}}}export class Mail{drivers=new Map;defaultDriver;constructor(options={}){this.defaultDriver=options.defaultDriver||config.email.default||"ses";this.registerDefaultDrivers()}registerDefaultDrivers(){this.drivers.set("log",new LogEmailDriver);this.drivers.set("ses",new SESDriver);this.drivers.set("sendgrid",new SendGridDriver);this.drivers.set("mailgun",new MailgunDriver);this.drivers.set("mailtrap",new MailtrapDriver);this.drivers.set("smtp",new SMTPDriver);this.drivers.set("capture",new CaptureEmailDriver)}async send(message){const driver=this.drivers.get(this.defaultDriver);if(!driver){const available=[...this.drivers.keys()].sort().join(", ");throw new Error(`Email driver '${this.defaultDriver}' is not registered. Available drivers: [${available}]. Check config.email.default or the MAIL_MAILER environment variable.`)}if(message.idempotencyKey){const cached=await findEmailByIdempotencyKey(message.idempotencyKey);if(cached)return cached}const suppressionType=await checkSuppressionForFirstRecipient(message);if(suppressionType){return{success:false,message:`suppressed:${suppressionType}`,provider:"suppression"}}const defaultFrom={name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"};const result=await driver.send({...message,from:message.from||defaultFrom});if(message.idempotencyKey){await recordEmailIdempotency(message.idempotencyKey,message,result)}return result}async sendOrFail(message){const result=await this.send(message);if(!result.success)throw new EmailDeliveryError(result);return result}use(driver){if(!this.drivers.has(driver)){throw new Error(`Email driver '${driver}' is not available`)}const instance=new Mail({defaultDriver:driver});return instance}fake(){const previous=this.defaultDriver;this.defaultDriver="capture";return previous}restoreDriver(driver){this.defaultDriver=driver}async queue(message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue("emails").dispatch()},{context:"queue"})}async later(delaySeconds,message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue("emails").delay(delaySeconds).dispatch()},{context:"later",delaySeconds})}async queueOn(queueName,message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue(queueName).dispatch()},{context:"queueOn",queueName})}async dispatchOrFallback(message,dispatch,logExtra){try{await dispatch();return}catch(error){const reason=error instanceof Error?error.message:String(error);log.warn("[email] Queue dispatch failed; falling back to synchronous send. Background email pipeline is degraded - check the queue worker / broker.",{...logExtra,reason})}await this.send(message)}}async function checkSuppressionForFirstRecipient(message){const recipients=collectRecipientAddresses(message);if(recipients.length===0)return null;for(const addr of recipients){const matched=await checkSuppressionFor(addr,message.tag);if(matched)return matched}return null}function collectRecipientAddresses(message){const out=[];const pushOne=(v)=>{if(typeof v==="string"){out.push(v);return}if(v&&typeof v==="object"&&"address"in v&&typeof v.address==="string")out.push(v.address)};for(const field of["to","cc","bcc"]){const v=message[field];if(!v)continue;if(Array.isArray(v)){for(const item of v)pushOne(item)}else{pushOne(v)}}return out}let _mail;function getMail(){if(!_mail){const driver=config?.email?.default||process.env.MAIL_MAILER||
|
|
1
|
+
import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{CaptureEmailDriver}from"./drivers/capture";import{CommsHqDriver,resolveDefaultMailDriver}from"./drivers/commshq";import{LogEmailDriver}from"./drivers/log";import{MailgunDriver}from"./drivers/mailgun";import{MailtrapDriver}from"./drivers/mailtrap";import{SendGridDriver}from"./drivers/sendgrid";import{SESDriver}from"./drivers/ses";import{SMTPDriver}from"./drivers/smtp";import{findEmailByIdempotencyKey,recordEmailIdempotency}from"./idempotency";import{checkSuppressionFor}from"./suppression";export class EmailDeliveryError extends Error{result;constructor(result){super(result.message||`Email delivery failed through ${result.provider||"the configured provider"}.`);this.name="EmailDeliveryError";this.result=result}}export class Email{name;subject;to;from;template;handle;onError;onSuccess;constructor(options){this.name=options.name;this.subject=options.subject;this.to=options.to;this.from=options.from;this.template=options.template;this.handle=options.handle;this.onError=options.onError;this.onSuccess=options.onSuccess}async renderTemplate(){if(!this.template)return"";try{const{path:p}=await import("@stacksjs/path");const templatePath=p.resourcesPath(`views/emails/${this.template}.html`);const file=Bun.file(templatePath);if(await file.exists()){return await file.text()}}catch{}if(this.template.includes("<")){return this.template}return`<p>${this.template}</p>`}async send(to){const target=to??this.to;const recipients=Array.isArray(target)?target:target?[target]:[];if(recipients.length===0){throw new Error("No recipient specified for email")}try{await mail.sendOrFail({to:recipients,from:this.from||{name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"},subject:this.subject,html:await this.renderTemplate()});if(this.onSuccess){this.onSuccess()}if(this.handle){return this.handle()}return{message:"Email sent"}}catch(error){if(this.onError){return this.onError(error instanceof Error?error:new Error(String(error)))}throw error}}}export class Mail{drivers=new Map;defaultDriver;constructor(options={}){this.defaultDriver=options.defaultDriver||config.email.default||"ses";this.registerDefaultDrivers()}registerDefaultDrivers(){this.drivers.set("log",new LogEmailDriver);this.drivers.set("ses",new SESDriver);this.drivers.set("sendgrid",new SendGridDriver);this.drivers.set("mailgun",new MailgunDriver);this.drivers.set("mailtrap",new MailtrapDriver);this.drivers.set("smtp",new SMTPDriver);this.drivers.set("commshq",new CommsHqDriver);this.drivers.set("capture",new CaptureEmailDriver)}async send(message){const driver=this.drivers.get(this.defaultDriver);if(!driver){const available=[...this.drivers.keys()].sort().join(", ");throw new Error(`Email driver '${this.defaultDriver}' is not registered. Available drivers: [${available}]. Check config.email.default or the MAIL_MAILER environment variable.`)}if(message.idempotencyKey){const cached=await findEmailByIdempotencyKey(message.idempotencyKey);if(cached)return cached}const suppressionType=await checkSuppressionForFirstRecipient(message);if(suppressionType){return{success:false,message:`suppressed:${suppressionType}`,provider:"suppression"}}const defaultFrom={name:config.email.from?.name||"Stacks",address:config.email.from?.address||"no-reply@stacksjs.com"};const result=await driver.send({...message,from:message.from||defaultFrom});if(message.idempotencyKey){await recordEmailIdempotency(message.idempotencyKey,message,result)}return result}async sendOrFail(message){const result=await this.send(message);if(!result.success)throw new EmailDeliveryError(result);return result}use(driver){if(!this.drivers.has(driver)){throw new Error(`Email driver '${driver}' is not available`)}const instance=new Mail({defaultDriver:driver});return instance}fake(){const previous=this.defaultDriver;this.defaultDriver="capture";return previous}restoreDriver(driver){this.defaultDriver=driver}async queue(message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue("emails").dispatch()},{context:"queue"})}async later(delaySeconds,message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue("emails").delay(delaySeconds).dispatch()},{context:"later",delaySeconds})}async queueOn(queueName,message){await this.dispatchOrFallback(message,async()=>{const{job}=await import("@stacksjs/queue");await job("SendEmailJob",{message,driver:this.defaultDriver}).onQueue(queueName).dispatch()},{context:"queueOn",queueName})}async dispatchOrFallback(message,dispatch,logExtra){try{await dispatch();return}catch(error){const reason=error instanceof Error?error.message:String(error);log.warn("[email] Queue dispatch failed; falling back to synchronous send. Background email pipeline is degraded - check the queue worker / broker.",{...logExtra,reason})}await this.send(message)}}async function checkSuppressionForFirstRecipient(message){const recipients=collectRecipientAddresses(message);if(recipients.length===0)return null;for(const addr of recipients){const matched=await checkSuppressionFor(addr,message.tag);if(matched)return matched}return null}function collectRecipientAddresses(message){const out=[];const pushOne=(v)=>{if(typeof v==="string"){out.push(v);return}if(v&&typeof v==="object"&&"address"in v&&typeof v.address==="string")out.push(v.address)};for(const field of["to","cc","bcc"]){const v=message[field];if(!v)continue;if(Array.isArray(v)){for(const item of v)pushOne(item)}else{pushOne(v)}}return out}let _mail;function getMail(){if(!_mail){const driver=resolveDefaultMailDriver({configured:config?.email?.default||process.env.MAIL_MAILER,explicit:Boolean(process.env.MAIL_MAILER||process.env.MAIL_DRIVER),commshqKey:config?.services?.commshq?.key||process.env.COMMSHQ_KEY,environment:process.env.APP_ENV||config?.app?.env});_mail=new Mail({defaultDriver:driver})}return _mail}export const mail=new Proxy({},{get(_t,prop){return getMail()[prop]},set(_t,prop,value){getMail()[prop]=value;return true}});
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./drivers";export*from"./email";export*from"./idempotency";export*from"./inbox-mailbox";export*from"./inbound-parser";export*from"./suppression";export*from"./unsubscribe";export*from"./webhook-dedup";export*from"./webhook-events";export*from"./webhook-handlers";export*from"./webhook-signatures";export*from"./mailable";export*from"./mime-preview";export*from"./sdk";export*from"./template";export*from"./types";export{inlineCss,shouldInlineByDefault}from"./css-inliner";export{discoverMailables,loadSampleProps,renderMailablePreview}from"./preview";export{renderIndexHtml,renderPreviewHtml}from"./preview-ui";
|
|
1
|
+
export*from"./dkim";export*from"./drivers";export*from"./email";export*from"./idempotency";export*from"./inbox-mailbox";export*from"./inbound-parser";export*from"./suppression";export*from"./unsubscribe";export*from"./webhook-dedup";export*from"./webhook-events";export*from"./webhook-handlers";export*from"./webhook-signatures";export*from"./mailable";export*from"./mime-preview";export*from"./sdk";export*from"./template";export*from"./types";export{inlineCss,shouldInlineByDefault}from"./css-inliner";export{discoverMailables,loadSampleProps,renderMailablePreview}from"./preview";export{renderIndexHtml,renderPreviewHtml}from"./preview-ui";
|
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.
|
|
5
|
+
"version": "0.75.611",
|
|
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.
|
|
65
|
-
"@stacksjs/database": "0.75.
|
|
66
|
-
"@stacksjs/events": "0.75.
|
|
67
|
-
"@stacksjs/logging": "0.75.
|
|
64
|
+
"@stacksjs/config": "0.75.611",
|
|
65
|
+
"@stacksjs/database": "0.75.611",
|
|
66
|
+
"@stacksjs/events": "0.75.611",
|
|
67
|
+
"@stacksjs/logging": "0.75.611",
|
|
68
68
|
"@stacksjs/mail": "^0.3.11",
|
|
69
|
-
"@stacksjs/path": "0.75.
|
|
70
|
-
"@stacksjs/storage": "0.75.
|
|
71
|
-
"@stacksjs/strings": "0.75.
|
|
69
|
+
"@stacksjs/path": "0.75.611",
|
|
70
|
+
"@stacksjs/storage": "0.75.611",
|
|
71
|
+
"@stacksjs/strings": "0.75.611",
|
|
72
72
|
"@stacksjs/stx": "^0.2.889",
|
|
73
73
|
"@stacksjs/ts-cloud": "^0.16.137",
|
|
74
|
-
"@stacksjs/utils": "0.75.
|
|
74
|
+
"@stacksjs/utils": "0.75.611"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@stacksjs/cli": "0.75.
|
|
78
|
-
"@stacksjs/error-handling": "0.75.
|
|
79
|
-
"@stacksjs/types": "0.75.
|
|
77
|
+
"@stacksjs/cli": "0.75.611",
|
|
78
|
+
"@stacksjs/error-handling": "0.75.611",
|
|
79
|
+
"@stacksjs/types": "0.75.611",
|
|
80
80
|
"better-dx": "^0.2.39"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
|
-
"@stacksjs/queue": "0.75.
|
|
83
|
+
"@stacksjs/queue": "0.75.611"
|
|
84
84
|
},
|
|
85
85
|
"peerDependenciesMeta": {
|
|
86
86
|
"@stacksjs/queue": {
|