# Backend APIs

All APIs are Next.js route handlers in `src/app/api`. They store data in MySQL through Prisma (`prisma/schema.prisma`; see `docs/database.md`), send email through ZeptoMail (`src/lib/mail.ts`) and post Slack alerts (`src/lib/slack.ts`).

**Shared rules**
- Requests and responses are JSON. Every response has `ok`; failures add a `code` and, for form problems, `errors: { field: message }`.
- Requests that change something must come from this site (Origin check). The session cookie `mz_session` is httpOnly and SameSite=Lax.
- Forms have a hidden honeypot field, `company_website`. Bots that fill it get a success response, and nothing is stored or sent.
- Rate limits answer `429 rate`. They're counted in MySQL where there's a table to count, otherwise in memory.

| Status | Meaning |
| --- | --- |
| 400 | Bad request |
| 401 | Not signed in |
| 403 | Other origin, or not staff |
| 404 | Not found |
| 409 | Conflict |
| 422 | Invalid fields |
| 429 | Too many requests |
| 502 | Couldn't save or send |
| 503 | Service not configured |

## Forms (public)

| Method and path | Body | What it does |
| --- | --- | --- |
| `POST /api/apply` | `name, email, property, property_type, traffic, goal, selected_products, source, family, inquiry, submission_id`; for advertisers also `lead_type: "advertiser", company` | Saves a publisher application or advertiser lead and emails the team. Advertisers go to `ADVERTISER_TO`, everyone else to `APPLY_TO`. Also emails the applicant and posts to Slack. A repeat `submission_id` returns the first result with `duplicate: true`. Limit: 5 per IP per 10 minutes. |
| `POST /api/contact` | `name, email, company?, topic (general\|support\|partnership\|advertising\|press), message, source?` | Saves a contact message, emails the team with the sender as Reply-To, sends the sender a copy and posts to Slack. Limit: 5 per IP per 10 minutes. |

## Publisher Hub accounts

| Method and path | Body | What it does |
| --- | --- | --- |
| `POST /api/auth/verify-email` | `token` | Confirms the email and signs in. The link works once. |
| `POST /api/auth/resend-verification` | `email` | Sends a new confirmation link. Always returns 200. |
| `POST /api/auth/login` | `email, password` | Signs in for 30 days. Returns `401 invalid_credentials` (the same answer for an unknown email) or `403 unverified`. Limit: 10 tries per 15 minutes per IP and per email. |
| `POST /api/auth/logout` | | Ends this session. |
| `GET /api/auth/me` | | The signed-in user. |
| `GET /api/auth/session` | | `{ signedIn, name? }`, always 200. The site header uses it to show "Dashboard" instead of "Publisher Login" when signed in. |
| `POST /api/auth/forgot-password` | `email` | Emails a `/hub-reset?token=` link that works once, for 1 hour. Always returns 200. |
| `POST /api/auth/reset-password` | `token, password` | Sets the new password, signs out every other session and signs this browser in. |
| `GET /api/hub/dashboard` | | The user's applications and messages (matched by account or email) and summary counts. Returns `reporting` and `payments` as `{ connected: false }` until a data source exists. |
| `PATCH /api/hub/account` | `name?, company?, website?` | Updates the profile. The email can't be changed here. |
| `POST /api/hub/account/password` | `currentPassword, newPassword` | Changes the password and signs out other sessions. |
| `GET /api/hub/sites` | | The user's sites: `{ id, domain, category, types[], key, installed }`. |
| `POST /api/hub/sites` | `{ action: "add", site: { domain, category, types[] } }`, `{ action: "update", id, site }` or `{ action: "delete", id }` | Adds, changes or removes a site. Each new site gets a 32-character key for its Monetize code. Category and types must come from the lists in `src/lib/sites.ts`. Up to 50 sites; a duplicate domain returns 409. |
| `POST /api/hub/install-check` | `url` | Loads the page and looks for `n.monetize.com/monetize.js?key=` with one of the user's keys. Returns `{ installed }` and marks that site installed. Only public addresses on ports 80 and 443 are fetched (private, loopback and link-local addresses are refused, including after a redirect), with an 8-second and 2 MB limit and 10 checks a minute. |
| `GET /api/hub/stats?sites=&device=&start=&end=` | | Revenue, EPC, clicks and pageviews for the dashboard. Returns all zeros with `connected: false` until the Monetize reporting is connected. |

Passwords need at least 10 characters, with letters and a number. They're stored as scrypt hashes. Session and email tokens are stored only as SHA-256 hashes.

## Staff (role ADMIN)

To give someone staff access, run `npm run admin:grant -- someone@monetize.com`, after they've created a Hub account. To take it away, add `--revoke`.

| Method and path | What it does |
| --- | --- |
| `GET /api/admin/stats` | Totals: applications by status, type and team; failed emails; open messages; accounts. |
| `GET /api/admin/applications?q=&status=&type=&from=&to=&page=&pageSize=` | Lists applications. `q` searches the reference, name, email, company and site. `type` is `publisher` or `advertiser`. |
| `GET` / `PATCH /api/admin/applications/:id` | One application; `PATCH` takes `{ status?, notes? }`. Statuses: `NEW, REVIEWING, CONTACTED, APPROVED, DECLINED, SPAM`. |
| `GET /api/admin/applications/export?…` | CSV export, with the same filters as the list, up to 10,000 rows. |
| `GET /api/admin/messages?…`, `GET` / `PATCH /api/admin/messages/:id`, `GET /api/admin/messages/export?…` | The same for contact messages. |
| `GET /api/admin/users?q=&page=` | Hub accounts. Password hashes are never returned. |
| `PATCH /api/admin/users/:id` | Takes `{ role?: "PUBLISHER" \| "ADMIN", signOut?: true }`. Staff can't remove their own admin role. |

## Pages

| Page | What it is |
| --- | --- |
| `/hub-login` | Sign in |
| `/hub-verify?token=` | Confirm the email |
| `/hub-reset` | Forgot password |
| `/hub-reset?token=` | Choose a new password |
| `/hub` | Dashboard: revenue, EPC, clicks and pageviews (zeros until reporting is connected) |
| `/hub/install` | The Monetize code for each site, and the installation check |
| `/hub/merchants` | Merchant search (empty until the merchant list is connected) |
| `/hub/sites` | Add, edit and delete sites; each site's key |
| `/hub/disclosure` | FTC, Amazon Associates and data protection disclosure guidance |
| `/hub/account` | Applications, messages, details and password |
| `/admin` | Staff dashboard. Publishers get a 404. |
| `/contact#message` | The "Ask a question" and "Advertise with us" forms |

All Hub and admin pages are `noindex` and disallowed in `robots.txt`. The `/hub` pages use the dashboard design from DES-1581 (Oct 27): `src/app/hub/layout.tsx`, `src/styles/dashboard.css` and `public/js/dashboard.js`.
