feat(saas): SquareMCP v2 — multi-tenant MCP platform complete

Steps 0–10 of the v2 plan, 194 tests passing.

Core infrastructure
- Shared Redis client (src/redis.ts); all four Redis consumers migrated
- Vitest test harness with vitest.config.ts and npm test/test:watch scripts

Billing & invoicing (Steps 1–2)
- Monthly invoice generation with idempotency (MySQL uq_customer_period unique key)
- Cron job with Redis distributed lock (Lua compare-delete, 1-hr TTL)
- Invoice emailer via nodemailer (FETCHERPAY SMTP)
- Billing middleware: checkLimit gate in handleToolCall; platform attribution fix

Email multi-tenancy (Step 3)
- EmailCtx = Account | EmailCredentials; imap.ts + smtp.ts accept both
- resolveEmailCtx helper in tools.ts; all email tools use customer credentials

Analytics + platform health (Steps 4–5)
- Chart.js bar charts for platform breakdown and daily activity
- Token expiry check in getCredential with dynamic import refresh
- platform-health.ts: per-platform health probe with 10-min Redis cache
- GET /api/health/platforms; "Token expired" amber badge in dashboard

Tool schema filtering (Step 6)
- stripAccountParam deep-clones tool schemas; multi-tenant sessions never
  see the internal account enum

OAuth hardening (Step 7)
- Atomic auth code consumption: UPDATE SET used=TRUE, check affectedRows
- customer_id threaded through oauth_auth_codes → oauth_tokens
- getTokenCustomer(); requireAuth resolves req.customer from Bearer token
- Consent page requires authenticated session; redirect_uri validated
  against registered URIs; http://localhost:* loopback wildcard

DCR browser flow (Step 8)
- ensureOAuthAppRegistered() upserts pre-registered SquareMCP OAuth app
  on startup with redirect URIs for mcp-callback, localhost:*, claude-desktop,
  opencode
- GET /oauth/connect-mcp → server-side redirect (client_id off frontend)
- GET /oauth/mcp-callback → exchanges code, renders config snippet page
  with copy buttons for Claude Desktop and Codex CLI

Webhooks (Step 9)
- webhook_url + webhook_secret columns on customers
- deliverWebhook(): HMAC-SHA256 signing, 3× exponential retry (1s/4s/16s),
  Redis DLQ with 7-day TTL on total failure
- isValidWebhookUrl(): SSRF protection (blocks RFC-1918, localhost, .local)
- POST /api/webhooks/config (secret returned once), GET, DELETE
- GET /api/admin/webhooks/dlq/:customerId
- WhatsApp POST route uses express.raw() for raw body preservation
- Dashboard Webhooks tab with secret-once display and copy button

Developer docs (Step 10)
- docs/ static HTML site (GitHub Pages, no build pipeline)
- index.html: landing page with client + platform overview
- getting-started.html: tabbed MCP config for Claude Desktop, Codex CLI, opencode
- platforms.html: LinkedIn, TikTok, WhatsApp, Instagram, Twitter, Telegram guides
- agent-tutorial.html: complete Node.js agent (Anthropic SDK + MCP SDK),
  LinkedIn posting loop, extensions for multi-platform + inbound webhook reaction

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Garfield
2026-05-13 23:43:35 -04:00
parent d4bc899b31
commit 61dab40585
38 changed files with 5042 additions and 238 deletions

View File

