A community based topic aggregation platform built on atproto
1package communities 2 3import ( 4 "bytes" 5 "context" 6 "encoding/json" 7 "fmt" 8 "io" 9 "log" 10 "net/http" 11 "regexp" 12 "strings" 13 "time" 14) 15 16// Community handle validation regex (DNS-valid handle: name.communities.instance.com) 17// Matches standard DNS hostname format (RFC 1035) 18var communityHandleRegex = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$`) 19 20type communityService struct { 21 repo Repository 22 provisioner *PDSAccountProvisioner 23 pdsURL string 24 instanceDID string 25 instanceDomain string 26 pdsAccessToken string 27} 28 29// NewCommunityService creates a new community service 30func NewCommunityService(repo Repository, pdsURL, instanceDID, instanceDomain string, provisioner *PDSAccountProvisioner) Service { 31 return &communityService{ 32 repo: repo, 33 pdsURL: pdsURL, 34 instanceDID: instanceDID, 35 instanceDomain: instanceDomain, 36 provisioner: provisioner, 37 } 38} 39 40// SetPDSAccessToken sets the PDS access token for authentication 41// This should be called after creating a session for the Coves instance DID on the PDS 42func (s *communityService) SetPDSAccessToken(token string) { 43 s.pdsAccessToken = token 44} 45 46// CreateCommunity creates a new community via write-forward to PDS 47// V2 Flow: 48// 1. Service creates PDS account for community (PDS generates signing keypair) 49// 2. Service writes community profile to COMMUNITY's own repository 50// 3. Firehose emits event 51// 4. Consumer indexes to AppView DB 52// 53// V2 Architecture: 54// - Community owns its own repository (at://community_did/social.coves.community.profile/self) 55// - PDS manages the signing keypair (we never see it) 56// - We store PDS credentials to act on behalf of the community 57// - Community can migrate to other instances (future V2.1 with rotation keys) 58func (s *communityService) CreateCommunity(ctx context.Context, req CreateCommunityRequest) (*Community, error) { 59 // Apply defaults before validation 60 if req.Visibility == "" { 61 req.Visibility = "public" 62 } 63 64 // Validate request 65 if err := s.validateCreateRequest(req); err != nil { 66 return nil, err 67 } 68 69 // V2: Provision a real PDS account for this community 70 // This calls com.atproto.server.createAccount internally 71 // The PDS will: 72 // 1. Generate a signing keypair (stored in PDS, we never see it) 73 // 2. Create a DID (did:plc:xxx) 74 // 3. Return credentials (DID, tokens) 75 pdsAccount, err := s.provisioner.ProvisionCommunityAccount(ctx, req.Name) 76 if err != nil { 77 return nil, fmt.Errorf("failed to provision PDS account for community: %w", err) 78 } 79 80 // Validate the atProto handle 81 if validateErr := s.ValidateHandle(pdsAccount.Handle); validateErr != nil { 82 return nil, fmt.Errorf("generated atProto handle is invalid: %w", validateErr) 83 } 84 85 // Build community profile record 86 profile := map[string]interface{}{ 87 "$type": "social.coves.community.profile", 88 "handle": pdsAccount.Handle, // atProto handle (e.g., gaming.communities.coves.social) 89 "name": req.Name, // Short name for !mentions (e.g., "gaming") 90 "visibility": req.Visibility, 91 "hostedBy": s.instanceDID, // V2: Instance hosts, community owns 92 "createdBy": req.CreatedByDID, 93 "createdAt": time.Now().Format(time.RFC3339), 94 "federation": map[string]interface{}{ 95 "allowExternalDiscovery": req.AllowExternalDiscovery, 96 }, 97 } 98 99 // Add optional fields 100 if req.DisplayName != "" { 101 profile["displayName"] = req.DisplayName 102 } 103 if req.Description != "" { 104 profile["description"] = req.Description 105 } 106 if len(req.Rules) > 0 { 107 profile["rules"] = req.Rules 108 } 109 if len(req.Categories) > 0 { 110 profile["categories"] = req.Categories 111 } 112 if req.Language != "" { 113 profile["language"] = req.Language 114 } 115 116 // Initialize counts 117 profile["memberCount"] = 0 118 profile["subscriberCount"] = 0 119 120 // TODO: Handle avatar and banner blobs 121 // For now, we'll skip blob uploads. This would require: 122 // 1. Upload blob to PDS via com.atproto.repo.uploadBlob 123 // 2. Get blob ref (CID) 124 // 3. Add to profile record 125 126 // V2: Write to COMMUNITY's own repository (not instance repo!) 127 // Repository: at://COMMUNITY_DID/social.coves.community.profile/self 128 // Authenticate using community's access token 129 recordURI, recordCID, err := s.createRecordOnPDSAs( 130 ctx, 131 pdsAccount.DID, // repo = community's DID (community owns its repo!) 132 "social.coves.community.profile", 133 "self", // canonical rkey for profile 134 profile, 135 pdsAccount.AccessToken, // authenticate as the community 136 ) 137 if err != nil { 138 return nil, fmt.Errorf("failed to create community profile record: %w", err) 139 } 140 141 // Build Community object with PDS credentials AND cryptographic keys 142 community := &Community{ 143 DID: pdsAccount.DID, // Community's DID (owns the repo!) 144 Handle: pdsAccount.Handle, // atProto handle (e.g., gaming.communities.coves.social) 145 Name: req.Name, 146 DisplayName: req.DisplayName, 147 Description: req.Description, 148 OwnerDID: pdsAccount.DID, // V2: Community owns itself 149 CreatedByDID: req.CreatedByDID, 150 HostedByDID: req.HostedByDID, 151 PDSEmail: pdsAccount.Email, 152 PDSPassword: pdsAccount.Password, 153 PDSAccessToken: pdsAccount.AccessToken, 154 PDSRefreshToken: pdsAccount.RefreshToken, 155 PDSURL: pdsAccount.PDSURL, 156 Visibility: req.Visibility, 157 AllowExternalDiscovery: req.AllowExternalDiscovery, 158 MemberCount: 0, 159 SubscriberCount: 0, 160 CreatedAt: time.Now(), 161 UpdatedAt: time.Now(), 162 RecordURI: recordURI, 163 RecordCID: recordCID, 164 // V2: Cryptographic keys for portability (will be encrypted by repository) 165 RotationKeyPEM: pdsAccount.RotationKeyPEM, // CRITICAL: Enables DID migration 166 SigningKeyPEM: pdsAccount.SigningKeyPEM, // For atproto operations 167 } 168 169 // CRITICAL: Persist PDS credentials immediately to database 170 // The Jetstream consumer will eventually index the community profile from the firehose, 171 // but it won't have the PDS credentials. We must store them now so we can: 172 // 1. Update the community profile later (using its own credentials) 173 // 2. Re-authenticate if access tokens expire 174 _, err = s.repo.Create(ctx, community) 175 if err != nil { 176 return nil, fmt.Errorf("failed to persist community with credentials: %w", err) 177 } 178 179 return community, nil 180} 181 182// GetCommunity retrieves a community from AppView DB 183// identifier can be either a DID or handle 184func (s *communityService) GetCommunity(ctx context.Context, identifier string) (*Community, error) { 185 if identifier == "" { 186 return nil, ErrInvalidInput 187 } 188 189 // Determine if identifier is DID or handle 190 if strings.HasPrefix(identifier, "did:") { 191 return s.repo.GetByDID(ctx, identifier) 192 } 193 194 if strings.HasPrefix(identifier, "!") { 195 return s.repo.GetByHandle(ctx, identifier) 196 } 197 198 return nil, NewValidationError("identifier", "must be a DID or handle") 199} 200 201// UpdateCommunity updates a community via write-forward to PDS 202func (s *communityService) UpdateCommunity(ctx context.Context, req UpdateCommunityRequest) (*Community, error) { 203 if req.CommunityDID == "" { 204 return nil, NewValidationError("communityDid", "required") 205 } 206 207 if req.UpdatedByDID == "" { 208 return nil, NewValidationError("updatedByDid", "required") 209 } 210 211 // Get existing community 212 existing, err := s.repo.GetByDID(ctx, req.CommunityDID) 213 if err != nil { 214 return nil, err 215 } 216 217 // Authorization: verify user is the creator 218 // TODO(Communities-Auth): Add moderator check when moderation system is implemented 219 if existing.CreatedByDID != req.UpdatedByDID { 220 return nil, ErrUnauthorized 221 } 222 223 // Build updated profile record (start with existing) 224 profile := map[string]interface{}{ 225 "$type": "social.coves.community.profile", 226 "handle": existing.Handle, 227 "name": existing.Name, 228 "owner": existing.OwnerDID, 229 "createdBy": existing.CreatedByDID, 230 "hostedBy": existing.HostedByDID, 231 "createdAt": existing.CreatedAt.Format(time.RFC3339), 232 } 233 234 // Apply updates 235 if req.DisplayName != nil { 236 profile["displayName"] = *req.DisplayName 237 } else { 238 profile["displayName"] = existing.DisplayName 239 } 240 241 if req.Description != nil { 242 profile["description"] = *req.Description 243 } else { 244 profile["description"] = existing.Description 245 } 246 247 if req.Visibility != nil { 248 profile["visibility"] = *req.Visibility 249 } else { 250 profile["visibility"] = existing.Visibility 251 } 252 253 if req.AllowExternalDiscovery != nil { 254 profile["federation"] = map[string]interface{}{ 255 "allowExternalDiscovery": *req.AllowExternalDiscovery, 256 } 257 } else { 258 profile["federation"] = map[string]interface{}{ 259 "allowExternalDiscovery": existing.AllowExternalDiscovery, 260 } 261 } 262 263 if req.ModerationType != nil { 264 profile["moderationType"] = *req.ModerationType 265 } 266 267 if len(req.ContentWarnings) > 0 { 268 profile["contentWarnings"] = req.ContentWarnings 269 } 270 271 // Preserve counts 272 profile["memberCount"] = existing.MemberCount 273 profile["subscriberCount"] = existing.SubscriberCount 274 275 // V2: Community profiles always use "self" as rkey 276 // (No need to extract from URI - it's always "self" for V2 communities) 277 278 // V2 CRITICAL FIX: Write-forward using COMMUNITY's own DID and credentials 279 // Repository: at://COMMUNITY_DID/social.coves.community.profile/self 280 // Authenticate as the community (not as instance!) 281 if existing.PDSAccessToken == "" { 282 return nil, fmt.Errorf("community %s missing PDS credentials - cannot update", existing.DID) 283 } 284 285 recordURI, recordCID, err := s.putRecordOnPDSAs( 286 ctx, 287 existing.DID, // repo = community's own DID (V2!) 288 "social.coves.community.profile", 289 "self", // V2: always "self" 290 profile, 291 existing.PDSAccessToken, // authenticate as the community 292 ) 293 if err != nil { 294 return nil, fmt.Errorf("failed to update community on PDS: %w", err) 295 } 296 297 // Return updated community representation 298 // Actual AppView DB update happens via Jetstream consumer 299 updated := *existing 300 if req.DisplayName != nil { 301 updated.DisplayName = *req.DisplayName 302 } 303 if req.Description != nil { 304 updated.Description = *req.Description 305 } 306 if req.Visibility != nil { 307 updated.Visibility = *req.Visibility 308 } 309 if req.AllowExternalDiscovery != nil { 310 updated.AllowExternalDiscovery = *req.AllowExternalDiscovery 311 } 312 if req.ModerationType != nil { 313 updated.ModerationType = *req.ModerationType 314 } 315 if len(req.ContentWarnings) > 0 { 316 updated.ContentWarnings = req.ContentWarnings 317 } 318 updated.RecordURI = recordURI 319 updated.RecordCID = recordCID 320 updated.UpdatedAt = time.Now() 321 322 return &updated, nil 323} 324 325// ListCommunities queries AppView DB for communities with filters 326func (s *communityService) ListCommunities(ctx context.Context, req ListCommunitiesRequest) ([]*Community, int, error) { 327 // Set defaults 328 if req.Limit <= 0 || req.Limit > 100 { 329 req.Limit = 50 330 } 331 332 return s.repo.List(ctx, req) 333} 334 335// SearchCommunities performs fuzzy search in AppView DB 336func (s *communityService) SearchCommunities(ctx context.Context, req SearchCommunitiesRequest) ([]*Community, int, error) { 337 if req.Query == "" { 338 return nil, 0, NewValidationError("query", "search query is required") 339 } 340 341 // Set defaults 342 if req.Limit <= 0 || req.Limit > 100 { 343 req.Limit = 50 344 } 345 346 return s.repo.Search(ctx, req) 347} 348 349// SubscribeToCommunity creates a subscription via write-forward to PDS 350func (s *communityService) SubscribeToCommunity(ctx context.Context, userDID, communityIdentifier string) (*Subscription, error) { 351 if userDID == "" { 352 return nil, NewValidationError("userDid", "required") 353 } 354 355 // Resolve community identifier to DID 356 communityDID, err := s.ResolveCommunityIdentifier(ctx, communityIdentifier) 357 if err != nil { 358 return nil, err 359 } 360 361 // Verify community exists 362 community, err := s.repo.GetByDID(ctx, communityDID) 363 if err != nil { 364 return nil, err 365 } 366 367 // Check visibility - can't subscribe to private communities without invitation (TODO) 368 if community.Visibility == "private" { 369 return nil, ErrUnauthorized 370 } 371 372 // Build subscription record 373 subRecord := map[string]interface{}{ 374 "$type": "social.coves.community.subscribe", 375 "community": communityDID, 376 } 377 378 // Write-forward: create subscription record in user's repo 379 recordURI, recordCID, err := s.createRecordOnPDS(ctx, userDID, "social.coves.community.subscribe", "", subRecord) 380 if err != nil { 381 return nil, fmt.Errorf("failed to create subscription on PDS: %w", err) 382 } 383 384 // Return subscription representation 385 subscription := &Subscription{ 386 UserDID: userDID, 387 CommunityDID: communityDID, 388 SubscribedAt: time.Now(), 389 RecordURI: recordURI, 390 RecordCID: recordCID, 391 } 392 393 return subscription, nil 394} 395 396// UnsubscribeFromCommunity removes a subscription via PDS delete 397func (s *communityService) UnsubscribeFromCommunity(ctx context.Context, userDID, communityIdentifier string) error { 398 if userDID == "" { 399 return NewValidationError("userDid", "required") 400 } 401 402 // Resolve community identifier 403 communityDID, err := s.ResolveCommunityIdentifier(ctx, communityIdentifier) 404 if err != nil { 405 return err 406 } 407 408 // Get the subscription from AppView to find the record key 409 subscription, err := s.repo.GetSubscription(ctx, userDID, communityDID) 410 if err != nil { 411 return err 412 } 413 414 // Extract rkey from record URI (at://did/collection/rkey) 415 rkey := extractRKeyFromURI(subscription.RecordURI) 416 if rkey == "" { 417 return fmt.Errorf("invalid subscription record URI") 418 } 419 420 // Write-forward: delete record from PDS 421 if err := s.deleteRecordOnPDS(ctx, userDID, "social.coves.community.subscribe", rkey); err != nil { 422 return fmt.Errorf("failed to delete subscription on PDS: %w", err) 423 } 424 425 return nil 426} 427 428// GetUserSubscriptions queries AppView DB for user's subscriptions 429func (s *communityService) GetUserSubscriptions(ctx context.Context, userDID string, limit, offset int) ([]*Subscription, error) { 430 if limit <= 0 || limit > 100 { 431 limit = 50 432 } 433 434 return s.repo.ListSubscriptions(ctx, userDID, limit, offset) 435} 436 437// GetCommunitySubscribers queries AppView DB for community subscribers 438func (s *communityService) GetCommunitySubscribers(ctx context.Context, communityIdentifier string, limit, offset int) ([]*Subscription, error) { 439 communityDID, err := s.ResolveCommunityIdentifier(ctx, communityIdentifier) 440 if err != nil { 441 return nil, err 442 } 443 444 if limit <= 0 || limit > 100 { 445 limit = 50 446 } 447 448 return s.repo.ListSubscribers(ctx, communityDID, limit, offset) 449} 450 451// GetMembership retrieves membership info from AppView DB 452func (s *communityService) GetMembership(ctx context.Context, userDID, communityIdentifier string) (*Membership, error) { 453 communityDID, err := s.ResolveCommunityIdentifier(ctx, communityIdentifier) 454 if err != nil { 455 return nil, err 456 } 457 458 return s.repo.GetMembership(ctx, userDID, communityDID) 459} 460 461// ListCommunityMembers queries AppView DB for members 462func (s *communityService) ListCommunityMembers(ctx context.Context, communityIdentifier string, limit, offset int) ([]*Membership, error) { 463 communityDID, err := s.ResolveCommunityIdentifier(ctx, communityIdentifier) 464 if err != nil { 465 return nil, err 466 } 467 468 if limit <= 0 || limit > 100 { 469 limit = 50 470 } 471 472 return s.repo.ListMembers(ctx, communityDID, limit, offset) 473} 474 475// ValidateHandle checks if a community handle is valid 476func (s *communityService) ValidateHandle(handle string) error { 477 if handle == "" { 478 return NewValidationError("handle", "required") 479 } 480 481 if !communityHandleRegex.MatchString(handle) { 482 return ErrInvalidHandle 483 } 484 485 return nil 486} 487 488// ResolveCommunityIdentifier converts a handle or DID to a DID 489func (s *communityService) ResolveCommunityIdentifier(ctx context.Context, identifier string) (string, error) { 490 if identifier == "" { 491 return "", ErrInvalidInput 492 } 493 494 // If it's already a DID, return it 495 if strings.HasPrefix(identifier, "did:") { 496 return identifier, nil 497 } 498 499 // If it's a handle, look it up in AppView DB 500 if strings.HasPrefix(identifier, "!") { 501 community, err := s.repo.GetByHandle(ctx, identifier) 502 if err != nil { 503 return "", err 504 } 505 return community.DID, nil 506 } 507 508 return "", NewValidationError("identifier", "must be a DID or handle") 509} 510 511// Validation helpers 512 513func (s *communityService) validateCreateRequest(req CreateCommunityRequest) error { 514 if req.Name == "" { 515 return NewValidationError("name", "required") 516 } 517 518 // DNS label limit: 63 characters per label 519 // Community handle format: {name}.communities.{instanceDomain} 520 // The first label is just req.Name, so it must be <= 63 chars 521 if len(req.Name) > 63 { 522 return NewValidationError("name", "must be 63 characters or less (DNS label limit)") 523 } 524 525 // Name can only contain alphanumeric and hyphens 526 // Must start and end with alphanumeric (not hyphen) 527 nameRegex := regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$`) 528 if !nameRegex.MatchString(req.Name) { 529 return NewValidationError("name", "must contain only alphanumeric characters and hyphens") 530 } 531 532 if req.Description != "" && len(req.Description) > 3000 { 533 return NewValidationError("description", "must be 3000 characters or less") 534 } 535 536 // Visibility should already be set with default in CreateCommunity 537 if req.Visibility != "public" && req.Visibility != "unlisted" && req.Visibility != "private" { 538 return ErrInvalidVisibility 539 } 540 541 if req.CreatedByDID == "" { 542 return NewValidationError("createdByDid", "required") 543 } 544 545 if req.HostedByDID == "" { 546 return NewValidationError("hostedByDid", "required") 547 } 548 549 return nil 550} 551 552// PDS write-forward helpers 553 554func (s *communityService) createRecordOnPDS(ctx context.Context, repoDID, collection, rkey string, record map[string]interface{}) (string, string, error) { 555 endpoint := fmt.Sprintf("%s/xrpc/com.atproto.repo.createRecord", strings.TrimSuffix(s.pdsURL, "/")) 556 557 payload := map[string]interface{}{ 558 "repo": repoDID, 559 "collection": collection, 560 "record": record, 561 } 562 563 if rkey != "" { 564 payload["rkey"] = rkey 565 } 566 567 return s.callPDS(ctx, "POST", endpoint, payload) 568} 569 570// createRecordOnPDSAs creates a record with a specific access token (for V2 community auth) 571func (s *communityService) createRecordOnPDSAs(ctx context.Context, repoDID, collection, rkey string, record map[string]interface{}, accessToken string) (string, string, error) { 572 endpoint := fmt.Sprintf("%s/xrpc/com.atproto.repo.createRecord", strings.TrimSuffix(s.pdsURL, "/")) 573 574 payload := map[string]interface{}{ 575 "repo": repoDID, 576 "collection": collection, 577 "record": record, 578 } 579 580 if rkey != "" { 581 payload["rkey"] = rkey 582 } 583 584 return s.callPDSWithAuth(ctx, "POST", endpoint, payload, accessToken) 585} 586 587// putRecordOnPDSAs updates a record with a specific access token (for V2 community auth) 588func (s *communityService) putRecordOnPDSAs(ctx context.Context, repoDID, collection, rkey string, record map[string]interface{}, accessToken string) (string, string, error) { 589 endpoint := fmt.Sprintf("%s/xrpc/com.atproto.repo.putRecord", strings.TrimSuffix(s.pdsURL, "/")) 590 591 payload := map[string]interface{}{ 592 "repo": repoDID, 593 "collection": collection, 594 "rkey": rkey, 595 "record": record, 596 } 597 598 return s.callPDSWithAuth(ctx, "POST", endpoint, payload, accessToken) 599} 600 601func (s *communityService) deleteRecordOnPDS(ctx context.Context, repoDID, collection, rkey string) error { 602 endpoint := fmt.Sprintf("%s/xrpc/com.atproto.repo.deleteRecord", strings.TrimSuffix(s.pdsURL, "/")) 603 604 payload := map[string]interface{}{ 605 "repo": repoDID, 606 "collection": collection, 607 "rkey": rkey, 608 } 609 610 _, _, err := s.callPDS(ctx, "POST", endpoint, payload) 611 return err 612} 613 614func (s *communityService) callPDS(ctx context.Context, method, endpoint string, payload map[string]interface{}) (string, string, error) { 615 // Use instance's access token 616 return s.callPDSWithAuth(ctx, method, endpoint, payload, s.pdsAccessToken) 617} 618 619// callPDSWithAuth makes a PDS call with a specific access token (V2: for community authentication) 620func (s *communityService) callPDSWithAuth(ctx context.Context, method, endpoint string, payload map[string]interface{}, accessToken string) (string, string, error) { 621 jsonData, err := json.Marshal(payload) 622 if err != nil { 623 return "", "", fmt.Errorf("failed to marshal payload: %w", err) 624 } 625 626 req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewBuffer(jsonData)) 627 if err != nil { 628 return "", "", fmt.Errorf("failed to create request: %w", err) 629 } 630 req.Header.Set("Content-Type", "application/json") 631 632 // Add authentication with provided access token 633 if accessToken != "" { 634 req.Header.Set("Authorization", "Bearer "+accessToken) 635 } 636 637 // Dynamic timeout based on operation type 638 // Write operations (createAccount, createRecord, putRecord) are slower due to: 639 // - Keypair generation 640 // - DID PLC registration 641 // - Database writes on PDS 642 timeout := 10 * time.Second // Default for read operations 643 if strings.Contains(endpoint, "createAccount") || 644 strings.Contains(endpoint, "createRecord") || 645 strings.Contains(endpoint, "putRecord") { 646 timeout = 30 * time.Second // Extended timeout for write operations 647 } 648 649 client := &http.Client{Timeout: timeout} 650 resp, err := client.Do(req) 651 if err != nil { 652 return "", "", fmt.Errorf("failed to call PDS: %w", err) 653 } 654 defer func() { 655 if closeErr := resp.Body.Close(); closeErr != nil { 656 log.Printf("Failed to close response body: %v", closeErr) 657 } 658 }() 659 660 body, err := io.ReadAll(resp.Body) 661 if err != nil { 662 return "", "", fmt.Errorf("failed to read response: %w", err) 663 } 664 665 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { 666 return "", "", fmt.Errorf("PDS returned status %d: %s", resp.StatusCode, string(body)) 667 } 668 669 // Parse response to extract URI and CID 670 var result struct { 671 URI string `json:"uri"` 672 CID string `json:"cid"` 673 } 674 if err := json.Unmarshal(body, &result); err != nil { 675 // For delete operations, there might not be a response body 676 if method == "POST" && strings.Contains(endpoint, "deleteRecord") { 677 return "", "", nil 678 } 679 return "", "", fmt.Errorf("failed to parse PDS response: %w", err) 680 } 681 682 return result.URI, result.CID, nil 683} 684 685// Helper functions 686 687func extractRKeyFromURI(uri string) string { 688 // at://did/collection/rkey -> rkey 689 parts := strings.Split(uri, "/") 690 if len(parts) >= 4 { 691 return parts[len(parts)-1] 692 } 693 return "" 694}