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

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

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

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

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

450 lines
14 KiB
Lua

-- 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,
}