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>
102 lines
2.8 KiB
TypeScript
102 lines
2.8 KiB
TypeScript
import redis from '../redis.js';
|
|
import { getCredential, WhatsAppCredentials } from './credential-store.js';
|
|
|
|
// Call this at customer onboarding when they connect their WhatsApp Business number
|
|
export async function registerWhatsAppNumber(
|
|
customerId: string,
|
|
phoneNumberId: string
|
|
): Promise<void> {
|
|
await redis.set(`wa_phone_id:${phoneNumberId}`, customerId);
|
|
}
|
|
|
|
export async function unregisterWhatsAppNumber(phoneNumberId: string): Promise<void> {
|
|
await redis.del(`wa_phone_id:${phoneNumberId}`);
|
|
}
|
|
|
|
export async function resolveCustomerFromPhoneNumberId(
|
|
phoneNumberId: string
|
|
): Promise<string | null> {
|
|
return redis.get(`wa_phone_id:${phoneNumberId}`);
|
|
}
|
|
|
|
// WhatsApp Cloud API webhook payload types
|
|
interface WhatsAppWebhookEntry {
|
|
id: string;
|
|
changes: Array<{
|
|
value: {
|
|
messaging_product: string;
|
|
metadata: {
|
|
display_phone_number: string;
|
|
phone_number_id: string;
|
|
};
|
|
messages?: WhatsAppInboundMessage[];
|
|
statuses?: WhatsAppStatus[];
|
|
};
|
|
field: string;
|
|
}>;
|
|
}
|
|
|
|
export interface WhatsAppInboundMessage {
|
|
from: string;
|
|
id: string;
|
|
timestamp: string;
|
|
text?: { body: string };
|
|
type: string;
|
|
}
|
|
|
|
interface WhatsAppStatus {
|
|
id: string;
|
|
status: string;
|
|
timestamp: string;
|
|
recipient_id: string;
|
|
}
|
|
|
|
export interface RoutedWebhookEvent {
|
|
customerId: string;
|
|
phoneNumberId: string;
|
|
message: WhatsAppInboundMessage;
|
|
credentials: WhatsAppCredentials;
|
|
}
|
|
|
|
// Parse the incoming webhook and return one routed event per message
|
|
export async function routeWhatsAppWebhook(
|
|
body: Record<string, unknown>
|
|
): Promise<RoutedWebhookEvent[]> {
|
|
const events: RoutedWebhookEvent[] = [];
|
|
|
|
if (body.object !== 'whatsapp_business_account') return events;
|
|
|
|
const entries = (body.entry as WhatsAppWebhookEntry[]) ?? [];
|
|
|
|
for (const entry of entries) {
|
|
for (const change of entry.changes) {
|
|
if (change.field !== 'messages') continue;
|
|
|
|
const { phone_number_id } = change.value.metadata;
|
|
const messages = change.value.messages ?? [];
|
|
|
|
if (messages.length === 0) continue;
|
|
|
|
// Resolve which customer owns this phone number
|
|
const customerId = await resolveCustomerFromPhoneNumberId(phone_number_id);
|
|
if (!customerId) {
|
|
console.warn(`[webhook-router] Unroutable WhatsApp message to phone_number_id=${phone_number_id}`);
|
|
continue;
|
|
}
|
|
|
|
// Load that customer's WhatsApp credentials
|
|
const credentials = await getCredential<WhatsAppCredentials>(customerId, 'whatsapp');
|
|
if (!credentials) {
|
|
console.error(`[webhook-router] No WhatsApp credentials for customerId=${customerId}`);
|
|
continue;
|
|
}
|
|
|
|
for (const message of messages) {
|
|
events.push({ customerId, phoneNumberId: phone_number_id, message, credentials });
|
|
}
|
|
}
|
|
}
|
|
|
|
return events;
|
|
}
|