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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package trust
import (
"context"
"encoding/json"
"errors"
"slices"
"strings"
"sync"
"time"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/opt"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/ttlcache"
"github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/atproto"
"github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/cache"
"github.com/johnandersen777/socialweb-computer-kcp/internal/policyengine/models"
)
const (
VouchNSID = "sh.tangled.graph.vouch"
BadgeBlueKeysNSID = "com.publicdomainrelay.temp.badgeBlueKeys"
AssociationNSID = "com.publicdomainrelay.temp.market.association"
BskyPostNSID = "app.bsky.feed.post"
DelvePostNSID = "town.delve.feed.post"
MentionFacetType = "app.bsky.richtext.facet#mention"
MirrorRKey = "association"
BidderAssociate = "bidder_associate"
RequesterAssociate = "requester_associate"
defaultTrustCacheTTL = 5 * time.Minute
trustErrorTTL = 5 * time.Second
)
type Host interface {
Resolve(ctx context.Context, ref atproto.StrongRef) (map[string]any, error)
ResolveOperatorDid(ctx context.Context, did string) (string, bool, error)
Vouches(ctx context.Context, voucher, subject string) (bool, error)
Log(level, msg string, meta map[string]any)
}
type Snapshot struct {
OperatorOf map[string]string `json:"operatorOf"`
VouchedBy map[string][]string `json:"vouchedBy"`
TrustedOperators []string `json:"trustedOperators"`
}
type ResolverOptions struct {
Client *atproto.Client
Store *cache.Store
TTL time.Duration
Log func(level, msg string, meta map[string]any)
}
type operatorKey struct {
did string
service string
assoc associationKey
}
type operatorEntry struct {
value string
found bool
}
type vouchKey struct {
voucher string
subject string
}
type claim struct {
operator string
subject string
service string
}
type Resolver struct {
client *atproto.Client
store *cache.Store
log func(level, msg string, meta map[string]any)
now func() time.Time
ops *ttlcache.Cache[operatorKey, operatorEntry]
vouch *ttlcache.Cache[vouchKey, bool]
}
func NewResolver(opts ResolverOptions) *Resolver {
client := opts.Client
if client == nil {
client = atproto.NewClient()
}
ttl := opts.TTL
ttl = opt.Positive(ttl, defaultTrustCacheTTL)
log := opts.Log
if log == nil {
log = func(string, string, map[string]any) {}
}
return &Resolver{
client: client,
store: opts.Store,
log: log,
now: time.Now,
ops: ttlcache.New[operatorKey, operatorEntry](ttlcache.Options{TTL: ttl}),
vouch: ttlcache.New[vouchKey, bool](ttlcache.Options{TTL: ttl}),
}
}
func (r *Resolver) Resolve(ctx context.Context, ref atproto.StrongRef) (map[string]any, error) {
if r.store != nil {
if value, ok := cache.ReadRecord(r.store, ref); ok {
return value, nil
}
}
value, err := r.client.GetRecord(ctx, ref)
if err != nil {
return nil, err
}
if r.store != nil {
cache.WriteRecord(r.store, ref, value)
}
return value, nil
}
func (r *Resolver) getRecord(ctx context.Context, repo, collection, rkey string) (map[string]any, error) {
value, err := r.client.GetRecord(ctx, atproto.StrongRef{URI: "at://" + repo + "/" + collection + "/" + rkey})
if errors.Is(err, atproto.ErrRecordNotFound) {
return nil, nil
}
return value, err
}
func (r *Resolver) ResolveOperatorDid(ctx context.Context, did string) (string, bool, error) {
return r.ResolveOperatorDidFor(ctx, did, "")
}
func (r *Resolver) ResolveOperatorDidFor(ctx context.Context, did, service string) (string, bool, error) {
return r.ResolveOperatorDidWith(ctx, did, service, Association{})
}
func (r *Resolver) ResolveOperatorDidWith(ctx context.Context, did, service string, assoc Association) (string, bool, error) {
did = strings.TrimSpace(did)
service = strings.TrimSpace(service)
if did == "" {
return "", false, nil
}
if !associationRole(service) {
r.log("info", "resolveOperatorDid needs a role", map[string]any{"did": did, "service": service})
return "", false, nil
}
akey := assoc.key()
key := operatorKey{did: did, service: service, assoc: akey}
if entry, ok := r.ops.Get(key); ok {
return entry.value, entry.found, nil
}
operator, found, err := r.operatorOf(ctx, did, service, akey)
if err != nil {
if ctx.Err() != nil {
return "", false, ctx.Err()
}
r.log("warn", "resolveOperatorDid failed", map[string]any{"did": did, "service": service, "error": err.Error()})
r.ops.SetTTL(key, operatorEntry{}, trustErrorTTL)
return "", false, nil
}
r.ops.Set(key, operatorEntry{value: operator, found: found})
return operator, found, nil
}
func (r *Resolver) operatorOf(ctx context.Context, did, service string, assoc associationKey) (string, bool, error) {
mirror, ok, err := r.mirrorOf(ctx, did, service)
if err != nil || !ok {
return "", false, err
}
if mirror.hasProof {
if mirror.proof == nil {
_, err := r.deny("the mirror proof is not a strongRef", mirror.claim, nil)
return "", false, err
}
held, err := r.proofHeld(ctx, mirror.claim, *mirror.proof, assoc)
if err != nil || !held {
return "", false, err
}
return mirror.operator, true, nil
}
if assoc.association {
held, err := r.associationHeld(ctx, mirror.claim, assoc)
if err != nil {
return "", false, err
}
if held {
return mirror.operator, true, nil
}
}
if assoc.claim && !assoc.requireContract {
held, err := r.claimHeld(ctx, mirror.claim)
if err != nil {
return "", false, err
}
if held {
return mirror.operator, true, nil
}
}
r.log("info", "resolveOperatorDid unclaimed mirror", map[string]any{"did": did, "operator": mirror.operator, "service": mirror.service})
return "", false, nil
}
type mirrorRecord struct {
claim
proof *atproto.StrongRef
hasProof bool
}
func (r *Resolver) mirrorOf(ctx context.Context, did, service string) (mirrorRecord, bool, error) {
value, err := r.getRecord(ctx, did, BadgeBlueKeysNSID, MirrorRKey)
if err != nil || value == nil {
return mirrorRecord{}, false, err
}
held, ok := claimOf(value)
rawProof, hasProof := value["proof"]
proof, _ := strongRefOf(rawProof)
mirror := mirrorRecord{claim: held, proof: proof, hasProof: hasProof}
return mirror, ok && mirror.subject == did && mirror.operator != did && associationService(mirror.service, service), nil
}
func ClaimRKey(service, subject string) string {
return service + "-" + strings.ReplaceAll(subject, ":", "-")
}
func (r *Resolver) claimHeld(ctx context.Context, want claim) (bool, error) {
value, err := r.getRecord(ctx, want.operator, BadgeBlueKeysNSID, ClaimRKey(want.service, want.subject))
if err != nil {
return false, err
}
held, ok := claimOf(value)
return ok && held == want, nil
}
func claimOf(value map[string]any) (claim, bool) {
service, _ := value["service"].(string)
subject, _ := value["keyId"].(string)
operator, _ := value["challenge"].(string)
c := claim{operator: strings.TrimSpace(operator), subject: strings.TrimSpace(subject), service: strings.TrimSpace(service)}
return c, strings.HasPrefix(c.operator, "did:") && strings.HasPrefix(c.subject, "did:")
}
func associationRole(service string) bool {
return service == BidderAssociate || service == RequesterAssociate
}
func associationService(recordService, want string) bool {
return associationRole(want) && recordService == want
}
func (r *Resolver) Vouches(ctx context.Context, voucher, subject string) (bool, error) {
voucher = strings.TrimSpace(voucher)
subject = strings.TrimSpace(subject)
if voucher == "" || !strings.HasPrefix(subject, "did:") {
return false, nil
}
key := vouchKey{voucher: voucher, subject: subject}
if vouched, ok := r.vouch.Get(key); ok {
return vouched, nil
}
value, err := r.getRecord(ctx, voucher, VouchNSID, subject)
if err != nil {
if ctx.Err() != nil {
return false, ctx.Err()
}
r.log("warn", "vouches failed", map[string]any{"voucher": voucher, "subject": subject, "error": err.Error()})
return false, nil
}
kind, _ := value["kind"].(string)
vouched := value != nil && kind != "denounce"
r.vouch.Set(key, vouched)
return vouched, nil
}
func (r *Resolver) Log(level, msg string, meta map[string]any) {
r.log(level, msg, meta)
}
func (r *Resolver) ApplyEvent(did, rkey string) {
r.ops.DeleteKeys(func(key operatorKey) bool { return key.did == did })
r.vouch.DeleteKeys(func(key vouchKey) bool {
return (did != "" && key.voucher == did) || (rkey != "" && key.voucher == rkey)
})
}
func (r *Resolver) Invalidate() {
r.ops.DeleteKeys(func(operatorKey) bool { return true })
r.vouch.DeleteKeys(func(vouchKey) bool { return true })
}
type opResult struct {
did string
operator string
found bool
err error
}
type vouchResult struct {
voucher string
subject string
vouched bool
err error
}
type ServiceOperatorResolver interface {
ResolveOperatorDidFor(ctx context.Context, did, service string) (string, bool, error)
}
type AssociationOperatorResolver interface {
ResolveOperatorDidWith(ctx context.Context, did, service string, assoc Association) (string, bool, error)
}
func BuildSnapshotFor(ctx context.Context, host Host, selfDid, counterpartyDid, selfService, counterpartyService string) (Snapshot, error) {
return BuildSnapshotWith(ctx, host, selfDid, counterpartyDid, selfService, counterpartyService, Association{})
}
func BuildSnapshotWith(ctx context.Context, host Host, selfDid, counterpartyDid, selfService, counterpartyService string, assoc Association) (Snapshot, error) {
snapshot := Snapshot{
OperatorOf: make(map[string]string),
VouchedBy: make(map[string][]string),
TrustedOperators: []string{},
}
if host == nil {
return snapshot, nil
}
var wg sync.WaitGroup
defer wg.Wait()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
roleResolver, _ := host.(ServiceOperatorResolver)
assocResolver, _ := host.(AssociationOperatorResolver)
selfAssoc := assoc
selfAssoc.RequireContract = false
resolve := func(did, service string) (string, bool, error) {
if assocResolver != nil {
if did == selfDid {
return assocResolver.ResolveOperatorDidWith(ctx, did, service, selfAssoc)
}
return assocResolver.ResolveOperatorDidWith(ctx, did, service, assoc)
}
if roleResolver != nil {
return roleResolver.ResolveOperatorDidFor(ctx, did, service)
}
return "", false, nil
}
dids := []string{selfDid}
if counterpartyDid != "" && counterpartyDid != selfDid {
dids = append(dids, counterpartyDid)
}
results := make(chan opResult, len(dids))
for _, did := range dids {
service := selfService
if did == counterpartyDid {
service = counterpartyService
}
wg.Go(func() {
operator, found, err := resolve(did, service)
results <- opResult{did: did, operator: operator, found: found, err: err}
})
}
operators := make(map[string]string, len(dids))
for range dids {
result := <-results
if result.err != nil {
return snapshot, result.err
}
if result.did == selfDid {
if result.found && result.operator != "" {
operators[selfDid] = result.operator
} else {
operators[selfDid] = selfDid
}
continue
}
if result.found && result.operator != "" {
operators[result.did] = result.operator
}
}
snapshot.OperatorOf = operators
trusted := []string{selfDid}
if operator := operators[selfDid]; operator != "" && operator != selfDid {
trusted = append(trusted, operator)
}
snapshot.TrustedOperators = trusted
vouchers := distinct(append(append([]string(nil), trusted...), counterpartyDid, operators[counterpartyDid]))
subjects := distinct([]string{selfDid, operators[selfDid], counterpartyDid, operators[counterpartyDid]})
pairs := 0
vouchResults := make(chan vouchResult, len(vouchers)*len(subjects))
for _, voucher := range vouchers {
snapshot.VouchedBy[voucher] = []string{}
for _, subject := range subjects {
if subject == voucher {
continue
}
pairs++
wg.Go(func() {
vouched, err := host.Vouches(ctx, voucher, subject)
vouchResults <- vouchResult{voucher: voucher, subject: subject, vouched: vouched, err: err}
})
}
}
for range pairs {
result := <-vouchResults
if result.err != nil {
return snapshot, result.err
}
if result.vouched {
snapshot.VouchedBy[result.voucher] = append(snapshot.VouchedBy[result.voucher], result.subject)
}
}
for _, list := range snapshot.VouchedBy {
slices.Sort(list)
}
return snapshot, nil
}
func distinct(values []string) []string {
seen := make(map[string]bool, len(values))
out := make([]string, 0, len(values))
for _, value := range values {
if value == "" || seen[value] {
continue
}
seen[value] = true
out = append(out, value)
}
return out
}
func (s Snapshot) ActionVouchedBy() map[string][]string {
out := make(map[string][]string, len(s.VouchedBy))
for voucher, list := range s.VouchedBy {
out[voucher] = slices.Clone(list)
}
if len(s.TrustedOperators) == 0 {
return out
}
self := s.TrustedOperators[0]
merged := []string{}
for _, operator := range s.TrustedOperators {
merged = append(merged, s.VouchedBy[operator]...)
}
slices.Sort(merged)
out[self] = slices.Compact(merged)
return out
}
func (s Snapshot) CacheFiles() models.CacheEntry {
operatorOf, _ := json.Marshal(s.OperatorOf)
vouchedBy, _ := json.Marshal(s.ActionVouchedBy())
trustedOperators, _ := json.Marshal(s.TrustedOperators)
return models.CacheEntry{
"operatorOf.json": {Data: string(operatorOf), Encoding: models.CacheEncodingText},
"vouchedBy.json": {Data: string(vouchedBy), Encoding: models.CacheEncodingText},
"trustedOperators.json": {Data: string(trustedOperators), Encoding: models.CacheEncodingText},
}
}