Skip to content

Commit 4c6860b

Browse files
robzolkosjeremy
andauthored
Handle CommonMark backslash escapes in MarkdownToHTML (#402)
* Handle CommonMark backslash escapes in MarkdownToHTML * Ignore backslash-escaped safe tags in IsHTML and add richtext escape coverage * Exclude @ from escapable punctuation to prevent unwanted mentions \@ is the idiomatic way to suppress a mention ping in Basecamp. Without this, the new CommonMark backslash-escape handling would unescape \@ into a bare @ before ResolveMentions runs, silently converting an intentionally suppressed mention into a real ping. * Percent-encode backslash escapes in link/image destinations Backslash-escaped characters inside href/src need percent-encoding (%22, %5C, etc.) per CommonMark §6.7, not HTML entity escaping (&quot;). Resolve ESC/ESCBT placeholders during link/image construction with a destination-safe character set derived from markdown-it, before the general escapeAttr pass. --------- Co-authored-by: Jeremy Daer <jeremy@37signals.com>
1 parent d8a7fb0 commit 4c6860b

2 files changed

Lines changed: 316 additions & 10 deletions

File tree

‎internal/richtext/richtext.go‎

Lines changed: 137 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,15 @@ var (
2323
olPattern = regexp.MustCompile(`^(\s*)\d+\.\s+(.*)$`)
2424
)
2525

26+
// CommonMark §2.4: any ASCII punctuation may be backslash-escaped.
27+
// Exact set: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
28+
//
29+
// We intentionally omit @ from the set: in Basecamp context \@ is the
30+
// idiomatic way to suppress a mention ping, so it must pass through
31+
// literally and not be unescaped into a bare @ that ResolveMentions
32+
// would convert into a <bc-attachment> mention.
33+
const commonMarkEscapablePunctuation = "!\"#$%&'()*+,-./:;<=>?[\\]^_`{|}~"
34+
2635
// Pre-compiled regexes for convertInline (Markdown → HTML inline elements)
2736
var (
2837
reCodeSpan = regexp.MustCompile("`([^`]+)`")
@@ -34,6 +43,11 @@ var (
3443
reImage = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`)
3544
reLink = regexp.MustCompile(`\[([^\]]+)\]\(([^)]+)\)`)
3645
reStrikethrough = regexp.MustCompile(`~~([^~]+)~~`)
46+
47+
// Protect escaped backticks before code-span detection so \` does not start a code span.
48+
reEscapedBacktick = regexp.MustCompile("\\\\`")
49+
// Matches a backslash followed by any CommonMark-escapable ASCII punctuation character.
50+
reBackslashEscape = regexp.MustCompile(`\\([` + regexp.QuoteMeta(commonMarkEscapablePunctuation) + `])`)
3751
)
3852

3953
// Pre-compiled regexes for HTMLToMarkdown (HTML → Markdown block elements)
@@ -341,12 +355,19 @@ func MarkdownToHTML(md string) string {
341355
}
342356

