package server import ( "bytes" "crypto/sha256" "encoding/hex" "errors" "io" "net/http" "os" "path/filepath" "regexp" "strings" "sync" "time" ) var diagramSourceCache = map[string]diagramCacheEntry{} var diagramSourceMu sync.Mutex type diagramCacheEntry struct { Type string Source string At time.Time Domain string Path string } func (s *Server) diagramCachePath(kind, hash string) string { root := s.diagramRoot if root == "" { root = "/data/cache/diagram" } return filepath.Join(root, kind, hash+".svg") } func readDiagramCache(path string) ([]byte, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() b, err := io.ReadAll(io.LimitReader(f, (4<<20)+1)) if len(b) > 4<<20 { return nil, errors.New("diagram cache exceeds limit") } return b, err } func diagramHash( diagramType string, source string, format string, ) string { sum := sha256.Sum256( []byte( diagramType + "\x00" + format + "\x00" + source, ), ) return hex.EncodeToString( sum[:], ) } func allowedDiagramType( t string, ) bool { switch t { case "mermaid", "plantuml", "graphviz", "dot", "d2": return true default: return false } } func normalizeDiagramType( t string, ) string { switch t { case "dot": return "graphviz" default: return t } } func krokiURL() string { v := strings.TrimSpace( os.Getenv("KROKI_URL"), ) if v == "" { return "http://kroki:8000" } return strings.TrimRight( v, "/", ) } func (s *Server) renderDiagramsInHTML( r *http.Request, path string, html string, ) string { re := regexp.MustCompile(`(?s)
(.+?)
`) return re.ReplaceAllStringFunc( html, func(block string) string { m := re.FindStringSubmatch( block, ) if len(m) != 3 { return block } diagramType := normalizeDiagramType( m[1], ) source := htmlUnescapeString( m[2], ) if len(source) > 32<<10 || path == "" { return block } hash := diagramHash( diagramType, htmlProjectionVersion+"\x00"+s.domainUUIDForRequest(r)+"\x00"+path+"\x00"+source, "svg", ) diagramSourceMu.Lock() if len(diagramSourceCache) >= 128 { oldest, key := time.Now(), "" for k, v := range diagramSourceCache { if v.At.Before(oldest) { oldest, key = v.At, k } } delete(diagramSourceCache, key) } diagramSourceCache[hash] = diagramCacheEntry{ Type: diagramType, Source: source, At: time.Now(), Domain: s.domainUUIDForRequest(r), Path: path, } diagramSourceMu.Unlock() return `
` + `` + diagramType + ` diagram` + `
` }, ) } func htmlUnescapeString( s string, ) string { r := strings.NewReplacer( "<", "<", ">", ">", "&", "&", """, `"`, "'", "'", ) return r.Replace( s, ) } func (s *Server) handleCompileDiagram( w http.ResponseWriter, r *http.Request, ) { // Apply also to disk-cache hits and direct navigation, not only new renders. w.Header().Set("Content-Security-Policy", "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:") w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Cache-Control", "private, no-store") if r.Method == http.MethodPost { s.handleCompileDiagramPost( w, r, ) return } rest := strings.TrimPrefix( r.URL.Path, "/:/compile/diagram/", ) parts := strings.Split( rest, "/", ) if len(parts) != 2 { http.NotFound(w, r) return } diagramType := normalizeDiagramType( parts[0], ) if !allowedDiagramType(diagramType) { http.NotFound(w, r) return } hashFile := parts[1] if !strings.HasSuffix(hashFile, ".svg") { http.NotFound(w, r) return } hash := strings.TrimSuffix( hashFile, ".svg", ) if !regexp.MustCompile(`^[a-f0-9]{64}$`).MatchString(hash) { http.NotFound(w, r) return } cachePath := s.diagramCachePath(diagramType, hash) diagramSourceMu.Lock() entry, ok := diagramSourceCache[hash] diagramSourceMu.Unlock() if !ok || entry.Type != diagramType || entry.Domain != s.domainUUIDForRequest(r) || time.Since(entry.At) > 30*time.Minute || !s.pathReadFilter(r)(entry.Path) { http.NotFound(w, r) return } if b, err := readDiagramCache(cachePath); err == nil { w.Header().Set( "Content-Type", "image/svg+xml; charset=utf-8", ) _, _ = w.Write(b) return } s.renderDiagramSVG( w, r, diagramType, entry.Source, cachePath, ) } func (s *Server) handleCompileDiagramPost( w http.ResponseWriter, r *http.Request, ) { rest := strings.TrimPrefix( r.URL.Path, "/:/compile/diagram/", ) diagramType := normalizeDiagramType( strings.Trim(rest, "/"), ) if !allowedDiagramType(diagramType) { http.NotFound(w, r) return } defer r.Body.Close() sourceBytes, err := io.ReadAll( io.LimitReader( r.Body, (1<<20)+1, ), ) if err != nil || len(sourceBytes) > 1<<20 { http.Error(w, "diagram source exceeds limit", http.StatusRequestEntityTooLarge) return } source := string(sourceBytes) hash := diagramHash( diagramType, source, "svg", ) cachePath := s.diagramCachePath(diagramType, hash) if b, err := readDiagramCache(cachePath); err == nil { w.Header().Set( "Content-Type", "image/svg+xml; charset=utf-8", ) _, _ = w.Write(b) return } s.renderDiagramSVG( w, r, diagramType, source, cachePath, ) } func (s *Server) renderDiagramSVG( w http.ResponseWriter, r *http.Request, diagramType string, source string, cachePath string, ) { req, err := http.NewRequestWithContext( r.Context(), http.MethodPost, krokiURL()+"/"+diagramType+"/svg", bytes.NewBufferString(source), ) if err != nil { http.Error(w, err.Error(), 500) return } req.Header.Set( "Content-Type", "text/plain; charset=utf-8", ) client := http.Client{ Timeout: 15 * time.Second, } resp, err := client.Do( req, ) if err != nil { http.Error(w, err.Error(), 502) return } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { http.Error(w, "diagram renderer failed", 502) return } b, err := io.ReadAll( io.LimitReader(resp.Body, (4<<20)+1), ) if err != nil || len(b) > 4<<20 { http.Error(w, "diagram output unavailable or exceeds limit", http.StatusBadGateway) return } _ = os.MkdirAll( filepath.Dir(cachePath), 0755, ) _ = os.WriteFile( cachePath, b, 0644, ) w.Header().Set( "Content-Type", "image/svg+xml; charset=utf-8", ) w.Header().Set( "Content-Security-Policy", "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:", ) _, _ = w.Write( b, ) }