# Tara Architecture Documentation

> **Canonical source:** the canonical architecture document for this domain is
> [`deep-dive/architecture.md`](./deep-dive/architecture.md), rendered in the
> docs center. This file is its operational companion (service topology, APIs,
> schemas, runtime detail) — reconciled by linking, not duplicated (§2, §13).

Tara is a modern meditation and mindfulness application designed to help users
develop a consistent meditation practice. This document provides a comprehensive
overview of the system architecture, component relationships, and data flows.

## Table of Contents

1. [System Overview](#system-overview)
2. [Project Structure](#project-structure)
3. [Technology Stack](#technology-stack)
4. [Component Architecture](#component-architecture)
5. [Data Architecture](#data-architecture)
6. [Authentication & Authorization](#authentication--authorization)
7. [API Architecture](#api-architecture)
8. [Web Application Architecture](#web-application-architecture)
9. [Mobile Application Architecture](#mobile-application-architecture)
10. [Shared Libraries](#shared-libraries)
11. [Data Flow Diagrams](#data-flow-diagrams)
12. [External Integrations](#external-integrations)
13. [Infrastructure & Deployment](#infrastructure--deployment)
14. [Security Considerations](#security-considerations)

---

## System Overview

Tara is a full-stack meditation platform consisting of:

- **API Server**: RESTful backend providing authentication, content management,
  user progress tracking, and subscription handling
- **Web Application**: Progressive Web App (PWA) for browser-based meditation
  sessions
- **Mobile Applications**: Native iOS and Android apps built with Expo/React
  Native
- **Content Library**: Curated collection of guided meditations, courses, and
  ambient sounds
- **Shared Libraries**: Cross-platform components, utilities, and business logic

### High-Level Architecture Diagram

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                              CLIENT LAYER                                    │
├───────────────────┬───────────────────┬─────────────────────────────────────┤
│   Mobile App      │    Web App        │         Admin Dashboard              │
│   (Expo/RN)       │    (Next.js)      │         (Future)                    │
│   iOS + Android   │    SSR + PWA      │                                     │
└─────────┬─────────┴─────────┬─────────┴──────────────────┬──────────────────┘
          │                   │                            │
          │    HTTPS/WSS     │                            │
          ▼                   ▼                            ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                              API LAYER                                       │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    Hono API Server (Port 3001)                        │   │
│  │  ┌─────────────┬─────────────┬──────────────┬──────────────────────┐ │   │
│  │  │ Auth Routes │ Content     │ User Routes  │ Analytics Routes     │ │   │
│  │  │ /api/v1/auth│ /meditations│ /sessions    │ /analytics           │ │   │
│  │  │             │ /courses    │ /progress    │ /experiments         │ │   │
│  │  │             │ /teachers   │ /favorites   │ /feature-flags       │ │   │
│  │  └─────────────┴─────────────┴──────────────┴──────────────────────┘ │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
└─────────┬─────────────────────────────┬─────────────────────────────────────┘
          │                             │
          ▼                             ▼
┌─────────────────────┐       ┌─────────────────────┐
│   DATA LAYER        │       │   CACHE LAYER       │
│   PostgreSQL        │       │   Redis             │
│   (Drizzle ORM)     │       │   - Session cache   │
│   - Users           │       │   - Rate limiting   │
│   - Content         │       │   - Feature flags   │
│   - Sessions        │       │                     │
│   - Subscriptions   │       └─────────────────────┘
│   - Analytics       │
└─────────────────────┘
          │
          ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                           STORAGE LAYER                                      │
│   ┌─────────────────────┐    ┌─────────────────────────────────────────┐    │
│   │   S3/MinIO          │    │   CDN (CloudFront/Similar)              │    │
│   │   - Audio files     │───▶│   - Audio streaming                     │    │
│   │   - Images          │    │   - Static assets                       │    │
│   │   - Course assets   │    │   - Signed URLs                         │    │
│   └─────────────────────┘    └─────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## Project Structure

```
oshun/
├── apps/tara/
│   ├── api/                    # Backend API server
│   │   ├── src/
│   │   │   ├── app.ts          # Hono application setup
│   │   │   ├── index.ts        # Server entry point
│   │   │   ├── db/             # Database schema and queries
│   │   │   ├── middleware/     # Auth, rate limiting, error handling
│   │   │   ├── routes/         # API route handlers
│   │   │   └── services/       # Business logic services
│   │   ├── test/               # Unit and integration tests
│   │   └── Dockerfile          # Production container
│   │
│   ├── web/                    # Next.js web application
│   │   ├── src/
│   │   │   ├── app/            # Next.js App Router pages
│   │   │   │   └── [locale]/   # i18n routing
│   │   │   ├── components/     # React components
│   │   │   ├── features/       # Feature-specific modules
│   │   │   ├── hooks/          # Custom React hooks
│   │   │   ├── lib/            # Utilities and helpers
│   │   │   ├── i18n/           # Internationalization
│   │   │   └── styles/         # Global styles
│   │   ├── e2e/                # Playwright E2E tests
│   │   └── public/             # Static assets
│   │
│   ├── mobile/                 # Expo React Native app
│   │   ├── src/
│   │   │   ├── screens/        # App screens
│   │   │   ├── components/     # React Native components
│   │   │   ├── services/       # Native services (audio, notifications)
│   │   │   ├── store/          # Zustand state stores
│   │   │   └── hooks/          # Custom hooks
│   │   ├── e2e/                # Maestro E2E tests
│   │   └── app.json            # Expo configuration
│   │
│   └── content/                # Content assets
│       ├── meditations/        # Guided meditation audio
│       ├── courses/            # Multi-day programs
│       ├── teachers/           # Teacher profiles
│       ├── sounds/             # Ambient sounds and bells
│       └── schemas/            # Content validation schemas
│
└── libs/tara/
    ├── ui/                     # Cross-platform component library
    ├── content/                # Content type definitions
    ├── database/               # Prisma schema and seeds
    ├── analytics/              # Event tracking
    ├── monitoring/             # Health checks
    ├── features/               # Shared business logic
    └── config/                 # Configuration management
```

---

## Technology Stack

### Backend (API)

| Component  | Technology           | Purpose                          |
| ---------- | -------------------- | -------------------------------- |
| Framework  | Hono 4.0             | Lightweight, fast HTTP framework |
| Language   | TypeScript           | Type-safe development            |
| ORM        | Drizzle ORM 0.38     | Type-safe database access        |
| Database   | PostgreSQL 16        | Primary data store               |
| Cache      | Redis 7              | Session cache, rate limiting     |
| Auth       | JWT + @oshun/auth    | Token-based authentication       |
| Validation | Zod                  | Runtime type validation          |
| API Docs   | OpenAPI + Swagger UI | Auto-generated documentation     |
| Testing    | Vitest, k6           | Unit tests, load testing         |

### Frontend (Web)

| Component     | Technology              | Purpose                  |
| ------------- | ----------------------- | ------------------------ |
| Framework     | Next.js 14              | React framework with SSR |
| Language      | TypeScript              | Type-safe development    |
| UI            | Radix UI + Tailwind CSS | Accessible components    |
| State         | Zustand 4.4             | Client state management  |
| Data Fetching | TanStack Query 5        | Server state management  |
| i18n          | next-intl 3.19          | Internationalization     |
| Animation     | Framer Motion 10        | UI animations            |
| Testing       | Vitest, Playwright      | Unit and E2E tests       |

### Mobile

| Component     | Technology         | Purpose                 |
| ------------- | ------------------ | ----------------------- |
| Framework     | Expo 51            | React Native toolchain  |
| Language      | TypeScript         | Type-safe development   |
| Routing       | Expo Router 3.5    | File-based navigation   |
| Audio         | Expo AV 14         | Audio playback          |
| State         | Zustand            | Client state management |
| Purchases     | RevenueCat         | In-app subscriptions    |
| Notifications | Expo Notifications | Push notifications      |
| Testing       | Jest, Maestro      | Unit and E2E tests      |

---

## Component Architecture

### API Component Diagram

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                           HONO API APPLICATION                               │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                        MIDDLEWARE STACK                              │    │
│  │  ┌──────────┐ ┌────────┐ ┌─────────┐ ┌──────────┐ ┌─────────────┐   │    │
│  │  │ Security │ │  CORS  │ │ Logging │ │   Auth   │ │ Rate Limit  │   │    │
│  │  │ Headers  │ │        │ │         │ │          │ │             │   │    │
│  │  └──────────┘ └────────┘ └─────────┘ └──────────┘ └─────────────┘   │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                    │                                         │
│                                    ▼                                         │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                         ROUTE HANDLERS                               │    │
│  │                                                                      │    │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐ │    │
│  │  │    Auth     │  │  Content    │  │    User     │  │  Analytics  │ │    │
│  │  │   Routes    │  │   Routes    │  │   Routes    │  │   Routes    │ │    │
│  │  │             │  │             │  │             │  │             │ │    │
│  │  │ - Register  │  │ - Meditatio │  │ - Sessions  │  │ - Events    │ │    │
│  │  │ - Login     │  │ - Courses   │  │ - Progress  │  │ - Experiments│ │    │
│  │  │ - Logout    │  │ - Teachers  │  │ - Favorites │  │ - Flags     │ │    │
│  │  │ - OAuth     │  │ - Search    │  │ - History   │  │             │ │    │
│  │  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘ │    │
│  └─────────┼────────────────┼────────────────┼────────────────┼────────┘    │
│            │                │                │                │              │
│            ▼                ▼                ▼                ▼              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                         SERVICE LAYER                                │    │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐ │    │
│  │  │ AuthService │  │ContentServ. │  │ UserService │  │AnalyticsSvc │ │    │
│  │  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘ │    │
│  └─────────┼────────────────┼────────────────┼────────────────┼────────┘    │
│            │                │                │                │              │
│            ▼                ▼                ▼                ▼              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                      DATA ACCESS LAYER                               │    │
│  │                        (Drizzle ORM)                                 │    │
│  │  ┌───────────────────────────────────────────────────────────────┐  │    │
│  │  │  Users │ Meditations │ Courses │ Sessions │ Subscriptions    │  │    │
│  │  └───────────────────────────────────────────────────────────────┘  │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Web Application Component Hierarchy

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                           NEXT.JS APPLICATION                                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                         ROOT LAYOUT                                  │    │
│  │  - Providers (Query, Auth, Theme, i18n)                             │    │
│  │  - Global styles                                                     │    │
│  │  - Analytics                                                         │    │
│  └──────────────────────────────┬──────────────────────────────────────┘    │
│                                 │                                            │
│                                 ▼                                            │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                      [LOCALE] LAYOUT                                 │    │
│  │  - Locale-specific configuration                                     │    │
│  │  - Navigation shell                                                  │    │
│  └──────────────────────────────┬──────────────────────────────────────┘    │
│                                 │                                            │
│      ┌──────────────────────────┼──────────────────────────┐                │
│      │                          │                          │                │
│      ▼                          ▼                          ▼                │
│  ┌────────────┐          ┌────────────┐          ┌────────────────┐        │
│  │   PUBLIC   │          │  (APP)     │          │  SUBSCRIPTION  │        │
│  │   ROUTES   │          │  ROUTES    │          │    ROUTES      │        │
│  │            │          │            │          │                │        │
│  │ - Landing  │          │ - Home     │          │ - Plans        │        │
│  │ - About    │          │ - Library  │          │ - Billing      │        │
│  │ - Auth     │          │ - Search   │          │ - Success      │        │
│  └────────────┘          │ - Timer    │          └────────────────┘        │
│                          │ - Play     │                                     │
│                          │ - Courses  │                                     │
│                          │ - Settings │                                     │
│                          └────────────┘                                     │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Mobile Application Screen Flow

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         EXPO ROUTER APPLICATION                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                       ONBOARDING FLOW                                │    │
│  │  ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌─────────┐             │    │
│  │  │ Welcome │──▶│ Goals   │──▶│ Schedule│──▶│ Trial   │             │    │
│  │  └─────────┘   └─────────┘   └─────────┘   └─────────┘             │    │
│  └──────────────────────────────────┬──────────────────────────────────┘    │
│                                     │                                        │
│                                     ▼                                        │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                       MAIN TAB NAVIGATOR                             │    │
│  │  ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌───────┐ │    │
│  │  │  Home   │   │ Explore │   │  Timer  │   │ Library │   │Profile│ │    │
│  │  └────┬────┘   └────┬────┘   └────┬────┘   └────┬────┘   └───┬───┘ │    │
│  └───────┼─────────────┼─────────────┼─────────────┼────────────┼─────┘    │
│          │             │             │             │            │           │
│          ▼             ▼             ▼             ▼            ▼           │
│  ┌───────────┐  ┌───────────┐  ┌───────────┐ ┌───────────┐ ┌───────────┐   │
│  │Daily Pick │  │ Search    │  │ Timer     │ │ Favorites │ │ Settings  │   │
│  │Recommended│  │ Categories│  │ Configure │ │ Downloads │ │ Account   │   │
│  │Progress   │  │ Courses   │  │           │ │ History   │ │ Premium   │   │
│  └─────┬─────┘  └─────┬─────┘  └───────────┘ └───────────┘ └───────────┘   │
│        │              │                                                     │
│        ▼              ▼                                                     │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │                       PLAYER SCREEN (Modal)                          │   │
│  │  ┌─────────────────────────────────────────────────────────────┐    │   │
│  │  │ Meditation Title                                              │    │   │
│  │  │ Teacher                                                       │    │   │
│  │  │ ┌─────────────────────────────────────────────────────────┐  │    │   │
│  │  │ │              Audio Waveform / Artwork                    │  │    │   │
│  │  │ └─────────────────────────────────────────────────────────┘  │    │   │
│  │  │ [========================================--------] 12:34     │    │   │
│  │  │           [Prev] [Play/Pause] [Next]                         │    │   │
│  │  │                 [Timer] [Sounds]                              │    │   │
│  │  └─────────────────────────────────────────────────────────────┘    │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## Data Architecture

### Database Entity Relationship Diagram

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         CORE DOMAIN ENTITIES                                 │
└─────────────────────────────────────────────────────────────────────────────┘

   ┌────────────────┐                         ┌────────────────┐
   │     users      │                         │   teachers     │
   ├────────────────┤                         ├────────────────┤
   │ id (PK)        │                         │ id (PK)        │
   │ email          │                         │ name           │
   │ password_hash  │                         │ bio            │
   │ name           │                         │ photo_url      │
   │ role           │                         │ credentials    │
   │ auth_provider  │                         │ specialties    │
   │ created_at     │                         └───────┬────────┘
   │ email_verified │                                 │
   └───────┬────────┘                                 │
           │                                          │
           │ 1:1                                      │ 1:N
           ▼                                          │
   ┌────────────────┐                                 │
   │ subscriptions  │                                 │
   ├────────────────┤                                 │
   │ user_id (FK)   │                                 │
   │ tier           │      ┌────────────────┐        │
   │ status         │      │  meditations   │◀───────┘
   │ stripe_id      │      ├────────────────┤
   │ current_period │      │ id (PK)        │
   │ cancel_at      │      │ title          │
   └────────────────┘      │ description    │
                           │ teacher_id (FK)│
   ┌────────────────┐      │ category       │
   │user_preferences│      │ duration       │
   ├────────────────┤      │ audio_url      │
   │ user_id (FK)   │      │ is_premium     │
   │ default_dur    │      │ experience_lvl │
   │ reminder_time  │      └───────┬────────┘
   │ notifications  │              │
   │ theme          │              │ N:M
   │ language       │              │
   └────────────────┘              ▼
                           ┌────────────────┐
                           │    courses     │
                           ├────────────────┤
                           │ id (PK)        │
                           │ title          │
                           │ description    │
                           │ teacher_id (FK)│
                           │ total_days     │
                           │ is_premium     │
                           └───────┬────────┘
                                   │
                                   │ 1:N
                                   ▼
                           ┌──────────────────┐
                           │course_meditations│
                           ├──────────────────┤
                           │ course_id (FK)   │
                           │ meditation_id(FK)│
                           │ day_number       │
                           │ order_in_day     │
                           └──────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│                         USER ACTIVITY ENTITIES                               │
└─────────────────────────────────────────────────────────────────────────────┘

   ┌────────────────┐      ┌────────────────┐      ┌────────────────┐
   │    sessions    │      │ user_progress  │      │course_progress │
   ├────────────────┤      ├────────────────┤      ├────────────────┤
   │ id (PK)        │      │ user_id (FK)   │      │ user_id (FK)   │
   │ user_id (FK)   │      │ total_minutes  │      │ course_id (FK) │
   │ meditation_id  │      │ total_sessions │      │ current_day    │
   │ started_at     │      │ current_streak │      │ completed_days │
   │ completed_at   │      │ longest_streak │      │ started_at     │
   │ duration       │      │ weekly_goal    │      │ completed_at   │
   │ completion_%   │      │ achievements   │      │ status         │
   │ rating         │      │ level          │      └────────────────┘
   └────────────────┘      └────────────────┘

   ┌────────────────┐      ┌────────────────┐      ┌────────────────┐
   │   favorites    │      │   downloads    │      │   collections  │
   ├────────────────┤      ├────────────────┤      ├────────────────┤
   │ user_id (FK)   │      │ user_id (FK)   │      │ id (PK)        │
   │ meditation_id  │      │ meditation_id  │      │ name           │
   │ created_at     │      │ downloaded_at  │      │ description    │
   └────────────────┘      │ file_size      │      │ type           │
                           │ expires_at     │      │ is_featured    │
                           └────────────────┘      └────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│                         ANALYTICS ENTITIES                                   │
└─────────────────────────────────────────────────────────────────────────────┘

   ┌────────────────┐      ┌────────────────┐      ┌────────────────┐
   │analytics_events│      │  experiments   │      │ feature_flags  │
   ├────────────────┤      ├────────────────┤      ├────────────────┤
   │ id (PK)        │      │ id (PK)        │      │ id (PK)        │
   │ user_id        │      │ name           │      │ key            │
   │ event_type     │      │ variants       │      │ enabled        │
   │ properties     │      │ status         │      │ rules          │
   │ timestamp      │      │ allocation     │      │ rollout_%      │
   │ session_id     │      │ targeting      │      │ targeting      │
   └────────────────┘      └────────────────┘      └────────────────┘
```

### Key Data Models

#### User Model

```typescript
interface User {
  id: string;
  email: string;
  passwordHash?: string;
  name?: string;
  role: 'user' | 'premium' | 'admin';
  authProvider: 'email' | 'google' | 'apple' | 'facebook';
  emailVerified: boolean;
  createdAt: Date;
  updatedAt: Date;
}
```

#### Meditation Model

```typescript
interface Meditation {
  id: string;
  title: string;
  description: string;
  teacherId: string;
  category: MeditationCategory;
  duration: number; // seconds
  audioUrl: string;
  imageUrl?: string;
  isPremium: boolean;
  experienceLevel: 'beginner' | 'intermediate' | 'advanced';
  contentType: 'guided' | 'unguided' | 'music' | 'soundscape' | 'story';
  tags: string[];
  createdAt: Date;
}
```

#### Session Model

```typescript
interface Session {
  id: string;
  userId: string;
  meditationId: string;
  startedAt: Date;
  completedAt?: Date;
  duration: number; // actual duration in seconds
  completionPercentage: number;
  rating?: number; // 1-5
  notes?: string;
}
```

---

## Authentication & Authorization

### Authentication Flow

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         AUTHENTICATION FLOWS                                 │
└─────────────────────────────────────────────────────────────────────────────┘

EMAIL/PASSWORD LOGIN:
┌──────────┐    POST /auth/login     ┌──────────┐    Verify      ┌──────────┐
│  Client  │ ─────────────────────▶  │   API    │ ─────────────▶ │ Database │
│          │                         │          │                │          │
│          │  ◀───────────────────── │          │ ◀───────────── │          │
└──────────┘  { accessToken,         └──────────┘  User + hash   └──────────┘
              refreshToken }

TOKEN REFRESH:
┌──────────┐  POST /auth/refresh     ┌──────────┐    Rotate      ┌──────────┐
│  Client  │ ─────────────────────▶  │   API    │ ─────────────▶ │  Redis   │
│          │  { refreshToken }       │          │                │          │
│          │  ◀───────────────────── │          │ ◀───────────── │          │
└──────────┘  { accessToken,         └──────────┘  New tokens    └──────────┘
              refreshToken }

OAUTH (Apple/Google):
┌──────────┐                         ┌──────────┐                ┌──────────┐
│  Client  │ ─────────────────────▶  │ Provider │                │          │
│          │  Redirect to OAuth      │ (Apple/  │                │          │
│          │                         │ Google)  │                │   API    │
│          │  ◀───────────────────── │          │                │          │
│          │  Auth code              └──────────┘                │          │
│          │                                                     │          │
│          │  POST /auth/oauth/{provider}                        │          │
│          │ ─────────────────────────────────────────────────▶  │          │
│          │                                                     │          │
│          │  ◀───────────────────────────────────────────────── │          │
└──────────┘  { accessToken, refreshToken }                      └──────────┘
```

### Authorization Model

```typescript
// Role-based access control
enum UserRole {
  USER = 'user',
  PREMIUM = 'premium',
  ADMIN = 'admin',
}

// Middleware usage
app.get('/protected', authMiddleware(), handler);
app.get('/premium-only', authMiddleware(), requireRole('premium'), handler);
app.get('/admin-only', authMiddleware(), requireMinRole('admin'), handler);
```

### Token Structure

```typescript
// Access Token Payload (1 hour TTL)
interface AccessTokenPayload {
  sub: string; // User ID
  email: string;
  role: UserRole;
  permissions: string[];
  iat: number;
  exp: number;
}

// Refresh Token (24 hour TTL, stored in DB)
interface RefreshToken {
  id: string;
  userId: string;
  tokenHash: string;
  family: string; // Token rotation family
  expiresAt: Date;
  revokedAt?: Date;
}
```

---

## API Architecture

### Endpoint Overview

| Category         | Endpoint                        | Methods           | Auth Required | Description              |
| ---------------- | ------------------------------- | ----------------- | ------------- | ------------------------ |
| **Auth**         | `/api/v1/auth/register`         | POST              | No            | User registration        |
|                  | `/api/v1/auth/login`            | POST              | No            | Email/password login     |
|                  | `/api/v1/auth/logout`           | POST              | Yes           | Logout and revoke tokens |
|                  | `/api/v1/auth/refresh`          | POST              | No            | Refresh access token     |
|                  | `/api/v1/auth/oauth/{provider}` | POST              | No            | OAuth authentication     |
|                  | `/api/v1/auth/verify-email`     | POST              | No            | Email verification       |
|                  | `/api/v1/auth/forgot-password`  | POST              | No            | Password reset request   |
|                  | `/api/v1/auth/reset-password`   | POST              | No            | Password reset           |
| **Content**      | `/api/v1/meditations`           | GET               | No            | List meditations         |
|                  | `/api/v1/meditations/:id`       | GET               | No            | Get meditation details   |
|                  | `/api/v1/meditations/featured`  | GET               | No            | Featured meditations     |
|                  | `/api/v1/courses`               | GET               | No            | List courses             |
|                  | `/api/v1/courses/:id`           | GET               | No            | Get course details       |
|                  | `/api/v1/teachers`              | GET               | No            | List teachers            |
|                  | `/api/v1/search`                | GET               | No            | Search content           |
| **User**         | `/api/v1/users/me`              | GET, PATCH        | Yes           | Current user profile     |
|                  | `/api/v1/sessions`              | GET, POST         | Yes           | Meditation sessions      |
|                  | `/api/v1/progress`              | GET               | Yes           | User progress stats      |
|                  | `/api/v1/achievements`          | GET               | Yes           | User achievements        |
|                  | `/api/v1/favorites`             | GET, POST, DELETE | Yes           | Favorite meditations     |
|                  | `/api/v1/downloads`             | GET, POST, DELETE | Yes           | Offline downloads        |
| **Subscription** | `/api/v1/subscription`          | GET               | Yes           | Current subscription     |
|                  | `/api/v1/subscription/checkout` | POST              | Yes           | Create checkout session  |
|                  | `/api/v1/subscription/portal`   | POST              | Yes           | Customer portal URL      |
| **Analytics**    | `/api/v1/analytics/events`      | POST              | Optional      | Track events             |
|                  | `/api/v1/analytics/experiments` | GET               | Optional      | Get experiment variants  |
|                  | `/api/v1/analytics/flags`       | GET               | Optional      | Get feature flags        |

### Error Response Format (RFC 7807)

```json
{
  "type": "https://api.tara.app/errors/validation",
  "title": "Validation Error",
  "status": 400,
  "detail": "The request body contains invalid data",
  "instance": "/api/v1/auth/register",
  "errors": [
    {
      "field": "email",
      "message": "Invalid email format"
    }
  ]
}
```

### Rate Limiting

| Tier         | Limit         | Window   |
| ------------ | ------------- | -------- |
| Anonymous    | 60 requests   | 1 minute |
| Free User    | 300 requests  | 1 minute |
| Premium User | 1000 requests | 1 minute |

Headers returned:

- `X-RateLimit-Limit`: Maximum requests allowed
- `X-RateLimit-Remaining`: Requests remaining
- `X-RateLimit-Reset`: Unix timestamp when limit resets

---

## Web Application Architecture

### Routing Structure

```
/[locale]/
├── (marketing)/
│   ├── /                    # Landing page
│   ├── /about               # About page
│   ├── /pricing             # Pricing page
│   └── /teachers            # Teacher profiles
├── (auth)/
│   ├── /login               # Login page
│   ├── /register            # Registration
│   ├── /forgot-password     # Password reset
│   └── /verify-email        # Email verification
├── (app)/
│   ├── /                    # Dashboard/Home
│   ├── /play/[id]           # Meditation player
│   ├── /search              # Search
│   ├── /timer               # Meditation timer
│   ├── /library             # Saved content
│   ├── /courses             # Course browser
│   ├── /courses/[id]        # Course detail
│   └── /settings/           # Settings pages
└── /subscription/
    ├── /                    # Subscription home
    ├── /plans               # Plan selection
    └── /billing             # Billing management
```

### State Management

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         STATE MANAGEMENT                                     │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                      TANSTACK QUERY (Server State)                   │    │
│  │  - Meditations, Courses, Teachers (cached, deduplicated)            │    │
│  │  - User profile, Progress, Favorites                                │    │
│  │  - Subscriptions, Sessions                                          │    │
│  │  - Automatic background refetching                                  │    │
│  │  - Optimistic updates for mutations                                 │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                      ZUSTAND (Client State)                          │    │
│  │  - Audio player state (playing, progress, volume)                   │    │
│  │  - UI state (modals, drawers, toasts)                               │    │
│  │  - User preferences (local cache)                                   │    │
│  │  - Onboarding progress                                              │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                      CONTEXT (React Context)                         │    │
│  │  - Auth context (current user, tokens)                              │    │
│  │  - Theme context (light/dark mode)                                  │    │
│  │  - i18n context (locale, translations)                              │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## Mobile Application Architecture

### Service Layer

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         MOBILE SERVICES                                      │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                      AUDIO SERVICE                                   │    │
│  │  - Singleton audio player instance                                  │    │
│  │  - Background audio playback (iOS/Android)                          │    │
│  │  - Lock screen controls                                             │    │
│  │  - Audio focus management                                           │    │
│  │  - Streaming with quality selection                                 │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                    NOTIFICATION SERVICE                              │    │
│  │  - Push notification registration (APNS/FCM)                        │    │
│  │  - Local notification scheduling                                    │    │
│  │  - Reminder management                                              │    │
│  │  - Badge count management                                           │    │
│  │  - Deep link handling from notifications                            │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                     PURCHASE SERVICE                                 │    │
│  │  - RevenueCat integration                                           │    │
│  │  - Subscription status management                                   │    │
│  │  - Receipt validation                                               │    │
│  │  - Restore purchases                                                │    │
│  │  - Cross-platform entitlement sync                                  │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                     DOWNLOAD SERVICE                                 │    │
│  │  - Offline content downloads                                        │    │
│  │  - Storage management                                               │    │
│  │  - Download progress tracking                                       │    │
│  │  - Expiration management                                            │    │
│  │  - Background downloads                                             │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Zustand Stores

```typescript
// User Store
interface UserStore {
  user: User | null;
  isAuthenticated: boolean;
  accessToken: string | null;
  login: (email: string, password: string) => Promise<void>;
  logout: () => Promise<void>;
  refreshToken: () => Promise<void>;
}

// Meditation Store
interface MeditationStore {
  meditations: Map<string, Meditation>;
  favorites: Set<string>;
  downloads: Map<string, DownloadStatus>;
  fetchMeditation: (id: string) => Promise<Meditation>;
  toggleFavorite: (id: string) => void;
  downloadMeditation: (id: string) => Promise<void>;
}

// Player Store
interface PlayerStore {
  currentMeditation: Meditation | null;
  isPlaying: boolean;
  progress: number;
  duration: number;
  play: () => void;
  pause: () => void;
  seek: (position: number) => void;
  setMeditation: (meditation: Meditation) => void;
}
```

---

## Data Flow Diagrams

### Meditation Playback Flow

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                    MEDITATION PLAYBACK DATA FLOW                             │
└─────────────────────────────────────────────────────────────────────────────┘

1. USER SELECTS MEDITATION
   ┌────────┐     tap       ┌────────────┐
   │  User  │ ───────────▶  │ Meditation │
   └────────┘               │   Card     │
                            └─────┬──────┘
                                  │
2. FETCH MEDITATION DETAILS       ▼
   ┌────────────┐   GET /meditations/:id   ┌────────────┐
   │   Client   │ ──────────────────────▶  │    API     │
   │            │                          │            │
   │            │  ◀────────────────────── │            │
   └─────┬──────┘  { meditation, audioUrl} └────────────┘
         │
3. INITIALIZE PLAYER              │
         │                        │
         ▼                        │
   ┌────────────┐                 │
   │   Audio    │                 │
   │  Service   │                 │
   └─────┬──────┘                 │
         │                        │
4. START STREAMING                │
         │    GET audio (CDN)     │
         │ ────────────────────▶  │
         │                        ▼
         │                   ┌────────────┐
         │                   │    CDN     │
         │  ◀────────────────│   (S3)    │
         │    audio stream   └────────────┘
         │
5. CREATE SESSION
         │    POST /sessions
         │ ────────────────────▶  ┌────────────┐
         │                        │    API     │
         │  ◀────────────────────│            │
         │    { sessionId }       └─────┬──────┘
         │                              │
6. UPDATE PROGRESS (periodic)           ▼
         │    PATCH /sessions/:id ┌────────────┐
         │ ────────────────────▶  │  Database  │
         │                        └────────────┘
         │
7. COMPLETE SESSION
         │    PATCH /sessions/:id
         │ ────────────────────▶  ┌────────────┐
         │    { completed: true } │    API     │
         │                        │ + Update   │
         │                        │   Progress │
         │                        └────────────┘
```

### Subscription Flow

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                      SUBSCRIPTION PURCHASE FLOW                              │
└─────────────────────────────────────────────────────────────────────────────┘

WEB (Stripe):
   ┌────────┐   Select Plan   ┌────────────┐
   │  User  │ ──────────────▶ │  Pricing   │
   └────────┘                 │   Page     │
                              └─────┬──────┘
                                    │
                POST /subscription/checkout
                                    │
                                    ▼
                              ┌────────────┐
                              │    API     │
                              │  (Stripe)  │
                              └─────┬──────┘
                                    │
                              Checkout URL
                                    │
                                    ▼
                              ┌────────────┐
                              │   Stripe   │
                              │  Checkout  │
                              └─────┬──────┘
                                    │
                              Payment Success
                                    │
                                    ▼
                              ┌────────────┐
                              │  Webhook   │───▶ Update subscription
                              │  Handler   │     in database
                              └────────────┘

MOBILE (RevenueCat):
   ┌────────┐   Select Plan   ┌────────────┐
   │  User  │ ──────────────▶ │ Paywall    │
   └────────┘                 │  Screen    │
                              └─────┬──────┘
                                    │
                              Purchase via
                              App Store / Play Store
                                    │
                                    ▼
                              ┌────────────┐
                              │ RevenueCat │
                              │    SDK     │
                              └─────┬──────┘
                                    │
                              Entitlement granted
                                    │
                                    ▼
                              ┌────────────┐
                              │  Webhook   │───▶ Sync with API
                              │  Handler   │     Update user tier
                              └────────────┘
```

---

## External Integrations

### Integration Map

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                       EXTERNAL INTEGRATIONS                                  │
└─────────────────────────────────────────────────────────────────────────────┘

   ┌─────────────────────────────────────────────────────────────────────┐
   │                         TARA PLATFORM                                │
   └───────────────────────────────┬─────────────────────────────────────┘
                                   │
       ┌───────────────────────────┼───────────────────────────┐
       │                           │                           │
       ▼                           ▼                           ▼
┌──────────────┐           ┌──────────────┐           ┌──────────────┐
│   PAYMENTS   │           │   STORAGE    │           │    AUTH      │
├──────────────┤           ├──────────────┤           ├──────────────┤
│              │           │              │           │              │
│   Stripe     │           │   AWS S3     │           │   Google     │
│   (Web)      │           │   (Audio,    │           │   OAuth      │
│              │           │    Images)   │           │              │
│   RevenueCat │           │              │           │   Apple      │
│   (Mobile)   │           │   CloudFront │           │   Sign-In    │
│              │           │   (CDN)      │           │              │
└──────────────┘           └──────────────┘           └──────────────┘
       │                           │                           │
       │                           │                           │
       ▼                           ▼                           ▼
┌──────────────┐           ┌──────────────┐           ┌──────────────┐
│  ANALYTICS   │           │    PUSH      │           │  MONITORING  │
├──────────────┤           ├──────────────┤           ├──────────────┤
│              │           │              │           │              │
│   Segment    │           │   APNs       │           │   Sentry     │
│   (optional) │           │   (iOS)      │           │   (Errors)   │
│              │           │              │           │              │
│   Mixpanel   │           │   FCM        │           │   Prometheus │
│   (optional) │           │   (Android)  │           │   (Metrics)  │
│              │           │              │           │              │
└──────────────┘           └──────────────┘           └──────────────┘
```

### Integration Details

| Service           | Purpose                    | Configuration                                   |
| ----------------- | -------------------------- | ----------------------------------------------- |
| **Stripe**        | Web subscription billing   | `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`    |
| **RevenueCat**    | Mobile IAP management      | `REVENUECAT_API_KEY`                            |
| **AWS S3**        | Audio/image storage        | `S3_ENDPOINT`, `S3_ACCESS_KEY`, `S3_SECRET_KEY` |
| **CloudFront**    | CDN for media delivery     | `CDN_URL`                                       |
| **APNs**          | iOS push notifications     | APNS certificates in EAS                        |
| **FCM**           | Android push notifications | `FCM_SERVER_KEY`                                |
| **Google OAuth**  | Social authentication      | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`      |
| **Apple Sign-In** | iOS authentication         | Configured in app entitlements                  |
| **Sentry**        | Error tracking             | `SENTRY_DSN`                                    |

---

## Infrastructure & Deployment

### Deployment Architecture

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                       DEPLOYMENT ARCHITECTURE                                │
└─────────────────────────────────────────────────────────────────────────────┘

                              ┌─────────────┐
                              │   Users     │
                              └──────┬──────┘
                                     │
                              ┌──────▼──────┐
                              │ CloudFlare  │
                              │    (DNS)    │
                              └──────┬──────┘
                                     │
              ┌──────────────────────┼──────────────────────┐
              │                      │                      │
              ▼                      ▼                      ▼
       ┌────────────┐        ┌────────────┐        ┌────────────┐
       │   Vercel   │        │ AWS ALB    │        │ App Store  │
       │   (Web)    │        │ (API)      │        │ / Play     │
       └────────────┘        └─────┬──────┘        │   Store    │
                                   │               └────────────┘
                            ┌──────┴──────┐
                            │  AWS ECS    │
                            │  (Fargate)  │
                            └──────┬──────┘
                                   │
              ┌────────────────────┼────────────────────┐
              │                    │                    │
              ▼                    ▼                    ▼
       ┌────────────┐       ┌────────────┐       ┌────────────┐
       │ PostgreSQL │       │   Redis    │       │  S3 + CDN  │
       │   (RDS)    │       │(ElastiCache│       │  (Media)   │
       └────────────┘       └────────────┘       └────────────┘
```

### Environment Configuration

| Environment | API URL                        | Web URL                    | Purpose                |
| ----------- | ------------------------------ | -------------------------- | ---------------------- |
| Development | `http://localhost:3001`        | `http://localhost:3000`    | Local development      |
| Staging     | `https://api.staging.tara.app` | `https://staging.tara.app` | Pre-production testing |
| Production  | `https://api.tara.app`         | `https://tara.app`         | Live users             |

---

## Security Considerations

### Security Measures

1. **Authentication**
   - JWT tokens with short expiry (1 hour)
   - Refresh token rotation with family tracking
   - Account lockout after failed login attempts
   - Email verification required for sensitive operations

2. **Authorization**
   - Role-based access control (RBAC)
   - Resource-level permissions
   - Premium content gating

3. **Data Protection**
   - TLS encryption in transit
   - Encrypted storage for sensitive data
   - PII handling compliant with GDPR/CCPA
   - Password hashing with bcrypt

4. **API Security**
   - Rate limiting per user tier
   - CORS configuration
   - Security headers (CSP, X-Frame-Options, etc.)
   - Request validation with Zod schemas

5. **Mobile Security**
   - Secure token storage (Keychain/Keystore)
   - Certificate pinning (optional)
   - App Transport Security (iOS)
   - ProGuard obfuscation (Android)

### Security Headers

```typescript
// Applied via secureHeaders middleware
{
  "X-Frame-Options": "DENY",
  "X-Content-Type-Options": "nosniff",
  "Referrer-Policy": "strict-origin-when-cross-origin",
  "Content-Security-Policy": "default-src 'self'; ...",
  "Strict-Transport-Security": "max-age=31536000; includeSubDomains"
}
```

---

## Appendix

### Key File Paths

| Component  | Path                             |
| ---------- | -------------------------------- |
| API Entry  | `apps/tara/api/src/index.ts`     |
| API Routes | `apps/tara/api/src/routes/`      |
| DB Schema  | `apps/tara/api/src/db/schema.ts` |
| Web App    | `apps/tara/web/src/app/`         |
| Mobile App | `apps/tara/mobile/src/`          |
| UI Library | `libs/tara/ui/src/`              |
| Content    | `apps/tara/content/`             |

### Technology Versions

| Technology | Version |
| ---------- | ------- |
| Node.js    | 22      |
| TypeScript | 6.0.3   |
| Hono       | 4.0     |
| Next.js    | 14      |
| Expo       | 51      |
| React      | 18      |
| PostgreSQL | 16      |
| Redis      | 7       |

### Related Documentation

- [API Documentation](./api/README.md)
- [Development Setup Guide](./development.md)
- [Deployment Guide](./deployment.md)
- [Content Management Guide](./content.md)
