| 1 | // Package contract resolves versioned contract templates into PDF previews. |
| 2 | // It performs no source lookup or authorisation and does not issue agreements. |
| 3 | // Callers must authorise and pin their inputs before invoking it. |
| 4 | package contract |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "regexp" |
| 9 | "strings" |
| 10 | "unicode" |
| 11 | "unicode/utf8" |
| 12 | |
| 13 | "github.com/carlosframework/docs/internal/export" |
| 14 | "github.com/carlosframework/docs/internal/fonts" |
| 15 | json "github.com/go-json-experiment/json" |
| 16 | ) |
| 17 | |
| 18 | const ( |
| 19 | Version = 1 |
| 20 | // Limits bound decoding, recursive traversal and repeated-field expansion |
| 21 | // while leaving room for a substantial contract, without attachments. |
| 22 | MaxTemplateBytes = 1 << 20 |
| 23 | MaxNodes = 10000 |
| 24 | MaxDepth = 32 |
| 25 | MaxFields = 128 |
| 26 | MaxValueBytes = 64 << 10 |
| 27 | MaxTextBytes = 1 << 20 |
| 28 | // Titles and field labels are short display metadata, not contract bodies. |
| 29 | MaxLabelBytes = 256 |
| 30 | // The exporter reshapes a word when wrapping it; bounding each word |
| 31 | // prevents a long identifier from causing quadratic shaping work. |
| 32 | MaxWordBytes = 1024 |
| 33 | // Rendering is more expensive than structural resolution. These caps |
| 34 | // bound an interactive preview to an ordinary contract, not a book. |
| 35 | MaxRenderTextBytes = 128 << 10 |
| 36 | MaxPreviewPages = 100 |
| 37 | ) |
| 38 | |
| 39 | type Kind string |
| 40 | |
| 41 | const ( |
| 42 | Text Kind = "text" |
| 43 | Date Kind = "date" |
| 44 | Money Kind = "money" |
| 45 | ) |
| 46 | |
| 47 | type Field struct { |
| 48 | Key string `json:"key"` |
| 49 | Label string `json:"label"` |
| 50 | Kind Kind `json:"kind"` |
| 51 | Optional bool `json:"optional,omitempty"` |
| 52 | Currency string `json:"currency,omitempty"` |
| 53 | } |
| 54 | |
| 55 | // Attrs deliberately names only attributes the contract renderer understands. |
| 56 | // Key belongs only to merge_field; the others are the Docs export vocabulary. |
| 57 | type Attrs struct { |
| 58 | Level int `json:"level,omitempty"` |
| 59 | Align string `json:"align,omitempty"` |
| 60 | Indent int `json:"indent,omitempty"` |
| 61 | Key string `json:"key,omitempty"` |
| 62 | } |
| 63 | |
| 64 | // Node is a template node, not a change to the live editor/CRDT schema. |
| 65 | type Node struct { |
| 66 | Type string `json:"type"` |
| 67 | Attrs Attrs `json:"attrs,omitempty"` |
| 68 | Content []Node `json:"content,omitempty"` |
| 69 | Text string `json:"text,omitempty"` |
| 70 | Marks []export.Mark `json:"marks,omitempty"` |
| 71 | } |
| 72 | |
| 73 | type Template struct { |
| 74 | Version int `json:"version"` |
| 75 | Title string `json:"title"` |
| 76 | Fields []Field `json:"fields"` |
| 77 | Root Node `json:"root"` |
| 78 | } |
| 79 | |
| 80 | // Diagnostic contains only a stable code and structural coordinate. Labels, |
| 81 | // text, raw parser errors and submitted values never enter an error string. |
| 82 | type Diagnostic struct { |
| 83 | Code string |
| 84 | Path string |
| 85 | } |
| 86 | |
| 87 | func (e *Diagnostic) Error() string { return "contract: " + e.Code + " at " + e.Path } |
| 88 | func problem(code, path string) error { return &Diagnostic{Code: code, Path: path} } |
| 89 | |
| 90 | // Parse rejects duplicate/unknown JSON properties and invalid Unicode using |
| 91 | // the same strict decoder already pinned by Docs. Validate also serves typed |
| 92 | // callers, so decoding is not the only enforcement point. |
| 93 | func Parse(data []byte) (Template, error) { |
| 94 | if len(data) > MaxTemplateBytes { |
| 95 | return Template{}, problem("template_too_large", "template") |
| 96 | } |
| 97 | var t Template |
| 98 | if err := json.Unmarshal(data, &t, json.RejectUnknownMembers(true)); err != nil { |
| 99 | return Template{}, problem("invalid_json", "template") |
| 100 | } |
| 101 | if err := t.Validate(); err != nil { |
| 102 | return Template{}, err |
| 103 | } |
| 104 | return t, nil |
| 105 | } |
| 106 | |
| 107 | var keyPattern = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]{0,63}$`) |
| 108 | |
| 109 | func validText(s string, max int) bool { |
| 110 | if len(s) > max || !utf8.ValidString(s) { |
| 111 | return false |
| 112 | } |
| 113 | for _, r := range s { |
| 114 | if (unicode.IsControl(r) && r != '\n' && r != '\t') || unicode.In(r, unicode.Cf) { |
| 115 | return false |
| 116 | } |
| 117 | } |
| 118 | return true |
| 119 | } |
| 120 | |
| 121 | func wordTooLong(s string) bool { |
| 122 | length := 0 |
| 123 | for _, r := range s { |
| 124 | if r == ' ' || r == '\n' || r == '\t' { |
| 125 | length = 0 |
| 126 | } else { |
| 127 | length += utf8.RuneLen(r) |
| 128 | } |
| 129 | if length > MaxWordBytes { |
| 130 | return true |
| 131 | } |
| 132 | } |
| 133 | return false |
| 134 | } |
| 135 | |
| 136 | func (t Template) Validate() error { |
| 137 | if t.Version != Version { |
| 138 | return problem("unsupported_version", "version") |
| 139 | } |
| 140 | if !validText(t.Title, MaxLabelBytes) || strings.ContainsAny(t.Title, "\n\t") { |
| 141 | return problem("invalid_title", "title") |
| 142 | } |
| 143 | if len(t.Fields) > MaxFields { |
| 144 | return problem("too_many_fields", "fields") |
| 145 | } |
| 146 | defs := make(map[string]Field, len(t.Fields)) |
| 147 | for i, f := range t.Fields { |
| 148 | path := fmt.Sprintf("fields[%d]", i) |
| 149 | if !keyPattern.MatchString(f.Key) || !validText(f.Label, MaxLabelBytes) || strings.TrimSpace(f.Label) == "" { |
| 150 | return problem("invalid_field", path) |
| 151 | } |
| 152 | if _, exists := defs[f.Key]; exists { |
| 153 | return problem("duplicate_field", path) |
| 154 | } |
| 155 | switch f.Kind { |
| 156 | case Text, Date: |
| 157 | if f.Currency != "" { |
| 158 | return problem("unexpected_currency", path) |
| 159 | } |
| 160 | case Money: |
| 161 | if _, ok := currencyScale(f.Currency); !ok { |
| 162 | return problem("invalid_currency", path) |
| 163 | } |
| 164 | default: |
| 165 | return problem("unsupported_kind", path) |
| 166 | } |
| 167 | defs[f.Key] = f |
| 168 | } |
| 169 | v := validator{defs: defs, used: map[string]bool{}} |
| 170 | if err := v.node(t.Root, "", "root", 0); err != nil { |
| 171 | return err |
| 172 | } |
| 173 | for i, f := range t.Fields { |
| 174 | if !v.used[f.Key] { |
| 175 | return problem("unused_field", fmt.Sprintf("fields[%d]", i)) |
| 176 | } |
| 177 | } |
| 178 | // Bound the encoded representation for typed callers too, after bounded |
| 179 | // traversal has excluded extreme depth and cyclic slice-backed trees. |
| 180 | b, err := json.Marshal(t) |
| 181 | if err != nil || len(b) > MaxTemplateBytes { |
| 182 | return problem("template_too_large", "template") |
| 183 | } |
| 184 | return nil |
| 185 | } |
| 186 | |
| 187 | type validator struct { |
| 188 | defs map[string]Field |
| 189 | used map[string]bool |
| 190 | nodes, bytes int |
| 191 | } |
| 192 | |
| 193 | func isBlock(s string) bool { |
| 194 | switch s { |
| 195 | case "paragraph", "heading", "blockquote", "code_block", "bullet_list", "ordered_list": |
| 196 | return true |
| 197 | } |
| 198 | return false |
| 199 | } |
| 200 | |
| 201 | func childAllowed(parent, child string) bool { |
| 202 | switch parent { |
| 203 | case "": |
| 204 | return child == "doc" |
| 205 | case "doc", "blockquote", "list_item": |
| 206 | return isBlock(child) |
| 207 | case "bullet_list", "ordered_list": |
| 208 | return child == "list_item" |
| 209 | case "paragraph", "heading": |
| 210 | return child == "text" || child == "hard_break" || child == "merge_field" |
| 211 | case "code_block": |
| 212 | return child == "text" |
| 213 | } |
| 214 | return false |
| 215 | } |
| 216 | |
| 217 | func (v *validator) node(n Node, parent, path string, depth int) error { |
| 218 | v.nodes++ |
| 219 | if depth > MaxDepth || v.nodes > MaxNodes { |
| 220 | return problem("tree_limit", path) |
| 221 | } |
| 222 | if !childAllowed(parent, n.Type) { |
| 223 | return problem("unsupported_structure", path) |
| 224 | } |
| 225 | inline := n.Type == "text" || n.Type == "hard_break" || n.Type == "merge_field" |
| 226 | if inline && len(n.Content) != 0 { |
| 227 | return problem("unexpected_children", path) |
| 228 | } |
| 229 | if !inline && n.Type != "paragraph" && n.Type != "heading" && n.Type != "code_block" && len(n.Content) == 0 { |
| 230 | return problem("missing_children", path) |
| 231 | } |
| 232 | if n.Type == "list_item" && n.Content[0].Type != "paragraph" { |
| 233 | return problem("list_item_paragraph", path) |
| 234 | } |
| 235 | if n.Type != "text" && n.Text != "" { |
| 236 | return problem("unexpected_text", path) |
| 237 | } |
| 238 | if !validText(n.Text, MaxTextBytes) { |
| 239 | return problem("invalid_text", path) |
| 240 | } |
| 241 | if wordTooLong(n.Text) { |
| 242 | return problem("word_limit", path) |
| 243 | } |
| 244 | v.bytes += len(n.Text) |
| 245 | if v.bytes > MaxTextBytes { |
| 246 | return problem("text_limit", path) |
| 247 | } |
| 248 | a := n.Attrs |
| 249 | if n.Type == "heading" { |
| 250 | if a.Level < 1 || a.Level > 6 { |
| 251 | return problem("invalid_heading", path) |
| 252 | } |
| 253 | } else if a.Level != 0 { |
| 254 | return problem("unexpected_level", path) |
| 255 | } |
| 256 | if a.Indent < 0 || a.Indent > export.MaxIndent || (a.Indent != 0 && n.Type != "paragraph" && n.Type != "heading") { |
| 257 | return problem("invalid_indent", path) |
| 258 | } |
| 259 | if a.Align != "" && (n.Type != "paragraph" || (a.Align != "left" && a.Align != "center" && a.Align != "right")) { |
| 260 | return problem("invalid_alignment", path) |
| 261 | } |
| 262 | if n.Type == "merge_field" { |
| 263 | if _, ok := v.defs[a.Key]; !ok { |
| 264 | return problem("unknown_field", path) |
| 265 | } |
| 266 | v.used[a.Key] = true |
| 267 | } else if a.Key != "" { |
| 268 | return problem("unexpected_key", path) |
| 269 | } |
| 270 | if !inline && len(n.Marks) != 0 { |
| 271 | return problem("unexpected_marks", path) |
| 272 | } |
| 273 | if err := validateMarks(n.Marks, path); err != nil { |
| 274 | return err |
| 275 | } |
| 276 | if parent == "code_block" && len(n.Marks) != 0 { |
| 277 | return problem("unexpected_marks", path) |
| 278 | } |
| 279 | for i, child := range n.Content { |
| 280 | if err := v.node(child, n.Type, fmt.Sprintf("%s.content[%d]", path, i), depth+1); err != nil { |
| 281 | return err |
| 282 | } |
| 283 | } |
| 284 | return nil |
| 285 | } |
| 286 | |
| 287 | func validateMarks(marks []export.Mark, path string) error { |
| 288 | groups := map[string]bool{} |
| 289 | for _, m := range marks { |
| 290 | group := m.Type |
| 291 | switch { |
| 292 | case m.Type == "strong" || m.Type == "em" || m.Type == "code": |
| 293 | case strings.HasPrefix(m.Type, "font_"): |
| 294 | if _, ok := fonts.ByKey(strings.TrimPrefix(m.Type, "font_")); !ok { |
| 295 | return problem("unsupported_mark", path) |
| 296 | } |
| 297 | group = "font" |
| 298 | case strings.HasPrefix(m.Type, "size_"): |
| 299 | if _, ok := export.SizePt(m.Type); !ok { |
| 300 | return problem("unsupported_mark", path) |
| 301 | } |
| 302 | group = "size" |
| 303 | default: |
| 304 | return problem("unsupported_mark", path) |
| 305 | } |
| 306 | if groups[group] { |
| 307 | return problem("conflicting_marks", path) |
| 308 | } |
| 309 | groups[group] = true |
| 310 | } |
| 311 | // The exporter forces the code family even if a font mark is present. |
| 312 | if groups["code"] && groups["font"] { |
| 313 | return problem("conflicting_marks", path) |
| 314 | } |
| 315 | return nil |
| 316 | } |
| 317 | |