Files
dibs/internal/config/config.go
T
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

229 lines
6.2 KiB
Go

// 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
}