# RoohAI SaaS Architecture Plan

## Goal
Turn the RoohAI framework into a multi-tenant SaaS platform where users can:
1. Auth with Google
2. Create voice AI agents via a dashboard
3. Embed those agents in their own applications

---

## 1. Auth Layer
- Use Google OAuth 2.0 (Firebase Auth, Auth0, or Cognito)
- On login, create a `users` record with Google ID, email, etc.
- Issue JWT/session token for subsequent API calls

## 2. Data Model

```
users
  - id, email, google_id, created_at, plan/tier

agents
  - id, user_id, name, created_at, status (active/inactive)
  - config (JSON/YAML) — STT model, TTS model, LLM model, system prompt, voice settings
  - api_key (unique per agent, for embed auth)

usage_logs
  - agent_id, user_id, timestamp, duration, tokens_used
```

## 3. Backend Hosting

### Option A: Shared Multi-Tenant Backend (recommended to start)
- One FastAPI deployment serves all users/agents
- Requests include the agent's API key -> look up agent config -> route to the right STT/TTS/LLM
- WebRTC sessions multiplexed on the same server
- Scale horizontally with more instances behind a load balancer
- **Pros**: Simple, cost-effective, fast to ship
- **Cons**: Noisy neighbor risk

### Option B: Isolated Per-Agent/Per-User Backends (future)
- Spin up containers (ECS/Fargate/EKS) per agent or per user
- **Pros**: Full isolation, independent scaling
- **Cons**: More complexity, higher cost, slower cold starts
- Only worth it with paying customers and SLA requirements

## 4. Embed Script (How Users Add the Agent to Their App)

Users get a JavaScript snippet:

```html
<script src="https://yourdomain.com/embed.js"
        data-agent-id="ag_abc123"
        data-api-key="key_xyz789"></script>
```

`embed.js` would:
- Inject the voice UI widget (floating button / chat panel)
- Connect to the backend via WebRTC using the agent's API key
- Backend validates the key, loads agent config, runs the pipeline

## 5. Embed Security

### Problem
API key in client-side JS is visible in browser dev tools.

### Solutions

#### Domain Allowlisting (primary defense)
- Users register allowed domains when creating an agent
- Backend checks `Origin`/`Referer` header on every request
- Requests from non-allowed domains are rejected

#### Publishable Key vs Secret Key (Stripe model)
- **Publishable key** (`pk_ag_abc123`) — in embed snippet, can only initiate sessions, restricted by domain allowlist
- **Secret key** (`sk_ag_abc123`) — never client-side, used for management API (CRUD agents, view usage)

#### Rate Limiting + Usage Caps
- Max concurrent sessions per agent
- Daily/monthly usage caps tied to user's plan
- Anomaly detection — usage spikes trigger alerts or auto-pause

#### Short-Lived Session Tokens (optional, for security-conscious users)
```
User's server  -> POST /api/agents/ag_123/session (with secret key)
               <- { "token": "sess_xyz", "expires_in": 300 }

User's frontend -> embed.js uses sess_xyz instead of raw API key
```
- Nothing long-lived in the browser
- Adds integration complexity — offer as optional

### Security Summary

| Layer                  | What it does                              |
|------------------------|-------------------------------------------|
| Domain allowlist       | Key only works from registered origins    |
| Publishable vs Secret  | Embed key can't access management APIs    |
| Rate limits + caps     | Abuse is bounded even if key leaks        |
| Session tokens (opt)   | Nothing long-lived in the browser         |

## 6. Infrastructure Needed

| Component        | Purpose                  | Options                                      |
|------------------|--------------------------|----------------------------------------------|
| Auth             | Google login             | Firebase Auth, Auth0, Cognito                |
| Database         | Users, agents, configs   | PostgreSQL (RDS/Aurora)                      |
| Backend          | FastAPI + WebRTC         | ECS Fargate, EC2, or single box to start     |
| GPU (if local)   | Whisper, SpeechT5        | EC2 g-instances, or switch to API-based      |
| CDN              | Serve embed.js           | CloudFront                                   |
| Domain + TLS     | HTTPS                    | Route53 + ACM                                |

## 7. Local Models vs APIs Consideration
- Local models (Whisper, SpeechT5) need GPU instances — expensive, harder to scale
- Consider API-based alternatives as default for hosted agents:
  - STT: Deepgram, AssemblyAI
  - TTS: ElevenLabs, Amazon Polly
- Keep local models as "bring your own infrastructure" option

## 8. Implementation Order
1. **Database + Auth** — Postgres + Firebase Auth
2. **Agent CRUD API** — endpoints to create/update/delete agents per user
3. **Multi-tenant runtime** — load config from DB per agent key instead of single config.yaml
4. **Embed script** — JS widget connecting to backend with agent key
5. **Dashboard UI** — where users manage their agents
6. **Billing/usage tracking** — meter usage per agent
