package deed import ( "fmt" "net/url" "strconv" "strings" "sync" "time" "git.smesh.lol/orly/pkg/nostr/encoders/event" "git.smesh.lol/orly/pkg/nostr/encoders/hex" "git.smesh.lol/orly/pkg/nostr/encoders/kind" ) // PresentDomain is the required content of a 22243 presentation proof. It is // the domain separator that stops a signature made for another purpose from // being replayed as a proof of possession. const PresentDomain = "musiquay.present:v1" // PresentationProof is a parsed kind 22243 event. type PresentationProof struct { Event *event.E // DeedID is the deed event id being presented. DeedID string // AssetID is the asset actually requested. AssetID string // Server is the host named by the proof. Server string // Nonce is the client-generated single-use nonce. Nonce string // Expires is the unix expiration. Expires int64 } // ParseProof structurally validates a presentation proof: kind, domain // content, signature, and the presence of its mandatory tags. It does not // check freshness, binding, or replay. func ParseProof(ev *event.E) (*PresentationProof, error) { if ev == nil { return nil, fmt.Errorf("deed: nil presentation proof") } if ev.Kind != kind.DeedPresentation.ToU16() { return nil, fmt.Errorf("deed: kind %d is not a presentation proof", ev.Kind) } if string(ev.Content) != PresentDomain { return nil, fmt.Errorf("deed: presentation proof content is not %q", PresentDomain) } if valid, err := ev.Verify(); err != nil { return nil, fmt.Errorf("deed: verify presentation proof: %w", err) } else if !valid { return nil, fmt.Errorf("deed: presentation proof signature invalid") } p := &PresentationProof{ Event: ev, DeedID: tagValue(ev, TagDeed), AssetID: tagValue(ev, TagAsset), Server: tagValue(ev, TagServer), Nonce: tagValue(ev, TagNonce), } if len(p.DeedID) != 64 { return nil, fmt.Errorf("deed: presentation proof has no valid deed tag") } if !IsAssetID(p.AssetID) { return nil, fmt.Errorf("deed: presentation proof has no valid asset tag") } if p.Server == "" { return nil, fmt.Errorf("deed: presentation proof has no server tag") } if !validNonce(p.Nonce) { return nil, fmt.Errorf("deed: presentation proof has an invalid nonce") } exp := tagValue(ev, TagExpiration) if exp == "" { return nil, fmt.Errorf("deed: presentation proof has no expiration") } n, err := strconv.ParseInt(exp, 10, 64) if err != nil { return nil, fmt.Errorf("deed: presentation proof has an invalid expiration") } p.Expires = n return p, nil } // validNonce bounds the nonce so a client cannot blow up the cache with one // enormous value, and rejects whitespace that would confuse logging. func validNonce(n string) bool { if len(n) < 8 || len(n) > 128 { return false } for i := 0; i < len(n); i++ { c := n[i] if c <= 0x20 || c == 0x7f { return false } } return true } // ProofVerifyOptions is everything a host must supply to accept a proof. type ProofVerifyOptions struct { // Deed is the already-verified deed being presented. Deed *Deed // RequestedAssetID is the asset the request is for. RequestedAssetID string // Server is this host's domain or origin. Server string // RequestPubkey is the BUD-11 request identity. RequestPubkey []byte // Now overrides the clock. Now time.Time // MaxAge is how old created_at may be. Zero means five minutes. MaxAge time.Duration // Nonces enforces single use. Required. Nonces *NonceCache } // Verify checks binding, freshness, scope, and single use. // // The proof must have been signed by the deed's buyer and by the same key that // signed the request, must name the requested asset, this server, and a fresh // nonce that has not been seen for that key. Those five checks together stop a // copied deed, a proof replayed to another host, and a proof captured from // another request from being useful. func (p *PresentationProof) Verify(o ProofVerifyOptions) error { if o.Deed == nil { return fmt.Errorf("deed: presentation proof has no deed to bind to") } if !equalBytes(p.Event.Pubkey, o.Deed.Buyer) { return fmt.Errorf("deed: presentation proof signer is not the deed buyer") } if len(o.RequestPubkey) != 32 || !equalBytes(p.Event.Pubkey, o.RequestPubkey) { return fmt.Errorf("deed: presentation proof signer is not the request identity") } if !IsAssetID(o.RequestedAssetID) { return fmt.Errorf("deed: requested asset id is invalid") } if p.AssetID != o.RequestedAssetID { return fmt.Errorf("deed: presentation proof names asset %s, request is for %s", p.AssetID, o.RequestedAssetID) } if p.DeedID != o.Deed.ID() { return fmt.Errorf("deed: presentation proof names a different deed") } if o.Server == "" { return fmt.Errorf("deed: no server to bind the proof to") } if !sameServer(p.Server, o.Server) { return fmt.Errorf("deed: presentation proof is for server %q, not %q", p.Server, o.Server) } now := o.Now if now.IsZero() { now = time.Now() } maxAge := o.MaxAge if maxAge <= 0 { maxAge = 5 * time.Minute } if p.Event.CreatedAt > now.Add(60*time.Second).Unix() { return fmt.Errorf("deed: presentation proof created_at is in the future") } if p.Event.CreatedAt < now.Add(-maxAge).Unix() { return fmt.Errorf("deed: presentation proof is stale") } if p.Expires <= now.Unix() { return fmt.Errorf("deed: presentation proof expired") } if p.Expires > now.Add(maxAge).Unix() { return fmt.Errorf("deed: presentation proof expiration is too far in the future") } if o.Nonces == nil { return fmt.Errorf("deed: presentation proof requires a nonce cache") } if !o.Nonces.Use(hex.Enc(p.Event.Pubkey), p.Nonce) { return fmt.Errorf("deed: presentation proof nonce has already been used") } return nil } // sameServer compares a proof's server tag with this host. Both may be bare // hosts or full origins; the host names must match and a named port must match. func sameServer(a, b string) bool { ha, pa := hostPort(a) hb, pb := hostPort(b) if ha == "" || hb == "" { return false } if !strings.EqualFold(ha, hb) { return false } if pa != "" && pb != "" && pa != pb { return false } return true } func hostPort(raw string) (host, port string) { raw = strings.TrimSpace(raw) if !strings.Contains(raw, "://") { raw = "https://" + raw } u, err := url.Parse(raw) if err != nil || u.Host == "" { return "", "" } return strings.ToLower(u.Hostname()), u.Port() } // NonceCache remembers (pubkey, nonce) pairs for a bounded window. // // The cache is deliberately in memory: a durable write per GET is the same // latency problem the proof replaced. A restart loses the window, which only // means a proof that was valid at the restart may be accepted once more; the // proof's own expiration bounds that. type NonceCache struct { mu sync.Mutex ttl time.Duration seen map[string]int64 lastFlush time.Time } // NewNonceCache creates a cache whose entries live for ttl. func NewNonceCache(ttl time.Duration) *NonceCache { if ttl <= 0 { ttl = 10 * time.Minute } return &NonceCache{ttl: ttl, seen: make(map[string]int64), lastFlush: time.Now()} } // Use records a nonce and reports whether it was fresh. It is atomic, so two // concurrent requests with the same proof cannot both succeed. func (c *NonceCache) Use(pubkeyHex, nonce string) bool { key := pubkeyHex + "|" + nonce now := time.Now().Unix() c.mu.Lock() defer c.mu.Unlock() c.flushLocked(now) if exp, ok := c.seen[key]; ok && exp > now { return false } c.seen[key] = now + int64(c.ttl/time.Second) return true } // Flush prunes expired entries. Call it periodically from a service loop. func (c *NonceCache) Flush() { now := time.Now().Unix() c.mu.Lock() c.flushLocked(now) c.mu.Unlock() } func (c *NonceCache) flushLocked(now int64) { if now-c.lastFlush.Unix() < 60 && len(c.seen) < 100000 { return } for k, exp := range c.seen { if exp <= now { delete(c.seen, k) } } c.lastFlush = time.Unix(now, 0) } // Len reports the number of live entries, for tests and metrics. func (c *NonceCache) Len() int { c.mu.Lock() defer c.mu.Unlock() return len(c.seen) }