main.go raw
1 package main
2
3 import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "fmt"
9 "log"
10 "net"
11 "net/http"
12 "net/url"
13 "os"
14 "os/signal"
15 "path/filepath"
16 "strconv"
17 "strings"
18 "sync"
19 "syscall"
20 "time"
21
22 "github.com/nbd-wtf/go-nostr"
23 "github.com/nbd-wtf/go-nostr/nip04"
24 )
25
26 type Config struct {
27 ServicePubkey string
28 ClientSecret string
29 ClientPubkey string
30 Relays []string
31 Username string
32 Domain string
33 // CommentAllowed advertises LUD-12 support. The callback does not forward a
34 // comment to the wallet yet, so this defaults to 0 (advertise nothing) to
35 // avoid clients sending a comment that would be silently dropped.
36 CommentAllowed int
37 // AllowedHosts are the hosts this server will serve. The request Host header
38 // selects which of them to advertise; anything else is refused.
39 AllowedHosts []string
40 }
41
42 type LnurlResponse struct {
43 Callback string `json:"callback"`
44 MaxSendable uint64 `json:"maxSendable"`
45 MinSendable uint64 `json:"minSendable"`
46 Metadata string `json:"metadata"`
47 CommentAllowed int `json:"commentAllowed"`
48 Tag string `json:"tag"`
49
50 // NIP-57. Advertised only when zap support is active; a client treats the
51 // absence of allowsNostr as "this address cannot be zapped".
52 AllowsNostr *bool `json:"allowsNostr,omitempty"`
53 NostrPubkey string `json:"nostrPubkey,omitempty"`
54 }
55
56 const (
57 // Advertised LUD-06 sendable range, in millisatoshis.
58 minSendableMsat = 1000
59 maxSendableMsat = 100000000
60 )
61
62 // LnurlCallbackResponse mirrors the LUD-06 payRequest callback response.
63 // successAction is omitempty on purpose: LUD-09 specifies that WHEN PRESENT it
64 // must be an object with a "tag". Serializing it as JSON null is not valid and
65 // strict clients (e.g. lnbits/lnurl, pydantic with extra="forbid") reject the
66 // whole callback response with a validation/encoding error.
67 type LnurlCallbackResponse struct {
68 Pr string `json:"pr"`
69 SuccessAction interface{} `json:"successAction,omitempty"`
70 Disposable *bool `json:"disposable"`
71 Routes []interface{} `json:"routes"`
72 }
73
74 // LnurlErrorResponse is the LUD-06 error envelope. LNURL is JSON end to end, so
75 // failures must still be JSON: a plain-text body makes clients report a JSON
76 // parse / "encoding" error instead of the real reason.
77 type LnurlErrorResponse struct {
78 Status string `json:"status"`
79 Reason string `json:"reason"`
80 }
81
82 // jsonError writes a spec-shaped JSON error with the appropriate HTTP status.
83 func jsonError(w http.ResponseWriter, httpStatus int, reason string) {
84 w.Header().Set("Content-Type", "application/json")
85 w.WriteHeader(httpStatus)
86 _ = json.NewEncoder(w).Encode(LnurlErrorResponse{Status: "ERROR", Reason: reason})
87 }
88
89 // payMetadata builds the LUD-06 metadata array for a user. The exact same bytes
90 // must be used for the payRequest response and for the description_hash sent to
91 // the wallet, otherwise clients that validate the invoice (lnurl-pay
92 // validateInvoice, lnbits, Zeus, ...) reject the invoice because
93 // sha256(metadata) != bolt11 description_hash.
94 func payMetadata(username, host string) string {
95 return fmt.Sprintf(`[["text/plain","Pay %s@%s"],["text/identifier","%s@%s"]]`,
96 username, host, username, host)
97 }
98
99 // setCorsHeaders makes the endpoint usable from browser-based LNURL clients.
100 func setCorsHeaders(w http.ResponseWriter) {
101 w.Header().Set("Access-Control-Allow-Origin", "*")
102 w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
103 w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
104 }
105
106 type NWCRequest struct {
107 Method string `json:"method"`
108 Params interface{} `json:"params"`
109 }
110
111 type CreateInvoiceParams struct {
112 Amount uint64 `json:"amount"`
113 Description string `json:"description,omitempty"`
114 DescriptionHash string `json:"description_hash,omitempty"`
115 }
116
117 type NWCResponse struct {
118 ResultType string `json:"result_type"`
119 Result interface{} `json:"result,omitempty"`
120 Error *NWCError `json:"error,omitempty"`
121 }
122
123 type NWCError struct {
124 Code string `json:"code"`
125 Message string `json:"message"`
126 }
127
128 type InvoiceResult struct {
129 Invoice string `json:"invoice"`
130 }
131
132 // nwcClient is a NIP-47 request/response client. It keeps one persistent relay
133 // connection for the common case and reuses it across requests. Requests are
134 // serialized with a mutex so concurrent callbacks never cross-talk.
135 //
136 // A relay can accept a request (NIP-01 "OK") yet never deliver the wallet's
137 // response - a subscription may have been dropped server-side without the
138 // client being told. Because a failed invoice means a failed payment, a
139 // non-delivery falls back to the next configured relay using the SAME signed
140 // event, so the wallet treats it as a duplicate instead of minting a second
141 // invoice.
142 type nwcClient struct {
143 mu sync.Mutex
144 servicePubkey string
145 clientSecret string
146 clientPubkey string
147 relays []string
148
149 relay *nostr.Relay
150 relayURL string
151 }
152
153 const (
154 // nwcTotalTimeout bounds one whole make_invoice exchange, including any
155 // relay failover.
156 nwcTotalTimeout = 22 * time.Second
157 // nwcAttemptTimeout bounds the wait for a response on a single relay, so one
158 // silent relay cannot consume the entire failover budget.
159 nwcAttemptTimeout = 8 * time.Second
160 )
161
162 func parseNWCURI(nwcURI string) (servicePubkey, clientSecret string, relays []string, err error) {
163 if !strings.HasPrefix(nwcURI, "nostr+walletconnect://") {
164 err = fmt.Errorf("invalid NWC URI format")
165 return
166 }
167
168 parts := strings.SplitN(nwcURI[22:], "?", 2)
169 servicePubkey = parts[0]
170
171 if len(parts) > 1 {
172 params, _ := url.ParseQuery(parts[1])
173 relays = params["relay"]
174 if len(relays) == 0 {
175 relays = []string{"wss://relay.getalby.com"}
176 }
177 clientSecret = params.Get("secret")
178 }
179
180 return
181 }
182
183 // ensurePreferredRelay moves the preferred relay to the front of the list so the
184 // persistent connection normally runs against it. The default is this project's
185 // own relay; LNURL_PREFERRED_RELAY overrides it (empty disables the preference).
186 func ensurePreferredRelay() {
187 preferred := os.Getenv("LNURL_PREFERRED_RELAY")
188 if preferred == "" {
189 preferred = "wss://relay.mleku.dev"
190 }
191 found := false
192 for i, r := range config.Relays {
193 if r == preferred {
194 if i != 0 {
195 config.Relays = append([]string{preferred}, append(config.Relays[:i], config.Relays[i+1:]...)...)
196 }
197 found = true
198 break
199 }
200 }
201 if !found {
202 config.Relays = append([]string{preferred}, config.Relays...)
203 }
204 }
205
206 // ensureRelay returns the persistent connection, (re)establishing it if it has
207 // dropped. The connection is kept for reuse; per-attempt failover is handled by
208 // makeInvoice, which connects ad hoc to the remaining relays.
209 func (c *nwcClient) ensureRelay(ctx context.Context) (*nostr.Relay, error) {
210 if c.relay != nil && c.relay.IsConnected() {
211 return c.relay, nil
212 }
213 if c.relay != nil {
214 c.relay.Close()
215 c.relay = nil
216 c.relayURL = ""
217 }
218 var lastErr error
219 for _, relayURL := range c.relays {
220 relay, err := nostr.RelayConnect(ctx, relayURL)
221 if err != nil {
222 log.Printf("failed to connect to %s: %v", relayURL, err)
223 lastErr = err
224 continue
225 }
226 c.relay = relay
227 c.relayURL = relayURL
228 log.Printf("connected to %s", relayURL)
229 return relay, nil
230 }
231 return nil, fmt.Errorf("all relays failed: %v", lastErr)
232 }
233
234 // newRequestEvent builds and signs a kind 23194 request. It is signed exactly
235 // once so every relay attempt carries the same event id and the wallet can tell
236 // a retry apart from a genuinely new request.
237 func (c *nwcClient) newRequestEvent(method string, params interface{}) (*nostr.Event, error) {
238 reqJSON, err := json.Marshal(NWCRequest{Method: method, Params: params})
239 if err != nil {
240 return nil, fmt.Errorf("failed to marshal request: %w", err)
241 }
242 sharedSecret, err := nip04.ComputeSharedSecret(c.servicePubkey, c.clientSecret)
243 if err != nil {
244 return nil, fmt.Errorf("failed to compute shared secret: %v", err)
245 }
246 content, err := nip04.Encrypt(string(reqJSON), sharedSecret)
247 if err != nil {
248 return nil, fmt.Errorf("failed to encrypt: %v", err)
249 }
250 ev := &nostr.Event{
251 CreatedAt: nostr.Now(),
252 Kind: 23194,
253 Content: content,
254 Tags: nostr.Tags{{"p", c.servicePubkey}},
255 }
256 for _, r := range c.relays {
257 ev.Tags = append(ev.Tags, nostr.Tag{"relay", r})
258 }
259 if err := ev.Sign(c.clientSecret); err != nil {
260 return nil, fmt.Errorf("failed to sign event: %v", err)
261 }
262 return ev, nil
263 }
264
265 // awaitResponse publishes ev on one relay and waits for the matching NIP-47
266 // response, decrypting it and returning the raw result JSON.
267 func (c *nwcClient) awaitResponse(ctx context.Context, relay *nostr.Relay, ev *nostr.Event) (json.RawMessage, error) {
268 // Subscribe BEFORE publishing so the response can never be missed. Filter on
269 // the request event id (#e) so only the response to THIS request matches -
270 // a late response to a previous request cannot be mis-delivered. Cancelling
271 // ctx tears down the subscription and closes sub.Events.
272 sub, err := relay.Subscribe(ctx, nostr.Filters{{
273 Kinds: []int{23195},
274 Authors: []string{c.servicePubkey},
275 Tags: nostr.TagMap{
276 "e": []string{ev.ID},
277 },
278 Limit: 1,
279 }})
280 if err != nil {
281 return nil, fmt.Errorf("failed to subscribe: %v", err)
282 }
283 defer sub.Unsub()
284
285 if err := relay.Publish(ctx, *ev); err != nil {
286 return nil, fmt.Errorf("failed to publish: %v", err)
287 }
288
289 select {
290 case msg, ok := <-sub.Events:
291 if !ok {
292 return nil, fmt.Errorf("subscription closed")
293 }
294 sharedSecret, err := nip04.ComputeSharedSecret(c.servicePubkey, c.clientSecret)
295 if err != nil {
296 return nil, fmt.Errorf("failed to compute shared secret: %v", err)
297 }
298 decrypted, err := nip04.Decrypt(msg.Content, sharedSecret)
299 if err != nil {
300 return nil, fmt.Errorf("failed to decrypt response: %v", err)
301 }
302 var resp NWCResponse
303 if err := json.Unmarshal([]byte(decrypted), &resp); err != nil {
304 return nil, fmt.Errorf("failed to parse response: %v", err)
305 }
306 if resp.Error != nil {
307 return nil, fmt.Errorf("NWC error: %s - %s", resp.Error.Code, resp.Error.Message)
308 }
309 resultJSON, err := json.Marshal(resp.Result)
310 if err != nil {
311 return nil, fmt.Errorf("failed to re-marshal result: %v", err)
312 }
313 return resultJSON, nil
314
315 case <-ctx.Done():
316 return nil, ctx.Err()
317 }
318 }
319
320 // call walks the configured relays until one delivers a response, and hands the
321 // raw result JSON to parse. It reuses the same signed event across relays so a
322 // re-delivered request is idempotent at the wallet.
323 func (c *nwcClient) call(ctx context.Context, method string, params interface{}, parse func(json.RawMessage) error) error {
324 ev, err := c.newRequestEvent(method, params)
325 if err != nil {
326 return err
327 }
328
329 // Bound the whole exchange, leaving time for the wallet to answer after the
330 // connection phase.
331 overall, cancel := context.WithTimeout(ctx, nwcTotalTimeout)
332 defer cancel()
333
334 connectCtx, cancelConnect := context.WithTimeout(overall, nwcTotalTimeout/2)
335 persistent, err := c.ensureRelay(connectCtx)
336 cancelConnect()
337 if err != nil {
338 return err
339 }
340
341 var (
342 lastErr error
343 tried = map[string]bool{persistent.URL: true}
344 )
345 attemptCtx, cancelAttempt := context.WithTimeout(overall, nwcAttemptTimeout)
346 raw, err := c.awaitResponse(attemptCtx, persistent, ev)
347 cancelAttempt()
348 if err == nil {
349 return parse(raw)
350 }
351 lastErr = err
352 log.Printf("no wallet response on %s: %v", persistent.URL, err)
353
354 for _, r := range c.relays {
355 if tried[r] {
356 continue
357 }
358 tried[r] = true
359 if overall.Err() != nil {
360 break
361 }
362
363 dialCtx, cancelDial := context.WithTimeout(overall, 5*time.Second)
364 relay, err := nostr.RelayConnect(dialCtx, r)
365 cancelDial()
366 if err != nil {
367 lastErr = err
368 log.Printf("failover: cannot connect to %s: %v", r, err)
369 continue
370 }
371 failoverCtx, cancelFailover := context.WithTimeout(overall, nwcAttemptTimeout)
372 raw, err = c.awaitResponse(failoverCtx, relay, ev)
373 cancelFailover()
374 relay.Close()
375 if err == nil {
376 log.Printf("failover: wallet responded via %s", r)
377 return parse(raw)
378 }
379 lastErr = err
380 log.Printf("no wallet response on %s: %v", r, err)
381 }
382
383 if lastErr == nil {
384 lastErr = fmt.Errorf("no relay available")
385 }
386 return fmt.Errorf("timeout waiting for wallet response: %w", lastErr)
387 }
388
389 // NWCNotification is the NIP-47 notification payload. Alby Hub sends these as
390 // kind 23196 events with result_type=notification.
391 type NWCNotification struct {
392 Type string `json:"type"` // e.g. payment_received
393 PaymentHash string `json:"payment_hash"`
394 Invoice string `json:"invoice"`
395 Preimage string `json:"preimage"`
396 }
397
398 // listenNotifications subscribes to wallet notifications and invokes fn for each
399 // successfully decrypted one. It reconnects on drop and blocks until ctx ends.
400 // Notifications let a settled zap be receipted in seconds; the periodic
401 // lookup_invoice sweep is the fallback when a notification is missed.
402 func (c *nwcClient) listenNotifications(ctx context.Context, fn func(NWCNotification)) {
403 backoff := time.Second
404 for ctx.Err() == nil {
405 if err := c.notificationSession(ctx, fn); err != nil && ctx.Err() == nil {
406 log.Printf("notification listener: %v (retrying in %s)", err, backoff)
407 select {
408 case <-ctx.Done():
409 return
410 case <-time.After(backoff):
411 }
412 if backoff < 30*time.Second {
413 backoff *= 2
414 }
415 continue
416 }
417 backoff = time.Second
418 }
419 }
420
421 func (c *nwcClient) notificationSession(ctx context.Context, fn func(NWCNotification)) error {
422 // Deliberately does not take c.mu: the mutex serializes request/response
423 // exchanges, and this is a long-lived read-only subscription that must not
424 // block invoice creation.
425 relay, err := nostr.RelayConnect(ctx, c.relays[0])
426 if err != nil {
427 return fmt.Errorf("connect: %w", err)
428 }
429 defer relay.Close()
430
431 sub, err := relay.Subscribe(ctx, nostr.Filters{{
432 Kinds: []int{23196},
433 Authors: []string{c.servicePubkey},
434 Tags: nostr.TagMap{"p": []string{c.clientPubkey}},
435 }})
436 if err != nil {
437 return fmt.Errorf("subscribe: %w", err)
438 }
439 defer sub.Unsub()
440 log.Printf("listening for wallet notifications on %s", c.relays[0])
441
442 sharedSecret, err := nip04.ComputeSharedSecret(c.servicePubkey, c.clientSecret)
443 if err != nil {
444 return fmt.Errorf("shared secret: %w", err)
445 }
446
447 for {
448 select {
449 case <-ctx.Done():
450 return nil
451 case ev, ok := <-sub.Events:
452 if !ok {
453 return fmt.Errorf("subscription closed")
454 }
455 decrypted, err := nip04.Decrypt(ev.Content, sharedSecret)
456 if err != nil {
457 log.Printf("notification: decrypt failed: %v", err)
458 continue
459 }
460 var note NWCNotification
461 if err := json.Unmarshal([]byte(decrypted), ¬e); err != nil {
462 log.Printf("notification: parse failed: %v", err)
463 continue
464 }
465 fn(note)
466 }
467 }
468 }
469
470 // LookupInvoiceParams is the NIP-47 lookup_invoice request. Payment hash or
471 // invoice must be supplied.
472 type LookupInvoiceParams struct {
473 PaymentHash string `json:"payment_hash,omitempty"`
474 Invoice string `json:"invoice,omitempty"`
475 }
476
477 // LookupInvoiceResult is the subset of the NIP-47 response we rely on.
478 // State is one of pending, settled, failed, accepted.
479 type LookupInvoiceResult struct {
480 Invoice string `json:"invoice"`
481 PaymentHash string `json:"payment_hash"`
482 Preimage string `json:"preimage"`
483 State string `json:"state"`
484 SettledAt int64 `json:"settled_at"`
485 }
486
487 // lookupInvoice asks the wallet for the current state of an invoice.
488 func (c *nwcClient) lookupInvoice(ctx context.Context, paymentHash, invoice string) (*LookupInvoiceResult, error) {
489 c.mu.Lock()
490 defer c.mu.Unlock()
491
492 var out *LookupInvoiceResult
493 err := c.call(ctx, "lookup_invoice", LookupInvoiceParams{
494 PaymentHash: paymentHash,
495 Invoice: invoice,
496 }, func(raw json.RawMessage) error {
497 var res LookupInvoiceResult
498 if err := json.Unmarshal(raw, &res); err != nil {
499 return fmt.Errorf("failed to parse lookup result: %v", err)
500 }
501 out = &res
502 return nil
503 })
504 if err != nil {
505 return nil, err
506 }
507 return out, nil
508 }
509
510 // makeInvoice sends a NIP-47 make_invoice request and returns the bolt11 invoice.
511 // It walks the configured relays until one delivers a response. The caller-supplied
512 // ctx bounds the whole exchange; a per-attempt timeout is layered on top so a hung
513 // relay never leaves a subscription or goroutine behind.
514 func (c *nwcClient) makeInvoice(ctx context.Context, amountMsat uint64, descriptionHash string) (string, error) {
515 c.mu.Lock()
516 defer c.mu.Unlock()
517
518 var invoice string
519 err := c.call(ctx, "make_invoice", CreateInvoiceParams{
520 Amount: amountMsat,
521 DescriptionHash: descriptionHash,
522 }, func(raw json.RawMessage) error {
523 var res InvoiceResult
524 if err := json.Unmarshal(raw, &res); err != nil {
525 return fmt.Errorf("failed to parse invoice result: %v", err)
526 }
527 if res.Invoice == "" {
528 return fmt.Errorf("wallet returned an empty invoice")
529 }
530 invoice = res.Invoice
531 return nil
532 })
533 if err != nil {
534 return "", err
535 }
536 return invoice, nil
537 }
538
539 // validUsername accepts only the username this server actually serves. Without
540 // this the catch-all route happily invents addresses like `@mleku.dev` (empty
541 // path) or serves arbitrary users, since invoices are funded by the one wallet.
542 func validUsername(username string) error {
543 if username == "" {
544 return fmt.Errorf("empty username")
545 }
546 if username != config.Username {
547 return fmt.Errorf("unknown user %q", username)
548 }
549 return nil
550 }
551
552 // publicHost resolves the host to advertise, stripping any port and refusing
553 // hosts we do not serve. The Host header is attacker-controlled, so reflecting it
554 // verbatim would let a request mint a payRequest (and invoice) claiming to be a
555 // lightning address on someone else's domain.
556 func publicHost(raw string) (string, error) {
557 host := raw
558 if h, _, err := net.SplitHostPort(raw); err == nil {
559 host = h
560 }
561 host = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
562 if host == "" {
563 // No Host at all (e.g. a health check over HTTP/1.0): fall back to the
564 // configured domain rather than emitting a malformed address.
565 return config.Domain, nil
566 }
567 if !validHostname(host) {
568 return "", fmt.Errorf("%q is not a valid hostname", host)
569 }
570 for _, allowed := range config.AllowedHosts {
571 if host == allowed {
572 return host, nil
573 }
574 }
575 return "", fmt.Errorf("%q is not a served host", host)
576 }
577
578 // validHostname is a light syntactic check; the allowlist is the real control.
579 func validHostname(h string) bool {
580 if len(h) == 0 || len(h) > 253 {
581 return false
582 }
583 for _, label := range strings.Split(h, ".") {
584 if label == "" || len(label) > 63 {
585 return false
586 }
587 for i := 0; i < len(label); i++ {
588 c := label[i]
589 switch {
590 case c >= 'a' && c <= 'z', c >= '0' && c <= '9', c == '-':
591 default:
592 return false
593 }
594 }
595 }
596 return true
597 }
598
599 func handleLnurl(w http.ResponseWriter, r *http.Request) {
600 setCorsHeaders(w)
601
602 // CORS preflight from a browser-based client. Answer before doing any work
603 // so it does not fall through to the callback parser and 400.
604 if r.Method == http.MethodOptions {
605 w.WriteHeader(http.StatusNoContent)
606 return
607 }
608
609 path := strings.TrimPrefix(r.URL.Path, "/.well-known/lnurlp/")
610 parts := strings.SplitN(path, "/", 2)
611
612 if len(parts) == 1 || parts[1] == "" {
613 username := parts[0]
614 if err := validUsername(username); err != nil {
615 jsonError(w, http.StatusNotFound, "Unknown user")
616 return
617 }
618 host, err := publicHost(r.Host)
619 if err != nil {
620 log.Printf("rejected request with unusable Host %q: %v", r.Host, err)
621 jsonError(w, http.StatusNotFound, "Unknown host")
622 return
623 }
624 metadata := payMetadata(username, host)
625
626 resp := LnurlResponse{
627 Callback: fmt.Sprintf("https://%s/.well-known/lnurlp/%s/callback", host, username),
628 MaxSendable: maxSendableMsat,
629 MinSendable: minSendableMsat,
630 Metadata: metadata,
631 CommentAllowed: config.CommentAllowed,
632 Tag: "payRequest",
633 }
634 // NIP-57 step 1: only advertise zap support when a receipt-signing key is
635 // available, otherwise clients would send zap requests we cannot receipt.
636 if zapServer != nil {
637 allows := true
638 resp.AllowsNostr = &allows
639 resp.NostrPubkey = zapServer.pubkey
640 }
641
642 w.Header().Set("Content-Type", "application/json")
643 if err := json.NewEncoder(w).Encode(resp); err != nil {
644 log.Printf("failed to write payRequest response: %v", err)
645 }
646 return
647 }
648
649 if parts[1] == "callback" {
650 username := parts[0]
651 if err := validUsername(username); err != nil {
652 jsonError(w, http.StatusNotFound, "Unknown user")
653 return
654 }
655 host, err := publicHost(r.Host)
656 if err != nil {
657 log.Printf("rejected callback with unusable Host %q: %v", r.Host, err)
658 jsonError(w, http.StatusNotFound, "Unknown host")
659 return
660 }
661 amountStr := r.URL.Query().Get("amount")
662 amountMsat, err := strconv.ParseUint(amountStr, 10, 64)
663 if err != nil {
664 jsonError(w, http.StatusBadRequest, "Invalid amount")
665 return
666 }
667 if amountMsat < minSendableMsat || amountMsat > maxSendableMsat {
668 jsonError(w, http.StatusBadRequest, "Amount out of range")
669 return
670 }
671
672 // Must be byte-identical to the metadata served by the payRequest
673 // branch; the same hash goes to the wallet and is what clients verify.
674 metadata := payMetadata(username, host)
675 hash := sha256.Sum256([]byte(metadata))
676 descriptionHash := hex.EncodeToString(hash[:])
677
678 // NIP-57: when a zap request is present it replaces the metadata as the
679 // invoice description. The hash MUST be taken over the exact bytes the
680 // client sent, because the receipt later embeds that same string and
681 // sha256(description) has to match the invoice's description hash.
682 var (
683 pendingZapRecord *pendingZap
684 zapReq *ZapRequest
685 )
686 if raw := r.URL.Query().Get("nostr"); raw != "" {
687 if zapServer == nil {
688 jsonError(w, http.StatusBadRequest, "zap support is not enabled")
689 return
690 }
691 zr, canonical, relays, verr := parseAndValidateZap(raw, amountMsat)
692 if verr != nil {
693 log.Printf("rejected zap request from %s: %v", r.RemoteAddr, verr)
694 jsonError(w, http.StatusBadRequest, "Invalid zap request")
695 return
696 }
697 zapReq = zr
698 // Hash the canonical event encoding, never the raw query bytes: the
699 // id and signature only commit to the canonical form.
700 sum := sha256.Sum256([]byte(canonical))
701 descriptionHash = hex.EncodeToString(sum[:])
702 pendingZapRecord = &pendingZap{
703 ZapRequest: canonical,
704 Relays: relays,
705 AmountMsat: amountMsat,
706 CreatedAt: time.Now(),
707 }
708 }
709
710 ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
711 defer cancel()
712
713 invoice, err := nwc.makeInvoice(ctx, amountMsat, descriptionHash)
714 if err != nil {
715 log.Printf("failed to create invoice for %s@%s (%d msat): %v", username, host, amountMsat, err)
716 jsonError(w, http.StatusInternalServerError, "Failed to create invoice")
717 return
718 }
719
720 // Persist the zap request against the invoice's payment hash so the
721 // receipt can be built when the invoice settles. Failure here means we
722 // could hand out an invoice we can never receipt, so fail loudly.
723 if pendingZapRecord != nil {
724 paymentHash, perr := paymentHashFromInvoice(invoice)
725 if perr != nil {
726 log.Printf("zap: cannot determine payment hash, not returning invoice: %v", perr)
727 jsonError(w, http.StatusInternalServerError, "Failed to create invoice")
728 return
729 }
730 pendingZapRecord.PaymentHash = paymentHash
731 pendingZapRecord.Invoice = invoice
732 if err := zapServer.remember(pendingZapRecord); err != nil {
733 log.Printf("zap: failed to persist pending zap %s: %v", paymentHash, err)
734 jsonError(w, http.StatusInternalServerError, "Failed to create invoice")
735 return
736 }
737 log.Printf("zap: invoice %s created for %d msat, receipt owed to %s", paymentHash, amountMsat, zapReq.PubKey)
738 }
739
740 disposable := false
741
742 // SuccessAction stays nil -> omitted entirely (see LnurlCallbackResponse).
743 callbackResp := LnurlCallbackResponse{
744 Pr: invoice,
745 Disposable: &disposable,
746 Routes: []interface{}{},
747 }
748
749 w.Header().Set("Content-Type", "application/json")
750 if err := json.NewEncoder(w).Encode(callbackResp); err != nil {
751 log.Printf("failed to write callback response: %v", err)
752 }
753 return
754 }
755
756 w.Header().Set("Content-Type", "application/json")
757 w.WriteHeader(http.StatusNotFound)
758 _ = json.NewEncoder(w).Encode(LnurlErrorResponse{Status: "ERROR", Reason: "Not found"})
759 }
760
761 var config Config
762 var nwc *nwcClient
763 var zapServer *ZapServer
764
765 func main() {
766 nwcURI := os.Getenv("NWC_URI")
767 if nwcURI == "" {
768 log.Fatal("NWC_URI environment variable required")
769 }
770
771 // rootCtx bounds background work (zap watcher, notification listener) so it
772 // stops on shutdown.
773 rootCtx, stopBackground := context.WithCancel(context.Background())
774 defer stopBackground()
775
776 var err error
777 config.ServicePubkey, config.ClientSecret, config.Relays, err = parseNWCURI(nwcURI)
778 if err != nil {
779 log.Fatalf("Failed to parse NWC URI: %v", err)
780 }
781
782 ensurePreferredRelay()
783
784 config.ClientPubkey, err = nostr.GetPublicKey(config.ClientSecret)
785 if err != nil {
786 log.Fatalf("Failed to derive client pubkey: %v", err)
787 }
788
789 nwc = &nwcClient{
790 servicePubkey: config.ServicePubkey,
791 clientSecret: config.ClientSecret,
792 clientPubkey: config.ClientPubkey,
793 relays: config.Relays,
794 }
795
796 config.Username = os.Getenv("LNURL_USERNAME")
797 if config.Username == "" {
798 config.Username = "me"
799 }
800
801 config.Domain = os.Getenv("LNURL_DOMAIN")
802 if config.Domain == "" {
803 config.Domain = "mleku.dev"
804 }
805
806 // LUD-12: only advertise a comment length we actually honour. Default 0.
807 config.CommentAllowed = 0
808 if v := os.Getenv("LNURL_COMMENT_ALLOWED"); v != "" {
809 n, err := strconv.Atoi(v)
810 if err != nil || n < 0 {
811 log.Printf("ignoring invalid LNURL_COMMENT_ALLOWED=%q", v)
812 } else if n > 256 {
813 // Keep the well-known response small; LUD-12 sets no upper bound.
814 config.CommentAllowed = 256
815 } else {
816 config.CommentAllowed = n
817 }
818 }
819
820 // Hosts we will serve. The configured domain is always included; extra
821 // domains (e.g. a secondary lightning address) go in LNURL_ALLOWED_HOSTS.
822 // The Host header is attacker-controlled, so it only ever selects from this
823 // list rather than being reflected into metadata/callbacks.
824 config.AllowedHosts = []string{strings.ToLower(config.Domain)}
825 if extra := os.Getenv("LNURL_ALLOWED_HOSTS"); extra != "" {
826 for _, h := range strings.Split(extra, ",") {
827 h = strings.ToLower(strings.TrimSpace(h))
828 if h == "" {
829 continue
830 }
831 dup := false
832 for _, have := range config.AllowedHosts {
833 if have == h {
834 dup = true
835 break
836 }
837 }
838 if !dup {
839 config.AllowedHosts = append(config.AllowedHosts, h)
840 }
841 }
842 }
843
844 log.Printf("LNURL server for %s@%s", config.Username, config.Domain)
845 log.Printf("Relays: %v", config.Relays)
846 log.Printf("Serving hosts: %v", config.AllowedHosts)
847 log.Printf("Comment allowed: %d", config.CommentAllowed)
848
849 // NIP-57 zap support. Disable with ZAP_ENABLED=false; without a key the
850 // payRequest simply omits allowsNostr and clients treat the address as
851 // non-zappable.
852 if os.Getenv("ZAP_ENABLED") != "false" {
853 statePath := os.Getenv("ZAP_STATE_FILE")
854 if statePath == "" {
855 base := os.Getenv("ZAP_STATE_DIR")
856 if base == "" {
857 base = "/var/lib/lnurl-server"
858 }
859 statePath = filepath.Join(base, "zaps.json")
860 }
861 zs, zerr := newZapServer(config.ClientSecret, statePath)
862 if zerr != nil {
863 log.Printf("zap support disabled: %v", zerr)
864 } else {
865 zapServer = zs
866 log.Printf("Zap receipts enabled, nostrPubkey: %s", zapServer.pubkey)
867 log.Printf("Zap state file: %s", statePath)
868 go runZapWatcher(rootCtx)
869 }
870 } else {
871 log.Printf("Zap support disabled by ZAP_ENABLED=false")
872 }
873
874 mux := http.NewServeMux()
875 mux.HandleFunc("/.well-known/lnurlp/", handleLnurl)
876
877 port := os.Getenv("PORT")
878 if port == "" {
879 port = "8096"
880 }
881
882 // Explicit timeouts prevent slow/stalled clients from pinning connections
883 // and goroutines open indefinitely. WriteTimeout must stay comfortably above
884 // the callback's own budget (25s), otherwise the invoice is generated but the
885 // HTTP response is cut off and the client sees an empty/encoding error.
886 srv := &http.Server{
887 Addr: ":" + port,
888 Handler: mux,
889 ReadHeaderTimeout: 5 * time.Second,
890 ReadTimeout: 30 * time.Second,
891 WriteTimeout: 45 * time.Second,
892 IdleTimeout: 60 * time.Second,
893 }
894
895 go func() {
896 log.Printf("Listening on :%s", port)
897 if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
898 log.Fatalf("server error: %v", err)
899 }
900 }()
901
902 // Graceful shutdown on SIGINT/SIGTERM.
903 sig := make(chan os.Signal, 1)
904 signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
905 <-sig
906 log.Printf("shutting down...")
907 stopBackground()
908 shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
909 defer shutdownCancel()
910 if err := srv.Shutdown(shutdownCtx); err != nil {
911 log.Printf("server shutdown error: %v", err)
912 }
913 if nwc != nil && nwc.relay != nil {
914 nwc.relay.Close()
915 }
916 log.Printf("stopped")
917 }
918