From 59e35c01f7909b82801428f059de3113fecacb90 Mon Sep 17 00:00:00 2001 From: Overlord Date: Tue, 13 Oct 2026 23:44:45 +0200 Subject: [PATCH 01/12] Update .gitignore --- .gitignore | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index 5b90e79..1dd4b20 100644 --- a/.gitignore +++ b/.gitignore @@ -1,27 +1,22 @@ -# ---> Go -# If you prefer the allow list template instead of the deny list, see community template: -# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore -# -# Binaries for programs and plugins +.* +!.git* +!.dockerignore + +*.md +!README.md + + *.exe *.exe~ *.dll *.so *.dylib -# Test binary, built with `go test -c` *.test - -# Output of the go coverage tool, specifically when used with LiteIDE *.out -# Dependency directories (remove the comment below to include it) -# vendor/ - -# Go workspace file go.work go.work.sum -# env file -.env +.env From 463c013056cf550e770892e6fd5deecf74f8ecfc Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 14 Oct 2026 00:22:19 +0200 Subject: [PATCH 02/12] Add config loading and validation. Strict dibs.toml decoding with line-numbered errors, defaults, and a [sandbox] section for the Lua call limits. Adds `dibs config validate` and `dibs version`. --- cmd/dibs/main.go | 159 ++++++++++++++ go.mod | 5 + go.sum | 2 + internal/config/config.go | 203 ++++++++++++++++++ internal/config/config_test.go | 336 +++++++++++++++++++++++++++++ internal/config/positions.go | 133 ++++++++++++ internal/config/validate.go | 372 +++++++++++++++++++++++++++++++++ 7 files changed, 1210 insertions(+) create mode 100644 cmd/dibs/main.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/config/config.go create mode 100644 internal/config/config_test.go create mode 100644 internal/config/positions.go create mode 100644 internal/config/validate.go 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 "" +} From 94bfc87e9d463917a6d35d0f73a9b0591208524d Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 14 Oct 2026 00:28:32 +0200 Subject: [PATCH 03/12] Refactor code style for improved readability and consistency. --- cmd/dibs/main.go | 56 +++++++-------- internal/config/config.go | 54 +++++++-------- internal/config/positions.go | 34 ++++----- internal/config/validate.go | 130 +++++++++++++++-------------------- 4 files changed, 118 insertions(+), 156 deletions(-) diff --git a/cmd/dibs/main.go b/cmd/dibs/main.go index 96e9701..8bcb09d 100644 --- a/cmd/dibs/main.go +++ b/cmd/dibs/main.go @@ -35,35 +35,31 @@ func main() { 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 + 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 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 - } + if _, ok := loadConfig(*configPath, stderr); !ok { return 1 } _, _ = fmt.Fprintln(stderr, "dibs: watching is not implemented yet") return 1 @@ -76,14 +72,10 @@ func runConfig(args []string, stdout, stderr io.Writer) int { } flags, configPath := newFlagSet("dibs config validate", stderr) - if err := flags.Parse(args[1:]); err != nil { - return 2 - } + if err := flags.Parse(args[1:]); err != nil { return 2 } cfg, ok := loadConfig(*configPath, stderr) - if !ok { - return 1 - } + if !ok { return 1 } urls := 0 for _, it := range cfg.Items { @@ -98,9 +90,7 @@ func runConfig(args []string, stdout, stderr io.Writer) int { } func plural(n int, noun string) string { - if n == 1 { - return "1 " + noun - } + if n == 1 { return "1 " + noun } return fmt.Sprintf("%d %ss", n, noun) } @@ -126,13 +116,13 @@ func loadConfig(path string, stderr io.Writer) (*config.Config, bool) { 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) + 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 diff --git a/internal/config/config.go b/internal/config/config.go index 2d9cf29..e33e779 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -29,10 +29,10 @@ const ( // Defaults for keys that may be omitted. const ( - DefaultInterval = 3 * time.Minute + DefaultInterval = 3 * time.Minute DefaultCooldown = 30 * time.Minute - DefaultSandboxTimeout = 2 * time.Second - DefaultSessionTimeout = 5 * time.Minute + DefaultSandboxTimeout = 2 * time.Second + DefaultSessionTimeout = 5 * time.Minute DefaultMemoryMB = 64 DefaultCallStack = 200 ) @@ -130,9 +130,7 @@ type Options struct { // DefaultPath returns dibs.toml in the user config dir. func DefaultPath() (string, error) { dir, err := os.UserConfigDir() - if err != nil { - return "", err - } + if err != nil { return "", err } return filepath.Join(dir, "dibs", "dibs.toml"), nil } @@ -140,22 +138,18 @@ func DefaultPath() (string, error) { // are returned together as Errors. func Load(path string, opts Options) (*Config, error) { data, err := os.ReadFile(path) - if err != nil { - return nil, err - } + if err != nil { return nil, err } abs, err := filepath.Abs(path) - if err != nil { - return nil, err - } + if err != nil { return nil, err } if opts.LookupEnv == nil { opts.LookupEnv = os.LookupEnv } cfg := &Config{ - Path: abs, - Notify: Notify{ + Path: abs, + Notify: Notify{ Desktop: true, Cooldown: Duration{Duration: DefaultCooldown}, }, @@ -177,27 +171,25 @@ func Load(path string, opts Options) (*Config, error) { 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" + 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) } - v.decodeError(&e, msg) - } - case errors.As(err, &decErr): - v.decodeError(decErr, "") - return nil, v.errs - default: - return nil, err + 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 - } + if len(v.errs) > 0 { return nil, v.errs } return cfg, nil } diff --git a/internal/config/positions.go b/internal/config/positions.go index e48f3fe..97978c4 100644 --- a/internal/config/positions.go +++ b/internal/config/positions.go @@ -24,18 +24,18 @@ func indexPositions(doc []byte) positions { 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) + 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) } } @@ -44,7 +44,7 @@ func indexPositions(doc []byte) positions { func (ps positions) keyValue(p *unstable.Parser, prefix string, kv *unstable.Node) { keys, first := keyParts(kv.Key()) - path := strings.Join(keys, ".") + path := strings.Join(keys, ".") if prefix != "" { path = prefix + "." + path @@ -84,9 +84,7 @@ func (ps positions) add(p *unstable.Parser, path string, n *unstable.Node) { // 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 - } + if pos, ok := ps[path]; ok { return pos, true } i := strings.LastIndexAny(path, ".[") if i < 0 { @@ -123,9 +121,7 @@ func keyParts(it unstable.Iterator) ([]string, *unstable.Node) { for it.Next() { n := it.Node() - if first == nil { - first = n - } + if first == nil { first = n } keys = append(keys, string(n.Data)) } diff --git a/internal/config/validate.go b/internal/config/validate.go index 99ce4da..3825042 100644 --- a/internal/config/validate.go +++ b/internal/config/validate.go @@ -19,9 +19,9 @@ import ( // Ranges for the [sandbox] limits. const ( minSandboxTimeout = 100 * time.Millisecond - maxSandboxTimeout = 30 * time.Second - minSessionTimeout = 10 * time.Second - maxSessionTimeout = 30 * time.Minute + maxSandboxTimeout = 30 * time.Second + minSessionTimeout = 10 * time.Second + maxSessionTimeout = 30 * time.Minute minMemoryMB = 4 maxMemoryMB = 1024 minCallStack = 50 @@ -50,7 +50,7 @@ var goTypeNames = map[string]string{ // Error is one problem in the config file. type Error struct { File string - Line int // 1-based; 0 if unknown + Line int // 1-based; 0 if unknown Col int Key string // e.g. "item[1].interval"; empty for file-level problems Msg string @@ -59,9 +59,7 @@ type Error struct { 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) - } + if e.Line > 0 { _, _ = fmt.Fprintf(&b, ":%d:%d", e.Line, e.Col) } b.WriteString(": ") if e.Key != "" { @@ -78,9 +76,7 @@ type Errors []Error func (es Errors) Error() string { lines := make([]string, len(es)) - for i, e := range es { - lines[i] = e.Error() - } + for i, e := range es { lines[i] = e.Error() } return strings.Join(lines, "\n") } @@ -93,9 +89,7 @@ type validator struct { 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 - } + if p, ok := v.pos.find(key); ok { e.Line, e.Col = p.Line, p.Column } v.errs = append(v.errs, e) } @@ -119,17 +113,11 @@ func (v *validator) decodeError(de *toml.DecodeError, msg string) { // types, into TOML terms. func friendlyDecodeMsg(msg string) string { m := typeErrRe.FindStringSubmatch(msg) - if m == nil { - return 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 - } + 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])) @@ -137,9 +125,7 @@ func friendlyDecodeMsg(msg string) string { func (v *validator) validate(cfg *Config, opts Options) { shops := map[string]bool{} - for _, b := range opts.Builtins { - shops[b] = true - } + for _, b := range opts.Builtins { shops[b] = true } v.plugins(cfg, shops) v.items(cfg, shops, opts.Builtins) @@ -180,10 +166,10 @@ func (v *validator) plugins(cfg *Config, shops map[string]bool) { 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) + 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) } } } @@ -195,27 +181,27 @@ func (v *validator) items(cfg *Config, shops map[string]bool, builtins []string) } names := map[string]int{} - urls := map[string]string{} + urls := map[string]string{} for i := range cfg.Items { - it := &cfg.Items[i] + 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 + 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, ", ")) + 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 { @@ -252,26 +238,26 @@ func (v *validator) items(cfg *Config, shops map[string]bool, builtins []string) 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") + 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) + 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) + 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) } } } @@ -286,11 +272,11 @@ func (v *validator) accounts(cfg *Config, shops map[string]bool, lookupEnv func( } 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) + 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 != "" { @@ -300,9 +286,7 @@ func (v *validator) accounts(cfg *Config, shops map[string]bool, lookupEnv func( } for _, f := range []struct{ name, raw string }{{"login_url", acc.LoginURL}, {"cart_url", acc.CartURL}} { - if f.raw == "" { - continue - } + if f.raw == "" { continue } if msg := checkURL(f.raw); msg != "" { v.errorf(key+"."+f.name, "%s", msg) @@ -324,11 +308,11 @@ func (v *validator) notify(n *Notify) { } 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) + 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) } } @@ -360,12 +344,12 @@ func durationRange(v *validator, key string, d, lo, hi time.Duration) { 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) + 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 "" From f90ef18f90a1c9049b4850daea7eeb3bcbd90563 Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 14 Oct 2026 00:48:23 +0200 Subject: [PATCH 04/12] Add tls-client fetch pipeline. Add Chrome 152 fingerprint and navigation headers, Accept-Language by TLD, challenge/block classification, and a cookie jar that can be saved and exported per host. Bumps x/net, x/text, x/crypto and circl for govulncheck findings. Co-Authored-By: Claude Opus 5.5 --- go.mod | 23 ++- go.sum | 50 +++++++ internal/config/positions.go | 33 +++-- internal/fetch/browser.go | 131 +++++++++++++++++ internal/fetch/classify.go | 99 +++++++++++++ internal/fetch/client.go | 116 +++++++++++++++ internal/fetch/fetch_test.go | 270 +++++++++++++++++++++++++++++++++++ internal/fetch/jar.go | 212 +++++++++++++++++++++++++++ 8 files changed, 918 insertions(+), 16 deletions(-) create mode 100644 internal/fetch/browser.go create mode 100644 internal/fetch/classify.go create mode 100644 internal/fetch/client.go create mode 100644 internal/fetch/fetch_test.go create mode 100644 internal/fetch/jar.go diff --git a/go.mod b/go.mod index 16fa08b..f52d780 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,25 @@ module git.security-command.org/Overlord/dibs go 1.26.0 -require github.com/pelletier/go-toml/v2 v2.4.3 +require ( + github.com/bogdanfinn/fhttp v0.6.9 + github.com/bogdanfinn/tls-client v1.16.0 + github.com/pelletier/go-toml/v2 v2.4.3 + golang.org/x/net v0.60.0 +) + +require ( + github.com/andybalholm/brotli v1.2.0 // indirect + github.com/bdandy/go-errors v1.2.2 // indirect + github.com/bdandy/go-socks4 v1.2.3 // indirect + github.com/bogdanfinn/quic-go-utls v1.0.10-utls // indirect + github.com/bogdanfinn/utls v1.7.8-barnius // indirect + github.com/bogdanfinn/websocket v1.5.6-barnius // indirect + github.com/cloudflare/circl v1.6.5 // indirect + github.com/klauspost/compress v1.18.2 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect + golang.org/x/crypto v0.57.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect +) diff --git a/go.sum b/go.sum index ddaf7d6..588e974 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,52 @@ +github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= +github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q= +github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM= +github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic= +github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI= +github.com/bogdanfinn/fhttp v0.6.9 h1:F9MsWR1K6JMRlXN4Q/MfjYmptr29nCdycQo+OPBG5U0= +github.com/bogdanfinn/fhttp v0.6.9/go.mod h1:7phoj3f/q54WuiTnCTlAhEoaVcdlruKkSzCSD47LzHk= +github.com/bogdanfinn/quic-go-utls v1.0.10-utls h1:oZN+J3OKMmWaVbI/sx4ULvHiAXbWJKVcvEFW4fkybMU= +github.com/bogdanfinn/quic-go-utls v1.0.10-utls/go.mod h1:bBLJ2Vy68Q7y6VfbG9czd825rTcQua7n+y12RM9Q588= +github.com/bogdanfinn/tls-client v1.16.0 h1:km3YLI6CMRLZnfrC+hGStePPryIicd3hoxFQvHB1itY= +github.com/bogdanfinn/tls-client v1.16.0/go.mod h1:TxbiXlpZhNN5xmxzsr3KhNAeqoEEPJafwgBbyp26Phc= +github.com/bogdanfinn/utls v1.7.8-barnius h1:wRT83mP4hmuMM1/lIpLKKhzaEuyEKjux7VSj7XHFXdg= +github.com/bogdanfinn/utls v1.7.8-barnius/go.mod h1:o5v09jf+9ayMEfcP+8sssNdSMm278cyhBV25H8jb5Lw= +github.com/bogdanfinn/websocket v1.5.6-barnius h1:QpdWVEZ9rKtcT7C2pU19uE2KQw2XevuKTDTzLxfDi/I= +github.com/bogdanfinn/websocket v1.5.6-barnius/go.mod h1:41/rXLDWpqJ5A4gOKSY/z4NLbW/hHZHneRcYM0kbpxA= +github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA= +github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= +github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= 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= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc= +github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng= +github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= +github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= +go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/config/positions.go b/internal/config/positions.go index 97978c4..6c4ec40 100644 --- a/internal/config/positions.go +++ b/internal/config/positions.go @@ -22,11 +22,12 @@ func indexPositions(doc []byte) positions { // A parse error stops the index early. The decoder reports it. for p.NextExpression() { e := p.Expression() + if e == nil { continue } switch e.Kind { case unstable.Table, unstable.ArrayTable: keys, first := keyParts(e.Key()) - path := strings.Join(keys, ".") + path := strings.Join(keys, ".") if e.Kind == unstable.ArrayTable { n := arrays[path] arrays[path]++ @@ -36,6 +37,8 @@ func indexPositions(doc []byte) positions { ps.add(&p, path, first) case unstable.KeyValue: ps.keyValue(&p, prefix, e) + default: + // Comments and other expressions have no key to record. } } @@ -56,21 +59,21 @@ func (ps positions) keyValue(p *unstable.Parser, prefix string, kv *unstable.Nod 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) + 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) } + } + default: + // Scalars have no nested keys. } } diff --git a/internal/fetch/browser.go b/internal/fetch/browser.go new file mode 100644 index 0000000..4eccdd6 --- /dev/null +++ b/internal/fetch/browser.go @@ -0,0 +1,131 @@ +package fetch + +import ( + "fmt" + "net/url" + "runtime" + "strings" + + http "github.com/bogdanfinn/fhttp" + "github.com/bogdanfinn/tls-client/profiles" + "golang.org/x/net/publicsuffix" +) + +// chromeMajor must match chromeProfile: the TLS and HTTP/2 fingerprint come +// from the profile, the headers from the version. Bump both together when +// updating tls-client. +const chromeMajor = 152 + +var chromeProfile = profiles.Chrome_152 + +// Browser is the browser that requests claim to come from. +type Browser struct { + Profile profiles.ClientProfile + Major int + UserAgent string + Platform string // sec-ch-ua-platform, without quotes +} + +// DefaultBrowser returns desktop Chrome on the current OS, so that cookies +// a real browser on this machine obtains later stay valid for us. +func DefaultBrowser() Browser { + ua, platform := "Windows NT 10.0; Win64; x64", "Windows" + + switch runtime.GOOS { + case "darwin": + ua, platform = "Macintosh; Intel Mac OS X 10_15_7", "macOS" + case "linux": + ua, platform = "X11; Linux x86_64", "Linux" + default: + // Windows, and anything else, which Chrome supports no better. + } + + return Browser{ + Profile: chromeProfile, + Major: chromeMajor, + UserAgent: fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.0.0 Safari/537.36", ua, chromeMajor), + Platform: platform, + } +} + +// navigationHeaders are the headers Chrome sends when the user opens u by +// typing it or from a bookmark, in Chrome's order. +func (b Browser) navigationHeaders(u *url.URL) http.Header { + return http.Header{ + "sec-ch-ua": {secCHUA(b.Major)}, + "sec-ch-ua-mobile": {"?0"}, + "sec-ch-ua-platform": {`"` + b.Platform + `"`}, + "upgrade-insecure-requests": {"1"}, + "user-agent": {b.UserAgent}, + "accept": {"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"}, + "sec-fetch-site": {"none"}, + "sec-fetch-mode": {"navigate"}, + "sec-fetch-user": {"?1"}, + "sec-fetch-dest": {"document"}, + "accept-encoding": {"gzip, deflate, br, zstd"}, + "accept-language": {acceptLanguage(u.Hostname())}, + "priority": {"u=0, i"}, + http.HeaderOrderKey: { + "sec-ch-ua", + "sec-ch-ua-mobile", + "sec-ch-ua-platform", + "upgrade-insecure-requests", + "user-agent", + "accept", + "sec-fetch-site", + "sec-fetch-mode", + "sec-fetch-user", + "sec-fetch-dest", + "accept-encoding", + "accept-language", + "cookie", + "priority", + }, + } +} + +// secCHUA builds Chrome's sec-ch-ua brand list. Chrome derives the GREASE +// brand and the brand order from its major version (GenerateBrandVersionList +// in Chromium's user_agent_utils.cc), so a fixed string would give us away +// after an update. +func secCHUA(major int) string { + chars := []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"} + versions := []string{"8", "99", "24"} + orders := [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} + + grease := fmt.Sprintf(`"Not%sA%sBrand";v="%s"`, chars[major%len(chars)], chars[(major+1)%len(chars)], versions[major%len(versions)]) + order := orders[major%len(orders)] + + var brands [3]string + brands[order[0]] = grease + brands[order[1]] = fmt.Sprintf(`"Chromium";v="%d"`, major) + brands[order[2]] = fmt.Sprintf(`"Google Chrome";v="%d"`, major) + + return strings.Join(brands[:], ", ") +} + +// languages maps a public suffix to the Accept-Language a local shopper's +// browser would send. +var languages = map[string]string{ + "de": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7", + "at": "de-AT,de;q=0.9,en-US;q=0.8,en;q=0.7", + "ch": "de-CH,de;q=0.9,en-US;q=0.8,en;q=0.7", + "co.uk": "en-GB,en;q=0.9", + "uk": "en-GB,en;q=0.9", + "ie": "en-IE,en;q=0.9", + "fr": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7", + "be": "nl-BE,nl;q=0.9,fr-BE;q=0.8,fr;q=0.7,en;q=0.6", + "it": "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7", + "es": "es-ES,es;q=0.9,en-US;q=0.8,en;q=0.7", + "nl": "nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7", + "pl": "pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7", + "se": "sv-SE,sv;q=0.9,en-US;q=0.8,en;q=0.7", + "com": "en-US,en;q=0.9", +} + +func acceptLanguage(host string) string { + suffix, _ := publicsuffix.PublicSuffix(strings.ToLower(host)) + if lang, ok := languages[suffix]; ok { return lang } + + return languages["com"] +} diff --git a/internal/fetch/classify.go b/internal/fetch/classify.go new file mode 100644 index 0000000..15157fb --- /dev/null +++ b/internal/fetch/classify.go @@ -0,0 +1,99 @@ +package fetch + +import ( + "bytes" + "net/http" + "strings" +) + +// Verdict says what a response means for the watcher. +type Verdict int + +const ( + // OK is a page the plugin can parse. + OK Verdict = iota + // NotFound (404, 410) means the item is not available, never an error. + NotFound + // Challenge is a bot check that a real browser may clear. + Challenge + // Blocked is a refusal without a recognisable challenge, e.g. a plain 403 + // or 429. Back off and retry later. + Blocked + // HTTPError is any other non-2xx status. + HTTPError +) + +func (v Verdict) String() string { + switch v { + case OK: + return "ok" + case NotFound: + return "not-found" + case Challenge: + return "challenge" + case Blocked: + return "blocked" + case HTTPError: + return "http-error" + default: + return "unknown" + } +} + +type marker struct { + name string + needle string +} + +// strongMarkers only appear on bot check pages, so they count whatever the +// status. Amazon answers its captcha with a 200, for example. +var strongMarkers = []marker{ + {"cloudflare", "window._cf_chl_opt"}, + {"amazon-captcha", `action="/errors/validateCaptcha"`}, + {"datadome", "geo.captcha-delivery.com"}, + {"perimeterx", `id="px-captcha"`}, +} + +// weakMarkers also show up on normal pages (Cloudflare injects its +// challenge-platform script, shops embed Turnstile in forms), so they only +// count on a refusal status. +var weakMarkers = []marker{ + {"cloudflare", "Just a moment..."}, + {"cloudflare", "/cdn-cgi/challenge-platform/"}, + {"turnstile", "challenges.cloudflare.com/turnstile"}, + {"recaptcha", "www.google.com/recaptcha/"}, + {"hcaptcha", "hcaptcha.com/1/api.js"}, + {"captcha", "captcha"}, +} + +// classify decides the verdict for a response. For Challenge it also names +// the bot check found. +func classify(status int, header http.Header, finalURL string, body []byte) (Verdict, string) { + lower := bytes.ToLower(body) + + if header.Get("cf-mitigated") == "challenge" { return Challenge, "cloudflare" } + if strings.Contains(finalURL, "/errors/validateCaptcha") { return Challenge, "amazon-captcha" } + if name := findMarker(lower, strongMarkers); name != "" { return Challenge, name } + + switch { + case status >= 200 && status < 300: + return OK, "" + case status == http.StatusNotFound || status == http.StatusGone: + return NotFound, "" + case status == http.StatusForbidden || status == http.StatusTooManyRequests || status == http.StatusServiceUnavailable: + if name := findMarker(lower, weakMarkers); name != "" { return Challenge, name } + + return Blocked, "" + default: + return HTTPError, "" + } +} + +// findMarker returns the name of the first marker in the lowercased body. +func findMarker(lower []byte, markers []marker) string { + for _, m := range markers { + if bytes.Contains(lower, []byte(strings.ToLower(m.needle))) { return m.name } + } + + return "" +} diff --git a/internal/fetch/client.go b/internal/fetch/client.go new file mode 100644 index 0000000..765f08c --- /dev/null +++ b/internal/fetch/client.go @@ -0,0 +1,116 @@ +// Package fetch downloads product pages with a browser-like TLS and HTTP/2 +// fingerprint and tells real pages apart from bot checks. +package fetch + +import ( + "context" + "errors" + "fmt" + "io" + stdhttp "net/http" + "net/url" + "time" + + http "github.com/bogdanfinn/fhttp" + tlsclient "github.com/bogdanfinn/tls-client" +) + +const ( + DefaultTimeout = 30 * time.Second + DefaultMaxBody = 16 << 20 +) + +// ErrBodyTooLarge is returned when a response exceeds Options.MaxBody. +var ErrBodyTooLarge = errors.New("response body too large") + +type Options struct { + // Browser to impersonate. Defaults to DefaultBrowser(). + Browser *Browser + // Jar holds the cookies. Defaults to a new, empty jar. + Jar *Jar + // Timeout per request, including redirects. Defaults to DefaultTimeout. + Timeout time.Duration + // MaxBody is the largest body read, after decompression. Defaults to + // DefaultMaxBody. + MaxBody int64 +} + +// Client fetches pages. It is safe for concurrent use. +type Client struct { + http tlsclient.HttpClient + browser Browser + jar *Jar + maxBody int64 +} + +// Response is a fetched page. +type Response struct { + URL string // as requested + FinalURL string // after redirects + Status int + Header stdhttp.Header + Body []byte + Verdict Verdict + // Challenge names the bot check found, such as "cloudflare", when + // Verdict is Challenge. + Challenge string + Elapsed time.Duration +} + +func New(opts Options) (*Client, error) { + browser := DefaultBrowser() + if opts.Browser != nil { browser = *opts.Browser } + if opts.Jar == nil { opts.Jar = NewJar() } + if opts.Timeout == 0 { opts.Timeout = DefaultTimeout } + if opts.MaxBody == 0 { opts.MaxBody = DefaultMaxBody } + + hc, err := tlsclient.NewHttpClient(nil, + tlsclient.WithClientProfile(browser.Profile), + tlsclient.WithRandomTLSExtensionOrder(), + tlsclient.WithCookieJar(opts.Jar), + tlsclient.WithTimeoutMilliseconds(int(opts.Timeout/time.Millisecond)), + ) + if err != nil { return nil, fmt.Errorf("creating HTTP client: %w", err) } + + return &Client{http: hc, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil +} + +// Jar returns the client's cookie jar. +func (c *Client) Jar() *Jar { return c.jar } + +// Get fetches rawURL the way Chrome opens a bookmark. A response with a bad +// status is not an error: check Verdict. +func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) { + u, err := url.Parse(rawURL) + if err != nil { return nil, err } + if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { return nil, err } + req.Header = c.browser.navigationHeaders(u) + + start := time.Now() + resp, err := c.http.Do(req) + if err != nil { return nil, err } + + // fhttp's decompressing readers close the raw body with them. + body := resp.Body + if !resp.Uncompressed && resp.Header.Get("Content-Encoding") != "" { body = http.DecompressBody(resp) } + defer func() { _ = body.Close() }() + + data, err := io.ReadAll(io.LimitReader(body, c.maxBody+1)) + if err != nil { return nil, fmt.Errorf("reading body: %w", err) } + if int64(len(data)) > c.maxBody { return nil, fmt.Errorf("%w: more than %d bytes", ErrBodyTooLarge, c.maxBody) } + + r := &Response{ + URL: rawURL, + FinalURL: resp.Request.URL.String(), + Status: resp.StatusCode, + Header: stdhttp.Header(resp.Header), + Body: data, + Elapsed: time.Since(start), + } + r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body) + + return r, nil +} diff --git a/internal/fetch/fetch_test.go b/internal/fetch/fetch_test.go new file mode 100644 index 0000000..32ccb85 --- /dev/null +++ b/internal/fetch/fetch_test.go @@ -0,0 +1,270 @@ +package fetch + +import ( + "compress/gzip" + "context" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + fhttp "github.com/bogdanfinn/fhttp" +) + +func TestSecCHUA(t *testing.T) { + // Real values, from tls-client's examples. + for major, want := range map[int]string{ + 105: `"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"`, + 107: `"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"`, + } { + if got := secCHUA(major); got != want { t.Errorf("secCHUA(%d) = %s, want %s", major, got, want) } + } +} + +func TestAcceptLanguage(t *testing.T) { + for host, want := range map[string]string{ + "www.amazon.de": "de-DE,", + "www.Amazon.co.uk": "en-GB,", + "www.amazon.fr": "fr-FR,", + "www.amazon.it": "it-IT,", + "www.amazon.es": "es-ES,", + "www.amazon.nl": "nl-NL,", + "www.amazon.com": "en-US,", + "www.amazon.co.jp": "en-US,", + "127.0.0.1": "en-US,", + } { + if got := acceptLanguage(host); !strings.HasPrefix(got, want) { t.Errorf("acceptLanguage(%q) = %q, want prefix %q", host, got, want) } + } +} + +func TestDefaultBrowserMatchesProfile(t *testing.T) { + b := DefaultBrowser() + if !strings.Contains(b.UserAgent, "Chrome/152.0.0.0") { t.Errorf("user agent %q does not match Chrome %d", b.UserAgent, b.Major) } + + want := map[string]string{"windows": "Windows", "darwin": "macOS", "linux": "Linux"}[runtime.GOOS] + if want != "" && b.Platform != want { t.Errorf("platform = %q, want %q", b.Platform, want) } +} + +func TestClassify(t *testing.T) { + cf := http.Header{"Cf-Mitigated": {"challenge"}} + + for name, tc := range map[string]struct { + status int + header http.Header + finalURL string + body string + verdict Verdict + challenge string + }{ + "product page": {200, nil, "https://www.amazon.de/dp/X", "Metro", OK, ""}, + "cf script on normal page": {200, nil, "", `", Challenge, "cloudflare"}, + "cf title": {403, nil, "", "Just a moment...", Challenge, "cloudflare"}, + "amazon captcha 200": {200, nil, "", `
`, Challenge, "amazon-captcha"}, + "amazon captcha url": {200, nil, "https://www.amazon.de/errors/validateCaptcha?x=1", "", Challenge, "amazon-captcha"}, + "datadome": {403, nil, "", `