A community based topic aggregation platform built on atproto
1package communities
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/base64"
7 "fmt"
8 "strings"
9
10 "github.com/bluesky-social/indigo/api/atproto"
11 comatproto "github.com/bluesky-social/indigo/api/atproto"
12 "github.com/bluesky-social/indigo/xrpc"
13)
14
15// CommunityPDSAccount represents PDS account credentials for a community
16type CommunityPDSAccount struct {
17 DID string // Community's DID (owns the repository)
18 Handle string // Community's handle (e.g., gaming.community.coves.social)
19 Email string // System email for PDS account
20 Password string // Cleartext password (MUST be encrypted before database storage)
21 AccessToken string // JWT for making API calls as the community
22 RefreshToken string // For refreshing sessions
23 PDSURL string // PDS hosting this community
24 RotationKeyPEM string // PEM-encoded rotation key (for portability)
25 SigningKeyPEM string // PEM-encoded signing key (for atproto operations)
26}
27
28// PDSAccountProvisioner creates PDS accounts for communities with PDS-managed DIDs
29type PDSAccountProvisioner struct {
30 instanceDomain string
31 pdsURL string // URL to call PDS (e.g., http://localhost:3001)
32}
33
34// NewPDSAccountProvisioner creates a new provisioner for V2.0 (PDS-managed keys)
35func NewPDSAccountProvisioner(instanceDomain, pdsURL string) *PDSAccountProvisioner {
36 return &PDSAccountProvisioner{
37 instanceDomain: instanceDomain,
38 pdsURL: pdsURL,
39 }
40}
41
42// ProvisionCommunityAccount creates a real PDS account for a community with PDS-managed keys
43//
44// V2.0 Architecture (PDS-Managed Keys):
45// 1. Generates community handle and credentials
46// 2. Calls com.atproto.server.createAccount (PDS generates DID and keys)
47// 3. Returns credentials for storage
48//
49// V2.0 Design Philosophy:
50// - PDS manages ALL cryptographic keys (signing + rotation)
51// - Communities can migrate between Coves-controlled PDSs using standard atProto migration
52// - Simpler, faster, ships immediately
53// - Migration uses com.atproto.server.getServiceAuth + standard migration endpoints
54//
55// Future V2.1 (Optional Portability Enhancement):
56// - Add Coves-controlled rotation key alongside PDS rotation key
57// - Enables migration to non-Coves PDSs
58// - Implement when actual external migration is needed
59//
60// SECURITY: The returned credentials MUST be encrypted before database storage
61func (p *PDSAccountProvisioner) ProvisionCommunityAccount(
62 ctx context.Context,
63 communityName string,
64) (*CommunityPDSAccount, error) {
65 if communityName == "" {
66 return nil, fmt.Errorf("community name is required")
67 }
68
69 // 1. Generate unique handle for the community
70 // Format: {name}.community.{instance-domain}
71 // Example: "gaming.community.coves.social"
72 // NOTE: Using SINGULAR "community" to follow atProto lexicon conventions
73 // (all record types use singular: app.bsky.feed.post, app.bsky.graph.follow, etc.)
74 handle := fmt.Sprintf("%s.community.%s", strings.ToLower(communityName), p.instanceDomain)
75
76 // 2. Generate system email for PDS account management
77 // This email is used for account operations, not for user communication
78 email := fmt.Sprintf("community-%s@community.%s", strings.ToLower(communityName), p.instanceDomain)
79
80 // 3. Generate secure random password (32 characters)
81 // This password is never shown to users - it's for Coves to authenticate as the community
82 password, err := generateSecurePassword(32)
83 if err != nil {
84 return nil, fmt.Errorf("failed to generate password: %w", err)
85 }
86
87 // 4. Create PDS account - let PDS generate DID and all keys
88 // The PDS will:
89 // 1. Generate a signing keypair (stored in PDS, never exported)
90 // 2. Generate rotation keys (stored in PDS)
91 // 3. Create a DID (did:plc:xxx)
92 // 4. Register DID with PLC directory
93 // 5. Return credentials (DID, handle, tokens)
94 client := &xrpc.Client{
95 Host: p.pdsURL,
96 }
97
98 emailStr := email
99 passwordStr := password
100
101 input := &atproto.ServerCreateAccount_Input{
102 Handle: handle,
103 Email: &emailStr,
104 Password: &passwordStr,
105 // No Did parameter - let PDS generate it
106 // No RecoveryKey - PDS manages rotation keys
107 }
108
109 output, err := atproto.ServerCreateAccount(ctx, client, input)
110 if err != nil {
111 return nil, fmt.Errorf("PDS account creation failed for community %s: %w", communityName, err)
112 }
113
114 // 5. Return account credentials with cleartext password
115 // CRITICAL: The password MUST be encrypted (not hashed) before database storage
116 // We need to recover the plaintext password to call com.atproto.server.createSession
117 // when access/refresh tokens expire (90-day window on refresh tokens)
118 // The repository layer handles encryption using pgp_sym_encrypt()
119 return &CommunityPDSAccount{
120 DID: output.Did, // The community's DID (PDS-generated)
121 Handle: output.Handle, // e.g., gaming.community.coves.social
122 Email: email, // community-gaming@community.coves.social
123 Password: password, // Cleartext - will be encrypted by repository
124 AccessToken: output.AccessJwt, // JWT for making API calls
125 RefreshToken: output.RefreshJwt, // For refreshing sessions
126 PDSURL: p.pdsURL, // PDS hosting this community
127 RotationKeyPEM: "", // Empty - PDS manages keys (V2.1: add Coves rotation key)
128 SigningKeyPEM: "", // Empty - PDS manages keys
129 }, nil
130}
131
132// generateSecurePassword creates a cryptographically secure random password
133// Uses crypto/rand for security-critical randomness
134func generateSecurePassword(length int) (string, error) {
135 if length < 8 {
136 return "", fmt.Errorf("password length must be at least 8 characters")
137 }
138
139 // Generate random bytes
140 bytes := make([]byte, length)
141 if _, err := rand.Read(bytes); err != nil {
142 return "", fmt.Errorf("failed to generate random bytes: %w", err)
143 }
144
145 // Encode as base64 URL-safe (no special chars that need escaping)
146 password := base64.URLEncoding.EncodeToString(bytes)
147
148 // Trim to exact length
149 if len(password) > length {
150 password = password[:length]
151 }
152
153 return password, nil
154}
155
156// FetchPDSDID queries the PDS to get its DID via com.atproto.server.describeServer
157// This is the proper way to get the PDS DID rather than hardcoding it
158// Works in both development (did:web:localhost) and production (did:web:pds.example.com)
159func FetchPDSDID(ctx context.Context, pdsURL string) (string, error) {
160 client := &xrpc.Client{
161 Host: pdsURL,
162 }
163
164 resp, err := comatproto.ServerDescribeServer(ctx, client)
165 if err != nil {
166 return "", fmt.Errorf("failed to describe server at %s: %w", pdsURL, err)
167 }
168
169 if resp.Did == "" {
170 return "", fmt.Errorf("PDS at %s did not return a DID", pdsURL)
171 }
172
173 return resp.Did, nil
174}