blindsign.go raw

   1  package blossom
   2  
   3  import (
   4  	"context"
   5  	"encoding/hex"
   6  	"encoding/json"
   7  	"fmt"
   8  	"net/http"
   9  
  10  	"git.smesh.lol/orly/pkg/musiquay/deed"
  11  	"git.smesh.lol/orly/pkg/musiquay/play"
  12  	"git.smesh.lol/orly/pkg/nostr/encoders/filter"
  13  	"git.smesh.lol/orly/pkg/nostr/encoders/kind"
  14  	"git.smesh.lol/orly/pkg/nostr/encoders/tag"
  15  	"git.smesh.lol/orly/pkg/nostr/interfaces/signer"
  16  )
  17  
  18  // BlindSignConfig configures the certified-play endpoint.
  19  type BlindSignConfig struct {
  20  	// Sign is the host's play key, distinct from the receipt and aggregate
  21  	// keys.
  22  	Sign signer.I
  23  	// Gate supplies the entitlement session. Required.
  24  	Gate *Gate
  25  	// Limiter enforces one signature per (identity, asset, window).
  26  	Limiter *play.IssuanceLimiter
  27  	// NeverLog suppresses request logging. It defaults to true and exists only
  28  	// so the intent is explicit in the wiring.
  29  	NeverLog bool
  30  }
  31  
  32  // blindSignRequest is the endpoint's JSON body.
  33  type blindSignRequest struct {
  34  	// B_ is the blinded point, compressed hex.
  35  	B_ string `json:"B_"`
  36  	// Statement is the exact statement, when the client built it.
  37  	Statement string `json:"statement"`
  38  	// Asset is the asset id the session is for.
  39  	Asset string `json:"asset"`
  40  	// Address is the asset address used in the statement.
  41  	Address string `json:"address"`
  42  	// Blob and the window are used to build the statement when it is absent.
  43  	Blob  string `json:"blob"`
  44  	Start int64  `json:"start"`
  45  	End   int64  `json:"end"`
  46  }
  47  
  48  // blindSignResponse is the endpoint's JSON response.
  49  type blindSignResponse struct {
  50  	C_     string    `json:"C_"`
  51  	DLEQ   play.DLEQ `json:"dleq"`
  52  	Host   string    `json:"host"`
  53  	Domain string    `json:"domain"`
  54  }
  55  
  56  // handleBlindSign issues a blind signature for a play the host observed.
  57  func (s *Server) handleBlindSign(w http.ResponseWriter, r *http.Request) {
  58  	if s.blindSign == nil {
  59  		http.Error(w, "blinded play certification is not enabled", http.StatusNotFound)
  60  		return
  61  	}
  62  	cfg := s.blindSign
  63  	if r.Method != http.MethodPost {
  64  		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  65  		return
  66  	}
  67  	var req blindSignRequest
  68  	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&req); err != nil {
  69  		http.Error(w, "invalid JSON", http.StatusBadRequest)
  70  		return
  71  	}
  72  	if req.B_ == "" {
  73  		http.Error(w, "missing B_", http.StatusBadRequest)
  74  		return
  75  	}
  76  
  77  	// The statement is either supplied or built from observed facts.
  78  	var statement []byte
  79  	if req.Statement != "" {
  80  		statement = []byte(req.Statement)
  81  	} else {
  82  		if req.Blob == "" || req.End <= 0 {
  83  			http.Error(w, "statement or blob/window is required", http.StatusBadRequest)
  84  			return
  85  		}
  86  		statement = play.Statement(req.Address, req.Blob, req.Start, req.End)
  87  	}
  88  	parsed, err := play.ParseStatement(statement)
  89  	if err != nil {
  90  		http.Error(w, err.Error(), http.StatusBadRequest)
  91  		return
  92  	}
  93  
  94  	// Entitlement: the request must carry a live session for the asset. A play
  95  	// signature is never issued to a caller the host has not served.
  96  	if cfg.Gate == nil {
  97  		http.Error(w, "no entitlement gate", http.StatusServiceUnavailable)
  98  		return
  99  	}
 100  	assetID := req.Asset
 101  	if assetID == "" {
 102  		assetID, err = cfg.Gate.AssetIDForAddress(r.Context(), parsed.AssetAddress)
 103  		if err != nil {
 104  			http.Error(w, "unknown asset", http.StatusNotFound)
 105  			return
 106  		}
 107  	}
 108  	// The statement's address must resolve to the asset the session covers,
 109  	// otherwise a caller could certify a play of something it did not buy.
 110  	addrAsset, err := cfg.Gate.AssetIDForAddress(r.Context(), parsed.AssetAddress)
 111  	if err != nil || addrAsset != assetID {
 112  		http.Error(w, "statement address does not match the asset", http.StatusBadRequest)
 113  		return
 114  	}
 115  	buyer, ok := cfg.Gate.SessionBuyer(r, assetID)
 116  	if !ok {
 117  		w.Header().Set("WWW-Authenticate", `Nostr realm="musiquay"`)
 118  		http.Error(w, "entitlement required", http.StatusUnauthorized)
 119  		return
 120  	}
 121  	if cfg.Limiter != nil && !cfg.Limiter.Allow(hex.EncodeToString(buyer), assetID, parsed.Start, parsed.End) {
 122  		http.Error(w, "already certified for this window", http.StatusTooManyRequests)
 123  		return
 124  	}
 125  
 126  	cert, err := play.Sign(cfg.Sign, req.B_)
 127  	if err != nil {
 128  		http.Error(w, err.Error(), http.StatusBadRequest)
 129  		return
 130  	}
 131  	w.Header().Set("Content-Type", "application/json")
 132  	w.WriteHeader(http.StatusOK)
 133  	_ = json.NewEncoder(w).Encode(blindSignResponse{
 134  		C_:     cert.C_,
 135  		DLEQ:   cert.DLEQ,
 136  		Host:   hex.EncodeToString(cfg.Sign.Pub()),
 137  		Domain: play.Domain,
 138  	})
 139  }
 140  
 141  // SessionBuyer returns the buyer a live session names for an asset, checking a
 142  // signed cookie first and a BUD-11 token second.
 143  func (g *Gate) SessionBuyer(r *http.Request, assetID string) ([]byte, bool) {
 144  	if buyer, ok := g.cookieBuyer(r); ok {
 145  		if g.sessions.Valid(deed.SessionKey{Buyer: hex.EncodeToString(buyer), Asset: assetID}) {
 146  			return buyer, true
 147  		}
 148  	}
 149  	if r.Header.Get(AuthorizationHeader) != "" {
 150  		authEv, err := ValidateAuthEventForGet(r, g.host, nil)
 151  		if err == nil && authEv != nil {
 152  			if g.sessions.Valid(deed.SessionKey{Buyer: hex.EncodeToString(authEv.Pubkey), Asset: assetID}) {
 153  				return authEv.Pubkey, true
 154  			}
 155  		}
 156  	}
 157  	return nil, false
 158  }
 159  
 160  // AssetIDForAddress resolves an addressable coordinate to its asset id.
 161  func (g *Gate) AssetIDForAddress(ctx context.Context, coordinate string) (string, error) {
 162  
 163  	parts := splitCoordinate(coordinate)
 164  	if parts == nil {
 165  		return "", fmt.Errorf("gate: invalid coordinate")
 166  	}
 167  	f := filter.New()
 168  	f.Kinds = kind.NewS(kind.New(parts.kind))
 169  	f.Authors = tag.NewFromBytesSlice(parts.pub)
 170  	f.Tags = tag.NewS(tag.NewFromBytesSlice([]byte("d"), []byte(parts.d)))
 171  	f.Limit = new(uint)
 172  	*f.Limit = 1
 173  	evs, err := g.db.QueryEvents(ctx, f)
 174  	if err != nil {
 175  		return "", err
 176  	}
 177  	if len(evs) == 0 {
 178  		return "", fmt.Errorf("gate: no event at %s", coordinate)
 179  	}
 180  	ev := evs[0]
 181  	if a := tagVal(ev, "asset"); a != "" {
 182  		return a, nil
 183  	}
 184  	// Derive from the event id only when the event is the first publication.
 185  	return deed.DeriveAssetID(ev.ID)
 186  }
 187  
 188  type coordParts struct {
 189  	kind uint16
 190  	pub  []byte
 191  	d    string
 192  }
 193  
 194  func splitCoordinate(a string) *coordParts {
 195  	var k uint32
 196  	var pubHex string
 197  	rest := ""
 198  	// Parse kind:pubkey:d without importing the deed package's unexported
 199  	// helper.
 200  	i := indexByte(a, ':')
 201  	if i <= 0 {
 202  		return nil
 203  	}
 204  	if _, err := fmt.Sscanf(a[:i], "%d", &k); err != nil || k > 65535 {
 205  		return nil
 206  	}
 207  	rest = a[i+1:]
 208  	j := indexByte(rest, ':')
 209  	if j != 64 {
 210  		return nil
 211  	}
 212  	pubHex = rest[:j]
 213  	pub, err := hex.DecodeString(pubHex)
 214  	if err != nil || len(pub) != 32 {
 215  		return nil
 216  	}
 217  	d := rest[j+1:]
 218  	if d == "" {
 219  		return nil
 220  	}
 221  	return &coordParts{kind: uint16(k), pub: pub, d: d}
 222  }
 223  
 224  func indexByte(s string, c byte) int {
 225  	for i := 0; i < len(s); i++ {
 226  		if s[i] == c {
 227  			return i
 228  		}
 229  	}
 230  	return -1
 231  }
 232