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

@@ -24,10 +24,14 @@ const modalClose = document.querySelector('.modal-close');
const modalBackdrop = document.querySelector('.modal-backdrop');
const navLinks = document.querySelectorAll('.nav-link');
const platformGrid = document.querySelector('.platform-grid');
const analyticsSection = document.getElementById('analytics-section');
const invoicesSection = document.getElementById('invoices-section');
const adminSection = document.getElementById('admin-section');
const adminNav = document.getElementById('admin-nav');
let platformChartInstance = null;
let dailyChartInstance = null;
// Platform config
const PLATFORM_CONFIG = {
tiktok: {
@@ -178,8 +182,14 @@ navLinks.forEach(link => {
platformGrid.classList.toggle('hidden', view !== 'platforms');
document.querySelector('.welcome').classList.toggle('hidden', view !== 'platforms');
document.querySelector('.usage-bar').classList.toggle('hidden', view !== 'platforms');
analyticsSection.classList.toggle('hidden', view !== 'analytics');
invoicesSection.classList.toggle('hidden', view !== 'invoices');
adminSection.classList.toggle('hidden', view !== 'admin');
document.getElementById('webhooks-section').classList.toggle('hidden', view !== 'webhooks');
if (view === 'analytics') loadAnalytics();
if (view === 'invoices') loadInvoices();
if (view === 'admin') loadAdminPanel();
if (view === 'webhooks') loadWebhookConfig();
});
});
@@ -227,6 +237,11 @@ logoutBtn.addEventListener('click', async () => {
showLogin();
});
// Connect MCP Client — start the browser OAuth flow
document.getElementById('connect-mcp-btn')?.addEventListener('click', () => {
window.open(`${API_BASE}/oauth/connect-mcp`, '_blank', 'width=560,height=600,noopener');
});
// Password reset request
resetRequestForm?.addEventListener('submit', async (e) => {
e.preventDefault();
@@ -291,21 +306,35 @@ loginForm.appendChild(forgotLink);
// Connection status
async function updateConnectionStatus() {
try {
const data = await apiGet('/api/connections');
const connections = data.connections || {};
const [connData, healthData] = await Promise.all([
apiGet('/api/connections').catch(() => ({ connections: {} })),
apiGet('/api/health/platforms').catch(() => ({ health: [] })),
]);
const connections = connData.connections || {};
const healthMap = {};
(healthData.health || []).forEach(h => { healthMap[h.platform] = h.status; });
document.querySelectorAll('.platform-card').forEach(card => {
const platform = card.dataset.platform;
const badge = card.querySelector('.status-badge');
const btn = card.querySelector('.btn-connect');
if (connections[platform]) {
const health = healthMap[platform];
if (health === 'healthy') {
badge.textContent = 'Connected';
badge.classList.remove('disconnected');
badge.classList.add('connected');
badge.className = 'status-badge connected';
btn.textContent = 'Manage';
} else if (health === 'expired') {
badge.textContent = 'Token expired';
badge.className = 'status-badge expired';
btn.textContent = 'Reconnect';
} else if (connections[platform]) {
badge.textContent = 'Connected';
badge.className = 'status-badge connected';
btn.textContent = 'Manage';
} else {
badge.textContent = 'Not connected';
badge.classList.remove('connected');
badge.classList.add('disconnected');
badge.className = 'status-badge disconnected';
btn.textContent = 'Connect';
}
});
@@ -364,6 +393,93 @@ async function loadInvoices() {
}
}
// Analytics
const PLATFORM_COLORS = {
email: '#ea4335', linkedin: '#0a66c2', twitter: '#000000',
instagram: '#e1306c', facebook: '#1877f2', tiktok: '#010101',
whatsapp: '#25d366', telegram: '#0088cc', discord: '#5865f2',
snapchat: '#fffc00', obsidian: '#7c3aed',
};
async function loadAnalytics() {
const emptyEl = document.getElementById('analytics-empty');
try {
const [usageData, dailyData] = await Promise.all([
apiGet('/api/usage'),
apiGet('/api/usage/daily'),
]);
const breakdown = usageData.breakdown || {};
const daily = dailyData.daily || [];
const hasData = Object.keys(breakdown).length > 0 || daily.length > 0;
emptyEl.classList.toggle('hidden', hasData);
document.querySelector('.charts-grid').classList.toggle('hidden', !hasData);
if (!hasData) return;
// Platform breakdown chart
const platformLabels = Object.keys(breakdown);
const platformCounts = platformLabels.map(p => breakdown[p]);
const platformColors = platformLabels.map(p => PLATFORM_COLORS[p] || '#888');
if (platformChartInstance) platformChartInstance.destroy();
platformChartInstance = new Chart(document.getElementById('platform-chart'), {
type: 'bar',
data: {
labels: platformLabels,
datasets: [{
label: 'Calls',
data: platformCounts,
backgroundColor: platformColors,
borderRadius: 6,
}],
},
options: {
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
x: { ticks: { color: '#888' }, grid: { color: '#2a2a2b' } },
y: { ticks: { color: '#e5e5e5' }, grid: { display: false } },
},
},
});
// Daily activity chart
const dailyLabels = daily.map(d => d.date);
const dailyCounts = daily.map(d => Number(d.count));
if (dailyChartInstance) dailyChartInstance.destroy();
dailyChartInstance = new Chart(document.getElementById('daily-chart'), {
type: 'bar',
data: {
labels: dailyLabels,
datasets: [{
label: 'Calls',
data: dailyCounts,
backgroundColor: '#10a37f',
borderRadius: 4,
}],
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
x: { ticks: { color: '#888', maxRotation: 45 }, grid: { color: '#2a2a2b' } },
y: { ticks: { color: '#888' }, grid: { color: '#2a2a2b' }, beginAtZero: true },
},
},
});
} catch {
emptyEl.classList.remove('hidden');
emptyEl.querySelector('p').textContent = 'Failed to load analytics.';
document.querySelector('.charts-grid').classList.add('hidden');
}
}
// Admin panel
async function loadAdminPanel() {
try {
@@ -528,5 +644,51 @@ async function checkSession() {
}
}
// Webhook config
async function loadWebhookConfig() {
try {
const data = await apiGet('/api/webhooks/config');
const display = document.getElementById('webhook-url-display');
const deleteBtn = document.getElementById('webhook-delete-btn');
const input = document.getElementById('webhook-url-input');
if (data.webhookUrl) {
display.textContent = data.webhookUrl;
deleteBtn.classList.remove('hidden');
input.value = data.webhookUrl;
} else {
display.textContent = 'No webhook configured';
deleteBtn.classList.add('hidden');
input.value = '';
}
document.getElementById('webhook-secret-box').classList.add('hidden');
} catch {
// ignore
}
}
document.getElementById('webhook-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const url = document.getElementById('webhook-url-input').value.trim();
const data = await apiPost('/api/webhooks/config', { webhook_url: url });
if (data.error) { alert(data.error); return; }
document.getElementById('webhook-url-display').textContent = data.webhookUrl;
document.getElementById('webhook-delete-btn').classList.remove('hidden');
if (data.webhookSecret) {
document.getElementById('webhook-secret-value').textContent = data.webhookSecret;
document.getElementById('webhook-secret-box').classList.remove('hidden');
}
});
document.getElementById('webhook-delete-btn')?.addEventListener('click', async () => {
if (!confirm('Remove webhook? This cannot be undone.')) return;
await fetch(`${API_BASE}/api/webhooks/config`, { method: 'DELETE', credentials: 'include' });
loadWebhookConfig();
});
window.copyWebhookSecret = () => {
const val = document.getElementById('webhook-secret-value').textContent;
navigator.clipboard.writeText(val).then(() => alert('Secret copied!'));
};
// Init
checkSession();