5.5 KiB
source, generated, branch
| source | generated | branch |
|---|---|---|
| gstack /plan-eng-review | 2026-05-13 | main |
Eng Review: Test Plan
Generated by /plan-eng-review on 2026-05-13 Branch: main | Repo: garfield/hermes-mcp
Framework
Vitest (ESM-compatible). npm install -D vitest @types/vitest
Scripts: "test": "vitest run", "test:watch": "vitest"
Mock strategy:
vi.mock('../db.js')→ mockgetPool()to return a fake poolvi.mock('../redis.js')→ mock Redis client methodsvi.mock('nodemailer')→ mock createTransport for emailInvoice testsvi.hoisted(() => ({ mockFn: vi.fn() }))pattern for mocks referenced before module init
Test Files (all implemented)
src/tools.test.ts— plan limit gate, platform attribution, error handling, stripAccountParamsrc/oauth.test.ts— isValidRedirectUri, createAuthCode, exchangeCodeForToken, getTokenCustomer, validateAccessTokensrc/oauth-dcr.test.ts— ensureOAuthAppRegistered SQL shape, all DCR redirect URI casessrc/webhooks/delivery.test.ts— SSRF URL validation (9 tests), delivery behavior (8 tests)src/multitenancy/credential-store.test.ts— round-trip encryption, expiry check, token refreshsrc/multitenancy/platform-health.test.ts— cache hit/miss, healthy/expired/disconnected/unknown states
Key Interactions Verified
Billing
generateMonthlyInvoice(): SQL WHERE uses previous month start/end, NOT current monthgenerateMonthlyInvoice(): returns existing invoice on(customer_id, period_start)unique constraint (MySQL 1062)generateInvoiceNumber(): usescrypto.randomBytes(4).toString('hex')— neverMath.random()emailInvoice(): calls nodemailer.sendMail with correct subject, HTML body, invoice_number
Usage Platform Attribution
send_email→emaillinkedin_create_post→linkedinobsidian_search_notes→obsidiantiktok_create_video→tiktokcreate_draft→emailwhatsapp_send_message→whatsapp- Known-prefix matching (not
name.split('_')[0]which was broken)
OAuth Customer Binding
getTokenCustomer(validToken)→ returns{ customerId }when token exists in DBgetTokenCustomer(expiredToken)→ returns nullexchangeCodeForToken()storescustomer_idinoauth_tokenstable- Atomic consume:
UPDATE SET used=TRUE WHERE used=FALSE+affectedRows === 0→ null (replay protection)
OAuth Security
GET /oauth/authorizewithredirect_urinot inclient.redirect_uris→ 400POST /oauth/authorizewith invalidredirect_uri→ 400, no code issuedhttp://localhost:*wildcard: allowshttp://localhost:\d+specificallyGET /oauth/authorizeunauthenticated → redirect to/login?return_to=...
MCP Session Threading
createSession(customer)stores customer insessionCustomersmap keyed by sessionId- Reused session → same customer from creation time
- Session close → deletes from both
httpTransportsANDsessionCustomers
Cron Invoice Lock
- First process acquires
invoice:cron:lockvia SET NX → runs loop - Second process finds lock → logs and returns immediately
- Lock released via Lua compare-delete (prevents A deleting B's lock on TTL expiry)
Webhook Delivery
signPayload(secret, rawBody)→sha256=<HMAC-SHA256-hex>- Success on first attempt → no retry, no DLQ
- Fails twice, succeeds third → 3 total attempts, no DLQ
- Fails all 4 attempts → appended to Redis
webhook:dlq:{customerId}EXPIRE 604800
SSRF Protection
- Accepts
https://my-server.example.com/hook - Rejects:
ftp://,127.x,10.x,192.168.x,172.16-31.x,localhost,.local
Edge Cases
generateMonthlyInvoice()for customer with zero usage → returns nullcheckLimit()for enterprise plan (limit === -1) → always{ allowed: true }handleToolCall()with customer over limit → returns MCP error object withisError: truegetTokenCustomer()when DB is down → returns null (error caught, not propagated)- Webhook delivery with non-2xx response → failure (retry)
- Webhook delivery with network timeout → failure (retry)
Critical Paths (must not regress)
- Invoice period: On June 1st at 09:00 UTC, cron bills May (NOT June)
- Invoice idempotency: admin endpoint + cron both calling generateMonthlyInvoice for same customer/month returns same invoice
- Bearer token auth: MCP session created with valid customer API key gets req.customer set correctly
- Webhook HMAC: Recipient verifies
X-SquareMCP-Signatureagainst raw body — not parsed body - Token refresh: 60-second buffer before expiry triggers refresh; dynamic import avoids circular dep
Architecture Decisions Captured
Dynamic import for token refresh
src/multitenancy/credential-store.ts uses await import('./token-refresh.js') inside the function body (not at module level) to break the circular dependency between credential-store and token-refresh.
vi.hoisted() pattern
Used in oauth.test.ts, credential-store.test.ts for mock factories that reference variables before module initialization. Pattern:
const { mockExecute } = vi.hoisted(() => ({ mockExecute: vi.fn() }));
vi.mock('../db.js', () => ({ getPool: vi.fn(() => ({ execute: mockExecute })) }));
Fake timers for retry testing
delivery.test.ts uses vi.useFakeTimers() + vi.advanceTimersByTimeAsync(1000/4000/16000) to test retry delay logic without real waits.
stripAccountParam deep-clone
Tools array is module-level global. stripAccountParam must use spread/Object.fromEntries to avoid mutating shared state across sessions.