# CF-API Endpoints

Express routes in `js/cf-api/routes/`. The cf-api acts as middleware between clients (VSC-Extension, CLI) and the aiservice backend.

## Route Registration Order (`routes/index.ts`)

Registration order matters — webhook routes must be before the body parser:

1. **Webhook routes** — before `express.json()` (raw body for signature verification)
2. **Body parser** — `express.json({ limit: JSON_BODY_LIMIT })`
3. **Public routes** — no authentication required
4. **Protected routes** — require API key (`checkForValidAPIKey` middleware)

## Route Files

### `webhook.routes.ts`

- `POST /github/webhooks` — GitHub App webhook handler (Octokit signature verification)
- `POST /stripe/webhooks` — Stripe webhook handler
- Both need raw body access (before JSON parser)

### `optimization.routes.ts`

Protected optimization endpoints:
- `POST /suggest-pr-changes` — suggest PR changes
- `POST /create-pr` — create optimization PR
- `POST /verify-existing-optimizations` — check existing optimizations
- `POST /is-already-optimized` — check if code was already optimized
- `POST /add-code-hash` — add optimized code context hash
- `POST /mark-as-success` — mark optimization as successful
- `POST /create-staging` — create staging review
- `POST /get-staging-code` — get staged code
- `POST /commit-staging-code` — commit staged code
- `POST /test-repo` — add repository manually

### `github.routes.ts`

GitHub-related endpoints for repository management.

### `subscription.routes.ts`

Subscription management endpoints.

### `user.routes.ts`

User management endpoints.

### `public.routes.ts`

Public endpoints (no authentication): health checks, version info.

## Middleware Stack

- `checkForValidAPIKey` — API key authentication
- `trackEndpointCalls` — PostHog endpoint tracking
- `idLimiter` — rate limiting
- `logAuthEvent` / `logRequestBody` — enhanced logging (dev only)
- `trackUsage` — usage tracking for optimization endpoints
