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,5 +1,6 @@
import nodemailer from 'nodemailer';
import type { Account } from './imap.js';
import type { Account, EmailCtx } from './imap.js';
import type { EmailCredentials } from './multitenancy/credential-store.js';
const FETCHERPAY_SMTP_HOST = process.env['FETCHERPAY_SMTP_HOST'] ?? 'mail.fetcherpay.com';
const FETCHERPAY_SMTP_PORT = parseInt(process.env['FETCHERPAY_SMTP_PORT'] ?? '30587');
@@ -8,13 +9,13 @@ function fetcherpaySmtpTransport(user: string, pass: string) {
return nodemailer.createTransport({
host: FETCHERPAY_SMTP_HOST,
port: FETCHERPAY_SMTP_PORT,
secure: false, // STARTTLS
secure: false,
auth: { user, pass },
tls: { rejectUnauthorized: false },
});
}
function getSmtpTransport(account: Account = 'yahoo') {
function getEnvSmtpTransport(account: Account = 'yahoo') {
switch (account) {
case 'fetcherpay':
return fetcherpaySmtpTransport(process.env['FETCHERPAY_EMAIL']!, process.env['FETCHERPAY_PASSWORD']!);
@@ -31,25 +32,33 @@ function getSmtpTransport(account: Account = 'yahoo') {
host: 'smtp.gmail.com',
port: 587,
secure: false,
auth: {
user: process.env['GMAIL_EMAIL']!,
pass: process.env['GMAIL_APP_PASSWORD']!,
},
auth: { user: process.env['GMAIL_EMAIL']!, pass: process.env['GMAIL_APP_PASSWORD']! },
});
default:
return nodemailer.createTransport({
host: 'smtp.mail.yahoo.com',
port: 587,
secure: false,
auth: {
user: process.env['YAHOO_EMAIL']!,
pass: process.env['YAHOO_APP_PASSWORD']!,
},
auth: { user: process.env['YAHOO_EMAIL']!, pass: process.env['YAHOO_APP_PASSWORD']! },
});
}
}
function getSenderEmail(account: Account = 'yahoo'): string {
function resolveSmtpTransport(ctx: EmailCtx) {
if (typeof ctx === 'object') {
return nodemailer.createTransport({
host: ctx.smtpHost ?? ctx.host,
port: ctx.smtpPort ?? 587,
secure: false,
auth: { user: ctx.user, pass: ctx.password },
tls: { rejectUnauthorized: false },
});
}
return getEnvSmtpTransport(ctx);
}
function resolveSenderEmail(ctx: EmailCtx): string {
if (typeof ctx === 'object') return ctx.user;
const emailMap: Record<Account, string> = {
yahoo: process.env['YAHOO_EMAIL'] ?? '',
fetcherpay: process.env['FETCHERPAY_EMAIL'] ?? '',
@@ -59,18 +68,18 @@ function getSenderEmail(account: Account = 'yahoo'): string {
founder: process.env['FOUNDER_EMAIL'] ?? '',
gmail: process.env['GMAIL_EMAIL'] ?? '',
};
return emailMap[account] ?? '';
return emailMap[ctx] ?? '';
}
export async function sendEmail(
to: string,
subject: string,
body: string,
account: Account = 'yahoo',
ctx: EmailCtx = 'yahoo',
): Promise<string> {
const transporter = getSmtpTransport(account);
const transporter = resolveSmtpTransport(ctx);
const info = await transporter.sendMail({
from: getSenderEmail(account),
from: resolveSenderEmail(ctx),
to,
subject,
text: body,
@@ -82,52 +91,52 @@ export async function createDraft(
to: string,
subject: string,
body: string,
account: Account = 'yahoo',
ctx: EmailCtx = 'yahoo',
): Promise<string> {
const { ImapFlow } = await import('imapflow');
const fetcherpayImapBase = {
host: process.env['FETCHERPAY_IMAP_HOST'] ?? 'mail.fetcherpay.com',
port: parseInt(process.env['FETCHERPAY_IMAP_PORT'] ?? '30993'),
secure: true,
tls: { rejectUnauthorized: false },
};
const fetcherpayImapAccounts: Partial<Record<Account, { user: string; pass: string }>> = {
fetcherpay: { user: process.env['FETCHERPAY_EMAIL']!, pass: process.env['FETCHERPAY_PASSWORD']! },
garfield: { user: process.env['GARFIELD_EMAIL']!, pass: process.env['GARFIELD_PASSWORD']! },
sales: { user: process.env['SALES_EMAIL']!, pass: process.env['SALES_PASSWORD']! },
leads: { user: process.env['LEADS_EMAIL']!, pass: process.env['LEADS_PASSWORD']! },
founder: { user: process.env['FOUNDER_EMAIL']!, pass: process.env['FOUNDER_PASSWORD']! },
};
let imapConfig;
if (fetcherpayImapAccounts[account]) {
imapConfig = { ...fetcherpayImapBase, auth: fetcherpayImapAccounts[account]! };
} else if (account === 'gmail') {
let imapConfig: any;
if (typeof ctx === 'object') {
imapConfig = {
host: 'imap.gmail.com',
port: 993,
secure: true,
auth: {
user: process.env['GMAIL_EMAIL']!,
pass: process.env['GMAIL_APP_PASSWORD']!,
},
host: ctx.host,
port: ctx.port,
secure: ctx.port === 993,
auth: { user: ctx.user, pass: ctx.password },
tls: { rejectUnauthorized: false },
};
} else {
imapConfig = {
host: 'imap.mail.yahoo.com',
port: 993,
const fetcherpayImapBase = {
host: process.env['FETCHERPAY_IMAP_HOST'] ?? 'mail.fetcherpay.com',
port: parseInt(process.env['FETCHERPAY_IMAP_PORT'] ?? '30993'),
secure: true,
auth: {
user: process.env['YAHOO_EMAIL']!,
pass: process.env['YAHOO_APP_PASSWORD']!,
},
tls: { rejectUnauthorized: false },
};
const fetcherpayAccounts: Partial<Record<Account, { user: string; pass: string }>> = {
fetcherpay: { user: process.env['FETCHERPAY_EMAIL']!, pass: process.env['FETCHERPAY_PASSWORD']! },
garfield: { user: process.env['GARFIELD_EMAIL']!, pass: process.env['GARFIELD_PASSWORD']! },
sales: { user: process.env['SALES_EMAIL']!, pass: process.env['SALES_PASSWORD']! },
leads: { user: process.env['LEADS_EMAIL']!, pass: process.env['LEADS_PASSWORD']! },
founder: { user: process.env['FOUNDER_EMAIL']!, pass: process.env['FOUNDER_PASSWORD']! },
};
if (fetcherpayAccounts[ctx]) {
imapConfig = { ...fetcherpayImapBase, auth: fetcherpayAccounts[ctx]! };
} else if (ctx === 'gmail') {
imapConfig = {
host: 'imap.gmail.com', port: 993, secure: true,
auth: { user: process.env['GMAIL_EMAIL']!, pass: process.env['GMAIL_APP_PASSWORD']! },
};
} else {
imapConfig = {
host: 'imap.mail.yahoo.com', port: 993, secure: true,
auth: { user: process.env['YAHOO_EMAIL']!, pass: process.env['YAHOO_APP_PASSWORD']! },
};
}
}
const client = new ImapFlow(imapConfig);
await client.connect();
const from = getSenderEmail(account);
const from = resolveSenderEmail(ctx);
const rawMessage = [
`From: ${from}`,
`To: ${to}`,