Compare commits

...
4 Commits
Author SHA1 Message Date
OverlordandClaude Bot bb010356a0 Add Lua plugin host, built-in amazon plugin and dibs check.
Sandboxed gopher-lua with time, memory and call-stack limits from
[sandbox], a goquery-backed doc API, price parsing, and the 'check',
'plugin test' and 'fixtures' commands. Sellers are first_party,
fulfilled (shipped by the shop) or third_party, and items accept
fulfilled by default; used-only offers are not available. Plugin tests
run on real pages that 'dibs fixtures' fetches into an untracked
directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 01:46:03 +02:00
OverlordandClaude Bot f90ef18f90 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 <noreply@anthropic.com>
2026-10-14 00:48:23 +02:00
Overlord 94bfc87e9d Refactor code style for improved readability and consistency. 2026-10-14 00:28:32 +02:00
Overlord 463c013056 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`.
2026-10-14 00:22:19 +02:00
33 changed files with 4144 additions and 0 deletions

No files matched your search

+3
View File
@@ -20,3 +20,6 @@ go.work.sum
.env
# Real shop pages fetched by 'dibs fixtures'.
testdata/*/pages/
+148
View File
@@ -0,0 +1,148 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/fetch"
"git.security-command.org/Overlord/dibs/internal/plugin"
)
// runCheck implements `dibs check [--shop NAME] <url>`: one fetch and parse,
// printed as JSON.
func runCheck(args []string, stdout, stderr io.Writer) int {
flags, configPath := newFlagSet("dibs check", stderr)
shop := flags.String("shop", "", "plugin to use (default: the first whose matches() accepts the URL)")
pos, ok := parseArgs(flags, args)
if !ok { return 2 }
if len(pos) != 1 {
_, _ = fmt.Fprintf(stderr, "dibs check: expected one URL\n\n%s", usage)
return 2
}
cfg, ok := loadOptionalConfig(*configPath, stderr)
if !ok { return 1 }
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
logger := slog.New(slog.NewTextHandler(stderr, nil))
host, err := newHost(cfg, logger)
if err != nil { return fail(stderr, "check", err) }
defer host.Close()
url := pos[0]
p, err := pickPlugin(ctx, host, *shop, url)
if err != nil { return fail(stderr, "check", err) }
fetchURL, err := p.Normalize(ctx, url)
if err != nil { return fail(stderr, "check", err) }
client, err := fetch.New(fetch.Options{})
if err != nil { return fail(stderr, "check", err) }
resp, err := client.Get(ctx, fetchURL)
if err != nil { return fail(stderr, "check", err) }
report, err := plugin.Evaluate(ctx, p, url, resp)
printJSON(stdout, report)
if err != nil { return fail(stderr, "check", err) }
return 0
}
// runPlugin implements `dibs plugin test [--status CODE] <file.lua>
// <fixture.html> [url]`: run a plugin on a saved page.
func runPlugin(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 || args[0] != "test" {
_, _ = fmt.Fprintf(stderr, "dibs plugin: expected \"test\"\n\n%s", usage)
return 2
}
flags, configPath := newFlagSet("dibs plugin test", stderr)
status := flags.Int("status", 200, "HTTP status the page was served with")
pos, ok := parseArgs(flags, args[1:])
if !ok { return 2 }
if len(pos) < 2 || len(pos) > 3 {
_, _ = fmt.Fprintf(stderr, "dibs plugin test: expected <file.lua> <fixture.html> [url]\n\n%s", usage)
return 2
}
cfg, ok := loadOptionalConfig(*configPath, stderr)
if !ok { return 1 }
code, err := os.ReadFile(pos[0])
if err != nil { return fail(stderr, "plugin test", err) }
page, err := os.ReadFile(pos[1])
if err != nil { return fail(stderr, "plugin test", err) }
url := "https://example.invalid/"
if len(pos) == 3 { url = pos[2] }
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(stderr, nil))
p, err := plugin.Load("", pos[0], code, limits(cfg), logger)
if err != nil { return fail(stderr, "plugin test", err) }
defer p.Close()
fetchURL, err := p.Normalize(ctx, url)
if err != nil { return fail(stderr, "plugin test", err) }
report, err := plugin.Evaluate(ctx, p, url, fetch.NewResponse(fetchURL, fetchURL, *status, nil, page))
printJSON(stdout, report)
if err != nil { return fail(stderr, "plugin test", err) }
return 0
}
func newHost(cfg *config.Config, logger *slog.Logger) (*plugin.Host, error) {
var user map[string]string
if cfg != nil { user = cfg.Plugins }
return plugin.NewHost(user, limits(cfg), logger)
}
func limits(cfg *config.Config) plugin.Limits {
if cfg == nil { return plugin.DefaultLimits() }
return plugin.LimitsFrom(cfg.Sandbox)
}
func pickPlugin(ctx context.Context, host *plugin.Host, shop, url string) (*plugin.Plugin, error) {
if shop == "" {
p, err := host.ForURL(ctx, url)
if errors.Is(err, plugin.ErrNoPlugin) { return nil, fmt.Errorf("%w; pick one with --shop", err) }
return p, err
}
p, ok := host.Plugin(shop)
if !ok { return nil, fmt.Errorf("no plugin named %q (built-in: %v)", shop, plugin.Builtins()) }
return p, nil
}
func printJSON(w io.Writer, v any) {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
_ = enc.Encode(v)
}
func fail(stderr io.Writer, cmd string, err error) int {
_, _ = fmt.Fprintf(stderr, "dibs %s: %v\n", cmd, err)
return 1
}
+126
View File
@@ -0,0 +1,126 @@
package main
import (
"context"
"fmt"
"io"
"log/slog"
"net/url"
"os"
"os/signal"
"time"
"git.security-command.org/Overlord/dibs/internal/fetch"
"git.security-command.org/Overlord/dibs/internal/fixtures"
"git.security-command.org/Overlord/dibs/internal/plugin"
)
// fixtureSpacing is the pause between two requests to the same host.
const fixtureSpacing = 12 * time.Second
// runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: fetch the
// pages listed in DIR/<shop>/cases.toml for the plugin tests.
func runFixtures(args []string, stdout, stderr io.Writer) int {
flags, configPath := newFlagSet("dibs fixtures", stderr)
dir := flags.String("dir", "testdata", "directory with <shop>/cases.toml files")
only := flags.String("only", "", "fetch only the case with this name")
pos, ok := parseArgs(flags, args)
if !ok { return 2 }
if len(pos) > 0 {
_, _ = fmt.Fprintf(stderr, "dibs fixtures: unexpected argument %q\n\n%s", pos[0], usage)
return 2
}
suites, err := fixtures.Load(*dir)
if err != nil { return fail(stderr, "fixtures", err) }
if len(suites) == 0 { return fail(stderr, "fixtures", fmt.Errorf("no */cases.toml in %s", *dir)) }
cfg, ok := loadOptionalConfig(*configPath, stderr)
if !ok { return 1 }
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
host, err := newHost(cfg, slog.New(slog.NewTextHandler(stderr, nil)))
if err != nil { return fail(stderr, "fixtures", err) }
defer host.Close()
client, err := fetch.New(fetch.Options{})
if err != nil { return fail(stderr, "fixtures", err) }
lastRequest := map[string]time.Time{}
failed := 0
for _, suite := range suites {
p, ok := host.Plugin(suite.Shop)
if !ok {
_, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: no plugin named %q, skipping\n", suite.Dir, suite.Shop)
continue
}
for _, c := range suite.Cases {
if *only != "" && c.Name != *only { continue }
if err := fetchFixture(ctx, client, p, suite, c, lastRequest, stdout); err != nil {
if ctx.Err() != nil { return fail(stderr, "fixtures", ctx.Err()) }
_, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: %v\n", c.Name, err)
failed++
}
}
}
if failed > 0 { return 1 }
return 0
}
func fetchFixture(ctx context.Context, client *fetch.Client, p *plugin.Plugin, suite fixtures.Suite, c fixtures.Case, lastRequest map[string]time.Time, stdout io.Writer) error {
fetchURL, err := p.Normalize(ctx, c.URL)
if err != nil { return err }
u, err := url.Parse(fetchURL)
if err != nil { return err }
if wait := time.Until(lastRequest[u.Host].Add(fixtureSpacing)); wait > 0 {
select {
case <-time.After(wait):
case <-ctx.Done():
return ctx.Err()
}
}
lastRequest[u.Host] = time.Now()
resp, err := client.Get(ctx, fetchURL)
if err != nil { return err }
report, err := plugin.Evaluate(ctx, p, c.URL, resp)
if err != nil { return err }
// Saved reports must not depend on how fast the shop answered.
report.ElapsedMS = 0
if err := suite.Save(c, resp.Body, report); err != nil { return err }
_, _ = fmt.Fprintf(stdout, "%-20s %s\n", c.Name, summary(report))
_, _ = fmt.Fprintf(stdout, "%-20s %s\n\n", "", c.Note)
return nil
}
func summary(r *plugin.Report) string {
s := r.Verdict
if r.Challenge != "" { s += " (" + r.Challenge + ")" }
if r.Result == nil { return s }
res := r.Result
avail := "unavailable"
if res.Available { avail = "AVAILABLE" }
price := "no price"
if res.Price != nil { price = fmt.Sprintf("%.2f %s", *res.Price, res.Currency) }
return fmt.Sprintf("%s, %s, %s, seller %s", s, avail, price, res.Seller)
}
+177
View File
@@ -0,0 +1,177 @@
// 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"
"git.security-command.org/Overlord/dibs/internal/plugin"
)
// version is set at build time with -ldflags "-X main.version=...".
var version = "dev"
const usage = `Usage:
dibs [--config FILE] [--headless] watch items (TUI unless --headless)
dibs check [--shop NAME] <url> fetch and parse one URL, print JSON
dibs plugin test [--status CODE] <file.lua> <fixture.html> [url]
dibs config validate [--config FILE]
dibs fixtures [--dir testdata] [--only NAME] fetch real pages for the plugin tests
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":
return runCheck(args[1:], stdout, stderr)
case "plugin":
return runPlugin(args[1:], stdout, stderr)
case "fixtures":
return runFixtures(args[1:], stdout, stderr)
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: plugin.Builtins()})
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
}
// loadOptionalConfig is loadConfig for commands that also work without a
// config: with no --config and no file at the default path it returns nil.
func loadOptionalConfig(path string, stderr io.Writer) (*config.Config, bool) {
if path == "" {
def, err := config.DefaultPath()
if err != nil { return nil, true }
if _, err := os.Stat(def); errors.Is(err, fs.ErrNotExist) { return nil, true }
}
return loadConfig(path, stderr)
}
// parseArgs parses flags anywhere among the arguments, so that
// "dibs check URL --shop amazon" works too, and returns the positional ones.
func parseArgs(flags *flag.FlagSet, args []string) ([]string, bool) {
var pos []string
for {
if err := flags.Parse(args); err != nil { return nil, false }
if flags.NArg() == 0 { return pos, true }
pos = append(pos, flags.Arg(0))
args = flags.Args()[1:]
}
}
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)
}
+29
View File
@@ -0,0 +1,29 @@
module git.security-command.org/Overlord/dibs
go 1.26.0
require (
github.com/PuerkitoBio/goquery v1.13.0
github.com/andybalholm/cascadia v1.3.4
github.com/bogdanfinn/fhttp v0.6.9
github.com/bogdanfinn/tls-client v1.16.0
github.com/pelletier/go-toml/v2 v2.4.3
github.com/yuin/gopher-lua v1.1.2
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
)
+58
View File
@@ -0,0 +1,58 @@
github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM=
github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g=
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
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=
github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA=
github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8=
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=
+228
View File
@@ -0,0 +1,228 @@
// 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 (
// Seller policies for an item: sold by the shop itself; sold or at least
// shipped by it (e.g. Fulfilled by Amazon); or anyone.
SellerFirstParty = "first_party"
SellerFulfilled = "fulfilled"
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
// DefaultSeller also accepts marketplace offers the shop ships (such as
// Fulfilled by Amazon), which is how many listings are sold.
DefaultSeller = SellerFulfilled
)
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 }
// sellerRanks orders the sellers a plugin reports, from most to least
// trusted. The values match plugin.Seller*.
var sellerRanks = map[string]int{
"first_party": 0,
"fulfilled": 1,
"third_party": 2,
"unknown": 3,
}
// policyRanks is the least trusted seller each policy still accepts.
var policyRanks = map[string]int{
SellerFirstParty: 0,
SellerFulfilled: 1,
SellerAny: 3,
}
// AcceptsSeller reports whether an offer from seller, as a plugin reports it,
// passes the item's seller policy. The policies are ordered: "fulfilled"
// accepts everything "first_party" does, and "any" accepts every seller.
func (it Item) AcceptsSeller(seller string) bool {
rank, ok := sellerRanks[seller]
if !ok { return false }
return rank <= policyRanks[it.Seller]
}
// 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
}
+353
View File
@@ -0,0 +1,353 @@
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"
seller = "fulfilled"
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))
}
if s := cfg.Items[1].Seller; s != SellerFulfilled { t.Errorf("item[1].seller: got %q, want fulfilled", s) }
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 != SellerFulfilled || 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", "fulfilled" 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)
}
}
func TestAcceptsSeller(t *testing.T) {
for policy, want := range map[string]map[string]bool{
SellerFirstParty: {"first_party": true, "fulfilled": false, "third_party": false, "unknown": false},
SellerFulfilled: {"first_party": true, "fulfilled": true, "third_party": false, "unknown": false},
SellerAny: {"first_party": true, "fulfilled": true, "third_party": true, "unknown": true},
} {
for seller, ok := range want {
if got := (Item{Seller: policy}).AcceptsSeller(seller); got != ok { t.Errorf("policy %s, seller %s: got %v, want %v", policy, seller, got, ok) }
}
if (Item{Seller: policy}).AcceptsSeller("amazon") { t.Errorf("policy %s accepts an invalid seller", policy) }
}
}
+132
View File
@@ -0,0 +1,132 @@
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()
if e == nil { continue }
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)
default:
// Comments and other expressions have no key to record.
}
}
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) }
}
default:
// Scalars have no nested keys.
}
}
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
}
+356
View File
@@ -0,0 +1,356 @@
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 = DefaultSeller
case SellerFirstParty, SellerFulfilled, SellerAny:
default:
v.errorf(key+".seller", "must be %q, %q or %q (got %q)", SellerFirstParty, SellerFulfilled, SellerAny, it.Seller)
}
switch {
case !it.Interval.IsSet():
it.Interval.Duration = DefaultInterval
case it.Interval.Duration < MinInterval:
v.errorf(key+".interval", "must be at least %s (got %s)", MinInterval, it.Interval)
}
}
}
func (v *validator) accounts(cfg *Config, shops map[string]bool, lookupEnv func(string) (string, bool)) {
for _, shop := range slices.Sorted(maps.Keys(cfg.Accounts)) {
acc := cfg.Accounts[shop]
key := "accounts." + shop
if !shops[shop] {
v.errorf(key, "no plugin named %q", shop)
}
switch acc.CartMode {
case "":
acc.CartMode = CartModeDeeplink
case CartModeDeeplink, CartModeSession:
default:
v.errorf(key+".cart_mode", "must be %q or %q (got %q)", CartModeDeeplink, CartModeSession, acc.CartMode)
}
if acc.PasswordEnv != "" {
if val, ok := lookupEnv(acc.PasswordEnv); !ok || val == "" {
v.errorf(key+".password_env", "environment variable %s is not set", acc.PasswordEnv)
}
}
for _, f := range []struct{ name, raw string }{{"login_url", acc.LoginURL}, {"cart_url", acc.CartURL}} {
if f.raw == "" { continue }
if msg := checkURL(f.raw); msg != "" {
v.errorf(key+"."+f.name, "%s", msg)
}
}
cfg.Accounts[shop] = acc
}
}
func (v *validator) notify(n *Notify) {
for i, wh := range n.Webhooks {
key := fmt.Sprintf("notify.webhooks[%d]", i)
if wh.URL == "" {
v.errorf(key+".url", "missing required key")
} else if msg := checkURL(wh.URL); msg != "" {
v.errorf(key+".url", "%s", msg)
}
switch wh.Format {
case FormatDiscord, FormatNtfy, FormatJSON:
case "":
v.errorf(key+".format", "missing required key (%q, %q or %q)", FormatDiscord, FormatNtfy, FormatJSON)
default:
v.errorf(key+".format", "must be %q, %q or %q (got %q)", FormatDiscord, FormatNtfy, FormatJSON, wh.Format)
}
}
if n.Cooldown.Duration < 0 {
v.errorf("notify.cooldown", "must not be negative (got %s)", n.Cooldown)
}
}
func (v *validator) sandbox(s *Sandbox) {
durationRange(v, "sandbox.timeout", s.Timeout.Duration, minSandboxTimeout, maxSandboxTimeout)
durationRange(v, "sandbox.session_timeout", s.SessionTimeout.Duration, minSessionTimeout, maxSessionTimeout)
if s.MemoryMB < minMemoryMB || s.MemoryMB > maxMemoryMB {
v.errorf("sandbox.memory_mb", "must be between %d and %d (got %d)", minMemoryMB, maxMemoryMB, s.MemoryMB)
}
if s.CallStack < minCallStack || s.CallStack > maxCallStack {
v.errorf("sandbox.call_stack", "must be between %d and %d (got %d)", minCallStack, maxCallStack, s.CallStack)
}
}
func durationRange(v *validator, key string, d, lo, hi time.Duration) {
if d < lo || d > hi {
v.errorf(key, "must be between %s and %s (got %s)", lo, hi, d)
}
}
// checkURL returns a problem with raw, or "" if it is an absolute http(s) URL.
func checkURL(raw string) string {
u, err := url.Parse(raw)
switch {
case err != nil:
return fmt.Sprintf("invalid URL: %v", err)
case u.Scheme != "http" && u.Scheme != "https":
return fmt.Sprintf("URL must start with http:// or https:// (got %q)", raw)
case u.Host == "":
return fmt.Sprintf("URL has no host (got %q)", raw)
}
return ""
}
+131
View File
@@ -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"]
}
+99
View File
@@ -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", "<title>Just a moment...</title>"},
{"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 ""
}
+126
View File
@@ -0,0 +1,126 @@
// 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 := NewResponse(rawURL, resp.Request.URL.String(), resp.StatusCode, stdhttp.Header(resp.Header), data)
r.Elapsed = time.Since(start)
return r, nil
}
// NewResponse builds and classifies a Response for a page obtained another
// way, such as a saved fixture or the browser fallback.
func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, body []byte) *Response {
if header == nil { header = stdhttp.Header{} }
r := &Response{
URL: rawURL,
FinalURL: finalURL,
Status: status,
Header: header,
Body: body,
}
r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body)
return r
}
+270
View File
@@ -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", "<title>Metro</title>", OK, ""},
"cf script on normal page": {200, nil, "", `<script src="/cdn-cgi/challenge-platform/scripts/jsd/main.js">`, OK, ""},
"turnstile in a form": {200, nil, "", `<script src="https://challenges.cloudflare.com/turnstile/v0/api.js">`, OK, ""},
"not found": {404, nil, "", "<title>Page not found</title>", NotFound, ""},
"gone": {410, nil, "", "", NotFound, ""},
"cf header": {403, cf, "", "", Challenge, "cloudflare"},
"cf js challenge": {503, nil, "", "<script>window._cf_chl_opt={}</script>", Challenge, "cloudflare"},
"cf title": {403, nil, "", "<title>Just a moment...</title>", Challenge, "cloudflare"},
"amazon captcha 200": {200, nil, "", `<form method="get" action="/errors/validateCaptcha">`, Challenge, "amazon-captcha"},
"amazon captcha url": {200, nil, "https://www.amazon.de/errors/validateCaptcha?x=1", "", Challenge, "amazon-captcha"},
"datadome": {403, nil, "", `<iframe src="https://geo.captcha-delivery.com/captcha/">`, Challenge, "datadome"},
"turnstile on 403": {403, nil, "", `<script src="https://challenges.cloudflare.com/turnstile/v0/api.js">`, Challenge, "turnstile"},
"plain 403": {403, nil, "", "Access Denied", Blocked, ""},
"429": {429, nil, "", "slow down", Blocked, ""},
"amazon 503 dog": {503, nil, "", "Sorry! Something went wrong!", Blocked, ""},
"500": {500, nil, "", "", HTTPError, ""},
} {
t.Run(name, func(t *testing.T) {
header := tc.header
if header == nil { header = http.Header{} }
v, c := classify(tc.status, header, tc.finalURL, []byte(tc.body))
if v != tc.verdict || c != tc.challenge { t.Errorf("got %s/%q, want %s/%q", v, c, tc.verdict, tc.challenge) }
})
}
}
func mustURL(t *testing.T, raw string) *url.URL {
t.Helper()
u, err := url.Parse(raw)
if err != nil { t.Fatal(err) }
return u
}
func cookieNames(cs []*fhttp.Cookie) string {
names := make([]string, len(cs))
for i, c := range cs { names[i] = c.Name + "=" + c.Value }
return strings.Join(names, " ")
}
func TestJarExportImport(t *testing.T) {
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
j := NewJar()
j.now = func() time.Time { return now }
j.SetCookies(mustURL(t, "https://www.amazon.de/dp/X"), []*fhttp.Cookie{
{Name: "session-id", Value: "1", Domain: ".amazon.de", Path: "/"},
{Name: "host", Value: "2"},
{Name: "short", Value: "3", MaxAge: 60},
{Name: "old", Value: "4", Expires: now.Add(-time.Hour)},
})
exported := j.Export()
got := exported["www.amazon.de"]
if len(got) != 3 { t.Fatalf("exported %d cookies, want 3: %+v", len(got), got) }
byName := map[string]Cookie{}
for _, c := range got { byName[c.Name] = c }
if c := byName["host"]; !c.HostOnly || c.Domain != "www.amazon.de" || c.Path != "/dp" { t.Errorf("host-only cookie: %+v", c) }
if c := byName["session-id"]; c.HostOnly || c.Domain != "amazon.de" { t.Errorf("domain cookie: %+v", c) }
if c := byName["short"]; !c.Expires.Equal(now.Add(time.Minute)) { t.Errorf("max-age cookie expires %v", c.Expires) }
// A new jar gets the same cookies, scoped the same way.
k := NewJar()
k.now = j.now
for host, cs := range exported { k.Import(host, cs) }
if got := cookieNames(k.Cookies(mustURL(t, "https://www.amazon.de/dp/Y"))); !strings.Contains(got, "host=2") || !strings.Contains(got, "session-id=1") {
t.Errorf("www.amazon.de/dp cookies after import: %s", got)
}
if got := cookieNames(k.Cookies(mustURL(t, "https://smile.amazon.de/"))); got != "session-id=1" { t.Errorf("smile.amazon.de cookies: %q, want only the domain cookie", got) }
// The server deletes a cookie.
j.SetCookies(mustURL(t, "https://www.amazon.de/"), []*fhttp.Cookie{{Name: "session-id", Domain: ".amazon.de", Path: "/", MaxAge: -1}})
for _, c := range j.Export()["www.amazon.de"] {
if c.Name == "session-id" { t.Errorf("deleted cookie still exported") }
}
// Later the max-age cookie runs out.
now = now.Add(2 * time.Minute)
for _, c := range j.Export()["www.amazon.de"] {
if c.Name == "short" { t.Errorf("expired cookie still exported") }
}
}
func TestJarSaveLoad(t *testing.T) {
path := filepath.Join(t.TempDir(), "sub", "cookies.json")
j := NewJar()
j.SetCookies(mustURL(t, "https://www.amazon.co.uk/"), []*fhttp.Cookie{{Name: "a", Value: "1", Path: "/", Expires: time.Now().Add(time.Hour)}})
if err := j.Save(path); err != nil { t.Fatal(err) }
if runtime.GOOS != "windows" {
info, err := os.Stat(path)
if err != nil { t.Fatal(err) }
if perm := info.Mode().Perm(); perm != 0o600 { t.Errorf("cookie file mode %o, want 600", perm) }
}
k := NewJar()
if err := k.Load(path); err != nil { t.Fatal(err) }
if got := cookieNames(k.Cookies(mustURL(t, "https://www.amazon.co.uk/x"))); got != "a=1" { t.Errorf("loaded cookies: %q", got) }
if err := NewJar().Load(filepath.Join(t.TempDir(), "missing.json")); err != nil { t.Errorf("missing file: %v", err) }
}
func newTestClient(t *testing.T, opts Options) *Client {
t.Helper()
c, err := New(opts)
if err != nil { t.Fatal(err) }
return c
}
func TestClientGet(t *testing.T) {
var seen []*http.Request
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = append(seen, r)
switch r.URL.Path {
case "/start":
http.SetCookie(w, &http.Cookie{Name: "sid", Value: "abc", Path: "/"})
http.Redirect(w, r, "/product", http.StatusFound)
case "/product":
w.Header().Set("Content-Encoding", "gzip")
zw := gzip.NewWriter(w)
_, _ = zw.Write([]byte("<title>Metro 2039</title>"))
_ = zw.Close()
case "/missing":
http.NotFound(w, r)
default:
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer srv.Close()
c := newTestClient(t, Options{})
resp, err := c.Get(context.Background(), srv.URL+"/start")
if err != nil { t.Fatal(err) }
if resp.Verdict != OK || resp.Status != 200 { t.Errorf("verdict %s, status %d", resp.Verdict, resp.Status) }
if resp.FinalURL != srv.URL+"/product" { t.Errorf("final URL %q", resp.FinalURL) }
if string(resp.Body) != "<title>Metro 2039</title>" { t.Errorf("body %q, want it decompressed", resp.Body) }
if len(seen) != 2 { t.Fatalf("server saw %d requests, want 2", len(seen)) }
first := seen[0]
for name, want := range map[string]string{
"User-Agent": "Chrome/152.0.0.0",
"Sec-Ch-Ua": `"Google Chrome";v="152"`,
"Sec-Ch-Ua-Platform": `"`,
"Sec-Fetch-Mode": "navigate",
"Accept-Language": "en-US",
"Accept-Encoding": "gzip",
} {
if got := first.Header.Get(name); !strings.Contains(got, want) { t.Errorf("%s = %q, want it to contain %q", name, got, want) }
}
if got := seen[1].Header.Get("Cookie"); got != "sid=abc" { t.Errorf("cookie on redirect = %q, want sid=abc", got) }
resp, err = c.Get(context.Background(), srv.URL+"/missing")
if err != nil { t.Fatal(err) }
if resp.Verdict != NotFound { t.Errorf("404 verdict %s", resp.Verdict) }
if got := c.Jar().Export()["127.0.0.1"]; len(got) != 1 || got[0].Name != "sid" { t.Errorf("jar after requests: %+v", got) }
}
func TestClientBodyLimit(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(strings.Repeat("x", 2048)))
}))
defer srv.Close()
_, err := newTestClient(t, Options{MaxBody: 1024}).Get(context.Background(), srv.URL)
if !errors.Is(err, ErrBodyTooLarge) { t.Errorf("got %v, want ErrBodyTooLarge", err) }
}
func TestClientContextCancel(t *testing.T) {
release := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-release:
case <-r.Context().Done():
}
}))
defer srv.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
start := time.Now()
if _, err := newTestClient(t, Options{}).Get(ctx, srv.URL); err == nil { t.Fatal("want an error from a cancelled request") }
if elapsed := time.Since(start); elapsed > 5*time.Second { t.Errorf("cancel took %s", elapsed) }
}
func TestClientRejectsOtherSchemes(t *testing.T) {
if _, err := newTestClient(t, Options{}).Get(context.Background(), "file:///etc/passwd"); err == nil { t.Error("want an error for file://") }
}
+212
View File
@@ -0,0 +1,212 @@
package fetch
import (
"encoding/json"
"errors"
"io/fs"
"maps"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
http "github.com/bogdanfinn/fhttp"
"github.com/bogdanfinn/fhttp/cookiejar"
"golang.org/x/net/publicsuffix"
)
// Cookie is a stored cookie, in a form that survives a restart and can be
// handed to and from a browser.
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain"` // the host for host-only cookies
HostOnly bool `json:"host_only,omitempty"`
Path string `json:"path"`
Expires time.Time `json:"expires,omitzero"` // zero for session cookies
Secure bool `json:"secure,omitempty"`
HTTPOnly bool `json:"http_only,omitempty"`
}
func (c Cookie) expired(now time.Time) bool {
return !c.Expires.IsZero() && !c.Expires.After(now)
}
// Jar is an RFC 6265 cookie jar that remembers every cookie by the host that
// set it, so the cookies can be saved, restored and exported per host.
type Jar struct {
mu sync.Mutex
jar *cookiejar.Jar
cookies map[string]map[string]Cookie // host -> domain|path|name -> cookie
now func() time.Time
}
func NewJar() *Jar {
jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
return &Jar{
jar: jar,
cookies: map[string]map[string]Cookie{},
now: time.Now,
}
}
// SetCookies implements http.CookieJar.
func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
j.mu.Lock()
defer j.mu.Unlock()
j.jar.SetCookies(u, cookies)
host := strings.ToLower(u.Hostname())
now := j.now()
for _, hc := range cookies {
c := Cookie{
Name: hc.Name,
Value: hc.Value,
Domain: strings.TrimPrefix(strings.ToLower(hc.Domain), "."),
Path: hc.Path,
Expires: hc.Expires,
Secure: hc.Secure,
HTTPOnly: hc.HttpOnly,
}
if c.Domain == "" { c.Domain, c.HostOnly = host, true }
if c.Path == "" || !strings.HasPrefix(c.Path, "/") { c.Path = defaultPath(u.Path) }
switch {
case hc.MaxAge < 0:
c.Expires = now
case hc.MaxAge > 0:
c.Expires = now.Add(time.Duration(hc.MaxAge) * time.Second)
default:
// No Max-Age: Expires decides.
}
j.store(host, c, now)
}
}
// Cookies implements http.CookieJar.
func (j *Jar) Cookies(u *url.URL) []*http.Cookie {
j.mu.Lock()
defer j.mu.Unlock()
return j.jar.Cookies(u)
}
// Export returns the live cookies of every host, sorted by name.
func (j *Jar) Export() map[string][]Cookie {
j.mu.Lock()
defer j.mu.Unlock()
now := j.now()
out := map[string][]Cookie{}
for host, byKey := range j.cookies {
for _, key := range slices.Sorted(maps.Keys(byKey)) {
if c := byKey[key]; !c.expired(now) { out[host] = append(out[host], c) }
}
}
return out
}
// Import adds cookies as if host had set them. Expired cookies are skipped.
func (j *Jar) Import(host string, cookies []Cookie) {
j.mu.Lock()
defer j.mu.Unlock()
host = strings.ToLower(host)
now := j.now()
for _, c := range cookies {
if c.expired(now) { continue }
hc := &http.Cookie{
Name: c.Name,
Value: c.Value,
Path: c.Path,
Expires: c.Expires,
Secure: c.Secure,
HttpOnly: c.HTTPOnly,
}
if !c.HostOnly { hc.Domain = c.Domain }
j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc})
j.store(host, c, now)
}
}
// store records c for host, or forgets it when it has expired. Callers hold mu.
func (j *Jar) store(host string, c Cookie, now time.Time) {
key := c.Domain + "|" + c.Path + "|" + c.Name
if c.expired(now) {
delete(j.cookies[host], key)
return
}
if j.cookies[host] == nil { j.cookies[host] = map[string]Cookie{} }
j.cookies[host][key] = c
}
// Save writes the live cookies to path, readable only by the user.
func (j *Jar) Save(path string) error {
data, err := json.MarshalIndent(j.Export(), "", " ")
if err != nil { return err }
return writeFileAtomic(path, data, 0o600)
}
// Load imports the cookies saved at path. A missing file is not an error.
func (j *Jar) Load(path string) error {
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) { return nil }
if err != nil { return err }
var saved map[string][]Cookie
if err := json.Unmarshal(data, &saved); err != nil { return err }
for host, cookies := range saved { j.Import(host, cookies) }
return nil
}
// defaultPath is the RFC 6265 default-path of a request path.
func defaultPath(p string) string {
if p == "" || p[0] != '/' { return "/" }
i := strings.LastIndex(p, "/")
if i == 0 { return "/" }
return p[:i]
}
// writeFileAtomic replaces path with data, so a crash never leaves a
// half-written file behind.
func writeFileAtomic(path string, data []byte, perm fs.FileMode) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err }
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
if err != nil { return err }
defer func() { _ = os.Remove(tmp.Name()) }()
if err := tmp.Chmod(perm); err != nil {
_ = tmp.Close()
return err
}
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Close(); err != nil { return err }
return os.Rename(tmp.Name(), path)
}
+104
View File
@@ -0,0 +1,104 @@
// Package fixtures manages the real product pages the plugin tests run on.
//
// Which pages to use is tracked, in testdata/<shop>/cases.toml. The pages
// themselves change over time and may contain personal data, so they are
// not tracked: `dibs fixtures` fetches them into testdata/<shop>/pages/,
// next to the report dibs produced for each. The tests then check that the
// plugin still reads every saved page the same way.
package fixtures
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"github.com/pelletier/go-toml/v2"
)
// Case is one page to test with.
type Case struct {
Name string `toml:"name"`
URL string `toml:"url"`
// Note says what the page is for, e.g. "only a used offer".
Note string `toml:"note"`
}
// Suite is the cases of one shop.
type Suite struct {
// Shop is the plugin to use, named after the directory.
Shop string
Dir string
Cases []Case
}
var nameRe = regexp.MustCompile(`^[a-z0-9-]+$`)
// Load reads every dir/<shop>/cases.toml.
func Load(dir string) ([]Suite, error) {
files, err := filepath.Glob(filepath.Join(dir, "*", "cases.toml"))
if err != nil { return nil, err }
var suites []Suite
for _, f := range files {
data, err := os.ReadFile(f)
if err != nil { return nil, err }
var doc struct {
Cases []Case `toml:"case"`
}
dec := toml.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&doc); err != nil { return nil, fmt.Errorf("%s: %w", f, err) }
seen := map[string]bool{}
for _, c := range doc.Cases {
switch {
case !nameRe.MatchString(c.Name):
return nil, fmt.Errorf("%s: case name %q must contain only a-z, 0-9 and -", f, c.Name)
case seen[c.Name]:
return nil, fmt.Errorf("%s: duplicate case %q", f, c.Name)
case c.URL == "":
return nil, fmt.Errorf("%s: case %q has no url", f, c.Name)
}
seen[c.Name] = true
}
suiteDir := filepath.Dir(f)
suites = append(suites, Suite{Shop: filepath.Base(suiteDir), Dir: suiteDir, Cases: doc.Cases})
}
return suites, nil
}
func (s Suite) PagePath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".html") }
func (s Suite) ReportPath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".json") }
// Save writes a fetched page and its report.
func (s Suite) Save(c Case, page []byte, report any) error {
data, err := EncodeReport(report)
if err != nil { return err }
if err := os.MkdirAll(filepath.Join(s.Dir, "pages"), 0o700); err != nil { return err }
if err := os.WriteFile(s.PagePath(c), page, 0o600); err != nil { return err }
return os.WriteFile(s.ReportPath(c), data, 0o600)
}
// EncodeReport is the one way reports are written, so saved and fresh ones
// compare byte for byte.
func EncodeReport(report any) ([]byte, error) {
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
if err := enc.Encode(report); err != nil { return nil, err }
return b.Bytes(), nil
}
+208
View File
@@ -0,0 +1,208 @@
-- Built-in plugin for Amazon product pages (de, co.uk, fr, it, es, nl, com).
--
-- It uses only the public plugin API, so it doubles as the reference for
-- writing your own: see "Writing a plugin" in README.md.
local tlds = {
["de"] = "EUR",
["fr"] = "EUR",
["it"] = "EUR",
["es"] = "EUR",
["nl"] = "EUR",
["co.uk"] = "GBP",
["com"] = "USD",
}
-- Amazon's own merchant IDs. A page sold by Amazon carries one of them in
-- the buybox form.
local amazon_merchants = {
A3JWKAKR8XB7XF = true, -- amazon.de
A3P5ROKL5A1OLE = true, -- amazon.co.uk
A1X6FK5RDHNB96 = true, -- amazon.fr
A11IL2PNWYJU7H = true, -- amazon.it
A1AT7YVPFBWXBL = true, -- amazon.es
A17D2BRD4YMT0X = true, -- amazon.nl
ATVPDKIKX0DER = true, -- amazon.com
}
-- Any of these buttons means a new item can go into the cart. The preorder
-- selectors are a best guess until we have a real preorder page.
-- "#add-to-cart-button-ubb" is deliberately missing: it belongs to the used
-- buybox, which Amazon shows when only used copies are left.
local buy_buttons = table.concat({
"#add-to-cart-button",
"#buy-now-button",
"input[name='submit.add-to-cart']",
"input[name='submit.buy-now']",
"input[name='submit.preorder']",
"#preorder-button",
}, ", ")
-- Where Amazon says an item can't be bought.
local availability_area = { "#availability", "#outOfStock", "#buybox" }
local unavailable_phrases = {
"currently unavailable",
"derzeit nicht verfĂĽgbar",
"actuellement indisponible",
"non disponibile",
"no disponible",
"momenteel niet verkrijgbaar",
}
-- Older layouts say who sells and ships the item in one sentence, such as
-- "Versand und Verkauf durch Amazon." or "Verkauf durch X und Versand durch
-- Amazon."
local sold_by_amazon_phrases = {
"sold by amazon",
"verkauf durch amazon",
"vendu par amazon",
"venduto da amazon",
"venduto e spedito da amazon",
"vendido por amazon",
"vendido y enviado por amazon",
"verkocht door amazon",
}
local shipped_by_amazon_phrases = {
"fulfilled by amazon",
"ships from amazon",
"dispatched from amazon",
"versand durch amazon",
"expédié par amazon",
"spedito da amazon",
"enviado por amazon",
"verzonden door amazon",
}
local price_selectors = {
"#corePrice_feature_div .a-price .a-offscreen",
"#corePriceDisplay_desktop_feature_div .priceToPay .a-offscreen",
"#apex_desktop .priceToPay .a-offscreen",
".priceToPay .a-offscreen",
"#price_inside_buybox",
"#priceblock_ourprice",
"#priceblock_dealprice",
}
-- split returns the TLD and ASIN of an Amazon product URL, or nil.
local function split(url)
local host = url:match("^[Hh][Tt][Tt][Pp][Ss]?://([^/?#]+)")
if not host then return nil end
local tld = host:lower():match("^www%.amazon%.(.+)$") or host:lower():match("^amazon%.(.+)$")
if not tld or not tlds[tld] then return nil end
local m = regex_match(url, "(?i)/(?:dp|gp/product|gp/aw/d|exec/obidos/asin)/([a-z0-9]{10})(?:[/?#]|$)")
if not m then return nil end
return tld, m[1]:upper()
end
-- Amazon itself appears as "Amazon", "Amazon.de", "Amazon EU S.Ă  r.l." and
-- similar. Shops called "Amazonas Games" must not count.
local function is_amazon(name)
if not name then return false end
local n = name:lower():gsub("^%s+", ""):gsub("[%s%.]+$", "")
return n == "amazon" or n:match("^amazon%.[%a%.]+$") ~= nil or n:match("^amazon eu") ~= nil or n:match("^amazon media eu") ~= nil
end
local function legacy_merchant_info(doc)
return doc:text("#merchant-info") or doc:text("#merchantInfoFeature_feature_div")
end
-- sold_by_amazon is true or false when the page says who sells the item, and
-- nil when it doesn't, e.g. when there is no offer at all.
local function sold_by_amazon(doc)
-- The buybox form names the merchant whose offer the buttons buy.
local id = doc:attr("input#merchantID, input[name='merchantID']", "value")
if id and id ~= "" then return amazon_merchants[id] == true end
-- Newer layout: a "Verkäufer" / "Sold by" row.
local name = doc:text("#merchantInfoFeature_feature_div .offer-display-feature-text-message")
if name then return is_amazon(name) end
local info = legacy_merchant_info(doc)
if info then return contains_any(info, sold_by_amazon_phrases) end
if doc:exists("#sellerProfileTriggerId") then return false end
return nil
end
local function shipped_by_amazon(doc)
-- Newer layout: a "Versand" / "Ships from" row.
local name = doc:text("#fulfillerInfoFeature_feature_div .offer-display-feature-text-message")
if name then return is_amazon(name) end
return contains_any(legacy_merchant_info(doc), shipped_by_amazon_phrases)
end
local function seller(doc)
local sold = sold_by_amazon(doc)
if sold == nil then return "unknown" end
if sold then return "first_party" end
if shipped_by_amazon(doc) then return "fulfilled" end
return "third_party"
end
local function unavailable(doc)
for _, sel in ipairs(availability_area) do
if contains_any(doc:text(sel), unavailable_phrases) then return true end
end
return false
end
local function find_price(doc)
for _, sel in ipairs(price_selectors) do
local value, currency = parse_price(doc:text(sel))
if value then return value, currency end
end
return nil
end
return {
name = "amazon",
matches = function(url)
return split(url) ~= nil
end,
-- Every variant of a product URL becomes https://www.amazon.<tld>/dp/<ASIN>,
-- so the same item is never watched twice.
normalize = function(url)
local tld, asin = split(url)
if not tld then return url end
return "https://www.amazon." .. tld .. "/dp/" .. asin
end,
parse = function(doc, url)
local tld, asin = split(url)
local title = doc:text("#productTitle")
local value, currency = find_price(doc)
return {
title = title,
-- A dog page or a search result has no product title, so it is
-- never available.
available = title ~= nil and doc:exists(buy_buttons) and not unavailable(doc),
price = value,
currency = currency or (tld and tlds[tld]),
seller = seller(doc),
id = asin,
}
end,
cart_link = function(url, id)
local tld, asin = split(url)
if not tld then return nil end
return "https://www.amazon." .. tld .. "/gp/aws/cart/add.html?ASIN.1=" .. (id or asin) .. "&Quantity.1=1"
end,
}
+168
View File
@@ -0,0 +1,168 @@
package plugin
import (
"strings"
"sync"
"github.com/PuerkitoBio/goquery"
"github.com/andybalholm/cascadia"
lua "github.com/yuin/gopher-lua"
"golang.org/x/net/html"
)
const nodeType = "dibs.node"
// The methods of doc and of the nodes doc:all() returns. Each takes an
// optional CSS selector: without one it works on the node itself, with one
// on the first match inside it.
var nodeMethods = map[string]lua.LGFunction{
"text": nodeText,
"attr": nodeAttr,
"exists": nodeExists,
"count": nodeCount,
"html": nodeHTML,
"all": nodeAll,
}
func registerNode(L *lua.LState) {
mt := L.NewTypeMetatable(nodeType)
L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), nodeMethods))
}
func pushNode(L *lua.LState, sel *goquery.Selection) lua.LValue {
ud := L.NewUserData()
ud.Value = sel
L.SetMetatable(ud, L.GetTypeMetatable(nodeType))
return ud
}
func checkNode(L *lua.LState) *goquery.Selection {
if ud, ok := L.Get(1).(*lua.LUserData); ok {
if sel, ok := ud.Value.(*goquery.Selection); ok { return sel }
}
L.ArgError(1, "node expected (call methods with a colon, as in doc:text(...))")
return nil
}
// target is the node itself, or what the selector in argument arg matches
// inside it.
func target(L *lua.LState, node *goquery.Selection, arg int) *goquery.Selection {
if L.GetTop() < arg || L.Get(arg) == lua.LNil { return node }
return node.FindMatcher(selector(L, arg))
}
var selectors sync.Map // string -> cascadia.Selector
func selector(L *lua.LState, arg int) cascadia.Selector {
src := L.CheckString(arg)
if s, ok := selectors.Load(src); ok { return s.(cascadia.Selector) }
s, err := cascadia.Compile(src)
if err != nil {
L.ArgError(arg, "invalid selector "+src+": "+err.Error())
return nil
}
selectors.Store(src, s)
return s
}
// node:text([sel]) is the visible text of the node or its first match, with
// whitespace collapsed. It is nil if nothing matches or the text is empty,
// so `if doc:text(sel) then` means "has text". Use exists to test presence.
func nodeText(L *lua.LState) int {
s := target(L, checkNode(L), 2).First()
text := ""
if s.Length() > 0 { text = visibleText(s) }
if text == "" { L.Push(lua.LNil) } else { L.Push(lua.LString(text)) }
return 1
}
// node:attr(name) or node:attr(sel, name) is an attribute value, or nil.
func nodeAttr(L *lua.LState) int {
node := checkNode(L)
s, name := node, L.CheckString(2)
if L.GetTop() >= 3 { s, name = target(L, node, 2), L.CheckString(3) }
if v, ok := s.First().Attr(name); ok { L.Push(lua.LString(v)) } else { L.Push(lua.LNil) }
return 1
}
// node:exists(sel) reports whether sel matches anything.
func nodeExists(L *lua.LState) int {
L.Push(lua.LBool(checkNode(L).FindMatcher(selector(L, 2)).Length() > 0))
return 1
}
// node:count(sel) is the number of matches.
func nodeCount(L *lua.LState) int {
L.Push(lua.LNumber(checkNode(L).FindMatcher(selector(L, 2)).Length()))
return 1
}
// node:html([sel]) is the outer HTML of the node or its first match, or nil.
func nodeHTML(L *lua.LState) int {
s := target(L, checkNode(L), 2).First()
if s.Length() == 0 {
L.Push(lua.LNil)
return 1
}
out, err := goquery.OuterHtml(s)
if err != nil { L.RaiseError("html: %v", err) }
L.Push(lua.LString(out))
return 1
}
// node:all(sel) is a list of nodes, one per match.
func nodeAll(L *lua.LState) int {
t := L.NewTable()
checkNode(L).FindMatcher(selector(L, 2)).Each(func(_ int, s *goquery.Selection) { t.Append(pushNode(L, s)) })
L.Push(t)
return 1
}
// hiddenElements never contribute visible text. Amazon puts large inline
// scripts inside its availability block, for example.
var hiddenElements = map[string]bool{"script": true, "style": true, "noscript": true, "template": true}
// inlineElements run into the text around them. Other elements are
// separated by a space, so "<li>a</li><li>b</li>" reads "a b".
var inlineElements = map[string]bool{
"a": true, "abbr": true, "b": true, "bdi": true, "bdo": true, "cite": true, "code": true, "data": true,
"em": true, "i": true, "kbd": true, "mark": true, "q": true, "s": true, "small": true, "span": true,
"strong": true, "sub": true, "sup": true, "time": true, "u": true, "var": true,
}
func visibleText(s *goquery.Selection) string {
var b strings.Builder
for _, n := range s.Nodes { writeText(&b, n) }
return strings.Join(strings.Fields(b.String()), " ")
}
func writeText(b *strings.Builder, n *html.Node) {
switch n.Type {
case html.TextNode:
b.WriteString(n.Data)
case html.ElementNode:
if hiddenElements[n.Data] { return }
block := !inlineElements[n.Data]
if block { b.WriteByte(' ') }
for c := n.FirstChild; c != nil; c = c.NextSibling { writeText(b, c) }
if block { b.WriteByte(' ') }
case html.DocumentNode:
for c := n.FirstChild; c != nil; c = c.NextSibling { writeText(b, c) }
default:
// Comments and doctypes have no visible text.
}
}
+107
View File
@@ -0,0 +1,107 @@
package plugin
import (
"log/slog"
"regexp"
"strings"
"sync"
lua "github.com/yuin/gopher-lua"
"git.security-command.org/Overlord/dibs/internal/price"
)
func registerHelpers(L *lua.LState, logger *slog.Logger) {
logFn := L.NewFunction(func(L *lua.LState) int {
parts := make([]string, L.GetTop())
for i := range parts { parts[i] = L.ToStringMeta(L.Get(i + 1)).String() }
logger.Info(strings.Join(parts, " "))
return 0
})
L.SetGlobal("log", logFn)
L.SetGlobal("print", logFn)
L.SetGlobal("contains_any", L.NewFunction(containsAny))
L.SetGlobal("parse_price", L.NewFunction(parsePrice))
L.SetGlobal("regex_match", L.NewFunction(regexMatch))
}
// contains_any(str, {phrases}) reports whether str contains any of the
// phrases, ignoring case. A nil str contains nothing.
func containsAny(L *lua.LState) int {
phrases := L.CheckTable(2)
if L.Get(1) == lua.LNil {
L.Push(lua.LFalse)
return 1
}
s := strings.ToLower(L.CheckString(1))
found := false
phrases.ForEach(func(_, v lua.LValue) {
if p, ok := v.(lua.LString); ok && !found && strings.Contains(s, strings.ToLower(string(p))) { found = true }
})
L.Push(lua.LBool(found))
return 1
}
// parse_price(str) returns the price in str and its currency code (or nil),
// or nil if str holds no price.
func parsePrice(L *lua.LState) int {
if L.Get(1) == lua.LNil {
L.Push(lua.LNil)
return 1
}
v, cur, ok := price.Parse(L.CheckString(1))
if !ok {
L.Push(lua.LNil)
return 1
}
L.Push(lua.LNumber(v))
if cur != "" { L.Push(lua.LString(cur)) } else { L.Push(lua.LNil) }
return 2
}
var regexps sync.Map // string -> *regexp.Regexp
// regex_match(str, pattern) matches a Go (RE2) regular expression. It
// returns a list of the capture groups, or of the whole match if the
// pattern has no groups, or nil if it does not match.
func regexMatch(L *lua.LState) int {
pattern := L.CheckString(2)
if L.Get(1) == lua.LNil {
L.Push(lua.LNil)
return 1
}
s := L.CheckString(1)
var re *regexp.Regexp
if cached, ok := regexps.Load(pattern); ok {
re = cached.(*regexp.Regexp)
} else {
compiled, err := regexp.Compile(pattern)
if err != nil { L.ArgError(2, "invalid pattern: "+err.Error()) }
re = compiled
regexps.Store(pattern, re)
}
m := re.FindStringSubmatch(s)
if m == nil {
L.Push(lua.LNil)
return 1
}
if len(m) > 1 { m = m[1:] }
t := L.NewTable()
for _, g := range m { t.Append(lua.LString(g)) }
L.Push(t)
return 1
}
+165
View File
@@ -0,0 +1,165 @@
package plugin
import (
"context"
"embed"
"errors"
"fmt"
"io/fs"
"log/slog"
"maps"
"os"
"slices"
"strings"
"git.security-command.org/Overlord/dibs/internal/fetch"
)
//go:embed builtin/*.lua
var builtinFS embed.FS
// ErrNoPlugin is returned when no plugin matches a URL.
var ErrNoPlugin = errors.New("no plugin matches the URL")
// Builtins returns the names of the embedded plugins.
func Builtins() []string {
files, _ := fs.Glob(builtinFS, "builtin/*.lua")
names := make([]string, len(files))
for i, f := range files { names[i] = strings.TrimSuffix(strings.TrimPrefix(f, "builtin/"), ".lua") }
return names
}
// BuiltinSource returns the code of an embedded plugin.
func BuiltinSource(name string) ([]byte, error) {
return builtinFS.ReadFile("builtin/" + name + ".lua")
}
// Host holds the loaded plugins.
type Host struct {
plugins map[string]*Plugin
// order is the order ForURL tries plugins in: user plugins first, so
// they win over built-ins they don't replace.
order []string
}
// NewHost loads the built-in plugins and the user's (name -> file). A user
// plugin replaces a built-in one of the same name.
func NewHost(user map[string]string, limits Limits, logger *slog.Logger) (*Host, error) {
h := &Host{plugins: map[string]*Plugin{}}
var errs []error
for _, name := range slices.Sorted(maps.Keys(user)) {
code, err := os.ReadFile(user[name])
if err != nil {
errs = append(errs, fmt.Errorf("plugin %s: %w", name, err))
continue
}
p, err := Load(name, user[name], code, limits, logger)
if err != nil {
errs = append(errs, err)
continue
}
h.plugins[name] = p
h.order = append(h.order, name)
}
for _, name := range Builtins() {
if _, replaced := user[name]; replaced { continue }
code, err := BuiltinSource(name)
if err == nil {
var p *Plugin
if p, err = Load(name, "built-in", code, limits, logger); err == nil {
h.plugins[name] = p
h.order = append(h.order, name)
continue
}
}
errs = append(errs, err)
}
if len(errs) > 0 {
h.Close()
return nil, errors.Join(errs...)
}
return h, nil
}
// Plugin returns the plugin called name.
func (h *Host) Plugin(name string) (*Plugin, bool) {
p, ok := h.plugins[name]
return p, ok
}
// ForURL returns the first plugin whose matches(url) is true.
func (h *Host) ForURL(ctx context.Context, url string) (*Plugin, error) {
for _, name := range h.order {
p := h.plugins[name]
ok, err := p.Matches(ctx, url)
if err != nil { return nil, err }
if ok { return p, nil }
}
return nil, ErrNoPlugin
}
func (h *Host) Close() {
for _, p := range h.plugins { p.Close() }
}
// Report is the outcome of checking one URL, as `dibs check` prints it.
type Report struct {
URL string `json:"url"`
FetchURL string `json:"fetch_url"`
FinalURL string `json:"final_url"`
Shop string `json:"shop"`
Status int `json:"status"`
Verdict string `json:"verdict"`
Challenge string `json:"challenge,omitempty"`
Result *Result `json:"result,omitempty"`
CartLink string `json:"cart_link,omitempty"`
ElapsedMS int64 `json:"elapsed_ms"`
}
// Evaluate turns a fetched page into a Report. Only pages with the OK
// verdict are parsed. A NotFound page is reported as unavailable without
// asking the plugin, and bot checks and errors have no result.
func Evaluate(ctx context.Context, p *Plugin, rawURL string, resp *fetch.Response) (*Report, error) {
r := &Report{
URL: rawURL,
FetchURL: resp.URL,
FinalURL: resp.FinalURL,
Shop: p.Name,
Status: resp.Status,
Verdict: resp.Verdict.String(),
Challenge: resp.Challenge,
ElapsedMS: resp.Elapsed.Milliseconds(),
}
switch resp.Verdict {
case fetch.OK:
res, err := p.Parse(ctx, resp.Body, resp.URL)
if err != nil { return r, err }
r.Result = res
link, err := p.CartLink(ctx, resp.URL, res.ID)
if err != nil { return r, err }
r.CartLink = link
case fetch.NotFound:
r.Result = &Result{Seller: SellerUnknown}
default:
// Challenge, Blocked or HTTPError: nothing to read.
}
return r, nil
}
+100
View File
@@ -0,0 +1,100 @@
package plugin
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
"slices"
"testing"
"github.com/pelletier/go-toml/v2"
"git.security-command.org/Overlord/dibs/internal/fetch"
"git.security-command.org/Overlord/dibs/internal/fixtures"
)
// testdata is the repository's top-level testdata directory.
var testdata = filepath.Join("..", "..", "testdata")
func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func builtin(t *testing.T, name string) *Plugin {
t.Helper()
code, err := BuiltinSource(name)
if err != nil { t.Fatal(err) }
p, err := Load(name, "built-in", code, DefaultLimits(), discardLogger())
if err != nil { t.Fatal(err) }
t.Cleanup(p.Close)
return p
}
// TestSavedPages re-reads every page `dibs fixtures` saved and checks the
// plugin still reports what it reported when the page was fetched.
func TestSavedPages(t *testing.T) {
suites, err := fixtures.Load(testdata)
if err != nil { t.Fatal(err) }
ran := 0
for _, suite := range suites {
if !slices.Contains(Builtins(), suite.Shop) { continue }
p := builtin(t, suite.Shop)
for _, c := range suite.Cases {
page, err := os.ReadFile(suite.PagePath(c))
if errors.Is(err, fs.ErrNotExist) { continue }
if err != nil { t.Fatal(err) }
ran++
t.Run(suite.Shop+"/"+c.Name, func(t *testing.T) {
want, err := os.ReadFile(suite.ReportPath(c))
if err != nil { t.Fatal(err) }
var saved Report
if err := json.Unmarshal(want, &saved); err != nil { t.Fatal(err) }
report, err := Evaluate(context.Background(), p, saved.URL, fetch.NewResponse(saved.FetchURL, saved.FinalURL, saved.Status, nil, page))
if err != nil { t.Fatal(err) }
got, err := fixtures.EncodeReport(report)
if err != nil { t.Fatal(err) }
if !bytes.Equal(got, want) { t.Errorf("%s (%s) now reads differently.\ngot:\n%s\nsaved:\n%s", c.Name, c.Note, got, want) }
})
}
}
if ran == 0 { t.Skip("no saved pages: run `dibs fixtures` to fetch them") }
}
func TestAmazonNormalize(t *testing.T) {
data, err := os.ReadFile(filepath.Join(testdata, "amazon", "urls.toml"))
if err != nil { t.Fatal(err) }
var urls struct {
Normalize []struct {
In string `toml:"in"`
Out string `toml:"out"`
} `toml:"normalize"`
}
if err := toml.Unmarshal(data, &urls); err != nil { t.Fatal(err) }
p := builtin(t, "amazon")
for _, u := range urls.Normalize {
got, err := p.Normalize(context.Background(), u.In)
if err != nil { t.Fatal(err) }
if got != u.Out { t.Errorf("normalize(%q) = %q, want %q", u.In, got, u.Out) }
}
}
+363
View File
@@ -0,0 +1,363 @@
// Package plugin runs shop plugins: sandboxed Lua files that read product
// pages.
package plugin
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"math"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"github.com/PuerkitoBio/goquery"
lua "github.com/yuin/gopher-lua"
)
// Who sells the item, as parse reports it.
const (
// SellerFirstParty: the shop itself sells it.
SellerFirstParty = "first_party"
// SellerFulfilled: a marketplace seller sells it, but the shop ships it
// (e.g. Fulfilled by Amazon).
SellerFulfilled = "fulfilled"
// SellerThirdParty: a marketplace seller sells and ships it.
SellerThirdParty = "third_party"
SellerUnknown = "unknown"
)
// Result is what a plugin's parse function read from a page.
type Result struct {
Title string `json:"title,omitempty"`
Available bool `json:"available"`
Price *float64 `json:"price"`
Currency string `json:"currency,omitempty"`
Seller string `json:"seller"`
// ID is the shop's product ID, such as an ASIN. It is passed to
// cart_link.
ID string `json:"id,omitempty"`
}
// hooks are the functions a plugin table may define. Only parse is required.
var hooks = []string{"matches", "normalize", "parse", "cart_link", "login", "add_to_cart"}
var currencyRe = regexp.MustCompile(`^[A-Z]{3}$`)
// Plugin is a loaded plugin. It is safe for concurrent use; calls into one
// plugin run one at a time.
type Plugin struct {
Name string
// Source is the plugin's file, or "built-in".
Source string
chunk string
code []byte
limits Limits
logger *slog.Logger
nameFixed bool // the name came from the config, not the table
mu sync.Mutex
state *lua.LState
funcs map[string]*lua.LFunction
}
// Load runs a plugin's code and checks the table it returns. An empty name
// takes the name from the table, or else from the file name.
func Load(name, source string, code []byte, limits Limits, logger *slog.Logger) (*Plugin, error) {
chunk := filepath.Base(source)
if source == "built-in" { chunk = name + ".lua" }
p := &Plugin{
Name: name,
Source: source,
chunk: chunk,
code: code,
limits: limits,
logger: logger,
nameFixed: name != "",
}
if !p.nameFixed { p.Name = strings.TrimSuffix(chunk, ".lua") }
shortCalls.Lock()
defer shortCalls.Unlock()
if err := p.reset(); err != nil { return nil, fmt.Errorf("plugin %s (%s): %w", name, source, err) }
return p, nil
}
// reset loads the plugin into a fresh Lua state. Callers hold shortCalls.
func (p *Plugin) reset() error {
if p.state != nil {
p.state.Close()
p.state = nil
}
L := newState(p.limits)
registerNode(L)
registerHelpers(L, p.logger.With("plugin", p.Name))
fn, err := L.Load(bytes.NewReader(p.code), p.chunk)
if err != nil {
L.Close()
return luaError(err)
}
var tbl *lua.LTable
err = run(L, context.Background(), p.limits.Timeout, p.limits.MemoryBytes, func() error {
if err := L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}); err != nil { return err }
ret := L.Get(-1)
L.Pop(1)
t, ok := ret.(*lua.LTable)
if !ok { return fmt.Errorf("must return a table, got %s", ret.Type()) }
tbl = t
return nil
})
if err == nil { err = p.readTable(tbl) }
if err != nil {
L.Close()
return err
}
p.state = L
return nil
}
// readTable checks the plugin table and picks up its functions.
func (p *Plugin) readTable(tbl *lua.LTable) error {
var problems []string
funcs := map[string]*lua.LFunction{}
tbl.ForEach(func(k, v lua.LValue) {
key := k.String()
switch {
case key == "name":
s, ok := v.(lua.LString)
switch {
case !ok || s == "":
problems = append(problems, fmt.Sprintf("name must be a non-empty string, got %s", v.Type()))
case !p.nameFixed:
p.Name = string(s)
case string(s) != p.Name:
problems = append(problems, fmt.Sprintf("name is %q, but the plugin is configured as %q", s, p.Name))
}
case slices.Contains(hooks, key):
if fn, ok := v.(*lua.LFunction); ok { funcs[key] = fn } else { problems = append(problems, fmt.Sprintf("%s must be a function, got %s", key, v.Type())) }
default:
problems = append(problems, fmt.Sprintf("unknown key %q (known: name, %s)", key, strings.Join(hooks, ", ")))
}
})
if funcs["parse"] == nil && !slices.ContainsFunc(problems, func(s string) bool { return strings.HasPrefix(s, "parse ") }) {
problems = append(problems, "parse function is missing")
}
if len(problems) > 0 {
slices.Sort(problems)
return errors.New(strings.Join(problems, "; "))
}
p.funcs = funcs
return nil
}
// Has reports whether the plugin defines hook.
func (p *Plugin) Has(hook string) bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.funcs[hook] != nil
}
// call runs a short hook, one of matches, normalize, parse and cart_link.
// args builds the arguments in the plugin's Lua state.
func (p *Plugin) call(ctx context.Context, hook string, nret int, args func(L *lua.LState) []lua.LValue) ([]lua.LValue, error) {
p.mu.Lock()
defer p.mu.Unlock()
shortCalls.Lock()
defer shortCalls.Unlock()
// An earlier call was killed and reloading failed.
if p.state == nil {
if err := p.reset(); err != nil { return nil, fmt.Errorf("plugin %s: %w", p.Name, err) }
}
L := p.state
var out []lua.LValue
err := run(L, ctx, p.limits.Timeout, p.limits.MemoryBytes, func() error {
if err := L.CallByParam(lua.P{Fn: p.funcs[hook], NRet: nret, Protect: true}, args(L)...); err != nil { return err }
for i := nret; i > 0; i-- { out = append(out, L.Get(-i)) }
L.Pop(nret)
return nil
})
// A killed call can stop anywhere, so start over with a clean state.
if errors.Is(err, ErrTimeout) || errors.Is(err, ErrMemoryLimit) {
if rerr := p.reset(); rerr != nil { p.logger.Error("reloading plugin failed", "plugin", p.Name, "err", rerr) }
}
if err != nil { return nil, fmt.Errorf("plugin %s: %s: %w", p.Name, hook, err) }
return out, nil
}
// Matches runs matches(url). A plugin without it matches nothing.
func (p *Plugin) Matches(ctx context.Context, url string) (bool, error) {
if !p.Has("matches") { return false, nil }
out, err := p.call(ctx, "matches", 1, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(url)} })
if err != nil { return false, err }
return lua.LVAsBool(out[0]), nil
}
// Normalize runs normalize(url). Without it, or if it returns nil, the URL
// stays as it is.
func (p *Plugin) Normalize(ctx context.Context, url string) (string, error) {
if !p.Has("normalize") { return url, nil }
out, err := p.call(ctx, "normalize", 1, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(url)} })
if err != nil { return "", err }
switch v := out[0].(type) {
case lua.LString:
return string(v), nil
case *lua.LNilType:
return url, nil
default:
return "", fmt.Errorf("plugin %s: normalize must return a string, got %s", p.Name, v.Type())
}
}
// Parse runs parse(doc, url) on a page.
func (p *Plugin) Parse(ctx context.Context, page []byte, url string) (*Result, error) {
// Parse the HTML before the call, so it does not count against the
// call's time and memory.
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page))
if err != nil { return nil, fmt.Errorf("parsing HTML: %w", err) }
out, err := p.call(ctx, "parse", 1, func(L *lua.LState) []lua.LValue { return []lua.LValue{pushNode(L, doc.Selection), lua.LString(url)} })
if err != nil { return nil, err }
r, err := toResult(out[0])
if err != nil { return nil, fmt.Errorf("plugin %s: parse: %w", p.Name, err) }
return r, nil
}
// CartLink runs cart_link(url, id). It returns "" if the plugin has no
// cart_link or it returns nil.
func (p *Plugin) CartLink(ctx context.Context, url, id string) (string, error) {
if !p.Has("cart_link") { return "", nil }
out, err := p.call(ctx, "cart_link", 1, func(*lua.LState) []lua.LValue {
idArg := lua.LValue(lua.LNil)
if id != "" { idArg = lua.LString(id) }
return []lua.LValue{lua.LString(url), idArg}
})
if err != nil { return "", err }
switch v := out[0].(type) {
case lua.LString:
return string(v), nil
case *lua.LNilType:
return "", nil
default:
return "", fmt.Errorf("plugin %s: cart_link must return a string, got %s", p.Name, v.Type())
}
}
// Close frees the Lua state.
func (p *Plugin) Close() {
p.mu.Lock()
defer p.mu.Unlock()
if p.state != nil {
p.state.Close()
p.state = nil
}
}
// toResult checks parse's return value field by field.
func toResult(v lua.LValue) (*Result, error) {
t, ok := v.(*lua.LTable)
if !ok { return nil, fmt.Errorf("must return a table, got %s", v.Type()) }
r := &Result{Seller: SellerUnknown}
var problems []string
bad := func(format string, args ...any) { problems = append(problems, fmt.Sprintf(format, args...)) }
hasAvailable := false
t.ForEach(func(k, val lua.LValue) {
key := k.String()
switch key {
case "title":
if s, ok := val.(lua.LString); ok { r.Title = strings.TrimSpace(string(s)) } else { bad("title must be a string or nil, got %s", val.Type()) }
case "available":
b, ok := val.(lua.LBool)
if !ok {
bad("available must be true or false, got %s", val.Type())
return
}
r.Available, hasAvailable = bool(b), true
case "price":
n, ok := val.(lua.LNumber)
switch f := float64(n); {
case !ok:
bad("price must be a number or nil, got %s", val.Type())
case f < 0 || math.IsInf(f, 0) || math.IsNaN(f):
bad("price must be a positive number, got %v", f)
default:
r.Price = &f
}
case "currency":
s, ok := val.(lua.LString)
if c := strings.ToUpper(string(s)); ok && currencyRe.MatchString(c) { r.Currency = c } else { bad("currency must be a 3-letter code such as EUR or nil, got %s", val) }
case "seller":
s, ok := val.(lua.LString)
switch string(s) {
case SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown:
if ok { r.Seller = string(s) }
default:
bad("seller must be %q, %q, %q or %q, got %s", SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown, val)
}
case "id":
if s, ok := val.(lua.LString); ok { r.ID = string(s) } else { bad("id must be a string or nil, got %s", val.Type()) }
default:
bad("unknown field %q", key)
}
})
if !hasAvailable && !slices.ContainsFunc(problems, func(s string) bool { return strings.HasPrefix(s, "available ") }) {
bad("available is missing")
}
if len(problems) > 0 {
slices.Sort(problems)
return nil, errors.New(strings.Join(problems, "; "))
}
return r, nil
}
+183
View File
@@ -0,0 +1,183 @@
package plugin
import (
"context"
"errors"
"fmt"
"runtime/metrics"
"strings"
"sync"
"sync/atomic"
"time"
lua "github.com/yuin/gopher-lua"
"git.security-command.org/Overlord/dibs/internal/config"
)
// Limits cap every Lua call. They come from [sandbox] in dibs.toml.
type Limits struct {
// Timeout applies to loading a plugin and to matches, normalize, parse
// and cart_link.
Timeout time.Duration
// SessionTimeout applies to login and add_to_cart.
SessionTimeout time.Duration
// MemoryBytes is the heap growth one call may cause. It is measured for
// the whole process, so it is approximate.
MemoryBytes int64
// CallStack is the maximum Lua call depth.
CallStack int
}
func DefaultLimits() Limits {
return Limits{
Timeout: config.DefaultSandboxTimeout,
SessionTimeout: config.DefaultSessionTimeout,
MemoryBytes: config.DefaultMemoryMB << 20,
CallStack: config.DefaultCallStack,
}
}
func LimitsFrom(s config.Sandbox) Limits {
return Limits{
Timeout: s.Timeout.Duration,
SessionTimeout: s.SessionTimeout.Duration,
MemoryBytes: int64(s.MemoryMB) << 20,
CallStack: s.CallStack,
}
}
var (
ErrTimeout = errors.New("timed out")
ErrMemoryLimit = errors.New("exceeded the memory limit")
)
// removedGlobals could load code, or reach the interpreter's internals.
// The os, io, debug, package and coroutine libraries are never opened.
var removedGlobals = []string{
"dofile", "loadfile", "load", "loadstring", "require", "module",
"collectgarbage", "getfenv", "setfenv", "newproxy", "_printregs",
}
// shortCalls lets one parse-type call run at a time, so the heap growth the
// memory watchdog sees is that call's. These calls take milliseconds.
var shortCalls sync.Mutex
const watchInterval = 2 * time.Millisecond
func newState(limits Limits) *lua.LState {
L := lua.NewState(lua.Options{
SkipOpenLibs: true,
CallStackSize: limits.CallStack,
RegistrySize: 16 * 1024,
RegistryMaxSize: 256 * 1024,
MinimizeStackMemory: true,
})
for _, lib := range []struct {
name string
open lua.LGFunction
} {
{lua.BaseLibName, lua.OpenBase},
{lua.TabLibName, lua.OpenTable},
{lua.StringLibName, lua.OpenString},
{lua.MathLibName, lua.OpenMath},
} {
L.Push(L.NewFunction(lib.open))
L.Push(lua.LString(lib.name))
L.Call(1, 0)
}
for _, name := range removedGlobals { L.SetGlobal(name, lua.LNil) }
// string.rep allocates its whole result at once, faster than the
// watchdog can react.
if str, ok := L.GetGlobal("string").(*lua.LTable); ok { str.RawSetString("rep", L.NewFunction(cappedRep(limits.MemoryBytes))) }
return L
}
func cappedRep(limit int64) lua.LGFunction {
return func(L *lua.LState) int {
s := L.CheckString(1)
n := L.CheckInt(2)
if n <= 0 || s == "" {
L.Push(lua.LString(""))
return 1
}
if int64(len(s))*int64(n) > limit { L.RaiseError("string.rep: result of %d bytes exceeds the memory limit", int64(len(s))*int64(n)) }
L.Push(lua.LString(strings.Repeat(s, n)))
return 1
}
}
// run calls fn, which must call into L, under a timeout and the memory
// watchdog.
func run(L *lua.LState, parent context.Context, timeout time.Duration, memLimit int64, fn func() error) error {
ctx, cancel := context.WithTimeout(parent, timeout)
defer cancel()
var overLimit atomic.Bool
done := make(chan struct{})
defer close(done)
go watchMemory(ctx, done, memLimit, &overLimit, cancel)
L.SetContext(ctx)
defer L.RemoveContext()
err := fn()
switch {
case err == nil:
return nil
case overLimit.Load():
return ErrMemoryLimit
case parent.Err() != nil:
return parent.Err()
case errors.Is(ctx.Err(), context.DeadlineExceeded):
return fmt.Errorf("%w after %s", ErrTimeout, timeout)
default:
return luaError(err)
}
}
// watchMemory cancels the call once the heap has grown by more than limit
// since the call started.
func watchMemory(ctx context.Context, done <-chan struct{}, limit int64, overLimit *atomic.Bool, cancel context.CancelFunc) {
sample := []metrics.Sample{{Name: "/memory/classes/heap/objects:bytes"}}
heap := func() int64 {
metrics.Read(sample)
return int64(sample[0].Value.Uint64())
}
base := heap()
ticker := time.NewTicker(watchInterval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-ctx.Done():
return
case <-ticker.C:
if heap()-base > limit {
overLimit.Store(true)
cancel()
return
}
}
}
}
// luaError turns a Lua error into a one-line error such as
// "amazon.lua:12: attempt to index a nil value".
func luaError(err error) error {
var apiErr *lua.ApiError
if errors.As(err, &apiErr) && apiErr.Object != nil { return errors.New(strings.TrimSpace(apiErr.Object.String())) }
return err
}
+80
View File
@@ -0,0 +1,80 @@
package plugin
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.security-command.org/Overlord/dibs/internal/config"
)
// sandboxed loads testdata/sandbox/<name>.lua.
func sandboxed(t *testing.T, name string, limits Limits) *Plugin {
t.Helper()
path := filepath.Join(testdata, "sandbox", name+".lua")
code, err := os.ReadFile(path)
if err != nil { t.Fatal(err) }
p, err := Load(name, path, code, limits, discardLogger())
if err != nil { t.Fatal(err) }
t.Cleanup(p.Close)
return p
}
func parse(p *Plugin, url string) (*Result, error) {
return p.Parse(context.Background(), []byte("<html></html>"), url)
}
func TestSandboxGlobals(t *testing.T) {
r, err := parse(sandboxed(t, "globals", DefaultLimits()), "")
if err != nil { t.Fatal(err) }
if !r.Available { t.Errorf("reachable from the sandbox: %s", r.Title) }
}
func TestSandboxTimeout(t *testing.T) {
limits := DefaultLimits()
limits.Timeout = 50 * time.Millisecond
p := sandboxed(t, "timeout", limits)
for _, url := range []string{"loop", "pcall"} {
start := time.Now()
if _, err := parse(p, url); !errors.Is(err, ErrTimeout) { t.Errorf("%s: got %v, want ErrTimeout", url, err) }
if d := time.Since(start); d > 2*time.Second { t.Errorf("%s: timeout took %s", url, d) }
}
// The plugin was reloaded and still works.
if r, err := parse(p, "fine"); err != nil || !r.Available { t.Errorf("after a timeout: %v, %+v", err, r) }
}
func TestSandboxMemoryLimit(t *testing.T) {
limits := DefaultLimits()
limits.Timeout = 20 * time.Second
limits.MemoryBytes = 16 << 20
if _, err := parse(sandboxed(t, "memory", limits), ""); !errors.Is(err, ErrMemoryLimit) { t.Errorf("got %v, want ErrMemoryLimit", err) }
if _, err := parse(sandboxed(t, "string_rep", limits), ""); err == nil || !strings.Contains(err.Error(), "memory limit") { t.Errorf("string.rep: got %v, want a memory limit error", err) }
}
func TestSandboxCallStack(t *testing.T) {
limits := DefaultLimits()
limits.CallStack = 50
if _, err := parse(sandboxed(t, "call_stack", limits), ""); err == nil || !strings.Contains(err.Error(), "stack overflow") { t.Errorf("got %v, want a stack overflow", err) }
}
// The config's seller policies rank these values by name, so a renamed
// constant would silently never pass a policy.
func TestSellersKnownToConfig(t *testing.T) {
anyone := config.Item{Seller: config.SellerAny}
for _, s := range []string{SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown} {
if !anyone.AcceptsSeller(s) { t.Errorf("config does not know seller %q", s) }
}
}
+82
View File
@@ -0,0 +1,82 @@
// Package price reads prices as shops print them.
package price
import (
"regexp"
"strconv"
"strings"
)
// symbols maps currency signs and local abbreviations to ISO 4217 codes.
// Ambiguous ones such as "kr" are left out on purpose.
var symbols = []struct{ sign, code string }{
{"€", "EUR"},
{"ÂŁ", "GBP"},
{"US$", "USD"},
{"$", "USD"},
{"ÂĄ", "JPY"},
{"zł", "PLN"},
{"KÄŤ", "CZK"},
{"Fr.", "CHF"},
}
var (
codeRe = regexp.MustCompile(`\b(EUR|GBP|USD|CHF|PLN|SEK|NOK|DKK|CZK|HUF|JPY|CAD|AUD)\b`)
numberRe = regexp.MustCompile(`\d[\d.,' \x{00a0}\x{202f}]*`)
)
// Parse reads the first price in s, such as "1.299,99 €", "£1,299.99",
// "1 299,99 €" or "EUR 12.50". It returns the amount, the ISO 4217
// currency code if `s` names one (or "" if not), and whether a price was
// found.
func Parse(s string) (float64, string, bool) {
num := strings.TrimRight(numberRe.FindString(s), ".,' \u00a0\u202f")
if num == "" { return 0, "", false }
v, err := strconv.ParseFloat(normalize(num), 64)
if err != nil { return 0, "", false }
return v, currency(s), true
}
// normalize turns a localized number into the form ParseFloat accepts.
func normalize(num string) string {
// Spaces and apostrophes only ever group thousands.
num = strings.NewReplacer(" ", "", "\u00a0", "", "\u202f", "", "'", "").Replace(num)
dot, comma := strings.LastIndex(num, "."), strings.LastIndex(num, ",")
switch {
case dot >= 0 && comma >= 0:
// Both present: the last one is the decimal separator.
if dot > comma { return strings.ReplaceAll(num, ",", "") }
return strings.ReplaceAll(strings.ReplaceAll(num, ".", ""), ",", ".")
case comma >= 0:
return decimalOrGrouping(num, ",")
case dot >= 0:
return decimalOrGrouping(num, ".")
default:
return num
}
}
// decimalOrGrouping handles a number with only one kind of separator. Used
// more than once, or followed by exactly three digits, it groups thousands
// ("1.299", "1,299,000"). Otherwise it is the decimal point ("12,5", "9.99").
func decimalOrGrouping(num, sep string) string {
last := num[strings.LastIndex(num, sep)+1:]
if strings.Count(num, sep) > 1 || len(last) == 3 { return strings.ReplaceAll(num, sep, "") }
return strings.Replace(num, sep, ".", 1)
}
func currency(s string) string {
if m := codeRe.FindString(s); m != "" { return m }
for _, sym := range symbols {
if strings.Contains(s, sym.sign) { return sym.code }
}
return ""
}
+42
View File
@@ -0,0 +1,42 @@
package price
import "testing"
func TestParse(t *testing.T) {
for in, want := range map[string]struct {
value float64
currency string
}{
"1.299,99 €": {1299.99, "EUR"},
"ÂŁ1,299.99": {1299.99, "GBP"},
"1 299,99 €": {1299.99, "EUR"},
"1\u00a0299,99\u00a0€": {1299.99, "EUR"},
"1\u202f299,99 €": {1299.99, "EUR"},
"129,99 €": {129.99, "EUR"},
"129,99€": {129.99, "EUR"},
"€129.99": {129.99, "EUR"},
"$1,299.99": {1299.99, "USD"},
"US$ 49.00": {49, "USD"},
"EUR 12,50": {12.5, "EUR"},
"12.50 GBP": {12.5, "GBP"},
"CHF 1'299.90": {1299.9, "CHF"},
"1.299 €": {1299, "EUR"},
"1,299": {1299, ""},
"1.299.000,00 €": {1299000, "EUR"},
"12,5": {12.5, ""},
"9.99": {9.99, ""},
"49": {49, ""},
"Preis: 59,99 € inkl. MwSt.": {59.99, "EUR"},
" ÂŁ7. ": {7, "GBP"},
"99,00 zł": {99, "PLN"},
} {
v, c, ok := Parse(in)
if !ok || v != want.value || c != want.currency { t.Errorf("Parse(%q) = %v, %q, %v; want %v, %q", in, v, c, ok, want.value, want.currency) }
}
}
func TestParseNoPrice(t *testing.T) {
for _, in := range []string{"", "Derzeit nicht verfügbar", "€", "kostenlos"} {
if v, c, ok := Parse(in); ok { t.Errorf("Parse(%q) = %v, %q, true; want no price", in, v, c) }
}
}
+36
View File
@@ -0,0 +1,36 @@
# Real Amazon pages the amazon plugin is tested on. `dibs fixtures` fetches
# them into pages/ (not tracked), together with the report dibs made for
# each. Pages change: when a case stops showing what its note says, pick
# another product.
#
# Still wanted: a page sold by Amazon itself, and a preorder.
[[case]]
name = "out-of-stock-de"
url = "https://www.amazon.de/dp/B0HMX2FSTF"
note = "Metro 2039 CE (Xbox), currently unavailable, no offer at all"
[[case]]
name = "out-of-stock-uk"
url = "https://www.amazon.co.uk/dp/B0HM497GJJ"
note = "Metro 2039 CE (PC), currently unavailable, prices in GBP"
[[case]]
name = "fulfilled-de"
url = "https://www.amazon.de/dp/B0DK51S84Z"
note = "Silkland cable, sold by Silkland-DE, shipped by Amazon"
[[case]]
name = "fulfilled-de-2"
url = "https://www.amazon.de/dp/B076WS2WJ6"
note = "UGREEN enclosure, sold by a marketplace seller, shipped by Amazon"
[[case]]
name = "used-only-de"
url = "https://www.amazon.de/dp/B0948LPGNG"
note = "Metro Exodus Complete (PS5), only a used copy in the buybox: not available"
[[case]]
name = "not-found-de"
url = "https://www.amazon.de/dp/B0NOTREAL1"
note = "no such product: Amazon's 404 dog page"
+20
View File
@@ -0,0 +1,20 @@
# How the amazon plugin's normalize() rewrites product URLs. Anything that is
# not an Amazon product URL on a supported TLD stays as it is.
normalize = [
{ in = "https://www.amazon.de/dp/B0HMX2FSTF", out = "https://www.amazon.de/dp/B0HMX2FSTF" },
{ in = "https://www.amazon.de/dp/B0HMX2FSTF?th=1", out = "https://www.amazon.de/dp/B0HMX2FSTF" },
{ in = "https://www.amazon.de/dp/B0HMX2FSTF/ref=sr_1_1?th=1&psc=1", out = "https://www.amazon.de/dp/B0HMX2FSTF" },
{ in = "https://www.amazon.de/Metro-2039-Collectors-Edition/dp/B0HMX2FSTF", out = "https://www.amazon.de/dp/B0HMX2FSTF" },
{ in = "https://www.amazon.co.uk/gp/product/B0HM497GJJ", out = "https://www.amazon.co.uk/dp/B0HM497GJJ" },
{ in = "https://www.amazon.co.uk/gp/product/B0HM497GJJ/ref=ppx_yo_dt_b_asin", out = "https://www.amazon.co.uk/dp/B0HM497GJJ" },
{ in = "https://www.amazon.fr/gp/aw/d/B0HMX2FSTF", out = "https://www.amazon.fr/dp/B0HMX2FSTF" },
{ in = "https://amazon.it/dp/b0hmx2fstf", out = "https://www.amazon.it/dp/B0HMX2FSTF" },
{ in = "HTTPS://WWW.AMAZON.ES/dp/B0HMX2FSTF#reviews", out = "https://www.amazon.es/dp/B0HMX2FSTF" },
{ in = "https://www.amazon.nl/dp/B0HMX2FSTF", out = "https://www.amazon.nl/dp/B0HMX2FSTF" },
{ in = "https://www.amazon.com/exec/obidos/ASIN/B0HMX2FSTF", out = "https://www.amazon.com/dp/B0HMX2FSTF" },
{ in = "https://www.amazon.co.jp/dp/B0HMX2FSTF", out = "https://www.amazon.co.jp/dp/B0HMX2FSTF" },
{ in = "https://www.amazon.de/s?k=metro", out = "https://www.amazon.de/s?k=metro" },
{ in = "https://www.amazon.de/dp/B0HMX2FSTFX", out = "https://www.amazon.de/dp/B0HMX2FSTFX" },
{ in = "https://www.notamazon.de/dp/B0HMX2FSTF", out = "https://www.notamazon.de/dp/B0HMX2FSTF" },
]
+8
View File
@@ -0,0 +1,8 @@
-- Recurses until the call stack limit is hit.
local function deep(n) return deep(n + 1) + 1 end
return { parse = function()
deep(0)
return { available = true }
end }
+9
View File
@@ -0,0 +1,9 @@
-- Nothing that reads files, loads code or reaches the interpreter's
-- internals may be visible to a plugin.
local leaked = {}
for _, name in ipairs({ "os", "io", "debug", "package", "coroutine", "dofile", "loadfile", "load",
"loadstring", "require", "module", "collectgarbage", "getfenv", "setfenv", "newproxy", "_printregs" }) do
if _G[name] ~= nil then leaked[#leaked + 1] = name end
end
return { parse = function() return { available = #leaked == 0, title = table.concat(leaked, ",") } end }
+7
View File
@@ -0,0 +1,7 @@
-- Grows a table until the memory watchdog stops it.
return { parse = function()
local t = {}
for i = 1, 1e8 do t[i] = "value " .. i end
return { available = true }
end }
+6
View File
@@ -0,0 +1,6 @@
-- string.rep would allocate 10 GB at once, faster than the watchdog reacts.
return { parse = function()
local s = string.rep("x", 1e10)
return { available = true }
end }
+8
View File
@@ -0,0 +1,8 @@
-- Loops forever on "loop" and "pcall"; pcall must not be able to swallow the
-- timeout. Any other URL returns normally.
return { parse = function(doc, url)
if url == "loop" then while true do end end
if url == "pcall" then while true do pcall(function() while true do end end) end end
return { available = true }
end }