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>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-14 01:46:03 +02:00
1 parent f90ef18f90
commit bb010356a0
28 files changed
+2096 -26

No files matched your search

+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)
}
+37 -9
View File
@@ -12,19 +12,18 @@ import (
"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"
// builtinPlugins are the plugins embedded in the binary.
var builtinPlugins = []string{"amazon"}
const usage = `Usage:
dibs [--config FILE] [--headless] watch items (TUI unless --headless)
dibs check <url> fetch and parse one URL, print JSON
dibs plugin test <file.lua> <fixture.html> [url]
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
`
@@ -40,9 +39,12 @@ func run(args []string, stdout, stderr io.Writer) int {
case "version":
printVersion(stdout)
return 0
case "check", "plugin":
_, _ = fmt.Fprintf(stderr, "dibs %s: not implemented yet\n", args[0])
return 1
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
@@ -112,7 +114,7 @@ func loadConfig(path string, stderr io.Writer) (*config.Config, bool) {
}
}
cfg, err := config.Load(path, config.Options{Builtins: builtinPlugins})
cfg, err := config.Load(path, config.Options{Builtins: plugin.Builtins()})
if err != nil {
var errs config.Errors
switch {
@@ -131,6 +133,32 @@ func loadConfig(path string, stderr io.Writer) (*config.Config, bool) {
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 {