diff --git a/cmd/dibs/main.go b/cmd/dibs/main.go new file mode 100644 index 0000000..96e9701 --- /dev/null +++ b/cmd/dibs/main.go @@ -0,0 +1,159 @@ +// Command dibs is a personal restock watcher. +package main + +import ( + "errors" + "flag" + "fmt" + "io" + "io/fs" + "os" + "runtime" + "runtime/debug" + + "git.security-command.org/Overlord/dibs/internal/config" +) + +// version is set at build time with -ldflags "-X main.version=...". +var version = "dev" + +// builtinPlugins are the plugins embedded in the binary. +var builtinPlugins = []string{"amazon"} + +const usage = `Usage: + dibs [--config FILE] [--headless] watch items (TUI unless --headless) + dibs check fetch and parse one URL, print JSON + dibs plugin test [url] + dibs config validate [--config FILE] + dibs version +` + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +func run(args []string, stdout, stderr io.Writer) int { + if len(args) > 0 { + switch args[0] { + case "config": + return runConfig(args[1:], stdout, stderr) + case "version": + printVersion(stdout) + return 0 + case "check", "plugin": + _, _ = fmt.Fprintf(stderr, "dibs %s: not implemented yet\n", args[0]) + return 1 + case "help", "-h", "--help": + _, _ = fmt.Fprint(stdout, usage) + return 0 + } + } + + flags, configPath := newFlagSet("dibs", stderr) + flags.Bool("headless", false, "run without the TUI, log to stdout") + + if err := flags.Parse(args); err != nil { + return 2 + } + + if flags.NArg() > 0 { + _, _ = fmt.Fprintf(stderr, "dibs: unknown command %q\n\n%s", flags.Arg(0), usage) + return 2 + } + + if _, ok := loadConfig(*configPath, stderr); !ok { + return 1 + } + + _, _ = fmt.Fprintln(stderr, "dibs: watching is not implemented yet") + return 1 +} + +func runConfig(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 || args[0] != "validate" { + _, _ = fmt.Fprintf(stderr, "dibs config: expected \"validate\"\n\n%s", usage) + return 2 + } + + flags, configPath := newFlagSet("dibs config validate", stderr) + if err := flags.Parse(args[1:]); err != nil { + return 2 + } + + cfg, ok := loadConfig(*configPath, stderr) + if !ok { + return 1 + } + + urls := 0 + for _, it := range cfg.Items { + urls += len(it.URLs) + } + + _, _ = fmt.Fprintf(stdout, "%s: OK (%s, %s, %s, %s)\n", cfg.Path, + plural(len(cfg.Items), "item"), plural(urls, "URL"), + plural(len(cfg.Accounts), "account"), plural(len(cfg.Plugins), "plugin")) + + return 0 +} + +func plural(n int, noun string) string { + if n == 1 { + return "1 " + noun + } + return fmt.Sprintf("%d %ss", n, noun) +} + +// newFlagSet returns a flag set with the --config flag every command takes. +func newFlagSet(name string, stderr io.Writer) (*flag.FlagSet, *string) { + flags := flag.NewFlagSet(name, flag.ContinueOnError) + flags.SetOutput(stderr) + path := flags.String("config", "", "config file (default: dibs.toml in the user config dir)") + + return flags, path +} + +func loadConfig(path string, stderr io.Writer) (*config.Config, bool) { + if path == "" { + var err error + if path, err = config.DefaultPath(); err != nil { + _, _ = fmt.Fprintf(stderr, "dibs: no config dir: %v\n", err) + return nil, false + } + } + + cfg, err := config.Load(path, config.Options{Builtins: builtinPlugins}) + if err != nil { + var errs config.Errors + switch { + case errors.As(err, &errs): + _, _ = fmt.Fprintln(stderr, errs) + _, _ = fmt.Fprintf(stderr, "%s in config\n", plural(len(errs), "problem")) + case errors.Is(err, fs.ErrNotExist): + _, _ = fmt.Fprintf(stderr, "dibs: no config at %s: create it or pass --config\n", path) + default: + _, _ = fmt.Fprintf(stderr, "dibs: %v\n", err) + } + + return nil, false + } + + return cfg, true +} + +func printVersion(w io.Writer) { + v, rev := version, "" + if info, ok := debug.ReadBuildInfo(); ok { + if v == "dev" && info.Main.Version != "" && info.Main.Version != "(devel)" { + v = info.Main.Version + } + + for _, s := range info.Settings { + if s.Key == "vcs.revision" && len(s.Value) >= 12 { + rev = " " + s.Value[:12] + } + } + } + + _, _ = fmt.Fprintf(w, "dibs %s%s (%s, %s/%s)\n", v, rev, runtime.Version(), runtime.GOOS, runtime.GOARCH) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..16fa08b --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module git.security-command.org/Overlord/dibs + +go 1.26.0 + +require github.com/pelletier/go-toml/v2 v2.4.3 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..ddaf7d6 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= +github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..2d9cf29 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,203 @@ +// Package config loads and validates dibs.toml. +package config + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "time" + + "github.com/pelletier/go-toml/v2" +) + +// MinInterval is the shortest allowed polling interval per URL. +const MinInterval = 60 * time.Second + +const ( + SellerFirstParty = "first_party" + SellerAny = "any" + + CartModeDeeplink = "deeplink" + CartModeSession = "session" + + FormatDiscord = "discord" + FormatNtfy = "ntfy" + FormatJSON = "json" +) + +// Defaults for keys that may be omitted. +const ( + DefaultInterval = 3 * time.Minute + DefaultCooldown = 30 * time.Minute + DefaultSandboxTimeout = 2 * time.Second + DefaultSessionTimeout = 5 * time.Minute + DefaultMemoryMB = 64 + DefaultCallStack = 200 +) + +type Config struct { + Items []Item `toml:"item"` + Accounts map[string]Account `toml:"accounts"` + Notify Notify `toml:"notify"` + // Plugins maps a plugin name to its file. After Load the paths are absolute. + Plugins map[string]string `toml:"plugins"` + Sandbox Sandbox `toml:"sandbox"` + + // Path is the absolute path of the loaded file. + Path string `toml:"-"` +} + +type Item struct { + Name string `toml:"name"` + Shop string `toml:"shop"` + URLs []string `toml:"urls"` + MaxPrice *float64 `toml:"max_price"` + Currency string `toml:"currency"` + // FXMargin is added to a converted price before it is compared with + // MaxPrice, to cover import fees and card exchange rates. 0.1 means 10%. + FXMargin float64 `toml:"fx_margin"` + Seller string `toml:"seller"` + Interval Duration `toml:"interval"` +} + +type Account struct { + Username string `toml:"username"` + PasswordEnv string `toml:"password_env"` + CartMode string `toml:"cart_mode"` + LoginURL string `toml:"login_url"` + CartURL string `toml:"cart_url"` + TwoFA bool `toml:"twofa"` +} + +type Notify struct { + Webhooks []Webhook `toml:"webhooks"` + Desktop bool `toml:"desktop"` + Cooldown Duration `toml:"cooldown"` +} + +type Webhook struct { + URL string `toml:"url"` + Format string `toml:"format"` +} + +// Sandbox holds the limits for Lua plugin calls. +type Sandbox struct { + // Timeout applies to matches, parse and cart_link. + Timeout Duration `toml:"timeout"` + // SessionTimeout applies to login and add_to_cart, which wait on the + // network and on the user typing 2FA codes. + SessionTimeout Duration `toml:"session_timeout"` + // MemoryMB is the approximate heap growth one call may cause before it is + // cancelled. + MemoryMB int `toml:"memory_mb"` + // CallStack is the maximum Lua call depth. + CallStack int `toml:"call_stack"` +} + +// Duration is a time.Duration written as a string such as "3m" or "90s". +type Duration struct { + time.Duration + set bool +} + +func (d *Duration) UnmarshalText(b []byte) error { + v, err := time.ParseDuration(string(b)) + if err != nil { + return fmt.Errorf(`invalid duration %q: use a number with a unit, such as "90s", "3m" or "1h30m"`, b) + } + + d.Duration, d.set = v, true + return nil +} + +func (d Duration) MarshalText() ([]byte, error) { + return []byte(d.String()), nil +} + +// IsSet reports whether the value came from the config file. +func (d Duration) IsSet() bool { return d.set } + +// Options control validation that depends on the environment. +type Options struct { + // Builtins are the names of the embedded plugins. + Builtins []string + // LookupEnv resolves password_env. Defaults to os.LookupEnv. + LookupEnv func(string) (string, bool) +} + +// DefaultPath returns dibs.toml in the user config dir. +func DefaultPath() (string, error) { + dir, err := os.UserConfigDir() + if err != nil { + return "", err + } + return filepath.Join(dir, "dibs", "dibs.toml"), nil +} + +// Load reads, decodes and validates the config at path. All problems found +// are returned together as Errors. +func Load(path string, opts Options) (*Config, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + abs, err := filepath.Abs(path) + if err != nil { + return nil, err + } + + if opts.LookupEnv == nil { + opts.LookupEnv = os.LookupEnv + } + + cfg := &Config{ + Path: abs, + Notify: Notify{ + Desktop: true, + Cooldown: Duration{Duration: DefaultCooldown}, + }, + Sandbox: Sandbox{ + Timeout: Duration{Duration: DefaultSandboxTimeout}, + SessionTimeout: Duration{Duration: DefaultSessionTimeout}, + MemoryMB: DefaultMemoryMB, + CallStack: DefaultCallStack, + }, + } + + v := &validator{file: path, pos: indexPositions(data)} + + dec := toml.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + err = dec.Decode(cfg) + + var strict *toml.StrictMissingError + var decErr *toml.DecodeError + + switch { + case err == nil: + case errors.As(err, &strict): + // The rest of the document was decoded, so keep validating it. + for _, e := range strict.Errors { + msg := "unknown key" + if k := e.Key(); len(k) > 0 && k[len(k)-1] == "quantity" { + msg = "unknown key: quantity is always 1 and cannot be configured" + } + v.decodeError(&e, msg) + } + case errors.As(err, &decErr): + v.decodeError(decErr, "") + return nil, v.errs + default: + return nil, err + } + + v.validate(cfg, opts) + if len(v.errs) > 0 { + return nil, v.errs + } + + return cfg, nil +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..98c2d67 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,336 @@ +package config + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +const fullConfig = ` +[[item]] +name = "Metro 2039 CE" +shop = "amazon" +urls = ["https://www.amazon.de/dp/B0HMX2FSTF", "https://www.amazon.co.uk/dp/B0HM497GJJ"] +max_price = 129.99 +currency = "eur" +fx_margin = 0.1 +seller = "any" +interval = "5m" + +[[item]] +name = "Console" +shop = "mediamarkt" +urls = ["https://www.mediamarkt.de/de/product/_console-123.html"] + +[accounts.amazon] +username = "me@example.com" +password_env = "DIBS_AMAZON_PASS" +cart_mode = "session" +twofa = true + +[notify] +webhooks = [ + { url = "https://discord.com/api/webhooks/1/abc", format = "discord" }, + { url = "https://ntfy.sh/my-topic", format = "ntfy" }, +] +desktop = false +cooldown = "1h" + +[plugins] +mediamarkt = "plugins/mediamarkt.lua" + +[sandbox] +timeout = "500ms" +session_timeout = "2m" +memory_mb = 32 +call_stack = 100 +` + +// load writes doc as dibs.toml in a temp dir, together with an empty +// plugins/mediamarkt.lua, and loads it. +func load(t *testing.T, doc string, env map[string]string) (*Config, error) { + t.Helper() + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "plugins"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "plugins", "mediamarkt.lua"), nil, 0o644); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "dibs.toml") + if err := os.WriteFile(path, []byte(doc), 0o644); err != nil { + t.Fatal(err) + } + return Load(path, Options{ + Builtins: []string{"amazon"}, + LookupEnv: func(k string) (string, bool) { + v, ok := env[k] + return v, ok + }, + }) +} + +// errs asserts that err is Errors and returns it. +func errs(t *testing.T, err error) Errors { + t.Helper() + var es Errors + if !errors.As(err, &es) { + t.Fatalf("want config.Errors, got %T: %v", err, err) + } + return es +} + +// wantErr asserts that es has an error for key on line whose message +// contains msg. +func wantErr(t *testing.T, es Errors, key string, line int, msg string) { + t.Helper() + for _, e := range es { + if e.Key == key && e.Line == line && strings.Contains(e.Msg, msg) { + return + } + } + t.Errorf("no error for %s on line %d containing %q; got:\n%v", key, line, msg, es) +} + +func TestLoadFull(t *testing.T) { + cfg, err := load(t, fullConfig, map[string]string{"DIBS_AMAZON_PASS": "secret"}) + if err != nil { + t.Fatal(err) + } + + if len(cfg.Items) != 2 { + t.Fatalf("items: got %d, want 2", len(cfg.Items)) + } + it := cfg.Items[0] + if it.Currency != "EUR" { + t.Errorf("currency: got %q, want it uppercased to EUR", it.Currency) + } + if it.MaxPrice == nil || *it.MaxPrice != 129.99 { + t.Errorf("max_price: got %v", it.MaxPrice) + } + if it.Seller != SellerAny || it.Interval.Duration != 5*time.Minute || it.FXMargin != 0.1 { + t.Errorf("item[0]: got %+v", it) + } + + if acc := cfg.Accounts["amazon"]; acc.CartMode != CartModeSession || !acc.TwoFA { + t.Errorf("account: got %+v", acc) + } + if n := cfg.Notify; n.Desktop || n.Cooldown.Duration != time.Hour || len(n.Webhooks) != 2 { + t.Errorf("notify: got %+v", n) + } + want := filepath.Join(filepath.Dir(cfg.Path), "plugins", "mediamarkt.lua") + if got := cfg.Plugins["mediamarkt"]; got != want { + t.Errorf("plugin path: got %q, want %q", got, want) + } + s := cfg.Sandbox + if s.Timeout.Duration != 500*time.Millisecond || s.SessionTimeout.Duration != 2*time.Minute || + s.MemoryMB != 32 || s.CallStack != 100 { + t.Errorf("sandbox: got %+v", s) + } +} + +func TestLoadDefaults(t *testing.T) { + cfg, err := load(t, ` +[[item]] +name = "x" +shop = "amazon" +urls = ["https://www.amazon.de/dp/B0HMX2FSTF"] + +[accounts.amazon] +`, nil) + if err != nil { + t.Fatal(err) + } + it := cfg.Items[0] + if it.Seller != SellerFirstParty || it.Interval.Duration != DefaultInterval || it.MaxPrice != nil { + t.Errorf("item defaults: got %+v", it) + } + if cfg.Accounts["amazon"].CartMode != CartModeDeeplink { + t.Errorf("cart_mode default: got %q", cfg.Accounts["amazon"].CartMode) + } + if !cfg.Notify.Desktop || cfg.Notify.Cooldown.Duration != DefaultCooldown { + t.Errorf("notify defaults: got %+v", cfg.Notify) + } + s := cfg.Sandbox + if s.Timeout.Duration != DefaultSandboxTimeout || s.SessionTimeout.Duration != DefaultSessionTimeout || + s.MemoryMB != DefaultMemoryMB || s.CallStack != DefaultCallStack { + t.Errorf("sandbox defaults: got %+v", s) + } +} + +func TestUnknownKeys(t *testing.T) { + _, err := load(t, ` +[[item]] +name = "x" +shop = "amazon" +urls = ["https://www.amazon.de/dp/B0HMX2FSTF"] +quantity = 2 + +[notfy] +desktop = true +`, nil) + es := errs(t, err) + wantErr(t, es, "item[0].quantity", 6, "quantity is always 1") + wantErr(t, es, "notfy", 8, "unknown key") +} + +func TestUnknownKeyStillValidatesRest(t *testing.T) { + _, err := load(t, ` +[[item]] +name = "x" +shop = "amazon" +urls = ["https://www.amazon.de/dp/B0HMX2FSTF"] +interval = "10s" +typo = 1 +`, nil) + es := errs(t, err) + if len(es) != 2 { + t.Errorf("want 2 errors, got:\n%v", es) + } + wantErr(t, es, "item[0].interval", 6, "at least 1m0s") +} + +func TestDecodeErrors(t *testing.T) { + for name, tc := range map[string]struct { + doc string + key string + line int + msg string + }{ + "wrong type": {"[[item]]\nname = \"x\"\nmax_price = \"cheap\"\n", "item[0].max_price", 3, "expected a number, got a TOML string"}, + "wrong element": {"[[item]]\nname = \"x\"\nurls = [1]\n", "item[0].urls[0]", 3, "expected a string, got a TOML integer"}, + "bad duration": {"[[item]]\nname = \"x\"\ninterval = \"3x\"\n", "item[0].interval", 3, "invalid duration"}, + "syntax": {"[[item]]\nname = \n", "", 2, ""}, + } { + t.Run(name, func(t *testing.T) { + _, err := load(t, tc.doc, nil) + es := errs(t, err) + if len(es) != 1 { + t.Fatalf("want one error, got:\n%v", es) + } + if tc.key != "" { + wantErr(t, es, tc.key, tc.line, tc.msg) + } else if es[0].Line != tc.line { + t.Errorf("want error on line %d, got:\n%v", tc.line, es) + } + }) + } +} + +func TestValidationErrors(t *testing.T) { + _, err := load(t, ` +[[item]] +shop = "amazn" +urls = ["ftp://example.com/x", "https://www.amazon.de/dp/B0HMX2FSTF"] +max_price = -5 +currency = "EURO" +seller = "amazon" +interval = "30s" + +[[item]] +name = "dup" +shop = "amazon" +urls = ["https://www.amazon.de/dp/B0HMX2FSTF"] +fx_margin = 0.2 + +[[item]] +name = "dup" +shop = "amazon" +urls = [] + +[accounts.amazon] +password_env = "DIBS_MISSING" +cart_mode = "auto" +login_url = "/signin" + +[accounts.ebay] + +[notify] +webhooks = [ + { url = "https://ntfy.sh/a", format = "ntfy" }, + { url = "https://example.com/hook", format = "slack" }, + { format = "json" }, +] +cooldown = "-1m" + +[plugins] +"Bad Name" = "x.lua" +missing = "plugins/missing.lua" + +[sandbox] +timeout = "1m" +session_timeout = "1s" +memory_mb = 0 +call_stack = 1 +`, nil) + es := errs(t, err) + + wantErr(t, es, "item[0].name", 2, "missing required key") + wantErr(t, es, "item[0].shop", 3, `unknown shop "amazn"`) + wantErr(t, es, "item[0].urls[0]", 4, "http:// or https://") + wantErr(t, es, "item[0].max_price", 5, "positive") + wantErr(t, es, "item[0].currency", 6, "ISO 4217") + wantErr(t, es, "item[0].seller", 7, `"first_party" or "any"`) + wantErr(t, es, "item[0].interval", 8, "at least 1m0s") + wantErr(t, es, "item[1].urls[0]", 13, "duplicate URL (also item[0].urls[1])") + wantErr(t, es, "item[1].fx_margin", 14, "needs both currency and max_price") + wantErr(t, es, "item[2].name", 17, "duplicate item name") + wantErr(t, es, "item[2].urls", 19, "at least one URL") + wantErr(t, es, "accounts.amazon.password_env", 22, "DIBS_MISSING is not set") + wantErr(t, es, "accounts.amazon.cart_mode", 23, `"deeplink" or "session"`) + wantErr(t, es, "accounts.amazon.login_url", 24, "http:// or https://") + wantErr(t, es, "accounts.ebay", 26, `no plugin named "ebay"`) + wantErr(t, es, "notify.webhooks[1].format", 31, `got "slack"`) + wantErr(t, es, "notify.webhooks[2].url", 32, "missing required key") + wantErr(t, es, "notify.cooldown", 34, "negative") + wantErr(t, es, "plugins.Bad Name", 37, "plugin name") + wantErr(t, es, "plugins.missing", 38, "cannot read plugin") + wantErr(t, es, "sandbox.timeout", 41, "between 100ms and 30s") + wantErr(t, es, "sandbox.session_timeout", 42, "between 10s and 30m0s") + wantErr(t, es, "sandbox.memory_mb", 43, "between 4 and 1024") + wantErr(t, es, "sandbox.call_stack", 44, "between 50 and 10000") + if len(es) != 24 { + t.Errorf("want 24 errors, got %d:\n%v", len(es), es) + } + for i := 1; i < len(es); i++ { + if es[i].Line < es[i-1].Line { + t.Errorf("errors not sorted by line:\n%v", es) + break + } + } +} + +func TestNoItems(t *testing.T) { + _, err := load(t, "[notify]\ndesktop = true\n", nil) + es := errs(t, err) + if len(es) != 1 || !strings.Contains(es[0].Msg, "no [[item]]") { + t.Errorf("got:\n%v", es) + } +} + +func TestEmptyPasswordEnv(t *testing.T) { + _, err := load(t, ` +[[item]] +name = "x" +shop = "amazon" +urls = ["https://www.amazon.de/dp/B0HMX2FSTF"] + +[accounts.amazon] +password_env = "DIBS_AMAZON_PASS" +`, map[string]string{"DIBS_AMAZON_PASS": ""}) + wantErr(t, errs(t, err), "accounts.amazon.password_env", 8, "is not set") +} + +func TestErrorFormat(t *testing.T) { + e := Error{File: "dibs.toml", Line: 14, Col: 3, Key: "item[1].interval", Msg: "must be at least 1m0s (got 30s)"} + if got, want := e.Error(), "dibs.toml:14:3: item[1].interval: must be at least 1m0s (got 30s)"; got != want { + t.Errorf("got %q, want %q", got, want) + } + e = Error{File: "dibs.toml", Msg: "no [[item]] configured"} + if got, want := e.Error(), "dibs.toml: no [[item]] configured"; got != want { + t.Errorf("got %q, want %q", got, want) + } +} diff --git a/internal/config/positions.go b/internal/config/positions.go new file mode 100644 index 0000000..e48f3fe --- /dev/null +++ b/internal/config/positions.go @@ -0,0 +1,133 @@ +package config + +import ( + "fmt" + "strings" + + "github.com/pelletier/go-toml/v2/unstable" +) + +// positions maps key paths such as "item[1].interval" or +// "notify.webhooks[0].url" to where they appear in the document, so that +// validation errors can point at a line. +type positions map[string]unstable.Position + +func indexPositions(doc []byte) positions { + ps := positions{} + var p unstable.Parser + p.Reset(doc) + + prefix := "" + arrays := map[string]int{} + // A parse error stops the index early. The decoder reports it. + for p.NextExpression() { + e := p.Expression() + + switch e.Kind { + case unstable.Table, unstable.ArrayTable: + keys, first := keyParts(e.Key()) + path := strings.Join(keys, ".") + if e.Kind == unstable.ArrayTable { + n := arrays[path] + arrays[path]++ + path = fmt.Sprintf("%s[%d]", path, n) + } + prefix = path + ps.add(&p, path, first) + case unstable.KeyValue: + ps.keyValue(&p, prefix, e) + } + } + + return ps +} + +func (ps positions) keyValue(p *unstable.Parser, prefix string, kv *unstable.Node) { + keys, first := keyParts(kv.Key()) + path := strings.Join(keys, ".") + + if prefix != "" { + path = prefix + "." + path + } + + ps.add(p, path, first) + ps.value(p, path, kv.Value()) +} + +func (ps positions) value(p *unstable.Parser, path string, v *unstable.Node) { + switch v.Kind { + case unstable.Array: + it := v.Children() + for i := 0; it.Next(); i++ { + el := it.Node() + elPath := fmt.Sprintf("%s[%d]", path, i) + ps.add(p, elPath, el) + ps.value(p, elPath, el) + } + case unstable.InlineTable: + it := v.Children() + for it.Next() { + if kv := it.Node(); kv.Kind == unstable.KeyValue { + ps.keyValue(p, path, kv) + } + } + } +} + +func (ps positions) add(p *unstable.Parser, path string, n *unstable.Node) { + if _, ok := ps[path]; !ok && n != nil { + ps[path] = p.Shape(n.Raw).Start + } +} + +// find returns the position of path, or of its closest present parent, so +// that a missing key points at the table it belongs in. +func (ps positions) find(path string) (unstable.Position, bool) { + for path != "" { + if pos, ok := ps[path]; ok { + return pos, true + } + + i := strings.LastIndexAny(path, ".[") + if i < 0 { + break + } + + path = path[:i] + } + + return unstable.Position{}, false +} + +// keyAt returns the path of the last key that starts on line at or before +// col, or "" if there is none. +func (ps positions) keyAt(line, col int) string { + best, bestCol := "", 0 + + for path, p := range ps { + if p.Line == line && p.Column <= col && p.Column >= bestCol { + // Prefer the longer path when an array element and its first key + // share a position. + if p.Column > bestCol || len(path) > len(best) { + best, bestCol = path, p.Column + } + } + } + + return best +} + +func keyParts(it unstable.Iterator) ([]string, *unstable.Node) { + var keys []string + var first *unstable.Node + + for it.Next() { + n := it.Node() + if first == nil { + first = n + } + keys = append(keys, string(n.Data)) + } + + return keys, first +} diff --git a/internal/config/validate.go b/internal/config/validate.go new file mode 100644 index 0000000..99ce4da --- /dev/null +++ b/internal/config/validate.go @@ -0,0 +1,372 @@ +package config + +import ( + "cmp" + "fmt" + "maps" + "math" + "net/url" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "time" + + "github.com/pelletier/go-toml/v2" +) + +// Ranges for the [sandbox] limits. +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"`, +} + +// Error is one problem in the config file. +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 every problem found in one config file, sorted by position. +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, so prefer the indexed path of + // the key at that position. + 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 = SellerFirstParty + case SellerFirstParty, SellerAny: + default: + v.errorf(key+".seller", "must be %q or %q (got %q)", SellerFirstParty, 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 "" +}