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:
co-authored by
Claude Fable 5.2
parent
3b361c17a1
commit
0d50f453a0
+147
-4
@@ -43,8 +43,16 @@ type Config struct {
|
||||
Worker Worker `toml:"worker"`
|
||||
Queue Queue `toml:"queue"`
|
||||
Limits Limits `toml:"limits"`
|
||||
LNbits LNbits `toml:"lnbits"`
|
||||
Prices Prices `toml:"prices"`
|
||||
Rate Rate `toml:"rate"`
|
||||
Log Log `toml:"log"`
|
||||
|
||||
// PublicURL is the HTTPS base URL this server is reachable at from the
|
||||
// internet, without a trailing slash. It is used for payment webhooks,
|
||||
// "open in wallet" links and the Mini App.
|
||||
PublicURL string `toml:"public_url" env:"PUBLIC_URL"`
|
||||
|
||||
// Owners are the Telegram user IDs allowed to use owner commands.
|
||||
Owners []int64 `toml:"owners" env:"OWNER_IDS"`
|
||||
}
|
||||
@@ -113,16 +121,72 @@ type Queue struct {
|
||||
MaxAttempts int `toml:"max_attempts" env:"QUEUE_MAX_ATTEMPTS"`
|
||||
}
|
||||
|
||||
// Tier is one set of per-download limits.
|
||||
// Tier is one set of limits.
|
||||
type Tier struct {
|
||||
MaxSizeMB int64 `toml:"max_size_mb"`
|
||||
MaxDuration Duration `toml:"max_duration"`
|
||||
ActiveJobs int `toml:"active_jobs"`
|
||||
// DailyDownloads is the number of downloads per UTC day, 0 for no cap.
|
||||
DailyDownloads int `toml:"daily_downloads"`
|
||||
// DailyMB is the volume per UTC day in MB, 0 for no cap. It applies to
|
||||
// paid users too, as a guard against abuse.
|
||||
DailyMB int64 `toml:"daily_mb"`
|
||||
}
|
||||
|
||||
// Limits holds the per-tier limits.
|
||||
// Limits holds the per-tier limits. Free applies to everyone without a
|
||||
// paid entitlement. Paid applies to passes, credits and one-off payments.
|
||||
type Limits struct {
|
||||
Free Tier `toml:"free"`
|
||||
Paid Tier `toml:"paid"`
|
||||
}
|
||||
|
||||
// LNbits holds the Lightning payment backend settings. Payments are
|
||||
// enabled when both URL and InvoiceKey are set.
|
||||
type LNbits struct {
|
||||
URL string `toml:"url" env:"LNBITS_URL"`
|
||||
// InvoiceKey is the wallet's invoice (read) key. The admin key is never
|
||||
// needed and must not be given to the bot.
|
||||
InvoiceKey string `toml:"invoice_key" env:"LNBITS_INVOICE_KEY"`
|
||||
// WebhookSecret is a random string that becomes part of the webhook
|
||||
// path, so only LNbits knows where to post.
|
||||
WebhookSecret string `toml:"webhook_secret" env:"LNBITS_WEBHOOK_SECRET"`
|
||||
// PollInterval is how often unsettled invoices are checked as a
|
||||
// fallback for lost webhooks.
|
||||
PollInterval Duration `toml:"poll_interval" env:"LNBITS_POLL_INTERVAL"`
|
||||
// InvoiceExpiry is how long an invoice can be paid.
|
||||
InvoiceExpiry Duration `toml:"invoice_expiry" env:"INVOICE_EXPIRY"`
|
||||
}
|
||||
|
||||
// Enabled reports whether payments are configured.
|
||||
func (l LNbits) Enabled() bool { return l.URL != "" && l.InvoiceKey != "" }
|
||||
|
||||
// Prices holds every price in sats. Nothing is hardcoded elsewhere.
|
||||
type Prices struct {
|
||||
PassDay int64 `toml:"pass_day" env:"PRICE_PASS_DAY"`
|
||||
PassWeek int64 `toml:"pass_week" env:"PRICE_PASS_WEEK"`
|
||||
PassMonth int64 `toml:"pass_month" env:"PRICE_PASS_MONTH"`
|
||||
// CreditPerDownload is what one download costs when credits pay.
|
||||
CreditPerDownload int64 `toml:"credit_per_download" env:"PRICE_CREDIT_DOWNLOAD"`
|
||||
// OneOff is base plus a step per started 100 MB.
|
||||
OneOffBase int64 `toml:"one_off_base" env:"PRICE_ONE_OFF_BASE"`
|
||||
OneOffPer100MB int64 `toml:"one_off_per_100mb" env:"PRICE_ONE_OFF_PER_100MB"`
|
||||
// SkipQueue moves one waiting free job to the paid lane.
|
||||
SkipQueue int64 `toml:"skip_queue" env:"PRICE_SKIP_QUEUE"`
|
||||
// CreditPacks are the top-up amounts offered.
|
||||
CreditPacks []int64 `toml:"credit_packs" env:"CREDIT_PACKS"`
|
||||
// DonationAmounts are the tip amounts offered by /donate.
|
||||
DonationAmounts []int64 `toml:"donation_amounts" env:"DONATION_AMOUNTS"`
|
||||
// ReferralReward is credited to the inviter when an invited user makes
|
||||
// a first purchase. 0 turns the reward off.
|
||||
ReferralReward int64 `toml:"referral_reward" env:"REFERRAL_REWARD"`
|
||||
}
|
||||
|
||||
// Rate holds the request rate limits.
|
||||
type Rate struct {
|
||||
// UserPerMinute is how many links one user may send per minute.
|
||||
UserPerMinute int `toml:"user_per_minute" env:"RATE_USER_PER_MINUTE"`
|
||||
// GroupPerMinute is how many links one group may send per minute.
|
||||
GroupPerMinute int `toml:"group_per_minute" env:"RATE_GROUP_PER_MINUTE"`
|
||||
}
|
||||
|
||||
// Log holds logging settings.
|
||||
@@ -162,9 +226,26 @@ func Default() Config {
|
||||
MaxAttempts: 2,
|
||||
},
|
||||
Limits: Limits{
|
||||
Free: Tier{MaxSizeMB: 50, MaxDuration: Duration(10 * time.Minute), ActiveJobs: 1},
|
||||
Free: Tier{MaxSizeMB: 50, MaxDuration: Duration(10 * time.Minute), ActiveJobs: 1,
|
||||
DailyDownloads: 5, DailyMB: 250},
|
||||
Paid: Tier{MaxSizeMB: 2000, MaxDuration: Duration(3 * time.Hour), ActiveJobs: 3,
|
||||
DailyDownloads: 100, DailyMB: 20000},
|
||||
},
|
||||
Log: Log{Level: "info", Format: "json"},
|
||||
LNbits: LNbits{
|
||||
PollInterval: Duration(5 * time.Second),
|
||||
InvoiceExpiry: Duration(10 * time.Minute),
|
||||
},
|
||||
Prices: Prices{
|
||||
PassDay: 700, PassWeek: 3000, PassMonth: 9000,
|
||||
CreditPerDownload: 50,
|
||||
OneOffBase: 100, OneOffPer100MB: 50,
|
||||
SkipQueue: 50,
|
||||
CreditPacks: []int64{1000, 5000, 20000},
|
||||
DonationAmounts: []int64{500, 2100, 10000},
|
||||
ReferralReward: 200,
|
||||
},
|
||||
Rate: Rate{UserPerMinute: 10, GroupPerMinute: 30},
|
||||
Log: Log{Level: "info", Format: "json"},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,6 +280,11 @@ func Load(path string) (Config, error) {
|
||||
if err := applyTierEnv("FREE", &cfg.Limits.Free, os.LookupEnv); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if err := applyTierEnv("PAID", &cfg.Limits.Paid, os.LookupEnv); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/")
|
||||
cfg.LNbits.URL = strings.TrimRight(cfg.LNbits.URL, "/")
|
||||
return cfg, cfg.Validate()
|
||||
}
|
||||
|
||||
@@ -236,6 +322,25 @@ func (c Config) Validate() error {
|
||||
if c.Queue.Heartbeat.D() >= c.Queue.Lease.D() {
|
||||
errs = append(errs, "QUEUE_HEARTBEAT must be shorter than QUEUE_LEASE")
|
||||
}
|
||||
if (c.LNbits.URL == "") != (c.LNbits.InvoiceKey == "") {
|
||||
errs = append(errs, "LNBITS_URL and LNBITS_INVOICE_KEY must be set together")
|
||||
}
|
||||
if c.LNbits.Enabled() {
|
||||
if c.LNbits.InvoiceExpiry.D() < time.Minute {
|
||||
errs = append(errs, "INVOICE_EXPIRY must be at least 1m")
|
||||
}
|
||||
if c.LNbits.PollInterval.D() <= 0 {
|
||||
errs = append(errs, "LNBITS_POLL_INTERVAL must be positive")
|
||||
}
|
||||
for name, v := range map[string]int64{
|
||||
"PRICE_PASS_DAY": c.Prices.PassDay, "PRICE_PASS_WEEK": c.Prices.PassWeek,
|
||||
"PRICE_PASS_MONTH": c.Prices.PassMonth, "PRICE_CREDIT_DOWNLOAD": c.Prices.CreditPerDownload,
|
||||
} {
|
||||
if v <= 0 {
|
||||
errs = append(errs, name+" must be positive")
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
return errors.New("config: " + strings.Join(errs, "; "))
|
||||
}
|
||||
@@ -275,9 +380,47 @@ func applyTierEnv(prefix string, t *Tier, lookup func(string) (string, bool)) er
|
||||
}
|
||||
t.ActiveJobs = n
|
||||
}
|
||||
if v, ok := lookup(prefix + "_DAILY_DOWNLOADS"); ok && v != "" {
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("config: %s_DAILY_DOWNLOADS: %w", prefix, err)
|
||||
}
|
||||
t.DailyDownloads = n
|
||||
}
|
||||
if v, ok := lookup(prefix + "_DAILY_MB"); ok && v != "" {
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("config: %s_DAILY_MB: %w", prefix, err)
|
||||
}
|
||||
t.DailyMB = n
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PassPrice returns the price of a pass kind ("day", "week", "month").
|
||||
func (p Prices) PassPrice(kind string) int64 {
|
||||
switch kind {
|
||||
case "day":
|
||||
return p.PassDay
|
||||
case "week":
|
||||
return p.PassWeek
|
||||
case "month":
|
||||
return p.PassMonth
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// OneOffPrice returns the price of a single download of the given size.
|
||||
// An unknown size is priced as 200 MB.
|
||||
func (p Prices) OneOffPrice(sizeBytes int64) int64 {
|
||||
const step = 100 << 20
|
||||
if sizeBytes <= 0 {
|
||||
sizeBytes = 2 * step
|
||||
}
|
||||
steps := (sizeBytes + step - 1) / step
|
||||
return p.OneOffBase + steps*p.OneOffPer100MB
|
||||
}
|
||||
|
||||
var durationType = reflect.TypeOf(Duration(0))
|
||||
|
||||
// applyEnv walks the struct and overrides every field that has an env tag
|
||||
|
||||
Reference in New Issue
Block a user