Files

349 lines
16 KiB
Markdown
Raw Permalink 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.
# SquareMCP / Hermes MCP — Dev Log
## 2026-05-14 — OAuth Login Fix (claude.ai Connection)
### Problem
Users connecting claude.ai to hermes.squaremcp.com via the MCP Servers panel could not complete the OAuth flow. The popup would either show "Cannot GET /login" (early state) or loop back to the dashboard at app.squaremcp.com.
### Root cause: browser cookie partitioning (CHIPS)
Browser partitioning (Cookies Having Independent Partitioned State) treats cookies differently depending on which site is the top-level context:
- Cookie set via a fetch from `app.squaremcp.com` is bound to the `app.squaremcp.com` top-level partition
- When a popup navigates to `hermes.squaremcp.com`, that cookie is NOT visible — the top-level context changed
- The old flow sent users to `app.squaremcp.com` to log in, then tried to redirect back to `hermes.squaremcp.com/oauth/authorize`. Because the cookie was partitioned to the app domain, hermes never saw it — bounce loop.
### Fix
Added a native login page at `hermes.squaremcp.com/login`:
- `GET /login` — serves a minimal HTML login form, carries `return_to` as a hidden field
- `POST /login` — validates email+password, sets session cookie in **first-party context** on hermes.squaremcp.com, then redirects to `return_to`
- Both redirects in `GET /oauth/authorize` changed from `app.squaremcp.com/?return_to=...` to `/login?return_to=...`
Because the cookie is now set when `hermes.squaremcp.com` IS the first-party context (the popup is open on hermes), it is visible for all subsequent navigations within the same popup.
### Side fix
`findCustomerByEmail`, `findCustomerById`, and `findCustomerByResetToken` in `src/auth.ts` were not selecting the `role` column. Added `role` to all three SELECT queries and to the `CustomerRow` interface.
### Files changed
- `src/index.ts` — added `GET /login`, `POST /login` routes; changed two redirects in `GET /oauth/authorize`
- `src/auth.ts` — added `role` to `CustomerRow` interface and all three SELECT queries
### Verified working
1. claude.ai → Settings → MCP Servers → `https://hermes.squaremcp.com` → Connect
2. Popup opens to `hermes.squaremcp.com/login`
3. Enter SquareMCP credentials → cookie set first-party → redirect to consent page
4. Click "Connect MCP client" → popup closes → claude.ai shows Connected
---
## 2026-05-13 — Full SaaS Implementation Complete
### Built
**1. Database schema additions**
- `customers.role` (ENUM: user/admin)
- `customers.reset_token` + `customers.reset_expires_at`
- `usage_logs` table (customer_id, platform, action, created_at)
- `invoices` table (invoice_number, amount, status, period_start/end, line_items)
**2. Auth system**
- `src/auth.ts` — bcrypt password hashing, JWT sign/verify, reset token management
- `POST /api/auth/signup` — auto-promotes first user to admin/enterprise
- `POST /api/auth/login` — returns JWT cookie + API key
- `POST /api/auth/logout` — clears cookie
- `GET /api/auth/me` — returns current user
- `POST /api/auth/forgot-password` — generates reset token
- `POST /api/auth/reset-password` — updates password with token
**3. Usage tracking**
- `src/billing/usage.ts` — recordUsage, getMonthlyUsage, getUsageBreakdown, checkLimit
- Integrated into `handleToolCall` — records usage on successful tool calls per customer
- `GET /api/usage` — returns plan, limit, used, remaining, breakdown
**4. Invoice system**
- `src/billing/invoices.ts` — createInvoice, getCustomerInvoices, generateMonthlyInvoice
- Invoices based on actual usage_logs data ($0.05 per action)
- `GET /api/invoices` — list user's invoices
- `GET /api/invoices/:number` — get specific invoice
**5. Admin panel**
- `GET /api/admin/customers` — list all customers
- `GET /api/admin/customers/:id/usage` — view customer usage breakdown
- `POST /api/admin/customers/:id/invoice` — generate monthly invoice
- `POST /api/admin/invoices/:number/send` — mark sent
- `POST /api/admin/invoices/:number/pay` — mark paid
- Global API key = superadmin bypass
**6. Unified auth middleware**
- `requireAuth` accepts: global API key → customer API key → OAuth Bearer → JWT cookie
- `meterMiddleware` accepts: API key OR JWT cookie
- `callTool(req, ...)` wrapper passes customer to handleToolCall for usage tracking
**7. Web app UI**
- `https://app.squaremcp.com` — full SPA
- Login/signup with tab switcher
- Password reset flow (forgot → email → reset form)
- Dashboard with usage bar (plan badge, progress, limits)
- 9 platform connection cards with status badges
- Connection modals per platform (OAuth links or token input forms)
- Invoices section
- Admin panel (customer table, generate invoice buttons)
- Navigation: Platforms / Invoices / Admin
### Files changed
- `src/db.ts` — schema updates
- `src/auth.ts` — new file
- `src/billing/middleware.ts` — JWT cookie support, exported resolve functions
- `src/billing/usage.ts` — new file
- `src/billing/invoices.ts` — new file
- `src/tools.ts` — usage tracking integration
- `src/index.ts` — all new endpoints, callTool wrapper, requireAdmin
- `product/app/*` — web app (HTML, CSS, JS, Dockerfile, K8s)
### What's working
- ✅ Signup/login with JWT cookies
- ✅ Per-user encrypted credential storage
- ✅ Platform connection via web UI
- ✅ API calls with personal API key use stored credentials
- ✅ Usage tracking on successful tool calls
- ✅ Monthly usage limits per plan
- ✅ Invoice generation from usage data
- ✅ Password reset flow
- ✅ Admin panel with customer management
### Next / pending
- Email sending for password reset (currently returns token in response)
- Payment collection for invoices (manual process for now)
- Webhook for invoice status updates
---
## 2026-05-12 — TikTok End-to-End Working
### Fixed
1. **URL verification** — added `tiktokIIxGZsCAoYNJVObSA8cYj8FyWrAu1nIW.txt` and `tiktokwJMUoUxgRBFO9T8p08qlMgtsez0Ktr9y.txt` to site root; rebuilt and deployed squaremcp-site
2. **Token resolution** — `resolveToken()` now falls back to `TIKTOK_DEFAULT_ACCESS_TOKEN` when account-specific env var is missing
3. **Sandbox privacy** — unaudited apps MUST use `SELF_ONLY`; `createVideo()` now prefers `SELF_ONLY` when `PUBLIC_TO_EVERYONE` unavailable
### Verified working
- `GET /api/tiktok/profile` → returns profile + stats
- `GET /api/tiktok/creator-info` → returns privacy options, duet/stitch settings
- `POST /api/tiktok/video` → returns `publish_id`
- `POST /api/tiktok/video/status` → returns `PUBLISH_COMPLETE`
### Demo video
- `product/site/tiktok-demo-video.mp4` — 2:36, 1.2 MB, 1280×800 MP4
- Recorded with Playwright showing chat UI flow: connect → profile → creator info → publish → status
### Files changed
- `src/clients/tiktok.ts` — token fallback + SELF_ONLY privacy fix
- `product/site/Dockerfile` — added verification file COPY lines
- `product/site/squaremcp-k8s-ingress.yaml` — updated digest
- `hermes-k8s.yaml` — updated digest
### Submission ready
- Review description: written
- App description: `AI gateway for TikTok: connect your account, view analytics, and publish videos from chat.`
- Demo video: recorded
- URLs verified: tiktok.squaremcp.com, squaremcp.com
---
## 2026-05-12 — Facebook Integration Verified
### Fixed
- **Facebook `getPosts()` endpoint** — changed from `/{pageId}/feed` to `/{pageId}/published_posts` because GET `/feed` requires `pages_read_engagement` permission that fails even when granted. POST to `/feed` works for publishing. `/published_posts` works for reading.
### Credentials added to K8s
```bash
microk8s kubectl set env deployment/hermes-mcp -n fetcherpay \
FACEBOOK_DEFAULT_ACCESS_TOKEN="..." \
FACEBOOK_DEFAULT_PAGE_ID="1152192567968569"
```
### Verified working (all via Hermes API)
| Endpoint | Status | Result |
|---|---|---|
| `GET /api/facebook/page` | ✅ | Returns Squaremcp page info |
| `GET /api/facebook/posts` | ✅ | Returns published posts |
| `POST /api/facebook/post` | ✅ | `post_id` returned |
| `POST /api/facebook/photo` | ✅ | `photo_id` + `post_id` returned (JPG/PNG only) |
| `POST /api/facebook/video` | ✅ | `video_id` + `post_id` returned |
### Notes
- Photo posts reject SVG; Facebook requires JPG, PNG, GIF, TIFF, HEIF, or WebP
- Page: "Squaremcp" (ID: 1152192567968569), Category: Business service
### Still missing credentials
- **Instagram**: needs `INSTAGRAM_DEFAULT_ACCESS_TOKEN` + `INSTAGRAM_DEFAULT_BUSINESS_ACCOUNT_ID`
- **Discord**: needs `DISCORD_DEFAULT_BOT_TOKEN`
---
## 2026-05-12 — SaaS Auth Foundation Built
### Added
- `src/auth.ts` — password hashing (bcrypt), JWT sign/verify, customer lookup
- `password_hash` column to `customers` table (with `ensureColumn` migration)
- `cookie-parser` middleware
- Auth endpoints:
- `POST /api/auth/signup` — creates customer, returns JWT cookie + api_key
- `POST /api/auth/login` — validates password, returns JWT cookie
- `POST /api/auth/logout` — clears session cookie
- `GET /api/auth/me` — returns current user from JWT
### Updated
- `requireAuth` now accepts 3 auth methods:
1. `x-api-key` header (backward compat)
2. OAuth Bearer token
3. `session` JWT cookie (new — for web app)
### Verified
```bash
# Signup ✅
curl -X POST https://hermes.squaremcp.com/api/auth/signup \
-d '{"email":"test@example.com","password":"testpass123"}'
# → { id, email, plan: "free", api_key }
# Login ✅
curl -X POST https://hermes.squaremcp.com/api/auth/login \
-d '{"email":"test@example.com","password":"testpass123"}' \
-c cookies.txt
# Me ✅
curl https://hermes.squaremcp.com/api/auth/me -b cookies.txt
# → { id, email, plan }
```
---
## 2026-05-12 — Web App UI Deployed
### Built
- `product/app/index.html` — SPA shell (login + dashboard)
- `product/app/styles.css` — dark theme, responsive grid
- `product/app/app.js` — auth, platform cards, connection modals
- `product/app/Dockerfile` + `nginx-app.conf` — nginx container
- `product/app/app-k8s.yaml` — K8s deployment + ingress
### Features
- Login / Signup tabs with form validation
- JWT session cookies (auto-login on refresh)
- Dashboard with 9 platform cards (TikTok, Facebook, Instagram, LinkedIn, Twitter, Telegram, Discord, WhatsApp, Email)
- Connection modal per platform:
- OAuth platforms: redirect link (TikTok)
- Token platforms: form with fields + instructions
- Logout clears session
### Deployed
- URL: `https://app.squaremcp.com`
- TLS: auto-provisioned via cert-manager (squaremcp-app-tls)
- K8s: `squaremcp-app` deployment in `fetcherpay` namespace
---
## 2026-05-12 — Per-User Credentials Working End-to-End
### Problem
`requireAuth` only checked the global `API_KEY` env var. Customer API keys and JWT cookies worked for `/api/connect/*` (meterMiddleware) but not for REST social endpoints like `/api/facebook/page`.
### Fixed
- Exported `resolveCustomerByApiKey` and `resolveCustomerById` from `billing/middleware.ts`
- Updated `requireAuth` to check 4 auth methods in order:
1. Global API key (backward compat)
2. Customer API key (resolves Customer, attaches to req.customer)
3. OAuth Bearer token
4. JWT session cookie (resolves Customer, attaches to req.customer + req.jwtUser)
---
## 2026-05-03 — Session Notes
### What was done (committed prior to this session)
- **Multi-account email** — 7 accounts (yahoo, fetcherpay, garfield, sales, leads, founder, gmail) with IMAP/SMTP
- **Obsidian vault integration** — search, read, append, update notes + sync status via Syncthing
- **OAuth 2.0 + DCR** — `/oauth/authorize`, `/oauth/token`, `/oauth/register`, RFC 8414 discovery
- **Streamable HTTP + SSE** transports, ChatGPT MCP proxy routes, pilot request endpoint
- **Product assets** — SquareMCP site, video render script, animaGen
### WhatsApp Business (Meta Cloud API)
#### New file: `src/clients/whatsapp.ts`
WhatsApp Business API client via Meta Cloud API (`graph.facebook.com/v18.0`):
- `sendMessage()` — send freeform text messages (24-hour window only)
- `sendTemplate()` — send approved template messages (works outside window)
- `listTemplates()` — list approved templates from business account
#### Product constraints
`whatsapp_send_message` (freeform text) only works when the recipient has messaged you within the last 24 hours. Outside that window, Meta rejects free-form messages — only approved templates can be sent via `whatsapp_send_template`.
---
## 2026-05-14 — Slack Lead Alerts (Phase 1)
### What was built
Added real-time Slack notifications for pilot intake form submissions.
**New files:**
- `src/notifications/slack.ts` — Slack Incoming Webhook integration with rich block formatting (header, fields, context)
- `src/notifications/index.ts` — Notification dispatcher with test-submission filtering
**Modified files:**
- `src/index.ts` — Wired `notifyNewPilotRequest()` into `POST /api/pilot-request` as fire-and-forget after vault save
- `hermes-k8s.yaml` — Added `SLACK_PILOT_WEBHOOK_URL` env var
- `.gitignore` — Added `.playwright-mcp/`
**Test filtering:**
Skips alerts for test submissions matching:
- Email: `@example.com`
- Name: `E2E`, `Smoke Test`, `QA Test`, `Browser Test`
- Company: `QA Check`, `QA Corp`, `SquareMCP` + test keywords
**Deployment:**
- Built new image: `localhost:32000/hermes-mcp@sha256:3bbf6e0e3e9082ed40106759946e45e1a60a2e3b775aa7d8a2a0cd132d21e641`
- Applied K8s deployment rollout
- Commit: `1742a2f`
**Status:**
- ✅ Code deployed and running
- ⏳ Awaiting Slack webhook URL to activate (user needs to create Slack app + Incoming Webhook)
- 🔮 Phase 2 (WhatsApp template alerts) queued for after Meta Business Manager template approval
---
## 2026-05-15 — Slack Platform + Chat Widget
### What was built
**Slack as a customer-facing messaging platform:**
- `src/clients/slack.ts` — Slack Bot API client (auth.test, conversations.list, chat.postMessage, conversations.history). Multi-tenant: reads credentials from dashboard or falls back to `SLACK_{ACCOUNT}_BOT_TOKEN` env var
- `src/multitenancy/credential-store.ts` — added `'slack'` to Platform type
- `src/tools.ts` — 4 new MCP tools: `slack_get_me`, `slack_get_channels`, `slack_send_message`, `slack_get_messages`. Added `'slack'` to PLATFORM_PREFIXES
- `product/app/index.html` — Slack platform card in dashboard (purple #4a154b, between Discord and Email)
- `product/app/app.js` — Slack connect modal config (Bot Token + Default Channel ID), analytics color
**Chat support widget (Claude-powered FAQ bot):**
- `src/chat.ts` — Claude Haiku handler with SquareMCP system prompt. Public `/api/chat` endpoint (POST, messages array → reply)
- `product/chat-widget.js` — Vanilla JS chat bubble, brand purple (#6c47ff), fixed bottom-right, conversation history per session, served as static file at `https://hermes.squaremcp.com/chat-widget.js`
- Injected into: all 4 docs pages, `product/site/index.html`, `product/app/index.html`
- `ANTHROPIC_API_KEY` set in `.env`
**Deployment:**
- Image: `localhost:32000/hermes-mcp@sha256:8fb8020a57ee8cbd16351d5efbd6acffd6044b55b0fa47f72e2d729d791abaa9`
- Rolled out cleanly, health check passed, tool count: 55
**Upgraded same session to Option B — live agentic demo bot:**
- `src/chat.ts` rewritten as a full Claude tool-use agentic loop (max 5 iterations)
- Exposes 9 demo tools: `slack_get_me/channels/send_message/get_messages`, `discord_get_me/guilds/send_message`, `telegram_get_me/send_message`
- Uses env-var credentials (no customer auth) — `SLACK_DEFAULT_BOT_TOKEN`, `DISCORD_DEFAULT_BOT_TOKEN`, `TELEGRAM_DEFAULT_BOT_TOKEN`
- Telegram is already set in K8s → works immediately. Slack + Discord need env vars added to deployment
- Widget shows purple **⚡ Live: tool_name** pill when agent calls a real platform
- Image: `localhost:32000/hermes-mcp@sha256:b8a71ead85f178dfd30d2cfa0378c1c754dfa713727be08dd0dcc549b0d71d4f`
- Commits: `4bf93d6`, `be1a14f`
---
## Context Note — gstack Skills Available
Saved for reference. gstack skills installed at `~/gstack/`.
Key skills: /context-save, /context-restore, /scrape, /qa, /qa-only, /investigate, /review, /ship, /land-and-deploy, /autoplan, /plan-ceo-review, /plan-eng-review, /plan-design-review, /design-consultation, /design-review, /office-hours, /skillify.
Invoke by name — I read the SKILL.md and follow the workflow manually.