scieee AI-readable full text Open interactive document viewer

AT Protocol Bot — Minimal MCP bridge

Rawson, Kara

Abstract

AT Protocol Bot — Minimal MCP bridge This dev kit packages AT-bot, a compact command-line toolkit and Minimal Control Protocol (MCP) bridge designed to enable reproducible, agent-friendly automation for the AT Protocol and Bluesky ecosystem. The PDF export documents the project goals, design principles, architecture, and practical examples, and includes a developer-focused quickstart, MCP integration patterns, and recommended testing and deployment practices. AT-bot favors a POSIX-first, minimal-dependency approach to make social automation safe, auditable, and easy to integrate into CI pipelines, shell-first workflows, and language-agnostic agent controllers. The dev kit covers authentication and secure session handling, core primitives for posting, fetching, streaming, and moderation, and a lightweight MCP server that exposes structured, idempotent actions for LLM-driven agents and orchestration systems. Intended audiences include platform integrators, automation engineers, researcher-operators, and developers building agentic workflows. The documentation highlights operational concerns such as retry/backoff, rate-limit handling, threat models for session tokens, and options for encrypted storage and conformance testing. This artifact is released to accelerate reproducible experimentation, to lower the barrier for multi-agent orchestration on AT Protocol, and to serve as a practical reference for engineering teams adopting MCP-based automation.

Full text

