// 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" ) // The sellers parse reports. const ( // SellerFirstParty means the shop itself sells the item. SellerFirstParty = "first_party" // SellerFulfilled means a marketplace seller sells the item and the shop // ships it, as with Fulfilled by Amazon. SellerFulfilled = "fulfilled" // SellerThirdParty means a marketplace seller sells and ships the item. 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"} // tableKeys are the other keys a plugin table may have. var tableKeys = []string{"name", "session_warning"} 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 // SessionWarning is shown once before the first login, such as a // warning that automated logins can get the account locked. SessionWarning 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() L, t, err := p.load() if err != nil { return nil, fmt.Errorf("plugin %s (%s): %w", name, source, err) } if t.name != "" { p.Name = t.name } p.SessionWarning = t.warning p.state, p.funcs = L, t.funcs 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, t, err := p.load() if err != nil { return err } p.state, p.funcs = L, t.funcs return nil } // table is what a plugin's table defines. type table struct { // name is the table's name, if the config did not fix it. name string warning string funcs map[string]*lua.LFunction } // load runs the plugin's code in a new Lua state and reads its table. // Callers hold shortCalls. func (p *Plugin) load() (*lua.LState, *table, error) { 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 nil, nil, luaError(err) } var t *table err = run(L, context.Background(), p.limits.Timeout, newMeter(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) tbl, ok := ret.(*lua.LTable) if !ok { return fmt.Errorf("must return a table, got %s", ret.Type()) } read, err := p.readTable(tbl) t = read return err }) if err != nil { L.Close() return nil, nil, err } return L, t, nil } // readTable checks the plugin table and picks up its functions. func (p *Plugin) readTable(tbl *lua.LTable) (*table, error) { var problems []string t := &table{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: t.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 key == "session_warning": if s, ok := v.(lua.LString); ok { t.warning = strings.TrimSpace(string(s)) } else { problems = append(problems, fmt.Sprintf("session_warning must be a string, got %s", v.Type())) } case slices.Contains(hooks, key): if fn, ok := v.(*lua.LFunction); ok { t.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: %s, %s)", key, strings.Join(tableKeys, ", "), strings.Join(hooks, ", "))) } }) if t.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 nil, errors.New(strings.Join(problems, "; ")) } return t, nil } 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, newMeter(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 the state is rebuilt from scratch. 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()) } } func (p *Plugin) Parse(ctx context.Context, page []byte, url string) (*Result, error) { // The HTML is parsed before the call, so parsing 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()) } } 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 }