Playground
foreign.gno
// Package foreign provides the realm-side helper for emitting the
// gno-foreign sandbox block. Realm authors wrap externally-built
// markdown (markdown returned by an interface method on a foreign
// realm, fetched from chain storage owned by another realm, etc.) in
// Foreign before flowing it into rendered output, so gnoweb renders
// the body inside its own goldmark sub-instance with structural
// extensions selectively loaded.
//
// The renderer-side contract lives in
// gno.land/pkg/gnoweb/markdown/ext_foreign.go. This helper produces
// bytes that satisfy the parser's opener requirements (CommonMark
// §4.6 Type-7 HTML block, no attribute fall-through) and neutralizes
// any literal sentinel lines in the body so the foreign markdown
// cannot terminate the outer block prematurely.
package foreign
import (
"chain/markdown"
"strings"
)
// Foreign wraps body in a `<gno-foreign>` ... `</gno-foreign>` sandbox
// block. The returned string is ready to concatenate into a larger
// markdown document.
//
// Three normalization steps apply to body:
//
// 1. \r\n and bare \r line endings are normalized to \n. The parser
// uses byte-equal matching against the sentinel close tag, so
// mixed line endings would otherwise change the match boundary.
//
// 2. Any line whose trimmed content looks like a gno-foreign tag
// opener OR closer — bare (`<gno-foreign>`, `</gno-foreign>`) or
// attribute-bearing (`<gno-foreign label="x">`, `</gno-foreign
// attr="…">`, etc.) — is neutralized by HTML-escaping the leading
// `<` to `<`. The parser tokenizes line bytes literally, so the
// escaped form is seen as text and cannot terminate the outer
// block or open an unintended inner block.
//
// Crucially, BOTH open-tag and close-tag attribute-bearing forms
// are neutralized. The parser recognizes a bare `<gno-foreign>`
// opener, a labeled `<gno-foreign label="x">` opener, and ANY
// `</gno-foreign…>` closer (golang.org/x/net/html drops attrs on
// end tags before our recognizer sees them, so attr-bearing
// closers are sentinel-equivalent). Leaving any of those forms
// un-neutralized in body bytes would let attacker-supplied
// markdown adjust the parser's framing-depth counter and either
// consume the helper's own close (capturing trailing realm
// content into the sandbox) or close the outer block early
// (escaping the sandbox entirely).
//
// There is therefore NO nesting via the helper: Foreign(Foreign(x))
// escapes the inner call's own `<gno-foreign>`/`</gno-foreign>`
// lines, so the inner block renders as visible literal text inside
// one sandbox, not as a nested sandbox. This is intended — wrapping
// foreign-built markdown that itself contains gno-foreign sentinels
// must neutralize them, not honor them.
//
// 3. A leading and trailing blank line are emitted around the
// opener / closer. CommonMark §4.6 forbids Type-7 HTML blocks
// from interrupting a paragraph; without the blank line, an
// opener following a non-blank line is absorbed into the
// preceding paragraph instead of opening a sandbox.
//
// The renderer caps cross-family nesting at 4 levels and per-Convert
// foreign blocks at 256. Beyond those caps, the opener falls through
// to raw HTML and is stripped by the renderer's safe mode.
func Foreign(body string) string {
return wrapForeign("", body)
}
// ForeignWithLabel wraps body like Foreign but emits an explicit
// `label="…"` attribute on the opener so the rendered sandbox carries
// a caller-supplied label (e.g., "Pulled from /r/foo") shown as a
// strip above the body. The label is sanitized so it cannot inject
// HTML or break out of the attribute value:
//
// - NUL bytes are dropped.
// - Other control characters (U+0000–U+001F, U+007F) become spaces.
// - `&`, `<`, `>`, and `"` are replaced with their HTML entities.
// - Leading/trailing whitespace is trimmed.
//
// A label that is empty after sanitization behaves identically to
// Foreign: no attribute is emitted, and the renderer shows the sandbox
// box with NO label strip (there is no default label text).
func ForeignWithLabel(label, body string) string {
return wrapForeign(label, body)
}
// MaxBlocksPerRender is gnoweb's per-render cap on the number of
// <gno-foreign> blocks a single page render admits; beyond it, later
// blocks fall through to raw HTML and are dropped. A realm emitting
// many foreign blocks (e.g. one per comment) should keep its rendered
// total under this. Re-exports chain/markdown.MaxForeignBlocksPerConvert
// — the single source of truth the gnoweb renderer also reads — so
// callers get the cap without importing chain/markdown directly.
func MaxBlocksPerRender() int {
return markdown.MaxForeignBlocksPerConvert()
}
func wrapForeign(rawLabel, body string) string {
label := sanitizeLabel(rawLabel)
// Normalize line endings (CR/CRLF → LF). The parser matches the
// sentinel close against \n-delimited lines, so mixed line endings
// would otherwise shift the match boundary. CR/CRLF → LF ONLY: do
// not fold Unicode separators here — they must stay verbatim in the
// body so the inner renderer sees the foreign markdown unaltered.
body = markdown.NormalizeBreaks(body)
// Mangle any line that would terminate the outer block or open
// an inner one. Covers bare and attribute-bearing forms of both
// the opener and the closer (see step 2 in the package doc).
var b strings.Builder
// b accumulates only the body lines (the opener/closer envelope is
// concatenated separately below), so len(body) is the exact size in
// the common case. Sentinel lines that expand `<`→`<` may force
// one growth — rare enough not to pre-size for.
b.Grow(len(body))
lines := strings.Split(body, "\n")
for i, line := range lines {
if isForeignSentinelLine(trimSentinel(line)) {
// Escape just the leading `<` so the html tokenizer
// sees this as text instead of a tag. Preserve any 0-3
// leading spaces the parser's trim would have stripped.
idx := strings.Index(line, "<")
if idx >= 0 {
line = line[:idx] + "<" + line[idx+1:]
}
}
b.WriteString(line)
if i < len(lines)-1 {
b.WriteByte('\n')
}
}
opener := "<gno-foreign>"
if label != "" {
opener = `<gno-foreign label="` + label + `">`
}
return "\n\n" + opener + "\n" + b.String() + "\n</gno-foreign>\n\n"
}
// sanitizeLabel makes a user-supplied label safe to splice into an
// HTML attribute value on the gno-foreign opener line.
func sanitizeLabel(s string) string {
// Strip bidi-override and zero-width controls FIRST — same ordering
// as the sanitize package's HTMLEscape — so invisible reordering or
// zero-width payloads can't survive into the rendered label.
s = markdown.StripBidiAndZeroWidth(s)
// Drop NUL; map other ASCII controls AND the Unicode line/paragraph
// separators (U+2028, U+2029, U+0085 NEL) to spaces. The opener is a
// single line, so any of these surviving in the label would either
// add a control payload or, for the separators, render as a stray
// line break inside the attribute.
s = strings.Map(func(r rune) rune {
if r == 0 {
return -1
}
if r < 0x20 || r == 0x7f || r == 0x2028 || r == 0x2029 || r == 0x0085 {
return ' '
}
return r
}, s)
// Escape `&` first so subsequent entity bytes don't get
// re-escaped.
s = strings.ReplaceAll(s, "&", "&")
s = strings.ReplaceAll(s, `"`, """)
s = strings.ReplaceAll(s, "<", "<")
s = strings.ReplaceAll(s, ">", ">")
return strings.TrimSpace(s)
}
// isForeignSentinelLine reports whether s (already trimmed via
// trimSentinel) begins with the gno-foreign tag prefix and so must be
// neutralized before it can reach the renderer-side parser.
//
// Deliberately OVER-INCLUSIVE: it matches any line whose trimmed form
// starts (case-INSENSITIVELY) with `<gno-foreign` or `</gno-foreign`,
// regardless of what follows. This is a strict superset of every line
// goldmark's html.Tokenizer can recognize as a <gno-foreign> opener or
// closer, which is what makes it safe:
//
// - The tokenizer lowercases tag names, so `<GNO-FOREIGN>` etc. are
// sentinels; the prefix match is case-folded to mirror that.
// - The tokenizer ends a tag name at ANY of several terminators
// (`>`, space, tab, form-feed, `/`). A precise check that
// enumerates terminators keeps missing variants — e.g.
// `</gno-foreign/>` and `</gno-foreign\f>` are both recognized as
// closers by the parser. Matching on the prefix alone cannot miss
// one: if a body line could be parsed as a sentinel, it starts with
// this prefix and is escaped here.
//
// The only cost is that an unrelated longer tag like `<gno-foreignx>`
// (a different tag name, not a sentinel) is also escaped — rendered as
// visible literal text instead of being raw-HTML-stripped — which is
// harmless for foreign body bytes.
func isForeignSentinelLine(s string) bool {
return hasASCIIFoldPrefix(s, "</gno-foreign") || hasASCIIFoldPrefix(s, "<gno-foreign")
}
// hasASCIIFoldPrefix reports whether s begins with prefix, comparing
// ASCII letters case-insensitively. prefix must be lowercase ASCII;
// folding is ASCII-only on purpose (Unicode case folding would
// over-match, and the sentinel envelope is pure ASCII anyway).
func hasASCIIFoldPrefix(s, prefix string) bool {
if len(s) < len(prefix) {
return false
}
for i := 0; i < len(prefix); i++ {
c := s[i]
if c >= 'A' && c <= 'Z' {
c += 'a' - 'A'
}
if c != prefix[i] {
return false
}
}
return true
}
// trimSentinel returns line with the leading 0-3 spaces and trailing
// ASCII whitespace that the parser's trimForeignLine strips. Mirrors
// the byte-level trim the parser performs so this helper detects the
// same sentinel match the parser would.
func trimSentinel(s string) string {
i := 0
for i < len(s) && i < 3 && s[i] == ' ' {
i++
}
s = s[i:]
for len(s) > 0 {
c := s[len(s)-1]
if c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r' {
s = s[:len(s)-1]
continue
}
break
}
return s
}
foreign_test.gno
package foreign
import (
"strings"
"testing"
)
func TestForeign_BasicWrap(t *testing.T) {
got := Foreign("hello")
want := "\n\n<gno-foreign>\nhello\n</gno-foreign>\n\n"
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestForeign_LeadingTrailingBlankLines(t *testing.T) {
// Parser requires a blank line before the opener (CM §4.6). Verify
// the helper emits exactly that.
got := Foreign("body")
if !strings.HasPrefix(got, "\n\n<gno-foreign>\n") {
t.Errorf("missing blank line before opener: %q", got)
}
if !strings.HasSuffix(got, "\n</gno-foreign>\n\n") {
t.Errorf("missing blank line after closer: %q", got)
}
}
func TestForeign_NormalizesCRLF(t *testing.T) {
got := Foreign("line1\r\nline2\r\nline3")
if strings.Contains(got, "\r") {
t.Errorf("CRLF not normalized: %q", got)
}
if !strings.Contains(got, "line1\nline2\nline3") {
t.Errorf("body content lost: %q", got)
}
}
func TestForeign_NormalizesBareCR(t *testing.T) {
got := Foreign("line1\rline2")
if strings.Contains(got, "\r") {
t.Errorf("bare CR not normalized: %q", got)
}
if !strings.Contains(got, "line1\nline2") {
t.Errorf("body content lost: %q", got)
}
}
func TestForeign_EscapesSentinelClose(t *testing.T) {
// Unbalanced </gno-foreign> in body would terminate the outer
// block early. Verify it's escaped to literal text — only the
// leading "<" is replaced with "<"; the trailing ">" stays
// literal (rendering as visible ">" in HTML).
got := Foreign("foo\n</gno-foreign>\nbar")
if strings.Contains(got, "\n</gno-foreign>\nbar") {
t.Errorf("unbalanced close not escaped: %q", got)
}
if !strings.Contains(got, "</gno-foreign>") {
t.Errorf("expected escaped close: %q", got)
}
}
func TestForeign_EscapesSentinelOpen(t *testing.T) {
// A bare opener inside body (without matching close in body)
// would be picked up as a nested inner foreign. Escape it.
got := Foreign("foo\n<gno-foreign>\nbar")
if !strings.Contains(got, "\n<gno-foreign>\n") {
t.Errorf("expected escaped inner opener: %q", got)
}
}
func TestForeign_EscapesIndentedSentinel(t *testing.T) {
// Parser strips 0-3 leading spaces before matching; helper
// must mirror that to catch indented sentinels.
got := Foreign("foo\n </gno-foreign>\nbar")
if !strings.Contains(got, "</gno-foreign>") {
t.Errorf("indented sentinel not escaped: %q", got)
}
}
func TestForeign_EscapesAttributeBearingOpener(t *testing.T) {
// `<gno-foreign label="x">` IS recognized by the parser as a
// nested opener. If left unmangled, the parser bumps framingDepth
// when it sees this line in body bytes, and then consumes the
// helper's own outer-close as a fake "inner close" — capturing
// realm content that follows the helper's output INTO the
// sandbox. Verify the helper escapes the leading "<".
got := Foreign(`<gno-foreign label="x">`)
if strings.Contains(got, `<gno-foreign label="x">`) {
t.Errorf("attribute-bearing opener was NOT mangled — escape vector:\n%q", got)
}
if !strings.Contains(got, `<gno-foreign label="x">`) {
t.Errorf("expected leading '<' escaped: %q", got)
}
}
func TestForeign_EscapesAttributeBearingCloser(t *testing.T) {
// golang.org/x/net/html zeroes the Attr slice on end tags, so the
// parser recognizes ANY `</gno-foreign attr…>` form as a sentinel
// close. Leaving such a line unmangled in body bytes would close
// the outer block early (framingDepth=0 case in the parser's
// Continue), letting body content that follows render OUTSIDE
// the sandbox at top level. Verify the helper escapes it.
got := Foreign(`</gno-foreign label="x">`)
if strings.Contains(got, `> </gno-foreign label="x"> </gno-foreign>`) {
t.Errorf("attribute-bearing closer was NOT mangled — escape vector:\n%q", got)
}
if !strings.Contains(got, `</gno-foreign label="x">`) {
t.Errorf("expected leading '<' escaped: %q", got)
}
}
func TestForeign_EscapesGnoForeignWithExtraContent(t *testing.T) {
// `<gno-foreign> extra` would not be recognized as a sentinel by
// the parser (tokenizer yields 2 tokens). But the helper is
// over-inclusive on purpose: anything that looks like a
// gno-foreign tag opener or closer gets mangled. Predictable
// behavior beats narrow matching that diverges from the parser
// on attribute-bearing forms.
got := Foreign("<gno-foreign> extra text")
if !strings.Contains(got, "<gno-foreign> extra text") {
t.Errorf("expected over-inclusive mangle of `<gno-foreign> extra`: %q", got)
}
}
func TestForeign_EscapesCaseVariantClose(t *testing.T) {
// The renderer-side parser recognizes tags case-insensitively
// (goldmark's tokenizer lowercases tag names). A case-variant close
// left unescaped would terminate the outer block early and let
// trailing body render OUTSIDE the sandbox. The helper must escape
// `</GNO-FOREIGN>` just like `</gno-foreign>`.
got := Foreign("foo\n</GNO-FOREIGN>\nbar")
if strings.Contains(got, "\n</GNO-FOREIGN>\nbar") {
t.Errorf("case-variant close not escaped — sandbox-escape vector: %q", got)
}
if !strings.Contains(got, "</GNO-FOREIGN>") {
t.Errorf("expected escaped case-variant close: %q", got)
}
}
func TestForeign_EscapesCaseVariantOpen(t *testing.T) {
// A case-variant opener left unescaped would be picked up by the
// parser as a nested inner foreign (framingDepth++), causing the
// helper's own outer-close to be consumed as a fake inner close and
// capturing trailing realm content into the sandbox.
got := Foreign("foo\n<GNO-FOREIGN>\nbar")
if !strings.Contains(got, "\n<GNO-FOREIGN>\n") {
t.Errorf("case-variant opener not escaped — capture vector: %q", got)
}
}
func TestForeign_EscapesMixedCaseSentinel(t *testing.T) {
// Mixed-case forms (the most likely hand-crafted evasion) must also
// be caught, including the attribute-bearing mixed-case opener.
for _, in := range []string{
"<Gno-Foreign>",
"</Gno-Foreign>",
`<GNO-foreign label="x">`,
"</gNo-fOrEiGn>",
} {
got := Foreign(in)
if !strings.Contains(got, "<") {
t.Errorf("mixed-case sentinel %q not escaped: %q", in, got)
}
}
}
func TestForeignWithLabel_StripsBidiAndZeroWidth(t *testing.T) {
// A bidi-override (U+202E) or zero-width (U+200C) run in the label
// is invisible-spoof payload; it must be stripped before the label
// is spliced into the opener attribute.
got := ForeignWithLabel("a\u202eb\u200cc", "body")
if !strings.Contains(got, `label="abc"`) {
t.Errorf("expected bidi/zero-width-stripped label: %q", got)
}
}
func TestForeignWithLabel_UnicodeSeparatorsBecomeSpaces(t *testing.T) {
// U+2028 / U+2029 / U+0085 must not survive in the single-line
// opener attribute; they fold to spaces like ASCII line breaks.
got := ForeignWithLabel("a\u2028b\u2029c\u0085d", "body")
if !strings.Contains(got, `label="a b c d"`) {
t.Errorf("expected space-folded label: %q", got)
}
}
func TestForeign_EscapesUnrelatedForeignPrefix(t *testing.T) {
// `<gno-foreignx>` is a different tag the parser would NOT treat as
// a sentinel, but the escaper is deliberately over-inclusive (it
// matches the `<gno-foreign` prefix alone), so it is escaped to
// visible literal text. Harmless, and the safe side of the trade.
got := Foreign("<gno-foreignx>")
if !strings.Contains(got, "<gno-foreignx>") {
t.Errorf("expected over-inclusive escape of <gno-foreignx>: %q", got)
}
}
func TestForeign_EscapesSlashAndFormFeedClosers(t *testing.T) {
// REGRESSION: goldmark's tokenizer ends a tag name at `/` and at
// form-feed (both HTML tag-name terminators), so `</gno-foreign/>`
// and `</gno-foreign\f>` are recognized as CLOSERS by the parser. A
// body line carrying one of these, if it reached the parser
// unescaped, would close the outer block early — a sandbox escape.
// The over-inclusive escaper must neutralize every such variant.
for _, in := range []string{
"foo\n</gno-foreign/>\nbar",
"foo\n</gno-foreign/ >\nbar",
"foo\n</gno-foreign\f>\nbar",
"foo\n<gno-foreign/>\nbar",
} {
got := Foreign(in)
if !strings.Contains(got, "<") {
t.Errorf("variant not escaped (sandbox-escape vector): %q -> %q", in, got)
}
}
}
func TestForeign_EmptyBody(t *testing.T) {
got := Foreign("")
want := "\n\n<gno-foreign>\n\n</gno-foreign>\n\n"
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestForeign_PreservesInternalBlankLines(t *testing.T) {
got := Foreign("para1\n\npara2")
if !strings.Contains(got, "para1\n\npara2") {
t.Errorf("internal blank line lost: %q", got)
}
}
func TestForeignWithLabel_BasicWrap(t *testing.T) {
got := ForeignWithLabel("My Label", "body")
want := "\n\n<gno-foreign label=\"My Label\">\nbody\n</gno-foreign>\n\n"
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestForeignWithLabel_EmptyLabelFallsBack(t *testing.T) {
// An empty label (or one that becomes empty after sanitization)
// should be identical to Foreign — no attribute on the opener.
got := ForeignWithLabel("", "body")
if strings.Contains(got, "label=") {
t.Errorf("empty label should not emit attribute: %q", got)
}
if got != Foreign("body") {
t.Errorf("empty label should match Foreign: got %q vs %q", got, Foreign("body"))
}
}
func TestForeignWithLabel_WhitespaceOnlyLabelFallsBack(t *testing.T) {
got := ForeignWithLabel(" ", "body")
if strings.Contains(got, "label=") {
t.Errorf("whitespace label should not emit attribute: %q", got)
}
}
func TestForeignWithLabel_EscapesAmpAndQuote(t *testing.T) {
got := ForeignWithLabel(`Tom & "Jerry"`, "body")
if !strings.Contains(got, `label="Tom & "Jerry""`) {
t.Errorf("expected & and \" escaped: %q", got)
}
}
func TestForeignWithLabel_EscapesAngleBrackets(t *testing.T) {
// An unescaped `>` would close the opener tag early. Must be
// escaped.
got := ForeignWithLabel(`a<b>c`, "body")
if !strings.Contains(got, `label="a<b>c"`) {
t.Errorf("expected < and > escaped: %q", got)
}
}
func TestForeignWithLabel_StripsNUL(t *testing.T) {
got := ForeignWithLabel("a\x00b\x00c", "body")
if strings.Contains(got, "\x00") {
t.Errorf("NUL not stripped: %q", got)
}
if !strings.Contains(got, `label="abc"`) {
t.Errorf("expected NUL-stripped label: %q", got)
}
}
func TestForeignWithLabel_ControlCharsBecomeSpaces(t *testing.T) {
// Newlines and tabs would break the single-line opener required
// by the parser. They must become spaces.
got := ForeignWithLabel("line1\nline2\ttab", "body")
if strings.Contains(got, "\nline2") || strings.Contains(got, "\t") {
t.Errorf("control chars not converted: %q", got)
}
if !strings.Contains(got, "line1 line2 tab") {
t.Errorf("expected space-separated label: %q", got)
}
}
func TestForeignWithLabel_TrimsLeadingTrailingSpace(t *testing.T) {
got := ForeignWithLabel(" hello ", "body")
if !strings.Contains(got, `label="hello"`) {
t.Errorf("expected trimmed label: %q", got)
}
}
func TestForeignWithLabel_PreservesBodyNormalization(t *testing.T) {
// Body normalization (CRLF, sentinel escaping) must still apply
// in the labeled variant.
got := ForeignWithLabel("L", "a\r\n</gno-foreign>\r\nb")
if strings.Contains(got, "\r") {
t.Errorf("CRLF not normalized in labeled variant: %q", got)
}
if !strings.Contains(got, "</gno-foreign>") {
t.Errorf("sentinel not escaped in labeled variant: %q", got)
}
}
func TestMaxBlocksPerRender(t *testing.T) {
// Surfaces gnoweb's per-render foreign-block cap to realms via the
// chain/markdown native. Pin the contract value; bump here if the
// renderer cap changes.
if got := MaxBlocksPerRender(); got != 256 {
t.Errorf("MaxBlocksPerRender() = %d, want 256", got)
}
}
gnomod.toml
module = "gno.land/p/nt/markdown/foreign/v0" gno = "0.9" [addpkg] creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"