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();

View File

@@ -80,7 +80,9 @@
<div class="header-right">
<nav class="header-nav">
<button class="nav-link active" data-view="platforms">Platforms</button>
<button class="nav-link" data-view="analytics">Analytics</button>
<button class="nav-link" data-view="invoices">Invoices</button>
<button class="nav-link" data-view="webhooks">Webhooks</button>
<button class="nav-link hidden" data-view="admin" id="admin-nav">Admin</button>
</nav>
<span id="user-email" class="user-email"></span>
@@ -92,6 +94,7 @@
<section class="welcome">
<h2>Connect your platforms</h2>
<p>Link your social accounts to publish, analyze, and manage content from one place.</p>
<button id="connect-mcp-btn" class="btn btn-primary" style="margin-top:16px;">Connect MCP Client</button>
</section>
<section class="usage-bar" id="usage-bar">
@@ -203,6 +206,24 @@
</div>
</section>
<section class="analytics-section hidden" id="analytics-section">
<h3 class="section-title">Analytics</h3>
<p class="section-subtitle">Tool calls this month, by platform and day</p>
<div class="charts-grid">
<div class="chart-card">
<h4>By platform</h4>
<div class="chart-container"><canvas id="platform-chart"></canvas></div>
</div>
<div class="chart-card">
<h4>Daily activity</h4>
<div class="chart-container"><canvas id="daily-chart"></canvas></div>
</div>
</div>
<div id="analytics-empty" class="analytics-empty hidden">
<p>No activity yet this month. Make your first tool call to see data here.</p>
</div>
</section>
<section class="invoices-section hidden" id="invoices-section">
<h3>Invoices</h3>
<div id="invoices-list" class="invoices-list"></div>
@@ -212,6 +233,29 @@
<h3>Admin Panel</h3>
<div id="admin-customers" class="admin-customers"></div>
</section>
<section class="webhooks-section hidden" id="webhooks-section">
<h3 class="section-title">Webhook</h3>
<p class="section-subtitle">Receive real-time events when messages arrive on your connected platforms.</p>
<div class="webhook-card" id="webhook-card">
<div id="webhook-status-row" class="webhook-status-row">
<span id="webhook-url-display" class="webhook-url-display">No webhook configured</span>
<button id="webhook-delete-btn" class="btn btn-ghost hidden">Remove</button>
</div>
<form id="webhook-form" class="webhook-form">
<input type="url" id="webhook-url-input" placeholder="https://your-server.com/webhook" required>
<button type="submit" class="btn btn-primary">Save &amp; generate secret</button>
</form>
<div id="webhook-secret-box" class="webhook-secret-box hidden">
<p class="webhook-secret-label">Signing secret — copy now, not shown again:</p>
<div class="webhook-secret-value" id="webhook-secret-value"></div>
<button class="btn btn-ghost" onclick="copyWebhookSecret()">Copy secret</button>
</div>
<div class="webhook-instructions">
<p>Verify each request by computing <code>sha256=HMAC-SHA256(secret, rawBody)</code> and comparing to the <code>X-SquareMCP-Signature</code> header.</p>
</div>
</div>
</section>
</main>
</div>
@@ -225,6 +269,7 @@
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script src="app.js"></script>
</body>
</html>

View File

@@ -315,6 +315,11 @@ body {
color: var(--text-secondary);
}
.status-badge.expired {
background: rgba(245, 158, 11, 0.15);
color: #f59e0b;
}
/* Modal */
.modal {
position: fixed;
@@ -601,6 +606,144 @@ body {
font-size: 11px;
}
/* Analytics */
.analytics-section {
margin-top: 24px;
}
.section-title {
font-size: 18px;
margin-bottom: 4px;
}
.section-subtitle {
color: var(--text-secondary);
font-size: 13px;
margin-bottom: 20px;
}
.charts-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
@media (max-width: 700px) {
.charts-grid { grid-template-columns: 1fr; }
}
.chart-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 20px;
}
.chart-card h4 {
font-size: 13px;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 16px;
}
.chart-container {
position: relative;
height: 220px;
}
.analytics-empty {
padding: 40px 20px;
text-align: center;
color: var(--text-secondary);
font-size: 14px;
}
/* Webhooks */
.webhooks-section {
margin-top: 24px;
}
.webhook-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
max-width: 640px;
}
.webhook-status-row {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
.webhook-url-display {
flex: 1;
font-size: 14px;
color: var(--text-secondary);
word-break: break-all;
}
.webhook-form {
display: flex;
gap: 10px;
margin-bottom: 16px;
}
.webhook-form input {
flex: 1;
padding: 10px 14px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
font-size: 14px;
outline: none;
}
.webhook-form input:focus {
border-color: var(--accent);
}
.webhook-secret-box {
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
padding: 14px;
margin-bottom: 16px;
}
.webhook-secret-label {
font-size: 12px;
color: #f59e0b;
margin-bottom: 8px;
}
.webhook-secret-value {
font-family: 'SF Mono', monospace;
font-size: 12px;
word-break: break-all;
margin-bottom: 8px;
color: var(--text);
}
.webhook-instructions {
font-size: 13px;
color: var(--text-secondary);
line-height: 1.6;
}
.webhook-instructions code {
background: #2a2a2b;
padding: 2px 6px;
border-radius: 4px;
font-family: 'SF Mono', monospace;
font-size: 12px;
}
/* Password reset */
.success-msg {
color: var(--accent);