musiquay.go raw

   1  package app
   2  
   3  import (
   4  	"context"
   5  	"crypto/rand"
   6  	"encoding/json"
   7  	"fmt"
   8  	"os"
   9  
  10  	"git.smesh.lol/orly/pkg/blossom"
  11  	"git.smesh.lol/orly/pkg/database"
  12  	"git.smesh.lol/orly/pkg/lol/log"
  13  	"git.smesh.lol/orly/pkg/musiquay/hostkey"
  14  	"git.smesh.lol/orly/pkg/musiquay/receipts"
  15  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
  16  	"git.smesh.lol/orly/pkg/nostr/encoders/hex"
  17  )
  18  
  19  // musiquayGateConfig builds the access gate from the environment. It returns
  20  // nil when ORLY_MUSIQUAY_HOST is unset, so an ordinary Blossom deployment is
  21  // unaffected.
  22  //
  23  // Environment:
  24  //
  25  //	ORLY_MUSIQUAY_HOST               public host of this Blossom server (required)
  26  //	ORLY_MUSIQUAY_COOKIE_SECRET     hex HMAC key for the session cookie
  27  //	ORLY_MUSIQUAY_KEY_DIR           directory for K_receipt/K_agg/K_play
  28  //	ORLY_MUSIQUAY_PUBLISHER_PUBKEY  optional publisher pubkey for receipt copies
  29  //	ORLY_MUSIQUAY_RECEIPT_NSEC      explicit receipt key
  30  func musiquayGateConfig(db database.Database) (*blossom.GateConfig, func(context.Context, blossom.ServeInfo)) {
  31  	host := os.Getenv("ORLY_MUSIQUAY_HOST")
  32  	if host == "" {
  33  		return nil, nil
  34  	}
  35  	secret := cookieSecret(db)
  36  	gc := &blossom.GateConfig{Host: host, CookieSecret: secret}
  37  
  38  	dir := os.Getenv("ORLY_MUSIQUAY_KEY_DIR")
  39  	explicit := os.Getenv("ORLY_MUSIQUAY_RECEIPT_NSEC")
  40  	if dir == "" && explicit == "" {
  41  		log.W.F("musiquay: gate enabled without a receipt key; receipts are disabled")
  42  		return gc, nil
  43  	}
  44  	keys := hostkey.New(hostkey.FromEnv(os.Getenv, dir))
  45  	sign, err := keys.Signer(hostkey.Receipt)
  46  	if err != nil {
  47  		log.E.F("musiquay: receipt key: %v", err)
  48  		return gc, nil
  49  	}
  50  	issuer := &receipts.Issuer{
  51  		Sign:         sign,
  52  		Archive:      receipts.NewArchive(db),
  53  		Publisher:    localWrapPublisher{db: db},
  54  		PublisherPub: publisherPubkey(),
  55  	}
  56  
  57  	hook := func(ctx context.Context, info blossom.ServeInfo) {
  58  		if _, _, err := issuer.Issue(ctx, receipts.Serve{
  59  			AssetID:    info.AssetID,
  60  			Coordinate: info.Coordinate,
  61  			Buyer:      info.Buyer,
  62  			Blob:       info.Blob,
  63  			Host:       info.Host,
  64  			Mode:       info.Mode,
  65  			Bytes:      info.Bytes,
  66  			AmountSats: info.AmountSats,
  67  		}); err != nil {
  68  			log.W.F("musiquay: receipt for %s: %v", info.Blob, err)
  69  		}
  70  	}
  71  	return gc, hook
  72  }
  73  
  74  // publisherPubkey reads the optional publisher address for receipt copies.
  75  func publisherPubkey() []byte {
  76  	s := os.Getenv("ORLY_MUSIQUAY_PUBLISHER_PUBKEY")
  77  	if s == "" {
  78  		return nil
  79  	}
  80  	pub, err := hex.Dec(s)
  81  	if err != nil || len(pub) != 32 {
  82  		log.W.F("musiquay: invalid ORLY_MUSIQUAY_PUBLISHER_PUBKEY")
  83  		return nil
  84  	}
  85  	return pub
  86  }
  87  
  88  // cookieSecret loads the session-cookie HMAC key, generating and persisting one
  89  // on first use. It must be stable across workers.
  90  func cookieSecret(db database.Database) []byte {
  91  	const marker = "musiquay:cookie-secret"
  92  	if v, err := db.GetMarker(marker); err == nil && len(v) >= 32 {
  93  		return v
  94  	}
  95  	if v := os.Getenv("ORLY_MUSIQUAY_COOKIE_SECRET"); v != "" {
  96  		if b, err := hex.Dec(v); err == nil && len(b) >= 32 {
  97  			_ = db.SetMarker(marker, b)
  98  			return b
  99  		}
 100  	}
 101  	b := make([]byte, 32)
 102  	if _, err := rand.Read(b); err != nil {
 103  		// Without a secret the cookie is disabled; the gate still works through
 104  		// BUD-11 tokens.
 105  		return nil
 106  	}
 107  	if err := db.SetMarker(marker, b); err != nil {
 108  		log.W.F("musiquay: persist cookie secret: %v", err)
 109  	}
 110  	return b
 111  }
 112  
 113  // localWrapPublisher writes a gift wrap to the relay database so the recipient
 114  // can fetch it. The relay serves a wrap only to its p-tagged recipient, so the
 115  // write does not leak the artifact.
 116  type localWrapPublisher struct{ db database.Database }
 117  
 118  func (p localWrapPublisher) Publish(ctx context.Context, ev *event.E) error {
 119  	if p.db == nil {
 120  		return fmt.Errorf("musiquay: no database for wrap publication")
 121  	}
 122  	// Round-trip through the wire form so the stored event and its indexes are
 123  	// identical to one received over NIP-01.
 124  	raw, err := ev.MarshalJSON()
 125  	if err != nil {
 126  		return err
 127  	}
 128  	var wire event.E
 129  	if err = json.Unmarshal(raw, &wire); err != nil {
 130  		return err
 131  	}
 132  	_, err = p.db.SaveEvent(ctx, &wire)
 133  	return err
 134  }
 135