package server import ( "encoding/csv" "errors" "html" "io" "net/http" "net/url" "path" "regexp" "strconv" "strings" "unicode/utf8" "github.com/google/uuid" ) // Projection only: no network fetch, shared rendered cache or write-back. const maxCSVMacroBytes = 256 << 10 var csvMacroRE = regexp.MustCompile(`^\{\{csv:(?:"([^"]+)"|([^\s}]+))(.*?)\}\}$`) var csvRangeRE = regexp.MustCompile(`^([A-Z]{1,2})([1-9][0-9]{0,3}):([A-Z]{1,2})([1-9][0-9]{0,3})$`) type csvMacroOptions struct { Path, Revision string Row, EndRow, Column, EndColumn int Header bool } func parseCSVMacro(raw string) (csvMacroOptions, error) { o := csvMacroOptions{Row: 1, EndRow: 200, Column: 1, EndColumn: 32, Header: true} m := csvMacroRE.FindStringSubmatch(raw) bad := errors.New("invalid CSV macro") if m == nil { return o, bad } o.Path = m[1] if o.Path == "" { o.Path = m[2] } if !strings.HasPrefix(o.Path, "/") || strings.HasPrefix(o.Path, "//") || path.Clean(o.Path) != o.Path || strings.ContainsAny(o.Path, "\\\x00\r\n") || len(o.Path) > 2048 { return o, bad } seen := map[string]bool{} for _, field := range strings.Fields(m[3]) { key, value, ok := strings.Cut(field, "=") if !ok || seen[key] { return o, bad } seen[key] = true switch key { case "header": if value != "true" && value != "false" { return o, bad } o.Header = value == "true" case "rev": if _, err := uuid.Parse(value); len(value) != 36 || err != nil { return o, bad } o.Revision = value case "range": parts := csvRangeRE.FindStringSubmatch(strings.ToUpper(value)) if parts == nil { return o, bad } col := func(s string) int { n := 0 for _, c := range s { n = n*26 + int(c-'A') + 1 } return n } o.Column, o.EndColumn = col(parts[1]), col(parts[3]) o.Row, _ = strconv.Atoi(parts[2]) o.EndRow, _ = strconv.Atoi(parts[4]) if o.Column > o.EndColumn || o.EndColumn > 100 || o.EndColumn-o.Column >= 32 || o.Row > o.EndRow || o.EndRow > 2000 || o.EndRow-o.Row >= 200 { return o, bad } default: return o, bad } } return o, nil } func csvMacroTable(body []byte, o csvMacroOptions) (string, error) { if len(body) > maxCSVMacroBytes || !utf8.Valid(body) || strings.IndexByte(string(body), 0) >= 0 { return "", errors.New("invalid CSV input") } reader := csv.NewReader(strings.NewReader(strings.TrimPrefix(string(body), "\ufeff"))) reader.FieldsPerRecord = -1 var out strings.Builder out.WriteString(`