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>
97 lines
2.9 KiB
TypeScript
97 lines
2.9 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
|
|
const { mockRedisSet, mockRedisEval } = vi.hoisted(() => ({
|
|
mockRedisSet: vi.fn(),
|
|
mockRedisEval: vi.fn(),
|
|
}));
|
|
|
|
const { mockQuery } = vi.hoisted(() => ({ mockQuery: vi.fn() }));
|
|
|
|
const { mockGenerateMonthlyInvoice } = vi.hoisted(() => ({
|
|
mockGenerateMonthlyInvoice: vi.fn(),
|
|
}));
|
|
|
|
vi.mock('../redis.js', () => ({
|
|
default: { set: mockRedisSet, eval: mockRedisEval },
|
|
}));
|
|
|
|
vi.mock('../db.js', () => ({
|
|
getPool: () => ({ query: mockQuery }),
|
|
}));
|
|
|
|
vi.mock('./invoices.js', () => ({
|
|
generateMonthlyInvoice: (...args: any[]) => mockGenerateMonthlyInvoice(...args),
|
|
}));
|
|
|
|
import { runInvoiceCron } from './cron.js';
|
|
|
|
const TWO_CUSTOMERS = [[{ id: 'cust-a' }, { id: 'cust-b' }]];
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mockRedisEval.mockResolvedValue(1);
|
|
mockGenerateMonthlyInvoice.mockResolvedValue(null);
|
|
});
|
|
|
|
describe('runInvoiceCron — Redis lock', () => {
|
|
it('runs invoice loop when lock is acquired', async () => {
|
|
mockRedisSet.mockResolvedValue('OK');
|
|
mockQuery.mockResolvedValue(TWO_CUSTOMERS);
|
|
|
|
await runInvoiceCron();
|
|
|
|
expect(mockRedisSet).toHaveBeenCalledWith(
|
|
'invoice:cron:lock',
|
|
expect.any(String),
|
|
{ NX: true, EX: 3600 }
|
|
);
|
|
expect(mockQuery).toHaveBeenCalled();
|
|
});
|
|
|
|
it('skips invoice loop when lock is already held', async () => {
|
|
mockRedisSet.mockResolvedValue(null);
|
|
|
|
await runInvoiceCron();
|
|
|
|
expect(mockQuery).not.toHaveBeenCalled();
|
|
expect(mockGenerateMonthlyInvoice).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('releases lock via compare-delete Lua script after success', async () => {
|
|
mockRedisSet.mockResolvedValue('OK');
|
|
mockQuery.mockResolvedValue([[{ id: 'cust-1' }]]);
|
|
|
|
await runInvoiceCron();
|
|
|
|
expect(mockRedisEval).toHaveBeenCalledWith(
|
|
expect.stringContaining('redis.call("get"'),
|
|
expect.objectContaining({ keys: ['invoice:cron:lock'], arguments: [expect.any(String)] })
|
|
);
|
|
});
|
|
|
|
it('does NOT release lock when the loop throws', async () => {
|
|
mockRedisSet.mockResolvedValue('OK');
|
|
mockQuery.mockRejectedValue(new Error('DB down'));
|
|
|
|
await expect(runInvoiceCron()).rejects.toThrow('DB down');
|
|
expect(mockRedisEval).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('runInvoiceCron — per-customer error isolation', () => {
|
|
it('continues processing remaining customers after one fails', async () => {
|
|
mockRedisSet.mockResolvedValue('OK');
|
|
mockQuery.mockResolvedValue([[{ id: 'cust-a' }, { id: 'cust-b' }, { id: 'cust-c' }]]);
|
|
|
|
mockGenerateMonthlyInvoice
|
|
.mockResolvedValueOnce({ invoice_number: 'SMCP-1', customer_id: 'cust-a' })
|
|
.mockRejectedValueOnce(new Error('Stripe error'))
|
|
.mockResolvedValueOnce({ invoice_number: 'SMCP-3', customer_id: 'cust-c' });
|
|
|
|
await runInvoiceCron();
|
|
|
|
expect(mockGenerateMonthlyInvoice).toHaveBeenCalledTimes(3);
|
|
expect(mockRedisEval).toHaveBeenCalled();
|
|
});
|
|
});
|