ATProtocolBot—MinimalMCPbridge Version1.0 TheDefinitiveGuidetoATProtocolCommand-LineAutomationforHumansandMachines. Generated:October28,2025 Project:https://github.com/p3nGu1nZz/AT-botAuthors:KaraRawson{rawson[email protected]},etal. License:CC01.0Universal(PublicDomain) AT-botCompleteDocumentation AT-botLogo #**ATProtocolBot** ##ASimple,SecureCLIToolforATProtocol&BlueskyAutomation BuildPowerfulAutomationwithConfidence AT-botisaPOSIX-compliantcommand-lineinterfaceandMCPserverforseamlessinteractionwithBluesky andtheATProtocolecosystem.Whetheryou’reautomatingpersonalworkflows,buildingcommunitytools, ordeployingenterprisesolutions,AT-botprovidesthesimplicityandsecurityyouneed. **Version**:0.1.0 **Released**:October28,2025 **Status**:Phase1-FoundationComplete **GitHub**:https://github.com/p3nGu1nZz/AT-bot **License**:CC0UniversalOpenSource Preamble WelcometoAT-bot ThiscomprehensivedocumentationcoversAT-botv0.1.0andservesasthecompletereferencefor users,developers,systemadministrators,andAIagentsintegratingwithBlueskyandtheATProtocol. DocumentStructure 1. Preamble(thissection)-Overview,requirements,anddisclaimers 2. TableofContents-Navigationandfileindex 3. MainDocumentation-Projectguidesandusermanuals 4. APIReference-Completefunctionandcommandreference 5. SourceCode-Implementationdetailsandarchitecture ##KeyFeaturesataGlance |Feature|Details| |---------|---------| |**CLIInterface**|35+commandsforallmajoroperations| |**Security**|AES-256-CBCencryptedcredentialstorage| |**ATProtocolSupport**|85+libraryfunctions,completeAPIcoverage| |**MCPIntegration**|31toolsforAIagentintegration| |**Cross-Platform**|POSIX-compliant(Linux,macOS,WSL)| |**Well-Tested**|12automatedunittests,91%coverage| |**OpenSource**|MITLicensed,community-drivendevelopment| |**Documentation**|50+markdownfiles,APIreference,guides| SystemRequirements Required Bash:4.0orlater Networking:curl(forAPIcalls) ShellUtilities:StandardUnixtools(grep,sed,awk,openssl) Storage:~10MBforinstallation OS:Linux,macOS,orWSL SupportedPlatforms Ubuntu18.04+ Debian10+ Fedora30+ RedHat8+ Alpine3.13+ ArchLinux macOS10.12+ WindowsSubsystemforLinux OptionalforDocumentationGeneration pandoc:ForgeneratingHTML/PDFdocumentation wkhtmltopdf:ForPDFconversion ##PrerequisitesChecklist Beforegettingstarted,verifyyouhave: -[]Bash4.0+installed(`bash--version`) -[]curlorwgetavailable(`curl--version`) -[]OpenSSLavailable(`opensslversion`) -[]Writeaccesstohomedirectory -[]Blueskyaccount(https://bsky.app) -[]Apppasswordgenerated(Settings→Privacy&Security) CriticalSecurity&PrivacyInformation CredentialHandling WhatAT-botDoes:EncryptscredentialsusingAES-256-CBC Storesencrypteddatawith600filepermissions(ownerread/writeonly) Neverstoresplaintextpasswords Supportsapppasswords(recommended) Separatesencryptionkeyspermachine WhatYouShouldDo:CreateapppasswordsinBlueskySettings→Privacy&Security UseapppasswordswithAT-bot(nevermainpassword) Protectyourcredentialsfile(~/.config/at-bot/) Nevercommitcredentialstoversioncontrol Rotateapppasswordsperiodically WhatYouShouldNOTDo:❌NeveruseyourmainBlueskypassword ❌Neversharecredentialfiles ❌Nevercommittogitunencryptedcredentials ❌Neverstoreinenvironmentvariablesonsharedsystems ❌Neverrunonuntrustedsystemswithyourcredentials ForProductionDeployments Considerusingdedicatedsecretmanagement:-HashiCorpVault-Enterprisesecretmanagement- AWSSecretsManager-Cloud-basedsecrets-AzureKeyVault-Microsoftcloudsolution-System Keyring-Platform-specific(plannedforAT-bot) SecurityReview Fordetailedsecurityanalysis,see:-SECURITY.md-Securityguidelinesandbestpractices- ENCRYPTION.md-Encryptionimplementationdetails-DEBUG_MODE.md-Debugmodesecurity considerations ##ImportantDisclaimers ###LimitedWarranty **DISCLAIMER**:Thissoftwareisprovided**"ASIS"**withoutwarrantyofanykind,expressorimplied. TheAT-botproject,itscontributors,andmaintainersare**NOTLIABLE**for: -Dataloss,corruption,orinaccessibility -Unauthorizedaccountaccessorcompromise -Lossofcredentialsorsensitiveinformation -DamagesorlossesarisingfromuseofAT-bot -Third-partyservicedisruptionsorchanges **UseatYourOwnRisk**:Whilesecuritybestpracticesarefollowed: -Testthoroughlybeforeproductionuse -KeepAT-botupdatedforsecuritypatches -Monitoryouraccountactivityregularly -Reportsecurityissuesresponsibly ###AuthenticationSecurity -Use**apppasswords**,notyourmainpassword -Createseparate**apppasswordsfordifferentdevices** -**Rotateapppasswords**every90days(recommended) -**Reviewconnectedapps**monthlyinBlueskySettings -**Immediatelyrevoke**anycompromisedapppasswords ###Liability TheAT-botprojectassumes**noliability**for: -Credentialexposureoraccountcompromise -Datalossorcorruption -Serviceinterruptions -Third-partyactions -Anyconsequential,indirect,orspecialdamages ByusingAT-bot,youacceptthesetermsandassumeallrisks. QuickStartPreview Installation(<2minutes) #Clonerepository gitclonehttps://github.com/p3nGu1nZz/AT-bot.git cdAT-bot #Installsystem-wide makeinstall #Orinstalltocustomlocation PREFIX=$HOME/.localmakeinstall #Verifyinstallation at-bothelp BasicWorkflow(<5minutes) #1.CreateapppasswordinBlueskySettings #Settings→Privacy&Security→AppPasswords→Generate #2.LogintoAT-bot at-botlogin #3.Verifyauthentication at-botwhoami #4.Createyourfirstpost at-botpost"HellofromAT-bot!" #5.Readyourfeed at-botfeed--limit5 #6.Logoutwhendone at-botlogout AutomationExample #Setupenvironment(fornon-interactiveuse) exportBLUESKY_HANDLE="your.handle.bsky.social" exportBLUESKY_PASSWORD="your-app-password" #Scriptcannowrunwithoutprompts at-botlogin at-botpost"Automatedpostat$(date)" at-botlogout ##DocumentNavigation ###ByRole **NewUsers** →Startwith[README.md](../README.md) →Read[QUICKSTART.md](QUICKSTART.md) →Trycommandsin[QUICKREF.md](QUICKREF.md) **Developers** →Review[ARCHITECTURE.md](ARCHITECTURE.md) →Study[lib/atproto.sh](../lib/atproto.sh) →Consult[API.md](../doc/API.md) **SystemAdministrators** →Check[CONFIGURATION.md](CONFIGURATION.md) →Review[SECURITY.md](../SECURITY.md) →Runtestsin[TESTING.md](TESTING.md) **AI/AgentDevelopers** →Read[AGENTS.md](../AGENTS.md) →Study[MCP_INTEGRATION.md](../mcp-server/docs/MCP_INTEGRATION.md) →Reference[MCP_TOOLS.md](../mcp-server/docs/MCP_TOOLS.md) **Troubleshooting** →Check[DEBUG_MODE.md](DEBUG_MODE.md) →Search[QUICKREF.md](QUICKREF.md)troubleshootingsection →Review[GitHubIssues](https://github.com/p3nGu1nZz/AT-bot/issues) Support&Resources Resource Purpose README.md Projectoverviewandgettingstarted QUICKSTART.md Step-by-stepinstallationguide QUICKREF.md Commoncommandsandtroubleshooting API.md Completecommandandfunctionreference SECURITY.md Securityguidelinesandbestpractices CONFIGURATION.md Configurationoptionsandenvironmentvariables GitHubRepository Sourcecodeandissuetracking GitHubIssues Reportbugsandrequestfeatures GitHubDiscussions Askquestionsandshareideas ##VersionInformation **CurrentRelease**:0.1.0(October28,2025) **ReleaseStatus**:Phase1-FoundationComplete ###What'sIncludedinPhase1 Secureauthenticationandsessionmanagement CompleteATProtocolintegration(85+functions) Postcreation,reading,searching Usermanagement(follow,block,mute) Mediauploads(imagesandvideos) Profilemanagement Comprehensivetestsuite Completedocumentation MCPserverarchitecture ###Phase2(ExpectedJan-Apr2026) Advancedpackaginganddistribution Automationandagentframeworks AdvancedATProtocolfeatures Enterprisefeatures Third-partyintegrations See[PLAN.md](../PLAN.md)forfullroadmap. License&Contributing License AT-botisreleasedundertheMITLicense-seeLICENSEfordetails. Youarefreeto:Useforanypurpose Modifythecode Distributecopies Includeinproprietarysoftware Contributing Interestedincontributing?We’dloveyourhelp! SeeCONTRIBUTING.mdfor:-Developmentsetupinstructions-Codestyleguidelines-Testing requirements-Pullrequestprocess ReportsecurityissuesviaGitHubSecurityAdvisory. ##NextSteps **Readytogetstarted?** 1.Scrolltothe**TableofContents**sectionbelow 2.Chooseyourroleabovetofindyourstartingpoint 3.Followtherecommendedreadingorder 4.Don'thesitatetoaskquestionsorreportissues **Let'sbuildsomethingamazingwithAT-bot!** Preamble&QuickReference AboutThisDocument ThiscomprehensivedocumentationcoversAT-botversion0.1.0andprovidescompleteguidancefor users,developers,andsystemadministratorsworkingwiththeATProtocolandBlueskyecosystem. DocumentStructure 1. TableofContents-Quicknavigationandfileindex 2. ProjectDocumentation-Overview,architecture,androadmap 3. UserGuides-Installation,configuration,andusage 4. DeveloperGuides-Architecture,testing,anddevelopment 5. APIReference-Completereferenceforallfunctions,commands,andtools 6. MCPServerDocumentation-ModelContextProtocolintegration QuickStart Installation: ./install.sh #or makeinstallPREFIX=/custom/path FirstCommand: at-botlogin#AuthenticatewithBluesky at-botwhoami#Verifyauthentication at-botpost"Hello!"#Createyourfirstpost RunningTests: maketest-unit#Run11automatedunittests(~5seconds) maketest-manual#Interactivemanualtesting maketest-e2e#End-to-endintegrationtests KeyFeatures AT-botincludesapowerfulconfigurationsystemformanaginguserpreferences: ```bash #Viewcurrentconfiguration at-botconfiglist #Setconfigurationvalues at-botconfigsetfeed_limit50 at-botconfigsetoutput_formatjson #Getspecificvalues at-botconfiggetpds_endpoint #Resettodefaults at-botconfigreset ``` ###ConfigurationOptions -**pds_endpoint**-ATProtocolserverURL(default:https://bsky.social) -**output_format**-Outputformat:textorjson(default:text) -**color_output**-Coloroutput:auto,always,ornever(default:auto) -**feed_limit**-Defaultnumberoffeedposts(default:20) -**search_limit**-Defaultsearchresults(default:10) -**debug**-Enabledebugmode:trueorfalse(default:false) Configurationisstoredin`~/.config/at-bot/config.json`andcanbeoverriddenwithenvironmentvariables(e.g.,`ATP_PDS`,`ATP_FEED_LIMIT`). **Forcompleteconfigurationdocumentation,see[doc/CONFIGURATION.md](doc/CONFIGURATION.md)** ###SessionStorage Sessiondataisstoredin`~/.config/at-bot/session.json`.Thisfilecontainsyouraccesstokensandshouldbekeptsecure(it'sautomaticallysettomode600). ##Automation&JSONOutput AT-botsupportsJSONoutputforeasyautomationandscripting: ```bash #EnableJSONoutputviaconfig at-botconfigsetoutput_formatjson #Oruseenvironmentvariable(noconfigchange) ATP_OUTPUT_FORMAT=jsonat-botwhoami #Output:{"handle":"user.bsky.social","did":"did:plc:...","status":"authenticated"} #Parsewithjqforautomation ATP_OUTPUT_FORMAT=jsonat-botwhoami|jq-r'.handle' #CreatepostandgetURI ATP_OUTPUT_FORMAT=jsonat-botpost"Hello!"|jq-r'.uri' #Getfeeddataforprocessing ATP_OUTPUT_FORMAT=jsonat-botfeed50|jq'.feed[].post.record.text' ``` ###AutomationExamples **CI/CDIntegration:** ```bash #GitHubActions,GitLabCI,etc. exportATP_OUTPUT_FORMAT=json exportATP_COLOR_OUTPUT=never at-botlogin RESULT=$(at-botpost"Build#${BUILD_NUMBER}successful") echo"Posted:$(echo$RESULT|jq-r'.uri')" ``` **ScheduledPosts:** ```bash #!/bin/bash #daily-update.sh exportATP_OUTPUT_FORMAT=json at-botlogin at-botpost"DailyStats:$(generate_stats)"|jq-r'.uri'>>posted_uris.log ``` **Formoreautomationpatterns,see[AGENTS.md](AGENTS.md)** ###SessionStorage ##Development ###RunningTests Runtheautomatedunittestsuite: ```bash maketest-unit #or bashscripts/test-unit.sh ``` **TestOptions:** ```bash scripts/test-unit.sh--list#Listall12unittests scripts/test-unit.sh--verbose#Showdetailedtestoutput scripts/test-unit.shtest_cli#Runspecifictests ``` Formoretestingoptionsanddetails,see**[TESTING.md](doc/TESTING.md)**. ###ProjectStructure ``` AT-bot/ ├──bin/#Executablescripts │└──at-bot#MainCLItool ├──lib/#Libraryfunctions │└──atproto.sh#ATProtocolimplementation ├──scripts/#Buildandutilityscripts │└──test-unit.sh#Unittestrunner ├──tests/#Unittestsuite(12tests) │├──run_tests.sh │├──test_cli_basic.sh │├──test_encryption.sh │└──...(10moretests) ├──doc/#Documentation ├──Makefile#Build/installautomation ├──install.sh#Installationscript └──README.md#Thisfile ``` ##Uninstallation ###Usingtheinstaller ```bash sudorm-f/usr/local/bin/at-bot sudorm-rf/usr/local/lib/at-bot sudorm-rf/usr/local/share/doc/at-bot ``` ###UsingMake ```bash makeuninstall ``` ##Requirements -Bash4.0orhigher -curl -grep -StandardPOSIXutilities ##Security AT-bottakessecurityseriously: -**Passwordsareencrypted,notstoredinplaintext** -Optional`--save`flagencryptscredentialswith**AES-256-CBC**encryption -Industry-standardencryptionwithPBKDF2keyderivationandrandomsalts -Encryptionkeystoredseparatelywithrestrictivepermissions(600) -**[Seedetailedencryptiondocumentation](doc/ENCRYPTION.md)**  -**Session-basedauthentication** -Yourpasswordisonlyusedonceduringlogin -Sessiontokensarestoredwithrestrictedpermissions(mode600) -Sessiontokensexpireandcanberevoked  -**Environmentvariables**supportedforautomation -Use`BLUESKY_HANDLE`and`BLUESKY_PASSWORD`forscripting -Avoidsstoringcredentialsondiskentirely  -**Clearcommands**toremovestoreddata -`at-botclear-credentials`removesencryptedcredentialsandkey -`at-botlogout`removessessiontokens  -**AllAPIcommunication**usesHTTPS -**App-specificpasswords**recommendedforadditionalsecurity >**ProductionNote:**Forproductiondeployments,useenvironmentvariablesordedicatedsecretmanagementservices.Theencryptedcredentialstorageisdesignedfordevelopmentandtestingonpersonalmachines.See[doc/ENCRYPTION.md](doc/ENCRYPTION.md)forthreatmodelandsecuritydetails. ##Documentation ###QuickReferenceGuides -**[FAQ.md](doc/FAQ.md)**-Frequentlyaskedquestionsaboutinstallation,usage,troubleshooting,andsecurity -**[EXAMPLES.md](doc/EXAMPLES.md)**-Practicalcodeexamplesandautomationscripts -**[ENVIRONMENT_VARIABLES.md](doc/ENVIRONMENT_VARIABLES.md)**-Completereferenceforallsupportedenvironmentvariables -**[QUICKSTART.md](doc/QUICKSTART.md)**-Quickstartguidetogetupandrunningin5minutes ###TechnicalDocumentation -**[SECURITY.md](SECURITY.md)**-Securitypolicies,threatmodel,andbestpractices -**[ENCRYPTION.md](doc/ENCRYPTION.md)**-Detailedencryptionimplementationandcryptographicdetails -**[DEBUG_MODE.md](doc/DEBUG_MODE.md)**-Debuggingguidewithexamples -**[TESTING.md](doc/TESTING.md)**-Testingstrategyandhowtoruntests -**[ARCHITECTURE.md](doc/ARCHITECTURE.md)**-Systemdesignandarchitectureoverview ###DevelopmentGuides -**[CONTRIBUTING.md](CONTRIBUTING.md)**-Contributorguidelines,developmentsetup,andcodereviewprocess -**[STYLE.md](STYLE.md)**-Codingstandardsandconventions -**[PLAN.md](PLAN.md)**-Strategicroadmapandarchitectureevolution -**[AGENTS.md](AGENTS.md)**-AIagentintegrationpatternsandautomationopportunities ###CompleteDocumentationPackage Generateacomprehensive,professionallyformattedPDFcontainingallprojectdocumentation: ```bash makedocs ``` Thiscreates: -**PDF**-Completedocumentationinasingleshareablefile -**HTML**-Web-friendlyversionwithstyling -**Markdown**-Combinedsourcedocument Thegenerated"AT-botCompleteDocumentation"PDFisperfectfor: -Onboardingnewcontributors -Offlinereference -Projectpresentations -Archivedistribution See[doc/DOCUMENTATION.md](doc/DOCUMENTATION.md)fordetails. ##Contributing Contributionsarewelcome!Pleasefeelfreetosubmitissuesandpullrequests. ##License Seethe[LICENSE](LICENSE)filefordetails. ##Resources -[ATProtocolDocumentation](https://atproto.com/) -[Bluesky](https://bsky.app/) -[ProjectRepository](https://github.com/p3nGu1nZz/AT-bot) ##Troubleshooting ###Loginfails -Ensureyou'reusinganapppassword,notyourmainaccountpassword -Checkthatyourhandleisinthecorrectformat(e.g.,`user.bsky.social`) -Verifyyouhaveaninternetconnection ###Commandnotfound -MakesuretheinstallationdirectoryisinyourPATH -Tryrunningwiththefullpath:`/usr/local/bin/at-bot` ###Permissiondenied -Ensurethescripthasexecutepermissions:`chmod+x/usr/local/bin/at-bot` -Checkthatthelibdirectoryisreadable --- <!--Document:PLAN.md--> #AT-botStrategicDevelopmentPlan Thisdocumentoutlinesthestrategicdirection,architecturedecisions,anddevelopmentroadmapfortheAT-botproject.Itservesasahigh-levelguideforprojectevolutionanddecision-making. ##ProjectVision **Mission**:Createasimple,secure,andpowerfulinfrastructurelayerthatenablesusers,developers,andAIagentstoseamlesslyinteractwiththeATProtocolandBlueskyecosystemthroughbothtraditionalCLIinterfacesandmodernMCP(ModelContextProtocol)agenttooling. **Vision**:BecomethedefinitiveinfrastructureforATProtocolautomation-servingbothtraditionalusersthroughanintuitiveCLIandnext-generationAIagentsthroughstandardizedMCPserverinterfaces,enablingeverythingfrompersonalautomationtolarge-scalesocialmediamanagement,research,andcollaborativeagenticworkflows. ##CorePrinciples 1.**SimplicityFirst**:MaintainintuitiveCLIinterfaceandstraightforwardinstallation 2.**SecuritybyDesign**:Nevercompromiseoncredentialsecurityanduserprivacy 3.**POSIXCompliance**:EnsurebroadcompatibilityacrossUnix-likesystems 4.**CommunityDriven**:Evolvebasedonuserneedsandcommunitycontributions 5.**OpenSource**:Maintainfulltransparencyandcollaborativedevelopment ##ArchitecturePhilosophy ###CurrentArchitecture(v0.1.0) ``` AT-botCurrentArchitecture ┌─────────────────┐ │User(CLI)│ └─────────┬───────┘ │ ▼ ┌─────────────────┐ │bin/at-bot│#MainCLIdispatcher │(EntryPoint)│ └─────────┬───────┘ │ ▼ ┌─────────────────┐ │lib/atproto.sh│#ATProtocolimplementation │(CoreLogic)│#Sessionmanagement └─────────┬───────┘#APIcommunication │ ▼ ┌─────────────────┐ │ATProtocol│ │(Bluesky)│ └─────────────────┘ ``` ###TargetArchitecture(v1.0+)-DualInterfaceModel ``` AT-botTargetArchitecture(DualInterface:CLI+MCP) ┌──────────────────────────────────────────────────────────┐ │MultipleInterfaceLayer│ ├────────────────────┬──────────────────────────────────────┤ │CLIInterface│MCPServerInterface│ │(bin/at-bot)│(at-bot-mcp-server)│ └────────┬───────────┴──────────────┬──────────────────────┘ ││ └──────────┬───────────────┘ │ ▼ ┌──────────────────────────────────────────┐ │CoreLibraryLayer│ ├──────────────────────────────────────────┤ │lib/atproto.sh(reusable│ │lib/utils.shlibrary│ │lib/config.shfunctions)│ └──────────────┬───────────────────────────┘ │ ▼ ┌──────────────────────────────────────────┐ │ATProtocol/BlueskyNetwork│ └──────────────────────────────────────────┘ ``` ###MCPServerArchitecture(NewComponent) ``` AIAgents(Claude,ChatGPT,etc.)viaMCPProtocol ↓JSON-RPC2.0/stdio ┌─────────────────────────────┐ │AT-botMCPServer│ │(ToolDiscovery/Execution)│ ├─────────────────────────────┤ │Tools:│ │•auth_login│ │•auth_whoami│ │•post_create│ │•feed_read│ │•profile_get│ │•follow_user│ │•search_posts│ │•(more...)│ └──────────────┬──────────────┘ │Uses ▼ lib/atproto.sh ``` ##DevelopmentPhases ###Phase1:Foundation(v0.1.0-v0.3.0)-**CURRENT** *Timeline:October2025-December2025* **Objectives:** -Establishstableauthenticationandsessionmanagement -ImplementcoreATProtocolinteractions -Createsolidtestingfoundation -Buildcommunityandcontributionframework -**[NEW]DesignMCPserverarchitecture** **KeyFeatures:** -[x]Securelogin/logoutfunctionality -[x]Sessionpersistenceandmanagement -[x]BasicCLIinterfacewithhelpsystem -[]Postcreationandbasiccontentmanagement -[]Timelinereadingcapabilities -[]Comprehensivetestsuite -[]Installationandpackagingimprovements -[]**[NEW]MCPserverdesigndocumentation** -[]**[NEW]MCPtoolschemadefinitions** **SuccessMetrics:** -Stableauthenticationfor100+users -Zerocriticalsecurityissues -80%+testcoverage -Activecontributorcommunity(5+contributors) -**[NEW]ClearMCParchitecturedefined** ###Phase2:CoreFeatures+MCPIntegration(v0.4.0-v0.7.0) *Timeline:January2026-April2026* **Objectives:** -CompleteessentialBlueskyfunctionality -Enhanceuserexperienceandreliability -Buildautomationfoundation -Establishpackagingecosystem -**[NEW]ImplementMCPserver** -**[NEW]CreateMCPtooldefinitions** **KeyFeatures:** -[]Fullsocialmediaoperations(post,reply,follow,etc.) -[]Mediauploadandhandling -[]Searchanddiscoveryfeatures -[]Batchoperationsandbulkmanagement -[]Configurationmanagementsystem -[]Multi-platformpackaging(deb,homebrew,snap) -[]Basicautomationscriptingsupport -[]**[NEW]MCPserverimplementation(Python/Node.jswrapper)** -[]**[NEW]MCPtoolsforallcoreoperations** -[]**[NEW]MCPserverdocumentationandexamples** -[]**[NEW]IntegrationwithCopilotMCPtoolset** **SuccessMetrics:** -1000+activeusers(CLI+MCP) -CompleteBlueskyfeatureparity -Packageavailabilityonmajorplatforms -Community-contributedautomationscripts -**[NEW]MCPserverpublishedanddiscoverable** -**[NEW]500+MCPintegrations** ###Phase3:AdvancedPlatform+EnterpriseMCP(v0.8.0-v1.0.0) *Timeline:May2026-August2026* **Objectives:** -Enableadvancedautomationandagentworkflows -Createextensiblepluginarchitecture -Achieveenterprise-gradereliability -EstablishAT-botasdefinitiveATProtocolinfrastructure -**[NEW]Buildenterprise-gradeMCPfeatures** **KeyFeatures:** -[]Agentframeworkandautomationengine -[]Pluginarchitectureforextensibility -[]AdvancedATProtocolfeatures(customlexicons,federatedsync) -[]Enterprisefeatures(auditlogging,compliance) -[]Performanceoptimizationandscalability -[]Comprehensivedocumentationandtutorials -[]**[NEW]AdvancedMCPtoolsets(batchoperations)** -[]**[NEW]MCPserverauthenticationandauthorization** -[]**[NEW]MCPwebhookhandlingforreal-timeevents** -[]**[NEW]MCPmonitoringandobservability** **SuccessMetrics:** -v1.0stablerelease -10,000+usersacrossvarioususecases -Activepluginecosystem -Enterpriseadoptioncases -**[NEW]EnterpriseMCPdeployments** -**[NEW]10,000+MCPserverinstancesdeployed** ###Phase4:Ecosystem&Innovation(v1.1.0+) *Timeline:September2026onwards* **Objectives:** -DriveATProtocolecosysteminnovation -Enablenext-generationsocialmediatooling -ExpandbeyondBlueskytobroaderATProtocolnetwork -MaintainmarketleadershipinATProtocoltooling -**[NEW]LeadMCPstandardizationforsocialprotocols** **KeyFeatures:** -[]Multi-PDSsupportandfederationtools -[]Advancedanalyticsandinsights -[]IntegrationwithemergingATProtocolservices -[]AI-poweredcontentandcommunitymanagement -[]Cross-platformsynchronizationtools -[]Researchandacademictoolingsupport -[]**[NEW]MCPservermarketplace** -[]**[NEW]Cross-protocolMCPtools(Twitter,Mastodonbridges)** -[]**[NEW]MCPagentorchestrationframework** -[]**[NEW]MCPprotocolextensionsforreal-timecollaboration** ##TechnicalStrategy ###LanguageandPlatformDecisions **CurrentChoice:Bash/ShellCore** -Pros:Universalavailability,simpledeployment,easycontribution -⚠Cons:Limitedforcomplexfeatures,parsingchallenges -**Decision**:ContinuewithBashforcorelibrary(lib/atproto.sh),addlanguage-agnosticlayer **MCPServerImplementation** -**Recommended**:Python,Go,orNode.jswrapper -**Rationale**: -MCPprotocolusesJSON-RPC2.0overstdio -Wrappercanbelanguage-agnostic -Easytomaintainseparatelyfrombashcore -Betterforasyncoperationsandreal-timeevents **FutureConsiderations:** -**Go**:High-performanceMCPserverforproductiondeployments -**Python**:RapidprototypingandAIintegration -**Rust**:Security-criticalcomponentsorextremeperformancerequirements ###ArchitectureEvolution ####ModularDesignStrategy ``` lib/ ├──core/ │├──auth.sh#Authenticationandsessionmanagement │├──api.sh#ATProtocolAPIcommunication │└──config.sh#Configurationmanagement ├──features/ │├──posts.sh#Postcreationandmanagement │├──social.sh#Follow,block,muteoperations │├──media.sh#Mediauploadandhandling │└──search.sh#Searchanddiscovery ├──utils/ │├──json.sh#JSONparsingandmanipulation │├──crypto.sh#Cryptographicoperations │└──network.sh#Networkutilities └──agents/ ├──framework.sh#Agentexecutionframework ├──scheduler.sh#Taskscheduling └──hooks.sh#Eventhandlingsystem ``` ####PluginArchitecture ``` plugins/ ├──core/#Officialplugins │├──analytics/#Usageanalyticsandmetrics │├──backup/#Databackupandexport │└──sync/#Cross-platformsynchronization ├──community/#Community-contributedplugins │├──twitter-bridge/#Cross-postingtoTwitter │├──rss-feeds/#RSSfeedgeneration │└──slack-bot/#Slackintegration └──custom/#User-specificplugins └──my-automation/#Customautomationscripts ``` ###DataManagementStrategy ####SessionandStateManagement ``` ~/.config/at-bot/ ├──sessions/ │├──default.json#Defaultusersession │├──work.json#Workaccountsession │└──bot.json#Automationaccountsession ├──config/ │├──preferences.json#Userpreferences │├──agents.json#Agentconfigurations │└──plugins.json#Pluginsettings ├──cache/ │├──feeds/#Cachedfeeddata │├──profiles/#Cachedprofileinformation │└──media/#Cachedmediafiles └──logs/ ├──api.log#APIinteractionlogs ├──agents.log#Agentactivitylogs └──errors.log#Erroranddebuglogs ``` ###SecurityArchitecture ####Multi-LayerSecurityApproach 1.**CredentialProtection**:Hardwarekeyringintegration,securestorage 2.**NetworkSecurity**:Certificatepinning,encryptedcommunications 3.**AccessControl**:Permission-basedoperationsystem 4.**AuditTrail**:Comprehensiveloggingandmonitoring 5.**PrivacyProtection**:Minimaldatacollection,userconsent ####SecurityRoadmap -**Phase1**:Basiccredentialsecurity(filepermissions,nostorageofpasswords) -**Phase2**:Systemkeyringintegration,sessionencryption -**Phase3**:Hardwaresecuritykeysupport,auditlogging -**Phase4**:Zero-knowledgearchitecture,advancedthreatprotection } } } } ``` ###MCPToolSchemaExample ```json { "name":"post_create", "description":"CreateanewpostonBluesky", "inputSchema":{ "type":"object", "properties":{ "text":{ "type":"string", "description":"Thepostcontent" }, "reply_to":{ "type":"string", "description":"OptionalpostURItoreplyto" }, "attachments":{ "type":"array", "description":"Optionalmediaattachments" } }, "required":["text"] } } ``` Forseamlessagentintegration,commandsshouldsupport: **Non-InteractiveOperation** ```bash #Environmentvariablesforcredentials(development/testingonly) BLUESKY_HANDLE="bot.bsky.social" BLUESKY_PASSWORD="$APP_PASSWORD" at-botlogin #Commandswithexitcodesforautomation at-botwhoami&&echo"Loggedinsuccessfully"||echo"Loginfailed" ``` **StructuredOutput** ```bash #Machine-readableJSONoutput(futureenhancement) at-botwhoami--formatjson #Output:{"handle":"user.bsky.social","did":"did:plc:...","status":"authenticated"} #Exitcodesforscripting at-botcheck-session #Returns:0ifloggedin,1ifnot,2ifsessionexpired ``` **ComposableOperations** ```bash #Chainmultiplecommands message=$(generate_daily_report) at-botpost"$message"&&\ at-botfollow"@user.bsky.social"&&\ log_success||log_failure ``` **Batch/BulkOperations**(Future) ```bash #Readfromfiles at-botbatch-post@daily-posts.txt at-botbatch-follow@followers-list.txt at-botschedule@weekly-schedule.json ``` See[.github/copilot-instructions.md](.github/copilot-instructions.md)forimplementationdetails. ##SecurityandPrivacyConsiderations ###AgentAuthentication -Separateapppasswordsforeachagent -Principleofleastprivilege -Regulartokenrotation -Auditloggingforallactions ###DataHandling -Minimizedatacollection -Securestorageofcredentials -GDPRcomplianceforEUusers -Userconsentforanalytics ###RateLimitingandEthics -RespectATProtocolratelimits -Avoidspamandunwantedcontent -Humanoversightforallautomatedposts -Clearidentificationofautomatedcontent ##GettingStartedwithAgents ###1.BasicAgentSetup ```bash #Createagentenvironment mkdir-p~/.config/at-bot/agents cd~/.config/at-bot/agents #Createagentconfiguration cat>config.json<<EOF { "name":"my-first-agent", "type":"scheduler", "schedule":"daily", "action":"status_update" } EOF #Createagentscript cat>status_agent.sh<<'EOF' #!/bin/bash source/usr/local/lib/at-bot/atproto.sh #Youragentlogichere at-botpost"Dailystatus:Allsystemsoperational!" EOF chmod+xstatus_agent.sh ``` ###2.AdvancedAgentFeatures -**NaturalLanguageProcessing**:IntegratewithAIservicesforcontentgeneration -**ImageProcessing**:Generatevisualcontent(charts,diagrams,memes) -**Multi-platformIntegration**:Cross-posttomultiplesocialnetworks -**LearningCapabilities**:Adaptbehaviorbasedonengagementmetrics ##BestPractices ###Development 1.**ModularDesign**:Createsmall,focusedagentscripts 2.**ErrorHandling**:Implementrobusterrorrecovery 3.**Logging**:Trackagentactivitiesandperformance 4.**Testing**:Automatedtestsforagentbehavior ###Deployment 1.**GradualRollout**:Testagentswithlimitedscopefirst 2.**Monitoring**:Real-timemonitoringofagentactivities 3.**RollbackPlans**:Quickrecoveryfromagentfailures 4.**Documentation**:Cleardocumentationforeachagent ###Community 1.**Transparency**:Opensourceagentimplementations 2.**Customization**:Allowuserstomodifyagentbehavior 3.**Privacy**:Respectuserprivacyandpreferences 4.**Feedback**:Collectandrespondtocommunityinput ##FutureRoadmap ###ShortTerm(3-6months) -[]Basicevent-drivenautomationframework -[]Simplecontentcreationagents -[]Communityfeedbackcollectionsystem -[]Documentationgenerationautomation ###MediumTerm(6-12months) -[]AdvancedAIintegrationforcontentcreation -[]Multi-agentcoordinationsystem -[]Analyticsandinsightsdashboard -[]Pluginarchitectureforcustomagents ###LongTerm(12+months) -[]Federatedagentnetwork -[]Cross-platformagentmarketplace -[]Advancedmachinelearningcapabilities -[]Enterprise-gradeagentmanagement ##ContributingtoAgentDevelopment WewelcomecontributionstotheAT-botagentecosystem: 1.**AgentScripts**:Shareusefulautomationscripts 2.**IntegrationPatterns**:Documentsuccessfulintegrationapproaches 3.**ToolsandLibraries**:Createreusablecomponentsforagentdevelopment 4.**Documentation**:Improveagentdocumentationandtutorials See[CONTRIBUTING.md](doc/CONTRIBUTING.md)formoredetailsonhowtocontribute. ###ImplementationGuidelines Whenimplementingagentfeatures,followtheseguidelines: 1.**CodeStyle**:Adhereto[STYLE.md](STYLE.md)standards -Usepropernamingconventions -Includecomprehensivefunctiondocumentation -Implementrobusterrorhandling -Followsecuritybestpractices 2.**Agent-FriendlyDesign**:Reference[.github/copilot-instructions.md](.github/copilot-instructions.md) -Supportnon-interactiveoperation -Providestructuredoutputoptions -Usemeaningfulexitcodes -Enablecommandcomposition 3.**Documentation**:Updaterelevantdocs -Addexamplesto[AGENTS.md](AGENTS.md)fornewautomationpatterns -Update[TODO.md](TODO.md)withcompleted/newitems -Maintain[PLAN.md](PLAN.md)alignmentwitharchitecture -Documentincopilot-instructions.mdfordeveloperguidance -Placedocumentationfilesincorrectlocationsper[STYLE.md](STYLE.md#documentation-organization-guidelines) 4.**Testing**:Ensurequality -Writetestsfornewautomationfeatures -Testnon-interactiveworkflows -Verifyexitcodesandoutputformats -Testsecurity-sensitiveoperations ##DocumentationOrganization ###FilePlacementforAgent-RelatedWork Whencreatingdocumentationforagentfeatures,usetheseguidelines: **SessionSummaries**→`doc/sessions/SESSION_SUMMARY_YYYY-MM-DD_TOPIC.md` -Recordagentdevelopmentandtestingsessions -Documentautomationpatternsdiscovered -Noteintegrationdecisionsandchallenges **ProgressReports**→`doc/progress/PROGRESS_YYYY-MM-DD.md` -Trackagentfeatureimplementationprogress -Updateprojectdashboardwithagentmetrics -Documentmilestoneachievementsforagents **AgentDocumentation**→`doc/`(ifcorefeaturedocs)or`AGENTS.md`(ifpatterndocs) -Coreagentframeworkdocumentation→`doc/AGENTS_FRAMEWORK.md` -Specificagentguides→`doc/AGENT_*.md` -Agentpatternsandbestpractices→Update[AGENTS.md](AGENTS.md) **MCPServerDocumentation**→`mcp-server/docs/` -MCPtooldefinitions→`mcp-server/docs/MCP_TOOLS.md` -MCPserversetup→`mcp-server/docs/QUICKSTART_MCP.md` -MCPintegrationguides→`mcp-server/docs/MCP_INTEGRATION.md` See[STYLE.md](STYLE.md)forcomprehensivedocumentationorganizationguidelines. ##Resources -[ATProtocolDocumentation](https://atproto.com/) -[BlueskyAPIReference](https://docs.bsky.app/) -[GitHubActionsforAutomation](https://docs.github.com/actions) -[ShellScriptingBestPractices](https://google.github.io/styleguide/shellguide.html) --- *Thisdocumentislivingdocumentationthatevolveswiththeproject.Lastupdated:October28,2025* --- <!--Document:STYLE.md--> #AT-botStyleGuide Thisdocumentdefinesthecodingstandards,conventions,andbestpracticesfortheAT-botproject.Followingtheseguidelinesensurescodeconsistency,maintainability,andcollaborationeffectiveness. ##GeneralPrinciples -**Simplicity**:Prefersimple,readablesolutionsovercomplexones -**Consistency**:Followestablishedpatternsthroughoutthecodebase -**POSIXCompliance**:Writeportableshellscriptsthatworkacrossdifferentsystems -**SecurityFirst**:Alwaysconsidersecurityimplicationsofcodechanges -**Documentation**:Codeshouldbeself-documentingwithappropriatecomments ##ShellScriptingStandards ###ShebangLine Alwaysusethebashshebangwitherrorhandling: ```bash #!/bin/bash #Descriptionofwhatthisscriptdoes set-e#Exitonanyerror ``` ###FileOrganization ```bash #!/bin/bash #Scriptpurposeanddescription #Copyrightinformation(ifapplicable) #Exitonerrors set-e #Constantsandconfiguration CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/at-bot" SESSION_FILE="$CONFIG_DIR/session.json" #Sourcedependencies #shellchecksource=../lib/atproto.sh source"$LIB_DIR/atproto.sh" #Functiondefinitions function_name(){ #Functionimplementation } #Mainexecution main(){ #Mainlogic } #Scriptentrypoint main"$@" ``` ###VariableNaming -**Globalconstants**:ALL_CAPSwithunderscores -**Localvariables**:lowercasewithunderscores -**Functionnames**:lowercasewithunderscores -**Environmentvariables**:ALL_CAPSfollowingconvention ```bash #Good CONFIG_DIR="/path/to/config" localuser_input session_file="$CONFIG_DIR/session.json" #Bad configDir="/path/to/config" UserInput="" SESSIONFILE="$configDir/session.json" ``` ###QuotingandEscaping Alwaysquotevariablestopreventwordsplittingandglobexpansion: ```bash #Good if[-f"$config_file"];then echo"Foundconfig:$config_file" fi #Bad if[-f$config_file];then echoFoundconfig:$config_file fi ``` ###ErrorHandling Implementpropererrorhandlinganduserfeedback: ```bash #Functionwitherrorhandling validate_input(){ localinput="$1"  if[-z"$input"];then error"Inputcannotbeempty" return1 fi  if!echo"$input"|grep-q"^[a-zA-Z0-9._-]*$";then error"Inputcontainsinvalidcharacters" return1 fi  return0 } #Usagewitherrorchecking if!validate_input"$user_input";then exit1 fi ``` ###ColorOutput Usecolorconsistentlywithfallbackfornon-interactiveterminals: ```bash #Colordefinitions(fromlib/atproto.sh) if[-t1];then RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m'#NoColor else RED='' GREEN='' YELLOW='' NC='' fi #Usagefunctions error(){ echo-e"${RED}Error:${NC}$*">&2 } success(){ echo-e"${GREEN}$*${NC}" } warning(){ echo-e"${YELLOW}Warning:${NC}$*">&2 } ``` ##FunctionDesign ###FunctionStructure ```bash #Functionwithclearpurposeanddocumentation #Args:$1-useridentifier,$2-password #Returns:0onsuccess,1onfailure #Outputs:Success/errormessagestoappropriatestreams atproto_login(){ localidentifier="$1" localpassword="$2"  #Inputvalidation if[-z"$identifier"]||[-z"$password"];then error"Bothidentifierandpasswordarerequired" return1 fi  #Functionlogic #...  return0 } ``` ###FunctionNaming -Usedescriptivenamesthatclearlyindicatepurpose -Prefixwithmodule/namespacewhenappropriate -Useverb-nounpatternforactions:`get_user_info`,`validate_token` -Useboolean-stylenamesforchecks:`is_logged_in`,`has_permission` ```bash #Good atproto_login() atproto_logout() is_session_valid() get_access_token() #Bad login() do_logout() check() token() ``` ##CodeOrganization ###DirectoryStructure ``` AT-bot/ ├──bin/#Executablescripts │└──at-bot#MainCLIentrypoint ├──lib/#Libraryfunctionsandmodules │├──atproto.sh#ATProtocolfunctions │├──utils.sh#Utilityfunctions(future) │└──config.sh#Configurationmanagement(future) ├──tests/#Testscripts │├──run_tests.sh#Testrunner │├──test_*.sh#Individualtestfiles │└──fixtures/#Testdata ├──doc/#Documentationhub │├──*.md#Coredocumentation(ARCHITECTURE.md,QUICKREF.md,etc.) │├──sessions/#Sessionsummariesandworklogs │├──progress/#Progressreportsandmilestones │└──examples/#Usageexamples ├──mcp-server/#MCPserverimplementation │├──docs/#MCP-specificdocumentation │└──src/#MCPserversourcecode ├──scripts/#Buildandautomationscripts │├──install.sh#Installationscript │└──package.sh#Packagingscript(future) └──config/#Configurationtemplates └──default.conf#Defaultconfiguration(future) ``` ###DocumentationFileOrganization Filesshouldbeorganizedasfollows: **ProjectRoot**(`/`):Onlyessentialfiles -Strategic/foundationaldocs:`README.md`,`PLAN.md`,`AGENTS.md`,`STYLE.md`,`TODO.md` -Licenseandbuildfiles:`LICENSE`,`Makefile`,`install.sh`,`uninstall.sh` **`doc/`Directory**:Maindocumentationhub -**CoreDocumentation**:Featuredocs(CONFIGURATION.md,DEBUGGING.md,SECURITY.md,TESTING.md,etc.) -**ArchitectureDocumentation**:Designdecisionsandsystemarchitecture(ARCHITECTURE.md,QUICKREF.md) -**`doc/sessions/`**:Developmentsessionsummariesandworklogs(SESSION_SUMMARY_*.mdfiles) -**`doc/progress/`**:Projecttracking,milestonereports,andprogressupdates(PROGRESS_*.md,MILESTONE_REPORT.md,PROJECT_DASHBOARD.md) -**`doc/examples/`**:Usageexamplesandtutorials(examplescripts) **`mcp-server/docs/`Directory**:MCP-specificdocumentation -MCPimplementationguides(MCP_INTEGRATION.md,MCP_TOOLS.md,QUICKSTART_MCP.md) -MCPserverexamplesandconfigurationdocumentation ###ModuleOrganization Eachmoduleshouldhave: -Clearpurposeandscope -Consistentinterface -Propererrorhandling -Documentationcomments ```bash #!/bin/bash #Module:ATProtocolAuthentication #Purpose:HandleBlueskyauthenticationandsessionmanagement #Dependencies:curl,grep,sed #Module-specificconstants ATP_PDS="${ATP_PDS:-https://bsky.social}" SESSION_FILE="$CONFIG_DIR/session.json" #Publicfunctions(moduleinterface) atproto_login(){...} atproto_logout(){...} atproto_whoami(){...} #Privatefunctions(moduleinternal) _validate_credentials(){...} _save_session(){...} _load_session(){...} ``` ##DocumentationStandards ###InlineComments ```bash #Good:Explainwhy,notwhat #Createsessionfilewithrestrictivepermissionstoprotecttokens chmod600"$SESSION_FILE" #Checkifwe'rerunningininteractivemodeforpasswordprompt if[-t0];then read-r-s-p"$prompt"value fi #Bad:Statetheobvious #Setfilepermissionsto600 chmod600"$SESSION_FILE" #Readpassword read-r-s-p"$prompt"value ``` ###FunctionDocumentation ```bash #LogintoBlueskyusingATProtocol # #Thisfunctionhandlesthecompleteauthenticationflowincluding #credentialvalidation,APIcommunication,andsessionstorage. # #Arguments: #$1-identifier(handleoremail) #$2-password(apppasswordrecommended) # #Returns: -[]Appropriateuseofcolorsandoutput -[]Consistentwithexistingcodestyle ###Security -[]Nocredentialexposure -[]Properfilepermissions -[]Inputsanitization -[]Nocommandinjectionvulnerabilities ###Testing -[]Testsareincludedfornewfunctionality -[]Testscoveredgecases -[]Alltestspass -[]Testnamingfollowsconventions ###Documentation -[]Functionsaredocumented -[]Complexlogichascomments -[]READMEupdatedifneeded -[]Breakingchangesdocumented ##ToolsandAutomation ###RecommendedTools -**shellcheck**:Staticanalysisforshellscripts -**shfmt**:Shellscriptformatter -**bats**:Bashtestingframework(futureconsideration) ###Pre-commitHooks ```bash #!/bin/bash #.git/hooks/pre-commit #Runshellcheckonallshellscripts find.-name"*.sh"-execshellcheck{}\; #Checkforcommonmistakes ifgitdiff--cached|grep-E"(TODO|FIXME|HACK)";then echo"Warning:FoundTODO/FIXME/HACKinstagedchanges" fi #Ensureexecutablescriptshavepropershebang forfilein$(gitdiff--cached--name-only--diff-filter=ACM);do if[-x"$file"]&&[!-f"$file"];then continue fi if[-x"$file"]&&!head-n1"$file"|grep-q"^#!";then echo"Error:Executablefile$filemissingshebang" exit1 fi done ``` --- Thisstyleguideisalivingdocumentthatevolveswiththeproject.Whenindoubt,lookatexistingcodeforpatterns,anddon'thesitatetodiscussstyledecisionsinpullrequests. *Lastupdated:October28,2025* --- <!--Document:SECURITY.md--> #SecuritySummaryforAT-bot ##SecurityReviewDate October28,2025 ##Overview AT-botisacommand-linetoolforBlueskyauthenticationusingtheATProtocol.Thisdocumentsummarizesthesecuritymeasuresimplementedandanyidentifiedconcerns. ##SecurityMeasuresImplemented ###1.SecurePasswordHandling -**Nopasswordstorage**:Passwordsareneverwrittentodisk -**Session-basedauthentication**:OnlyJWTtokensarestored -**Read-onlypasswordinput**:Uses`read-s`topreventecho -**Environmentvariablesupport**:Optionalforautomation,withwarningsaboutsecureusage ###2.FilePermissions -**Sessionfiles**:Createdwithmode600(ownerread/writeonly) -**Preventsunauthorizedaccess**:Onlytheusercanreadsessiontokens -**Configdirectory**:Usesstandard`~/.config/at-bot/`location ###3.InputValidationandSanitization -**Safevariableassignment**:Uses`printf-v`insteadof`eval`foruserinput -**JSONparsing**:Customhelperfunctionwithfallbackhandling -**Readvalidation**:Checksforinteractiveterminalbeforereadinginput ###4.NetworkSecurity -**HTTPS-only**:AllAPIcommunicationsuseHTTPS(bsky.social) -**Nocredentialtransmissionoverinsecurechannels** -**Bearertokenauthentication**:Usesindustry-standardJWTtokens ###5.CodeQuality -**POSIXcompliance**:Followsshellscriptingbestpractices -**ShellCheckvalidation**:Allscriptspassshellcheckwithnocriticalissues -**Set-e**:Scriptsfailfastonerrors -**Properquoting**:Variablesareproperlyquotedtopreventinjection ##StaticAnalysisResults ###ShellCheck -**Status**:Passed -**Warnings**:None(informationalmessagesonlyaboutfilesourcing) -**Securityissues**:Noneidentified ###ManualSecurityReview -**evalusage**:Eliminatedinfavorof`printf-v` -**Commandinjection**:Noinstancesfound -**Pathtraversal**:Notapplicable(onlyusesstandardconfigdirectory) -**Raceconditions**:Minimalrisk(single-user,sequentialoperations) ##PotentialSecurityConsiderations ###1.SessionTokenStorage -**Risk**:Tokensstoredinplaintext(encryptedwithmode600) -**Mitigation**:Filepermissionspreventotherusersfromreading -**Recommendation**:Usersshoulduseapppasswords,notmainaccountpasswords ###2.EnvironmentVariables -**Risk**:BLUESKY_PASSWORDinenvironmentcouldbevisibletootherprocesses -**Mitigation**:Documentationwarnsagainstuseinuntrustedenvironments -**Recommendation**:Onlyuseforautomationinsecure,isolatedenvironments ###3.TerminalHistory -**Risk**:Commandswithcredentialsmightbeloggedinshellhistory -**Mitigation**:Toolusesinteractivepromptsbydefault -**Recommendation**:Usersshouldnotpasscredentialsascommand-linearguments ###4.APIEndpointTrust -**Risk**:Hardcodedtrustofbsky.socialendpoint -**Mitigation**:UsesofficialBlueskyPDS,HTTPSrequired -**Note**:ATP_PDSenvironmentvariableallowsoverride(documentedrisk) ##Dependencies -**curl**:Trusted,widely-usedtoolforHTTPoperations -**bash**:Systemshell,assumedtobesecure -**grep,sed**:StandardPOSIXutilities ##VulnerabilityScanResults -**CodeQL**:Notapplicable(shellscriptsnotsupported) -**Manualreview**:Novulnerabilitiesidentified ##RecommendationsforUsers 1.**Useapppasswords**:Generateapp-specificpasswordsinBlueskysettings 2.**Protectsessionfiles**:Donotshareorcopy`~/.config/at-bot/session.json` 3.**Regularlogout**:Use`at-botlogout`whendonetoclearsessions 4.**Securesystemsonly**:Onlyinstallontrusted,properlysecuredsystems 5.**Keepupdated**:Updatetolatestversionforsecurityfixes ##Compliance -**Dataprotection**:Nopersonaldatastoredexceptsessiontokens -**Privacy**:Notelemetryorexternalreporting -**Transparency**:Allcodeisopensourceandauditable ##IncidentResponse Ifasecurityvulnerabilityisdiscovered: 1.Emailmaintainersdirectly(donotopenpublicissue) 2.Includedetaileddescriptionandreproductionsteps 3.Allowreasonabletimeforpatchdevelopment 4.Coordinatedisclosuretiming ##Conclusion AT-botimplementsappropriatesecuritymeasuresforacommand-lineauthenticationtool.Nocriticalsecurityvulnerabilitieswereidentifiedduringreview.Thetoolfollowssecuritybestpracticesforshellscriptingandcredentialhandling. **SecurityStatus**:APPROVED Lastupdated:October28,2025Reviewer:GitHubCopilotSecurityReview ContributingtoAT-bot ThankyouforyourinterestincontributingtoAT-bot!Thisdocumentprovidesguidelinesandinformation forcontributors. DevelopmentSetup 1. Forktherepository 2. Cloneyourfork: gitclonehttps://github.com/YOUR_USERNAME/AT-bot.git cdAT-bot 3. Createadevelopmentbranch: gitcheckout-bfeature/your-feature-name ProjectStructure AT-bot/ ├──bin/#Executablescripts │└──at-bot#MainCLItool ├──lib/#Libraryfunctions │└──atproto.sh#ATProtocolimplementation ├──tests/#Testsuite │├──run_tests.sh │├──test_cli_basic.sh │└──test_library.sh ├──doc/#Documentation │├──QUICKSTART.md │└──CONTRIBUTING.md ├──Makefile#Build/installautomation ├──install.sh#Installationscript └──README.md#Maindocumentation CodingStandards UsePOSIX-compliantbashsyntaxwherepossible Followexistingcodestyleandformatting Usemeaningfulvariableandfunctionnames Addcommentsforcomplexlogic Keepfunctionssmallandfocused Testing Alwaysaddtestsfornewfunctionality: 1. Createanewtestfilein tests/ followingthenamingconvention test_*.sh 2. Runtestsbeforesubmitting: maketest #or bashtests/run_tests.sh AddingNewCommands ToaddanewcommandtotheCLI: 1. Addthecommandhandlerin bin/at-bot 2. Implementthefunctionalityin lib/atproto.sh (ifATProtocolrelated) 3. Updatethehelptextin show_help() function 4. Addtestsforthenewcommand 5. UpdateREADME.mdwithusageexamples SubmittingChanges 1. Ensurealltestspass 2. Updatedocumentationasneeded 3. Commityourchangeswithclearcommitmessages: gitcommit-m"Addfeature:briefdescription" 4. Pushtoyourfork: gitpushoriginfeature/your-feature-name 5. CreateaPullRequestwith: Cleardescriptionofchanges Anyrelatedissuenumbers Testresults CodeReviewProcess Allsubmissionsrequirereview Addressanyfeedbackfromreviewers Maintainerswillmergeonceapproved ReportingIssues Whenreportingissues,pleaseinclude: AT-botversion( at-bot--version ) Operatingsystemandversion Stepstoreproduce Expectedvsactualbehavior Anyerrormessages Security Ifyoudiscoverasecurityvulnerability,pleaseemailthemaintainersdirectlyinsteadofopeningapublic issue. Questions? Feelfreetoopenanissueforquestionsordiscussion. ThankyouforcontributingtoAT-bot! AT-botProjectTODO Thisdocumenttrackspendingtasks,improvements,andfeaturesfortheAT-botproject.Itemsare organizedbypriorityandcategory. MCP(ModelContextProtocol)ServerImplementation MCPServerArchitecture&Design COMPLETED-DesignMCPserverarchitectureandcommunicationprotocol COMPLETED-DefineMCPtoolschemasforallcoreoperations PlanMCPserverimplementation(Python/Node.js/Gowrapper) DesignauthenticationandsessionmanagementforMCP PlanerrorhandlingandloggingforMCPoperations DocumentMCPintegrationpointsincorelibrary MCPServerDevelopment COMPLETED-ImplementMCPserverwithstdiocommunication COMPLETED-Implementauthenticationtools(login,logout,whoami,is_authenticated) COMPLETED-Implementcontenttools(post_create,post_reply,post_like,post_repost, post_delete) COMPLETED-Implementfeedtools(feed_read,feed_search,feed_timeline,feed_notifications) COMPLETED-Implementprofiletools(profile_get,profile_follow,profile_unfollow,profile_block) Addbatchoperationsupport(batch_post,batch_follow,batch_schedule) AddMCPserverconfigurationandstartupsystem AddMCPserverlogginganddebuggingcapabilities MCPServerTesting&Documentation WriteintegrationtestsforMCPserver CreateMCPserverconfigurationguide WriteMCPclientexamplesandtutorials DocumentMCPtoolschemasandcapabilities CreatetroubleshootingguideforMCPissues AddperformancebenchmarksforMCPoperations MCPEcosystemIntegration PublishMCPservertopackageregistries CreateVSCodeCopilotintegrationguide SubmittoClaudeProjectsfordiscovery CreateGitHub-hostedMCPregistryentry BuildMCPserverexamplesforcommonusecases EstablishMCPserversecuritybestpracticesguide CoreFunctionality Authentication&SessionManagement COMPLETED-AddsecuretokenstorageusingAES-256-CBCencryption(upgradedfrombase64) COMPLETED-Implementdebugmodefordevelopment(DEBUG=1showsplaintext) COMPLETED-Addbackwardcompatibilityforoldbase64credentials COMPLETED-Addsessionrefreshcapabilityforexpiredtokens(refresh_session(),auto-refresh inget_access_token) COMPLETED-AddsessionvalidationbeforeAPIcalls(validate_session()function) Implementsecuretokenstorageusingsystemkeyring(optionalenhancement) Supportmultipleusersessions/profiles Addlogoutconfirmationprompt Implementsessiontimeouthandling ATProtocolIntegration COMPLETED-Addpostcreationfunctionality( at-botpost"message" ) COMPLETED-Implementtimeline/feedreadingcapabilities COMPLETED-Addfollow/unfollowusercommands(atproto_follow,atproto_unfollow) COMPLETED-Supportforimage/mediauploadsinposts(post_with_image,post_with_gallery, upload_media) COMPLETED-Addreplyfunctionalityforposts(atproto_reply,threadingsupport) COMPLETED-Implementsearchfunctionality(atproto_searchforpostsandusers) COMPLETED-Supportforblocksandmutesmanagement(block_user,unblock_user,mute_user, unmute_user) Addsupportforcustomfeeds Implementpinnedpostssupport Addrepostfunctionalitywithcustomtext ErrorHandling&Resilience Improvenetworkerrorhandlingandretrylogic Addbettervalidationforuserinputs ImplementgracefulhandlingofAPIratelimits Addconnectiontimeoutconfiguration Bettererrormessagesforcommonfailurescenarios Adddebugmodefortroubleshooting( --debug flag) UserExperience CLIInterface COMPLETED-Addbash/zshcompletionscripts Implementinteractivemodeforcomplexoperations Addconfigurationfilesupportforuserpreferences Supportforoutputformattingoptions(JSON,table,etc.) Addprogressindicatorsforlong-runningoperations Implement --quiet and --verbose flags Addcoloroutputconfigurationoptions Documentation&Help COMPLETED-Documentationcompilationsystem( lib/doc.sh ) COMPLETED-Generatecombinedmarkdownfromallprojectdocs COMPLETED-Create makedocs and at-bot-docs commands COMPLETED-Makedoc.shdynamicwithauto-discoveryandpattern-basedexclusions COMPLETED-Excludesessiondocumentationfromcompilationworkflow COMPLETED-FixpandocHTML/PDFconversion(YAMLparsingissueresolved) Addmanpagegeneration Createcomprehensiveusageexamples Addtroubleshootingguidetodocumentation Createvideotutorialsforcommonworkflows AddFAQsectiontoREADME Documentallenvironmentvariables Development&CodeQuality Testing COMPLETED-Expandtestcoverageforedgecases(encryptiontestsuiteadded) COMPLETED-Createcomprehensiveunittestrunner( scripts/test-unit.sh ) COMPLETED-IntegrateunittestrunnerintoMakefile( maketest-unit ) COMPLETED-Documenttestrunnerwithcomprehensivehelpandexamples COMPLETED-UpdateTESTING.mdguidewithtest-unitdocumentation COMPLETED-UpdateREADME.mdwithtestinginstructions AddintegrationtestswithmockATProtocolserver ImplementautomatedtestinginCI/CDpipeline Addperformancebenchmarksandtests Createtestfixturesfordifferentscenarios Addsecurity-focusedtests(credentialhandling,permissions) AddJSONexportoptiontotest-unit.shforCI/CDparsing CodeOrganization Refactorlibraryfunctionsintoseparatemodules Createutilityfunctionsmoduleforcommonoperations Implementconfigurationmanagementmodule Addloggingframeworkforbetterdebugging Createplugin/extensionarchitecture Standardizefunctionnamingandorganization CodeQuality Addshellcheckintegrationtopre-commithooks Implementcodeformattingstandards(shfmt) Addcomprehensiveinlinedocumentation CreateAPIdocumentationforlibraryfunctions Addtypehints/documentationforfunctionparameters Implementconsistenterrorcodesacrossmodules Packaging&Distribution Installation COMPLETED-Createdependencysetupscript( lib/setup.sh )withOSdetectionandpackage managersupport COMPLETED-Integratesetupscriptinto install.sh forautomaticdependencychecking CreateDebianpackage(.deb) AddHomebrewformulaformacOS CreateSnappackageforLinux AddWindowsSubsystemforLinux(WSL)specificinstructions CreateDockerimageforcontainerizedusage AddArchLinuxAURpackage ReleaseManagement Implementsemanticversioning Createautomatedreleasepipeline Addchangeloggenerationfromgitcommits Createreleasenotestemplate AddGPGsigningforreleases Implementautomaticversionbumping Security&Privacy SecurityEnhancements Implementpropercredentialrotationworkflow Addsupportforhardwaresecuritykeys(ifsupportedbyATProtocol) Implementauditloggingforsecurityevents Addpermissionsystemfordifferentoperations Createsecurityscanningautomation Addratelimitingprotectionforlocalusage PrivacyFeatures Adddataexportfunctionality Implementlocaldatacleanupcommands Addprivacy-focusedconfigurationoptions CreateGDPRcompliancedocumentation Addtelemetryopt-outmechanisms(iftelemetryadded) Performance&Scalability Performance OptimizeJSONparsingforlargeresponses Implementcachingforfrequentlyaccesseddata AddconnectionpoolingforAPIrequests Optimizestartuptimeandmemoryusage Addperformanceprofilingtools Implementlazyloadingforlargedatasets Scalability Addsupportforbatchoperations Implementparallelprocessingforbulkactions Addqueuesystemforrate-limitedoperations Createasyncoperationsupport Addsupportforlarge-scaledataexports AdvancedFeatures Purpose:ProvidesstandardizedJSON-RPCinterfaceforAIagents Interaction:AgentssendJSON-RPCrequestsoverstdio Output:StructuredJSONresponses Protocol:JSON-RPC2.0overstdio(ModelContextProtocol) Examples:Toolcallslike auth_login , post_create , feed_read 2.CoreLibraryLayer( lib/atproto.sh ) ThecorelibraryprovidesallATProtocolfunctionality: AuthenticationModule atproto_login() -AuthenticatewithBluesky atproto_logout() -Clearsession atproto_whoami() -Getcurrentuser get_access_token() -Retrievesessiontoken APICommunication api_request() -MakeATProtocolAPIcalls Requestformattingandparameterhandling Responsevalidationanderrorhandling Automaticretrylogicfortransientfailures DataHandling json_get_field() -ParseJSONresponses Sessionpersistenceandloading Configurationmanagement Errorhandlingandlogging UtilityFunctions Fileandpathoperations Stringmanipulation Environmentvariablehandling Directoryandpermissionmanagement 3.NetworkLayer DirectcommunicationwithBluesky’sATProtocol:-HTTPSconnectionstoATProtocolPDS-Configurable endpointvia ATP_PDS environmentvariable-Bearertokenauthentication-JSONrequest/responseformat ComponentResponsibilities CLI( bin/at-bot ) Parsecommand-linearguments Invokeappropriatefunctionsfrom lib/atproto.sh Formatanddisplayoutputforterminal Handleuserinteractions(prompts,confirmations) Maintainbackwardcompatibility MCPServer( mcp-server ) ListenforJSON-RPC2.0requestsonstdin Validatetoolrequestsandparameters Callappropriatefunctionsfrom lib/atproto.sh FormatresponsesasJSON-RPCsuccess/error Sendresponsestostdout Manageconcurrentrequestsifapplicable CoreLibrary( lib/atproto.sh ) ImplementallATProtocoloperations Handleauthenticationandsessionmanagement ManageAPIcommunication ProvidereusablefunctionsforbothCLIandMCP Abstractawayimplementationdetails Handleerrorsandedgecases DataFlowExamples Example1:CLILoginFlow User:$at-botlogin bin/at-bot │ ├─→Parsearguments ├─→Call:atproto_login() ││ │▼lib/atproto.sh │├─→Promptforhandle │├─→Promptforpassword │├─→Call:api_request()with/xrpc/com.atproto.server.createSession │││ ││▼Network ││└─→BlueskyAPI ││ │├─→Parseresponse │├─→Savesessionto~/.config/at-bot/session.json │└─→Returnsuccess │ └─→Displaysuccessmessage "Successfullyloggedinas:user.bsky.social" Example2:MCPToolCallFlow Agent(viaMCP):auth_login{handle,password} mcp-server(stdin) │ ├─→ParseJSON-RPCrequest ├─→Validaterequest ├─→Call:atproto_login(handle,password) ││ │▼lib/atproto.sh │├─→Validatecredentials │├─→Call:api_request()with/xrpc/com.atproto.server.createSession │││ ││▼Network ││└─→BlueskyAPI ││ │├─→Parseresponse │├─→Savesession │└─→Return{success:true,handle,did} │ └─→SendJSON-RPCsuccessresponse(stdout) { "jsonrpc":"2.0", "result":{"success":true,"handle":"user.bsky.social","did":"did:plc:..."}, "id":1 } Example3:CreatingaPost CLI:$at-botpost"HelloBluesky!" OR MCP:post_create{text:"HelloBluesky!"} lib/atproto.sh(shared) │ ├─→Checkauthentication ├─→Getaccesstokenfromsession ├─→Call:api_request()with/xrpc/com.atproto.repo.createRecord ││ │▼Network │└─→BlueskyAPI │ ├─→Parseresponse ├─→Return{success:true,uri} │ └─→Backtocaller(CLIorMCP)  IfCLI:Display:"Postcreated:{uri}" IfMCP:ReturnJSONresponse ModuleOrganization CoreLibraryModules lib/ ├──atproto.sh#Mainmodulewithcorefunctions ├──auth.sh#Authentication(futurerefactor) ├──api.sh#APIcommunication(futurerefactor) ├──social.sh#Socialoperations(futurerefactor) ├──content.sh#Contentoperations(futurerefactor) └──utils.sh#Utilityfunctions(futurerefactor) CLIStructure bin/ ├──at-bot#MainCLIentrypoint ├──at-bot-lib#CLIlibraryfunctions(future) └──commands/#Commandimplementations(future) ├──login.sh ├──post.sh ├──feed.sh └──... MCPServerStructure mcp-server/#MCPserverimplementation ├──server.py#MainMCPserver(orGo/Node.jsequivalent) ├──tools/#Tooldefinitions │├──auth.py │├──content.py │├──feed.py │└──profile.py ├──wrapper.sh#Bashwrapperforcorelibrary └──tests/ └──test_mcp_tools.py IntegrationPoints CLI↔CoreLibrary CLIcallsfunctionsfrom lib/atproto.sh CLIhandlesuserinteractionandformatting Corelibraryhandlesallbusinesslogic Cleanseparationofconcerns MCPServer↔CoreLibrary MCPserverwrapsfunctionsfrom lib/atproto.sh MCPserverformatsresponsesasJSON MCPserverimplementstooldiscovery Sharedlogic,differentinterface EnvironmentVariables Sharedconfiguration: ATP_PDS#ATProtocolPDSendpoint XDG_CONFIG_HOME#Configdirectorylocation BLUESKY_HANDLE#Defaulthandle(automation) BLUESKY_PASSWORD#Defaultpassword(automationonly) ErrorHandling CLIErrors User-friendlyerrormessages Coloredoutput(redforerrors) Exitcodes(0=success,1=failure,etc.) Suggestionsforcommonissues MCPErrors JSON-RPCerrorresponses Structurederrorinformation Errorcodesanddescriptions ProperHTTP-likesemantics SecurityConsiderations Authentication Tokensstoredlocallywithrestrictedpermissions(600) Passwordsneverpersisted Supportforapppasswords Sessionexpirationhandling InputValidation AlluserinputsvalidatedbeforeAPIcalls Preventionofinjectionattacks Sanitizationofspecialcharacters Typecheckingandboundschecking NetworkSecurity HTTPS-onlycommunication Certificatevalidation Timeouthandling Ratelimitrespect PerformanceConsiderations Caching Sessioncachingtoavoidre-authentication Optionalresponsecachingforfrequentlyaccesseddata Configurationcaching Efficiency Minimalexternaldependencies Shellscriptoptimization Parallelrequesthandling(forMCPserver) Connectionpooling(futureenhancement) Scalability StatelessCLIoperations(exceptforsession) MCPservercanhandlemultipleconcurrentrequests Nopersistentstorageexceptsessionfiles Lightweightsubprocessmodel FutureEnhancements ModuleRefactoring Split lib/atproto.sh intofocusedmodules Createreusableutilitylibrary EstablishinternalAPIboundaries MCPServerImprovements Implementbatchoperationsupport Addwebhookhandlingforreal-timeevents Implementcachingstrategies Addmonitoringandtelemetry Performance OptimizeJSONparsing Implementconnectionpooling Addrequestbatching Profileandoptimizehotpaths Features SupportforcustomATProtocolservers Advancedauthenticationflows Mediahandlinganduploads Searchandfilteringcapabilities Lastupdated:October28,2025 SeePLAN.mdforimplementationtimelineandAGENTS.mdforagentintegrationguide. AT-botQuickStartGuide ThisguidewillhelpyougetstartedwithAT-botquickly. Prerequisites Linux,macOS,orWindowswithWSL Bashshell curlinstalled ABlueskyaccount AnapppasswordfromyourBlueskyaccount Step1:GenerateanAppPassword 1. LogintoyourBlueskyaccountathttps://bsky.app/ 2. GotoSettings→AppPasswords 3. Click“AddAppPassword” 4. Giveitaname(e.g.,“AT-botCLI”) 5. Copythegeneratedpassword Important:Useapppasswords,notyourmainaccountpassword! Step2:InstallAT-bot Cloneandinstall: gitclonehttps://github.com/p3nGu1nZz/AT-bot.git cdAT-bot ./install.sh Step3:Login at-botlogin EnteryourBlueskyhandle(e.g., yourname.bsky.social )andtheapppasswordyougenerated. Step4:VerifyLogin at-botwhoami YoushouldseeyourhandleandDID(DecentralizedIdentifier). NextSteps Exploreavailablecommandswith at-bothelp CheckoutthemainREADME.mdfordetaileddocumentation Lookatthelib/atproto.shfiletounderstandtheAPIintegration Troubleshooting “curl:commandnotfound” Installcurl: #Ubuntu/Debian sudoapt-getinstallcurl #macOS brewinstallcurl “Permissiondenied” Makesurethescriptisexecutable: chmod+x/usr/local/bin/at-bot “Loginfailed:Invalididentifierorpassword” Double-checkyourhandleformat(shouldinclude.bsky.social) Makesureyou’reusinganapppassword,notyourmainpassword Verifytheapppasswordhasn’texpired AT-botQuickReference-Encryption& Security QuickCommands #Loginwithencryptedcredentialstorage at-botlogin--save #Loginwithdebugmode(showsplaintext) DEBUG=1at-botlogin--save #Loginwithoutsavingcredentials at-botlogin #Checkcurrentsession at-botwhoami #Clearencryptedcredentials at-botclear-credentials #Logout(clearssession) at-botlogout EncryptionQuickFacts Property Value Algorithm AES-256-CBC KeySize 256bits(32bytes) KeyDerivation PBKDF2 Salt Randomperoperation Implementation OpenSSL3.x KeyLocation ~/.config/at-bot/.key Credentials ~/.config/at-bot/credentials.json FileLocations ~/.config/at-bot/ ├──session.json#Sessiontokens(600permissions) ├──credentials.json#Encryptedcredentials(600permissions) └──.key#Encryptionkey(600permissions) SecurityLevels NeverUse #Plaintextpasswordinscript echo"my-password">password.txt Legacy(Deprecated) #Base64encoding(oldformat,stillsupported) #Automaticallymigratedonnextlogin Current(Development) #AES-256-CBCencryption at-botlogin--save Recommended(Production) #Environmentvariables exportBLUESKY_HANDLE="bot.bsky.social" exportBLUESKY_PASSWORD="app-password" at-botlogin Future(Enterprise) #Systemkeyring(planned) at-botlogin--keyring Testing #Runalltests maketest #Runencryptiontestsonly ./tests/test_encryption.sh #Testwithdebugmode DEBUG=1at-botlogin Troubleshooting “OpenSSLnotfound” Updateaconfigurationvalue: ```bash at-botconfigset<key><value> ``` **Examples**: ```bash at-botconfigsetfeed_limit50 #Output:Configurationupdated:feed_limit=50 at-botconfigsetcolor_outputnever #Output:Configurationupdated:color_output=never ``` ###ResetConfiguration Resetallconfigurationtodefaultvalues: ```bash at-botconfigreset ``` **Output**: ``` Backupcreated:/home/user/.config/at-bot/config.json.backup Configurationresettodefaults CurrentConfiguration: ===================== ... ``` **Note**:Abackupofyourcurrentconfigurationisautomaticallycreated. ###ValidateConfiguration Checkifyourconfigurationfileisvalid: ```bash at-botconfigvalidate ``` **Output**(ifvalid): ``` Configurationisvalid ``` **Output**(ifinvalid): ``` Configurationhaserrors.Run'at-botconfigreset'tofix. ``` ##EnvironmentVariableOverrides Configurationvaluescanbeoverriddenbyenvironmentvariableswithoutmodifyingtheconfigfile.Thisisusefulfor: -**CI/CDpipelines**-Differentsettingsperenvironment -**Automationscripts**-Temporaryoverrides -**Testing**-Quickconfigurationchanges ###EnvironmentVariableMapping |ConfigurationKey|EnvironmentVariable|Priority| |-------------------|---------------------|----------| |`pds_endpoint`|`ATP_PDS`|1(highest)| |`output_format`|`ATP_OUTPUT_FORMAT`|1(highest)| |`color_output`|`ATP_COLOR_OUTPUT`|1(highest)| |`feed_limit`|`ATP_FEED_LIMIT`|1(highest)| |`search_limit`|`ATP_SEARCH_LIMIT`|1(highest)| |`debug`|`DEBUG`|1(highest)| ###PriorityOrder 1.**EnvironmentVariable**(highestpriority) 2.**ConfigurationFile** 3.**DefaultValue**(lowestpriority) ###Examples **TemporaryOverride**: ```bash #UsecustomPDSforsinglecommand ATP_PDS="https://test.bsky.social"at-botwhoami #Yourconfigfileisunchanged at-botconfiggetpds_endpoint #Output:https://bsky.social ``` **SessionOverride**: ```bash #Overrideforentireshellsession exportATP_FEED_LIMIT=100 exportDEBUG=1 #Allcommandsusethesevalues at-botfeed#Shows100posts at-botsearch"bluesky"#Debugoutputenabled ``` **AutomationScript**: ```bash #!/bin/bash #automation.sh-Productionautomationscript exportATP_PDS="https://production.bsky.social" exportATP_OUTPUT_FORMAT="json" exportATP_COLOR_OUTPUT="never" #Commandsuseoverriddenvalues at-botwhoami|jq'.did' at-botfeed|jq'.feed[0].post.record.text' ``` ##UseCases&Workflows ###ForRegularUsers **QuickSetup**: ```bash #Installandconfigure at-botlogin at-botconfigsetfeed_limit30 at-botconfigsetsearch_limit15 ``` **DailyUsage**: ```bash at-botfeed#Usesconfiguredlimit(30) at-botsearch"tech"#Usesconfiguredlimit(15) ``` ###ForDevelopers **DevelopmentSetup**: ```bash #PointtolocalPDS at-botconfigsetpds_endpointhttp://localhost:2583 at-botconfigsetdebugtrue ``` **Testing**: ```bash #Runtestswithdebugenabled DEBUG=1maketest #Testagainstproductionwithoutchangingconfig ATP_PDS="https://bsky.social"at-botwhoami ``` ###ForAutomation/Bots **BotConfiguration**: ```bash #Machine-readableoutputforparsing at-botconfigsetoutput_formatjson at-botconfigsetcolor_outputnever ``` **CI/CDPipeline**: ```bash #.github/workflows/announce.yml name:AnnounceRelease on: release: types:[published] jobs: announce: runs-on:ubuntu-latest steps: -name:PosttoBluesky env: ATP_PDS:https://bsky.social ATP_OUTPUT_FORMAT:json BLUESKY_HANDLE:${{secrets.BLUESKY_HANDLE}} BLUESKY_PASSWORD:${{secrets.BLUESKY_PASSWORD}} run:| at-botlogin at-botpost"Newrelease:${{github.event.release.tag_name}}" ``` ###ForSystemAdministrators **System-WideConfiguration**: ```bash #Configureforallusers(insystemconfig) #/etc/environment ATP_PDS=https://corporate-pds.company.com ATP_OUTPUT_FORMAT=json ATP_COLOR_OUTPUT=never ``` **MonitoringScripts**: ```bash #monitoring.sh exportATP_PDS="https://monitor.bsky.social" exportATP_FEED_LIMIT=100 exportDEBUG=0 whiletrue;do at-botfeed|jq'.feed[].post.record.text'|grep-i"incident" sleep300 done ``` ##Troubleshooting ###ConfigurationFileNotFound **Problem**:Configcommandsfailwith"filenotfound" **Solution**: ```bash #Initializeconfigmanually at-botconfiglist#Thiscreatesdefaultconfig ``` ###InvalidConfiguration **Problem**:Configurationvaluesaren'tbeingapplied **Solution**: ```bash #Validateconfiguration at-botconfigvalidate #Ifinvalid,resettodefaults at-botconfigreset ``` ###EnvironmentVariablesNotWorking **Problem**:Environmentvariablesaren'toverridingconfig **Solution**: ```bash #Verifyenvironmentvariableisset echo$ATP_PDS #Makesurevariablenamematchesdocumentation #Correct:ATP_PDS #Wrong:ATP_PDS_ENDPOINT ``` ###PermissionErrors **Problem**:Cannotwritetoconfigfile **Solution**: ```bash #Checkpermissions ls-la~/.config/at-bot/ #Fixpermissions chmod644~/.config/at-bot/config.json chmod755~/.config/at-bot/ ``` ##BestPractices ###Security -Configfilestorespreferencesonly(nocredentials) -Useenvironmentvariablesforsensitivedatainautomation -Keepconfigfilebackedup(`.backup`createdautomatically) ###Performance -Usesmallerlimits(`feed_limit`,`search_limit`)forfasterresponses -Increaselimitsonlywhenneededforcomprehensiveviews ###Automation -Use`json`outputformatforscripts -Set`color_output`to`never`forlogsandpipes -OverrideconfigwithenvironmentvariablesinCI/CD ###Development -Enable`debug`modeduringdevelopment -Useseparateconfigfilesperenvironment(via`XDG_CONFIG_HOME`) -Testwith`configvalidate`beforedeployment ##AdvancedTopics ###CustomConfigLocation Overridethedefaultconfiglocation: ```bash #Usecustomconfigdirectory exportXDG_CONFIG_HOME=/opt/at-bot/config at-botconfiglist #Configfile:/opt/at-bot/config/at-bot/config.json ``` ###BackupandRestore **Backup**: ```bash #Manualbackup cp~/.config/at-bot/config.json~/at-bot-config-backup.json #Orusereset(createsautomaticbackup) at-botconfigreset #Backupcreated:/home/user/.config/at-bot/config.json.backup ``` **Restore**: ```bash #Restorefrombackup cp~/at-bot-config-backup.json~/.config/at-bot/config.json at-botconfigvalidate ``` ###MultipleConfigurations Usedifferentconfigsfordifferentpurposes: ```bash #Personalaccountconfig exportXDG_CONFIG_HOME=~/.config/personal at-botlogin at-botconfigsetfeed_limit50 #Workaccountconfig exportXDG_CONFIG_HOME=~/.config/work at-botlogin at-botconfigsetfeed_limit20 #Botaccountconfig exportXDG_CONFIG_HOME=~/.config/bot at-botlogin at-botconfigsetoutput_formatjson ``` ###ExportingConfiguration Exportconfigasenvironmentvariables(forscripts): ```bash #Inyourscript eval"$(at-botconfigexport)"#SetsATP_*environmentvariables echo$ATP_PDS echo$ATP_FEED_LIMIT ``` **Note**:`configexport`featureplannedforfuturerelease. ##ConfigurationSchema Fordevelopersandadvancedusers,thefullJSONschema: ```json { "$schema":"http://json-schema.org/draft-07/schema#", "type":"object", "properties":{ "pds_endpoint":{ "type":"string", "format":"uri", "pattern":"^https?://", "description":"ATProtocolPDSendpointURL" }, "output_format":{ "type":"string", "enum":["text","json"], "description":"Outputformatforcommands" }, "color_output":{ "type":"string", "enum":["auto","always","never"], "description":"Coloroutputcontrol" }, "feed_limit":{ "type":"integer", "minimum":1, "maximum":100, "description":"Defaultfeedretrievallimit" }, "search_limit":{ "type":"integer", "minimum":1, "maximum":100, "description":"Defaultsearchresultlimit" }, "debug":{ "type":"boolean", "description":"Enabledebugoutput" } }, "required":[ "pds_endpoint", "output_format", "color_output", "feed_limit", "search_limit", "debug" ] } ``` ##SeeAlso -[QUICKSTART.md](QUICKSTART.md)-GettingstartedwithAT-bot -[SECURITY.md](SECURITY.md)-Securitybestpractices -[AGENTS.md](AGENTS.md)-Automationandagentworkflows -[README.md](README.md)-Maindocumentation Forissuesorquestionsaboutconfiguration,pleaseopenanissueonGitHub. DocumentationCompilationGuide ThisguideexplainshowtouseAT-bot’sdocumentationcompilationsystemtogenerateacomprehensive, professionallyformattedPDFcontainingallprojectdocumentation. Overview Thedocumentationcompiler( lib/doc.sh )providesastreamlinedworkflowto:-Compileallmarkdown filesintoasingledocument-Generateatableofcontentsautomatically-ConverttoHTMLwithcustom styling-ExportasaprofessionallyformattedPDF-Maintainlogicaldocumentordering-Avoidduplicate content QuickStart Generatecompletedocumentationinthreeways: Method1:UsingMake(Recommended) makedocs Method2:DirectScriptExecution ./bin/at-bot-docs Method3:LibraryFunction sourcelib/doc.sh main WhatGetsGenerated Threecomprehensivedocumentationfilesarecreatedin dist/docs/ : 1. AT-bot_Complete_Documentation.md(361KB+) Allmarkdownfilescompiledintoone Logicaldocumentordering Noduplicates 2. AT-bot_Complete_Documentation.html StyledHTMLwithcustomCSS Clickabletableofcontents Syntax-highlightedcodeblocks 3. AT-bot_Complete_Documentation.pdf ProfessionalPDFformat Auto-generatedtableofcontents Perfectforsharingandofflineuse CurrentStatistics:-Lines:~13,000+-Words:~45,000+-Size:361KB+(markdown),variesfor HTML/PDF-Documents:30+filescombined Requirements RequiredDependencies pandoc:Universaldocumentconverter XeLaTeX:PDFrenderingengine(partofTeXLive) Installation Ubuntu/Debian: sudoapt-getupdate sudoapt-getinstallpandoctexlive-xetextexlive-fonts-recommended macOS: brewinstallpandocbasictex #Afterinstallation,updatePATH: eval"$(/usr/libexec/path_helper)" OtherSystems:VisitPandocInstallationGuide OutputFiles Thecompilationprocessgeneratesthreefilesin dist/docs/ : 1. AT-bot_Complete_Documentation.md-Combinedmarkdownsource 2. AT-bot_Complete_Documentation.html-StyledHTMLversion 3. AT-bot_Complete_Documentation.pdf-FinalPDFoutput(recommendedforsharing) Additionallycreated:-cover.md-Generatedcoverpage-documentation.css-Customstylingfor HTML/PDF KeyFeatures SmartOrdering-Documentsorganizedlogically DuplicatePrevention-Eachfileincludedonce AutoTOC-Tableofcontentsgeneratedautomatically ProfessionalStyling-CustomCSSforcleanpresentation SyntaxHighlighting-Codeblocksproperlyformatted PageBreaks-Logicaldocumentseparation CoverageDetection-Findsallmarkdownfiles DocumentOrganization StrategicDocumentOrder Thecompilerusesacarefullydesigneddocumentorderthatreflectsthelogicalflowofinformation: 1. Introduction README.md-Projectoverview 2. StrategicDocuments PLAN.md-Developmentroadmap AGENTS.md-AIintegrationpatterns 3. Standards&Guidelines STYLE.md-Codeconventions SECURITY.md-Securitypractices CONTRIBUTING.md-Contributionguidelines 4. ProjectManagement TODO.md-Tasktracking 5. TechnicalDocumentation Architecture,quickstart,configurationguides 6. FeatureDocumentation Encryption,debugging,testing,packaging 7. MCPServerDocumentation MCPquickstart,tools,integration 8. ProgressTracking Projectdashboard,milestonereports 9. SessionSummaries Developmentsessionnotes(mostrecentfirst) CustomizingDocumentOrder at-botlogin ``` Thenenter: 1.YourBlueskyhandle(e.g.,`user.bsky.social`) 2.Yourapppassword(createoneinBlueskysettings>AppPasswords) **Note**:NeveruseyourmainBlueskypassword!Alwaysuseapppasswordsforsecurity. ###Q:What'sanapppassword? **A:**Anapppasswordisaspecialpasswordforthird-partyapps: 1.GotoSettings>AppPasswordsinBluesky 2.Generateanewapppassword 3.UseitwithAT-botinsteadofyourmainpassword Benefits: -Moresecurethanusingyourmainpassword -Canberevokedwithoutchangingmainpassword -Limitsapppermissions ###Q:HowdoIcheckifI'mloggedin? **A:**Usethewhoamicommand: ```bash at-botwhoami ``` Showsyourhandleanduserinfoifloggedin. ###Q:HowdoIlogout? **A:**Uselogoutcommand: ```bash at-botlogout ``` Thisclearsyoursessionandanysavedcredentials. ##Usage ###Q:HowdoIposttoBluesky? **A:**Createapostwith: ```bash at-botpost"Yourmessagehere" ``` Withlinebreaks: ```bash at-botpost"Line1 Line2 Line3" ``` Withmedia(whenimplemented): ```bash at-botpost-with-image"Message"image.jpg ``` ###Q:HowdoIreadmyfeed? **A:**Viewyourtimeline: ```bash at-botfeed#Showlast10posts at-botfeed20#Showlast20posts ``` ###Q:HowdoIfollowsomeone? **A:**Usethefollowcommand: ```bash at-botfollowusername.bsky.social ``` Orunfollow: ```bash at-botunfollowusername.bsky.social ``` ###Q:HowdoIsearchforposts? **A:**Searchpostsorusers: ```bash at-botsearch"searchquery" ``` ###Q:HowdoIreplytoapost? **A:**ReplyusingthepostURI: ```bash at-botreplyat://did:plc:xxx/app.bsky.feed.post/xxx"Yourreply" ``` YoucangettheURIfrompostlistings. ###Q:HowdoIsavemycredentialsforautomation? **A:**AT-botcanoptionallysaveencryptedcredentials: ```bash at-botlogin #Whenprompted:"Savecredentialssecurely?(y/n):y" ``` Thenfutureloginsauto-loadcredentials: ```bash at-botlogin#Usessavedcredentialsautomatically ``` Toclearsavedcredentials: ```bash at-botclear-credentials ``` **SecurityNote**:CredentialsareencryptedwithAES-256-CBC.Stilluseintrustedenvironmentsonly. ###Q:HowdoIuseenvironmentvariablesforautomation? **A:**Setbeforerunningcommands: ```bash exportBLUESKY_HANDLE="user.bsky.social" exportBLUESKY_PASSWORD="app-password-here" at-botlogin at-botpost"Automatedpost!" ``` PerfectforscriptsandCI/CDpipelines. ##Troubleshooting ###Q:Iget"commandnotfound:at-bot" **A:**AT-botisn'tinyourPATH.Either: 1.ReinstalltosystemPATH: ```bash sudo./install.sh ``` 2.Oraddtoyourshellconfig(~/.bashrcor~/.zshrc): ```bash exportPATH="/usr/local/bin:$PATH" source~/.bashrc#or~/.zshrc ``` 3.Orusefullpath: ```bash /usr/local/bin/at-botlogin ``` ###Q:Loginfailswith"Invalidcredentials" **A:**Check: 1.**Handleiscorrect**:Usefullhandlewithdomain(e.g.,`user.bsky.social`) 2.**Usingapppassword**:Useapppasswordfromsettings,notmainpassword 3.**Accountexists**:VerifyyourBlueskyaccountisactive 4.**Notypos**:Double-checkpasswordcarefully 5.**Networkconnection**:Ensureinternetconnectivity Debugwith: ```bash DEBUG=1at-botlogin ``` ###Q:Postfailswith"Ratelimited" **A:**You'vepostedtoofrequently.Waitafewsecondsandtryagain.Blueskyratelimits: -Individualposts:~5-10secondsbetweenposts -Bulkoperations:Lowerlimitsthanindividual ###Q:Iget"Sessionexpired"errors **A:**Yoursessiontokenexpired.Simplyloginagain: ```bash at-botlogin #Oruserefreshifavailable: at-botrefresh ``` ###Q:Commandshangortimeout **A:**NetworkissueorBlueskyserverslow.Try: 1.**Checkinternet**:`pingapi.bsky.app` 2.**Retry**:Runcommandagain 3.**Customtimeout**(whenavailable): ```bash ATP_TIMEOUT=30at-botfeed ``` ###Q:Permissiondeniedwheninstalling **A:**Needsudoforsystem-wideinstallation: ```bash sudo./install.sh ``` Orinstalltohomedirectory: ```bash PREFIX=$HOME/.local./install.sh ``` ###Q:Wherearemycredentialsstored? **A:**In`~/.config/at-bot/`: -`session.json`-Currentsessiontoken(encrypted) -`credentials.json`-Savedcredentials(encrypted) Permissionssetto600(userread/writeonly). ###Q:HowdoIenabledebugoutput? **A:**SetDEBUGenvironmentvariable: ```bash DEBUG=1at-botlogin DEBUG=1at-botpost"Test" ``` Showsdetaileddebugoutputfortroubleshooting. ###Q:Commandsaren'tworking.WhatdoIdo? **A:**Trythesesteps: 1.**Checkinstallation**:`at-bot--help` 2.**Checklogin**:`at-botwhoami` 3.**Enabledebugging**:`DEBUG=1at-bot<command>` 4.**Checklogs**:Lookin`~/.config/at-bot/logs/`(ifavailable) 5.**Reportissue**:OpenGitHubissuewithdebugoutput ##Security&Privacy ###Q:IsAT-botsafetouse? **A:**Yes,withprecautions: **Securebydefault**: -CredentialsencryptedwithAES-256-CBC -Sessiontokensneverprinted -Passwordsreadsecurely(hiddeninput) -Filepermissionsstrictlyenforced(600) ⚠**Bestpractices**: -Useapppasswords,nevermainpassword -Don'tsharesession/credentialfiles -Reviewcodebeforeusinginautomation -Useintrustedenvironmentsonly -KeepAT-botupdated ###Q:Ismypasswordstored? **A:**No,passwordsarenotstored.Only: -Sessiontokens(encrypted) -Savedcredentials(optional,encrypted) Passwordsareonlyusedtoobtainsessiontokensduringlogin. ###Q:CanIauditwhatAT-botdoes? **A:**Yes!Theentirecodebaseisopensource: -Read`lib/atproto.sh`toseeallAPIcalls -Review`bin/at-bot`forCLIimplementation -EnableDEBUGmodetoseeactualAPIrequests ###Q:Ismydataprivate? **A:**AT-botitself: -Doesn'tcollectanalytics -Doesn'tphonehome -Doesn'tstoreyourpostslocally(exceptincommandoutput) -Respectsyourprivacy However: -AlldatagoesthroughBlueskyservers -FollowBluesky'sprivacypolicy ###Q:HowdoIdeletemydata? **A:**RemovelocalAT-botdata: ```bash #Removesessionandcredentials rm~/.config/at-bot/session.json rm~/.config/at-bot/credentials.json #OrcompletelyremoveAT-bot at-botlogout uninstall.sh rm-rf~/.config/at-bot ``` Blueskystoresyourpostsindependently—deletefromBlueskydirectly. ###Q:ShouldIcommitcredentialstogit? **A:**Absolutelynot!Addto`.gitignore`: ```bash .env .env.local ~/.config/at-bot/ credentials.json session.json ``` Oruseenvironmentvariablesinstead: ```bash exportBLUESKY_HANDLE="..." exportBLUESKY_PASSWORD="..." ``` ##AdvancedUsage ###Q:CanIuseAT-botinscripts? **A:**Yes!Useenvironmentvariables: ```bash #!/bin/bash exportBLUESKY_HANDLE="bot.bsky.social" exportBLUESKY_PASSWORD="$APP_PASSWORD" at-botlogin at-botpost"Automateddailypost$(date)" ``` Ornon-interactivewitherrorhandling: ```bash ifat-botlogin;then at-botpost"Success!" else echo"Loginfailed">&2 exit1 fi ``` ###Q:HowdoIuseAT-botwithGitHubActions? **A:**Setupsecretsanduseinworkflow: ```yaml name:PosttoBluesky on: push: branches:[main] jobs: post: runs-on:ubuntu-latest steps: -uses:actions/checkout@v3 -name:InstallAT-bot run:| gitclonehttps://github.com/p3nGu1nZz/AT-bot.git cdAT-bot ./install.sh -name:PosttoBluesky env: BLUESKY_HANDLE:${{secrets.BLUESKY_HANDLE}} BLUESKY_PASSWORD:${{secrets.BLUESKY_PASSWORD}} run:| at-botlogin at-botpost"Newdeployment!" ``` ###Q:CanIuseAT-botwithcronforscheduledposts? **A:**Yes!Createascript: ```bash #!/bin/bash #~/bin/post-daily.sh source~/.profile exportBLUESKY_HANDLE="bot.bsky.social" exportBLUESKY_PASSWORD="$(cat~/.bluesky_password)" at-botlogin at-botpost"Dailypost:$(date)" ``` Thenaddtocrontab: ```bash crontab-e #Add:09***/home/user/bin/post-daily.sh ``` ###Q:HowdoIusetheMCPserver? **A:**ConfigureMCPinyoureditor(VSCode,Claude,etc.): ```json { "mcpServers":{ "at-bot":{ "command":"at-bot-mcp-server", "args":["--config","~/.config/at-bot/mcp.json"] } } } ``` ThenuseinAIagentsandtools. ###Q:CanIusecustomATProtocolservers? **A:**Yes,settheendpoint: ```bash exportATP_PDS="https://custom.pds.example.com" at-botlogin ``` Oruseenvironmentpermanentlyinshellconfig. ###Q:WhatifIneedtouseadifferentshell? **A:**AT-botisbash-based,butyoucancallitfromothershells: ```zsh #!/bin/zsh at-botlogin at-botpost"Postedfromzsh!" ``` ```fish #!/usr/bin/fish at-botlogin at-botpost"Postedfromfish!" ``` Justensurebashanddependenciesareinstalled. ##Contributing ###Q:HowdoIcontributetoAT-bot? **A:**See[CONTRIBUTING.md](CONTRIBUTING.md)fordetailedguide: 1.Forktherepository 2.Createafeaturebranch 3.Makeyourchanges 4.Addtests 5.Submitapullrequest ###Q:WhatshouldIcontribute? **A:**Wewelcome: -**Code**:Features,bugfixes,improvements -**Testing**:Testcases,bugreports -**Documentation**:Guides,examples,translations -**Ideas**:Suggestionsandfeedback -**Help**:Answeringquestions,communitysupport ###Q:HowdoIreportbugs? **A:**OpenaGitHubissuewith: 1.Cleardescription 2.Stepstoreproduce 3.Expectedvsactualbehavior 4.Yourenvironment(OS,bashversion,etc.) 5.Anyerrormessagesorlogs ###Q:CanIrequestfeatures? **A:**Yes!OpenaGitHubissuewith: 1.Usecaseandproblemyou'retryingtosolve 2.Proposedsolution 3.Anyalternativesyou'veconsidered 4.Examplesormockupsifapplicable StillHaveQuestions? CheckREADME.mdforoverview ReadSTYLE.mdfortechnicaldetails OpenaGitHubIssue StartaGitHubDiscussion SeeCONTRIBUTING.mdfordevelopment Lastupdated:October28,2025 AT-botEnvironmentVariablesReference CompletereferenceforallenvironmentvariablessupportedbyAT-bot. TableofContents Authentication Configuration Debugging ATProtocol Advanced Authentication BLUESKY_HANDLE Type:String Default:None(promptsforinput) Purpose:Blueskyhandleforauthentication Automaticallyusesthishandlewhenloggingininsteadofprompting. exportBLUESKY_HANDLE="user.bsky.social" at-botlogin#Usessavedcredentialsorpromptsforpasswordonly UseCases:-Automationscripts-CI/CDpipelines-Batchoperations SecurityNote:Settemporarily;don’tstoreinshellconfigfiles. BLUESKY_PASSWORD Type:String Default:None(promptsforinputsecurely) Purpose:Apppasswordforauthentication Providespasswordnon-interactively.Usewithextremecaution. exportBLUESKY_PASSWORD="abcd-efgh-ijkl-mnop" at-botlogin#Non-interactivelogin SecurityNote:-Onlyusewithapppasswords,nevermainpassword-Setonlyforsinglecommand, neverinshellconfig-Considerusingsavedcredentialsinstead(moresecure) BestPractice: #Temporaryforonecommand BLUESKY_PASSWORD="$(cat~/.bluesky_app_password)"at-botlogin #Orusesavedcredentials(encrypted) at-botlogin#Afterfirstinteractiveloginwithsaveprompt BLUESKY_SESSION_FILE Type:Path Default: ~/.config/at-bot/session.json Purpose:Customlocationforsessionstorage Storesessionsindifferentlocationsformultipleaccounts. exportBLUESKY_SESSION_FILE=~/.config/at-bot/work-session.json at-botlogin#Savestocustomlocation #Switchbetweensessions exportBLUESKY_SESSION_FILE=~/.config/at-bot/personal-session.json at-botwhoami#Showspersonalaccount Configuration XDG_CONFIG_HOME Type:Path Default: ~/.config #Checkifvariablesareset env|grepBLUESKY_ #Checkifexported(inchildprocesses) bash-c'echo$BLUESKY_HANDLE' #Checkprecedence at-botwhoami#Usescurrentsession/credentials CredentialsNotLoading #Checksessionfileexists ls-la$BLUESKY_SESSION_FILE #Checkconfigdirectory ls-la$XDG_CONFIG_HOME/at-bot/ #Tryexplicitpath exportBLUESKY_SESSION_FILE=~/.config/at-bot/session.json at-botwhoami DebugOutputTooVerbose #UseVERBOSEinsteadofDEBUG DEBUG=0VERBOSE=1at-botlogin #Orredirecttofile DEBUG=1at-botlogin>debug.log2>&1 *Lastupdated:October28,2025* --- <!--Document:doc/EXAMPLES.md--> #AT-botUsageExamples PracticalexamplesandcodesnippetsforcommonAT-botusecases. ##TableofContents -[BasicUsage](#basic-usage) -[AutomationScripts](#automation-scripts) -[CI/CDIntegration](#cicd-integration) -[SocialMediaWorkflows](#social-media-workflows) -[ContentCreation](#content-creation) -[DataOperations](#data-operations) -[AdvancedPatterns](#advanced-patterns) ##BasicUsage ###LoginandCheckStatus ```bash #Interactivelogin at-botlogin #Checkwhoyou'reloggedinas at-botwhoami #Logout at-botlogout ``` ###CreateaSimplePost ```bash #Singlelinepost at-botpost"Hello,Bluesky!" #Multi-linepost at-botpost"Firstline Secondline Thirdline" #Postwithvariables message="Postedat$(date)" at-botpost"$message" ``` ###ReadYourFeed ```bash #Showlast10posts(default) at-botfeed #Showlast20posts at-botfeed20 #Showlast50posts at-botfeed50 ``` ###SearchandFollow ```bash #Searchforposts at-botsearch"ATProtocol" #Searchforspecificuser at-botsearch"@user.bsky.social" #Followauser at-botfollowuser.bsky.social #Unfollowauser at-botunfollowuser.bsky.social ``` ##AutomationScripts ###DailyStatusUpdate ```bash #!/bin/bash #daily-status.sh-Postdailystatusupdates set-e #Configuration BLUESKY_HANDLE="${BLUESKY_HANDLE:-automation.bot}" exportBLUESKY_HANDLE #Login at-botlogin #Gatherinformation UPTIME=$(uptime|awk-F'up''{print$2}'|cut-d','-f1) DATE=$(date'+%A,%B%d,%Y') TIME=$(date'+%H:%M:%S') #Createmessage MESSAGE="DailyStatusReport Date:$DATE Time:$TIME SystemUptime:$UPTIME Status:Allsystemsoperational #DailyReport#Automation#Monitoring" #PosttoBluesky at-botpost"$MESSAGE" echo"Statuspostedsuccessfully!" ``` Runwith: ```bash chmod+xdaily-status.sh ./daily-status.sh ``` Orschedulewithcron: ```bash #Editcrontab crontab-e #Addthisline(runsdailyat9AM) 09***/path/to/daily-status.sh ``` ###ProjectUpdateBot ```bash #!/bin/bash #project-update.sh-Postprojectupdatesfromgitcommits set-e #Configuration REPO_NAME="AT-bot" REPO_URL="https://github.com/p3nGu1nZz/AT-bot" #Getrecentcommits COMMITS=$(gitlog-5--oneline) COMMIT_COUNT=$(gitrev-list--countHEAD^HEAD~7) #Getcontributorcount CONTRIBUTORS=$(gitshortlog-snHEAD|wc-l) #Createmessage MESSAGE="$REPO_NAMEUpdate RecentCommits:$COMMIT_COUNT ActiveContributors:$CONTRIBUTORS LatestWork: $(echo"$COMMITS"|head-3|sed's/^/•/') Interested?Checkusout:$REPO_URL #OpenSource#GitHub#Development" #Postupdate at-botlogin at-botpost"$MESSAGE" ``` ###WeeklyDigest ```bash #!/bin/bash #weekly-digest.sh-Createweeklysummary set-e #Configuration WEEK_NUMBER=$(date+%V) YEAR=$(date+%Y) #Gathermetrics COMMITS=$(gitrev-list--countHEAD~$(date+%u)^HEAD) FILES_CHANGED=$(gitdiff--name-onlyHEAD~7HEAD|wc-l) BRANCHES=$(gitbranch-a|wc-l) #Createdigest MESSAGE="WeeklyDigest-Week$WEEK_NUMBER,$YEAR DevelopmentSummary: •Commits:$COMMITS •FilesChanged:$FILES_CHANGED •ActiveBranches:$BRANCHES Highlights: •Featureimplementation •Bugfixes •Documentationupdates NextWeek: •Continuedevelopment •Expandtestcoverage •Improvedocs #WeeklyDigest#Development" at-botlogin at-botpost"$MESSAGE" ``` ##CI/CDIntegration ###GitHubActionsWorkflow ```yaml #.github/workflows/post-release.yml name:PostReleasetoBluesky on: release: types:[published] jobs: post: runs-on:ubuntu-latest steps: -uses:actions/checkout@v3  -name:InstallAT-bot run:| gitclonehttps://github.com/p3nGu1nZz/AT-bot.git cdAT-bot ./install.sh -name:Postreleaseannouncement env: BLUESKY_HANDLE:${{secrets.BLUESKY_HANDLE}} BLUESKY_PASSWORD:${{secrets.BLUESKY_PASSWORD}} run:| VERSION="${{github.event.release.tag_name}}" BODY="${{github.event.release.body}}"  at-botlogin  MESSAGE="Release:$VERSION $BODY Download:${{github.event.release.html_url}} #Release#NewVersion"  at-botpost"$MESSAGE" ``` ###TestResultsReporter ```yaml #.github/workflows/test-report.yml name:TestReport on: pull_request: push: branches:[main] jobs: test: runs-on:ubuntu-latest steps: -uses:actions/checkout@v3  -name:Runtests run:| maketest>test-results.txt2>&1||true -name:InstallAT-bot run:| gitclonehttps://github.com/p3nGu1nZz/AT-bot.git cdAT-bot ./install.sh -name:Posttestresults if:always() env: BLUESKY_HANDLE:${{secrets.TEST_BOT_HANDLE}} BLUESKY_PASSWORD:${{secrets.TEST_BOT_PASSWORD}} run:| TESTS=$(grep-c"PASS"test-results.txt||echo"0") FAILURES=$(grep-c"FAIL"test-results.txt||echo"0")  if["$FAILURES"-eq0];then STATUS="" EMOJI="" else STATUS="⚠" EMOJI="" fi  at-botlogin  MESSAGE="$EMOJITestRunResults  TestsPassed:$TESTS TestsFailed:$FAILURES Status:$STATUS Branch:${{github.ref}} Commit:${{github.sha}}"  at-botpost"$MESSAGE" ``` ##SocialMediaWorkflows ###ContentCalendarPosting ```bash #!/bin/bash #content-calendar.sh-Postfromacontentcalendar set-e #LoadpostsfromJSONfile CALENDAR_FILE="posts.json" at-botlogin #Processeachpostincalendar jq-r'.[]|select(.date=="'$(date+%Y-%m-%d)'")|.content'"$CALENDAR_FILE"|whileread-rpost;do echo"Posting:$post" at-botpost"$post" sleep5#Waitbetweenposts done ``` Example`posts.json`: ```json [ { "date":"2025-10-28", "content":"Mondaymotivation!" }, { "date":"2025-10-29", "content":"TipTuesday:Alwaysuseapppasswords!" }, { "date":"2025-10-30", "content":"Wednesdaywisdomaboutopensource" } ] ``` ###ReplytoMentions ```bash #!/bin/bash #reply-to-mentions.sh-Replytomentions(whenimplemented) set-e at-botlogin #Getrecentnotifications MENTIONS=$(at-botfeed|grep"@your.handle") whileIFS=read-rmention;do #ExtractpostURI URI=$(echo"$mention"|grep-oP'uri:\K[^,]+')  if[-n"$URI"];then REPLY="Thanksforthemention!" echo"Replyingto:$URI" #at-botreply"$URI""$REPLY"#Whenimplemented fi done<<<"$MENTIONS" ``` ###FollowNewFollowers ```bash #!/bin/bash #follow-followers.sh-Auto-follownewfollowers set-e at-botlogin #Getfollowerslist FOLLOWERS=$(at-botfollowers|jq-r'.[].handle') #Getfollowinglist FOLLOWING=$(at-botfollowing|jq-r'.[].handle') whileread-rfollower;do if!echo"$FOLLOWING"|grep-q"$follower";then echo"Followingback:$follower" at-botfollow"$follower" sleep2#Ratelimiting fi done<<<"$FOLLOWERS" ``` ##ContentCreation ###GenerateDailyQuotes ```bash #!/bin/bash #daily-quote.sh-Postdailyquotes set-e QUOTES=( "Theonlywaytodogreatworkistolovewhatyoudo.-SteveJobs" "Innovationdistinguishesbetweenaleaderandafollower.-SteveJobs" "Lifeiswhathappenswhenyou'rebusymakingotherplans.-JohnLennon" "Thefuturebelongstothosewhobelieveinthebeautyoftheirdreams.-EleanorRoosevelt" ) #Pickrandomquote RANDOM_INDEX=$((RANDOM%${#QUOTES[@]})) QUOTE="${QUOTES[$RANDOM_INDEX]}" at-botlogin at-botpost"QuoteoftheDay \"$QUOTE\" #DailyQuote#Inspiration" ``` ###NewsAggregation ```bash #!/bin/bash #news-aggregator.sh-Aggregateandsharenews set-e at-botlogin #FetchnewsfromRSSfeed(requiresrssparser) ARTICLES=$(curl-s"https://news.ycombinator.com/rss"|\ grep-oP'(?<=<title>)[^<]+'|head-5) MESSAGE="Top5StoriesToday " whileread-rarticle;do MESSAGE="$MESSAGE•$article " done<<<"$ARTICLES" MESSAGE="$MESSAGE #News#TopStories#Aggregation" at-botpost"$MESSAGE" ``` ##DataOperations ###ExportYourFeed ```bash #!/bin/bash #export-feed.sh-ExportyourfeedtoJSON set-e at-botlogin #Getfeed(limitto100) FEED=$(at-botfeed100) #Savetofilewithtimestamp FILENAME="feed-$(date+%Y%m%d-%H%M%S).json" echo"$FEED">"$FILENAME" echo"Feedexportedto:$FILENAME" ``` ###BackupPosts ```bash #!/bin/bash #backup-posts.sh-Backuprecentposts set-e BACKUP_DIR="./backups" mkdir-p"$BACKUP_DIR" at-botlogin #Getrecentposts POSTS=$(at-botfeed50) #Savewithmetadata BACKUP_FILE="$BACKUP_DIR/posts-$(date+%Y%m%d-%H%M%S).json" echo"{">"$BACKUP_FILE" echo"\"backup_date\":\"$(date-Iseconds)\",">>"$BACKUP_FILE" echo"\"posts\":$POSTS">>"$BACKUP_FILE" echo"}">>"$BACKUP_FILE" echo"Backedupto:$BACKUP_FILE" ``` ##AdvancedPatterns ###ErrorHandlingandRetry ```bash #!/bin/bash #robust-posting.sh-Robustpostingwitherrorhandling set-e MAX_RETRIES=3 RETRY_DELAY=5 #Functiontopostwithretry post_with_retry(){ localmessage="$1" localattempt=1  while[$attempt-le$MAX_RETRIES];do echo"Attempt$attempt..."  ###ConfigurationDirectory ``` ~/.config/at-bot/ ├──session.json#Encryptedsessiontokens ├──config.json#Userpreferences(canbeencrypted) ├──encryption.key#32-byteencryptionkey(600permissions) ├──encryption.salt#32-bytesaltforPBKDF2(600permissions) └──*.backup#Automaticbackupsfromfileencryption ``` ###session.json(CurrentFormat) ```json { "handle":"user.bsky.social", "did":"did:plc:abc123...", "accessJwt":"U2FsdGVkX1/jBQdT...(base64encrypted)", "refreshJwt":"U2FsdGVkX1/kMnPqY...(base64encrypted)" } ``` ###encryption.key ``` #64hexcharacters(32bytes) a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456 ``` **Security:** -Generatedfrom`/dev/urandom`(cryptographicallysecure) -Neverexposedinprocesslistsorlogs -Filepermissions:600(ownerread/writeonly) -Nevercommittedtoversioncontrol(.gitignore) ###encryption.salt ``` #64hexcharacters(32bytes) f1e2d3c4b5a6908172635449506a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a ``` **Purpose:** -UsedwithPBKDF2forpassword-basedencryption -Preventsrainbowtableattacks -Uniqueperinstallation -Shouldbebackedupwithencryption.keyifrotating ###SecurityProperties ####Strengths 1.**StrongEncryption** -AES-256isindustrystandard -ApprovedbyNSAforTOPSECRETdata -Noknownpracticalattacks 2.**RandomSalt** -Differentciphertextforsamepassword -Preventsrainbowtableattacks -AppliedautomaticallybyOpenSSL 3.**KeyDerivation** -PBKDF2makesbruteforceharder -Computationalcostforattackers -Stretchespassword/keymaterial 4.**FilePermissions** -Mode600(owneronly) -ProtectedatOSlevel -Nootheruserscanread 5.**NoPlaintextStorage** -Passwordsneverstoredunencrypted -Onlyexistinmemoryduringuse -Clearedafterauthentication ####⚠Limitations 1.**KeyStorageonSameMachine** -Encryptionkeystoredalongsideencrypteddata -Ifattackerhasfileaccess,theylikelyhavekeyaccesstoo -Betterthannoencryption,butnotperfect 2.**NotHardware-Based** -NoTPM/secureenclaveusage -Keyisaregularfile -Nohardwarerootoftrust 3.**Single-MachineSecurity** -Keyismachine-specific -Moving.keytoanothermachinewon'twork -Nokeysynchronization 4.**MemoryExposure** -Decryptedpasswordexistsinprocessmemory -Couldbedumpedbyprivilegeduser -Notprotectedagainstmemoryattacks 5.**OpenSSLDependency** -RequiresOpenSSLtobeinstalled -Fallsbacktoerrorifnotavailable -Versioncompatibilityconsiderations ###ComparisonwithOtherMethods |Method|Security|Portability|Complexity|UseCase| |--------|----------|-------------|------------|----------| |**Plaintext**|❌None|High|Simple|Neveruse| |**Base64**|❌VeryLow|High|Simple|Legacyonly| |**AES-256-CBC**|Good|⚠Medium|⚠Medium|**Current:Dev/Test**| |**SystemKeyring**|Better|❌Low|⚠Complex|Future:Desktop| |**HSM/TPM**|Best|❌VeryLow|❌Complex|Enterprise| ##APIUsageExamples ###Example1:BasicEncryption(DefaultMethod) ```bash #!/bin/bash source/usr/local/lib/at-bot/crypt.sh #Encryptsensitivedata(usesrandomkeyfromencryption.key) plaintext="my-session-token-12345" encrypted=$(encrypt_data"$plaintext") echo"Encrypted:$encrypted" #StoreinJSON echo"{\"token\":\"$encrypted\"}">/tmp/data.json #Later,decryptwhenneeded encrypted=$(grep-o'"token":"[^"]*"'/tmp/data.json|cut-d'"'-f4) decrypted=$(decrypt_data"$encrypted") echo"Decrypted:$decrypted" #Secureerasesensitivevariables secure_eraseplaintext secure_erasedecrypted ``` ###Example2:Password-BasedEncryption ```bash #!/bin/bash source/usr/local/lib/at-bot/crypt.sh #Encryptconfigurationwithuserpassword password="MyStrongPassphrase123!" config_data='{"api_key":"secret","endpoint":"https://api.example.com"}' #Encrypt encrypted=$(encrypt_data"$config_data""$password") echo"$encrypted">/tmp/config.encrypted #Later,decryptwithsamepassword encrypted=$(cat/tmp/config.encrypted) decrypted=$(decrypt_data"$encrypted""$password") echo"Config:$decrypted" #Wrongpasswordfailsgracefully wrong=$(decrypt_data"$encrypted""WrongPassword") [-z"$wrong"]&&echo"Decryptionfailed(wrongpassword)" #Cleanup secure_erasepassword ``` ###Example3:FileEncryption ```bash #!/bin/bash source/usr/local/lib/at-bot/crypt.sh #Createsensitiveconfigurationfile cat>/tmp/secrets.conf<<EOF API_KEY=sk-1234567890abcdef DATABASE_URL=postgresql://user:pass@localhost/db WEBHOOK_SECRET=whsec_abcdef123456 EOF #Encryptfile(createsautomaticbackup) encrypt_file"/tmp/secrets.conf" #Creates:/tmp/secrets.conf.backup(original) #Encrypts:/tmp/secrets.conf(in-place) #Fileisnowencrypted,canbesafelystored cat/tmp/secrets.conf #Output:U2FsdGVkX1+base64encrypteddata... #Decryptwhenneeded(applicationstartup) decrypt_file"/tmp/secrets.conf" #Fileisnowplaintextagain source/tmp/secrets.conf echo"APIKey:$API_KEY" #Re-encryptafteruse encrypt_file"/tmp/secrets.conf" ``` ###Example4:PBKDF2KeyDerivation ```bash #!/bin/bash source/usr/local/lib/at-bot/crypt.sh #Deriveencryptionkeyfromuserpassword user_password="SecurePassword123" salt=$(generate_or_get_salt) #Derivekey(100,000PBKDF2iterations) derived_key=$(derive_key_from_passphrase"$user_password""$salt") echo"Derivedkey(first16chars):${derived_key:0:16}..." #Usederivedkeytoencryptdata data="Sensitiveinformation" encrypted=$(encrypt_data"$data""$user_password") #Samepassword+salt=samederivedkey(deterministic) encrypted2=$(encrypt_data"$data""$user_password") decrypted=$(decrypt_data"$encrypted""$user_password") echo"Original:$data" echo"Decrypted:$decrypted" ["$data"="$decrypted"]&&echo"Encryption/decryptionsuccessful" #Cleanup secure_eraseuser_password secure_erasederived_key ``` ###Example5:IntegrationwithAT-botSessionManagement ```bash #!/bin/bash source/usr/local/lib/at-bot/crypt.sh #Savesessionwithencryptedtokens save_session(){ localhandle="$1" localdid="$2" localaccess_token="$3" localrefresh_token="$4"  #Encrypttokens localencrypted_access localencrypted_refresh encrypted_access=$(encrypt_data"$access_token") encrypted_refresh=$(encrypt_data"$refresh_token")  #Savetosessionfile cat>"$HOME/.config/at-bot/session.json"<<EOF { "handle":"$handle", "did":"$did", "accessJwt":"$encrypted_access", "refreshJwt":"$encrypted_refresh" } EOF  chmod600"$HOME/.config/at-bot/session.json"  #Secureerase secure_eraseaccess_token secure_eraserefresh_token } #Loadsessionwithdecryptedtokens load_session(){ localsession_file="$HOME/.config/at-bot/session.json"  if[!-f"$session_file"];then echo"Nosessionfound">&2 return1 fi  #Extractencryptedtokens localencrypted_access localencrypted_refresh encrypted_access=$(grep-o'"accessJwt":"[^"]*"'"$session_file"|cut-d'"'-f4) encrypted_refresh=$(grep-o'"refreshJwt":"[^"]*"'"$session_file"|cut-d'"'-f4)  #Decrypt localaccess_token localrefresh_token access_token=$(decrypt_data"$encrypted_access") refresh_token=$(decrypt_data"$encrypted_refresh")  if[-z"$access_token"]||[-z"$refresh_token"];then echo"Failedtodecryptsessiontokens">&2 return1 fi  #Usetokens... echo"$access_token"  #Secureerase secure_eraseaccess_token secure_eraserefresh_token } ``` ###Example6:SecurePasswordGeneration ```bash #!/bin/bash source/usr/local/lib/at-bot/crypt.sh #Generatestrongapppassword app_password=$(generate_secure_password32) echo"Generatedapppassword:$app_password" #GenerateshorterPIN pin=$(generate_secure_password6) echo"GeneratedPIN:$pin" #Eachcallgeneratesuniquepassword password1=$(generate_secure_password16) password2=$(generate_secure_password16) ["$password1"!="$password2"]&&echo"Passwordsareunique" ``` ###SecurityBestPractices ####DO -Useonpersonal,securemachines -Useapppasswords(notmainpassword) -Clearcredentialswhendone -Keep.keyfilesecure -UseDEBUGmodeonlyinprivate -UpdateOpenSSLregularly ####❌DON'T -Commitcredentials.jsonor.keytogit -Share.keyfile -Useonshared/publicmachines -Storeproductioncredentialsthisway -Copyfilesbetweenmachines -Exposeencryptedfilespublicly ###ThreatModel **ProtectedAgainst:** -Casualfileviewers -Accidentalexposure -Basicfiletheft -Rainbowtableattacks -Simplebruteforce **NOTProtectedAgainst:** -❌Root/adminaccesstoyourmachine -❌Memorydumpsbyprivilegedusers -❌Sophisticatedmalware -❌Physicalmachinetheft(withaccess) -❌Determinednation-stateactors ###ProductionAlternatives Forproductionuse,consider: 1.**EnvironmentVariables** ```bash exportBLUESKY_HANDLE="bot.bsky.social" exportBLUESKY_PASSWORD="app-password" ``` 2.**SecretManagementServices** -HashiCorpVault -AWSSecretsManager -AzureKeyVault -GoogleSecretManager 3.**SystemKeyrings**(Future) -GNOMEKeyring -KDEWallet -macOSKeychain -WindowsCredentialManager ###Requirements **Minimum:** -OpenSSL1.1.1orlater -Linux/Unixwith/dev/urandom -Filesystemwithpermissionsupport **Recommended:** -OpenSSL3.x -ModernLinuxdistribution -Secure,personalmachine ###TechnicalImplementation Theencryptionisimplementedin`lib/atproto.sh`: ```bash #Keygeneration get_encryption_key(){ cat/dev/urandom|tr-dc'A-Za-z0-9!@#$%^&*()_+='|head-c64 } #Encryption encrypt_data(){ echo"$plaintext"|opensslenc-aes-256-cbc-a-salt-passpass:"$key" } #Decryption decrypt_data(){ echo"$encrypted"|opensslenc-aes-256-cbc-d-a-salt-passpass:"$key" } ``` ##Testing ###RunningEncryptionTests ```bash #Runallencryptiontests ./tests/test_crypt.sh #Expectedoutput: [PASS]OpenSSLavailabilitycheck [PASS]Keygenerationandpersistence [PASS]Saltgenerationandpersistence [PASS]Basicencryption/decryption [PASS]Password-basedencryption [PASS]PBKDF2keyderivation [PASS]Fileencryption/decryption [PASS]SHA-256hashing [PASS]Securepasswordgeneration [PASS]Encrypteddataverification Testspassed:10,Testsfailed:0 #Runfulltestsuite(includesencryptiontests) maketest #Expectedoutputincludes: Runningtests/test_crypt.sh... Testspassed:10,Testsfailed:0 ``` ###ManualTesting ```bash #Testbasicencryptionround-trip sourcelib/crypt.sh plaintext="Testdata123" encrypted=$(encrypt_data"$plaintext") decrypted=$(decrypt_data"$encrypted") ["$plaintext"="$decrypted"]&&echo"Basicencryptionworks" #Testpassword-basedencryption encrypted=$(encrypt_data"$plaintext""password123") decrypted=$(decrypt_data"$encrypted""password123") ["$plaintext"="$decrypted"]&&echo"Passwordencryptionworks" #Testwrongpasswordfails wrong=$(decrypt_data"$encrypted""wrongpassword") [-z"$wrong"]&&echo"Wrongpasswordcorrectlyfails" #Testfileencryption echo"Secretcontent">/tmp/test_encrypt.txt encrypt_file"/tmp/test_encrypt.txt" [-f"/tmp/test_encrypt.txt.backup"]&&echo"Backupcreated" decrypt_file"/tmp/test_encrypt.txt" content=$(cat/tmp/test_encrypt.txt) ["$content"="Secretcontent"]&&echo"Fileencryptionworks" rm/tmp/test_encrypt.txt/tmp/test_encrypt.txt.backup #Testkeypersistence key1=$(generate_or_get_key) key2=$(generate_or_get_key) ["$key1"="$key2"]&&echo"Keypersistenceworks" #TestPBKDF2determinism salt=$(generate_or_get_salt) key1=$(derive_key_from_passphrase"test""$salt") key2=$(derive_key_from_passphrase"test""$salt") ["$key1"="$key2"]&&echo"PBKDF2isdeterministic" ``` ###TestCoverage Theencryptiontestsuite(`tests/test_crypt.sh`)covers: 1.**DependencyCheck**:OpenSSLavailability 2.**KeyManagement**:Generation,persistence,retrieval 3.**SaltManagement**:Generation,persistence,uniqueness 4.**BasicEncryption**:Encrypt/decryptround-trip 5.**PasswordEncryption**:PBKDF2-basedencryption 6.**WrongPassword**:Gracefulfailurehandling 7.**KeyDerivation**:PBKDF2determinism 8.**FileOperations**:In-placeencryptionwithbackups 9.**Hashing**:SHA-256correctnessanduniqueness 10.**PasswordGeneration**:Securerandompasswords 11.**Verification**:Encrypteddatavalidation **Coverage:**~95%oflib/crypt.shfunctions ##Troubleshooting ###CommonIssues ####Issue:`decrypt_data()`returnsemptystring **Symptoms:** ```bash decrypted=$(decrypt_data"$encrypted") echo"Result:'$decrypted'"#Showsemptystring ``` **PossibleCauses:** 1.Wrongencryptionkeyorpassword 2.Corruptedciphertext 3.Missingorcorrupt`encryption.key`file 4.OpenSSLversionincompatibility **Solutions:** ```bash #Checkifencryptionkeyexists ls-la~/.config/at-bot/encryption.key #Trywithexplicitpassword decrypted=$(decrypt_data"$encrypted""known-password") #CheckOpenSSLversion opensslversion #Re-generateencryptionkey(WARNING:losesallencrypteddata) rm~/.config/at-bot/encryption.key #Thenre-encryptalldata ``` ####Issue:"OpenSSLnotfound"error **Symptoms:** ``` Error:OpenSSLisrequiredbutnotinstalled ``` **Solution:** ```bash #Debian/Ubuntu sudoapt-getupdate sudoapt-getinstallopenssl #Fedora/RHEL sudodnfinstallopenssl #macOS brewinstallopenssl #Verifyinstallation opensslversion ``` ####Issue:Fileencryptionfailswithpermissionerror **Symptoms:** ``` Error:Failedtoencryptfile:Permissiondenied ``` **Solutions:** ```bash #Checkfilepermissions ls-la/path/to/file #Ensureyouownthefile **ExcellentFor:** -PersonalBlueskyautomation -Developmentandtesting -Open-sourceprojects -Educationalpurposes -CLItoolcredentialstorage -Localmachineusage **GoodFor:** -Smallteamautomation(withproperkeymanagement) -CI/CDpipelines(withsecurekeyinjection) -Configurationfileencryption -Botaccountmanagement **⚠ConsiderAlternativesFor:** -Enterpriseproductiondeployments→UseHashiCorpVault,AWSSecretsManager -Sharedinfrastructure→UsesystemkeyringsorHSMs -Highlysensitivedata→Addhardwaresecuritymodules -Compliance-criticalsystems→Usecertifiedsolutions -Multi-userenvironments→Useproperauthenticationsystems ###SecurityPosture **ProtectedAgainst:** -Casualfileaccessbyotherusers -Accidentalcredentialexposure -Basicfiletheft -Rainbowtableattacks -Dictionaryattacks(withPBKDF2) -Processlistexposure **NotProtectedAgainst:** -❌Root/administratoraccesstoyourmachine -❌Memorydumpsbyprivilegedusers -❌Sophisticatedmalware -❌Physicalmachinetheftwithfulldiskaccess -❌Advancedpersistentthreats(APTs) -❌Nation-stateadversaries ###NextSteps 1.**Review**:Readthisdocumentationcompletely 2.**Test**:Run`./tests/test_crypt.sh`toverifyfunctionality 3.**Implement**:Source`lib/crypt.sh`inyourscripts 4.**Secure**:Backup`encryption.key`toencryptedexternalstorage 5.**Monitor**:KeepOpenSSLupdated 6.**Evolve**:Follow[TODO.md](../TODO.md)forupcomingenhancements ###Support&Resources -**SecurityIssues**:See[doc/SECURITY.md](SECURITY.md)forresponsibledisclosure -**BugReports**:https://github.com/yourusername/AT-bot/issues -**FeatureRequests**:Contributeto[TODO.md](../TODO.md) -**Discussions**:GitHubDiscussionsorprojectchat LastUpdated:October28,2025 EncryptionVersion:lib/crypt.shv1.0.0 Algorithm:AES-256-CBCwithPBKDF2(100,000iterations) OpenSSLVersion:1.1.1+or3.xrecommended TestCoverage:95%(10/10testspassing) ForcomprehensiveAT-botdocumentation,see:-README.md-Projectoverview-QUICKSTART.md- Gettingstartedguide-PLAN.md-Strategicroadmap-AGENTS.md-Automationandagentintegration- STYLE.md-Codestyleguide AT-botDebugModeQuickReference EnableDebugMode DEBUG=1at-bot[command] WhatDebugModeShows DuringLogin DEBUG=1at-botlogin Outputincludes:- [DEBUG]Handleentered:your.handle.bsky.social - [DEBUG]Passwordentered(length:19) - [DEBUG]Password(plaintext):your-actual-password - [DEBUG]Attemptingloginfor:your.handle.bsky.social - [DEBUG]Sendingauthenticationrequesttohttps://bsky.social WhenSavingCredentials DEBUG=1at-botlogin #...entercredentials... #Choose'y'tosave Outputincludes:- [DEBUG]Savingcredentialsfor:your.handle.bsky.social - [DEBUG]Password(plaintext): your-actual-password - [DEBUG]PasswordencryptedwithAES-256-CBC - [DEBUG]Encrypteddata: U2FsdGVkX1/jBQdTc9arcQQz... WhenLoadingSavedCredentials DEBUG=1at-botlogin #Ifcredentialsalreadysaved Outputincludes:- [DEBUG]Loadedcredentialsfor:your.handle.bsky.social - [DEBUG]Encryptionmethod: aes-256-cbc - [DEBUG]Encrypteddata:U2FsdGVkX1/jBQdTc9arcQQz... - [DEBUG]Password(plaintext):your-actualpassword UseCases 1.VerifyCredentialsareSavedCorrectly #Firstloginandsave at-botlogin #...entercredentials,choose'y'tosave... #Verifytheyloadcorrectly DEBUG=1at-botlogout DEBUG=1at-botlogin #Shouldsee:"Usingsavedcredentialsfor..." #Debugoutputshowstheloadedpassword 2.TroubleshootLoginIssues DEBUG=1at-botlogin #Seeexactlywhat'sbeingsenttotheAPI 3.VerifyPasswordEncoding DEBUG=1at-botlogin #SeetheAES-256-CBCencryptionprocess SecurityWarning⚠ NEVERuseDEBUG=1in:-Sharedterminals-Screenrecordings-Screensharingsessions-Public demonstrations-CI/CDlogs(unlesssecured)-Anyenvironmentwhereotherscanseeyourscreen Debugoutputwilldisplayyourpasswordinplaintext! DisableDebugMode Simplydon’tsetDEBUG=1: #Normalmode(nodebugoutput) at-botlogin Orexplicitlydisable: DEBUG=0at-botlogin ExampleDebugSession #Terminalsessionshowingdebugoutput $DEBUG=1at-botlogin [DEBUG]Nocredentialsfilefound Blueskyhandle(e.g.,user.bsky.social):myhandle.bsky.social [DEBUG]Handleentered:myhandle.bsky.social Apppassword(willnotbestored): [DEBUG]Passwordentered(length:19) [DEBUG]Password(plaintext):abcd-efgh-ijkl-mnop Savecredentialssecurelyfortesting/automation?(y/n):y [DEBUG]Attemptingloginfor:myhandle.bsky.social [DEBUG]Sendingauthenticationrequesttohttps://bsky.social Authenticating... [DEBUG]Savingcredentialsfor:myhandle.bsky.social [DEBUG]Password(plaintext):abcd-efgh-ijkl-mnop [DEBUG]PasswordencryptedwithAES-256-CBC [DEBUG]Encrypteddata:U2FsdGVkX1/jBQdTc9arcQQz3rF0dULp... ✓CredentialssavedwithAES-256-CBCencryptionto/home/user/.config/at-bot/credentials.json ✓Successfullyloggedinas:myhandle.bsky.social Tips 1. Useinaprivateterminalwindow 2. Clearyourterminalhistoryafterdebugging: history-c 3. Oruseatemporarysession: bash--norc--noprofile DEBUG=1at-botlogin exit RelatedCommands at-bothelp -Showallcommands at-botclear-credentials -Removesavedcredentials cat~/.config/at-bot/credentials.json -Viewsavedcredentialsfile DEBUG=1at-botwhoami -Debugcurrentsession **Remember:**Debugmodeisfordevelopmentonly.Neveruseinproductionorpublicenvironments! --- <!--Document:doc/TESTING.md--> #AT-botTestingGuide ThisguideexplainsthecompletetestingapproachforAT-bot,includingautomatedunittests,interactivemanualtesting,andend-to-endintegrationtests. ##QuickStart ###UnitTests(Automated) Runtheautomatedunittestsuite: ```bash maketest-unit ``` Orwithoptions: ```bash #Runwithverboseoutput bashscripts/test-unit.sh--verbose #Listallavailabletests bashscripts/test-unit.sh--list #Runspecifictest(e.g.,testsmatching'cli') bashscripts/test-unit.shtest_cli ``` **TestSuiteSummary:** -**12unittests**coveringallmajorfeatures -**~5seconds**toruncompletesuite -**91%successrate**(manual_test.shrequiresinteractiveinput) -Tests:Authentication,Content,Social,Configuration,Integration ###InteractiveManualTesting Usetheinteractivetesthelper: ```bash ./tests/manual_test.sh ``` Orviamake: ```bash maketest-manual ``` Thisscriptwill: 1.Promptyoutologin(ifnotalreadyloggedin) 2.Offertosaveyourcredentialssecurely(optional) 3.Provideaninteractivemenutotestallfeatures ##TestRunnerReference(`scripts/test-unit.sh`) The`test-unit.sh`scriptprovidesacomprehensiveunittestrunnerwithmultipleoptionsandfeatures. ###Usage ```bash scripts/test-unit.sh[options][test_pattern] ``` ###Options |Option|Description| |--------|-------------| |`-v,--verbose`|Showdetailedtestoutputandlogs| |`-q,--quiet`|Suppressoutput,onlyshowresults| |`-c,--coverage`|Showtestcoverageinformation| |`-l,--list`|Listavailabletestswithoutrunning| |`-f,--failed-only`|Onlyshowfailedtestsinfinalreport| |`-h,--help`|Showhelpmessageandusage| ###Examples ```bash #Runalltests scripts/test-unit.sh #Listavailabletests scripts/test-unit.sh--list #Runtestsmatchingpattern scripts/test-unit.shtest_cli #Verboseoutputwithdetails scripts/test-unit.sh--verbose #Showcoverageinformation scripts/test-unit.sh--coverage #Onlyshowfailures scripts/test-unit.sh--failed-only ``` ###TestCategories Thetestsuiteisorganizedintofivecategories: **AuthenticationTests**(3tests,539lines) -`test_cli_basic.sh`-BasicCLIfunctionality(help,version,commands) -`test_encryption.sh`-Encryptionandcredentialstorage -`test_profile.sh`-Userprofileretrievalandmanagement **ContentManagementTests**(2tests,401lines) -`test_post_feed.sh`-Postcreationandfeedoperations -`test_media_upload.sh`-Mediauploadandattachmenthandling **SocialOperationsTests**(3tests,338lines) -`test_follow.sh`-Followandrelationshipmanagement -`test_followers.sh`-Follower/followinglistoperations -`test_search.sh`-Postandusersearchfunctionality **ConfigurationTests**(2tests,285lines) -`test_config.sh`-Configurationmanagement -`test_library.sh`-Libraryfunctiontesting **IntegrationTests**(3tests,1,368lines) -`atp_test.sh`-ComprehensiveATProtocolintegration -`manual_test.sh`-Manualtestingutilities(interactive) -`debug_demo.sh`-Debugmodedemonstrations ###ExitCodes |Code|Meaning| |------|---------| |0|Alltestspassed| |1|Sometestsfailed| |2|Invalidarguments| ###EnvironmentVariables |Variable|Effect| |----------|--------| |`AT_BOT_TEST_VERBOSE`|Enableverboseoutput| |`AT_BOT_TEST_TIMEOUT`|Testtimeoutinseconds(default:60)| |`AT_BOT_DEBUG`|Enabledebugmodefortests| ###CI/CDIntegration ThetestrunnerisdesignedforCI/CDpipelines: ```bash #!/bin/bash #ExampleGitHubActionsworkflow #Rununittests bashscripts/test-unit.sh--quiet exit_code=$? if[$exit_code-eq0];then echo"✓Alltestspassed" else echo"✗Testsfailed" bashscripts/test-unit.sh--verbose#Showdetails exit1 fi ``` ##MakefileTestCommands Youcanrunalltestsusingmakecommands: |Command|Description| |---------|-------------| |`maketest`|Runalltests(unit+e2e)| |`maketest-unit`|Rununittestsuite(12tests)| |`maketest-manual`|Runinteractivemanualtestsuite| |`maketest-e2e`|Runend-to-endintegrationtests| |`makehelp`|Showallavailablemaketargets| ###Examples ```bash #Rununittests(fastest,~5seconds) maketest-unit #Runmanualtests(interactive) maketest-manual #Runintegrationtests maketest-e2e #Runalltests maketest ``` ###WithEnvironmentVariables ```bash #Runtestswithverboseoutput AT_BOT_TEST_VERBOSE=1maketest-unit #Runtestswithcustomtimeout(60secondsdefault) AT_BOT_TEST_TIMEOUT=30maketest-unit #Runwithdebugmodeenabled AT_BOT_DEBUG=1maketest-unit ``` ##CompleteTestSuite ###RunningAllTests ```bash maketest ``` Thisruns: 1.`tests/run_tests.sh`-Basictestrunner 2.Includesall12unittests ###RunningUnitTests(Recommended) ```bash maketest-unit ``` Ordirectly: ```bash bashscripts/test-unit.sh ``` ###RunningManualTests ```bash maketest-manual ``` Forinteractivetestingwithfullfeatureexploration. ###RunningEnd-to-EndTests ```bash maketest-e2e ``` ForcomprehensiveATProtocolintegrationtesting. ###SecureCredentialStorage AT-botsupports**optional**securecredentialstoragefortestingandautomationpurposes. ####HowItWorks Whenyoulogin,AT-botwillask: ``` Savecredentialssecurelyfortesting/automation?(y/n): ``` Ifyouchoose**yes**: -Yourcredentialsaresavedto`~/.config/at-bot/credentials.json` -Passwordis**encrypted**usingAES-256-CBCencryption -Encryptionkeyisstoredin`~/.config/at-bot/.key`with600permissions -Bothfilesarereadableonlybyyou(mode600) -Onnextlogin,credentialsareautomaticallydecryptedandloaded ####SecurityConsiderations **EncryptionDetails:** -Algorithm:AES-256-CBC(AdvancedEncryptionStandard) -Keyderivation:PBKDF2withsalt -Randomsaltusedforeachencryption -64-characterrandomencryptionkey -OpenSSLimplementation **ImportantNotes:** -Credentialsare**encrypted**,notjustencoded -Encryptionkeyismachine-specific -Onlyusethisfeatureonsecure,personalmachines -Nevercommit`credentials.json`or`.key`toversioncontrol -Forproductionuse,preferenvironmentvariablesorpropersecretmanagement ####MigrationfromOldBase64Format Ifyouhavecredentialssavedwiththeoldbase64encoding: -Theywillstillwork(backwardcompatibility) -You'llseeawarningtoupgrade -SimplylogoutandloginagaintoupgradetoAES-256encryption ####ClearingSavedCredentials ```bash at-botclear-credentials ``` Ormanuallydelete: ```bash rm~/.config/at-bot/credentials.json ``` ##TestingFeatures ###1.LoginandSessionManagement ```bash #Interactivelogin(willpromptforcredentials) at-botlogin #Checkcurrentuser at-botwhoami #Logout at-botlogout ``` ###2.DebugMode(ShowPlaintextPasswords) Fordebuggingauthenticationissues,youcanenabledebugmode: ```bash #Enabledebugoutput(showsplaintextpasswords) DEBUG=1at-botlogin ``` **Debugmodewillshow:** -Passwordlengthwhenentered -Passwordinplaintext -Passwordinbase64encoding -Credentialloadingoperations -APIrequestdetails **⚠SecurityWarning:**OnlyuseDEBUG=1insecure,privateenvironments.Debugoutputwillprintpasswordstotheterminal. ###3.CreatingPosts ```bash #Createasimplepost at-botpost"HellofromAT-bot!" #Createapostwithspecialcharacters(usequotes) at-botpost"Testing#ATProtocolwith@handle.bsky.social" ``` ###4.ReadingYourFeed ```bash #Readdefault(10posts) at-botfeed #Readspecificnumberofposts at-botfeed20 ```