package main import ( "context" "encoding/json" "flag" "fmt" "log/slog" "net/http" "net/url" "os" "os/exec" "path" "path/filepath" "strings" "tangled.org/core/cmd/claimer/emit" tlog "tangled.org/core/log" ) var ( outFile = flag.String("out", "/tmp/claimer-claims.sql", "where to write the emitted claim SQL") pdsHost = flag.String("pds", "https://tngl.sh", "PDS host URL") dryRun = flag.Bool("dry-run", false, "print what would be done without emitting SQL") verbose = flag.Bool("v", false, "log pagination progress") apply = flag.Bool("apply", false, "execute the emitted SQL against D1 via wrangler") yes = flag.Bool("yes", false, "required together with -apply as a destructive-action gate") local = flag.Bool("local", false, "apply against the local D1 instead of remote") d1Name = flag.String("d1", "tangled-sites", "D1 database name for wrangler d1 execute") ) type repo struct { DID string `json:"did"` Head string `json:"head"` } type listReposResponse struct { Cursor string `json:"cursor"` Repos []repo `json:"repos"` } type describeRepoResponse struct { Handle string `json:"handle"` DID string `json:"did"` } func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: claimer [flags]\n\n") fmt.Fprintf(os.Stderr, "Backfills domain_claims for all existing users on the tngl.sh PDS.\n") fmt.Fprintf(os.Stderr, "DIDs are fetched via com.atproto.sync.listRepos, handles are resolved\n") fmt.Fprintf(os.Stderr, "via com.atproto.repo.describeRepo (no DNS verification required).\n") fmt.Fprintf(os.Stderr, "Claims are emitted as literal INSERT OR IGNORE SQL for D1.\n\n") fmt.Fprintf(os.Stderr, "Flags:\n") flag.PrintDefaults() } flag.Parse() ctx := context.Background() logger := tlog.New("claimer") ctx = tlog.IntoContext(ctx, logger) pdsDomain, err := domainFromURL(*pdsHost) if err != nil { logger.Error("invalid pds host", "host", *pdsHost, "error", err) os.Exit(1) } logger.Info("starting claimer", "pds", *pdsHost, "pds_domain", pdsDomain, "out", *outFile, "dry_run", *dryRun, ) dids, err := fetchAllDIDs(ctx, *pdsHost, logger) if err != nil { logger.Error("failed to fetch repos from PDS", "error", err) os.Exit(1) } logger.Info("fetched repos", "count", len(dids)) suffix := "." + pdsDomain var ( rows [][]emit.Cell skipped int errCount int ) var b strings.Builder for _, did := range dids { handle, err := describeRepo(ctx, *pdsHost, did) if err != nil { logger.Error("failed to describe repo", "did", did, "error", err) errCount++ continue } if !strings.HasSuffix(handle, suffix) { logger.Info("skipping account: handle does not match pds domain", "did", did, "handle", handle, "suffix", suffix) skipped++ continue } if !claimableHandle(handle, pdsDomain) { logger.Warn("skipping account: handle fails the sites-domain label rules", "did", did, "handle", handle) skipped++ continue } if !strings.HasSuffix(handle, ".tngl.sh") { logger.Warn("skipping account: only tngl.sh handle domains are claimed by the backfill", "did", did, "handle", handle) skipped++ continue } if *dryRun { logger.Info("[dry-run] would claim domain", "did", did, "domain", handle) continue } if !handleIsPermanent(handle) { logger.Error("internal invariant broken: non-permanent handle reached emission", "did", did, "handle", handle) continue } writeClaimSQL(&b, did, handle) rows = append(rows, []emit.Cell{{V: did}, {V: handle}, {Nil: true}}) logger.Info("would claim domain", "did", did, "domain", handle) } if *dryRun { logger.Info("dry run finished", "dids", len(dids), "skipped", skipped, "errors", errCount) if errCount > 0 { os.Exit(1) } return } emit.Insert(&b, "INSERT OR IGNORE INTO domain_claims (did, domain, deleted) VALUES ", rows) absOut, err := filepath.Abs(*outFile) if err != nil { logger.Error("resolving output path", "path", *outFile, "error", err) os.Exit(1) } if err := os.WriteFile(absOut, []byte(b.String()), 0o644); err != nil { logger.Error("writing output", "path", absOut, "error", err) os.Exit(1) } if *apply && !*yes { logger.Error("-apply is destructive for the target D1 tables; pass -yes to confirm") os.Exit(1) } if *apply && len(rows) > 0 { args := []string{"wrangler", "d1", "execute", *d1Name, "--file", absOut} if !*local { args = append(args, "--remote") } cmd := exec.CommandContext(ctx, "npx", args...) cmd.Dir = sitesDir() out, err := cmd.CombinedOutput() if err != nil { logger.Error("applying claims to D1 failed", "error", err, "output", strings.TrimSpace(string(out)), ) os.Exit(1) } logger.Info("applied claims to D1", "out", absOut, "d1", *d1Name, "local", *local) } logger.Info("claimer finished", slog.Group("results", "claims", len(rows), "skipped", skipped, "errors", errCount, ), "out", *outFile, ) if errCount > 0 { os.Exit(1) } } func writeClaimSQL(b *strings.Builder, did, handle string) { cutoff := "strftime('%Y-%m-%dT%H:%M:%SZ', 'now', '-30 days')" b.WriteString("UPDATE domain_claims SET deleted = NULL WHERE domain = ") b.WriteString(emit.Esc(handle)) b.WriteString(" AND did = ") b.WriteString(emit.Esc(did)) b.WriteString(" AND deleted IS NOT NULL;\n") b.WriteString("DELETE FROM domain_claims WHERE domain = ") b.WriteString(emit.Esc(handle)) b.WriteString(" AND did != ") b.WriteString(emit.Esc(did)) b.WriteString(" AND deleted IS NOT NULL AND deleted < ") b.WriteString(cutoff) b.WriteString(";\n") b.WriteString("UPDATE domain_claims SET domain = ") b.WriteString(emit.Esc(handle)) b.WriteString(", deleted = NULL WHERE did = ") b.WriteString(emit.Esc(did)) b.WriteString(" AND domain != ") b.WriteString(emit.Esc(handle)) b.WriteString(" AND deleted IS NOT NULL AND deleted < ") b.WriteString(cutoff) b.WriteString(";\n") } func sitesDir() string { wd, err := os.Getwd() if err != nil { return "sites" } for dir := wd; ; dir = path.Dir(dir) { if _, err := os.Stat(path.Join(dir, "sites", "wrangler.toml")); err == nil { return path.Join(dir, "sites") } if dir == path.Dir(dir) || len(dir) < len(wd)-len("core")-2 { break } } return "sites" } func handleIsPermanent(handle string) bool { return strings.HasSuffix(handle, ".tngl.sh") } func claimableHandle(handle, pdsDomain string) bool { label := strings.TrimSuffix(handle, "."+pdsDomain) if label == "" || len(label) > 63 || strings.Contains(label, ".") { return false } bytes := []byte(label) if bytes[0] == '-' || bytes[len(bytes)-1] == '-' { return false } for _, c := range bytes { if !((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') { return false } } return true } func fetchAllDIDs(ctx context.Context, pdsHost string, logger *slog.Logger) ([]string, error) { var all []string cursor := "" for { batch, nextCursor, err := listRepos(ctx, pdsHost, cursor) if err != nil { return nil, err } for _, r := range batch { all = append(all, r.DID) } if *verbose { logger.Info("fetched page", "count", len(batch), "total", len(all), "next_cursor", nextCursor) } if nextCursor == "" || nextCursor == cursor { break } cursor = nextCursor } return all, nil } func listRepos(ctx context.Context, pdsHost, cursor string) ([]repo, string, error) { params := url.Values{} params.Set("limit", "100") if cursor != "" { params.Set("cursor", cursor) } endpoint := pdsHost + "/xrpc/com.atproto.sync.listRepos?" + params.Encode() req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, "", fmt.Errorf("building listRepos request: %w", err) } resp, err := http.DefaultClient.Do(req) if err != nil { return nil, "", fmt.Errorf("executing listRepos request: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { var errBody struct { Error string `json:"error"` Message string `json:"message"` } json.NewDecoder(resp.Body).Decode(&errBody) return nil, "", fmt.Errorf("PDS returned %d: %s — %s", resp.StatusCode, errBody.Error, errBody.Message) } var result listReposResponse if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { return nil, "", fmt.Errorf("decoding listRepos response: %w", err) } return result.Repos, result.Cursor, nil } func describeRepo(ctx context.Context, pdsHost, did string) (string, error) { params := url.Values{} params.Set("repo", did) endpoint := pdsHost + "/xrpc/com.atproto.repo.describeRepo?" + params.Encode() req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return "", fmt.Errorf("building describeRepo request: %w", err) } resp, err := http.DefaultClient.Do(req) if err != nil { return "", fmt.Errorf("executing describeRepo request: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { var errBody struct { Error string `json:"error"` Message string `json:"message"` } json.NewDecoder(resp.Body).Decode(&errBody) return "", fmt.Errorf("PDS returned %d: %s — %s", resp.StatusCode, errBody.Error, errBody.Message) } var result describeRepoResponse if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { return "", fmt.Errorf("decoding describeRepo response: %w", err) } return result.Handle, nil } func domainFromURL(rawURL string) (string, error) { if !strings.Contains(rawURL, "://") { return rawURL, nil } u, err := url.Parse(rawURL) if err != nil { return "", err } host := u.Hostname() if host == "" { return "", fmt.Errorf("no hostname in URL %q", rawURL) } return host, nil }