336 lines
9.9 KiB
Go
336 lines
9.9 KiB
Go
// 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("no cookies from Chrome 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
|
|
}
|