@@ -1,8 +1,9 @@
import { Tool } from '@modelcontextprotocol/sdk/types.js';
import type { Customer } from './billing/middleware.js';
import { recordUsage } from './billing/usage.js';
import { searchMessages, readMessage, getProfile, listFolders, type Account } from './imap.js';
import { recordUsage, checkLimit } from './billing/usage.js';
import { searchMessages, readMessage, getProfile, listFolders, type Account, type EmailCtx } from './imap.js';
import { sendEmail, createDraft } from './smtp.js';
import type { EmailCredentials } from './multitenancy/credential-store.js';
import { searchNotes, getNote, appendToNote, updateNote, getSyncStatus } from './clients/obsidian.js';
import { sendMessage, sendTemplate, getMessageStatus, listTemplates } from './clients/whatsapp.js';
import { getProfile as getLinkedInProfile, createPost as createLinkedInPost, createVideoPost as createLinkedInVideoPost, searchConnections, sendMessage as sendLinkedInMessage } from './clients/linkedin.js';
@@ -727,40 +728,81 @@ function acct(args: Record<string, unknown>): Account {
return (args.account as Account) ?? 'yahoo';
}
async function resolveEmailCtx(args: Record<string, unknown>, customer?: Customer): Promise<EmailCtx> {
if (customer) {
const creds = await customer.getCredential<EmailCredentials>('email');
if (creds) return creds;
}
return acct(args);
}
const PLATFORM_PREFIXES = [
'linkedin', 'obsidian', 'whatsapp', 'telegram', 'discord',
'instagram', 'twitter', 'tiktok', 'snapchat', 'facebook',
];
function toolPlatform(name: string): string {
const prefix = name.split('_')[0];
return PLATFORM_PREFIXES.includes(prefix) ? prefix : 'email';
}
export async function handleToolCall(
name: string,
args: Record<string, unknown>,
customer?: Customer
): Promise<{ content: Array<{ type: string; text: string }> }> {
): Promise<{ content: Array<{ type: string; text: string }>; isError?: boolean }> {
console.log(`[tool] ${name}`, JSON.stringify(args));
const t0 = Date.now();
if (customer) {
const { allowed } = await checkLimit(customer.id, customer.plan);
if (!allowed) {
return {
content: [{ type: 'text', text: 'Monthly tool call limit reached. Please upgrade your plan.' }],
isError: true,
};
}
}
try {
let result: unknown;
switch (name) {
case 'get_profile':
result = await getProfile(acct(args));
case 'get_profile': {
const emailCtx = await resolveEmailCtx(args, customer);
result = await getProfile(emailCtx);
break;
}
case 'search_messages':
result = await searchMessages(args.q as string, (args.maxResults as number) ?? 20, acct(args), args.folder as string | undefined);
case 'search_messages': {
const emailCtx = await resolveEmailCtx(args, customer);
result = await searchMessages(args.q as string, (args.maxResults as number) ?? 20, emailCtx, args.folder as string | undefined);
break;
}
case 'read_message':
result = await readMessage(args.uid as number, acct(args), args.folder as string | undefined);
case 'read_message': {
const emailCtx = await resolveEmailCtx(args, customer);
result = await readMessage(args.uid as number, emailCtx, args.folder as string | undefined);
break;
}
case 'list_folders':
result = await listFolders(acct(args));
case 'list_folders': {
const emailCtx = await resolveEmailCtx(args, customer);
result = await listFolders(emailCtx);
break;
}
case 'create_draft':
result = await createDraft(args.to as string, args.subject as string, args.body as string, acct(args));
case 'create_draft': {
const emailCtx = await resolveEmailCtx(args, customer);
result = await createDraft(args.to as string, args.subject as string, args.body as string, emailCtx);
break;
}
case 'send_email':
result = await sendEmail(args.to as string, args.subject as string, args.body as string, acct(args));
case 'send_email': {
const emailCtx = await resolveEmailCtx(args, customer);
result = await sendEmail(args.to as string, args.subject as string, args.body as string, emailCtx);
break;
}
// ── Obsidian ──────────────────────────────────────────────────────────
case 'obsidian_search_notes':
@@ -1126,8 +1168,7 @@ export async function handleToolCall(
console.log(`[tool] ${name} OK (${Date.now() - t0}ms)`);
if (customer) {
const platform = name.split('_')[0];
recordUsage(customer.id, platform, name).catch(() => {});
recordUsage(customer.id, toolPlatform(name), name).catch(() => {});
}
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
@@ -1139,6 +1180,19 @@ export async function handleToolCall(
console.error(stack);
return {
content: [{ type: 'text', text: `Error: ${msg}` }],
isError: true,
};
}
}
export function stripAccountParam(tool: Tool): Tool {
const props = tool.inputSchema.properties ?? {};
const filtered = Object.fromEntries(Object.entries(props).filter(([k]) => k !== 'account'));
return {
...tool,
inputSchema: {
...tool.inputSchema,
properties: filtered as Tool['inputSchema']['properties'],
},
};
}