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

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0
93 lines · 2.7 KB Raw History
package pds

import (
	"net"
	"net/http"
	"strings"

	"github.com/bluesky-social/indigo/atproto/syntax"

	"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/httpjson"
)

func (s *Server) handleWellKnownDID(w http.ResponseWriter, r *http.Request) {
	did := s.serviceDID
	if account := s.accountOfHost(r); account != "" {
		did = account
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte(did))
}

// handleResolveHandle is com.atproto.identity.resolveHandle for this PDS's own accounts: a market network's DNS answers
// _atproto TXT from it (plan 0045)
func (s *Server) handleResolveHandle(w http.ResponseWriter, r *http.Request) {
	handle, err := syntax.ParseHandle(strings.ToLower(strings.TrimSpace(r.URL.Query().Get("handle"))))
	if err != nil {
		writeXRPCError(w, http.StatusBadRequest, "InvalidRequest", "handle: "+err.Error())
		return
	}
	did := s.accountDID(r, handle.String())
	if did == "" {
		writeXRPCError(w, http.StatusBadRequest, "HandleNotFound", "no account holds "+handle.String())
		return
	}
	httpjson.Write(w, http.StatusOK, map[string]string{"did": did})
}

func (s *Server) accountDID(r *http.Request, handle string) string {
	if s.store == nil {
		return ""
	}
	acct, err := s.store.GetAccountByIdentifier(r.Context(), handle)
	if err != nil || acct == nil || !strings.EqualFold(acct.Handle, handle) {
		return ""
	}
	return acct.DID.String()
}

func (s *Server) accountOfHost(r *http.Request) string {
	host := r.Host
	if h, _, err := net.SplitHostPort(host); err == nil {
		host = h
	}
	handle, err := syntax.ParseHandle(strings.ToLower(strings.TrimSuffix(host, ".")))
	if err != nil {
		return ""
	}
	return s.accountDID(r, handle.String())
}

func (s *Server) handleWellKnownDIDDocument(w http.ResponseWriter, r *http.Request) {
	doc := map[string]any{
		"@context": []string{
			"https://www.w3.org/ns/did/v1",
			"https://w3id.org/security/multikey/v1",
		},
		"id": s.serviceDID,
	}
	if len(s.cfg.AlsoKnownAs) > 0 {
		doc["alsoKnownAs"] = append([]string(nil), s.cfg.AlsoKnownAs...)
	}
	if s.cfg.OAuth != nil && s.cfg.OAuth.Signer.Key != nil {
		if pub, err := s.cfg.OAuth.Signer.Key.PublicKey(); err == nil {
			doc["verificationMethod"] = []map[string]any{{
				"id":                 s.serviceDID + "#atproto",
				"type":               "Multikey",
				"controller":         s.serviceDID,
				"publicKeyMultibase": pub.Multibase(),
			}}
		}
	}
	endpoint := s.cfg.PublicBaseURL
	if endpoint == "" {
		endpoint = s.publicURL(r)
	}
	doc["service"] = []map[string]any{{
		"id":              "#atproto_pds",
		"type":            "AtprotoPersonalDataServer",
		"serviceEndpoint": endpoint,
	}}
	httpjson.Write(w, http.StatusOK, doc)
}