/* eslint-disable no-console */ import Inject, { RegisterScoped, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import * as smtpServer from "smtp-server"; import * as fsp from "node:fs/promises"; import { spf } from "mailauth/lib/spf/index.js"; import SmtpError from "./SmtpError.js"; import Mailbox from "../../model/entities/Mailbox.js"; import TempFileService from "../../storage/TempFileService.js"; import { authenticate, SPFResult } from "mailauth"; import EmailAddressService from "../../services/EmailAddressService.js"; import { SmtpStatusCodes } from "../client/SmtpStatusCodes.js"; import { isTestMode } from "../../../globalServices.js"; import EmailSerializerService from "./EmailSerializerService.js"; import ChannelService from "./ChannelService.js"; import { globalEnv } from "../../../common/globalEnv.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import sleep from "../../../common/sleep.js"; import Sql from "@entity-access/entity-access/dist/sql/Sql.js"; import { serverActivities } from "../../model/entities/ServerActivity.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import TagService from "../../services/tags/TagService.js"; import DomainReputationService from "./DomainReputationService.js"; import MessagingService from "../../services/message-events/MessagingService.js"; import { join } from "node:path"; import { networkInterfaces } from "node:os"; import BaseDiskCache from "@entity-access/server-pages/dist/cache/BaseDiskCache.js"; const tmpdir = globalEnv.tmpDir; const tmpPath = join(tmpdir, "spf"); const localIPs = Object.values(networkInterfaces()).map(([x]) => x.address); const spfCache = new BaseDiskCache({ root: tmpPath }); export interface IEmailRecipientInfo { emailAddress: string; type: string; name: string; } // const combineAddresses = (type: string, items: AddressObject | AddressObject[]): IEmailRecipientInfo[] => { // const r = [] as IEmailRecipientInfo[]; // if (!items) { // return r; // } // if (Array.isArray(items)) { // return items.map((x) => combineAddresses(type, x)).flat(); // } // for (const { address: emailAddress, name } of items.value) { // r.push({ // type, // emailAddress, // name // }); // } // return r; // }; @RegisterScoped export default class MailReceiverService { @Inject private db: SocialMailContext; @Inject private tempFileService: TempFileService; @Inject private emailSerializerService: EmailSerializerService; @Inject private emailAddressService: EmailAddressService; @Inject private tagService: TagService; @Inject private domainReputation: DomainReputationService; @Inject private ms: MessagingService; private session: { user? , remoteAddress?, hostNameAppearsAs?, clientHostname?: string }; private from: { address: string }; private fromDomain: string; // private sender: EmailAddress; private recipients: Map; private domain: string; start(session: { user?, remoteAddress?, hostNameAppearsAs?, clientHostname?: string }) { this.session = session; } async auth(auth: smtpServer.SMTPServerAuthentication): Promise { throw new EntityAccessError("Not Supported Yet."); // const ats = ServiceProvider.resolve(this, AccessTokenService); // const user = await ats.login(auth.username, auth.password); // return { user }; } async verifySpf(address: string) { if(globalEnv.smtp.trustSender) { return; } // ignore ips... const senderAddress = this.session.remoteAddress; if (localIPs.includes(senderAddress)) { return; } const domain = address.split("@", 2).pop().toLocaleLowerCase(); const cacheKey = domain + ":" + this.session.remoteAddress; const result = await spfCache.getOrCreateJsonAsync(cacheKey, () => spf({ sender: address, ip: this.session.remoteAddress, helo: this.session.hostNameAppearsAs, mta: this.session.clientHostname })); // const result = await spf({ // sender: address, // ip: this.session.remoteAddress, // helo: this.session.hostNameAppearsAs, // mta: this.session.clientHostname // }); if (!/pass/i.test(result.status.result)) { console.error(result.status.comment); throw new SmtpError("SPF Check Failed " + result.status.comment, SmtpStatusCodes.DeliveryNotPermitted); } } async acceptFrom(address: { address: string, args? }) { // check if we are planning to block anyone... if (this.from) { throw new SmtpError("Unknown sequence of commands", SmtpStatusCodes.BadCommandSequence); } await this.verifySpf(address.address); this.from = address; const domain = this.fromDomain = this.from.address.split("@",2).pop(); this.domain = domain; // const mailbox = await this.emailAddressService.getHostedMailboxByAddress(address.address); // if (mailbox && !mailbox.isExternal) { // if (!this.session.user) { // console.error(`Login required for ${address.address}`); // throw new SmtpError("Login required", SmtpStatusCodes.AuthenticationRequired); // } // } const hostedDomain = await this.emailAddressService.getHostedDomain(domain); if (hostedDomain) { if (!this.session.user) { console.error(`Login required for ${address.address}`); throw new SmtpError("Login required", SmtpStatusCodes.AuthenticationRequired); } } this.recipients = new Map(); } async acceptRecipient(address: { address: string, args?}) { if (!this.recipients) { throw new SmtpError("Unknown sequence of commands", SmtpStatusCodes.BadCommandSequence); } const mailbox = await this.db.mailboxes .where(address, (x, p) => x.emailAddress.emailAddress === p.address && x.domain.hostedDomain.enableReceive === true ) .first(); if (mailbox == null) { await this.addDomainActivity("rcpt-not-found"); // update domain reputation throw new SmtpError(`Mailbox ${address.address} not found`, SmtpStatusCodes.MailboxUnavailable); } if (BigInt(mailbox.storage) >= BigInt(mailbox.maxStorage)) { throw new SmtpError(`Mailbox ${address.address} full`, SmtpStatusCodes.InsufficientStorage); } await this.addDomainActivity("mail-received"); // check if email is blocked... const mailboxID = mailbox.mailboxID; const contactID = (await this.emailAddressService.getIdIfExists(this.from.address)) || 0; const newTagID = await this.tagService.getSystemTagID("New"); const contact = await this.db.mailboxContacts.where({ mailboxID, contactID}, (x, p) => x.mailboxID === p.mailboxID && x.emailAddressID === p.contactID).first(); let isBlocked = false; let unacceptable = false; if (contact) { isBlocked = contact.blocked; unacceptable = !mailbox.isChannel && contact.folderTagID === newTagID && contact.total > 3; } if (isBlocked) { await sleep(3000); throw new SmtpError("Mailbox Unavailable", SmtpStatusCodes.MailboxUnavailable); } // await this.db.mailboxContacts.where({ mailboxID, contactID, newTagID }, (x, p) => x.mailboxID === p.mailboxID // && x.emailAddressID === p.contactID // && (x.blocked === true // || // (x.folderTagID === p.newTagID && x.total > 3) // )) // .some(); if (unacceptable) { await sleep(3000); throw new SmtpError("Content not acceptable", SmtpStatusCodes.DeliveryNotPermitted); } if (mailbox.isChannel) { const channelService = ServiceProvider.resolve(this, ChannelService); await channelService.getAccess(mailbox, contact); } this.recipients.set(address.address, mailbox); } async addDomainActivity(activity: serverActivities) { const ipAddress = this.session.remoteAddress; const domainID = await this.emailAddressService.getOrCreateDomain(this.fromDomain); await this.db.serverActivities.statements.insert({ domainID, activity, ipAddress }); const [d] = await this.db.domains .where({ domainID }, (x, p) => x.domainID === p.domainID) .updateSelect((x) => ({ received: Sql.coll.sum(x.activities.map((a) => a.activity === "mail-received" ? 1 : 0)), failed: Sql.coll.sum(x.activities.map((a) => a.activity === "rcpt-not-found" ? 1 : 0)), })); if (activity === "rcpt-not-found") { const { failed, received } = d ?? {}; if (failed > 3) { if (failed > (received / 10)) { this.ms.reputationCleared.notify(""); } } } } async acceptDataFile(tempFile: LocalFile): Promise { if (!this.recipients.size) { // this is the case when SMTP client still tries to send message // even when recipient was rejected await sleep(3000); throw new SmtpError("Content not acceptable", SmtpStatusCodes.DeliveryNotPermitted); } const { domain } = this; const error = await this.domainReputation.checkReputation(domain); if (error) { const recipients = Array.from(this.recipients.keys()).join(); console.error(`Reputation failed for ${this.from.address} rcpt to ${recipients}`); throw error; } // store file locally somewhere... await this.acceptFile(tempFile); } async acceptData(stream: smtpServer.SMTPServerDataStream): Promise { if (!this.recipients.size) { // this is the case when SMTP client still tries to send message // even when recipient was rejected await sleep(3000); throw new SmtpError("Content not acceptable", SmtpStatusCodes.DeliveryNotPermitted); } const { domain } = this; const error = await this.domainReputation.checkReputation(domain); if (error) { const recipients = Array.from(this.recipients.keys()).join(); console.error(`Reputation failed for ${this.from.address} rcpt to ${recipients}`); throw error; } // store file locally somewhere... const tempFile = await this.tempFileService.createTempFile(".eml"); await fsp.writeFile(tempFile.path, stream); await this.acceptFile(tempFile); } async acceptFile(tempFile: LocalFile) { const { ars, authHeaders, logs } = await this.authenticate(tempFile); const log = JSON.stringify(logs); const file = await this.tempFileService.createTempFile(".eml"); await fsp.appendFile(file.path, authHeaders); await fsp.appendFile(file.path, await fsp.readFile(tempFile.path)); await this.emailSerializerService.save(file, { sender: this.from.address, ars, log, mailboxes: Array.from(this.recipients.values()), received: true }); } // private async parse(file: LocalFile) { // return new Promise((resolve, reject) => { // simpleParser(file.openRead(), (error, result) => { // if (error) { // reject(error); // return; // } // resolve(result); // }); // }); // } private async authenticate(tempFile: LocalFile) { const ars = { dkim: "none", spf: "none", dmarc: "none" }; // skip dmarc for local testing... if(globalEnv.smtp.skipDmarcForTest) { return { ars, logs: [], authHeaders: ""}; } const ids = Array.from(this.recipients.values()).map((x) => x.domainID); const dkimSignerKey = await this.db.domainKeys .where({ ids }, (x, p) => x.domainID in p.ids) .include((x) => x.hostedDomain.domain) .first(); let seal = void 0; if (dkimSignerKey) { seal = { signingDomain: dkimSignerKey.hostedDomain.domain.name, selector: dkimSignerKey.name, privateKey: dkimSignerKey.privateKey }; } const ip = this.session.remoteAddress; const helo = this.session.hostNameAppearsAs; const sender = this.from.address; const logs = await authenticate(tempFile.openReadStream(), { ip, helo, sender, mta: globalEnv.host, seal }); const { dmarc, headers: authHeaders } = logs; if(!isTestMode) { if (dmarc) { if (dmarc.status.result !== "pass") { console.error(`Permanent error evaluating dmarc policy for ${ip}, sender ${sender}, helo: ${helo} ${JSON.stringify(dmarc, void 0, 2)}`); throw new SmtpError(`5.7.5 permanent error evaluating dmarc policy for ${ip}`, SmtpStatusCodes.TransactionFailed); } } else { console.error(`DMARC not setup for ${this.session.hostNameAppearsAs}`); } } if (logs) { const { spf: spfResult, dmarc: dmarc1, dkim } = logs; if (dmarc1 && dmarc1.status) { ars.dmarc = dmarc1.status.result; } if(spfResult && spfResult.status) { ars.spf = spfResult.status.result; } if(dkim?.results) { for (const iterator of dkim.results) { const { result } = iterator.status ?? {}; if(result !== "pass") { ars.dkim = "reject"; continue; } if (ars.dkim === "reject") { continue; } if (result=== "pass") { ars.dkim = "pass"; } } } } return { ars, logs, authHeaders }; } }