Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add markdown support for consent message #2100

Merged
merged 2 commits into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"format-check": "prettier --check src/showcase src/frontend tsconfig.json .eslintrc.json vite.config.ts vite.plugins.ts vitest.config.ts demos"
},
"devDependencies": {
"@types/dompurify": "^3.0.5",
"@types/html-minifier-terser": "^7.0.0",
"@types/http-proxy": "^1.17.14",
"@types/selenium-standalone": "^7.0.1",
Expand Down Expand Up @@ -63,9 +64,11 @@
"@dfinity/utils": "^0.0.20",
"bip39": "^3.0.4",
"buffer": "^6.0.3",
"dompurify": "^3.0.6",
"idb-keyval": "^6.2.1",
"jose": "^5.1.3",
"lit-html": "^2.7.2",
"marked": "^11.0.0",
peterpeterparker marked this conversation as resolved.
Show resolved Hide resolved
"process": "^0.11.10",
"qr-creator": "^1.0.0",
"stream-browserify": "^3.0.0",
Expand Down
23 changes: 19 additions & 4 deletions src/frontend/src/flows/verifiableCredentials/allowCredentials.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { mkAnchorInput } from "$src/components/anchorInput";
import { mainWindow } from "$src/components/mainWindow";
import { I18n } from "$src/i18n";
import { mount, renderPage } from "$src/utils/lit-html";
import { TemplateResult, html } from "lit-html";
import { markdownToHTML } from "$src/utils/html";
import { mount, renderPage, TemplateElement } from "$src/utils/lit-html";
import { Chan } from "$src/utils/utils";
import { html, TemplateResult } from "lit-html";
import { asyncReplace } from "lit-html/directives/async-replace.js";
import { unsafeHTML } from "lit-html/directives/unsafe-html.js";

import DOMPurify from "dompurify";

import copyJson from "./allowCredentials.json";

Expand All @@ -13,7 +19,7 @@ const allowCredentialsTemplate = ({
i18n,
relyingOrigin,
providerOrigin,
consentMessage,
consentMessage: consentMessage_,
userNumber,
onAllow,
onCancel,
Expand All @@ -35,6 +41,15 @@ const allowCredentialsTemplate = ({
onSubmit: (userNumber) => onAllow(userNumber),
});

const consentMessage = new Chan<TemplateElement>(html`${consentMessage_}`);

// Kickstart markdown parsing & sanitizing; once done, replace the consent message
void (async () => {
peterpeterparker marked this conversation as resolved.
Show resolved Hide resolved
const parsed = await markdownToHTML(consentMessage_);
const sanitized = await DOMPurify.sanitize(parsed);
consentMessage.send(unsafeHTML(sanitized));
})();

const slot = html`
<hgroup
data-page="vc-allow"
Expand All @@ -52,7 +67,7 @@ const allowCredentialsTemplate = ({
</p>

<div class="l-stack c-input c-input--readonly">
<pre class="c-consent-message">${consentMessage}</pre>
<pre class="c-consent-message">${asyncReplace(consentMessage)}</pre>
</div>

<div class="c-button-group">
Expand Down
7 changes: 7 additions & 0 deletions src/frontend/src/styles/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -2780,6 +2780,13 @@ input[type="checkbox"] {
font-family: monospace;
}

/* The styling for the markdown-rendered elements of the message
* (very minimalistic styling) */
.c-consent-message h1 {
font-size: 1.2em;
margin-bottom: 0.5em;
}

/*
Marquee

Expand Down
109 changes: 109 additions & 0 deletions src/frontend/src/utils/html.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Copied verbatim (modulo linting comment, formatting & eager importing) from NNS dapp
// https://github.com/dfinity/nns-dapp/blob/4619857a316be5b47a950c6b8461ffcaa1a3dde3/frontend/src/lib/utils/html.utils.ts#L94
//

import { isNullish } from "@dfinity/utils";
import type { marked as markedTypes, Renderer } from "marked";
import { marked } from "marked";

type Marked = typeof markedTypes;

export const targetBlankLinkRenderer = (
href: string | null | undefined,
title: string | null | undefined,
text: string
): string =>
`<a${
href === null || href === undefined
? ""
: ` target="_blank" rel="noopener noreferrer" href="${href}"`
}${title === null || title === undefined ? "" : ` title="${title}"`}>${
text.length === 0 ? href ?? title : text
}</a>`;

/**
* Based on https://github.com/markedjs/marked/blob/master/src/Renderer.js#L186
* @returns <a> tag to image
*/
export const imageToLinkRenderer = (
src: string | null | undefined,
title: string | null | undefined,
alt: string
): string => {
if (src === undefined || src === null || src?.length === 0) {
return alt;
}
const fileExtention = src.includes(".")
? (src.split(".").pop() as string)
: "";
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-type
const typeProp =
fileExtention === "" ? undefined : ` type="image/${fileExtention}"`;
const titleDefined = title !== undefined && title !== null;
const titleProp = titleDefined ? ` title="${title}"` : undefined;
const text = alt === "" ? (titleDefined ? title : src) : alt;

return `<a href="${src}" target="_blank" rel="noopener noreferrer"${
typeProp ?? ""
}${titleProp ?? ""}>${text}</a>`;
};

const escapeHtml = (html: string): string =>
html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
const escapeSvgs = (html: string): string =>
html.replace(/<svg[^>]*>[\s\S]*?<\/svg>/gi, escapeHtml);

/**
* Escape <img> tags or convert them to links
*/
const transformImg = (img: string): string => {
const src = img.match(/src="([^"]+)"/)?.[1];
// eslint-disable-next-line
const alt = img.match(/alt="([^"]+)"/)?.[1] || "img";
const title = img.match(/title="([^"]+)"/)?.[1];
const shouldEscape = isNullish(src) || src.startsWith("data:image");
const imageHtml = shouldEscape
? escapeHtml(img)
: imageToLinkRenderer(src, title, alt);

return imageHtml;
};

/** Avoid <img> tags; instead, apply the same logic as for markdown images by either escaping them or converting them to links. */
export const htmlRenderer = (html: string): string =>
/<img\s+[^>]*>/gi.test(html) ? transformImg(html) : html;

/**
* Marked.js renderer for proposal summary.
* Customized renderers
* - targetBlankLinkRenderer
* - imageToLinkRenderer
* - htmlRenderer
*
* @param marked
*/
const proposalSummaryRenderer = (marked: Marked): Renderer => {
const renderer = new marked.Renderer();

renderer.link = targetBlankLinkRenderer;
renderer.image = imageToLinkRenderer;
renderer.html = htmlRenderer;

return renderer;
};

/**
* Uses markedjs.
* Escape or transform to links some raw HTML tags (img, svg)
* @see {@link https://github.com/markedjs/marked}
*/
export const markdownToHTML = async (text: string): Promise<string> => {
// Replace the SVG elements in the HTML with their escaped versions to improve security.
// It's not possible to do it with html renderer because the svg consists of multiple tags.
// One edge case is not covered: if the svg is inside the <code> tag, it will be rendered as with &lt; & &gt; instead of "<" & ">"
const escapedText = escapeSvgs(text);

return await marked(escapedText, {
renderer: proposalSummaryRenderer(marked),
});
};