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 market
import (
"context"
"crypto/sha256"
"fmt"
"sync"
"github.com/mr-tron/base58"
)
func Base58BTCEncode(b []byte) string {
return base58.Encode(b)
}
func BadgeBlueKeysRkey(did, keyID string) string {
sum := sha256.Sum256([]byte(did + ":" + keyID))
rkey := base58.Encode(sum[:24])
if len(rkey) > 32 {
rkey = rkey[:32]
}
return rkey
}
func KeyBoundByBadgeBlueKey(ctx context.Context, getter RecordGetter, did, key string) bool {
if getter == nil {
return false
}
rkey := BadgeBlueKeysRkey(did, key)
rec, err := getter.GetRecord(ctx, did, BadgeBlueKeysNSID, rkey)
if err != nil {
return false
}
keyID, _ := rec.Value["keyId"].(string)
challenge, _ := rec.Value["challenge"].(string)
return keyID == key && challenge == did
}
type BadgeBlueKeyBinding struct {
getter RecordGetter
mu sync.Mutex
cache map[string]bool
}
func NewBadgeBlueKeyBinding(getter RecordGetter) *BadgeBlueKeyBinding {
return &BadgeBlueKeyBinding{getter: getter, cache: map[string]bool{}}
}
func (b *BadgeBlueKeyBinding) Check(ctx context.Context, did, key string) (bool, error) {
cacheKey := did + "#" + key
b.mu.Lock()
cached, ok := b.cache[cacheKey]
b.mu.Unlock()
if ok {
return cached, nil
}
bound := KeyBoundByBadgeBlueKey(ctx, b.getter, did, key)
b.mu.Lock()
b.cache[cacheKey] = bound
b.mu.Unlock()
return bound, nil
}
type BadgeBlueKeysRecordOptions struct {
DID string
KeyID string
Service string
CreatedAt string
}
func BuildBadgeBlueKeysRecord(opts BadgeBlueKeysRecordOptions) BadgeBlueKeys {
return BadgeBlueKeys{KeyID: opts.KeyID, Challenge: opts.DID, Service: opts.Service, CreatedAt: isoOrNow(opts.CreatedAt)}
}
func CreateBadgeBlueKeysRecord(ctx context.Context, w RecordWriter, opts BadgeBlueKeysRecordOptions) (StrongRef, error) {
if w == nil {
return StrongRef{}, fmt.Errorf("%w: nil writer", ErrInvalidRecord)
}
if opts.DID == "" || opts.KeyID == "" {
return StrongRef{}, fmt.Errorf("%w: badgeBlueKeys needs did and keyId", ErrInvalidRecord)
}
record, err := EncodeRecord(BuildBadgeBlueKeysRecord(opts))
if err != nil {
return StrongRef{}, err
}
return w.PutRecord(ctx, opts.DID, BadgeBlueKeysNSID, BadgeBlueKeysRkey(opts.DID, opts.KeyID), record)
}