/* eslint-disable @typescript-eslint/no-base-to-string */ import Inject, { RegisterScoped } from "@entity-access/entity-access/dist/di/di.js"; import TempFileService from "../../storage/TempFileService.js"; import BaseStorage from "../../storage/BaseStorage.js"; import { emailStatusType } from "../../model/entities/Email.js"; import EmailAddressService from "../../services/EmailAddressService.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import type { contentDispositionTypes } from "../../model/entities/AppFile.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import { writeFile } from "fs/promises"; import FileInfectedError from "../../storage/FileInfectedError.js"; import { spawnPromise } from "../../../common/spawnPromise.js"; import { hash, randomUUID } from "crypto"; import MailComposer from "nodemailer/lib/mail-composer/index.js"; import { unlinkSync } from "fs"; import EmailParserService from "./EmailParserService.js"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import { AppStringHelper } from "../../../common/AppStringHelper.js"; import Mailbox from "../../model/entities/Mailbox.js"; import EmailLogService from "../../services/email-logs/EmailLogService.js"; import AVService from "../../storage/volume/av/AVService.js"; import EmailRecipient from "../../model/entities/EmailRecipient.js"; import { ReactionExtractor } from "../../../protocols/core/ReactionExtractor.js"; import { stripBrackets } from "../../../common/stripBrackets.js"; import SmtpError from "./SmtpError.js"; import { SmtpStatusCodes } from "../client/SmtpStatusCodes.js"; import { Base36 } from "../../../common/Base36.js"; import DownloadExternalAttachmentWorkflow from "../../workflows/external-body/DownloadExternalAttachmentWorkflow.js"; import { AppWorkflowContext } from "../../workflows/AppWorkflowContext.js"; import HeaderContactList from "@social-mail/shared/dist/mime-parser/HeaderContactList.js"; import HeaderEmailAddress from "@social-mail/shared/dist/mime-parser/HeaderEmailAddress.js"; import FailedReporter from "../../../common/FailedReporter.js"; 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, name } of items.value) { // // emailAddress can have comma... not allowed but bankers still do ... // if (!address) { // continue; // } // for (const emailAddress of tokenize(address, ",")) { // if (!emailAddress) { // continue; // } // r.push({ // type, // emailAddress, // name // }); // } // } // return r; // }; // const stripDuplicates = (addresses: IEmailRecipientInfo[]) => { // const r = []; // const set = new Set(); // for (const iterator of addresses) { // if (!iterator.emailAddress) { // continue; // } // iterator.emailAddress = iterator.emailAddress.trim().toLocaleLowerCase(); // if (set.has(iterator.emailAddress)) { // continue; // } // r.push(iterator); // set.add(iterator.emailAddress); // } // return r; // }; export interface IEmailInfo { externalEmailID: string, labels: string[], mailbox: Mailbox, silent?: boolean, receivedViaSMTP?: boolean, messageId: string isDraft?: boolean; localEmailID?: number; }; export interface ISaveEmailInfo { sender?: string, localEmailID?: number, syncedMailbox?: Mailbox, mailboxes: Mailbox[], received?: boolean, silent?: boolean, isDraft?: boolean, ars?: any, log?: string, labels?: string[], externalEmailID?: string } @RegisterScoped export default class EmailSerializerService { @Inject storage: BaseStorage; @Inject private emailAddressService: EmailAddressService; @Inject private db: SocialMailContext; @Inject private tempFileService: TempFileService; @Inject private emailParserService: EmailParserService; @Inject private emailLogService: EmailLogService; @Inject private workflowContext: AppWorkflowContext; async saveRFC822(text: string, emailInfo: IEmailInfo) { const { tempFileService } = this; const file = await tempFileService.createTempFile(".eml", void 0, "message/rfc822"); await writeFile(file.path, text, "utf-8"); await this.saveRFC822File(file, emailInfo); } async saveRFC822File(file: LocalFile, emailInfo: IEmailInfo) { const { externalEmailID, labels, mailbox, silent, receivedViaSMTP, localEmailID, isDraft} = emailInfo; const { tempFileService, db } = this; const mailboxes = [mailbox]; try { // scan for viruses.... await AVService.scan(file); await this.save(file, { syncedMailbox: mailbox, mailboxes, externalEmailID, silent, labels, localEmailID, isDraft, received: receivedViaSMTP }); } catch (error) { if (error instanceof FileInfectedError) { // eslint-disable-next-line no-console console.error(error); const f = await tempFileService.createTempFile(".zip", "email"); unlinkSync(f.path); // encrypt and save... const id = randomUUID().replaceAll("-", "").toLowerCase(); await spawnPromise(`7z`, ["a", f.path, file.path, "-p" + id, "-mem=AES256"], { logData: false, logCommand: false }); const parsedMail = await this.emailParserService.parse(file); const mail = new MailComposer({ from: parsedMail.from.emailAddress ?? "antivirus@antivirus.none", html: `

This email may contain harmful content, so it is encrypted with following password, please open with caution.

${id}

`, subject: `AV-WARNING - ${parsedMail.subject}`, messageId: parsedMail.messageId, date: parsedMail.date, attachments: [ { filename: "harmful-email.zip", contentType: "application/zip", content: f.openReadStream() } ] }); const mime = mail.compile(); const emailFile = await tempFileService.createFrom("harmful-email.zip", mime.createReadStream(), "message/rfc822"); await this.saveRFC822File(emailFile, emailInfo); return; } await FailedReporter.copy(file); throw error; } db.changeSet.clear(); } async save(file: LocalFile, { mailboxes, syncedMailbox, received = true, isDraft, silent, ars, sender, log, localEmailID, externalEmailID, labels }: ISaveEmailInfo) { const { tempFileService, db } = this; db.verifyFilters = false; db.raiseEvents = true; // parse mail... // console.log(`Parsing ${file.path}`); const parsedMail = await this.emailParserService.parse(file); // console.log(`Parsed ${file.path}`); // console.log(JSON.stringify(parsedMail, void 0 ,2)); const from = parsedMail.from ?? { emailAddress: "", name: "" }; let parentID = null; const subject = AppStringHelper.remove00(parsedMail.subject || ""); const { messageId, priority, replyTo } = parsedMail; const recipients = [] as Partial[]; const recipientSet = new Set(); const addRecipients = async (type, cl: HeaderContactList) => { for (const iterator of cl.addresses) { let { name, emailAddress } = iterator; if (!emailAddress) { continue; } emailAddress = emailAddress.trim(); if(!emailAddress) { continue; } if (name) { if (name.length > 400) { name = name.substring(0, 399); } } // console.log(`Saving recipient "${emailAddress}" with "${name}"`); const emailAddressID = await this.emailAddressService.getId(emailAddress, name); // console.log(`Recipient "${emailAddress}" saved.`); if(recipientSet.has(emailAddressID)) { continue; } recipientSet.add(emailAddressID); recipients.push({ emailAddressID, type }); } }; const { to, cc, bcc} = parsedMail; if (to) { await addRecipients("to", to); } if (cc) { await addRecipients("cc", cc); } if (bcc) { await addRecipients("bcc", bcc); } // put mailboxes as bcc // bcc fixed const syncedMailboxID = syncedMailbox?.mailboxID; if(syncedMailboxID) { for (const mb of mailboxes) { if(recipients.some((r) => r.emailAddressID === mb.mailboxID)) { continue; } recipients.push({ emailAddressID: mb.mailboxID, type: "bcc"}); } } const senderID = await this.emailAddressService.getId(from.emailAddress || sender || "", from.name, false); let inReplyTo = parsedMail.inReplyTo; const headerObj = { ars, messageId, priority, inReplyTo } as any; if (replyTo) { headerObj.replyTo = replyTo; } const headers = JSON.stringify(headerObj); const htmlBody = AppStringHelper.remove00(parsedMail.html || parsedMail.textAsHtml); const textBody = AppStringHelper.remove00(parsedMail.text); const status: emailStatusType = isDraft ? "draft" : "received"; // console.log("Saving Recipients"); // const recipients = await Promise.all(stripDuplicates([ // ... combineAddresses("to", parsedMail.to), // ... combineAddresses("cc", parsedMail.cc)]).map(async ({ name, type, emailAddress }) => { // return { // emailAddressID: await this.emailAddressService.getId(emailAddress, name), // name, // type: type as any // }; // })); // console.log("Recipients Saved"); const dateReceived = DateTime.from(parsedMail.date ?? DateTime.now); const dateSent = dateReceived; let tags = null; if (labels) { tags = labels.map((x) => x.startsWith("#") ? x : `#${x}`).join(","); } let engagement = null; let verifyParentID = null; if (received) { // check for engagements... const e1 = await ReactionExtractor.extractWithInReplyTo({ subject, textBody, firstHeader: (h) => parsedMail.firstHeaderString(h) }, () => Promise.resolve(parsedMail.attachments), true); engagement = e1.engagement; if (!inReplyTo) { inReplyTo = [ HeaderEmailAddress.parse(e1.inReplyTo)]; verifyParentID = Base36.decode(e1.emailID) as any; } } if (inReplyTo) { // find the id.. for(const ea of inReplyTo) { let q = db.emails.where(ea, (x, p) => x.headerMessageID === p.emailAddress); if (verifyParentID) { q = q.where({ verifyParentID }, (x, p) => x.emailID === p.verifyParentID); } const original = await q .orderBy((x) => x.emailID) .first(); if (original) { parentID = original.emailID; inReplyTo = null; } } } // console.log(`Saving Log ${file.path}`); const mimeFile = await this.emailLogService.save(null, file); // console.log(`Saved Log ${file.path}`); let emailID = void 0; if (localEmailID) { // delete all children... // including logs... emailID = localEmailID; await this.emailLogService.deleteAll(emailID); } // add recipient from mailboxes if (mailboxes) { for (const mailbox of mailboxes) { // check if it is a channel // verify if (mailbox.isChannel) { if (!engagement) { if(subject.startsWith("subscribe")) { engagement = "➕"; } } // if it is engagement... if (!/^(➕-)?subscribe/ui.test(subject)) { if (!mailbox.membersCanPostTopLevel) { if (!parentID && !engagement) { const me = await this.db.mailboxContacts.statements.select({}, { mailboxID: mailbox.mailboxID, emailAddressID: senderID}); const canContribute = me && (me.canContribute || me.isOwner); if (!canContribute) { throw new SmtpError("Only active members of channel can create new posts to channel", SmtpStatusCodes.SenderBlocked); } } } } } } } const hasUnsubscribe = !!(parsedMail.firstHeaderString("list-unsubscribe") || parsedMail.firstHeaderString("list-unsubscribe-post")); const email = emailID ? await db.emails.withKeys({ emailID}).select(true) : db.emails.add({ }); email.emailID = emailID; email.attachments ??= []; email.recipients ??= []; email.dateCreated = DateTime.now; email.dateReceived = dateReceived; email.dateSent = dateSent; email.senderName = from.name || from.emailAddress; email.headerMessageID = stripBrackets(parsedMail.messageId); email.senderID = senderID; email.received = received; email.parentID = parentID; email.inReplyTo = inReplyTo?.toString(); email.mimeFileID = mimeFile.logID; email.tags = tags; email.hasUnsubscribe = hasUnsubscribe; email.engagement = engagement; email.headers = headers; email.externalEmailID = externalEmailID; email.syncedMailboxID = syncedMailboxID; email.htmlBody = htmlBody; email.subject = subject; email.status = status; email.textBody = textBody; email.silent = silent; if (emailID) { // we need to regenerate these collections as in draft mode // if email recipients or attachments were modified, we can update them. await db.emailRecipients.asQuery().delete(email, (x, p) => x.emailID === p.emailID); await db.appFiles.asQuery().delete(email, (x, p) => x.emailID === p.emailID); } for(const er of recipients) { email.recipients.push(db.emailRecipients.add(er)); } await db.saveChanges(); // lets queue emailID = email.emailID; if (log) { await this.emailLogService.saveText(email.emailID, "received.log", log); } await db.emailLogs.withKeys({ logID: mimeFile.logID}) .update({ emailID }); // we cannot parallelize this // saving too many attachments will // fail with maximum size of pool reached error. if(parsedMail.attachments) { for(const x of parsedMail.attachments) { const { fileName, disposition, contentId } = x; let { type: contentType } = x; if (contentType === "message/external-body") { contentType = x.firstHeaderString("expect-content-type"); const link = await x.text(); const ea = await this.db.externalAttachments.statements.insert({ name: fileName, contentType, contentDisposition: disposition, link, emailID, contentID: contentId, }); await this.workflowContext.queue(DownloadExternalAttachmentWorkflow, ea.attachmentID, { id: `external-attachment-${emailID}-${hash("sha256", link)}` }); continue; } const f = await tempFileService.createFrom(fileName, Buffer.from(await x.arrayBuffer()), contentType); await this.storage.saveFile(f, { contentDisposition: disposition as contentDispositionTypes, contentID: contentId, emailID: email.emailID }); }; } return email; } }