Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tweaked the NIP 42 Validation #58

Merged
merged 3 commits into from
Feb 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}