carlos / platform Public

docsite: diagram and stepper fences, gated

Docs site Plan 2 Task 2. Two fence kinds the website renders as figures, with their SVGs in docs/site/diagrams/: ParseDiagramFence checks the format, CheckDiagrams checks every named SVG exists and is inert (no script, event handlers, javascript: links or foreign HTML), since the website inlines them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 65293043f14362eed4bdcd60690a15056303ac68 parent eb72053
3 files changed, +273 −0
  • internal/docsite/diagrams.go +171 −0
  • internal/docsite/diagrams_test.go +100 −0
  • internal/docsite/fences_test.go +2 −0
diff --git a/internal/docsite/diagrams.go b/internal/docsite/diagrams.go
new file mode 100644
index 000000000..365f9553f
--- /dev/null
+++ b/internal/docsite/diagrams.go
@@ -0,0 +1,171 @@
+package docsite
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+// Diagrams in the docs are fenced blocks the website renders as figures,
+// inlining each SVG from docs/site/diagrams/ so it takes the page's
+// colours. Two kinds:
+//
+// ```diagram
+// file: system-map.svg
+// The caption, one or more lines.
+// ```
+//
+// ```stepper
+// title: A request wakes a sleeping instance
+// frame: wake-1.svg
+// The first frame's caption.
+// frame: wake-2.svg
+// The second frame's caption.
+// ```
+//
+// A stepper reads as numbered figures without JavaScript and as one frame
+// at a time with it. The website parses the same format (the website's
+// hack/docs-markdown.mjs), so a change here changes there too.
+
+// Figure is one SVG and its caption.
+type Figure struct {
+ File string
+ Caption string
+}
+
+// Diagram is one diagram or stepper fence.
+type Diagram struct {
+ Page string
+ Line int
+ Kind string // "diagram" or "stepper"
+ Title string // steppers only
+ Frames []Figure
+}
+
+var diagramFile = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*\.svg$`)
+
+// activeSVG matches what an inlined SVG must never carry: script, event
+// handlers, javascript: URLs and foreign HTML.
+var activeSVG = regexp.MustCompile(`(?i)<script|\son[a-z]+\s*=|javascript:|<foreignobject`)
+
+// ParseDiagramFence parses the body of a diagram or stepper fence.
+func ParseDiagramFence(kind, body string) (Diagram, error) {
+ d := Diagram{Kind: kind}
+ lines := strings.Split(strings.TrimSpace(body), "\n")
+ var cur *Figure
+ var caption []string
+ flush := func() error {
+ if cur == nil {
+ return nil
+ }
+ cur.Caption = strings.Join(strings.Fields(strings.Join(caption, " ")), " ")
+ if cur.Caption == "" {
+ return fmt.Errorf("%s has no caption", cur.File)
+ }
+ d.Frames = append(d.Frames, *cur)
+ cur, caption = nil, nil
+ return nil
+ }
+ start := func(key, line string) error {
+ name := strings.TrimSpace(strings.TrimPrefix(line, key))
+ if !diagramFile.MatchString(name) {
+ return fmt.Errorf("%q is not a diagram file name (lower case letters, digits and hyphens, ending .svg)", name)
+ }
+ if err := flush(); err != nil {
+ return err
+ }
+ cur = &Figure{File: name}
+ return nil
+ }
+ switch kind {
+ case "diagram":
+ if len(lines) == 0 || !strings.HasPrefix(lines[0], "file:") {
+ return d, errors.New("a diagram fence starts with a file: line")
+ }
+ if err := start("file:", lines[0]); err != nil {
+ return d, err
+ }
+ caption = lines[1:]
+ if err := flush(); err != nil {
+ return d, err
+ }
+ case "stepper":
+ if len(lines) == 0 || !strings.HasPrefix(lines[0], "title:") {
+ return d, errors.New("a stepper fence starts with a title: line")
+ }
+ d.Title = strings.TrimSpace(strings.TrimPrefix(lines[0], "title:"))
+ if d.Title == "" {
+ return d, errors.New("the stepper's title is empty")
+ }
+ for _, line := range lines[1:] {
+ if strings.HasPrefix(line, "frame:") {
+ if err := start("frame:", line); err != nil {
+ return d, err
+ }
+ continue
+ }
+ if cur == nil {
+ if strings.TrimSpace(line) != "" {
+ return d, errors.New("text before the first frame: line")
+ }
+ continue
+ }
+ caption = append(caption, line)
+ }
+ if err := flush(); err != nil {
+ return d, err
+ }
+ if len(d.Frames) < 2 {
+ return d, fmt.Errorf("a stepper needs at least 2 frames, this one has %d", len(d.Frames))
+ }
+ default:
+ return d, fmt.Errorf("%q is not a diagram kind", kind)
+ }
+ return d, nil
+}
+
+// CheckDiagrams parses every diagram and stepper fence in the site and
+// checks each SVG it names exists under dir and is inert. Each problem
+// names the page and the fence's line. A missing dir is treated as empty.
+func CheckDiagrams(site *Site, dir string) []string {
+ var problems []string
+ checked := map[string]string{}
+ for _, p := range site.Pages() {
+ for _, f := range p.Fences {
+ if f.Lang != "diagram" && f.Lang != "stepper" {
+ continue
+ }
+ where := fmt.Sprintf("%s:%d", p.Slug, f.Line)
+ d, err := ParseDiagramFence(f.Lang, f.Body)
+ if err != nil {
+ problems = append(problems, fmt.Sprintf("%s: %v", where, err))
+ continue
+ }
+ for _, fr := range d.Frames {
+ verdict, seen := checked[fr.File]
+ if !seen {
+ verdict = checkSVG(filepath.Join(dir, fr.File))
+ checked[fr.File] = verdict
+ }
+ if verdict != "" {
+ problems = append(problems, fmt.Sprintf("%s: %s %s", where, fr.File, verdict))
+ }
+ }
+ }
+ }
+ return problems
+}
+
+func checkSVG(path string) string {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ return "does not exist in docs/site/diagrams"
+ }
+ if m := activeSVG.Find(raw); m != nil {
+ return fmt.Sprintf("carries %q, and an inlined SVG must hold no script, event handlers, javascript: links or foreign HTML", strings.TrimSpace(string(m)))
+ }
+ return ""
+}
diff --git a/internal/docsite/diagrams_test.go b/internal/docsite/diagrams_test.go
new file mode 100644
index 000000000..aa2f93bbc
--- /dev/null
+++ b/internal/docsite/diagrams_test.go
@@ -0,0 +1,100 @@
+package docsite
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestParseDiagramFence(t *testing.T) {
+ d, err := ParseDiagramFence("diagram", "file: system-map.svg\nOne console, one bucket\nand a fleet of boxes.")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if d.Kind != "diagram" || len(d.Frames) != 1 || d.Frames[0].File != "system-map.svg" || d.Frames[0].Caption != "One console, one bucket and a fleet of boxes." {
+ t.Errorf("diagram parsed as %+v", d)
+ }
+
+ s, err := ParseDiagramFence("stepper", "title: A request wakes an instance\nframe: wake-1.svg\nThe request arrives.\nframe: wake-2.svg\nThe edge holds it.\nframe: wake-3.svg\nThe instance answers.")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if s.Title != "A request wakes an instance" || len(s.Frames) != 3 || s.Frames[2].File != "wake-3.svg" || s.Frames[1].Caption != "The edge holds it." {
+ t.Errorf("stepper parsed as %+v", s)
+ }
+
+ refusals := map[string][2]string{
+ "no file line": {"diagram", "One console."},
+ "empty caption": {"diagram", "file: map.svg\n \n"},
+ "one frame": {"stepper", "title: T\nframe: a.svg\nOnly one."},
+ "no title": {"stepper", "frame: a.svg\nOne.\nframe: b.svg\nTwo."},
+ "empty frame": {"stepper", "title: T\nframe: a.svg\nframe: b.svg\nTwo."},
+ "path escape": {"diagram", "file: ../x.svg\nCaption."},
+ "upper case name": {"diagram", "file: X.SVG\nCaption."},
+ "not an svg": {"diagram", "file: map.png\nCaption."},
+ "unknown kind": {"chart", "file: map.svg\nCaption."},
+ "text before file": {"stepper", "title: T\nloose text\nframe: a.svg\nOne.\nframe: b.svg\nTwo."},
+ }
+ for name, c := range refusals {
+ if _, err := ParseDiagramFence(c[0], c[1]); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
+
+func diagramSite(t *testing.T, body string) *Site {
+ t.Helper()
+ p := Parse("guide", body)
+ return &Site{Sections: []Section{{Title: "Guides", Pages: []*Page{p}}}, BySlug: map[string]*Page{"guide": p}}
+}
+
+func TestCheckDiagramsFindsMissingFiles(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "here.svg"), []byte(`<svg xmlns="http://www.w3.org/2000/svg"></svg>`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ site := diagramSite(t, "# Guide\n\n```diagram\nfile: here.svg\nPresent.\n```\n\n```stepper\ntitle: T\nframe: here.svg\nOne.\nframe: gone.svg\nTwo.\n```\n")
+ problems := CheckDiagrams(site, dir)
+ if len(problems) != 1 || !strings.Contains(problems[0], "gone.svg") || !strings.Contains(problems[0], "guide") {
+ t.Errorf("problems = %q, want one naming guide and gone.svg", problems)
+ }
+}
+
+func TestCheckDiagramsReportsBadFences(t *testing.T) {
+ site := diagramSite(t, "# Guide\n\n```stepper\ntitle: T\nframe: a.svg\nOnly one.\n```\n")
+ problems := CheckDiagrams(site, t.TempDir())
+ if len(problems) != 1 || !strings.Contains(problems[0], "guide:3") {
+ t.Errorf("problems = %q, want one naming guide:3", problems)
+ }
+}
+
+func TestCheckDiagramsRefusesActiveSVG(t *testing.T) {
+ for name, svg := range map[string]string{
+ "script": `<svg><script>alert(1)</script></svg>`,
+ "onload": `<svg onload="alert(1)"></svg>`,
+ "onclick": `<svg><rect OnClick="x()"/></svg>`,
+ "javascript": `<svg><a href="javascript:alert(1)"><text>x</text></a></svg>`,
+ "foreign": `<svg><foreignObject><div>x</div></foreignObject></svg>`,
+ } {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "bad.svg"), []byte(svg), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ site := diagramSite(t, "# Guide\n\n```diagram\nfile: bad.svg\nCaption.\n```\n")
+ problems := CheckDiagrams(site, dir)
+ if len(problems) != 1 || !strings.Contains(problems[0], "bad.svg") {
+ t.Errorf("%s: problems = %q, want one naming bad.svg", name, problems)
+ }
+ }
+}
+
+func TestCheckDiagramsOnTheRealCorpus(t *testing.T) {
+ site, err := Load(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range CheckDiagrams(site, filepath.Join(root, "diagrams")) {
+ t.Error(p)
+ }
+}
diff --git a/internal/docsite/fences_test.go b/internal/docsite/fences_test.go
index 9424fc5dd..3795c5119 100644
--- a/internal/docsite/fences_test.go
+++ b/internal/docsite/fences_test.go
@@ -24,6 +24,8 @@ var knownFenceLangs = map[string]bool{
// word (rails_sample_test.go holds it to that), and the Laravel notes
// show the one line of config/database.php that differs.
"dockerfile": true, "ruby": true, "php": true,
+ // Rendered as figures by the website; gated by CheckDiagrams.
+ "diagram": true, "stepper": true,
}
func TestFenceLanguagesAreDeclared(t *testing.T) {