Fixes formatted description in email + sanitize html everywhere (#7928)

* use sanitize-html instead

* add list formatting

* add lost changes from merging main

* fixes caused by merge

* remove dompurify

* Revert "remove dompurify"

This reverts commit 583bb623c7d3c0c7daa28e63ab2b1ac2da68c0d8.

* sanitize already done in editor

* Update yarn.lock

---------

Co-authored-by: CarinaWolli <[email protected]>
Co-authored-by: Alex van Andel <[email protected]>
This commit is contained in:
authored and GitHub committed 2023-03-28 09:40:13 +00:00
1 parent 02d32321aa
commit 3aaa1cde0d
26 files changed
+175 -87

No files matched your search

+20 -1
View File
@@ -1,3 +1,5 @@
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
const Spacer = () => <p style={{ height: 6 }} />;
export const Info = (props: {
@@ -6,8 +8,14 @@ export const Info = (props: {
extraInfo?: React.ReactNode;
withSpacer?: boolean;
lineThrough?: boolean;
formatted?: boolean;
}) => {
if (!props.description || props.description === "") return null;
const descriptionCSS = "color: '#101010'; font-weight: 400; line-height: 24px; margin: 0;";
const safeDescription = markdownToSafeHTML(props.description.toString()) || "";
return (
<>
{props.withSpacer && <Spacer />}
@@ -21,7 +29,18 @@ export const Info = (props: {
whiteSpace: "pre-wrap",
textDecoration: props.lineThrough ? "line-through" : undefined,
}}>
{props.description}
{props.formatted ? (
<p
className="dark:text-darkgray-600 mt-2 text-sm text-gray-500 [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
dangerouslySetInnerHTML={{
__html: safeDescription
.replaceAll("<p>", `<p style="${descriptionCSS}">`)
.replaceAll("<li>", `<li style="${descriptionCSS}">`),
}}
/>
) : (
props.description
)}
</p>
{props.extraInfo}
</div>
@@ -76,7 +76,7 @@ export const BaseScheduledEmail = (
<WhenInfo calEvent={props.calEvent} t={t} timeZone={timeZone} />
<WhoInfo calEvent={props.calEvent} t={t} />
<LocationInfo calEvent={props.calEvent} t={t} />
<Info label={t("description")} description={props.calEvent.description} withSpacer />
<Info label={t("description")} description={props.calEvent.description} withSpacer formatted />
<Info label={t("additional_notes")} description={props.calEvent.additionalNotes} withSpacer />
{props.includeAppsStatus && <AppsStatus calEvent={props.calEvent} t={t} />}
<UserFieldsResponses calEvent={props.calEvent} />
@@ -256,7 +256,7 @@ const ProfileView = () => {
<Label className="mt-5 text-black">{t("about")}</Label>
<div
className="dark:text-darkgray-600 text-sm text-gray-500 [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600"
dangerouslySetInnerHTML={{ __html: md.render(team.bio || "") }}
dangerouslySetInnerHTML={{ __html: team.safeBio || "" }}
/>
</>
)}
@@ -7,7 +7,6 @@ import type { z } from "zod";
import { classNames, parseRecurringEvent } from "@calcom/lib";
import getPaymentAppData from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { addListFormatting, md } from "@calcom/lib/markdownIt";
import type { baseEventTypeSelect } from "@calcom/prisma";
import type { EventTypeModel } from "@calcom/prisma/zod";
import { Badge } from "@calcom/ui";
@@ -26,6 +25,7 @@ export type EventTypeDescriptionProps = {
z.infer<typeof EventTypeModel>,
Exclude<keyof typeof baseEventTypeSelect, "recurringEvent"> | "metadata"
> & {
descriptionAsSafeHTML?: string | null;
recurringEvent: Prisma.JsonValue;
seatsPerTimeSlot?: number;
};
@@ -57,7 +57,7 @@ export const EventTypeDescription = ({
shortenDescription ? "line-clamp-4" : ""
)}
dangerouslySetInnerHTML={{
__html: addListFormatting(md.render(eventType.description)),
__html: eventType.descriptionAsSafeHTML || "",
}}
/>
)}
-9
View File
@@ -1,12 +1,3 @@
import MarkdownIt from "markdown-it";
export const md = new MarkdownIt("default", { html: true, breaks: true, linkify: true });
export function addListFormatting(html: string) {
return html
.replaceAll("<ul>", "<ul style='list-style-type: disc; list-style-position: inside; margin-left: 12px'>")
.replaceAll(
"<ol>",
"<ol style='list-style-type: decimal; list-style-position: inside; margin-left: 12px'>"
);
}
+23
View File
@@ -0,0 +1,23 @@
import sanitizeHtml from "sanitize-html";
import { md } from "@calcom/lib/markdownIt";
export function markdownToSafeHTML(markdown: string | null) {
if (!markdown) return null;
const html = md.render(markdown);
const safeHTML = sanitizeHtml(html);
const safeHTMLWithListFormatting = safeHTML
.replace(
/<ul>/g,
"<ul style='list-style-type: disc; list-style-position: inside; margin-left: 12px; margin-bottom: 4px'>"
)
.replace(
/<ol>/g,
"<ol style='list-style-type: decimal; list-style-position: inside; margin-left: 12px; margin-bottom: 4px'>"
);
return safeHTMLWithListFormatting;
}
+3 -3
View File
@@ -1,6 +1,7 @@
import { Prisma, PrismaClient } from "@prisma/client";
import type { Prisma } from "@prisma/client";
import { PrismaClient } from "@prisma/client";
import { bookingReferenceMiddleware, eventTypeDescriptionParseAndSanitizeMiddleware } from "./middleware";
import { bookingReferenceMiddleware } from "./middleware";
declare global {
// eslint-disable-next-line no-var
@@ -21,7 +22,6 @@ if (process.env.NODE_ENV !== "production") {
}
// If any changed on middleware server restart is required
bookingReferenceMiddleware(prisma);
eventTypeDescriptionParseAndSanitizeMiddleware(prisma);
export default prisma;
@@ -1,43 +0,0 @@
import type { PrismaClient, EventType } from "@prisma/client";
import { md } from "@calcom/lib/markdownIt";
function parseAndSanitize(description: string) {
const parsedMarkdown = md.render(description);
return parsedMarkdown;
}
function getParsedResults(eventTypes: EventType | EventType[]) {
const results = Array.isArray(eventTypes) ? eventTypes : [eventTypes];
const parsedResults = results.map((record) => ({
...record,
descriptionAsSafeHTML: record.description ? parseAndSanitize(record.description) : null,
}));
/* If the original result was an array, return the parsed array, otherwise is a single record */
return Array.isArray(eventTypes) ? parsedResults : parsedResults[0];
}
/**
* Parses event type descriptions and treat them as markdown,
* then sanitizes the resulting HTML and adds a new `descriptionAsSafeHTML` property.
*/
function eventTypeDescriptionParseAndSanitize(prisma: PrismaClient) {
prisma.$use(async (params, next) => {
if (params.model === "Team") {
const result = await next(params);
if (result?.eventTypes) {
result.eventTypes = getParsedResults(result.eventTypes);
}
return result;
} else if (params.model === "EventType") {
const result = await next(params);
if (result) {
return getParsedResults(result);
}
return result;
}
return next(params);
});
}
export default eventTypeDescriptionParseAndSanitize;
-1
View File
@@ -1,2 +1 @@
export { default as bookingReferenceMiddleware } from "./bookingReference";
export { default as eventTypeDescriptionParseAndSanitizeMiddleware } from "./eventTypeDescriptionParseAndSanitize";
+2 -1
View File
@@ -203,7 +203,8 @@
"categories": ["video"],
"slug": "facetime",
"type": "facetime_video",
"isTemplate": false},
"isTemplate": false
},
{
"dirName": "zohocrm",
"categories": ["other"],
@@ -12,6 +12,7 @@ import getApps, { getAppFromLocationValue, getAppFromSlug } from "@calcom/app-st
import { validateIntervalLimitOrder } from "@calcom/lib";
import { CAL_URL } from "@calcom/lib/constants";
import getEventTypeById from "@calcom/lib/getEventTypeById";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import { baseEventTypeSelect, baseUserSelect } from "@calcom/prisma";
import { _DestinationCalendarModel, _EventTypeModel } from "@calcom/prisma/zod";
import type { CustomInputSchema } from "@calcom/prisma/zod-utils";
@@ -283,6 +284,7 @@ export const eventTypesRouter = router({
const mapEventType = (eventType: (typeof user.eventTypes)[number]) => ({
...eventType,
safeDescription: markdownToSafeHTML(eventType.description),
users: !!eventType.hosts?.length ? eventType.hosts.map((host) => host.user) : eventType.users,
// @FIXME: cc @hariombalhara This is failing with production data
// metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
@@ -11,6 +11,7 @@ import {
updateQuantitySubscriptionFromStripe,
} from "@calcom/features/ee/teams/lib/payments";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import { getTranslation } from "@calcom/lib/server/i18n";
import { getTeamWithMembers, isTeamAdmin, isTeamMember, isTeamOwner } from "@calcom/lib/server/queries/teams";
import slugify from "@calcom/lib/slugify";
@@ -42,9 +43,9 @@ export const viewerTeamsRouter = router({
throw new TRPCError({ code: "NOT_FOUND", message: "Team not found." });
}
const membership = team?.members.find((membership) => membership.id === ctx.user.id);
return {
...team,
safeBio: markdownToSafeHTML(team.bio),
membership: {
role: membership?.role as MembershipRole,
accepted: membership?.accepted,
@@ -351,7 +351,7 @@ export default function ToolbarPlugin(props: TextEditorProps) {
editor.registerUpdateListener(({ editorState, prevEditorState }) => {
editorState.read(() => {
const textInHtml = $generateHtmlFromNodes(editor);
const textInHtml = $generateHtmlFromNodes(editor).replace(/&lt;/g, "<").replace(/&gt;/g, ">");
props.setText(textInHtml);
});
if (!prevEditorState._selection) editor.blur();