A Minecraft Fabric mod that connects the game with ATProtocol ⛏️
8
fork

Configure Feed

Select the types of activity you want to include in your feed.

at main 649 lines 17 kB view raw view rendered
1# Architecture & Deployment Guide 2 3## System Architecture 4 5### High-Level Overview 6 7``` 8┌─────────────────────────────────────┐ 9│ Minecraft Server (Fabric) │ 10│ ┌─────────────────────────────────┐│ 11│ │ atproto-connect Mod ││ 12│ │ ┌─────────────────────────────┐ ││ 13│ │ │ Command Handlers │ ││ 14│ │ │ (/atproto link, login...) │ ││ 15│ │ └─────────────────────────────┘ ││ 16│ │ ┌─────────────────────────────┐ ││ 17│ │ │ Player Event Hooks │ ││ 18│ │ │ (Advancement, Stats, etc) │ ││ 19│ │ └─────────────────────────────┘ ││ 20│ │ ┌─────────────────────────────┐ ││ 21│ │ │ Sync Services │ ││ 22│ │ │ (Achievements, Stats, │ ││ 23│ │ │ Sessions, Server Status) │ ││ 24│ │ └─────────────────────────────┘ ││ 25│ └─────────────────────────────────┘│ 26└─────────────────────────────────────┘ 27 28┌─────────────────────────────────────┐ 29│ atproto-connect Core Services │ 30│ ┌─────────────────────────────────┐ │ 31│ │ AtProtoSessionManager │ │ 32│ │ • OAuth & App Password Auth │ │ 33│ │ • Token Management │ │ 34│ │ • Session Persistence │ │ 35│ └─────────────────────────────────┘ │ 36│ ┌─────────────────────────────────┐ │ 37│ │ RecordManager │ │ 38│ │ • Create Records │ │ 39│ │ • Query Records │ │ 40│ │ • Update/Delete │ │ 41│ └─────────────────────────────────┘ │ 42│ ┌─────────────────────────────────┐ │ 43│ │ Security Layer │ │ 44│ │ • Encryption (AES-256-GCM) │ │ 45│ │ • Rate Limiting │ │ 46│ │ • Audit Logging │ │ 47│ └─────────────────────────────────┘ │ 48│ ┌─────────────────────────────────┐ │ 49│ │ Storage Layer │ │ 50│ │ • Encrypted Sessions │ │ 51│ │ • Identity Mappings │ │ 52│ │ • Sync Preferences │ │ 53│ └─────────────────────────────────┘ │ 54└─────────────────────────────────────┘ 55 56┌─────────────────────────────────────┐ 57│ AT Protocol Network │ 58│ ┌─────────────────────────────────┐ │ 59│ │ AtProtoClient (HTTP + XRPC) │ │ 60│ │ ┌──────────────────────────────┤ │ 61│ │ │ Player PDS │ │ 62│ │ │ (Data & Identity Storage) │ │ 63│ │ └──────────────────────────────┤ │ 64│ │ ┌──────────────────────────────┤ │ 65│ │ │ Slingshot Service │ │ 66│ │ │ (PDS Resolution) │ │ 67│ │ └──────────────────────────────┤ │ 68│ │ ┌──────────────────────────────┤ │ 69│ │ │ plc.directory │ │ 70│ │ │ (DID Resolution) │ │ 71│ │ └──────────────────────────────┤ │ 72│ └─────────────────────────────────┘ │ 73└─────────────────────────────────────┘ 74``` 75 76### Module Dependencies 77 78``` 79Minecraft Mod (client & server) 80 81 Command Handlers ← → Session Manager 82 ↓ ↓ 83 Event Listeners ← → Record Manager 84 ↓ ↓ 85 Sync Services ← → AT Proto Client 86 ↓ ↓ 87 Security Layer ← → Storage Layer 88 89 File System (config/atproto-connect/) 90``` 91 92--- 93 94## Component Deep Dive 95 96### 1. Command System 97 98**Location:** `AtProtoCommands.kt` 99 100**Responsibility:** 101- Parse player commands 102- Validate arguments 103- Delegate to appropriate services 104- Format responses 105 106**Flow:** 107``` 108Player types /atproto command 109110CommandDispatcher catches command 111112AtProtoCommands.onCommand() invoked 113114Validate command & arguments 115116Route to handler (login, link, sync, etc) 117118Handler calls services (SessionManager, StorageLayer) 119120Result formatted and sent to player 121``` 122 123--- 124 125### 2. Session Management 126 127**Location:** `AtProtoSessionManager.kt` 128 129**Responsibility:** 130- Handle OAuth flow 131- Manage JWT tokens 132- Auto-refresh before expiration 133- Persist encrypted sessions 134 135**Key Features:** 136- Browser-based OAuth with DPoP support 137- App password fallback authentication 138- Automatic token refresh (2-hour expiry) 139- Encrypted token storage (AES-256-GCM) 140 141**State Diagram:** 142``` 143[Not Authenticated] 144145 /atproto login 146147[Authenticating] ←→ (AT Protocol PDS) 148 ↓ (Success) 149[Authenticated] ←→ (Token Refresh Check) 150 ↓ ↑ 151/atproto logout 152153[Not Authenticated] 154``` 155 156--- 157 158### 3. Record Management 159 160**Location:** `RecordManager.kt` 161 162**Responsibility:** 163- Create records (auto-generated TIDs) 164- Query records (single and paginated) 165- Update records 166- Delete records 167- Type-safe JSON serialization 168 169**Record Types:** 170``` 171Player Profile (literal:self) 172 ↓ (one per account) 173 Player stats, sessions, achievements 174 175Player Stats (tid) 176 ↓ (multiple, time-ordered) 177 Periodic snapshots 178 179Achievements (tid) 180 ↓ (multiple, time-ordered) 181 Earned advancements 182 183Play Sessions (tid) 184 ↓ (multiple, time-ordered) 185 Join/leave events 186 187Server Status (literal:self) 188 ↓ (one per server) 189 MOTD, player count, version 190``` 191 192--- 193 194### 4. Data Syncing Services 195 196**Location:** `atproto/server/*SyncService.kt` 197 198**Services:** 199- `PlayerStatSyncService` - Periodic stat snapshots 200- `AchievementSyncService` - Achievement records 201- `PlayerSessionSyncService` - Session tracking 202- `ServerStatusSyncService` - Server info snapshots 203 204**Sync Workflow:** 205``` 206Player Event (stat update, achievement earned) 207208Event Hook triggered 209210Check sync preferences 211 ↓ (if enabled) 212Format record 213214RecordManager.createRecord() 215216AT Protocol PDS 217``` 218 219--- 220 221### 5. Security Layer 222 223**Location:** `security/*.kt` 224 225**Components:** 226 227**SecurityUtils** 228- AES-256-GCM encryption/decryption 229- Path validation (prevent directory traversal) 230- Random token generation 231 232**RateLimiter** 233- 3 failed attempts per 15 minutes 234- 30-minute lockout 235- Per-UUID and per-handle tracking 236 237**SecurityAuditor** 238- Log all security events 239- Separate file: `security-audit.log` 240- Events: auth, rate limits, session ops, errors 241 242--- 243 244### 6. Storage Layer 245 246**Location:** `PlayerIdentityStore.kt`, `PlayerSyncPreferencesStore.kt` 247 248**Files:** 249``` 250config/atproto-connect/ 251├── player-identities.json (plaintext UUID↔DID mapping) 252├── player-sessions.json (AES-256-GCM encrypted) 253├── sync-preferences/ (per-player settings) 254│ ├── {uuid}.json 255│ └── {uuid}.json 256├── .encryption.key (32-byte AES-256 key) 257└── security-audit.log (security events) 258``` 259 260**Access Pattern:** 261``` 262Request for player data 263264Check in-memory cache 265 ↓ (miss) 266Load from file 267 ↓ (if encrypted, decrypt with .encryption.key) 268Cache in memory 269270Return data 271``` 272 273--- 274 275## Data Flow Examples 276 277### Example 1: Player Authentication Flow 278 279``` 280Player: /atproto login alice.bsky.social abcd-1234-efgh-5678 281282AtProtoCommands.handleLogin() 283284SessionManager.authenticateWithPassword() 285286AtProtoClient.makeAuthenticatedRequest("com.atproto.server.createSession") 287288AT Protocol PDS (Validates credentials) 289290Returns: {access_token, refresh_token, did, handle} 291292SessionManager encrypts and stores in player-sessions.json 293294Session cached in memory 295296Player: "✓ Successfully authenticated!" 297``` 298 299--- 300 301### Example 2: Stats Syncing Flow 302 303``` 304Player earns stats (blocks mined, mobs killed, etc) 305306Minecraft event: StatUpdateEvent 307308PlayerStatSyncService.onStatUpdate() 309310Check: is sync enabled? (PlayerSyncPreferencesStore) 311 ↓ (yes) 312Format: PlayerStatsRecord {player, server, stats, level, gamemode} 313314RecordManager.createRecord("com.jollywhoppers.minecraft.player.stats") 315316Serialize to JSON with $type field 317318SessionManager.getSession() (auto-refresh if needed) 319320AtProtoClient.makeAuthenticatedRequest("com.atproto.repo.createRecord") 321322Include: repo (DID), collection, record, validate=true 323324AT Protocol PDS creates record with auto-generated TID 325326Returns: {uri, cid} 327328SecurityAuditor.logEvent("RECORD_CREATED", ...) 329330Data now visible on AT Protocol network 331``` 332 333--- 334 335### Example 3: AppView Leaderboard Query 336 337``` 338User queries: GET /leaderboard/minecraft.mined.oak_log 339340AppViewHttpServer.handleGetLeaderboard() 341342AppViewService.getLeaderboard("minecraft.mined.oak_log", limit=20) 343344Query in-memory leaderboard data structure 345346Sort by value descending 347348Take top 20 349350Format as LeaderboardEntryView JSON 351352Response: [{username, value, recordedAt}, ...] 353354Client renders leaderboard UI 355``` 356 357--- 358 359## Deployment Scenarios 360 361### Scenario 1: Single Server (Local) 362 363**Setup:** 364- Minecraft server (local or cloud VM) 365- Config stored on server 366- No AppView 367 368**Considerations:** 369- Simple setup, minimal overhead 370- No cross-server leaderboards 371- Players' data only visible on their own PDS 372 373--- 374 375### Scenario 2: Multiple Servers 376 377**Setup:** 378- Multiple Minecraft servers (same cluster) 379- Shared config storage (database or shared filesystem) 380- Players' data synced to AT Protocol independently 381 382**Considerations:** 383- Each server manages its own data syncing 384- All servers' data visible on players' PDS 385- Can create unified AppView across servers 386 387--- 388 389### Scenario 3: With AppView 390 391**Setup:** 392- Minecraft server(s) syncing to AT Protocol 393- AppView service (separate deployment) 394- Firehose subscription for real-time updates 395- PostgreSQL for indexing 396- Redis for caching 397 398**Architecture:** 399``` 400Minecraft Servers 401 ↓ (publish records) 402AT Protocol Network 403 ↓ (Firehose subscription) 404AppView Service 405 ├─ Index to PostgreSQL 406 ├─ Cache in Redis 407 └─ Serve HTTP API 408409 Bluesky Custom Feeds / Web Dashboard 410``` 411 412--- 413 414### Scenario 4: Enterprise Deployment 415 416**Setup:** 417- Multiple Minecraft servers across regions 418- Centralized session management 419- Dedicated AppView cluster 420- Full monitoring & alerting 421- Database replication & backups 422 423**Security:** 424- All traffic encrypted (TLS) 425- Rate limiting on all endpoints 426- DDoS protection 427- Security audit logging 428- Regular security audits 429 430--- 431 432## Installation & Configuration 433 434### For Minecraft Server 435 436**Step 1: Install Dependencies** 437```bash 438# Install Fabric Loader for 1.21.10 439# Install Fabric API 0.138.4+1.21.10 440# Install Fabric Language Kotlin 1.13.8+kotlin.2.3.0 441``` 442 443**Step 2: Install Mod** 444```bash 445cp social-sync.jar mods/ 446``` 447 448**Step 3: Configure (Optional)** 449Create `config/atproto-connect/config.json`: 450```json 451{ 452 "sync_interval_minutes": 60, 453 "log_level": "INFO", 454 "enable_security_audit": true, 455 "rate_limit_attempts": 3, 456 "rate_limit_window_minutes": 15, 457 "rate_limit_lockout_minutes": 30 458} 459``` 460 461**Step 4: Start Server** 462```bash 463java -Xmx4G -jar server.jar nogui 464``` 465 466**Step 5: Player Setup** 467``` 468Player joins, then runs: 469/atproto link alice.bsky.social 470/atproto login alice.bsky.social abcd-1234-efgh-5678 471/atproto sync stats on 472``` 473 474--- 475 476## Monitoring & Operations 477 478### Health Checks 479 480**Mod Status:** 481``` 482/atproto status 483``` 484 485**Security Audit Log:** 486```bash 487tail -f config/atproto-connect/security-audit.log 488``` 489 490--- 491 492### Common Operations 493 494**Backup Configuration:** 495```bash 496cp -r config/atproto-connect/ backup/atproto-connect-$(date +%s)/ 497``` 498 499**Rotate Encryption Key** (requires re-encryption): 500```bash 501# Generate new key 502# Re-encrypt all sessions with new key 503# This is complex - should be automated 504``` 505 506**Clear Expired Sessions:** 507```bash 508# Remove sessions older than 30 days 509# Periodically clear stale data 510``` 511 512--- 513 514## Performance Optimization 515 516### Caching Strategy 517 518**Session Cache:** 519- TTL: 5 minutes 520- Size: ~1KB per entry 521- Invalidate on logout 522 523**Identity Cache:** 524- TTL: 60 minutes 525- Size: ~100 bytes per entry 526- Invalidate on link/unlink 527 528--- 529 530### Database Indexing (for AppView) 531 532```sql 533-- For leaderboard queries 534CREATE INDEX idx_stat_value ON indexed_records(statistic_key, value DESC); 535 536-- For player queries 537CREATE INDEX idx_player_uuid ON indexed_records(player_uuid); 538 539-- For time-range queries 540CREATE INDEX idx_synced_at ON indexed_records(synced_at DESC); 541 542-- For search 543CREATE INDEX idx_username ON indexed_records(username); 544``` 545 546--- 547 548## Troubleshooting 549 550### Issue: Sessions not persisting 551 552**Cause:** `.encryption.key` missing or corrupted 553 554**Solution:** 555```bash 556rm config/atproto-connect/.encryption.key 557# Server will regenerate on next start 558# Players must re-authenticate 559``` 560 561--- 562 563### Issue: High memory usage 564 565**Cause:** In-memory caches growing unbounded 566 567**Solution:** 568- Implement cache eviction policy 569- Reduce cache TTL 570- Monitor with `jmap -histo <pid>` 571 572--- 573 574### Issue: Slow record creation 575 576**Cause:** Network latency to PDS 577 578**Solution:** 579- Use Slingshot for fast PDS resolution 580- Implement request batching 581- Add local caching layer 582 583--- 584 585## Scaling Considerations 586 587### Vertical Scaling 588- Increase Java heap: `-Xmx8G` 589- Use NVMe for faster config I/O 590- Scale to 100+ concurrent players 591 592### Horizontal Scaling 593- Run multiple Minecraft servers 594- Share config via database 595- Deploy AppView across multiple nodes 596 597--- 598 599## Security Hardening 600 6011. **File Permissions:** 602 ```bash 603 chmod 600 config/atproto-connect/.encryption.key 604 chmod 600 config/atproto-connect/player-sessions.json 605 chmod 700 config/atproto-connect/ 606 ``` 607 6082. **Network:** 609 - Use TLS for AppView (https://...) 610 - Whitelist CORS origins 611 - Enable rate limiting 612 6133. **Secrets:** 614 - Rotate encryption keys regularly 615 - Never commit config to version control 616 - Use environment variables for sensitive data 617 618--- 619 620## Backup & Recovery 621 622### Backup Strategy 623 624**Daily Backups:** 625```bash 626tar -czf backup-$(date +%Y%m%d).tar.gz config/atproto-connect/ 627``` 628 629**Offsite Storage:** 630- S3/cloud storage for critical backups 631- 30-day retention 632 633### Recovery Procedure 634 6351. Stop mod/server 6362. Restore from backup 6373. Verify file permissions 6384. Restart server 6395. Test player commands 640 641--- 642 643## References 644 645- [System Architecture](../README.md#architecture) 646- [Security Guide](../README.md#authentication--security) 647- [Configuration Files](../README.md#configuration-files) 648- [API Reference](API_REFERENCE.md) 649- [AppView Guide](APPVIEW.md)