# 01 - Session Initialization Architecture

Welcome to **Milestone 1, Step 1.7**: Session Initialization Endpoint (`POST /api/v1/session/init`).

---

## 1. What is a Session and Why Do We Need It?

A **Session** represents a single visitor's interactive conversation thread with the chatbot on a tenant website.

- **`siteId`:** Identifies **WHO** owns the website (the Tenant/Customer).
- **`sessionId`:** Identifies **THIS SPECIFIC VISITOR'S** active conversation instance (e.g. `sess_a1b2c3d4e5f6`).

---

## 2. End-to-End Session Initialization Flow

```text
  [Browser / Widget]
          │
          │ 1. Reads data-site-id="site_demo_123"
          │ 2. Sends HTTP POST /api/v1/session/init with body: {"siteId": "site_demo_123"}
          │    Includes browser header: Origin: http://127.0.0.1:5500
          ▼
  [FastAPI Backend - app/routers/session.py]
          │
          │ 3. Finds Tenant in MongoDB by siteId
          │    Returns 404 Not Found if siteId doesn't exist
          │
          │ 4. Extracts HTTP 'Origin' header & validates against Tenant.domain
          │    Returns 403 Forbidden if Origin is not authorized
          │
          │ 5. Generates unique server-side sessionId (sess_...)
          │ 6. Inserts Session document into MongoDB 'sessions' collection
          ▼
  [Response Returned: 201 Created]
  {"sessionId": "sess_a1b2c3d4e5f6"}
```

---

## 3. Server-Side Origin Header Security

### Why Origin comes from the HTTP Header (NOT JSON Body)
A malicious client could easily send a JSON body containing `{"domain": "authorized-site.com"}`. 

Browsers automatically attach the immutable **`Origin` HTTP Header** (e.g. `Origin: http://127.0.0.1:5500`) to cross-origin requests. Client JavaScript running in a browser **cannot forge or override** the HTTP `Origin` header.

### Validation Helper (`is_origin_allowed`)
The backend extracts the hostname/port from the browser's `Origin` header and compares it against the tenant's registered `domain` in MongoDB:
- Matches protocol (`http://`, `https://`).
- Matches host and optional development ports (`127.0.0.1:5500`, `localhost:8000`).
- If validation fails, returns `403 Forbidden`.

---

## 4. MongoDB `sessions` Document Structure

When initialized, a new document is persisted in the **`sessions`** collection:

```json
{
  "_id": ObjectId("..."),
  "sessionId": "sess_8f3a1b9c4d2e",
  "siteId": "site_demo_123",
  "mode": "rule",
  "createdAt": ISODate("2026-08-13T11:40:00Z"),
  "lastActiveAt": ISODate("2026-08-13T11:40:00Z")
}
```

---

## 5. Difference: `siteId` vs. `sessionId`

| Identifier | Belongs To | Purpose | Example |
|---|---|---|---|
| **`siteId`** | Tenant (Website Owner) | Multi-tenancy key identifying the site account | `site_demo_123` |
| **`sessionId`** | Visitor (Individual User) | Unique thread key for the active visitor chat session | `sess_8f3a1b9c4d2e` |
