diff --git a/cmd/dibs/env.go b/cmd/dibs/env.go index 2487dad..197e97c 100644 --- a/cmd/dibs/env.go +++ b/cmd/dibs/env.go @@ -12,7 +12,6 @@ import ( "git.security-command.org/Overlord/dibs/internal/fetch" "git.security-command.org/Overlord/dibs/internal/ratelimit" "git.security-command.org/Overlord/dibs/internal/state" - "git.security-command.org/Overlord/dibs/internal/watch" ) // env is what every command that talks to shops shares with every other @@ -89,7 +88,7 @@ func (e *env) fetch(ctx context.Context, fetchURL string, get getter, logger *sl resp, err := get(ctx, fetchURL) if ctx.Err() == nil { if u, perr := url.Parse(fetchURL); perr == nil { - if d := watch.RecordOutcome(e.limiter, u.Hostname(), resp, err); d > 0 { logger.Warn("host backed off", "host", u.Hostname(), "for", d.Round(time.Second)) } + if d := fetch.RecordOutcome(e.limiter, u.Hostname(), resp, err); d > 0 { logger.Warn("host backed off", "host", u.Hostname(), "for", d.Round(time.Second)) } } e.save(logger) diff --git a/cmd/dibs/login.go b/cmd/dibs/login.go new file mode 100644 index 0000000..0287914 --- /dev/null +++ b/cmd/dibs/login.go @@ -0,0 +1,181 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net/url" + "os" + "os/signal" + "slices" + "strings" + + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/plugin" + "git.security-command.org/Overlord/dibs/internal/session" +) + +// runLogin implements `dibs login [--browser] [url]`: it signs in to +// the shop's account for session mode, on the site of url, or else on every +// site of the shop's URLs in the config. +func runLogin(args []string, stdout, stderr io.Writer) int { + flags, configPath := newFlagSet("dibs login", stderr) + browser := flags.Bool("browser", false, "sign in yourself in a Chrome window instead of letting the plugin sign in") + + pos, ok := parseArgs(flags, args) + if !ok { return 2 } + if len(pos) < 1 || len(pos) > 2 { + _, _ = fmt.Fprintf(stderr, "dibs login: expected a shop and at most one URL\n\n%s", usage) + return 2 + } + + cfg, ok := loadConfig(*configPath, stderr) + if !ok { return 1 } + + shop := pos[0] + + acc, err := sessionAccount(cfg, shop) + if err != nil { return fail(stderr, "login", err) } + + 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, "login", err) } + defer host.Close() + + if err := checkSessions(cfg, host); err != nil { return fail(stderr, "login", err) } + + p, _ := host.Plugin(shop) + + var sites []string + + if len(pos) == 2 { + u, err := url.Parse(pos[1]) + if err != nil || u.Hostname() == "" { return fail(stderr, "login", fmt.Errorf("not a URL: %q", pos[1])) } + + sites = []string{u.Scheme + "://" + u.Host + "/"} + } else { + for _, it := range cfg.Items { + if it.Shop != shop { continue } + + for _, raw := range it.URLs { + fetchURL, err := p.Normalize(ctx, raw) + if err != nil { return fail(stderr, "login", err) } + + u, err := url.Parse(fetchURL) + if err != nil { continue } + + if s := u.Scheme + "://" + u.Host + "/"; !slices.Contains(sites, s) { sites = append(sites, s) } + } + } + } + + if len(sites) == 0 { return fail(stderr, "login", fmt.Errorf("the config has no URLs for %s: pass a URL on the site to sign in to", shop)) } + + m, e, err := openSession(shop, logger) + if err != nil { return fail(stderr, "login", err) } + + m.Update(acc, newTerminalPrompter(stderr)) + + failed := 0 + + for _, site := range sites { + u, _ := url.Parse(site) + + if *browser { + // The configured login_url is for one site; any other starts + // from its home page. + loginURL := "" + if lu, err := url.Parse(acc.LoginURL); err == nil && strings.EqualFold(lu.Host, u.Host) { loginURL = acc.LoginURL } + + _, _ = fmt.Fprintf(stdout, "Sign in to %s in the Chrome window, then close it.\n", u.Host) + err = m.BrowserLogin(ctx, site, loginURL) + } else { + err = m.Login(ctx, p, site) + } + + switch { + case errors.Is(err, session.ErrDeclined): + _, _ = fmt.Fprintln(stdout, "Not signing in.") + return 1 + case ctx.Err() != nil: + return 1 + case err != nil: + _, _ = fmt.Fprintf(stderr, "dibs login: %s: %v\n", u.Host, err) + failed++ + default: + _, _ = fmt.Fprintf(stdout, "Signed in to %s. A running dibs uses the session from its next addition to the cart.\n", u.Host) + } + } + + e.save(logger) + + if failed > 0 { return 1 } + + return 0 +} + +// runLogout implements `dibs logout `: it deletes the shop's +// signed-in cookies, in running dibs processes too. +func runLogout(args []string, stdout, stderr io.Writer) int { + flags, configPath := newFlagSet("dibs logout", stderr) + + pos, ok := parseArgs(flags, args) + if !ok { return 2 } + if len(pos) != 1 { + _, _ = fmt.Fprintf(stderr, "dibs logout: expected a shop\n\n%s", usage) + return 2 + } + + cfg, ok := loadOptionalConfig(*configPath, stderr) + if !ok { return 1 } + + // The shop names a file, so it must be a plugin's name, which the + // config keeps to safe characters. Logging out needs no account in + // the config. + shop := pos[0] + if !slices.Contains(plugin.Builtins(), shop) && (cfg == nil || cfg.Plugins[shop] == "") { return fail(stderr, "logout", fmt.Errorf("no plugin named %q", shop)) } + + logger := slog.New(slog.NewTextHandler(stderr, nil)) + + m, _, err := openSession(shop, logger) + if err != nil { return fail(stderr, "logout", err) } + + if err := m.Logout(); err != nil { return fail(stderr, "logout", err) } + + _, _ = fmt.Fprintf(stdout, "Signed out of %s: dibs deleted the account's cookies.\n", shop) + return 0 +} + +// sessionAccount returns the account of shop, which must be in session +// mode. +func sessionAccount(cfg *config.Config, shop string) (config.Account, error) { + acc, ok := cfg.Accounts[shop] + + switch { + case !ok: + return acc, fmt.Errorf("the config has no [accounts.%s]", shop) + case acc.CartMode != config.CartModeSession: + return acc, fmt.Errorf("accounts.%s.cart_mode is %q: signing in is only for %q", shop, acc.CartMode, config.CartModeSession) + } + + return acc, nil +} + +func openSession(shop string, logger *slog.Logger) (*session.Manager, *env, error) { + e, err := openEnv(logger) + if err != nil { return nil, nil, err } + + vault, err := session.OpenVault(e.dir) + if err != nil { logger.Warn(err.Error()) } + + m, err := session.New(shop, vault, e.limiter, e.store, logger) + if err != nil { return nil, nil, err } + + return m, e, nil +} diff --git a/cmd/dibs/main.go b/cmd/dibs/main.go index 485390d..3500cf7 100644 --- a/cmd/dibs/main.go +++ b/cmd/dibs/main.go @@ -10,6 +10,8 @@ import ( "os" "runtime" "runtime/debug" + "slices" + "strings" "git.security-command.org/Overlord/dibs/internal/config" "git.security-command.org/Overlord/dibs/internal/plugin" @@ -19,9 +21,11 @@ import ( var version = "dev" const usage = `Usage: - dibs [--config FILE] [--headless] watch items (TUI unless --headless) - dibs check [--shop NAME] [--chrome] fetch and parse one URL, print JSON + dibs [--config FILE] [--headless] watch items (TUI unless --headless) + dibs check [--shop NAME] [--chrome] fetch and parse one URL, print JSON dibs solve [--shop NAME] pass a bot check in a Chrome window + dibs login [--browser] [url] sign in to a shop for cart_mode = "session" + dibs logout delete a shop's signed-in cookies dibs plugin test [--status CODE] [url] dibs config validate [--config FILE] dibs notify test [--config FILE] [--item NAME] send a sample alert to every channel @@ -33,7 +37,33 @@ func main() { os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) } +// commands are the subcommands run dispatches on. +var commands = []string{"config", "version", "check", "plugin", "fixtures", "notify", "solve", "login", "logout", "help"} + +// commandFirst moves a --config given before the command behind it, so +// that "dibs --config f.toml logout amazon" works like "dibs logout +// --config f.toml amazon". +func commandFirst(args []string) []string { + n := 0 + + switch { + case len(args) > 0 && (strings.HasPrefix(args[0], "--config=") || strings.HasPrefix(args[0], "-config=")): + n = 1 + case len(args) > 1 && (args[0] == "--config" || args[0] == "-config"): + n = 2 + } + + if n == 0 || len(args) <= n || !slices.Contains(commands, args[n]) { return args } + + out := []string{args[n]} + out = append(out, args[:n]...) + + return append(out, args[n+1:]...) +} + func run(args []string, stdout, stderr io.Writer) int { + args = commandFirst(args) + if len(args) > 0 { switch args[0] { case "config": @@ -51,6 +81,10 @@ func run(args []string, stdout, stderr io.Writer) int { return runNotify(args[1:], stdout, stderr) case "solve": return runSolve(args[1:], stdout, stderr) + case "login": + return runLogin(args[1:], stdout, stderr) + case "logout": + return runLogout(args[1:], stdout, stderr) case "help", "-h", "--help": _, _ = fmt.Fprint(stdout, usage) return 0 diff --git a/cmd/dibs/main_test.go b/cmd/dibs/main_test.go new file mode 100644 index 0000000..58cee1d --- /dev/null +++ b/cmd/dibs/main_test.go @@ -0,0 +1,18 @@ +package main + +import ( + "slices" + "testing" +) + +func TestCommandFirst(t *testing.T) { + for _, tc := range []struct{ in, want []string } { + {[]string{"--config", "f.toml", "logout", "amazon"}, []string{"logout", "--config", "f.toml", "amazon"}}, + {[]string{"--config=f.toml", "check", "URL"}, []string{"check", "--config=f.toml", "URL"}}, + {[]string{"--config", "f.toml", "--headless"}, []string{"--config", "f.toml", "--headless"}}, + {[]string{"--config", "f.toml"}, []string{"--config", "f.toml"}}, + {[]string{"logout", "--config", "f.toml", "amazon"}, []string{"logout", "--config", "f.toml", "amazon"}}, + } { + if got := commandFirst(tc.in); !slices.Equal(got, tc.want) { t.Errorf("commandFirst(%q) = %q, want %q", tc.in, got, tc.want) } + } +} diff --git a/cmd/dibs/prompt.go b/cmd/dibs/prompt.go new file mode 100644 index 0000000..1566313 --- /dev/null +++ b/cmd/dibs/prompt.go @@ -0,0 +1,92 @@ +package main + +import ( + "bufio" + "context" + "fmt" + "io" + "os" + "strings" + "sync" + + "github.com/charmbracelet/x/term" + + "git.security-command.org/Overlord/dibs/internal/session" +) + +// noPrompter is the prompter until the TUI or the terminal takes over. +type noPrompter struct{} + +func (noPrompter) Prompt(context.Context, string, string, bool) (string, error) { return "", session.ErrNoPrompt } +func (noPrompter) Confirm(context.Context, string, string) (bool, error) { return false, session.ErrNoPrompt } + +// terminalPrompter asks on stderr and reads the answer from stdin. Without +// a terminal on stdin, nobody is there to answer. +type terminalPrompter struct { + in *os.File + out io.Writer + lines *bufio.Reader + + mu sync.Mutex +} + +func newTerminalPrompter(stderr io.Writer) *terminalPrompter { + return &terminalPrompter{in: os.Stdin, out: stderr, lines: bufio.NewReader(os.Stdin)} +} + +func (t *terminalPrompter) Prompt(ctx context.Context, title, label string, secret bool) (string, error) { + if !term.IsTerminal(t.in.Fd()) { return "", session.ErrNoPrompt } + + t.mu.Lock() + defer t.mu.Unlock() + + _, _ = fmt.Fprintf(t.out, "%s: %s: ", title, label) + + return t.read(ctx, secret) +} + +func (t *terminalPrompter) Confirm(ctx context.Context, title, message string) (bool, error) { + if !term.IsTerminal(t.in.Fd()) { return false, session.ErrNoPrompt } + + t.mu.Lock() + defer t.mu.Unlock() + + _, _ = fmt.Fprintf(t.out, "%s\n\n%s\n\nContinue? [y/N] ", title, message) + + answer, err := t.read(ctx, false) + if err != nil { return false, err } + + answer = strings.ToLower(strings.TrimSpace(answer)) + return answer == "y" || answer == "yes", nil +} + +// read reads one line. A read cannot be interrupted, so when ctx ends first, +// the line typed next is lost. +func (t *terminalPrompter) read(ctx context.Context, secret bool) (string, error) { + type answer struct { + text string + err error + } + + done := make(chan answer, 1) + + go func() { + if secret { + b, err := term.ReadPassword(t.in.Fd()) + _, _ = fmt.Fprintln(t.out) + done <- answer{string(b), err} + return + } + + line, err := t.lines.ReadString('\n') + done <- answer{strings.TrimRight(line, "\r\n"), err} + }() + + select { + case a := <-done: + return a.text, a.err + case <-ctx.Done(): + _, _ = fmt.Fprintln(t.out) + return "", ctx.Err() + } +} diff --git a/cmd/dibs/session.go b/cmd/dibs/session.go new file mode 100644 index 0000000..6fb38b0 --- /dev/null +++ b/cmd/dibs/session.go @@ -0,0 +1,239 @@ +package main + +import ( + "context" + "errors" + "fmt" + "maps" + "net/url" + "slices" + "strings" + + "git.security-command.org/Overlord/dibs/internal/alert" + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/notify" + "git.security-command.org/Overlord/dibs/internal/plugin" + "git.security-command.org/Overlord/dibs/internal/session" +) + +// cartResult is the outcome of adding an item to the cart. +type cartResult struct { + Item string + // URL is the URL as configured. + URL string + // Link is the cart page, or the cart link if adding failed. + Link string + Err error +} + +// checkSessions makes sure every shop in session mode has a plugin that can +// take it. +func checkSessions(cfg *config.Config, host *plugin.Host) error { + var errs []error + + for _, shop := range slices.Sorted(maps.Keys(cfg.Accounts)) { + acc := cfg.Accounts[shop] + if acc.CartMode != config.CartModeSession { continue } + + p, ok := host.Plugin(shop) + + switch { + case !ok: + errs = append(errs, fmt.Errorf("accounts.%s: no plugin named %q", shop, shop)) + case !p.Has("add_to_cart"): + errs = append(errs, fmt.Errorf("accounts.%s: cart_mode is session, but plugin %s has no add_to_cart", shop, shop)) + case acc.PasswordEnv != "" && !p.Has("login"): + errs = append(errs, fmt.Errorf("accounts.%s: password_env is set, but plugin %s has no login", shop, shop)) + } + } + + return errors.Join(errs...) +} + +// applySessions sets up a session for every shop in session mode and drops +// the others. Reloads retry failed and declined logins. +func (w *watcher) applySessions(cfg *config.Config) { + // Opening the vault may wait for the user to unlock the keyring, so it + // happens before taking the lock. + if w.vault == nil && usesSessions(cfg) { + vault, err := session.OpenVault(w.env.dir) + if err != nil { w.logger.Warn(err.Error()) } + + w.vault = vault + } + + w.mu.Lock() + defer w.mu.Unlock() + + w.failed, w.declined = map[string]bool{}, map[string]bool{} + + for shop := range w.managers { + if cfg.Accounts[shop].CartMode != config.CartModeSession { delete(w.managers, shop) } + } + + for _, shop := range slices.Sorted(maps.Keys(cfg.Accounts)) { + acc := cfg.Accounts[shop] + if acc.CartMode != config.CartModeSession { continue } + + m := w.managers[shop] + if m == nil { + var err error + if m, err = session.New(shop, w.vault, w.env.limiter, w.env.store, w.logger); err != nil { + w.logger.Warn("session mode unavailable, alerts carry cart links", "shop", shop, "err", err) + continue + } + + w.managers[shop] = m + } + + m.Update(acc, w) + } +} + +func usesSessions(cfg *config.Config) bool { + for _, acc := range cfg.Accounts { + if acc.CartMode == config.CartModeSession { return true } + } + + return false +} + +// site is a shop site to sign in to. +type site struct { + shop string + host string + url string // such as https://www.amazon.de/ +} + +// sites are the sites of the watched URLs of shops in session mode. +func (w *watcher) sites() []site { + w.mu.Lock() + shops := slices.Collect(maps.Keys(w.managers)) + w.mu.Unlock() + + var out []site + + for _, st := range w.sched.Statuses() { + if !slices.Contains(shops, st.Shop) { continue } + + u, err := url.Parse(st.FetchURL) + if err != nil { continue } + + s := site{shop: st.Shop, host: strings.ToLower(u.Hostname()), url: u.Scheme + "://" + u.Host + "/"} + if !slices.Contains(out, s) { out = append(out, s) } + } + + return out +} + +// signIn signs in to every site in session mode that has no session yet. +// A failed login is not retried until the next reload, since repeated +// failed logins are what gets accounts locked. +func (w *watcher) signIn() { + w.signingIn.Lock() + defer w.signingIn.Unlock() + + for _, s := range w.sites() { + key := s.shop + " " + s.host + + w.mu.Lock() + m, skip := w.managers[s.shop], w.declined[s.shop] || w.failed[key] + p, _ := w.host.Plugin(s.shop) + w.mu.Unlock() + + if m == nil || skip || m.SignedIn(s.host) { continue } + + if !m.HasPassword() { + w.logger.Warn("not signed in, so alerts carry cart links: sign in with dibs login "+s.shop+" --browser", "shop", s.shop, "host", s.host) + continue + } + + err := m.Login(w.ctx, p, s.url) + + switch { + case w.ctx.Err() != nil: + return + case errors.Is(err, session.ErrDeclined): + w.mu.Lock() + w.declined[s.shop] = true + w.mu.Unlock() + + w.logger.Info("session mode off until the next reload, alerts carry cart links", "shop", s.shop) + case err != nil: + w.mu.Lock() + w.failed[key] = true + w.mu.Unlock() + + w.logger.Warn("signing in failed, so alerts carry cart links until you sign in with dibs login "+s.shop, "shop", s.shop, "host", s.host, "err", err) + } + } +} + +// sessionFor returns the session that puts items from rawURL's site in the +// cart, if session mode applies to it: the shop uses it, the user did not +// decline it, and dibs is signed in to the site. +func (w *watcher) sessionFor(shop, rawURL string) (*session.Manager, *plugin.Plugin) { + u, err := url.Parse(rawURL) + if err != nil { return nil, nil } + + w.mu.Lock() + m, declined := w.managers[shop], w.declined[shop] + p, _ := w.host.Plugin(shop) + w.mu.Unlock() + + if m == nil || declined || !m.SignedIn(u.Hostname()) { return nil, nil } + + return m, p +} + +// cart sends a fired item's alert at once, without a cart link, then adds +// the item to the cart and sends a second alert with the outcome. +func (w *watcher) cart(n *notify.Notifier, m *session.Manager, p *plugin.Plugin, configured string, a alert.Alert) { + first := a + first.Cart, first.CartLink = alert.CartAdding, "" + w.fire(n, first) + + w.carts.Go(func() { + cartURL, err := m.AddToCart(w.ctx, p, a.URL) + + next := a + res := cartResult{Item: a.Item, URL: configured} + + switch { + case err == nil: + next.Cart, next.CartURL, next.CartLink = alert.CartAdded, cartURL, "" + res.Link = cartURL + case w.ctx.Err() != nil: + next.Cart, next.CartError = alert.CartFailed, "dibs was stopped before it finished" + default: + next.Cart, next.CartError = alert.CartFailed, err.Error() + } + + if err != nil { + res.Link, res.Err = a.CartLink, err + w.logger.Warn("adding to the cart failed", "item", a.Item, "url", a.URL, "err", err) + } + + w.fire(n, next) + w.onCart(res) + + if errors.Is(err, plugin.ErrSignedOut) { go w.signIn() } + }) +} + +// Prompt asks the user for a login, and sends a desktop notification with +// the question: a login after the session runs out may ask long after the +// user last looked. +func (w *watcher) Prompt(ctx context.Context, title, label string, secret bool) (string, error) { + w.mu.Lock() + n := w.notifier + w.mu.Unlock() + + if err := n.Notice("dibs needs you: "+title, label); err != nil { w.logger.Warn("desktop notification failed", "err", err) } + + return w.prompter.Prompt(ctx, title, label, secret) +} + +func (w *watcher) Confirm(ctx context.Context, title, message string) (bool, error) { + return w.prompter.Confirm(ctx, title, message) +} diff --git a/cmd/dibs/tui.go b/cmd/dibs/tui.go index cfdf2b7..ca67071 100644 --- a/cmd/dibs/tui.go +++ b/cmd/dibs/tui.go @@ -31,6 +31,9 @@ func runTUI(cfg *config.Config, stderr io.Writer) int { p := tea.NewProgram(tui.New(w, cfg.Path, logs), append(terminalOptions(), tea.WithContext(ctx))...) + w.prompter = tui.NewPrompter(p) + w.onCart = func(c cartResult) { p.Send(tui.CartMsg{Item: c.Item, URL: c.URL, Link: c.Link, Err: c.Err}) } + done := make(chan struct{}) go func() { defer close(done) diff --git a/cmd/dibs/watch.go b/cmd/dibs/watch.go index ed13292..1c43184 100644 --- a/cmd/dibs/watch.go +++ b/cmd/dibs/watch.go @@ -19,6 +19,7 @@ import ( "git.security-command.org/Overlord/dibs/internal/fx" "git.security-command.org/Overlord/dibs/internal/notify" "git.security-command.org/Overlord/dibs/internal/plugin" + "git.security-command.org/Overlord/dibs/internal/session" "git.security-command.org/Overlord/dibs/internal/watch" ) @@ -34,6 +35,8 @@ func runWatch(cfg *config.Config, headless bool, stdout, stderr io.Writer) int { w, err := newWatcher(ctx, cfg, logger, slog.LevelInfo) if err != nil { return fail(stderr, "watch", err) } + w.prompter = newTerminalPrompter(stderr) + ring := isTerminal(stderr) w.run(func(c check) { @@ -83,7 +86,22 @@ type watcher struct { // told once, not on every retry. humans map[string]bool - sends sync.WaitGroup + // Session mode. managers has a session per shop in session mode. The + // declined shops and the failed "shop host" logins fall back to cart + // links until the next reload. + vault *session.Vault + managers map[string]*session.Manager + declined map[string]bool + failed map[string]bool + + // prompter reaches the user, and onCart sees the outcome of each + // addition to the cart. Both are set before run. + prompter session.Prompter + onCart func(cartResult) + + signingIn sync.Mutex + sends sync.WaitGroup + carts sync.WaitGroup } func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, checkLevel slog.Level) (*watcher, error) { @@ -93,6 +111,11 @@ func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, ch host, err := newHost(cfg, logger) if err != nil { return nil, err } + if err := checkSessions(cfg, host); err != nil { + host.Close() + return nil, err + } + sched, warnings, err := watch.New(ctx, cfg, host, e.client, e.limiter) if err != nil { host.Close() @@ -109,6 +132,9 @@ func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, ch rates: fx.New(e.store, e.limiter), checkLevel: checkLevel, humans: map[string]bool{}, + managers: map[string]*session.Manager{}, + prompter: noPrompter{}, + onCart: func(cartResult) {}, } w.apply(cfg, host) @@ -117,25 +143,27 @@ func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, ch return w, nil } -// apply switches the alert settings and plugins to cfg's. +// apply switches the alert settings, plugins and sessions to cfg's. func (w *watcher) apply(cfg *config.Config, host *plugin.Host) { if needsRates(cfg) { w.rates.Warm() } w.mu.Lock() - defer w.mu.Unlock() - if w.host != nil { w.retired = append(w.retired, w.host) } w.cfg = cfg w.host = host w.alerts = alert.NewEngine(cfg.Notify.Cooldown.Duration, w.rates, w.env.store) w.notifier = notify.New(cfg.Notify, userAgent()) + w.mu.Unlock() + + w.applySessions(cfg) } // run handles every check until the watcher's context ends. observe sees // each check after it is logged and its alert is on its way. func (w *watcher) run(observe func(check)) { go w.sched.Run(w.ctx) + go w.signIn() // Saving also takes in the cookies other dibs processes saved, such as // those of a `dibs solve` for a host that is backed off here. @@ -173,9 +201,19 @@ func (w *watcher) consider(r watch.Result) check { c.Decision, c.PriceErr = alerts.Consider(w.ctx, r.Item, r.Report, r.Time) + m, p := w.sessionFor(r.Item.Shop, r.Report.FetchURL) + + // In session mode, the cart link would add a second copy. + if m != nil && r.Report.CartLink != "" { + rep := *r.Report + rep.CartLink, c.Report = "", &rep + } + switch { case c.PriceErr != nil: w.logger.Warn("available, but the price cannot be checked", "item", r.Item.Name, "url", r.URL, "err", c.PriceErr) + case c.Decision.Alert != nil && m != nil: + w.cart(notifier, m, p, r.URL, *c.Decision.Alert) case c.Decision.Alert != nil: w.fire(notifier, *c.Decision.Alert) case c.Decision.Reason != "": @@ -190,8 +228,14 @@ func (w *watcher) fire(n *notify.Notifier, a alert.Alert) { attrs := []any{"item", a.Item, "url", a.URL, "title", a.Title, "price", a.PriceText(), "seller", a.Seller} if a.CartLink != "" { attrs = append(attrs, "cart_link", a.CartLink) } if a.PreviousPrice != nil { attrs = append(attrs, "previous_price", alert.Money(*a.PreviousPrice, a.PreviousCurrency)) } + if a.Cart != "" { attrs = append(attrs, "cart", a.Cart) } + if a.CartURL != "" { attrs = append(attrs, "cart_url", a.CartURL) } + if a.CartError != "" { attrs = append(attrs, "cart_error", a.CartError) } - w.logger.Info("ALERT", attrs...) + msg := "ALERT" + if a.Cart == alert.CartAdded { msg = "IN CART" } + + w.logger.Info(msg, attrs...) if len(n.Channels()) == 0 { return } @@ -266,6 +310,7 @@ func (w *watcher) Solve(fetchURL string) error { // close waits for the notifications still being sent and releases the // plugins. func (w *watcher) close() { + w.carts.Wait() w.sends.Wait() w.mu.Lock() @@ -306,6 +351,12 @@ func (w *watcher) Reload() ([]string, error) { host, err := newHost(cfg, w.logger) if err != nil { return nil, err } + if err := checkSessions(cfg, host); err != nil { + host.Close() + w.logger.Warn("config reload failed", "err", err) + return nil, err + } + warnings, err := w.sched.Reload(w.ctx, cfg, host) if err != nil { host.Close() @@ -320,6 +371,8 @@ func (w *watcher) Reload() ([]string, error) { for _, line := range summary { w.logger.Info("config reloaded", "change", line) } for _, msg := range warnings { w.logger.Warn(msg) } + go w.signIn() + return summary, nil } diff --git a/go.mod b/go.mod index a2b0c00..6437cfa 100644 --- a/go.mod +++ b/go.mod @@ -12,10 +12,14 @@ require ( github.com/bogdanfinn/tls-client v1.16.0 github.com/charmbracelet/colorprofile v0.4.3 github.com/charmbracelet/x/ansi v0.11.9 + github.com/charmbracelet/x/term v0.2.2 github.com/gen2brain/beeep v0.11.2 + github.com/go-rod/rod v0.116.2 + github.com/go-rod/stealth v0.4.9 github.com/pelletier/go-toml/v2 v2.4.3 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c github.com/yuin/gopher-lua v1.1.2 + github.com/zalando/go-keyring v0.2.8 golang.org/x/net v0.60.0 golang.org/x/sys v0.48.0 ) @@ -23,23 +27,22 @@ require ( require ( git.sr.ht/~jackmordaunt/go-toast v1.1.2 // indirect github.com/andybalholm/brotli v1.2.0 // indirect + github.com/atotto/clipboard v0.1.4 // indirect github.com/bdandy/go-errors v1.2.2 // indirect github.com/bdandy/go-socks4 v1.2.3 // indirect github.com/bogdanfinn/quic-go-utls v1.0.10-utls // indirect github.com/bogdanfinn/utls v1.7.8-barnius // indirect github.com/bogdanfinn/websocket v1.5.6-barnius // indirect github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect - github.com/charmbracelet/x/term v0.2.2 // indirect github.com/charmbracelet/x/termios v0.1.1 // indirect github.com/charmbracelet/x/windows v0.2.2 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/cloudflare/circl v1.6.5 // indirect + github.com/danieljoos/wincred v1.2.3 // indirect github.com/esiqveland/notify v0.13.3 // indirect github.com/go-ole/go-ole v1.3.0 // indirect - github.com/go-rod/rod v0.116.2 // indirect - github.com/go-rod/stealth v0.4.9 // indirect - github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/godbus/dbus/v5 v5.2.2 // indirect github.com/jackmordaunt/icns/v3 v3.0.1 // indirect github.com/klauspost/compress v1.18.2 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect diff --git a/go.sum b/go.sum index 48d7509..297bfbd 100644 --- a/go.sum +++ b/go.sum @@ -12,6 +12,8 @@ github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwTo github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg= github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o= github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w= github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q= @@ -48,6 +50,8 @@ github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJ github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA= github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= +github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ= +github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -62,8 +66,9 @@ github.com/go-rod/rod v0.116.2 h1:A5t2Ky2A+5eD/ZJQr1EfsQSe5rms5Xof/qj296e+ZqA= github.com/go-rod/rod v0.116.2/go.mod h1:H+CMO9SCNc2TJ2WfrG+pKhITz57uGNYU43qYHh438Mg= github.com/go-rod/stealth v0.4.9 h1:X2PmQk4DUF2wzw6GOsWjW/glb8K5ebnftbEvLh7MlZ4= github.com/go-rod/stealth v0.4.9/go.mod h1:eAzyvw8c0iAd5nJJsSWeh0fQ5z94vCIfdi1hUmYDimc= -github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= +github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= github.com/jackmordaunt/icns/v3 v3.0.1 h1:xxot6aNuGrU+lNgxz5I5H0qSeCjNKp8uTXB1j8D4S3o= github.com/jackmordaunt/icns/v3 v3.0.1/go.mod h1:5sHL59nqTd2ynTnowxB/MDQFhKNqkK8X687uKNygaSQ= github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= @@ -93,6 +98,8 @@ github.com/sergeymakinen/go-ico v1.0.0-beta.0/go.mod h1:wQ47mTczswBO5F0NoDt7O0IX github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= @@ -111,9 +118,12 @@ github.com/ysmood/fetchup v0.2.3/go.mod h1:xhibcRKziSvol0H1/pj33dnKrYyI2ebIvz5cO github.com/ysmood/goob v0.4.0 h1:HsxXhyLBeGzWXnqVKtmT9qM7EuVs/XOgkX7T6r1o1AQ= github.com/ysmood/goob v0.4.0/go.mod h1:u6yx7ZhS4Exf2MwciFr6nIM8knHQIE22lFpWHnfql18= github.com/ysmood/gop v0.0.2/go.mod h1:rr5z2z27oGEbyB787hpEcx4ab8cCiPnKxn0SUHt6xzk= +github.com/ysmood/gop v0.2.0 h1:+tFrG0TWPxT6p9ZaZs+VY+opCvHU8/3Fk6BaNv6kqKg= +github.com/ysmood/gop v0.2.0/go.mod h1:rr5z2z27oGEbyB787hpEcx4ab8cCiPnKxn0SUHt6xzk= github.com/ysmood/got v0.34.1/go.mod h1:yddyjq/PmAf08RMLSwDjPyCvHvYed+WjHnQxpH851LM= github.com/ysmood/got v0.40.0 h1:ZQk1B55zIvS7zflRrkGfPDrPG3d7+JOza1ZkNxcc74Q= github.com/ysmood/got v0.40.0/go.mod h1:W7DdpuX6skL3NszLmAsC5hT7JAhuLZhByVzHTq874Qg= +github.com/ysmood/gotrace v0.6.0 h1:SyI1d4jclswLhg7SWTL6os3L1WOKeNn/ZtzVQF8QmdY= github.com/ysmood/gotrace v0.6.0/go.mod h1:TzhIG7nHDry5//eYZDYcTzuJLYQIkykJzCRIo4/dzQM= github.com/ysmood/gson v0.7.3 h1:QFkWbTH8MxyUTKPkVWAENJhxqdBa4lYTQWqZCiLG6kE= github.com/ysmood/gson v0.7.3/go.mod h1:3Kzs5zDl21g5F/BlLTNcuAGAYLKt2lV5G8D1zF3RNmg= @@ -122,6 +132,8 @@ github.com/ysmood/leakless v0.9.0 h1:qxCG5VirSBvmi3uynXFkcnLMzkphdh3xx5FtrORwDCU github.com/ysmood/leakless v0.9.0/go.mod h1:R8iAXPRaG97QJwqxs74RdwzcRHT1SWCGTNqY8q0JvMQ= github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA= github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8= +github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs= +github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0= go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= diff --git a/internal/alert/alert.go b/internal/alert/alert.go index c409180..6c87a7f 100644 --- a/internal/alert/alert.go +++ b/internal/alert/alert.go @@ -35,10 +35,25 @@ type Alert struct { // during the cooldown because the price dropped below it. PreviousPrice *float64 PreviousCurrency string + // Cart is what session mode did about the cart, in the order the + // notifications go out: CartAdding, then CartAdded or CartFailed. It is + // "" without session mode. + Cart string + // CartURL is the cart page, once the item is in the cart. + CartURL string + // CartError says why adding to the cart failed. + CartError string // Test marks the sample alert of `dibs notify test`. Test bool } +// The cart steps of session mode. +const ( + CartAdding = "adding" + CartAdded = "added" + CartFailed = "failed" +) + // PriceText is the price as notifications show it, such as "129.99 EUR" or // "149.99 USD (≈ 133.95 EUR)". func (a Alert) PriceText() string { diff --git a/internal/chrome/chrome.go b/internal/chrome/chrome.go index 98f617b..880348e 100644 --- a/internal/chrome/chrome.go +++ b/internal/chrome/chrome.go @@ -47,15 +47,17 @@ type Chrome struct { browser fetch.Browser jar *fetch.Jar logger *slog.Logger - // challengeTimeout is ChallengeTimeout, shorter in tests. + // challengeTimeout and humanTimeout are ChallengeTimeout and + // HumanTimeout, shorter in tests. challengeTimeout time.Duration + humanTimeout time.Duration mu sync.Mutex bin string } func New(browser fetch.Browser, jar *fetch.Jar, logger *slog.Logger) *Chrome { - return &Chrome{browser: browser, jar: jar, logger: logger, challengeTimeout: ChallengeTimeout} + return &Chrome{browser: browser, jar: jar, logger: logger, challengeTimeout: ChallengeTimeout, humanTimeout: HumanTimeout} } // Fetch loads rawURL in headless Chrome and gives a bot check up to @@ -70,8 +72,8 @@ func (c *Chrome) Fetch(ctx context.Context, rawURL string) (*fetch.Response, err // and closes it as soon as the page shows none. It returns the page then, // or ErrClosed, and keeps Chrome's cookies. func (c *Chrome) Solve(ctx context.Context, rawURL string) (*fetch.Response, error) { - resp, err := c.visit(ctx, rawURL, false, HumanTimeout) - if err == nil && resp.Verdict == fetch.Challenge { return resp, fmt.Errorf("the bot check did not clear within %s", HumanTimeout) } + resp, err := c.visit(ctx, rawURL, false, c.humanTimeout) + if err == nil && resp.Verdict == fetch.Challenge { return resp, fmt.Errorf("the bot check did not clear within %s", c.humanTimeout) } return resp, err } @@ -87,35 +89,13 @@ func (c *Chrome) visit(ctx context.Context, rawURL string, headless bool, timeou host := strings.ToLower(u.Hostname()) - bin, err := c.binary() + b, cleanup, err := c.launch(ctx, headless) if err != nil { return nil, err } + defer cleanup() - l := launcher.New().Context(ctx).Bin(bin).Leakless(false) - if headless { - // Images are not needed to clear a bot check, and fewer requests - // reach the shop. - l = l.HeadlessNew(true).Set("blink-settings", "imagesEnabled=false") - } else { - l = l.Headless(false) - } - - controlURL, err := l.Launch() - if err != nil { return nil, fmt.Errorf("starting %s: %w", bin, err) } - defer l.Cleanup() - defer l.Kill() - - b := rod.New().ControlURL(controlURL).Context(ctx) - if err := b.Connect(); err != nil { return nil, fmt.Errorf("connecting to Chrome: %w", err) } - - page, err := stealth.Page(b) + page, err := c.open(b, u, host) if err != nil { return nil, err } - if err := c.identity(host).Call(page); err != nil { return nil, err } - - if cookies := c.jar.Export()[host]; len(cookies) > 0 { - if err := b.SetCookies(cookieParams(cookies, u.Scheme)); err != nil { return nil, err } - } - doc := &document{} go page.EachEvent(func(e *proto.NetworkResponseReceived) { if e.Type == proto.NetworkResourceTypeDocument && e.FrameID == page.FrameID { doc.set(e.Response) } @@ -153,6 +133,170 @@ func (c *Chrome) visit(ctx context.Context, rawURL string, headless bool, timeou } } +// ClickTimeout is how long Click waits for the page a click leads to. +const ClickTimeout = 30 * time.Second + +// Click loads rawURL in headless Chrome, clicks the element sel matches and +// returns the page the click leads to. Page scripts run as for a user, so +// shops that only accept forms their scripts have seen work. wait is called +// between loading and clicking, for the rate limits. Chrome's cookies go +// into the jar. +func (c *Chrome) Click(ctx context.Context, rawURL, sel string, wait func() error) (*fetch.Response, error) { + c.mu.Lock() + defer c.mu.Unlock() + + start := time.Now() + + u, err := url.Parse(rawURL) + if err != nil { return nil, err } + + host := strings.ToLower(u.Hostname()) + + b, cleanup, err := c.launch(ctx, true) + if err != nil { return nil, err } + defer cleanup() + + page, err := c.open(b, u, host) + if err != nil { return nil, err } + + doc := &document{} + go page.EachEvent(func(e *proto.NetworkResponseReceived) { + if e.Type == proto.NetworkResourceTypeDocument && e.FrameID == page.FrameID { doc.set(e.Response) } + })() + + if err := page.Navigate(rawURL); err != nil { return nil, err } + if err := page.Timeout(ClickTimeout).WaitLoad(); err != nil { return nil, fmt.Errorf("loading %s: %w", rawURL, err) } + + el, err := page.Timeout(ClickTimeout).Element(sel) + if err != nil { return nil, fmt.Errorf("no %s on %s: %w", sel, rawURL, err) } + + if err := wait(); err != nil { return nil, err } + + navigated := page.Timeout(ClickTimeout).WaitNavigation(proto.PageLifecycleEventNameLoad) + + // A script click works even when a banner, such as a cookie notice, + // covers the element. + if _, err := el.Eval("() => this.click()"); err != nil { return nil, fmt.Errorf("clicking %s: %w", sel, err) } + + navigated() + + if ctx.Err() != nil { return nil, ctx.Err() } + + resp, err := snapshot(page, rawURL, doc) + if err != nil { return nil, err } + + c.keepCookies(page, resp.FinalURL, host) + resp.Elapsed = time.Since(start) + + return resp, nil +} + +// SignIn opens rawURL in a visible window for the user to sign in to a shop. +// When the window is closed, or after HumanTimeout, the cookies Chrome has +// for rawURL's host go into the jar. It returns how many there were. +func (c *Chrome) SignIn(ctx context.Context, rawURL string) (int, error) { + return c.signIn(ctx, rawURL, false) +} + +func (c *Chrome) signIn(ctx context.Context, rawURL string, headless bool) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + + u, err := url.Parse(rawURL) + if err != nil { return 0, err } + + host := strings.ToLower(u.Hostname()) + + b, cleanup, err := c.launch(ctx, headless) + if err != nil { return 0, err } + defer cleanup() + + page, err := c.open(b, u, host) + if err != nil { return 0, err } + + if err := page.Navigate(rawURL); err != nil { return 0, err } + + deadline := time.After(c.humanTimeout) + + // Once the window is closed, Chrome's cookies are out of reach, so the + // latest copy is kept while it is open. + var last []*proto.NetworkCookie + +watch: + for { + cookies, err := b.GetCookies() + if err != nil || !alive(b) { break } + + last = cookies + + select { + case <-ctx.Done(): + return 0, ctx.Err() + case <-deadline: + break watch + case <-time.After(poll): + } + } + + now := time.Now() + kept := make([]fetch.Cookie, 0, len(last)) + + for _, ck := range last { + if domainMatch(host, strings.TrimPrefix(ck.Domain, ".")) { kept = append(kept, fromChrome(ck, now)) } + } + + c.jar.Import(host, kept) + + return len(kept), nil +} + +// launch starts Chrome and connects to it. cleanup stops it and removes its +// profile. +func (c *Chrome) launch(ctx context.Context, headless bool) (*rod.Browser, func(), error) { + bin, err := c.binary() + if err != nil { return nil, nil, err } + + l := launcher.New().Context(ctx).Bin(bin).Leakless(false) + if headless { + // Images are not needed to clear a bot check, and fewer requests + // reach the shop. + l = l.HeadlessNew(true).Set("blink-settings", "imagesEnabled=false") + } else { + l = l.Headless(false) + } + + controlURL, err := l.Launch() + if err != nil { return nil, nil, fmt.Errorf("starting %s: %w", bin, err) } + + cleanup := func() { + l.Kill() + l.Cleanup() + } + + b := rod.New().ControlURL(controlURL).Context(ctx) + if err := b.Connect(); err != nil { + cleanup() + return nil, nil, fmt.Errorf("connecting to Chrome: %w", err) + } + + return b, cleanup, nil +} + +// open creates a page that claims tls-client's identity and has the jar's +// cookies for host. +func (c *Chrome) open(b *rod.Browser, u *url.URL, host string) (*rod.Page, error) { + page, err := stealth.Page(b) + if err != nil { return nil, err } + + if err := c.identity(host).Call(page); err != nil { return nil, err } + + if cookies := c.jar.Export()[host]; len(cookies) > 0 { + if err := b.SetCookies(cookieParams(cookies, u.Scheme)); err != nil { return nil, err } + } + + return page, nil +} + // binary finds Chrome, Chromium or Edge, and otherwise downloads the // Chromium build rod is tested with. func (c *Chrome) binary() (string, error) { @@ -218,26 +362,34 @@ func (c *Chrome) keepCookies(page *rod.Page, rawURL, host string) { now := time.Now() out := make([]fetch.Cookie, 0, len(cookies)) - - for _, ck := range cookies { - fc := fetch.Cookie{ - Name: ck.Name, - Value: ck.Value, - Domain: strings.TrimPrefix(ck.Domain, "."), - HostOnly: !strings.HasPrefix(ck.Domain, "."), - Path: ck.Path, - Secure: ck.Secure, - HTTPOnly: ck.HTTPOnly, - Set: now, - } - if !ck.Session { fc.Expires = ck.Expires.Time() } - - out = append(out, fc) - } + for _, ck := range cookies { out = append(out, fromChrome(ck, now)) } c.jar.Import(host, out) } +func fromChrome(ck *proto.NetworkCookie, now time.Time) fetch.Cookie { + c := fetch.Cookie{ + Name: ck.Name, + Value: ck.Value, + Domain: strings.TrimPrefix(ck.Domain, "."), + HostOnly: !strings.HasPrefix(ck.Domain, "."), + Path: ck.Path, + Secure: ck.Secure, + HTTPOnly: ck.HTTPOnly, + Set: now, + } + if !ck.Session { c.Expires = ck.Expires.Time() } + + return c +} + +// domainMatch reports whether a cookie for domain is sent to host. +func domainMatch(host, domain string) bool { + host, domain = strings.ToLower(host), strings.ToLower(domain) + + return host == domain || strings.HasSuffix(host, "."+domain) +} + func cookieParams(cookies []fetch.Cookie, scheme string) []*proto.NetworkCookieParam { out := make([]*proto.NetworkCookieParam, 0, len(cookies)) @@ -292,9 +444,10 @@ func snapshot(page *rod.Page, rawURL string, doc *document) (*fetch.Response, er return fetch.NewResponse(rawURL, info.URL, status, header, []byte(html)), nil } -// alive reports whether Chrome still answers, which it stops doing once the -// user closes its last window. +// alive reports whether Chrome still has a window open. On Linux and +// Windows, Chrome exits with its last window; on macOS, it keeps running +// without one. func alive(b *rod.Browser) bool { - _, err := b.Pages() - return err == nil + pages, err := b.Pages() + return err == nil && len(pages) > 0 } diff --git a/internal/chrome/chrome_test.go b/internal/chrome/chrome_test.go index 2dee1e6..647d02f 100644 --- a/internal/chrome/chrome_test.go +++ b/internal/chrome/chrome_test.go @@ -92,6 +92,7 @@ func TestFetchGivesUp(t *testing.T) { type noLimit struct{} func (noLimit) WaitCheck(context.Context, string) error { return nil } +func (noLimit) Wait(context.Context, string) error { return nil } func TestPipelineEscalates(t *testing.T) { c, jar := newChrome(t) @@ -114,3 +115,59 @@ func TestPipelineEscalates(t *testing.T) { if err != nil { t.Fatal(err) } if resp.Verdict != fetch.OK { t.Errorf("tls-client after Chrome: verdict %s", resp.Verdict) } } + +// TestSignIn has the page sign in the way a user would, by script here, and +// checks that the cookies reach the jar when the window's time is up. +func TestSignIn(t *testing.T) { + c, jar := newChrome(t) + c.humanTimeout = 3 * time.Second + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if _, err := r.Cookie("guest"); err != nil { t.Error("the jar's cookie did not reach Chrome") } + + http.SetCookie(w, &http.Cookie{Name: "account", Value: "signed-in", Path: "/", HttpOnly: true, Expires: time.Now().Add(time.Hour)}) + _, _ = io.WriteString(w, `Signed in`) + })) + defer srv.Close() + + u, _ := url.Parse(srv.URL + "/") + jar.SetCookies(u, []*fhttp.Cookie{{Name: "guest", Value: "1", Path: "/"}}) + + n, err := c.signIn(context.Background(), u.String(), true) + if err != nil { t.Fatal(err) } + if n != 3 { t.Errorf("kept %d cookies, want 3", n) } + + got := map[string]string{} + for _, ck := range jar.Cookies(u) { got[ck.Name] = ck.Value } + if got["account"] != "signed-in" || got["later"] != "1" { t.Errorf("jar after signing in: %v", got) } +} + +func TestClick(t *testing.T) { + c, _ := newChrome(t) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/item": + _, _ = io.WriteString(w, `
+
`) + case "/cart": + _ = r.ParseForm() + _, _ = fmt.Fprintf(w, "

%s %s

", r.PostForm.Get("id"), r.PostForm.Get("submit.add")) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + + waited := 0 + wait := func() error { + waited++ + return nil + } + + resp, err := c.Click(context.Background(), srv.URL+"/item", "#add", wait) + if err != nil { t.Fatal(err) } + + if !strings.Contains(string(resp.Body), "X Add") || resp.FinalURL != srv.URL+"/cart" { t.Errorf("after the click: %s %s", resp.FinalURL, resp.Body) } + if waited != 1 { t.Errorf("waited %d times before clicking, want 1", waited) } +} diff --git a/internal/chrome/pipeline.go b/internal/chrome/pipeline.go index 8dbcad1..bd50fad 100644 --- a/internal/chrome/pipeline.go +++ b/internal/chrome/pipeline.go @@ -3,6 +3,7 @@ package chrome import ( "context" "log/slog" + "net/url" "git.security-command.org/Overlord/dibs/internal/fetch" ) @@ -10,6 +11,7 @@ import ( // Limiter is ratelimit.Limiter. type Limiter interface { WaitCheck(ctx context.Context, url string) error + Wait(ctx context.Context, host string) error } // Pipeline fetches pages the way the shops expect a browser to, escalating @@ -28,10 +30,27 @@ func (p *Pipeline) Get(ctx context.Context, rawURL string) (*fetch.Response, err resp, err := p.Client.Get(ctx, rawURL) if err != nil || resp.Verdict != fetch.Challenge || p.Chrome == nil { return resp, err } + // Chrome's visit is a check of the URL like any other. + return p.escalate(ctx, rawURL, resp, func() error { return p.Limiter.WaitCheck(ctx, rawURL) }) +} + +// Do sends a session request. A GET that runs into a bot check is retried +// in headless Chrome like a check, but waits only for the host floor. +func (p *Pipeline) Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) { + resp, err := p.Client.Do(ctx, r) + if err != nil || resp.Verdict != fetch.Challenge || p.Chrome == nil || r.Method != "GET" { return resp, err } + + u, err := url.Parse(r.URL) + if err != nil { return nil, err } + + return p.escalate(ctx, r.URL, resp, func() error { return p.Limiter.Wait(ctx, u.Hostname()) }) +} + +// escalate retries a bot check in headless Chrome once wait allows it. +func (p *Pipeline) escalate(ctx context.Context, rawURL string, resp *fetch.Response, wait func() error) (*fetch.Response, error) { p.Logger.Info("bot check, retrying in headless Chrome once the rate limits allow", "url", rawURL, "challenge", resp.Challenge) - // Chrome's visit is a check of the URL like any other. - if err := p.Limiter.WaitCheck(ctx, rawURL); err != nil { return nil, err } + if err := wait(); err != nil { return nil, err } cr, err := p.Chrome.Fetch(ctx, rawURL) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c643f67..c9dbe63 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -327,6 +327,20 @@ password_env = "DIBS_AMAZON_PASS" wantErr(t, errs(t, err), "accounts.amazon.password_env", 8, "is not set") } +func TestSessionNeedsUsername(t *testing.T) { + _, err := load(t, ` +[[item]] +name = "x" +shop = "amazon" +urls = ["https://www.amazon.de/dp/B0HMX2FSTF"] + +[accounts.amazon] +password_env = "DIBS_AMAZON_PASS" +cart_mode = "session" +`, map[string]string{"DIBS_AMAZON_PASS": "hunter2"}) + wantErr(t, errs(t, err), "accounts.amazon", 7, "username is missing") +} + func TestErrorFormat(t *testing.T) { e := Error{File: "dibs.toml", Line: 14, Col: 3, Key: "item[1].interval", Msg: "must be at least 1m0s (got 30s)"} if got, want := e.Error(), "dibs.toml:14:3: item[1].interval: must be at least 1m0s (got 30s)"; got != want { diff --git a/internal/config/validate.go b/internal/config/validate.go index 9c0575f..dd9a797 100644 --- a/internal/config/validate.go +++ b/internal/config/validate.go @@ -289,6 +289,10 @@ func (v *validator) accounts(cfg *Config, shops map[string]bool, lookupEnv func( } } + if acc.CartMode == CartModeSession && acc.PasswordEnv != "" && acc.Username == "" { + v.errorf(key, "username is missing: signing in with password_env needs it") + } + for _, f := range []struct{ name, raw string }{{"login_url", acc.LoginURL}, {"cart_url", acc.CartURL}} { if f.raw == "" { continue } diff --git a/internal/fetch/browser.go b/internal/fetch/browser.go index 977d7c5..64ea741 100644 --- a/internal/fetch/browser.go +++ b/internal/fetch/browser.go @@ -48,17 +48,18 @@ func DefaultBrowser() Browser { } } -// navigationHeaders are the headers Chrome sends when the user opens u by -// typing it or from a bookmark, in Chrome's order. -func (b Browser) navigationHeaders(u *url.URL) http.Header { - return http.Header{ +// navigationHeaders are the headers Chrome sends when the user opens u, in +// Chrome's order. Without a referer, u was typed in or opened from a +// bookmark. A content type makes it the submission of a form on referer. +func (b Browser) navigationHeaders(u, referer *url.URL, contentType string) http.Header { + h := http.Header{ "sec-ch-ua": {secCHUA(b.Major)}, "sec-ch-ua-mobile": {"?0"}, "sec-ch-ua-platform": {`"` + b.Platform + `"`}, "upgrade-insecure-requests": {"1"}, "user-agent": {b.UserAgent}, "accept": {"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"}, - "sec-fetch-site": {"none"}, + "sec-fetch-site": {fetchSite(u, referer)}, "sec-fetch-mode": {"navigate"}, "sec-fetch-user": {"?1"}, "sec-fetch-dest": {"document"}, @@ -66,9 +67,13 @@ func (b Browser) navigationHeaders(u *url.URL) http.Header { "accept-language": {acceptLanguage(u.Hostname())}, "priority": {"u=0, i"}, http.HeaderOrderKey: { + "content-length", + "cache-control", "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", + "origin", + "content-type", "upgrade-insecure-requests", "user-agent", "accept", @@ -76,12 +81,56 @@ func (b Browser) navigationHeaders(u *url.URL) http.Header { "sec-fetch-mode", "sec-fetch-user", "sec-fetch-dest", + "referer", "accept-encoding", "accept-language", "cookie", "priority", }, } + + if referer != nil { + // Chrome's default referrer policy leaves out the path on requests + // to other origins. + ref := referer.Scheme + "://" + referer.Host + "/" + if sameOrigin(u, referer) { ref = (&url.URL{Scheme: referer.Scheme, Host: referer.Host, Path: referer.Path, RawPath: referer.RawPath, RawQuery: referer.RawQuery}).String() } + + h.Set("referer", ref) + } + + if contentType != "" { + h.Set("cache-control", "max-age=0") + h.Set("content-type", contentType) + if referer != nil { h.Set("origin", referer.Scheme+"://"+referer.Host) } else { h.Set("origin", "null") } + } + + return h +} + +// fetchSite is the Sec-Fetch-Site of a navigation to u from referer. +func fetchSite(u, referer *url.URL) string { + switch { + case referer == nil: + return "none" + case sameOrigin(u, referer): + return "same-origin" + case u.Scheme == referer.Scheme && site(u.Hostname()) == site(referer.Hostname()): + return "same-site" + default: + return "cross-site" + } +} + +func sameOrigin(a, b *url.URL) bool { + return a.Scheme == b.Scheme && strings.EqualFold(a.Host, b.Host) +} + +// site is the registrable domain of host, such as amazon.co.uk. +func site(host string) string { + s, err := publicsuffix.EffectiveTLDPlusOne(strings.ToLower(host)) + if err != nil { return strings.ToLower(host) } + + return s } // Brand is one entry of Chrome's brand list, which sec-ch-ua and diff --git a/internal/fetch/client.go b/internal/fetch/client.go index 9ae7850..d381e24 100644 --- a/internal/fetch/client.go +++ b/internal/fetch/client.go @@ -3,12 +3,14 @@ package fetch import ( + "bytes" "context" "errors" "fmt" "io" stdhttp "net/http" "net/url" + "strings" "time" http "github.com/bogdanfinn/fhttp" @@ -27,7 +29,10 @@ var ErrBodyTooLarge = errors.New("response body too large") // Limiter decides when a page may be fetched. Every request waits for it. type Limiter interface { + // WaitCheck is for checks of a page, which Get makes. WaitCheck(ctx context.Context, url string) error + // Wait is for other requests to host, which Do makes. + Wait(ctx context.Context, host string) error } type Options struct { @@ -93,16 +98,85 @@ func (c *Client) Jar() *Jar { return c.jar } // a check of it. A response with a bad status is not an error; its Verdict // says what it is. func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) { - u, err := url.Parse(rawURL) + u, err := parseURL(rawURL) if err != nil { return nil, err } - if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) } if err := c.limiter.WaitCheck(ctx, rawURL); err != nil { return nil, err } req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { return nil, err } - req.Header = c.browser.navigationHeaders(u) + req.Header = c.browser.navigationHeaders(u, nil, "") + return c.send(req, rawURL) +} + +// Request is a request made for the user in session mode, such as +// submitting a sign-in form. +type Request struct { + // Method is GET or POST. + Method string + URL string + // Form is the body of a POST, sent as a submitted HTML form. Body and + // ContentType replace it for other bodies. + Form url.Values + Body []byte + ContentType string + // Referer is the page the request comes from. Without one, the request + // looks typed in. + Referer string + // Header adds or replaces headers. + Header map[string]string +} + +// Do sends r the way Chrome follows a link or submits a form, once the +// limiter allows a request to the host. Unlike Get, it is not a check of the +// page, so the URL floor does not apply. +func (c *Client) Do(ctx context.Context, r Request) (*Response, error) { + u, err := parseURL(r.URL) + if err != nil { return nil, err } + + var ref *url.URL + if r.Referer != "" { + if ref, err = parseURL(r.Referer); err != nil { return nil, fmt.Errorf("referer: %w", err) } + } + + var body io.Reader + contentType := r.ContentType + + switch { + case r.Method == http.MethodGet && (r.Form != nil || r.Body != nil): + return nil, errors.New("a GET request has no body") + case r.Method == http.MethodGet: + case r.Method == http.MethodPost && r.Body == nil: + body, contentType = strings.NewReader(r.Form.Encode()), "application/x-www-form-urlencoded" + case r.Method == http.MethodPost && contentType == "": + return nil, errors.New("a POST body needs a content type") + case r.Method == http.MethodPost: + body = bytes.NewReader(r.Body) + default: + return nil, fmt.Errorf("unsupported method %q", r.Method) + } + + if err := c.limiter.Wait(ctx, u.Hostname()); err != nil { return nil, err } + + req, err := http.NewRequestWithContext(ctx, r.Method, u.String(), body) + if err != nil { return nil, err } + + req.Header = c.browser.navigationHeaders(u, ref, contentType) + for k, v := range r.Header { req.Header.Set(strings.ToLower(k), v) } + + return c.send(req, r.URL) +} + +func parseURL(rawURL string) (*url.URL, error) { + u, err := url.Parse(rawURL) + if err != nil { return nil, err } + if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) } + + return u, nil +} + +func (c *Client) send(req *http.Request, rawURL string) (*Response, error) { start := time.Now() resp, err := c.http.Do(req) if err != nil { return nil, err } @@ -138,3 +212,20 @@ func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, bod return r } + +// RecordOutcome tells the limiter how a request to host went: bot checks, +// refusals and failed requests back the host off, anything else clears its +// backoff. It returns the backoff, or 0. +func RecordOutcome(l *ratelimit.Limiter, host string, resp *Response, err error) time.Duration { + switch { + case errors.Is(err, context.Canceled): + return 0 + case err != nil: + return l.Failure(host) + case resp.Verdict == Challenge || resp.Verdict == NeedsHuman || resp.Verdict == Blocked || resp.Verdict == HTTPError: + return l.Failure(host) + default: + l.Success(host) + return 0 + } +} diff --git a/internal/fetch/fetch_test.go b/internal/fetch/fetch_test.go index 39c2ea3..b8ea0d6 100644 --- a/internal/fetch/fetch_test.go +++ b/internal/fetch/fetch_test.go @@ -206,12 +206,23 @@ func TestJarShared(t *testing.T) { fresh.now = watcher.now if err := fresh.Load(path); err != nil { t.Fatal(err) } if got := cookieNames(fresh.Cookies(u)); got != "session=solved" { t.Errorf("file after both saved: %q", got) } + + // Logging out in another process clears the watcher's copy as well. + fresh.now = func() time.Time { return now.Add(3 * time.Minute) } + fresh.Clear() + if got := cookieNames(fresh.Cookies(u)); got != "" { t.Errorf("after Clear: %q", got) } + if err := fresh.Save(path); err != nil { t.Fatal(err) } + + watcher.now = func() time.Time { return now.Add(4 * time.Minute) } + if err := watcher.Save(path); err != nil { t.Fatal(err) } + if got := cookieNames(watcher.Cookies(u)); got != "" { t.Errorf("watcher after another process cleared the jar: %q", got) } } // noLimit lets tests talk to their local server without the host floor. type noLimit struct{} func (noLimit) WaitCheck(context.Context, string) error { return nil } +func (noLimit) Wait(context.Context, string) error { return nil } func newTestClient(t *testing.T, opts Options) *Client { t.Helper() @@ -279,6 +290,78 @@ func TestClientGet(t *testing.T) { if got := c.Jar().Export()["127.0.0.1"]; len(got) != 1 || got[0].Name != "sid" { t.Errorf("jar after requests: %+v", got) } } +// countingLimiter records which kind of wait each request made. +type countingLimiter struct{ checks, waits []string } + +func (l *countingLimiter) WaitCheck(_ context.Context, u string) error { + l.checks = append(l.checks, u) + return nil +} + +func (l *countingLimiter) Wait(_ context.Context, host string) error { + l.waits = append(l.waits, host) + return nil +} + +func TestClientDo(t *testing.T) { + var seen []*http.Request + var forms []url.Values + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + seen = append(seen, r) + forms = append(forms, r.PostForm) + + if r.URL.Path == "/signin" { http.Redirect(w, r, "/home", http.StatusFound) } + })) + defer srv.Close() + + limiter := &countingLimiter{} + c := newTestClient(t, Options{Limiter: limiter}) + + resp, err := c.Do(context.Background(), Request{ + Method: "POST", + URL: srv.URL + "/signin", + Form: url.Values{"email": {"me@example.com"}, "password": {"p&ss word"}}, + Referer: srv.URL + "/ap/signin?x=1", + }) + if err != nil { t.Fatal(err) } + + if resp.FinalURL != srv.URL+"/home" { t.Errorf("final URL %q, want the redirect followed", resp.FinalURL) } + if len(seen) != 2 { t.Fatalf("server saw %d requests, want 2", len(seen)) } + + post := seen[0] + if post.Method != "POST" || forms[0].Get("password") != "p&ss word" { t.Errorf("first request %s with form %v", post.Method, forms[0]) } + + for name, want := range map[string]string{ + "Content-Type": "application/x-www-form-urlencoded", + "Origin": srv.URL, + "Referer": srv.URL + "/ap/signin?x=1", + "Sec-Fetch-Site": "same-origin", + "Cache-Control": "max-age=0", + } { + if got := post.Header.Get(name); got != want { t.Errorf("%s = %q, want %q", name, got, want) } + } + + if len(limiter.checks) != 0 || len(limiter.waits) != 1 { t.Errorf("limiter saw checks %v and waits %v, want one host wait", limiter.checks, limiter.waits) } + + // A link from another site sends only that site's origin. + if _, err := c.Do(context.Background(), Request{Method: "GET", URL: srv.URL + "/cart", Referer: "https://www.example.com/a/b"}); err != nil { t.Fatal(err) } + + get := seen[len(seen)-1] + if got := get.Header.Get("Referer"); got != "https://www.example.com/" { t.Errorf("cross-site referer %q", got) } + if got := get.Header.Get("Sec-Fetch-Site"); got != "cross-site" { t.Errorf("cross-site Sec-Fetch-Site %q", got) } + if got := get.Header.Get("Origin"); got != "" { t.Errorf("GET sent Origin %q", got) } + + for _, bad := range []Request{ + {Method: "GET", URL: srv.URL, Form: url.Values{"a": {"b"}}}, + {Method: "POST", URL: srv.URL, Body: []byte("{}")}, + {Method: "DELETE", URL: srv.URL}, + } { + if _, err := c.Do(context.Background(), bad); err == nil { t.Errorf("%s with form %v and body %q: want an error", bad.Method, bad.Form, bad.Body) } + } +} + func TestClientBodyLimit(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(strings.Repeat("x", 2048))) diff --git a/internal/fetch/jar.go b/internal/fetch/jar.go index 7aa6d8f..f57a4fa 100644 --- a/internal/fetch/jar.go +++ b/internal/fetch/jar.go @@ -154,6 +154,28 @@ func (j *Jar) importLocked(host string, cookies []Cookie, now time.Time) { } } +// Clear deletes every cookie. The deletions are saved like any other +// change, so other processes sharing the file drop the cookies too. +func (j *Jar) Clear() { + j.mu.Lock() + defer j.mu.Unlock() + + now := j.now() + + for host, byKey := range j.cookies { + for _, c := range byKey { + if c.expired(now) { continue } + + hc := &http.Cookie{Name: c.Name, Path: c.Path, MaxAge: -1} + if !c.HostOnly { hc.Domain = c.Domain } + j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc}) + + c.Expires, c.Set = now, now + j.store(host, c, now) + } + } +} + func key(c Cookie) string { return c.Domain + "|" + c.Path + "|" + c.Name } // store records c for host. Callers hold mu. @@ -164,14 +186,26 @@ func (j *Jar) store(host string, c Cookie, now time.Time) { j.cookies[host][key(c)] = c } +// Codec turns the cookie file's JSON into what is stored on disk and back, +// such as to encrypt it. +type Codec interface { + Encode(data []byte) ([]byte, error) + Decode(data []byte) ([]byte, error) +} + // Save writes the cookies to path, readable only by the user. Other dibs // processes may share the file, so it first takes in their newer cookies. func (j *Jar) Save(path string) error { + return j.SaveWith(path, nil) +} + +// SaveWith is Save through codec, which may be nil. +func (j *Jar) SaveWith(path string, codec Codec) error { unlock, err := fsutil.Lock(path + ".lock") if err != nil { return err } defer unlock() - saved, err := readCookies(path) + saved, err := readCookies(path, codec) if err != nil { return err } j.mu.Lock() @@ -195,12 +229,21 @@ func (j *Jar) Save(path string) error { data, err := json.MarshalIndent(out, "", " ") if err != nil { return err } + if codec != nil { + if data, err = codec.Encode(data); err != nil { return err } + } + return fsutil.WriteFileAtomic(path, data, 0o600) } // Load imports the cookies saved at path. A missing file is not an error. func (j *Jar) Load(path string) error { - saved, err := readCookies(path) + return j.LoadWith(path, nil) +} + +// LoadWith is Load through codec, which may be nil. +func (j *Jar) LoadWith(path string, codec Codec) error { + saved, err := readCookies(path, codec) if err != nil { return err } for host, cookies := range saved { j.Import(host, cookies) } @@ -208,11 +251,15 @@ func (j *Jar) Load(path string) error { return nil } -func readCookies(path string) (map[string][]Cookie, error) { +func readCookies(path string, codec Codec) (map[string][]Cookie, error) { data, err := os.ReadFile(path) if errors.Is(err, fs.ErrNotExist) { return nil, nil } if err != nil { return nil, err } + if codec != nil { + if data, err = codec.Decode(data); err != nil { return nil, err } + } + var saved map[string][]Cookie if err := json.Unmarshal(data, &saved); err != nil { return nil, err } diff --git a/internal/notify/notify.go b/internal/notify/notify.go index 6af8f1e..270cf2e 100644 --- a/internal/notify/notify.go +++ b/internal/notify/notify.go @@ -192,17 +192,38 @@ func sleep(ctx context.Context, d time.Duration) error { } } -// link is where tapping a notification leads: the cart link if the shop has -// one, otherwise the product page. +// link is where tapping a notification leads: the cart page once session +// mode has added the item, the cart link if the shop has one, otherwise the +// product page. While session mode is adding the item, a cart link would add +// a second copy. func link(a alert.Alert) string { - if a.CartLink != "" { return a.CartLink } - - return a.URL + switch { + case a.Cart == alert.CartAdded && a.CartURL != "": + return a.CartURL + case a.Cart == alert.CartAdding || a.Cart == alert.CartAdded: + return a.URL + case a.CartLink != "": + return a.CartLink + default: + return a.URL + } } func headline(a alert.Alert) string { h := "In stock: " + a.Item - if a.Test { h = "Test alert: " + a.Item } + + switch a.Cart { + case alert.CartAdding: + h += ", adding to cart" + case alert.CartAdded: + h = "In cart: " + a.Item + ", finish checkout" + case alert.CartFailed: + h += ", adding to cart failed" + default: + // Deeplink mode. + } + + if a.Test { h = "Test alert: " + h } return h } @@ -215,17 +236,29 @@ func summary(a alert.Alert) string { return s } -func desktopText(a alert.Alert) (string, string) { - lines := []string{summary(a)} +// details are the lines under the summary. +func details(a alert.Alert) []string { + var lines []string + if a.CartError != "" { lines = append(lines, "Adding to the cart failed: "+a.CartError) } if a.Title != "" { lines = append(lines, a.Title) } - return headline(a), strings.Join(lines, "\n") + return lines +} + +func desktopText(a alert.Alert) (string, string) { + return headline(a), strings.Join(append([]string{summary(a)}, details(a)...), "\n") } func ntfyMessage(a alert.Alert) string { - lines := []string{summary(a)} - if a.Title != "" { lines = append(lines, a.Title) } - if a.CartLink != "" { lines = append(lines, "Cart: "+a.CartLink) } + lines := append([]string{summary(a)}, details(a)...) + + switch { + case a.Cart == alert.CartAdded && a.CartURL != "": + lines = append(lines, "Cart: "+a.CartURL) + case a.Cart != alert.CartAdding && a.Cart != alert.CartAdded && a.CartLink != "": + lines = append(lines, "Add to cart: "+a.CartLink) + } + lines = append(lines, "Page: "+a.URL) return strings.Join(lines, "\n") @@ -270,7 +303,22 @@ func discordPayload(a alert.Alert) discordMessage { if a.PreviousPrice != nil { price += ", down from " + alert.Money(*a.PreviousPrice, a.PreviousCurrency) } desc := "[Product page](" + a.URL + ")" - if a.CartLink != "" { desc = "[Add to cart](" + a.CartLink + ") · " + desc } + + switch l := link(a); { + case a.Cart == alert.CartAdded && l != a.URL: + desc = "[Cart](" + l + ") · " + desc + case l != a.URL: + desc = "[Add to cart](" + l + ") · " + desc + } + + fields := []discordField{ + {Name: "Price", Value: price, Inline: true}, + {Name: "Seller", Value: a.SellerText(), Inline: true}, + } + if a.CartError != "" { fields = append(fields, discordField{Name: "Adding to the cart failed", Value: truncate(a.CartError, 1024)}) } + + color := 0x2ecc71 + if a.Cart == alert.CartFailed { color = 0xe67e22 } return discordMessage{ Username: "dibs", @@ -280,11 +328,8 @@ func discordPayload(a alert.Alert) discordMessage { Title: truncate(title, 256), URL: link(a), Description: desc, - Color: 0x2ecc71, - Fields: []discordField{ - {Name: "Price", Value: price, Inline: true}, - {Name: "Seller", Value: a.SellerText(), Inline: true}, - }, + Color: color, + Fields: fields, Timestamp: a.Time.UTC().Format(time.RFC3339), }}, // Page titles never ping anyone. diff --git a/internal/notify/notify_test.go b/internal/notify/notify_test.go index 21edf70..8cac586 100644 --- a/internal/notify/notify_test.go +++ b/internal/notify/notify_test.go @@ -56,3 +56,40 @@ func TestRetries(t *testing.T) { if c.requests > 1 && waited != 7*time.Second { t.Errorf("%d: waited %s between attempts, want 7s", c.status, waited) } } } + +// TestCartSteps checks where each session-mode notification leads. While +// the item is being added, nothing may link to the cart link, which would +// add a second copy. +func TestCartSteps(t *testing.T) { + const ( + page = "https://www.amazon.de/dp/B0HMX2FSTF" + addLink = "https://www.amazon.de/gp/aws/cart/add.html?ASIN.1=B0HMX2FSTF&Quantity.1=1" + cart = "https://www.amazon.de/gp/cart/view.html" + ) + + base := alert.Alert{Item: "metro", Shop: "amazon", URL: page, CartLink: addLink, Time: time.Now()} + + cases := []struct { + cart, cartURL, cartErr string + headline, link string + } { + {"", "", "", "In stock: metro", addLink}, + {alert.CartAdding, "", "", "In stock: metro, adding to cart", page}, + {alert.CartAdded, cart, "", "In cart: metro, finish checkout", cart}, + {alert.CartFailed, "", "timeout", "In stock: metro, adding to cart failed", addLink}, + } + + for _, tc := range cases { + a := base + a.Cart, a.CartURL, a.CartError = tc.cart, tc.cartURL, tc.cartErr + + if got := headline(a); got != tc.headline { t.Errorf("%q: headline %q, want %q", tc.cart, got, tc.headline) } + if got := link(a); got != tc.link { t.Errorf("%q: link %q, want %q", tc.cart, got, tc.link) } + + msg := ntfyMessage(a) + desc := discordPayload(a).Embeds[0].Description + + if hasAdd := strings.Contains(msg, addLink) || strings.Contains(desc, addLink); hasAdd != (tc.link == addLink) { t.Errorf("%q: cart link in ntfy %v or discord %q", tc.cart, strings.Contains(msg, addLink), desc) } + if tc.cartErr != "" && !strings.Contains(msg, tc.cartErr) { t.Errorf("%q: ntfy message without the error: %q", tc.cart, msg) } + } +} diff --git a/internal/notify/payload.go b/internal/notify/payload.go index 75eab8e..0971d4e 100644 --- a/internal/notify/payload.go +++ b/internal/notify/payload.go @@ -27,10 +27,18 @@ const PayloadVersion = 1 // "previous_currency": null, // "seller": "first_party", // "cart_link": "https://www.amazon.de/gp/aws/cart/add.html?ASIN.1=B0HMX2FSTF&Quantity.1=1", +// "cart": null, +// "cart_url": null, +// "cart_error": null, // "time": "2026-10-14T09:30:00Z" // } // // Every key is always present; values that do not apply are null. +// +// In session mode, an item that fires sends up to two payloads: one with +// "cart": "adding" and no cart_link, then one with "cart": "added" and the +// cart page in cart_url, or "cart": "failed", the reason in cart_error and +// the cart link. type Payload struct { Version int `json:"version"` // Test is true for the sample alert of `dibs notify test`. @@ -55,6 +63,11 @@ type Payload struct { // Seller is "first_party", "fulfilled", "third_party" or "unknown". Seller string `json:"seller"` CartLink *string `json:"cart_link"` + // Cart is null without session mode, else "adding", "added" or + // "failed". + Cart *string `json:"cart"` + CartURL *string `json:"cart_url"` + CartError *string `json:"cart_error"` // Time is when the page was checked, in UTC. Time time.Time `json:"time"` } @@ -75,6 +88,9 @@ func NewPayload(a alert.Alert) Payload { PreviousCurrency: orNull(a.PreviousCurrency), Seller: a.Seller, CartLink: orNull(a.CartLink), + Cart: orNull(a.Cart), + CartURL: orNull(a.CartURL), + CartError: orNull(a.CartError), Time: a.Time.UTC().Truncate(time.Second), } } diff --git a/internal/plugin/amazon_session_test.go b/internal/plugin/amazon_session_test.go new file mode 100644 index 0000000..4becb0d --- /dev/null +++ b/internal/plugin/amazon_session_test.go @@ -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/.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 = `` + +func signInPage(fields string) string { + return `
` + fields + `
` +} + +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("" + body + "")) } + + switch { + case r.URL.Path == "/ap/signin" && r.Method == "GET" && r.URL.Query().Get("skip") == "fixup": + f.skipped = true + write(`
`) + 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(``)) + 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(`
Wrong code
`) + 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(`
Ihr Passwort ist falsch
` + signInPage(``)) + case f.captcha: + write(`` + signInPage(``)) + default: + // As on amazon.de: a request for a phone number, with a link + // to skip it. + write(`
` + + `
` + + `Nicht jetzt`) + } + 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(``)) + case r.URL.Path == "/" && signedIn: + write(``) + case r.URL.Path == "/gp/cart/view.html" && !signedIn: + write(signedOutNav + `
`) + case r.URL.Path == "/gp/cart/view.html": + items := "" + if f.inCart { items = `
` } + + write(`
` + items + `
`) + 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 + `
In den Einkaufswagen gelegt
`) + 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) } +} diff --git a/internal/plugin/builtin/amazon.lua b/internal/plugin/builtin/amazon.lua index 6050e52..bb5c7d1 100644 --- a/internal/plugin/builtin/amazon.lua +++ b/internal/plugin/builtin/amazon.lua @@ -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, } diff --git a/internal/plugin/plugin.go b/internal/plugin/plugin.go index 7afaa07..52246e8 100644 --- a/internal/plugin/plugin.go +++ b/internal/plugin/plugin.go @@ -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)) } diff --git a/internal/plugin/sandbox.go b/internal/plugin/sandbox.go index b19fc19..fb317cf 100644 --- a/internal/plugin/sandbox.go +++ b/internal/plugin/sandbox.go @@ -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 { diff --git a/internal/plugin/session.go b/internal/plugin/session.go new file mode 100644 index 0000000..3ee59fe --- /dev/null +++ b/internal/plugin/session.go @@ -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) +} diff --git a/internal/plugin/session_test.go b/internal/plugin/session_test.go new file mode 100644 index 0000000..b8917fc --- /dev/null +++ b/internal/plugin/session_test.go @@ -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 := "

sign in

", 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 = `

