package blossom import ( "context" "encoding/hex" "encoding/json" "fmt" "net/http" "git.smesh.lol/orly/pkg/musiquay/deed" "git.smesh.lol/orly/pkg/musiquay/play" "git.smesh.lol/orly/pkg/nostr/encoders/filter" "git.smesh.lol/orly/pkg/nostr/encoders/kind" "git.smesh.lol/orly/pkg/nostr/encoders/tag" "git.smesh.lol/orly/pkg/nostr/interfaces/signer" ) // BlindSignConfig configures the certified-play endpoint. type BlindSignConfig struct { // Sign is the host's play key, distinct from the receipt and aggregate // keys. Sign signer.I // Gate supplies the entitlement session. Required. Gate *Gate // Limiter enforces one signature per (identity, asset, window). Limiter *play.IssuanceLimiter // NeverLog suppresses request logging. It defaults to true and exists only // so the intent is explicit in the wiring. NeverLog bool } // blindSignRequest is the endpoint's JSON body. type blindSignRequest struct { // B_ is the blinded point, compressed hex. B_ string `json:"B_"` // Statement is the exact statement, when the client built it. Statement string `json:"statement"` // Asset is the asset id the session is for. Asset string `json:"asset"` // Address is the asset address used in the statement. Address string `json:"address"` // Blob and the window are used to build the statement when it is absent. Blob string `json:"blob"` Start int64 `json:"start"` End int64 `json:"end"` } // blindSignResponse is the endpoint's JSON response. type blindSignResponse struct { C_ string `json:"C_"` DLEQ play.DLEQ `json:"dleq"` Host string `json:"host"` Domain string `json:"domain"` } // handleBlindSign issues a blind signature for a play the host observed. func (s *Server) handleBlindSign(w http.ResponseWriter, r *http.Request) { if s.blindSign == nil { http.Error(w, "blinded play certification is not enabled", http.StatusNotFound) return } cfg := s.blindSign if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } var req blindSignRequest if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16*1024)).Decode(&req); err != nil { http.Error(w, "invalid JSON", http.StatusBadRequest) return } if req.B_ == "" { http.Error(w, "missing B_", http.StatusBadRequest) return } // The statement is either supplied or built from observed facts. var statement []byte if req.Statement != "" { statement = []byte(req.Statement) } else { if req.Blob == "" || req.End <= 0 { http.Error(w, "statement or blob/window is required", http.StatusBadRequest) return } statement = play.Statement(req.Address, req.Blob, req.Start, req.End) } parsed, err := play.ParseStatement(statement) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Entitlement: the request must carry a live session for the asset. A play // signature is never issued to a caller the host has not served. if cfg.Gate == nil { http.Error(w, "no entitlement gate", http.StatusServiceUnavailable) return } assetID := req.Asset if assetID == "" { assetID, err = cfg.Gate.AssetIDForAddress(r.Context(), parsed.AssetAddress) if err != nil { http.Error(w, "unknown asset", http.StatusNotFound) return } } // The statement's address must resolve to the asset the session covers, // otherwise a caller could certify a play of something it did not buy. addrAsset, err := cfg.Gate.AssetIDForAddress(r.Context(), parsed.AssetAddress) if err != nil || addrAsset != assetID { http.Error(w, "statement address does not match the asset", http.StatusBadRequest) return } buyer, ok := cfg.Gate.SessionBuyer(r, assetID) if !ok { w.Header().Set("WWW-Authenticate", `Nostr realm="musiquay"`) http.Error(w, "entitlement required", http.StatusUnauthorized) return } if cfg.Limiter != nil && !cfg.Limiter.Allow(hex.EncodeToString(buyer), assetID, parsed.Start, parsed.End) { http.Error(w, "already certified for this window", http.StatusTooManyRequests) return } cert, err := play.Sign(cfg.Sign, req.B_) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _ = json.NewEncoder(w).Encode(blindSignResponse{ C_: cert.C_, DLEQ: cert.DLEQ, Host: hex.EncodeToString(cfg.Sign.Pub()), Domain: play.Domain, }) } // SessionBuyer returns the buyer a live session names for an asset, checking a // signed cookie first and a BUD-11 token second. func (g *Gate) SessionBuyer(r *http.Request, assetID string) ([]byte, bool) { if buyer, ok := g.cookieBuyer(r); ok { if g.sessions.Valid(deed.SessionKey{Buyer: hex.EncodeToString(buyer), Asset: assetID}) { return buyer, true } } if r.Header.Get(AuthorizationHeader) != "" { authEv, err := ValidateAuthEventForGet(r, g.host, nil) if err == nil && authEv != nil { if g.sessions.Valid(deed.SessionKey{Buyer: hex.EncodeToString(authEv.Pubkey), Asset: assetID}) { return authEv.Pubkey, true } } } return nil, false } // AssetIDForAddress resolves an addressable coordinate to its asset id. func (g *Gate) AssetIDForAddress(ctx context.Context, coordinate string) (string, error) { parts := splitCoordinate(coordinate) if parts == nil { return "", fmt.Errorf("gate: invalid coordinate") } f := filter.New() f.Kinds = kind.NewS(kind.New(parts.kind)) f.Authors = tag.NewFromBytesSlice(parts.pub) f.Tags = tag.NewS(tag.NewFromBytesSlice([]byte("d"), []byte(parts.d))) f.Limit = new(uint) *f.Limit = 1 evs, err := g.db.QueryEvents(ctx, f) if err != nil { return "", err } if len(evs) == 0 { return "", fmt.Errorf("gate: no event at %s", coordinate) } ev := evs[0] if a := tagVal(ev, "asset"); a != "" { return a, nil } // Derive from the event id only when the event is the first publication. return deed.DeriveAssetID(ev.ID) } type coordParts struct { kind uint16 pub []byte d string } func splitCoordinate(a string) *coordParts { var k uint32 var pubHex string rest := "" // Parse kind:pubkey:d without importing the deed package's unexported // helper. i := indexByte(a, ':') if i <= 0 { return nil } if _, err := fmt.Sscanf(a[:i], "%d", &k); err != nil || k > 65535 { return nil } rest = a[i+1:] j := indexByte(rest, ':') if j != 64 { return nil } pubHex = rest[:j] pub, err := hex.DecodeString(pubHex) if err != nil || len(pub) != 32 { return nil } d := rest[j+1:] if d == "" { return nil } return &coordParts{kind: uint16(k), pub: pub, d: d} } func indexByte(s string, c byte) int { for i := 0; i < len(s); i++ { if s[i] == c { return i } } return -1 }