package atproto import ( "context" "encoding/json" "fmt" "io" "net" "net/http" "strings" "time" ) const DefaultPLCURL = "https://plc.directory" type DIDService struct { ID string `json:"id"` Type string `json:"type"` ServiceEndpoint string `json:"serviceEndpoint"` } type DIDDocument struct { ID string `json:"id"` AlsoKnownAs []string `json:"alsoKnownAs"` Service []DIDService `json:"service"` } // PDSEndpoint returns the account's PDS URL from the DID document. func (d *DIDDocument) PDSEndpoint() (string, bool) { for _, svc := range d.Service { if strings.HasSuffix(svc.ID, "#atproto_pds") && svc.Type == "AtprotoPersonalDataServer" { return strings.TrimRight(svc.ServiceEndpoint, "/"), svc.ServiceEndpoint != "" } } return "", false } // Handle returns the first at:// alias claimed by the DID document. func (d *DIDDocument) Handle() (string, bool) { for _, aka := range d.AlsoKnownAs { if h, ok := strings.CutPrefix(aka, "at://"); ok && h != "" { return h, true } } return "", false } func httpClientOrDefault(client *http.Client) *http.Client { if client == nil { return &http.Client{Timeout: 15 * time.Second} } return client } func getJSON(ctx context.Context, client *http.Client, endpoint string, out any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return err } req.Header.Set("Accept", "application/json") resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return err } if resp.StatusCode != http.StatusOK { return fmt.Errorf("GET %s failed (%d): %s", endpoint, resp.StatusCode, strings.TrimSpace(string(body))) } if err := json.Unmarshal(body, out); err != nil { return fmt.Errorf("decode %s: %w", endpoint, err) } return nil } // FetchDIDDocument resolves a did:plc (via plcURL) or did:web DID. func FetchDIDDocument(ctx context.Context, client *http.Client, plcURL, did string) (*DIDDocument, error) { client = httpClientOrDefault(client) var endpoint string switch { case strings.HasPrefix(did, "did:plc:"): if plcURL == "" { plcURL = DefaultPLCURL } endpoint = strings.TrimRight(plcURL, "/") + "/" + did case strings.HasPrefix(did, "did:web:"): rest := strings.TrimPrefix(did, "did:web:") parts := strings.Split(rest, ":") host := parts[0] if len(parts) == 1 { endpoint = "https://" + host + "/.well-known/did.json" } else { endpoint = "https://" + host + "/" + strings.Join(parts[1:], "/") + "/did.json" } default: return nil, fmt.Errorf("unsupported DID method in %q (want did:plc or did:web)", did) } var doc DIDDocument if err := getJSON(ctx, client, endpoint, &doc); err != nil { return nil, err } if doc.ID != did { return nil, fmt.Errorf("DID document id %q does not match requested %q", doc.ID, did) } return &doc, nil } func resolveHandleDNS(ctx context.Context, handle string) (string, error) { records, err := net.DefaultResolver.LookupTXT(ctx, "_atproto."+handle) if err != nil { return "", err } for _, rec := range records { if did, ok := strings.CutPrefix(rec, "did="); ok && strings.HasPrefix(did, "did:") { return did, nil } } return "", fmt.Errorf("no did= TXT record at _atproto.%s", handle) } func resolveHandleWellKnown(ctx context.Context, client *http.Client, baseURL string) (string, error) { endpoint := strings.TrimRight(baseURL, "/") + "/.well-known/atproto-did" req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return "", err } resp, err := client.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return "", err } if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("GET %s failed (%d)", endpoint, resp.StatusCode) } did := strings.TrimSpace(strings.SplitN(string(body), "\n", 2)[0]) if !strings.HasPrefix(did, "did:") { return "", fmt.Errorf("%s did not return a DID", endpoint) } return did, nil } // ResolveHandle resolves a handle to its DID, trying DNS TXT first and // then the HTTPS well-known endpoint (per the atproto Handle spec). func ResolveHandle(ctx context.Context, client *http.Client, handle string) (string, error) { client = httpClientOrDefault(client) handle = strings.ToLower(strings.TrimSpace(strings.TrimPrefix(handle, "@"))) if handle == "" || !strings.Contains(handle, ".") { return "", fmt.Errorf("invalid handle %q", handle) } if did, err := resolveHandleDNS(ctx, handle); err == nil { return did, nil } return resolveHandleWellKnown(ctx, client, "https://"+handle) } // ResolveIdentifier resolves a user-supplied handle or DID to a DID // document. For handles it bidirectionally verifies that the DID // document claims the handle, as the OAuth spec mandates. func ResolveIdentifier(ctx context.Context, client *http.Client, plcURL, identifier string) (did, handle string, doc *DIDDocument, err error) { client = httpClientOrDefault(client) identifier = strings.TrimSpace(identifier) if strings.HasPrefix(identifier, "did:") { doc, err := FetchDIDDocument(ctx, client, plcURL, identifier) if err != nil { return "", "", nil, err } handle, _ = doc.Handle() return identifier, handle, doc, nil } handle = strings.ToLower(strings.TrimPrefix(identifier, "@")) did, err = ResolveHandle(ctx, client, handle) if err != nil { return "", "", nil, fmt.Errorf("resolve handle %q: %w", handle, err) } doc, err = FetchDIDDocument(ctx, client, plcURL, did) if err != nil { return "", "", nil, err } claimed, ok := doc.Handle() if !ok || !strings.EqualFold(claimed, handle) { return "", "", nil, fmt.Errorf("DID document for %s does not claim handle %q", did, handle) } return did, handle, doc, nil }