API Authentication Enforcement
Every API endpoint follows a strict authentication and authorization pattern.
Auth Matrix
| Endpoint | Auth Level | Token Cost | Notes |
|---|---|---|---|
GET /api/track-pixel | None | None | Public tracking pixel (hashed email, salted IP hash) |
POST /api/track-amp-event | None | None | Public AMP interaction tracking |
GET /api/view-email | None | None | Public "View in Browser" page |
GET /api/blog-og | None | None | Public OG image |
GET /api/rag-stats | None | None | Public knowledge base stats (/how-it-works) |
POST /api/generate | User | ai_generation | Main RAG pipeline |
POST /api/generate-email | User | ai_generation | Simple generation |
POST /api/gen/copy / gen/blueprint / gen/continuity | User | None | Staged generation pipeline |
POST /api/send-email-mailgun | User | None | Mailgun delivery; sender = verified account email |
POST /api/validate-amp | None | None | AMP validation (stateless validator) |
POST /api/unsubscribe | Session or HMAC token | None | Signed token via UNSUB_TOKEN_SECRET |
POST /api/mailgun-webhook | HMAC signature | None | MAILGUN_WEBHOOK_SIGNING_KEY required |
POST /api/notify-signup | Shared secret | None | Supabase webhook, SIGNUP_WEBHOOK_SECRET |
POST /api/eval/judge | Admin | None | Eval harness LLM judge |
POST /api/deploy-email | Admin | None | Email deployment |
/api/admin/* | Admin | None | RAG management, eval storage, auto-tagging |
Enforcement Pattern
Every protected endpoint follows this pattern at the top of the handler:
export default async function handler(req, res) {
// 1. Method check
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
// 2. Auth verification
const user = await verifyUser(req, res);
if (!user) return; // 401 already sent
// 3. Token spending (if applicable)
const tokenResult = await spendTokensServer(req, res, 'ai_generation');
if (!tokenResult) return; // 402 already sent
// 4. Input validation
const { prompt } = req.body;
if (!prompt) {
return res.status(400).json({ error: 'Prompt is required' });
}
// 5. Business logic...
}
Auth Module
A single shared module, api/_auth.ts, provides verifyUser, verifyAdmin, spendTokensServer, and setCorsHeaders. All routes — TypeScript and JavaScript alike (generate.js, api/admin/*.js, api/gen/*.js, api/eval/*.js) — import from it using the .js extension, which the ESM api/ runtime requires.
Token Spending Security
Token deduction is server-side only. The flow:
- Frontend calls
checkCanAfford()— read-only, no deduction - Frontend executes the API call if affordable
- Server calls
spendTokensServer()— atomic deduction viaspend_tokensRPC - Frontend calls
refreshBalance()to sync UI
This ensures users cannot bypass token costs by calling APIs directly (e.g., via curl).