Files
hermes-mcp/src/multitenancy/credential-store.test.ts
Garfield 61dab40585 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>
2026-05-13 23:43:56 -04:00

102 lines
3.9 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
const { mockRedisGet, mockRedisSet, mockRedisDel, mockRedisKeys } = vi.hoisted(() => ({
mockRedisGet: vi.fn(),
mockRedisSet: vi.fn(),
mockRedisDel: vi.fn(),
mockRedisKeys: vi.fn(),
}));
vi.mock('../redis.js', () => ({
default: {
get: mockRedisGet,
set: mockRedisSet,
del: mockRedisDel,
keys: mockRedisKeys,
},
}));
const mockTryRefreshToken = vi.hoisted(() => vi.fn());
vi.mock('./token-refresh.js', () => ({ tryRefreshToken: mockTryRefreshToken }));
// Use a real 32-byte key so AES-256-GCM doesn't throw
process.env.CREDENTIAL_ENCRYPTION_KEY = '0'.repeat(64);
import { getCredential, storeCredential } from './credential-store.js';
function encryptCreds(creds: object): string {
// We can't call encrypt() directly (not exported), so we'll round-trip through storeCredential
// For tests, we'll use a helper approach: just test behavior using storeCredential to set up state.
return JSON.stringify(creds); // placeholder — see note below
}
describe('getCredential', () => {
beforeEach(() => {
vi.clearAllMocks();
mockRedisSet.mockResolvedValue('OK');
});
it('returns null when no credential stored', async () => {
mockRedisGet.mockResolvedValue(null);
const result = await getCredential('cust1', 'linkedin');
expect(result).toBeNull();
});
it('returns credential when not expired', async () => {
// Store then retrieve using real encryption
const creds = { accessToken: 'tok', expiresAt: Date.now() + 3_600_000 };
await storeCredential('cust1', 'linkedin', creds);
const stored = mockRedisSet.mock.calls[0][1] as string;
mockRedisGet.mockResolvedValue(stored);
const result = await getCredential('cust1', 'linkedin');
expect(result).toMatchObject({ accessToken: 'tok' });
expect(mockTryRefreshToken).not.toHaveBeenCalled();
});
it('attempts refresh when token is within 60s of expiry', async () => {
const creds = { accessToken: 'old', refreshToken: 'ref', expiresAt: Date.now() + 30_000 };
await storeCredential('cust1', 'linkedin', creds);
const stored = mockRedisSet.mock.calls[0][1] as string;
mockRedisGet.mockResolvedValue(stored);
mockTryRefreshToken.mockResolvedValue({ accessToken: 'new', expiresAt: Date.now() + 3_600_000 });
const result = await getCredential<{ accessToken: string }>('cust1', 'linkedin');
expect(mockTryRefreshToken).toHaveBeenCalledWith('cust1', 'linkedin', expect.objectContaining({ accessToken: 'old' }));
expect(result?.accessToken).toBe('new');
});
it('returns null when token expired and no refresh token', async () => {
const creds = { accessToken: 'old', expiresAt: Date.now() - 1000 };
await storeCredential('cust1', 'linkedin', creds);
const stored = mockRedisSet.mock.calls[0][1] as string;
mockRedisGet.mockResolvedValue(stored);
const result = await getCredential('cust1', 'linkedin');
expect(result).toBeNull();
expect(mockTryRefreshToken).not.toHaveBeenCalled();
});
it('returns null when refresh fails', async () => {
const creds = { accessToken: 'old', refreshToken: 'ref', expiresAt: Date.now() - 1000 };
await storeCredential('cust1', 'linkedin', creds);
const stored = mockRedisSet.mock.calls[0][1] as string;
mockRedisGet.mockResolvedValue(stored);
mockTryRefreshToken.mockResolvedValue(null);
const result = await getCredential('cust1', 'linkedin');
expect(result).toBeNull();
});
it('returns non-OAuth credentials without expiry check', async () => {
const creds = { host: 'imap.gmail.com', port: 993, user: 'u', password: 'p' };
await storeCredential('cust1', 'email', creds);
const stored = mockRedisSet.mock.calls[0][1] as string;
mockRedisGet.mockResolvedValue(stored);
const result = await getCredential('cust1', 'email');
expect(result).toMatchObject({ host: 'imap.gmail.com' });
expect(mockTryRefreshToken).not.toHaveBeenCalled();
});
});