package api import ( "crypto/subtle" "html" "net/http" "github.com/noderunners/dlbot/internal/billing" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/i18n" ) // Payments serves the two payment routes of the core: // // POST /lnbits/webhook/{secret} payment notifications from LNbits // GET /pay/{purchase} "open in wallet" page for an invoice type Payments struct { Billing *billing.Billing Store *db.Store I18n *i18n.Bundle // Secret is the random path segment that LNbits was given. An empty // secret disables the webhook route. Secret string } // Register adds the routes to the server. func (s *Server) RegisterPayments(p Payments) { if p.Secret != "" { s.mux.HandleFunc("POST /lnbits/webhook/{secret}", p.webhook) } s.mux.HandleFunc("GET /pay/{purchase}", p.payPage) } // webhook accepts a notification. LNbits does not sign its webhooks, so // the secret in the path only keeps strangers out; the payment itself is // confirmed with LNbits by the billing service before anything is // credited. The answer is always 200 for a well-formed request: LNbits // does not retry, and polling covers anything that fails here. func (p Payments) webhook(w http.ResponseWriter, r *http.Request) { if subtle.ConstantTimeCompare([]byte(r.PathValue("secret")), []byte(p.Secret)) != 1 { http.NotFound(w, r) return } hash, ok := billing.ParseWebhook(r.Body) if !ok { http.Error(w, "bad request", http.StatusBadRequest) return } // Errors are logged by the billing service and retried by its poller. _ = p.Billing.HandleWebhook(r.Context(), hash) w.WriteHeader(http.StatusOK) } // payPage forwards a browser to the lightning: link of an invoice. // Telegram URL buttons only accept http and https, which is why this small // hop exists. The purchase ID in the path is unguessable, and the page // shows nothing but the invoice, which is meant to be shared with a wallet. func (p Payments) payPage(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-store") w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("X-Content-Type-Options", "nosniff") pur, err := p.Store.GetPurchase(r.Context(), r.PathValue("purchase")) lang := i18n.Default if err == nil { lang = pur.Lang } t := func(id string) string { return html.EscapeString(p.I18n.T(lang, id, nil)) } page := func(code int, body string) { w.WriteHeader(code) _, _ = w.Write([]byte(`` + `` + t("pay.title") + `` + body + ``)) } if err != nil || pur.Status != db.PurchasePending { page(http.StatusGone, `

`+t("pay.gone")+`

`) return } link := "lightning:" + pur.Bolt11 esc := html.EscapeString(link) page(http.StatusOK, `

`+t("pay.hint")+ `

`+t("pay.open")+``+html.EscapeString(pur.Bolt11)+`
`) }