using System.Diagnostics; using System.Net; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using AppBsky.Actor; using AppBsky.Feed; using AppBsky.Notification; using ComAtproto.Repo; using CarpaNet.OAuth; using CarpaNet.OAuth.Storage; using CarpaNet.Storage; using CarpaNet; const string SessionDir = ".atproto-sessions"; Console.WriteLine("=== CarpaNet Auth Test ==="); while (true) { Console.WriteLine(); Console.WriteLine("Choose auth method:"); Console.WriteLine(" 1. Password (App Password)"); Console.WriteLine(" 2. OAuth (Localhost)"); Console.WriteLine(" 3. Restore Password Session"); Console.WriteLine(" 4. Restore OAuth Session"); Console.WriteLine(" 5. Exit"); Console.Write("> "); var choice = Console.ReadLine()?.Trim(); switch (choice) { case "1": await PasswordFlowAsync(); break; case "2": await OAuthFlowAsync(); break; case "3": await RestorePasswordSessionAsync(); break; case "4": await RestoreOAuthSessionAsync(); break; case "5": return; default: Console.WriteLine("Invalid choice."); break; } } async Task PasswordFlowAsync() { Console.Write("Handle or DID: "); var identifier = Console.ReadLine()?.Trim(); if (string.IsNullOrEmpty(identifier)) { Console.WriteLine("Identifier is required."); return; } Console.Write("App Password: "); var password = ReadPassword(); Console.WriteLine(); if (string.IsNullOrEmpty(password)) { Console.WriteLine("Password is required."); return; } try { var sessionStore = new FileSessionStore(GetSessionDir()); var client = ATProtoClientFactory.CreateSessionClient(sessionStore); var session = await client.LoginAsync(identifier, password); Console.WriteLine($"Logged in as {session.Handle} ({session.Did})"); Console.WriteLine("Session saved automatically."); await AuthenticatedMenuAsync(client, client.Handle, session.Did); } catch (Exception ex) { Console.WriteLine($"Login failed: {ex.Message}"); } } async Task OAuthFlowAsync() { Console.Write("Handle: "); var handle = Console.ReadLine()?.Trim(); if (string.IsNullOrEmpty(handle)) { Console.WriteLine("Handle is required."); return; } // Find a free port var listener = new HttpListener(); var port = FindFreePort(); var redirectUri = $"http://127.0.0.1:{port}/callback"; var clientId = $"http://localhost?redirect_uri={Uri.EscapeDataString(redirectUri)}&scope={Uri.EscapeDataString("atproto transition:generic")}"; listener.Prefixes.Add($"http://127.0.0.1:{port}/"); listener.Start(); try { var sessionStore = new FileOAuthSessionStore(GetSessionDir()); var config = new OAuthClientConfig { ClientId = clientId, RedirectUri = redirectUri, Scope = "atproto transition:generic", JsonOptions = ATProtoClientFactory.CreateJsonOptions(), SessionStore = sessionStore }; using var oauthClient = new OAuthSession(config); Console.WriteLine("Starting OAuth flow..."); var authUrl = await oauthClient.AuthorizeAsync(handle); Console.WriteLine($"Opening browser for authorization..."); Console.WriteLine($"If the browser doesn't open, visit: {authUrl}"); // Open browser try { Process.Start(new ProcessStartInfo(authUrl) { UseShellExecute = true }); } catch { Console.WriteLine("Could not open browser automatically."); } Console.WriteLine("Waiting for callback..."); // Wait for callback var context = await listener.GetContextAsync(); var callbackUrl = context.Request.Url!.ToString(); // Send response to browser var responseBytes = Encoding.UTF8.GetBytes( "
You can close this tab.
"); context.Response.ContentType = "text/html"; context.Response.ContentLength64 = responseBytes.Length; await context.Response.OutputStream.WriteAsync(responseBytes); context.Response.Close(); Console.WriteLine("Processing callback..."); var session = await oauthClient.CallbackAsync(callbackUrl); Console.WriteLine($"Authenticated as {session.Did}"); Console.WriteLine("OAuth session saved automatically."); await AuthenticatedMenuAsync(session, null, session.Did); } catch (Exception ex) { Console.WriteLine($"OAuth flow failed: {ex.Message}"); } finally { listener.Stop(); } } async Task RestorePasswordSessionAsync() { Console.Write("DID to restore: "); var did = Console.ReadLine()?.Trim(); if (string.IsNullOrEmpty(did)) { Console.WriteLine("DID is required."); return; } try { Console.WriteLine($"Restoring session for {did}..."); var sessionStore = new FileSessionStore(GetSessionDir()); var client = ATProtoClientFactory.CreateSessionClient(sessionStore); var restored = await client.RestoreSessionAsync(did); if (!restored) { Console.WriteLine("No saved password session found for that DID."); return; } // Refresh to verify the session is still valid await client.TokenProvider!.RefreshAsync(); Console.WriteLine($"Session restored for {client.Handle} ({client.AuthenticatedDid})"); await AuthenticatedMenuAsync(client, client.Handle, client.AuthenticatedDid!); } catch (Exception ex) { Console.WriteLine($"Failed to restore session: {ex.Message}"); } } async Task RestoreOAuthSessionAsync() { Console.Write("DID to restore: "); var did = Console.ReadLine()?.Trim(); if (string.IsNullOrEmpty(did)) { Console.WriteLine("DID is required."); return; } try { Console.WriteLine($"Restoring OAuth session for {did}..."); var sessionStore = new FileOAuthSessionStore(GetSessionDir()); // Load stored session data to get the client config var sessionData = await sessionStore.GetAsync(did); if (sessionData == null || string.IsNullOrEmpty(sessionData.ClientId)) { Console.WriteLine("No saved OAuth session found for that DID."); return; } var config = new OAuthClientConfig { ClientId = sessionData.ClientId, RedirectUri = sessionData.RedirectUri ?? string.Empty, Scope = sessionData.Scope ?? "atproto", JsonOptions = ATProtoClientFactory.CreateJsonOptions(), SessionStore = sessionStore }; using var oauthClient = new OAuthSession(config); var session = await oauthClient.RestoreSessionAsync(did); if (session == null) { Console.WriteLine("Failed to restore OAuth session."); return; } Console.WriteLine($"OAuth session restored for {session.Did}"); await AuthenticatedMenuAsync(session, null, session.Did); } catch (Exception ex) { Console.WriteLine($"Failed to restore OAuth session: {ex.Message}"); } } async Task AuthenticatedMenuAsync(IATProtoClient client, string? handle, string did) { while (true) { Console.WriteLine(); Console.WriteLine($"=== Authenticated as {handle ?? did} ==="); Console.WriteLine(" 1. Get my profile"); Console.WriteLine(" 2. Get my preferences"); Console.WriteLine(" 3. Get my timeline"); Console.WriteLine(" 4. Get posts by URIs"); Console.WriteLine(" 5. Get notifications"); Console.WriteLine(" 6. Create a post"); Console.WriteLine(" 7. Delete a post"); Console.WriteLine(" 8. Save session"); Console.WriteLine(" 9. Show session tokens"); Console.WriteLine(" 10. Exit"); Console.Write("> "); var choice = Console.ReadLine()?.Trim(); try { switch (choice) { case "1": await GetProfileAsync(client, handle ?? did); break; case "2": await GetPreferencesAsync(client); break; case "3": await GetTimelineAsync(client); break; case "4": await GetPostsAsync(client); break; case "5": await GetNotificationsAsync(client); break; case "6": await CreatePostAsync(client, did); break; case "7": await DeletePostAsync(client, did); break; case "8": SaveCurrentSession(client); break; case "9": await ShowSessionTokensAsync(client); break; case "10": return; default: Console.WriteLine("Invalid choice."); break; } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } async Task GetProfileAsync(IATProtoClient client, string actor) { var parameters = new GetProfileParameters { Actor = new ATHandle(actor) }; var profile = await client.AppBskyActorGetProfileAsync(parameters); Console.WriteLine($" Display Name: {profile.DisplayName}"); Console.WriteLine($" Handle: {profile.Handle}"); Console.WriteLine($" DID: {profile.Did}"); Console.WriteLine($" Followers: {profile.FollowersCount}"); Console.WriteLine($" Following: {profile.FollowsCount}"); Console.WriteLine($" Posts: {profile.PostsCount}"); if (!string.IsNullOrEmpty(profile.Description)) { Console.WriteLine($" Bio: {profile.Description}"); } } async Task GetPreferencesAsync(IATProtoClient client) { var prefs = await client.AppBskyActorGetPreferencesAsync(); Console.WriteLine($" Preferences count: {prefs.Preferences?.Count ?? 0}"); } async Task GetTimelineAsync(IATProtoClient client) { var parameters = new GetTimelineParameters { Limit = 5 }; var timeline = await client.AppBskyFeedGetTimelineAsync(parameters); Console.WriteLine($" Feed items: {timeline.Feed?.Count ?? 0}"); if (timeline.Feed != null) { foreach (var item in timeline.Feed) { var author = item.Post?.Author; Console.WriteLine($" - @{author?.Handle}: (post by {author?.DisplayName})"); } } } async Task GetPostsAsync(IATProtoClient client) { Console.WriteLine("Enter AT URIs (one per line, blank line to finish):"); var uris = new List