343357
// convertInline converts inline Markdown elements (bold, italic, links, code) to HTML.
344-
// Code spans are protected from further processing to preserve their literal content.
358+
// Code spans and backslash escapes are protected from further processing to preserve
359+
// their literal content.
345360
func convertInline(text string) string {
346-
// Escape HTML entities first
347-
text = escapeHTML(text)
361+
// Protect escaped backticks before code-span detection so \` remains literal
362+
// and cannot be interpreted as a code-span delimiter.
363+
var escapedBackticks []string
364+
text = reEscapedBacktick.ReplaceAllStringFunc(text, func(_ string) string {
365+
idx := len(escapedBackticks)
366+
escapedBackticks = append(escapedBackticks, "`")
367+
return "\x00ESCBT" + strconv.Itoa(idx) + "\x00"
368+
})
348369

349-
// Extract code spans and replace with placeholders to protect them
370+
// Extract code spans — their content must be completely literal.
350371
var codeSpans []string
351372
text = reCodeSpan.ReplaceAllStringFunc(text, func(match string) string {
352373
inner := reCodeSpan.FindStringSubmatch(match)
@@ -358,6 +379,21 @@ func convertInline(text string) string {
358379
return match
359380
})
360381

382+
// Process backslash escapes (CommonMark §2.4): a backslash before an ASCII
383+
// punctuation character produces the literal character. We extract these into
384+
// placeholders so they are not treated as Markdown delimiters and restore
385+
// them afterward. We use attribute-safe escaping on restore because escaped
386+
// punctuation can be captured inside href/src values before link/image HTML is built.
387+
var escaped []string
388+
text = reBackslashEscape.ReplaceAllStringFunc(text, func(match string) string {
389+
idx := len(escaped)
390+
escaped = append(escaped, match[1:]) // the punctuation character after the backslash
391+
return "\x00ESC" + strconv.Itoa(idx) + "\x00"
392+
})
393+
394+
// Escape HTML entities
395+
text = escapeHTML(text)
396+
361397
// Bold with ** or __
362398
text = reBoldStar.ReplaceAllString(text, "<strong>$1</strong>")
363399
text = reBoldUnder.ReplaceAllString(text, "<strong>$1</strong>")
@@ -385,7 +421,8 @@ func convertInline(text string) string {
385421
parts := reImage.FindStringSubmatch(match)
386422
if len(parts) >= 3 {
387423
alt := escapeAttr(parts[1])
388-
src := escapeAttr(parts[2])
424+
src := resolveDestinationEscapes(parts[2], escaped, escapedBackticks)
425+
src = escapeAttr(src)
389426
return `<img src="` + src + `" alt="` + alt + `">`
390427
}
391428
return match
@@ -396,7 +433,8 @@ func convertInline(text string) string {
396433
parts := reLink.FindStringSubmatch(match)
397434
if len(parts) >= 3 {
398435
linkText := parts[1]
399-
href := escapeAttr(parts[2])
436+
href := resolveDestinationEscapes(parts[2], escaped, escapedBackticks)
437+
href = escapeAttr(href)
400438
return `<a href="` + href + `">` + linkText + `</a>`
401439
}
402440
return match
@@ -405,15 +443,45 @@ func convertInline(text string) string {
405443
// Strikethrough ~~text~~
406444
text = reStrikethrough.ReplaceAllString(text, "<del>$1</del>")
407445

408-
// Restore code spans
446+
// Restore backslash-escaped characters in body text. Placeholders inside
447+
// link/image destinations were already resolved with percent-encoding above.
448+
escapedRendered := make([]string, len(escaped))
449+
for i, ch := range escaped {
450+
escapedRendered[i] = escapeAttr(ch)
451+
}
452+
text = restorePlaceholders(text, "ESC", escapedRendered)
453+
text = restorePlaceholders(text, "ESCBT", escapedRenderedBackticks(escapedBackticks))
454+
455+
// Restore code spans (HTML-escape their content since extraction now
456+
// happens before escapeHTML to allow backslash-escape processing).
457+
codeRendered := make([]string, len(codeSpans))
409458
for i, code := range codeSpans {
410-
placeholder := "\x00CODE" + strconv.Itoa(i) + "\x00"
411-
text = strings.Replace(text, placeholder, "<code>"+code+"</code>", 1)
459+
codeRendered[i] = "<code>" + escapeHTML(code) + "</code>"
412460
}
461+
text = restorePlaceholders(text, "CODE", codeRendered)
413462

414463
return text
415464
}
416465

466+
func escapedRenderedBackticks(backticks []string) []string {
467+
rendered := make([]string, len(backticks))
468+
for i, bt := range backticks {
469+
rendered[i] = escapeAttr(bt)
470+
}
471+
return rendered
472+
}
473+
474+
func restorePlaceholders(text, prefix string, replacements []string) string {
475+
if len(replacements) == 0 {
476+
return text
477+
}
478+
pairs := make([]string, 0, len(replacements)*2)
479+
for i, repl := range replacements {
480+
pairs = append(pairs, "\x00"+prefix+strconv.Itoa(i)+"\x00", repl)
481+
}
482+
return strings.NewReplacer(pairs...).Replace(text)
483+
}
484+
417485
// escapeHTML escapes special HTML characters.
418486
func escapeHTML(s string) string {
419487
s = strings.ReplaceAll(s, "&", "&amp;")
@@ -430,6 +498,51 @@ func escapeAttr(s string) string {
430498
return s
431499
}
432500

501+
// percentEncodeChar percent-encodes a single byte for use in URL destinations.
502+
// Characters left literal match the destination-safe set derived from markdown-it:
503+
// !$&'()*+,-./:;=?@_~#
504+
// Everything else gets %XX hex encoding.
505+
func percentEncodeChar(ch byte) string {
506+
switch {
507+
case ch >= 'A' && ch <= 'Z', ch >= 'a' && ch <= 'z', ch >= '0' && ch <= '9':
508+
return string(ch)
509+
case ch == '!' || ch == '$' || ch == '&' || ch == '\'' ||
510+
ch == '(' || ch == ')' || ch == '*' || ch == '+' ||
511+
ch == ',' || ch == '-' || ch == '.' || ch == '/' ||
512+
ch == ':' || ch == ';' || ch == '=' || ch == '?' ||
513+
ch == '@' || ch == '_' || ch == '~' || ch == '#':
514+
return string(ch)
515+
default:
516+
return fmt.Sprintf("%%%02X", ch)
517+
}
518+
}
519+
520+
// resolveDestinationEscapes restores ESC and ESCBT placeholders within a link/image
521+
// destination using percent-encoding instead of HTML entity escaping.
522+
func resolveDestinationEscapes(dest string, escaped []string, escapedBackticks []string) string {
523+
for i, ch := range escaped {
524+
placeholder := "\x00ESC" + strconv.Itoa(i) + "\x00"
525+
if strings.Contains(dest, placeholder) {
526+
var encoded strings.Builder
527+
for j := range len(ch) {
528+
encoded.WriteString(percentEncodeChar(ch[j]))
529+
}
530+
dest = strings.ReplaceAll(dest, placeholder, encoded.String())
531+
}
532+
}
533+
for i, bt := range escapedBackticks {
534+
placeholder := "\x00ESCBT" + strconv.Itoa(i) + "\x00"
535+
if strings.Contains(dest, placeholder) {
536+
var encoded strings.Builder
537+
for j := range len(bt) {
538+
encoded.WriteString(percentEncodeChar(bt[j]))
539+
}
540+
dest = strings.ReplaceAll(dest, placeholder, encoded.String())
541+
}
542+
}
543+
return dest
544+
}
545+
433546
// sanitizeLanguage sanitizes a code block language identifier to prevent attribute injection.
434547
// Only allows alphanumeric characters, hyphens, and underscores.
435548
func sanitizeLanguage(lang string) string {
@@ -1007,7 +1120,21 @@ func IsHTML(s string) bool {
10071120
stripped := reFencedBlock.ReplaceAllString(s, "")
10081121
stripped = reCodeSpan.ReplaceAllString(stripped, "")
10091122

1010-
return reSafeTag.MatchString(stripped)
1123+
for _, match := range reSafeTag.FindAllStringIndex(stripped, -1) {
1124+
if !isEscapedAt(stripped, match[0]) {
1125+
return true
1126+
}
1127+
}
1128+
1129+
return false
1130+
}
1131+
1132+
func isEscapedAt(s string, pos int) bool {
1133+
backslashes := 0
1134+
for i := pos - 1; i >= 0 && s[i] == '\\'; i-- {
1135+
backslashes++
1136+
}
1137+
return backslashes%2 == 1
10111138
}
10121139

10131140
// ParsedAttachment holds metadata extracted from a <bc-attachment> tag in HTML content.

0 commit comments

Comments
 (0)