"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.EmailTransport=void 0;const shared_1=require("../_deps/shared/index.js"),email_templates_js_1=require("./email-templates.js"),nodemailer_1=__importDefault(require("nodemailer"));class EmailTransport{config;transporter;rateLimits;constructor(e){this.config={...e,rateLimit:e.rateLimit??10,tokenExpiryHours:e.tokenExpiryHours??48},this.transporter=nodemailer_1.default.createTransport({host:this.config.smtpHost,port:this.config.smtpPort,secure:!1,auth:{user:this.config.smtpUser,pass:this.config.smtpPass}}),this.rateLimits=new Map}async send(e,t){const{from:r,to:i,payload:s}=e;if(!this.isValidEmail(i))return(0,shared_1.err)("SEND_FAILED");if(!this.checkRateLimit(r).ok)return(0,shared_1.err)("SEND_FAILED");try{const t=await this.generateInviteToken(e),a=`${this.config.acceptBaseUrl}/${t}`,o=(0,email_templates_js_1.renderInviteEmail)({agentName:s.agentName||r,did:r,acceptUrl:a,message:s.message});return await this.transporter.sendMail({from:`"${this.config.fromName}" <${this.config.fromEmail}>`,to:i,subject:`${s.agentName||"Agent"} wants to connect`,html:o}),this.incrementRateLimit(r),(0,shared_1.ok)(void 0)}catch{return(0,shared_1.err)("NETWORK_ERROR")}}isValidEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}checkRateLimit(e){const t=Date.now(),r=this.rateLimits.get(e);return r?t>=r.resetAt?(this.rateLimits.delete(e),(0,shared_1.ok)(void 0)):r.count>=this.config.rateLimit?(0,shared_1.err)(void 0):(0,shared_1.ok)(void 0):(0,shared_1.ok)(void 0)}incrementRateLimit(e){const t=Date.now(),r=this.rateLimits.get(e);r?r.count+=1:this.rateLimits.set(e,{count:1,resetAt:t+36e5})}async generateInviteToken(e){const t={from:e.from,publicKey:e.payload.publicKey,endpoint:e.payload.endpoint,timestamp:Date.now(),expiresAt:Date.now()+60*this.config.tokenExpiryHours*60*1e3},r=JSON.stringify(t);return Buffer.from(r).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async verify(){try{return await this.transporter.verify(),(0,shared_1.ok)(void 0)}catch{return(0,shared_1.err)("NETWORK_ERROR")}}async close(){this.transporter.close()}onReceive(e){}dispose(){this.transporter.close()}}exports.EmailTransport=EmailTransport;