This commit is contained in:
commit
f9a6f20afb
79 files changed
+12648
-13
No files matched your search
@@ -0,0 +1,35 @@
|
|||||||
|
# Builds dibs for every v* tag and publishes it as a release with the binaries for Linux
|
||||||
|
# (amd64), Windows (amd64) and macOS (arm64) attached (the Makefile's TARGETS), so
|
||||||
|
# .../releases/download/latest/dibs-<os>-<arch> always serves the newest one.
|
||||||
|
# Pre-release tags (containing "-") and tags on commits that are not on master are built and
|
||||||
|
# tested but not released (see ci/release.sh).
|
||||||
|
# Uses the repository secret RELEASE_TOKEN (a token with "repository: Read and Write") when it
|
||||||
|
# exists, else the job's automatic token.
|
||||||
|
name: release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
|
with:
|
||||||
|
# release.sh reads the v* tag on HEAD and checks that HEAD is on origin/master
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
|
||||||
|
# The build runs without the token; only the publish step gets it.
|
||||||
|
- name: Build
|
||||||
|
run: ci/release.sh build
|
||||||
|
|
||||||
|
- name: Publish
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITEA_TOKEN }}
|
||||||
|
run: ci/release.sh publish
|
||||||
+17
-13
@@ -1,27 +1,31 @@
|
|||||||
# ---> Go
|
.*
|
||||||
# If you prefer the allow list template instead of the deny list, see community template:
|
!.git*
|
||||||
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
!.dockerignore
|
||||||
#
|
!.golangci.yml
|
||||||
# Binaries for programs and plugins
|
|
||||||
|
*.md
|
||||||
|
!README.md
|
||||||
|
|
||||||
|
|
||||||
*.exe
|
*.exe
|
||||||
*.exe~
|
*.exe~
|
||||||
*.dll
|
*.dll
|
||||||
*.so
|
*.so
|
||||||
*.dylib
|
*.dylib
|
||||||
|
|
||||||
# Test binary, built with `go test -c`
|
|
||||||
*.test
|
*.test
|
||||||
|
|
||||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
|
||||||
*.out
|
*.out
|
||||||
|
|
||||||
# Dependency directories (remove the comment below to include it)
|
|
||||||
# vendor/
|
|
||||||
|
|
||||||
# Go workspace file
|
|
||||||
go.work
|
go.work
|
||||||
go.work.sum
|
go.work.sum
|
||||||
|
|
||||||
# env file
|
|
||||||
.env
|
.env
|
||||||
|
|
||||||
|
# Real shop pages fetched by 'dibs fixtures'.
|
||||||
|
testdata/*/pages/
|
||||||
|
|
||||||
|
# Build output.
|
||||||
|
/dist/
|
||||||
|
/dibs
|
||||||
|
/dibs.exe
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
version: "2"
|
||||||
|
|
||||||
|
linters:
|
||||||
|
default: standard
|
||||||
|
|
||||||
|
formatters:
|
||||||
|
enable: []
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# make build builds dibs for this machine
|
||||||
|
# make test runs the tests; GOTESTFLAGS=-short skips those that start Chrome
|
||||||
|
# make lint runs golangci-lint, built from source at a pinned version
|
||||||
|
# make release cross-compiles TARGETS into dist/, with SHA256SUMS
|
||||||
|
#
|
||||||
|
# VERSION defaults to `git describe`, such as v0.3.0 or v0.3.0-4-gabc1234-dirty.
|
||||||
|
|
||||||
|
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
|
||||||
|
TARGETS ?= linux/amd64 windows/amd64 darwin/arm64
|
||||||
|
GOTESTFLAGS ?=
|
||||||
|
|
||||||
|
GOLANGCI_LINT ?= go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0
|
||||||
|
|
||||||
|
# File names carry the version without its "v", like dibs-0.3.0-linux-amd64.
|
||||||
|
FILE_VERSION := $(patsubst v%,%,$(VERSION))
|
||||||
|
LDFLAGS := -s -w -X main.version=$(VERSION)
|
||||||
|
|
||||||
|
.PHONY: build test lint release clean
|
||||||
|
|
||||||
|
build:
|
||||||
|
CGO_ENABLED=0 go build -trimpath -ldflags '$(LDFLAGS)' -o dibs$(shell go env GOEXE) ./cmd/dibs
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test $(GOTESTFLAGS) ./...
|
||||||
|
|
||||||
|
lint:
|
||||||
|
$(GOLANGCI_LINT) run ./...
|
||||||
|
|
||||||
|
release:
|
||||||
|
rm -rf dist
|
||||||
|
mkdir -p dist
|
||||||
|
set -e; for target in $(TARGETS); do \
|
||||||
|
os=$${target%/*}; arch=$${target#*/}; ext=; \
|
||||||
|
if [ "$$os" = windows ]; then ext=.exe; fi; \
|
||||||
|
out=dist/dibs-$(FILE_VERSION)-$$os-$$arch$$ext; \
|
||||||
|
echo "$$out"; \
|
||||||
|
CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -trimpath -ldflags '$(LDFLAGS)' -o "$$out" ./cmd/dibs; \
|
||||||
|
done
|
||||||
|
cd dist && sha256sum dibs-* > SHA256SUMS
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -rf dist dibs dibs.exe
|
||||||
Executable
+214
@@ -0,0 +1,214 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# Builds dibs for the v* git tag on HEAD and publishes the binaries as a Gitea release. The
|
||||||
|
# targets are the Makefile's TARGETS. Each binary is attached twice: as
|
||||||
|
# dibs-<version>-<os>-<arch>, and as dibs-<os>-<arch>, the stable name behind
|
||||||
|
# <server>/<owner>/<repo>/releases/download/latest/dibs-<os>-<arch>. SHA256SUMS covers the
|
||||||
|
# versioned names.
|
||||||
|
#
|
||||||
|
# A pre-release tag (containing "-", e.g. v0.2.0-rc.1), or a tag on a commit that is not on
|
||||||
|
# master, is built and tested but not released.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# ci/release.sh build runs the tests and the linter, and builds the binaries into dist/
|
||||||
|
# ci/release.sh publish creates the release (or reuses the tag's release) and uploads dist/
|
||||||
|
#
|
||||||
|
# Environment:
|
||||||
|
# GITEA_TOKEN token with write access to the repository's releases (publish)
|
||||||
|
# GITHUB_API_URL Gitea API, e.g. https://git.security-command.org/api/v1 (publish; set by Gitea Actions)
|
||||||
|
# GITHUB_REPOSITORY owner/repo (publish; set by Gitea Actions)
|
||||||
|
|
||||||
|
set -o errexit
|
||||||
|
set -o nounset
|
||||||
|
set -o pipefail
|
||||||
|
shopt -s inherit_errexit
|
||||||
|
|
||||||
|
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
readonly REPO_ROOT
|
||||||
|
|
||||||
|
readonly RELEASE_BRANCH="master"
|
||||||
|
|
||||||
|
# Seconds publish waits for HEAD to arrive on the release branch. A push can deliver the tag
|
||||||
|
# before the branch (git-flow pushes both), so the checkout may hold the branch from before.
|
||||||
|
readonly RELEASE_BRANCH_WAIT=60
|
||||||
|
readonly RELEASE_BRANCH_POLL=10
|
||||||
|
|
||||||
|
readonly DIST="${REPO_ROOT}/dist"
|
||||||
|
|
||||||
|
log() {
|
||||||
|
echo "[release] $*" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
log "$*"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Whether HEAD is on the release branch. Fetches the branch again rather than trusting the
|
||||||
|
# checkout, and waits up to RELEASE_BRANCH_WAIT seconds for it to arrive.
|
||||||
|
on_release_branch() {
|
||||||
|
local waited=0
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
git -C "${REPO_ROOT}" fetch --quiet origin "+refs/heads/${RELEASE_BRANCH}:refs/remotes/origin/${RELEASE_BRANCH}" \
|
||||||
|
|| log "Cannot fetch ${RELEASE_BRANCH}; checking against the one fetched before"
|
||||||
|
|
||||||
|
if git -C "${REPO_ROOT}" merge-base --is-ancestor HEAD "origin/${RELEASE_BRANCH}" 2> /dev/null; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if (( waited >= RELEASE_BRANCH_WAIT )); then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "HEAD is not on ${RELEASE_BRANCH} (yet); fetching it again in ${RELEASE_BRANCH_POLL} seconds"
|
||||||
|
sleep "${RELEASE_BRANCH_POLL}"
|
||||||
|
waited=$(( waited + RELEASE_BRANCH_POLL ))
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
# Prints the v* tag on HEAD, or nothing.
|
||||||
|
release_tag() {
|
||||||
|
git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null || true
|
||||||
|
}
|
||||||
|
|
||||||
|
build() {
|
||||||
|
local tag="$1"
|
||||||
|
|
||||||
|
# The tests that start Chrome are skipped; a runner rarely has one installed.
|
||||||
|
log "Testing"
|
||||||
|
make -C "${REPO_ROOT}" test GOTESTFLAGS=-short
|
||||||
|
|
||||||
|
log "Linting"
|
||||||
|
make -C "${REPO_ROOT}" lint
|
||||||
|
|
||||||
|
log "Building ${tag}"
|
||||||
|
make -C "${REPO_ROOT}" release VERSION="${tag}"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Calls the Gitea API; prints the response body. Extra arguments go to curl.
|
||||||
|
api() {
|
||||||
|
local method="$1"
|
||||||
|
local path="$2"
|
||||||
|
shift 2
|
||||||
|
|
||||||
|
curl --fail --silent --show-error \
|
||||||
|
--request "${method}" \
|
||||||
|
--header "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
--header "Accept: application/json" \
|
||||||
|
"$@" \
|
||||||
|
"${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}${path}"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Prints the id of the tag's release, created when it does not exist yet.
|
||||||
|
release_id() {
|
||||||
|
local tag="$1"
|
||||||
|
local status
|
||||||
|
local body
|
||||||
|
|
||||||
|
# curl exits non-zero when the server cannot be reached; the status is then 000.
|
||||||
|
status="$(curl --silent --output /dev/null --write-out '%{http_code}' \
|
||||||
|
--header "Authorization: token ${GITEA_TOKEN}" \
|
||||||
|
"${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases/tags/${tag}" || true)"
|
||||||
|
|
||||||
|
case "${status}" in
|
||||||
|
200)
|
||||||
|
log "Release '${tag}' exists; replacing its files"
|
||||||
|
api GET "/releases/tags/${tag}" | jq --raw-output '.id'
|
||||||
|
return
|
||||||
|
;;
|
||||||
|
404)
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
fail "Cannot read the releases of '${GITHUB_REPOSITORY}' (HTTP ${status}); is GITEA_TOKEN valid for it?"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
body="$(jq --null-input \
|
||||||
|
--arg tag "${tag}" \
|
||||||
|
--arg name "Release ${tag} - Stable, Automated" \
|
||||||
|
--arg body "$(date --utc +%Y-%m-%d)"$'\n'"$(git -C "${REPO_ROOT}" rev-parse HEAD)" \
|
||||||
|
'{tag_name: $tag, name: $name, body: $body, draft: false, prerelease: false}')"
|
||||||
|
|
||||||
|
log "Creating release '${tag}'"
|
||||||
|
api POST "/releases" --header "Content-Type: application/json" --data "${body}" | jq --raw-output '.id'
|
||||||
|
}
|
||||||
|
|
||||||
|
# Uploads ${file} as ${name}, replacing an attached file of that name.
|
||||||
|
upload() {
|
||||||
|
local id="$1"
|
||||||
|
local file="$2"
|
||||||
|
local name="$3"
|
||||||
|
local existing
|
||||||
|
|
||||||
|
existing="$(api GET "/releases/${id}/assets" | jq --raw-output --arg name "${name}" '.[] | select(.name == $name) | .id')"
|
||||||
|
if [[ -n "${existing}" ]]; then
|
||||||
|
api DELETE "/releases/${id}/assets/${existing}" > /dev/null
|
||||||
|
fi
|
||||||
|
|
||||||
|
api POST "/releases/${id}/assets?name=${name}" --form "attachment=@${file}" > /dev/null
|
||||||
|
log "Attached '${name}'"
|
||||||
|
}
|
||||||
|
|
||||||
|
publish() {
|
||||||
|
local tag="$1"
|
||||||
|
local version="${tag#v}"
|
||||||
|
local id
|
||||||
|
local file
|
||||||
|
local name
|
||||||
|
|
||||||
|
if [[ "${version}" == *-* ]]; then
|
||||||
|
log "${tag} is a pre-release tag; nothing is released."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! on_release_branch; then
|
||||||
|
log "${tag} is not on ${RELEASE_BRANCH}; nothing is released."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
: "${GITEA_TOKEN:?GITEA_TOKEN is not set}"
|
||||||
|
: "${GITHUB_API_URL:?GITHUB_API_URL is not set}"
|
||||||
|
: "${GITHUB_REPOSITORY:?GITHUB_REPOSITORY is not set}"
|
||||||
|
|
||||||
|
[[ -f "${DIST}/SHA256SUMS" ]] || fail "'${DIST}' has no release build; run 'ci/release.sh build' first."
|
||||||
|
|
||||||
|
id="$(release_id "${tag}")"
|
||||||
|
|
||||||
|
for file in "${DIST}/dibs-${version}-"*; do
|
||||||
|
[[ -f "${file}" ]] || fail "'${DIST}' has no binaries for ${version}; run 'ci/release.sh build' first."
|
||||||
|
|
||||||
|
name="$(basename "${file}")"
|
||||||
|
upload "${id}" "${file}" "${name}"
|
||||||
|
upload "${id}" "${file}" "dibs-${name#dibs-"${version}"-}"
|
||||||
|
done
|
||||||
|
|
||||||
|
upload "${id}" "${DIST}/SHA256SUMS" "SHA256SUMS"
|
||||||
|
|
||||||
|
log "Released ${tag}: ${GITHUB_SERVER_URL:-}/${GITHUB_REPOSITORY}/releases/tag/${tag}"
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
local step="${1:-}"
|
||||||
|
local tag
|
||||||
|
|
||||||
|
tag="$(release_tag)"
|
||||||
|
if [[ -z "${tag}" ]]; then
|
||||||
|
fail "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to release."
|
||||||
|
fi
|
||||||
|
|
||||||
|
case "${step}" in
|
||||||
|
build)
|
||||||
|
build "${tag}"
|
||||||
|
;;
|
||||||
|
publish)
|
||||||
|
publish "${tag}"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
log "Usage: ci/release.sh build|publish"
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runCheck implements `dibs check [--shop NAME] <url>`: one fetch and parse,
|
||||||
|
// printed as JSON.
|
||||||
|
func runCheck(args []string, stdout, stderr io.Writer) int {
|
||||||
|
flags, configPath := newFlagSet("dibs check", stderr)
|
||||||
|
shop := flags.String("shop", "", "plugin to use (default: the first whose matches() accepts the URL)")
|
||||||
|
useChrome := flags.Bool("chrome", false, "fetch with headless Chrome instead of tls-client")
|
||||||
|
|
||||||
|
pos, ok := parseArgs(flags, args)
|
||||||
|
if !ok { return 2 }
|
||||||
|
if len(pos) != 1 {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs check: expected one URL\n\n%s", usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, ok := loadOptionalConfig(*configPath, stderr)
|
||||||
|
if !ok { return 1 }
|
||||||
|
|
||||||
|
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, "check", err) }
|
||||||
|
defer host.Close()
|
||||||
|
|
||||||
|
url := pos[0]
|
||||||
|
|
||||||
|
p, err := pickPlugin(ctx, host, *shop, url)
|
||||||
|
if err != nil { return fail(stderr, "check", err) }
|
||||||
|
|
||||||
|
fetchURL, err := p.Normalize(ctx, url)
|
||||||
|
if err != nil { return fail(stderr, "check", err) }
|
||||||
|
|
||||||
|
e, err := openEnv(logger)
|
||||||
|
if err != nil { return fail(stderr, "check", err) }
|
||||||
|
|
||||||
|
get := e.pipeline.Get
|
||||||
|
if *useChrome { get = e.chromeGet }
|
||||||
|
|
||||||
|
resp, err := e.fetch(ctx, fetchURL, get, logger)
|
||||||
|
if err != nil { return fail(stderr, "check", err) }
|
||||||
|
|
||||||
|
report, err := plugin.Evaluate(ctx, p, url, resp)
|
||||||
|
printJSON(stdout, report)
|
||||||
|
if err != nil { return fail(stderr, "check", err) }
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// runPlugin implements `dibs plugin test [--status CODE] <file.lua>
|
||||||
|
// <fixture.html> [url]`: it runs a plugin on a saved page.
|
||||||
|
func runPlugin(args []string, stdout, stderr io.Writer) int {
|
||||||
|
if len(args) == 0 || args[0] != "test" {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs plugin: expected \"test\"\n\n%s", usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
flags, configPath := newFlagSet("dibs plugin test", stderr)
|
||||||
|
status := flags.Int("status", 200, "HTTP status the page was served with")
|
||||||
|
|
||||||
|
pos, ok := parseArgs(flags, args[1:])
|
||||||
|
if !ok { return 2 }
|
||||||
|
if len(pos) < 2 || len(pos) > 3 {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs plugin test: expected <file.lua> <fixture.html> [url]\n\n%s", usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, ok := loadOptionalConfig(*configPath, stderr)
|
||||||
|
if !ok { return 1 }
|
||||||
|
|
||||||
|
code, err := os.ReadFile(pos[0])
|
||||||
|
if err != nil { return fail(stderr, "plugin test", err) }
|
||||||
|
|
||||||
|
page, err := os.ReadFile(pos[1])
|
||||||
|
if err != nil { return fail(stderr, "plugin test", err) }
|
||||||
|
|
||||||
|
url := "https://example.invalid/"
|
||||||
|
if len(pos) == 3 { url = pos[2] }
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
logger := slog.New(slog.NewTextHandler(stderr, nil))
|
||||||
|
|
||||||
|
p, err := plugin.Load("", pos[0], code, limits(cfg), logger)
|
||||||
|
if err != nil { return fail(stderr, "plugin test", err) }
|
||||||
|
defer p.Close()
|
||||||
|
|
||||||
|
fetchURL, err := p.Normalize(ctx, url)
|
||||||
|
if err != nil { return fail(stderr, "plugin test", err) }
|
||||||
|
|
||||||
|
report, err := plugin.Evaluate(ctx, p, url, fetch.NewResponse(fetchURL, fetchURL, *status, nil, page))
|
||||||
|
printJSON(stdout, report)
|
||||||
|
if err != nil { return fail(stderr, "plugin test", err) }
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func newHost(cfg *config.Config, logger *slog.Logger) (*plugin.Host, error) {
|
||||||
|
var user map[string]string
|
||||||
|
if cfg != nil { user = cfg.Plugins }
|
||||||
|
|
||||||
|
return plugin.NewHost(user, limits(cfg), logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func limits(cfg *config.Config) plugin.Limits {
|
||||||
|
if cfg == nil { return plugin.DefaultLimits() }
|
||||||
|
|
||||||
|
return plugin.LimitsFrom(cfg.Sandbox)
|
||||||
|
}
|
||||||
|
|
||||||
|
func pickPlugin(ctx context.Context, host *plugin.Host, shop, url string) (*plugin.Plugin, error) {
|
||||||
|
if shop == "" {
|
||||||
|
p, err := host.ForURL(ctx, url)
|
||||||
|
if errors.Is(err, plugin.ErrNoPlugin) { return nil, fmt.Errorf("%w; pick one with --shop", err) }
|
||||||
|
|
||||||
|
return p, err
|
||||||
|
}
|
||||||
|
|
||||||
|
p, ok := host.Plugin(shop)
|
||||||
|
if !ok { return nil, fmt.Errorf("no plugin named %q (built-in: %v)", shop, plugin.Builtins()) }
|
||||||
|
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func printJSON(w io.Writer, v any) {
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
_ = enc.Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func fail(stderr io.Writer, cmd string, err error) int {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs %s: %v\n", cmd, err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/url"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/chrome"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/state"
|
||||||
|
)
|
||||||
|
|
||||||
|
// env is what every command that talks to shops shares with every other
|
||||||
|
// dibs process: the state file behind the rate limits, and the cookies.
|
||||||
|
type env struct {
|
||||||
|
dir string
|
||||||
|
store *state.Store
|
||||||
|
limiter *ratelimit.Limiter
|
||||||
|
jar *fetch.Jar
|
||||||
|
client *fetch.Client
|
||||||
|
chrome *chrome.Chrome
|
||||||
|
pipeline *chrome.Pipeline
|
||||||
|
}
|
||||||
|
|
||||||
|
func openEnv(logger *slog.Logger) (*env, error) {
|
||||||
|
dir, err := state.Dir()
|
||||||
|
if err != nil { return nil, fmt.Errorf("no config dir for the state file: %w", err) }
|
||||||
|
|
||||||
|
store := state.Open(dir)
|
||||||
|
limiter := ratelimit.New(store)
|
||||||
|
|
||||||
|
jar := fetch.NewJar()
|
||||||
|
if err := jar.Load(filepath.Join(dir, "cookies.json")); err != nil { logger.Warn("ignoring saved cookies", "err", err) }
|
||||||
|
|
||||||
|
client, err := fetch.New(fetch.Options{Limiter: limiter, Jar: jar})
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
browser := chrome.New(fetch.DefaultBrowser(), jar, logger)
|
||||||
|
|
||||||
|
return &env{
|
||||||
|
dir: dir,
|
||||||
|
store: store,
|
||||||
|
limiter: limiter,
|
||||||
|
jar: jar,
|
||||||
|
client: client,
|
||||||
|
chrome: browser,
|
||||||
|
pipeline: &chrome.Pipeline{Client: client, Chrome: browser, Limiter: limiter, Logger: logger},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// save writes the cookies, and reports trouble with the state file.
|
||||||
|
func (e *env) save(logger *slog.Logger) {
|
||||||
|
if err := e.jar.Save(filepath.Join(e.dir, "cookies.json")); err != nil { logger.Warn("saving cookies failed", "err", err) }
|
||||||
|
if err := e.store.Err(); err != nil { logger.Warn("state file unusable, rate limits only hold within this process", "err", err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// explainWait says why the next check of fetchURL will take a while, if it
|
||||||
|
// will: it was checked less than a minute ago, by this or another dibs
|
||||||
|
// process, or its host is busy or backed off.
|
||||||
|
func (e *env) explainWait(fetchURL string, logger *slog.Logger) {
|
||||||
|
if wait := time.Until(e.limiter.URLReady(fetchURL)); wait > time.Second {
|
||||||
|
logger.Info("URL was checked recently, waiting", "url", fetchURL, "wait", wait.Round(time.Second))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
u, err := url.Parse(fetchURL)
|
||||||
|
if err != nil { return }
|
||||||
|
|
||||||
|
if wait := e.limiter.Delay(u.Hostname()); wait > time.Second {
|
||||||
|
logger.Info("waiting for the host's rate limit", "host", u.Hostname(), "wait", wait.Round(time.Second))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// getter is one way to fetch a page: env.pipeline.Get, env.client.Get or
|
||||||
|
// env.chromeGet.
|
||||||
|
type getter func(ctx context.Context, url string) (*fetch.Response, error)
|
||||||
|
|
||||||
|
// fetch makes a single check of fetchURL with get that counts like a
|
||||||
|
// scheduled one: it waits for its turn, and the outcome is recorded for
|
||||||
|
// every dibs process.
|
||||||
|
func (e *env) fetch(ctx context.Context, fetchURL string, get getter, logger *slog.Logger) (*fetch.Response, error) {
|
||||||
|
e.explainWait(fetchURL, logger)
|
||||||
|
|
||||||
|
resp, err := get(ctx, fetchURL)
|
||||||
|
if ctx.Err() == nil {
|
||||||
|
if u, perr := url.Parse(fetchURL); perr == nil {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// chromeGet fetches with headless Chrome only, after the rate limits allow
|
||||||
|
// it.
|
||||||
|
func (e *env) chromeGet(ctx context.Context, fetchURL string) (*fetch.Response, error) {
|
||||||
|
if err := e.limiter.WaitCheck(ctx, fetchURL); err != nil { return nil, err }
|
||||||
|
|
||||||
|
return e.chrome.Fetch(ctx, fetchURL)
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fixtures"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: it fetches
|
||||||
|
// the pages listed in DIR/<shop>/cases.toml for the plugin tests.
|
||||||
|
func runFixtures(args []string, stdout, stderr io.Writer) int {
|
||||||
|
flags, configPath := newFlagSet("dibs fixtures", stderr)
|
||||||
|
dir := flags.String("dir", "testdata", "directory with <shop>/cases.toml files")
|
||||||
|
only := flags.String("only", "", "fetch only the case with this name")
|
||||||
|
|
||||||
|
pos, ok := parseArgs(flags, args)
|
||||||
|
if !ok { return 2 }
|
||||||
|
if len(pos) > 0 {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs fixtures: unexpected argument %q\n\n%s", pos[0], usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
suites, err := fixtures.Load(*dir)
|
||||||
|
if err != nil { return fail(stderr, "fixtures", err) }
|
||||||
|
if len(suites) == 0 { return fail(stderr, "fixtures", fmt.Errorf("no */cases.toml in %s", *dir)) }
|
||||||
|
|
||||||
|
cfg, ok := loadOptionalConfig(*configPath, stderr)
|
||||||
|
if !ok { return 1 }
|
||||||
|
|
||||||
|
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, "fixtures", err) }
|
||||||
|
defer host.Close()
|
||||||
|
|
||||||
|
e, err := openEnv(logger)
|
||||||
|
if err != nil { return fail(stderr, "fixtures", err) }
|
||||||
|
|
||||||
|
failed := 0
|
||||||
|
|
||||||
|
for _, suite := range suites {
|
||||||
|
p, ok := host.Plugin(suite.Shop)
|
||||||
|
if !ok {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: no plugin named %q, skipping\n", suite.Dir, suite.Shop)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range suite.Cases {
|
||||||
|
if *only != "" && c.Name != *only { continue }
|
||||||
|
|
||||||
|
if err := fetchFixture(ctx, e, p, suite, c, logger, stdout); err != nil {
|
||||||
|
if ctx.Err() != nil { return fail(stderr, "fixtures", ctx.Err()) }
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: %v\n", c.Name, err)
|
||||||
|
failed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if failed > 0 { return 1 }
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func fetchFixture(ctx context.Context, e *env, p *plugin.Plugin, suite fixtures.Suite, c fixtures.Case, logger *slog.Logger, stdout io.Writer) error {
|
||||||
|
fetchURL, err := p.Normalize(ctx, c.URL)
|
||||||
|
if err != nil { return err }
|
||||||
|
|
||||||
|
// The saved page is what the shop sent, not what Chrome made of it.
|
||||||
|
resp, err := e.fetch(ctx, fetchURL, e.client.Get, logger)
|
||||||
|
if err != nil { return err }
|
||||||
|
|
||||||
|
report, err := plugin.Evaluate(ctx, p, c.URL, resp)
|
||||||
|
if err != nil { return err }
|
||||||
|
|
||||||
|
// Saved reports must not depend on how fast the shop answered.
|
||||||
|
report.ElapsedMS = 0
|
||||||
|
|
||||||
|
if err := suite.Save(c, resp.Body, report); err != nil { return err }
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintf(stdout, "%-20s %s\n", c.Name, summary(report))
|
||||||
|
_, _ = fmt.Fprintf(stdout, "%-20s %s\n\n", "", c.Note)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func summary(r *plugin.Report) string {
|
||||||
|
s := r.Verdict
|
||||||
|
if r.Challenge != "" { s += " (" + r.Challenge + ")" }
|
||||||
|
if r.Result == nil { return s }
|
||||||
|
|
||||||
|
res := r.Result
|
||||||
|
|
||||||
|
avail := "unavailable"
|
||||||
|
if res.Available { avail = "AVAILABLE" }
|
||||||
|
|
||||||
|
price := "no price"
|
||||||
|
if res.Price != nil { price = fmt.Sprintf("%.2f %s", *res.Price, res.Currency) }
|
||||||
|
|
||||||
|
return fmt.Sprintf("%s, %s, %s, seller %s", s, avail, price, res.Seller)
|
||||||
|
}
|
||||||
@@ -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] <shop> [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 <shop>`: 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
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
// Command dibs is a personal restock watcher.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"runtime/debug"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// version is set at build time with -ldflags "-X main.version=...".
|
||||||
|
var version = "dev"
|
||||||
|
|
||||||
|
const usage = `Usage:
|
||||||
|
dibs [--config FILE] [--headless] watch items (TUI unless --headless)
|
||||||
|
dibs check [--shop NAME] [--chrome] <url> fetch and parse one URL, print JSON
|
||||||
|
dibs solve [--shop NAME] <url> pass a bot check in a Chrome window
|
||||||
|
dibs login [--browser] <shop> [url] sign in to a shop for cart_mode = "session"
|
||||||
|
dibs logout <shop> delete a shop's signed-in cookies
|
||||||
|
dibs plugin test [--status CODE] <file.lua> <fixture.html> [url]
|
||||||
|
dibs config validate [--config FILE]
|
||||||
|
dibs notify test [--config FILE] [--item NAME] send a sample alert to every channel
|
||||||
|
dibs fixtures [--dir testdata] [--only NAME] fetch real pages for the plugin tests
|
||||||
|
dibs version
|
||||||
|
`
|
||||||
|
|
||||||
|
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":
|
||||||
|
return runConfig(args[1:], stdout, stderr)
|
||||||
|
case "version", "-v", "--version":
|
||||||
|
printVersion(stdout)
|
||||||
|
return 0
|
||||||
|
case "check":
|
||||||
|
return runCheck(args[1:], stdout, stderr)
|
||||||
|
case "plugin":
|
||||||
|
return runPlugin(args[1:], stdout, stderr)
|
||||||
|
case "fixtures":
|
||||||
|
return runFixtures(args[1:], stdout, stderr)
|
||||||
|
case "notify":
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
flags, configPath := newFlagSet("dibs", stderr)
|
||||||
|
headless := flags.Bool("headless", false, "run without the TUI, log JSON to stdout")
|
||||||
|
|
||||||
|
if err := flags.Parse(args); err != nil { return 2 }
|
||||||
|
|
||||||
|
if flags.NArg() > 0 {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs: unknown command %q\n\n%s", flags.Arg(0), usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, ok := loadConfig(*configPath, stderr)
|
||||||
|
if !ok { return 1 }
|
||||||
|
|
||||||
|
return runWatch(cfg, *headless, stdout, stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runConfig(args []string, stdout, stderr io.Writer) int {
|
||||||
|
if len(args) == 0 || args[0] != "validate" {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs config: expected \"validate\"\n\n%s", usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
flags, configPath := newFlagSet("dibs config validate", stderr)
|
||||||
|
if err := flags.Parse(args[1:]); err != nil { return 2 }
|
||||||
|
|
||||||
|
cfg, ok := loadConfig(*configPath, stderr)
|
||||||
|
if !ok { return 1 }
|
||||||
|
|
||||||
|
urls := 0
|
||||||
|
for _, it := range cfg.Items {
|
||||||
|
urls += len(it.URLs)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintf(stdout, "%s: OK (%s, %s, %s, %s)\n", cfg.Path,
|
||||||
|
plural(len(cfg.Items), "item"), plural(urls, "URL"),
|
||||||
|
plural(len(cfg.Accounts), "account"), plural(len(cfg.Plugins), "plugin"))
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func plural(n int, noun string) string {
|
||||||
|
if n == 1 { return "1 " + noun }
|
||||||
|
return fmt.Sprintf("%d %ss", n, noun)
|
||||||
|
}
|
||||||
|
|
||||||
|
// newFlagSet returns a flag set with the --config flag every command takes.
|
||||||
|
func newFlagSet(name string, stderr io.Writer) (*flag.FlagSet, *string) {
|
||||||
|
flags := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||||
|
flags.SetOutput(stderr)
|
||||||
|
path := flags.String("config", "", "config file (default: dibs.toml in the user config dir)")
|
||||||
|
|
||||||
|
return flags, path
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadConfig(path string, stderr io.Writer) (*config.Config, bool) {
|
||||||
|
if path == "" {
|
||||||
|
var err error
|
||||||
|
if path, err = config.DefaultPath(); err != nil {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs: no config dir: %v\n", err)
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := config.Load(path, config.Options{Builtins: plugin.Builtins()})
|
||||||
|
if err != nil {
|
||||||
|
var errs config.Errors
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &errs):
|
||||||
|
_, _ = fmt.Fprintln(stderr, errs)
|
||||||
|
_, _ = fmt.Fprintf(stderr, "%s in config\n", plural(len(errs), "problem"))
|
||||||
|
case errors.Is(err, fs.ErrNotExist):
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs: no config at %s: create it or pass --config\n", path)
|
||||||
|
default:
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs: %v\n", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadOptionalConfig is loadConfig for commands that also work without a
|
||||||
|
// config: with no --config and no file at the default path it returns nil.
|
||||||
|
func loadOptionalConfig(path string, stderr io.Writer) (*config.Config, bool) {
|
||||||
|
if path == "" {
|
||||||
|
def, err := config.DefaultPath()
|
||||||
|
if err != nil { return nil, true }
|
||||||
|
if _, err := os.Stat(def); errors.Is(err, fs.ErrNotExist) { return nil, true }
|
||||||
|
}
|
||||||
|
|
||||||
|
return loadConfig(path, stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseArgs parses flags anywhere among the arguments, so that
|
||||||
|
// "dibs check URL --shop amazon" works too, and returns the positional ones.
|
||||||
|
func parseArgs(flags *flag.FlagSet, args []string) ([]string, bool) {
|
||||||
|
var pos []string
|
||||||
|
|
||||||
|
for {
|
||||||
|
if err := flags.Parse(args); err != nil { return nil, false }
|
||||||
|
if flags.NArg() == 0 { return pos, true }
|
||||||
|
|
||||||
|
pos = append(pos, flags.Arg(0))
|
||||||
|
args = flags.Args()[1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func printVersion(w io.Writer) {
|
||||||
|
v, rev := version, ""
|
||||||
|
if info, ok := debug.ReadBuildInfo(); ok {
|
||||||
|
if v == "dev" && info.Main.Version != "" && info.Main.Version != "(devel)" {
|
||||||
|
v = info.Main.Version
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, s := range info.Settings {
|
||||||
|
if s.Key == "vcs.revision" && len(s.Value) >= 12 {
|
||||||
|
rev = " " + s.Value[:12]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintf(w, "dibs %s%s (%s, %s/%s)\n", v, rev, runtime.Version(), runtime.GOOS, runtime.GOARCH)
|
||||||
|
}
|
||||||
@@ -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) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sendTimeout covers every retry of every channel of one alert.
|
||||||
|
const sendTimeout = time.Minute
|
||||||
|
|
||||||
|
// runNotify implements `dibs notify test [--item NAME]`: it sends a sample
|
||||||
|
// alert for one item to every configured channel.
|
||||||
|
func runNotify(args []string, stdout, stderr io.Writer) int {
|
||||||
|
if len(args) == 0 || args[0] != "test" {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs notify: expected \"test\"\n\n%s", usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
flags, configPath := newFlagSet("dibs notify test", stderr)
|
||||||
|
name := flags.String("item", "", "item to build the sample alert from (default: the first)")
|
||||||
|
|
||||||
|
pos, ok := parseArgs(flags, args[1:])
|
||||||
|
if !ok { return 2 }
|
||||||
|
if len(pos) > 0 {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs notify test: unexpected argument %q\n\n%s", pos[0], usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, ok := loadConfig(*configPath, stderr)
|
||||||
|
if !ok { return 1 }
|
||||||
|
|
||||||
|
item, ok := findItem(cfg, *name)
|
||||||
|
if !ok {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs notify test: no item named %q\n", *name)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
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, "notify test", err) }
|
||||||
|
defer host.Close()
|
||||||
|
|
||||||
|
a, err := sampleAlert(ctx, host, item)
|
||||||
|
if err != nil { return fail(stderr, "notify test", err) }
|
||||||
|
|
||||||
|
n := notify.New(cfg.Notify, userAgent())
|
||||||
|
if len(n.Channels()) == 0 {
|
||||||
|
_, _ = fmt.Fprintln(stderr, "dibs notify test: no webhooks configured and desktop notifications are off")
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if err := n.Send(ctx, a); err != nil { return fail(stderr, "notify test", err) }
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintf(stdout, "sent a test alert for %q to: %v\n", item.Name, n.Channels())
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func findItem(cfg *config.Config, name string) (config.Item, bool) {
|
||||||
|
for _, it := range cfg.Items {
|
||||||
|
if name == "" || it.Name == name { return it, true }
|
||||||
|
}
|
||||||
|
|
||||||
|
return config.Item{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// sampleAlert is what the item's first URL would send if it fired at its
|
||||||
|
// max_price.
|
||||||
|
func sampleAlert(ctx context.Context, host *plugin.Host, item config.Item) (alert.Alert, error) {
|
||||||
|
p, ok := host.Plugin(item.Shop)
|
||||||
|
if !ok { return alert.Alert{}, fmt.Errorf("no plugin named %q", item.Shop) }
|
||||||
|
|
||||||
|
pageURL, err := p.Normalize(ctx, item.URLs[0])
|
||||||
|
if err != nil { return alert.Alert{}, err }
|
||||||
|
|
||||||
|
cartLink, err := p.CartLink(ctx, pageURL, "")
|
||||||
|
if err != nil { return alert.Alert{}, err }
|
||||||
|
|
||||||
|
price := 99.99
|
||||||
|
if item.MaxPrice != nil { price = *item.MaxPrice }
|
||||||
|
|
||||||
|
currency := item.Currency
|
||||||
|
if currency == "" { currency = "EUR" }
|
||||||
|
|
||||||
|
return alert.Alert{
|
||||||
|
Item: item.Name,
|
||||||
|
Shop: item.Shop,
|
||||||
|
URL: pageURL,
|
||||||
|
Title: "Sample product title",
|
||||||
|
Price: &price,
|
||||||
|
Currency: currency,
|
||||||
|
Seller: plugin.SellerFirstParty,
|
||||||
|
CartLink: cartLink,
|
||||||
|
Time: time.Now(),
|
||||||
|
Test: true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func userAgent() string { return "dibs/" + version }
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runSolve implements `dibs solve [--shop NAME] <url>`: it opens the URL in
|
||||||
|
// a visible Chrome window for the user to pass a bot check, and keeps the
|
||||||
|
// cookies for every dibs process.
|
||||||
|
func runSolve(args []string, stdout, stderr io.Writer) int {
|
||||||
|
flags, configPath := newFlagSet("dibs solve", stderr)
|
||||||
|
shop := flags.String("shop", "", "plugin to normalize the URL with (default: the first whose matches() accepts it)")
|
||||||
|
|
||||||
|
pos, ok := parseArgs(flags, args)
|
||||||
|
if !ok { return 2 }
|
||||||
|
if len(pos) != 1 {
|
||||||
|
_, _ = fmt.Fprintf(stderr, "dibs solve: expected one URL\n\n%s", usage)
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, ok := loadOptionalConfig(*configPath, stderr)
|
||||||
|
if !ok { return 1 }
|
||||||
|
|
||||||
|
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, "solve", err) }
|
||||||
|
defer host.Close()
|
||||||
|
|
||||||
|
p, err := pickPlugin(ctx, host, *shop, pos[0])
|
||||||
|
if err != nil { return fail(stderr, "solve", err) }
|
||||||
|
|
||||||
|
fetchURL, err := p.Normalize(ctx, pos[0])
|
||||||
|
if err != nil { return fail(stderr, "solve", err) }
|
||||||
|
|
||||||
|
e, err := openEnv(logger)
|
||||||
|
if err != nil { return fail(stderr, "solve", err) }
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintln(stdout, "Pass the bot check in the Chrome window. It closes by itself once the page shows up.")
|
||||||
|
|
||||||
|
if _, err := e.chrome.Solve(ctx, fetchURL); err != nil { return fail(stderr, "solve", err) }
|
||||||
|
|
||||||
|
u, _ := url.Parse(fetchURL)
|
||||||
|
e.limiter.Success(u.Hostname())
|
||||||
|
e.save(logger)
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintf(stdout, "Solved. The cookies for %s are saved; a running dibs uses them once its current backoff for the host ends.\n", u.Hostname())
|
||||||
|
return 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
tea "charm.land/bubbletea/v2"
|
||||||
|
"github.com/charmbracelet/colorprofile"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/tui"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runTUI watches every configured URL in the TUI until the user quits.
|
||||||
|
func runTUI(cfg *config.Config, stderr io.Writer) int {
|
||||||
|
// Ctrl-C reaches the TUI as a key press.
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
logs := tui.NewLogHandler(slog.LevelInfo)
|
||||||
|
logger := slog.New(logs)
|
||||||
|
|
||||||
|
w, err := newWatcher(ctx, cfg, logger, slog.LevelDebug)
|
||||||
|
if err != nil { return fail(stderr, "watch", err) }
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
w.run(func(c check) { p.Send(tui.CheckMsg{Result: c.Result, Decision: c.Decision, PriceErr: c.PriceErr}) })
|
||||||
|
}()
|
||||||
|
|
||||||
|
_, err = p.Run()
|
||||||
|
|
||||||
|
logs.Redirect(stderr)
|
||||||
|
stop()
|
||||||
|
<-done
|
||||||
|
w.close()
|
||||||
|
|
||||||
|
if err != nil && !errors.Is(err, tea.ErrProgramKilled) { return fail(stderr, "tui", err) }
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// terminalOptions works around terminals that claim to be xterm but are not.
|
||||||
|
// Under a TERM the renderer does not know, it redraws with plain writes only.
|
||||||
|
// The color profile is detected from the real environment first, so colors stay.
|
||||||
|
func terminalOptions() []tea.ProgramOption {
|
||||||
|
if os.Getenv("TERMINAL_EMULATOR") != "JetBrains-JediTerm" { return nil }
|
||||||
|
|
||||||
|
profile := colorprofile.Detect(os.Stdout, os.Environ())
|
||||||
|
|
||||||
|
env := []string{"TERM=jediterm"}
|
||||||
|
for _, kv := range os.Environ() {
|
||||||
|
if !strings.HasPrefix(kv, "TERM=") { env = append(env, kv) }
|
||||||
|
}
|
||||||
|
|
||||||
|
return []tea.ProgramOption{tea.WithEnvironment(env), tea.WithColorProfile(profile)}
|
||||||
|
}
|
||||||
@@ -0,0 +1,421 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runWatch watches every configured URL until interrupted.
|
||||||
|
func runWatch(cfg *config.Config, headless bool, stdout, stderr io.Writer) int {
|
||||||
|
if !headless { return runTUI(cfg, stderr) }
|
||||||
|
|
||||||
|
logger := slog.New(slog.NewJSONHandler(stdout, nil))
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
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) {
|
||||||
|
if ring && c.Decision.Alert != nil { _, _ = io.WriteString(stderr, "\a") }
|
||||||
|
})
|
||||||
|
|
||||||
|
// A second Ctrl-C stops dibs without waiting for notifications.
|
||||||
|
stop()
|
||||||
|
w.close()
|
||||||
|
|
||||||
|
logger.Info("stopped")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// check is one finished check and what the alert engine made of it.
|
||||||
|
type check struct {
|
||||||
|
watch.Result
|
||||||
|
Decision alert.Decision
|
||||||
|
// PriceErr means the page was available but its price could not be
|
||||||
|
// checked.
|
||||||
|
PriceErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
// watcher runs the scheduler and turns its results into alerts, for the
|
||||||
|
// TUI and headless mode alike.
|
||||||
|
type watcher struct {
|
||||||
|
ctx context.Context
|
||||||
|
logger *slog.Logger
|
||||||
|
env *env
|
||||||
|
sched *watch.Scheduler
|
||||||
|
rates *fx.Service
|
||||||
|
// checkLevel is the level checks are logged at. Failed checks are
|
||||||
|
// always warnings.
|
||||||
|
checkLevel slog.Level
|
||||||
|
|
||||||
|
reloadMu sync.Mutex
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
cfg *config.Config
|
||||||
|
host *plugin.Host
|
||||||
|
alerts *alert.Engine
|
||||||
|
notifier *notify.Notifier
|
||||||
|
// retired are the hosts reloads replaced. Checks that started before a
|
||||||
|
// reload may still use them, so they are closed on exit.
|
||||||
|
retired []*plugin.Host
|
||||||
|
// humans are the hosts whose bot check needs the user, so the user is
|
||||||
|
// told once, not on every retry.
|
||||||
|
humans map[string]bool
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
e, err := openEnv(logger)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
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()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, msg := range warnings { logger.Warn(msg) }
|
||||||
|
|
||||||
|
w := &watcher{
|
||||||
|
ctx: ctx,
|
||||||
|
logger: logger,
|
||||||
|
env: e,
|
||||||
|
sched: sched,
|
||||||
|
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)
|
||||||
|
|
||||||
|
logger.Info("watching", "items", len(cfg.Items), "urls", len(sched.Statuses()), "notify", w.notifier.Channels())
|
||||||
|
|
||||||
|
return w, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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()
|
||||||
|
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.
|
||||||
|
go func() {
|
||||||
|
t := time.NewTicker(time.Minute)
|
||||||
|
defer t.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-w.ctx.Done():
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
w.env.save(w.logger)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
for r := range w.sched.Results() {
|
||||||
|
w.env.save(w.logger)
|
||||||
|
observe(w.consider(r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *watcher) consider(r watch.Result) check {
|
||||||
|
logResult(w.logger, w.checkLevel, r)
|
||||||
|
|
||||||
|
c := check{Result: r}
|
||||||
|
if r.Err != nil { return c }
|
||||||
|
|
||||||
|
w.mu.Lock()
|
||||||
|
alerts, notifier := w.alerts, w.notifier
|
||||||
|
w.mu.Unlock()
|
||||||
|
|
||||||
|
w.trackHuman(notifier, r)
|
||||||
|
|
||||||
|
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 != "":
|
||||||
|
w.logger.Info("available, not alerting", "item", r.Item.Name, "url", r.URL, "reason", c.Decision.Reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// fire logs an alert and sends its notifications in the background.
|
||||||
|
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) }
|
||||||
|
|
||||||
|
msg := "ALERT"
|
||||||
|
if a.Cart == alert.CartAdded { msg = "IN CART" }
|
||||||
|
|
||||||
|
w.logger.Info(msg, attrs...)
|
||||||
|
|
||||||
|
if len(n.Channels()) == 0 { return }
|
||||||
|
|
||||||
|
w.sends.Go(func() {
|
||||||
|
// Alerts still go out when dibs is stopped right after one fires.
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), sendTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if err := n.Send(ctx, a); err != nil {
|
||||||
|
w.logger.Warn("notification failed", "item", a.Item, "err", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.logger.Info("notified", "item", a.Item, "channels", n.Channels())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// trackHuman tells the user, once per host, when a bot check needs them,
|
||||||
|
// and forgets it when the host lets dibs through again.
|
||||||
|
func (w *watcher) trackHuman(n *notify.Notifier, r watch.Result) {
|
||||||
|
u, err := url.Parse(r.Report.FetchURL)
|
||||||
|
if err != nil { return }
|
||||||
|
|
||||||
|
host := strings.ToLower(u.Hostname())
|
||||||
|
|
||||||
|
w.mu.Lock()
|
||||||
|
known := w.humans[host]
|
||||||
|
|
||||||
|
switch r.Report.Verdict {
|
||||||
|
case fetch.NeedsHuman.String():
|
||||||
|
w.humans[host] = true
|
||||||
|
case fetch.OK.String(), fetch.NotFound.String():
|
||||||
|
delete(w.humans, host)
|
||||||
|
}
|
||||||
|
w.mu.Unlock()
|
||||||
|
|
||||||
|
if known || r.Report.Verdict != fetch.NeedsHuman.String() { return }
|
||||||
|
|
||||||
|
w.logger.Warn("a bot check needs you: press enter on the row in the TUI, or run dibs solve with the URL", "host", host, "url", r.Report.FetchURL)
|
||||||
|
|
||||||
|
if err := n.Notice("dibs needs you on "+host, "A bot check only a person can pass blocks "+host+". Open dibs to solve it."); err != nil {
|
||||||
|
w.logger.Warn("desktop notification failed", "err", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solve opens fetchURL in a visible Chrome window for the user to pass its
|
||||||
|
// bot check. Afterwards the host is no longer backed off, and its URLs are
|
||||||
|
// checked again as soon as the URL floor allows.
|
||||||
|
func (w *watcher) Solve(fetchURL string) error {
|
||||||
|
u, err := url.Parse(fetchURL)
|
||||||
|
if err != nil { return err }
|
||||||
|
|
||||||
|
host := strings.ToLower(u.Hostname())
|
||||||
|
|
||||||
|
w.logger.Info("opening Chrome for the bot check", "url", fetchURL)
|
||||||
|
|
||||||
|
if _, err := w.env.chrome.Solve(w.ctx, fetchURL); err != nil { return err }
|
||||||
|
|
||||||
|
w.env.limiter.Success(host)
|
||||||
|
w.env.save(w.logger)
|
||||||
|
|
||||||
|
w.mu.Lock()
|
||||||
|
delete(w.humans, host)
|
||||||
|
w.mu.Unlock()
|
||||||
|
|
||||||
|
w.sched.CheckHost(host)
|
||||||
|
w.logger.Info("bot check solved, checking again", "host", host)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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()
|
||||||
|
defer w.mu.Unlock()
|
||||||
|
|
||||||
|
for _, h := range w.retired { h.Close() }
|
||||||
|
w.host.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *watcher) Statuses() []watch.Status { return w.sched.Statuses() }
|
||||||
|
func (w *watcher) Pause(item string, paused bool) bool { return w.sched.Pause(item, paused) }
|
||||||
|
func (w *watcher) PauseAll(paused bool) { w.sched.PauseAll(paused) }
|
||||||
|
func (w *watcher) CheckNow(item string) bool { return w.sched.CheckNow(item) }
|
||||||
|
|
||||||
|
// Reload reads the config file again and switches to it. Plugins are
|
||||||
|
// loaded afresh, so edits to plugin files apply too. On error, nothing
|
||||||
|
// changes. It returns a summary of the changes.
|
||||||
|
func (w *watcher) Reload() ([]string, error) {
|
||||||
|
w.reloadMu.Lock()
|
||||||
|
defer w.reloadMu.Unlock()
|
||||||
|
|
||||||
|
w.mu.Lock()
|
||||||
|
old := w.cfg
|
||||||
|
w.mu.Unlock()
|
||||||
|
|
||||||
|
cfg, err := config.Load(old.Path, config.Options{Builtins: plugin.Builtins()})
|
||||||
|
if err != nil {
|
||||||
|
var errs config.Errors
|
||||||
|
if errors.As(err, &errs) {
|
||||||
|
for _, e := range errs { w.logger.Warn("config reload failed", "problem", e.Brief()) }
|
||||||
|
} else {
|
||||||
|
w.logger.Warn("config reload failed", "err", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
w.apply(cfg, host)
|
||||||
|
|
||||||
|
summary := config.Diff(old, cfg)
|
||||||
|
if len(summary) == 0 { summary = []string{"no changes"} }
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// needsRates reports whether any item may need a currency conversion.
|
||||||
|
func needsRates(cfg *config.Config) bool {
|
||||||
|
for _, it := range cfg.Items {
|
||||||
|
if it.Currency != "" { return true }
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isTerminal(w io.Writer) bool {
|
||||||
|
f, ok := w.(*os.File)
|
||||||
|
if !ok { return false }
|
||||||
|
|
||||||
|
info, err := f.Stat()
|
||||||
|
return err == nil && info.Mode()&os.ModeCharDevice != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// logResult logs a check at level, or as a warning if it failed or ran into
|
||||||
|
// a bot check.
|
||||||
|
func logResult(logger *slog.Logger, level slog.Level, r watch.Result) {
|
||||||
|
attrs := []any{"item", r.Item.Name, "url", r.URL, "next", r.Next.Format(time.RFC3339)}
|
||||||
|
|
||||||
|
if r.Backoff > 0 { attrs = append(attrs, "backoff", r.Backoff.Round(time.Second).String()) }
|
||||||
|
|
||||||
|
if r.Report != nil {
|
||||||
|
attrs = append(attrs, "verdict", r.Report.Verdict, "status", r.Report.Status)
|
||||||
|
if r.Report.Challenge != "" { attrs = append(attrs, "challenge", r.Report.Challenge) }
|
||||||
|
|
||||||
|
if res := r.Report.Result; res != nil {
|
||||||
|
attrs = append(attrs, "title", res.Title, "available", res.Available, "seller", res.Seller)
|
||||||
|
if res.Price != nil { attrs = append(attrs, "price", *res.Price, "currency", res.Currency) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case r.Err != nil:
|
||||||
|
logger.Warn("check failed", append(attrs, "err", r.Err.Error())...)
|
||||||
|
case r.Report.Verdict != fetch.OK.String() && r.Report.Verdict != fetch.NotFound.String():
|
||||||
|
logger.Warn("check got "+r.Report.Verdict, attrs...)
|
||||||
|
default:
|
||||||
|
logger.Log(context.Background(), level, "checked", attrs...)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
module git.security-command.org/Overlord/dibs
|
||||||
|
|
||||||
|
go 1.26.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
charm.land/bubbles/v2 v2.2.1
|
||||||
|
charm.land/bubbletea/v2 v2.1.0
|
||||||
|
charm.land/lipgloss/v2 v2.0.6
|
||||||
|
github.com/PuerkitoBio/goquery v1.13.0
|
||||||
|
github.com/andybalholm/cascadia v1.3.4
|
||||||
|
github.com/bogdanfinn/fhttp v0.6.9
|
||||||
|
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
|
||||||
|
)
|
||||||
|
|
||||||
|
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/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/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
|
||||||
|
github.com/mattn/go-runewidth v0.0.30 // indirect
|
||||||
|
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||||
|
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
|
||||||
|
github.com/quic-go/qpack v0.6.0 // indirect
|
||||||
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
|
github.com/sergeymakinen/go-bmp v1.0.0 // indirect
|
||||||
|
github.com/sergeymakinen/go-ico v1.0.0-beta.0 // indirect
|
||||||
|
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect
|
||||||
|
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
|
||||||
|
github.com/xo/terminfo v1.0.0 // indirect
|
||||||
|
github.com/ysmood/fetchup v0.2.3 // indirect
|
||||||
|
github.com/ysmood/goob v0.4.0 // indirect
|
||||||
|
github.com/ysmood/got v0.40.0 // indirect
|
||||||
|
github.com/ysmood/gson v0.7.3 // indirect
|
||||||
|
github.com/ysmood/leakless v0.9.0 // indirect
|
||||||
|
golang.org/x/crypto v0.57.0 // indirect
|
||||||
|
golang.org/x/sync v0.23.0 // indirect
|
||||||
|
golang.org/x/text v0.42.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
|
||||||
|
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
|
||||||
|
charm.land/bubbletea/v2 v2.1.0 h1:A9fj9h5LFrvQhQHFNggp8K8rvY6CUfgn9dMbb6p2HIw=
|
||||||
|
charm.land/bubbletea/v2 v2.1.0/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
|
||||||
|
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
|
||||||
|
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
|
||||||
|
git.sr.ht/~jackmordaunt/go-toast v1.1.2 h1:/yrfI55LRt1M7H1vkaw+NaH1+L1CDxrqDltwm5euVuE=
|
||||||
|
git.sr.ht/~jackmordaunt/go-toast v1.1.2/go.mod h1:jA4OqHKTQ4AFBdwrSnwnskUIIS3HYzlJSgdzCKqfavo=
|
||||||
|
github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM=
|
||||||
|
github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g=
|
||||||
|
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
|
||||||
|
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=
|
||||||
|
github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM=
|
||||||
|
github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic=
|
||||||
|
github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI=
|
||||||
|
github.com/bogdanfinn/fhttp v0.6.9 h1:F9MsWR1K6JMRlXN4Q/MfjYmptr29nCdycQo+OPBG5U0=
|
||||||
|
github.com/bogdanfinn/fhttp v0.6.9/go.mod h1:7phoj3f/q54WuiTnCTlAhEoaVcdlruKkSzCSD47LzHk=
|
||||||
|
github.com/bogdanfinn/quic-go-utls v1.0.10-utls h1:oZN+J3OKMmWaVbI/sx4ULvHiAXbWJKVcvEFW4fkybMU=
|
||||||
|
github.com/bogdanfinn/quic-go-utls v1.0.10-utls/go.mod h1:bBLJ2Vy68Q7y6VfbG9czd825rTcQua7n+y12RM9Q588=
|
||||||
|
github.com/bogdanfinn/tls-client v1.16.0 h1:km3YLI6CMRLZnfrC+hGStePPryIicd3hoxFQvHB1itY=
|
||||||
|
github.com/bogdanfinn/tls-client v1.16.0/go.mod h1:TxbiXlpZhNN5xmxzsr3KhNAeqoEEPJafwgBbyp26Phc=
|
||||||
|
github.com/bogdanfinn/utls v1.7.8-barnius h1:wRT83mP4hmuMM1/lIpLKKhzaEuyEKjux7VSj7XHFXdg=
|
||||||
|
github.com/bogdanfinn/utls v1.7.8-barnius/go.mod h1:o5v09jf+9ayMEfcP+8sssNdSMm278cyhBV25H8jb5Lw=
|
||||||
|
github.com/bogdanfinn/websocket v1.5.6-barnius h1:QpdWVEZ9rKtcT7C2pU19uE2KQw2XevuKTDTzLxfDi/I=
|
||||||
|
github.com/bogdanfinn/websocket v1.5.6-barnius/go.mod h1:41/rXLDWpqJ5A4gOKSY/z4NLbW/hHZHneRcYM0kbpxA=
|
||||||
|
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
|
||||||
|
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
|
||||||
|
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw=
|
||||||
|
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
|
||||||
|
github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM=
|
||||||
|
github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w=
|
||||||
|
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
|
||||||
|
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
|
||||||
|
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
|
||||||
|
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
|
||||||
|
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
|
||||||
|
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
|
||||||
|
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
|
||||||
|
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
|
||||||
|
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
|
||||||
|
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
|
||||||
|
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
|
||||||
|
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=
|
||||||
|
github.com/esiqveland/notify v0.13.3 h1:QCMw6o1n+6rl+oLUfg8P1IIDSFsDEb2WlXvVvIJbI/o=
|
||||||
|
github.com/esiqveland/notify v0.13.3/go.mod h1:hesw/IRYTO0x99u1JPweAl4+5mwXJibQVUcP0Iu5ORE=
|
||||||
|
github.com/gen2brain/beeep v0.11.2 h1:+KfiKQBbQCuhfJFPANZuJ+oxsSKAYNe88hIpJuyKWDA=
|
||||||
|
github.com/gen2brain/beeep v0.11.2/go.mod h1:jQVvuwnLuwOcdctHn/uyh8horSBNJ8uGb9Cn2W4tvoc=
|
||||||
|
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||||
|
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||||
|
github.com/go-rod/rod v0.113.0/go.mod h1:aiedSEFg5DwG/fnNbUOTPMTTWX3MRj6vIs/a684Mthw=
|
||||||
|
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/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=
|
||||||
|
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||||
|
github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk=
|
||||||
|
github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
|
||||||
|
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||||
|
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||||
|
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||||
|
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||||
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||||
|
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||||
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
|
github.com/sergeymakinen/go-bmp v1.0.0 h1:SdGTzp9WvCV0A1V0mBeaS7kQAwNLdVJbmHlqNWq0R+M=
|
||||||
|
github.com/sergeymakinen/go-bmp v1.0.0/go.mod h1:/mxlAQZRLxSvJFNIEGGLBE/m40f3ZnUifpgVDlcUIEY=
|
||||||
|
github.com/sergeymakinen/go-ico v1.0.0-beta.0 h1:m5qKH7uPKLdrygMWxbamVn+tl2HfiA3K6MFJw4GfZvQ=
|
||||||
|
github.com/sergeymakinen/go-ico v1.0.0-beta.0/go.mod h1:wQ47mTczswBO5F0NoDt7O0IXgnV4Xy3ojrroMQzyhUk=
|
||||||
|
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=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=
|
||||||
|
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
|
||||||
|
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc=
|
||||||
|
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng=
|
||||||
|
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
|
||||||
|
github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||||
|
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||||
|
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||||
|
github.com/ysmood/fetchup v0.2.3 h1:ulX+SonA0Vma5zUFXtv52Kzip/xe7aj4vqT5AJwQ+ZQ=
|
||||||
|
github.com/ysmood/fetchup v0.2.3/go.mod h1:xhibcRKziSvol0H1/pj33dnKrYyI2ebIvz5cOOkYGns=
|
||||||
|
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=
|
||||||
|
github.com/ysmood/leakless v0.8.0/go.mod h1:R8iAXPRaG97QJwqxs74RdwzcRHT1SWCGTNqY8q0JvMQ=
|
||||||
|
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=
|
||||||
|
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||||
|
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
||||||
|
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
||||||
|
golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||||
|
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||||
|
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||||
|
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||||
|
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||||
|
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
// Package alert decides when an item fires: when one of its pages offers it
|
||||||
|
// from an accepted seller at an accepted price, and the item's cooldown
|
||||||
|
// allows another alert.
|
||||||
|
package alert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Alert is one item becoming buyable.
|
||||||
|
type Alert struct {
|
||||||
|
Item string
|
||||||
|
Shop string
|
||||||
|
// URL is the product page, as the plugin normalized it.
|
||||||
|
URL string
|
||||||
|
Title string
|
||||||
|
Price *float64
|
||||||
|
Currency string
|
||||||
|
// Converted is Price in the item's currency, when the page uses another
|
||||||
|
// one and the conversion worked.
|
||||||
|
Converted *float64
|
||||||
|
ConvertedCurrency string
|
||||||
|
Seller string
|
||||||
|
CartLink string
|
||||||
|
Time time.Time
|
||||||
|
// PreviousPrice is the price of the last alert, when this one fires
|
||||||
|
// 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 {
|
||||||
|
if a.Price == nil { return "price unknown" }
|
||||||
|
|
||||||
|
s := Money(*a.Price, a.Currency)
|
||||||
|
if a.Converted != nil { s += " (≈ " + Money(*a.Converted, a.ConvertedCurrency) + ")" }
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// SellerText describes the seller for notifications.
|
||||||
|
func (a Alert) SellerText() string {
|
||||||
|
switch a.Seller {
|
||||||
|
case plugin.SellerFirstParty:
|
||||||
|
return "sold by " + a.Shop
|
||||||
|
case plugin.SellerFulfilled:
|
||||||
|
return "shipped by " + a.Shop
|
||||||
|
case plugin.SellerThirdParty:
|
||||||
|
return "marketplace seller"
|
||||||
|
default:
|
||||||
|
return "seller unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Money(amount float64, currency string) string {
|
||||||
|
s := strconv.FormatFloat(amount, 'f', 2, 64)
|
||||||
|
if currency != "" { s += " " + currency }
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// Converter is fx.Service.
|
||||||
|
type Converter interface {
|
||||||
|
Convert(ctx context.Context, amount float64, from, to string) (float64, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sent is what an item's cooldown remembers about its last alert.
|
||||||
|
type Sent struct {
|
||||||
|
Time time.Time `json:"time"`
|
||||||
|
Price *float64 `json:"price,omitempty"`
|
||||||
|
Currency string `json:"currency,omitempty"`
|
||||||
|
// ItemPrice is the price in the item's currency, so that pages in
|
||||||
|
// different currencies compare.
|
||||||
|
ItemPrice *float64 `json:"item_price,omitempty"`
|
||||||
|
ItemCurrency string `json:"item_currency,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store keeps the cooldowns between runs and shares them with other dibs
|
||||||
|
// processes. Lock is held from loading an item's last alert until the new
|
||||||
|
// one is stored, so two processes never both send it.
|
||||||
|
type Store interface {
|
||||||
|
Lock() func()
|
||||||
|
LoadAlert(item string) (Sent, bool)
|
||||||
|
StoreAlert(item string, s Sent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Engine turns check results into alerts. It is safe for concurrent use.
|
||||||
|
type Engine struct {
|
||||||
|
cooldown time.Duration
|
||||||
|
fx Converter
|
||||||
|
store Store
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
sent map[string]Sent // used when store is nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewEngine returns an engine. store may be nil to keep cooldowns in memory.
|
||||||
|
func NewEngine(cooldown time.Duration, fx Converter, store Store) *Engine {
|
||||||
|
return &Engine{cooldown: cooldown, fx: fx, store: store, sent: map[string]Sent{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decision is what Consider made of a checked page.
|
||||||
|
type Decision struct {
|
||||||
|
// Alert is set when the item fires.
|
||||||
|
Alert *Alert
|
||||||
|
// Qualifies reports whether the page passed the seller and price checks,
|
||||||
|
// even if the cooldown held the alert back.
|
||||||
|
Qualifies bool
|
||||||
|
// Reason says why an available page did not fire.
|
||||||
|
Reason string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Consider decides whether a checked page makes its item fire. A page that
|
||||||
|
// is not available decides nothing. An error means the price could not be
|
||||||
|
// checked, such as when no current exchange rate is available.
|
||||||
|
func (e *Engine) Consider(ctx context.Context, item config.Item, rep *plugin.Report, now time.Time) (Decision, error) {
|
||||||
|
if rep == nil || rep.Result == nil || !rep.Result.Available { return Decision{}, nil }
|
||||||
|
|
||||||
|
a, why, err := e.qualify(ctx, item, rep, now)
|
||||||
|
if a == nil { return Decision{Reason: why}, err }
|
||||||
|
|
||||||
|
unlock := e.lock()
|
||||||
|
defer unlock()
|
||||||
|
|
||||||
|
next := a.sent(item.Currency)
|
||||||
|
|
||||||
|
last, ok := e.load(item.Name)
|
||||||
|
allowed, drop := Allows(last, ok, next, e.cooldown)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case !allowed:
|
||||||
|
return Decision{Qualifies: true, Reason: "in cooldown until " + last.Time.Add(e.cooldown).Format(time.TimeOnly)}, nil
|
||||||
|
case drop && last.Currency == next.Currency:
|
||||||
|
a.PreviousPrice, a.PreviousCurrency = last.Price, last.Currency
|
||||||
|
case drop:
|
||||||
|
a.PreviousPrice, a.PreviousCurrency = last.ItemPrice, last.ItemCurrency
|
||||||
|
}
|
||||||
|
|
||||||
|
e.save(item.Name, next)
|
||||||
|
|
||||||
|
return Decision{Alert: a, Qualifies: true}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sent is what the cooldown remembers of a.
|
||||||
|
func (a *Alert) sent(itemCurrency string) Sent {
|
||||||
|
s := Sent{Time: a.Time, Price: a.Price, Currency: a.Currency}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case a.Converted != nil:
|
||||||
|
s.ItemPrice, s.ItemCurrency = a.Converted, a.ConvertedCurrency
|
||||||
|
case a.Price != nil && (a.Currency == itemCurrency || a.Currency == "" || itemCurrency == ""):
|
||||||
|
s.ItemPrice, s.ItemCurrency = a.Price, itemCurrency
|
||||||
|
}
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// qualify checks an available page against the item's seller policy and
|
||||||
|
// max_price.
|
||||||
|
func (e *Engine) qualify(ctx context.Context, item config.Item, rep *plugin.Report, now time.Time) (*Alert, string, error) {
|
||||||
|
res := rep.Result
|
||||||
|
|
||||||
|
if !item.AcceptsSeller(res.Seller) { return nil, fmt.Sprintf("seller is %s, the item accepts %s", res.Seller, item.Seller), nil }
|
||||||
|
|
||||||
|
a := &Alert{
|
||||||
|
Item: item.Name,
|
||||||
|
Shop: rep.Shop,
|
||||||
|
URL: rep.FetchURL,
|
||||||
|
Title: res.Title,
|
||||||
|
Price: res.Price,
|
||||||
|
Currency: res.Currency,
|
||||||
|
Seller: res.Seller,
|
||||||
|
CartLink: rep.CartLink,
|
||||||
|
Time: now,
|
||||||
|
}
|
||||||
|
|
||||||
|
// A page without a currency is taken to use the item's.
|
||||||
|
foreign := item.Currency != "" && res.Currency != "" && res.Currency != item.Currency
|
||||||
|
|
||||||
|
var convErr error
|
||||||
|
if foreign && res.Price != nil {
|
||||||
|
v, err := e.fx.Convert(ctx, *res.Price, res.Currency, item.Currency)
|
||||||
|
v = math.Round(v*100) / 100
|
||||||
|
if err == nil { a.Converted, a.ConvertedCurrency = &v, item.Currency } else { convErr = err }
|
||||||
|
}
|
||||||
|
|
||||||
|
if item.MaxPrice == nil { return a, "", nil }
|
||||||
|
|
||||||
|
limit := *item.MaxPrice
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case res.Price == nil:
|
||||||
|
return nil, "no price on the page to compare with max_price", nil
|
||||||
|
case foreign && convErr != nil:
|
||||||
|
return nil, "", fmt.Errorf("cannot compare %s with max_price %s: %w", Money(*res.Price, res.Currency), Money(limit, item.Currency), convErr)
|
||||||
|
case foreign:
|
||||||
|
if p := *a.Converted * (1 + item.FXMargin); p > limit {
|
||||||
|
return nil, fmt.Sprintf("price %s with fx_margin is above max_price %s", Money(p, item.Currency), Money(limit, item.Currency)), nil
|
||||||
|
}
|
||||||
|
case *res.Price > limit:
|
||||||
|
return nil, fmt.Sprintf("price %s is above max_price %s", Money(*res.Price, res.Currency), Money(limit, item.Currency)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return a, "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allows applies an item's cooldown: after an alert, the item stays quiet
|
||||||
|
// for cooldown unless its price drops below the last alert's. It also
|
||||||
|
// reports whether next is for such a drop.
|
||||||
|
//
|
||||||
|
// Prices in the same page currency compare as they are, so that exchange
|
||||||
|
// rates moving overnight never look like a price drop. Prices in different
|
||||||
|
// currencies compare in the item's currency.
|
||||||
|
func Allows(last Sent, hasLast bool, next Sent, cooldown time.Duration) (allowed, drop bool) {
|
||||||
|
if !hasLast || !next.Time.Before(last.Time.Add(cooldown)) { return true, false }
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case next.Price != nil && last.Price != nil && next.Currency == last.Currency:
|
||||||
|
drop = *next.Price < *last.Price
|
||||||
|
case next.ItemPrice != nil && last.ItemPrice != nil && next.ItemCurrency == last.ItemCurrency:
|
||||||
|
drop = *next.ItemPrice < *last.ItemPrice
|
||||||
|
default:
|
||||||
|
// Without a price in a shared currency, nothing compares.
|
||||||
|
}
|
||||||
|
|
||||||
|
return drop, drop
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Engine) lock() func() {
|
||||||
|
if e.store == nil { return func() {} }
|
||||||
|
|
||||||
|
return e.store.Lock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Engine) load(item string) (Sent, bool) {
|
||||||
|
if e.store != nil { return e.store.LoadAlert(item) }
|
||||||
|
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
|
||||||
|
s, ok := e.sent[item]
|
||||||
|
return s, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *Engine) save(item string, s Sent) {
|
||||||
|
if e.store != nil {
|
||||||
|
e.store.StoreAlert(item, s)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
|
||||||
|
e.sent[item] = s
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package alert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// usdPerEUR converts USD and EUR at a fixed rate, or fails when down.
|
||||||
|
type usdPerEUR struct {
|
||||||
|
rate float64
|
||||||
|
down bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c usdPerEUR) Convert(_ context.Context, amount float64, from, to string) (float64, error) {
|
||||||
|
switch {
|
||||||
|
case c.down:
|
||||||
|
return 0, errors.New("no rates")
|
||||||
|
case from == "USD" && to == "EUR":
|
||||||
|
return amount / c.rate, nil
|
||||||
|
case from == "EUR" && to == "USD":
|
||||||
|
return amount * c.rate, nil
|
||||||
|
default:
|
||||||
|
return 0, errors.New("unexpected conversion " + from + " to " + to)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func page(price float64, currency, seller string) *plugin.Report {
|
||||||
|
return &plugin.Report{
|
||||||
|
Shop: "amazon",
|
||||||
|
FetchURL: "https://www.amazon.de/dp/B0HMX2FSTF",
|
||||||
|
Result: &plugin.Result{Title: "Metro", Available: true, Price: &price, Currency: currency, Seller: seller},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func metro(maxPrice float64) config.Item {
|
||||||
|
return config.Item{Name: "metro", Shop: "amazon", MaxPrice: &maxPrice, Currency: "EUR", Seller: config.SellerFulfilled}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCooldown follows one item through a day of restocks.
|
||||||
|
func TestCooldown(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
start := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
|
||||||
|
fx := &usdPerEUR{rate: 1.25}
|
||||||
|
e := NewEngine(30*time.Minute, fx, nil)
|
||||||
|
it := metro(130)
|
||||||
|
|
||||||
|
steps := []struct {
|
||||||
|
name string
|
||||||
|
after time.Duration
|
||||||
|
report *plugin.Report
|
||||||
|
fires bool
|
||||||
|
prev string // the previous price a price-drop alert shows
|
||||||
|
} {
|
||||||
|
{"first alert", 0, page(129.99, "EUR", plugin.SellerFirstParty), true, ""},
|
||||||
|
{"same price in cooldown", 5 * time.Minute, page(129.99, "EUR", plugin.SellerFirstParty), false, ""},
|
||||||
|
{"higher price in cooldown", 10 * time.Minute, page(129.995, "EUR", plugin.SellerFulfilled), false, ""},
|
||||||
|
{"price drop in cooldown", 15 * time.Minute, page(119.99, "EUR", plugin.SellerFirstParty), true, "129.99 EUR"},
|
||||||
|
{"drop restarted the cooldown", 40 * time.Minute, page(119.99, "EUR", plugin.SellerFirstParty), false, ""},
|
||||||
|
{"cooldown over", 45 * time.Minute, page(125, "EUR", plugin.SellerFirstParty), true, ""},
|
||||||
|
// 140 USD is 112 EUR, cheaper than 125 EUR.
|
||||||
|
{"cheaper in another currency", 50 * time.Minute, page(140, "USD", plugin.SellerFirstParty), true, "125.00 EUR"},
|
||||||
|
// Same currency as the last alert: compared in USD, so the euro
|
||||||
|
// strengthening to 1.30 USD does not make it a drop to 107.69 EUR.
|
||||||
|
{"same USD price, new rate", 55 * time.Minute, page(140, "USD", plugin.SellerFirstParty), false, ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, st := range steps {
|
||||||
|
if strings.HasSuffix(st.name, "new rate") { fx.rate = 1.30 }
|
||||||
|
|
||||||
|
d, err := e.Consider(ctx, it, st.report, start.Add(st.after))
|
||||||
|
if err != nil { t.Fatalf("%s: %v", st.name, err) }
|
||||||
|
|
||||||
|
a := d.Alert
|
||||||
|
if fired := a != nil; fired != st.fires { t.Errorf("%s: fired = %v, want %v (%s)", st.name, fired, st.fires, d.Reason) }
|
||||||
|
if !d.Qualifies { t.Errorf("%s: does not qualify: %s", st.name, d.Reason) }
|
||||||
|
if a == nil { continue }
|
||||||
|
|
||||||
|
prev := ""
|
||||||
|
if a.PreviousPrice != nil { prev = Money(*a.PreviousPrice, a.PreviousCurrency) }
|
||||||
|
if prev != st.prev { t.Errorf("%s: previous price %q, want %q", st.name, prev, st.prev) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQualify(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
noPrice := page(0, "EUR", plugin.SellerFirstParty)
|
||||||
|
noPrice.Result.Price = nil
|
||||||
|
|
||||||
|
withMargin := metro(120)
|
||||||
|
withMargin.FXMargin = 0.1
|
||||||
|
|
||||||
|
anySeller := metro(130)
|
||||||
|
anySeller.Seller = config.SellerAny
|
||||||
|
|
||||||
|
noLimit := config.Item{Name: "metro", Currency: "EUR", Seller: config.SellerAny}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
item config.Item
|
||||||
|
report *plugin.Report
|
||||||
|
fx usdPerEUR
|
||||||
|
want string // "fire", "error" or part of the reason
|
||||||
|
} {
|
||||||
|
{"at max_price", metro(129.99), page(129.99, "EUR", plugin.SellerFirstParty), usdPerEUR{}, "fire"},
|
||||||
|
{"above max_price", metro(129.99), page(130, "EUR", plugin.SellerFirstParty), usdPerEUR{}, "above max_price"},
|
||||||
|
{"marketplace seller", metro(130), page(99, "EUR", plugin.SellerThirdParty), usdPerEUR{}, "seller is third_party"},
|
||||||
|
{"unknown seller, any", anySeller, page(99, "EUR", plugin.SellerUnknown), usdPerEUR{}, "fire"},
|
||||||
|
{"no price", metro(130), noPrice, usdPerEUR{}, "no price"},
|
||||||
|
// 125 USD is 100 EUR, 110 EUR with the margin.
|
||||||
|
{"converted within", withMargin, page(125, "USD", plugin.SellerFirstParty), usdPerEUR{rate: 1.25}, "fire"},
|
||||||
|
// 140 USD is 112 EUR, 123.20 EUR with the margin.
|
||||||
|
{"margin tips it over", withMargin, page(140, "USD", plugin.SellerFirstParty), usdPerEUR{rate: 1.25}, "with fx_margin is above"},
|
||||||
|
{"no rates", metro(130), page(99, "USD", plugin.SellerFirstParty), usdPerEUR{down: true}, "error"},
|
||||||
|
{"no rates, no max_price", noLimit, page(99, "USD", plugin.SellerFirstParty), usdPerEUR{down: true}, "fire"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases {
|
||||||
|
d, err := NewEngine(time.Hour, c.fx, nil).Consider(ctx, c.item, c.report, now)
|
||||||
|
a, why := d.Alert, d.Reason
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case c.want == "fire" && a == nil:
|
||||||
|
t.Errorf("%s: did not fire: %s %v", c.name, why, err)
|
||||||
|
case c.want == "error" && err == nil:
|
||||||
|
t.Errorf("%s: no error (fired: %v, reason %q)", c.name, a != nil, why)
|
||||||
|
case c.want != "fire" && c.want != "error" && !strings.Contains(why, c.want):
|
||||||
|
t.Errorf("%s: reason %q, want %q (fired: %v, err %v)", c.name, why, c.want, a != nil, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
// Package chrome runs a real Chrome for the bot checks tls-client cannot
|
||||||
|
// pass: headless for JavaScript challenges, which clear on their own, and in
|
||||||
|
// a visible window for the ones a person has to solve. Nothing here solves a
|
||||||
|
// captcha.
|
||||||
|
//
|
||||||
|
// Chrome claims the same user agent and client hints as tls-client, so the
|
||||||
|
// cookies it obtains stay valid for the requests that follow.
|
||||||
|
package chrome
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
stdhttp "net/http"
|
||||||
|
"net/url"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-rod/rod"
|
||||||
|
"github.com/go-rod/rod/lib/launcher"
|
||||||
|
"github.com/go-rod/rod/lib/proto"
|
||||||
|
"github.com/go-rod/stealth"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// ChallengeTimeout is how long headless Chrome waits for a bot check to
|
||||||
|
// clear.
|
||||||
|
ChallengeTimeout = 30 * time.Second
|
||||||
|
// HumanTimeout is how long a visible window waits for the user.
|
||||||
|
HumanTimeout = 10 * time.Minute
|
||||||
|
|
||||||
|
poll = time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrClosed means the user closed the window before the bot check cleared.
|
||||||
|
var ErrClosed = errors.New("the browser window was closed")
|
||||||
|
|
||||||
|
// Chrome launches a fresh Chrome per visit, with a throwaway profile that
|
||||||
|
// gets the cookies of the URL's host from the jar. It is safe for concurrent
|
||||||
|
// use; visits run one at a time.
|
||||||
|
type Chrome struct {
|
||||||
|
browser fetch.Browser
|
||||||
|
jar *fetch.Jar
|
||||||
|
logger *slog.Logger
|
||||||
|
// 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, humanTimeout: HumanTimeout}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch loads rawURL in headless Chrome and gives a bot check up to
|
||||||
|
// ChallengeTimeout to clear. The page it ends on is returned as a response,
|
||||||
|
// which is still a Challenge if the check did not clear. Chrome's cookies go
|
||||||
|
// into the jar either way.
|
||||||
|
func (c *Chrome) Fetch(ctx context.Context, rawURL string) (*fetch.Response, error) {
|
||||||
|
return c.visit(ctx, rawURL, true, c.challengeTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solve opens rawURL in a visible window for the user to pass a bot check,
|
||||||
|
// 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, 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
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Chrome) visit(ctx context.Context, rawURL string, headless bool, timeout time.Duration) (*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, headless)
|
||||||
|
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 }
|
||||||
|
_ = page.Timeout(timeout).WaitLoad()
|
||||||
|
|
||||||
|
deadline := time.Now().Add(timeout)
|
||||||
|
|
||||||
|
for {
|
||||||
|
resp, err := snapshot(page, rawURL, doc)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case err != nil && ctx.Err() != nil:
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case err != nil && !headless && !alive(b):
|
||||||
|
return nil, ErrClosed
|
||||||
|
case err != nil && headless:
|
||||||
|
return nil, err
|
||||||
|
case err == nil && (resp.Verdict != fetch.Challenge || time.Now().After(deadline)):
|
||||||
|
c.keepCookies(page, rawURL, host)
|
||||||
|
resp.Elapsed = time.Since(start)
|
||||||
|
return resp, nil
|
||||||
|
default:
|
||||||
|
// A page that is navigating has no document to read for a
|
||||||
|
// moment, and the bot check may still be running.
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case <-time.After(poll):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
if c.bin != "" { return c.bin, nil }
|
||||||
|
|
||||||
|
if bin, ok := launcher.LookPath(); ok {
|
||||||
|
c.bin = bin
|
||||||
|
return bin, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c.logger.Info("no Chrome, Chromium or Edge found, downloading Chromium")
|
||||||
|
|
||||||
|
bin, err := launcher.NewBrowser().Get()
|
||||||
|
if err != nil { return "", fmt.Errorf("no Chrome found and downloading Chromium failed: %w", err) }
|
||||||
|
|
||||||
|
c.bin = bin
|
||||||
|
return bin, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// identity makes Chrome claim the browser tls-client claims to be.
|
||||||
|
func (c *Chrome) identity(host string) proto.NetworkSetUserAgentOverride {
|
||||||
|
var brands, full []*proto.EmulationUserAgentBrandVersion
|
||||||
|
for _, br := range c.browser.Brands() {
|
||||||
|
brands = append(brands, &proto.EmulationUserAgentBrandVersion{Brand: br.Name, Version: br.Version})
|
||||||
|
full = append(full, &proto.EmulationUserAgentBrandVersion{Brand: br.Name, Version: br.Version + ".0.0.0"})
|
||||||
|
}
|
||||||
|
|
||||||
|
arch := "x86"
|
||||||
|
if runtime.GOARCH == "arm64" { arch = "arm" }
|
||||||
|
|
||||||
|
return proto.NetworkSetUserAgentOverride{
|
||||||
|
UserAgent: c.browser.UserAgent,
|
||||||
|
AcceptLanguage: fetch.AcceptLanguage(host),
|
||||||
|
Platform: navigatorPlatform(c.browser.Platform),
|
||||||
|
UserAgentMetadata: &proto.EmulationUserAgentMetadata{
|
||||||
|
Brands: brands,
|
||||||
|
FullVersionList: full,
|
||||||
|
Platform: c.browser.Platform,
|
||||||
|
Architecture: arch,
|
||||||
|
Bitness: "64",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func navigatorPlatform(platform string) string {
|
||||||
|
switch platform {
|
||||||
|
case "Windows":
|
||||||
|
return "Win32"
|
||||||
|
case "macOS":
|
||||||
|
return "MacIntel"
|
||||||
|
default:
|
||||||
|
return "Linux x86_64"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// keepCookies copies Chrome's cookies for rawURL into the jar.
|
||||||
|
func (c *Chrome) keepCookies(page *rod.Page, rawURL, host string) {
|
||||||
|
cookies, err := page.Cookies([]string{rawURL})
|
||||||
|
if err != nil {
|
||||||
|
c.logger.Warn("reading Chrome's cookies failed", "url", rawURL, "err", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
out := make([]fetch.Cookie, 0, len(cookies))
|
||||||
|
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))
|
||||||
|
|
||||||
|
for _, ck := range cookies {
|
||||||
|
p := &proto.NetworkCookieParam{Name: ck.Name, Value: ck.Value, Path: ck.Path, Secure: ck.Secure, HTTPOnly: ck.HTTPOnly}
|
||||||
|
|
||||||
|
// Chrome sets a cookie without a domain as host-only for the URL.
|
||||||
|
if ck.HostOnly { p.URL = scheme + "://" + ck.Domain + ck.Path } else { p.Domain = "." + ck.Domain }
|
||||||
|
if !ck.Expires.IsZero() { p.Expires = proto.TimeSinceEpoch(ck.Expires.Unix()) }
|
||||||
|
|
||||||
|
out = append(out, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// document is the status and headers of the page's latest document.
|
||||||
|
type document struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
status int
|
||||||
|
header stdhttp.Header
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *document) set(r *proto.NetworkResponse) {
|
||||||
|
h := stdhttp.Header{}
|
||||||
|
for k, v := range r.Headers { h.Set(k, v.Str()) }
|
||||||
|
|
||||||
|
d.mu.Lock()
|
||||||
|
defer d.mu.Unlock()
|
||||||
|
|
||||||
|
d.status, d.header = r.Status, h
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *document) get() (int, stdhttp.Header) {
|
||||||
|
d.mu.Lock()
|
||||||
|
defer d.mu.Unlock()
|
||||||
|
|
||||||
|
if d.status == 0 { return stdhttp.StatusOK, nil }
|
||||||
|
|
||||||
|
return d.status, d.header
|
||||||
|
}
|
||||||
|
|
||||||
|
// snapshot classifies the page as it is now.
|
||||||
|
func snapshot(page *rod.Page, rawURL string, doc *document) (*fetch.Response, error) {
|
||||||
|
html, err := page.HTML()
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
info, err := page.Info()
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
status, header := doc.get()
|
||||||
|
return fetch.NewResponse(rawURL, info.URL, status, header, []byte(html)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
pages, err := b.Pages()
|
||||||
|
return err == nil && len(pages) > 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package chrome
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
fhttp "github.com/bogdanfinn/fhttp"
|
||||||
|
"github.com/go-rod/rod/lib/launcher"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
)
|
||||||
|
|
||||||
|
// challengeServer answers /item with a JavaScript challenge until the
|
||||||
|
// browser has run it, which sets a clearance cookie, and /stuck with one
|
||||||
|
// that never clears. Past the challenge it shows what the browser sent.
|
||||||
|
func challengeServer() *httptest.Server {
|
||||||
|
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if _, err := r.Cookie("clearance"); err != nil || r.URL.Path == "/stuck" {
|
||||||
|
w.WriteHeader(http.StatusServiceUnavailable)
|
||||||
|
_, _ = io.WriteString(w, `<html><head><title>Just a moment...</title><script>window._cf_chl_opt = {};
|
||||||
|
if (location.pathname === "/item") { document.cookie = "clearance=ok; path=/"; setTimeout(() => location.reload(), 300) }
|
||||||
|
</script></head><body>Checking your browser</body></html>`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
session := ""
|
||||||
|
if ck, err := r.Cookie("session"); err == nil { session = ck.Value }
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintf(w, "<html><body><p id=ua>%s</p><p id=ch>%s</p><p id=session>%s</p></body></html>",
|
||||||
|
r.UserAgent(), r.Header.Get("Sec-Ch-Ua"), session)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func newChrome(t *testing.T) (*Chrome, *fetch.Jar) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
if testing.Short() { t.Skip("starts Chrome") }
|
||||||
|
if _, ok := launcher.LookPath(); !ok { t.Skip("no Chrome, Chromium or Edge installed") }
|
||||||
|
|
||||||
|
jar := fetch.NewJar()
|
||||||
|
c := New(fetch.DefaultBrowser(), jar, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||||
|
c.challengeTimeout = 5 * time.Second
|
||||||
|
|
||||||
|
return c, jar
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchClearsChallenge(t *testing.T) {
|
||||||
|
c, jar := newChrome(t)
|
||||||
|
srv := challengeServer()
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
u, _ := url.Parse(srv.URL + "/item")
|
||||||
|
jar.SetCookies(u, []*fhttp.Cookie{{Name: "session", Value: "from-the-jar", Path: "/"}})
|
||||||
|
|
||||||
|
resp, err := c.Fetch(context.Background(), u.String())
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
body := string(resp.Body)
|
||||||
|
browser := fetch.DefaultBrowser()
|
||||||
|
|
||||||
|
if resp.Verdict != fetch.OK { t.Fatalf("verdict %s, want ok: %s", resp.Verdict, body) }
|
||||||
|
if !strings.Contains(body, browser.UserAgent) { t.Errorf("Chrome did not claim the user agent of tls-client: %s", body) }
|
||||||
|
if !strings.Contains(body, fmt.Sprintf(`"Chromium";v="%d"`, browser.Major)) { t.Errorf("Chrome did not claim the client hints of tls-client: %s", body) }
|
||||||
|
if !strings.Contains(body, "from-the-jar") { t.Errorf("Chrome did not send the jar's cookies: %s", body) }
|
||||||
|
|
||||||
|
got := ""
|
||||||
|
for _, ck := range jar.Cookies(u) { got += ck.Name + "=" + ck.Value + " " }
|
||||||
|
if !strings.Contains(got, "clearance=ok") { t.Errorf("the clearance cookie did not reach the jar: %s", got) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchGivesUp(t *testing.T) {
|
||||||
|
c, _ := newChrome(t)
|
||||||
|
srv := challengeServer()
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
resp, err := c.Fetch(context.Background(), srv.URL+"/stuck")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
if resp.Verdict != fetch.Challenge { t.Errorf("verdict %s, want challenge", resp.Verdict) }
|
||||||
|
if d := time.Since(start); d > 20*time.Second { t.Errorf("gave up after %s", d) }
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
srv := challengeServer()
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
client, err := fetch.New(fetch.Options{Limiter: noLimit{}, Jar: jar})
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
p := &Pipeline{Client: client, Chrome: c, Limiter: noLimit{}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
|
||||||
|
|
||||||
|
for path, want := range map[string]fetch.Verdict{"/item": fetch.OK, "/stuck": fetch.NeedsHuman} {
|
||||||
|
resp, err := p.Get(context.Background(), srv.URL+path)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
if resp.Verdict != want { t.Errorf("%s: verdict %s, want %s", path, resp.Verdict, want) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Chrome's clearance cookie lets tls-client through on its own now.
|
||||||
|
resp, err := client.Get(context.Background(), srv.URL+"/item")
|
||||||
|
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, `<html><body><script>document.cookie = "later=1; path=/"</script>Signed in</body></html>`)
|
||||||
|
}))
|
||||||
|
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, `<html><body><form method="post" action="/wrong"><input type="hidden" name="id" value="X">
|
||||||
|
<input type="submit" id="add" name="submit.add" value="Add" formaction="/cart"></form></body></html>`)
|
||||||
|
case "/cart":
|
||||||
|
_ = r.ParseForm()
|
||||||
|
_, _ = fmt.Fprintf(w, "<html><body><p id=added>%s %s</p></body></html>", 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) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package chrome
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// only on failure: tls-client first, then headless Chrome when a bot check
|
||||||
|
// answers. A bot check Chrome cannot clear either comes back as
|
||||||
|
// fetch.NeedsHuman.
|
||||||
|
type Pipeline struct {
|
||||||
|
Client *fetch.Client
|
||||||
|
// Chrome may be nil, which leaves bot checks as they are.
|
||||||
|
Chrome *Chrome
|
||||||
|
Limiter Limiter
|
||||||
|
Logger *slog.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pipeline) Get(ctx context.Context, rawURL string) (*fetch.Response, error) {
|
||||||
|
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)
|
||||||
|
|
||||||
|
if err := wait(); err != nil { return nil, err }
|
||||||
|
|
||||||
|
cr, err := p.Chrome.Fetch(ctx, rawURL)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case ctx.Err() != nil:
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case err != nil:
|
||||||
|
p.Logger.Warn("headless Chrome failed", "url", rawURL, "err", err)
|
||||||
|
return resp, nil
|
||||||
|
case cr.Verdict == fetch.Challenge:
|
||||||
|
cr.Verdict = fetch.NeedsHuman
|
||||||
|
default:
|
||||||
|
p.Logger.Info("headless Chrome cleared the bot check", "url", rawURL, "challenge", resp.Challenge)
|
||||||
|
}
|
||||||
|
|
||||||
|
return cr, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
// Package config loads and validates dibs.toml.
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pelletier/go-toml/v2"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MinInterval is the shortest allowed polling interval per URL. The
|
||||||
|
// scheduler enforces it too, whatever the config says.
|
||||||
|
const MinInterval = ratelimit.URLFloor
|
||||||
|
|
||||||
|
// MaxCooldown is the longest allowed cooldown. The state file forgets alerts
|
||||||
|
// after it.
|
||||||
|
const MaxCooldown = 7 * 24 * time.Hour
|
||||||
|
|
||||||
|
const (
|
||||||
|
// The seller policies accept offers sold by the shop itself, offers it
|
||||||
|
// sells or only ships (such as Fulfilled by Amazon), or any offer.
|
||||||
|
SellerFirstParty = "first_party"
|
||||||
|
SellerFulfilled = "fulfilled"
|
||||||
|
SellerAny = "any"
|
||||||
|
|
||||||
|
CartModeDeeplink = "deeplink"
|
||||||
|
CartModeSession = "session"
|
||||||
|
|
||||||
|
FormatDiscord = "discord"
|
||||||
|
FormatNtfy = "ntfy"
|
||||||
|
FormatJSON = "json"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DefaultInterval = 3 * time.Minute
|
||||||
|
DefaultCooldown = 30 * time.Minute
|
||||||
|
DefaultSandboxTimeout = 2 * time.Second
|
||||||
|
DefaultSessionTimeout = 5 * time.Minute
|
||||||
|
DefaultMemoryMB = 64
|
||||||
|
DefaultCallStack = 200
|
||||||
|
|
||||||
|
// DefaultSeller also accepts marketplace offers the shop ships (such as
|
||||||
|
// Fulfilled by Amazon), which is how many listings are sold.
|
||||||
|
DefaultSeller = SellerFulfilled
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Items []Item `toml:"item"`
|
||||||
|
Accounts map[string]Account `toml:"accounts"`
|
||||||
|
Notify Notify `toml:"notify"`
|
||||||
|
// Plugins maps plugin names to files. Load makes the paths absolute.
|
||||||
|
Plugins map[string]string `toml:"plugins"`
|
||||||
|
Sandbox Sandbox `toml:"sandbox"`
|
||||||
|
|
||||||
|
// Path is the absolute path of the loaded file.
|
||||||
|
Path string `toml:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Item struct {
|
||||||
|
Name string `toml:"name"`
|
||||||
|
Shop string `toml:"shop"`
|
||||||
|
URLs []string `toml:"urls"`
|
||||||
|
MaxPrice *float64 `toml:"max_price"`
|
||||||
|
Currency string `toml:"currency"`
|
||||||
|
// FXMargin is added to a converted price before it is compared with
|
||||||
|
// MaxPrice, to cover import fees and card exchange rates. 0.1 means 10%.
|
||||||
|
FXMargin float64 `toml:"fx_margin"`
|
||||||
|
Seller string `toml:"seller"`
|
||||||
|
Interval Duration `toml:"interval"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Account struct {
|
||||||
|
Username string `toml:"username"`
|
||||||
|
PasswordEnv string `toml:"password_env"`
|
||||||
|
CartMode string `toml:"cart_mode"`
|
||||||
|
LoginURL string `toml:"login_url"`
|
||||||
|
CartURL string `toml:"cart_url"`
|
||||||
|
TwoFA bool `toml:"twofa"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Notify struct {
|
||||||
|
Webhooks []Webhook `toml:"webhooks"`
|
||||||
|
Desktop bool `toml:"desktop"`
|
||||||
|
Cooldown Duration `toml:"cooldown"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Webhook struct {
|
||||||
|
URL string `toml:"url"`
|
||||||
|
Format string `toml:"format"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Sandbox struct {
|
||||||
|
// Timeout applies to matches, parse and cart_link.
|
||||||
|
Timeout Duration `toml:"timeout"`
|
||||||
|
// SessionTimeout applies to login and add_to_cart, which wait on the
|
||||||
|
// network and on the user typing 2FA codes.
|
||||||
|
SessionTimeout Duration `toml:"session_timeout"`
|
||||||
|
// MemoryMB is the approximate heap growth one call may cause before it is
|
||||||
|
// cancelled.
|
||||||
|
MemoryMB int `toml:"memory_mb"`
|
||||||
|
// CallStack is the maximum Lua call depth.
|
||||||
|
CallStack int `toml:"call_stack"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Duration is a time.Duration written as a string such as "3m" or "90s".
|
||||||
|
type Duration struct {
|
||||||
|
time.Duration
|
||||||
|
set bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Duration) UnmarshalText(b []byte) error {
|
||||||
|
v, err := time.ParseDuration(string(b))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf(`invalid duration %q: use a number with a unit, such as "90s", "3m" or "1h30m"`, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
d.Duration, d.set = v, true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d Duration) MarshalText() ([]byte, error) {
|
||||||
|
return []byte(d.String()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsSet reports whether the value came from the config file.
|
||||||
|
func (d Duration) IsSet() bool { return d.set }
|
||||||
|
|
||||||
|
// sellerRanks orders the sellers a plugin reports, from most to least
|
||||||
|
// trusted. The values match plugin.Seller*.
|
||||||
|
var sellerRanks = map[string]int{
|
||||||
|
"first_party": 0,
|
||||||
|
"fulfilled": 1,
|
||||||
|
"third_party": 2,
|
||||||
|
"unknown": 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
// policyRanks is the least trusted seller each policy still accepts.
|
||||||
|
var policyRanks = map[string]int{
|
||||||
|
SellerFirstParty: 0,
|
||||||
|
SellerFulfilled: 1,
|
||||||
|
SellerAny: 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
// AcceptsSeller reports whether an offer from seller, as a plugin reports it,
|
||||||
|
// passes the item's seller policy. The policies are ordered: "fulfilled"
|
||||||
|
// accepts everything "first_party" does, and "any" accepts every seller.
|
||||||
|
func (it Item) AcceptsSeller(seller string) bool {
|
||||||
|
rank, ok := sellerRanks[seller]
|
||||||
|
if !ok { return false }
|
||||||
|
|
||||||
|
return rank <= policyRanks[it.Seller]
|
||||||
|
}
|
||||||
|
|
||||||
|
type Options struct {
|
||||||
|
// Builtins are the names of the embedded plugins.
|
||||||
|
Builtins []string
|
||||||
|
// LookupEnv resolves password_env. Defaults to os.LookupEnv.
|
||||||
|
LookupEnv func(string) (string, bool)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultPath returns dibs.toml in the user config dir.
|
||||||
|
func DefaultPath() (string, error) {
|
||||||
|
dir, err := os.UserConfigDir()
|
||||||
|
if err != nil { return "", err }
|
||||||
|
return filepath.Join(dir, "dibs", "dibs.toml"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load returns every problem it finds at once, as Errors.
|
||||||
|
func Load(path string, opts Options) (*Config, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
abs, err := filepath.Abs(path)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
if opts.LookupEnv == nil {
|
||||||
|
opts.LookupEnv = os.LookupEnv
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := &Config{
|
||||||
|
Path: abs,
|
||||||
|
Notify: Notify{
|
||||||
|
Desktop: true,
|
||||||
|
Cooldown: Duration{Duration: DefaultCooldown},
|
||||||
|
},
|
||||||
|
Sandbox: Sandbox{
|
||||||
|
Timeout: Duration{Duration: DefaultSandboxTimeout},
|
||||||
|
SessionTimeout: Duration{Duration: DefaultSessionTimeout},
|
||||||
|
MemoryMB: DefaultMemoryMB,
|
||||||
|
CallStack: DefaultCallStack,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
v := &validator{file: path, pos: indexPositions(data)}
|
||||||
|
|
||||||
|
dec := toml.NewDecoder(bytes.NewReader(data))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
err = dec.Decode(cfg)
|
||||||
|
|
||||||
|
var strict *toml.StrictMissingError
|
||||||
|
var decErr *toml.DecodeError
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
case errors.As(err, &strict):
|
||||||
|
// The rest of the document was decoded, so validation goes on.
|
||||||
|
for _, e := range strict.Errors {
|
||||||
|
msg := "unknown key"
|
||||||
|
if k := e.Key(); len(k) > 0 && k[len(k)-1] == "quantity" {
|
||||||
|
msg = "unknown key: quantity is always 1 and cannot be configured"
|
||||||
|
}
|
||||||
|
v.decodeError(&e, msg)
|
||||||
|
}
|
||||||
|
case errors.As(err, &decErr):
|
||||||
|
v.decodeError(decErr, "")
|
||||||
|
return nil, v.errs
|
||||||
|
default:
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
v.validate(cfg, opts)
|
||||||
|
if len(v.errs) > 0 { return nil, v.errs }
|
||||||
|
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,367 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const fullConfig = `
|
||||||
|
[[item]]
|
||||||
|
name = "Metro 2039 CE"
|
||||||
|
shop = "amazon"
|
||||||
|
urls = ["https://www.amazon.de/dp/B0HMX2FSTF", "https://www.amazon.co.uk/dp/B0HM497GJJ"]
|
||||||
|
max_price = 129.99
|
||||||
|
currency = "eur"
|
||||||
|
fx_margin = 0.1
|
||||||
|
seller = "any"
|
||||||
|
interval = "5m"
|
||||||
|
|
||||||
|
[[item]]
|
||||||
|
name = "Console"
|
||||||
|
shop = "mediamarkt"
|
||||||
|
seller = "fulfilled"
|
||||||
|
urls = ["https://www.mediamarkt.de/de/product/_console-123.html"]
|
||||||
|
|
||||||
|
[accounts.amazon]
|
||||||
|
username = "me@example.com"
|
||||||
|
password_env = "DIBS_AMAZON_PASS"
|
||||||
|
cart_mode = "session"
|
||||||
|
twofa = true
|
||||||
|
|
||||||
|
[notify]
|
||||||
|
webhooks = [
|
||||||
|
{ url = "https://discord.com/api/webhooks/1/abc", format = "discord" },
|
||||||
|
{ url = "https://ntfy.sh/my-topic", format = "ntfy" },
|
||||||
|
]
|
||||||
|
desktop = false
|
||||||
|
cooldown = "1h"
|
||||||
|
|
||||||
|
[plugins]
|
||||||
|
mediamarkt = "plugins/mediamarkt.lua"
|
||||||
|
|
||||||
|
[sandbox]
|
||||||
|
timeout = "500ms"
|
||||||
|
session_timeout = "2m"
|
||||||
|
memory_mb = 32
|
||||||
|
call_stack = 100
|
||||||
|
`
|
||||||
|
|
||||||
|
// load writes doc as dibs.toml in a temp dir, together with an empty
|
||||||
|
// plugins/mediamarkt.lua, and loads it.
|
||||||
|
func load(t *testing.T, doc string, env map[string]string) (*Config, error) {
|
||||||
|
t.Helper()
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.MkdirAll(filepath.Join(dir, "plugins"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "plugins", "mediamarkt.lua"), nil, 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
path := filepath.Join(dir, "dibs.toml")
|
||||||
|
if err := os.WriteFile(path, []byte(doc), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return Load(path, Options{
|
||||||
|
Builtins: []string{"amazon"},
|
||||||
|
LookupEnv: func(k string) (string, bool) {
|
||||||
|
v, ok := env[k]
|
||||||
|
return v, ok
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// errs asserts that err is Errors and returns it.
|
||||||
|
func errs(t *testing.T, err error) Errors {
|
||||||
|
t.Helper()
|
||||||
|
var es Errors
|
||||||
|
if !errors.As(err, &es) {
|
||||||
|
t.Fatalf("want config.Errors, got %T: %v", err, err)
|
||||||
|
}
|
||||||
|
return es
|
||||||
|
}
|
||||||
|
|
||||||
|
// wantErr asserts that es has an error for key on line whose message
|
||||||
|
// contains msg.
|
||||||
|
func wantErr(t *testing.T, es Errors, key string, line int, msg string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, e := range es {
|
||||||
|
if e.Key == key && e.Line == line && strings.Contains(e.Msg, msg) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Errorf("no error for %s on line %d containing %q; got:\n%v", key, line, msg, es)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadFull(t *testing.T) {
|
||||||
|
cfg, err := load(t, fullConfig, map[string]string{"DIBS_AMAZON_PASS": "secret"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(cfg.Items) != 2 {
|
||||||
|
t.Fatalf("items: got %d, want 2", len(cfg.Items))
|
||||||
|
}
|
||||||
|
|
||||||
|
if s := cfg.Items[1].Seller; s != SellerFulfilled { t.Errorf("item[1].seller: got %q, want fulfilled", s) }
|
||||||
|
it := cfg.Items[0]
|
||||||
|
if it.Currency != "EUR" {
|
||||||
|
t.Errorf("currency: got %q, want it uppercased to EUR", it.Currency)
|
||||||
|
}
|
||||||
|
if it.MaxPrice == nil || *it.MaxPrice != 129.99 {
|
||||||
|
t.Errorf("max_price: got %v", it.MaxPrice)
|
||||||
|
}
|
||||||
|
if it.Seller != SellerAny || it.Interval.Duration != 5*time.Minute || it.FXMargin != 0.1 {
|
||||||
|
t.Errorf("item[0]: got %+v", it)
|
||||||
|
}
|
||||||
|
|
||||||
|
if acc := cfg.Accounts["amazon"]; acc.CartMode != CartModeSession || !acc.TwoFA {
|
||||||
|
t.Errorf("account: got %+v", acc)
|
||||||
|
}
|
||||||
|
if n := cfg.Notify; n.Desktop || n.Cooldown.Duration != time.Hour || len(n.Webhooks) != 2 {
|
||||||
|
t.Errorf("notify: got %+v", n)
|
||||||
|
}
|
||||||
|
want := filepath.Join(filepath.Dir(cfg.Path), "plugins", "mediamarkt.lua")
|
||||||
|
if got := cfg.Plugins["mediamarkt"]; got != want {
|
||||||
|
t.Errorf("plugin path: got %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
s := cfg.Sandbox
|
||||||
|
if s.Timeout.Duration != 500*time.Millisecond || s.SessionTimeout.Duration != 2*time.Minute ||
|
||||||
|
s.MemoryMB != 32 || s.CallStack != 100 {
|
||||||
|
t.Errorf("sandbox: got %+v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadDefaults(t *testing.T) {
|
||||||
|
cfg, err := load(t, `
|
||||||
|
[[item]]
|
||||||
|
name = "x"
|
||||||
|
shop = "amazon"
|
||||||
|
urls = ["https://www.amazon.de/dp/B0HMX2FSTF"]
|
||||||
|
|
||||||
|
[accounts.amazon]
|
||||||
|
`, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
it := cfg.Items[0]
|
||||||
|
if it.Seller != SellerFulfilled || it.Interval.Duration != DefaultInterval || it.MaxPrice != nil {
|
||||||
|
t.Errorf("item defaults: got %+v", it)
|
||||||
|
}
|
||||||
|
if cfg.Accounts["amazon"].CartMode != CartModeDeeplink {
|
||||||
|
t.Errorf("cart_mode default: got %q", cfg.Accounts["amazon"].CartMode)
|
||||||
|
}
|
||||||
|
if !cfg.Notify.Desktop || cfg.Notify.Cooldown.Duration != DefaultCooldown {
|
||||||
|
t.Errorf("notify defaults: got %+v", cfg.Notify)
|
||||||
|
}
|
||||||
|
s := cfg.Sandbox
|
||||||
|
if s.Timeout.Duration != DefaultSandboxTimeout || s.SessionTimeout.Duration != DefaultSessionTimeout ||
|
||||||
|
s.MemoryMB != DefaultMemoryMB || s.CallStack != DefaultCallStack {
|
||||||
|
t.Errorf("sandbox defaults: got %+v", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnknownKeys(t *testing.T) {
|
||||||
|
_, err := load(t, `
|
||||||
|
[[item]]
|
||||||
|
name = "x"
|
||||||
|
shop = "amazon"
|
||||||
|
urls = ["https://www.amazon.de/dp/B0HMX2FSTF"]
|
||||||
|
quantity = 2
|
||||||
|
|
||||||
|
[notfy]
|
||||||
|
desktop = true
|
||||||
|
`, nil)
|
||||||
|
es := errs(t, err)
|
||||||
|
wantErr(t, es, "item[0].quantity", 6, "quantity is always 1")
|
||||||
|
wantErr(t, es, "notfy", 8, "unknown key")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnknownKeyStillValidatesRest(t *testing.T) {
|
||||||
|
_, err := load(t, `
|
||||||
|
[[item]]
|
||||||
|
name = "x"
|
||||||
|
shop = "amazon"
|
||||||
|
urls = ["https://www.amazon.de/dp/B0HMX2FSTF"]
|
||||||
|
interval = "10s"
|
||||||
|
typo = 1
|
||||||
|
`, nil)
|
||||||
|
es := errs(t, err)
|
||||||
|
if len(es) != 2 {
|
||||||
|
t.Errorf("want 2 errors, got:\n%v", es)
|
||||||
|
}
|
||||||
|
wantErr(t, es, "item[0].interval", 6, "at least 1m0s")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeErrors(t *testing.T) {
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
doc string
|
||||||
|
key string
|
||||||
|
line int
|
||||||
|
msg string
|
||||||
|
}{
|
||||||
|
"wrong type": {"[[item]]\nname = \"x\"\nmax_price = \"cheap\"\n", "item[0].max_price", 3, "expected a number, got a TOML string"},
|
||||||
|
"wrong element": {"[[item]]\nname = \"x\"\nurls = [1]\n", "item[0].urls[0]", 3, "expected a string, got a TOML integer"},
|
||||||
|
"bad duration": {"[[item]]\nname = \"x\"\ninterval = \"3x\"\n", "item[0].interval", 3, "invalid duration"},
|
||||||
|
"syntax": {"[[item]]\nname = \n", "", 2, ""},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
_, err := load(t, tc.doc, nil)
|
||||||
|
es := errs(t, err)
|
||||||
|
if len(es) != 1 {
|
||||||
|
t.Fatalf("want one error, got:\n%v", es)
|
||||||
|
}
|
||||||
|
if tc.key != "" {
|
||||||
|
wantErr(t, es, tc.key, tc.line, tc.msg)
|
||||||
|
} else if es[0].Line != tc.line {
|
||||||
|
t.Errorf("want error on line %d, got:\n%v", tc.line, es)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidationErrors(t *testing.T) {
|
||||||
|
_, err := load(t, `
|
||||||
|
[[item]]
|
||||||
|
shop = "amazn"
|
||||||
|
urls = ["ftp://example.com/x", "https://www.amazon.de/dp/B0HMX2FSTF"]
|
||||||
|
max_price = -5
|
||||||
|
currency = "EURO"
|
||||||
|
seller = "amazon"
|
||||||
|
interval = "30s"
|
||||||
|
|
||||||
|
[[item]]
|
||||||
|
name = "dup"
|
||||||
|
shop = "amazon"
|
||||||
|
urls = ["https://www.amazon.de/dp/B0HMX2FSTF"]
|
||||||
|
fx_margin = 0.2
|
||||||
|
|
||||||
|
[[item]]
|
||||||
|
name = "dup"
|
||||||
|
shop = "amazon"
|
||||||
|
urls = []
|
||||||
|
|
||||||
|
[accounts.amazon]
|
||||||
|
password_env = "DIBS_MISSING"
|
||||||
|
cart_mode = "auto"
|
||||||
|
login_url = "/signin"
|
||||||
|
|
||||||
|
[accounts.ebay]
|
||||||
|
|
||||||
|
[notify]
|
||||||
|
webhooks = [
|
||||||
|
{ url = "https://ntfy.sh/a", format = "ntfy" },
|
||||||
|
{ url = "https://example.com/hook", format = "slack" },
|
||||||
|
{ format = "json" },
|
||||||
|
]
|
||||||
|
cooldown = "-1m"
|
||||||
|
|
||||||
|
[plugins]
|
||||||
|
"Bad Name" = "x.lua"
|
||||||
|
missing = "plugins/missing.lua"
|
||||||
|
|
||||||
|
[sandbox]
|
||||||
|
timeout = "1m"
|
||||||
|
session_timeout = "1s"
|
||||||
|
memory_mb = 0
|
||||||
|
call_stack = 1
|
||||||
|
`, nil)
|
||||||
|
es := errs(t, err)
|
||||||
|
|
||||||
|
wantErr(t, es, "item[0].name", 2, "missing required key")
|
||||||
|
wantErr(t, es, "item[0].shop", 3, `unknown shop "amazn"`)
|
||||||
|
wantErr(t, es, "item[0].urls[0]", 4, "http:// or https://")
|
||||||
|
wantErr(t, es, "item[0].max_price", 5, "positive")
|
||||||
|
wantErr(t, es, "item[0].currency", 6, "ISO 4217")
|
||||||
|
wantErr(t, es, "item[0].seller", 7, `"first_party", "fulfilled" or "any"`)
|
||||||
|
wantErr(t, es, "item[0].interval", 8, "at least 1m0s")
|
||||||
|
wantErr(t, es, "item[1].urls[0]", 13, "duplicate URL (also item[0].urls[1])")
|
||||||
|
wantErr(t, es, "item[1].fx_margin", 14, "needs both currency and max_price")
|
||||||
|
wantErr(t, es, "item[2].name", 17, "duplicate item name")
|
||||||
|
wantErr(t, es, "item[2].urls", 19, "at least one URL")
|
||||||
|
wantErr(t, es, "accounts.amazon.password_env", 22, "DIBS_MISSING is not set")
|
||||||
|
wantErr(t, es, "accounts.amazon.cart_mode", 23, `"deeplink" or "session"`)
|
||||||
|
wantErr(t, es, "accounts.amazon.login_url", 24, "http:// or https://")
|
||||||
|
wantErr(t, es, "accounts.ebay", 26, `no plugin named "ebay"`)
|
||||||
|
wantErr(t, es, "notify.webhooks[1].format", 31, `got "slack"`)
|
||||||
|
wantErr(t, es, "notify.webhooks[2].url", 32, "missing required key")
|
||||||
|
wantErr(t, es, "notify.cooldown", 34, "between 0s and 168h")
|
||||||
|
wantErr(t, es, "plugins.Bad Name", 37, "plugin name")
|
||||||
|
wantErr(t, es, "plugins.missing", 38, "cannot read plugin")
|
||||||
|
wantErr(t, es, "sandbox.timeout", 41, "between 100ms and 30s")
|
||||||
|
wantErr(t, es, "sandbox.session_timeout", 42, "between 10s and 30m0s")
|
||||||
|
wantErr(t, es, "sandbox.memory_mb", 43, "between 4 and 1024")
|
||||||
|
wantErr(t, es, "sandbox.call_stack", 44, "between 50 and 10000")
|
||||||
|
if len(es) != 24 {
|
||||||
|
t.Errorf("want 24 errors, got %d:\n%v", len(es), es)
|
||||||
|
}
|
||||||
|
for i := 1; i < len(es); i++ {
|
||||||
|
if es[i].Line < es[i-1].Line {
|
||||||
|
t.Errorf("errors not sorted by line:\n%v", es)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNoItems(t *testing.T) {
|
||||||
|
_, err := load(t, "[notify]\ndesktop = true\n", nil)
|
||||||
|
es := errs(t, err)
|
||||||
|
if len(es) != 1 || !strings.Contains(es[0].Msg, "no [[item]]") {
|
||||||
|
t.Errorf("got:\n%v", es)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmptyPasswordEnv(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"
|
||||||
|
`, map[string]string{"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 {
|
||||||
|
t.Errorf("got %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
e = Error{File: "dibs.toml", Msg: "no [[item]] configured"}
|
||||||
|
if got, want := e.Error(), "dibs.toml: no [[item]] configured"; got != want {
|
||||||
|
t.Errorf("got %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAcceptsSeller(t *testing.T) {
|
||||||
|
for policy, want := range map[string]map[string]bool{
|
||||||
|
SellerFirstParty: {"first_party": true, "fulfilled": false, "third_party": false, "unknown": false},
|
||||||
|
SellerFulfilled: {"first_party": true, "fulfilled": true, "third_party": false, "unknown": false},
|
||||||
|
SellerAny: {"first_party": true, "fulfilled": true, "third_party": true, "unknown": true},
|
||||||
|
} {
|
||||||
|
for seller, ok := range want {
|
||||||
|
if got := (Item{Seller: policy}).AcceptsSeller(seller); got != ok { t.Errorf("policy %s, seller %s: got %v, want %v", policy, seller, got, ok) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Item{Seller: policy}).AcceptsSeller("amazon") { t.Errorf("policy %s accepts an invalid seller", policy) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"maps"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Diff summarizes what changed from old to cfg, one line per change, for
|
||||||
|
// the reload message.
|
||||||
|
func Diff(old, cfg *Config) []string {
|
||||||
|
var out []string
|
||||||
|
|
||||||
|
oldItems := map[string]Item{}
|
||||||
|
for _, it := range old.Items { oldItems[it.Name] = it }
|
||||||
|
|
||||||
|
for _, it := range cfg.Items {
|
||||||
|
prev, ok := oldItems[it.Name]
|
||||||
|
if !ok {
|
||||||
|
out = append(out, fmt.Sprintf("+ item %s (%s)", it.Name, countURLs(len(it.URLs))))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(oldItems, it.Name)
|
||||||
|
if changes := itemChanges(prev, it); len(changes) > 0 { out = append(out, fmt.Sprintf("~ item %s: %s", it.Name, strings.Join(changes, ", "))) }
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, it := range old.Items {
|
||||||
|
if _, gone := oldItems[it.Name]; gone { out = append(out, fmt.Sprintf("- item %s", it.Name)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if changes := notifyChanges(old.Notify, cfg.Notify); len(changes) > 0 { out = append(out, "~ notify: "+strings.Join(changes, ", ")) }
|
||||||
|
if !maps.Equal(old.Plugins, cfg.Plugins) { out = append(out, "~ plugins") }
|
||||||
|
if !maps.Equal(old.Accounts, cfg.Accounts) { out = append(out, "~ accounts") }
|
||||||
|
if !sameSandbox(old.Sandbox, cfg.Sandbox) { out = append(out, "~ sandbox") }
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func itemChanges(a, b Item) []string {
|
||||||
|
var out []string
|
||||||
|
|
||||||
|
change := func(key, from, to string) {
|
||||||
|
if from != to { out = append(out, fmt.Sprintf("%s %s → %s", key, from, to)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
change("shop", a.Shop, b.Shop)
|
||||||
|
change("max_price", optPrice(a.MaxPrice), optPrice(b.MaxPrice))
|
||||||
|
change("currency", orNone(a.Currency), orNone(b.Currency))
|
||||||
|
change("fx_margin", strconv.FormatFloat(a.FXMargin, 'f', -1, 64), strconv.FormatFloat(b.FXMargin, 'f', -1, 64))
|
||||||
|
change("seller", a.Seller, b.Seller)
|
||||||
|
change("interval", a.Interval.String(), b.Interval.String())
|
||||||
|
|
||||||
|
added, removed := 0, 0
|
||||||
|
for _, u := range b.URLs {
|
||||||
|
if !slices.Contains(a.URLs, u) { added++ }
|
||||||
|
}
|
||||||
|
for _, u := range a.URLs {
|
||||||
|
if !slices.Contains(b.URLs, u) { removed++ }
|
||||||
|
}
|
||||||
|
|
||||||
|
if added > 0 { out = append(out, "+"+countURLs(added)) }
|
||||||
|
if removed > 0 { out = append(out, "-"+countURLs(removed)) }
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func notifyChanges(a, b Notify) []string {
|
||||||
|
var out []string
|
||||||
|
|
||||||
|
if !slices.Equal(a.Webhooks, b.Webhooks) { out = append(out, "webhooks") }
|
||||||
|
if a.Desktop != b.Desktop { out = append(out, fmt.Sprintf("desktop %v → %v", a.Desktop, b.Desktop)) }
|
||||||
|
if a.Cooldown.Duration != b.Cooldown.Duration { out = append(out, fmt.Sprintf("cooldown %s → %s", a.Cooldown, b.Cooldown)) }
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// sameSandbox compares the limits, not whether they were written out.
|
||||||
|
func sameSandbox(a, b Sandbox) bool {
|
||||||
|
return a.Timeout.Duration == b.Timeout.Duration && a.SessionTimeout.Duration == b.SessionTimeout.Duration &&
|
||||||
|
a.MemoryMB == b.MemoryMB && a.CallStack == b.CallStack
|
||||||
|
}
|
||||||
|
|
||||||
|
func countURLs(n int) string {
|
||||||
|
if n == 1 { return "1 URL" }
|
||||||
|
|
||||||
|
return strconv.Itoa(n) + " URLs"
|
||||||
|
}
|
||||||
|
|
||||||
|
func optPrice(p *float64) string {
|
||||||
|
if p == nil { return "none" }
|
||||||
|
|
||||||
|
return strconv.FormatFloat(*p, 'f', -1, 64)
|
||||||
|
}
|
||||||
|
|
||||||
|
func orNone(s string) string {
|
||||||
|
if s == "" { return "none" }
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/pelletier/go-toml/v2/unstable"
|
||||||
|
)
|
||||||
|
|
||||||
|
// positions maps key paths such as "item[1].interval" or
|
||||||
|
// "notify.webhooks[0].url" to where they appear in the document, so that
|
||||||
|
// validation errors can point at a line.
|
||||||
|
type positions map[string]unstable.Position
|
||||||
|
|
||||||
|
func indexPositions(doc []byte) positions {
|
||||||
|
ps := positions{}
|
||||||
|
var p unstable.Parser
|
||||||
|
p.Reset(doc)
|
||||||
|
|
||||||
|
prefix := ""
|
||||||
|
arrays := map[string]int{}
|
||||||
|
// A parse error stops the index early. The decoder reports it.
|
||||||
|
for p.NextExpression() {
|
||||||
|
e := p.Expression()
|
||||||
|
if e == nil { continue }
|
||||||
|
|
||||||
|
switch e.Kind {
|
||||||
|
case unstable.Table, unstable.ArrayTable:
|
||||||
|
keys, first := keyParts(e.Key())
|
||||||
|
path := strings.Join(keys, ".")
|
||||||
|
if e.Kind == unstable.ArrayTable {
|
||||||
|
n := arrays[path]
|
||||||
|
arrays[path]++
|
||||||
|
path = fmt.Sprintf("%s[%d]", path, n)
|
||||||
|
}
|
||||||
|
prefix = path
|
||||||
|
ps.add(&p, path, first)
|
||||||
|
case unstable.KeyValue:
|
||||||
|
ps.keyValue(&p, prefix, e)
|
||||||
|
default:
|
||||||
|
// Comments and other expressions have no key to record.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ps positions) keyValue(p *unstable.Parser, prefix string, kv *unstable.Node) {
|
||||||
|
keys, first := keyParts(kv.Key())
|
||||||
|
path := strings.Join(keys, ".")
|
||||||
|
|
||||||
|
if prefix != "" {
|
||||||
|
path = prefix + "." + path
|
||||||
|
}
|
||||||
|
|
||||||
|
ps.add(p, path, first)
|
||||||
|
ps.value(p, path, kv.Value())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ps positions) value(p *unstable.Parser, path string, v *unstable.Node) {
|
||||||
|
switch v.Kind {
|
||||||
|
case unstable.Array:
|
||||||
|
it := v.Children()
|
||||||
|
for i := 0; it.Next(); i++ {
|
||||||
|
el := it.Node()
|
||||||
|
elPath := fmt.Sprintf("%s[%d]", path, i)
|
||||||
|
ps.add(p, elPath, el)
|
||||||
|
ps.value(p, elPath, el)
|
||||||
|
}
|
||||||
|
case unstable.InlineTable:
|
||||||
|
it := v.Children()
|
||||||
|
for it.Next() {
|
||||||
|
if kv := it.Node(); kv.Kind == unstable.KeyValue { ps.keyValue(p, path, kv) }
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// Scalars have no nested keys.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ps positions) add(p *unstable.Parser, path string, n *unstable.Node) {
|
||||||
|
if _, ok := ps[path]; !ok && n != nil {
|
||||||
|
ps[path] = p.Shape(n.Raw).Start
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// find returns the position of path, or of its closest present parent, so
|
||||||
|
// that a missing key points at the table it belongs in.
|
||||||
|
func (ps positions) find(path string) (unstable.Position, bool) {
|
||||||
|
for path != "" {
|
||||||
|
if pos, ok := ps[path]; ok { return pos, true }
|
||||||
|
|
||||||
|
i := strings.LastIndexAny(path, ".[")
|
||||||
|
if i < 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
path = path[:i]
|
||||||
|
}
|
||||||
|
|
||||||
|
return unstable.Position{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// keyAt returns the path of the last key that starts on line at or before
|
||||||
|
// col, or "" if there is none.
|
||||||
|
func (ps positions) keyAt(line, col int) string {
|
||||||
|
best, bestCol := "", 0
|
||||||
|
|
||||||
|
for path, p := range ps {
|
||||||
|
if p.Line == line && p.Column <= col && p.Column >= bestCol {
|
||||||
|
// An array element and its first key can share a position; the
|
||||||
|
// longer path wins.
|
||||||
|
if p.Column > bestCol || len(path) > len(best) {
|
||||||
|
best, bestCol = path, p.Column
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
func keyParts(it unstable.Iterator) ([]string, *unstable.Node) {
|
||||||
|
var keys []string
|
||||||
|
var first *unstable.Node
|
||||||
|
|
||||||
|
for it.Next() {
|
||||||
|
n := it.Node()
|
||||||
|
if first == nil { first = n }
|
||||||
|
keys = append(keys, string(n.Data))
|
||||||
|
}
|
||||||
|
|
||||||
|
return keys, first
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"cmp"
|
||||||
|
"fmt"
|
||||||
|
"maps"
|
||||||
|
"math"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pelletier/go-toml/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
minSandboxTimeout = 100 * time.Millisecond
|
||||||
|
maxSandboxTimeout = 30 * time.Second
|
||||||
|
minSessionTimeout = 10 * time.Second
|
||||||
|
maxSessionTimeout = 30 * time.Minute
|
||||||
|
minMemoryMB = 4
|
||||||
|
maxMemoryMB = 1024
|
||||||
|
minCallStack = 50
|
||||||
|
maxCallStack = 10000
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
pluginNameRe = regexp.MustCompile(`^[a-z0-9_-]+$`)
|
||||||
|
currencyRe = regexp.MustCompile(`^[A-Z]{3}$`)
|
||||||
|
typeErrRe = regexp.MustCompile(`^cannot decode TOML (\S+) into (?:struct field \S+ of type )?(\S+)$`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// goTypeNames describes the Go types of config fields in TOML terms.
|
||||||
|
var goTypeNames = map[string]string{
|
||||||
|
"string": "a string",
|
||||||
|
"bool": "true or false",
|
||||||
|
"int": "an integer",
|
||||||
|
"float64": "a number",
|
||||||
|
"*float64": "a number",
|
||||||
|
"[]string": "a list of strings",
|
||||||
|
"[]config.Webhook": "a list of tables",
|
||||||
|
"[]config.Item": "a list of tables",
|
||||||
|
"config.Duration": `a duration string such as "3m"`,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Error struct {
|
||||||
|
File string
|
||||||
|
Line int // 1-based; 0 if unknown
|
||||||
|
Col int
|
||||||
|
Key string // e.g. "item[1].interval"; empty for file-level problems
|
||||||
|
Msg string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Error) Error() string {
|
||||||
|
if e.Line > 0 { return e.File + ":" + e.Brief() }
|
||||||
|
|
||||||
|
return e.File + ": " + e.Brief()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Brief is the error without the file name, such as "12:3: item[0].shop:
|
||||||
|
// missing required key".
|
||||||
|
func (e Error) Brief() string {
|
||||||
|
var b strings.Builder
|
||||||
|
if e.Line > 0 { _, _ = fmt.Fprintf(&b, "%d:%d: ", e.Line, e.Col) }
|
||||||
|
|
||||||
|
if e.Key != "" {
|
||||||
|
b.WriteString(e.Key)
|
||||||
|
b.WriteString(": ")
|
||||||
|
}
|
||||||
|
|
||||||
|
b.WriteString(e.Msg)
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errors is sorted by position in the file.
|
||||||
|
type Errors []Error
|
||||||
|
|
||||||
|
func (es Errors) Error() string {
|
||||||
|
lines := make([]string, len(es))
|
||||||
|
for i, e := range es { lines[i] = e.Error() }
|
||||||
|
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
type validator struct {
|
||||||
|
file string
|
||||||
|
pos positions
|
||||||
|
errs Errors
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) errorf(key, format string, args ...any) {
|
||||||
|
e := Error{File: v.file, Key: key, Msg: fmt.Sprintf(format, args...)}
|
||||||
|
if p, ok := v.pos.find(key); ok { e.Line, e.Col = p.Line, p.Column }
|
||||||
|
v.errs = append(v.errs, e)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) decodeError(de *toml.DecodeError, msg string) {
|
||||||
|
line, col := de.Position()
|
||||||
|
if msg == "" {
|
||||||
|
msg = friendlyDecodeMsg(strings.TrimPrefix(de.Error(), "toml: "))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The decoder's key has no array indexes; the key indexed at the same
|
||||||
|
// position has them.
|
||||||
|
key := v.pos.keyAt(line, col)
|
||||||
|
if key == "" {
|
||||||
|
key = strings.Join(de.Key(), ".")
|
||||||
|
}
|
||||||
|
|
||||||
|
v.errs = append(v.errs, Error{File: v.file, Line: line, Col: col, Key: key, Msg: msg})
|
||||||
|
}
|
||||||
|
|
||||||
|
// friendlyDecodeMsg rewrites go-toml's type mismatch errors, which name Go
|
||||||
|
// types, into TOML terms.
|
||||||
|
func friendlyDecodeMsg(msg string) string {
|
||||||
|
m := typeErrRe.FindStringSubmatch(msg)
|
||||||
|
if m == nil { return msg }
|
||||||
|
|
||||||
|
want, ok := goTypeNames[m[2]]
|
||||||
|
if !ok {
|
||||||
|
if strings.HasPrefix(m[2], "map[") { want = "a table" } else { return msg }
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("expected %s, got a TOML %s", want, strings.ToLower(m[1]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) validate(cfg *Config, opts Options) {
|
||||||
|
shops := map[string]bool{}
|
||||||
|
for _, b := range opts.Builtins { shops[b] = true }
|
||||||
|
|
||||||
|
v.plugins(cfg, shops)
|
||||||
|
v.items(cfg, shops, opts.Builtins)
|
||||||
|
v.accounts(cfg, shops, opts.LookupEnv)
|
||||||
|
v.notify(&cfg.Notify)
|
||||||
|
v.sandbox(&cfg.Sandbox)
|
||||||
|
|
||||||
|
// File-level errors first, then in document order.
|
||||||
|
slices.SortStableFunc(v.errs, func(a, b Error) int {
|
||||||
|
return cmp.Or(cmp.Compare(a.Line, b.Line), cmp.Compare(a.Col, b.Col))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// plugins resolves plugin paths against the config dir and adds the plugin
|
||||||
|
// names to shops.
|
||||||
|
func (v *validator) plugins(cfg *Config, shops map[string]bool) {
|
||||||
|
dir := filepath.Dir(cfg.Path)
|
||||||
|
for _, name := range slices.Sorted(maps.Keys(cfg.Plugins)) {
|
||||||
|
key := "plugins." + name
|
||||||
|
if !pluginNameRe.MatchString(name) {
|
||||||
|
v.errorf(key, "plugin name must contain only a-z, 0-9, _ and -")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
shops[name] = true
|
||||||
|
|
||||||
|
path := cfg.Plugins[name]
|
||||||
|
if path == "" {
|
||||||
|
v.errorf(key, "path is empty")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
path = filepath.Join(dir, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.Plugins[name] = path
|
||||||
|
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
v.errorf(key, "cannot read plugin: %v", err)
|
||||||
|
case !info.Mode().IsRegular():
|
||||||
|
v.errorf(key, "%s is not a regular file", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) items(cfg *Config, shops map[string]bool, builtins []string) {
|
||||||
|
if len(cfg.Items) == 0 {
|
||||||
|
v.errorf("", "no [[item]] configured")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
names := map[string]int{}
|
||||||
|
urls := map[string]string{}
|
||||||
|
|
||||||
|
for i := range cfg.Items {
|
||||||
|
it := &cfg.Items[i]
|
||||||
|
key := fmt.Sprintf("item[%d]", i)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case it.Name == "":
|
||||||
|
v.errorf(key+".name", "missing required key")
|
||||||
|
case names[it.Name] > 0:
|
||||||
|
v.errorf(key+".name", "duplicate item name %q (also item[%d])", it.Name, names[it.Name]-1)
|
||||||
|
default:
|
||||||
|
names[it.Name] = i + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case it.Shop == "":
|
||||||
|
v.errorf(key+".shop", "missing required key")
|
||||||
|
case !shops[it.Shop]:
|
||||||
|
v.errorf(key+".shop", "unknown shop %q: built-in plugins are %s, others must be listed under [plugins]",
|
||||||
|
it.Shop, strings.Join(builtins, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(it.URLs) == 0 {
|
||||||
|
v.errorf(key+".urls", "at least one URL is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
for j, raw := range it.URLs {
|
||||||
|
ukey := fmt.Sprintf("%s.urls[%d]", key, j)
|
||||||
|
if msg := checkURL(raw); msg != "" {
|
||||||
|
v.errorf(ukey, "%s", msg)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if prev, dup := urls[raw]; dup {
|
||||||
|
v.errorf(ukey, "duplicate URL (also %s)", prev)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
urls[raw] = ukey
|
||||||
|
}
|
||||||
|
|
||||||
|
if it.MaxPrice != nil {
|
||||||
|
if p := *it.MaxPrice; p <= 0 || math.IsInf(p, 0) || math.IsNaN(p) {
|
||||||
|
v.errorf(key+".max_price", "must be a positive number (got %v)", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if it.Currency != "" {
|
||||||
|
it.Currency = strings.ToUpper(it.Currency)
|
||||||
|
if !currencyRe.MatchString(it.Currency) {
|
||||||
|
v.errorf(key+".currency", "must be a 3-letter ISO 4217 code such as EUR (got %q)", it.Currency)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if it.FXMargin != 0 {
|
||||||
|
switch {
|
||||||
|
case it.FXMargin < 0 || it.FXMargin > 1:
|
||||||
|
v.errorf(key+".fx_margin", "must be between 0 and 1, e.g. 0.1 for 10%% (got %v)", it.FXMargin)
|
||||||
|
case it.Currency == "" || it.MaxPrice == nil:
|
||||||
|
v.errorf(key+".fx_margin", "needs both currency and max_price to have an effect")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch it.Seller {
|
||||||
|
case "":
|
||||||
|
it.Seller = DefaultSeller
|
||||||
|
case SellerFirstParty, SellerFulfilled, SellerAny:
|
||||||
|
default:
|
||||||
|
v.errorf(key+".seller", "must be %q, %q or %q (got %q)", SellerFirstParty, SellerFulfilled, SellerAny, it.Seller)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case !it.Interval.IsSet():
|
||||||
|
it.Interval.Duration = DefaultInterval
|
||||||
|
case it.Interval.Duration < MinInterval:
|
||||||
|
v.errorf(key+".interval", "must be at least %s (got %s)", MinInterval, it.Interval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) accounts(cfg *Config, shops map[string]bool, lookupEnv func(string) (string, bool)) {
|
||||||
|
for _, shop := range slices.Sorted(maps.Keys(cfg.Accounts)) {
|
||||||
|
acc := cfg.Accounts[shop]
|
||||||
|
key := "accounts." + shop
|
||||||
|
|
||||||
|
if !shops[shop] {
|
||||||
|
v.errorf(key, "no plugin named %q", shop)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch acc.CartMode {
|
||||||
|
case "":
|
||||||
|
acc.CartMode = CartModeDeeplink
|
||||||
|
case CartModeDeeplink, CartModeSession:
|
||||||
|
default:
|
||||||
|
v.errorf(key+".cart_mode", "must be %q or %q (got %q)", CartModeDeeplink, CartModeSession, acc.CartMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
if acc.PasswordEnv != "" {
|
||||||
|
if val, ok := lookupEnv(acc.PasswordEnv); !ok || val == "" {
|
||||||
|
v.errorf(key+".password_env", "environment variable %s is not set", acc.PasswordEnv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 }
|
||||||
|
|
||||||
|
if msg := checkURL(f.raw); msg != "" {
|
||||||
|
v.errorf(key+"."+f.name, "%s", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.Accounts[shop] = acc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) notify(n *Notify) {
|
||||||
|
for i, wh := range n.Webhooks {
|
||||||
|
key := fmt.Sprintf("notify.webhooks[%d]", i)
|
||||||
|
|
||||||
|
if wh.URL == "" {
|
||||||
|
v.errorf(key+".url", "missing required key")
|
||||||
|
} else if msg := checkURL(wh.URL); msg != "" {
|
||||||
|
v.errorf(key+".url", "%s", msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch wh.Format {
|
||||||
|
case FormatDiscord, FormatNtfy, FormatJSON:
|
||||||
|
case "":
|
||||||
|
v.errorf(key+".format", "missing required key (%q, %q or %q)", FormatDiscord, FormatNtfy, FormatJSON)
|
||||||
|
default:
|
||||||
|
v.errorf(key+".format", "must be %q, %q or %q (got %q)", FormatDiscord, FormatNtfy, FormatJSON, wh.Format)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if n.Cooldown.Duration < 0 || n.Cooldown.Duration > MaxCooldown {
|
||||||
|
v.errorf("notify.cooldown", "must be between 0s and %gh (got %s)", MaxCooldown.Hours(), n.Cooldown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *validator) sandbox(s *Sandbox) {
|
||||||
|
durationRange(v, "sandbox.timeout", s.Timeout.Duration, minSandboxTimeout, maxSandboxTimeout)
|
||||||
|
durationRange(v, "sandbox.session_timeout", s.SessionTimeout.Duration, minSessionTimeout, maxSessionTimeout)
|
||||||
|
|
||||||
|
if s.MemoryMB < minMemoryMB || s.MemoryMB > maxMemoryMB {
|
||||||
|
v.errorf("sandbox.memory_mb", "must be between %d and %d (got %d)", minMemoryMB, maxMemoryMB, s.MemoryMB)
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.CallStack < minCallStack || s.CallStack > maxCallStack {
|
||||||
|
v.errorf("sandbox.call_stack", "must be between %d and %d (got %d)", minCallStack, maxCallStack, s.CallStack)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func durationRange(v *validator, key string, d, lo, hi time.Duration) {
|
||||||
|
if d < lo || d > hi {
|
||||||
|
v.errorf(key, "must be between %s and %s (got %s)", lo, hi, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkURL returns a problem with raw, or "" if it is an absolute http(s) URL.
|
||||||
|
func checkURL(raw string) string {
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
return fmt.Sprintf("invalid URL: %v", err)
|
||||||
|
case u.Scheme != "http" && u.Scheme != "https":
|
||||||
|
return fmt.Sprintf("URL must start with http:// or https:// (got %q)", raw)
|
||||||
|
case u.Host == "":
|
||||||
|
return fmt.Sprintf("URL has no host (got %q)", raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
package fetch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
http "github.com/bogdanfinn/fhttp"
|
||||||
|
"github.com/bogdanfinn/tls-client/profiles"
|
||||||
|
"golang.org/x/net/publicsuffix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// chromeMajor must match chromeProfile: the TLS and HTTP/2 fingerprint come
|
||||||
|
// from the profile, the headers from the version, so the two change together.
|
||||||
|
const chromeMajor = 152
|
||||||
|
|
||||||
|
var chromeProfile = profiles.Chrome_152
|
||||||
|
|
||||||
|
// Browser is the browser that requests claim to come from.
|
||||||
|
type Browser struct {
|
||||||
|
Profile profiles.ClientProfile
|
||||||
|
Major int
|
||||||
|
UserAgent string
|
||||||
|
Platform string // sec-ch-ua-platform, without quotes
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultBrowser returns desktop Chrome on the current OS, so that cookies a
|
||||||
|
// real browser on this machine obtains later stay valid for these requests.
|
||||||
|
func DefaultBrowser() Browser {
|
||||||
|
ua, platform := "Windows NT 10.0; Win64; x64", "Windows"
|
||||||
|
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "darwin":
|
||||||
|
ua, platform = "Macintosh; Intel Mac OS X 10_15_7", "macOS"
|
||||||
|
case "linux":
|
||||||
|
ua, platform = "X11; Linux x86_64", "Linux"
|
||||||
|
default:
|
||||||
|
// Windows. Other systems pass as Windows too.
|
||||||
|
}
|
||||||
|
|
||||||
|
return Browser{
|
||||||
|
Profile: chromeProfile,
|
||||||
|
Major: chromeMajor,
|
||||||
|
UserAgent: fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.0.0 Safari/537.36", ua, chromeMajor),
|
||||||
|
Platform: platform,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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": {fetchSite(u, referer)},
|
||||||
|
"sec-fetch-mode": {"navigate"},
|
||||||
|
"sec-fetch-user": {"?1"},
|
||||||
|
"sec-fetch-dest": {"document"},
|
||||||
|
"accept-encoding": {"gzip, deflate, br, zstd"},
|
||||||
|
"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",
|
||||||
|
"sec-fetch-site",
|
||||||
|
"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
|
||||||
|
// navigator.userAgentData report.
|
||||||
|
type Brand struct {
|
||||||
|
Name string
|
||||||
|
Version string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Brands is Chrome's brand list. Chrome derives the GREASE brand and the
|
||||||
|
// brand order from its major version (GenerateBrandVersionList in
|
||||||
|
// Chromium's user_agent_utils.cc), so a fixed list would stand out after an
|
||||||
|
// update.
|
||||||
|
func (b Browser) Brands() []Brand {
|
||||||
|
return brands(b.Major)
|
||||||
|
}
|
||||||
|
|
||||||
|
func brands(major int) []Brand {
|
||||||
|
chars := []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"}
|
||||||
|
versions := []string{"8", "99", "24"}
|
||||||
|
orders := [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}
|
||||||
|
|
||||||
|
grease := Brand{"Not" + chars[major%len(chars)] + "A" + chars[(major+1)%len(chars)] + "Brand", versions[major%len(versions)]}
|
||||||
|
order := orders[major%len(orders)]
|
||||||
|
|
||||||
|
var out [3]Brand
|
||||||
|
out[order[0]] = grease
|
||||||
|
out[order[1]] = Brand{"Chromium", strconv.Itoa(major)}
|
||||||
|
out[order[2]] = Brand{"Google Chrome", strconv.Itoa(major)}
|
||||||
|
|
||||||
|
return out[:]
|
||||||
|
}
|
||||||
|
|
||||||
|
func secCHUA(major int) string {
|
||||||
|
var parts []string
|
||||||
|
for _, b := range brands(major) { parts = append(parts, fmt.Sprintf(`"%s";v="%s"`, b.Name, b.Version)) }
|
||||||
|
|
||||||
|
return strings.Join(parts, ", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// AcceptLanguage is the Accept-Language a local shopper's browser would
|
||||||
|
// send to host.
|
||||||
|
func AcceptLanguage(host string) string {
|
||||||
|
return acceptLanguage(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
// languages maps a public suffix to the Accept-Language a local shopper's
|
||||||
|
// browser would send.
|
||||||
|
var languages = map[string]string{
|
||||||
|
"de": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"at": "de-AT,de;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"ch": "de-CH,de;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"co.uk": "en-GB,en;q=0.9",
|
||||||
|
"uk": "en-GB,en;q=0.9",
|
||||||
|
"ie": "en-IE,en;q=0.9",
|
||||||
|
"fr": "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"be": "nl-BE,nl;q=0.9,fr-BE;q=0.8,fr;q=0.7,en;q=0.6",
|
||||||
|
"it": "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"es": "es-ES,es;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"nl": "nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"pl": "pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"se": "sv-SE,sv;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"com": "en-US,en;q=0.9",
|
||||||
|
}
|
||||||
|
|
||||||
|
func acceptLanguage(host string) string {
|
||||||
|
suffix, _ := publicsuffix.PublicSuffix(strings.ToLower(host))
|
||||||
|
if lang, ok := languages[suffix]; ok { return lang }
|
||||||
|
|
||||||
|
return languages["com"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package fetch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Verdict says what a response means for the watcher.
|
||||||
|
type Verdict int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// OK is a page the plugin can parse.
|
||||||
|
OK Verdict = iota
|
||||||
|
// NotFound (404, 410) means the item is not available, never an error.
|
||||||
|
NotFound
|
||||||
|
// Challenge is a bot check that a real browser may clear.
|
||||||
|
Challenge
|
||||||
|
// Blocked is a refusal without a recognisable challenge, such as a plain
|
||||||
|
// 403 or 429. The host is backed off and retried later.
|
||||||
|
Blocked
|
||||||
|
// HTTPError is any other non-2xx status.
|
||||||
|
HTTPError
|
||||||
|
// NeedsHuman is a bot check that headless Chrome could not clear either,
|
||||||
|
// such as a captcha. classify never returns it.
|
||||||
|
NeedsHuman
|
||||||
|
)
|
||||||
|
|
||||||
|
func (v Verdict) String() string {
|
||||||
|
switch v {
|
||||||
|
case OK:
|
||||||
|
return "ok"
|
||||||
|
case NotFound:
|
||||||
|
return "not-found"
|
||||||
|
case Challenge:
|
||||||
|
return "challenge"
|
||||||
|
case Blocked:
|
||||||
|
return "blocked"
|
||||||
|
case HTTPError:
|
||||||
|
return "http-error"
|
||||||
|
case NeedsHuman:
|
||||||
|
return "needs-human"
|
||||||
|
default:
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type marker struct {
|
||||||
|
name string
|
||||||
|
needle string
|
||||||
|
}
|
||||||
|
|
||||||
|
// strongMarkers only appear on bot check pages, so they count whatever the
|
||||||
|
// status. Amazon answers its captcha with a 200, for example.
|
||||||
|
var strongMarkers = []marker{
|
||||||
|
{"cloudflare", "window._cf_chl_opt"},
|
||||||
|
{"amazon-captcha", `action="/errors/validateCaptcha"`},
|
||||||
|
{"datadome", "geo.captcha-delivery.com"},
|
||||||
|
{"perimeterx", `id="px-captcha"`},
|
||||||
|
}
|
||||||
|
|
||||||
|
// weakMarkers also show up on normal pages (Cloudflare injects its
|
||||||
|
// challenge-platform script, shops embed Turnstile in forms), so they only
|
||||||
|
// count on a refusal status.
|
||||||
|
var weakMarkers = []marker{
|
||||||
|
{"cloudflare", "<title>Just a moment...</title>"},
|
||||||
|
{"cloudflare", "/cdn-cgi/challenge-platform/"},
|
||||||
|
{"turnstile", "challenges.cloudflare.com/turnstile"},
|
||||||
|
{"recaptcha", "www.google.com/recaptcha/"},
|
||||||
|
{"hcaptcha", "hcaptcha.com/1/api.js"},
|
||||||
|
{"captcha", "captcha"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// classify decides the verdict for a response. For Challenge it also names
|
||||||
|
// the bot check found.
|
||||||
|
func classify(status int, header http.Header, finalURL string, body []byte) (Verdict, string) {
|
||||||
|
lower := bytes.ToLower(body)
|
||||||
|
|
||||||
|
if header.Get("cf-mitigated") == "challenge" { return Challenge, "cloudflare" }
|
||||||
|
if strings.Contains(finalURL, "/errors/validateCaptcha") { return Challenge, "amazon-captcha" }
|
||||||
|
if name := findMarker(lower, strongMarkers); name != "" { return Challenge, name }
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case status >= 200 && status < 300:
|
||||||
|
return OK, ""
|
||||||
|
case status == http.StatusNotFound || status == http.StatusGone:
|
||||||
|
return NotFound, ""
|
||||||
|
case status == http.StatusForbidden || status == http.StatusTooManyRequests || status == http.StatusServiceUnavailable:
|
||||||
|
if name := findMarker(lower, weakMarkers); name != "" { return Challenge, name }
|
||||||
|
|
||||||
|
return Blocked, ""
|
||||||
|
default:
|
||||||
|
return HTTPError, ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// findMarker returns the name of the first marker in the lowercased body.
|
||||||
|
func findMarker(lower []byte, markers []marker) string {
|
||||||
|
for _, m := range markers {
|
||||||
|
if bytes.Contains(lower, []byte(strings.ToLower(m.needle))) { return m.name }
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
// Package fetch downloads product pages with a browser-like TLS and HTTP/2
|
||||||
|
// fingerprint and tells real pages apart from bot checks.
|
||||||
|
package fetch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
stdhttp "net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
http "github.com/bogdanfinn/fhttp"
|
||||||
|
tlsclient "github.com/bogdanfinn/tls-client"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
DefaultTimeout = 30 * time.Second
|
||||||
|
DefaultMaxBody = 16 << 20
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrBodyTooLarge is returned when a response exceeds Options.MaxBody.
|
||||||
|
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 {
|
||||||
|
// Limiter defaults to a new in-memory ratelimit.Limiter, so requests are
|
||||||
|
// never unlimited.
|
||||||
|
Limiter Limiter
|
||||||
|
// Browser defaults to DefaultBrowser().
|
||||||
|
Browser *Browser
|
||||||
|
// Jar defaults to a new, empty jar.
|
||||||
|
Jar *Jar
|
||||||
|
// Timeout covers a request and its redirects. It defaults to
|
||||||
|
// DefaultTimeout.
|
||||||
|
Timeout time.Duration
|
||||||
|
// MaxBody limits the body after decompression. It defaults to
|
||||||
|
// DefaultMaxBody.
|
||||||
|
MaxBody int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client fetches pages. It is safe for concurrent use.
|
||||||
|
type Client struct {
|
||||||
|
http tlsclient.HttpClient
|
||||||
|
limiter Limiter
|
||||||
|
browser Browser
|
||||||
|
jar *Jar
|
||||||
|
maxBody int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Response struct {
|
||||||
|
URL string // as requested
|
||||||
|
FinalURL string // after redirects
|
||||||
|
Status int
|
||||||
|
Header stdhttp.Header
|
||||||
|
Body []byte
|
||||||
|
Verdict Verdict
|
||||||
|
// Challenge names the bot check found, such as "cloudflare", when
|
||||||
|
// Verdict is Challenge.
|
||||||
|
Challenge string
|
||||||
|
Elapsed time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(opts Options) (*Client, error) {
|
||||||
|
browser := DefaultBrowser()
|
||||||
|
if opts.Browser != nil { browser = *opts.Browser }
|
||||||
|
if opts.Limiter == nil { opts.Limiter = ratelimit.New(nil) }
|
||||||
|
if opts.Jar == nil { opts.Jar = NewJar() }
|
||||||
|
if opts.Timeout == 0 { opts.Timeout = DefaultTimeout }
|
||||||
|
if opts.MaxBody == 0 { opts.MaxBody = DefaultMaxBody }
|
||||||
|
|
||||||
|
hc, err := tlsclient.NewHttpClient(nil,
|
||||||
|
tlsclient.WithClientProfile(browser.Profile),
|
||||||
|
tlsclient.WithRandomTLSExtensionOrder(),
|
||||||
|
tlsclient.WithCookieJar(opts.Jar),
|
||||||
|
tlsclient.WithTimeoutMilliseconds(int(opts.Timeout/time.Millisecond)),
|
||||||
|
)
|
||||||
|
if err != nil { return nil, fmt.Errorf("creating HTTP client: %w", err) }
|
||||||
|
|
||||||
|
return &Client{http: hc, limiter: opts.Limiter, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Jar() *Jar { return c.jar }
|
||||||
|
|
||||||
|
// Get fetches rawURL the way Chrome opens a bookmark, once the limiter allows
|
||||||
|
// 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 := parseURL(rawURL)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
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, 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 }
|
||||||
|
|
||||||
|
// fhttp's decompressing readers close the raw body with them.
|
||||||
|
body := resp.Body
|
||||||
|
if !resp.Uncompressed && resp.Header.Get("Content-Encoding") != "" { body = http.DecompressBody(resp) }
|
||||||
|
defer func() { _ = body.Close() }()
|
||||||
|
|
||||||
|
data, err := io.ReadAll(io.LimitReader(body, c.maxBody+1))
|
||||||
|
if err != nil { return nil, fmt.Errorf("reading body: %w", err) }
|
||||||
|
if int64(len(data)) > c.maxBody { return nil, fmt.Errorf("%w: more than %d bytes", ErrBodyTooLarge, c.maxBody) }
|
||||||
|
|
||||||
|
r := NewResponse(rawURL, resp.Request.URL.String(), resp.StatusCode, stdhttp.Header(resp.Header), data)
|
||||||
|
r.Elapsed = time.Since(start)
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewResponse builds and classifies a Response for a page obtained another
|
||||||
|
// way, such as a saved fixture or the browser fallback.
|
||||||
|
func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, body []byte) *Response {
|
||||||
|
if header == nil { header = stdhttp.Header{} }
|
||||||
|
|
||||||
|
r := &Response{
|
||||||
|
URL: rawURL,
|
||||||
|
FinalURL: finalURL,
|
||||||
|
Status: status,
|
||||||
|
Header: header,
|
||||||
|
Body: body,
|
||||||
|
}
|
||||||
|
r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body)
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
package fetch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
fhttp "github.com/bogdanfinn/fhttp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSecCHUA(t *testing.T) {
|
||||||
|
// Real values, from tls-client's examples.
|
||||||
|
for major, want := range map[int]string{
|
||||||
|
105: `"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"`,
|
||||||
|
107: `"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"`,
|
||||||
|
} {
|
||||||
|
if got := secCHUA(major); got != want { t.Errorf("secCHUA(%d) = %s, want %s", major, got, want) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAcceptLanguage(t *testing.T) {
|
||||||
|
for host, want := range map[string]string{
|
||||||
|
"www.amazon.de": "de-DE,",
|
||||||
|
"www.Amazon.co.uk": "en-GB,",
|
||||||
|
"www.amazon.fr": "fr-FR,",
|
||||||
|
"www.amazon.it": "it-IT,",
|
||||||
|
"www.amazon.es": "es-ES,",
|
||||||
|
"www.amazon.nl": "nl-NL,",
|
||||||
|
"www.amazon.com": "en-US,",
|
||||||
|
"www.amazon.co.jp": "en-US,",
|
||||||
|
"127.0.0.1": "en-US,",
|
||||||
|
} {
|
||||||
|
if got := acceptLanguage(host); !strings.HasPrefix(got, want) { t.Errorf("acceptLanguage(%q) = %q, want prefix %q", host, got, want) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultBrowserMatchesProfile(t *testing.T) {
|
||||||
|
b := DefaultBrowser()
|
||||||
|
if !strings.Contains(b.UserAgent, "Chrome/152.0.0.0") { t.Errorf("user agent %q does not match Chrome %d", b.UserAgent, b.Major) }
|
||||||
|
|
||||||
|
want := map[string]string{"windows": "Windows", "darwin": "macOS", "linux": "Linux"}[runtime.GOOS]
|
||||||
|
if want != "" && b.Platform != want { t.Errorf("platform = %q, want %q", b.Platform, want) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClassify(t *testing.T) {
|
||||||
|
cf := http.Header{"Cf-Mitigated": {"challenge"}}
|
||||||
|
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
status int
|
||||||
|
header http.Header
|
||||||
|
finalURL string
|
||||||
|
body string
|
||||||
|
verdict Verdict
|
||||||
|
challenge string
|
||||||
|
}{
|
||||||
|
"product page": {200, nil, "https://www.amazon.de/dp/X", "<title>Metro</title>", OK, ""},
|
||||||
|
"cf script on normal page": {200, nil, "", `<script src="/cdn-cgi/challenge-platform/scripts/jsd/main.js">`, OK, ""},
|
||||||
|
"turnstile in a form": {200, nil, "", `<script src="https://challenges.cloudflare.com/turnstile/v0/api.js">`, OK, ""},
|
||||||
|
"not found": {404, nil, "", "<title>Page not found</title>", NotFound, ""},
|
||||||
|
"gone": {410, nil, "", "", NotFound, ""},
|
||||||
|
"cf header": {403, cf, "", "", Challenge, "cloudflare"},
|
||||||
|
"cf js challenge": {503, nil, "", "<script>window._cf_chl_opt={}</script>", Challenge, "cloudflare"},
|
||||||
|
"cf title": {403, nil, "", "<title>Just a moment...</title>", Challenge, "cloudflare"},
|
||||||
|
"amazon captcha 200": {200, nil, "", `<form method="get" action="/errors/validateCaptcha">`, Challenge, "amazon-captcha"},
|
||||||
|
"amazon captcha url": {200, nil, "https://www.amazon.de/errors/validateCaptcha?x=1", "", Challenge, "amazon-captcha"},
|
||||||
|
"datadome": {403, nil, "", `<iframe src="https://geo.captcha-delivery.com/captcha/">`, Challenge, "datadome"},
|
||||||
|
"turnstile on 403": {403, nil, "", `<script src="https://challenges.cloudflare.com/turnstile/v0/api.js">`, Challenge, "turnstile"},
|
||||||
|
"plain 403": {403, nil, "", "Access Denied", Blocked, ""},
|
||||||
|
"429": {429, nil, "", "slow down", Blocked, ""},
|
||||||
|
"amazon 503 dog": {503, nil, "", "Sorry! Something went wrong!", Blocked, ""},
|
||||||
|
"500": {500, nil, "", "", HTTPError, ""},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
header := tc.header
|
||||||
|
if header == nil { header = http.Header{} }
|
||||||
|
|
||||||
|
v, c := classify(tc.status, header, tc.finalURL, []byte(tc.body))
|
||||||
|
if v != tc.verdict || c != tc.challenge { t.Errorf("got %s/%q, want %s/%q", v, c, tc.verdict, tc.challenge) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustURL(t *testing.T, raw string) *url.URL {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
func cookieNames(cs []*fhttp.Cookie) string {
|
||||||
|
names := make([]string, len(cs))
|
||||||
|
for i, c := range cs { names[i] = c.Name + "=" + c.Value }
|
||||||
|
|
||||||
|
return strings.Join(names, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestJarExportImport(t *testing.T) {
|
||||||
|
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
|
||||||
|
|
||||||
|
j := NewJar()
|
||||||
|
j.now = func() time.Time { return now }
|
||||||
|
j.SetCookies(mustURL(t, "https://www.amazon.de/dp/X"), []*fhttp.Cookie{
|
||||||
|
{Name: "session-id", Value: "1", Domain: ".amazon.de", Path: "/"},
|
||||||
|
{Name: "host", Value: "2"},
|
||||||
|
{Name: "short", Value: "3", MaxAge: 60},
|
||||||
|
{Name: "old", Value: "4", Expires: now.Add(-time.Hour)},
|
||||||
|
})
|
||||||
|
|
||||||
|
exported := j.Export()
|
||||||
|
got := exported["www.amazon.de"]
|
||||||
|
if len(got) != 3 { t.Fatalf("exported %d cookies, want 3: %+v", len(got), got) }
|
||||||
|
|
||||||
|
byName := map[string]Cookie{}
|
||||||
|
for _, c := range got { byName[c.Name] = c }
|
||||||
|
|
||||||
|
if c := byName["host"]; !c.HostOnly || c.Domain != "www.amazon.de" || c.Path != "/dp" { t.Errorf("host-only cookie: %+v", c) }
|
||||||
|
if c := byName["session-id"]; c.HostOnly || c.Domain != "amazon.de" { t.Errorf("domain cookie: %+v", c) }
|
||||||
|
if c := byName["short"]; !c.Expires.Equal(now.Add(time.Minute)) { t.Errorf("max-age cookie expires %v", c.Expires) }
|
||||||
|
|
||||||
|
// A new jar gets the same cookies, scoped the same way.
|
||||||
|
k := NewJar()
|
||||||
|
k.now = j.now
|
||||||
|
for host, cs := range exported { k.Import(host, cs) }
|
||||||
|
|
||||||
|
if got := cookieNames(k.Cookies(mustURL(t, "https://www.amazon.de/dp/Y"))); !strings.Contains(got, "host=2") || !strings.Contains(got, "session-id=1") {
|
||||||
|
t.Errorf("www.amazon.de/dp cookies after import: %s", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := cookieNames(k.Cookies(mustURL(t, "https://smile.amazon.de/"))); got != "session-id=1" { t.Errorf("smile.amazon.de cookies: %q, want only the domain cookie", got) }
|
||||||
|
|
||||||
|
// The server deletes a cookie.
|
||||||
|
j.SetCookies(mustURL(t, "https://www.amazon.de/"), []*fhttp.Cookie{{Name: "session-id", Domain: ".amazon.de", Path: "/", MaxAge: -1}})
|
||||||
|
for _, c := range j.Export()["www.amazon.de"] {
|
||||||
|
if c.Name == "session-id" { t.Errorf("deleted cookie still exported") }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Later the max-age cookie runs out.
|
||||||
|
now = now.Add(2 * time.Minute)
|
||||||
|
for _, c := range j.Export()["www.amazon.de"] {
|
||||||
|
if c.Name == "short" { t.Errorf("expired cookie still exported") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestJarSaveLoad(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "sub", "cookies.json")
|
||||||
|
|
||||||
|
j := NewJar()
|
||||||
|
j.SetCookies(mustURL(t, "https://www.amazon.co.uk/"), []*fhttp.Cookie{{Name: "a", Value: "1", Path: "/", Expires: time.Now().Add(time.Hour)}})
|
||||||
|
if err := j.Save(path); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
if runtime.GOOS != "windows" {
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
if perm := info.Mode().Perm(); perm != 0o600 { t.Errorf("cookie file mode %o, want 600", perm) }
|
||||||
|
}
|
||||||
|
|
||||||
|
k := NewJar()
|
||||||
|
if err := k.Load(path); err != nil { t.Fatal(err) }
|
||||||
|
if got := cookieNames(k.Cookies(mustURL(t, "https://www.amazon.co.uk/x"))); got != "a=1" { t.Errorf("loaded cookies: %q", got) }
|
||||||
|
|
||||||
|
if err := NewJar().Load(filepath.Join(t.TempDir(), "missing.json")); err != nil { t.Errorf("missing file: %v", err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestJarShared has two processes share a cookie file. Neither may undo the
|
||||||
|
// other's newer cookies when it saves.
|
||||||
|
func TestJarShared(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "cookies.json")
|
||||||
|
u := mustURL(t, "https://www.amazon.de/")
|
||||||
|
now := time.Now()
|
||||||
|
set := func(j *Jar, name, value string, maxAge int) {
|
||||||
|
j.SetCookies(u, []*fhttp.Cookie{{Name: name, Value: value, Path: "/", Expires: now.Add(time.Hour), MaxAge: maxAge}})
|
||||||
|
}
|
||||||
|
|
||||||
|
watcher, solver := NewJar(), NewJar()
|
||||||
|
watcher.now = func() time.Time { return now }
|
||||||
|
solver.now = func() time.Time { return now.Add(time.Minute) }
|
||||||
|
|
||||||
|
set(watcher, "session", "old", 0)
|
||||||
|
set(watcher, "tracking", "x", 0)
|
||||||
|
if err := watcher.Save(path); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
// The solver gets a new session and drops the tracking cookie.
|
||||||
|
if err := solver.Load(path); err != nil { t.Fatal(err) }
|
||||||
|
set(solver, "session", "solved", 0)
|
||||||
|
set(solver, "tracking", "", -1)
|
||||||
|
if err := solver.Save(path); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
// The watcher saves again later, without having seen either change.
|
||||||
|
watcher.now = func() time.Time { return now.Add(2 * time.Minute) }
|
||||||
|
if err := watcher.Save(path); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
if got := cookieNames(watcher.Cookies(u)); got != "session=solved" { t.Errorf("watcher after saving: %q", got) }
|
||||||
|
|
||||||
|
fresh := NewJar()
|
||||||
|
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()
|
||||||
|
|
||||||
|
if opts.Limiter == nil { opts.Limiter = noLimit{} }
|
||||||
|
|
||||||
|
c, err := New(opts)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientGet(t *testing.T) {
|
||||||
|
var seen []*http.Request
|
||||||
|
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
seen = append(seen, r)
|
||||||
|
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/start":
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "sid", Value: "abc", Path: "/"})
|
||||||
|
http.Redirect(w, r, "/product", http.StatusFound)
|
||||||
|
case "/product":
|
||||||
|
w.Header().Set("Content-Encoding", "gzip")
|
||||||
|
zw := gzip.NewWriter(w)
|
||||||
|
_, _ = zw.Write([]byte("<title>Metro 2039</title>"))
|
||||||
|
_ = zw.Close()
|
||||||
|
case "/missing":
|
||||||
|
http.NotFound(w, r)
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
c := newTestClient(t, Options{})
|
||||||
|
|
||||||
|
resp, err := c.Get(context.Background(), srv.URL+"/start")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
if resp.Verdict != OK || resp.Status != 200 { t.Errorf("verdict %s, status %d", resp.Verdict, resp.Status) }
|
||||||
|
if resp.FinalURL != srv.URL+"/product" { t.Errorf("final URL %q", resp.FinalURL) }
|
||||||
|
if string(resp.Body) != "<title>Metro 2039</title>" { t.Errorf("body %q, want it decompressed", resp.Body) }
|
||||||
|
|
||||||
|
if len(seen) != 2 { t.Fatalf("server saw %d requests, want 2", len(seen)) }
|
||||||
|
|
||||||
|
first := seen[0]
|
||||||
|
for name, want := range map[string]string{
|
||||||
|
"User-Agent": "Chrome/152.0.0.0",
|
||||||
|
"Sec-Ch-Ua": `"Google Chrome";v="152"`,
|
||||||
|
"Sec-Ch-Ua-Platform": `"`,
|
||||||
|
"Sec-Fetch-Mode": "navigate",
|
||||||
|
"Accept-Language": "en-US",
|
||||||
|
"Accept-Encoding": "gzip",
|
||||||
|
} {
|
||||||
|
if got := first.Header.Get(name); !strings.Contains(got, want) { t.Errorf("%s = %q, want it to contain %q", name, got, want) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := seen[1].Header.Get("Cookie"); got != "sid=abc" { t.Errorf("cookie on redirect = %q, want sid=abc", got) }
|
||||||
|
|
||||||
|
resp, err = c.Get(context.Background(), srv.URL+"/missing")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
if resp.Verdict != NotFound { t.Errorf("404 verdict %s", resp.Verdict) }
|
||||||
|
|
||||||
|
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)))
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
|
||||||
|
_, err := newTestClient(t, Options{MaxBody: 1024}).Get(context.Background(), srv.URL)
|
||||||
|
if !errors.Is(err, ErrBodyTooLarge) { t.Errorf("got %v, want ErrBodyTooLarge", err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientContextCancel(t *testing.T) {
|
||||||
|
release := make(chan struct{})
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
select {
|
||||||
|
case <-release:
|
||||||
|
case <-r.Context().Done():
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
defer close(release)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
if _, err := newTestClient(t, Options{}).Get(ctx, srv.URL); err == nil { t.Fatal("want an error from a cancelled request") }
|
||||||
|
if elapsed := time.Since(start); elapsed > 5*time.Second { t.Errorf("cancel took %s", elapsed) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClientRejectsOtherSchemes(t *testing.T) {
|
||||||
|
if _, err := newTestClient(t, Options{}).Get(context.Background(), "file:///etc/passwd"); err == nil { t.Error("want an error for file://") }
|
||||||
|
}
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
package fetch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io/fs"
|
||||||
|
"maps"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
http "github.com/bogdanfinn/fhttp"
|
||||||
|
"github.com/bogdanfinn/fhttp/cookiejar"
|
||||||
|
"golang.org/x/net/publicsuffix"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fsutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cookie is a stored cookie, in a form that survives a restart and can be
|
||||||
|
// handed to and from a browser.
|
||||||
|
type Cookie struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
Domain string `json:"domain"` // the host for host-only cookies
|
||||||
|
HostOnly bool `json:"host_only,omitempty"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
Expires time.Time `json:"expires,omitzero"` // zero for session cookies
|
||||||
|
Secure bool `json:"secure,omitempty"`
|
||||||
|
HTTPOnly bool `json:"http_only,omitempty"`
|
||||||
|
// Set is when the cookie was last set. When dibs processes share a
|
||||||
|
// cookie file, the newest version of each cookie wins.
|
||||||
|
Set time.Time `json:"set,omitzero"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Cookie) expired(now time.Time) bool {
|
||||||
|
return !c.Expires.IsZero() && !c.Expires.After(now)
|
||||||
|
}
|
||||||
|
|
||||||
|
// forgetDeleted is how long a deleted cookie is remembered, so that saving
|
||||||
|
// does not bring back the copy another process still has on file.
|
||||||
|
const forgetDeleted = 24 * time.Hour
|
||||||
|
|
||||||
|
// Jar is an RFC 6265 cookie jar that remembers every cookie by the host that
|
||||||
|
// set it, so the cookies can be saved, restored and exported per host.
|
||||||
|
type Jar struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
jar *cookiejar.Jar
|
||||||
|
// cookies keeps deleted and expired cookies too, until forgetDeleted
|
||||||
|
// has passed.
|
||||||
|
cookies map[string]map[string]Cookie // host -> domain|path|name -> cookie
|
||||||
|
now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewJar() *Jar {
|
||||||
|
jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
|
||||||
|
|
||||||
|
return &Jar{
|
||||||
|
jar: jar,
|
||||||
|
cookies: map[string]map[string]Cookie{},
|
||||||
|
now: time.Now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
|
||||||
|
j.mu.Lock()
|
||||||
|
defer j.mu.Unlock()
|
||||||
|
|
||||||
|
j.jar.SetCookies(u, cookies)
|
||||||
|
|
||||||
|
host := strings.ToLower(u.Hostname())
|
||||||
|
now := j.now()
|
||||||
|
|
||||||
|
for _, hc := range cookies {
|
||||||
|
c := Cookie{
|
||||||
|
Name: hc.Name,
|
||||||
|
Value: hc.Value,
|
||||||
|
Domain: strings.TrimPrefix(strings.ToLower(hc.Domain), "."),
|
||||||
|
Path: hc.Path,
|
||||||
|
Expires: hc.Expires,
|
||||||
|
Secure: hc.Secure,
|
||||||
|
HTTPOnly: hc.HttpOnly,
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.Domain == "" { c.Domain, c.HostOnly = host, true }
|
||||||
|
if c.Path == "" || !strings.HasPrefix(c.Path, "/") { c.Path = defaultPath(u.Path) }
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case hc.MaxAge < 0:
|
||||||
|
c.Expires = now
|
||||||
|
case hc.MaxAge > 0:
|
||||||
|
c.Expires = now.Add(time.Duration(hc.MaxAge) * time.Second)
|
||||||
|
default:
|
||||||
|
// No Max-Age: Expires decides.
|
||||||
|
}
|
||||||
|
|
||||||
|
j.store(host, c, now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *Jar) Cookies(u *url.URL) []*http.Cookie {
|
||||||
|
j.mu.Lock()
|
||||||
|
defer j.mu.Unlock()
|
||||||
|
|
||||||
|
return j.jar.Cookies(u)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export returns the live cookies of every host, sorted by name.
|
||||||
|
func (j *Jar) Export() map[string][]Cookie {
|
||||||
|
j.mu.Lock()
|
||||||
|
defer j.mu.Unlock()
|
||||||
|
|
||||||
|
now := j.now()
|
||||||
|
out := map[string][]Cookie{}
|
||||||
|
|
||||||
|
for host, byKey := range j.cookies {
|
||||||
|
for _, key := range slices.Sorted(maps.Keys(byKey)) {
|
||||||
|
if c := byKey[key]; !c.expired(now) { out[host] = append(out[host], c) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Import adds cookies as if host had set them, unless the jar has a newer
|
||||||
|
// version. A cookie without a Set time loses to any version in the jar.
|
||||||
|
func (j *Jar) Import(host string, cookies []Cookie) {
|
||||||
|
j.mu.Lock()
|
||||||
|
defer j.mu.Unlock()
|
||||||
|
|
||||||
|
j.importLocked(strings.ToLower(host), cookies, j.now())
|
||||||
|
}
|
||||||
|
|
||||||
|
// importLocked is Import. Callers hold mu.
|
||||||
|
func (j *Jar) importLocked(host string, cookies []Cookie, now time.Time) {
|
||||||
|
for _, c := range cookies {
|
||||||
|
if have, ok := j.cookies[host][key(c)]; ok && !c.Set.After(have.Set) { continue }
|
||||||
|
|
||||||
|
hc := &http.Cookie{
|
||||||
|
Name: c.Name,
|
||||||
|
Value: c.Value,
|
||||||
|
Path: c.Path,
|
||||||
|
Expires: c.Expires,
|
||||||
|
Secure: c.Secure,
|
||||||
|
HttpOnly: c.HTTPOnly,
|
||||||
|
}
|
||||||
|
if !c.HostOnly { hc.Domain = c.Domain }
|
||||||
|
if c.expired(now) { hc.MaxAge = -1 }
|
||||||
|
|
||||||
|
j.jar.SetCookies(&url.URL{Scheme: "https", Host: host, Path: c.Path}, []*http.Cookie{hc})
|
||||||
|
j.store(host, c, now)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
func (j *Jar) store(host string, c Cookie, now time.Time) {
|
||||||
|
if c.Set.IsZero() { c.Set = now }
|
||||||
|
|
||||||
|
if j.cookies[host] == nil { j.cookies[host] = map[string]Cookie{} }
|
||||||
|
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, codec)
|
||||||
|
if err != nil { return err }
|
||||||
|
|
||||||
|
j.mu.Lock()
|
||||||
|
now := j.now()
|
||||||
|
for host, cookies := range saved { j.importLocked(host, cookies, now) }
|
||||||
|
|
||||||
|
out := map[string][]Cookie{}
|
||||||
|
for host, byKey := range j.cookies {
|
||||||
|
for _, k := range slices.Sorted(maps.Keys(byKey)) {
|
||||||
|
c := byKey[k]
|
||||||
|
if c.expired(now) && now.Sub(c.Set) > forgetDeleted {
|
||||||
|
delete(byKey, k)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
out[host] = append(out[host], c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
j.mu.Unlock()
|
||||||
|
|
||||||
|
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 {
|
||||||
|
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) }
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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 }
|
||||||
|
|
||||||
|
return saved, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// defaultPath is the RFC 6265 default-path of a request path.
|
||||||
|
func defaultPath(p string) string {
|
||||||
|
if p == "" || p[0] != '/' { return "/" }
|
||||||
|
|
||||||
|
i := strings.LastIndex(p, "/")
|
||||||
|
if i == 0 { return "/" }
|
||||||
|
|
||||||
|
return p[:i]
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
// Package fixtures manages the real product pages the plugin tests run on.
|
||||||
|
//
|
||||||
|
// Which pages to use is tracked, in testdata/<shop>/cases.toml. The pages
|
||||||
|
// themselves change over time and may contain personal data, so they are
|
||||||
|
// not tracked: `dibs fixtures` fetches them into testdata/<shop>/pages/,
|
||||||
|
// next to the report dibs produced for each. The tests then check that the
|
||||||
|
// plugin still reads every saved page the same way.
|
||||||
|
package fixtures
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
|
||||||
|
"github.com/pelletier/go-toml/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Case is one page to test with.
|
||||||
|
type Case struct {
|
||||||
|
Name string `toml:"name"`
|
||||||
|
URL string `toml:"url"`
|
||||||
|
// Note says what the page is for, e.g. "only a used offer".
|
||||||
|
Note string `toml:"note"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Suite is the cases of one shop.
|
||||||
|
type Suite struct {
|
||||||
|
// Shop is the plugin to use, named after the directory.
|
||||||
|
Shop string
|
||||||
|
Dir string
|
||||||
|
Cases []Case
|
||||||
|
}
|
||||||
|
|
||||||
|
var nameRe = regexp.MustCompile(`^[a-z0-9-]+$`)
|
||||||
|
|
||||||
|
// Load reads every dir/<shop>/cases.toml.
|
||||||
|
func Load(dir string) ([]Suite, error) {
|
||||||
|
files, err := filepath.Glob(filepath.Join(dir, "*", "cases.toml"))
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
var suites []Suite
|
||||||
|
|
||||||
|
for _, f := range files {
|
||||||
|
data, err := os.ReadFile(f)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
var doc struct {
|
||||||
|
Cases []Case `toml:"case"`
|
||||||
|
}
|
||||||
|
|
||||||
|
dec := toml.NewDecoder(bytes.NewReader(data))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
if err := dec.Decode(&doc); err != nil { return nil, fmt.Errorf("%s: %w", f, err) }
|
||||||
|
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, c := range doc.Cases {
|
||||||
|
switch {
|
||||||
|
case !nameRe.MatchString(c.Name):
|
||||||
|
return nil, fmt.Errorf("%s: case name %q must contain only a-z, 0-9 and -", f, c.Name)
|
||||||
|
case seen[c.Name]:
|
||||||
|
return nil, fmt.Errorf("%s: duplicate case %q", f, c.Name)
|
||||||
|
case c.URL == "":
|
||||||
|
return nil, fmt.Errorf("%s: case %q has no url", f, c.Name)
|
||||||
|
}
|
||||||
|
|
||||||
|
seen[c.Name] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
suiteDir := filepath.Dir(f)
|
||||||
|
suites = append(suites, Suite{Shop: filepath.Base(suiteDir), Dir: suiteDir, Cases: doc.Cases})
|
||||||
|
}
|
||||||
|
|
||||||
|
return suites, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Suite) PagePath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".html") }
|
||||||
|
func (s Suite) ReportPath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".json") }
|
||||||
|
|
||||||
|
func (s Suite) Save(c Case, page []byte, report any) error {
|
||||||
|
data, err := EncodeReport(report)
|
||||||
|
if err != nil { return err }
|
||||||
|
|
||||||
|
if err := os.MkdirAll(filepath.Join(s.Dir, "pages"), 0o700); err != nil { return err }
|
||||||
|
if err := os.WriteFile(s.PagePath(c), page, 0o600); err != nil { return err }
|
||||||
|
|
||||||
|
return os.WriteFile(s.ReportPath(c), data, 0o600)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EncodeReport is the one way reports are written, so saved and fresh ones
|
||||||
|
// compare byte for byte.
|
||||||
|
func EncodeReport(report any) ([]byte, error) {
|
||||||
|
var b bytes.Buffer
|
||||||
|
|
||||||
|
enc := json.NewEncoder(&b)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
if err := enc.Encode(report); err != nil { return nil, err }
|
||||||
|
|
||||||
|
return b.Bytes(), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// Package fsutil has file helpers shared by the packages that persist data.
|
||||||
|
package fsutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WriteFileAtomic replaces path with data, so a crash never leaves a
|
||||||
|
// half-written file behind. Missing parent directories are created for the
|
||||||
|
// user only.
|
||||||
|
func WriteFileAtomic(path string, data []byte, perm fs.FileMode) error {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err }
|
||||||
|
|
||||||
|
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
|
||||||
|
if err != nil { return err }
|
||||||
|
defer func() { _ = os.Remove(tmp.Name()) }()
|
||||||
|
|
||||||
|
if err := tmp.Chmod(perm); err != nil {
|
||||||
|
_ = tmp.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := tmp.Write(data); err != nil {
|
||||||
|
_ = tmp.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tmp.Close(); err != nil { return err }
|
||||||
|
|
||||||
|
return os.Rename(tmp.Name(), path)
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package fsutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Lock takes an exclusive lock on path, creating it if needed, and blocks
|
||||||
|
// until it gets it. The lock is shared with other processes. The returned
|
||||||
|
// function releases it.
|
||||||
|
func Lock(path string) (func(), error) {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return nil, err }
|
||||||
|
|
||||||
|
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
if err := lockFile(f); err != nil {
|
||||||
|
_ = f.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return func() {
|
||||||
|
_ = unlockFile(f)
|
||||||
|
_ = f.Close()
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
//go:build unix
|
||||||
|
|
||||||
|
package fsutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func lockFile(f *os.File) error { return syscall.Flock(int(f.Fd()), syscall.LOCK_EX) }
|
||||||
|
func unlockFile(f *os.File) error { return syscall.Flock(int(f.Fd()), syscall.LOCK_UN) }
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package fsutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
func lockFile(f *os.File) error {
|
||||||
|
return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, new(windows.Overlapped))
|
||||||
|
}
|
||||||
|
|
||||||
|
func unlockFile(f *os.File) error {
|
||||||
|
return windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, new(windows.Overlapped))
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
// Package fx converts prices between currencies with the ECB's daily
|
||||||
|
// reference rates.
|
||||||
|
package fx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RatesURL is the ECB's feed of the latest reference rates. It needs no API
|
||||||
|
// key and changes once per working day, around 16:00 CET.
|
||||||
|
const RatesURL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Rates fetched more than refreshAfter ago are refreshed in the
|
||||||
|
// background while still in use.
|
||||||
|
refreshAfter = 6 * time.Hour
|
||||||
|
// MaxAge is how long rates stay usable without a successful refresh.
|
||||||
|
MaxAge = 72 * time.Hour
|
||||||
|
// retryAfter spaces out refreshes after one fails.
|
||||||
|
retryAfter = 15 * time.Minute
|
||||||
|
fetchTimeout = 30 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// Rates are the ECB reference rates of one day.
|
||||||
|
type Rates struct {
|
||||||
|
// Date is the ECB's publication day, as YYYY-MM-DD.
|
||||||
|
Date string `json:"date"`
|
||||||
|
// Fetched is when the rates were last downloaded, even if the ECB had
|
||||||
|
// not published newer ones.
|
||||||
|
Fetched time.Time `json:"fetched"`
|
||||||
|
// PerEUR is how much of each currency one euro buys.
|
||||||
|
PerEUR map[string]float64 `json:"per_eur"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert converts amount from one currency to another, through the euro.
|
||||||
|
func (r *Rates) Convert(amount float64, from, to string) (float64, error) {
|
||||||
|
if from == to { return amount, nil }
|
||||||
|
|
||||||
|
f, err := r.perEUR(from)
|
||||||
|
if err != nil { return 0, err }
|
||||||
|
|
||||||
|
t, err := r.perEUR(to)
|
||||||
|
if err != nil { return 0, err }
|
||||||
|
|
||||||
|
return amount / f * t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Rates) perEUR(currency string) (float64, error) {
|
||||||
|
if currency == "EUR" { return 1, nil }
|
||||||
|
|
||||||
|
if rate, ok := r.PerEUR[currency]; ok && rate > 0 { return rate, nil }
|
||||||
|
|
||||||
|
return 0, fmt.Errorf("the ECB publishes no rate for %s", currency)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store keeps the rates between runs and shares them with other dibs
|
||||||
|
// processes.
|
||||||
|
type Store interface {
|
||||||
|
Lock() func()
|
||||||
|
LoadRates() (*Rates, bool)
|
||||||
|
StoreRates(r *Rates)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limiter is ratelimit.Limiter, which spaces out the requests to the ECB
|
||||||
|
// like every other request dibs makes.
|
||||||
|
type Limiter interface {
|
||||||
|
WaitCheck(ctx context.Context, url string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Service hands out current rates and refreshes them when they are due. It
|
||||||
|
// is safe for concurrent use.
|
||||||
|
type Service struct {
|
||||||
|
store Store
|
||||||
|
limiter Limiter
|
||||||
|
client *http.Client
|
||||||
|
url string
|
||||||
|
now func() time.Time
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
rates *Rates
|
||||||
|
lastTry time.Time
|
||||||
|
lastErr error
|
||||||
|
inflight chan struct{} // closed when the running refresh ends
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(store Store, limiter Limiter) *Service {
|
||||||
|
return &Service{
|
||||||
|
store: store,
|
||||||
|
limiter: limiter,
|
||||||
|
client: &http.Client{Timeout: fetchTimeout},
|
||||||
|
url: RatesURL,
|
||||||
|
now: time.Now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warm starts a refresh in the background if the rates are due for one, so
|
||||||
|
// the first conversion does not wait for the network.
|
||||||
|
func (s *Service) Warm() {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
s.load()
|
||||||
|
if s.due() { s.startRefresh() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert converts amount with the newest usable rates. When the rates are
|
||||||
|
// older than MaxAge, it waits for a refresh; if that fails, it fails too.
|
||||||
|
func (s *Service) Convert(ctx context.Context, amount float64, from, to string) (float64, error) {
|
||||||
|
if from == to { return amount, nil }
|
||||||
|
|
||||||
|
r, err := s.current(ctx)
|
||||||
|
if err != nil { return 0, err }
|
||||||
|
|
||||||
|
return r.Convert(amount, from, to)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) current(ctx context.Context) (*Rates, error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
|
||||||
|
s.load()
|
||||||
|
if s.due() { s.startRefresh() }
|
||||||
|
|
||||||
|
if s.usable() {
|
||||||
|
r := s.rates
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
wait := s.inflight
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if wait != nil {
|
||||||
|
select {
|
||||||
|
case <-wait:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
if s.usable() { return s.rates, nil }
|
||||||
|
|
||||||
|
var cause string
|
||||||
|
if s.lastErr != nil { cause = ": " + s.lastErr.Error() }
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("no exchange rates younger than %s%s", MaxAge, cause)
|
||||||
|
}
|
||||||
|
|
||||||
|
// load picks up rates another dibs process may have fetched. Callers hold
|
||||||
|
// mu.
|
||||||
|
func (s *Service) load() {
|
||||||
|
if s.store == nil { return }
|
||||||
|
|
||||||
|
if r, ok := s.store.LoadRates(); ok && (s.rates == nil || r.Fetched.After(s.rates.Fetched)) { s.rates = r }
|
||||||
|
}
|
||||||
|
|
||||||
|
// due reports whether a refresh should start. Callers hold mu.
|
||||||
|
func (s *Service) due() bool {
|
||||||
|
now := s.now()
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case s.inflight != nil:
|
||||||
|
return false
|
||||||
|
case !s.lastTry.IsZero() && now.Sub(s.lastTry) < retryAfter:
|
||||||
|
return false
|
||||||
|
case s.rates == nil:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return now.Sub(s.rates.Fetched) >= refreshAfter
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// usable reports whether the rates are young enough to use. Callers hold
|
||||||
|
// mu.
|
||||||
|
func (s *Service) usable() bool {
|
||||||
|
return s.rates != nil && s.now().Sub(s.rates.Fetched) < MaxAge
|
||||||
|
}
|
||||||
|
|
||||||
|
// startRefresh fetches the rates in the background. Callers hold mu.
|
||||||
|
func (s *Service) startRefresh() {
|
||||||
|
done := make(chan struct{})
|
||||||
|
s.inflight = done
|
||||||
|
s.lastTry = s.now()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer close(done)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), fetchTimeout+time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
r, err := s.fetch(ctx)
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
s.inflight, s.lastErr = nil, err
|
||||||
|
if err == nil { s.rates = r }
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if err == nil && s.store != nil {
|
||||||
|
unlock := s.store.Lock()
|
||||||
|
s.store.StoreRates(r)
|
||||||
|
unlock()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) fetch(ctx context.Context) (*Rates, error) {
|
||||||
|
if s.limiter != nil {
|
||||||
|
if err := s.limiter.WaitCheck(ctx, s.url); err != nil { return nil, err }
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.url, nil)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
resp, err := s.client.Do(req)
|
||||||
|
if err != nil { return nil, fmt.Errorf("fetching exchange rates: %w", err) }
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("fetching exchange rates: %s", resp.Status) }
|
||||||
|
|
||||||
|
r, err := Parse(io.LimitReader(resp.Body, 1<<20))
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
r.Fetched = s.now()
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse reads the ECB's eurofxref XML.
|
||||||
|
func Parse(rd io.Reader) (*Rates, error) {
|
||||||
|
var doc struct {
|
||||||
|
Days []struct {
|
||||||
|
Time string `xml:"time,attr"`
|
||||||
|
Rates []struct {
|
||||||
|
Currency string `xml:"currency,attr"`
|
||||||
|
Rate string `xml:"rate,attr"`
|
||||||
|
} `xml:"Cube"`
|
||||||
|
} `xml:"Cube>Cube"`
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := xml.NewDecoder(rd).Decode(&doc); err != nil { return nil, fmt.Errorf("reading exchange rates: %w", err) }
|
||||||
|
if len(doc.Days) == 0 { return nil, errors.New("reading exchange rates: no rates in the feed") }
|
||||||
|
|
||||||
|
day := doc.Days[0]
|
||||||
|
r := &Rates{Date: day.Time, PerEUR: map[string]float64{}}
|
||||||
|
|
||||||
|
for _, c := range day.Rates {
|
||||||
|
rate, err := strconv.ParseFloat(c.Rate, 64)
|
||||||
|
if err != nil || rate <= 0 { return nil, fmt.Errorf("reading exchange rates: bad rate %q for %s", c.Rate, c.Currency) }
|
||||||
|
|
||||||
|
r.PerEUR[c.Currency] = rate
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(r.PerEUR) == 0 { return nil, errors.New("reading exchange rates: no rates in the feed") }
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package fx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConvert(t *testing.T) {
|
||||||
|
r := &Rates{PerEUR: map[string]float64{"USD": 1.25, "GBP": 0.8}}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
amount float64
|
||||||
|
from, to string
|
||||||
|
want float64
|
||||||
|
} {
|
||||||
|
{100, "EUR", "USD", 125},
|
||||||
|
{125, "USD", "EUR", 100},
|
||||||
|
{100, "GBP", "USD", 156.25},
|
||||||
|
{100, "GBP", "GBP", 100},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases {
|
||||||
|
got, err := r.Convert(c.amount, c.from, c.to)
|
||||||
|
if err != nil || math.Abs(got-c.want) > 1e-9 { t.Errorf("%v %s in %s = %v, %v; want %v", c.amount, c.from, c.to, got, err, c.want) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := r.Convert(1, "JPY", "EUR"); err == nil { t.Error("converted a currency without a rate") }
|
||||||
|
}
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
// 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]) + "…"
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestRetries sends one alert to a webhook that fails with each status
|
||||||
|
// until the last attempt.
|
||||||
|
func TestRetries(t *testing.T) {
|
||||||
|
price := 129.99
|
||||||
|
a := alert.Alert{Item: "metro", Shop: "amazon", URL: "https://www.amazon.de/dp/B0HMX2FSTF", Price: &price, Currency: "EUR", Time: time.Now()}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
status int
|
||||||
|
requests int32
|
||||||
|
ok bool
|
||||||
|
} {
|
||||||
|
{http.StatusServiceUnavailable, retries + 1, false},
|
||||||
|
{http.StatusTooManyRequests, retries + 1, false},
|
||||||
|
{http.StatusNotFound, 1, false},
|
||||||
|
{http.StatusNoContent, 1, true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases {
|
||||||
|
var requests atomic.Int32
|
||||||
|
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
requests.Add(1)
|
||||||
|
w.WriteHeader(c.status)
|
||||||
|
}))
|
||||||
|
|
||||||
|
// The path stands in for a webhook token.
|
||||||
|
n := New(config.Notify{Webhooks: []config.Webhook{{URL: srv.URL + "/secret-token", Format: config.FormatJSON}}}, "dibs/test")
|
||||||
|
|
||||||
|
var waited time.Duration
|
||||||
|
n.wait = func(_ context.Context, d time.Duration) error {
|
||||||
|
waited += d
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
err := n.Send(context.Background(), a)
|
||||||
|
srv.Close()
|
||||||
|
|
||||||
|
if got := requests.Load(); got != c.requests { t.Errorf("%d: %d requests, want %d", c.status, got, c.requests) }
|
||||||
|
if (err == nil) != c.ok { t.Errorf("%d: err = %v", c.status, err) }
|
||||||
|
if err != nil && strings.Contains(err.Error(), "secret-token") { t.Errorf("%d: error shows the webhook URL: %v", c.status, err) }
|
||||||
|
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) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package notify
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PayloadVersion changes only when a field is removed or changes meaning.
|
||||||
|
// New fields may appear in any version.
|
||||||
|
const PayloadVersion = 1
|
||||||
|
|
||||||
|
// Payload is the body of a "json" webhook, POSTed as application/json.
|
||||||
|
//
|
||||||
|
// {
|
||||||
|
// "version": 1,
|
||||||
|
// "test": false,
|
||||||
|
// "item": "Metro 2039 CE",
|
||||||
|
// "shop": "amazon",
|
||||||
|
// "url": "https://www.amazon.de/dp/B0HMX2FSTF",
|
||||||
|
// "title": "Metro 2039 Collector's Edition (PS5)",
|
||||||
|
// "price": 129.99,
|
||||||
|
// "currency": "EUR",
|
||||||
|
// "converted_price": null,
|
||||||
|
// "converted_currency": null,
|
||||||
|
// "previous_price": null,
|
||||||
|
// "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`.
|
||||||
|
Test bool `json:"test"`
|
||||||
|
Item string `json:"item"`
|
||||||
|
Shop string `json:"shop"`
|
||||||
|
// URL is the product page.
|
||||||
|
URL string `json:"url"`
|
||||||
|
Title *string `json:"title"`
|
||||||
|
// Price is null when the page shows none, which only fires items without
|
||||||
|
// max_price.
|
||||||
|
Price *float64 `json:"price"`
|
||||||
|
Currency *string `json:"currency"`
|
||||||
|
// ConvertedPrice is the price in the item's currency, when the page uses
|
||||||
|
// another one.
|
||||||
|
ConvertedPrice *float64 `json:"converted_price"`
|
||||||
|
ConvertedCurrency *string `json:"converted_currency"`
|
||||||
|
// PreviousPrice is set when the item fires again during its cooldown
|
||||||
|
// because the price dropped below the previous alert's.
|
||||||
|
PreviousPrice *float64 `json:"previous_price"`
|
||||||
|
PreviousCurrency *string `json:"previous_currency"`
|
||||||
|
// 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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPayload(a alert.Alert) Payload {
|
||||||
|
return Payload{
|
||||||
|
Version: PayloadVersion,
|
||||||
|
Test: a.Test,
|
||||||
|
Item: a.Item,
|
||||||
|
Shop: a.Shop,
|
||||||
|
URL: a.URL,
|
||||||
|
Title: orNull(a.Title),
|
||||||
|
Price: a.Price,
|
||||||
|
Currency: orNull(a.Currency),
|
||||||
|
ConvertedPrice: a.Converted,
|
||||||
|
ConvertedCurrency: orNull(a.ConvertedCurrency),
|
||||||
|
PreviousPrice: a.PreviousPrice,
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func orNull(s string) *string {
|
||||||
|
if s == "" { return nil }
|
||||||
|
|
||||||
|
return &s
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/PuerkitoBio/goquery"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeAmazon imitates the sign-in, product page and cart of amazon.de, as
|
||||||
|
// far as the plugin uses them. The product page is a saved real one.
|
||||||
|
type fakeAmazon struct {
|
||||||
|
t *testing.T
|
||||||
|
// product is the saved page as a signed-in customer sees it, guest as
|
||||||
|
// it was saved, signed out.
|
||||||
|
product, guest string
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
// captcha makes the password step ask for a captcha.
|
||||||
|
captcha bool
|
||||||
|
// expireOnProduct ends the session when the product page loads.
|
||||||
|
expireOnProduct bool
|
||||||
|
// skipped is set once the request for a phone number was skipped.
|
||||||
|
skipped bool
|
||||||
|
// session is the signed-in session's cookie value.
|
||||||
|
session string
|
||||||
|
inCart bool
|
||||||
|
// adds counts the additions to the account's cart.
|
||||||
|
adds int
|
||||||
|
}
|
||||||
|
|
||||||
|
const fakeASIN = "B0DK51S84Z"
|
||||||
|
|
||||||
|
func newFakeAmazon(t *testing.T) *fakeAmazon {
|
||||||
|
page := savedPage(t, "fulfilled-de")
|
||||||
|
|
||||||
|
return &fakeAmazon{t: t, product: signedIn(page), guest: string(page)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// savedPage reads testdata/amazon/pages/<name>.html. Saved pages are not
|
||||||
|
// tracked, so tests without them are skipped.
|
||||||
|
func savedPage(t *testing.T, name string) []byte {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
page, err := os.ReadFile(filepath.Join(testdata, "amazon", "pages", name+".html"))
|
||||||
|
if errors.Is(err, os.ErrNotExist) { t.Skip("no saved page " + name + ": run `dibs fixtures` to fetch the product pages") }
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
return page
|
||||||
|
}
|
||||||
|
|
||||||
|
// signedIn turns a saved page, which is a guest's, into what a signed-in
|
||||||
|
// customer sees.
|
||||||
|
func signedIn(page []byte) string {
|
||||||
|
html := regexp.MustCompile(`https://www\.amazon\.de/ap/signin\?[^"]*`).ReplaceAllString(string(page), "https://www.amazon.de/gp/css/homepage.html")
|
||||||
|
return strings.ReplaceAll(html, "nav_ya_signin", "nav_youraccount_btn")
|
||||||
|
}
|
||||||
|
|
||||||
|
// state returns whether the item is in the cart, how often it was added and
|
||||||
|
// the session.
|
||||||
|
func (f *fakeAmazon) state() (bool, int, string) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
return f.inCart, f.adds, f.session
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAmazon) setExpireOnProduct(on bool) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
f.expireOnProduct = on
|
||||||
|
}
|
||||||
|
|
||||||
|
const signedOutNav = `<div id="nav-link-accountList"><a href="https://www.amazon.de/ap/signin?openid.assoc_handle=deflex" data-csa-c-content-id="nav_ya_signin">Hallo, anmelden</a></div>`
|
||||||
|
|
||||||
|
func signInPage(fields string) string {
|
||||||
|
return `<form name="signIn" method="post" action="https://www.amazon.de/ap/signin">` + fields + `<input type="submit" id="signInSubmit"></form>`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAmazon) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
_ = r.ParseForm()
|
||||||
|
|
||||||
|
cookie, _ := r.Cookie("at-acbde")
|
||||||
|
signedIn := cookie != nil && f.session != "" && cookie.Value == f.session
|
||||||
|
|
||||||
|
write := func(body string) { _, _ = w.Write([]byte("<html><body>" + body + "</body></html>")) }
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case r.URL.Path == "/ap/signin" && r.Method == "GET" && r.URL.Query().Get("skip") == "fixup":
|
||||||
|
f.skipped = true
|
||||||
|
write(`<form id="auth-mfa-form" method="post" action="/ap/signin"><input type="hidden" name="mfaToken" value="mfa"><input name="otpCode"><input type="checkbox" name="rememberDevice"></form>`)
|
||||||
|
case r.URL.Path == "/ap/signin" && r.Method == "GET":
|
||||||
|
if r.URL.Query().Get("openid.assoc_handle") != "deflex" { f.t.Errorf("sign-in URL %s", r.URL) }
|
||||||
|
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "session-id", Value: "guest", Path: "/"})
|
||||||
|
write(signInPage(`<input type="hidden" name="appActionToken" value="tok1"><input type="email" name="email">`))
|
||||||
|
case r.URL.Path == "/ap/accountfixup":
|
||||||
|
f.t.Error("dibs submitted the phone number form")
|
||||||
|
case r.URL.Path == "/ap/signin" && r.Form.Has("otpCode"):
|
||||||
|
if r.Form.Get("otpCode") != "123456" || r.Form.Get("mfaToken") != "mfa" {
|
||||||
|
write(`<form id="auth-mfa-form" method="post" action="/ap/signin"><div id="auth-error-message-box">Wrong code</div></form>`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
f.session = "signed-in"
|
||||||
|
http.SetCookie(w, &http.Cookie{Name: "at-acbde", Value: f.session, Path: "/"})
|
||||||
|
http.Redirect(w, r, "/?ref_=signin", http.StatusFound)
|
||||||
|
case r.URL.Path == "/ap/signin" && r.Form.Has("password"):
|
||||||
|
switch {
|
||||||
|
case r.Form.Get("appActionToken") != "tok2" || r.Form.Get("email") != "me@example.com":
|
||||||
|
f.t.Errorf("password step got %v", r.Form)
|
||||||
|
case r.Form.Get("password") != "hunter2":
|
||||||
|
write(`<div id="auth-error-message-box">Ihr Passwort ist falsch</div>` + signInPage(`<input type="hidden" name="appActionToken" value="tok2"><input type="password" name="password">`))
|
||||||
|
case f.captcha:
|
||||||
|
write(`<img id="auth-captcha-image" src="/captcha.jpg">` + signInPage(`<input type="password" name="password">`))
|
||||||
|
default:
|
||||||
|
// As on amazon.de: a request for a phone number, with a link
|
||||||
|
// to skip it.
|
||||||
|
write(`<form id="auth-account-fixup-phone-form" name="accountFixup" method="post" action="https://www.amazon.de/ap/accountfixup">` +
|
||||||
|
`<input type="tel" name="mobilePhoneNumber"><input type="submit"></form>` +
|
||||||
|
`<a id="ap-account-fixup-phone-skip-link" href="https://www.amazon.de/ap/signin?skip=fixup">Nicht jetzt</a>`)
|
||||||
|
}
|
||||||
|
case r.URL.Path == "/ap/signin":
|
||||||
|
if r.Form.Get("appActionToken") != "tok1" || r.Form.Get("email") != "me@example.com" { f.t.Errorf("email step got %v", r.Form) }
|
||||||
|
|
||||||
|
write(signInPage(`<input type="hidden" name="appActionToken" value="tok2"><input type="hidden" name="email" value="me@example.com"><input type="password" name="password"><input type="checkbox" name="rememberMe" value="true">`))
|
||||||
|
case r.URL.Path == "/" && signedIn:
|
||||||
|
write(`<div id="nav-link-accountList"><a href="/gp/css/homepage.html" data-csa-c-content-id="nav_youraccount_btn">Hallo, Me</a></div>`)
|
||||||
|
case r.URL.Path == "/gp/cart/view.html" && !signedIn:
|
||||||
|
write(signedOutNav + `<div id="sc-active-cart"></div>`)
|
||||||
|
case r.URL.Path == "/gp/cart/view.html":
|
||||||
|
items := ""
|
||||||
|
if f.inCart { items = `<div class="sc-list-item" data-asin="` + fakeASIN + `"></div>` }
|
||||||
|
|
||||||
|
write(`<div id="sc-active-cart">` + items + `</div><div id="sc-saved-cart"><div data-asin="` + fakeASIN + `"></div></div>`)
|
||||||
|
case r.URL.Path == "/dp/"+fakeASIN:
|
||||||
|
if f.expireOnProduct { f.session = "expired" }
|
||||||
|
|
||||||
|
_, _ = w.Write([]byte(f.product))
|
||||||
|
case strings.HasPrefix(r.URL.Path, "/cart/add-to-cart/") && r.Method == "POST":
|
||||||
|
for name, want := range map[string]string{
|
||||||
|
"anti-csrftoken-a2z": "hOgocjo+1KjiCPsF4LU3lHBSy+VeMLo/5zSecGDC+HnZAAAAAGrOvcg1Y2U5ZjJiZC0zZGNiLTRjYzctYWNhNC05YjE0ZTkzMjk0ZTA=",
|
||||||
|
"items[0.base][quantity]": "1",
|
||||||
|
"items[0.base][asin]": fakeASIN,
|
||||||
|
"submit.add-to-cart": "In den Einkaufswagen",
|
||||||
|
} {
|
||||||
|
if got := r.Form.Get(name); got != want { f.t.Errorf("add to cart: %s = %q, want %q", name, got, want) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Form.Has("submit.buy-now") { f.t.Error("add to cart pressed buy now") }
|
||||||
|
|
||||||
|
if signedIn { f.inCart, f.adds = true, f.adds+1 }
|
||||||
|
|
||||||
|
http.Redirect(w, r, "/cart/smart-wagon?newItems="+fakeASIN, http.StatusFound)
|
||||||
|
case r.URL.Path == "/cart/smart-wagon":
|
||||||
|
// A guest's item goes into a guest cart, under Amazon's real
|
||||||
|
// signed-out header.
|
||||||
|
header := ""
|
||||||
|
if !signedIn { header = f.guest }
|
||||||
|
|
||||||
|
write(header + `<div id="NATC_SMART_WAGON_CONF_MSG_SUCCESS">In den Einkaufswagen gelegt</div>`)
|
||||||
|
default:
|
||||||
|
f.t.Errorf("unexpected %s %s", r.Method, r.URL)
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// amazonSession sends the plugin's requests to the fake instead of
|
||||||
|
// www.amazon.de.
|
||||||
|
type amazonSession struct {
|
||||||
|
client *fetch.Client
|
||||||
|
srv string
|
||||||
|
codes int
|
||||||
|
}
|
||||||
|
|
||||||
|
const amazonOrigin = "https://www.amazon.de"
|
||||||
|
|
||||||
|
func (s *amazonSession) local(u string) string { return strings.Replace(u, amazonOrigin, s.srv, 1) }
|
||||||
|
func (s *amazonSession) remote(u string) string { return strings.Replace(u, s.srv, amazonOrigin, 1) }
|
||||||
|
|
||||||
|
func (s *amazonSession) Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) {
|
||||||
|
if !strings.HasPrefix(r.URL, amazonOrigin+"/") { return nil, errors.New("request outside amazon.de: " + r.URL) }
|
||||||
|
|
||||||
|
r.URL = s.local(r.URL)
|
||||||
|
if r.Referer != "" { r.Referer = s.local(r.Referer) }
|
||||||
|
|
||||||
|
resp, err := s.client.Do(ctx, r)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
resp.URL, resp.FinalURL = s.remote(resp.URL), s.remote(resp.FinalURL)
|
||||||
|
return resp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Click submits the button's form as Chrome does: every field, the button's
|
||||||
|
// own name and value, to the button's formaction if it has one.
|
||||||
|
func (s *amazonSession) Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error) {
|
||||||
|
page, err := s.Do(ctx, fetch.Request{Method: "GET", URL: rawURL})
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page.Body))
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
button := doc.Find(sel).First()
|
||||||
|
if button.Length() == 0 { return nil, errors.New("no " + sel) }
|
||||||
|
|
||||||
|
f := button.Closest("form")
|
||||||
|
form := url.Values{}
|
||||||
|
|
||||||
|
f.Find("input[name]").Each(func(_ int, in *goquery.Selection) {
|
||||||
|
kind := in.AttrOr("type", "text")
|
||||||
|
if kind == "submit" || (kind == "checkbox" && in.AttrOr("checked", "-") == "-") { return }
|
||||||
|
|
||||||
|
form.Add(in.AttrOr("name", ""), in.AttrOr("value", ""))
|
||||||
|
})
|
||||||
|
f.Find("select[name]").Each(func(_ int, sl *goquery.Selection) { form.Add(sl.AttrOr("name", ""), sl.Find("option").First().AttrOr("value", "")) })
|
||||||
|
form.Add(button.AttrOr("name", ""), button.AttrOr("value", ""))
|
||||||
|
|
||||||
|
return s.Do(ctx, fetch.Request{Method: "POST", URL: amazonOrigin + button.AttrOr("formaction", f.AttrOr("action", "")), Form: form, Referer: rawURL})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *amazonSession) Prompt(_ context.Context, label string, secret bool) (string, error) {
|
||||||
|
s.codes++
|
||||||
|
return "123456", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *amazonSession) Cookies(u string) map[string]string {
|
||||||
|
parsed, _ := url.Parse(s.local(u))
|
||||||
|
|
||||||
|
out := map[string]string{}
|
||||||
|
for _, c := range s.client.Jar().Cookies(parsed) { out[c.Name] = c.Value }
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
type noWait struct{}
|
||||||
|
|
||||||
|
func (noWait) WaitCheck(context.Context, string) error { return nil }
|
||||||
|
func (noWait) Wait(context.Context, string) error { return nil }
|
||||||
|
|
||||||
|
func newAmazonSession(t *testing.T) (*fakeAmazon, *amazonSession) {
|
||||||
|
fake := newFakeAmazon(t)
|
||||||
|
srv := httptest.NewServer(fake)
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
|
||||||
|
client, err := fetch.New(fetch.Options{Limiter: noWait{}})
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
return fake, &amazonSession{client: client, srv: srv.URL}
|
||||||
|
}
|
||||||
|
|
||||||
|
var amazonAccount = Account{Username: "me@example.com", Password: "hunter2", TwoFA: true, Site: "https://www.amazon.de/"}
|
||||||
|
|
||||||
|
func TestAmazonSession(t *testing.T) {
|
||||||
|
p := builtin(t, "amazon")
|
||||||
|
fake, s := newAmazonSession(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
product := "https://www.amazon.de/dp/" + fakeASIN
|
||||||
|
|
||||||
|
// Without a session, the cart shows a guest.
|
||||||
|
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Fatalf("before signing in: got %v, want ErrSignedOut", err) }
|
||||||
|
|
||||||
|
if err := p.Login(ctx, s, amazonAccount); err != nil { t.Fatal(err) }
|
||||||
|
if s.codes != 1 { t.Errorf("asked for %d codes, want 1", s.codes) }
|
||||||
|
if !fake.skipped { t.Error("the request for a phone number was not skipped") }
|
||||||
|
|
||||||
|
// The session runs out between the cart and the click. The page the
|
||||||
|
// click leads to has Amazon's real signed-out header.
|
||||||
|
fake.setExpireOnProduct(true)
|
||||||
|
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("session ran out before the click: got %v, want ErrSignedOut", err) }
|
||||||
|
if inCart, _, _ := fake.state(); inCart { t.Error("added to the account's cart while signed out") }
|
||||||
|
fake.setExpireOnProduct(false)
|
||||||
|
|
||||||
|
if err := p.Login(ctx, s, amazonAccount); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
// The item saved for later is not in the cart.
|
||||||
|
cart, err := p.AddToCart(ctx, s, amazonAccount, product)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
if cart != "https://www.amazon.de/gp/cart/view.html" { t.Errorf("cart page %q", cart) }
|
||||||
|
if inCart, adds, _ := fake.state(); !inCart || adds != 1 { t.Errorf("in cart %v after %d adds", inCart, adds) }
|
||||||
|
|
||||||
|
// Already in the cart: nothing is added again.
|
||||||
|
if _, err := p.AddToCart(ctx, s, amazonAccount, product); err != nil { t.Fatal(err) }
|
||||||
|
if _, adds, _ := fake.state(); adds != 1 { t.Errorf("%d adds, want 1: the item went in twice", adds) }
|
||||||
|
|
||||||
|
// The session runs out.
|
||||||
|
fake.mu.Lock()
|
||||||
|
fake.session, fake.inCart = "expired", false
|
||||||
|
fake.mu.Unlock()
|
||||||
|
|
||||||
|
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("after the session ran out: got %v, want ErrSignedOut", err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmazonLoginFailures(t *testing.T) {
|
||||||
|
p := builtin(t, "amazon")
|
||||||
|
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
account Account
|
||||||
|
captcha bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"wrong password": {Account{Username: "me@example.com", Password: "wrong", TwoFA: true, Site: amazonAccount.Site}, false, "Ihr Passwort ist falsch"},
|
||||||
|
"captcha": {amazonAccount, true, "dibs login amazon --browser"},
|
||||||
|
"twofa off": {Account{Username: "me@example.com", Password: "hunter2", Site: amazonAccount.Site}, false, "twofa is off"},
|
||||||
|
"no password": {Account{Username: "me@example.com", Site: amazonAccount.Site}, false, "no password"},
|
||||||
|
} {
|
||||||
|
fake, s := newAmazonSession(t)
|
||||||
|
fake.captcha = tc.captcha
|
||||||
|
|
||||||
|
err := p.Login(context.Background(), s, tc.account)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tc.want) { t.Errorf("%s: got %v, want an error containing %q", name, err, tc.want) }
|
||||||
|
if _, _, session := fake.state(); session != "" { t.Errorf("%s: signed in", name) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pageSession serves saved real pages by path and refuses to send forms,
|
||||||
|
// recording them instead.
|
||||||
|
type pageSession struct {
|
||||||
|
pages map[string][]byte
|
||||||
|
posted []fetch.Request
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *pageSession) Do(_ context.Context, r fetch.Request) (*fetch.Response, error) {
|
||||||
|
if r.Method == "POST" {
|
||||||
|
s.posted = append(s.posted, r)
|
||||||
|
return nil, errors.New("stopped before posting")
|
||||||
|
}
|
||||||
|
|
||||||
|
u, _ := url.Parse(r.URL)
|
||||||
|
|
||||||
|
page, ok := s.pages[u.Path]
|
||||||
|
if !ok { return nil, errors.New("no saved page for " + u.Path) }
|
||||||
|
|
||||||
|
return fetch.NewResponse(r.URL, r.URL, 200, nil, page), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *pageSession) Click(context.Context, string, string) (*fetch.Response, error) {
|
||||||
|
return nil, errors.New("no clicks on saved pages")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *pageSession) Prompt(context.Context, string, bool) (string, error) { return "", errors.New("no prompts") }
|
||||||
|
func (s *pageSession) Cookies(string) map[string]string { return nil }
|
||||||
|
|
||||||
|
// TestAmazonSavedSessionPages runs the plugin on pages saved from a guest
|
||||||
|
// session on amazon.de: the sign-in page, an empty cart and a cart holding
|
||||||
|
// fakeASIN.
|
||||||
|
func TestAmazonSavedSessionPages(t *testing.T) {
|
||||||
|
p := builtin(t, "amazon")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
signin := savedPage(t, "session-signin-de")
|
||||||
|
empty := savedPage(t, "session-cart-guest-de")
|
||||||
|
full := savedPage(t, "session-cart-item-de")
|
||||||
|
|
||||||
|
product := "https://www.amazon.de/dp/" + fakeASIN
|
||||||
|
|
||||||
|
if _, err := p.AddToCart(ctx, &pageSession{pages: map[string][]byte{"/gp/cart/view.html": empty}}, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("guest cart: got %v, want ErrSignedOut", err) }
|
||||||
|
|
||||||
|
cart, err := p.AddToCart(ctx, &pageSession{pages: map[string][]byte{"/gp/cart/view.html": []byte(signedIn(full))}}, amazonAccount, product)
|
||||||
|
if err != nil || cart == "" { t.Errorf("cart holding the item: %q, %v, want it found without adding", cart, err) }
|
||||||
|
|
||||||
|
// The first step of signing in asks for the email only. Its password
|
||||||
|
// input is a hidden one for autofill.
|
||||||
|
s := &pageSession{pages: map[string][]byte{"/ap/signin": signin}}
|
||||||
|
if err := p.Login(ctx, s, amazonAccount); err == nil { t.Fatal("login went past the saved page") }
|
||||||
|
if len(s.posted) != 1 { t.Fatalf("%d forms posted, want 1", len(s.posted)) }
|
||||||
|
|
||||||
|
r := s.posted[0]
|
||||||
|
if !strings.HasPrefix(r.URL, "https://www.amazon.de/ax/claim?") { t.Errorf("posted to %s", r.URL) }
|
||||||
|
if r.Form.Get("email") != amazonAccount.Username { t.Errorf("email = %q", r.Form.Get("email")) }
|
||||||
|
if r.Form.Get("password") != "" { t.Error("the password went out with the email") }
|
||||||
|
if r.Form.Get("anti-csrftoken-a2z") == "" || r.Form.Get("appAction") != "SIGNIN_CLAIM_COLLECT" { t.Errorf("hidden fields missing: %v", r.Form) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,449 @@
|
|||||||
|
-- Built-in plugin for Amazon product pages (de, co.uk, fr, it, es, nl, com).
|
||||||
|
-- It uses only the public plugin API, so it doubles as the reference
|
||||||
|
-- implementation of a plugin.
|
||||||
|
|
||||||
|
local tlds = {
|
||||||
|
["de"] = "EUR",
|
||||||
|
["fr"] = "EUR",
|
||||||
|
["it"] = "EUR",
|
||||||
|
["es"] = "EUR",
|
||||||
|
["nl"] = "EUR",
|
||||||
|
["co.uk"] = "GBP",
|
||||||
|
["com"] = "USD",
|
||||||
|
}
|
||||||
|
|
||||||
|
-- Amazon's own merchant IDs. A page sold by Amazon carries one of them in
|
||||||
|
-- the buybox form.
|
||||||
|
local amazon_merchants = {
|
||||||
|
A3JWKAKR8XB7XF = true, -- amazon.de
|
||||||
|
A3P5ROKL5A1OLE = true, -- amazon.co.uk
|
||||||
|
A1X6FK5RDHNB96 = true, -- amazon.fr
|
||||||
|
A11IL2PNWYJU7H = true, -- amazon.it
|
||||||
|
A1AT7YVPFBWXBL = true, -- amazon.es
|
||||||
|
A17D2BRD4YMT0X = true, -- amazon.nl
|
||||||
|
ATVPDKIKX0DER = true, -- amazon.com
|
||||||
|
}
|
||||||
|
|
||||||
|
-- Any of these buttons means a new item can go into the cart. The preorder
|
||||||
|
-- selectors are unverified: no real preorder page has been checked yet.
|
||||||
|
-- "#add-to-cart-button-ubb" is deliberately missing: it belongs to the used
|
||||||
|
-- buybox, which Amazon shows when only used copies are left.
|
||||||
|
local buy_buttons = table.concat({
|
||||||
|
"#add-to-cart-button",
|
||||||
|
"#buy-now-button",
|
||||||
|
"input[name='submit.add-to-cart']",
|
||||||
|
"input[name='submit.buy-now']",
|
||||||
|
"input[name='submit.preorder']",
|
||||||
|
"#preorder-button",
|
||||||
|
}, ", ")
|
||||||
|
|
||||||
|
-- Where Amazon says an item can't be bought.
|
||||||
|
local availability_area = { "#availability", "#outOfStock", "#buybox" }
|
||||||
|
|
||||||
|
local unavailable_phrases = {
|
||||||
|
"currently unavailable",
|
||||||
|
"derzeit nicht verfügbar",
|
||||||
|
"actuellement indisponible",
|
||||||
|
"non disponibile",
|
||||||
|
"no disponible",
|
||||||
|
"momenteel niet verkrijgbaar",
|
||||||
|
}
|
||||||
|
|
||||||
|
-- Older layouts say who sells and ships the item in one sentence, such as
|
||||||
|
-- "Versand und Verkauf durch Amazon." or "Verkauf durch X und Versand durch
|
||||||
|
-- Amazon."
|
||||||
|
local sold_by_amazon_phrases = {
|
||||||
|
"sold by amazon",
|
||||||
|
"verkauf durch amazon",
|
||||||
|
"vendu par amazon",
|
||||||
|
"venduto da amazon",
|
||||||
|
"venduto e spedito da amazon",
|
||||||
|
"vendido por amazon",
|
||||||
|
"vendido y enviado por amazon",
|
||||||
|
"verkocht door amazon",
|
||||||
|
}
|
||||||
|
|
||||||
|
local shipped_by_amazon_phrases = {
|
||||||
|
"fulfilled by amazon",
|
||||||
|
"ships from amazon",
|
||||||
|
"dispatched from amazon",
|
||||||
|
"versand durch amazon",
|
||||||
|
"expédié par amazon",
|
||||||
|
"spedito da amazon",
|
||||||
|
"enviado por amazon",
|
||||||
|
"verzonden door amazon",
|
||||||
|
}
|
||||||
|
|
||||||
|
local price_selectors = {
|
||||||
|
"#corePrice_feature_div .a-price .a-offscreen",
|
||||||
|
"#corePriceDisplay_desktop_feature_div .priceToPay .a-offscreen",
|
||||||
|
"#apex_desktop .priceToPay .a-offscreen",
|
||||||
|
".priceToPay .a-offscreen",
|
||||||
|
"#price_inside_buybox",
|
||||||
|
"#priceblock_ourprice",
|
||||||
|
"#priceblock_dealprice",
|
||||||
|
}
|
||||||
|
|
||||||
|
-- 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
|
||||||
|
|
||||||
|
return tld, m[1]:upper()
|
||||||
|
end
|
||||||
|
|
||||||
|
-- Amazon itself appears as "Amazon", "Amazon.de", "Amazon EU S.à r.l." and
|
||||||
|
-- similar. Shops called "Amazonas Games" must not count.
|
||||||
|
local function is_amazon(name)
|
||||||
|
if not name then return false end
|
||||||
|
|
||||||
|
local n = name:lower():gsub("^%s+", ""):gsub("[%s%.]+$", "")
|
||||||
|
return n == "amazon" or n:match("^amazon%.[%a%.]+$") ~= nil or n:match("^amazon eu") ~= nil or n:match("^amazon media eu") ~= nil
|
||||||
|
end
|
||||||
|
|
||||||
|
local function legacy_merchant_info(doc)
|
||||||
|
return doc:text("#merchant-info") or doc:text("#merchantInfoFeature_feature_div")
|
||||||
|
end
|
||||||
|
|
||||||
|
-- sold_by_amazon is true or false when the page says who sells the item, and
|
||||||
|
-- nil when it doesn't, e.g. when there is no offer at all.
|
||||||
|
local function sold_by_amazon(doc)
|
||||||
|
-- The buybox form names the merchant whose offer the buttons buy.
|
||||||
|
local id = doc:attr("input#merchantID, input[name='merchantID']", "value")
|
||||||
|
if id and id ~= "" then return amazon_merchants[id] == true end
|
||||||
|
|
||||||
|
-- Newer layout: a "Verkäufer" / "Sold by" row.
|
||||||
|
local name = doc:text("#merchantInfoFeature_feature_div .offer-display-feature-text-message")
|
||||||
|
if name then return is_amazon(name) end
|
||||||
|
|
||||||
|
local info = legacy_merchant_info(doc)
|
||||||
|
if info then return contains_any(info, sold_by_amazon_phrases) end
|
||||||
|
|
||||||
|
if doc:exists("#sellerProfileTriggerId") then return false end
|
||||||
|
|
||||||
|
return nil
|
||||||
|
end
|
||||||
|
|
||||||
|
local function shipped_by_amazon(doc)
|
||||||
|
-- Newer layout: a "Versand" / "Ships from" row.
|
||||||
|
local name = doc:text("#fulfillerInfoFeature_feature_div .offer-display-feature-text-message")
|
||||||
|
if name then return is_amazon(name) end
|
||||||
|
|
||||||
|
return contains_any(legacy_merchant_info(doc), shipped_by_amazon_phrases)
|
||||||
|
end
|
||||||
|
|
||||||
|
local function seller(doc)
|
||||||
|
local sold = sold_by_amazon(doc)
|
||||||
|
|
||||||
|
if sold == nil then return "unknown" end
|
||||||
|
if sold then return "first_party" end
|
||||||
|
if shipped_by_amazon(doc) then return "fulfilled" end
|
||||||
|
|
||||||
|
return "third_party"
|
||||||
|
end
|
||||||
|
|
||||||
|
local function unavailable(doc)
|
||||||
|
for _, sel in ipairs(availability_area) do
|
||||||
|
if contains_any(doc:text(sel), unavailable_phrases) then return true end
|
||||||
|
end
|
||||||
|
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
|
||||||
|
local function find_price(doc)
|
||||||
|
for _, sel in ipairs(price_selectors) do
|
||||||
|
local value, currency = parse_price(doc:text(sel))
|
||||||
|
if value then return value, currency end
|
||||||
|
end
|
||||||
|
|
||||||
|
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,
|
||||||
|
|
||||||
|
-- Every variant of a product URL becomes https://www.amazon.<tld>/dp/<ASIN>,
|
||||||
|
-- so the same item is never watched twice.
|
||||||
|
normalize = function(url)
|
||||||
|
local tld, asin = split(url)
|
||||||
|
if not tld then return url end
|
||||||
|
|
||||||
|
return "https://www.amazon." .. tld .. "/dp/" .. asin
|
||||||
|
end,
|
||||||
|
|
||||||
|
parse = function(doc, url)
|
||||||
|
local tld, asin = split(url)
|
||||||
|
local title = doc:text("#productTitle")
|
||||||
|
local value, currency = find_price(doc)
|
||||||
|
|
||||||
|
return {
|
||||||
|
title = title,
|
||||||
|
-- A dog page or a search result has no product title, so it is
|
||||||
|
-- never available.
|
||||||
|
available = title ~= nil and doc:exists(buy_buttons) and not unavailable(doc),
|
||||||
|
price = value,
|
||||||
|
currency = currency or (tld and tlds[tld]),
|
||||||
|
seller = seller(doc),
|
||||||
|
id = asin,
|
||||||
|
}
|
||||||
|
end,
|
||||||
|
|
||||||
|
cart_link = function(url, id)
|
||||||
|
local tld, asin = split(url)
|
||||||
|
if not tld then return nil end
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/PuerkitoBio/goquery"
|
||||||
|
"github.com/andybalholm/cascadia"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
"golang.org/x/net/html"
|
||||||
|
)
|
||||||
|
|
||||||
|
const nodeType = "dibs.node"
|
||||||
|
|
||||||
|
// nodeMethods are the methods of doc and of the nodes doc:all() returns.
|
||||||
|
// Each takes an optional CSS selector: without one it works on the node
|
||||||
|
// itself, with one on the first match inside it.
|
||||||
|
var nodeMethods = map[string]lua.LGFunction{
|
||||||
|
"text": nodeText,
|
||||||
|
"attr": nodeAttr,
|
||||||
|
"exists": nodeExists,
|
||||||
|
"count": nodeCount,
|
||||||
|
"html": nodeHTML,
|
||||||
|
"all": nodeAll,
|
||||||
|
}
|
||||||
|
|
||||||
|
func registerNode(L *lua.LState) {
|
||||||
|
mt := L.NewTypeMetatable(nodeType)
|
||||||
|
L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), nodeMethods))
|
||||||
|
}
|
||||||
|
|
||||||
|
func pushNode(L *lua.LState, sel *goquery.Selection) lua.LValue {
|
||||||
|
ud := L.NewUserData()
|
||||||
|
ud.Value = sel
|
||||||
|
L.SetMetatable(ud, L.GetTypeMetatable(nodeType))
|
||||||
|
|
||||||
|
return ud
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkNode(L *lua.LState) *goquery.Selection {
|
||||||
|
if ud, ok := L.Get(1).(*lua.LUserData); ok {
|
||||||
|
if sel, ok := ud.Value.(*goquery.Selection); ok { return sel }
|
||||||
|
}
|
||||||
|
|
||||||
|
L.ArgError(1, "node expected (call methods with a colon, as in doc:text(...))")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// target is the node itself, or what the selector in argument arg matches
|
||||||
|
// inside it.
|
||||||
|
func target(L *lua.LState, node *goquery.Selection, arg int) *goquery.Selection {
|
||||||
|
if L.GetTop() < arg || L.Get(arg) == lua.LNil { return node }
|
||||||
|
|
||||||
|
return node.FindMatcher(selector(L, arg))
|
||||||
|
}
|
||||||
|
|
||||||
|
var selectors sync.Map // string -> cascadia.Selector
|
||||||
|
|
||||||
|
func selector(L *lua.LState, arg int) cascadia.Selector {
|
||||||
|
src := L.CheckString(arg)
|
||||||
|
if s, ok := selectors.Load(src); ok { return s.(cascadia.Selector) }
|
||||||
|
|
||||||
|
s, err := cascadia.Compile(src)
|
||||||
|
if err != nil {
|
||||||
|
L.ArgError(arg, "invalid selector "+src+": "+err.Error())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
selectors.Store(src, s)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// node:text([sel]) is the visible text of the node or its first match, with
|
||||||
|
// whitespace collapsed. It is nil if nothing matches or the text is empty,
|
||||||
|
// so `if doc:text(sel) then` means "has text"; exists tests presence.
|
||||||
|
func nodeText(L *lua.LState) int {
|
||||||
|
s := target(L, checkNode(L), 2).First()
|
||||||
|
|
||||||
|
text := ""
|
||||||
|
if s.Length() > 0 { text = visibleText(s) }
|
||||||
|
|
||||||
|
if text == "" { L.Push(lua.LNil) } else { L.Push(lua.LString(text)) }
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// node:attr(name) or node:attr(sel, name) is an attribute value, or nil.
|
||||||
|
func nodeAttr(L *lua.LState) int {
|
||||||
|
node := checkNode(L)
|
||||||
|
|
||||||
|
s, name := node, L.CheckString(2)
|
||||||
|
if L.GetTop() >= 3 { s, name = target(L, node, 2), L.CheckString(3) }
|
||||||
|
|
||||||
|
if v, ok := s.First().Attr(name); ok { L.Push(lua.LString(v)) } else { L.Push(lua.LNil) }
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// node:exists(sel) reports whether sel matches anything.
|
||||||
|
func nodeExists(L *lua.LState) int {
|
||||||
|
L.Push(lua.LBool(checkNode(L).FindMatcher(selector(L, 2)).Length() > 0))
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// node:count(sel) is the number of matches.
|
||||||
|
func nodeCount(L *lua.LState) int {
|
||||||
|
L.Push(lua.LNumber(checkNode(L).FindMatcher(selector(L, 2)).Length()))
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// node:html([sel]) is the outer HTML of the node or its first match, or nil.
|
||||||
|
func nodeHTML(L *lua.LState) int {
|
||||||
|
s := target(L, checkNode(L), 2).First()
|
||||||
|
if s.Length() == 0 {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := goquery.OuterHtml(s)
|
||||||
|
if err != nil { L.RaiseError("html: %v", err) }
|
||||||
|
|
||||||
|
L.Push(lua.LString(out))
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// node:all(sel) is a list of nodes, one per match.
|
||||||
|
func nodeAll(L *lua.LState) int {
|
||||||
|
t := L.NewTable()
|
||||||
|
checkNode(L).FindMatcher(selector(L, 2)).Each(func(_ int, s *goquery.Selection) { t.Append(pushNode(L, s)) })
|
||||||
|
|
||||||
|
L.Push(t)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// hiddenElements never contribute visible text. Amazon puts large inline
|
||||||
|
// scripts inside its availability block, for example.
|
||||||
|
var hiddenElements = map[string]bool{"script": true, "style": true, "noscript": true, "template": true}
|
||||||
|
|
||||||
|
// inlineElements run into the text around them. Other elements are
|
||||||
|
// separated by a space, so "<li>a</li><li>b</li>" reads "a b".
|
||||||
|
var inlineElements = map[string]bool{
|
||||||
|
"a": true, "abbr": true, "b": true, "bdi": true, "bdo": true, "cite": true, "code": true, "data": true,
|
||||||
|
"em": true, "i": true, "kbd": true, "mark": true, "q": true, "s": true, "small": true, "span": true,
|
||||||
|
"strong": true, "sub": true, "sup": true, "time": true, "u": true, "var": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
func visibleText(s *goquery.Selection) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, n := range s.Nodes { writeText(&b, n) }
|
||||||
|
|
||||||
|
return strings.Join(strings.Fields(b.String()), " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeText(b *strings.Builder, n *html.Node) {
|
||||||
|
switch n.Type {
|
||||||
|
case html.TextNode:
|
||||||
|
b.WriteString(n.Data)
|
||||||
|
case html.ElementNode:
|
||||||
|
if hiddenElements[n.Data] { return }
|
||||||
|
|
||||||
|
block := !inlineElements[n.Data]
|
||||||
|
if block { b.WriteByte(' ') }
|
||||||
|
for c := n.FirstChild; c != nil; c = c.NextSibling { writeText(b, c) }
|
||||||
|
if block { b.WriteByte(' ') }
|
||||||
|
case html.DocumentNode:
|
||||||
|
for c := n.FirstChild; c != nil; c = c.NextSibling { writeText(b, c) }
|
||||||
|
default:
|
||||||
|
// Comments and doctypes have no visible text.
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log/slog"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/price"
|
||||||
|
)
|
||||||
|
|
||||||
|
func registerHelpers(L *lua.LState, logger *slog.Logger) {
|
||||||
|
logFn := L.NewFunction(func(L *lua.LState) int {
|
||||||
|
parts := make([]string, L.GetTop())
|
||||||
|
for i := range parts { parts[i] = L.ToStringMeta(L.Get(i + 1)).String() }
|
||||||
|
|
||||||
|
logger.Info(strings.Join(parts, " "))
|
||||||
|
return 0
|
||||||
|
})
|
||||||
|
|
||||||
|
L.SetGlobal("log", logFn)
|
||||||
|
L.SetGlobal("print", logFn)
|
||||||
|
L.SetGlobal("contains_any", L.NewFunction(containsAny))
|
||||||
|
L.SetGlobal("parse_price", L.NewFunction(parsePrice))
|
||||||
|
L.SetGlobal("regex_match", L.NewFunction(regexMatch))
|
||||||
|
}
|
||||||
|
|
||||||
|
// contains_any(str, {phrases}) reports whether str contains any of the
|
||||||
|
// phrases, ignoring case. A nil str contains nothing.
|
||||||
|
func containsAny(L *lua.LState) int {
|
||||||
|
phrases := L.CheckTable(2)
|
||||||
|
if L.Get(1) == lua.LNil {
|
||||||
|
L.Push(lua.LFalse)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
s := strings.ToLower(L.CheckString(1))
|
||||||
|
found := false
|
||||||
|
|
||||||
|
phrases.ForEach(func(_, v lua.LValue) {
|
||||||
|
if p, ok := v.(lua.LString); ok && !found && strings.Contains(s, strings.ToLower(string(p))) { found = true }
|
||||||
|
})
|
||||||
|
|
||||||
|
L.Push(lua.LBool(found))
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse_price(str) returns the price in str and its currency code (or nil),
|
||||||
|
// or nil if str holds no price.
|
||||||
|
func parsePrice(L *lua.LState) int {
|
||||||
|
if L.Get(1) == lua.LNil {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
v, cur, ok := price.Parse(L.CheckString(1))
|
||||||
|
if !ok {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
L.Push(lua.LNumber(v))
|
||||||
|
if cur != "" { L.Push(lua.LString(cur)) } else { L.Push(lua.LNil) }
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
var regexps sync.Map // string -> *regexp.Regexp
|
||||||
|
|
||||||
|
// regex_match(str, pattern) matches a Go (RE2) regular expression. It
|
||||||
|
// returns a list of the capture groups, or of the whole match if the
|
||||||
|
// pattern has no groups, or nil if it does not match.
|
||||||
|
func regexMatch(L *lua.LState) int {
|
||||||
|
pattern := L.CheckString(2)
|
||||||
|
if L.Get(1) == lua.LNil {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
s := L.CheckString(1)
|
||||||
|
|
||||||
|
var re *regexp.Regexp
|
||||||
|
if cached, ok := regexps.Load(pattern); ok {
|
||||||
|
re = cached.(*regexp.Regexp)
|
||||||
|
} else {
|
||||||
|
compiled, err := regexp.Compile(pattern)
|
||||||
|
if err != nil { L.ArgError(2, "invalid pattern: "+err.Error()) }
|
||||||
|
|
||||||
|
re = compiled
|
||||||
|
regexps.Store(pattern, re)
|
||||||
|
}
|
||||||
|
|
||||||
|
m := re.FindStringSubmatch(s)
|
||||||
|
if m == nil {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(m) > 1 { m = m[1:] }
|
||||||
|
|
||||||
|
t := L.NewTable()
|
||||||
|
for _, g := range m { t.Append(lua.LString(g)) }
|
||||||
|
|
||||||
|
L.Push(t)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"embed"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"log/slog"
|
||||||
|
"maps"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed builtin/*.lua
|
||||||
|
var builtinFS embed.FS
|
||||||
|
|
||||||
|
// ErrNoPlugin is returned when no plugin matches a URL.
|
||||||
|
var ErrNoPlugin = errors.New("no plugin matches the URL")
|
||||||
|
|
||||||
|
func Builtins() []string {
|
||||||
|
files, _ := fs.Glob(builtinFS, "builtin/*.lua")
|
||||||
|
|
||||||
|
names := make([]string, len(files))
|
||||||
|
for i, f := range files { names[i] = strings.TrimSuffix(strings.TrimPrefix(f, "builtin/"), ".lua") }
|
||||||
|
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
func BuiltinSource(name string) ([]byte, error) {
|
||||||
|
return builtinFS.ReadFile("builtin/" + name + ".lua")
|
||||||
|
}
|
||||||
|
|
||||||
|
type Host struct {
|
||||||
|
plugins map[string]*Plugin
|
||||||
|
// order is the order ForURL tries plugins in: user plugins first, so
|
||||||
|
// they win over built-ins they don't replace.
|
||||||
|
order []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHost loads the built-in plugins and the user's (name -> file). A user
|
||||||
|
// plugin replaces a built-in one of the same name.
|
||||||
|
func NewHost(user map[string]string, limits Limits, logger *slog.Logger) (*Host, error) {
|
||||||
|
h := &Host{plugins: map[string]*Plugin{}}
|
||||||
|
|
||||||
|
var errs []error
|
||||||
|
|
||||||
|
for _, name := range slices.Sorted(maps.Keys(user)) {
|
||||||
|
code, err := os.ReadFile(user[name])
|
||||||
|
if err != nil {
|
||||||
|
errs = append(errs, fmt.Errorf("plugin %s: %w", name, err))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
p, err := Load(name, user[name], code, limits, logger)
|
||||||
|
if err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
h.plugins[name] = p
|
||||||
|
h.order = append(h.order, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name := range Builtins() {
|
||||||
|
if _, replaced := user[name]; replaced { continue }
|
||||||
|
|
||||||
|
code, err := BuiltinSource(name)
|
||||||
|
if err == nil {
|
||||||
|
var p *Plugin
|
||||||
|
if p, err = Load(name, "built-in", code, limits, logger); err == nil {
|
||||||
|
h.plugins[name] = p
|
||||||
|
h.order = append(h.order, name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(errs) > 0 {
|
||||||
|
h.Close()
|
||||||
|
return nil, errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Host) Plugin(name string) (*Plugin, bool) {
|
||||||
|
p, ok := h.plugins[name]
|
||||||
|
return p, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// ForURL returns the first plugin whose matches(url) is true.
|
||||||
|
func (h *Host) ForURL(ctx context.Context, url string) (*Plugin, error) {
|
||||||
|
for _, name := range h.order {
|
||||||
|
p := h.plugins[name]
|
||||||
|
|
||||||
|
ok, err := p.Matches(ctx, url)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
if ok { return p, nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, ErrNoPlugin
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Host) Close() {
|
||||||
|
for _, p := range h.plugins { p.Close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Report is the outcome of checking one URL, as `dibs check` prints it.
|
||||||
|
type Report struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
FetchURL string `json:"fetch_url"`
|
||||||
|
FinalURL string `json:"final_url"`
|
||||||
|
Shop string `json:"shop"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
Verdict string `json:"verdict"`
|
||||||
|
Challenge string `json:"challenge,omitempty"`
|
||||||
|
Result *Result `json:"result,omitempty"`
|
||||||
|
CartLink string `json:"cart_link,omitempty"`
|
||||||
|
ElapsedMS int64 `json:"elapsed_ms"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evaluate turns a fetched page into a Report. Only pages with the OK
|
||||||
|
// verdict are parsed. A NotFound page is reported as unavailable without
|
||||||
|
// asking the plugin, and bot checks and errors have no result.
|
||||||
|
func Evaluate(ctx context.Context, p *Plugin, rawURL string, resp *fetch.Response) (*Report, error) {
|
||||||
|
r := &Report{
|
||||||
|
URL: rawURL,
|
||||||
|
FetchURL: resp.URL,
|
||||||
|
FinalURL: resp.FinalURL,
|
||||||
|
Shop: p.Name,
|
||||||
|
Status: resp.Status,
|
||||||
|
Verdict: resp.Verdict.String(),
|
||||||
|
Challenge: resp.Challenge,
|
||||||
|
ElapsedMS: resp.Elapsed.Milliseconds(),
|
||||||
|
}
|
||||||
|
|
||||||
|
switch resp.Verdict {
|
||||||
|
case fetch.OK:
|
||||||
|
res, err := p.Parse(ctx, resp.Body, resp.URL)
|
||||||
|
if err != nil { return r, err }
|
||||||
|
|
||||||
|
r.Result = res
|
||||||
|
|
||||||
|
link, err := p.CartLink(ctx, resp.URL, res.ID)
|
||||||
|
if err != nil { return r, err }
|
||||||
|
|
||||||
|
r.CartLink = link
|
||||||
|
case fetch.NotFound:
|
||||||
|
r.Result = &Result{Seller: SellerUnknown}
|
||||||
|
default:
|
||||||
|
// Challenge, Blocked or HTTPError: nothing to read.
|
||||||
|
}
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/pelletier/go-toml/v2"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fixtures"
|
||||||
|
)
|
||||||
|
|
||||||
|
// testdata is the repository's top-level testdata directory.
|
||||||
|
var testdata = filepath.Join("..", "..", "testdata")
|
||||||
|
|
||||||
|
func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
|
||||||
|
|
||||||
|
func builtin(t *testing.T, name string) *Plugin {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
code, err := BuiltinSource(name)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
p, err := Load(name, "built-in", code, DefaultLimits(), discardLogger())
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
t.Cleanup(p.Close)
|
||||||
|
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSavedPages re-reads every page `dibs fixtures` saved and checks the
|
||||||
|
// plugin still reports what it reported when the page was fetched.
|
||||||
|
func TestSavedPages(t *testing.T) {
|
||||||
|
suites, err := fixtures.Load(testdata)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
ran := 0
|
||||||
|
|
||||||
|
for _, suite := range suites {
|
||||||
|
if !slices.Contains(Builtins(), suite.Shop) { continue }
|
||||||
|
|
||||||
|
p := builtin(t, suite.Shop)
|
||||||
|
|
||||||
|
for _, c := range suite.Cases {
|
||||||
|
page, err := os.ReadFile(suite.PagePath(c))
|
||||||
|
if errors.Is(err, fs.ErrNotExist) { continue }
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
ran++
|
||||||
|
|
||||||
|
t.Run(suite.Shop+"/"+c.Name, func(t *testing.T) {
|
||||||
|
want, err := os.ReadFile(suite.ReportPath(c))
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var saved Report
|
||||||
|
if err := json.Unmarshal(want, &saved); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
report, err := Evaluate(context.Background(), p, saved.URL, fetch.NewResponse(saved.FetchURL, saved.FinalURL, saved.Status, nil, page))
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
got, err := fixtures.EncodeReport(report)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
if !bytes.Equal(got, want) { t.Errorf("%s (%s) now reads differently.\ngot:\n%s\nsaved:\n%s", c.Name, c.Note, got, want) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ran == 0 { t.Skip("no saved pages: run `dibs fixtures` to fetch them") }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAmazonNormalize(t *testing.T) {
|
||||||
|
data, err := os.ReadFile(filepath.Join(testdata, "amazon", "urls.toml"))
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
var urls struct {
|
||||||
|
Normalize []struct {
|
||||||
|
In string `toml:"in"`
|
||||||
|
Out string `toml:"out"`
|
||||||
|
} `toml:"normalize"`
|
||||||
|
}
|
||||||
|
if err := toml.Unmarshal(data, &urls); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
p := builtin(t, "amazon")
|
||||||
|
|
||||||
|
for _, u := range urls.Normalize {
|
||||||
|
got, err := p.Normalize(context.Background(), u.In)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
if got != u.Out { t.Errorf("normalize(%q) = %q, want %q", u.In, got, u.Out) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
// Package plugin runs shop plugins: sandboxed Lua files that read product
|
||||||
|
// pages.
|
||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"math"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/PuerkitoBio/goquery"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The sellers parse reports.
|
||||||
|
const (
|
||||||
|
// SellerFirstParty means the shop itself sells the item.
|
||||||
|
SellerFirstParty = "first_party"
|
||||||
|
// SellerFulfilled means a marketplace seller sells the item and the shop
|
||||||
|
// ships it, as with Fulfilled by Amazon.
|
||||||
|
SellerFulfilled = "fulfilled"
|
||||||
|
// SellerThirdParty means a marketplace seller sells and ships the item.
|
||||||
|
SellerThirdParty = "third_party"
|
||||||
|
SellerUnknown = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Result is what a plugin's parse function read from a page.
|
||||||
|
type Result struct {
|
||||||
|
Title string `json:"title,omitempty"`
|
||||||
|
Available bool `json:"available"`
|
||||||
|
Price *float64 `json:"price"`
|
||||||
|
Currency string `json:"currency,omitempty"`
|
||||||
|
Seller string `json:"seller"`
|
||||||
|
// ID is the shop's product ID, such as an ASIN. It is passed to
|
||||||
|
// cart_link.
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// plugin run one at a time.
|
||||||
|
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
|
||||||
|
limits Limits
|
||||||
|
logger *slog.Logger
|
||||||
|
nameFixed bool // the name came from the config, not the table
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
state *lua.LState
|
||||||
|
funcs map[string]*lua.LFunction
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load runs a plugin's code and checks the table it returns. An empty name
|
||||||
|
// takes the name from the table, or else from the file name.
|
||||||
|
func Load(name, source string, code []byte, limits Limits, logger *slog.Logger) (*Plugin, error) {
|
||||||
|
chunk := filepath.Base(source)
|
||||||
|
if source == "built-in" { chunk = name + ".lua" }
|
||||||
|
|
||||||
|
p := &Plugin{
|
||||||
|
Name: name,
|
||||||
|
Source: source,
|
||||||
|
chunk: chunk,
|
||||||
|
code: code,
|
||||||
|
limits: limits,
|
||||||
|
logger: logger,
|
||||||
|
nameFixed: name != "",
|
||||||
|
}
|
||||||
|
if !p.nameFixed { p.Name = strings.TrimSuffix(chunk, ".lua") }
|
||||||
|
|
||||||
|
shortCalls.Lock()
|
||||||
|
defer shortCalls.Unlock()
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// reset loads the plugin into a fresh Lua state. Callers hold shortCalls.
|
||||||
|
func (p *Plugin) reset() error {
|
||||||
|
if p.state != nil {
|
||||||
|
p.state.Close()
|
||||||
|
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))
|
||||||
|
|
||||||
|
fn, err := L.Load(bytes.NewReader(p.code), p.chunk)
|
||||||
|
if err != nil {
|
||||||
|
L.Close()
|
||||||
|
return nil, nil, luaError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var t *table
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
tbl, ok := ret.(*lua.LTable)
|
||||||
|
if !ok { return fmt.Errorf("must return a table, got %s", ret.Type()) }
|
||||||
|
|
||||||
|
read, err := p.readTable(tbl)
|
||||||
|
t = read
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
L.Close()
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return L, t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// readTable checks the plugin table and picks up its functions.
|
||||||
|
func (p *Plugin) readTable(tbl *lua.LTable) (*table, error) {
|
||||||
|
var problems []string
|
||||||
|
|
||||||
|
t := &table{funcs: map[string]*lua.LFunction{}}
|
||||||
|
|
||||||
|
tbl.ForEach(func(k, v lua.LValue) {
|
||||||
|
key := k.String()
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case key == "name":
|
||||||
|
s, ok := v.(lua.LString)
|
||||||
|
switch {
|
||||||
|
case !ok || s == "":
|
||||||
|
problems = append(problems, fmt.Sprintf("name must be a non-empty string, got %s", v.Type()))
|
||||||
|
case !p.nameFixed:
|
||||||
|
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 { 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: %s, %s)", key, strings.Join(tableKeys, ", "), strings.Join(hooks, ", ")))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
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 nil, errors.New(strings.Join(problems, "; "))
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Has(hook string) bool {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
return p.funcs[hook] != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// call runs a short hook, one of matches, normalize, parse and cart_link.
|
||||||
|
// args builds the arguments in the plugin's Lua state.
|
||||||
|
func (p *Plugin) call(ctx context.Context, hook string, nret int, args func(L *lua.LState) []lua.LValue) ([]lua.LValue, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
shortCalls.Lock()
|
||||||
|
defer shortCalls.Unlock()
|
||||||
|
|
||||||
|
// An earlier call was killed and reloading failed.
|
||||||
|
if p.state == nil {
|
||||||
|
if err := p.reset(); err != nil { return nil, fmt.Errorf("plugin %s: %w", p.Name, err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
L := p.state
|
||||||
|
|
||||||
|
var out []lua.LValue
|
||||||
|
|
||||||
|
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)) }
|
||||||
|
L.Pop(nret)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
// A killed call can stop anywhere, so the state is rebuilt from scratch.
|
||||||
|
if errors.Is(err, ErrTimeout) || errors.Is(err, ErrMemoryLimit) {
|
||||||
|
if rerr := p.reset(); rerr != nil { p.logger.Error("reloading plugin failed", "plugin", p.Name, "err", rerr) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil { return nil, fmt.Errorf("plugin %s: %s: %w", p.Name, hook, err) }
|
||||||
|
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Matches runs matches(url). A plugin without it matches nothing.
|
||||||
|
func (p *Plugin) Matches(ctx context.Context, url string) (bool, error) {
|
||||||
|
if !p.Has("matches") { return false, nil }
|
||||||
|
|
||||||
|
out, err := p.call(ctx, "matches", 1, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(url)} })
|
||||||
|
if err != nil { return false, err }
|
||||||
|
|
||||||
|
return lua.LVAsBool(out[0]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize runs normalize(url). Without it, or if it returns nil, the URL
|
||||||
|
// stays as it is.
|
||||||
|
func (p *Plugin) Normalize(ctx context.Context, url string) (string, error) {
|
||||||
|
if !p.Has("normalize") { return url, nil }
|
||||||
|
|
||||||
|
out, err := p.call(ctx, "normalize", 1, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(url)} })
|
||||||
|
if err != nil { return "", err }
|
||||||
|
|
||||||
|
switch v := out[0].(type) {
|
||||||
|
case lua.LString:
|
||||||
|
return string(v), nil
|
||||||
|
case *lua.LNilType:
|
||||||
|
return url, nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("plugin %s: normalize must return a string, got %s", p.Name, v.Type())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Parse(ctx context.Context, page []byte, url string) (*Result, error) {
|
||||||
|
// The HTML is parsed before the call, so parsing does not count against
|
||||||
|
// the call's time and memory.
|
||||||
|
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page))
|
||||||
|
if err != nil { return nil, fmt.Errorf("parsing HTML: %w", err) }
|
||||||
|
|
||||||
|
out, err := p.call(ctx, "parse", 1, func(L *lua.LState) []lua.LValue { return []lua.LValue{pushNode(L, doc.Selection), lua.LString(url)} })
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
r, err := toResult(out[0])
|
||||||
|
if err != nil { return nil, fmt.Errorf("plugin %s: parse: %w", p.Name, err) }
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CartLink runs cart_link(url, id). It returns "" if the plugin has no
|
||||||
|
// cart_link or it returns nil.
|
||||||
|
func (p *Plugin) CartLink(ctx context.Context, url, id string) (string, error) {
|
||||||
|
if !p.Has("cart_link") { return "", nil }
|
||||||
|
|
||||||
|
out, err := p.call(ctx, "cart_link", 1, func(*lua.LState) []lua.LValue {
|
||||||
|
idArg := lua.LValue(lua.LNil)
|
||||||
|
if id != "" { idArg = lua.LString(id) }
|
||||||
|
|
||||||
|
return []lua.LValue{lua.LString(url), idArg}
|
||||||
|
})
|
||||||
|
if err != nil { return "", err }
|
||||||
|
|
||||||
|
switch v := out[0].(type) {
|
||||||
|
case lua.LString:
|
||||||
|
return string(v), nil
|
||||||
|
case *lua.LNilType:
|
||||||
|
return "", nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("plugin %s: cart_link must return a string, got %s", p.Name, v.Type())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) Close() {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
if p.state != nil {
|
||||||
|
p.state.Close()
|
||||||
|
p.state = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// toResult checks parse's return value field by field.
|
||||||
|
func toResult(v lua.LValue) (*Result, error) {
|
||||||
|
t, ok := v.(*lua.LTable)
|
||||||
|
if !ok { return nil, fmt.Errorf("must return a table, got %s", v.Type()) }
|
||||||
|
|
||||||
|
r := &Result{Seller: SellerUnknown}
|
||||||
|
|
||||||
|
var problems []string
|
||||||
|
|
||||||
|
bad := func(format string, args ...any) { problems = append(problems, fmt.Sprintf(format, args...)) }
|
||||||
|
|
||||||
|
hasAvailable := false
|
||||||
|
|
||||||
|
t.ForEach(func(k, val lua.LValue) {
|
||||||
|
key := k.String()
|
||||||
|
|
||||||
|
switch key {
|
||||||
|
case "title":
|
||||||
|
if s, ok := val.(lua.LString); ok { r.Title = strings.TrimSpace(string(s)) } else { bad("title must be a string or nil, got %s", val.Type()) }
|
||||||
|
case "available":
|
||||||
|
b, ok := val.(lua.LBool)
|
||||||
|
if !ok {
|
||||||
|
bad("available must be true or false, got %s", val.Type())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Available, hasAvailable = bool(b), true
|
||||||
|
case "price":
|
||||||
|
n, ok := val.(lua.LNumber)
|
||||||
|
switch f := float64(n); {
|
||||||
|
case !ok:
|
||||||
|
bad("price must be a number or nil, got %s", val.Type())
|
||||||
|
case f < 0 || math.IsInf(f, 0) || math.IsNaN(f):
|
||||||
|
bad("price must be a positive number, got %v", f)
|
||||||
|
default:
|
||||||
|
r.Price = &f
|
||||||
|
}
|
||||||
|
case "currency":
|
||||||
|
s, ok := val.(lua.LString)
|
||||||
|
if c := strings.ToUpper(string(s)); ok && currencyRe.MatchString(c) { r.Currency = c } else { bad("currency must be a 3-letter code such as EUR or nil, got %s", val) }
|
||||||
|
case "seller":
|
||||||
|
s, ok := val.(lua.LString)
|
||||||
|
switch string(s) {
|
||||||
|
case SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown:
|
||||||
|
if ok { r.Seller = string(s) }
|
||||||
|
default:
|
||||||
|
bad("seller must be %q, %q, %q or %q, got %s", SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown, val)
|
||||||
|
}
|
||||||
|
case "id":
|
||||||
|
if s, ok := val.(lua.LString); ok { r.ID = string(s) } else { bad("id must be a string or nil, got %s", val.Type()) }
|
||||||
|
default:
|
||||||
|
bad("unknown field %q", key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if !hasAvailable && !slices.ContainsFunc(problems, func(s string) bool { return strings.HasPrefix(s, "available ") }) {
|
||||||
|
bad("available is missing")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(problems) > 0 {
|
||||||
|
slices.Sort(problems)
|
||||||
|
return nil, errors.New(strings.Join(problems, "; "))
|
||||||
|
}
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"runtime/metrics"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Limits cap every Lua call. They come from [sandbox] in dibs.toml.
|
||||||
|
type Limits struct {
|
||||||
|
// Timeout applies to loading a plugin and to matches, normalize, parse
|
||||||
|
// and cart_link.
|
||||||
|
Timeout time.Duration
|
||||||
|
// SessionTimeout applies to login and add_to_cart.
|
||||||
|
SessionTimeout time.Duration
|
||||||
|
// MemoryBytes is the heap growth one call may cause. It is measured for
|
||||||
|
// the whole process, so it is approximate.
|
||||||
|
MemoryBytes int64
|
||||||
|
// CallStack is the maximum Lua call depth.
|
||||||
|
CallStack int
|
||||||
|
}
|
||||||
|
|
||||||
|
func DefaultLimits() Limits {
|
||||||
|
return Limits{
|
||||||
|
Timeout: config.DefaultSandboxTimeout,
|
||||||
|
SessionTimeout: config.DefaultSessionTimeout,
|
||||||
|
MemoryBytes: config.DefaultMemoryMB << 20,
|
||||||
|
CallStack: config.DefaultCallStack,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func LimitsFrom(s config.Sandbox) Limits {
|
||||||
|
return Limits{
|
||||||
|
Timeout: s.Timeout.Duration,
|
||||||
|
SessionTimeout: s.SessionTimeout.Duration,
|
||||||
|
MemoryBytes: int64(s.MemoryMB) << 20,
|
||||||
|
CallStack: s.CallStack,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrTimeout = errors.New("timed out")
|
||||||
|
ErrMemoryLimit = errors.New("exceeded the memory limit")
|
||||||
|
)
|
||||||
|
|
||||||
|
// removedGlobals could load code, or reach the interpreter's internals.
|
||||||
|
// The os, io, debug, package and coroutine libraries are never opened.
|
||||||
|
var removedGlobals = []string{
|
||||||
|
"dofile", "loadfile", "load", "loadstring", "require", "module",
|
||||||
|
"collectgarbage", "getfenv", "setfenv", "newproxy", "_printregs",
|
||||||
|
}
|
||||||
|
|
||||||
|
// shortCalls lets one parse-type call run at a time, so the heap growth the
|
||||||
|
// memory watchdog sees is that call's. These calls take milliseconds.
|
||||||
|
var shortCalls sync.Mutex
|
||||||
|
|
||||||
|
const watchInterval = 2 * time.Millisecond
|
||||||
|
|
||||||
|
func newState(limits Limits) *lua.LState {
|
||||||
|
L := lua.NewState(lua.Options{
|
||||||
|
SkipOpenLibs: true,
|
||||||
|
CallStackSize: limits.CallStack,
|
||||||
|
RegistrySize: 16 * 1024,
|
||||||
|
RegistryMaxSize: 256 * 1024,
|
||||||
|
MinimizeStackMemory: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, lib := range []struct {
|
||||||
|
name string
|
||||||
|
open lua.LGFunction
|
||||||
|
} {
|
||||||
|
{lua.BaseLibName, lua.OpenBase},
|
||||||
|
{lua.TabLibName, lua.OpenTable},
|
||||||
|
{lua.StringLibName, lua.OpenString},
|
||||||
|
{lua.MathLibName, lua.OpenMath},
|
||||||
|
} {
|
||||||
|
L.Push(L.NewFunction(lib.open))
|
||||||
|
L.Push(lua.LString(lib.name))
|
||||||
|
L.Call(1, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, name := range removedGlobals { L.SetGlobal(name, lua.LNil) }
|
||||||
|
|
||||||
|
// string.rep allocates its whole result at once, faster than the
|
||||||
|
// watchdog can react.
|
||||||
|
if str, ok := L.GetGlobal("string").(*lua.LTable); ok { str.RawSetString("rep", L.NewFunction(cappedRep(limits.MemoryBytes))) }
|
||||||
|
|
||||||
|
return L
|
||||||
|
}
|
||||||
|
|
||||||
|
func cappedRep(limit int64) lua.LGFunction {
|
||||||
|
return func(L *lua.LState) int {
|
||||||
|
s := L.CheckString(1)
|
||||||
|
n := L.CheckInt(2)
|
||||||
|
if n <= 0 || s == "" {
|
||||||
|
L.Push(lua.LString(""))
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if int64(len(s))*int64(n) > limit { L.RaiseError("string.rep: result of %d bytes exceeds the memory limit", int64(len(s))*int64(n)) }
|
||||||
|
|
||||||
|
L.Push(lua.LString(strings.Repeat(s, n)))
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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, m *meter, fn func() error) error {
|
||||||
|
ctx, cancel := context.WithTimeout(parent, timeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
|
defer close(done)
|
||||||
|
go m.watch(ctx, done, cancel)
|
||||||
|
|
||||||
|
L.SetContext(ctx)
|
||||||
|
defer L.RemoveContext()
|
||||||
|
|
||||||
|
err := fn()
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
return nil
|
||||||
|
case m.overLimit.Load():
|
||||||
|
return ErrMemoryLimit
|
||||||
|
case parent.Err() != nil:
|
||||||
|
return parent.Err()
|
||||||
|
case errors.Is(ctx.Err(), context.DeadlineExceeded):
|
||||||
|
return fmt.Errorf("%w after %s", ErrTimeout, timeout)
|
||||||
|
default:
|
||||||
|
return luaError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
return
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
if !m.paused.Load() && heapBytes()-m.base.Load() > m.limit {
|
||||||
|
m.overLimit.Store(true)
|
||||||
|
cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
var apiErr *lua.ApiError
|
||||||
|
if errors.As(err, &apiErr) && apiErr.Object != nil { return errors.New(strings.TrimSpace(apiErr.Object.String())) }
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sandboxed loads testdata/sandbox/<name>.lua.
|
||||||
|
func sandboxed(t *testing.T, name string, limits Limits) *Plugin {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
path := filepath.Join(testdata, "sandbox", name+".lua")
|
||||||
|
|
||||||
|
code, err := os.ReadFile(path)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
p, err := Load(name, path, code, limits, discardLogger())
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
t.Cleanup(p.Close)
|
||||||
|
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func parse(p *Plugin, url string) (*Result, error) {
|
||||||
|
return p.Parse(context.Background(), []byte("<html></html>"), url)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSandboxGlobals(t *testing.T) {
|
||||||
|
r, err := parse(sandboxed(t, "globals", DefaultLimits()), "")
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
if !r.Available { t.Errorf("reachable from the sandbox: %s", r.Title) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSandboxTimeout(t *testing.T) {
|
||||||
|
limits := DefaultLimits()
|
||||||
|
limits.Timeout = 50 * time.Millisecond
|
||||||
|
|
||||||
|
p := sandboxed(t, "timeout", limits)
|
||||||
|
|
||||||
|
for _, url := range []string{"loop", "pcall"} {
|
||||||
|
start := time.Now()
|
||||||
|
if _, err := parse(p, url); !errors.Is(err, ErrTimeout) { t.Errorf("%s: got %v, want ErrTimeout", url, err) }
|
||||||
|
if d := time.Since(start); d > 2*time.Second { t.Errorf("%s: timeout took %s", url, d) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// The plugin was reloaded and still works.
|
||||||
|
if r, err := parse(p, "fine"); err != nil || !r.Available { t.Errorf("after a timeout: %v, %+v", err, r) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSandboxMemoryLimit(t *testing.T) {
|
||||||
|
limits := DefaultLimits()
|
||||||
|
limits.Timeout = 20 * time.Second
|
||||||
|
limits.MemoryBytes = 16 << 20
|
||||||
|
|
||||||
|
if _, err := parse(sandboxed(t, "memory", limits), ""); !errors.Is(err, ErrMemoryLimit) { t.Errorf("got %v, want ErrMemoryLimit", err) }
|
||||||
|
if _, err := parse(sandboxed(t, "string_rep", limits), ""); err == nil || !strings.Contains(err.Error(), "memory limit") { t.Errorf("string.rep: got %v, want a memory limit error", err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSandboxCallStack(t *testing.T) {
|
||||||
|
limits := DefaultLimits()
|
||||||
|
limits.CallStack = 50
|
||||||
|
|
||||||
|
if _, err := parse(sandboxed(t, "call_stack", limits), ""); err == nil || !strings.Contains(err.Error(), "stack overflow") { t.Errorf("got %v, want a stack overflow", err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// The config's seller policies rank these values by name, so a renamed
|
||||||
|
// constant would silently never pass a policy.
|
||||||
|
func TestSellersKnownToConfig(t *testing.T) {
|
||||||
|
anyone := config.Item{Seller: config.SellerAny}
|
||||||
|
for _, s := range []string{SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown} {
|
||||||
|
if !anyone.AcceptsSeller(s) { t.Errorf("config does not know seller %q", s) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/PuerkitoBio/goquery"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
"golang.org/x/net/html"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrSignedOut means add_to_cart found the session signed out.
|
||||||
|
var ErrSignedOut = errors.New("not signed in")
|
||||||
|
|
||||||
|
// Account is what login and add_to_cart see of the shop's [accounts] entry.
|
||||||
|
type Account struct {
|
||||||
|
Username string
|
||||||
|
// Password is empty when the account has no password_env. Only login
|
||||||
|
// sees it.
|
||||||
|
Password string
|
||||||
|
TwoFA bool
|
||||||
|
LoginURL string
|
||||||
|
CartURL string
|
||||||
|
// Site is the shop's site to sign in to, such as https://www.amazon.de/.
|
||||||
|
Site string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Session is what ctx offers login and add_to_cart: requests with the
|
||||||
|
// account's cookies, questions to the user and the cookies themselves.
|
||||||
|
type Session interface {
|
||||||
|
Do(ctx context.Context, r fetch.Request) (*fetch.Response, error)
|
||||||
|
// Click opens rawURL in a browser, clicks the element sel matches and
|
||||||
|
// returns the page the click leads to.
|
||||||
|
Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error)
|
||||||
|
Prompt(ctx context.Context, label string, secret bool) (string, error)
|
||||||
|
Cookies(rawURL string) map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login runs login(ctx, account), which signs in to acc.Site.
|
||||||
|
func (p *Plugin) Login(ctx context.Context, s Session, acc Account) error {
|
||||||
|
_, err := p.session(ctx, "login", s, acc, 0, func(L *lua.LState) []lua.LValue { return []lua.LValue{accountTable(L, acc, true)} })
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddToCart runs add_to_cart(ctx, url), which puts the item on url in the
|
||||||
|
// cart unless it is there already. It returns the cart page to send the user
|
||||||
|
// to, which may be "", or ErrSignedOut.
|
||||||
|
func (p *Plugin) AddToCart(ctx context.Context, s Session, acc Account, rawURL string) (string, error) {
|
||||||
|
out, err := p.session(ctx, "add_to_cart", s, acc, 2, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(rawURL)} })
|
||||||
|
if err != nil { return "", err }
|
||||||
|
|
||||||
|
switch v := out[0]; {
|
||||||
|
case v == lua.LFalse:
|
||||||
|
return "", ErrSignedOut
|
||||||
|
case v != lua.LTrue:
|
||||||
|
return "", fmt.Errorf("plugin %s: add_to_cart must return true or false, got %s", p.Name, v.Type())
|
||||||
|
}
|
||||||
|
|
||||||
|
switch v := out[1].(type) {
|
||||||
|
case lua.LString:
|
||||||
|
return string(v), nil
|
||||||
|
case *lua.LNilType:
|
||||||
|
return acc.CartURL, nil
|
||||||
|
default:
|
||||||
|
return "", fmt.Errorf("plugin %s: add_to_cart must return the cart page as a string or nil, got %s", p.Name, v.Type())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// session runs a login or add_to_cart hook. These wait on the network and
|
||||||
|
// on the user for minutes, so each call gets a Lua state of its own instead
|
||||||
|
// of holding up the plugin's other calls.
|
||||||
|
func (p *Plugin) session(ctx context.Context, hook string, s Session, acc Account, nret int, args func(L *lua.LState) []lua.LValue) ([]lua.LValue, error) {
|
||||||
|
if !p.Has(hook) { return nil, fmt.Errorf("plugin %s has no %s function", p.Name, hook) }
|
||||||
|
|
||||||
|
shortCalls.Lock()
|
||||||
|
L, t, err := p.load()
|
||||||
|
shortCalls.Unlock()
|
||||||
|
|
||||||
|
if err != nil { return nil, fmt.Errorf("plugin %s: %w", p.Name, err) }
|
||||||
|
defer L.Close()
|
||||||
|
|
||||||
|
m := newMeter(p.limits.MemoryBytes)
|
||||||
|
self := newCtx(L, s, acc, m)
|
||||||
|
|
||||||
|
var out []lua.LValue
|
||||||
|
|
||||||
|
err = run(L, ctx, p.limits.SessionTimeout, m, func() error {
|
||||||
|
if err := L.CallByParam(lua.P{Fn: t.funcs[hook], NRet: nret, Protect: true}, append([]lua.LValue{self}, args(L)...)...); err != nil { return err }
|
||||||
|
|
||||||
|
for i := nret; i > 0; i-- { out = append(out, L.Get(-i)) }
|
||||||
|
L.Pop(nret)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil { return nil, fmt.Errorf("plugin %s: %s: %w", p.Name, hook, err) }
|
||||||
|
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// accountTable is the account as Lua sees it. Settings that are not set are
|
||||||
|
// nil.
|
||||||
|
func accountTable(L *lua.LState, acc Account, password bool) *lua.LTable {
|
||||||
|
t := L.NewTable()
|
||||||
|
|
||||||
|
for k, v := range map[string]string{"username": acc.Username, "login_url": acc.LoginURL, "cart_url": acc.CartURL, "site": acc.Site} {
|
||||||
|
if v != "" { t.RawSetString(k, lua.LString(v)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if password && acc.Password != "" { t.RawSetString("password", lua.LString(acc.Password)) }
|
||||||
|
t.RawSetString("twofa", lua.LBool(acc.TwoFA))
|
||||||
|
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
// newCtx builds the ctx table: ctx:get(url, opts), ctx:post(url, opts),
|
||||||
|
// ctx:click(url, sel), ctx:prompt(label, secret), ctx:cookies(url) and
|
||||||
|
// ctx.account, which has no password.
|
||||||
|
func newCtx(L *lua.LState, s Session, acc Account, m *meter) *lua.LTable {
|
||||||
|
t := L.NewTable()
|
||||||
|
|
||||||
|
t.RawSetString("get", L.NewFunction(func(L *lua.LState) int { return request(L, s, m, "GET") }))
|
||||||
|
t.RawSetString("post", L.NewFunction(func(L *lua.LState) int { return request(L, s, m, "POST") }))
|
||||||
|
|
||||||
|
t.RawSetString("click", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
rawURL := L.CheckString(2)
|
||||||
|
sel := L.CheckString(3)
|
||||||
|
|
||||||
|
m.pause()
|
||||||
|
resp, err := s.Click(L.Context(), rawURL, sel)
|
||||||
|
m.resume()
|
||||||
|
|
||||||
|
if err != nil { L.RaiseError("clicking %s on %s: %v", sel, rawURL, err) }
|
||||||
|
|
||||||
|
L.Push(responseTable(L, resp))
|
||||||
|
return 1
|
||||||
|
}))
|
||||||
|
|
||||||
|
t.RawSetString("prompt", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
label := L.CheckString(2)
|
||||||
|
secret := L.OptBool(3, false)
|
||||||
|
|
||||||
|
m.pause()
|
||||||
|
answer, err := s.Prompt(L.Context(), label, secret)
|
||||||
|
m.resume()
|
||||||
|
|
||||||
|
if err != nil { L.RaiseError("prompt: %v", err) }
|
||||||
|
|
||||||
|
L.Push(lua.LString(answer))
|
||||||
|
return 1
|
||||||
|
}))
|
||||||
|
|
||||||
|
t.RawSetString("cookies", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
target := L.OptString(2, acc.Site)
|
||||||
|
|
||||||
|
out := L.NewTable()
|
||||||
|
for name, value := range s.Cookies(target) { out.RawSetString(name, lua.LString(value)) }
|
||||||
|
|
||||||
|
L.Push(out)
|
||||||
|
return 1
|
||||||
|
}))
|
||||||
|
|
||||||
|
t.RawSetString("account", accountTable(L, acc, false))
|
||||||
|
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
// request implements ctx:get and ctx:post. opts may have form (a table of
|
||||||
|
// fields), body and content_type, referer, and headers (a table).
|
||||||
|
func request(L *lua.LState, s Session, m *meter, method string) int {
|
||||||
|
r := fetch.Request{Method: method, URL: L.CheckString(2)}
|
||||||
|
|
||||||
|
if opts := L.OptTable(3, nil); opts != nil {
|
||||||
|
opts.ForEach(func(k, v lua.LValue) {
|
||||||
|
switch k.String() {
|
||||||
|
case "form":
|
||||||
|
r.Form = formValues(L, v)
|
||||||
|
case "body":
|
||||||
|
r.Body = []byte(optString(L, "body", v))
|
||||||
|
case "content_type":
|
||||||
|
r.ContentType = optString(L, "content_type", v)
|
||||||
|
case "referer":
|
||||||
|
r.Referer = optString(L, "referer", v)
|
||||||
|
case "headers":
|
||||||
|
r.Header = map[string]string{}
|
||||||
|
checkTable(L, "headers", v).ForEach(func(name, value lua.LValue) { r.Header[name.String()] = optString(L, "header "+name.String(), value) })
|
||||||
|
default:
|
||||||
|
L.ArgError(3, "unknown option "+k.String()+" (known: form, body, content_type, referer, headers)")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
m.pause()
|
||||||
|
resp, err := s.Do(L.Context(), r)
|
||||||
|
m.resume()
|
||||||
|
|
||||||
|
if err != nil { L.RaiseError("%s %s: %v", method, r.URL, err) }
|
||||||
|
|
||||||
|
L.Push(responseTable(L, resp))
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// responseTable is a response as Lua sees it: status, url, verdict, body,
|
||||||
|
// headers (lower-case names), doc and challenge.
|
||||||
|
func responseTable(L *lua.LState, resp *fetch.Response) *lua.LTable {
|
||||||
|
headers := L.NewTable()
|
||||||
|
for name, values := range resp.Header {
|
||||||
|
if len(values) > 0 { headers.RawSetString(strings.ToLower(name), lua.LString(values[0])) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// A page that does not parse still has a body.
|
||||||
|
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(resp.Body))
|
||||||
|
if err != nil { doc = goquery.NewDocumentFromNode(&html.Node{Type: html.DocumentNode}) }
|
||||||
|
|
||||||
|
out := L.NewTable()
|
||||||
|
out.RawSetString("status", lua.LNumber(resp.Status))
|
||||||
|
out.RawSetString("url", lua.LString(resp.FinalURL))
|
||||||
|
out.RawSetString("verdict", lua.LString(resp.Verdict.String()))
|
||||||
|
out.RawSetString("body", lua.LString(resp.Body))
|
||||||
|
out.RawSetString("headers", headers)
|
||||||
|
out.RawSetString("doc", pushNode(L, doc.Selection))
|
||||||
|
if resp.Challenge != "" { out.RawSetString("challenge", lua.LString(resp.Challenge)) }
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func formValues(L *lua.LState, v lua.LValue) url.Values {
|
||||||
|
form := url.Values{}
|
||||||
|
|
||||||
|
checkTable(L, "form", v).ForEach(func(name, value lua.LValue) {
|
||||||
|
switch value.(type) {
|
||||||
|
case lua.LString, lua.LNumber, lua.LBool:
|
||||||
|
form.Set(name.String(), value.String())
|
||||||
|
default:
|
||||||
|
L.ArgError(3, "form field "+name.String()+" must be a string, number or boolean, got "+value.Type().String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return form
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkTable(L *lua.LState, option string, v lua.LValue) *lua.LTable {
|
||||||
|
t, ok := v.(*lua.LTable)
|
||||||
|
if !ok { L.ArgError(3, option+" must be a table, got "+v.Type().String()) }
|
||||||
|
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
func optString(L *lua.LState, option string, v lua.LValue) string {
|
||||||
|
s, ok := v.(lua.LString)
|
||||||
|
if !ok { L.ArgError(3, option+" must be a string, got "+v.Type().String()) }
|
||||||
|
|
||||||
|
return string(s)
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package plugin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeSession answers the requests of testdata/session/shop.lua.
|
||||||
|
type fakeSession struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
requests []fetch.Request
|
||||||
|
signedIn bool
|
||||||
|
prompts []string
|
||||||
|
// prompt, if set, answers prompts instead of "123456".
|
||||||
|
prompt func(ctx context.Context) (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeSession) Do(_ context.Context, r fetch.Request) (*fetch.Response, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
f.requests = append(f.requests, r)
|
||||||
|
|
||||||
|
body, header := "<p>sign in</p>", http.Header{}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case r.Method == "POST" && strings.HasSuffix(r.URL, "/signin"):
|
||||||
|
if r.Form.Get("password") == "hunter2" && r.Form.Get("code") == "123456" {
|
||||||
|
f.signedIn = true
|
||||||
|
body = `<p id="result">welcome</p>`
|
||||||
|
}
|
||||||
|
case r.Method == "POST" && r.URL == "https://shop.test/cart" && r.Header["X-Test"] == "yes":
|
||||||
|
header.Set("X-Cart", "1")
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch.NewResponse(r.URL, r.URL, 200, header, []byte(body)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Click submits the add button's form, as the shop's page would.
|
||||||
|
func (f *fakeSession) Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error) {
|
||||||
|
form := url.Values{"items[0][quantity]": {"1"}, "submit.add-to-cart": {"Add"}}
|
||||||
|
|
||||||
|
return f.Do(ctx, fetch.Request{Method: "POST", URL: strings.TrimSuffix(rawURL, "item") + "cart", Form: form, Header: map[string]string{"X-Test": "yes"}})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeSession) Prompt(ctx context.Context, label string, secret bool) (string, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
f.prompts = append(f.prompts, label)
|
||||||
|
f.mu.Unlock()
|
||||||
|
|
||||||
|
if !secret { return "", errors.New("want a secret prompt") }
|
||||||
|
if f.prompt != nil { return f.prompt(ctx) }
|
||||||
|
|
||||||
|
return "123456", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeSession) Cookies(string) map[string]string {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
|
||||||
|
if f.signedIn { return map[string]string{"session": "yes"} }
|
||||||
|
|
||||||
|
return map[string]string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func shopPlugin(t *testing.T, limits Limits) *Plugin {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
path := filepath.Join(testdata, "session", "shop.lua")
|
||||||
|
|
||||||
|
code, err := os.ReadFile(path)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
p, err := Load("shop", path, code, limits, discardLogger())
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
t.Cleanup(p.Close)
|
||||||
|
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
var shopAccount = Account{Username: "me@example.com", Password: "hunter2", Site: "https://shop.test/", CartURL: "https://shop.test/cart"}
|
||||||
|
|
||||||
|
func TestSessionLogin(t *testing.T) {
|
||||||
|
p := shopPlugin(t, DefaultLimits())
|
||||||
|
if p.SessionWarning != "Automated logins can lock the account." { t.Errorf("session warning %q", p.SessionWarning) }
|
||||||
|
|
||||||
|
s := &fakeSession{}
|
||||||
|
if err := p.Login(context.Background(), s, shopAccount); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
if len(s.prompts) != 1 || s.prompts[0] != "code for me@example.com" { t.Errorf("prompts %q", s.prompts) }
|
||||||
|
if len(s.requests) != 2 { t.Fatalf("%d requests, want 2", len(s.requests)) }
|
||||||
|
if r := s.requests[1]; r.Referer != "https://shop.test/signin" || r.Form.Get("user") != "me@example.com" { t.Errorf("sign-in form %+v", r) }
|
||||||
|
|
||||||
|
wrong := shopAccount
|
||||||
|
wrong.Password = "wrong"
|
||||||
|
if err := p.Login(context.Background(), &fakeSession{}, wrong); err == nil || !strings.Contains(err.Error(), "refused") { t.Errorf("wrong password: %v", err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionAddToCart(t *testing.T) {
|
||||||
|
p := shopPlugin(t, DefaultLimits())
|
||||||
|
|
||||||
|
cart, err := p.AddToCart(context.Background(), &fakeSession{}, shopAccount, "https://shop.test/item/ok")
|
||||||
|
if err != nil || cart != "https://shop.test/cart" { t.Errorf("added: %q, %v", cart, err) }
|
||||||
|
|
||||||
|
if _, err := p.AddToCart(context.Background(), &fakeSession{}, shopAccount, "https://shop.test/item/signedout"); !errors.Is(err, ErrSignedOut) { t.Errorf("signed out: got %v", err) }
|
||||||
|
if _, err := p.AddToCart(context.Background(), &fakeSession{}, shopAccount, "https://shop.test/item/nonsense"); err == nil { t.Error("a string result: want an error") }
|
||||||
|
|
||||||
|
if _, err := p.AddToCart(context.Background(), &fakeSession{}, shopAccount, "https://shop.test/item/click"); err != nil { t.Errorf("click: %v", err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// A login waiting for the user must not hold up the plugin's checks.
|
||||||
|
func TestSessionCallDoesNotBlockParse(t *testing.T) {
|
||||||
|
p := shopPlugin(t, DefaultLimits())
|
||||||
|
|
||||||
|
asked := make(chan struct{})
|
||||||
|
release := make(chan struct{})
|
||||||
|
s := &fakeSession{prompt: func(context.Context) (string, error) {
|
||||||
|
close(asked)
|
||||||
|
<-release
|
||||||
|
return "123456", nil
|
||||||
|
}}
|
||||||
|
|
||||||
|
go func() { _ = p.Login(context.Background(), s, shopAccount) }()
|
||||||
|
|
||||||
|
<-asked
|
||||||
|
defer close(release)
|
||||||
|
|
||||||
|
parsed := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, err := parse(p, "https://shop.test/item/ok")
|
||||||
|
parsed <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-parsed:
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("parse waits for the login")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionPromptTimesOut(t *testing.T) {
|
||||||
|
limits := DefaultLimits()
|
||||||
|
limits.SessionTimeout = 100 * time.Millisecond
|
||||||
|
|
||||||
|
p := shopPlugin(t, limits)
|
||||||
|
s := &fakeSession{prompt: func(ctx context.Context) (string, error) {
|
||||||
|
<-ctx.Done()
|
||||||
|
return "", ctx.Err()
|
||||||
|
}}
|
||||||
|
|
||||||
|
if err := p.Login(context.Background(), s, shopAccount); !errors.Is(err, ErrTimeout) { t.Errorf("got %v, want ErrTimeout", err) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
// Package price reads prices as shops print them.
|
||||||
|
package price
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// symbols maps currency signs and local abbreviations to ISO 4217 codes.
|
||||||
|
// Ambiguous ones such as "kr" are left out on purpose.
|
||||||
|
var symbols = []struct{ sign, code string }{
|
||||||
|
{"€", "EUR"},
|
||||||
|
{"£", "GBP"},
|
||||||
|
{"US$", "USD"},
|
||||||
|
{"$", "USD"},
|
||||||
|
{"¥", "JPY"},
|
||||||
|
{"zł", "PLN"},
|
||||||
|
{"Kč", "CZK"},
|
||||||
|
{"Fr.", "CHF"},
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
codeRe = regexp.MustCompile(`\b(EUR|GBP|USD|CHF|PLN|SEK|NOK|DKK|CZK|HUF|JPY|CAD|AUD)\b`)
|
||||||
|
numberRe = regexp.MustCompile(`\d[\d.,' \x{00a0}\x{202f}]*`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Parse reads the first price in s, such as "1.299,99 €", "£1,299.99",
|
||||||
|
// "1 299,99 €" or "EUR 12.50". It returns the amount, the ISO 4217
|
||||||
|
// currency code if `s` names one (or "" if not), and whether a price was
|
||||||
|
// found.
|
||||||
|
func Parse(s string) (float64, string, bool) {
|
||||||
|
num := strings.TrimRight(numberRe.FindString(s), ".,' \u00a0\u202f")
|
||||||
|
if num == "" { return 0, "", false }
|
||||||
|
|
||||||
|
v, err := strconv.ParseFloat(normalize(num), 64)
|
||||||
|
if err != nil { return 0, "", false }
|
||||||
|
|
||||||
|
return v, currency(s), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// normalize turns a localized number into the form ParseFloat accepts.
|
||||||
|
func normalize(num string) string {
|
||||||
|
// Spaces and apostrophes only ever group thousands.
|
||||||
|
num = strings.NewReplacer(" ", "", "\u00a0", "", "\u202f", "", "'", "").Replace(num)
|
||||||
|
|
||||||
|
dot, comma := strings.LastIndex(num, "."), strings.LastIndex(num, ",")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case dot >= 0 && comma >= 0:
|
||||||
|
// Both present: the last one is the decimal separator.
|
||||||
|
if dot > comma { return strings.ReplaceAll(num, ",", "") }
|
||||||
|
|
||||||
|
return strings.ReplaceAll(strings.ReplaceAll(num, ".", ""), ",", ".")
|
||||||
|
case comma >= 0:
|
||||||
|
return decimalOrGrouping(num, ",")
|
||||||
|
case dot >= 0:
|
||||||
|
return decimalOrGrouping(num, ".")
|
||||||
|
default:
|
||||||
|
return num
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// decimalOrGrouping handles a number with only one kind of separator. Used
|
||||||
|
// more than once, or followed by exactly three digits, it groups thousands
|
||||||
|
// ("1.299", "1,299,000"). Otherwise it is the decimal point ("12,5", "9.99").
|
||||||
|
func decimalOrGrouping(num, sep string) string {
|
||||||
|
last := num[strings.LastIndex(num, sep)+1:]
|
||||||
|
if strings.Count(num, sep) > 1 || len(last) == 3 { return strings.ReplaceAll(num, sep, "") }
|
||||||
|
|
||||||
|
return strings.Replace(num, sep, ".", 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func currency(s string) string {
|
||||||
|
if m := codeRe.FindString(s); m != "" { return m }
|
||||||
|
|
||||||
|
for _, sym := range symbols {
|
||||||
|
if strings.Contains(s, sym.sign) { return sym.code }
|
||||||
|
}
|
||||||
|
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package price
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestParse(t *testing.T) {
|
||||||
|
for in, want := range map[string]struct {
|
||||||
|
value float64
|
||||||
|
currency string
|
||||||
|
}{
|
||||||
|
"1.299,99 €": {1299.99, "EUR"},
|
||||||
|
"£1,299.99": {1299.99, "GBP"},
|
||||||
|
"1 299,99 €": {1299.99, "EUR"},
|
||||||
|
"1\u00a0299,99\u00a0€": {1299.99, "EUR"},
|
||||||
|
"1\u202f299,99 €": {1299.99, "EUR"},
|
||||||
|
"129,99 €": {129.99, "EUR"},
|
||||||
|
"129,99€": {129.99, "EUR"},
|
||||||
|
"€129.99": {129.99, "EUR"},
|
||||||
|
"$1,299.99": {1299.99, "USD"},
|
||||||
|
"US$ 49.00": {49, "USD"},
|
||||||
|
"EUR 12,50": {12.5, "EUR"},
|
||||||
|
"12.50 GBP": {12.5, "GBP"},
|
||||||
|
"CHF 1'299.90": {1299.9, "CHF"},
|
||||||
|
"1.299 €": {1299, "EUR"},
|
||||||
|
"1,299": {1299, ""},
|
||||||
|
"1.299.000,00 €": {1299000, "EUR"},
|
||||||
|
"12,5": {12.5, ""},
|
||||||
|
"9.99": {9.99, ""},
|
||||||
|
"49": {49, ""},
|
||||||
|
"Preis: 59,99 € inkl. MwSt.": {59.99, "EUR"},
|
||||||
|
" £7. ": {7, "GBP"},
|
||||||
|
"99,00 zł": {99, "PLN"},
|
||||||
|
} {
|
||||||
|
v, c, ok := Parse(in)
|
||||||
|
if !ok || v != want.value || c != want.currency { t.Errorf("Parse(%q) = %v, %q, %v; want %v, %q", in, v, c, ok, want.value, want.currency) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseNoPrice(t *testing.T) {
|
||||||
|
for _, in := range []string{"", "Derzeit nicht verfügbar", "€", "kostenlos"} {
|
||||||
|
if v, c, ok := Parse(in); ok { t.Errorf("Parse(%q) = %v, %q, true; want no price", in, v, c) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
// Package ratelimit enforces how often dibs may talk to a shop.
|
||||||
|
//
|
||||||
|
// The floors are constants on purpose: no config value, flag or caller can
|
||||||
|
// lower them.
|
||||||
|
package ratelimit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"math/rand/v2"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// URLFloor is the shortest time between two checks of one URL.
|
||||||
|
URLFloor = 60 * time.Second
|
||||||
|
// HostFloor is the shortest time between two requests to one host.
|
||||||
|
HostFloor = 10 * time.Second
|
||||||
|
|
||||||
|
// Jitter is the fraction intervals are randomly stretched or shrunk by.
|
||||||
|
Jitter = 0.2
|
||||||
|
|
||||||
|
backoffBase = 2 * time.Minute
|
||||||
|
backoffCap = 30 * time.Minute
|
||||||
|
|
||||||
|
// recheck caps each sleep of a waiting request, so that a cleared
|
||||||
|
// backoff lets it go soon.
|
||||||
|
recheck = 5 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// HostState is what the limiter remembers about a host. It is persisted so
|
||||||
|
// the floors hold across restarts and between dibs processes.
|
||||||
|
type HostState struct {
|
||||||
|
// Next is the earliest time of the next request.
|
||||||
|
Next time.Time `json:"next"`
|
||||||
|
// Failures counts bot checks and refusals in a row.
|
||||||
|
Failures int `json:"failures,omitempty"`
|
||||||
|
// BackoffUntil blocks the host after repeated failures.
|
||||||
|
BackoffUntil time.Time `json:"backoff_until,omitzero"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persister shares host and URL state with other dibs processes. The Load
|
||||||
|
// methods return the newest state on disk, and the Store methods record this
|
||||||
|
// process's. Lock serializes the limiters' decisions across processes and
|
||||||
|
// returns the unlock function.
|
||||||
|
type Persister interface {
|
||||||
|
Lock() func()
|
||||||
|
LoadHost(host string) (HostState, bool)
|
||||||
|
StoreHost(host string, h HostState)
|
||||||
|
LoadURL(pageURL string) (time.Time, bool)
|
||||||
|
StoreURL(pageURL string, last time.Time)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clock abstracts time so tests can replace it.
|
||||||
|
type Clock interface {
|
||||||
|
Now() time.Time
|
||||||
|
After(d time.Duration) <-chan time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// SystemClock is the real clock.
|
||||||
|
var SystemClock Clock = systemClock{}
|
||||||
|
|
||||||
|
type systemClock struct{}
|
||||||
|
|
||||||
|
func (systemClock) Now() time.Time { return time.Now() }
|
||||||
|
func (systemClock) After(d time.Duration) <-chan time.Time { return time.After(d) }
|
||||||
|
|
||||||
|
// Limiter spaces requests per host and checks per URL, and backs off from
|
||||||
|
// hosts that keep answering with bot checks. It is safe for concurrent use.
|
||||||
|
type Limiter struct {
|
||||||
|
clock Clock
|
||||||
|
persist Persister
|
||||||
|
rand func() float64
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
hosts map[string]HostState
|
||||||
|
urls map[string]time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Option func(*Limiter)
|
||||||
|
|
||||||
|
// WithClock replaces the system clock, for tests.
|
||||||
|
func WithClock(c Clock) Option { return func(l *Limiter) { l.clock = c } }
|
||||||
|
|
||||||
|
// WithRand replaces the jitter source, which returns values in [0, 1).
|
||||||
|
func WithRand(r func() float64) Option { return func(l *Limiter) { l.rand = r } }
|
||||||
|
|
||||||
|
// New returns a limiter. persist may be nil to keep state in memory only.
|
||||||
|
func New(persist Persister, opts ...Option) *Limiter {
|
||||||
|
l := &Limiter{
|
||||||
|
clock: SystemClock,
|
||||||
|
persist: persist,
|
||||||
|
rand: rand.Float64,
|
||||||
|
hosts: map[string]HostState{},
|
||||||
|
urls: map[string]time.Time{},
|
||||||
|
}
|
||||||
|
for _, o := range opts { o(l) }
|
||||||
|
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Limiter) Clock() Clock { return l.clock }
|
||||||
|
|
||||||
|
// Wait blocks until a request to host is allowed, then reserves the slot.
|
||||||
|
// It is for requests that are not checks of a product page.
|
||||||
|
func (l *Limiter) Wait(ctx context.Context, host string) error {
|
||||||
|
return l.wait(ctx, strings.ToLower(host), "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// WaitCheck blocks until url may be checked: its host's floor and backoff,
|
||||||
|
// and the URL floor since its last check by any dibs process, all allow it.
|
||||||
|
// It then reserves both at once, so the request must follow right away.
|
||||||
|
func (l *Limiter) WaitCheck(ctx context.Context, rawURL string) error {
|
||||||
|
u, err := url.Parse(rawURL)
|
||||||
|
if err != nil { return err }
|
||||||
|
|
||||||
|
return l.wait(ctx, strings.ToLower(u.Hostname()), rawURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Limiter) wait(ctx context.Context, host, checkURL string) error {
|
||||||
|
for {
|
||||||
|
var at time.Time
|
||||||
|
|
||||||
|
reserved := false
|
||||||
|
|
||||||
|
l.locked(func() {
|
||||||
|
h := l.host(host)
|
||||||
|
now := l.clock.Now()
|
||||||
|
at = latest(h.Next, h.BackoffUntil)
|
||||||
|
if checkURL != "" { at = latest(at, l.urlReady(checkURL)) }
|
||||||
|
|
||||||
|
if now.Before(at) { return }
|
||||||
|
|
||||||
|
// The host gap is stretched randomly, never below the floor.
|
||||||
|
h.Next = now.Add(time.Duration(float64(HostFloor) * (1 + Jitter*l.rand())))
|
||||||
|
l.setHost(host, h)
|
||||||
|
|
||||||
|
if checkURL != "" {
|
||||||
|
l.urls[checkURL] = now
|
||||||
|
if l.persist != nil { l.persist.StoreURL(checkURL, now) }
|
||||||
|
}
|
||||||
|
|
||||||
|
reserved = true
|
||||||
|
})
|
||||||
|
|
||||||
|
if reserved { return nil }
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-l.clock.After(min(at.Sub(l.clock.Now()), recheck)):
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delay is how long a request to host would have to wait now.
|
||||||
|
func (l *Limiter) Delay(host string) time.Duration {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
|
||||||
|
h := l.host(strings.ToLower(host))
|
||||||
|
return max(0, latest(h.Next, h.BackoffUntil).Sub(l.clock.Now()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failure records a bot check or refusal from host and backs off
|
||||||
|
// exponentially, from 2 minutes up to 30.
|
||||||
|
func (l *Limiter) Failure(host string) time.Duration {
|
||||||
|
host = strings.ToLower(host)
|
||||||
|
|
||||||
|
var d time.Duration
|
||||||
|
|
||||||
|
l.locked(func() {
|
||||||
|
h := l.host(host)
|
||||||
|
h.Failures++
|
||||||
|
|
||||||
|
d = min(backoffBase<<min(h.Failures-1, 10), backoffCap)
|
||||||
|
d = min(l.Jittered(d, 0), backoffCap)
|
||||||
|
|
||||||
|
h.BackoffUntil = l.clock.Now().Add(d)
|
||||||
|
l.setHost(host, h)
|
||||||
|
})
|
||||||
|
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success clears the backoff of host.
|
||||||
|
func (l *Limiter) Success(host string) {
|
||||||
|
host = strings.ToLower(host)
|
||||||
|
|
||||||
|
l.locked(func() {
|
||||||
|
h := l.host(host)
|
||||||
|
if h.Failures == 0 && h.BackoffUntil.IsZero() { return }
|
||||||
|
|
||||||
|
h.Failures, h.BackoffUntil = 0, time.Time{}
|
||||||
|
l.setHost(host, h)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// NextCheck is when url may be checked next, given its interval: the
|
||||||
|
// interval jittered by ±20%, but never less than URLFloor after the last
|
||||||
|
// check, by this or another dibs process.
|
||||||
|
func (l *Limiter) NextCheck(pageURL string, interval time.Duration) time.Time {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
|
||||||
|
last := l.lastCheck(pageURL)
|
||||||
|
if last.IsZero() { return l.clock.Now() }
|
||||||
|
|
||||||
|
return last.Add(l.Jittered(interval, URLFloor))
|
||||||
|
}
|
||||||
|
|
||||||
|
// URLReady is the earliest time url may be checked at all.
|
||||||
|
func (l *Limiter) URLReady(pageURL string) time.Time {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
|
||||||
|
return l.urlReady(pageURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LastCheck is when the URL was last checked by any dibs process, or zero.
|
||||||
|
func (l *Limiter) LastCheck(pageURL string) time.Time {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
|
||||||
|
return l.lastCheck(pageURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Jittered stretches or shrinks d randomly by up to ±20%, but never below
|
||||||
|
// floor.
|
||||||
|
func (l *Limiter) Jittered(d, floor time.Duration) time.Duration {
|
||||||
|
return max(time.Duration(float64(d)*(1+Jitter*(2*l.rand()-1))), floor)
|
||||||
|
}
|
||||||
|
|
||||||
|
// locked runs fn holding the limiter's lock and, if there is one, the lock
|
||||||
|
// shared with other processes.
|
||||||
|
func (l *Limiter) locked(fn func()) {
|
||||||
|
l.mu.Lock()
|
||||||
|
defer l.mu.Unlock()
|
||||||
|
|
||||||
|
if l.persist != nil { defer l.persist.Lock()() }
|
||||||
|
|
||||||
|
fn()
|
||||||
|
}
|
||||||
|
|
||||||
|
// host returns what this and other processes know about host. Callers hold
|
||||||
|
// mu.
|
||||||
|
func (l *Limiter) host(host string) HostState {
|
||||||
|
h := l.hosts[host]
|
||||||
|
if l.persist == nil { return h }
|
||||||
|
|
||||||
|
if p, ok := l.persist.LoadHost(host); ok {
|
||||||
|
h.Next = latest(h.Next, p.Next)
|
||||||
|
h.BackoffUntil = latest(h.BackoffUntil, p.BackoffUntil)
|
||||||
|
h.Failures = max(h.Failures, p.Failures)
|
||||||
|
}
|
||||||
|
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *Limiter) setHost(host string, h HostState) {
|
||||||
|
l.hosts[host] = h
|
||||||
|
if l.persist != nil { l.persist.StoreHost(host, h) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// urlReady is when url may be checked again. Callers hold mu.
|
||||||
|
func (l *Limiter) urlReady(pageURL string) time.Time {
|
||||||
|
last := l.lastCheck(pageURL)
|
||||||
|
if last.IsZero() { return last }
|
||||||
|
|
||||||
|
return last.Add(URLFloor)
|
||||||
|
}
|
||||||
|
|
||||||
|
// lastCheck is the newest check of the URL that this or another process
|
||||||
|
// knows of. Callers hold mu.
|
||||||
|
func (l *Limiter) lastCheck(pageURL string) time.Time {
|
||||||
|
last := l.urls[pageURL]
|
||||||
|
if l.persist != nil {
|
||||||
|
if p, ok := l.persist.LoadURL(pageURL); ok { last = latest(last, p) }
|
||||||
|
}
|
||||||
|
|
||||||
|
return last
|
||||||
|
}
|
||||||
|
|
||||||
|
func latest(a, b time.Time) time.Time {
|
||||||
|
if a.After(b) { return a }
|
||||||
|
|
||||||
|
return b
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package ratelimit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FakeClock moves forward only when something waits on it, by exactly the
|
||||||
|
// time waited.
|
||||||
|
type FakeClock struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
now time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFakeClock() *FakeClock { return &FakeClock{now: time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)} }
|
||||||
|
|
||||||
|
func (c *FakeClock) Now() time.Time {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
return c.now
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *FakeClock) After(d time.Duration) <-chan time.Time {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
c.now = c.now.Add(d)
|
||||||
|
|
||||||
|
ch := make(chan time.Time, 1)
|
||||||
|
ch <- c.now
|
||||||
|
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func fixedRand(v float64) Option { return WithRand(func() float64 { return v }) }
|
||||||
|
|
||||||
|
func TestHostFloor(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
for _, r := range []float64{0, 0.5, 0.999} {
|
||||||
|
clock := NewFakeClock()
|
||||||
|
l := New(nil, WithClock(clock), fixedRand(r))
|
||||||
|
|
||||||
|
if err := l.Wait(ctx, "www.amazon.de"); err != nil { t.Fatal(err) }
|
||||||
|
first := clock.Now()
|
||||||
|
|
||||||
|
// Another host is not held up.
|
||||||
|
if err := l.Wait(ctx, "www.amazon.co.uk"); err != nil { t.Fatal(err) }
|
||||||
|
if !clock.Now().Equal(first) { t.Errorf("rand %v: a request to another host waited", r) }
|
||||||
|
|
||||||
|
if err := l.Wait(ctx, "WWW.AMAZON.DE"); err != nil { t.Fatal(err) }
|
||||||
|
gap := clock.Now().Sub(first)
|
||||||
|
|
||||||
|
if gap < HostFloor || gap > time.Duration(float64(HostFloor)*(1+Jitter)) { t.Errorf("rand %v: gap %s, want between %s and %s", r, gap, HostFloor, time.Duration(float64(HostFloor)*(1+Jitter))) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestURLFloor(t *testing.T) {
|
||||||
|
clock := NewFakeClock()
|
||||||
|
l := New(nil, WithClock(clock), fixedRand(0)) // shortest jitter: -20%
|
||||||
|
|
||||||
|
const url = "https://www.amazon.de/dp/B0HMX2FSTF"
|
||||||
|
|
||||||
|
if next := l.NextCheck(url, time.Minute); !next.Equal(clock.Now()) { t.Errorf("never checked: next %s, want now", next) }
|
||||||
|
|
||||||
|
if err := l.WaitCheck(context.Background(), url); err != nil { t.Fatal(err) }
|
||||||
|
last := clock.Now()
|
||||||
|
|
||||||
|
// 60s - 20% would be 48s, and an interval below the floor (which the
|
||||||
|
// config rejects anyway) must not get through either.
|
||||||
|
for _, interval := range []time.Duration{time.Minute, time.Second} {
|
||||||
|
if next := l.NextCheck(url, interval); next.Sub(last) < URLFloor { t.Errorf("interval %s: next check %s after the last, below the floor", interval, next.Sub(last)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
if ready := l.URLReady(url); ready.Sub(last) != URLFloor { t.Errorf("URLReady %s after the last check, want %s", ready.Sub(last), URLFloor) }
|
||||||
|
|
||||||
|
if next := l.NextCheck(url, 10*time.Minute); next.Sub(last) != 8*time.Minute { t.Errorf("10m interval at -20%%: next after %s, want 8m", next.Sub(last)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBackoff(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clock := NewFakeClock()
|
||||||
|
l := New(nil, WithClock(clock), fixedRand(0.5)) // no jitter
|
||||||
|
|
||||||
|
for i, want := range []time.Duration{2, 4, 8, 16, 30, 30} {
|
||||||
|
if got := l.Failure("www.amazon.de"); got != want*time.Minute { t.Errorf("failure %d: backoff %s, want %dm", i+1, got, want) }
|
||||||
|
}
|
||||||
|
|
||||||
|
start := clock.Now()
|
||||||
|
if err := l.Wait(ctx, "www.amazon.de"); err != nil { t.Fatal(err) }
|
||||||
|
if waited := clock.Now().Sub(start); waited != 30*time.Minute { t.Errorf("waited %s for a backed-off host, want 30m", waited) }
|
||||||
|
|
||||||
|
l.Success("www.amazon.de")
|
||||||
|
if got := l.Failure("www.amazon.de"); got != 2*time.Minute { t.Errorf("after a success: backoff %s, want it to start over at 2m", got) }
|
||||||
|
}
|
||||||
@@ -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("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
|
||||||
|
}
|
||||||
@@ -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(`<p id="result">welcome</p>`))
|
||||||
|
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") }
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
// Package state keeps what dibs must remember between runs in a JSON file in
|
||||||
|
// the user config dir. Every dibs process shares it, so a `dibs check` run
|
||||||
|
// next to a running watcher still respects the rate limits.
|
||||||
|
package state
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/config"
|
||||||
|
"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
|
||||||
|
// removed from the config. An alert is kept for as long as the longest
|
||||||
|
// cooldown lasts.
|
||||||
|
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"`
|
||||||
|
// 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,
|
||||||
|
// fx.Store and session.Store.
|
||||||
|
type Store struct {
|
||||||
|
path string
|
||||||
|
lock string
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dir is the directory dibs keeps its files in.
|
||||||
|
func Dir() (string, error) {
|
||||||
|
dir, err := os.UserConfigDir()
|
||||||
|
if err != nil { return "", err }
|
||||||
|
|
||||||
|
return filepath.Join(dir, "dibs"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open returns the store at dir/state.json. The file is created on the first
|
||||||
|
// write.
|
||||||
|
func Open(dir string) *Store {
|
||||||
|
return &Store{path: filepath.Join(dir, "state.json"), lock: filepath.Join(dir, "state.lock")}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Err returns the last error reading or writing the file, if any. The
|
||||||
|
// limiter still works in memory without the file.
|
||||||
|
func (s *Store) Err() error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
return s.err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lock takes the lock shared by every dibs process using this directory.
|
||||||
|
// When that fails, the limiter carries on with only its in-process lock.
|
||||||
|
func (s *Store) Lock() func() {
|
||||||
|
unlock, err := fsutil.Lock(s.lock)
|
||||||
|
if err != nil {
|
||||||
|
s.mu.Lock()
|
||||||
|
s.err = err
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
return func() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
return unlock
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) LoadHost(host string) (ratelimit.HostState, bool) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
h, ok := s.read().Hosts[host]
|
||||||
|
return h, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// StoreHost replaces the state of host. The limiter has already merged in
|
||||||
|
// what other processes stored.
|
||||||
|
func (s *Store) StoreHost(host string, h ratelimit.HostState) {
|
||||||
|
s.update(func(f *file) { f.Hosts[host] = h })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) LoadURL(url string) (time.Time, bool) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
t, ok := s.read().URLs[url]
|
||||||
|
return t, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) StoreURL(url string, last time.Time) {
|
||||||
|
s.update(func(f *file) {
|
||||||
|
if last.After(f.URLs[url]) { f.URLs[url] = last }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) LoadAlert(item string) (alert.Sent, bool) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
a, ok := s.read().Alerts[item]
|
||||||
|
return a, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) StoreAlert(item string, a alert.Sent) {
|
||||||
|
s.update(func(f *file) { f.Alerts[item] = a })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) LoadRates() (*fx.Rates, bool) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
r := s.read().FX
|
||||||
|
return r, r != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) StoreRates(r *fx.Rates) {
|
||||||
|
s.update(func(f *file) {
|
||||||
|
if f.FX == nil || r.Fetched.After(f.FX.Fetched) { f.FX = r }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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{}, Sessions: map[string]session.Record{}}
|
||||||
|
|
||||||
|
data, err := os.ReadFile(s.path)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, fs.ErrNotExist):
|
||||||
|
return f
|
||||||
|
case err != nil:
|
||||||
|
s.err = err
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := json.Unmarshal(data, f); err != nil {
|
||||||
|
s.err = err
|
||||||
|
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.Sessions == nil { f.Sessions = map[string]session.Record{} }
|
||||||
|
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) update(change func(f *file)) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
f := s.read()
|
||||||
|
change(f)
|
||||||
|
|
||||||
|
cutoff := time.Now().Add(-forgetAfter)
|
||||||
|
for host, h := range f.Hosts {
|
||||||
|
if h.Next.Before(cutoff) && h.BackoffUntil.Before(cutoff) { delete(f.Hosts, host) }
|
||||||
|
}
|
||||||
|
for url, t := range f.URLs {
|
||||||
|
if t.Before(cutoff) { delete(f.URLs, url) }
|
||||||
|
}
|
||||||
|
for item, a := range f.Alerts {
|
||||||
|
if a.Time.Before(cutoff) { delete(f.Alerts, item) }
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.MarshalIndent(f, "", " ")
|
||||||
|
if err == nil { err = fsutil.WriteFileAtomic(s.path, data, 0o600) }
|
||||||
|
|
||||||
|
s.err = err
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package state
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Two dibs processes, such as a watcher and a `dibs check`, share the floors
|
||||||
|
// through the state file.
|
||||||
|
func TestFloorsHoldAcrossProcesses(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
watcher := ratelimit.New(Open(dir))
|
||||||
|
check := ratelimit.New(Open(dir))
|
||||||
|
|
||||||
|
const page = "https://www.amazon.de/dp/B0HMX2FSTF"
|
||||||
|
|
||||||
|
if err := watcher.WaitCheck(ctx, page); err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
if d := check.Delay("www.amazon.de"); d < 9*time.Second { t.Errorf("the other process may request again in %s, want about %s", d, ratelimit.HostFloor) }
|
||||||
|
if wait := time.Until(check.URLReady(page)); wait < 59*time.Second { t.Errorf("the other process may check the URL again in %s, want about %s", wait, ratelimit.URLFloor) }
|
||||||
|
|
||||||
|
watcher.Failure("www.amazon.de")
|
||||||
|
if d := check.Delay("www.amazon.de"); d < time.Minute { t.Errorf("the other process ignores the backoff: delay %s", d) }
|
||||||
|
|
||||||
|
if err := Open(dir).Err(); err != nil { t.Error(err) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// stoppedClock never moves, so a limiter that has to wait blocks until its
|
||||||
|
// context ends.
|
||||||
|
type stoppedClock struct{ now time.Time }
|
||||||
|
|
||||||
|
func (c stoppedClock) Now() time.Time { return c.now }
|
||||||
|
func (c stoppedClock) After(time.Duration) <-chan time.Time { return nil }
|
||||||
|
|
||||||
|
// Two processes asking for the same host at the same instant: exactly one
|
||||||
|
// may get it. Without the file lock, both sometimes read "free" before
|
||||||
|
// either writes.
|
||||||
|
func TestReservationsAreExclusive(t *testing.T) {
|
||||||
|
clock := stoppedClock{now: time.Now()}
|
||||||
|
|
||||||
|
for round := range 30 {
|
||||||
|
dir := t.TempDir()
|
||||||
|
|
||||||
|
var (
|
||||||
|
wg sync.WaitGroup
|
||||||
|
granted atomic.Int32
|
||||||
|
)
|
||||||
|
|
||||||
|
for i := range 2 {
|
||||||
|
l := ratelimit.New(Open(dir), ratelimit.WithClock(clock))
|
||||||
|
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
page := []string{"https://www.amazon.de/dp/B0DK51S84Z", "https://www.amazon.de/dp/B076WS2WJ6"}[i]
|
||||||
|
if l.WaitCheck(ctx, page) == nil { granted.Add(1) }
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
if n := granted.Load(); n != 1 {
|
||||||
|
t.Fatalf("round %d: %d processes got the host at once, want 1", round, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LogLine is one log record, formatted for the log pane.
|
||||||
|
type LogLine struct {
|
||||||
|
Time time.Time
|
||||||
|
Level slog.Level
|
||||||
|
Msg string
|
||||||
|
// Attrs are the record's attributes as key=value pairs.
|
||||||
|
Attrs string
|
||||||
|
}
|
||||||
|
|
||||||
|
// LogHandler is a slog.Handler that feeds the log pane.
|
||||||
|
type LogHandler struct {
|
||||||
|
level slog.Level
|
||||||
|
sink *sink
|
||||||
|
attrs string
|
||||||
|
prefix string
|
||||||
|
}
|
||||||
|
|
||||||
|
// sink is shared by a handler and the handlers derived from it.
|
||||||
|
type sink struct {
|
||||||
|
lines chan LogLine
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
out io.Writer // set once the TUI is gone
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewLogHandler returns a handler for records at level or above.
|
||||||
|
func NewLogHandler(level slog.Level) *LogHandler {
|
||||||
|
return &LogHandler{level: level, sink: &sink{lines: make(chan LogLine, 1024)}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect sends all further lines to w, for after the TUI exits.
|
||||||
|
func (h *LogHandler) Redirect(w io.Writer) {
|
||||||
|
h.sink.mu.Lock()
|
||||||
|
defer h.sink.mu.Unlock()
|
||||||
|
|
||||||
|
h.sink.out = w
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *LogHandler) Enabled(_ context.Context, l slog.Level) bool { return l >= h.level }
|
||||||
|
|
||||||
|
// Handle never blocks. When the TUI falls 1024 lines behind, new lines are
|
||||||
|
// dropped.
|
||||||
|
func (h *LogHandler) Handle(_ context.Context, r slog.Record) error {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(h.attrs)
|
||||||
|
r.Attrs(func(a slog.Attr) bool {
|
||||||
|
writeAttr(&b, h.prefix, a)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
l := LogLine{Time: r.Time, Level: r.Level, Msg: r.Message, Attrs: b.String()}
|
||||||
|
|
||||||
|
h.sink.mu.Lock()
|
||||||
|
defer h.sink.mu.Unlock()
|
||||||
|
|
||||||
|
if h.sink.out != nil {
|
||||||
|
_, err := io.WriteString(h.sink.out, l.Time.Format(time.TimeOnly)+" "+l.Level.String()+" "+l.Msg+" "+l.Attrs+"\n")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case h.sink.lines <- l:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(h.attrs)
|
||||||
|
for _, a := range attrs { writeAttr(&b, h.prefix, a) }
|
||||||
|
|
||||||
|
c := *h
|
||||||
|
c.attrs = b.String()
|
||||||
|
return &c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *LogHandler) WithGroup(name string) slog.Handler {
|
||||||
|
c := *h
|
||||||
|
c.prefix = h.prefix + name + "."
|
||||||
|
return &c
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAttr(b *strings.Builder, prefix string, a slog.Attr) {
|
||||||
|
v := a.Value.Resolve()
|
||||||
|
|
||||||
|
if v.Kind() == slog.KindGroup {
|
||||||
|
for _, g := range v.Group() { writeAttr(b, prefix+a.Key+".", g) }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if a.Key == "" { return }
|
||||||
|
|
||||||
|
s := v.String()
|
||||||
|
switch v.Kind() {
|
||||||
|
case slog.KindTime:
|
||||||
|
s = v.Time().Local().Format(time.TimeOnly)
|
||||||
|
case slog.KindDuration:
|
||||||
|
s = v.Duration().Round(time.Second).String()
|
||||||
|
default:
|
||||||
|
// Strings, numbers and errors print as they are.
|
||||||
|
}
|
||||||
|
|
||||||
|
if s == "" || strings.ContainsAny(s, " =\"\n") { s = strconv.Quote(s) }
|
||||||
|
|
||||||
|
if b.Len() > 0 { b.WriteByte(' ') }
|
||||||
|
b.WriteString(prefix + a.Key + "=" + s)
|
||||||
|
}
|
||||||
@@ -0,0 +1,441 @@
|
|||||||
|
// Package tui is the interactive view of dibs: a table with one row per
|
||||||
|
// URL, a log pane and a status bar.
|
||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"charm.land/bubbles/v2/viewport"
|
||||||
|
tea "charm.land/bubbletea/v2"
|
||||||
|
"github.com/pkg/browser"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||||
|
"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/watch"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// tick is how often the table refreshes. It is also the flash rate.
|
||||||
|
tick = 500 * time.Millisecond
|
||||||
|
flashFor = 30 * time.Second
|
||||||
|
noteFor = 10 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxLines is how many lines the log pane keeps.
|
||||||
|
const maxLines = 2000
|
||||||
|
|
||||||
|
// Controller is the running watcher.
|
||||||
|
type Controller interface {
|
||||||
|
Statuses() []watch.Status
|
||||||
|
Pause(item string, paused bool) bool
|
||||||
|
PauseAll(paused bool)
|
||||||
|
CheckNow(item string) bool
|
||||||
|
Reload() ([]string, error)
|
||||||
|
// Solve opens a visible browser on fetchURL for the user to pass its
|
||||||
|
// bot check. It blocks until the check is passed or the window closes.
|
||||||
|
Solve(fetchURL string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckMsg is one finished check and what the alert engine made of it.
|
||||||
|
type CheckMsg struct {
|
||||||
|
Result watch.Result
|
||||||
|
Decision alert.Decision
|
||||||
|
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
|
||||||
|
reloadMsg struct {
|
||||||
|
summary []string
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
openMsg struct {
|
||||||
|
url string
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
solveMsg struct {
|
||||||
|
host string
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Status texts, as the STATUS column shows them.
|
||||||
|
const (
|
||||||
|
statusWatching = "watching"
|
||||||
|
statusAvailable = "AVAILABLE"
|
||||||
|
statusBlocked = "blocked"
|
||||||
|
statusNeedsHuman = "needs-human"
|
||||||
|
statusError = "error"
|
||||||
|
statusPaused = "paused"
|
||||||
|
)
|
||||||
|
|
||||||
|
// result is what the last check of a URL found.
|
||||||
|
type result struct {
|
||||||
|
status string
|
||||||
|
price string
|
||||||
|
seller string
|
||||||
|
cartLink string
|
||||||
|
flash time.Time // the row flashes until then
|
||||||
|
}
|
||||||
|
|
||||||
|
type Model struct {
|
||||||
|
ctl Controller
|
||||||
|
path string
|
||||||
|
lines <-chan LogLine
|
||||||
|
|
||||||
|
now time.Time
|
||||||
|
rows []watch.Status
|
||||||
|
results map[string]*result // by configured URL
|
||||||
|
cursor int
|
||||||
|
offset int // the first table row on screen
|
||||||
|
widths []int // the column widths, reset by resizes and reloads
|
||||||
|
|
||||||
|
logs []LogLine
|
||||||
|
log viewport.Model
|
||||||
|
logFocus bool
|
||||||
|
|
||||||
|
width, height int
|
||||||
|
|
||||||
|
note string
|
||||||
|
noteError bool
|
||||||
|
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
|
||||||
|
// handler the watcher logs to.
|
||||||
|
func New(ctl Controller, path string, logs *LogHandler) *Model {
|
||||||
|
// The browser's own output would draw over the TUI.
|
||||||
|
browser.Stdout, browser.Stderr = io.Discard, io.Discard
|
||||||
|
|
||||||
|
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(path, home+string(os.PathSeparator)) { path = "~" + path[len(home):] }
|
||||||
|
|
||||||
|
m := &Model{
|
||||||
|
ctl: ctl,
|
||||||
|
path: path,
|
||||||
|
lines: logs.sink.lines,
|
||||||
|
now: time.Now(),
|
||||||
|
results: map[string]*result{},
|
||||||
|
log: viewport.New(),
|
||||||
|
}
|
||||||
|
m.rows = ctl.Statuses()
|
||||||
|
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) Init() tea.Cmd {
|
||||||
|
return tea.Batch(m.tick(), m.nextLine())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) tick() tea.Cmd {
|
||||||
|
return tea.Tick(tick, func(t time.Time) tea.Msg { return tickMsg(t) })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) nextLine() tea.Cmd {
|
||||||
|
return func() tea.Msg { return logMsg(<-m.lines) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
m.width, m.height = msg.Width, msg.Height
|
||||||
|
m.widths = nil
|
||||||
|
m.layout()
|
||||||
|
case tickMsg:
|
||||||
|
m.now = time.Time(msg)
|
||||||
|
m.rows = m.ctl.Statuses()
|
||||||
|
m.clampCursor()
|
||||||
|
return m, m.tick()
|
||||||
|
case logMsg:
|
||||||
|
m.addLog(LogLine(msg))
|
||||||
|
return m, m.nextLine()
|
||||||
|
case CheckMsg:
|
||||||
|
return m, m.checked(msg)
|
||||||
|
case reloadMsg:
|
||||||
|
m.reloading = false
|
||||||
|
m.rows = m.ctl.Statuses()
|
||||||
|
m.widths = nil
|
||||||
|
m.clampCursor()
|
||||||
|
if msg.err != nil { m.setNote(reloadError(msg.err), true) } else { m.setNote(reloadNote(msg.summary), false) }
|
||||||
|
case solveMsg:
|
||||||
|
m.solving = ""
|
||||||
|
if msg.err != nil { m.setNote("bot check on "+msg.host+" not solved: "+msg.err.Error(), true) } else { m.setNote("bot check on "+msg.host+" solved, checking again", false) }
|
||||||
|
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]
|
||||||
|
if r == nil {
|
||||||
|
r = &result{}
|
||||||
|
m.results[c.Result.URL] = r
|
||||||
|
}
|
||||||
|
|
||||||
|
r.status = statusOf(c)
|
||||||
|
|
||||||
|
if rep := c.Result.Report; rep != nil {
|
||||||
|
r.price, r.seller = "", ""
|
||||||
|
if res := rep.Result; res != nil {
|
||||||
|
if res.Price != nil { r.price = alert.Money(*res.Price, res.Currency) }
|
||||||
|
r.seller = sellerText(res.Seller)
|
||||||
|
}
|
||||||
|
|
||||||
|
if rep.CartLink != "" { r.cartLink = rep.CartLink }
|
||||||
|
}
|
||||||
|
|
||||||
|
m.rows = m.ctl.Statuses()
|
||||||
|
|
||||||
|
if c.Decision.Alert == nil { return nil }
|
||||||
|
|
||||||
|
r.flash = m.now.Add(flashFor)
|
||||||
|
return tea.Raw("\a")
|
||||||
|
}
|
||||||
|
|
||||||
|
func statusOf(c CheckMsg) string {
|
||||||
|
rep := c.Result.Report
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case rep == nil:
|
||||||
|
return statusError
|
||||||
|
case rep.Verdict == fetch.NeedsHuman.String():
|
||||||
|
return statusNeedsHuman
|
||||||
|
case rep.Verdict == fetch.Challenge.String() || rep.Verdict == fetch.Blocked.String():
|
||||||
|
return statusBlocked
|
||||||
|
case c.Result.Err != nil || rep.Verdict == fetch.HTTPError.String():
|
||||||
|
return statusError
|
||||||
|
case c.Decision.Qualifies:
|
||||||
|
return statusAvailable
|
||||||
|
default:
|
||||||
|
return statusWatching
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sellerText(seller string) string {
|
||||||
|
switch seller {
|
||||||
|
case plugin.SellerFirstParty:
|
||||||
|
return "first party"
|
||||||
|
case plugin.SellerFulfilled:
|
||||||
|
return "fulfilled"
|
||||||
|
case plugin.SellerThirdParty:
|
||||||
|
return "third party"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) key(msg tea.KeyPressMsg) tea.Cmd {
|
||||||
|
k := msg.String()
|
||||||
|
|
||||||
|
switch k {
|
||||||
|
case "q", "ctrl+c":
|
||||||
|
return tea.Quit
|
||||||
|
case "l", "tab":
|
||||||
|
m.logFocus = !m.logFocus
|
||||||
|
return nil
|
||||||
|
case "r":
|
||||||
|
return m.reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.logFocus {
|
||||||
|
if k == "esc" {
|
||||||
|
m.logFocus = false
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var cmd tea.Cmd
|
||||||
|
m.log, cmd = m.log.Update(msg)
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
switch k {
|
||||||
|
case "up", "k":
|
||||||
|
m.cursor--
|
||||||
|
case "down", "j":
|
||||||
|
m.cursor++
|
||||||
|
case "home", "g":
|
||||||
|
m.cursor = 0
|
||||||
|
case "end", "G":
|
||||||
|
m.cursor = len(m.rows) - 1
|
||||||
|
case "P":
|
||||||
|
m.pauseAll()
|
||||||
|
default:
|
||||||
|
return m.rowKey(k)
|
||||||
|
}
|
||||||
|
|
||||||
|
m.clampCursor()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// rowKey handles the keys that act on the selected row.
|
||||||
|
func (m *Model) rowKey(k string) tea.Cmd {
|
||||||
|
if m.cursor >= len(m.rows) { return nil }
|
||||||
|
|
||||||
|
row := m.rows[m.cursor]
|
||||||
|
|
||||||
|
switch k {
|
||||||
|
case "p":
|
||||||
|
m.ctl.Pause(row.Item, !row.Paused)
|
||||||
|
if row.Paused { m.setNote("resumed "+row.Item, false) } else { m.setNote("paused "+row.Item, false) }
|
||||||
|
m.rows = m.ctl.Statuses()
|
||||||
|
case "c":
|
||||||
|
m.ctl.CheckNow(row.Item)
|
||||||
|
m.setNote("checking "+row.Item+" as soon as the rate limits allow", false)
|
||||||
|
m.rows = m.ctl.Statuses()
|
||||||
|
case "o":
|
||||||
|
return open(row.FetchURL)
|
||||||
|
case "enter":
|
||||||
|
r := m.results[row.URL]
|
||||||
|
if r != nil && r.status == statusNeedsHuman { return m.solve(row) }
|
||||||
|
if r != nil && r.cartLink != "" { return open(r.cartLink) }
|
||||||
|
|
||||||
|
m.setNote("no cart link yet, opening the product page", false)
|
||||||
|
return open(row.FetchURL)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// solve opens the row's page in a browser for the user. One bot check is
|
||||||
|
// open at a time.
|
||||||
|
func (m *Model) solve(row watch.Status) tea.Cmd {
|
||||||
|
if m.solving != "" {
|
||||||
|
m.setNote("a browser is already open for "+m.solving, true)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
m.solving = row.Host
|
||||||
|
m.setNote("pass the bot check in the Chrome window; it closes by itself", false)
|
||||||
|
|
||||||
|
return func() tea.Msg { return solveMsg{host: row.Host, err: m.ctl.Solve(row.FetchURL)} }
|
||||||
|
}
|
||||||
|
|
||||||
|
// pauseAll pauses every URL, or resumes them all if all are paused.
|
||||||
|
func (m *Model) pauseAll() {
|
||||||
|
pause := false
|
||||||
|
for _, row := range m.rows {
|
||||||
|
if !row.Paused { pause = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
m.ctl.PauseAll(pause)
|
||||||
|
m.rows = m.ctl.Statuses()
|
||||||
|
|
||||||
|
if pause { m.setNote("paused everything", false) } else { m.setNote("resumed everything", false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) reload() tea.Cmd {
|
||||||
|
if m.reloading { return nil }
|
||||||
|
|
||||||
|
m.reloading = true
|
||||||
|
m.setNote("reloading "+m.path, false)
|
||||||
|
|
||||||
|
return func() tea.Msg {
|
||||||
|
summary, err := m.ctl.Reload()
|
||||||
|
return reloadMsg{summary: summary, err: err}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func reloadNote(summary []string) string {
|
||||||
|
if len(summary) == 1 { return "reloaded: " + summary[0] }
|
||||||
|
|
||||||
|
return fmt.Sprintf("reloaded: %d changes (see log)", len(summary))
|
||||||
|
}
|
||||||
|
|
||||||
|
// reloadError shows the first problem in the config. The log has them all.
|
||||||
|
func reloadError(err error) string {
|
||||||
|
var errs config.Errors
|
||||||
|
if errors.As(err, &errs) && len(errs) > 0 {
|
||||||
|
msg := "reload failed, config unchanged: line " + errs[0].Brief()
|
||||||
|
if len(errs) > 1 { msg += fmt.Sprintf(" (+%d more)", len(errs)-1) }
|
||||||
|
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
return "reload failed, config unchanged: " + err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
func open(url string) tea.Cmd {
|
||||||
|
return func() tea.Msg { return openMsg{url: url, err: browser.OpenURL(url)} }
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) setNote(note string, isError bool) {
|
||||||
|
m.note, m.noteError, m.noteTime = note, isError, time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) addLog(l LogLine) {
|
||||||
|
follow := m.log.AtBottom()
|
||||||
|
|
||||||
|
m.logs = append(m.logs, l)
|
||||||
|
if len(m.logs) > maxLines { m.logs = m.logs[len(m.logs)-maxLines:] }
|
||||||
|
|
||||||
|
m.log.SetContentLines(m.logLines())
|
||||||
|
if follow { m.log.GotoBottom() }
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) clampCursor() {
|
||||||
|
m.cursor = max(0, min(m.cursor, len(m.rows)-1))
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -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") }
|
||||||
|
}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
tea "charm.land/bubbletea/v2"
|
||||||
|
"charm.land/lipgloss/v2"
|
||||||
|
"github.com/charmbracelet/x/ansi"
|
||||||
|
"golang.org/x/net/publicsuffix"
|
||||||
|
|
||||||
|
"git.security-command.org/Overlord/dibs/internal/watch"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The colors are ANSI palette entries, so they follow the terminal's theme.
|
||||||
|
var (
|
||||||
|
bold = lipgloss.NewStyle().Bold(true)
|
||||||
|
faint = lipgloss.NewStyle().Faint(true)
|
||||||
|
green = lipgloss.NewStyle().Foreground(lipgloss.Color("10")).Bold(true)
|
||||||
|
yellow = lipgloss.NewStyle().Foreground(lipgloss.Color("11"))
|
||||||
|
red = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
|
||||||
|
blue = lipgloss.NewStyle().Foreground(lipgloss.Color("12"))
|
||||||
|
magenta = lipgloss.NewStyle().Foreground(lipgloss.Color("13")).Bold(true)
|
||||||
|
selected = lipgloss.NewStyle().Reverse(true)
|
||||||
|
flashing = lipgloss.NewStyle().Background(lipgloss.Color("10")).Foreground(lipgloss.Color("0")).Bold(true)
|
||||||
|
)
|
||||||
|
|
||||||
|
// fixedLines are the lines around the table body and the log: the header,
|
||||||
|
// the column titles, the log title, the status bar and the key help.
|
||||||
|
const fixedLines = 5
|
||||||
|
|
||||||
|
var columns = []struct {
|
||||||
|
title string
|
||||||
|
min, max int
|
||||||
|
} {
|
||||||
|
{"ITEM", 8, 32},
|
||||||
|
{"SHOP", 4, 12},
|
||||||
|
{"TLD", 3, 6},
|
||||||
|
{"STATUS", 11, 11},
|
||||||
|
{"PRICE", 5, 16},
|
||||||
|
{"SELLER", 6, 11},
|
||||||
|
{"LAST", 10, 10},
|
||||||
|
{"NEXT", 9, 9},
|
||||||
|
}
|
||||||
|
|
||||||
|
// layout sizes the table and the log pane to the window.
|
||||||
|
func (m *Model) layout() {
|
||||||
|
avail := max(m.height-fixedLines, 2)
|
||||||
|
body := min(len(m.rows), max(3, avail*55/100), avail-1)
|
||||||
|
body = max(body, 1)
|
||||||
|
|
||||||
|
m.log.SetWidth(m.width)
|
||||||
|
m.log.SetHeight(max(avail-body, 1))
|
||||||
|
|
||||||
|
if m.cursor < m.offset { m.offset = m.cursor }
|
||||||
|
if m.cursor >= m.offset+body { m.offset = m.cursor - body + 1 }
|
||||||
|
m.offset = max(0, min(m.offset, len(m.rows)-body))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) bodyHeight() int {
|
||||||
|
return max(m.height-fixedLines, 2) - m.log.Height()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) View() tea.View {
|
||||||
|
v := tea.NewView("")
|
||||||
|
v.AltScreen = true
|
||||||
|
v.WindowTitle = "dibs"
|
||||||
|
|
||||||
|
if n := m.count(statusAvailable); n > 0 { v.WindowTitle = fmt.Sprintf("dibs · %d AVAILABLE", n) }
|
||||||
|
|
||||||
|
if m.width == 0 { return v }
|
||||||
|
|
||||||
|
m.layout()
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(fit(bold.Render("dibs")+" "+faint.Render(m.path), m.width) + "\n")
|
||||||
|
b.WriteString(m.table())
|
||||||
|
b.WriteString(m.logTitle() + "\n")
|
||||||
|
b.WriteString(m.log.View() + "\n")
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) table() string {
|
||||||
|
cells := make([][]string, len(m.rows))
|
||||||
|
widths := make([]int, len(columns))
|
||||||
|
|
||||||
|
for i, c := range columns { widths[i] = max(c.min, len(c.title)) }
|
||||||
|
|
||||||
|
for i, row := range m.rows {
|
||||||
|
cells[i] = m.cells(row)
|
||||||
|
for j, c := range cells[i] { widths[j] = max(widths[j], min(ansi.StringWidth(c), columns[j].max)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Columns only grow, so they do not shift every time a price or a time
|
||||||
|
// gets shorter.
|
||||||
|
if len(m.widths) == len(widths) {
|
||||||
|
for i := range widths { widths[i] = max(widths[i], m.widths[i]) }
|
||||||
|
}
|
||||||
|
m.widths = append(m.widths[:0], widths...)
|
||||||
|
|
||||||
|
// The ITEM column gives way first when the window is narrow.
|
||||||
|
total := 2
|
||||||
|
for _, w := range widths { total += w + 2 }
|
||||||
|
if over := total - m.width; over > 0 { widths[0] = max(columns[0].min, widths[0]-over) }
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
|
||||||
|
titles := make([]string, len(columns))
|
||||||
|
for i, c := range columns { titles[i] = c.title }
|
||||||
|
b.WriteString(fit(faint.Render(" "+joinCells(titles, widths)), m.width) + "\n")
|
||||||
|
|
||||||
|
body := m.bodyHeight()
|
||||||
|
for i := m.offset; i < m.offset+body; i++ {
|
||||||
|
if i >= len(m.rows) {
|
||||||
|
b.WriteString("\n")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
b.WriteString(m.rowLine(i, cells[i], widths) + "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) rowLine(i int, cells []string, widths []int) string {
|
||||||
|
r := m.results[m.rows[i].URL]
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case r != nil && m.now.Before(r.flash) && m.now.UnixMilli()/tick.Milliseconds()%2 == 0:
|
||||||
|
return flashing.Render(padRight(" "+joinCells(cells, widths), m.width))
|
||||||
|
case i == m.cursor && !m.logFocus:
|
||||||
|
return selected.Render(padRight("> "+joinCells(cells, widths), m.width))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the status cell is colored.
|
||||||
|
status := statusStyle(cells[3]).Render(padRight(cells[3], widths[3]))
|
||||||
|
line := " " + joinCells(cells[:3], widths[:3]) + " " + status + " " + joinCells(cells[4:], widths[4:])
|
||||||
|
|
||||||
|
return fit(line, m.width)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) cells(row watch.Status) []string {
|
||||||
|
r := m.results[row.URL]
|
||||||
|
if r == nil { r = &result{status: statusWatching} }
|
||||||
|
|
||||||
|
status := r.status
|
||||||
|
if row.Paused { status = statusPaused }
|
||||||
|
|
||||||
|
return []string{row.Item, row.Shop, tld(row.Host), status, orDash(r.price), orDash(r.seller), m.ago(row.Last), m.until(row)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func statusStyle(status string) lipgloss.Style {
|
||||||
|
switch status {
|
||||||
|
case statusAvailable:
|
||||||
|
return green
|
||||||
|
case statusBlocked:
|
||||||
|
return yellow
|
||||||
|
case statusNeedsHuman:
|
||||||
|
return magenta
|
||||||
|
case statusError:
|
||||||
|
return red
|
||||||
|
case statusPaused:
|
||||||
|
return faint
|
||||||
|
default:
|
||||||
|
return lipgloss.NewStyle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) logTitle() string {
|
||||||
|
title := "── log "
|
||||||
|
if m.logFocus { return fit(bold.Render(title+"(scrolling) "+strings.Repeat("─", m.width)), m.width) }
|
||||||
|
|
||||||
|
return fit(faint.Render(title+strings.Repeat("─", m.width)), m.width)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) logLines() []string {
|
||||||
|
out := make([]string, len(m.logs))
|
||||||
|
|
||||||
|
for i, l := range m.logs {
|
||||||
|
level := fmt.Sprintf("%-5s", l.Level)
|
||||||
|
switch {
|
||||||
|
case l.Level >= slog.LevelError:
|
||||||
|
level = red.Render(level)
|
||||||
|
case l.Level >= slog.LevelWarn:
|
||||||
|
level = yellow.Render(level)
|
||||||
|
case l.Level >= slog.LevelInfo:
|
||||||
|
level = blue.Render(level)
|
||||||
|
default:
|
||||||
|
level = faint.Render(level)
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := l.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)
|
||||||
|
}
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) statusBar() string {
|
||||||
|
parts := []string{fmt.Sprintf("%d URLs", len(m.rows))}
|
||||||
|
|
||||||
|
for _, s := range []struct {
|
||||||
|
status string
|
||||||
|
style lipgloss.Style
|
||||||
|
} {
|
||||||
|
{statusAvailable, green},
|
||||||
|
{statusNeedsHuman, magenta},
|
||||||
|
{statusBlocked, yellow},
|
||||||
|
{statusError, red},
|
||||||
|
{statusPaused, faint},
|
||||||
|
} {
|
||||||
|
if n := m.count(s.status); n > 0 { parts = append(parts, s.style.Render(fmt.Sprintf("%d %s", n, s.status))) }
|
||||||
|
}
|
||||||
|
|
||||||
|
left := strings.Join(parts, faint.Render(" · "))
|
||||||
|
|
||||||
|
note := ""
|
||||||
|
if m.note != "" && time.Since(m.noteTime) < noteFor {
|
||||||
|
note = m.note
|
||||||
|
if m.noteError { note = red.Render(note) }
|
||||||
|
}
|
||||||
|
|
||||||
|
gap := m.width - ansi.StringWidth(left) - ansi.StringWidth(note)
|
||||||
|
if gap < 2 { return fit(left+" "+note, m.width) }
|
||||||
|
|
||||||
|
return left + strings.Repeat(" ", gap) + note
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) help() string {
|
||||||
|
if m.logFocus { return "↑↓ pgup pgdn scroll · l/esc back to the table · r reload · q quit" }
|
||||||
|
|
||||||
|
return "↑↓ select · p pause · P pause all · c check now · o open page · enter cart or bot check · l log · r reload · q quit"
|
||||||
|
}
|
||||||
|
|
||||||
|
// count is the number of rows showing status.
|
||||||
|
func (m *Model) count(status string) int {
|
||||||
|
n := 0
|
||||||
|
for _, row := range m.rows {
|
||||||
|
if m.cells(row)[3] == status { n++ }
|
||||||
|
}
|
||||||
|
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) ago(t time.Time) string {
|
||||||
|
if t.IsZero() { return "—" }
|
||||||
|
|
||||||
|
return short(m.now.Sub(t)) + " ago"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Model) until(row watch.Status) string {
|
||||||
|
switch {
|
||||||
|
case row.Paused:
|
||||||
|
return "—"
|
||||||
|
case row.Checking:
|
||||||
|
return "checking"
|
||||||
|
}
|
||||||
|
|
||||||
|
d := row.Next.Sub(m.now)
|
||||||
|
if d <= 0 { return "due" }
|
||||||
|
|
||||||
|
return "in " + short(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
// short formats d as "45s", "3m05s" or "1h20m".
|
||||||
|
func short(d time.Duration) string {
|
||||||
|
d = max(d, 0).Round(time.Second)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case d < time.Minute:
|
||||||
|
return fmt.Sprintf("%ds", int(d.Seconds()))
|
||||||
|
case d < time.Hour:
|
||||||
|
return fmt.Sprintf("%dm%02ds", int(d.Minutes()), int(d.Seconds())%60)
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("%dh%02dm", int(d.Hours()), int(d.Minutes())%60)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func tld(host string) string {
|
||||||
|
suffix, _ := publicsuffix.PublicSuffix(host)
|
||||||
|
return suffix
|
||||||
|
}
|
||||||
|
|
||||||
|
func orDash(s string) string {
|
||||||
|
if s == "" { return "—" }
|
||||||
|
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func joinCells(cells []string, widths []int) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for i, c := range cells {
|
||||||
|
if i > 0 { b.WriteString(" ") }
|
||||||
|
b.WriteString(padRight(ansi.Truncate(c, widths[i], "…"), widths[i]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func padRight(s string, w int) string {
|
||||||
|
return s + strings.Repeat(" ", max(0, w-ansi.StringWidth(s)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// fit cuts s to the window width.
|
||||||
|
func fit(s string, w int) string {
|
||||||
|
return ansi.Truncate(s, w, "")
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
// Package watch schedules the checks of every configured URL.
|
||||||
|
package watch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"math/rand/v2"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// tick is how often the scheduler looks for due URLs.
|
||||||
|
const tick = time.Second
|
||||||
|
|
||||||
|
// queue is how many checks a host's worker can have waiting. With the
|
||||||
|
// host floor of 10s, a full queue is over an hour of checks.
|
||||||
|
const queue = 512
|
||||||
|
|
||||||
|
// Fetcher fetches pages. *fetch.Client is the real one; it waits for the
|
||||||
|
// limiter's WaitCheck itself.
|
||||||
|
type Fetcher interface {
|
||||||
|
Get(ctx context.Context, url string) (*fetch.Response, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Result is one finished check.
|
||||||
|
type Result struct {
|
||||||
|
Item config.Item
|
||||||
|
// URL is the URL as configured.
|
||||||
|
URL string
|
||||||
|
Time time.Time
|
||||||
|
Report *plugin.Report
|
||||||
|
Err error
|
||||||
|
// Backoff is how long the host is avoided after this result, if at all.
|
||||||
|
Backoff time.Duration
|
||||||
|
// Next is when the URL is checked next.
|
||||||
|
Next time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status is a snapshot of one URL for display.
|
||||||
|
type Status struct {
|
||||||
|
Item string
|
||||||
|
Shop string
|
||||||
|
URL string
|
||||||
|
FetchURL string
|
||||||
|
Host string
|
||||||
|
Last time.Time
|
||||||
|
Next time.Time
|
||||||
|
Paused bool
|
||||||
|
Checking bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// target is one URL to check. Reload may change any field, so everything
|
||||||
|
// is guarded by Scheduler.mu.
|
||||||
|
type target struct {
|
||||||
|
item config.Item
|
||||||
|
url string // as configured
|
||||||
|
fetchURL string // normalized by the plugin
|
||||||
|
host string
|
||||||
|
plugin *plugin.Plugin
|
||||||
|
|
||||||
|
last time.Time
|
||||||
|
next time.Time
|
||||||
|
paused bool
|
||||||
|
inFlight bool
|
||||||
|
// removed is set when a reload drops the URL during its check.
|
||||||
|
removed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scheduler checks every URL at its interval. Each round, the due URLs are
|
||||||
|
// shuffled and handed to one worker per host, so hosts are checked in
|
||||||
|
// parallel and each host's requests in sequence.
|
||||||
|
type Scheduler struct {
|
||||||
|
fetcher Fetcher
|
||||||
|
limiter *ratelimit.Limiter
|
||||||
|
clock ratelimit.Clock
|
||||||
|
results chan Result
|
||||||
|
wake chan struct{}
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
targets []*target
|
||||||
|
}
|
||||||
|
|
||||||
|
// New plans a check for every URL of every item. It returns warnings about
|
||||||
|
// URLs a plugin's matches() rejects; they are still checked.
|
||||||
|
func New(ctx context.Context, cfg *config.Config, host *plugin.Host, fetcher Fetcher, limiter *ratelimit.Limiter) (*Scheduler, []string, error) {
|
||||||
|
s := &Scheduler{
|
||||||
|
fetcher: fetcher,
|
||||||
|
limiter: limiter,
|
||||||
|
clock: limiter.Clock(),
|
||||||
|
results: make(chan Result, 64),
|
||||||
|
wake: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
targets, warnings, err := s.plan(ctx, cfg, host)
|
||||||
|
if err != nil { return nil, nil, err }
|
||||||
|
|
||||||
|
s.targets = targets
|
||||||
|
return s, warnings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reload switches to a new config. URLs in both configs keep their timing
|
||||||
|
// and pause state; a changed interval applies from the next check. A
|
||||||
|
// failed reload changes nothing.
|
||||||
|
func (s *Scheduler) Reload(ctx context.Context, cfg *config.Config, host *plugin.Host) ([]string, error) {
|
||||||
|
targets, warnings, err := s.plan(ctx, cfg, host)
|
||||||
|
if err != nil { return nil, err }
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
old := map[string]*target{}
|
||||||
|
for _, t := range s.targets { old[t.fetchURL] = t }
|
||||||
|
|
||||||
|
for i, t := range targets {
|
||||||
|
prev, ok := old[t.fetchURL]
|
||||||
|
if !ok { continue }
|
||||||
|
|
||||||
|
delete(old, t.fetchURL)
|
||||||
|
|
||||||
|
interval := prev.item.Interval.Duration
|
||||||
|
prev.item, prev.url, prev.plugin = t.item, t.url, t.plugin
|
||||||
|
if !prev.inFlight && t.item.Interval.Duration != interval { prev.next = t.next }
|
||||||
|
|
||||||
|
targets[i] = prev
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, t := range old { t.removed = true }
|
||||||
|
|
||||||
|
s.targets = targets
|
||||||
|
s.poke()
|
||||||
|
|
||||||
|
return warnings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// plan builds the targets of cfg.
|
||||||
|
func (s *Scheduler) plan(ctx context.Context, cfg *config.Config, host *plugin.Host) ([]*target, []string, error) {
|
||||||
|
var targets []*target
|
||||||
|
var warnings []string
|
||||||
|
|
||||||
|
seen := map[string]string{}
|
||||||
|
|
||||||
|
for _, item := range cfg.Items {
|
||||||
|
p, ok := host.Plugin(item.Shop)
|
||||||
|
if !ok { return nil, nil, fmt.Errorf("item %q: no plugin named %q", item.Name, item.Shop) }
|
||||||
|
|
||||||
|
for _, raw := range item.URLs {
|
||||||
|
if p.Has("matches") {
|
||||||
|
ok, err := p.Matches(ctx, raw)
|
||||||
|
if err != nil { return nil, nil, err }
|
||||||
|
if !ok { warnings = append(warnings, fmt.Sprintf("item %q: %s does not look like a %s URL", item.Name, raw, item.Shop)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchURL, err := p.Normalize(ctx, raw)
|
||||||
|
if err != nil { return nil, nil, err }
|
||||||
|
|
||||||
|
// Two spellings of one product would be checked twice as often.
|
||||||
|
if prev, dup := seen[fetchURL]; dup { return nil, nil, fmt.Errorf("item %q: %s is the same page as %s", item.Name, raw, prev) }
|
||||||
|
seen[fetchURL] = raw
|
||||||
|
|
||||||
|
u, err := url.Parse(fetchURL)
|
||||||
|
if err != nil { return nil, nil, err }
|
||||||
|
|
||||||
|
targets = append(targets, &target{
|
||||||
|
item: item,
|
||||||
|
url: raw,
|
||||||
|
fetchURL: fetchURL,
|
||||||
|
host: strings.ToLower(u.Hostname()),
|
||||||
|
plugin: p,
|
||||||
|
last: s.limiter.LastCheck(fetchURL),
|
||||||
|
next: s.limiter.NextCheck(fetchURL, item.Interval.Duration),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return targets, warnings, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Results delivers every finished check. It is closed when Run returns.
|
||||||
|
func (s *Scheduler) Results() <-chan Result { return s.results }
|
||||||
|
|
||||||
|
// Run checks URLs until ctx is done.
|
||||||
|
func (s *Scheduler) Run(ctx context.Context) {
|
||||||
|
workers := map[string]chan *target{}
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
for _, ch := range workers { close(ch) }
|
||||||
|
wg.Wait()
|
||||||
|
close(s.results)
|
||||||
|
}()
|
||||||
|
|
||||||
|
for {
|
||||||
|
due := s.due()
|
||||||
|
rand.Shuffle(len(due), func(i, j int) { due[i], due[j] = due[j], due[i] })
|
||||||
|
|
||||||
|
for _, t := range due {
|
||||||
|
ch, ok := workers[t.host]
|
||||||
|
if !ok {
|
||||||
|
ch = make(chan *target, queue)
|
||||||
|
workers[t.host] = ch
|
||||||
|
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for t := range ch { s.check(ctx, t) }
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
ch <- t
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-s.clock.After(tick):
|
||||||
|
case <-s.wake:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// due marks and returns the targets whose time has come.
|
||||||
|
func (s *Scheduler) due() []*target {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
now := s.clock.Now()
|
||||||
|
|
||||||
|
var due []*target
|
||||||
|
for _, t := range s.targets {
|
||||||
|
if t.paused || t.inFlight || now.Before(t.next) { continue }
|
||||||
|
|
||||||
|
// Another dibs process may have checked the URL since this check was
|
||||||
|
// planned.
|
||||||
|
if ready := s.limiter.URLReady(t.fetchURL); now.Before(ready) {
|
||||||
|
t.next = s.limiter.NextCheck(t.fetchURL, t.item.Interval.Duration)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
t.inFlight = true
|
||||||
|
due = append(due, t)
|
||||||
|
}
|
||||||
|
|
||||||
|
return due
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) check(ctx context.Context, t *target) {
|
||||||
|
if ctx.Err() != nil { return }
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
item, rawURL, fetchURL, p := t.item, t.url, t.fetchURL, t.plugin
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
// The fetcher reserves the check with the limiter right before the request.
|
||||||
|
resp, err := s.fetcher.Get(ctx, fetchURL)
|
||||||
|
if ctx.Err() != nil { return }
|
||||||
|
|
||||||
|
backoff := fetch.RecordOutcome(s.limiter, t.host, resp, err)
|
||||||
|
|
||||||
|
var report *plugin.Report
|
||||||
|
if err == nil { report, err = plugin.Evaluate(ctx, p, rawURL, resp) }
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
t.last = s.clock.Now()
|
||||||
|
t.next = s.limiter.NextCheck(fetchURL, t.item.Interval.Duration)
|
||||||
|
t.inFlight = false
|
||||||
|
last, next := t.last, t.next
|
||||||
|
removed := t.removed
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if removed { return }
|
||||||
|
|
||||||
|
r := Result{Item: item, URL: rawURL, Time: last, Report: report, Err: err, Backoff: backoff, Next: next}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case s.results <- r:
|
||||||
|
case <-ctx.Done():
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
found := s.each(func(t *target) bool { return t.item.Name == name }, func(t *target) { t.paused = paused })
|
||||||
|
s.poke()
|
||||||
|
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) PauseAll(paused bool) {
|
||||||
|
s.each(func(*target) bool { return true }, func(t *target) { t.paused = paused })
|
||||||
|
s.poke()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckNow moves the checks of the item called name forward, as far as the
|
||||||
|
// URL floor allows. It reports whether there is such an item.
|
||||||
|
func (s *Scheduler) CheckNow(name string) bool {
|
||||||
|
found := s.each(func(t *target) bool { return t.item.Name == name }, s.soon)
|
||||||
|
s.poke()
|
||||||
|
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
// soon moves the check of t forward to the earliest time the URL floor
|
||||||
|
// allows. Callers hold mu.
|
||||||
|
func (s *Scheduler) soon(t *target) {
|
||||||
|
ready := s.limiter.URLReady(t.fetchURL)
|
||||||
|
if now := s.clock.Now(); ready.Before(now) { ready = now }
|
||||||
|
if ready.Before(t.next) { t.next = ready }
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckHost moves the checks of every URL on host forward, as far as the
|
||||||
|
// URL floor allows.
|
||||||
|
func (s *Scheduler) CheckHost(host string) {
|
||||||
|
host = strings.ToLower(host)
|
||||||
|
|
||||||
|
s.each(func(t *target) bool { return t.host == host }, s.soon)
|
||||||
|
s.poke()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Statuses returns a snapshot of every URL, in config order.
|
||||||
|
func (s *Scheduler) Statuses() []Status {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
out := make([]Status, len(s.targets))
|
||||||
|
for i, t := range s.targets {
|
||||||
|
out[i] = Status{
|
||||||
|
Item: t.item.Name,
|
||||||
|
Shop: t.item.Shop,
|
||||||
|
URL: t.url,
|
||||||
|
FetchURL: t.fetchURL,
|
||||||
|
Host: t.host,
|
||||||
|
Last: t.last,
|
||||||
|
Next: t.next,
|
||||||
|
Paused: t.paused,
|
||||||
|
Checking: t.inFlight,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Scheduler) each(match func(*target) bool, change func(*target)) bool {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
found := false
|
||||||
|
for _, t := range s.targets {
|
||||||
|
if !match(t) { continue }
|
||||||
|
|
||||||
|
change(t)
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
// poke makes Run look for due URLs right away.
|
||||||
|
func (s *Scheduler) poke() {
|
||||||
|
select {
|
||||||
|
case s.wake <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
package watch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"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/state"
|
||||||
|
)
|
||||||
|
|
||||||
|
// clock moves forward only when something waits on it.
|
||||||
|
type clock struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
now time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *clock) Now() time.Time {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
return c.now
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *clock) After(d time.Duration) <-chan time.Time {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
c.now = c.now.Add(d)
|
||||||
|
|
||||||
|
ch := make(chan time.Time, 1)
|
||||||
|
ch <- c.now
|
||||||
|
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetcher waits for the limiter like fetch.Client does, records when each
|
||||||
|
// request went out, and answers 404 so no plugin has to parse anything.
|
||||||
|
type fetcher struct {
|
||||||
|
limiter *ratelimit.Limiter
|
||||||
|
clock *clock
|
||||||
|
requests map[string][]time.Time // by URL
|
||||||
|
hosts map[string][]time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fetcher) Get(ctx context.Context, rawURL string) (*fetch.Response, error) {
|
||||||
|
u, _ := url.Parse(rawURL)
|
||||||
|
if err := f.limiter.WaitCheck(ctx, rawURL); err != nil { return nil, err }
|
||||||
|
|
||||||
|
now := f.clock.Now()
|
||||||
|
f.requests[rawURL] = append(f.requests[rawURL], now)
|
||||||
|
f.hosts[u.Hostname()] = append(f.hosts[u.Hostname()], now)
|
||||||
|
|
||||||
|
return fetch.NewResponse(rawURL, rawURL, 404, nil, nil), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func item(name string, interval time.Duration, urls ...string) config.Item {
|
||||||
|
it := config.Item{Name: name, Shop: "amazon", URLs: urls, Seller: config.SellerFulfilled}
|
||||||
|
it.Interval.Duration = interval
|
||||||
|
|
||||||
|
return it
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSchedulerFloors runs the scheduler's rounds by hand for two simulated
|
||||||
|
// hours and checks no URL or host was ever asked too often.
|
||||||
|
func TestSchedulerFloors(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clk := &clock{now: time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)}
|
||||||
|
|
||||||
|
limiter := ratelimit.New(nil, ratelimit.WithClock(clk))
|
||||||
|
|
||||||
|
host, err := plugin.NewHost(nil, plugin.DefaultLimits(), slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
defer host.Close()
|
||||||
|
|
||||||
|
cfg := &config.Config{Items: []config.Item{
|
||||||
|
item("metro", ratelimit.URLFloor, "https://www.amazon.de/dp/B0HMX2FSTF?th=1", "https://www.amazon.co.uk/dp/B0HM497GJJ"),
|
||||||
|
item("cable", ratelimit.URLFloor, "https://www.amazon.de/dp/B0DK51S84Z"),
|
||||||
|
item("disk", 5*time.Minute, "https://www.amazon.de/dp/B076WS2WJ6"),
|
||||||
|
item("held", ratelimit.URLFloor, "https://www.amazon.de/dp/B0948LPGNG"),
|
||||||
|
}}
|
||||||
|
|
||||||
|
f := &fetcher{limiter: limiter, clock: clk, requests: map[string][]time.Time{}, hosts: map[string][]time.Time{}}
|
||||||
|
|
||||||
|
s, _, err := New(ctx, cfg, host, f, limiter)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
s.Pause("held", true)
|
||||||
|
|
||||||
|
end := clk.Now().Add(2 * time.Hour)
|
||||||
|
for clk.Now().Before(end) {
|
||||||
|
for _, tg := range s.due() { s.check(ctx, tg) }
|
||||||
|
for len(s.results) > 0 { <-s.results }
|
||||||
|
|
||||||
|
<-clk.After(tick)
|
||||||
|
}
|
||||||
|
|
||||||
|
for u, times := range f.requests {
|
||||||
|
if len(times) < 10 { t.Errorf("%s: only %d checks in two hours", u, len(times)) }
|
||||||
|
|
||||||
|
for i := 1; i < len(times); i++ {
|
||||||
|
if gap := times[i].Sub(times[i-1]); gap < ratelimit.URLFloor { t.Errorf("%s: checks %s apart", u, gap) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for h, times := range f.hosts {
|
||||||
|
for i := 1; i < len(times); i++ {
|
||||||
|
if gap := times[i].Sub(times[i-1]); gap < ratelimit.HostFloor { t.Errorf("%s: requests %s apart", h, gap) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if n := len(f.requests["https://www.amazon.de/dp/B0948LPGNG"]); n > 0 { t.Errorf("paused item was checked %d times", n) }
|
||||||
|
if _, ok := f.requests["https://www.amazon.de/dp/B0HMX2FSTF"]; !ok { t.Errorf("URLs are not fetched normalized: %v", f.requests) }
|
||||||
|
|
||||||
|
// A forced check still waits for the URL floor.
|
||||||
|
s.CheckNow("cable")
|
||||||
|
for _, st := range s.Statuses() {
|
||||||
|
if st.Item == "cable" && st.Next.Sub(st.Last) < ratelimit.URLFloor-tick { t.Errorf("forced check at %s, only %s after the last", st.Next, st.Next.Sub(st.Last)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A `dibs check` of a URL between two scheduled checks pushes the next one
|
||||||
|
// back to the URL floor.
|
||||||
|
func TestSchedulerSeesOtherProcess(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
dir := t.TempDir()
|
||||||
|
clk := &clock{now: time.Now()} // the state file forgets entries older than a week
|
||||||
|
|
||||||
|
limiter := ratelimit.New(state.Open(dir), ratelimit.WithClock(clk))
|
||||||
|
other := ratelimit.New(state.Open(dir), ratelimit.WithClock(clk))
|
||||||
|
|
||||||
|
host, err := plugin.NewHost(nil, plugin.DefaultLimits(), slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
defer host.Close()
|
||||||
|
|
||||||
|
const u = "https://www.amazon.de/dp/B0DK51S84Z"
|
||||||
|
|
||||||
|
f := &fetcher{limiter: limiter, clock: clk, requests: map[string][]time.Time{}, hosts: map[string][]time.Time{}}
|
||||||
|
|
||||||
|
s, _, err := New(ctx, &config.Config{Items: []config.Item{item("cable", ratelimit.URLFloor, u)}}, host, f, limiter)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
for _, tg := range s.due() { s.check(ctx, tg) }
|
||||||
|
|
||||||
|
// Before the next scheduled check, the other process checks the URL as
|
||||||
|
// soon as the floor allows.
|
||||||
|
<-clk.After(30 * time.Second)
|
||||||
|
if err := other.WaitCheck(ctx, u); err != nil { t.Fatal(err) }
|
||||||
|
checkedByOther := clk.Now()
|
||||||
|
|
||||||
|
for clk.Now().Before(checkedByOther.Add(2 * time.Minute)) {
|
||||||
|
for _, tg := range s.due() { s.check(ctx, tg) }
|
||||||
|
for len(s.results) > 0 { <-s.results }
|
||||||
|
|
||||||
|
<-clk.After(tick)
|
||||||
|
}
|
||||||
|
|
||||||
|
times := f.requests[u]
|
||||||
|
if len(times) < 2 { t.Fatalf("checked %d times, want at least 2", len(times)) }
|
||||||
|
if gap := times[1].Sub(checkedByOther); gap < ratelimit.URLFloor { t.Errorf("checked %s after the other process did", gap) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDuplicateURLs(t *testing.T) {
|
||||||
|
host, err := plugin.NewHost(nil, plugin.DefaultLimits(), slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
defer host.Close()
|
||||||
|
|
||||||
|
cfg := &config.Config{Items: []config.Item{
|
||||||
|
item("a", ratelimit.URLFloor, "https://www.amazon.de/dp/B0HMX2FSTF"),
|
||||||
|
item("b", ratelimit.URLFloor, "https://www.amazon.de/Metro/dp/B0HMX2FSTF/ref=x"),
|
||||||
|
}}
|
||||||
|
|
||||||
|
if _, _, err := New(context.Background(), cfg, host, nil, ratelimit.New(nil)); err == nil { t.Error("two spellings of one product were accepted") }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReload(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
clk := &clock{now: time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)}
|
||||||
|
|
||||||
|
limiter := ratelimit.New(nil, ratelimit.WithClock(clk))
|
||||||
|
|
||||||
|
host, err := plugin.NewHost(nil, plugin.DefaultLimits(), slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
defer host.Close()
|
||||||
|
|
||||||
|
f := &fetcher{limiter: limiter, clock: clk, requests: map[string][]time.Time{}, hosts: map[string][]time.Time{}}
|
||||||
|
|
||||||
|
s, _, err := New(ctx, &config.Config{Items: []config.Item{
|
||||||
|
item("metro", ratelimit.URLFloor, "https://www.amazon.de/dp/B0HMX2FSTF", "https://www.amazon.co.uk/dp/B0HM497GJJ"),
|
||||||
|
item("cable", ratelimit.URLFloor, "https://www.amazon.de/dp/B0DK51S84Z"),
|
||||||
|
}}, host, f, limiter)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
for _, tg := range s.due() { s.check(ctx, tg) }
|
||||||
|
s.Pause("metro", true)
|
||||||
|
|
||||||
|
before := map[string]Status{}
|
||||||
|
for _, st := range s.Statuses() { before[st.URL] = st }
|
||||||
|
|
||||||
|
// The DE URL stays under a new spelling, the UK one goes, cable is
|
||||||
|
// renamed and a new item comes in.
|
||||||
|
_, err = s.Reload(ctx, &config.Config{Items: []config.Item{
|
||||||
|
item("metro", ratelimit.URLFloor, "https://www.amazon.de/dp/B0HMX2FSTF?th=1"),
|
||||||
|
item("cable2", ratelimit.URLFloor, "https://www.amazon.de/dp/B0DK51S84Z"),
|
||||||
|
item("disk", ratelimit.URLFloor, "https://www.amazon.de/dp/B076WS2WJ6"),
|
||||||
|
}}, host)
|
||||||
|
if err != nil { t.Fatal(err) }
|
||||||
|
|
||||||
|
got := s.Statuses()
|
||||||
|
if len(got) != 3 { t.Fatalf("%d URLs after reload, want 3", len(got)) }
|
||||||
|
|
||||||
|
metro, cable, disk := got[0], got[1], got[2]
|
||||||
|
if !metro.Paused || !metro.Last.Equal(before["https://www.amazon.de/dp/B0HMX2FSTF"].Last) { t.Errorf("metro lost its state: %+v", metro) }
|
||||||
|
if cable.Item != "cable2" || !cable.Next.Equal(before["https://www.amazon.de/dp/B0DK51S84Z"].Next) { t.Errorf("cable lost its state: %+v", cable) }
|
||||||
|
if disk.Paused || !disk.Last.IsZero() { t.Errorf("new item has old state: %+v", disk) }
|
||||||
|
}
|
||||||
Vendored
+36
@@ -0,0 +1,36 @@
|
|||||||
|
# Real Amazon pages the amazon plugin is tested on. `dibs fixtures` fetches
|
||||||
|
# them into pages/ (not tracked), together with the report dibs made for
|
||||||
|
# each. Pages change over time, so a case that stops showing what its note
|
||||||
|
# says needs another product.
|
||||||
|
#
|
||||||
|
# No case covers a page sold by Amazon itself or a preorder yet.
|
||||||
|
|
||||||
|
[[case]]
|
||||||
|
name = "out-of-stock-de"
|
||||||
|
url = "https://www.amazon.de/dp/B0HMX2FSTF"
|
||||||
|
note = "Metro 2039 CE (Xbox), currently unavailable, no offer at all"
|
||||||
|
|
||||||
|
[[case]]
|
||||||
|
name = "out-of-stock-uk"
|
||||||
|
url = "https://www.amazon.co.uk/dp/B0HM497GJJ"
|
||||||
|
note = "Metro 2039 CE (PC), currently unavailable, prices in GBP"
|
||||||
|
|
||||||
|
[[case]]
|
||||||
|
name = "fulfilled-de"
|
||||||
|
url = "https://www.amazon.de/dp/B0DK51S84Z"
|
||||||
|
note = "Silkland cable, sold by Silkland-DE, shipped by Amazon"
|
||||||
|
|
||||||
|
[[case]]
|
||||||
|
name = "fulfilled-de-2"
|
||||||
|
url = "https://www.amazon.de/dp/B076WS2WJ6"
|
||||||
|
note = "UGREEN enclosure, sold by a marketplace seller, shipped by Amazon"
|
||||||
|
|
||||||
|
[[case]]
|
||||||
|
name = "used-only-de"
|
||||||
|
url = "https://www.amazon.de/dp/B0948LPGNG"
|
||||||
|
note = "Metro Exodus Complete (PS5), only a used copy in the buybox: not available"
|
||||||
|
|
||||||
|
[[case]]
|
||||||
|
name = "not-found-de"
|
||||||
|
url = "https://www.amazon.de/dp/B0NOTREAL1"
|
||||||
|
note = "no such product: Amazon's 404 dog page"
|
||||||
Vendored
+20
@@ -0,0 +1,20 @@
|
|||||||
|
# How the amazon plugin's normalize() rewrites product URLs. Anything that is
|
||||||
|
# not an Amazon product URL on a supported TLD stays as it is.
|
||||||
|
|
||||||
|
normalize = [
|
||||||
|
{ in = "https://www.amazon.de/dp/B0HMX2FSTF", out = "https://www.amazon.de/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://www.amazon.de/dp/B0HMX2FSTF?th=1", out = "https://www.amazon.de/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://www.amazon.de/dp/B0HMX2FSTF/ref=sr_1_1?th=1&psc=1", out = "https://www.amazon.de/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://www.amazon.de/Metro-2039-Collectors-Edition/dp/B0HMX2FSTF", out = "https://www.amazon.de/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://www.amazon.co.uk/gp/product/B0HM497GJJ", out = "https://www.amazon.co.uk/dp/B0HM497GJJ" },
|
||||||
|
{ in = "https://www.amazon.co.uk/gp/product/B0HM497GJJ/ref=ppx_yo_dt_b_asin", out = "https://www.amazon.co.uk/dp/B0HM497GJJ" },
|
||||||
|
{ in = "https://www.amazon.fr/gp/aw/d/B0HMX2FSTF", out = "https://www.amazon.fr/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://amazon.it/dp/b0hmx2fstf", out = "https://www.amazon.it/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "HTTPS://WWW.AMAZON.ES/dp/B0HMX2FSTF#reviews", out = "https://www.amazon.es/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://www.amazon.nl/dp/B0HMX2FSTF", out = "https://www.amazon.nl/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://www.amazon.com/exec/obidos/ASIN/B0HMX2FSTF", out = "https://www.amazon.com/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://www.amazon.co.jp/dp/B0HMX2FSTF", out = "https://www.amazon.co.jp/dp/B0HMX2FSTF" },
|
||||||
|
{ in = "https://www.amazon.de/s?k=metro", out = "https://www.amazon.de/s?k=metro" },
|
||||||
|
{ in = "https://www.amazon.de/dp/B0HMX2FSTFX", out = "https://www.amazon.de/dp/B0HMX2FSTFX" },
|
||||||
|
{ in = "https://www.notamazon.de/dp/B0HMX2FSTF", out = "https://www.notamazon.de/dp/B0HMX2FSTF" },
|
||||||
|
]
|
||||||
Vendored
+8
@@ -0,0 +1,8 @@
|
|||||||
|
-- Recurses until the call stack limit is hit.
|
||||||
|
local function deep(n) return deep(n + 1) + 1 end
|
||||||
|
|
||||||
|
return { parse = function()
|
||||||
|
deep(0)
|
||||||
|
|
||||||
|
return { available = true }
|
||||||
|
end }
|
||||||
Vendored
+9
@@ -0,0 +1,9 @@
|
|||||||
|
-- Nothing that reads files, loads code or reaches the interpreter's
|
||||||
|
-- internals may be visible to a plugin.
|
||||||
|
local leaked = {}
|
||||||
|
for _, name in ipairs({ "os", "io", "debug", "package", "coroutine", "dofile", "loadfile", "load",
|
||||||
|
"loadstring", "require", "module", "collectgarbage", "getfenv", "setfenv", "newproxy", "_printregs" }) do
|
||||||
|
if _G[name] ~= nil then leaked[#leaked + 1] = name end
|
||||||
|
end
|
||||||
|
|
||||||
|
return { parse = function() return { available = #leaked == 0, title = table.concat(leaked, ",") } end }
|
||||||
Vendored
+7
@@ -0,0 +1,7 @@
|
|||||||
|
-- Grows a table until the memory watchdog stops it.
|
||||||
|
return { parse = function()
|
||||||
|
local t = {}
|
||||||
|
for i = 1, 1e8 do t[i] = "value " .. i end
|
||||||
|
|
||||||
|
return { available = true }
|
||||||
|
end }
|
||||||
Vendored
+6
@@ -0,0 +1,6 @@
|
|||||||
|
-- string.rep would allocate 10 GB at once, faster than the watchdog reacts.
|
||||||
|
return { parse = function()
|
||||||
|
local s = string.rep("x", 1e10)
|
||||||
|
|
||||||
|
return { available = true }
|
||||||
|
end }
|
||||||
Vendored
+8
@@ -0,0 +1,8 @@
|
|||||||
|
-- Loops forever on "loop" and "pcall"; pcall must not be able to swallow the
|
||||||
|
-- timeout. Any other URL returns normally.
|
||||||
|
return { parse = function(doc, url)
|
||||||
|
if url == "loop" then while true do end end
|
||||||
|
if url == "pcall" then while true do pcall(function() while true do end end) end end
|
||||||
|
|
||||||
|
return { available = true }
|
||||||
|
end }
|
||||||
Vendored
+43
@@ -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,
|
||||||
|
}
|
||||||
Reference in new issue
Block a user