Files
conversation-history/SquareMCP/Monetization & Security Architecture.md
T

207 lines
7.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Monetization & Security Architecture
Date: 2026-05-12
Status: Design phase
---
## Current Architecture
Hermes is currently **single-tenant**:
- One API key (`MCP_API_KEY`) protects all endpoints
- Platform credentials are stored as **Kubernetes env vars**
- Only the operator (us) can add/remove credentials
- No user signup, no billing, no per-user isolation
This works for a personal tool or internal use, but not for a SaaS product.
---
## Monetization Models
### Option A: SaaS Subscription Tiers
| Tier | Price | Features |
|---|---|---|
| **Free** | $0 | 1 platform, 10 posts/month, basic analytics |
| **Creator** | $19/mo | 3 platforms, unlimited posts, analytics, scheduling |
| **Agency** | $49/mo | All platforms, unlimited posts, team seats, white-label |
| **Enterprise** | Custom | Self-hosted, SLA, dedicated support |
**Pros:** Predictable MRR, easy to implement
**Cons:** Requires billing infrastructure (Stripe), user management, credential isolation
### Option B: Pay-Per-Use
| Action | Price |
|---|---|
| Text post | $0.01 |
| Image post | $0.05 |
| Video post | $0.15 |
| Analytics query | $0.001 |
**Pros:** Scales with usage, no upfront commitment
**Cons:** Harder to predict revenue, requires metering infrastructure
### Option C: API-Key Licensing
Sell API keys with usage limits:
- Developer tier: 1,000 calls/month
- Business tier: 10,000 calls/month
- Unlimited tier: Unlimited calls
**Pros:** Simplest to implement, appeals to developers
**Cons:** Lower revenue ceiling, harder to justify for non-technical users
### Recommendation
**Start with Option A (SaaS tiers)** because:
- Social media managers expect monthly subscriptions
- Easier to explain value vs. per-post pricing
- Natural upsell path from Free → Creator → Agency
---
## User Credential Input Architecture
### Problem
Users need to connect their own social accounts. Currently we store tokens in K8s env vars. For a SaaS, each user needs their own encrypted credential store.
### Solution: OAuth-First + Manual Token Fallback
For platforms that support OAuth (TikTok, Facebook, Instagram, LinkedIn, Twitter/X):
1. User clicks "Connect Platform" in UI
2. Redirected to platform OAuth consent screen
3. Platform redirects back with auth code
4. Hermes exchanges code for access token + refresh token
5. Tokens encrypted and stored in MySQL per-user
For platforms that require manual tokens (Telegram, Discord, WhatsApp, Email):
1. User sees a form: "Paste your Bot Token"
2. Hermes validates the token with a test API call
3. Token encrypted and stored in MySQL
### Credential Storage Schema
```sql
CREATE TABLE user_credentials (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT NOT NULL,
platform VARCHAR(32) NOT NULL, -- 'tiktok', 'facebook', 'discord', etc.
account_name VARCHAR(64) NOT NULL, -- user-defined nickname
credential_type VARCHAR(32), -- 'oauth', 'bot_token', 'api_key'
access_token BLOB NOT NULL, -- AES-encrypted
refresh_token BLOB, -- AES-encrypted (for OAuth)
expires_at TIMESTAMP, -- token expiration
metadata JSON, -- page_id, business_account_id, etc.
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
UNIQUE KEY (user_id, platform, account_name)
);
```
Encryption uses `CREDENTIAL_ENCRYPTION_KEY` (already exists in env vars).
---
## Security Architecture
### Threat Model
| Threat | Impact | Mitigation |
|---|---|---|
| Token theft from DB | High | AES-256 encryption at rest, key in K8s secrets |
| Token theft in transit | High | TLS 1.3 everywhere, no token logging |
| User A accesses User B's accounts | Critical | Row-level security, user_id filtering on every query |
| OAuth redirect hijacking | High | PKCE + state parameter validation |
| API key brute force | Medium | Rate limiting, API key rotation |
| Insider threat (operator) | Medium | Audit logs, least-privilege K8s RBAC |
### Where to Host the Credential UI
**Option 1: Subdomain (`https://settings.squaremcp.com`)**
- Pros: Clean separation, can have different CSP headers, feels like a dedicated admin panel
- Cons: Extra TLS cert management, CORS considerations, more complex routing
**Option 2: Path (`https://squaremcp.com/settings`)**
- Pros: Same domain, simpler routing, single TLS cert
- Cons: Credential UI mixed with marketing site, harder to apply strict security headers
**Option 3: Separate App (`https://app.squaremcp.com`)**
- Pros: Full SPA experience, clear product boundary, can use React/Vue
- Cons: More infrastructure, separate deployment
**Recommendation: Option 3 (`app.squaremcp.com`)**
Reasoning:
- Marketing site (`squaremcp.com`) and product app should be separate
- The app needs auth (login/signup), billing, dashboard — nothing to do with the marketing site
- Can deploy as a separate K8s service with its own scaling and security policies
- Future white-label clients can point their own domain at the app service
### Auth Flow for the App
```
User visits app.squaremcp.com
→ Login/Signup (email + password, or OAuth via Google/GitHub)
→ JWT issued, stored in httpOnly cookie
→ Dashboard loads
→ User clicks "Connect TikTok"
→ Popup to TikKit OAuth
→ Callback to hermes.squaremcp.com/auth/tiktok/callback
→ Token encrypted → stored in MySQL
→ Dashboard refreshes → shows "Connected ✅"
```
### Security Headers for App Subdomain
```
Strict-Transport-Security: max-age=31536000; includeSubDomains
Content-Security-Policy: default-src 'self'; connect-src 'self' https://hermes.squaremcp.com; frame-ancestors 'none'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
```
---
## Implementation Roadmap
### Phase 1: Foundation (2–3 weeks)
- [ ] User table (`users`: id, email, password_hash, plan, created_at)
- [ ] Credential table (schema above)
- [ ] JWT auth middleware (login, signup, logout)
- [ ] Encrypt/decrypt helpers using `CREDENTIAL_ENCRYPTION_KEY`
- [ ] Update all clients to query user credentials from DB instead of env vars
- [ ] Fallback to env vars for backward compatibility (default account)
### Phase 2: OAuth UI (2 weeks)
- [ ] Static app at `app.squaremcp.com` (React/Vue or plain HTML)
- [ ] Login/signup pages
- [ ] Platform connection UI (cards with "Connect" buttons)
- [ ] OAuth callback handling per platform
- [ ] Token refresh logic (background job for expired tokens)
### Phase 3: Billing (2 weeks)
- [ ] Stripe integration
- [ ] Subscription tiers in DB
- [ ] Usage metering (posts per month, API calls)
- [ ] Webhook handlers for payment events
- [ ] Upgrade/downgrade flow
### Phase 4: Team/Agency (3–4 weeks)
- [ ] Organizations table
- [ ] Team member invites
- [ ] Role-based access (admin, editor, viewer)
- [ ] Shared credential pools within organization
---
## Open Questions
1. **Self-hosted option?** Some users may want to run Hermes on their own infra. Should we offer a Docker Compose + license key model?
2. **Data residency?** EU users may require GDPR compliance and EU-based servers.
3. **Token refresh responsibility?** For OAuth platforms, who handles refresh — background cron or lazy refresh on use?
4. **Credential audit?** Should users see a log of when their tokens were accessed/used?