25 KiB
[claude-sonnet-4-6] Multi-Tenancy Implementation Spec — Agent Executable
Agent: claude-sonnet-4-6 Date: 2026-05-08 For: Claude Code CLI, Codex, KIMI Code, opencode Repo: hermes-mcp (TypeScript/Node.js, MicroK8s deployment) Priority: Complete before any paid customer goes live
Context for the coding agent
You are implementing multi-tenant data isolation for hermes-mcp, a TypeScript MCP gateway server. The server currently serves one user (the builder). We are preparing it to serve multiple paying customers (e.g. a publisher and a mortgage broker) with complete data isolation between them.
The server stack:
- Runtime: TypeScript / Node.js
- Transport: Streamable HTTP MCP + REST API endpoints
- Cache: Redis (via
ioredisorredisnpm package) - Database: Postgres (via
pgorpostgresnpm package) - Deployment: MicroK8s at hermes.squaremcp.com
The billing layer (src/billing/) already exists with:
src/billing/plans.ts— plan definitionssrc/billing/meter.ts— Redis call countersrc/billing/middleware.ts— API key → customer resolution + limit enforcementsrc/billing/stripe.ts— Stripe checkout + webhook
You must NOT break any existing tool functionality. All changes are additive or refactoring existing patterns. After each file change, run npm run build to verify TypeScript compilation.
Task 1 — Audit and fix Redis key namespace
Goal: Verify every Redis key in the codebase includes the customerId. Fix any that do not.
Step 1.1 — Search for all Redis SET/GET/INCR calls
grep -rn "redis\.\(set\|get\|incr\|expire\|del\|hset\|hget\)" src/ --include="*.ts"
For every key found, verify it follows the pattern {namespace}:{customerId}:{rest}.
Step 1.2 — Verify meter.ts key format
Open src/billing/meter.ts. The usageKey function must produce:
usage:{customerId}:{YYYY-MM}
If it currently produces usage:{YYYY-MM} without the customerId, fix it:
// CORRECT
function usageKey(customerId: string): string {
const now = new Date();
const month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
return `usage:${customerId}:${month}`;
}
Step 1.3 — Verify customer cache key format
In src/billing/middleware.ts, the cache key for customer lookup must be:
customer:apikey:{apiKey}
NOT customer:{apiKey} — the apikey: namespace prevents collision with other customer keys.
Step 1.4 — Fix any non-namespaced credential keys
Search for any place credentials (tokens, passwords) are stored in Redis:
grep -rn "token\|password\|credential\|oauth" src/ --include="*.ts" | grep -i "redis\|cache"
All credential keys must follow: creds:{customerId}:{platform}
Task 2 — Create credential store
File to create: src/multitenancy/credential-store.ts
This module handles encrypted storage and retrieval of per-customer platform credentials. Credentials are encrypted at rest using AES-256-GCM with a key from environment variables.
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
redis.connect();
const ENCRYPTION_KEY = Buffer.from(process.env.CREDENTIAL_ENCRYPTION_KEY!, 'hex');
// CREDENTIAL_ENCRYPTION_KEY must be a 64-char hex string (32 bytes)
// Generate with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
function encrypt(plaintext: string): string {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', ENCRYPTION_KEY, iv);
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return `${iv.toString('hex')}:${tag.toString('hex')}:${encrypted.toString('hex')}`;
}
function decrypt(ciphertext: string): string {
const [ivHex, tagHex, encHex] = ciphertext.split(':');
const iv = Buffer.from(ivHex, 'hex');
const tag = Buffer.from(tagHex, 'hex');
const encrypted = Buffer.from(encHex, 'hex');
const decipher = createDecipheriv('aes-256-gcm', ENCRYPTION_KEY, iv);
decipher.setAuthTag(tag);
return decipher.update(encrypted) + decipher.final('utf8');
}
export type Platform = 'email' | 'whatsapp' | 'linkedin' | 'telegram' | 'discord' | 'instagram' | 'twitter' | 'obsidian';
export interface EmailCredentials {
host: string;
port: number;
user: string;
password: string;
smtpHost?: string;
smtpPort?: number;
}
export interface OAuthCredentials {
accessToken: string;
refreshToken?: string;
expiresAt?: number;
scope?: string;
}
export interface WhatsAppCredentials {
phoneNumberId: string;
accessToken: string;
businessAccountId: string;
}
export type PlatformCredentials = EmailCredentials | OAuthCredentials | WhatsAppCredentials | Record<string, string>;
export async function storeCredential(
customerId: string,
platform: Platform,
credentials: PlatformCredentials
): Promise<void> {
const key = `creds:${customerId}:${platform}`;
const encrypted = encrypt(JSON.stringify(credentials));
// Credentials don't expire — they persist until explicitly revoked
await redis.set(key, encrypted);
}
export async function getCredential<T extends PlatformCredentials>(
customerId: string,
platform: Platform
): Promise<T | null> {
const key = `creds:${customerId}:${platform}`;
const encrypted = await redis.get(key);
if (!encrypted) return null;
return JSON.parse(decrypt(encrypted)) as T;
}
export async function revokeCredential(customerId: string, platform: Platform): Promise<void> {
await redis.del(`creds:${customerId}:${platform}`);
}
export async function revokeAllCredentials(customerId: string): Promise<void> {
const pattern = `creds:${customerId}:*`;
const keys = await redis.keys(pattern);
if (keys.length > 0) await redis.del(keys);
}
Environment variable to add to .env and Kubernetes secret:
CREDENTIAL_ENCRYPTION_KEY=<generate with: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))">
Task 3 — Create WhatsApp webhook router
File to create: src/multitenancy/webhook-router.ts
WhatsApp Cloud API sends ALL incoming messages to one webhook endpoint, regardless of which customer's number received the message. This module routes incoming webhooks to the correct customer context using the phone_number_id from the payload.
import { createClient } from 'redis';
import { getCredential, WhatsAppCredentials } from './credential-store';
const redis = createClient({ url: process.env.REDIS_URL });
redis.connect();
// 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;
}
Task 4 — Create audit log
File to create: src/multitenancy/audit-log.ts
Every tool call must be logged per customer. Logs are the compliance artefact. No cross-customer query is possible.
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
redis.connect();
export interface AuditEntry {
customerId: string;
tool: string;
args: Record<string, unknown>;
result: 'success' | 'error';
errorMessage?: string;
durationMs: number;
timestamp: string;
}
// Retain 90 days of logs per customer. Key: logs:{customerId}:{ISO-date}:{ulid/counter}
export async function logToolCall(entry: AuditEntry): Promise<void> {
const date = entry.timestamp.slice(0, 10); // YYYY-MM-DD
const seqKey = `log_seq:${entry.customerId}:${date}`;
const seq = await redis.incr(seqKey);
// Expire the sequence key after 95 days so it cleans up
if (seq === 1) await redis.expire(seqKey, 60 * 60 * 24 * 95);
const logKey = `logs:${entry.customerId}:${date}:${String(seq).padStart(8, '0')}`;
await redis.set(logKey, JSON.stringify(entry), { EX: 60 * 60 * 24 * 90 });
}
// Retrieve logs for one customer for a date range — customerId is REQUIRED
export async function getCustomerLogs(
customerId: string,
fromDate: string, // YYYY-MM-DD
toDate: string // YYYY-MM-DD
): Promise<AuditEntry[]> {
// Generate date keys between fromDate and toDate
const dates = getDatesInRange(fromDate, toDate);
const entries: AuditEntry[] = [];
for (const date of dates) {
const pattern = `logs:${customerId}:${date}:*`;
const keys = await redis.keys(pattern);
for (const key of keys) {
const raw = await redis.get(key);
if (raw) entries.push(JSON.parse(raw) as AuditEntry);
}
}
return entries.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
}
function getDatesInRange(from: string, to: string): string[] {
const dates: string[] = [];
const current = new Date(from);
const end = new Date(to);
while (current <= end) {
dates.push(current.toISOString().slice(0, 10));
current.setDate(current.getDate() + 1);
}
return dates;
}
// Convenience wrapper for tool handlers — call before and after
export function createToolAudit(customerId: string, tool: string) {
const start = Date.now();
return {
success: async (args: Record<string, unknown>) => {
await logToolCall({
customerId, tool, args,
result: 'success',
durationMs: Date.now() - start,
timestamp: new Date().toISOString(),
});
},
error: async (args: Record<string, unknown>, errorMessage: string) => {
await logToolCall({
customerId, tool, args,
result: 'error', errorMessage,
durationMs: Date.now() - start,
timestamp: new Date().toISOString(),
});
},
};
}
Task 5 — Update Customer type and middleware
File to modify: src/billing/middleware.ts
Add credential loading to the resolved Customer object so tool handlers receive credentials directly.
Step 5.1 — Update the Customer interface
// Add to the top of middleware.ts
import { getCredential, Platform, PlatformCredentials } from '../multitenancy/credential-store';
export interface Customer {
id: string;
plan: PlanKey;
active: boolean;
email: string;
// Credential loader — tool handlers call this to get their platform credentials
getCredential: <T extends PlatformCredentials>(platform: Platform) => Promise<T | null>;
}
Step 5.2 — Update resolveCustomer to return credential loader
async function resolveCustomer(apiKey: string): Promise<Customer | null> {
const cached = await redis.get(`customer:apikey:${apiKey}`);
if (cached) {
const base = JSON.parse(cached);
// Re-attach the credential loader (functions can't be cached)
return {
...base,
getCredential: <T extends PlatformCredentials>(platform: Platform) =>
getCredential<T>(base.id, platform),
};
}
const row = await db.query(
'SELECT id, plan, active, email FROM customers WHERE api_key = $1',
[apiKey]
);
if (!row.rows.length) return null;
const { id, plan, active, email } = row.rows[0];
const customer: Customer = {
id, plan, active, email,
getCredential: <T extends PlatformCredentials>(platform: Platform) =>
getCredential<T>(id, platform),
};
// Cache only the serialisable fields (not the function)
await redis.setEx(`customer:apikey:${apiKey}`, 60, JSON.stringify({ id, plan, active, email }));
return customer;
}
Task 6 — Refactor all tool handlers to use customer credentials
Pattern to enforce across ALL tool files in src/tools/:
Every tool handler function must:
- Accept a
customer: Customerparameter - Call
customer.getCredential('platform')to get credentials - Never import a global credential config or use hardcoded tokens
- Wrap the call in
createToolAudit
Example — src/tools/whatsapp.ts before and after:
// BEFORE (single-user, credentials from env)
export async function sendWhatsAppMessage(to: string, body: string) {
const response = await fetch(
`https://graph.facebook.com/v18.0/${process.env.WA_PHONE_NUMBER_ID}/messages`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.WA_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ messaging_product: 'whatsapp', to, type: 'text', text: { body } }),
}
);
return response.json();
}
// AFTER (multi-tenant, credentials from customer object)
import { Customer } from '../billing/middleware';
import { WhatsAppCredentials } from '../multitenancy/credential-store';
import { createToolAudit } from '../multitenancy/audit-log';
export async function sendWhatsAppMessage(
to: string,
body: string,
customer: Customer
): Promise<unknown> {
const audit = createToolAudit(customer.id, 'whatsapp:sendMessage');
const args = { to, body };
const creds = await customer.getCredential<WhatsAppCredentials>('whatsapp');
if (!creds) throw new Error('WhatsApp not connected for this account');
try {
const response = await fetch(
`https://graph.facebook.com/v18.0/${creds.phoneNumberId}/messages`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${creds.accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ messaging_product: 'whatsapp', to, type: 'text', text: { body } }),
}
);
const result = await response.json();
await audit.success(args);
return result;
} catch (err) {
await audit.error(args, String(err));
throw err;
}
}
Apply this same pattern to ALL tool files:
src/tools/email.ts— usecustomer.getCredential('email')src/tools/linkedin.ts— usecustomer.getCredential('linkedin')src/tools/telegram.ts— usecustomer.getCredential('telegram')src/tools/discord.ts— usecustomer.getCredential('discord')src/tools/instagram.ts— usecustomer.getCredential('instagram')src/tools/twitter.ts— usecustomer.getCredential('twitter')src/tools/obsidian.ts— usecustomer.getCredential('obsidian')
For each file: find the hardcoded process.env.* token references, replace with customer.getCredential(platform), add audit logging.
Task 7 — Update WhatsApp webhook endpoint in src/index.ts
Find the existing WhatsApp webhook handler. It currently handles all incoming messages for the single-user setup. Replace it with the routed version:
import { routeWhatsAppWebhook } from './multitenancy/webhook-router';
// WhatsApp webhook verification (GET) — unchanged
app.get('/webhook/whatsapp', (req, res) => {
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (mode === 'subscribe' && token === process.env.WA_VERIFY_TOKEN) {
res.status(200).send(challenge);
} else {
res.status(403).send('Forbidden');
}
});
// WhatsApp webhook delivery (POST) — now multi-tenant
app.post('/webhook/whatsapp', express.json(), async (req, res) => {
// Always acknowledge immediately to prevent Meta retries
res.status(200).send('EVENT_RECEIVED');
try {
const events = await routeWhatsAppWebhook(req.body);
for (const event of events) {
// Hand off to your existing message handling logic
// Pass the customer context so the handler uses the right credentials
await handleInboundWhatsAppMessage(event);
}
} catch (err) {
console.error('[webhook/whatsapp] routing error:', err);
}
});
Task 8 — Add customer onboarding API endpoints
File to modify: src/index.ts
These endpoints are called by the squaremcp.com onboarding flow when a customer connects a new platform. They store encrypted credentials and register phone number mappings.
import { storeCredential } from './multitenancy/credential-store';
import { registerWhatsAppNumber } from './multitenancy/webhook-router';
// Connect WhatsApp — called after customer enters their Meta credentials
app.post('/api/connect/whatsapp', meterMiddleware, async (req, res) => {
const customer = (req as any).customer as Customer;
const { phoneNumberId, accessToken, businessAccountId } = req.body;
if (!phoneNumberId || !accessToken || !businessAccountId) {
return res.status(400).json({ error: 'missing_fields' });
}
// Store encrypted credentials
await storeCredential(customer.id, 'whatsapp', {
phoneNumberId, accessToken, businessAccountId,
});
// Register phone number → customer mapping for webhook routing
await registerWhatsAppNumber(customer.id, phoneNumberId);
res.json({ connected: true, platform: 'whatsapp' });
});
// Connect email (IMAP/SMTP)
app.post('/api/connect/email', meterMiddleware, async (req, res) => {
const customer = (req as any).customer as Customer;
const { host, port, user, password, smtpHost, smtpPort } = req.body;
await storeCredential(customer.id, 'email', {
host, port: parseInt(port), user, password, smtpHost, smtpPort: smtpPort ? parseInt(smtpPort) : undefined,
});
res.json({ connected: true, platform: 'email' });
});
// Connect OAuth platforms (LinkedIn, Telegram, Discord, Instagram, Twitter)
// These would be called at the end of OAuth callback flows
app.post('/api/connect/:platform', meterMiddleware, async (req, res) => {
const customer = (req as any).customer as Customer;
const platform = req.params.platform as Platform;
const { accessToken, refreshToken, expiresAt, scope } = req.body;
const validPlatforms: Platform[] = ['linkedin', 'telegram', 'discord', 'instagram', 'twitter'];
if (!validPlatforms.includes(platform)) {
return res.status(400).json({ error: 'unknown_platform' });
}
await storeCredential(customer.id, platform, { accessToken, refreshToken, expiresAt, scope });
res.json({ connected: true, platform });
});
// Get connection status for a customer
app.get('/api/connections', meterMiddleware, async (req, res) => {
const customer = (req as any).customer as Customer;
const platforms: Platform[] = ['email', 'whatsapp', 'linkedin', 'telegram', 'discord', 'instagram', 'twitter', 'obsidian'];
const status: Record<string, boolean> = {};
for (const platform of platforms) {
const cred = await customer.getCredential(platform);
status[platform] = cred !== null;
}
res.json({ customerId: customer.id, connections: status });
});
Task 9 — Verification tests
After completing all tasks, run these verification checks manually or as integration tests:
Test 1 — Key isolation
// Create two test customers with known IDs
const customerA = 'test_cust_aaa';
const customerB = 'test_cust_bbb';
// Store credential for A
await storeCredential(customerA, 'whatsapp', { phoneNumberId: '111', accessToken: 'token-a', businessAccountId: 'ba-a' });
// Attempt to retrieve A's credential using B's ID — must return null
const result = await getCredential(customerB, 'whatsapp');
console.assert(result === null, 'FAIL: Customer B retrieved Customer A credentials');
console.log('Test 1 passed: credential isolation confirmed');
Test 2 — Webhook routing isolation
await registerWhatsAppNumber(customerA, 'phone_111');
await registerWhatsAppNumber(customerB, 'phone_222');
const resolved_a = await resolveCustomerFromPhoneNumberId('phone_111');
const resolved_b = await resolveCustomerFromPhoneNumberId('phone_222');
console.assert(resolved_a === customerA, 'FAIL: phone_111 routed to wrong customer');
console.assert(resolved_b === customerB, 'FAIL: phone_222 routed to wrong customer');
console.log('Test 2 passed: webhook routing isolation confirmed');
Test 3 — Audit log isolation
// Log an entry for customer A
await logToolCall({ customerId: customerA, tool: 'test', args: {}, result: 'success', durationMs: 10, timestamp: new Date().toISOString() });
// Retrieve logs for customer B — must be empty
const logs_b = await getCustomerLogs(customerB, '2026-05-01', '2026-05-31');
console.assert(logs_b.length === 0, 'FAIL: Customer B can see Customer A logs');
console.log('Test 3 passed: audit log isolation confirmed');
Test 4 — Build verification
npm run build
# Must produce zero TypeScript errors
# Pay particular attention to: type errors on tool handler signatures missing the customer parameter
Environment variables to add
Add these to .env (local) and to your Kubernetes Secret manifest:
# Credential encryption — generate once, never rotate without re-encrypting all stored credentials
CREDENTIAL_ENCRYPTION_KEY=<64-char hex string>
# Existing WhatsApp verify token — confirm this is set
WA_VERIFY_TOKEN=<your meta webhook verify token>
Kubernetes secret update:
kubectl create secret generic hermes-secrets \
--from-env-file=.env \
--dry-run=client -o yaml | kubectl apply -f -
Order of execution for the coding agent
Execute tasks in this exact order to avoid breaking the build mid-way:
- Task 1 — Redis audit (no file changes, just verification)
- Task 2 — Create
src/multitenancy/credential-store.ts - Task 3 — Create
src/multitenancy/webhook-router.ts - Task 4 — Create
src/multitenancy/audit-log.ts - Task 5 — Update
src/billing/middleware.tsCustomer type - Task 6 — Refactor tool handlers (one file at a time, build after each)
- Task 7 — Update WhatsApp webhook endpoint in
src/index.ts - Task 8 — Add onboarding endpoints to
src/index.ts - Task 9 — Run verification tests
npm run build— must produce zero errors- Deploy to staging, run tests against real Redis instance
- Deploy to production
If any task produces a TypeScript error: stop, fix it before proceeding. Do not accumulate errors across tasks.
Definition of done
- All Redis keys include customerId namespace
- All tool handlers accept Customer parameter and use customer.getCredential()
- No hardcoded process.env token references in tool handler files
- WhatsApp webhook routes by phone_number_id to correct customer
- Audit log entries are partitioned by customerId with no cross-customer query path
- Credential encryption key is in Kubernetes secret
- Three verification tests pass
- npm run build produces zero TypeScript errors
- Two test customers can be active simultaneously with no data leakage
claude-sonnet-4-6 | 2026-05-08 | product-incubation Implementation spec — ready for Claude Code CLI, Codex, KIMI Code, or opencode execution