// Package contract resolves versioned contract templates into PDF previews. // It performs no source lookup or authorisation and does not issue agreements. // Callers must authorise and pin their inputs before invoking it. package contract import ( "fmt" "regexp" "strings" "unicode" "unicode/utf8" "github.com/carlosframework/docs/internal/export" "github.com/carlosframework/docs/internal/fonts" json "github.com/go-json-experiment/json" ) const ( Version = 1 // Limits bound decoding, recursive traversal and repeated-field expansion // while leaving room for a substantial contract, without attachments. MaxTemplateBytes = 1 << 20 MaxNodes = 10000 MaxDepth = 32 MaxFields = 128 MaxValueBytes = 64 << 10 MaxTextBytes = 1 << 20 // Titles and field labels are short display metadata, not contract bodies. MaxLabelBytes = 256 // The exporter reshapes a word when wrapping it; bounding each word // prevents a long identifier from causing quadratic shaping work. MaxWordBytes = 1024 // Rendering is more expensive than structural resolution. These caps // bound an interactive preview to an ordinary contract, not a book. MaxRenderTextBytes = 128 << 10 MaxPreviewPages = 100 ) type Kind string const ( Text Kind = "text" Date Kind = "date" Money Kind = "money" ) type Field struct { Key string `json:"key"` Label string `json:"label"` Kind Kind `json:"kind"` Optional bool `json:"optional,omitempty"` Currency string `json:"currency,omitempty"` } // Attrs deliberately names only attributes the contract renderer understands. // Key belongs only to merge_field; the others are the Docs export vocabulary. type Attrs struct { Level int `json:"level,omitempty"` Align string `json:"align,omitempty"` Indent int `json:"indent,omitempty"` Key string `json:"key,omitempty"` } // Node is a template node, not a change to the live editor/CRDT schema. type Node struct { Type string `json:"type"` Attrs Attrs `json:"attrs,omitempty"` Content []Node `json:"content,omitempty"` Text string `json:"text,omitempty"` Marks []export.Mark `json:"marks,omitempty"` } type Template struct { Version int `json:"version"` Title string `json:"title"` Fields []Field `json:"fields"` Root Node `json:"root"` } // Diagnostic contains only a stable code and structural coordinate. Labels, // text, raw parser errors and submitted values never enter an error string. type Diagnostic struct { Code string Path string } func (e *Diagnostic) Error() string { return "contract: " + e.Code + " at " + e.Path } func problem(code, path string) error { return &Diagnostic{Code: code, Path: path} } // Parse rejects duplicate/unknown JSON properties and invalid Unicode using // the same strict decoder already pinned by Docs. Validate also serves typed // callers, so decoding is not the only enforcement point. func Parse(data []byte) (Template, error) { if len(data) > MaxTemplateBytes { return Template{}, problem("template_too_large", "template") } var t Template if err := json.Unmarshal(data, &t, json.RejectUnknownMembers(true)); err != nil { return Template{}, problem("invalid_json", "template") } if err := t.Validate(); err != nil { return Template{}, err } return t, nil } var keyPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]{0,63}$`) func validText(s string, max int) bool { if len(s) > max || !utf8.ValidString(s) { return false } for _, r := range s { if (unicode.IsControl(r) && r != '\n' && r != '\t') || unicode.In(r, unicode.Cf) { return false } } return true } func wordTooLong(s string) bool { length := 0 for _, r := range s { if r == ' ' || r == '\n' || r == '\t' { length = 0 } else { length += utf8.RuneLen(r) } if length > MaxWordBytes { return true } } return false } func (t Template) Validate() error { if t.Version != Version { return problem("unsupported_version", "version") } if !validText(t.Title, MaxLabelBytes) || strings.ContainsAny(t.Title, "\n\t") { return problem("invalid_title", "title") } if len(t.Fields) > MaxFields { return problem("too_many_fields", "fields") } defs := make(map[string]Field, len(t.Fields)) for i, f := range t.Fields { path := fmt.Sprintf("fields[%d]", i) if !keyPattern.MatchString(f.Key) || !validText(f.Label, MaxLabelBytes) || strings.TrimSpace(f.Label) == "" { return problem("invalid_field", path) } if _, exists := defs[f.Key]; exists { return problem("duplicate_field", path) } switch f.Kind { case Text, Date: if f.Currency != "" { return problem("unexpected_currency", path) } case Money: if _, ok := currencyScale(f.Currency); !ok { return problem("invalid_currency", path) } default: return problem("unsupported_kind", path) } defs[f.Key] = f } v := validator{defs: defs, used: map[string]bool{}} if err := v.node(t.Root, "", "root", 0); err != nil { return err } for i, f := range t.Fields { if !v.used[f.Key] { return problem("unused_field", fmt.Sprintf("fields[%d]", i)) } } // Bound the encoded representation for typed callers too, after bounded // traversal has excluded extreme depth and cyclic slice-backed trees. b, err := json.Marshal(t) if err != nil || len(b) > MaxTemplateBytes { return problem("template_too_large", "template") } return nil } type validator struct { defs map[string]Field used map[string]bool nodes, bytes int } func isBlock(s string) bool { switch s { case "paragraph", "heading", "blockquote", "code_block", "bullet_list", "ordered_list": return true } return false } func childAllowed(parent, child string) bool { switch parent { case "": return child == "doc" case "doc", "blockquote", "list_item": return isBlock(child) case "bullet_list", "ordered_list": return child == "list_item" case "paragraph", "heading": return child == "text" || child == "hard_break" || child == "merge_field" case "code_block": return child == "text" } return false } func (v *validator) node(n Node, parent, path string, depth int) error { v.nodes++ if depth > MaxDepth || v.nodes > MaxNodes { return problem("tree_limit", path) } if !childAllowed(parent, n.Type) { return problem("unsupported_structure", path) } inline := n.Type == "text" || n.Type == "hard_break" || n.Type == "merge_field" if inline && len(n.Content) != 0 { return problem("unexpected_children", path) } if !inline && n.Type != "paragraph" && n.Type != "heading" && n.Type != "code_block" && len(n.Content) == 0 { return problem("missing_children", path) } if n.Type == "list_item" && n.Content[0].Type != "paragraph" { return problem("list_item_paragraph", path) } if n.Type != "text" && n.Text != "" { return problem("unexpected_text", path) } if !validText(n.Text, MaxTextBytes) { return problem("invalid_text", path) } if wordTooLong(n.Text) { return problem("word_limit", path) } v.bytes += len(n.Text) if v.bytes > MaxTextBytes { return problem("text_limit", path) } a := n.Attrs if n.Type == "heading" { if a.Level < 1 || a.Level > 6 { return problem("invalid_heading", path) } } else if a.Level != 0 { return problem("unexpected_level", path) } if a.Indent < 0 || a.Indent > export.MaxIndent || (a.Indent != 0 && n.Type != "paragraph" && n.Type != "heading") { return problem("invalid_indent", path) } if a.Align != "" && (n.Type != "paragraph" || (a.Align != "left" && a.Align != "center" && a.Align != "right")) { return problem("invalid_alignment", path) } if n.Type == "merge_field" { if _, ok := v.defs[a.Key]; !ok { return problem("unknown_field", path) } v.used[a.Key] = true } else if a.Key != "" { return problem("unexpected_key", path) } if !inline && len(n.Marks) != 0 { return problem("unexpected_marks", path) } if err := validateMarks(n.Marks, path); err != nil { return err } if parent == "code_block" && len(n.Marks) != 0 { return problem("unexpected_marks", path) } for i, child := range n.Content { if err := v.node(child, n.Type, fmt.Sprintf("%s.content[%d]", path, i), depth+1); err != nil { return err } } return nil } func validateMarks(marks []export.Mark, path string) error { groups := map[string]bool{} for _, m := range marks { group := m.Type switch { case m.Type == "strong" || m.Type == "em" || m.Type == "code": case strings.HasPrefix(m.Type, "font_"): if _, ok := fonts.ByKey(strings.TrimPrefix(m.Type, "font_")); !ok { return problem("unsupported_mark", path) } group = "font" case strings.HasPrefix(m.Type, "size_"): if _, ok := export.SizePt(m.Type); !ok { return problem("unsupported_mark", path) } group = "size" default: return problem("unsupported_mark", path) } if groups[group] { return problem("conflicting_marks", path) } groups[group] = true } // The exporter forces the code family even if a font mark is present. if groups["code"] && groups["font"] { return problem("conflicting_marks", path) } return nil }