--- source: gstack /plan-eng-review generated: 2026-05-13 branch: 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')` → mock `getPool()` to return a fake pool - `vi.mock('../redis.js')` → mock Redis client methods - `vi.mock('nodemailer')` → mock createTransport for emailInvoice tests - `vi.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, stripAccountParam - `src/oauth.test.ts` — isValidRedirectUri, createAuthCode, exchangeCodeForToken, getTokenCustomer, validateAccessToken - `src/oauth-dcr.test.ts` — ensureOAuthAppRegistered SQL shape, all DCR redirect URI cases - `src/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 refresh - `src/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 month - `generateMonthlyInvoice()`: returns existing invoice on `(customer_id, period_start)` unique constraint (MySQL 1062) - `generateInvoiceNumber()`: uses `crypto.randomBytes(4).toString('hex')` — never `Math.random()` - `emailInvoice()`: calls nodemailer.sendMail with correct subject, HTML body, invoice_number ### Usage Platform Attribution - `send_email` → `email` - `linkedin_create_post` → `linkedin` - `obsidian_search_notes` → `obsidian` - `tiktok_create_video` → `tiktok` - `create_draft` → `email` - `whatsapp_send_message` → `whatsapp` - Known-prefix matching (not `name.split('_')[0]` which was broken) ### OAuth Customer Binding - `getTokenCustomer(validToken)` → returns `{ customerId }` when token exists in DB - `getTokenCustomer(expiredToken)` → returns null - `exchangeCodeForToken()` stores `customer_id` in `oauth_tokens` table - Atomic consume: `UPDATE SET used=TRUE WHERE used=FALSE` + `affectedRows === 0` → null (replay protection) ### OAuth Security - `GET /oauth/authorize` with `redirect_uri` not in `client.redirect_uris` → 400 - `POST /oauth/authorize` with invalid `redirect_uri` → 400, no code issued - `http://localhost:*` wildcard: allows `http://localhost:\d+` specifically - `GET /oauth/authorize` unauthenticated → redirect to `/login?return_to=...` ### MCP Session Threading - `createSession(customer)` stores customer in `sessionCustomers` map keyed by sessionId - Reused session → same customer from creation time - Session close → deletes from both `httpTransports` AND `sessionCustomers` ### Cron Invoice Lock - First process acquires `invoice:cron:lock` via 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=` - 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 null - `checkLimit()` for enterprise plan (limit === -1) → always `{ allowed: true }` - `handleToolCall()` with customer over limit → returns MCP error object with `isError: true` - `getTokenCustomer()` 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-Signature` against 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: ```typescript 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.