~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
172 lines · 4.0 KB Raw History
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"sort"
	"strings"
	"sync"

	"github.com/bluesky-social/indigo/atproto/atcrypto"
	"github.com/bluesky-social/indigo/atproto/identity"
	"github.com/bluesky-social/indigo/atproto/syntax"
	"github.com/did-method-plc/go-didplc"
)

func readFile(path string) ([]byte, error) { return os.ReadFile(path) }

// failures collects check failures; every checker exits non-zero if any were recorded.
type failures struct {
	mu    sync.Mutex
	items []string
}

func (f *failures) add(format string, args ...any) {
	msg := fmt.Sprintf(format, args...)
	f.mu.Lock()
	f.items = append(f.items, msg)
	f.mu.Unlock()
	fmt.Fprintln(os.Stderr, "FAIL", msg)
}

func (f *failures) count() int {
	f.mu.Lock()
	defer f.mu.Unlock()
	return len(f.items)
}

func (f *failures) list() []string {
	f.mu.Lock()
	defer f.mu.Unlock()
	return append([]string{}, f.items...)
}

// resolver resolves DIDs through the harness PLC directory over plain HTTP.
// goat and indigo's default directory refuse loopback and private addresses,
// which is why the checkers carry their own.
type resolver struct {
	plc string
}

func (r resolver) doc(ctx context.Context, did string) (*identity.DIDDocument, error) {
	var doc identity.DIDDocument
	if err := getJSON(ctx, r.plc+"/"+url.PathEscape(did), &doc); err != nil {
		return nil, err
	}
	return &doc, nil
}

func (r resolver) lookup(ctx context.Context, did string) (*identity.Identity, error) {
	doc, err := r.doc(ctx, did)
	if err != nil {
		return nil, err
	}
	ident := identity.ParseIdentity(doc)
	return &ident, nil
}

// historicKeys returns every atproto signing key the DID has ever published,
// newest first, so a replay that starts before a key rotation still verifies.
func (r resolver) historicKeys(ctx context.Context, did string) ([]atcrypto.PublicKey, error) {
	var ops []didplc.OpEnum
	if err := getJSON(ctx, r.plc+"/"+url.PathEscape(did)+"/log", &ops); err != nil {
		return nil, err
	}
	var out []atcrypto.PublicKey
	for i := len(ops) - 1; i >= 0; i-- {
		if ops[i].Regular == nil {
			continue
		}
		dk, ok := ops[i].Regular.VerificationMethods["atproto"]
		if !ok {
			continue
		}
		pk, err := atcrypto.ParsePublicDIDKey(dk)
		if err != nil {
			return nil, err
		}
		out = append(out, pk)
	}
	return out, nil
}

func getJSON(ctx context.Context, u string, v any) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	if err != nil {
		return err
	}
	resp, err := plcClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf("GET %s: %d %s", u, resp.StatusCode, strings.TrimSpace(string(body)))
	}
	return json.Unmarshal(body, v)
}

func getBytes(ctx context.Context, u string) ([]byte, http.Header, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	if err != nil {
		return nil, nil, err
	}
	resp, err := repoClient.Do(req)
	if err != nil {
		return nil, nil, err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(io.LimitReader(resp.Body, 256<<20))
	if err != nil {
		return nil, nil, err
	}
	if resp.StatusCode != 200 {
		return nil, resp.Header, fmt.Errorf("GET %s: %d %s", u, resp.StatusCode, strings.TrimSpace(string(body)))
	}
	return body, resp.Header, nil
}

func xrpcURL(base, method string, params map[string]string) string {
	q := url.Values{}
	for k, v := range params {
		if v != "" {
			q.Set(k, v)
		}
	}
	u := strings.TrimRight(base, "/") + "/xrpc/" + method
	if len(q) > 0 {
		u += "?" + q.Encode()
	}
	return u
}

func sortedKeys[V any](m map[string]V) []string {
	out := make([]string, 0, len(m))
	for k := range m {
		out = append(out, k)
	}
	sort.Strings(out)
	return out
}

func validDID(s string) bool {
	_, err := syntax.ParseDID(s)
	return err == nil
}

func writeJSONFile(path string, v any) error {
	b, err := json.MarshalIndent(v, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(path, append(b, '\n'), 0o644)
}