Files
Media-download-telegram-bot/internal/app/money_test.go
T
MichilisandClaude Fable 5.2 51371da0e0 Phase 5: groups
Group wallets, group passes, spending rules and admin-only settings.

- Groups recorded from my_chat_member; admin rights verified with
  getChatMember and cached for five minutes
- Group context in entitlement resolution: group pass, group credits under
  the spending rule (anyone, admins only, capped per person per day) and
  the group's daily cap; refunds go back to the wallet that paid
- Group gate before any lookup: bot on or off, who may use it, allowed
  and blocked sites, plus the owner's maintenance mode
- /settings with inline toggles checked on every press, /grouplang,
  /autodetect, /allow, /block, /spending, /groupwallet, /grouppass,
  /groupstats
- Deep links with the target pre-selected: paying for a group happens in
  the private chat; a refused download in a group offers "Buy for me" and
  "Add group credits"
- Optional link detection, tidy mode, default quality and language per
  group; per-member usage
- /quality, /language, /app, /privacy, /terms, /support
- Remaining owner tools: /stats, /queue all, /user, /group, /ban, /unban,
  /grant (passes and gift codes), /credit, /refund, /blocklist,
  /broadcast with confirmation, /maint, /reload i18n

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 09:46:32 +00:00

1130 lines
39 KiB
Go

