summaryrefslogtreecommitdiffstats
path: root/internal/auth/credentials.go
blob: 6019a287cd6fb6f0e6d599c34704b335394ff208 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package auth

import (
	"context"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"time"

	"code.northwest.io/nostr"
)

// NostrCredentials implements credentials.PerRPCCredentials for NIP-98 auth.
type NostrCredentials struct {
	key            *nostr.Key
	includePayload bool
}

func NewNostrCredentials(key *nostr.Key) *NostrCredentials {
	return &NostrCredentials{
		key:            key,
		includePayload: false,
	}
}

func NewNostrCredentialsWithPayload(key *nostr.Key) *NostrCredentials {
	return &NostrCredentials{
		key:            key,
		includePayload: true,
	}
}

func (n *NostrCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	if len(uri) == 0 {
		return nil, fmt.Errorf("no URI provided")
	}

	event := &nostr.Event{
		PubKey:    n.key.Public(),
		CreatedAt: time.Now().Unix(),
		Kind:      27235,
		Tags:      nostr.Tags{},
		Content:   "",
	}

	event.Tags = append(event.Tags, nostr.Tag{"u", uri[0]})
	event.Tags = append(event.Tags, nostr.Tag{"method", "POST"})

	if err := n.key.Sign(event); err != nil {
		return nil, fmt.Errorf("failed to sign auth event: %w", err)
	}

	eventJSON, err := json.Marshal(event)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal auth event: %w", err)
	}

	authHeader := "Nostr " + base64.StdEncoding.EncodeToString(eventJSON)

	return map[string]string{
		"authorization": authHeader,
	}, nil
}

func (n *NostrCredentials) RequireTransportSecurity() bool {
	return false
}

type NostrCredentialsWithTLS struct {
	*NostrCredentials
}

func NewNostrCredentialsWithTLS(key *nostr.Key) *NostrCredentialsWithTLS {
	return &NostrCredentialsWithTLS{
		NostrCredentials: NewNostrCredentials(key),
	}
}

func (n *NostrCredentialsWithTLS) RequireTransportSecurity() bool {
	return true
}

func HashPayload(payload []byte) string {
	hash := sha256.Sum256(payload)
	return fmt.Sprintf("%x", hash)
}