package plugin import ( "bytes" "context" "errors" "fmt" "net/url" "strings" "github.com/PuerkitoBio/goquery" lua "github.com/yuin/gopher-lua" "golang.org/x/net/html" "git.security-command.org/Overlord/dibs/internal/fetch" ) // ErrSignedOut means add_to_cart found the session signed out. var ErrSignedOut = errors.New("not signed in") // Account is what login and add_to_cart see of the shop's [accounts] entry. type Account struct { Username string // Password is empty when the account has no password_env. Only login // sees it. Password string TwoFA bool LoginURL string CartURL string // Site is the shop's site to sign in to, such as https://www.amazon.de/. Site string } // Session is what ctx offers login and add_to_cart: requests with the // account's cookies, questions to the user and the cookies themselves. type Session interface { Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) // Click opens rawURL in a browser, clicks the element sel matches and // returns the page the click leads to. Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error) Prompt(ctx context.Context, label string, secret bool) (string, error) Cookies(rawURL string) map[string]string } // Login runs login(ctx, account), which signs in to acc.Site. func (p *Plugin) Login(ctx context.Context, s Session, acc Account) error { _, err := p.session(ctx, "login", s, acc, 0, func(L *lua.LState) []lua.LValue { return []lua.LValue{accountTable(L, acc, true)} }) return err } // AddToCart runs add_to_cart(ctx, url), which puts the item on url in the // cart unless it is there already. It returns the cart page to send the user // to, which may be "", or ErrSignedOut. func (p *Plugin) AddToCart(ctx context.Context, s Session, acc Account, rawURL string) (string, error) { out, err := p.session(ctx, "add_to_cart", s, acc, 2, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(rawURL)} }) if err != nil { return "", err } switch v := out[0]; { case v == lua.LFalse: return "", ErrSignedOut case v != lua.LTrue: return "", fmt.Errorf("plugin %s: add_to_cart must return true or false, got %s", p.Name, v.Type()) } switch v := out[1].(type) { case lua.LString: return string(v), nil case *lua.LNilType: return acc.CartURL, nil default: return "", fmt.Errorf("plugin %s: add_to_cart must return the cart page as a string or nil, got %s", p.Name, v.Type()) } } // session runs a login or add_to_cart hook. These wait on the network and // on the user for minutes, so each call gets a Lua state of its own instead // of holding up the plugin's other calls. func (p *Plugin) session(ctx context.Context, hook string, s Session, acc Account, nret int, args func(L *lua.LState) []lua.LValue) ([]lua.LValue, error) { if !p.Has(hook) { return nil, fmt.Errorf("plugin %s has no %s function", p.Name, hook) } shortCalls.Lock() L, t, err := p.load() shortCalls.Unlock() if err != nil { return nil, fmt.Errorf("plugin %s: %w", p.Name, err) } defer L.Close() m := newMeter(p.limits.MemoryBytes) self := newCtx(L, s, acc, m) var out []lua.LValue err = run(L, ctx, p.limits.SessionTimeout, m, func() error { if err := L.CallByParam(lua.P{Fn: t.funcs[hook], NRet: nret, Protect: true}, append([]lua.LValue{self}, args(L)...)...); err != nil { return err } for i := nret; i > 0; i-- { out = append(out, L.Get(-i)) } L.Pop(nret) return nil }) if err != nil { return nil, fmt.Errorf("plugin %s: %s: %w", p.Name, hook, err) } return out, nil } // accountTable is the account as Lua sees it. Settings that are not set are // nil. func accountTable(L *lua.LState, acc Account, password bool) *lua.LTable { t := L.NewTable() for k, v := range map[string]string{"username": acc.Username, "login_url": acc.LoginURL, "cart_url": acc.CartURL, "site": acc.Site} { if v != "" { t.RawSetString(k, lua.LString(v)) } } if password && acc.Password != "" { t.RawSetString("password", lua.LString(acc.Password)) } t.RawSetString("twofa", lua.LBool(acc.TwoFA)) return t } // newCtx builds the ctx table: ctx:get(url, opts), ctx:post(url, opts), // ctx:click(url, sel), ctx:prompt(label, secret), ctx:cookies(url) and // ctx.account, which has no password. func newCtx(L *lua.LState, s Session, acc Account, m *meter) *lua.LTable { t := L.NewTable() t.RawSetString("get", L.NewFunction(func(L *lua.LState) int { return request(L, s, m, "GET") })) t.RawSetString("post", L.NewFunction(func(L *lua.LState) int { return request(L, s, m, "POST") })) t.RawSetString("click", L.NewFunction(func(L *lua.LState) int { rawURL := L.CheckString(2) sel := L.CheckString(3) m.pause() resp, err := s.Click(L.Context(), rawURL, sel) m.resume() if err != nil { L.RaiseError("clicking %s on %s: %v", sel, rawURL, err) } L.Push(responseTable(L, resp)) return 1 })) t.RawSetString("prompt", L.NewFunction(func(L *lua.LState) int { label := L.CheckString(2) secret := L.OptBool(3, false) m.pause() answer, err := s.Prompt(L.Context(), label, secret) m.resume() if err != nil { L.RaiseError("prompt: %v", err) } L.Push(lua.LString(answer)) return 1 })) t.RawSetString("cookies", L.NewFunction(func(L *lua.LState) int { target := L.OptString(2, acc.Site) out := L.NewTable() for name, value := range s.Cookies(target) { out.RawSetString(name, lua.LString(value)) } L.Push(out) return 1 })) t.RawSetString("account", accountTable(L, acc, false)) return t } // request implements ctx:get and ctx:post. opts may have form (a table of // fields), body and content_type, referer, and headers (a table). func request(L *lua.LState, s Session, m *meter, method string) int { r := fetch.Request{Method: method, URL: L.CheckString(2)} if opts := L.OptTable(3, nil); opts != nil { opts.ForEach(func(k, v lua.LValue) { switch k.String() { case "form": r.Form = formValues(L, v) case "body": r.Body = []byte(optString(L, "body", v)) case "content_type": r.ContentType = optString(L, "content_type", v) case "referer": r.Referer = optString(L, "referer", v) case "headers": r.Header = map[string]string{} checkTable(L, "headers", v).ForEach(func(name, value lua.LValue) { r.Header[name.String()] = optString(L, "header "+name.String(), value) }) default: L.ArgError(3, "unknown option "+k.String()+" (known: form, body, content_type, referer, headers)") } }) } m.pause() resp, err := s.Do(L.Context(), r) m.resume() if err != nil { L.RaiseError("%s %s: %v", method, r.URL, err) } L.Push(responseTable(L, resp)) return 1 } // responseTable is a response as Lua sees it: status, url, verdict, body, // headers (lower-case names), doc and challenge. func responseTable(L *lua.LState, resp *fetch.Response) *lua.LTable { headers := L.NewTable() for name, values := range resp.Header { if len(values) > 0 { headers.RawSetString(strings.ToLower(name), lua.LString(values[0])) } } // A page that does not parse still has a body. doc, err := goquery.NewDocumentFromReader(bytes.NewReader(resp.Body)) if err != nil { doc = goquery.NewDocumentFromNode(&html.Node{Type: html.DocumentNode}) } out := L.NewTable() out.RawSetString("status", lua.LNumber(resp.Status)) out.RawSetString("url", lua.LString(resp.FinalURL)) out.RawSetString("verdict", lua.LString(resp.Verdict.String())) out.RawSetString("body", lua.LString(resp.Body)) out.RawSetString("headers", headers) out.RawSetString("doc", pushNode(L, doc.Selection)) if resp.Challenge != "" { out.RawSetString("challenge", lua.LString(resp.Challenge)) } return out } func formValues(L *lua.LState, v lua.LValue) url.Values { form := url.Values{} checkTable(L, "form", v).ForEach(func(name, value lua.LValue) { switch value.(type) { case lua.LString, lua.LNumber, lua.LBool: form.Set(name.String(), value.String()) default: L.ArgError(3, "form field "+name.String()+" must be a string, number or boolean, got "+value.Type().String()) } }) return form } func checkTable(L *lua.LState, option string, v lua.LValue) *lua.LTable { t, ok := v.(*lua.LTable) if !ok { L.ArgError(3, option+" must be a table, got "+v.Type().String()) } return t } func optString(L *lua.LState, option string, v lua.LValue) string { s, ok := v.(lua.LString) if !ok { L.ArgError(3, option+" must be a string, got "+v.Type().String()) } return string(s) }