package app_test
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
"testing"
"time"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/billing/lnbitstest"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/service"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
"github.com/noderunners/dlbot/internal/ytdlp"
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
)
const (
bigLink = "https://example.com/big"
bigLink2 = "https://example.com/big2"
)
// bigInfo is an 80 MB, one minute video: over the free size cap, well
// inside the paid one.
func bigInfo() *ytdlp.Info {
return &ytdlp.Info{
Type: "video", ID: "big1", Title: "Big Video", Extractor: "fake", Duration: 60,
Formats: []ytdlp.Format{{Ext: "mp4", VCodec: "avc1", ACodec: "mp4a", Height: 1080, Filesize: 80 << 20}},
}
}
// moneyHarness adds a fake LNbits to the harness.
type moneyHarness struct {
*harness
ln *lnbitstest.Server
}
func freePort(t *testing.T) string {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer l.Close()
return l.Addr().String()
}
func startMoney(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *moneyHarness {
t.Helper()
ln := lnbitstest.New()
t.Cleanup(ln.Close)
if fake == nil {
fake = &ytdlptest.Fake{}
}
if fake.Infos == nil {
fake.Infos = map[string]*ytdlp.Info{}
}
fake.Infos[bigLink] = bigInfo()
second := bigInfo()
second.ID = "big2"
fake.Infos[bigLink2] = second
addr := freePort(t)
h := start(t, fake, func(c *config.Config) {
c.HTTP.Listen = addr
c.PublicURL = "http://" + addr
c.LNbits.URL = ln.URL()
c.LNbits.InvoiceKey = lnbitstest.Key
c.LNbits.WebhookSecret = "test-hook-secret"
// Polling is slow on purpose: tests that pass quickly prove the
// webhook path. Tests of the polling path shorten it.
c.LNbits.PollInterval = config.Duration(time.Hour)
c.Telegram.MaxUploadMB = 2000
if mut != nil {
mut(c)
}
})
return &moneyHarness{harness: h, ln: ln}
}
func (h *moneyHarness) wallet(user int64) *db.Wallet {
h.t.Helper()
w, err := h.app.Billing.Wallet(context.Background(), db.OwnerUser, user)
if err != nil {
h.t.Fatal(err)
}
return w
}
func (h *moneyHarness) balance(user int64) int64 { return h.wallet(user).Balance }
func (h *moneyHarness) grant(user, sats int64) {
h.t.Helper()
if _, err := h.app.Billing.Credit(context.Background(), h.wallet(user).ID, sats, "test", "", fmt.Sprintf("test:%d:%d", user, time.Now().UnixNano()), 0); err != nil {
h.t.Fatal(err)
}
}
// invoice waits for the n-th invoice at LNbits and for the bot message
// that shows it.
func (h *moneyHarness) invoice(after, n int) (lnbitstest.Invoice, fakeserver.Call) {
h.t.Helper()
inv, ok := h.ln.WaitInvoice(n, 10*time.Second)
if !ok {
h.t.Fatalf("invoice %d was not created", n)
}
msg := h.wait(after, "sendPhoto|sendMessage", func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), inv.Bolt11)
})
return inv, msg
}
func (h *moneyHarness) pay(inv lnbitstest.Invoice) {
h.t.Helper()
if err := h.ln.Pay(inv.PaymentHash); err != nil {
h.t.Fatalf("pay: %v", err)
}
}
func (h *moneyHarness) booksBalance() {
h.t.Helper()
bad, err := h.app.Store.VerifyWallets(context.Background())
if err != nil || len(bad) > 0 {
h.t.Fatalf("wallet balances disagree with the ledger: %+v, %v", bad, err)
}
}
func (h *moneyHarness) deliveriesOf(user int64, status string) []*db.Delivery {
h.t.Helper()
rows, err := h.app.DB.SQL.Query(h.app.DB.Rebind(`SELECT id FROM deliveries WHERE user_id = ? AND status = ? ORDER BY id`), user, status)
if err != nil {
h.t.Fatal(err)
}
var idList []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
h.t.Fatal(err)
}
idList = append(idList, id)
}
rows.Close()
var out []*db.Delivery
for _, id := range idList {
d, err := h.app.Store.GetDelivery(context.Background(), id)
if err != nil {
h.t.Fatal(err)
}
out = append(out, d)
}
return out
}
// waitInvoiceSaved waits until the bot recorded which message shows the
// invoice, which happens just after Telegram accepted that message.
func (h *moneyHarness) waitInvoiceSaved(inv lnbitstest.Invoice) *db.Purchase {
h.t.Helper()
deadline := time.Now().Add(5 * time.Second)
for {
p, err := h.app.Store.GetPurchaseByHash(context.Background(), inv.PaymentHash)
if err == nil && p.MessageID != 0 {
return p
}
if time.Now().After(deadline) {
h.t.Fatalf("the invoice message was never recorded: %+v, %v", p, err)
}
time.Sleep(5 * time.Millisecond)
}
}
// waitSent waits until the user has n delivered files and returns them.
func (h *moneyHarness) waitSent(user int64, n int) []*db.Delivery {
h.t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
d := h.deliveriesOf(user, db.DeliverySent)
if len(d) == n {
return d
}
if time.Now().After(deadline) {
h.t.Fatalf("%d sent deliveries for user %d, want %d", len(d), user, n)
}
time.Sleep(20 * time.Millisecond)
}
}
func labels(c fakeserver.Call) string {
var out []string
for _, b := range c.Buttons() {
out = append(out, b.Text)
}
return strings.Join(out, " | ")
}
// --- buying ----------------------------------------------------------------
func TestBuyDayPassSettledByWebhook(t *testing.T) {
h := startMoney(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/buy")
menu := h.wait(seq, "sendMessage", textHas("Passes and credits"))
want := "Day pass · 700 sats | Week pass · 3,000 sats | Month pass · 9,000 sats | 1,000 sats | 5,000 sats | 20,000 sats"
if labels(menu) != want {
t.Fatalf("buy buttons = %q\nwant %q", labels(menu), want)
}
if !strings.Contains(menu.Text(), "50 sats each") || !strings.Contains(menu.Text(), "1.95 GB") {
t.Fatalf("buy text = %q", menu.Text())
}
seq = h.press(alice, alice, menu, "by:pass_day")
inv, msg := h.invoice(seq, 1)
if inv.AmountSats != 700 || inv.Expiry != 600 || inv.Memo != "The Noderunners Download Bot: Day pass" ||
!strings.HasSuffix(inv.Webhook, "/lnbits/webhook/test-hook-secret") {
t.Fatalf("invoice at LNbits = %+v", inv)
}
if msg.Method != "sendPhoto" || msg.Files["photo"].Name != "invoice.png" || msg.Files["photo"].Size < 500 {
t.Fatalf("the invoice must be a QR photo: %s %+v", msg.Method, msg.Files)
}
if !strings.Contains(msg.Text(), "<code>"+inv.Bolt11+"</code>") || !strings.Contains(msg.Text(), "Day pass") ||
!strings.Contains(msg.Text(), "700 sats") || !strings.Contains(msg.Text(), "10 minutes") {
t.Fatalf("invoice caption = %q", msg.Text())
}
btns := msg.Buttons()
if len(btns) != 3 || btns[0].Text != "Open in wallet" || !strings.Contains(btns[0].URL, "/pay/") ||
!strings.HasPrefix(btns[1].Data, "pc:") || !strings.HasPrefix(btns[2].Data, "px:") {
t.Fatalf("invoice buttons = %+v", btns)
}
// Telegram rejects lightning: links in buttons, so it must be http(s).
if !strings.HasPrefix(btns[0].URL, "http") {
t.Fatalf("open-in-wallet URL = %q", btns[0].URL)
}
h.pay(inv) // LNbits calls the webhook
paid := h.wait(seq, "editMessageCaption", textHas("Paid."))
if paid.MessageID != msg.MessageID || len(paid.Buttons()) != 0 ||
!strings.Contains(paid.Text(), "Your pass is active until") {
t.Fatalf("paid message = %q buttons=%v", paid.Text(), paid.Buttons())
}
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/account")
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), "Pass: active until") && strings.Contains(c.Text(), "Downloads: 0 of 100")
})
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/limits")
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), "(Your pass)") && strings.Contains(c.Text(), "Length per download: 3 hours")
})
// With the pass the 80 MB file goes through, in the paid lane.
card := h.card(alice, alice, bigLink)
seq = h.press(alice, alice, card, "dl:")
h.wait(seq, "sendVideo", nil)
sent := h.waitSent(alice, 1)
if sent[0].Source != "own_pass" || sent[0].ChargeSats != 0 {
t.Fatalf("delivery = %+v", sent)
}
job, _ := h.app.Store.GetJob(context.Background(), sent[0].JobID)
if job.Lane != db.LanePaid || job.MaxSize != 2000<<20 {
t.Fatalf("job lane=%s max_size=%d", job.Lane, job.MaxSize)
}
h.booksBalance()
}
func TestCreditsTopUpAndPayPerDownload(t *testing.T) {
h := startMoney(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/credits")
menu := h.wait(seq, "sendMessage", textHas("Your balance: 0 sats"))
seq = h.press(alice, alice, menu, "by:credits:1000")
inv, _ := h.invoice(seq, 1)
h.pay(inv)
h.wait(seq, "editMessageCaption", textHas("Your balance is now 1,000 sats."))
card := h.card(alice, alice, bigLink)
seq = h.press(alice, alice, card, "dl:")
h.wait(seq, "sendVideo", nil)
h.wait(seq, edits, textHas("Done"))
if got := h.balance(alice); got != 950 {
t.Fatalf("balance = %d, want 950 after one 50 sat download", got)
}
sent := h.waitSent(alice, 1)
if sent[0].Source != "own_credits" || sent[0].ChargeSats != 50 || sent[0].Released {
t.Fatalf("delivery = %+v", sent[0])
}
usage, _ := h.app.Service.Usage(context.Background(), alice)
if usage.Downloads != 1 || usage.Bytes != 1024 {
t.Fatalf("usage = %+v", usage)
}
h.booksBalance()
}
// --- acceptance: refunds ---------------------------------------------------
func TestFailedDownloadIsRefunded(t *testing.T) {
netErr := &ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "reset"}
h := startMoney(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{link: {netErr, netErr}}}, nil)
h.grant(alice, 200)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
failed := h.wait(seq, edits, textHas("That did not work"))
if !strings.Contains(failed.Text(), "50 sats went back to your balance.") {
t.Fatalf("failure text = %q", failed.Text())
}
// It was retried once before the refund.
if n := len(h.fake.Downloads()); n != 2 {
t.Fatalf("downloads = %d, want 2", n)
}
if got := h.balance(alice); got != 200 {
t.Fatalf("balance = %d, want the full 200 back", got)
}
es, _ := h.app.Store.ListLedger(context.Background(), h.wallet(alice).ID, 10)
if len(es) != 3 || es[0].Kind != db.LedgerRefund || es[0].Amount != 50 || es[1].Kind != db.LedgerDebit || es[1].Amount != 50 {
t.Fatalf("ledger = %+v", es)
}
// The failed attempt does not use up the daily quota either.
if usage, _ := h.app.Service.Usage(context.Background(), alice); usage.Downloads != 0 {
t.Fatalf("usage after refund = %+v", usage)
}
d := h.deliveriesOf(alice, db.DeliveryFailed)
if len(d) != 1 || !d[0].Released {
t.Fatalf("delivery = %+v", d)
}
// Refunding again changes nothing.
for i := 0; i < 3; i++ {
if n, err := h.app.Service.Release(context.Background(), d[0].ID); err != nil || n != 0 {
t.Fatalf("second release = %d, %v", n, err)
}
}
if got := h.balance(alice); got != 200 {
t.Fatalf("balance after repeated release = %d", got)
}
h.booksBalance()
}
func TestCancelledDownloadIsRefunded(t *testing.T) {
block := make(chan struct{})
defer close(block)
h := startMoney(t, &ytdlptest.Fake{Block: block}, nil)
h.grant(alice, 100)
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
status := h.wait(seq, edits, textHas("Downloading"))
if got := h.balance(alice); got != 50 {
t.Fatalf("balance while running = %d, want 50", got)
}
seq = h.press(alice, alice, status, "jc:")
h.wait(seq, edits, func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), "Cancelled") && strings.Contains(c.Text(), "50 sats went back")
})
if got := h.balance(alice); got != 100 {
t.Fatalf("balance after cancel = %d", got)
}
}
func TestSendFailureIsRefunded(t *testing.T) {
h := startMoney(t, nil, nil)
h.grant(alice, 100)
card := h.card(alice, alice, link)
for i := 0; i < 3; i++ {
h.srv.FailNext("sendVideo", 500, "Internal Server Error")
}
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), "could not send the file") && strings.Contains(c.Text(), "50 sats went back")
})
if got := h.balance(alice); got != 100 {
t.Fatalf("balance = %d", got)
}
}
// --- over-limit flow -------------------------------------------------------
func TestOverLimitPayForThisFileOnly(t *testing.T) {
h := startMoney(t, &ytdlptest.Fake{FileSize: 4096}, nil)
card := h.card(alice, alice, bigLink)
seq := h.press(alice, alice, card, "dl:")
offer := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
if !strings.Contains(offer.Text(), "larger than your limit of 50.0 MB") {
t.Fatalf("offer text = %q", offer.Text())
}
// 80 MB is one started 100 MB step: 100 base + 50.
want := "Day pass · 700 sats | Week pass · 3,000 sats | Month pass · 9,000 sats | This file only · 150 sats"
if labels(offer) != want {
t.Fatalf("offer buttons = %q", labels(offer))
}
for _, b := range offer.Buttons() {
if b.URL != "" {
t.Fatalf("a private offer must not use URL buttons: %+v", b)
}
}
if n := len(h.fake.Downloads()); n != 0 {
t.Fatalf("an over-limit file was downloaded %d times before payment", n)
}
seq = h.press(alice, alice, offer, "ob:one_off")
inv, _ := h.invoice(seq, 1)
if inv.AmountSats != 150 {
t.Fatalf("one-off price = %d", inv.AmountSats)
}
h.pay(inv)
video := h.wait(seq, "sendVideo", nil)
if video.Files["video"].Size != 4096 {
t.Fatalf("video = %+v", video.Files)
}
// The original card became the status message.
done := h.wait(seq, edits, textHas("Done"))
if done.MessageID != card.MessageID {
t.Fatalf("status went to message %d, want the card %d", done.MessageID, card.MessageID)
}
sent := h.waitSent(alice, 1)
if sent[0].Source != "one_off" || sent[0].ChargeSats != 150 {
t.Fatalf("delivery = %+v", sent)
}
job, _ := h.app.Store.GetJob(context.Background(), sent[0].JobID)
if job.Lane != db.LanePaid {
t.Fatalf("a one-off job must be in the paid lane, got %s", job.Lane)
}
if h.balance(alice) != 0 {
t.Fatal("a delivered one-off must not leave credits behind")
}
// It was for one file. The next big file is refused again.
card = h.card(alice, alice, bigLink2)
seq = h.press(alice, alice, card, "dl:")
h.wait(seq, "sendMessage", textHas("You can lift the limit"))
}
func TestOneOffIsRefundedAsCreditsWhenTheDownloadFails(t *testing.T) {
h := startMoney(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{
bigLink: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "private"}},
}}, nil)
card := h.card(alice, alice, bigLink)
seq := h.press(alice, alice, card, "dl:")
offer := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
seq = h.press(alice, alice, offer, "ob:one_off")
inv, _ := h.invoice(seq, 1)
h.pay(inv)
h.wait(seq, edits, func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), "That did not work") && strings.Contains(c.Text(), "150 sats went back to your balance")
})
// A Lightning payment cannot be sent back, so it becomes credits.
if got := h.balance(alice); got != 150 {
t.Fatalf("balance = %d, want 150", got)
}
h.booksBalance()
}
func TestOverLimitBuyPassStartsTheDownload(t *testing.T) {
h := startMoney(t, nil, nil)
card := h.card(alice, alice, bigLink)
seq := h.press(alice, alice, card, "dl:")
offer := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
seq = h.press(alice, alice, offer, "ob:pass_week")
inv, _ := h.invoice(seq, 1)
if inv.AmountSats != 3000 {
t.Fatalf("week pass price = %d", inv.AmountSats)
}
h.pay(inv)
h.wait(seq, "editMessageCaption", textHas("Your pass is active until"))
h.wait(seq, "sendVideo", nil)
if sent := h.waitSent(alice, 1); sent[0].Source != "own_pass" {
t.Fatalf("delivery = %+v", sent)
}
}
func TestGroupOverLimitUsesDeepLinks(t *testing.T) {
h := startMoney(t, nil, nil)
card := h.card(group, alice, "/dl "+bigLink)
seq := h.press(group, alice, card, "dl:")
offer := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
if offer.ChatID() != group {
t.Fatalf("the offer must answer in the group")
}
// Both targets are offered, and both are plain links: web app buttons
// and invoices do not belong in a group.
btns := offer.Buttons()
if len(btns) != 2 || btns[0].Text != "Buy for me" || btns[1].Text != "Add group credits" {
t.Fatalf("group offer buttons = %+v", btns)
}
for _, b := range btns {
if b.Data != "" || !strings.HasPrefix(b.URL, "https://t.me/"+fakeserver.BotUsername+"?start=") {
t.Fatalf("group offer button is not a deep link: %+v", b)
}
}
if !strings.HasSuffix(btns[1].URL, fmt.Sprintf("?start=gw_%d", group)) {
t.Fatalf("group credits link = %q", btns[1].URL)
}
prefix := "https://t.me/" + fakeserver.BotUsername + "?start=buy_"
if !strings.HasPrefix(btns[0].URL, prefix) {
t.Fatalf("deep link = %q", btns[0].URL)
}
payload := strings.TrimPrefix(btns[0].URL, "https://t.me/"+fakeserver.BotUsername+"?start=")
for _, r := range payload {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '-') {
t.Fatalf("start parameter %q has a character Telegram does not allow", payload)
}
}
// Somebody else opening the link gets nothing.
seq = h.srv.Seq()
h.srv.PushMessage(bob, bob, "/start "+payload)
h.wait(seq, "sendMessage", textHas("expired"))
// The requester lands in the private chat and gets the real offer.
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/start "+payload)
private := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
if private.ChatID() != alice {
t.Fatal("the private offer went to the wrong chat")
}
seq = h.press(alice, alice, private, "ob:one_off")
inv, msg := h.invoice(seq, 1)
if msg.ChatID() != alice {
t.Fatal("the invoice must go to the private chat, never to the group")
}
h.pay(inv)
// The file is delivered where it was asked for: in the group.
video := h.wait(seq, "sendVideo", nil)
if video.ChatID() != group {
t.Fatalf("the file went to %d, want the group", video.ChatID())
}
}
func TestPaymentsDisabledFallsBackToPlainRefusal(t *testing.T) {
h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{bigLink: bigInfo()}}, nil)
card := h.card(alice, alice, bigLink)
seq := h.press(alice, alice, card, "dl:")
alert := h.wait(seq, "answerCallbackQuery", nil)
if !strings.Contains(alert.Params["text"], "larger than your limit") || alert.Params["show_alert"] != "true" {
t.Fatalf("alert = %+v", alert.Params)
}
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/buy")
h.wait(seq, "sendMessage", textHas("Payments are not set up"))
}
// --- invoices: expiry, cancel, check, polling ------------------------------
func TestUnpaidInvoiceExpiresAndNothingStarts(t *testing.T) {
h := startMoney(t, nil, func(c *config.Config) {
c.LNbits.InvoiceExpiry = config.Duration(300 * time.Millisecond)
c.LNbits.PollInterval = config.Duration(50 * time.Millisecond)
})
card := h.card(alice, alice, bigLink)
seq := h.press(alice, alice, card, "dl:")
offer := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
seq = h.press(alice, alice, offer, "ob:one_off")
_, msg := h.invoice(seq, 1)
expired := h.wait(seq, "editMessageCaption", textHas("has expired"))
if expired.MessageID != msg.MessageID || len(expired.Buttons()) != 0 {
t.Fatalf("expired message = %+v", expired.Params)
}
h.never(seq, "sendVideo", nil)
if n := len(h.fake.Downloads()); n != 0 {
t.Fatalf("an unpaid download ran %d times", n)
}
if n := len(h.jobs(db.JobQueued)) + len(h.jobs(db.JobRunning)) + len(h.jobs(db.JobDone)); n != 0 {
t.Fatalf("%d jobs exist for an unpaid invoice", n)
}
}
func TestLostWebhookIsCaughtByPollingAndByTheCheckButton(t *testing.T) {
h := startMoney(t, nil, func(c *config.Config) { c.LNbits.PollInterval = config.Duration(80 * time.Millisecond) })
h.ln.DropWebhooks = true
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/credits")
menu := h.wait(seq, "sendMessage", textHas("Your balance"))
seq = h.press(alice, alice, menu, "by:credits:5000")
inv, msg := h.invoice(seq, 1)
// Pressing "Check payment" before paying says so and changes nothing.
seq = h.press(alice, alice, msg, "pc:")
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
return strings.Contains(c.Params["text"], "Not paid yet")
})
h.pay(inv) // no webhook is sent
h.wait(seq, "editMessageCaption", textHas("Your balance is now 5,000 sats."))
if h.balance(alice) != 5000 {
t.Fatalf("balance = %d", h.balance(alice))
}
// A late press finds it settled.
seq = h.press(alice, alice, msg, "pc:")
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
return strings.Contains(c.Params["text"], "Payment received")
})
if h.balance(alice) != 5000 {
t.Fatalf("balance after a second check = %d", h.balance(alice))
}
}
func TestCheckButtonSettlesWithoutWebhookOrPoll(t *testing.T) {
h := startMoney(t, nil, nil) // polling every hour
h.ln.DropWebhooks = true
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/credits")
menu := h.wait(seq, "sendMessage", textHas("Your balance"))
seq = h.press(alice, alice, menu, "by:credits:1000")
inv, msg := h.invoice(seq, 1)
h.pay(inv)
seq = h.press(alice, alice, msg, "pc:")
h.wait(seq, "editMessageCaption", textHas("Your balance is now 1,000 sats."))
}
func TestCancelInvoice(t *testing.T) {
h := startMoney(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/credits")
menu := h.wait(seq, "sendMessage", textHas("Your balance"))
seq = h.press(alice, alice, menu, "by:credits:1000")
inv, msg := h.invoice(seq, 1)
// Bob cannot cancel or check Alice's invoice.
seq2 := h.press(alice, bob, msg, "px:")
h.wait(seq2, "answerCallbackQuery", nil)
p, _ := h.app.Store.GetPurchaseByHash(context.Background(), inv.PaymentHash)
if p.Status != db.PurchasePending {
t.Fatalf("a stranger changed the purchase to %s", p.Status)
}
seq = h.press(alice, alice, msg, "px:")
h.wait(seq, "deleteMessage", func(c fakeserver.Call) bool {
return c.Params["message_id"] == fmt.Sprint(msg.MessageID)
})
p, _ = h.app.Store.GetPurchaseByHash(context.Background(), inv.PaymentHash)
if p.Status != db.PurchaseCancelled {
t.Fatalf("status = %s", p.Status)
}
}
// --- acceptance: reconciliation on startup, end to end ---------------------
func TestPaymentDuringDowntimeIsSettledAndFulfilledOnStartup(t *testing.T) {
h := startMoney(t, &ytdlptest.Fake{FileSize: 2048}, nil)
card := h.card(alice, alice, bigLink)
seq := h.press(alice, alice, card, "dl:")
offer := h.wait(seq, "sendMessage", textHas("You can lift the limit"))
seq = h.press(alice, alice, offer, "ob:one_off")
inv, _ := h.invoice(seq, 1)
h.waitInvoiceSaved(inv)
// The core goes down. The user pays while it is away, so the webhook
// has nowhere to go.
h.stop()
h.ln.DropWebhooks = true
h.pay(inv)
seq = h.srv.Seq()
h.boot()
h.wait(seq, "editMessageCaption", textHas("Paid."))
video := h.wait(seq, "sendVideo", nil)
if video.Files["video"].Size != 2048 {
t.Fatalf("video = %+v", video.Files)
}
p, _ := h.app.Store.GetPurchaseByHash(context.Background(), inv.PaymentHash)
if p.Status != db.PurchasePaid || !p.Fulfilled {
t.Fatalf("purchase = %+v", p)
}
h.waitSent(alice, 1)
time.Sleep(200 * time.Millisecond)
if n := len(h.fake.Downloads()); n != 1 {
t.Fatalf("the paid file was downloaded %d times, want once", n)
}
}
// --- daily quota -----------------------------------------------------------
func TestDailyQuota(t *testing.T) {
failing := "https://example.com/fails"
h := startMoney(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{
failing: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: "x"}},
}}, func(c *config.Config) { c.Limits.Free.DailyDownloads = 2 })
// A failed download does not count.
card := h.card(alice, alice, failing)
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, textHas("That did not work"))
for i := 0; i < 2; i++ {
card := h.card(alice, alice, fmt.Sprintf("https://example.com/ok%d", i))
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, textHas("Done"))
}
card = h.card(alice, alice, "https://example.com/third")
seq = h.press(alice, alice, card, "dl:")
offer := h.wait(seq, "sendMessage", textHas("You used your 2 downloads for today"))
// A pass lifts the quota; "this file only" would not, so it is absent.
if labels(offer) != "Day pass · 700 sats | Week pass · 3,000 sats | Month pass · 9,000 sats" {
t.Fatalf("quota offer buttons = %q", labels(offer))
}
if n := len(h.fake.Downloads()); n != 3 {
t.Fatalf("downloads = %d, want 3 (one failed, two fine)", n)
}
// Another user has their own quota.
card = h.card(bob, bob, "https://example.com/bob")
seq = h.press(bob, bob, card, "dl:")
h.wait(seq, edits, textHas("Done"))
}
func TestDailyVolumeCapAppliesToPaidUsers(t *testing.T) {
h := startMoney(t, &ytdlptest.Fake{FileSize: 3 << 20}, func(c *config.Config) { c.Limits.Paid.DailyMB = 2 })
if _, err := h.app.Billing.GrantPass(context.Background(), h.wallet(alice).ID, "day", "test"); err != nil {
t.Fatal(err)
}
card := h.card(alice, alice, link)
seq := h.press(alice, alice, card, "dl:")
h.wait(seq, edits, textHas("Done")) // 3 MB delivered, cap is 2 MB
card = h.card(alice, alice, "https://example.com/more")
seq = h.press(alice, alice, card, "dl:")
alert := h.wait(seq, "answerCallbackQuery", nil)
if !strings.Contains(alert.Params["text"], "daily volume of 2.0 MB") {
t.Fatalf("alert = %q", alert.Params["text"])
}
}
// --- skip the queue --------------------------------------------------------
// queued sets up a busy single worker with alice's job running and bob's
// job waiting, and returns bob's queued status message.
func (h *moneyHarness) queued() fakeserver.Call {
h.t.Helper()
first := h.card(alice, alice, "https://example.com/running")
h.press(alice, alice, first, "dl:")
h.waitJobs(db.JobRunning, 1)
second := h.card(bob, bob, "https://example.com/waiting")
seq := h.press(bob, bob, second, "dl:")
return h.wait(seq, edits, textHas("In the queue"))
}
func TestSkipTheQueueWithCredits(t *testing.T) {
block := make(chan struct{})
defer close(block)
h := startMoney(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 })
h.grant(bob, 40) // not enough for a paid download, so bob queues as free
status := h.queued()
if labels(status) != "Skip the queue · 50 sats | Cancel" {
t.Fatalf("queued buttons = %q", labels(status))
}
// Alice cannot skip bob's job.
seq := h.press(bob, alice, status, "sq:")
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
return strings.Contains(c.Params["text"], "belong to the person who asked")
})
h.grant(bob, 20) // now 60
seq = h.press(bob, bob, status, "sq:")
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
return strings.Contains(c.Params["text"], "moved to the front")
})
if got := h.balance(bob); got != 10 {
t.Fatalf("balance = %d, want 10", got)
}
q := h.jobs(db.JobQueued)
if len(q) != 1 || q[0].Lane != db.LanePaid {
t.Fatalf("queued job = %+v", q)
}
// The button is gone once the job is in the paid lane.
after := h.wait(seq, edits, func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), "In the queue") && labels(c) == "Cancel"
})
_ = after
// Pressing the stale button again costs nothing.
seq = h.press(bob, bob, status, "sq:")
h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool {
return strings.Contains(c.Params["text"], "not waiting in the queue anymore")
})
if got := h.balance(bob); got != 10 {
t.Fatalf("balance after a second press = %d", got)
}
h.booksBalance()
}
func TestSkipTheQueueWithInvoice(t *testing.T) {
block := make(chan struct{})
defer close(block)
h := startMoney(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 })
status := h.queued()
seq := h.press(bob, bob, status, "sq:")
inv, _ := h.invoice(seq, 1)
if inv.AmountSats != 50 {
t.Fatalf("skip price = %d", inv.AmountSats)
}
h.pay(inv)
h.wait(seq, "editMessageCaption", textHas("Paid."))
deadline := time.Now().Add(5 * time.Second)
for {
if q := h.jobs(db.JobQueued); len(q) == 1 && q[0].Lane == db.LanePaid {
break
}
if time.Now().After(deadline) {
t.Fatal("the job was not promoted after payment")
}
time.Sleep(20 * time.Millisecond)
}
if h.balance(bob) != 0 {
t.Fatal("a fulfilled skip must not leave credits")
}
}
func TestSkipPaymentThatArrivesTooLateBecomesCredits(t *testing.T) {
block := make(chan struct{})
h := startMoney(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 })
status := h.queued()
seq := h.press(bob, bob, status, "sq:")
inv, _ := h.invoice(seq, 1)
close(block) // both jobs finish before bob pays
h.waitJobs(db.JobDone, 2)
h.pay(inv)
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool {
return strings.Contains(c.Text(), "had already left the queue") && strings.Contains(c.Text(), "50 sats were added")
})
if got := h.balance(bob); got != 50 {
t.Fatalf("balance = %d, want the 50 sats as credits", got)
}
h.booksBalance()
}
// --- HTTP routes -----------------------------------------------------------
func TestWebhookEndpoint(t *testing.T) {
h := startMoney(t, nil, nil)
h.ln.DropWebhooks = true
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/credits")
menu := h.wait(seq, "sendMessage", textHas("Your balance"))
seq = h.press(alice, alice, menu, "by:credits:1000")
inv, _ := h.invoice(seq, 1)
base := "http://" + h.app.HTTP.Addr()
post := func(path, body string) int {
resp, err := http.Post(base+path, "application/json", bytes.NewBufferString(body))
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
return resp.StatusCode
}
body := fmt.Sprintf(`{"payment_hash": %q, "pending": false, "amount": 1000000}`, inv.PaymentHash)
if code := post("/lnbits/webhook/wrong-secret", body); code != http.StatusNotFound {
t.Fatalf("wrong secret answered %d, want 404", code)
}
if code := post("/lnbits/webhook/test-hook-secret", "not json"); code != http.StatusBadRequest {
t.Fatalf("bad body answered %d, want 400", code)
}
// A correct secret with an invoice that is not paid: accepted, ignored.
if code := post("/lnbits/webhook/test-hook-secret", body); code != http.StatusOK {
t.Fatalf("forged webhook answered %d", code)
}
if h.balance(alice) != 0 {
t.Fatal("a forged webhook credited the wallet")
}
// Once LNbits confirms, the very same request settles it, once.
if err := h.ln.Pay(inv.PaymentHash); err != nil {
t.Fatal(err)
}
for i := 0; i < 5; i++ {
if code := post("/lnbits/webhook/test-hook-secret", body); code != http.StatusOK {
t.Fatalf("webhook answered %d", code)
}
}
if got := h.balance(alice); got != 1000 {
t.Fatalf("balance = %d, want exactly 1000", got)
}
h.booksBalance()
}
func TestPayPage(t *testing.T) {
h := startMoney(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/credits")
menu := h.wait(seq, "sendMessage", textHas("Your balance"))
seq = h.press(alice, alice, menu, "by:credits:1000")
inv, msg := h.invoice(seq, 1)
url := msg.Buttons()[0].URL
get := func(u string) (int, string) {
resp, err := http.Get(u)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, string(b)
}
code, body := get(url)
if code != 200 || !strings.Contains(body, `href="lightning:`+inv.Bolt11+`"`) || !strings.Contains(body, "Open in wallet") {
t.Fatalf("pay page = %d %s", code, body)
}
if code, _ := get("http://" + h.app.HTTP.Addr() + "/pay/doesnotexist"); code != http.StatusGone {
t.Fatalf("unknown purchase answered %d, want 410", code)
}
h.pay(inv)
h.wait(seq, "editMessageCaption", textHas("Paid."))
if code, body := get(url); code != http.StatusGone || strings.Contains(body, inv.Bolt11) {
t.Fatalf("a paid invoice must not be offered again: %d", code)
}
}
// --- other money commands --------------------------------------------------
func TestRedeemGiftCode(t *testing.T) {
h := startMoney(t, nil, nil)
g, err := h.app.Billing.NewGiftCode(context.Background(), billing.GiftCredits, 300, 1, 0, 1)
if err != nil {
t.Fatal(err)
}
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/redeem")
h.wait(seq, "sendMessage", textHas("Send the code after the command"))
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/redeem "+strings.ToLower(g.Code))
h.wait(seq, "sendMessage", textHas("300 sats were added to your balance"))
if h.balance(alice) != 300 {
t.Fatalf("balance = %d", h.balance(alice))
}
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/redeem "+g.Code)
h.wait(seq, "sendMessage", textHas("already used"))
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/redeem NR-AAAA-BBBB-CCCC")
h.wait(seq, "sendMessage", textHas("not valid"))
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/redeem cashuAeyJ0b2tlbiI6W119")
h.wait(seq, "sendMessage", textHas("Cashu tokens are not accepted"))
}
func TestReferralRewardEndToEnd(t *testing.T) {
h := startMoney(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/referral")
ref := h.wait(seq, "sendMessage", textHas("Invite friends"))
link := fmt.Sprintf("https://t.me/%s?start=ref_%d", fakeserver.BotUsername, alice)
if !strings.Contains(ref.Text(), link) || !strings.Contains(ref.Text(), "you get 200 sats") ||
!strings.Contains(ref.Text(), "You invited 0 people") {
t.Fatalf("referral text = %q", ref.Text())
}
// Bob is new and arrives through the link.
seq = h.srv.Seq()
h.srv.PushMessage(bob, bob, fmt.Sprintf("/start ref_%d", alice))
h.wait(seq, "sendMessage", textHas("welcome"))
// Alice already knows the bot: a link to herself or from bob does nothing.
h.srv.PushMessage(alice, alice, fmt.Sprintf("/start ref_%d", bob))
seq = h.srv.Seq()
h.srv.PushMessage(bob, bob, "/credits")
menu := h.wait(seq, "sendMessage", textHas("Your balance"))
seq = h.press(bob, bob, menu, "by:credits:1000")
inv, _ := h.invoice(seq, 1)
h.pay(inv)
h.wait(seq, "editMessageCaption", textHas("Paid."))
if got := h.balance(alice); got != 200 {
t.Fatalf("inviter balance = %d, want 200", got)
}
if got := h.balance(bob); got != 1000 {
t.Fatalf("invited balance = %d", got)
}
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/referral")
h.wait(seq, "sendMessage", textHas("You invited 1 person so far"))
u, _ := h.app.Store.GetUser(context.Background(), alice)
if u.ReferredBy != 0 {
t.Fatalf("an existing user was referred: %+v", u)
}
h.booksBalance()
}
func TestDonate(t *testing.T) {
h := startMoney(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/donate")
menu := h.wait(seq, "sendMessage", textHas("Thank you for supporting"))
if labels(menu) != "500 sats | 2,100 sats | 10,000 sats" {
t.Fatalf("donation buttons = %q", labels(menu))
}
seq = h.press(alice, alice, menu, "by:donation:2100")
inv, _ := h.invoice(seq, 1)
h.pay(inv)
h.wait(seq, "editMessageCaption", textHas("Thank you for the support."))
if h.balance(alice) != 0 {
t.Fatal("a donation must not become credits")
}
}
func TestBuyerCannotChooseThePriceOfAPass(t *testing.T) {
h := startMoney(t, nil, nil)
seq := h.srv.Seq()
// A crafted callback asks for a day pass for 1 sat.
h.srv.PushCallback(alice, alice, 1, "by:pass_day:1")
inv, _ := h.invoice(seq, 1)
if inv.AmountSats != 700 {
t.Fatalf("a crafted callback got a pass for %d sats", inv.AmountSats)
}
seq = h.srv.Seq()
h.srv.PushCallback(alice, alice, 1, "by:credits:-5")
h.wait(seq, "sendMessage", textHas("amount is not possible"))
seq = h.srv.Seq()
h.srv.PushCallback(alice, alice, 1, "by:yacht")
h.wait(seq, "sendMessage", textHas("amount is not possible"))
}
func TestMoneyCommandsInGroupsPointToPrivateChat(t *testing.T) {
h := startMoney(t, nil, nil)
for _, cmd := range []string{"/buy", "/account", "/credits", "/redeem X", "/referral", "/donate"} {
seq := h.srv.Seq()
h.srv.PushMessage(group, alice, cmd)
c := h.wait(seq, "sendMessage", textHas("private chat"))
if b := c.Buttons(); len(b) != 1 || b[0].URL != "https://t.me/"+fakeserver.BotUsername {
t.Fatalf("%s: buttons = %+v", cmd, b)
}
}
if n, _ := h.ln.Calls(); n != 0 {
t.Fatalf("%d invoices were created from a group", n)
}
}
func TestLightningDownIsExplained(t *testing.T) {
h := startMoney(t, nil, nil)
h.ln.SetDown(true)
seq := h.srv.Seq()
h.srv.PushCallback(alice, alice, 1, "by:pass_day")
h.wait(seq, "sendMessage", textHas("cannot reach the payment service"))
}
func TestRateLimit(t *testing.T) {
h := startMoney(t, nil, func(c *config.Config) { c.Rate.UserPerMinute = 3 })
seq := h.srv.Seq()
for i := 0; i < 6; i++ {
h.srv.PushMessage(alice, alice, fmt.Sprintf("https://example.com/r%d", i))
}
h.wait(seq, "sendMessage", textHas("That is a lot of links"))
time.Sleep(300 * time.Millisecond)
if n := len(h.fake.Probes()); n != 3 {
t.Fatalf("probes = %d, want 3", n)
}
notices := 0
for _, c := range h.srv.Calls("sendMessage") {
if strings.Contains(c.Text(), "That is a lot of links") {
notices++
}
}
if notices != 1 {
t.Fatalf("rate limit notices = %d, want 1", notices)
}
// Other users are not affected.
h.card(bob, bob, "https://example.com/bob")
}
func TestEntitlementSurvivesInService(t *testing.T) {
// The decision the service makes must follow the resolver's order with
// real wallets behind it.
h := startMoney(t, nil, nil)
ctx := context.Background()
who := service.Who{UserID: alice, ChatID: alice, ChatType: "private"}
source := func() string {
d, err := h.app.Service.Entitlement(ctx, who, false)
if err != nil {
t.Fatal(err)
}
return string(d.Source)
}
if got := source(); got != "free" {
t.Fatalf("no wallet: %s", got)
}
h.grant(alice, 49)
if got := source(); got != "free" {
t.Fatalf("49 sats: %s", got)
}
h.grant(alice, 1)
if got := source(); got != "own_credits" {
t.Fatalf("50 sats: %s", got)
}
if _, err := h.app.Billing.GrantPass(ctx, h.wallet(alice).ID, "day", "test"); err != nil {
t.Fatal(err)
}
if got := source(); got != "own_pass" {
t.Fatalf("with a pass: %s", got)
}
if d, _ := h.app.Service.Entitlement(ctx, who, true); d.Source != "one_off" {
t.Fatalf("one-off: %s", d.Source)
}
}
func TestPaymentIsConfirmedEvenWhenTheInvoiceMessageIsUnknown(t *testing.T) {
// The core can stop in the instant between Telegram accepting the
// invoice message and the bot saving its ID. The payer must still hear
// that the payment arrived.
h := startMoney(t, nil, nil)
ctx := context.Background()
p, err := h.app.Billing.CreatePurchase(ctx, billing.NewPurchase{
UserID: alice, WalletID: h.wallet(alice).ID, Product: billing.ProductCredits, Amount: 1000, Lang: "en",
})
if err != nil {
t.Fatal(err)
}
seq := h.srv.Seq()
if err := h.ln.Pay(p.PaymentHash); err != nil { // no invoice message was ever recorded
t.Fatal(err)
}
confirm := h.wait(seq, "sendMessage", textHas("Paid."))
if confirm.ChatID() != alice || !strings.Contains(confirm.Text(), "Your balance is now 1,000 sats.") {
t.Fatalf("confirmation = %q to %d", confirm.Text(), confirm.ChatID())
}
time.Sleep(400 * time.Millisecond)
n := 0
for _, c := range h.srv.Calls("sendMessage") {
if strings.Contains(c.Text(), "Paid.") {
n++
}
}
if n != 1 {
t.Fatalf("%d confirmations were sent, want 1", n)
}
}