Files
pages/internal/kunstzeal/diagram.go
T
Anya Tokugawa d5d21b7841
Build and publish container images / images (push) Successful in 9m34s
Release container images / release (push) Successful in 36s
Refactor architecture into eight components and consolidate reliability work
Extract Grammaratur, Dregarnuhr, Geduldh, Mestionora, Ordoschnellic, Schutzaria, Kunstzeal and Seheweit behind compatible application contracts.

Include accumulated editor resilience, navigation and theme UX, remote CLI, storage/schema and DR groundwork, tests and design/operations documentation.

Verified: uncached full Go suite; go vet ./...; race tests for all eight components; 11 targeted Chromium tests; Node suites; 19 Python CLI tests; reproducible editor build. No push, release tag or deployment in this checkpoint.
2026-11-01 15:23:31 +09:00

117 lines
3.3 KiB
Go

package kunstzeal
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const Component = "kunstzeal"
const DiagramSourceLimit = 1 << 20
const DiagramOutputLimit = 4 << 20
const DiagramInlineLimit = 32 << 10
const DiagramTimeout = 15 * time.Second
var (
ErrDiagramKind = errors.New("unsupported diagram type")
ErrDiagramSource = errors.New("diagram source exceeds limit")
ErrDiagramOutput = errors.New("diagram output unavailable or exceeds limit")
ErrProviderConfig = errors.New("diagram renderer configuration invalid")
ErrProviderUnavailable = errors.New("diagram renderer unavailable")
ErrProviderFailed = errors.New("diagram renderer failed")
)
// DiagramProvider does not authorize a request or trust its SVG output.
// Callers must retain source access checks and the sandbox response policy.
type DiagramProvider interface {
Render(context.Context, string, string) ([]byte, error)
}
func DiagramHash(kind, source, format string) string {
sum := sha256.Sum256([]byte(kind + "\x00" + format + "\x00" + source))
return hex.EncodeToString(sum[:])
}
func AllowedDiagramType(kind string) bool {
switch kind {
case "mermaid", "plantuml", "graphviz", "dot", "d2":
return true
}
return false
}
func NormalizeDiagramType(kind string) string {
if kind == "dot" {
return "graphviz"
}
return kind
}
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
// Kroki receives an administrator-configured service address, never a URL from
// document content. Private service-network endpoints are intentional here.
// Client must honor context cancellation and reject redirects. No default
// client is used, and provider failures never expose its URL or response body.
type Kroki struct {
Endpoint string
Client HTTPClient
}
func (k Kroki) Render(parent context.Context, kind, source string) ([]byte, error) {
if err := parent.Err(); err != nil {
return nil, err
}
kind = NormalizeDiagramType(kind)
if !AllowedDiagramType(kind) {
return nil, ErrDiagramKind
}
if len(source) > DiagramSourceLimit {
return nil, ErrDiagramSource
}
u, err := url.Parse(k.Endpoint)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || k.Client == nil {
return nil, ErrProviderConfig
}
ctx, cancel := context.WithTimeout(parent, DiagramTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(k.Endpoint, "/")+"/"+kind+"/svg", strings.NewReader(source))
if err != nil {
return nil, ErrProviderConfig
}
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
resp, err := k.Client.Do(req)
if err != nil {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, ErrProviderUnavailable
}
if resp == nil || resp.Body == nil {
return nil, ErrProviderUnavailable
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, ErrProviderFailed
}
b, err := io.ReadAll(io.LimitReader(resp.Body, DiagramOutputLimit+1))
if ctx.Err() != nil {
return nil, ctx.Err()
}
if err != nil || len(b) > DiagramOutputLimit {
return nil, ErrDiagramOutput
}
return b, nil
}