Phase 2: money

Lightning payments through LNbits, wallets, passes, credits, the
entitlement resolver and priority lanes.

- internal/entitle: pure resolver (one-off, own pass, group pass, group
  credits, own credits, free) with a table-driven suite and an invariant
  check over every input combination
- internal/billing: wallets, append-only ledger with dedupe keys, stacking
  passes, purchases, gift codes, referral reward
- LNbits client verified against v0.12.12 and v1.7.1 source
- Settlement by one conditional UPDATE: idempotent under any mix of
  webhooks, polls and the check button. Webhooks are unsigned, so every
  payment is confirmed with LNbits before it is credited
- Polling fallback, reconciliation of all unsettled invoices at startup,
  late payments still honored, no expiry while LNbits is unreachable
- Charge, quota and job are written in one transaction; failed, cancelled
  and undeliverable downloads are refunded exactly once
- Paid lane first with one slot of the fleet reserved for free users
- Daily download quota and daily volume cap, per-user and per-group rate
  limits
- Bot: /buy /account /limits /credits /redeem /referral /donate, QR invoice
  message that flips to paid, over-limit offer (passes or this file only),
  deep links from groups, skip the queue
- Fake LNbits server for tests; end-to-end money flows including a payment
  made while the core was down

Cashu redemption is behind an interface and not implemented.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 08:09:35 +00:00
co-authored by Claude Fable 5.2
parent 3b361c17a1
commit 0d50f453a0
42 changed files with 7040 additions and 140 deletions
+20 -3
View File
@@ -14,6 +14,8 @@ import (
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/api"
"github.com/noderunners/dlbot/internal/billing"
"github.com/noderunners/dlbot/internal/billing/lnbits"
"github.com/noderunners/dlbot/internal/bot"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/db"
@@ -45,6 +47,7 @@ type App struct {
Store *db.Store
Storage storage.Storage
Sched *sched.Scheduler
Billing *billing.Billing
Service *service.Service
Bot *bot.Bot
HTTP *api.Server
@@ -105,7 +108,10 @@ func Redactor(secrets ...string) func(groups []string, a slog.Attr) slog.Attr {
// Secrets lists the configured values that must never appear in logs.
func Secrets(cfg config.Config) []string {
return []string{cfg.Telegram.Token, cfg.Telegram.WebhookSecret}
return []string{
cfg.Telegram.Token, cfg.Telegram.WebhookSecret,
cfg.LNbits.InvoiceKey, cfg.LNbits.WebhookSecret,
}
}
// New opens the database and storage and builds every component. Nothing
@@ -160,7 +166,12 @@ func New(ctx context.Context, opts Options) (*App, error) {
FreeMaxLen: cfg.Queue.FreeMaxLen,
MaxAttempts: cfg.Queue.MaxAttempts,
}, log)
a.Service = service.New(cfg, a.Store, a.Sched, a.runner, log)
var ln billing.Lightning
if cfg.LNbits.Enabled() {
ln = lnbits.New(cfg.LNbits.URL, cfg.LNbits.InvoiceKey)
}
a.Billing = billing.New(a.Store, ln, cfg, log)
a.Service = service.New(cfg, a.Store, a.Sched, a.Billing, a.runner, log)
if a.tgBot, err = tg.NewBot(cfg.Telegram.Token, cfg.Telegram.APIURL); err != nil {
return fail(fmt.Errorf("app: telegram client: %w", err))
@@ -171,6 +182,7 @@ func New(ctx context.Context, opts Options) (*App, error) {
Store: a.Store,
Sched: a.Sched,
Service: a.Service,
Billing: a.Billing,
Storage: a.Storage,
I18n: tr,
Log: log,
@@ -184,6 +196,9 @@ func New(ctx context.Context, opts Options) (*App, error) {
}
a.HTTP = api.New(cfg.HTTP.Listen, func(ctx context.Context) error { return a.DB.SQL.PingContext(ctx) }, log)
a.HTTP.RegisterPayments(api.Payments{
Billing: a.Billing, Store: a.Store, I18n: tr, Secret: cfg.LNbits.WebhookSecret,
})
if cfg.Worker.Embedded {
a.worker = worker.New(worker.Config{
@@ -220,7 +235,8 @@ func (a *App) Run(ctx context.Context) error {
close(a.ready)
a.log.Info("core started", "bot", a.Bot.Username(), "mode", a.cfg.Telegram.Mode,
"http", a.HTTP.Addr(), "db", a.cfg.Database.Driver, "storage", a.cfg.Storage.Backend,
"embedded_worker", a.cfg.Worker.Embedded)
"embedded_worker", a.cfg.Worker.Embedded, "payments", a.Billing.Enabled(),
"payment_webhook", a.Billing.WebhookURL() != "")
var wg sync.WaitGroup
run := func(fn func()) {
@@ -240,6 +256,7 @@ func (a *App) Run(ctx context.Context) error {
}
})
run(func() { a.Sched.Run(ctx) })
run(func() { a.Billing.Run(ctx) })
if a.worker != nil {
run(func() { a.worker.Run(ctx) })
}
+37 -2
View File
@@ -81,9 +81,15 @@ func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config)
func (h *harness) boot() {
h.t.Helper()
ctx, cancel := context.WithCancel(context.Background())
// DLBOT_TEST_LOG=1 prints the core's log, which helps with a failing test.
var logOut io.Writer = io.Discard
if os.Getenv("DLBOT_TEST_LOG") != "" {
logOut = os.Stderr
}
base := slog.NewTextHandler(logOut, &slog.HandlerOptions{Level: slog.LevelDebug})
a, err := app.New(ctx, app.Options{
Config: h.cfg,
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
Log: slog.New(&guardHandler{Handler: base, t: h.t}),
Runner: h.runner,
Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) },
})
@@ -102,6 +108,35 @@ func (h *harness) boot() {
}
}
// guardHandler fails the test when the core logs something that is always
// a bug: a message ID that is missing from the catalog, or a panic.
type guardHandler struct {
slog.Handler
t *testing.T
}
func (g *guardHandler) Handle(ctx context.Context, r slog.Record) error {
if strings.HasPrefix(r.Message, "i18n: missing message") || r.Message == "panic recovered" {
var sb strings.Builder
r.Attrs(func(a slog.Attr) bool {
if a.Key != "stack" {
fmt.Fprintf(&sb, " %s=%v", a.Key, a.Value)
}
return true
})
g.t.Errorf("core logged a bug: %s%s", r.Message, sb.String())
}
return g.Handler.Handle(ctx, r)
}
func (g *guardHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &guardHandler{Handler: g.Handler.WithAttrs(attrs), t: g.t}
}
func (g *guardHandler) WithGroup(name string) slog.Handler {
return &guardHandler{Handler: g.Handler.WithGroup(name), t: g.t}
}
func (h *harness) stop() {
if h.cancel == nil {
return
@@ -739,7 +774,7 @@ func TestCommandMenuIsRegistered(t *testing.T) {
if err := json.Unmarshal([]byte(calls[0].Params["commands"]), &cmds); err != nil {
t.Fatal(err)
}
if len(cmds) != 7 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" {
if len(cmds) != 9 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" {
t.Fatalf("commands = %+v", cmds)
}
for _, c := range cmds {
File diff suppressed because it is too large Load Diff