Add session mode: signing in and adding to the cart.
With cart_mode = "session", dibs signs in to the shop's account and puts an item in the cart when it fires. The account's cookies are kept apart from the watcher's and stored encrypted, with the key in the OS keyring. Without a keyring, they're stored in a file only you can read. An alert now goes out right away, without a cart link, and a second one follows once the item is in the cart. If adding fails, the second alert carries the cart link instead. Amazon only accepts additions its page scripts have seen, so plugins can now press a button in headless Chrome with ctx:click. The TUI asks for one-time codes and shows the plugin's warning about account locks in a modal. 'dibs login' signs in from a terminal, or with --browser in a Chrome window, and 'dibs logout' deletes the cookies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e2cbc1a55c
commit
15a34e1f84
39 files changed
+3529
-163
No files matched your search
@@ -0,0 +1,389 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
)
|
||||
|
||||
// fakeAmazon imitates the sign-in, product page and cart of amazon.de, as
|
||||
// far as the plugin uses them. The product page is a saved real one.
|
||||
type fakeAmazon struct {
|
||||
t *testing.T
|
||||
// product is the saved page as a signed-in customer sees it, guest as
|
||||
// it was saved, signed out.
|
||||
product, guest string
|
||||
|
||||
mu sync.Mutex
|
||||
// captcha makes the password step ask for a captcha.
|
||||
captcha bool
|
||||
// expireOnProduct ends the session when the product page loads.
|
||||
expireOnProduct bool
|
||||
// skipped is set once the request for a phone number was skipped.
|
||||
skipped bool
|
||||
// session is the signed-in session's cookie value.
|
||||
session string
|
||||
inCart bool
|
||||
// adds counts the additions to the account's cart.
|
||||
adds int
|
||||
}
|
||||
|
||||
const fakeASIN = "B0DK51S84Z"
|
||||
|
||||
func newFakeAmazon(t *testing.T) *fakeAmazon {
|
||||
page := savedPage(t, "fulfilled-de")
|
||||
|
||||
return &fakeAmazon{t: t, product: signedIn(page), guest: string(page)}
|
||||
}
|
||||
|
||||
// savedPage reads testdata/amazon/pages/<name>.html. Saved pages are not
|
||||
// tracked, so tests without them are skipped.
|
||||
func savedPage(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
|
||||
page, err := os.ReadFile(filepath.Join(testdata, "amazon", "pages", name+".html"))
|
||||
if errors.Is(err, os.ErrNotExist) { t.Skip("no saved page " + name + ": run `dibs fixtures` to fetch the product pages") }
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
return page
|
||||
}
|
||||
|
||||
// signedIn turns a saved page, which is a guest's, into what a signed-in
|
||||
// customer sees.
|
||||
func signedIn(page []byte) string {
|
||||
html := regexp.MustCompile(`https://www\.amazon\.de/ap/signin\?[^"]*`).ReplaceAllString(string(page), "https://www.amazon.de/gp/css/homepage.html")
|
||||
return strings.ReplaceAll(html, "nav_ya_signin", "nav_youraccount_btn")
|
||||
}
|
||||
|
||||
// state returns whether the item is in the cart, how often it was added and
|
||||
// the session.
|
||||
func (f *fakeAmazon) state() (bool, int, string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
return f.inCart, f.adds, f.session
|
||||
}
|
||||
|
||||
func (f *fakeAmazon) setExpireOnProduct(on bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
f.expireOnProduct = on
|
||||
}
|
||||
|
||||
const signedOutNav = `<div id="nav-link-accountList"><a href="https://www.amazon.de/ap/signin?openid.assoc_handle=deflex" data-csa-c-content-id="nav_ya_signin">Hallo, anmelden</a></div>`
|
||||
|
||||
func signInPage(fields string) string {
|
||||
return `<form name="signIn" method="post" action="https://www.amazon.de/ap/signin">` + fields + `<input type="submit" id="signInSubmit"></form>`
|
||||
}
|
||||
|
||||
func (f *fakeAmazon) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
_ = r.ParseForm()
|
||||
|
||||
cookie, _ := r.Cookie("at-acbde")
|
||||
signedIn := cookie != nil && f.session != "" && cookie.Value == f.session
|
||||
|
||||
write := func(body string) { _, _ = w.Write([]byte("<html><body>" + body + "</body></html>")) }
|
||||
|
||||
switch {
|
||||
case r.URL.Path == "/ap/signin" && r.Method == "GET" && r.URL.Query().Get("skip") == "fixup":
|
||||
f.skipped = true
|
||||
write(`<form id="auth-mfa-form" method="post" action="/ap/signin"><input type="hidden" name="mfaToken" value="mfa"><input name="otpCode"><input type="checkbox" name="rememberDevice"></form>`)
|
||||
case r.URL.Path == "/ap/signin" && r.Method == "GET":
|
||||
if r.URL.Query().Get("openid.assoc_handle") != "deflex" { f.t.Errorf("sign-in URL %s", r.URL) }
|
||||
|
||||
http.SetCookie(w, &http.Cookie{Name: "session-id", Value: "guest", Path: "/"})
|
||||
write(signInPage(`<input type="hidden" name="appActionToken" value="tok1"><input type="email" name="email">`))
|
||||
case r.URL.Path == "/ap/accountfixup":
|
||||
f.t.Error("dibs submitted the phone number form")
|
||||
case r.URL.Path == "/ap/signin" && r.Form.Has("otpCode"):
|
||||
if r.Form.Get("otpCode") != "123456" || r.Form.Get("mfaToken") != "mfa" {
|
||||
write(`<form id="auth-mfa-form" method="post" action="/ap/signin"><div id="auth-error-message-box">Wrong code</div></form>`)
|
||||
return
|
||||
}
|
||||
|
||||
f.session = "signed-in"
|
||||
http.SetCookie(w, &http.Cookie{Name: "at-acbde", Value: f.session, Path: "/"})
|
||||
http.Redirect(w, r, "/?ref_=signin", http.StatusFound)
|
||||
case r.URL.Path == "/ap/signin" && r.Form.Has("password"):
|
||||
switch {
|
||||
case r.Form.Get("appActionToken") != "tok2" || r.Form.Get("email") != "me@example.com":
|
||||
f.t.Errorf("password step got %v", r.Form)
|
||||
case r.Form.Get("password") != "hunter2":
|
||||
write(`<div id="auth-error-message-box">Ihr Passwort ist falsch</div>` + signInPage(`<input type="hidden" name="appActionToken" value="tok2"><input type="password" name="password">`))
|
||||
case f.captcha:
|
||||
write(`<img id="auth-captcha-image" src="/captcha.jpg">` + signInPage(`<input type="password" name="password">`))
|
||||
default:
|
||||
// As on amazon.de: a request for a phone number, with a link
|
||||
// to skip it.
|
||||
write(`<form id="auth-account-fixup-phone-form" name="accountFixup" method="post" action="https://www.amazon.de/ap/accountfixup">` +
|
||||
`<input type="tel" name="mobilePhoneNumber"><input type="submit"></form>` +
|
||||
`<a id="ap-account-fixup-phone-skip-link" href="https://www.amazon.de/ap/signin?skip=fixup">Nicht jetzt</a>`)
|
||||
}
|
||||
case r.URL.Path == "/ap/signin":
|
||||
if r.Form.Get("appActionToken") != "tok1" || r.Form.Get("email") != "me@example.com" { f.t.Errorf("email step got %v", r.Form) }
|
||||
|
||||
write(signInPage(`<input type="hidden" name="appActionToken" value="tok2"><input type="hidden" name="email" value="me@example.com"><input type="password" name="password"><input type="checkbox" name="rememberMe" value="true">`))
|
||||
case r.URL.Path == "/" && signedIn:
|
||||
write(`<div id="nav-link-accountList"><a href="/gp/css/homepage.html" data-csa-c-content-id="nav_youraccount_btn">Hallo, Me</a></div>`)
|
||||
case r.URL.Path == "/gp/cart/view.html" && !signedIn:
|
||||
write(signedOutNav + `<div id="sc-active-cart"></div>`)
|
||||
case r.URL.Path == "/gp/cart/view.html":
|
||||
items := ""
|
||||
if f.inCart { items = `<div class="sc-list-item" data-asin="` + fakeASIN + `"></div>` }
|
||||
|
||||
write(`<div id="sc-active-cart">` + items + `</div><div id="sc-saved-cart"><div data-asin="` + fakeASIN + `"></div></div>`)
|
||||
case r.URL.Path == "/dp/"+fakeASIN:
|
||||
if f.expireOnProduct { f.session = "expired" }
|
||||
|
||||
_, _ = w.Write([]byte(f.product))
|
||||
case strings.HasPrefix(r.URL.Path, "/cart/add-to-cart/") && r.Method == "POST":
|
||||
for name, want := range map[string]string{
|
||||
"anti-csrftoken-a2z": "hOgocjo+1KjiCPsF4LU3lHBSy+VeMLo/5zSecGDC+HnZAAAAAGrOvcg1Y2U5ZjJiZC0zZGNiLTRjYzctYWNhNC05YjE0ZTkzMjk0ZTA=",
|
||||
"items[0.base][quantity]": "1",
|
||||
"items[0.base][asin]": fakeASIN,
|
||||
"submit.add-to-cart": "In den Einkaufswagen",
|
||||
} {
|
||||
if got := r.Form.Get(name); got != want { f.t.Errorf("add to cart: %s = %q, want %q", name, got, want) }
|
||||
}
|
||||
|
||||
if r.Form.Has("submit.buy-now") { f.t.Error("add to cart pressed buy now") }
|
||||
|
||||
if signedIn { f.inCart, f.adds = true, f.adds+1 }
|
||||
|
||||
http.Redirect(w, r, "/cart/smart-wagon?newItems="+fakeASIN, http.StatusFound)
|
||||
case r.URL.Path == "/cart/smart-wagon":
|
||||
// A guest's item goes into a guest cart, under Amazon's real
|
||||
// signed-out header.
|
||||
header := ""
|
||||
if !signedIn { header = f.guest }
|
||||
|
||||
write(header + `<div id="NATC_SMART_WAGON_CONF_MSG_SUCCESS">In den Einkaufswagen gelegt</div>`)
|
||||
default:
|
||||
f.t.Errorf("unexpected %s %s", r.Method, r.URL)
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// amazonSession sends the plugin's requests to the fake instead of
|
||||
// www.amazon.de.
|
||||
type amazonSession struct {
|
||||
client *fetch.Client
|
||||
srv string
|
||||
codes int
|
||||
}
|
||||
|
||||
const amazonOrigin = "https://www.amazon.de"
|
||||
|
||||
func (s *amazonSession) local(u string) string { return strings.Replace(u, amazonOrigin, s.srv, 1) }
|
||||
func (s *amazonSession) remote(u string) string { return strings.Replace(u, s.srv, amazonOrigin, 1) }
|
||||
|
||||
func (s *amazonSession) Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) {
|
||||
if !strings.HasPrefix(r.URL, amazonOrigin+"/") { return nil, errors.New("request outside amazon.de: " + r.URL) }
|
||||
|
||||
r.URL = s.local(r.URL)
|
||||
if r.Referer != "" { r.Referer = s.local(r.Referer) }
|
||||
|
||||
resp, err := s.client.Do(ctx, r)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
resp.URL, resp.FinalURL = s.remote(resp.URL), s.remote(resp.FinalURL)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Click submits the button's form as Chrome does: every field, the button's
|
||||
// own name and value, to the button's formaction if it has one.
|
||||
func (s *amazonSession) Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error) {
|
||||
page, err := s.Do(ctx, fetch.Request{Method: "GET", URL: rawURL})
|
||||
if err != nil { return nil, err }
|
||||
|
||||
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page.Body))
|
||||
if err != nil { return nil, err }
|
||||
|
||||
button := doc.Find(sel).First()
|
||||
if button.Length() == 0 { return nil, errors.New("no " + sel) }
|
||||
|
||||
f := button.Closest("form")
|
||||
form := url.Values{}
|
||||
|
||||
f.Find("input[name]").Each(func(_ int, in *goquery.Selection) {
|
||||
kind := in.AttrOr("type", "text")
|
||||
if kind == "submit" || (kind == "checkbox" && in.AttrOr("checked", "-") == "-") { return }
|
||||
|
||||
form.Add(in.AttrOr("name", ""), in.AttrOr("value", ""))
|
||||
})
|
||||
f.Find("select[name]").Each(func(_ int, sl *goquery.Selection) { form.Add(sl.AttrOr("name", ""), sl.Find("option").First().AttrOr("value", "")) })
|
||||
form.Add(button.AttrOr("name", ""), button.AttrOr("value", ""))
|
||||
|
||||
return s.Do(ctx, fetch.Request{Method: "POST", URL: amazonOrigin + button.AttrOr("formaction", f.AttrOr("action", "")), Form: form, Referer: rawURL})
|
||||
}
|
||||
|
||||
func (s *amazonSession) Prompt(_ context.Context, label string, secret bool) (string, error) {
|
||||
s.codes++
|
||||
return "123456", nil
|
||||
}
|
||||
|
||||
func (s *amazonSession) Cookies(u string) map[string]string {
|
||||
parsed, _ := url.Parse(s.local(u))
|
||||
|
||||
out := map[string]string{}
|
||||
for _, c := range s.client.Jar().Cookies(parsed) { out[c.Name] = c.Value }
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
type noWait struct{}
|
||||
|
||||
func (noWait) WaitCheck(context.Context, string) error { return nil }
|
||||
func (noWait) Wait(context.Context, string) error { return nil }
|
||||
|
||||
func newAmazonSession(t *testing.T) (*fakeAmazon, *amazonSession) {
|
||||
fake := newFakeAmazon(t)
|
||||
srv := httptest.NewServer(fake)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
client, err := fetch.New(fetch.Options{Limiter: noWait{}})
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
return fake, &amazonSession{client: client, srv: srv.URL}
|
||||
}
|
||||
|
||||
var amazonAccount = Account{Username: "me@example.com", Password: "hunter2", TwoFA: true, Site: "https://www.amazon.de/"}
|
||||
|
||||
func TestAmazonSession(t *testing.T) {
|
||||
p := builtin(t, "amazon")
|
||||
fake, s := newAmazonSession(t)
|
||||
ctx := context.Background()
|
||||
|
||||
product := "https://www.amazon.de/dp/" + fakeASIN
|
||||
|
||||
// Without a session, the cart shows a guest.
|
||||
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Fatalf("before signing in: got %v, want ErrSignedOut", err) }
|
||||
|
||||
if err := p.Login(ctx, s, amazonAccount); err != nil { t.Fatal(err) }
|
||||
if s.codes != 1 { t.Errorf("asked for %d codes, want 1", s.codes) }
|
||||
if !fake.skipped { t.Error("the request for a phone number was not skipped") }
|
||||
|
||||
// The session runs out between the cart and the click. The page the
|
||||
// click leads to has Amazon's real signed-out header.
|
||||
fake.setExpireOnProduct(true)
|
||||
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("session ran out before the click: got %v, want ErrSignedOut", err) }
|
||||
if inCart, _, _ := fake.state(); inCart { t.Error("added to the account's cart while signed out") }
|
||||
fake.setExpireOnProduct(false)
|
||||
|
||||
if err := p.Login(ctx, s, amazonAccount); err != nil { t.Fatal(err) }
|
||||
|
||||
// The item saved for later is not in the cart.
|
||||
cart, err := p.AddToCart(ctx, s, amazonAccount, product)
|
||||
if err != nil { t.Fatal(err) }
|
||||
if cart != "https://www.amazon.de/gp/cart/view.html" { t.Errorf("cart page %q", cart) }
|
||||
if inCart, adds, _ := fake.state(); !inCart || adds != 1 { t.Errorf("in cart %v after %d adds", inCart, adds) }
|
||||
|
||||
// Already in the cart: nothing is added again.
|
||||
if _, err := p.AddToCart(ctx, s, amazonAccount, product); err != nil { t.Fatal(err) }
|
||||
if _, adds, _ := fake.state(); adds != 1 { t.Errorf("%d adds, want 1: the item went in twice", adds) }
|
||||
|
||||
// The session runs out.
|
||||
fake.mu.Lock()
|
||||
fake.session, fake.inCart = "expired", false
|
||||
fake.mu.Unlock()
|
||||
|
||||
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("after the session ran out: got %v, want ErrSignedOut", err) }
|
||||
}
|
||||
|
||||
func TestAmazonLoginFailures(t *testing.T) {
|
||||
p := builtin(t, "amazon")
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
account Account
|
||||
captcha bool
|
||||
want string
|
||||
}{
|
||||
"wrong password": {Account{Username: "me@example.com", Password: "wrong", TwoFA: true, Site: amazonAccount.Site}, false, "Ihr Passwort ist falsch"},
|
||||
"captcha": {amazonAccount, true, "dibs login amazon --browser"},
|
||||
"twofa off": {Account{Username: "me@example.com", Password: "hunter2", Site: amazonAccount.Site}, false, "twofa is off"},
|
||||
"no password": {Account{Username: "me@example.com", Site: amazonAccount.Site}, false, "no password"},
|
||||
} {
|
||||
fake, s := newAmazonSession(t)
|
||||
fake.captcha = tc.captcha
|
||||
|
||||
err := p.Login(context.Background(), s, tc.account)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) { t.Errorf("%s: got %v, want an error containing %q", name, err, tc.want) }
|
||||
if _, _, session := fake.state(); session != "" { t.Errorf("%s: signed in", name) }
|
||||
}
|
||||
}
|
||||
|
||||
// pageSession serves saved real pages by path and refuses to send forms,
|
||||
// recording them instead.
|
||||
type pageSession struct {
|
||||
pages map[string][]byte
|
||||
posted []fetch.Request
|
||||
}
|
||||
|
||||
func (s *pageSession) Do(_ context.Context, r fetch.Request) (*fetch.Response, error) {
|
||||
if r.Method == "POST" {
|
||||
s.posted = append(s.posted, r)
|
||||
return nil, errors.New("stopped before posting")
|
||||
}
|
||||
|
||||
u, _ := url.Parse(r.URL)
|
||||
|
||||
page, ok := s.pages[u.Path]
|
||||
if !ok { return nil, errors.New("no saved page for " + u.Path) }
|
||||
|
||||
return fetch.NewResponse(r.URL, r.URL, 200, nil, page), nil
|
||||
}
|
||||
|
||||
func (s *pageSession) Click(context.Context, string, string) (*fetch.Response, error) {
|
||||
return nil, errors.New("no clicks on saved pages")
|
||||
}
|
||||
|
||||
func (s *pageSession) Prompt(context.Context, string, bool) (string, error) { return "", errors.New("no prompts") }
|
||||
func (s *pageSession) Cookies(string) map[string]string { return nil }
|
||||
|
||||
// TestAmazonSavedSessionPages runs the plugin on pages saved from a guest
|
||||
// session on amazon.de: the sign-in page, an empty cart and a cart holding
|
||||
// fakeASIN.
|
||||
func TestAmazonSavedSessionPages(t *testing.T) {
|
||||
p := builtin(t, "amazon")
|
||||
ctx := context.Background()
|
||||
|
||||
signin := savedPage(t, "session-signin-de")
|
||||
empty := savedPage(t, "session-cart-guest-de")
|
||||
full := savedPage(t, "session-cart-item-de")
|
||||
|
||||
product := "https://www.amazon.de/dp/" + fakeASIN
|
||||
|
||||
if _, err := p.AddToCart(ctx, &pageSession{pages: map[string][]byte{"/gp/cart/view.html": empty}}, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("guest cart: got %v, want ErrSignedOut", err) }
|
||||
|
||||
cart, err := p.AddToCart(ctx, &pageSession{pages: map[string][]byte{"/gp/cart/view.html": []byte(signedIn(full))}}, amazonAccount, product)
|
||||
if err != nil || cart == "" { t.Errorf("cart holding the item: %q, %v, want it found without adding", cart, err) }
|
||||
|
||||
// The first step of signing in asks for the email only. Its password
|
||||
// input is a hidden one for autofill.
|
||||
s := &pageSession{pages: map[string][]byte{"/ap/signin": signin}}
|
||||
if err := p.Login(ctx, s, amazonAccount); err == nil { t.Fatal("login went past the saved page") }
|
||||
if len(s.posted) != 1 { t.Fatalf("%d forms posted, want 1", len(s.posted)) }
|
||||
|
||||
r := s.posted[0]
|
||||
if !strings.HasPrefix(r.URL, "https://www.amazon.de/ax/claim?") { t.Errorf("posted to %s", r.URL) }
|
||||
if r.Form.Get("email") != amazonAccount.Username { t.Errorf("email = %q", r.Form.Get("email")) }
|
||||
if r.Form.Get("password") != "" { t.Error("the password went out with the email") }
|
||||
if r.Form.Get("anti-csrftoken-a2z") == "" || r.Form.Get("appAction") != "SIGNIN_CLAIM_COLLECT" { t.Errorf("hidden fields missing: %v", r.Form) }
|
||||
}
|
||||
@@ -84,14 +84,22 @@ local price_selectors = {
|
||||
"#priceblock_dealprice",
|
||||
}
|
||||
|
||||
-- split returns the TLD and ASIN of an Amazon product URL, or nil.
|
||||
local function split(url)
|
||||
-- tld_of returns the TLD of a URL on an Amazon site, or nil.
|
||||
local function tld_of(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
|
||||
|
||||
return tld
|
||||
end
|
||||
|
||||
-- split returns the TLD and ASIN of an Amazon product URL, or nil.
|
||||
local function split(url)
|
||||
local tld = tld_of(url)
|
||||
if not 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
|
||||
|
||||
@@ -165,9 +173,240 @@ local function find_price(doc)
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Session mode, for accounts with cart_mode = "session": signing in and
|
||||
-- adding to the cart.
|
||||
|
||||
-- The sign-in page of each marketplace is chosen by its association handle.
|
||||
local assoc_handles = {
|
||||
["de"] = "deflex",
|
||||
["fr"] = "frflex",
|
||||
["it"] = "itflex",
|
||||
["es"] = "esflex",
|
||||
["nl"] = "nlflex",
|
||||
["co.uk"] = "gbflex",
|
||||
["com"] = "usflex",
|
||||
}
|
||||
|
||||
local function origin(tld)
|
||||
return "https://www.amazon." .. tld
|
||||
end
|
||||
|
||||
local function escape(s)
|
||||
return (s:gsub("[^%w%-%._~]", function(c) return string.format("%%%02X", c:byte()) end))
|
||||
end
|
||||
|
||||
local function sign_in_url(tld)
|
||||
local id = escape("http://specs.openid.net/auth/2.0/identifier_select")
|
||||
|
||||
return origin(tld) .. "/ap/signin?openid.pape.max_auth_age=0"
|
||||
.. "&openid.return_to=" .. escape(origin(tld) .. "/")
|
||||
.. "&openid.identity=" .. id
|
||||
.. "&openid.assoc_handle=" .. assoc_handles[tld]
|
||||
.. "&openid.mode=checkid_setup"
|
||||
.. "&openid.claimed_id=" .. id
|
||||
.. "&openid.ns=" .. escape("http://specs.openid.net/auth/2.0")
|
||||
end
|
||||
|
||||
-- resolve turns a link or form action on the page at base into a URL. An
|
||||
-- empty action submits to the page itself.
|
||||
local function resolve(base, ref)
|
||||
base = base:match("^[^#]*")
|
||||
if not ref or ref == "" then return base end
|
||||
if ref:match("^[Hh][Tt][Tt][Pp][Ss]?://") then return ref end
|
||||
|
||||
local scheme, host = base:match("^(https?:)//([^/?#]+)")
|
||||
if ref:sub(1, 2) == "//" then return scheme .. ref end
|
||||
if ref:sub(1, 1) == "/" then return scheme .. "//" .. host .. ref end
|
||||
|
||||
return (base:match("^(https?://[^?]*/)") or (scheme .. "//" .. host .. "/")) .. ref
|
||||
end
|
||||
|
||||
-- form returns the action and fields of the first form sel matches, as a
|
||||
-- browser submits it without pressing a button. Of fields with the same
|
||||
-- name, the first wins: Amazon's add-to-cart form also holds the wish
|
||||
-- list's token.
|
||||
local function form(doc, sel)
|
||||
local f = doc:all(sel)[1]
|
||||
if not f then return nil end
|
||||
|
||||
local fields = {}
|
||||
|
||||
for _, input in ipairs(f:all("input[name]")) do
|
||||
local name = input:attr("name")
|
||||
local kind = (input:attr("type") or "text"):lower()
|
||||
|
||||
local button = kind == "submit" or kind == "image" or kind == "button"
|
||||
local unchecked = (kind == "checkbox" or kind == "radio") and not input:attr("checked")
|
||||
|
||||
if name ~= "" and not button and not unchecked and fields[name] == nil then fields[name] = input:attr("value") or "" end
|
||||
end
|
||||
|
||||
for _, select in ipairs(f:all("select[name]")) do
|
||||
local name = select:attr("name")
|
||||
if name ~= "" and fields[name] == nil then fields[name] = select:attr("option[selected]", "value") or select:attr("option", "value") or "" end
|
||||
end
|
||||
|
||||
return f:attr("action"), fields
|
||||
end
|
||||
|
||||
local function expect_page(page, what)
|
||||
if page.verdict == "challenge" or page.verdict == "needs-human" then
|
||||
error("a bot check blocks " .. what .. "; sign in with: dibs login amazon --browser", 0)
|
||||
end
|
||||
|
||||
if page.status >= 400 then error(what .. " answered HTTP " .. page.status, 0) end
|
||||
end
|
||||
|
||||
-- The header links to the sign-in page only when nobody is signed in.
|
||||
local function signed_out(doc)
|
||||
return doc:exists("[data-csa-c-content-id='nav_ya_signin'], #nav-link-accountList a[href*='/ap/signin']")
|
||||
end
|
||||
|
||||
local login_forms = {
|
||||
"form[name='signIn']",
|
||||
"form#ap_login_form",
|
||||
"form:has(input[name='email'])",
|
||||
"form:has(input[name='password'])",
|
||||
}
|
||||
|
||||
-- visible narrows a selector to inputs the user can type into. The first
|
||||
-- step asks for the email only, next to a hidden password input for
|
||||
-- autofill that a browser sends empty.
|
||||
local visible = ":not([type='hidden']):not(.aok-hidden)"
|
||||
|
||||
local function login_form(doc)
|
||||
for _, sel in ipairs(login_forms) do
|
||||
if doc:exists(sel) then return sel end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Requests to add a phone number to the account, which dibs turns down.
|
||||
local skip_links = { "#ap-account-fixup-phone-skip-link", "a[id^='ap-account-fixup'][id$='skip-link']" }
|
||||
|
||||
local function skip_link(doc)
|
||||
for _, sel in ipairs(skip_links) do
|
||||
local href = doc:attr(sel, "href")
|
||||
if href then return href end
|
||||
end
|
||||
|
||||
return nil
|
||||
end
|
||||
|
||||
-- Steps of the sign-in only a person can take.
|
||||
local human_steps = {
|
||||
{ "#auth-captcha-image, input[name='cvf_captcha_input'], #cvf-aamation-challenge-iframe, #aacb-captcha-header", "a captcha" },
|
||||
{ "#resend-approval-form, #resend-approval-link, input[name='transactionApprovalStatus']", "an approval on your phone" },
|
||||
{ "form[action*='/ap/cvf/']", "a verification" },
|
||||
}
|
||||
|
||||
local function sign_in(ctx, account)
|
||||
local tld = account.site and tld_of(account.site)
|
||||
if not tld then error("not an Amazon site: " .. tostring(account.site), 0) end
|
||||
if not account.password then error("no password: set password_env for the account, or sign in with: dibs login amazon --browser", 0) end
|
||||
|
||||
local page = ctx:get(account.login_url or sign_in_url(tld))
|
||||
|
||||
for step = 1, 8 do
|
||||
expect_page(page, "the sign-in")
|
||||
|
||||
local doc = page.doc
|
||||
local form_sel = login_form(doc)
|
||||
|
||||
if not page.url:find("/ap/", 1, true) and not form_sel then return end
|
||||
|
||||
-- The first page has no error to report yet.
|
||||
local problem = step > 1 and doc:text("#auth-error-message-box")
|
||||
if problem then error("Amazon refused the sign-in: " .. problem, 0) end
|
||||
|
||||
for _, s in ipairs(human_steps) do
|
||||
if doc:exists(s[1]) then error("Amazon asks for " .. s[2] .. "; sign in with: dibs login amazon --browser", 0) end
|
||||
end
|
||||
|
||||
local action, fields
|
||||
local skip = skip_link(doc)
|
||||
|
||||
if skip then
|
||||
page = ctx:get(resolve(page.url, skip), { referer = page.url })
|
||||
elseif form_sel then
|
||||
action, fields = form(doc, form_sel)
|
||||
|
||||
local email = doc:exists(form_sel .. " input[name='email']" .. visible)
|
||||
local password = doc:exists(form_sel .. " input[name='password']" .. visible)
|
||||
|
||||
if not email and not password then error("unexpected sign-in step at " .. page.url, 0) end
|
||||
|
||||
if email then fields.email = account.username end
|
||||
|
||||
if password then
|
||||
fields.password = account.password
|
||||
fields.rememberMe = "true"
|
||||
end
|
||||
elseif doc:exists("#auth-mfa-form") then
|
||||
if not account.twofa then error("Amazon asks for a one-time code, but twofa is off for the account", 0) end
|
||||
|
||||
action, fields = form(doc, "#auth-mfa-form")
|
||||
fields.otpCode = ctx:prompt("Amazon one-time code for " .. account.username, false)
|
||||
fields.rememberDevice = "true"
|
||||
else
|
||||
error("unexpected page while signing in: " .. page.url, 0)
|
||||
end
|
||||
|
||||
if not skip then page = ctx:post(resolve(page.url, action), { form = fields, referer = page.url }) end
|
||||
end
|
||||
|
||||
error("signing in took more steps than expected, ending at " .. page.url, 0)
|
||||
end
|
||||
|
||||
local function in_cart(doc, asin)
|
||||
return doc:exists("#sc-active-cart [data-asin='" .. asin .. "']")
|
||||
end
|
||||
|
||||
local function added(page)
|
||||
return page.url:find("/smart-wagon", 1, true) ~= nil
|
||||
or page.url:find("/huc/", 1, true) ~= nil
|
||||
or page.doc:exists("#NATC_SMART_WAGON_CONF_MSG_SUCCESS, #sw-atc-confirmation, #huc-v2-order-row-confirm-text, #attachDisplayAddBaseAlert")
|
||||
end
|
||||
|
||||
local function add_to_cart(ctx, url)
|
||||
local tld, asin = split(url)
|
||||
if not tld then error("not an Amazon product page: " .. url, 0) end
|
||||
|
||||
local cart = ctx.account.cart_url or (origin(tld) .. "/gp/cart/view.html")
|
||||
|
||||
local page = ctx:get(cart)
|
||||
expect_page(page, "the cart")
|
||||
if signed_out(page.doc) then return false end
|
||||
|
||||
-- Adding it again would put a second copy in the cart.
|
||||
if in_cart(page.doc, asin) then return true, cart end
|
||||
|
||||
-- Amazon refuses the add-to-cart form unless its page scripts ran, so a
|
||||
-- browser presses the button.
|
||||
page = ctx:click(origin(tld) .. "/dp/" .. asin, "#add-to-cart-button")
|
||||
expect_page(page, "adding to the cart")
|
||||
|
||||
-- A session that ran out since the cart was checked added it to a guest
|
||||
-- cart.
|
||||
if signed_out(page.doc) then return false end
|
||||
if added(page) then return true, cart end
|
||||
|
||||
page = ctx:get(cart, { referer = page.url })
|
||||
expect_page(page, "the cart")
|
||||
if in_cart(page.doc, asin) then return true, cart end
|
||||
if signed_out(page.doc) then return false end
|
||||
|
||||
error("the item did not show up in the cart", 0)
|
||||
end
|
||||
|
||||
return {
|
||||
name = "amazon",
|
||||
|
||||
session_warning = "Signing in to Amazon automatically can get the account locked or sent through extra verification. "
|
||||
.. "dibs signs in only when it has no session, but the risk remains. "
|
||||
.. "Signing in yourself with 'dibs login amazon --browser' avoids the automated sign-in.",
|
||||
|
||||
matches = function(url)
|
||||
return split(url) ~= nil
|
||||
end,
|
||||
@@ -204,4 +443,7 @@ return {
|
||||
|
||||
return "https://www.amazon." .. tld .. "/gp/aws/cart/add.html?ASIN.1=" .. (id or asin) .. "&Quantity.1=1"
|
||||
end,
|
||||
|
||||
login = sign_in,
|
||||
add_to_cart = add_to_cart,
|
||||
}
|
||||
+50
-21
@@ -46,6 +46,9 @@ type Result struct {
|
||||
// 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
|
||||
@@ -54,6 +57,9 @@ 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
|
||||
@@ -86,7 +92,12 @@ func Load(name, source string, code []byte, limits Limits, logger *slog.Logger)
|
||||
shortCalls.Lock()
|
||||
defer shortCalls.Unlock()
|
||||
|
||||
if err := p.reset(); err != nil { return nil, fmt.Errorf("plugin %s (%s): %w", name, source, err) }
|
||||
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
|
||||
}
|
||||
@@ -98,6 +109,24 @@ func (p *Plugin) reset() error {
|
||||
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))
|
||||
@@ -105,38 +134,37 @@ func (p *Plugin) reset() error {
|
||||
fn, err := L.Load(bytes.NewReader(p.code), p.chunk)
|
||||
if err != nil {
|
||||
L.Close()
|
||||
return luaError(err)
|
||||
return nil, nil, luaError(err)
|
||||
}
|
||||
|
||||
var tbl *lua.LTable
|
||||
var t *table
|
||||
|
||||
err = run(L, context.Background(), p.limits.Timeout, p.limits.MemoryBytes, func() error {
|
||||
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)
|
||||
|
||||
t, ok := ret.(*lua.LTable)
|
||||
tbl, ok := ret.(*lua.LTable)
|
||||
if !ok { return fmt.Errorf("must return a table, got %s", ret.Type()) }
|
||||
|
||||
tbl = t
|
||||
return nil
|
||||
read, err := p.readTable(tbl)
|
||||
t = read
|
||||
return err
|
||||
})
|
||||
if err == nil { err = p.readTable(tbl) }
|
||||
if err != nil {
|
||||
L.Close()
|
||||
return err
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
p.state = L
|
||||
return nil
|
||||
return L, t, nil
|
||||
}
|
||||
|
||||
// readTable checks the plugin table and picks up its functions.
|
||||
func (p *Plugin) readTable(tbl *lua.LTable) error {
|
||||
func (p *Plugin) readTable(tbl *lua.LTable) (*table, error) {
|
||||
var problems []string
|
||||
|
||||
funcs := map[string]*lua.LFunction{}
|
||||
t := &table{funcs: map[string]*lua.LFunction{}}
|
||||
|
||||
tbl.ForEach(func(k, v lua.LValue) {
|
||||
key := k.String()
|
||||
@@ -148,28 +176,29 @@ func (p *Plugin) readTable(tbl *lua.LTable) error {
|
||||
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)
|
||||
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 { funcs[key] = fn } else { problems = append(problems, fmt.Sprintf("%s must be a function, got %s", key, v.Type())) }
|
||||
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: name, %s)", key, strings.Join(hooks, ", ")))
|
||||
problems = append(problems, fmt.Sprintf("unknown key %q (known: %s, %s)", key, strings.Join(tableKeys, ", "), strings.Join(hooks, ", ")))
|
||||
}
|
||||
})
|
||||
|
||||
if funcs["parse"] == nil && !slices.ContainsFunc(problems, func(s string) bool { return strings.HasPrefix(s, "parse ") }) {
|
||||
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 errors.New(strings.Join(problems, "; "))
|
||||
return nil, errors.New(strings.Join(problems, "; "))
|
||||
}
|
||||
|
||||
p.funcs = funcs
|
||||
return nil
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (p *Plugin) Has(hook string) bool {
|
||||
@@ -197,7 +226,7 @@ func (p *Plugin) call(ctx context.Context, hook string, nret int, args func(L *l
|
||||
|
||||
var out []lua.LValue
|
||||
|
||||
err := run(L, ctx, p.limits.Timeout, p.limits.MemoryBytes, func() error {
|
||||
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)) }
|
||||
|
||||
+38
-16
@@ -115,15 +115,13 @@ func cappedRep(limit int64) lua.LGFunction {
|
||||
|
||||
// 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 {
|
||||
func run(L *lua.LState, parent context.Context, timeout time.Duration, m *meter, 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)
|
||||
go m.watch(ctx, done, cancel)
|
||||
|
||||
L.SetContext(ctx)
|
||||
defer L.RemoveContext()
|
||||
@@ -133,7 +131,7 @@ func run(L *lua.LState, parent context.Context, timeout time.Duration, memLimit
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case overLimit.Load():
|
||||
case m.overLimit.Load():
|
||||
return ErrMemoryLimit
|
||||
case parent.Err() != nil:
|
||||
return parent.Err()
|
||||
@@ -144,16 +142,33 @@ func run(L *lua.LState, parent context.Context, timeout time.Duration, memLimit
|
||||
}
|
||||
}
|
||||
|
||||
// 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())
|
||||
}
|
||||
// meter is the memory watchdog of one call. It measures the heap growth of
|
||||
// the whole process, so host functions that wait on the network or the user
|
||||
// pause it: what they allocate is the host's, and the measurement starts
|
||||
// over when they return.
|
||||
type meter struct {
|
||||
limit int64
|
||||
base atomic.Int64
|
||||
paused atomic.Bool
|
||||
overLimit atomic.Bool
|
||||
}
|
||||
|
||||
base := heap()
|
||||
func newMeter(limit int64) *meter {
|
||||
m := &meter{limit: limit}
|
||||
m.base.Store(heapBytes())
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *meter) pause() { m.paused.Store(true) }
|
||||
|
||||
func (m *meter) resume() {
|
||||
m.base.Store(heapBytes())
|
||||
m.paused.Store(false)
|
||||
}
|
||||
|
||||
// watch cancels the call once the heap has grown by more than the limit.
|
||||
func (m *meter) watch(ctx context.Context, done <-chan struct{}, cancel context.CancelFunc) {
|
||||
ticker := time.NewTicker(watchInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
@@ -164,8 +179,8 @@ func watchMemory(ctx context.Context, done <-chan struct{}, limit int64, overLim
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if heap()-base > limit {
|
||||
overLimit.Store(true)
|
||||
if !m.paused.Load() && heapBytes()-m.base.Load() > m.limit {
|
||||
m.overLimit.Store(true)
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
@@ -173,6 +188,13 @@ func watchMemory(ctx context.Context, done <-chan struct{}, limit int64, overLim
|
||||
}
|
||||
}
|
||||
|
||||
func heapBytes() int64 {
|
||||
sample := []metrics.Sample{{Name: "/memory/classes/heap/objects:bytes"}}
|
||||
metrics.Read(sample)
|
||||
|
||||
return int64(sample[0].Value.Uint64())
|
||||
}
|
||||
|
||||
// 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 {
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
)
|
||||
|
||||
// fakeSession answers the requests of testdata/session/shop.lua.
|
||||
type fakeSession struct {
|
||||
mu sync.Mutex
|
||||
requests []fetch.Request
|
||||
signedIn bool
|
||||
prompts []string
|
||||
// prompt, if set, answers prompts instead of "123456".
|
||||
prompt func(ctx context.Context) (string, error)
|
||||
}
|
||||
|
||||
func (f *fakeSession) Do(_ context.Context, r fetch.Request) (*fetch.Response, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
f.requests = append(f.requests, r)
|
||||
|
||||
body, header := "<p>sign in</p>", http.Header{}
|
||||
|
||||
switch {
|
||||
case r.Method == "POST" && strings.HasSuffix(r.URL, "/signin"):
|
||||
if r.Form.Get("password") == "hunter2" && r.Form.Get("code") == "123456" {
|
||||
f.signedIn = true
|
||||
body = `<p id="result">welcome</p>`
|
||||
}
|
||||
case r.Method == "POST" && r.URL == "https://shop.test/cart" && r.Header["X-Test"] == "yes":
|
||||
header.Set("X-Cart", "1")
|
||||
}
|
||||
|
||||
return fetch.NewResponse(r.URL, r.URL, 200, header, []byte(body)), nil
|
||||
}
|
||||
|
||||
// Click submits the add button's form, as the shop's page would.
|
||||
func (f *fakeSession) Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error) {
|
||||
form := url.Values{"items[0][quantity]": {"1"}, "submit.add-to-cart": {"Add"}}
|
||||
|
||||
return f.Do(ctx, fetch.Request{Method: "POST", URL: strings.TrimSuffix(rawURL, "item") + "cart", Form: form, Header: map[string]string{"X-Test": "yes"}})
|
||||
}
|
||||
|
||||
func (f *fakeSession) Prompt(ctx context.Context, label string, secret bool) (string, error) {
|
||||
f.mu.Lock()
|
||||
f.prompts = append(f.prompts, label)
|
||||
f.mu.Unlock()
|
||||
|
||||
if !secret { return "", errors.New("want a secret prompt") }
|
||||
if f.prompt != nil { return f.prompt(ctx) }
|
||||
|
||||
return "123456", nil
|
||||
}
|
||||
|
||||
func (f *fakeSession) Cookies(string) map[string]string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
if f.signedIn { return map[string]string{"session": "yes"} }
|
||||
|
||||
return map[string]string{}
|
||||
}
|
||||
|
||||
func shopPlugin(t *testing.T, limits Limits) *Plugin {
|
||||
t.Helper()
|
||||
|
||||
path := filepath.Join(testdata, "session", "shop.lua")
|
||||
|
||||
code, err := os.ReadFile(path)
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
p, err := Load("shop", path, code, limits, discardLogger())
|
||||
if err != nil { t.Fatal(err) }
|
||||
t.Cleanup(p.Close)
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
var shopAccount = Account{Username: "me@example.com", Password: "hunter2", Site: "https://shop.test/", CartURL: "https://shop.test/cart"}
|
||||
|
||||
func TestSessionLogin(t *testing.T) {
|
||||
p := shopPlugin(t, DefaultLimits())
|
||||
if p.SessionWarning != "Automated logins can lock the account." { t.Errorf("session warning %q", p.SessionWarning) }
|
||||
|
||||
s := &fakeSession{}
|
||||
if err := p.Login(context.Background(), s, shopAccount); err != nil { t.Fatal(err) }
|
||||
|
||||
if len(s.prompts) != 1 || s.prompts[0] != "code for me@example.com" { t.Errorf("prompts %q", s.prompts) }
|
||||
if len(s.requests) != 2 { t.Fatalf("%d requests, want 2", len(s.requests)) }
|
||||
if r := s.requests[1]; r.Referer != "https://shop.test/signin" || r.Form.Get("user") != "me@example.com" { t.Errorf("sign-in form %+v", r) }
|
||||
|
||||
wrong := shopAccount
|
||||
wrong.Password = "wrong"
|
||||
if err := p.Login(context.Background(), &fakeSession{}, wrong); err == nil || !strings.Contains(err.Error(), "refused") { t.Errorf("wrong password: %v", err) }
|
||||
}
|
||||
|
||||
func TestSessionAddToCart(t *testing.T) {
|
||||
p := shopPlugin(t, DefaultLimits())
|
||||
|
||||
cart, err := p.AddToCart(context.Background(), &fakeSession{}, shopAccount, "https://shop.test/item/ok")
|
||||
if err != nil || cart != "https://shop.test/cart" { t.Errorf("added: %q, %v", cart, err) }
|
||||
|
||||
if _, err := p.AddToCart(context.Background(), &fakeSession{}, shopAccount, "https://shop.test/item/signedout"); !errors.Is(err, ErrSignedOut) { t.Errorf("signed out: got %v", err) }
|
||||
if _, err := p.AddToCart(context.Background(), &fakeSession{}, shopAccount, "https://shop.test/item/nonsense"); err == nil { t.Error("a string result: want an error") }
|
||||
|
||||
if _, err := p.AddToCart(context.Background(), &fakeSession{}, shopAccount, "https://shop.test/item/click"); err != nil { t.Errorf("click: %v", err) }
|
||||
}
|
||||
|
||||
// A login waiting for the user must not hold up the plugin's checks.
|
||||
func TestSessionCallDoesNotBlockParse(t *testing.T) {
|
||||
p := shopPlugin(t, DefaultLimits())
|
||||
|
||||
asked := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
s := &fakeSession{prompt: func(context.Context) (string, error) {
|
||||
close(asked)
|
||||
<-release
|
||||
return "123456", nil
|
||||
}}
|
||||
|
||||
go func() { _ = p.Login(context.Background(), s, shopAccount) }()
|
||||
|
||||
<-asked
|
||||
defer close(release)
|
||||
|
||||
parsed := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := parse(p, "https://shop.test/item/ok")
|
||||
parsed <- err
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-parsed:
|
||||
if err != nil { t.Fatal(err) }
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("parse waits for the login")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionPromptTimesOut(t *testing.T) {
|
||||
limits := DefaultLimits()
|
||||
limits.SessionTimeout = 100 * time.Millisecond
|
||||
|
||||
p := shopPlugin(t, limits)
|
||||
s := &fakeSession{prompt: func(ctx context.Context) (string, error) {
|
||||
<-ctx.Done()
|
||||
return "", ctx.Err()
|
||||
}}
|
||||
|
||||
if err := p.Login(context.Background(), s, shopAccount); !errors.Is(err, ErrTimeout) { t.Errorf("got %v, want ErrTimeout", err) }
|
||||
}
|
||||
Reference in new issue
Block a user