welcome

` + } + 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) } +} diff --git a/internal/session/session.go b/internal/session/session.go new file mode 100644 index 0000000..cc42834 --- /dev/null +++ b/internal/session/session.go @@ -0,0 +1,335 @@ +// Package session runs a shop's session mode: signing in to the user's +// account and adding an item to its cart, through the plugin's login and +// add_to_cart. The account's cookies are kept apart from the watcher's, so +// checks of product pages never carry the account. +package session + +import ( + "context" + "errors" + "fmt" + "log/slog" + "maps" + "net/url" + "os" + "strings" + "sync" + "time" + + "git.security-command.org/Overlord/dibs/internal/chrome" + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/fetch" + "git.security-command.org/Overlord/dibs/internal/plugin" + "git.security-command.org/Overlord/dibs/internal/ratelimit" +) + +var ( + // ErrNoPrompt means nobody can answer a question, such as when dibs + // runs headless without a terminal. + ErrNoPrompt = errors.New("no terminal to ask in") + // ErrDeclined means the user turned down the plugin's session warning. + ErrDeclined = errors.New("session mode declined") +) + +// Prompter asks the user. The TUI shows a modal; on the command line, the +// question goes to the terminal. +type Prompter interface { + // Prompt asks for text, such as a one-time code. title names the shop + // and site that ask. + Prompt(ctx context.Context, title, label string, secret bool) (string, error) + // Confirm asks the user to accept message before going on. + Confirm(ctx context.Context, title, message string) (bool, error) +} + +// Record is what the state file remembers of a shop's session mode. +type Record struct { + // Warned is when the user accepted the plugin's session warning. + Warned time.Time `json:"warned,omitzero"` + // Logins has the time of the last sign-in to each host. + Logins map[string]time.Time `json:"logins,omitempty"` +} + +// Store shares the records with other dibs processes. +type Store interface { + Lock() func() + LoadSession(shop string) (Record, bool) + StoreSession(shop string, r Record) +} + +// Manager is one shop's session. It is safe for concurrent use; logins and +// additions to the cart run one at a time. +type Manager struct { + shop string + vault *Vault + jar *fetch.Jar + pipeline *chrome.Pipeline + chrome *chrome.Chrome + limiter *ratelimit.Limiter + store Store + logger *slog.Logger + + calls sync.Mutex + + mu sync.Mutex + account config.Account + prompter Prompter +} + +// New returns shop's session with the cookies saved in vault. Requests wait +// for limiter like every other request to the shop. +func New(shop string, vault *Vault, limiter *ratelimit.Limiter, store Store, logger *slog.Logger) (*Manager, error) { + jar := fetch.NewJar() + + if err := vault.Load(shop, jar); err != nil { + logger.Warn("signed-in cookies unreadable, signing in again", "shop", shop, "err", err) + if err := vault.Forget(shop); err != nil { return nil, err } + + jar = fetch.NewJar() + } + + client, err := fetch.New(fetch.Options{Limiter: limiter, Jar: jar}) + if err != nil { return nil, err } + + browser := chrome.New(fetch.DefaultBrowser(), jar, logger) + + return &Manager{ + shop: shop, + vault: vault, + jar: jar, + pipeline: &chrome.Pipeline{Client: client, Chrome: browser, Limiter: limiter, Logger: logger}, + chrome: browser, + limiter: limiter, + store: store, + logger: logger, + }, nil +} + +// Update switches to new account settings and to the way to reach the +// user, after a reload. +func (m *Manager) Update(account config.Account, prompter Prompter) { + m.mu.Lock() + defer m.mu.Unlock() + + m.account, m.prompter = account, prompter +} + +func (m *Manager) settings() (config.Account, Prompter) { + m.mu.Lock() + defer m.mu.Unlock() + + return m.account, m.prompter +} + +// HasPassword reports whether the account can sign in without the user. +func (m *Manager) HasPassword() bool { + acc, _ := m.settings() + return acc.PasswordEnv != "" && os.Getenv(acc.PasswordEnv) != "" +} + +// SignedIn reports whether dibs, in this or another process, signed in to +// host and has not found the session signed out since. +func (m *Manager) SignedIn(host string) bool { + r, _ := m.store.LoadSession(m.shop) + _, ok := r.Logins[strings.ToLower(host)] + + return ok +} + +// Accept shows p's session warning, unless the user accepted it before. It +// returns ErrDeclined if the user turns it down now. Without anyone to ask, +// the warning is logged and counts as accepted. +func (m *Manager) Accept(ctx context.Context, p *plugin.Plugin) error { + if p.SessionWarning == "" { return nil } + + if r, _ := m.store.LoadSession(m.shop); !r.Warned.IsZero() { return nil } + + _, prompter := m.settings() + + ok, err := prompter.Confirm(ctx, "Session mode for "+m.shop, p.SessionWarning) + + switch { + case errors.Is(err, ErrNoPrompt): + m.logger.Warn(p.SessionWarning, "shop", m.shop) + case err != nil: + return err + case !ok: + return ErrDeclined + } + + m.update(func(r *Record) { r.Warned = time.Now() }) + return nil +} + +// Login signs in to site, such as https://www.amazon.de/, with the plugin's +// login and the account's password. +func (m *Manager) Login(ctx context.Context, p *plugin.Plugin, site string) error { + host, err := hostOf(site) + if err != nil { return err } + + if err := m.Accept(ctx, p); err != nil { return err } + + acc, prompter := m.settings() + if acc.PasswordEnv == "" { return fmt.Errorf("accounts.%s has no password_env; sign in with: dibs login %s --browser", m.shop, m.shop) } + + m.calls.Lock() + defer m.calls.Unlock() + + m.sync() + defer m.sync() + + account := m.pluginAccount(acc, site) + account.Password = os.Getenv(acc.PasswordEnv) + + m.logger.Info("signing in", "shop", m.shop, "host", host, "user", acc.Username) + + if err := p.Login(ctx, m.session(prompter, host), account); err != nil { return err } + + m.update(func(r *Record) { r.Logins[host] = time.Now() }) + m.logger.Info("signed in", "shop", m.shop, "host", host) + + return nil +} + +// BrowserLogin opens loginURL, or site if it is empty, in a visible Chrome +// window for the user to sign in themselves, and keeps the cookies once the +// window is closed. The window does not count against the rate limits. +func (m *Manager) BrowserLogin(ctx context.Context, site, loginURL string) error { + host, err := hostOf(site) + if err != nil { return err } + + if loginURL == "" { loginURL = site } + + m.calls.Lock() + defer m.calls.Unlock() + + m.sync() + defer m.sync() + + n, err := m.chrome.SignIn(ctx, loginURL) + if err != nil { return err } + if n == 0 { return fmt.Errorf("Chrome had no cookies for %s", host) } + + m.update(func(r *Record) { r.Logins[host] = time.Now() }) + m.limiter.Success(host) + + return nil +} + +// AddToCart puts the item on productURL in the cart, unless it is there +// already, and returns the cart page. It returns plugin.ErrSignedOut when +// the session has run out; the next Login signs in again. +func (m *Manager) AddToCart(ctx context.Context, p *plugin.Plugin, productURL string) (string, error) { + host, err := hostOf(productURL) + if err != nil { return "", err } + + acc, prompter := m.settings() + + m.calls.Lock() + defer m.calls.Unlock() + + m.sync() + defer m.sync() + + u, _ := url.Parse(productURL) + + cart, err := p.AddToCart(ctx, m.session(prompter, host), m.pluginAccount(acc, u.Scheme+"://"+u.Host+"/"), productURL) + if errors.Is(err, plugin.ErrSignedOut) { m.update(func(r *Record) { delete(r.Logins, host) }) } + + return cart, err +} + +// Logout deletes the session's cookies, in every dibs process. +func (m *Manager) Logout() error { + m.calls.Lock() + defer m.calls.Unlock() + + m.jar.Clear() + m.update(func(r *Record) { r.Logins = nil }) + + return m.vault.Save(m.shop, m.jar) +} + +func (m *Manager) pluginAccount(acc config.Account, site string) plugin.Account { + return plugin.Account{Username: acc.Username, TwoFA: acc.TwoFA, LoginURL: acc.LoginURL, CartURL: acc.CartURL, Site: site} +} + +// sync saves the cookies, which also takes in what other processes saved, +// such as a `dibs login` next to a running watcher. +func (m *Manager) sync() { + if err := m.vault.Save(m.shop, m.jar); err != nil { m.logger.Warn("saving signed-in cookies failed", "shop", m.shop, "err", err) } +} + +func (m *Manager) update(change func(r *Record)) { + unlock := m.store.Lock() + defer unlock() + + r, _ := m.store.LoadSession(m.shop) + + logins := maps.Clone(r.Logins) + if logins == nil { logins = map[string]time.Time{} } + r.Logins = logins + + change(&r) + m.store.StoreSession(m.shop, r) +} + +func (m *Manager) session(prompter Prompter, host string) *pluginSession { + return &pluginSession{m: m, prompter: prompter, title: m.shop + " · " + host} +} + +// pluginSession is the plugin.Session of one call. +type pluginSession struct { + m *Manager + prompter Prompter + title string +} + +// Do sends a request with the account's cookies. Its outcome backs the +// host off or clears its backoff like a check's. +func (s *pluginSession) Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) { + resp, err := s.m.pipeline.Do(ctx, r) + + if u, perr := url.Parse(r.URL); perr == nil && ctx.Err() == nil { fetch.RecordOutcome(s.m.limiter, u.Hostname(), resp, err) } + + return resp, err +} + +// Click presses a button in headless Chrome. Loading the page and clicking +// each wait for the host floor. +func (s *pluginSession) Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error) { + host, err := hostOf(rawURL) + if err != nil { return nil, err } + + wait := func() error { return s.m.limiter.Wait(ctx, host) } + if err := wait(); err != nil { return nil, err } + + resp, err := s.m.chrome.Click(ctx, rawURL, sel, wait) + + // A missing button or a failed Chrome is no sign of the host's mood. + if err == nil { fetch.RecordOutcome(s.m.limiter, host, resp, nil) } + + return resp, err +} + +func (s *pluginSession) Prompt(ctx context.Context, label string, secret bool) (string, error) { + return s.prompter.Prompt(ctx, s.title, label, secret) +} + +func (s *pluginSession) Cookies(rawURL string) map[string]string { + out := map[string]string{} + + u, err := url.Parse(rawURL) + if err != nil { return out } + + for _, c := range s.m.jar.Cookies(u) { out[c.Name] = c.Value } + + return out +} + +func hostOf(rawURL string) (string, error) { + u, err := url.Parse(rawURL) + if err != nil { return "", err } + if u.Hostname() == "" { return "", fmt.Errorf("no host in %q", rawURL) } + + return strings.ToLower(u.Hostname()), nil +} diff --git a/internal/session/session_test.go b/internal/session/session_test.go new file mode 100644 index 0000000..8099378 --- /dev/null +++ b/internal/session/session_test.go @@ -0,0 +1,197 @@ +package session_test + +import ( + "bytes" + "context" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + fhttp "github.com/bogdanfinn/fhttp" + "github.com/zalando/go-keyring" + + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/fetch" + "git.security-command.org/Overlord/dibs/internal/plugin" + "git.security-command.org/Overlord/dibs/internal/ratelimit" + "git.security-command.org/Overlord/dibs/internal/session" + "git.security-command.org/Overlord/dibs/internal/state" +) + +func discard() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } + +func TestVault(t *testing.T) { + dir := t.TempDir() + u := &url.URL{Scheme: "https", Host: "www.amazon.de", Path: "/"} + + jar := fetch.NewJar() + jar.SetCookies(u, []*fhttp.Cookie{{Name: "at-acbde", Value: "secret-session", Path: "/", Expires: time.Now().Add(time.Hour)}}) + + // Without a keyring, the cookies are stored, but in plain text. + keyring.MockInitWithError(errors.New("no secret service")) + + plain, err := session.OpenVault(dir) + if err == nil || plain.Encrypted() { t.Fatalf("without a keyring: err %v, encrypted %v", err, plain.Encrypted()) } + if err := plain.Save("amazon", jar); err != nil { t.Fatal(err) } + + data, err := os.ReadFile(filepath.Join(dir, "sessions", "amazon.json")) + if err != nil || !bytes.Contains(data, []byte("secret-session")) { t.Fatalf("plain file: %v, %s", err, data) } + + // With a keyring, the plain file is encrypted on first use. + keyring.MockInit() + + vault, err := session.OpenVault(dir) + if err != nil || !vault.Encrypted() { t.Fatalf("with a keyring: err %v, encrypted %v", err, vault.Encrypted()) } + + loaded := fetch.NewJar() + if err := vault.Load("amazon", loaded); err != nil { t.Fatal(err) } + if got := loaded.Cookies(u); len(got) != 1 || got[0].Value != "secret-session" { t.Errorf("loaded %v", got) } + + if _, err := os.Stat(filepath.Join(dir, "sessions", "amazon.json")); !errors.Is(err, os.ErrNotExist) { t.Errorf("plain file still there: %v", err) } + + data, err = os.ReadFile(filepath.Join(dir, "sessions", "amazon.cookies")) + if err != nil || bytes.Contains(data, []byte("secret-session")) || bytes.Contains(data, []byte("at-acbde")) { t.Errorf("encrypted file: %v, %q", err, data) } + + // Another process opening the vault uses the same key. + again, err := session.OpenVault(dir) + if err != nil { t.Fatal(err) } + + other := fetch.NewJar() + if err := again.Load("amazon", other); err != nil { t.Fatal(err) } + if got := other.Cookies(u); len(got) != 1 { t.Errorf("second process loaded %v", got) } +} + +// instantClock lets the limiter's waits pass at once. +type instantClock struct { + mu sync.Mutex + now time.Time +} + +func (c *instantClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + + return c.now +} + +func (c *instantClock) After(d time.Duration) <-chan time.Time { + c.mu.Lock() + c.now = c.now.Add(d) + c.mu.Unlock() + + ch := make(chan time.Time, 1) + ch <- c.Now() + return ch +} + +type fakePrompter struct { + accept bool + confirms int +} + +func (f *fakePrompter) Prompt(context.Context, string, string, bool) (string, error) { return "123456", nil } + +func (f *fakePrompter) Confirm(context.Context, string, string) (bool, error) { + f.confirms++ + return f.accept, nil +} + +// shop serves testdata/session/shop.lua's sign-in and cart. +func shop(t *testing.T) (*httptest.Server, *atomic.Int32) { + requests := &atomic.Int32{} + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _ = r.ParseForm() + + c, _ := r.Cookie("session") + + switch { + case r.URL.Path == "/signin" && r.Method == "POST" && r.Form.Get("password") == "hunter2": + http.SetCookie(w, &http.Cookie{Name: "session", Value: "yes", Path: "/"}) + _, _ = w.Write([]byte(`

