/* eslint-disable no-console */
import { RegisterSingleton } from "@entity-access/entity-access/dist/di/di.js";
import { JSDOM } from 'jsdom';
import DOMPurify, { WindowLike } from 'dompurify';
import SmtpError from "../../smtp/services/SmtpError.js";
import { SmtpStatusCodes } from "../../smtp/client/SmtpStatusCodes.js";
import { globalEnv } from "../../../common/globalEnv.js";
import { expandPlaceholders } from "../TemplateExpander.js";
import { URLSearchParams } from "url";
import BaseTransform from "./transforms/BaseTransform.js";
import Button3x from "./transforms/Button3x.js";
import type AppFile from "../../model/entities/AppFile.js";
import { tokenizeCssUrl } from "../../../protocols/core/tokenizer.js";
import XNode from "@entity-access/server-pages/dist/html/XNode.js";
import { descendentIterator } from "../../../common/html/Html.js";
const maxAttachmentSize = 25*1024*1024;
const url = `https://${globalEnv.host}`;
export interface ISanitizeParameters {
activityID?: number;
senderEmail?: string;
uid?: string;
emailID?: any;
postID?: string;
subscribed?: boolean;
messageID?: string;
recipientID?: any;
replaceButtons?: boolean;
accessCode?: string;
trackerUrl?: string;
listID?: any;
attachments?: AppFile[];
}
const transformerSymbol = Symbol("transformerSymbol");
@RegisterSingleton
export default class HtmlSanitizer {
prepareForPreview(html: string) {
const window = new JSDOM('', { url }).window as any as WindowLike;
const purify = DOMPurify(window);
const clean = purify.sanitize( `
${html}
`, { RETURN_DOM: true }) as HTMLElement;
const remove = [];
for (const iterator of clean.querySelectorAll(`*`)) {
const tx = this.getTransform(iterator);
if (tx) {
tx.undo(iterator);
continue;
}
const e1 = iterator as HTMLElement;
const swap = iterator.getAttribute("data-swap");
if (swap) {
e1.style.background = "";
for (const child of iterator.children) {
const ce = child as HTMLElement;
ce.style.color = "";
ce.style.backgroundColor = "";
}
continue;
}
const src = iterator.getAttribute("src");
if (src) {
if (/\/social\-mail\/social\//.test(url)
||
src.toLocaleLowerCase().startsWith(url)) {
remove.push(iterator);
continue;
}
}
const preview = iterator.getAttribute("data-preview");
if (!preview) {
continue;
}
if (preview === "true") {
e1.style.removeProperty("display");
continue;
}
remove.push(e1);
}
for (const iterator of remove) {
iterator.remove();
}
return clean.innerHTML;
}
sanitizeExternalResources({ html, text, prefix, blog }: { html: string, text: string, prefix, blog?: string }) {
const window = new JSDOM('', { url }).window as any as WindowLike;
const purify = DOMPurify(window);
const clean = purify.sanitize(html, { RETURN_DOM: true }) as HTMLElement;
const replacements = [] as Node[];
for (const node of descendentIterator(clean)) {
switch(node.nodeType) {
case 1:
const e = node as HTMLElement;
this.replaceSrc(e, prefix);
this.replaceSrc(e, prefix);
this.replaceBackground(e, prefix);
continue;
case 3:
const parent = node.parentElement;
if (!/^(STYLE|SCRIPT|A)$/.test(parent.tagName)) {
replacements.push(node);
}
continue;
}
}
// const div = window.document.createElement("div");
// for (const node of replacements) {
// const replaced = RegExpExtra.replaceLinks(node.nodeValue, blog);
// if (node.nodeValue !== replaced) {
// div.innerHTML = replaced;
// const parent = node.parentNode;
// let child = div.firstChild;
// while(child) {
// const next = child.nextSibling;
// div.removeChild(child);
// parent.insertBefore(child, node);
// child = next;
// }
// parent.removeChild(node);
// }
// }
html = clean?.outerHTML;
text ||= clean?.outerText;
for (const element of tokenizeCssUrl(html)) {
html = html.replaceAll(element, element.replace(/https?\:\/\//, prefix));
}
return { html, text };
}
replaceBackground(e: Element, prefix: any) {
if (!/body|td|th|table/i.test(e.tagName)) {
return;
}
const attributeName = "background";
let src = e.getAttribute(attributeName);
if (!src || src.startsWith("cid:")) {
return;
}
src = src.replace(/https?\:\/\//, prefix);
e.setAttribute(attributeName, src);
}
replaceSrc(e: Element, prefix: any) {
if (!/img|picture|video|source/i.test(e.tagName)) {
return;
}
const attributeName = "src";
let src = e.getAttribute(attributeName);
if (!src || src.startsWith("cid:")) {
return;
}
src = src.replace(/https?\:\/\//, prefix);
e.setAttribute(attributeName, src);
}
sanitize(html: string, text: string, replace?: ISanitizeParameters) {
const window = new JSDOM('', { url }).window as any as WindowLike;
const purify = DOMPurify(window);
const clean = purify.sanitize(html, { RETURN_DOM: true }) as HTMLElement;
if (replace) {
const senderDomain = replace.senderEmail.split("@").pop();
const { postID } = replace;
for(const e of clean.querySelectorAll("*")) {
if (postID) {
if(e.hasAttribute("data-stream-enabled")) {
const contentID = e.getAttribute("data-content-id");
if (contentID) {
const file = replace.attachments?.find((x) => x.contentID === contentID);
if (file) {
const webMUrl = `https://${globalEnv.host}/social-mail/c/d/${senderDomain}/webm-branded/${postID}/${file.appFileID}/${file.name}.b.webm`;
const webMLinkUrl = `https://${globalEnv.host}/social-mail/video-player/${senderDomain}/webm-branded/${postID}/${file.appFileID}/${file.name}.b.webm`;
const imgUrl = `https://${globalEnv.host}/social-mail/c/d/${senderDomain}/webp(700)/${postID}/${file.appFileID}/${file.name}.700.webp`;
switch(e.tagName) {
case "A":
e.setAttribute("href", webMLinkUrl);
break;
case "VIDEO":
if (file.fileSize > maxAttachmentSize) {
e.setAttribute("src", webMUrl);
e.setAttribute("poster", imgUrl);
}
break;
// case "IMG":
// e.setAttribute("src", imgUrl);
// break;
}
}
}
}
}
// replace all attributes
for (const iterator of e.attributes) {
if (!iterator.nodeValue) {
continue;
}
iterator.nodeValue = expandPlaceholders(iterator.nodeValue, replace);
}
if(e.childElementCount === 0) {
const { textContent } = e;
if (textContent) {
e.textContent = expandPlaceholders(textContent, replace);
}
}
this.updateCommandAttributes(e, replace);
const img = e.tagName === "IMG" ? e as HTMLImageElement : void 0;
if (!img) {
continue;
}
const src = img.getAttribute("src");
if (src?.startsWith("/")) {
const newSrc = url + src;
img.setAttribute("src", newSrc);
}
}
if (replace.trackerUrl) {
let trackerImg = clean.querySelector(`*[data-social-mail-tracker]`) as HTMLImageElement;
if (!trackerImg) {
trackerImg = window.document.createElement("img");
clean.appendChild(trackerImg);
}
trackerImg.setAttribute("data-social-mail-tracker","tracker");
trackerImg.src = replace.trackerUrl;
trackerImg.style.width = "1px";
trackerImg.style.height = "1px";
trackerImg.style.margin = "0";
trackerImg.style.opacity = "0";
}
const { listID, senderEmail, messageID } = replace;
if (listID) {
try {
let emojiBar = clean.querySelector(`:not(blockquote,details) [data-social-mail-commands="emoji-bar"]`);
if (!emojiBar) {
emojiBar = clean.ownerDocument.createElement("footer");
emojiBar.setAttribute("data-social-mail-commands", "emoji-bar");
clean.ownerDocument.body.appendChild(emojiBar);
}
emojiBar.setAttribute("style", "border: solid 1px lightgray;border-radius: 9999px;padding: 2px;padding-left: 5px;" +
"padding-right: 5px;display: table;margin-top: 20px;width: 100%;box-sizing: border-box;");
const emojiButton = (emoji, label = "", { body = emoji, mail = emoji, style=""} = {}) =>
(({emoji}{label}
) as XNode).render();
emojiBar.innerHTML = `
${ emojiButton("🙂")}
${ emojiButton("👍")}
${ emojiButton("✅")}
${emojiButton("💬", "Reply", { body: "" })}
${ emojiButton("❌", "Unsubscribe", { style: "display:table-cell; text-align: right;"})}
`;
} catch (error) {
console.error(error);
}
}
}
html = clean?.outerHTML ?? "";
text ||= clean?.outerText ?? "";
return { html, text, root: clean };
}
verifyChannelMessage(html: string) {
if (!html) {
throw new SmtpError("Invalid email format, only html expected", SmtpStatusCodes.DeliveryNotPermitted);
}
const window = new JSDOM('').window as any as WindowLike;
const purify = DOMPurify(window);
const clean = purify.sanitize(html, { RETURN_DOM: true}) as HTMLElement;
if (!clean.querySelector(`[data-command="unsubscribe"]`)) {
throw new SmtpError(`Unsubscribe button is missing`, SmtpStatusCodes.DeliveryNotPermitted);
}
// if(clean.querySelector(`[data-click-action="like-email"]`)) {
// throw new SmtpError(`Like button is missing`, SmtpStatusCodes.DeliveryNotPermitted);
// }
// if(clean.querySelector(`[data-click-action="comment-email"]`)) {
// throw new SmtpError(`Comment button is missing`, SmtpStatusCodes.DeliveryNotPermitted);
// }
}
protected getTransform(e: Element): BaseTransform {
const transform = e.getAttribute("data-social-mail-transform");
switch(transform) {
case "buttons-3x":
return Button3x[transformerSymbol] ??= new Button3x();
}
}
private updateCommandAttributes(e: Element, replace: ISanitizeParameters) {
const dataCommand = e.getAttribute("data-social-mail-command");
if (!dataCommand) {
return;
}
const { uid, senderEmail, subscribed, messageID, emailID = "$emailID$", activityID = "$activityID$" } = replace;
const usp = new URLSearchParams();
if (messageID) {
usp.append("in-reply-to", messageID);
}
let method = "track";
let track = e.getAttribute("data-social-mail-track");
let { accessCode } = replace;
if (!accessCode) {
accessCode = "";
}
switch (dataCommand) {
case "track":
case "approve":
case "reject":
switch(dataCommand) {
case "approve":
track = "✅";
break;
case "reject":
track = "❌";
break;
}
method = track;
usp.append("subject", `${track}:${uid}:${accessCode}`);
usp.append("body", `${track}\n\n`);
e.setAttribute("href", `mailto:${senderEmail}?${usp}`);
break;
case "subscribe":
if (!subscribed) {
usp.append("subject", `Subscribe:${uid}:${accessCode}`);
usp.append("body", `Subscribe\n\n`);
e.setAttribute("href", `mailto:${senderEmail}?${usp}`);
}
break;
case "unsubscribe":
if (subscribed) {
usp.append("subject", `Unsubscribe:${uid}:${accessCode}`);
usp.append("body", `Unsubscribe\n\n`);
e.setAttribute("href", `mailto:${senderEmail}?${usp}`);
}
break;
}
const className = "." + e.getAttribute("class");
const src = `${url}/social-mail/social/buttons-3x/${method}/${className}/${emailID}/${activityID}/`;
const tx = this.getTransform(e);
if (tx) {
tx.apply(e, src);
return;
}
// if (e.getAttribute("data-swap") === "background") {
// this.swapBackground(e as HTMLElement, src);
// return;
// }
if (e.getAttribute("data-replace") !== "true") {
return;
}
for (const iterator of e.children) {
iterator.setAttribute("data-preview", "true");
const element = iterator as HTMLElement;
element.style.setProperty("display", "none");
}
const img = e.ownerDocument.createElement("img");
const maxHeight = e.getAttribute("data-max-height") || "20px";
e.appendChild(img);
img.setAttribute("data-preview", "false");
if (maxHeight) {
img.setAttribute("style", `max-height: ${maxHeight}`);
}
img.setAttribute("src", src);
}
// private swapBackground(e: HTMLElement, src: string) {
// e.style.backgroundImage = `url("${src}")`;
// e.style.backgroundSize = "cover";
// e.style.backgroundPosition = "center";
// for (const iterator of e.children) {
// const ie = iterator as HTMLElement;
// ie.style.color = "transparent";
// ie.style.backgroundColor = "transparent";
// }
// }
}