go-nostr/nip05/nip05.go

91 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-05-04 11:15:26 -03:00
package nip05
import (
"context"
"encoding/hex"
2022-05-04 11:15:26 -03:00
"encoding/json"
"fmt"
"net/http"
"strings"
2023-02-05 16:25:00 -03:00
"github.com/nbd-wtf/go-nostr"
2022-05-04 11:15:26 -03:00
)
2022-11-26 19:31:49 -03:00
type (
2023-02-05 16:22:41 -03:00
name2KeyMap map[string]string
key2RelaysMap map[string][]string
2022-11-26 19:31:49 -03:00
)
type WellKnownResponse struct {
2023-02-05 16:22:41 -03:00
Names name2KeyMap `json:"names"` // NIP-05
Relays key2RelaysMap `json:"relays"` // NIP-35
2022-11-26 19:31:49 -03:00
}
func QueryIdentifier(ctx context.Context, fullname string) (*nostr.ProfilePointer, error) {
2022-05-04 11:15:26 -03:00
spl := strings.Split(fullname, "@")
var name, domain string
switch len(spl) {
case 1:
name = "_"
domain = spl[0]
case 2:
name = spl[0]
domain = spl[1]
default:
return nil, fmt.Errorf("not a valid nip-05 identifier")
}
if strings.Index(domain, ".") == -1 {
return nil, fmt.Errorf("hostname doesn't have a dot")
2022-05-04 11:15:26 -03:00
}
req, err := http.NewRequestWithContext(ctx, "GET",
fmt.Sprintf("https://%s/.well-known/nostr.json?name=%s", domain, name), nil)
if err != nil {
return nil, fmt.Errorf("failed to create a request: %w", err)
}
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
res, err := client.Do(req)
2022-05-04 11:15:26 -03:00
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
2022-05-04 11:15:26 -03:00
}
defer res.Body.Close()
2022-05-04 11:15:26 -03:00
2022-11-26 19:31:49 -03:00
var result WellKnownResponse
2022-05-04 11:15:26 -03:00
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("failed to decode json response: %w", err)
2022-05-04 11:15:26 -03:00
}
pubkey, ok := result.Names[name]
if !ok {
return &nostr.ProfilePointer{}, nil
}
if len(pubkey) == 64 {
if _, err := hex.DecodeString(pubkey); err != nil {
return &nostr.ProfilePointer{}, nil
}
}
2023-02-05 16:25:00 -03:00
relays, _ := result.Relays[pubkey]
return &nostr.ProfilePointer{
PublicKey: pubkey,
Relays: relays,
}, nil
2022-05-04 11:15:26 -03:00
}
func NormalizeIdentifier(fullname string) string {
if strings.HasPrefix(fullname, "_@") {
return fullname[2:]
}
return fullname
}