Skip to content

LafaekStreet Backend API ​

Empowering Timor-Leste Citizens Through AI and Blockchain-Powered Civic Engagement

API: https://api.lafaekstreet.com

HederaAWSFastAPIPythonPostgreSQL

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:

  1. Relevance Check: Amazon Bedrock automatically rejects "garbage" images (selfies, food, memes) before they hit the database.
  2. 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 ​

bash
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.sh

3️⃣ Configuration ​

Create a .env file based on .env.example:

bash
cp .env.example .env

Key Variables:

  • DATABASE_URL: postgresql+asyncpg://user:pass@localhost/dbname
  • HEDERA_ACCOUNT_ID & HEDERA_PRIVATE_KEY: Hedera testnet credentials
  • AWS_KMS_KEY_ID: Your KMS ARN for hardware-backed signing
  • BEDROCK_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:

sql
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 ​

bash
# 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:


πŸ“‚ 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 ​

MethodEndpointPurpose
POST/api/v1/auth/registerRegister a new user with email
POST/api/v1/auth/verify-otpVerify email using 6-digit OTP
POST/api/v1/auth/resend-otpResend verification code
POST/api/v1/auth/loginEmail/Password login
POST/api/v1/auth/googleGoogle OAuth 2.0 Authentication
POST/api/v1/auth/forgot-passwordRequest password reset code
POST/api/v1/auth/reset-passwordReset password using OTP
POST/api/v1/auth/refreshRefresh expired access tokens
POST/api/v1/auth/logoutRevoke session tokens

πŸ‘€ User Management ​

MethodEndpointPurpose
GET/api/v1/users/meGet current user profile
PATCH/api/v1/users/meUpdate personal information
GET/api/v1/users/{user_id}Get user profile by ID

πŸ“‹ Citizen Reports ​

MethodEndpointPurpose
POST/api/v1/reportsCreate new civic report
GET/api/v1/reportsList all reports (Paginated)
GET/api/v1/reports/my-reportsView own report history
GET/api/v1/reports/nearbySearch 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-imageUpload image to S3 (Optimized)
POST/api/v1/reports/{id}/imagesAdd image to existing report
DELETE/api/v1/reports/{id}/images/{img_id}Remove evidence photo

πŸ’¬ Community & AI ​

MethodEndpointPurpose
POST/api/v1/reports/{id}/commentsAdd comment to a report
GET/api/v1/reports/{id}/commentsList all comments for a report
DELETE/api/v1/reports/{id}/comments/{c_id}Delete a comment
GET/api/v1/reports/{id}/ai-analysisGet full AI analysis history
GET/api/v1/reports/{id}/ai-analysis/latestGet latest AI assessment

πŸ“Š Monitoring & Blockchain ​

MethodEndpointPurpose
GET/api/v1/reports/stats/summaryGlobal system analytics
GET/api/v1/reports/stats/by-typeStats by infrastructure type
GET/api/v1/reports/stats/by-municipalityStats by region
GET/api/v1/blockchain/report/{id}/historyFetch Hedera audit trail

πŸ“ Location Services ​

MethodEndpointPurpose
GET/api/v1/locations/municipalitiesList all municipalities
GET/api/v1/locations/reverse-geocodeGet address from GPS
GET/api/v1/locations/searchSearch for locations

πŸ”” Notifications ​

MethodEndpointPurpose
GET/api/v1/notificationsList user notifications
GET/api/v1/notifications/unread-countGet unread alerts count
POST/api/v1/notifications/read-allMark 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 ​

ComponentServiceRole
ComputeAmazon Lightsail1 GB RAM, 2 vCPUs, 40 GB SSD
Reverse ProxyNginxSSL (Let's Encrypt), Rate Limiting, Security Headers
App ServerGunicorn + Uvicorn2 Async Workers (Port 8000)
DatabaseAiven PostgreSQLManaged DB with PostGIS & pgvector
CacheAiven ValkeySession storage & Rate limit tracking
SecurityFail2BanAutomated 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 ​

ScenarioResultAction TakenEvidence
Infrastructure Issueβœ… ApprovedFull AI analysis + Hedera Anchor
Irrelevant Photo❌ RejectedReport 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.

FeatureDescriptionEvidence
Reverse GeocodingAuto-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 ​

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.py with 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}
FeatureDescriptionEvidence
HashScan VerificationEvery 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 /health returns 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.py to 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 πŸ‡ΉπŸ‡±

Built for Timor-Leste