LafaekStreet Backend API β
Empowering Timor-Leste Citizens Through AI and Blockchain-Powered Civic Engagement
API: https://api.lafaekstreet.com
LafaekStreet Backend is the high-performance, secure backbone of the LafaekStreet ecosystem. It serves the Citizen Mobile App (Flutter), providing robust APIs for civic issue reporting, AI-driven infrastructure analysis, and immutable blockchain record-keeping.
ποΈ Architecture Overview β
The backend is built with FastAPI, leveraging asynchronous processing for high concurrency. It integrates multiple enterprise-grade services to ensure security, transparency, and intelligence.
π§© Core Components β
- API Engine: FastAPI with Pydantic for validation and SQLAlchemy (Async) for ORM.
- AI Brain: Amazon Bedrock (Nova 2) for automated image relevance checking and road damage assessment.
- Trust Layer: Hedera Hashgraph (HCS) for immutable audit trails of every report.
- Vault: AWS KMS for hardware-backed cryptographic signing of blockchain transactions.
- Storage: AWS S3 for secure image hosting.
- Cache: Valkey (Redis) for session and data caching.
- Database: PostgreSQL 15+ with PostGIS (Geospatial) and
pgvector(AI Similarity).
β¨ Features for Judges & Developers β
π‘οΈ Smart AI Validation Pipeline β
Unlike traditional reporting apps, LafaekStreet uses AI to protect system integrity:
- Relevance Check: Amazon Bedrock automatically rejects "garbage" images (selfies, food, memes) before they hit the database.
- Damage Assessment: AI analyzes road issues, determines severity, and suggests repair types.
βοΈ Hardware-Backed Transparency β
Every citizen report is anchored to the Hedera Testnet:
- Enterprise Security: Private keys are stored in AWS KMS (FIPS 140-2 Level 2 HSM). They never leave the hardware.
- Immutable Proof: Reports generate a unique transaction ID on Hedera, providing public proof of submission.
π Geospatial Intelligence β
Using PostGIS, the API can:
- Find "nearby" reports within a specific radius.
- Cluster issues by Municipality and District.
- Prevent duplicate reports via geospatial and AI vector search.
πΊοΈ System Data Flow β
The following diagram illustrates the complete end-to-end architecture, from the mobile client to the AI validation pipeline and blockchain anchoring.
π οΈ Tech Stack & Dependencies β
- Framework: FastAPI (Async)
- Database: PostgreSQL 15+ + PostGIS + pgvector
- AI: Amazon Bedrock (Nova 2 / Multimodal Embeddings)
- Blockchain: Hedera SDK + AWS KMS (SECP256K1)
- Security: JWT, Google OAuth 2.0, OTP (SMTP)
- Infrastructure: AWS (S3, KMS, Bedrock), Valkey
π Getting Started β
1οΈβ£ Prerequisites β
- Python 3.11+
- PostgreSQL 15+ (with PostGIS and pgvector)
- Valkey or Redis
- AWS Account (S3, KMS, Bedrock access)
- Hedera Testnet Account
2οΈβ£ Installation β
git clone https://github.com/your-repo/lafaekstreet.git
cd lafaekstreet_backend
# Setup Virtual Env
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install Core Deps
pip install -r requirements.txt
# Install KMS Cryptography Extensions
./install_kms_dependencies.sh3οΈβ£ Configuration β
Create a .env file based on .env.example:
cp .env.example .envKey Variables:
DATABASE_URL:postgresql+asyncpg://user:pass@localhost/dbnameHEDERA_ACCOUNT_ID&HEDERA_PRIVATE_KEY: Hedera testnet credentialsAWS_KMS_KEY_ID: Your KMS ARN for hardware-backed signingBEDROCK_MODEL_ID:us.amazon.nova-2-lite-v1:0
π Security: AWS KMS provides hardware-backed key storage (FIPS 140-2 Level 2). See KMS Quick Start for setup.
4οΈβ£ Database Initialization β
Ensure your database has the required extensions:
CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS pg_trgm;Then run migrations or initialize from schema.sql.
5οΈβ£ Run the Server β
# Development
python run.py
# Production
gunicorn -k uvicorn.workers.UvicornWorker app.main:app --bind 0.0.0.0:8000π API Documentation β
Once running, explore the interactive docs:
- Swagger UI:
http://localhost:8000/docs| https://api.lafaekstreet.com/docs - ReDoc:
http://localhost:8000/redoc| https://api.lafaekstreet.com/redoc
π Project Structure β
/app/api: Endpoint definitions (v1)./app/core: Configuration, Security, and Exceptions./app/services: Integrations (AWS, Hedera, Google, AI)./app/models: SQLAlchemy database models./app/schemas: Pydantic validation models./AWS_KMS_IMPLEMENTATION.md: Deep dive into hardware signing.
π€ Relationship with Flutter App β
This backend is the exclusive data provider for the LafaekStreet Mobile App.
- Auth: Supports Google Sign-In and Email OTP shared with the app.
- Offline Sync: Handles batch processing for reports created while the app was offline.
- Push Notifications: Sends real-time updates when a report status changes (e.g., from "Pending" to "Fixed").
π API Endpoints β
Below is a comprehensive list of the LafaekStreet Backend API endpoints. All endpoints (except Auth) require a valid JWT token in the Authorization: Bearer <token> header.
π Authentication β
| Method | Endpoint | Purpose |
|---|---|---|
| POST | /api/v1/auth/register | Register a new user with email |
| POST | /api/v1/auth/verify-otp | Verify email using 6-digit OTP |
| POST | /api/v1/auth/resend-otp | Resend verification code |
| POST | /api/v1/auth/login | Email/Password login |
| POST | /api/v1/auth/google | Google OAuth 2.0 Authentication |
| POST | /api/v1/auth/forgot-password | Request password reset code |
| POST | /api/v1/auth/reset-password | Reset password using OTP |
| POST | /api/v1/auth/refresh | Refresh expired access tokens |
| POST | /api/v1/auth/logout | Revoke session tokens |
π€ User Management β
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /api/v1/users/me | Get current user profile |
| PATCH | /api/v1/users/me | Update personal information |
| GET | /api/v1/users/{user_id} | Get user profile by ID |
π Citizen Reports β
| Method | Endpoint | Purpose |
|---|---|---|
| POST | /api/v1/reports | Create new civic report |
| GET | /api/v1/reports | List all reports (Paginated) |
| GET | /api/v1/reports/my-reports | View own report history |
| GET | /api/v1/reports/nearby | Search reports near GPS location |
| GET | /api/v1/reports/{id} | Get detailed report information |
| PATCH | /api/v1/reports/{id} | Update report details |
| DELETE | /api/v1/reports/{id} | Remove a report |
| POST | /api/v1/reports/pre-upload-image | Upload image to S3 (Optimized) |
| POST | /api/v1/reports/{id}/images | Add image to existing report |
| DELETE | /api/v1/reports/{id}/images/{img_id} | Remove evidence photo |
π¬ Community & AI β
| Method | Endpoint | Purpose |
|---|---|---|
| POST | /api/v1/reports/{id}/comments | Add comment to a report |
| GET | /api/v1/reports/{id}/comments | List all comments for a report |
| DELETE | /api/v1/reports/{id}/comments/{c_id} | Delete a comment |
| GET | /api/v1/reports/{id}/ai-analysis | Get full AI analysis history |
| GET | /api/v1/reports/{id}/ai-analysis/latest | Get latest AI assessment |
π Monitoring & Blockchain β
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /api/v1/reports/stats/summary | Global system analytics |
| GET | /api/v1/reports/stats/by-type | Stats by infrastructure type |
| GET | /api/v1/reports/stats/by-municipality | Stats by region |
| GET | /api/v1/blockchain/report/{id}/history | Fetch Hedera audit trail |
π Location Services β
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /api/v1/locations/municipalities | List all municipalities |
| GET | /api/v1/locations/reverse-geocode | Get address from GPS |
| GET | /api/v1/locations/search | Search for locations |
π Notifications β
| Method | Endpoint | Purpose |
|---|---|---|
| GET | /api/v1/notifications | List user notifications |
| GET | /api/v1/notifications/unread-count | Get unread alerts count |
| POST | /api/v1/notifications/read-all | Mark all as read |
π Security & Performance β
- Rate Limiting: 60 requests/min per IP to prevent abuse.
- Authorization: Role-based access (Citizen vs Admin).
- Concurrency: Fully async/await stack for high scalability.
π Deployment & Infrastructure β
The LafaekStreet Backend is production-ready and optimized for Amazon Lightsail (Ubuntu 22.04 LTS). It is designed to be cost-effective (~$8.50/month) while maintaining high security and performance for users in Timor-Leste.
π Hosting Architecture β
| Component | Service | Role |
|---|---|---|
| Compute | Amazon Lightsail | 1 GB RAM, 2 vCPUs, 40 GB SSD |
| Reverse Proxy | Nginx | SSL (Let's Encrypt), Rate Limiting, Security Headers |
| App Server | Gunicorn + Uvicorn | 2 Async Workers (Port 8000) |
| Database | Aiven PostgreSQL | Managed DB with PostGIS & pgvector |
| Cache | Aiven Valkey | Session storage & Rate limit tracking |
| Security | Fail2Ban | Automated brute-force protection |
π οΈ Automated Deployment β
We provide two production-grade scripts to manage the infrastructure directly from your local machine:
new_deploy_server.sh: One-click full deployment. Creates the instance, installs dependencies, configures Nginx, SSL, and systemd services.new_update_server.sh: Safe, zero-downtime updates with automatic backups, health checks, and rollbacks.
For detailed instructions, see the Deployment README.
π¬ Evidence & Validation β
Below are real-world logs and flows of the system in action.
π‘οΈ AI Image Validation Gate β
To maintain data quality, every report passes through an AI filter powered by Amazon Bedrock (Nova 2). This ensures that only genuine infrastructure issues are recorded and anchored to the blockchain.
πΈ Real-world Examples β
| Scenario | Result | Action Taken | Evidence |
|---|---|---|---|
| Infrastructure Issue | β Approved | Full AI analysis + Hedera Anchor | |
| Irrelevant Photo | β Rejected | Report marked 'Rejected' |
Example Logs: β
- Auto-Rejection:text
Report ID: 8d26a4ae-... - Image NOT relevant (confidence: 0.95). Auto-rejecting. - Full Pipeline:text
β REPORT SUCCESSFULLY SUBMITTED TO HEDERA. Signed with AWS KMS.
π Auto Location Detection β
When users submit reports with GPS coordinates, the backend automatically detects and fills in administrative location details using OpenStreetMap Nominatim reverse geocoding.
| Feature | Description | Evidence |
|---|---|---|
| Reverse Geocoding | Auto-fills Municipality, District, Suco, and Street from GPS coordinates |
How it works:
- User submits report with latitude/longitude
- Backend calls Nominatim API to reverse geocode
- Municipality, District, Suco, and Street are auto-populated
- Falls back gracefully if detection fails
βοΈ Blockchain Integration β
- β Detailed KMS Implementation information can be found in the QUICK START KMS.
- β Detailed HEDERA BLOCKCHAIN INTEGRATION information can be found in the HEDERA BLOCKCHAIN INTEGRATION.
Every report is anchored to the Hedera Testnet for immutability.
π Enterprise Security: Transaction signing uses AWS KMS with hardware-backed keys (FIPS 140-2 Level 2). Private keys never leave AWS infrastructure. See KMS Quick Start for details.
AWS KMS + Hedera Architecture β
Hedera HCS (Hashgraph Consensus Service) β
Every report and status change is recorded on Hedera, creating a public, immutable audit trail.
Security with AWS KMS:
- β Hardware-backed keys - SECP256K1 key in AWS HSM (FIPS 140-2 Level 2)
- β
Signing service -
kms_service.pywith keccak256 hashing + DER parsing - β Full audit trail - Every signing operation logged in AWS CloudTrail
- β Immutable records - Public verification via Hedera Explorer
π Public Verification β
Citizens can verify any report on HashScan Explorer:
https://hashscan.io/testnet/transaction/{transaction_id}| Feature | Description | Evidence |
|---|---|---|
| HashScan Verification | Every report transaction is publicly verifiable on Hedera's blockchain explorer |
Why Hedera? Every report becomes tamper-proof public evidence that cannot be deleted or altered by anyoneβincluding system administrators.
π§ Notification Services β
The backend keeps citizens informed via:
- Email OTP: Secure registration and password reset via SMTP.
- In-App Notifications: Real-time updates when reports are verified or fixed.
ποΈ Database & Scaling β
Detailed schema information can be found in the Database README.
π Monitoring & Health β
- Health Check:
GET /healthreturns system status. - Audit Logs: Comprehensive activity logging for administrative transparency.
π Developer Notes β
- Authentication: All endpoints (except auth) require
Authorization: Bearer <token>. - Image Limits: Max 1 image per report, 10MB each.
- Background Tasks: Report creation is async. AI validation, Hedera submission, and embeddings happen in the background.
π Troubleshooting & Support β
- KMS Issues: Run
python test_kms_integration.pyto verify AWS signing. - Database: Ensure PostGIS and pgvector extensions are active.
- AWS Permissions: Verify IAM roles for Bedrock, S3, and KMS.
Built with β€οΈ for Timor-Leste πΉπ±
