@AGENTS.md

# WebNexa: notes for coding agents

WebNexa is our own multi-site CMS (WebNexa Core). Plan documents: `D:\repos\gurpret\docs\cms-plan.md`
(main plan), `week-1-plan.md`, `save-as-template.md`, `template-library.md`.

## Rules

- **No outside services.** No hosted APIs, no API keys, no CDN fonts (`next/font/google` is not
  allowed), no telemetry. Open-source libraries only, installed in our code.
- Server code that touches the database or secrets imports `server-only`.
- Environment variables are read only through `getServerEnv()` in `src/core/env`.
- Database access goes through `src/db`. Never send database errors or connection details to the
  browser; log them on the server.
- Drizzle's "Failed query" error message contains the query's parameter values. Never log it raw
  for queries with personal or secret data (logins, users, form submissions); log the `cause`
  and the query name instead.
- Blocks: no client details in block code; every field is marked design or client content and
  every client-content field has a placeholder; options (variants), not copies.
- **Auth:** every admin page starts with `await requireUser()` or `await requirePermission(...)`
  (`src/core/auth/dal.ts`), and so does every Server Action. A check in a layout or in Proxy is
  never enough on its own. Role rules live only in `src/core/auth/permissions.ts`. Site work by
  client editors also needs `canAccessSite()`.
- **Services** (`src/core/*/service.ts`) take `(db, actor, …)`, call `assertPermission()`
  themselves, and save a change plus its `insertActivity()` row in one transaction. Use
  `recordActivity()` (never throws) only outside transactions. Pages and actions stay thin.
- **Drizzle pitfall:** in single-table queries column names are unqualified, so a correlated
  sql`` subquery like `where ${a.siteId} = ${sites.id}` silently compares against the
  subquery's own `id`. Use joins (`.leftJoin` + grouped subquery `.as()`) instead.
- Forms: Server Actions return `FormState` via `formResult()` (fresh `key` each time; the form
  remounts its fields with it). Never echo passwords in `values`.
- Don't call `Date.now()`/`new Date()` while rendering (lint `react-hooks/purity`); compute
  time-based flags (e.g. `locked`) in the query.
- Never call `redirect()` inside `try/catch` (it works by throwing). Don't use the experimental
  `forbidden()`; redirect to `/admin/no-access` instead.
- Login rate limits are in memory (one server). Moving to several servers means moving them to
  PostgreSQL. Production must set `TRUST_PROXY=true` behind Caddy, or per-IP limits are off.
- Before using a Next.js API, read the matching guide in `node_modules/next/dist/docs/`.
- Before calling work done: `npm run check`, `npm run test:db` and `npm run build` must pass.
- Schema changes: edit `src/db/schema`, `npm run db:generate`, read the SQL, `npm run db:migrate`,
  and add a rule test to `src/db/schema.integration.test.ts`. A foreign key may only target a
  `unique()` table constraint or primary key (not a `uniqueIndex`): drizzle-kit adds foreign
  keys before separate indexes, so the migration fails otherwise.
- On Windows PowerShell, `npm run x -- --flag` drops the flag. Scripts must not rely on
  arguments after `--`; call the tool with `npx` or ask interactively instead.

## Status

- [x] Week 1, day 1: project set-up (Next.js 16, Tailwind 4, shadcn, ESLint, Prettier, Vitest,
      env validation, PostgreSQL connection, `/api/health`)
- [x] Day 2: Drizzle schema (users, sessions, sites, site_domains, site_members, pages,
      page_versions, media, activity_log), first migration, seed, reset, argon2id passwords,
      database rule tests
- [x] Day 3: logins and roles (argon2id, DB sessions with hashed tokens, `__Host-` cookie in
      production, idle 8h / absolute 24h / remember-me 30d, lock after 5 failures, per-IP limit,
      no account enumeration, roles via `requirePermission`, Proxy redirect, sign-out)
- [x] Day 4: admin shell (sidebar by permission, mobile menu), Users (list, add, edit role/
      status/sites, set password, unlock), Sites (list, create with domain + draft home page,
      settings, domains), Activity page; every change logged in the same transaction
- [x] Day 5 (reshaped): page builder v1. Format section → row → column → element
      (`src/core/builder`, validated by zod), shared header/footer/theme in
      `sites.settings.layout` (draft/published), renderer `src/components/site` (container
      queries, same code for live site and canvas), editor `src/components/builder`
      (drag-drop, column resize, inline text, undo/redo, autosave with revision check, publish),
      media upload `/api/admin/media` + `/media/[id]`, public site by domain `(site)/[[...path]]`
- [x] Form builder: `form` element (10 field types, presets), public submit Server Action
      `src/components/site/form-action.ts` (form looked up in the PUBLISHED page on the
      request's domain; honeypot, min fill time, per-IP limit), `form_submissions` table,
      email via our own SMTP (`SMTP_URL`; without it .eml files go to
      `STORAGE_DIR/mail-outbox`), admin `/admin/submissions` (read/new, delete, CSV export).
      Submissions are personal data: never log their contents; never pass `notifyEmail`
      to the browser.
- [x] File upload field (`file`, `accept`: images | documents | both; default images):
      max 3 per form, 5 MB each, 10 MB per message (`src/core/submissions/limits.ts`).
      Checked by content in `sniff-file.ts`: JPEG/PNG/WebP/GIF, PDF, .docx/.xlsx (ZIP
      file list; macros/ActiveX refused); no SVG, no old .doc/.xls. Name always ends in
      the real extension. Stored in `form_submission_files` (bytea, cascades with the
      message), attached to the email up to 7 MB, private admin route
      `/admin/submissions/file/[id]` (documents always download). Not a virus scan.
      Server Action body limit is 11mb in `next.config.ts`; keep it above the total.
- [x] Export site (`/admin/sites/[id]/export`, `sites.manage` only): ZIP of plain HTML per
      published page + `assets/site.css` (reset + `src/styles/site.css`) + `assets/site.js`
      (sliders, unconnected-form notice) + images + README. No CMS code. Built in the admin's
      browser (`export/build.tsx`) because `react-dom/server` throws in the server component
      layer; data from `src/core/export/service.ts` (never `notifyEmail`). Links made relative;
      forms lose our hidden fields and get label-based names. The server deployment must keep
      `src/styles/site.css` (read at runtime). Logged as `site.exported`.
- [x] Export option "Include form handler (PHP + MySQL)" (default on when the site has forms):
      adds `forms/` with `send.php`, `admin.php`, `lib.php` (source:
      `src/core/export/form-handler/*.php`, PHP 7.4+, keep in the deployment) plus generated
      `config.php` (db, `notify_email` = site contact email, random `setup_key`) and `forms.php`
      (definitions as JSON in a `phpString` literal; never `notifyEmail`). Messages go to the
      client's OWN MySQL (`wn_submissions`, `wn_submission_files`, `wn_settings`, `wn_limits`,
      created on first use); files in `forms/files/` under random names; `.htaccess` closes
      lib/config/forms/files. Same rules as the CMS (validation messages, content sniffing,
      honeypot, 2.5 s, 10 per IP per 10 min). `admin.php`: one password set with the setup key,
      CSRF tokens, login lock, CSP, downloads always attachments, CSV. Check PHP with
      `php -l`; there is no PHP test runner in this repo.
- [ ] Builder next: client-editor content-only mode, share-preview link, save section as
      preset, version history/restore, image resizing, more presets
- [ ] Day 6: server, Docker, HTTPS, backups
- [ ] Day 7: test, demo, week 2 plan
