Files
dibs/internal/notify/notify.go
T
OverlordandClaude Bot 15a34e1f84 Add session mode: signing in and adding to the cart.
With cart_mode = "session", dibs signs in to the shop's account and puts
an item in the cart when it fires. The account's cookies are kept apart
from the watcher's and stored encrypted, with the key in the OS keyring.
Without a keyring, they're stored in a file only you can read.

An alert now goes out right away, without a cart link, and a second one
follows once the item is in the cart. If adding fails, the second alert
carries the cart link instead.

Amazon only accepts additions its page scripts have seen, so plugins can
now press a button in headless Chrome with ctx:click.

The TUI asks for one-time codes and shows the plugin's warning about
account locks in a modal. 'dibs login' signs in from a terminal, or
with --browser in a Chrome window, and 'dibs logout' deletes the cookies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:26:26 +02:00

346 lines
9.4 KiB
Go

// Package notify delivers alerts to webhooks and the desktop.
package notify
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/gen2brain/beeep"
"git.security-command.org/Overlord/dibs/internal/alert"
"git.security-command.org/Overlord/dibs/internal/config"
)
const (
// retries follow the first attempt, with waits of 1s, 2s and 4s.
retries = 3
retryBase = 1 * time.Second
maxRetryAfter = 30 * time.Second
requestTimeout = 10 * time.Second
)
// Notifier sends alerts to every configured channel.
type Notifier struct {
webhooks []config.Webhook
desktop bool
userAgent string
client *http.Client
wait func(ctx context.Context, d time.Duration) error
showToast func(title, message string) error
}
// New returns a notifier for the [notify] config. Webhook requests are not
// rate limited: they go to the user's own services, and only when an item
// fires.
func New(cfg config.Notify, userAgent string) *Notifier {
beeep.AppName = "dibs"
return &Notifier{
webhooks: cfg.Webhooks,
desktop: cfg.Desktop,
userAgent: userAgent,
client: &http.Client{Timeout: requestTimeout},
wait: sleep,
showToast: func(title, message string) error { return beeep.Notify(title, message, "") },
}
}
// Send delivers a to every webhook and the desktop at once and returns when
// all are done. The error joins one error per failed channel.
func (n *Notifier) Send(ctx context.Context, a alert.Alert) error {
errs := make([]error, len(n.webhooks)+1)
var wg sync.WaitGroup
for i, wh := range n.webhooks {
wg.Go(func() {
if err := n.webhook(ctx, wh, a); err != nil { errs[i] = fmt.Errorf("webhook %d (%s, %s): %w", i, wh.Format, hostOf(wh.URL), err) }
})
}
if n.desktop {
wg.Go(func() {
title, message := desktopText(a)
if err := n.showToast(title, message); err != nil { errs[len(n.webhooks)] = fmt.Errorf("desktop notification: %w", err) }
})
}
wg.Wait()
return errors.Join(errs...)
}
// Notice shows a desktop notification that is not an alert, such as a
// request to solve a captcha. It does nothing when desktop notifications
// are off.
func (n *Notifier) Notice(title, message string) error {
if !n.desktop { return nil }
return n.showToast(title, message)
}
// Channels says where alerts go, for the startup log.
func (n *Notifier) Channels() []string {
var out []string
for _, wh := range n.webhooks { out = append(out, wh.Format+" "+hostOf(wh.URL)) }
if n.desktop { out = append(out, "desktop") }
return out
}
// hostOf names a webhook in logs and errors. Its full URL often contains a
// secret token.
func hostOf(raw string) string {
if u, err := url.Parse(raw); err == nil { return u.Host }
return "invalid URL"
}
func (n *Notifier) webhook(ctx context.Context, wh config.Webhook, a alert.Alert) error {
var (
body []byte
header = http.Header{}
err error
)
switch wh.Format {
case config.FormatDiscord:
body, err = json.Marshal(discordPayload(a))
header.Set("Content-Type", "application/json")
case config.FormatNtfy:
body = []byte(ntfyMessage(a))
ntfyHeaders(header, a)
default:
body, err = json.Marshal(NewPayload(a))
header.Set("Content-Type", "application/json")
}
if err != nil { return err }
header.Set("User-Agent", n.userAgent)
return n.post(ctx, wh.URL, header, body)
}
// post sends body, retrying network errors, 429 and 5xx answers.
func (n *Notifier) post(ctx context.Context, rawURL string, header http.Header, body []byte) error {
var last error
for attempt := 0; ; attempt++ {
retryAfter, err := n.try(ctx, rawURL, header, body)
if err == nil { return nil }
last = err
if retryAfter < 0 || attempt == retries || ctx.Err() != nil { return last }
d := retryBase << attempt
if retryAfter > d { d = min(retryAfter, maxRetryAfter) }
if err := n.wait(ctx, d); err != nil { return last }
}
}
// try makes one request. A failed request returns how long the server asked
// to wait before the next one, 0 if it did not say, or -1 if retrying is
// pointless.
func (n *Notifier) try(ctx context.Context, rawURL string, header http.Header, body []byte) (time.Duration, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, bytes.NewReader(body))
if err != nil { return -1, err }
req.Header = header.Clone()
resp, err := n.client.Do(req)
if err != nil { return 0, err }
defer func() { _ = resp.Body.Close() }()
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
if resp.StatusCode < 300 { return 0, nil }
err = fmt.Errorf("%s", resp.Status)
if text := strings.TrimSpace(string(msg)); text != "" { err = fmt.Errorf("%s: %s", resp.Status, text) }
switch {
case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500:
secs, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
return time.Duration(max(secs, 0)) * time.Second, err
default:
return -1, err
}
}
func sleep(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
// 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 {
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
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
}
// summary is the price and seller line, with the price drop if there is one.
func summary(a alert.Alert) string {
s := a.PriceText() + ", " + a.SellerText()
if a.PreviousPrice != nil { s += ", down from " + alert.Money(*a.PreviousPrice, a.PreviousCurrency) }
return s
}
// 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 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 := 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")
}
func ntfyHeaders(h http.Header, a alert.Alert) {
// HTTP headers are ASCII. ntfy decodes RFC 2047 encoded words, which
// carry titles such as "Édition Limitée".
h.Set("Title", mime.BEncoding.Encode("utf-8", headline(a)))
h.Set("Click", link(a))
h.Set("Priority", "high")
h.Set("Tags", "shopping_cart")
}
type discordMessage struct {
Username string `json:"username"`
Content string `json:"content"`
Embeds []discordEmbed `json:"embeds"`
AllowedMentions map[string][]string `json:"allowed_mentions"`
}
type discordEmbed struct {
Title string `json:"title"`
URL string `json:"url"`
Description string `json:"description,omitempty"`
Color int `json:"color"`
Fields []discordField `json:"fields"`
Timestamp string `json:"timestamp"`
}
type discordField struct {
Name string `json:"name"`
Value string `json:"value"`
Inline bool `json:"inline"`
}
func discordPayload(a alert.Alert) discordMessage {
title := a.Title
if title == "" { title = a.Item }
price := a.PriceText()
if a.PreviousPrice != nil { price += ", down from " + alert.Money(*a.PreviousPrice, a.PreviousCurrency) }
desc := "[Product page](" + a.URL + ")"
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",
// The angle brackets keep Discord from adding a preview of the link.
Content: "**" + headline(a) + "** <" + link(a) + ">",
Embeds: []discordEmbed{{
Title: truncate(title, 256),
URL: link(a),
Description: desc,
Color: color,
Fields: fields,
Timestamp: a.Time.UTC().Format(time.RFC3339),
}},
// Page titles never ping anyone.
AllowedMentions: map[string][]string{"parse": {}},
}
}
func truncate(s string, n int) string {
if utf8.RuneCountInString(s) <= n { return s }
r := []rune(s)
return string(r[:n-1]) + "…"
}