Skip to content

Commit

Permalink
Tweaked the NIP 42 Validation (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
barkyq authored Feb 9, 2023
1 parent 72386d2 commit 3ccef5e
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions nip42/nip42.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,33 +23,26 @@ func CreateUnsignedAuthEvent(challenge, pubkey, relayURL string) nostr.Event {
}
}

// helper function for ValidateAuthEvent
func parseUrl(input string) (*url.URL, error) {
return url.Parse(
strings.ToLower(
strings.TrimSuffix(input, "/"),
),
)
}

// ValidateAuthEvent checks whether event is a valid NIP-42 event for given challenge and relayURL.
// The result of the validation is encoded in the ok bool.
func ValidateAuthEvent(event *nostr.Event, challenge string, relayURL string) (pubkey string, ok bool) {
if ok, _ := event.CheckSignature(); !ok {
return "", false
}
if event.Kind != 22242 {
return "", false
}

now := time.Now()
if event.CreatedAt.After(now.Add(10*time.Minute)) || event.CreatedAt.Before(now.Add(-10*time.Minute)) {
return "", false
}

if event.Tags.GetFirst([]string{"challenge", challenge}) == nil {
return "", false
}

parseUrl := func(input string) (*url.URL, error) {
return url.Parse(
strings.ToLower(
strings.TrimSuffix(input, "/"),
),
)
}

expected, err := parseUrl(relayURL)
if err != nil {
return "", false
Expand All @@ -66,5 +59,16 @@ func ValidateAuthEvent(event *nostr.Event, challenge string, relayURL string) (p
return "", false
}

now := time.Now()
if event.CreatedAt.After(now.Add(10*time.Minute)) || event.CreatedAt.Before(now.Add(-10*time.Minute)) {
return "", false
}

// save for last, as it is most expensive operation
// no need to check returned error, since ok == true implies err == nil.
if ok, _ := event.CheckSignature(); !ok {
return "", false
}

return event.PubKey, true
}

0 comments on commit 3ccef5e

Please sign in to comment.