package config import ( "cmp" "fmt" "maps" "math" "net/url" "os" "path/filepath" "regexp" "slices" "strings" "time" "github.com/pelletier/go-toml/v2" ) const ( minSandboxTimeout = 100 * time.Millisecond maxSandboxTimeout = 30 * time.Second minSessionTimeout = 10 * time.Second maxSessionTimeout = 30 * time.Minute minMemoryMB = 4 maxMemoryMB = 1024 minCallStack = 50 maxCallStack = 10000 ) var ( pluginNameRe = regexp.MustCompile(`^[a-z0-9_-]+$`) currencyRe = regexp.MustCompile(`^[A-Z]{3}$`) typeErrRe = regexp.MustCompile(`^cannot decode TOML (\S+) into (?:struct field \S+ of type )?(\S+)$`) ) // goTypeNames describes the Go types of config fields in TOML terms. var goTypeNames = map[string]string{ "string": "a string", "bool": "true or false", "int": "an integer", "float64": "a number", "*float64": "a number", "[]string": "a list of strings", "[]config.Webhook": "a list of tables", "[]config.Item": "a list of tables", "config.Duration": `a duration string such as "3m"`, } type Error struct { File string Line int // 1-based; 0 if unknown Col int Key string // e.g. "item[1].interval"; empty for file-level problems Msg string } func (e Error) Error() string { var b strings.Builder b.WriteString(e.File) if e.Line > 0 { _, _ = fmt.Fprintf(&b, ":%d:%d", e.Line, e.Col) } b.WriteString(": ") if e.Key != "" { b.WriteString(e.Key) b.WriteString(": ") } b.WriteString(e.Msg) return b.String() } // Errors is sorted by position in the file. type Errors []Error func (es Errors) Error() string { lines := make([]string, len(es)) for i, e := range es { lines[i] = e.Error() } return strings.Join(lines, "\n") } type validator struct { file string pos positions errs Errors } func (v *validator) errorf(key, format string, args ...any) { e := Error{File: v.file, Key: key, Msg: fmt.Sprintf(format, args...)} if p, ok := v.pos.find(key); ok { e.Line, e.Col = p.Line, p.Column } v.errs = append(v.errs, e) } func (v *validator) decodeError(de *toml.DecodeError, msg string) { line, col := de.Position() if msg == "" { msg = friendlyDecodeMsg(strings.TrimPrefix(de.Error(), "toml: ")) } // The decoder's key has no array indexes; the key indexed at the same // position has them. key := v.pos.keyAt(line, col) if key == "" { key = strings.Join(de.Key(), ".") } v.errs = append(v.errs, Error{File: v.file, Line: line, Col: col, Key: key, Msg: msg}) } // friendlyDecodeMsg rewrites go-toml's type mismatch errors, which name Go // types, into TOML terms. func friendlyDecodeMsg(msg string) string { m := typeErrRe.FindStringSubmatch(msg) if m == nil { return msg } want, ok := goTypeNames[m[2]] if !ok { if strings.HasPrefix(m[2], "map[") { want = "a table" } else { return msg } } return fmt.Sprintf("expected %s, got a TOML %s", want, strings.ToLower(m[1])) } func (v *validator) validate(cfg *Config, opts Options) { shops := map[string]bool{} for _, b := range opts.Builtins { shops[b] = true } v.plugins(cfg, shops) v.items(cfg, shops, opts.Builtins) v.accounts(cfg, shops, opts.LookupEnv) v.notify(&cfg.Notify) v.sandbox(&cfg.Sandbox) // File-level errors first, then in document order. slices.SortStableFunc(v.errs, func(a, b Error) int { return cmp.Or(cmp.Compare(a.Line, b.Line), cmp.Compare(a.Col, b.Col)) }) } // plugins resolves plugin paths against the config dir and adds the plugin // names to shops. func (v *validator) plugins(cfg *Config, shops map[string]bool) { dir := filepath.Dir(cfg.Path) for _, name := range slices.Sorted(maps.Keys(cfg.Plugins)) { key := "plugins." + name if !pluginNameRe.MatchString(name) { v.errorf(key, "plugin name must contain only a-z, 0-9, _ and -") continue } shops[name] = true path := cfg.Plugins[name] if path == "" { v.errorf(key, "path is empty") continue } if !filepath.IsAbs(path) { path = filepath.Join(dir, path) } cfg.Plugins[name] = path info, err := os.Stat(path) switch { case err != nil: v.errorf(key, "cannot read plugin: %v", err) case !info.Mode().IsRegular(): v.errorf(key, "%s is not a regular file", path) } } } func (v *validator) items(cfg *Config, shops map[string]bool, builtins []string) { if len(cfg.Items) == 0 { v.errorf("", "no [[item]] configured") return } names := map[string]int{} urls := map[string]string{} for i := range cfg.Items { it := &cfg.Items[i] key := fmt.Sprintf("item[%d]", i) switch { case it.Name == "": v.errorf(key+".name", "missing required key") case names[it.Name] > 0: v.errorf(key+".name", "duplicate item name %q (also item[%d])", it.Name, names[it.Name]-1) default: names[it.Name] = i + 1 } switch { case it.Shop == "": v.errorf(key+".shop", "missing required key") case !shops[it.Shop]: v.errorf(key+".shop", "unknown shop %q: built-in plugins are %s, others must be listed under [plugins]", it.Shop, strings.Join(builtins, ", ")) } if len(it.URLs) == 0 { v.errorf(key+".urls", "at least one URL is required") } for j, raw := range it.URLs { ukey := fmt.Sprintf("%s.urls[%d]", key, j) if msg := checkURL(raw); msg != "" { v.errorf(ukey, "%s", msg) continue } if prev, dup := urls[raw]; dup { v.errorf(ukey, "duplicate URL (also %s)", prev) continue } urls[raw] = ukey } if it.MaxPrice != nil { if p := *it.MaxPrice; p <= 0 || math.IsInf(p, 0) || math.IsNaN(p) { v.errorf(key+".max_price", "must be a positive number (got %v)", p) } } if it.Currency != "" { it.Currency = strings.ToUpper(it.Currency) if !currencyRe.MatchString(it.Currency) { v.errorf(key+".currency", "must be a 3-letter ISO 4217 code such as EUR (got %q)", it.Currency) } } if it.FXMargin != 0 { switch { case it.FXMargin < 0 || it.FXMargin > 1: v.errorf(key+".fx_margin", "must be between 0 and 1, e.g. 0.1 for 10%% (got %v)", it.FXMargin) case it.Currency == "" || it.MaxPrice == nil: v.errorf(key+".fx_margin", "needs both currency and max_price to have an effect") } } switch it.Seller { case "": it.Seller = DefaultSeller case SellerFirstParty, SellerFulfilled, SellerAny: default: v.errorf(key+".seller", "must be %q, %q or %q (got %q)", SellerFirstParty, SellerFulfilled, SellerAny, it.Seller) } switch { case !it.Interval.IsSet(): it.Interval.Duration = DefaultInterval case it.Interval.Duration < MinInterval: v.errorf(key+".interval", "must be at least %s (got %s)", MinInterval, it.Interval) } } } func (v *validator) accounts(cfg *Config, shops map[string]bool, lookupEnv func(string) (string, bool)) { for _, shop := range slices.Sorted(maps.Keys(cfg.Accounts)) { acc := cfg.Accounts[shop] key := "accounts." + shop if !shops[shop] { v.errorf(key, "no plugin named %q", shop) } switch acc.CartMode { case "": acc.CartMode = CartModeDeeplink case CartModeDeeplink, CartModeSession: default: v.errorf(key+".cart_mode", "must be %q or %q (got %q)", CartModeDeeplink, CartModeSession, acc.CartMode) } if acc.PasswordEnv != "" { if val, ok := lookupEnv(acc.PasswordEnv); !ok || val == "" { v.errorf(key+".password_env", "environment variable %s is not set", acc.PasswordEnv) } } for _, f := range []struct{ name, raw string }{{"login_url", acc.LoginURL}, {"cart_url", acc.CartURL}} { if f.raw == "" { continue } if msg := checkURL(f.raw); msg != "" { v.errorf(key+"."+f.name, "%s", msg) } } cfg.Accounts[shop] = acc } } func (v *validator) notify(n *Notify) { for i, wh := range n.Webhooks { key := fmt.Sprintf("notify.webhooks[%d]", i) if wh.URL == "" { v.errorf(key+".url", "missing required key") } else if msg := checkURL(wh.URL); msg != "" { v.errorf(key+".url", "%s", msg) } switch wh.Format { case FormatDiscord, FormatNtfy, FormatJSON: case "": v.errorf(key+".format", "missing required key (%q, %q or %q)", FormatDiscord, FormatNtfy, FormatJSON) default: v.errorf(key+".format", "must be %q, %q or %q (got %q)", FormatDiscord, FormatNtfy, FormatJSON, wh.Format) } } if n.Cooldown.Duration < 0 { v.errorf("notify.cooldown", "must not be negative (got %s)", n.Cooldown) } } func (v *validator) sandbox(s *Sandbox) { durationRange(v, "sandbox.timeout", s.Timeout.Duration, minSandboxTimeout, maxSandboxTimeout) durationRange(v, "sandbox.session_timeout", s.SessionTimeout.Duration, minSessionTimeout, maxSessionTimeout) if s.MemoryMB < minMemoryMB || s.MemoryMB > maxMemoryMB { v.errorf("sandbox.memory_mb", "must be between %d and %d (got %d)", minMemoryMB, maxMemoryMB, s.MemoryMB) } if s.CallStack < minCallStack || s.CallStack > maxCallStack { v.errorf("sandbox.call_stack", "must be between %d and %d (got %d)", minCallStack, maxCallStack, s.CallStack) } } func durationRange(v *validator, key string, d, lo, hi time.Duration) { if d < lo || d > hi { v.errorf(key, "must be between %s and %s (got %s)", lo, hi, d) } } // checkURL returns a problem with raw, or "" if it is an absolute http(s) URL. func checkURL(raw string) string { u, err := url.Parse(raw) switch { case err != nil: return fmt.Sprintf("invalid URL: %v", err) case u.Scheme != "http" && u.Scheme != "https": return fmt.Sprintf("URL must start with http:// or https:// (got %q)", raw) case u.Host == "": return fmt.Sprintf("URL has no host (got %q)", raw) } return "" }