welcome

`)) + case r.URL.Path == "/cart" && c != nil && r.Header.Get("X-Test") == "yes": + w.Header().Set("X-Cart", "1") + } + })) + t.Cleanup(srv.Close) + + return srv, requests +} + +func newManager(t *testing.T, dir string, prompter session.Prompter) (*session.Manager, *plugin.Plugin) { + t.Helper() + + code, err := os.ReadFile(filepath.Join("..", "..", "testdata", "session", "shop.lua")) + if err != nil { t.Fatal(err) } + + p, err := plugin.Load("shop", "shop.lua", code, plugin.DefaultLimits(), discard()) + if err != nil { t.Fatal(err) } + t.Cleanup(p.Close) + + vault, err := session.OpenVault(dir) + if err != nil { t.Fatal(err) } + + limiter := ratelimit.New(nil, ratelimit.WithClock(&instantClock{now: time.Now()})) + + m, err := session.New("shop", vault, limiter, state.Open(dir), discard()) + if err != nil { t.Fatal(err) } + + t.Setenv("DIBS_TEST_SHOP_PASS", "hunter2") + m.Update(config.Account{Username: "me@example.com", PasswordEnv: "DIBS_TEST_SHOP_PASS", CartMode: config.CartModeSession, TwoFA: true}, prompter) + + return m, p +} + +func TestManager(t *testing.T) { + keyring.MockInit() + + dir := t.TempDir() + srv, requests := shop(t) + site := srv.URL + "/" + host := "127.0.0.1" + ctx := context.Background() + + // Turning down the session warning stops the login before any request. + declining := &fakePrompter{} + m, p := newManager(t, dir, declining) + + if err := m.Login(ctx, p, site); !errors.Is(err, session.ErrDeclined) { t.Fatalf("declined: got %v", err) } + if n := requests.Load(); n != 0 { t.Errorf("%d requests after declining", n) } + + accepting := &fakePrompter{accept: true} + m.Update(config.Account{Username: "me@example.com", PasswordEnv: "DIBS_TEST_SHOP_PASS", TwoFA: true}, accepting) + + if err := m.Login(ctx, p, site); err != nil { t.Fatal(err) } + if !m.SignedIn(host) { t.Error("not signed in after Login") } + + // The warning is shown once. + if err := m.Login(ctx, p, site); err != nil { t.Fatal(err) } + if accepting.confirms != 1 { t.Errorf("warning shown %d times", accepting.confirms) } + + // Another process picks up the session from the vault and the state + // file. + other, p2 := newManager(t, dir, accepting) + if !other.SignedIn(host) { t.Error("other process: not signed in") } + + cart, err := other.AddToCart(ctx, p2, site+"item/ok") + if err != nil || cart != site+"cart" { t.Errorf("other process: %q, %v", cart, err) } + + // A session found signed out needs a new login. + if _, err := other.AddToCart(ctx, p2, site+"item/signedout"); !errors.Is(err, plugin.ErrSignedOut) { t.Errorf("signed out: got %v", err) } + if m.SignedIn(host) { t.Error("still signed in after the session ran out") } + + // Logging out clears the cookies of the other process too. + if err := m.Login(ctx, p, site); err != nil { t.Fatal(err) } + if err := m.Logout(); err != nil { t.Fatal(err) } + if _, err := other.AddToCart(ctx, p2, site+"item/ok"); err == nil { t.Error("added to the cart after logging out") } +} diff --git a/internal/session/vault.go b/internal/session/vault.go new file mode 100644 index 0000000..4591fc7 --- /dev/null +++ b/internal/session/vault.go @@ -0,0 +1,145 @@ +package session + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + + "github.com/zalando/go-keyring" + + "git.security-command.org/Overlord/dibs/internal/fetch" + "git.security-command.org/Overlord/dibs/internal/fsutil" +) + +const ( + keyringService = "dibs" + keyringUser = "session-key" +) + +// Vault keeps each shop's signed-in cookies in a file of their own. The +// files are encrypted with a key kept in the OS keyring. Without a keyring, +// they are plain files only the user can read. +// +// The keyring holds only the key: Windows limits a keyring entry to 2560 +// bytes, which a shop's cookies can exceed. +type Vault struct { + dir string + codec fetch.Codec // nil without a keyring +} + +// OpenVault returns the vault in dir/sessions. When the keyring cannot be +// used, it also returns an error saying so, and the vault stores plain +// files. +func OpenVault(dir string) (*Vault, error) { + v := &Vault{dir: filepath.Join(dir, "sessions")} + + key, err := v.key() + if err != nil { return v, fmt.Errorf("no usable OS keyring, so signed-in cookies are stored unencrypted in %s: %w", v.dir, err) } + + block, err := aes.NewCipher(key) + if err != nil { return v, err } + + aead, err := cipher.NewGCM(block) + if err != nil { return v, err } + + v.codec = sealer{aead} + return v, nil +} + +// Encrypted reports whether the files are encrypted. +func (v *Vault) Encrypted() bool { return v.codec != nil } + +// key returns the vault's key from the keyring, creating it on first use. +func (v *Vault) key() ([]byte, error) { + // Two processes creating a key at once would each encrypt with their + // own. + unlock, err := fsutil.Lock(filepath.Join(v.dir, "key.lock")) + if err != nil { return nil, err } + defer unlock() + + s, err := keyring.Get(keyringService, keyringUser) + + switch { + case err == nil: + key, err := base64.StdEncoding.DecodeString(s) + if err != nil || len(key) != 32 { return nil, errors.New("the session key in the keyring is not a 256-bit key") } + + return key, nil + case errors.Is(err, keyring.ErrNotFound): + key := make([]byte, 32) + _, _ = rand.Read(key) + + if err := keyring.Set(keyringService, keyringUser, base64.StdEncoding.EncodeToString(key)); err != nil { return nil, err } + + return key, nil + default: + return nil, err + } +} + +func (v *Vault) path(shop string) string { + if v.codec != nil { return filepath.Join(v.dir, shop+".cookies") } + + return v.plainPath(shop) +} + +func (v *Vault) plainPath(shop string) string { return filepath.Join(v.dir, shop+".json") } + +// Load reads shop's cookies into jar. Cookies stored unencrypted before a +// keyring was available are encrypted now. +func (v *Vault) Load(shop string, jar *fetch.Jar) error { + if err := jar.LoadWith(v.path(shop), v.codec); err != nil { return fmt.Errorf("reading %s: %w", v.path(shop), err) } + + if v.codec == nil { return nil } + + plain := v.plainPath(shop) + if _, err := os.Stat(plain); errors.Is(err, fs.ErrNotExist) { return nil } + + if err := jar.Load(plain); err != nil { return fmt.Errorf("reading %s: %w", plain, err) } + if err := v.Save(shop, jar); err != nil { return err } + + return os.Remove(plain) +} + +// Save writes jar as shop's cookies, after taking in newer cookies other +// dibs processes saved. +func (v *Vault) Save(shop string, jar *fetch.Jar) error { + return jar.SaveWith(v.path(shop), v.codec) +} + +// Forget removes shop's file, such as one that cannot be decrypted. +func (v *Vault) Forget(shop string) error { + for _, p := range []string{v.path(shop), v.plainPath(shop)} { + if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) { return err } + } + + return nil +} + +// sealer encrypts with AES-GCM, with the nonce in front of the ciphertext. +type sealer struct{ aead cipher.AEAD } + +var additionalData = []byte("dibs session cookies v1") + +func (s sealer) Encode(data []byte) ([]byte, error) { + nonce := make([]byte, s.aead.NonceSize()) + _, _ = rand.Read(nonce) + + return s.aead.Seal(nonce, nonce, data, additionalData), nil +} + +func (s sealer) Decode(data []byte) ([]byte, error) { + n := s.aead.NonceSize() + if len(data) < n { return nil, errors.New("the file is too short to be encrypted cookies") } + + out, err := s.aead.Open(nil, data[:n], data[n:], additionalData) + if err != nil { return nil, errors.New("the file cannot be decrypted with the key in the keyring") } + + return out, nil +} diff --git a/internal/state/state.go b/internal/state/state.go index 2cbdbcf..43f29c3 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -17,6 +17,7 @@ import ( "git.security-command.org/Overlord/dibs/internal/fsutil" "git.security-command.org/Overlord/dibs/internal/fx" "git.security-command.org/Overlord/dibs/internal/ratelimit" + "git.security-command.org/Overlord/dibs/internal/session" ) // Hosts, URLs and alerts untouched for forgetAfter are dropped, such as URLs @@ -25,14 +26,16 @@ import ( const forgetAfter = config.MaxCooldown type file struct { - Hosts map[string]ratelimit.HostState `json:"hosts"` - URLs map[string]time.Time `json:"urls"` - Alerts map[string]alert.Sent `json:"alerts,omitempty"` - FX *fx.Rates `json:"fx,omitempty"` + Hosts map[string]ratelimit.HostState `json:"hosts"` + URLs map[string]time.Time `json:"urls"` + Alerts map[string]alert.Sent `json:"alerts,omitempty"` + FX *fx.Rates `json:"fx,omitempty"` + // Sessions are never forgotten, unlike the rest. + Sessions map[string]session.Record `json:"sessions,omitempty"` } -// Store is the state file. It implements ratelimit.Persister, alert.Store -// and fx.Store. +// Store is the state file. It implements ratelimit.Persister, alert.Store, +// fx.Store and session.Store. type Store struct { path string lock string @@ -133,10 +136,24 @@ func (s *Store) StoreRates(r *fx.Rates) { }) } +func (s *Store) LoadSession(shop string) (session.Record, bool) { + s.mu.Lock() + defer s.mu.Unlock() + + r, ok := s.read().Sessions[shop] + return r, ok +} + +func (s *Store) StoreSession(shop string, r session.Record) { + s.update(func(f *file) { + if r.Warned.IsZero() && len(r.Logins) == 0 { delete(f.Sessions, shop) } else { f.Sessions[shop] = r } + }) +} + // read returns the file's contents, or empty state if there is none yet. // Callers hold mu. func (s *Store) read() *file { - f := &file{Hosts: map[string]ratelimit.HostState{}, URLs: map[string]time.Time{}, Alerts: map[string]alert.Sent{}} + f := &file{Hosts: map[string]ratelimit.HostState{}, URLs: map[string]time.Time{}, Alerts: map[string]alert.Sent{}, Sessions: map[string]session.Record{}} data, err := os.ReadFile(s.path) switch { @@ -152,9 +169,10 @@ func (s *Store) read() *file { return f } - if f.Hosts == nil { f.Hosts = map[string]ratelimit.HostState{} } - if f.URLs == nil { f.URLs = map[string]time.Time{} } - if f.Alerts == nil { f.Alerts = map[string]alert.Sent{} } + if f.Hosts == nil { f.Hosts = map[string]ratelimit.HostState{} } + if f.URLs == nil { f.URLs = map[string]time.Time{} } + if f.Alerts == nil { f.Alerts = map[string]alert.Sent{} } + if f.Sessions == nil { f.Sessions = map[string]session.Record{} } return f } diff --git a/internal/tui/model.go b/internal/tui/model.go index a4a9a93..ecb1771 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -50,6 +50,17 @@ type CheckMsg struct { PriceErr error } +// CartMsg is the outcome of adding an item to the cart in session mode. +type CartMsg struct { + Item string + // URL is the URL as configured. + URL string + // Link is the cart page, or the cart link when adding failed. It is + // what enter opens from now on. + Link string + Err error +} + type ( tickMsg time.Time logMsg LogLine @@ -109,6 +120,7 @@ type Model struct { noteTime time.Time reloading bool solving string // the host whose bot check is open in a browser + modal *modal } // New returns the TUI for ctl. path is the config file, and logs is the @@ -172,13 +184,50 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.rows = m.ctl.Statuses() case openMsg: if msg.err != nil { m.setNote("cannot open the browser: "+msg.err.Error(), true) } else { m.setNote("opened "+msg.url, false) } + case CartMsg: + m.carted(msg) + case promptMsg: + if m.modal != nil { m.answer(promptReply{}) } + + var cmd tea.Cmd + m.modal, cmd = newModal(msg) + return m, tea.Batch(cmd, tea.Raw("\a")) + case closePromptMsg: + if m.modal != nil && m.modal.msg.id == msg.id { m.modal = nil } case tea.KeyPressMsg: + if m.modal != nil { return m, m.modalKey(msg) } + return m, m.key(msg) + default: + // The modal's cursor blinks. + if m.modal != nil { + var cmd tea.Cmd + m.modal.input, cmd = m.modal.input.Update(msg) + return m, cmd + } } return m, nil } +// carted records the outcome of adding an item to the cart. +func (m *Model) carted(c CartMsg) { + r := m.results[c.URL] + if r == nil { + r = &result{} + m.results[c.URL] = r + } + + r.cartLink = c.Link + + if c.Err != nil { + m.setNote("adding "+c.Item+" to the cart failed: "+c.Err.Error(), true) + return + } + + m.setNote(c.Item+" is in the cart: press enter on its row and finish checkout", false) +} + // checked records a check. A new alert flashes its row and rings the bell. func (m *Model) checked(c CheckMsg) tea.Cmd { r := m.results[c.Result.URL] diff --git a/internal/tui/prompt.go b/internal/tui/prompt.go new file mode 100644 index 0000000..b43cefd --- /dev/null +++ b/internal/tui/prompt.go @@ -0,0 +1,146 @@ +package tui + +import ( + "context" + "errors" + "sync" + + "charm.land/bubbles/v2/textinput" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" +) + +// ErrCancelled means the user closed a modal with esc. +var ErrCancelled = errors.New("cancelled in the TUI") + +// Prompter asks the user in a modal, for session mode: one-time codes and +// the session warnings of plugins. One modal shows at a time; other +// questions wait for it. +type Prompter struct { + program *tea.Program + + mu sync.Mutex + next int +} + +func NewPrompter(p *tea.Program) *Prompter { + return &Prompter{program: p} +} + +// Prompt asks for text. A secret is masked as it is typed. +func (pr *Prompter) Prompt(ctx context.Context, title, label string, secret bool) (string, error) { + r, err := pr.ask(ctx, promptMsg{title: title, label: label, secret: secret}) + if err != nil { return "", err } + if !r.ok { return "", ErrCancelled } + + return r.text, nil +} + +// Confirm shows message until the user accepts it with enter or turns it +// down with esc. +func (pr *Prompter) Confirm(ctx context.Context, title, message string) (bool, error) { + r, err := pr.ask(ctx, promptMsg{title: title, label: message, confirm: true}) + return r.ok, err +} + +func (pr *Prompter) ask(ctx context.Context, msg promptMsg) (promptReply, error) { + pr.mu.Lock() + defer pr.mu.Unlock() + + pr.next++ + reply := make(chan promptReply, 1) + msg.id = pr.next + msg.reply = reply + + pr.program.Send(msg) + + select { + case r := <-reply: + return r, nil + case <-ctx.Done(): + pr.program.Send(closePromptMsg{id: msg.id}) + return promptReply{}, ctx.Err() + } +} + +type ( + promptMsg struct { + id int + title string + label string + secret bool + confirm bool + reply chan<- promptReply + } + promptReply struct { + text string + ok bool + } + // closePromptMsg closes a modal whose question timed out. + closePromptMsg struct{ id int } +) + +type modal struct { + msg promptMsg + input textinput.Model +} + +func newModal(msg promptMsg) (*modal, tea.Cmd) { + in := textinput.New() + in.Prompt = "> " + if msg.secret { in.EchoMode = textinput.EchoPassword } + + return &modal{msg: msg, input: in}, in.Focus() +} + +// answer replies and closes the modal. +func (m *Model) answer(r promptReply) { + m.modal.msg.reply <- r + m.modal = nil +} + +func (m *Model) modalKey(msg tea.KeyPressMsg) tea.Cmd { + switch msg.String() { + case "ctrl+c": + m.answer(promptReply{}) + return tea.Quit + case "esc": + m.answer(promptReply{}) + return nil + case "enter": + m.answer(promptReply{text: m.modal.input.Value(), ok: true}) + return nil + } + + if m.modal.msg.confirm { return nil } + + var cmd tea.Cmd + m.modal.input, cmd = m.modal.input.Update(msg) + return cmd +} + +var modalBox = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color("13")).Padding(1, 2) + +// modalView draws the modal in the middle of screen, which is the rest of +// the view. +func (m *Model) modalView(screen string) string { + width := max(min(m.width-4, 72), 20) + + help := "enter send · esc cancel" + if m.modal.msg.confirm { help = "enter continue · esc not now" } + + body := bold.Render(m.modal.msg.title) + "\n\n" + m.modal.msg.label + if !m.modal.msg.confirm { + m.modal.input.SetWidth(width - 10) + body += "\n\n" + m.modal.input.View() + } + body += "\n\n" + faint.Render(help) + + box := modalBox.Width(width).Render(body) + x := max((m.width-lipgloss.Width(box))/2, 0) + y := max((m.height-lipgloss.Height(box))/2, 0) + + layers := lipgloss.NewCompositor(lipgloss.NewLayer(screen), lipgloss.NewLayer(box).X(x).Y(y).Z(1)) + + return lipgloss.NewCanvas(m.width, m.height).Compose(layers).Render() +} diff --git a/internal/tui/prompt_test.go b/internal/tui/prompt_test.go new file mode 100644 index 0000000..b255056 --- /dev/null +++ b/internal/tui/prompt_test.go @@ -0,0 +1,78 @@ +package tui + +import ( + "log/slog" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + + "git.security-command.org/Overlord/dibs/internal/watch" +) + +type idle struct{} + +func (idle) Statuses() []watch.Status { return nil } +func (idle) Pause(string, bool) bool { return false } +func (idle) PauseAll(bool) {} +func (idle) CheckNow(string) bool { return false } +func (idle) Reload() ([]string, error) { return nil, nil } +func (idle) Solve(string) error { return nil } + +func newTestModel() *Model { + m := New(idle{}, "/tmp/dibs.toml", NewLogHandler(slog.LevelInfo)) + m.Update(tea.WindowSizeMsg{Width: 100, Height: 30}) + + return m +} + +func ask(m *Model, msg promptMsg) <-chan promptReply { + reply := make(chan promptReply, 1) + msg.reply = reply + m.Update(msg) + + return reply +} + +func typeText(m *Model, s string) { + for _, r := range s { m.Update(tea.KeyPressMsg{Code: r, Text: string(r)}) } +} + +func TestModalPrompt(t *testing.T) { + m := newTestModel() + reply := ask(m, promptMsg{id: 1, title: "amazon · www.amazon.de", label: "One-time code", secret: true}) + + typeText(m, "123456") + + view := m.View().Content + if !strings.Contains(view, "One-time code") { t.Error("the modal is not shown") } + if strings.Contains(view, "123456") { t.Error("the secret shows as it is typed") } + + m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + + if r := <-reply; !r.ok || r.text != "123456" { t.Errorf("reply %+v", r) } + if m.modal != nil { t.Error("the modal is still open") } +} + +func TestModalCancelAndConfirm(t *testing.T) { + m := newTestModel() + + // Keys go to the modal, so q is typed instead of quitting. + reply := ask(m, promptMsg{id: 1, title: "t", label: "code"}) + typeText(m, "q") + if got := m.modal.input.Value(); got != "q" { t.Errorf("typed %q", got) } + + m.Update(tea.KeyPressMsg{Code: tea.KeyEscape}) + if r := <-reply; r.ok { t.Errorf("esc replied %+v", r) } + + reply = ask(m, promptMsg{id: 2, title: "Session mode for amazon", label: "Automated logins can lock the account.", confirm: true}) + m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + if r := <-reply; !r.ok { t.Error("enter did not accept the warning") } + + // A question that timed out closes its modal, but no newer one. + ask(m, promptMsg{id: 3, title: "t", label: "code"}) + m.Update(closePromptMsg{id: 2}) + if m.modal == nil { t.Error("an old timeout closed the modal") } + m.Update(closePromptMsg{id: 3}) + if m.modal != nil { t.Error("the timed-out modal is still open") } +} diff --git a/internal/tui/view.go b/internal/tui/view.go index ba7ea1c..adbe7a4 100644 --- a/internal/tui/view.go +++ b/internal/tui/view.go @@ -82,6 +82,11 @@ func (m *Model) View() tea.View { b.WriteString(m.statusBar() + "\n") b.WriteString(fit(faint.Render(m.help()), m.width)) + if m.modal != nil { + v.SetContent(m.modalView(b.String())) + return v + } + v.SetContent(b.String()) return v } @@ -196,7 +201,7 @@ func (m *Model) logLines() []string { } msg := l.Msg - if msg == "ALERT" { msg = green.Render(msg) } + if msg == "ALERT" || msg == "IN CART" { msg = green.Render(msg) } out[i] = faint.Render(l.Time.Format(time.TimeOnly)) + " " + level + " " + msg + " " + faint.Render(l.Attrs) } diff --git a/internal/watch/watch.go b/internal/watch/watch.go index 07503c5..c4f242f 100644 --- a/internal/watch/watch.go +++ b/internal/watch/watch.go @@ -3,7 +3,6 @@ package watch import ( "context" - "errors" "fmt" "math/rand/v2" "net/url" @@ -263,7 +262,7 @@ func (s *Scheduler) check(ctx context.Context, t *target) { resp, err := s.fetcher.Get(ctx, fetchURL) if ctx.Err() != nil { return } - backoff := RecordOutcome(s.limiter, t.host, resp, err) + backoff := fetch.RecordOutcome(s.limiter, t.host, resp, err) var report *plugin.Report if err == nil { report, err = plugin.Evaluate(ctx, p, rawURL, resp) } @@ -286,23 +285,6 @@ func (s *Scheduler) check(ctx context.Context, t *target) { } } -// RecordOutcome tells the limiter how a request to host went: bot checks, -// refusals and failed requests back the host off, anything else clears its -// backoff. It returns the backoff, or 0. -func RecordOutcome(l *ratelimit.Limiter, host string, resp *fetch.Response, err error) time.Duration { - switch { - case errors.Is(err, context.Canceled): - return 0 - case err != nil: - return l.Failure(host) - case resp.Verdict == fetch.Challenge || resp.Verdict == fetch.NeedsHuman || resp.Verdict == fetch.Blocked || resp.Verdict == fetch.HTTPError: - return l.Failure(host) - default: - l.Success(host) - return 0 - } -} - // Pause pauses or resumes the item called name. It reports whether there is // such an item. func (s *Scheduler) Pause(name string, paused bool) bool { diff --git a/testdata/session/shop.lua b/testdata/session/shop.lua new file mode 100644 index 0000000..92f2324 --- /dev/null +++ b/testdata/session/shop.lua @@ -0,0 +1,43 @@ +-- A plugin for the session tests. Its add_to_cart reads what to do from the +-- URL's path. +return { + name = "shop", + + session_warning = "Automated logins can lock the account.", + + parse = function(doc, url) + return { available = true } + end, + + login = function(ctx, account) + local page = ctx:get(account.site .. "signin") + local code = ctx:prompt("code for " .. account.username, true) + + page = ctx:post(account.site .. "signin", { + form = { user = account.username, password = account.password, code = code }, + referer = page.url, + }) + + if page.doc:text("#result") ~= "welcome" then error("refused: " .. tostring(page.doc:text("#result")), 0) end + if ctx:cookies().session ~= "yes" then error("no session cookie", 0) end + end, + + add_to_cart = function(ctx, url) + local what = url:match("/(%a+)$") + local site = ctx.account.site + + if ctx.account.password then error("ctx.account has the password", 0) end + + if what == "signedout" then return false end + if what == "nonsense" then return "yes" end + + if what == "click" then + local page = ctx:click(site .. "item", "#add") + return page.headers["x-cart"] == "1", site .. "cart" + end + + local page = ctx:post(site .. "cart", { form = { id = "X", quantity = 1 }, headers = { ["X-Test"] = "yes" } }) + + return page.status == 200 and page.headers["x-cart"] == "1", site .. "cart" + end, +}