All Architecture Showcase Artifacts
System Workflows
Interactive sequence diagrams detailing OAuth flows, webhooks, and complex async event processing.
Category: architecture
Tags: Sequence, State, Data Flow
Detailed Architecture Specification:
# 17. ADVANCED BUSINESS PROCESS FLOWS
## 17.1 Dispute Resolution Flow
**Trigger**: Buyer marks order as "Item Not Received" or "Not as Described".
**Actors**: Buyer, Seller, Admin.
```mermaid
stateDiagram-v2
[*] --> Draft
Draft --> Open: Buyer submits claim
Open --> SellerAction: Notify Seller
state SellerAction {
[*] --> Waiting
Waiting --> OfferRefund: Seller offers Full Refund
Waiting --> OfferPartial: Seller offers Partial
Waiting --> RejectClaim: Seller denies (Provides Proof)
}
OfferRefund --> Closed: Buyer Accepted (Auto)
OfferPartial --> BuyerAction: Buyer reviews offer
RejectClaim --> Mediation: Buyer escalates
state BuyerAction {
[*] --> Review
Review --> Closed: Accept Partial
Review --> Mediation: Reject Partial
}
state Mediation {
[*] --> AdminQueue
AdminQueue --> EvidenceReview
EvidenceReview --> DecisionBuyer: Refund Buyer
EvidenceReview --> DecisionSeller: Release Funds
}
DecisionBuyer --> Closed
DecisionSeller --> Closed
```
STRIDE Security Analysis
Proactive threat modeling matrix identifying vulnerabilities and required mitigations out-of-the-box.
Category: security
Tags: Infosec, Compliance, OWASP
Detailed Architecture Specification:
# 21. SECURITY ARCHITECTURE
## 21.2 Threat Models (STRIDE Analysis)
### 21.2.1 Feature: Auction Bidding
| Threat | Description | Mitigation Strategy |
|--------|-------------|---------------------|
| **Spoofing** | Attacker places bid as another user. | **MFA Step-up**: Require TOTP for bids > $1,000. **Session Binding**: Validate `device_id` in JWT matches request. |
| **Tampering** | Attacker modifies bid amount in transit. | **TLS 1.3**: Mandatory. **Payload Validation**: Server-side check `bid_amount > current_price + increment`. |
| **Repudiation** | User denies placing a winning bid. | **Audit Logs**: Log IP, User-Agent, Timestamp. **Email Confirmation**: Instant email on bid placement. |
| **Information Disclosure** | Competitor sees user's Max Bid (Proxy). | **Server-Side Logic**: Max bid stored in DB, never sent to client. Client only sees `current_price`. |
| **Denial of Service** | Bot floods auction with bids to crash DB. | **Rate Limiting**: 10 bids/min per user. **Captcha**: Triggered on rapid bidding. **Redis Locking**: Serializes bid processing. |
| **Elevation of Privilege** | User accesses admin bid removal tools. | **RBAC**: Strict checks on `/admin/bids/*` endpoints. **Network Isolation**: Admin API on private subnet or VPN only. |
Phase-Based Roadmap
MVP through V3 feature prioritization matrices to ensure you ship the core value proposition first.
Category: planning
Tags: MVP, Agile, Prioritization
Detailed Architecture Specification:
# 11. IMPLEMENTATION ROADMAP
## Phase 1: Core Foundation & Identity
**Objective**: Establish the secure perimeter and user identity.
- **Tasks**:
- Setup Monorepo (Turbo) + Docker environment.
- Implement Identity Service (NestJS + Postgres).
- Implement Auth (JWT, Refresh Tokens, RBAC).
- Build User Profile UI (Next.js).
- **Critical Code**: `AuthGuard`, `UserEntity`, `ProfileService`.
## Phase 2: Marketplace Engine
**Objective**: Build core transactional product listing features.
- **Tasks**:
- Schema generation and DB migrations.
- CRUD for Product Listings API.
- Payment Webhook integration (Stripe).
Entity Relationship Schema
Fully normalized database schemas tailored for your specific stack (PostgreSQL, MongoDB, DynamoDB).
Category: database
Tags: Schema, Indexes, Relations
Detailed Architecture Specification:
# 12. RELATIONAL DATA MODELING
## 12.1 Core Entities & Relationships
```mermaid
erDiagram
USERS ||--o{ AUCTIONS : creates
USERS ||--o{ BIDS : places
USERS ||--o{ REVIEWS : writes
AUCTIONS {
uuid id PK
uuid seller_id FK
varchar title
numeric starting_price
timestamp ends_at
enum status "DRAFT, ACTIVE, CLOSED"
}
BIDS {
uuid id PK
uuid auction_id FK
uuid bidder_id FK
numeric amount
timestamp placed_at
boolean is_winning
}
AUCTIONS ||--o{ BIDS : receives
```
Component Architectures
Frontend state management strategies and backend service layer patterns specific to your framework.
Category: integration
Tags: Patterns, State, Services
Detailed Architecture Specification:
## 9.3 Frontend Implementation (Next.js App Router)
### `apps/web/app/listings/[id]/page.tsx`
```tsx
import { notFound } from 'next/navigation';
import { getListing } from '@/lib/api/listings';
import { BidForm } from './_components/bid-form';
import { ImageGallery } from '@/components/ui/image-gallery';
import { formatDate } from '@/lib/utils';
export default async function ListingPage({ params }: { params: { id: string } }) {
const listing = await getListing(params.id);
if (!listing) {
notFound();
}
return (
<div className="container mx-auto px-4 py-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
<ImageGallery images={listing.images} />
<div className="space-y-6">
<h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">
{listing.title}
</h1>
<div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
<div>
<p className="text-sm text-gray-500">Current Price</p>
<p className="text-2xl font-bold text-primary">
${listing.price.toFixed(2)}
</p>
</div>
{listing.type === 'AUCTION' && (
<div className="text-right">
<p className="text-sm text-gray-500">Ends In</p>
<p className="text-xl font-mono">
{formatDate(listing.endsAt)}
</p>
</div>
)}
</div>
<div className="prose dark:prose-invert">
<h3>Description</h3>
<p>{listing.description}</p>
</div>
{listing.status === 'ACTIVE' && (
<BidForm
listingId={listing.id}
currentPrice={listing.price}
minIncrement={listing.minBidIncrement}
/>
)}
</div>
</div>
</div>
);
}
```
Deployment Topology
Serverless deployment architecture detailing VPCs, subnets, API Gateways, and managed services.
Category: architecture
Tags: Cloud, Network, Infrastructure
Detailed Architecture Specification:
# 4. MONITORING & OBSERVABILITY
## 4.1 Metrics & Dashboards
Key business and technical metrics are continuously collected and visualized on a centralized dashboard.
- **Technical**: API request rates, p95/p99 latency, error rates by HTTP status, DB connection pool utilization, cold start frequency.
- **Business**: Active voting sessions, total votes cast per hour, user registration rates.
## 4.2 Health Checks
The NestJS backend exposes a comprehensive `/health` endpoint implementing both **liveness** and **readiness** probes:
1. **Liveness** — Confirms the Node.js process is running and not deadlocked.
2. **Readiness** — Executes a `SELECT 1` against the database, pings Redis, and verifies S3 API connectivity.
3. **Circuit Breakers** — External calls (e.g., Email Provider) use circuit breakers; if the service fails repeatedly, the health check degrades gracefully.
## 4.3 Alerting Thresholds
| Metric | Warning Threshold | Critical Threshold | Escalation Action |
|--------|-------------------|--------------------|--------------------|
| API p95 Latency | > 300ms for 5 min | > 500ms for 5 min | Page On-Call Engineer |
| HTTP 5xx Error Rate | > 1% of traffic | > 5% of traffic | Page Engineer + Auto-Rollback |
| Database CPU Utilization | > 70% for 10 min | > 90% for 5 min | Trigger DB Auto-Scale Alert |
| Connection Pool Saturation | > 80% capacity | 100% (Exhaustion) | Page Database Admin immediately |
| WebSocket Drop Rate | > 5% disconnects/min | > 15% disconnects/min | Investigate Redis Pub/Sub health |
## 4.4 SLO Definitions
- **Availability**: Core voting API maintains **99.9%** uptime over a rolling 30-day window.
- **Read Latency**: 95% of all read requests served in under **200ms**.
- **Write Latency**: 95% of all write requests (casting a vote) processed in under **400ms**.
OWASP Threat Model
Specific mitigation strategies implemented at the ORM and API Gateway levels to defend against common attack vectors.
Category: security
Tags: Vulnerabilities, Mitigation, Defense
Detailed Architecture Specification:
# 7.1 OWASP TOP 10 THREAT MODEL
## 7.1.1 Mitigation Matrix
| # | Threat | Risk | Mitigation Strategy |
|---|--------|------|---------------------|
| 1 | **Broken Access Control** | High | Strict NestJS Guards enforcing RBAC on every endpoint. Direct object references validate requester ID matches target or has Admin role. |
| 2 | **Cryptographic Failures** | High | TLS 1.3 enforced globally. AES-256 at rest for all PII. Argon2id for password hashing. No secrets in code or logs. |
| 3 | **Injection (SQL/NoSQL)** | High | Parameterized queries via ORM. Zod schema validation on all inputs. No raw SQL concatenation permitted. |
| 4 | **Insecure Design** | Medium | Threat modeling conducted per feature (STRIDE). Rate limiting and CAPTCHA on sensitive flows. |
| 5 | **Security Misconfiguration** | Medium | Automated infrastructure-as-code (Terraform). No default credentials. CORS locked to known origins. |
| 6 | **Vulnerable Components** | Medium | Dependabot + Snyk scanning on every PR. Lock files committed. `npm audit` in CI pipeline. |
| 7 | **Auth & ID Failures** | High | Short-lived JWTs (15 min). Refresh token rotation. Account lockout after 5 failed attempts. |
| 8 | **Data Integrity Failures** | Medium | Signed deployment artifacts. Immutable audit logs. Database migration checksums verified pre-deploy. |
| 9 | **Logging & Monitoring Gaps** | Medium | Structured JSON logging. PII masking before log write. 30-day hot retention, 1-year cold archive. |
| 10 | **SSRF** | Low | Outbound request allow-list. No user-supplied URLs passed to backend HTTP clients without validation. |
## 7.1.2 Compliance Frameworks
### GDPR (EU)
- **Right to Erasure**: `DELETE /api/users/me` triggers a cascading soft-delete, anonymizing PII within 30 days.
- **Data Portability**: `GET /api/users/me/export` returns a JSON archive of all personal data.
- **Consent**: Explicit opt-in recorded with timestamp, IP address, and document version.
### CCPA / CPRA (California)
- **Do Not Sell**: Toggle in user settings disables all non-essential analytics telemetry.
- **Notice at Collection**: Registration flow discloses exactly what data is captured and its purpose.
### PIPEDA (Canada)
- **Principle 3 (Consent)**: Plain-language Privacy Policies presented before account creation.
- **Principle 7 (Safeguards)**: TLS 1.3 in transit, AES-256 at rest, strict RBAC for admin access.
DevOps Runbooks
Incident response plans, backup strategies, and deployment pipelines to keep your app stable.
Category: security
Tags: SRE, CI/CD, Disaster Recovery
Detailed Architecture Specification:
# 32. OPERATIONAL RUNBOOKS
## 32.1 Incident: High Database CPU
**Symptom**: RDS CPU utilization > 90% for > 5 minutes. Latency spikes.
**Diagnosis**:
1. Check `pg_stat_activity` for long-running queries.
2. Check for "Death Spiral" (connection pile-up).
**Mitigation**:
1. **Immediate**: Kill queries running > 30s.
```sql
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'active' AND now() - query_start > interval '30 seconds';
```
2. **Short-term**: Scale up Read Replicas via AWS Console.
3. **Root Cause**: Analyze query plan. Add missing index.
## 32.2 Incident: Payment Webhook Failure
**Symptom**: Users complaining "I paid but order is still pending".
**Diagnosis**:
1. Check Stripe Dashboard -> Developers -> Webhooks. Look for 500/400 errors.
2. Check Application Logs for `StripeSignatureVerificationError`.
**Mitigation**:
1. **Fix**: If code bug, deploy hotfix.
2. **Replay**: Use Stripe CLI or Dashboard to "Resend Event" for failed webhooks.
Optimized PostgreSQL ERD
An advanced view of relational entity structures utilizing heavy JSONB fields.
Category: database
Tags: Relational, SQL, Indexes
Detailed Architecture Specification:
# 6. RELATIONAL DATA MODELING
## 6.1 Entity Relationship Diagram
```mermaid
erDiagram
USER ||--o{ SESSION : has
USER ||--o{ API_KEY : owns
USER ||--o{ SUBSCRIPTION : subscribes
USER {
uuid id PK
string email UK
string password_hash
string display_name
enum role
timestamp created_at
timestamp last_login
boolean is_verified
jsonb preferences
}
SUBSCRIPTION ||--|{ INVOICE : generates
SUBSCRIPTION {
uuid id PK
uuid user_id FK
enum plan
enum status
timestamp current_period_start
timestamp current_period_end
string stripe_subscription_id UK
}
WORKSPACE ||--o{ PROJECT : contains
WORKSPACE ||--o{ WORKSPACE_MEMBER : has
USER ||--o{ WORKSPACE_MEMBER : joins
WORKSPACE {
uuid id PK
string name
string slug UK
uuid owner_id FK
jsonb settings
timestamp created_at
}
PROJECT ||--o{ GENERATION : produces
PROJECT ||--o{ DOCUMENT : stores
PROJECT {
uuid id PK
uuid workspace_id FK
string name
text description
jsonb tech_stack
jsonb config
enum architecture_style
timestamp created_at
timestamp updated_at
}
GENERATION ||--o{ GENERATION_PHASE : has
GENERATION ||--o{ GENERATION_ARTIFACT : outputs
GENERATION {
uuid id PK
uuid project_id FK
uuid user_id FK
enum template_type
enum status
integer quality_score
integer token_count
decimal cost_usd
timestamp started_at
timestamp completed_at
}
GENERATION_PHASE {
uuid id PK
uuid generation_id FK
string phase_name
integer phase_order
integer duration_ms
integer quality_score
boolean success
integer retry_count
}
GENERATION_ARTIFACT {
uuid id PK
uuid generation_id FK
enum artifact_type
text content
string storage_path
integer size_bytes
boolean is_encrypted
}
AUDIT_LOG {
uuid id PK
uuid user_id FK
string action
string resource_type
uuid resource_id
jsonb metadata
inet ip_address
timestamp created_at
}
```
## 6.2 Core Entities
| Entity | Row Estimate | Key Indexes | Relationships |
|--------|:----------:|-------------|---------------|
| **USER** | ~50K | `email` (unique), `created_at` | → Session, API_Key, Subscription, Workspace |
| **SUBSCRIPTION** | ~30K | `stripe_subscription_id` (unique), `user_id` | → Invoice |
| **WORKSPACE** | ~15K | `slug` (unique), `owner_id` | → Project, Workspace_Member |
| **PROJECT** | ~40K | `workspace_id`, `created_at` | → Generation, Document |
| **GENERATION** | ~200K | `project_id`, `status`, `started_at` | → Phase, Artifact |
| **AUDIT_LOG** | ~2M | `user_id`, `action`, `created_at` | — (append-only) |
Comprehensive Component Tree
Frontend structural mapping linking UI pages to atomic interactive elements directly.
Category: integration
Tags: UI, Frontend, React
Detailed Architecture Specification:
# 5. COMPREHENSIVE COMPONENT TREE
## 5.1 Project Directory Structure
The following scaffolding represents the complete file system layout generated for a production-grade Next.js application with TypeScript, Prisma, tRPC, and Stripe integration.
```
├── .github/
│ ├── workflows/
│ │ ├── ci.yml
│ │ ├── deploy-staging.yml
│ │ └── deploy-production.yml
│ ├── CODEOWNERS
│ └── pull_request_template.md
├── .husky/
│ ├── pre-commit
│ └── commit-msg
├── docker/
│ ├── Dockerfile
│ ├── Dockerfile.dev
│ ├── docker-compose.yml
│ ├── docker-compose.dev.yml
│ └── nginx.conf
├── docs/
│ ├── architecture/
│ │ ├── ADR-001-framework-selection.md
│ │ ├── ADR-002-database-strategy.md
│ │ ├── ADR-003-auth-approach.md
│ │ └── system-diagram.mermaid
│ ├── api/
│ │ └── openapi.yaml
│ └── runbook.md
├── prisma/
│ ├── schema.prisma
│ ├── seed.ts
│ └── migrations/
│ └── 001_initial_schema/
│ └── migration.sql
├── src/
│ ├── app/
│ │ ├── layout.tsx
│ │ ├── page.tsx
│ │ ├── loading.tsx
│ │ ├── error.tsx
│ │ ├── not-found.tsx
│ │ ├── (auth)/
│ │ │ ├── login/page.tsx
│ │ │ ├── signup/page.tsx
│ │ │ └── layout.tsx
│ │ ├── (dashboard)/
│ │ │ ├── layout.tsx
│ │ │ ├── overview/page.tsx
│ │ │ ├── projects/
│ │ │ │ ├── page.tsx
│ │ │ │ └── [id]/page.tsx
│ │ │ ├── settings/page.tsx
│ │ │ └── billing/page.tsx
│ │ └── api/
│ │ ├── auth/[...nextauth]/route.ts
│ │ ├── webhooks/stripe/route.ts
│ │ ├── trpc/[trpc]/route.ts
│ │ └── health/route.ts
│ ├── components/
│ │ ├── ui/
│ │ │ ├── Button.tsx
│ │ │ ├── Input.tsx
│ │ │ ├── Modal.tsx
│ │ │ ├── Toast.tsx
│ │ │ ├── Skeleton.tsx
│ │ │ └── index.ts
│ │ ├── layouts/
│ │ │ ├── AppShell.tsx
│ │ │ ├── Sidebar.tsx
│ │ │ ├── Header.tsx
│ │ │ └── Footer.tsx
│ │ └── features/
│ │ ├── auth/
│ │ │ ├── LoginForm.tsx
│ │ │ ├── SignupForm.tsx
│ │ │ └── AuthGuard.tsx
│ │ └── projects/
│ │ ├── ProjectCard.tsx
│ │ ├── ProjectList.tsx
│ │ └── CreateProjectModal.tsx
│ ├── server/
│ │ ├── trpc/
│ │ │ ├── router.ts
│ │ │ ├── context.ts
│ │ │ └── procedures/
│ │ │ ├── user.ts
│ │ │ ├── project.ts
│ │ │ └── billing.ts
│ │ ├── db/
│ │ │ ├── client.ts
│ │ │ └── queries/
│ │ │ ├── users.ts
│ │ │ └── projects.ts
│ │ └── services/
│ │ ├── auth.service.ts
│ │ ├── email.service.ts
│ │ ├── stripe.service.ts
│ │ └── analytics.service.ts
│ ├── lib/
│ │ ├── utils.ts
│ │ ├── constants.ts
│ │ ├── validators.ts
│ │ └── hooks/
│ │ ├── useAuth.ts
│ │ ├── useDebounce.ts
│ │ └── useMediaQuery.ts
│ ├── styles/
│ │ ├── globals.css
│ │ └── tokens.css
│ └── types/
│ ├── index.ts
│ ├── api.ts
│ └── database.ts
├── tests/
│ ├── unit/
│ │ └── services/
│ │ └── auth.test.ts
│ ├── integration/
│ │ └── api/
│ │ └── users.test.ts
│ └── e2e/
│ ├── auth.spec.ts
│ └── projects.spec.ts
├── .env.example
├── .eslintrc.cjs
├── .prettierrc
├── .gitignore
├── next.config.ts
├── tailwind.config.ts
├── tsconfig.json
├── vitest.config.ts
├── playwright.config.ts
└── package.json
```
## 5.2 Key Directories
| Directory | Purpose | Key Files |
|-----------|---------|-----------|
| **`.github/`** | CI/CD pipelines + CODEOWNERS | `ci.yml`, `deploy-production.yml` |
| **`docker/`** | Container configuration | `Dockerfile`, `docker-compose.yml` |
| **`prisma/`** | Database schema + migrations | `schema.prisma`, `seed.ts` |
| **`src/app/`** | Next.js App Router pages | Route groups: `(auth)`, `(dashboard)` |
| **`src/components/`** | UI library + feature components | `ui/`, `layouts/`, `features/` |
| **`src/server/`** | Backend logic + tRPC routes | `trpc/`, `db/`, `services/` |
| **`tests/`** | Unit, integration, E2E tests | Vitest + Playwright |
System Context & Architecture
High-level actor communication flows and detailed backend microservice dependency mapping.
Category: architecture
Tags: Actors, Services, Systems, Diagrams
Detailed Architecture Specification:
# 1. SYSTEM CONTEXT & ARCHITECTURE
## 1.1 Project Overview
The application is a **community engagement platform** enabling residents to browse, vote, and interact with curated content across multiple categories (Activities, Meals, Films). The system targets deployment across **North America, Europe, and Australasia**.
## 1.2 Architectural Decisions (ADRs)
### ADR 1: Serverless NestJS Backend
- **Context**: The application requires elastic scaling for unpredictable voting surges.
- **Decision**: Deploy the NestJS API as a Serverless function (AWS Lambda / Azure Functions).
- **Consequences**: Near-zero idle cost, automatic scaling, but introduces cold-start latency (~300ms).
### ADR 2: Expo with React Native Frontend
- **Context**: The product must ship on both iOS and Android with a single codebase.
- **Decision**: Use Expo SDK with React Native and Material Design components.
- **Consequences**: Faster development cycle, OTA updates via EAS, but limited access to some native APIs.
### ADR 3: Pre-Signed URL Uploads
- **Context**: Content Admins need to upload images (activity photos, meal images) directly.
- **Decision**: Use pre-signed S3 URLs to allow direct-to-cloud uploads from the mobile client.
- **Consequences**: Reduces backend bandwidth, but the client must handle multi-step upload workflows.
### ADR 4: Soft Deletion Strategy
- **Context**: Data retention policies and historical voting analytics require data preservation.
- **Decision**: Implement soft deletion across all core entities via a `deleted_at` timestamp column.
- **Consequences**: Preserves historical data, allows easy recovery. All queries auto-filter soft-deleted records.
## 1.3 Technology Stack
| Layer | Technology | Justification |
|-------|-----------|---------------|
| **Frontend** | Expo / React Native | Cross-platform mobile with OTA updates |
| **Backend** | NestJS (TypeScript) | Enterprise-grade, modular, decorator-based |
| **Database** | PostgreSQL (Aurora) | ACID compliance, JSONB support, partitioning |
| **Cache** | Redis Cluster | Session store, rate limiting, Pub/Sub |
| **Storage** | AWS S3 | Scalable media storage with CDN integration |
| **Auth** | JWT + Refresh Tokens | Stateless auth for Serverless compatibility |
REST/GraphQL API Specs
Production-ready endpoint definitions, request/response schemas, and error handling protocols.
Category: integration
Tags: OpenAPI, Endpoints, Payloads
Detailed Architecture Specification:
# 8. API SPECIFICATION (Key Interfaces)
| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| POST | `/auth/login` | None | Returns JWT Access + Refresh Token |
| GET | `/listings` | Public | Search listings with filters (Elasticsearch) |
| POST | `/listings` | Seller | Create a new listing |
| POST | `/listings/:id/bid` | User | Place a bid (Atomic transaction) |
| GET | `/feed` | User | Get personalized activity feed |
| POST | `/checkout/session` | User | Create Stripe Checkout Session |
Global Compliance Frameworks
Documentation outlining adherence to strict privacy laws including GDPR, CCPA, and PIPEDA data sovereignty.
Category: security
Tags: GDPR, Privacy, Legal
Detailed Architecture Specification:
# 7.3 GLOBAL COMPLIANCE FRAMEWORKS
## 7.3.1 Data Classification Matrix
| Data Type | Classification | Storage Requirements | Retention Policy |
|-----------|---------------|---------------------|------------------|
| User Credentials (Passwords) | **Highly Sensitive** | Argon2id hash, never logged | Until account deletion |
| User PII (Name, Email, IP) | **Sensitive / PII** | Encrypted at rest (AES-256) | Active account + 30 days post-deletion |
| Voting Records | Internal | Standard relational storage | Indefinite (anonymized if user deleted) |
| Content (Activities, Meals) | Public | Standard relational + S3 | Indefinite (soft deleted) |
| Audit Logs | Internal | Immutable append-only storage | 7 years (compliance requirement) |
| System Analytics | Internal | Aggregated time-series storage | Raw: 30 days; Aggregated: 1 year |
## 7.3.2 Encryption Strategy
The application employs a **defense-in-depth** encryption strategy:
### In-Transit
- **TLS 1.3** enforced globally with strong cipher suites (`TLS_AES_256_GCM_SHA384`).
- Automated certificate management via the cloud provider's managed certificate service.
- Mobile app implements **certificate pinning** to prevent MitM attacks on public Wi-Fi.
### At-Rest
- Managed database and S3 storage use **AES-256** encryption with KMS-managed keys.
- Automated **annual key rotation** schedules.
- Field-level encryption (AES-256-GCM) for future highly sensitive data at the application layer.
Data Flow Orchestration
Comprehensive data-flow architectures for massive scale and concurrency.
Category: architecture
Tags: Orchestration, Scaling
Detailed Architecture Specification:
# 4. DATA FLOW ORCHESTRATION
## 4.1 Comprehensive Technology Stack
| Layer | Technology | Version | Rationale |
|-------|-----------|---------|-----------|
| **Language** | TypeScript | Latest | Static typing, interfaces, and advanced generics across the entire stack |
| **Frontend Framework** | Expo (React Native) | Latest | Managed workflow for cross-platform mobile development |
| **Backend Framework** | NestJS | Latest | Enterprise-grade architecture with dependency injection and modularity |
| **UI/Component Library** | Material Design | Latest | Accessible, highly tested UI components ensuring UX consistency |
| **Database** | PostgreSQL (Aurora) | Latest | ACID-compliant relational storage with complex joins and connection pooling |
| **Hosting/Cloud** | AWS (Serverless) | Latest | API Gateway, Lambda functions, and managed infrastructure |
| **Auth Provider** | Firebase Auth | Latest | Secure identity management and token issuance |
| **Caching & Pub/Sub** | Redis Cluster | Latest | Microsecond latency for read-heavy operations and WebSocket broadcasting |
| **File Storage** | S3-Compatible Storage | Latest | Durable, scalable object storage for user-uploaded media |
| **State Management** | Zustand | Latest | Lightweight global state for auth status, theme, and cached API responses |
| **ORM/Query Builder** | Prisma | Latest | Type-safe database queries, streamlined migrations, reduced SQL injection |
| **Testing Framework** | Jest + Supertest | Latest | Unit testing with robust mocking and integration test support |
## 4.2 Stack Synergy Rationale
The combination of **TypeScript**, **Expo**, and **NestJS** creates a highly synergistic, full-stack JavaScript/TypeScript ecosystem:
1. **Shared Types** — Interface definitions in `shared/types/` are consumed by both frontend and backend, eliminating contract drift.
2. **Shared Validation** — Zod schemas in `shared/schemas/` validate payloads identically on client and server.
3. **Single Language** — Developers context-switch without cognitive overhead between frontend and backend codebases.
## 4.3 Data Flow Pipeline
```
Client Request → API Gateway → WAF Filter → Lambda (NestJS)
↓
Redis Cache Check
↓ (HIT) ↓ (MISS)
Return Cached Query PostgreSQL
↓
Populate Cache
↓
Return Response
```
Data Classification Matrix
Data mapping that classifies PII and dictates encryption, retention, and storage requirements for the database layer.
Category: security
Tags: PII, Encryption, Retention
Detailed Architecture Specification:
# 9. TESTING STRATEGY
## 9.1 Unit Testing (Jest)
All business logic within NestJS Services must have **100% test coverage**, including all error paths and edge cases.
```typescript
describe('VotingService', () => {
let service: VotingService;
beforeEach(async () => {
const module = await Test.createTestingModule({
providers: [
VotingService,
{ provide: 'DATABASE', useValue: mockDatabase },
],
}).compile();
service = module.get(VotingService);
});
it('should successfully record a vote', async () => {
mockDatabase.findContentItem
.mockResolvedValue({ id: 'item-1', status: 'PUBLISHED' });
mockDatabase.findVote.mockResolvedValue(null);
mockDatabase.createVote
.mockResolvedValue({ id: 'vote-1' });
const result = await service.recordVote('user-1', 'item-1');
expect(result.id).toBe('vote-1');
});
it('should throw ConflictException on double vote', async () => {
mockDatabase.findVote
.mockResolvedValue({ id: 'existing-vote' });
await expect(service.recordVote('user-1', 'item-1'))
.rejects.toThrow(ConflictException);
});
});
```
## 9.2 Integration Testing
- **Docker**: Ephemeral test containers for Postgres and Redis spun up before suite runs.
- **Seeding**: Factory functions generate realistic dummy data (`createUserFactory`, `createContentItemFactory`).
- **Teardown**: Database truncated (not dropped) between runs for speed.
## 9.3 E2E Testing (Detox)
End-to-End testing simulates real user interactions on iOS and Android simulators:
1. Complete registration → login → vote → verify real-time update flow.
2. Admin content creation → publish → verify on resident device.
3. GDPR data export → verify JSON archive completeness.
Unified Error Handling
Standardized error catalogs detailing response codes, validation failures, and exception mapping.
Category: integration
Tags: Exceptions, Validation, HTTP
Detailed Architecture Specification:
# 6.3 UNIFIED ERROR HANDLING
## 6.3.1 Standardized Error Response Format
All API errors follow a **single, predictable JSON envelope** so the client never has to guess the shape of an error.
```json
{
"error": {
"code": "VALIDATION_FAILED",
"message": "The provided input is invalid.",
"details": [
{ "field": "email", "issue": "Must be a valid email address" }
],
"correlation_id": "req-a1b2c3d4-5678",
"timestamp": "2023-10-27T10:00:00Z"
}
}
```
## 6.3.2 Error Code Catalog
| Code | HTTP | Description |
|------|------|-------------|
| `VALIDATION_FAILED` | 400 | Request body or query params failed Zod schema validation. |
| `INVALID_STATE` | 400 | Action cannot be performed in the current entity state. |
| `UNAUTHORIZED` | 401 | Missing or invalid Bearer token. |
| `TOKEN_REVOKED` | 401 | Session was manually terminated by admin or password reset. |
| `FORBIDDEN_ROLE` | 403 | User lacks required RBAC permissions for this endpoint. |
| `ACCOUNT_LOCKED` | 403 | Account suspended due to 5+ consecutive failed login attempts. |
| `NOT_FOUND` | 404 | Requested resource does not exist or has been soft-deleted. |
| `CONFLICT_DOUBLE_VOTE` | 409 | User attempted to cast a duplicate vote on the same item. |
| `FILE_TOO_LARGE` | 413 | Uploaded media exceeds the 5 MB file size limit. |
| `UNSUPPORTED_MEDIA_TYPE` | 415 | Uploaded file is not a valid image (JPEG, PNG, WebP only). |
| `RATE_LIMIT_EXCEEDED` | 429 | Client sent too many requests within the rate window. |
| `LEGAL_CONSENT_REQUIRED` | 451 | User must accept updated Terms before proceeding. |
| `INTERNAL_SERVER_ERROR` | 500 | Unhandled backend exception (generic fallback). |
| `SERVICE_UNAVAILABLE` | 503 | System is in maintenance mode or a dependency is down. |
| `GATEWAY_TIMEOUT` | 504 | External dependency (e.g., Auth Provider) timed out. |
## 6.3.3 Exception Filter Implementation
All exceptions pass through a global NestJS filter that standardizes the output:
```typescript
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const res = ctx.getResponse();
const req = ctx.getRequest();
const status = exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const errorResponse = {
error: {
code: this.mapStatusToCode(status),
message: this.extractMessage(exception),
correlation_id: req.headers['x-request-id'] ?? uuidv4(),
timestamp: new Date().toISOString(),
},
};
res.status(status).json(errorResponse);
}
}
```
Complete Mobile App Architecture
A full-stack architecture specification including React Native frontend, Serverless NestJS backend, and Aurora Postgres database schemas.
Category: planning
Tags: React Native, Serverless, Full Stack
Detailed Architecture Specification:
# 1. EXECUTIVE SUMMARY
## 1.1 Project Overview
A **full-stack mobile application** enabling community residents to browse, vote, and interact with curated content across multiple categories. The platform targets deployment across **three major regions**: North America, Europe, and Australasia.
## 1.2 Technology Stack
| Layer | Technology | Purpose |
|-------|-----------|---------|
| **Mobile Frontend** | React Native (Expo SDK) | Cross-platform iOS & Android |
| **Backend API** | NestJS (TypeScript) | Modular, decorator-based REST API |
| **Database** | PostgreSQL (Aurora Serverless) | ACID-compliant relational storage |
| **Cache / Pub-Sub** | Redis Cluster | Session storage, rate limiting, real-time events |
| **Object Storage** | AWS S3 + CloudFront CDN | Media uploads with global edge caching |
| **Authentication** | JWT + Refresh Token Rotation | Stateless auth optimized for Serverless |
| **CI/CD** | GitHub Actions | Automated testing, staging, and production deploys |
## 1.3 Core Feature Set
1. **User Registration & RBAC** — Secure authentication with three-tier role system (Resident, Content Admin, Super Admin).
2. **Full CRUD** — Content management for Activities, Meals, and Films with soft-deletion.
3. **Real-Time Voting** — WebSocket-powered live vote tallies with Redis Pub/Sub broadcasting.
4. **Media Uploads** — Pre-signed S3 URLs for direct-to-cloud image uploads.
5. **Internationalization** — Multi-locale support (EN, FR, ES, DE) with WCAG 2.1 AA accessibility.
6. **Compliance** — GDPR, CCPA, PIPEDA-ready with automated data export and erasure.
Alternative Execution Flow
Sequence diagram covering pessimistic locking strategies in database reads.
Category: architecture
Tags: Locking, Concurrency
Detailed Architecture Specification:
# 3. ALTERNATIVE EXECUTION FLOW
## 3.1 Request Processing Pipeline
All incoming HTTPS requests pass through the **Web Application Firewall** before hitting the NestJS Serverless functions.
### 3.1.1 Read Path (Cache-Aside Pattern)
1. Client sends `GET /api/content/items` request
2. NestJS interceptor checks **Redis cache** for the requested key
3. **Cache HIT** → Return cached response immediately (< 5ms)
4. **Cache MISS** → Query PostgreSQL primary database
5. Populate Redis cache with TTL (5 minutes for content lists)
6. Return response to client
### 3.1.2 Write Path (Cache Invalidation)
1. Client sends `POST /api/votes` with vote payload
2. NestJS validates JWT, checks RBAC permissions
3. Business logic checks for double-vote conflict
4. **Write to PostgreSQL** (primary writer instance)
5. **Invalidate** relevant Redis cache keys
6. **Emit** `voteUpdated` event via Redis Pub/Sub → WebSocket Gateway
7. All connected clients receive real-time update
## 3.2 External Integration Resilience
| Service | Pattern | Failure Handling |
|---------|---------|-----------------|
| **S3 Storage** | Pre-signed URL generation | Retry with exponential backoff (1s, 2s, 4s) |
| **Email Service** | Async via SQS queue | Circuit breaker trips after 5 failures; dead-letter queue |
| **Auth Provider** | Token verification | Cached JWKS keys for 1 hour; magic-link fallback |
## 3.3 Error Propagation Strategy
All unhandled exceptions are caught by the **Global Exception Filter**:
```
Exception Thrown → ExceptionFilter → Log (correlation_id + stack trace)
→ Transform → Standardized JSON Error Envelope
→ Return → Localized, secure HTTP response
```
> **Key Guarantee**: No raw stack traces, internal paths, or database schemas are ever exposed to the client.
RBAC & Authentication Strategies
Implementation plans for stateless JWT sessions, token rotation, and Role-Based Access Control matrices.
Category: security
Tags: JWT, Roles, Permissions
Detailed Architecture Specification:
# 8. AUTHENTICATION & AUTHORIZATION
## 8.1 JWT Authentication Flow
Authentication uses a **stateless JWT architecture** optimized for Serverless:
1. User submits credentials → `POST /api/auth/login`
2. Backend validates credentials and issues two tokens:
- **Access Token** (JWT, 15-min expiry) — contains `user_id`, `role`, and `jti` claims.
- **Refresh Token** (Opaque, 7-day expiry) — stored in DB, sent as `HttpOnly` cookie.
3. Client stores Access Token in Expo SecureStore; attaches as `Authorization: Bearer <token>`.
4. On expiry, client sends Refresh Token to `/api/auth/refresh` for silent rotation.
## 8.2 RBAC Permission Matrix
| Permission | RESIDENT | CONTENT_ADMIN | SUPER_ADMIN |
|------------|:--------:|:-------------:|:-----------:|
| View published content | ✅ | ✅ | ✅ |
| Cast votes | ✅ | ✅ | ✅ |
| Update own profile | ✅ | ✅ | ✅ |
| Create / edit content | ❌ | ✅ | ✅ |
| Upload media (S3) | ❌ | ✅ | ✅ |
| View all users | ❌ | ❌ | ✅ |
| Manage roles | ❌ | ❌ | ✅ |
| View analytics dashboard | ❌ | ❌ | ✅ |
| Trigger GDPR data export | ✅ | ✅ | ✅ |
## 8.3 Security Edge Cases
| Scenario | Handling |
|----------|----------|
| Compromised JWT | Silent refresh triggers; if refresh token also expired, redirect to login. |
| Brute-force login | Account locked after 5 consecutive failures + alert email dispatched. |
| Concurrent multi-device login | Monitored; session invalidated if security threshold breached. |
| Auth provider outage | Graceful degradation with clear error message to user. |
Async Background Jobs
Detailed specifications for queue workers, DLQ policies, idempotency, and job retries.
Category: architecture
Tags: Queues, Workers, Async
Detailed Architecture Specification:
# 2.3 REAL-TIME WEBSOCKETS & ASYNC
## 2.3.1 Live Voting Updates (WebSocket Gateway)
When a resident casts a vote, the results are **instantly broadcast** to all connected clients viewing that specific poll.
**Data Flow**:
1. Resident taps "Vote" → HTTP POST to record the vote.
2. Upon successful DB insertion, NestJS emits an event to the **WebSocket Gateway**.
3. The Gateway broadcasts a lightweight JSON payload to all clients subscribed to that poll's room.
4. Expo app updates Material Design progress bars in real-time — no page refresh required.
## 2.3.2 Acceptance Criteria
- Vote updates broadcast to all subscribed clients within **200ms** of the DB transaction completing.
- WebSocket connection auto-reconnects with **exponential backoff** (1s, 2s, 4s, 8s) on network drop.
- All WebSocket payloads are strictly typed and validated against injection attacks.
- System supports **≥ 1,000 concurrent** WebSocket connections per Serverless instance.
## 2.3.3 Edge Cases
| Scenario | Handling Strategy |
|----------|-------------------|
| Temporary network disconnection | Client fetches latest state via HTTP on reconnect before resuming WS listening |
| Race condition (WS update arrives before own HTTP response) | Client deduplicates by `vote_id`; HTTP response is source of truth |
| Zombie connections (no close frame) | Ping/pong heartbeat every 30s; clean up resources after 3 missed pongs |
| Multi-instance broadcasting | Redis Pub/Sub adapter ensures all clients receive updates regardless of instance |
## 2.3.4 Internationalization (i18n) & Accessibility
Given the target regions (North America, Europe, Australasia), the application implements:
- **i18n**: All user-facing strings extracted to locale JSON files (`en`, `fr`, `es`, `de`).
- **WCAG 2.1 AA**: Minimum contrast ratios, screen reader labels on all interactive elements, keyboard navigation support.
Deep Cloud Infrastructure
Low-latency serverless endpoint topology and VPC network mappings.
Category: architecture
Tags: Cloud, Network
Detailed Architecture Specification:
# 5. DEEP CLOUD INFRASTRUCTURE
## 5.1 Cloud Deployment Architecture
The cloud architecture is designed for **high availability** and **zero-maintenance scaling**. The NestJS application is deployed as Serverless functions behind an API Gateway, which handles SSL termination and routes HTTP traffic.
### 5.1.1 Network Topology
| Component | Service | Configuration |
|-----------|---------|---------------|
| **Edge Protection** | Web Application Firewall (WAF) | DDoS mitigation, OWASP rule sets |
| **Traffic Routing** | API Gateway | SSL termination, path-based routing, throttling |
| **Compute** | Serverless Functions (Lambda) | Auto-scaling, 256 MB memory, 30s timeout |
| **WebSocket** | WebSocket Gateway | Sticky sessions via Redis adapter |
| **Connection Pooling** | PgBouncer | Multiplexes 1,000+ connections → 50 DB connections |
| **Primary Database** | PostgreSQL (Multi-AZ) | Automatic failover, point-in-time recovery |
| **Read Replicas** | PostgreSQL Replica | Horizontal read scaling for GET endpoints |
| **Cache** | Redis Cluster (Private Subnet) | Microsecond latency, LRU eviction, Pub/Sub |
| **Object Storage** | S3 + CloudFront CDN | Global edge caching for media assets |
### 5.1.2 Scaling Strategy
1. **Compute Layer** — Horizontal auto-scaling based on request volume. Provisioned concurrency keeps baseline instances warm during voting events.
2. **Database Layer** — Vertical scaling for the primary writer; horizontal scaling via read replicas. Auto-scaling triggers at **75% CPU** for 5 minutes.
3. **Queue-Based Load Leveling** — Non-critical tasks (batch emails, data deletion) are placed in SQS for asynchronous processing.
### 5.1.3 Environment Isolation
| Environment | Infrastructure | Purpose |
|-------------|---------------|---------|
| **Development** | Docker Compose (local) | Rapid iteration with hot-reload |
| **Staging** | Separate VPC / Cloud Account | Pre-production validation |
| **Production** | Isolated VPC with private subnets | Live traffic, strict IAM policies |
## 5.2 Disaster Recovery & Backup
- **RPO (Recovery Point Objective)**: < 1 hour via continuous WAL archiving
- **RTO (Recovery Time Objective)**: < 15 minutes via Multi-AZ failover
- **Backup Schedule**: Automated daily snapshots retained for 30 days
- **Cross-Region Replication**: Asynchronous replication to secondary region for catastrophic failure
Core API Endpoints
Tabular route definitions mapping out HTTP methods, rate limits, and authentication requirements.
Category: integration
Tags: Routes, Controllers, REST
Detailed Architecture Specification:
# 8. API SPECIFICATION (Key Interfaces)
| Method | Endpoint | Auth | Description |
|--------|----------|------|-------------|
| POST | `/auth/login` | None | Returns JWT Access + Refresh Token |
| GET | `/listings` | Public | Search listings with filters (Elasticsearch) |
| POST | `/listings` | Seller | Create a new listing |
| POST | `/listings/:id/bid` | User | Place a bid (Atomic transaction) |
| GET | `/feed` | User | Get personalized activity feed |
| POST | `/checkout/session` | User | Create Stripe Checkout Session |
Exception Handling States
Fallback mappings for unstable network condition recovery across edge nodes.
Category: integration
Tags: Handlers, Resilience
Detailed Architecture Specification:
# 6.4 EXCEPTION HANDLING STATES
## 6.4.1 API Exception Handling Architecture
The API layer employs a **NestJS Global Exception Filter** that catches all unhandled exceptions, ensuring no raw stack traces leak to the client.
### Request → Response Pipeline
```json
{
"error": {
"code": "CONFLICT_DOUBLE_VOTE",
"message": "User has already voted for this item.",
"details": [],
"correlation_id": "req-x9k2m4n7-8901",
"timestamp": "2023-10-27T10:05:00Z"
}
}
```
## 6.4.2 Error Code Catalog
| Code | HTTP Status | Description | Recovery Action |
|------|-------------|-------------|-----------------|
| `VALIDATION_FAILED` | 400 | Payload fails Zod schema validation | Fix request payload |
| `UNAUTHORIZED` | 401 | Missing, invalid, or expired JWT | Re-authenticate or refresh token |
| `FORBIDDEN_ROLE` | 403 | User lacks required RBAC permissions | Request role elevation |
| `NOT_FOUND` | 404 | Requested resource does not exist | Verify resource ID |
| `CONFLICT_DOUBLE_VOTE` | 409 | User attempted to vote twice | Display "already voted" state |
| `RATE_LIMIT_EXCEEDED` | 429 | Client sent too many requests | Retry with exponential backoff |
| `FILE_TOO_LARGE` | 413 | Uploaded media exceeds 5 MB limit | Compress file before upload |
| `LEGAL_CONSENT_REQUIRED` | 451 | User must accept new terms | Show consent blocking modal |
| `INTERNAL_SERVER_ERROR` | 500 | Unhandled backend exception | Automatic alert to on-call team |
| `SERVICE_UNAVAILABLE` | 503 | System is in maintenance mode | Retry after maintenance window |
| `GATEWAY_TIMEOUT` | 504 | External dependency timed out | Circuit breaker activates |
| `ACCOUNT_LOCKED` | 403 | Account suspended (failed logins) | Contact support for unlock |
## 6.4.3 Circuit Breaker Pattern
External integrations (email, S3, auth provider) implement a three-state circuit breaker:
1. **Closed** (Normal) — Requests flow through. Failure count is tracked.
2. **Open** (Tripped) — After 5 consecutive failures, all requests immediately fail-fast with a cached fallback.
3. **Half-Open** (Probing) — After a 30-second cooldown, one probe request is sent. If it succeeds, the circuit resets to Closed.
## 6.4.4 WebSocket Reconnection Strategy
| Attempt | Delay | Action |
|---------|-------|--------|
| 1 | 1 second | Auto-reconnect |
| 2 | 2 seconds | Auto-reconnect |
| 3 | 4 seconds | Auto-reconnect |
| 4 | 8 seconds | Auto-reconnect + show banner |
| 5+ | 16 seconds | Manual reconnect prompt |
Detailed Implementation Plan
Step-by-step phased execution map focusing on rapid prototyping techniques.
Category: planning
Tags: Implementation, Execution
Detailed Architecture Specification:
# 10. DETAILED IMPLEMENTATION PLAN
## 10.1 Phase 1 — Project Setup & Configuration
1. Initialize the monorepo: `mkdir community-voting-app && cd community-voting-app`
2. Initialize Expo frontend: `npx create-expo-app mobile-client -t expo-template-blank-typescript`
3. Initialize NestJS backend: `npx @nestjs/cli new backend-api --strict --package-manager npm`
4. Create shared types directory: `mkdir -p shared/types shared/schemas`
5. Install **Zod** in the shared directory for cross-stack validation
6. Configure `docker-compose.yml` for local PostgreSQL + Redis
7. Set up root `.env.example` with all required configuration variables
8. Configure **ESLint** and **Prettier** across both projects
## 10.2 Phase 2 — Database & ORM Setup
1. Install ORM and database drivers in `backend-api`
2. Define `User` and `AuditLog` schema models
3. Define `ContentCategory`, `ContentItem`, and `Vote` models
4. Define `LegalDocument` and `UserConsent` models
5. Generate initial migration: `npm run migration:generate -- --name InitialSchema`
6. Create development seed script with dummy data
7. Run migration and seed scripts to verify database integrity
## 10.3 Phase 3 — Core Backend & Authentication
1. Implement `AuthModule` with JWT strategy and payload interfaces
2. Write `RolesGuard` to enforce RBAC based on JWT payload
3. Implement `POST /api/auth/register` with password hashing + Zod validation
4. Implement `POST /api/auth/login` to issue Access and Refresh tokens
5. Create global **Exception Filter** for standardized JSON error envelopes
6. Implement structured logging middleware with correlation IDs and PII scrubbing
## 10.4 Phase 4 — API Routes & Business Logic
1. Implement `ContentModule` CRUD endpoints (GET, POST, PATCH, DELETE)
2. Integrate **Redis caching** into GET endpoints using cache-aside pattern
3. Implement S3 **pre-signed URL** generation in a dedicated `UploadModule`
4. Implement `VotingModule` with double-vote prevention logic
5. Set up NestJS **WebSocket Gateway** with `subscribeToPoll` and `voteUpdated` events
6. Implement `LegalModule` for fetching policies and recording consent
7. Implement GDPR data deletion background job via `DELETE /api/users/me`
Event-Driven Architectures
Event bridge mappings for async messaging between distributed microservices.
Category: architecture
Tags: Events, Kafka, SQS
Detailed Architecture Specification:
# 2. EVENT-DRIVEN ARCHITECTURES
## 2.1 Real-Time WebSocket Specification
### 2.1.1 Connection Lifecycle
Clients connect to `wss://api.acme.dev/ws` passing their JWT in the connection payload. The server validates the token and accepts the connection.
### 2.1.2 Event Catalog
| Event | Direction | Payload | Description |
|-------|-----------|---------|-------------|
| `subscribeToPoll` | Client → Server | `{ "content_item_id": "uuid" }` | Joins a Redis Pub/Sub room for live updates |
| `voteUpdated` | Server → Client | `{ "content_item_id": "uuid", "new_total": 43 }` | Broadcasted when a new vote is recorded |
| `pollClosed` | Server → Client | `{ "content_item_id": "uuid", "final_total": 128 }` | Sent when an admin closes a voting session |
| `maintenanceMode` | Server → Client | `{ "message": "System maintenance in 5 minutes" }` | Pre-scheduled maintenance warning |
### 2.1.3 Redis Pub/Sub Architecture
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Lambda #1 │ │ Lambda #2 │ │ Lambda #3 │
│ (WebSocket) │ │ (WebSocket) │ │ (WebSocket) │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
└──────────┬───────┴──────────┬───────┘
│ Redis Pub/Sub │
│ (Adapter) │
└──────────────────┘
```
## 2.2 Internationalization (i18n) & Accessibility
### 2.2.1 Supported Locales
| Language | Code | Status |
|----------|------|--------|
| English | `en` | ✅ Default |
| French | `fr` | ✅ Supported |
| Spanish | `es` | ✅ Supported |
| German | `de` | 🔜 Planned |
### 2.2.2 WCAG 2.1 AA Compliance
- **Color Contrast**: Minimum **4.5:1** ratio for all text elements
- **Screen Readers**: Full `accessibilityLabel` coverage (VoiceOver + TalkBack)
- **Keyboard Navigation**: Logical tab order, focus trapping in modals
- **Dynamic Text**: Support for user-configured font scaling
- **Live Regions**: `accessibilityLiveRegion="polite"` for real-time vote updates
Role-Based Access Matrices
Granular permissions mappings for multi-tenant enterprise applications.
Category: security
Tags: RBAC, Tenancy
Detailed Architecture Specification:
# 10. ENFORCED CODING CONSTRAINTS
## 10.1 Framework Version Enforcement
| Banned Pattern | Required Alternative | Rationale |
|----------------|---------------------|-----------|
| **React class components** | Functional components + hooks | Modern API surface, better tree-shaking |
| `componentWillMount`, `componentWillUpdate` | `useEffect` | Deprecated lifecycle methods |
| `getInitialState` | `useState` or `useReducer` | Legacy API |
| `createClass` syntax | Arrow function components | Deprecated factory pattern |
| `PropTypes` runtime validation | TypeScript interfaces | Compile-time > runtime checking |
| `defaultProps` static | ES6 default parameters | Cleaner, co-located defaults |
## 10.2 TypeScript Enforcement
| Banned Pattern | Required Alternative | Rationale |
|----------------|---------------------|-----------|
| `any` type annotations | `unknown` + type guards | Type safety preservation |
| `@ts-ignore` comments | Fix the actual type error | No suppression of real errors |
| Non-null assertions (`!`) | Optional chaining (`?.`) | Safer null handling |
| `enum` keyword | `as const` union types | Better tree-shaking, no runtime overhead |
| `namespace` declarations | ES modules | Modern module system |
## 10.3 Security Constraints
| Banned Pattern | Required Alternative | Rationale |
|----------------|---------------------|-----------|
| `eval()`, `Function()` constructors | Static code paths | Code injection prevention |
| `innerHTML` assignments | `textContent` or sanitise | XSS prevention |
| Hardcoded secrets / API keys | Environment variables + Secret Manager | Credential exposure prevention |
| `http://` URLs in production | Enforce `https://` | Transport security |
| `*` CORS origins in production | Whitelist domains | Cross-origin attack prevention |
| SQL string concatenation | Parameterised queries | SQL injection prevention |
| `localStorage` for auth tokens | httpOnly cookies | Token theft prevention |
## 10.4 State Management
| Banned Pattern | Required Alternative | Rationale |
|----------------|---------------------|-----------|
| Prop drilling beyond 2 levels | Context or Zustand | Maintainability |
| `useEffect` for data fetching | React Query / SWR | Proper cache + retry semantics |
| Mutable state mutations | Immutable update patterns | Predictable state transitions |
| Global mutable variables | React state or stores | Reactivity + debugging |
## 10.5 API & Data Patterns
| Banned Pattern | Required Alternative | Rationale |
|----------------|---------------------|-----------|
| `fetch` without error handling | Wrap in try/catch | Error resilience |
| Untyped API responses | Define response interfaces | End-to-end type safety |
| `console.log` in production | Structured logger | Observability |
| Synchronous file I/O | async/await patterns | Non-blocking I/O |
| Unbounded `.find()` / `.filter()` | Map/Set lookups | O(1) vs O(n) performance |
## 10.6 CSS & Styling
| Banned Pattern | Required Alternative | Rationale |
|----------------|---------------------|-----------|
| Inline styles for layout | CSS modules or Tailwind | Separation of concerns |
| `!important` overrides | Fix specificity properly | Maintainable cascade |
| Fixed pixel breakpoints | Relative units (rem/em) | Responsive scaling |
| `z-index` values > 100 | z-index scale system | Predictable stacking |
Compliance & Audit Logs
Automated audit trailing definitions mapped to SOC2 regulatory policies.
Category: security
Tags: Audit, SOC2
Detailed Architecture Specification:
# 7. COMPLIANCE & AUDIT LOGS
## 7.1 Analytics & System Health Monitoring
To ensure the application meets its performance targets and provides actionable insights, a comprehensive **Analytics and System Health** module is integrated.
### 7.1.1 Monitoring Architecture
| Metric Category | Data Points | Collection Method |
|----------------|-------------|-------------------|
| **Technical** | API request rates, p95/p99 latency, error rates by HTTP status | NestJS interceptors + structured JSON logging |
| **Business** | Active voting sessions, votes cast/hour, user registrations | Custom analytics endpoints |
| **Infrastructure** | DB connection pool, Redis memory, Lambda cold starts | CloudWatch metrics + custom dashboards |
### 7.1.2 Health Check Endpoint
The backend exposes a comprehensive `/health` endpoint:
```json
{
"status": "healthy",
"checks": {
"database": { "status": "up", "latency_ms": 3 },
"redis": { "status": "up", "latency_ms": 1 },
"s3": { "status": "up", "latency_ms": 12 }
},
"uptime_seconds": 86400,
"version": "1.4.2"
}
```
## 7.2 Audit Log Schema
All security-relevant events are captured in an immutable `AuditLog` table:
| Field | Type | Description |
|-------|------|-------------|
| `id` | UUID (PK) | Unique event identifier |
| `user_id` | UUID (FK → User) | Acting user (`null` for system events) |
| `action` | VARCHAR | Event type (e.g., `USER_LOGIN`, `CONTENT_DELETED`) |
| `entity_type` | VARCHAR | Target entity (e.g., `ContentItem`, `Vote`) |
| `entity_id` | UUID | Target entity identifier |
| `metadata` | JSONB | Flexible payload (IP address, user agent, diff) |
| `created_at` | TIMESTAMP | Immutable event timestamp |
## 7.3 Acceptance Criteria
1. The system must track unique user counts, active sessions, and page views with **< 5 minute** data latency.
2. All API errors (4xx and 5xx) must be logged with a unique **correlation ID**, request path, and user ID.
3. Administrators must be able to toggle **Maintenance Mode**, returning `503 Service Unavailable` for non-admin requests.
4. Telemetry collection must strictly respect user **GDPR consent** choices.
C4 Modular Framework
A different layout of the standard C4 model emphasizing specific boundary limits.
Category: architecture
Tags: C4 Module, System
Detailed Architecture Specification:
## 5.1 System Architecture(C4 Level 2)
```mermaid
graph TD
User((User)) -->|HTTPS| CDN[Cloudflare CDN]
CDN -->|Load Balance| Gateway[API Gateway / BFF<br/>NestJS]
subgraph "Service Mesh"
Gateway -->|gRPC| Auth[Identity Service]
Gateway -->|gRPC| Market[Marketplace Service]
Gateway -->|gRPC| Social[Social Service]
Gateway -->|gRPC| Pay[Payment Service]
Gateway -->|gRPC| Search[Search Service]
end
subgraph "Data Layer"
Auth --> DB_Auth[(Postgres: Users)]
Market --> DB_Market[(Postgres: Listings)]
Social --> DB_Social[(Postgres: Graph)]
Social --> Redis_Feed[(Redis: Feeds)]
Pay --> DB_Pay[(Postgres: Ledger)]
Search --> Elastic[(Elasticsearch)]
end
subgraph "Async / Background"
Market -->|Event| RabbitMQ
RabbitMQ -->|Consume| Search
RabbitMQ -->|Consume| NotificationService
end
```
Performance Budgets
Core web vital constraints and monitoring logic designed to keep loading times under 1s.
Category: planning
Tags: Performace, Metrics
Detailed Architecture Specification:
# 11. PERFORMANCE BUDGETS
## 11.1 Load Testing Benchmarks
| Scenario | Concurrent Users | Expected RPS | Response Time Budget | Success Criteria |
|----------|:----------------:|:------------:|:--------------------:|:----------------:|
| **Baseline Traffic** | 50 | 10 | p95 < 150ms | 0% Error Rate |
| **Peak Voting Event** | 500 | 150 | p95 < 300ms | < 0.1% Error Rate |
| **Stress Test** | 1,500 | 450 | p95 < 800ms | Graceful degradation, no DB crash |
| **Soak Test** | 200 (12 hours) | 40 | p95 < 200ms | No memory leaks in Lambda/Redis |
## 11.2 WCAG 2.1 AA Compliance Targets
The application targets strict compliance with **WCAG 2.1 Level AA** standards.
### 11.2.1 Accessibility Success Criteria
| Criterion | Standard | Implementation |
|-----------|----------|----------------|
| **1.4.3** Color Contrast | Minimum 4.5:1 ratio | Material Design theme validation |
| **2.1.1** Keyboard Access | All functions via keyboard | Logical tab order, focus management |
| **2.4.7** Focus Visible | Clear focus indicators | Custom focus ring styles (3px solid) |
| **4.1.2** Name, Role, Value | Programmatic labels | `accessibilityRole` + `accessibilityLabel` on all elements |
### 11.2.2 ARIA Implementation Patterns
| Component | Prop | Example |
|-----------|------|---------|
| Buttons | `accessibilityRole="button"` | Vote, Submit, Navigate |
| Toggle (Dark Mode) | `accessibilityState={{ checked: true }}` | Theme switcher |
| Live Vote Count | `accessibilityLiveRegion="polite"` | Real-time WebSocket updates |
| Decorative Images | `importantForAccessibility="no"` | Background patterns, icons |
## 11.3 Core Web Vitals
| Metric | Target | Monitoring |
|--------|--------|------------|
| **LCP** (Largest Contentful Paint) | < 2.5s | Lighthouse CI in pipeline |
| **FID** (First Input Delay) | < 100ms | Real User Monitoring (RUM) |
| **CLS** (Cumulative Layout Shift) | < 0.1 | Layout shift detection in E2E tests |
| **TTFB** (Time to First Byte) | < 200ms | API Gateway latency monitoring |
Authentication Fallbacks
Contingency plans for identity provider outages bridging to magic-link logins.
Category: security
Tags: Auth, Identity
Detailed Architecture Specification:
# 8.3 AUTHENTICATION FALLBACKS
## 8.3.1 Token Lifecycle Management
Authentication uses a **dual-token** strategy optimized for Serverless:
| Token | Type | Expiry | Storage | Purpose |
|-------|------|--------|---------|---------|
| **Access Token** | JWT | 15 minutes | Expo SecureStore | API authorization via `Bearer` header |
| **Refresh Token** | Opaque | 7 days | `HttpOnly` cookie | Silent token rotation |
### Token Refresh Flow
1. Client detects **401 Unauthorized** from API response
2. Axios interceptor automatically sends Refresh Token to `POST /api/auth/refresh`
3. Backend validates the Refresh Token against the database
4. New Access Token + rotated Refresh Token issued
5. Original failed request is automatically retried
## 8.3.2 Identity Provider Outage Contingency
If the primary authentication provider experiences an outage:
| Fallback Level | Trigger | Action |
|---------------|---------|--------|
| **Level 1** — Cache | Auth provider latency > 2s | Serve cached JWT verification keys for up to 1 hour |
| **Level 2** — Magic Link | Auth provider unreachable for > 5 min | Email-based one-time login link (bypasses provider) |
| **Level 3** — Read-Only | Extended outage > 30 min | Disable write operations; allow cached content browsing |
| **Level 4** — Maintenance | Provider confirms major incident | Activate maintenance mode with `503` responses |
## 8.3.3 Account Security Policies
| Policy | Value | Enforcement |
|--------|-------|-------------|
| **Failed Login Lockout** | 5 attempts → 15-minute lock | Server-side rate limiter + `ACCOUNT_LOCKED` response |
| **Password Complexity** | Min 8 chars, 1 uppercase, 1 number, 1 special | Zod schema validation on client + server |
| **Session Invalidation** | Password change revokes all sessions | Database sweep of all active Refresh Tokens |
| **Suspicious Activity** | Login from new device/region | Email notification + optional MFA challenge |
Deployment Workflows
Github Actions and Gitlab CI/CD workflow mappings for streamlined rollouts.
Category: planning
Tags: CI/CD, Git
Detailed Architecture Specification:
# 10. DEPLOYMENT WORKFLOWS
## 10.1 Docker Containerization
The NestJS application uses a **multi-stage Docker build** for optimized, secure images:
```dockerfile
# Stage 1: Build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: Production
FROM node:18-alpine AS production
WORKDIR /app
RUN addgroup -S nestgroup && adduser -S nestuser -G nestgroup
USER nestuser
COPY package*.json ./
RUN npm ci --only=production
COPY --from=builder /app/dist ./dist
EXPOSE 3000
CMD ["node", "dist/main"]
```
## 10.2 CI/CD Pipeline (GitHub Actions)
| Stage | Trigger | Actions | Pass Criteria |
|-------|---------|---------|--------------|
| **Lint** | Push to any branch | ESLint + Prettier check | Zero warnings |
| **Typecheck** | Push to any branch | `tsc --noEmit` | Zero type errors |
| **Unit Tests** | Push to any branch | Jest with coverage | ≥ 80% coverage |
| **Integration Tests** | PR to `main` | Supertest + test DB container | All endpoints pass |
| **E2E Tests** | PR to `main` | Detox (iOS + Android simulators) | Critical flows pass |
| **Build** | Merge to `main` | Docker build + push to ECR | Image builds successfully |
| **Deploy (Staging)** | Merge to `main` | Serverless Framework deploy | Health check passes |
| **Deploy (Production)** | Manual approval | Blue-green deployment | Canary metrics pass |
## 10.3 Load Testing with k6
```javascript
export const options = {
stages: [
{ duration: '1m', target: 500 }, // Ramp up
{ duration: '3m', target: 500 }, // Hold peak
{ duration: '30s', target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ['p(95) < 200'],
http_req_failed: ['rate == 0.00'],
},
};
```
## 10.4 Deployment Checklist
1. ✅ All tests pass in CI pipeline
2. ✅ Database migrations reviewed and approved
3. ✅ Environment variables verified in staging
4. ✅ Canary deployment to 5% traffic
5. ✅ Monitor error rates for 15 minutes
6. ✅ Promote to 100% traffic
Advanced Payload Mitigation
In-depth review of specific endpoints subjected to injection attacks.
Category: security
Tags: Injection, Defense
Detailed Architecture Specification:
# 7.4 ADVANCED PAYLOAD MITIGATION
## 7.4.1 OWASP Top 10 Threat Model (Continued)
| Threat | Risk Level | Mitigation Strategy |
|--------|:----------:|---------------------|
| **Security Misconfiguration** | Medium | IaC-provisioned environments with least-privilege IAM roles; HSTS + CSP headers enforced via NestJS middleware |
| **Vulnerable Components** | Medium | CI/CD pipeline includes `npm audit` / Snyk scanning; builds fail on high-severity CVEs |
| **Auth Failures** | High | Robust JWT validation, `HttpOnly` cookies for refresh tokens, rate limiting on login, account lockout policies |
| **Software Integrity Failures** | Medium | Signed commits required; external packages fetched with integrity checksums; OTA Expo updates cryptographically signed |
| **Security Logging Failures** | Medium | All auth events + access denials logged to `AuditLog` table + external SIEM; automatic alerts on anomalous error spikes |
| **Server-Side Request Forgery** | Low | Backend never fetches arbitrary user-provided URLs; S3 pre-signed URLs strictly control target bucket and object key |
## 7.4.2 GDPR & UK GDPR Compliance
The application satisfies the following GDPR articles:
| Article | Requirement | Implementation |
|---------|-------------|----------------|
| **Article 7** | Conditions for Consent | Legal & Compliance module; explicit, unbundled consent tracked in `UserConsent` table |
| **Articles 15–22** | Data Subject Rights | Automated endpoints for data export (JSON) and "Right to be Forgotten" |
| **Article 17** | Right to Erasure | Background job scrubs PII (name, email, IP) within 30 days; anonymized voting records preserved |
| **Article 25** | Data Protection by Design | Encryption at rest (AES-256) + in transit (TLS 1.3); field-level encryption for sensitive columns |
## 7.4.3 PIPEDA (Canada) Compliance
| Principle | Requirement | Implementation |
|-----------|-------------|----------------|
| **Principle 3** | Meaningful Consent | Clear, plain-language Privacy Policies before account creation |
| **Principle 7** | Security Safeguards | TLS 1.3 in transit, AES-256 at rest, comprehensive audit logging |
| **Principle 9** | Individual Access | Self-service data export endpoint (`GET /api/users/me/export`) |
Aggressive MVP Timelines
A fast-tracked launch sequence roadmap designed for 30-day go-to-markets.
Category: planning
Tags: Fast-track, GTM
Detailed Architecture Specification:
# 12. AGGRESSIVE MVP TIMELINES
## 12.1 Phase 5 — Frontend Layout & State
1. Install **React Navigation** and configure root stack + bottom tab navigators
2. Install and configure **Material Design** components (`react-native-paper`) + Dark Mode theme
3. Implement global auth state manager (**Zustand**) to store JWT and user profile
4. Create Axios API client with request interceptors for automatic `Bearer` token attachment
5. Implement response interceptor for `401` handling and automatic token refresh
## 12.2 Phase 6 — Frontend Features & UI
1. Build **Login** and **Registration** screens with React Hook Form + Zod validation
2. Build main **Voting Dashboard** — fetch active content lists, render Material Design cards
3. Implement **WebSocket client hook** for real-time vote updates with local state mutation
4. Build **Content Admin** screens for creating activities + S3 pre-signed URL image uploads
5. Build **Legal Consent** blocking modal — forces acceptance of updated policies before dashboard access
6. Audit all UI components for **WCAG 2.1** compliance (`accessibilityLabel`, `accessibilityRole`)
## 12.3 Phase 7 — Testing & CI/CD
| Task | Tool | Target |
|------|------|--------|
| Unit Tests — VotingService, AuthService | Jest (mocking DB + Redis) | ≥ 80% coverage |
| Integration Tests — CRUD endpoints | Supertest + test DB container | All endpoints pass |
| E2E Tests — Login + Voting flow | Detox (iOS + Android) | Critical flows pass |
| CI Pipeline | GitHub Actions YAML | Lint → Typecheck → Test → Build |
| Deployment Config | Serverless Framework (`serverless.yml`) | Functions + API Gateway + env vars |
| Final Validation | Local build + test run | Clean commit to repository |
## 12.4 Timeline Summary
| Phase | Duration | Deliverables |
|-------|----------|-------------|
| Phase 1–2 | Week 1 | Project scaffold, DB schema, migrations, seed data |
| Phase 3–4 | Week 2–3 | Auth, CRUD, voting, WebSockets, legal module |
| Phase 5–6 | Week 3–4 | Mobile UI, navigation, real-time features, accessibility |
| Phase 7 | Week 4 | Testing suite, CI/CD pipeline, staging deployment |
Automated Disaster Recovery
Runbook outlines detailing cross-region replication failovers visually.
Category: security
Tags: DR, Failover
Detailed Architecture Specification:
# 9. AUTOMATED DISASTER RECOVERY
## 9.1 Load Testing & Capacity Planning
The project uses **k6** to simulate concurrent user traffic and validate infrastructure resilience.
### 9.1.1 Test Profile
| Phase | Duration | Virtual Users | Purpose |
|-------|----------|:-------------:|---------|
| **Ramp Up** | 1 minute | 0 → 500 | Simulate gradual traffic increase |
| **Sustained Peak** | 3 minutes | 500 | Validate steady-state performance |
| **Ramp Down** | 30 seconds | 500 → 0 | Verify graceful connection teardown |
### 9.1.2 Success Thresholds
- **p95 response time** must remain under **200ms**
- **HTTP error rate** must be exactly **0.00%**
- If error rate spikes → indicates DB connection exhaustion or Lambda concurrency limits
## 9.2 Infrastructure & Deployment
### 9.2.1 Docker Multi-Stage Build
| Stage | Base Image | Contents | Optimizations |
|-------|-----------|----------|---------------|
| **Builder** | `node:18-alpine` | Source + devDependencies + compiled JS | Full `npm ci` + TypeScript compilation |
| **Production** | `node:18-alpine` | Compiled JS + production deps only | Non-root user, minimal attack surface |
### 9.2.2 Disaster Recovery Matrix
| Scenario | Detection | RTO | RPO | Recovery Procedure |
|----------|-----------|:---:|:---:|-------------------|
| **Single Instance Failure** | Health check (30s) | < 1 min | 0 | Auto-replacement via ASG |
| **Database Failover** | Multi-AZ heartbeat | < 5 min | < 1 min | Automatic DNS switchover |
| **Region Outage** | Route 53 health check | < 15 min | < 1 hour | Cross-region replica promotion |
| **Data Corruption** | Anomaly detection alert | < 30 min | User-defined | Point-in-time restore from WAL |
| **Complete Data Loss** | Manual detection | < 2 hours | < 24 hours | Restore from S3 backup archive |
Enterprise Logistics ERD
Entity Relationship Diagram mapping the complex logistical domain including Hubs, Drivers, Orders, and Tickets.
Category: database
Tags: ERD, Logistics, Enterprise
Detailed Architecture Specification:
### **Core Reasoning:**
Mapping complex logistics requires strict relational integrity to prevent orphaned sub-tasks and phantom inventory adjustments.
### **Pain Points Addressed:**
Resolves previous issues with misaligned delivery routes and inventory synchronization delays.
```mermaid
erDiagram
USER ||--o{ ORDER : "places/manages"
USER ||--o{ TICKET : "submits"
USER }|--|| ROLE : "has"
ROLE ||--o{ PERMISSION : "grants"
HUB ||--o{ USER : "employs"
HUB ||--o{ INVENTORY : "stores"
HUB ||--o{ ORDER : "processes"
ORDER ||--o{ ORDER_ITEM : "contains"
ORDER ||--|| INVOICE : "generates"
ORDER }|--|| USER : "assigned_to_driver"
PRODUCT ||--o{ INVENTORY : "tracked_in"
PRODUCT ||--o{ ORDER_ITEM : "included_in"
TICKET ||--o{ TICKET_REPLY : "has"
```Event-Driven Platform Topology
Top-down view of the Flutter mobile client interacting with the NextJS Web App, bounded by NestJS API gateways.
Category: architecture
Tags: Microservices, Topology
Detailed Architecture Specification:
### **Core Reasoning:**
To handle 10,000+ driver telematics pings per second, we adopted a robust Edge/CDN overlay combined with WebSockets.
### **Pain Points Addressed:**
Eliminates high latency experienced during peak fulfillment hours in previous legacy monoliths.
```mermaid
graph TD
subgraph Clients
A["Flutter Mobile App (Drivers/Customers)"]
B["Next.js Web App (Hub Managers/Admins)"]
end
subgraph Edge / CDN
C["Cloudflare / AWS CloudFront"]
D["API Gateway / Load Balancer"]
end
subgraph External Services
E["Stripe (Payments)"]
F["Twilio (SMS) / SendGrid (Email)"]
G["Segment (Analytics)"]
H["Google Maps API"]
end
subgraph Core Infrastructure
I["PostgreSQL (Primary DB)"]
J["Redis (Cache / WebSockets)"]
K["Elastic Search (Search Engine)"]
L["AWS S3 (Blob Storage)"]
M["Message Broker (SQS / RabbitMQ)"]
end
A -->|HTTPS / WSS| C
B -->|HTTPS| C
C --> D
D -->|REST / GraphQL| NestJS_API["NestJS API Gateway"]
D -->|WebSockets| NestJS_WS["NestJS WebSocket Gateway"]
NestJS_API --> I
NestJS_API --> J
NestJS_API --> K
NestJS_API --> M
NestJS_WS --> J
M --> NestJS_Workers["NestJS Background Workers"]
NestJS_Workers --> I
NestJS_Workers --> E
NestJS_Workers --> F
NestJS_API --> G
A --> H
B --> H
A -->|Direct Upload via Pre-signed URL| L
B -->|Direct Upload via Pre-signed URL| L
```Technology Stack & Rationale
Detailed analysis of selected enterprise technologies, explaining the necessity of NestJS, Flutter, and PostgreSQL.
Category: planning
Tags: Stack, Tech Selection
Detailed Architecture Specification:
### **Core Reasoning:**
Selected technologies favor strong static typing and standardized DI constraints (TypeScript/NestJS) over rapid-but-fragile dynamic stacks.
### **Pain Points Addressed:**
Prevents "type-drift" across the massive 20+ microservice monorepo structure.
| Layer | Technology | Version | Rationale |
| :--- | :--- | :--- | :--- |
| **Language** | TypeScript | Latest | Provides strict static typing, advanced generic capabilities, and seamless integration across both the Next.js frontend and NestJS backend ecosystems, drastically reducing runtime errors. |
| **Language** | Dart | Latest | The required language for Flutter, offering Ahead-of-Time (AOT) compilation for native mobile performance and Just-in-Time (JIT) compilation for rapid development cycles. |
| **Web Framework** | Next.js | Latest | Delivers optimal SPA performance with built-in routing, API routes for edge functions, and extensive React ecosystem compatibility. |
| **Mobile Framework** | Flutter | Latest | Ensures pixel-perfect UI rendering and high-performance execution for complex, map-heavy mobile interfaces across iOS and Android. |
| **Backend Framework** | NestJS | Latest | Enforces a highly structured, modular, and testable architecture utilizing decorators and Dependency Injection, ideal for enterprise scale. |
| **Database** | PostgreSQL | Latest | Provides robust ACID compliance, advanced indexing, and JSONB support necessary for complex logistical and financial data models. |
| **Message Queue** | AWS SQS / BullMQ | Latest | Facilitates the Event-Driven architecture by decoupling services and guaranteeing message delivery for background processing. |
Core API Specification
Detailed API route definitions mapping out HTTP methods, rate limits, and authentication requirements for the Foam Train backend.
Category: integration
Tags: Routes, REST, Endpoints
Detailed Architecture Specification:
### **Core Reasoning:**
Strict rate limiting (e.g., 5/min on login) and partial auth blocks brute-force and scraping attempts.
### **Pain Points Addressed:**
Eliminated API abuse from unauthenticated driver scrapers.
| Method | Path | Description | Auth Required | Rate Limit |
| :--- | :--- | :--- | :--- | :--- |
| POST | `/api/v1/auth/login` | Authenticate user and issue JWT | No | 5/min |
| POST | `/api/v1/auth/mfa/verify` | Verify TOTP/SMS code for MFA | Yes (Partial) | 5/min |
| GET | `/api/v1/users/me` | Retrieve current authenticated user profile | Yes | 60/min |
| POST | `/api/v1/users` | Create a new user (Admin/HR only) | Yes (Admin) | 20/min |
| GET | `/api/v1/hubs` | List all delivery hubs with pagination | Yes | 60/min |
| POST | `/api/v1/orders` | Create a new delivery order | Yes (Manager) | 30/min |
| GET | `/api/v1/orders/:id` | Retrieve specific order details | Yes | 120/min |
| PATCH | `/api/v1/orders/:id/status` | Update order status (Driver/Manager) | Yes | 60/min |
| POST | `/api/v1/inventory/adjust` | Adjust stock levels in a warehouse | Yes (Manager) | 30/min |
| GET | `/api/v1/content/posts` | Retrieve published CMS content | No | 120/min |
| POST | `/api/v1/tickets` | Submit a new support ticket | Yes | 10/min |
| POST | `/api/v1/payments/intent` | Create Stripe PaymentIntent | Yes | 20/min |
Internal Backend Microservices
Internal module architecture demonstrating event-driven communication between Auth, Logistics, and WebSocket Gateways.
Category: architecture
Tags: Backend, NestJS
Detailed Architecture Specification:
### **Core Reasoning:**
Synchronous REST calls between internal modules created tight coupling and cascading load failures.
### **Pain Points Addressed:**
Implemented an internal Event Bus to decouple services, stabilizing the system under heavy load.
```mermaid
flowchart TD
subgraph NestJS Backend Application
API_Gateway["API Gateway Module"]
Auth_Module["Auth & IAM Module"]
Logistics_Module["Logistics & Order Module"]
Finance_Module["Finance & Billing Module"]
Notification_Module["Notification Module"]
WebSocket_Gateway["WebSocket Gateway"]
API_Gateway --> Auth_Module
API_Gateway --> Logistics_Module
API_Gateway --> Finance_Module
Logistics_Module -->|Publishes Event| Event_Bus{"Event Bus (Internal)"}
Finance_Module -->|Publishes Event| Event_Bus
Auth_Module -->|Publishes Event| Event_Bus
Event_Bus -->|Consumes Event| Notification_Module
Event_Bus -->|Consumes Event| WebSocket_Gateway
Logistics_Module -.->|Reads/Writes| DB_Repo["Database Repository Layer"]
Finance_Module -.->|Reads/Writes| DB_Repo
Auth_Module -.->|Reads/Writes| DB_Repo
WebSocket_Gateway -.->|Pub/Sub| Redis_Adapter["Redis IoAdapter"]
end
```Multi-AZ AWS Cloud Infrastructure
Highly available deployment topology encompassing Route 53, ECS Fargate, ALB, and secure VPC partitioning.
Category: architecture
Tags: AWS, Cloud, Infrastructure
Detailed Architecture Specification:
### **Core Reasoning:**
Containerized compute on AWS Fargate allows serverless scaling based strictly on active metrics, reducing idle spend.
### **Pain Points Addressed:**
Provides an automated failover (RDS Multi-AZ) solving previous downtime issues during maintenance.
```mermaid
graph TD
subgraph AWS Cloud
Route53["Amazon Route 53 (DNS)"]
CloudFront["Amazon CloudFront (CDN)"]
WAF["AWS WAF (Security)"]
Route53 --> CloudFront
CloudFront --> WAF
WAF --> ALB["Application Load Balancer"]
subgraph VPC - Public Subnet
ALB
NAT["NAT Gateway"]
end
subgraph VPC - Private Subnet (App Tier)
ECS_Next["ECS Fargate: Next.js Web"]
ECS_Nest["ECS Fargate: NestJS API"]
ECS_Worker["ECS Fargate: Background Workers"]
ALB --> ECS_Next
ALB --> ECS_Nest
end
subgraph VPC - Private Subnet (Data Tier)
RDS["Amazon RDS (PostgreSQL) Primary"]
RDS_Replica["Amazon RDS Read Replica"]
Redis["Amazon ElastiCache (Redis)"]
Elastic["Amazon OpenSearch (Elastic)"]
ECS_Nest --> RDS
ECS_Nest --> RDS_Replica
ECS_Nest --> Redis
ECS_Nest --> Elastic
ECS_Worker --> RDS
end
SQS["Amazon SQS (Message Queue)"]
S3["Amazon S3 (Blob Storage)"]
ECS_Nest --> SQS
SQS --> ECS_Worker
ECS_Nest --> S3
ECS_Next --> S3
end
```OWASP Threat Model
Proactive threat modeling matrix identifying vulnerabilities and required mitigations out-of-the-box.
Category: security
Tags: Infosec, Compliance, OWASP
Detailed Architecture Specification:
### **Core Reasoning:**
To ensure enterprise readiness from day one, strict adherence to OWASP Top 10 mitigation strategies was mandated.
### **Pain Points Addressed:**
Prevents devastating security vulnerabilities like SQL injection and Broken Access Control.
| Threat | Risk Level | Mitigation Strategy |
| :--- | :--- | :--- |
| Injection (SQL/NoSQL) | Critical | TypeORM strictly utilizes parameterized queries and prepared statements for all database interactions. Raw SQL execution is globally disabled via linting rules. |
| Broken Authentication | Critical | Implemented stateless JWTs with short expiries, secure HttpOnly cookies for refresh tokens, and mandatory MFA for administrative roles. Brute-force protection via Redis rate limiting. |
| Sensitive Data Exposure | High | All data in transit is encrypted via TLS 1.3. Data at rest (PostgreSQL, S3) is encrypted using AES-256. Passwords are hashed using Argon2id with unique salts. |
| XML External Entities (XXE) | Low | The NestJS backend is configured to exclusively accept and parse `application/json`. XML parsing libraries are explicitly excluded from the dependency tree. |
| Broken Access Control | Critical | A centralized RBAC middleware (NestJS Guards) evaluates permissions on every single route. Direct object references are validated against the user's scope (e.g., Driver can only view *their* orders). |
| Security Misconfiguration | Medium | Infrastructure is provisioned via IaC (Terraform) to prevent manual drift. Docker containers run as non-root users. Security headers (HSTS, CSP) are enforced via Next.js and NestJS middleware. |
| Cross-Site Scripting (XSS) | High | Next.js natively escapes all rendered variables. The NestJS backend utilizes DOMPurify to sanitize any rich-text HTML input from the CMS before storage. |
| Insecure Deserialization | Medium | The application utilizes strict Zod schema validation for all incoming payloads. Payloads failing exact structural validation are immediately rejected before processing. |
| Using Components with Known Vulnerabilities | High | The CI/CD pipeline integrates automated dependency scanning (e.g., `npm audit`, Snyk). Builds automatically fail if vulnerabilities with a severity of High or Critical are detected. |
| Insufficient Logging & Monitoring | Medium | All critical actions (login, data mutation, permission changes) generate structured audit logs. Datadog/Prometheus triggers immediate alerts for anomalous error spikes or failed login bursts. |
Data Classification Matrix
Data mapping that classifies PII and dictates encryption, retention, and storage requirements for the database layer.
Category: security
Tags: PII, Encryption, Retention
Detailed Architecture Specification:
### **Core Reasoning:**
Automated tracking of sensitive vs public data prevents unintentional PII leaks into logs or unrestricted endpoints.
### **Pain Points Addressed:**
Ensures adherence to privacy regulations by tracking exactly where sensitive data resides and how long it is kept.
| Data Type | Classification | Storage Requirements | Retention Policy |
| :--- | :--- | :--- | :--- |
| Passwords / MFA Secrets | Restricted | Argon2id Hash / AES-256 Encrypted | Until account deletion |
| User PII (Name, Email, Phone) | Sensitive | Encrypted at rest (AES-256) | Account deletion + 30 days |
| Driver Telemetry (GPS) | Sensitive | Encrypted at rest, scrubbed after 90 days | 90 days (Aggregated thereafter) |
| Financial Invoices | Confidential | Encrypted at rest (S3), access logged | 7 years (Tax compliance) |
| System Logs (No PII) | Internal | Standard storage, read-only access | 1 year |
| Public CMS Content | Public | CDN Cached, unencrypted | Indefinite |
RBAC Permission Matrix
Granular permissions mappings for multi-tenant enterprise applications across different roles.
Category: security
Tags: RBAC, Tenancy
Detailed Architecture Specification:
### **Core Reasoning:**
Explicit declaration of permissions prevents privilege escalation vulnerabilities ensuring drivers cannot mutate administrative domains.
### **Pain Points Addressed:**
Removes ambiguity in authorization logic leading to robust, secure middleware implementation.
| Role | Resource: Orders | Resource: Users | Resource: Inventory | Resource: Finance | Resource: CMS |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **ADMIN** | Create, Read, Update, Delete | Create, Read, Update, Delete | Create, Read, Update, Delete | Read, Update | Create, Read, Update, Delete |
| **HUB_MANAGER** | Create, Read, Update | Read (Own Hub) | Read, Update (Own Hub) | None | Read |
| **DRIVER** | Read, Update (Assigned) | Read (Self) | None | None | Read |
| **CUSTOMER** | Read (Own Orders) | Read, Update (Self) | None | Read (Own Invoices)| Read |
Alerting Thresholds Table
Pre-defined warning and critical thresholds mapped to escalation actions for rapid incident response.
Category: integration
Tags: Alerts, Monitoring
Detailed Architecture Specification:
### **Core Reasoning:**
Proactive alerting catches systemic degradation before major outages occur, integrating directly into PagerDuty for on-call engineers.
### **Pain Points Addressed:**
Mysterious service degradation without actionable notifications is eliminated.
| Metric | Warning Threshold | Critical Threshold | Escalation Action |
| :--- | :--- | :--- | :--- |
| API 5xx Error Rate | > 1% over 5 mins | > 5% over 5 mins | PagerDuty to On-Call Engineer |
| API p95 Latency | > 300ms | > 800ms | Slack Alert to Backend Team |
| DB CPU Utilization | > 70% for 10 mins | > 90% for 5 mins | Auto-scale Read Replicas / PagerDuty |
| SQS Queue Depth | > 5,000 messages | > 20,000 messages | Scale Background Workers / Slack Alert |
| Redis Memory Usage | > 75% | > 90% | Evict old keys / PagerDuty |
| SSL Certificate Expiry | < 14 days | < 3 days | Jira Ticket / Slack Alert to DevOps |
Load Testing Benchmarks
Defined scenarios targeting expected concurrent users, RPS and response time budgets to validate scalability.
Category: planning
Tags: Load Testing, Performance
Detailed Architecture Specification:
### **Core Reasoning:**
Without concrete load testing benchmarks, system scalability is speculative. We enforce strict p95 latency targets.
### **Pain Points Addressed:**
Identifies memory leaks and connection starvation before deployment to production environments.
| Scenario | Target Concurrent Users | Expected RPS | Response Time Budget | Success Criteria |
| :--- | :--- | :--- | :--- | :--- |
| Baseline Traffic | 1,000 | 500 | p95 < 150ms | 0% Error Rate, CPU < 40% |
| Peak Traffic | 5,000 | 2,500 | p95 < 300ms | < 0.1% Error Rate, Auto-scaling triggers |
| Stress Test | 15,000 | 7,500 | p95 < 800ms | System degrades gracefully, no DB crashes |
| Soak Test | 2,000 | 1,000 | p95 < 200ms | Run for 24h, no memory leaks detected |
AI Developer Execution Plan
Step-by-step phased execution map specifically optimized for consumption by autonomous AI coding agents.
Category: planning
Tags: Implementation, Execution
Detailed Architecture Specification:
### **Core Reasoning:**
AI agents require deterministic, sequential instructions to avoid generating hallucinated or incomplete features.
### **Pain Points Addressed:**
Prevents an AI from writing frontend UI components before the underlying database schema and backend endpoints exist.
### Phase 1: Project Setup & Repository Initialization
1. Initialize the monorepo structure using `npx create-turbo@latest`.
2. Initialize the NestJS backend application: `npx @nestjs/cli new api-backend --strict`.
3. Initialize the Next.js frontend application: `npx create-next-app@latest web-dashboard --typescript --tailwind --eslint --app --src-dir`.
4. Initialize the Flutter mobile application: `flutter create mobile_app --platforms ios,android`.
5. Configure the shared TypeScript packages (`packages/shared-types`) and update `tsconfig.json` path aliases in both web and api projects.
6. Install core backend dependencies: `npm install @nestjs/typeorm typeorm pg @nestjs/jwt @nestjs/passport passport-jwt redis ioredis @nestjs/event-emitter`.
7. Install core frontend dependencies: `npm install zustand react-hook-form @hookform/resolvers/zod zod`.
8. Initialize `shadcn/ui` in the Next.js project: `npx shadcn@latest init` and add core components: `npx shadcn@latest add button form input table dialog`.
9. Create the `docker-compose.yml` file at the root, defining `postgres`, `redis`, and `localstack` (for S3/SQS simulation) services.
### Phase 2: Database & Data Modeling
10. Step 10 depends on Step 9 completing successfully. Start the Docker Compose services: `docker-compose up -d`.
11. Create the `User` TypeORM entity in `api-backend/src/users/entities/user.entity.ts` with all columns and constraints defined in Section 5.
12. Create the `Hub` TypeORM entity in `api-backend/src/hubs/entities/hub.entity.ts`.
13. Create the `Order` TypeORM entity in `api-backend/src/orders/entities/order.entity.ts`, establishing foreign key relations to `User` and `Hub`.
14. Generate the initial TypeORM database migration: `npm run typeorm migration:generate -- -n InitialSchema`.
15. Run the migration against the local PostgreSQL container: `npm run typeorm migration:run`.
16. Implement the database seed script utilizing `faker.js` to populate 10 Hubs and 50 Users.
### Phase 3: Authentication & Authorization
17. Implement the `AuthModule` in NestJS, configuring the `JwtModule` with secrets from the `.env` file.
18. Write the `AuthService.login` method, validating passwords against Argon2id hashes and issuing Access/Refresh tokens.
19. Create the `JwtAuthGuard` (as defined in Section 8) to protect routes.
20. Create the `@Roles()` decorator and `RolesGuard` to enforce the RBAC permission matrix.
21. Implement the Next.js login page (`src/app/login/page.tsx`) with React Hook Form and Zod validation.
22. Create the Zustand auth store in Next.js to manage the JWT state and handle token refresh logic via Axios interceptors.
### Phase 4: Core API & Event-Driven Logic
23. Implement the `OrdersModule`, `OrdersController`, and `OrdersService` in NestJS.
24. Write the `POST /api/v1/orders` endpoint, ensuring it utilizes a database transaction to reserve inventory and save the order.
25. Integrate `@nestjs/event-emitter`. Emit an `OrderCreated` event upon successful order creation.
26. Create a background worker service that listens for the `OrderCreated` event and simulates assigning a driver.
27. Implement the `WebSocketGateway` in NestJS, authenticating connections via JWT and joining clients to specific Redis rooms.
28. Create the `PATCH /api/v1/orders/:id/status` endpoint, emitting a WebSocket event to the specific Hub room when an order status changes.
### Phase 5: Frontend Dashboard & Integrations
29. Build the Next.js Dashboard layout (`src/app/dashboard/layout.tsx`) with a responsive sidebar and dark mode toggle.
30. Implement the Orders Data Table component using `shadcn/ui`, fetching data from the NestJS API with pagination.
31. Integrate Google Maps into the Next.js dashboard, connecting to the WebSocket gateway to render live driver locations.
32. Implement the Stripe PaymentIntent endpoint in NestJS and integrate Stripe Elements into the Next.js billing page.
33. Create the AWS S3 pre-signed URL endpoint in NestJS and implement the direct-upload logic in the Flutter application for Proof of Delivery images.
### Phase 6: Testing & Deployment
34. Write unit tests for the `OrdersService` using Jest, mocking the database repository and event emitter.
35. Write E2E tests for the Next.js login and order creation flow using Playwright.
36. Create the `.github/workflows/ci-cd.yml` file with the complete pipeline defined in Section 12.
37. Write the multi-stage `Dockerfile` for the NestJS and Next.js applications.
38. Finalize the `README.md` with local setup instructions, environment variable definitions, and architecture diagrams.
API Specification Table
REST API spec detailing endpoints, authentication requirements, and rate limits.
Category: integration
Tags: API, HTTP, Endpoints
Detailed Architecture Specification:
### **Core Reasoning:**
Defines the clear contract between frontend components and backend services.
### **Pain Points Addressed:**
Removes ambiguity surrounding API endpoints, ensuring accurate data fetching without endless iteration.
| Method | Path | Description | Auth Required | Rate Limit |
| :--- | :--- | :--- | :--- | :--- |
| POST | `/api/v1/auth/login` | Authenticate user and issue JWT | No | 5/min |
| POST | `/api/v1/auth/mfa/verify` | Verify TOTP/SMS code for MFA | Yes (Partial) | 5/min |
| GET | `/api/v1/users/me` | Retrieve current authenticated user profile | Yes | 60/min |
| POST | `/api/v1/users` | Create a new user (Admin/HR only) | Yes (Admin) | 20/min |
| GET | `/api/v1/hubs` | List all delivery hubs with pagination | Yes | 60/min |
| POST | `/api/v1/orders` | Create a new delivery order | Yes (Manager) | 30/min |
| GET | `/api/v1/orders/:id` | Retrieve specific order details | Yes | 120/min |
| PATCH | `/api/v1/orders/:id/status` | Update order status (Driver/Manager) | Yes | 60/min |
| POST | `/api/v1/inventory/adjust` | Adjust stock levels in a warehouse | Yes (Manager) | 30/min |
| GET | `/api/v1/content/posts` | Retrieve published CMS content | No | 120/min |
| POST | `/api/v1/tickets` | Submit a new support ticket | Yes | 10/min |
| POST | `/api/v1/payments/intent` | Create Stripe PaymentIntent | Yes | 20/min |
Mock JSON Payloads
Detailed JSON request and response payloads matching the API specifications.
Category: integration
Tags: JSON, Payloads, Types
Detailed Architecture Specification:
### **Core Reasoning:**
Provides explicit data structures expected by the backend, helping the AI generate perfectly-typed frontend clients.
### **Pain Points Addressed:**
Prevents 500 internal errors caused by mismatched data transfer objects (DTOs) passing between systems.
```json
// POST /api/v1/orders - Request
{
"hub_id": "a1b2c3d4-5678-90ab-cdef-1234567890ab",
"customer_id": "b2c3d4e5-6789-01bc-defa-234567890abc",
"items": [
{
"product_id": "c3d4e5f6-7890-12cd-efab-34567890abcd",
"quantity": 2
}
],
"total_amount": 149.98,
"currency": "USD"
}
// POST /api/v1/orders - Response (201 Created)
{
"status": "success",
"data": {
"id": "d4e5f6a7-8901-23de-fabc-4567890abcde",
"tracking_number": "TRK-987654321",
"status": "PENDING",
"created_at": "2023-10-27T10:30:00Z"
}
}
// PATCH /api/v1/orders/:id/status - Request
{
"status": "DELIVERED",
"proof_of_delivery_url": "https://s3.amazonaws.com/bucket/pod-123.jpg"
}
```NestJS Order Controller
A complete, production-ready NestJS controller blueprint including Guards and custom Responses.
Category: architecture
Tags: NestJS, Controllers, Typescript
Detailed Architecture Specification:
### **Core Reasoning:**
Establishes clean architectural patterns that the AI can replicate across all other endpoints.
### **Pain Points Addressed:**
Avoids spaghetti code by strictly adhering to the Controller-Service layered architecture out-of-the-box.
```typescript
import {
Controller,
Post,
Body,
UseGuards,
Req,
HttpException,
HttpStatus,
Logger
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
import { UserRole } from '../users/entities/user.entity';
import { OrdersService } from './orders.service';
import { CreateOrderDto } from './dto/create-order.dto';
export interface ApiResponse<T> {
status: 'success' | 'error';
data?: T;
message?: string;
}
@Controller('api/v1/orders')
@UseGuards(JwtAuthGuard, RolesGuard)
export class OrdersController {
private readonly logger = new Logger(OrdersController.name);
constructor(private readonly ordersService: OrdersService) {}
@Post()
@Roles(UserRole.HUB_MANAGER, UserRole.ADMIN)
export async createOrder(
@Body() createOrderDto: CreateOrderDto,
@Req() req: any
): Promise<ApiResponse<any>> {
try {
this.logger.log(`Creating order for hub ${createOrderDto.hub_id} by user ${req.user.id}`);
const order = await this.ordersService.create(createOrderDto, req.user.id);
return {
status: 'success',
data: order
};
} catch (error) {
this.logger.error(`Failed to create order: ${error.message}`, error.stack);
if (error.name === 'InsufficientInventoryError') {
throw new HttpException({
status: 'error',
code: 'ERR_INSUFFICIENT_INVENTORY',
message: error.message
}, HttpStatus.CONFLICT);
}
throw new HttpException({
status: 'error',
code: 'ERR_INTERNAL_SERVER',
message: 'An unexpected error occurred while processing the order.'
}, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
```JWT Auth Guard
Security middleware enforcing authentication rules mapped directly to our RBAC matrix.
Category: security
Tags: Auth, Middleware, Security
Detailed Architecture Specification:
### **Core Reasoning:**
Creates a solid authorization barrier, standardizing how users and tokens are validated.
### **Pain Points Addressed:**
Eliminates security bypasses by implementing token validation logically and correctly on day one.
```typescript
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException,
ForbiddenException,
Logger
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { UserRole } from '../users/entities/user.entity';
export interface JwtPayload {
sub: string;
email: string;
role: UserRole;
hub_id?: string;
}
@Injectable()
export class JwtAuthGuard implements CanActivate {
private readonly logger = new Logger(JwtAuthGuard.name);
constructor(
private jwtService: JwtService,
private reflector: Reflector
) {}
export async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
context.getHandler(),
context.getClass(),
]);
if (isPublic) {
return true;
}
const request = context.switchToHttp().getRequest<Request>();
const token = this.extractTokenFromHeader(request);
if (!token) {
this.logger.warn(`Unauthorized access attempt to ${request.url} - Missing token`);
throw new UnauthorizedException('Authentication token is missing');
}
try {
const payload = await this.jwtService.verifyAsync<JwtPayload>(token, {
secret: process.env.JWT_SECRET,
});
// Attach the payload to the request object for downstream use
request['user'] = {
id: payload.sub,
email: payload.email,
role: payload.role,
hub_id: payload.hub_id
};
return true;
} catch (error) {
this.logger.warn(`Token validation failed: ${error.message}`);
throw new UnauthorizedException('Authentication token is invalid or expired');
}
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}
```Unit Test Scenarios (Jest)
Explicit unit tests mapping to edge cases, using fully mocked repositories and services.
Category: planning
Tags: Testing, Jest, Coverage
Detailed Architecture Specification:
### **Core Reasoning:**
Teaching the AI exact mocking paradigms ensures it writes tests that actually run instead of failing on dependency injection.
### **Pain Points Addressed:**
Stops the AI from skipping test coverage or writing brittle tests that constantly fail due to side effects.
```typescript
import { Test, TestingModule } from '@nestjs/testing';
import { OrdersService } from './orders.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Order, OrderStatus } from './entities/order.entity';
import { InventoryService } from '../inventory/inventory.service';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { HttpException } from '@nestjs/common';
export const mockOrderRepository = {
create: jest.fn(),
save: jest.fn(),
findOne: jest.fn(),
};
export const mockInventoryService = {
reserveStock: jest.fn(),
};
export const mockEventEmitter = {
emit: jest.fn(),
};
describe('OrdersService', () => {
let service: OrdersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
OrdersService,
{ provide: getRepositoryToken(Order), useValue: mockOrderRepository },
{ provide: InventoryService, useValue: mockInventoryService },
{ provide: EventEmitter2, useValue: mockEventEmitter },
],
}).compile();
service = module.get<OrdersService>(OrdersService);
});
it('should successfully create an order and emit an event', async () => {
const createDto = { hub_id: 'hub-1', items: [{ product_id: 'prod-1', quantity: 2 }] };
const userId = 'user-1';
const savedOrder = { id: 'order-1', status: OrderStatus.PENDING, ...createDto };
mockInventoryService.reserveStock.mockResolvedValue(true);
mockOrderRepository.create.mockReturnValue(savedOrder);
mockOrderRepository.save.mockResolvedValue(savedOrder);
const result = await service.create(createDto, userId);
expect(mockInventoryService.reserveStock).toHaveBeenCalledWith(createDto.items);
expect(mockOrderRepository.save).toHaveBeenCalled();
expect(mockEventEmitter.emit).toHaveBeenCalledWith('order.created', expect.any(Object));
expect(result.id).toEqual('order-1');
});
it('should throw an error if inventory reservation fails', async () => {
const createDto = { hub_id: 'hub-1', items: [{ product_id: 'prod-1', quantity: 999 }] };
mockInventoryService.reserveStock.mockRejectedValue(new Error('Insufficient stock'));
try {
await service.create(createDto, 'user-1');
fail('Expected exception was not thrown');
} catch (error) {
expect(error).toBeInstanceOf(HttpException);
expect(error.message).toContain('Insufficient stock');
expect(mockOrderRepository.save).not.toHaveBeenCalled();
}
});
});
```Playwright E2E Strategy
End-to-End browser testing mimicking actual user journeys, validating the final shipped integration.
Category: integration
Tags: E2E, Playwright, Testing
Detailed Architecture Specification:
### **Core Reasoning:**
Validates that the generated frontend components successfully communicate with the generated API backend.
### **Pain Points Addressed:**
Creates reliable confidence that the AI hasn't hallucinogenically disconnected the UI from the database.
```typescript
import { test, expect } from '@playwright/test';
export const loginAsManager = async (page) => {
await page.goto('/login');
await page.fill('input[name="email"]', 'manager@acme.dev');
await page.fill('input[name="password"]', 'SecurePass123!');
await page.click('button[type="submit"]');
await expect(page).toHaveURL('/dashboard');
};
test.describe('Order Management E2E', () => {
test('Hub Manager can successfully create a new order', async ({ page }) => {
await loginAsManager(page);
await page.click('text=Create Order');
await page.fill('input[name="customerEmail"]', 'alice@acme.dev');
await page.selectOption('select[name="product"]', 'Industrial Foam Roll');
await page.fill('input[name="quantity"]', '5');
await page.click('button:has-text("Submit Order")');
// Verify success toast appears
const toast = page.locator('.toast-success');
await expect(toast).toContainText('Order created successfully');
// Verify order appears in the data table
const tableRow = page.locator('tr', { hasText: 'alice@acme.dev' }).first();
await expect(tableRow).toBeVisible();
await expect(tableRow.locator('td.status')).toHaveText('PENDING');
});
});
```Multi-Stage Dockerfile
Production-ready containerization blueprint optimized for build speed and minimal image sizes.
Category: architecture
Tags: Docker, DevOps, Containers
Detailed Architecture Specification:
### **Core Reasoning:**
A well-constructed Dockerfile is the foundation of immutable deployments, ensuring parity across local and dev environments.
### **Pain Points Addressed:**
Prevents the AI from using bloated base images or accidentally shipping developer dependency vulnerabilities.
```dockerfile
# Build Stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production Stage
FROM node:20-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
# Copy only necessary files from builder
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
# Security: Run as non-root user
USER node
EXPOSE 3000
CMD ["node", "dist/main"]
```
Monorepo Architecture Map
Top-to-bottom folder structure definition utilizing TurboRepo for shared libraries and modular applications.
Category: architecture
Tags: Monorepo, Architecture, Folders
Detailed Architecture Specification:
### **Core Reasoning:**
Giving the AI a map of exactly where every file belongs ensures it doesn't create fragmented, unorganized repositories.
### **Pain Points Addressed:**
Solves the classic "where did the AI save that file?" problem by establishing the exact structural boundaries.
```text
the-foam-train/
├── apps/
│ ├── api-backend/ # NestJS Application
│ │ ├── src/
│ │ │ ├── auth/ # IAM, Guards, Strategies
│ │ │ ├── logistics/ # Orders, Hubs, Routing
│ │ │ ├── finance/ # Stripe integrations
│ │ │ ├── ws-gateway/ # WebSocket handlers
│ │ │ └── main.ts
│ │ ├── test/ # E2E and Unit tests
│ │ ├── Dockerfile
│ │ └── package.json
│ ├── web-dashboard/ # Next.js Application
│ │ ├── src/
│ │ │ ├── app/ # App Router pages
│ │ │ ├── components/ # shadcn/ui & custom React components
│ │ │ ├── lib/ # API clients, Zod schemas
│ │ │ └── stores/ # Zustand state management
│ │ ├── Dockerfile
│ │ └── package.json
│ └── mobile-app/ # Flutter Application
│ ├── lib/
│ │ ├── screens/ # UI Views
│ │ ├── widgets/ # Reusable components
│ │ ├── services/ # API and WebSocket clients
│ │ └── main.dart
│ └── pubspec.yaml
├── packages/ # Shared Monorepo Packages
│ ├── shared-types/ # TS Interfaces used by Web & API
│ └── eslint-config/ # Standardized linting rules
├── infrastructure/ # Terraform IaC
├── docker-compose.yml # Local development environment
└── .github/ # CI/CD Workflows
```
AWS Deployment Map (Mermaid)
Visual diagram of the target cloud infrastructure spanning from Route53 down to private subnets.
Category: architecture
Tags: AWS, Mermaid, Deployment
Detailed Architecture Specification:
### **Core Reasoning:**
Shows engineers exactly what infrastructure pieces they're targeting when deploying the code generated by the prompt.
### **Pain Points Addressed:**
Bridging the gap between the application code the AI writes, and the actual cloud environment where it must live.
```mermaid
graph TD
subgraph AWS Cloud
Route53["Amazon Route 53 (DNS)"]
CloudFront["Amazon CloudFront (CDN)"]
WAF["AWS WAF (Security)"]
Route53 --> CloudFront
CloudFront --> WAF
WAF --> ALB["Application Load Balancer"]
subgraph VPC - Public Subnet
ALB
NAT["NAT Gateway"]
end
subgraph VPC - Private Subnet (App Tier)
ECS_Next["ECS Fargate: Next.js Web"]
ECS_Nest["ECS Fargate: NestJS API"]
ECS_Worker["ECS Fargate: Background Workers"]
ALB --> ECS_Next
ALB --> ECS_Nest
end
subgraph VPC - Private Subnet (Data Tier)
RDS["Amazon RDS (PostgreSQL) Primary"]
RDS_Replica["Amazon RDS Read Replica"]
Redis["Amazon ElastiCache (Redis)"]
Elastic["Amazon OpenSearch (Elastic)"]
ECS_Nest --> RDS
ECS_Nest --> RDS_Replica
ECS_Nest --> Redis
ECS_Nest --> Elastic
ECS_Worker --> RDS
end
SQS["Amazon SQS (Message Queue)"]
S3["Amazon S3 (Blob Storage)"]
ECS_Nest --> SQS
SQS --> ECS_Worker
ECS_Nest --> S3
ECS_Next --> S3
end
```Enterprise CI/CD Action
Automated deployment pipelines explicitly built to enforce security scans, type checking, and Docker registry pushes.
Category: integration
Tags: CI/CD, GitHub Actions, DevOps
Detailed Architecture Specification:
### **Core Reasoning:**
Establishes production deployment channels instantly, moving code from the repository into staging seamlessly.
### **Pain Points Addressed:**
Removes the manual overhead of building complex deployment scripts; the CI logic is generated concurrently with the codebase.
```yaml
name: Enterprise CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
env:
NODE_VERSION: '20.x'
DOCKER_REGISTRY: ghcr.io
jobs:
validate-and-test:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: TypeScript Type Checking
run: npm run typecheck
- name: Unit Tests (with Coverage)
run: npm run test:cov
security-scan:
runs-on: ubuntu-latest
needs: validate-and-test
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Dependency Audit
run: npm audit --audit-level=high
build-and-push:
runs-on: ubuntu-latest
needs: [validate-and-test, security-scan]
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop'
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Build and Push Docker Image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ env.DOCKER_REGISTRY }}/the-foam-train-api:${{ github.sha }}
```