# ENGINEERING_LESSONS.md

Format for each entry: **Problem**, **Root cause**, **Why it happened**, **Fix**, **Prevention**, **Reference**.

The first entries (L-001 to L-012) come from the 2026-11-30 audit of the prototype artifact. They describe problems to **avoid in the real build**. The prototype is a demo, so they are not defects to patch there.

---

### L-001 Stored XSS through `innerHTML` templating
- **Problem:** Customer name, vehicle name, company name, and search text are interpolated into `innerHTML` and into `value="..."` attributes without escaping. A booking name like `<img src=x onerror=...>` would run script in the admin dashboard.
- **Root cause:** String-template rendering with no output encoding.
- **Why:** Fast prototyping pattern.
- **Fix:** React text nodes only. No `dangerouslySetInnerHTML` with user data.
- **Prevention:** Add an ESLint rule (`react/no-danger`) and an E2E test that submits an XSS payload as a name.
- **Ref:** OWASP A05:2025 Injection; OWASP XSS Prevention Cheat Sheet.

### L-002 Admin area has no access control
- **Problem:** Anyone can open `#admin` and change bookings, vehicles, and settings.
- **Root cause:** No auth or roles exist.
- **Fix:** Supabase Auth, a staff role in `app_metadata` or a staff table, and RLS on every admin-writable table.
- **Prevention:** RLS tests that use the anon and customer roles against admin operations.
- **Ref:** OWASP A01:2025.

### L-003 Availability and double-booking checks are client-only
- **Problem:** `busy()` runs in the browser. Two customers can book the same car at the same time.
- **Root cause:** No server, so there is no atomic check.
- **Fix:** A Postgres exclusion constraint: `EXCLUDE USING gist (vehicle_id WITH =, tstzrange(pickup_at, return_at, '[)') WITH &&) WHERE (status IN ('pending','confirmed','active'))`, which needs `btree_gist`. Create bookings through an RPC that returns a clear conflict error.
- **Prevention:** A concurrency test that fires two simultaneous inserts and expects exactly one to succeed.
- **Ref:** PostgreSQL docs, Exclusion Constraints and Range Types.

### L-004 Price is calculated on the client
- **Problem:** `price()` computes the total in the browser. A real API that accepted that total could be tampered with.
- **Fix:** Compute the price in the booking RPC from DB rates and extras. The client gets a quote, and the server recomputes it on submit.
- **Prevention:** A test that posts a tampered total and checks it is ignored.

### L-005 "Today" is hard-coded
- **Problem:** `new Date("2026-11-29T00:00")` is the past-date guard and calendar anchor, so it breaks every other day.
- **Fix:** Use the server time (`now()`) for validation and the client clock only for UI defaults.

### L-006 Timezone mixing (UTC vs local)
- **Problem:** `dd()` uses `toISOString()` (UTC) to fill `datetime-local` inputs (local). In Beirut (UTC+2) that shifts the shown times by 2 hours. Date-only comparisons slice ISO strings.
- **Fix:** Store `timestamptz`. Convert explicitly to and from Asia/Beirut with a vetted date library or `Intl`. Never slice ISO strings for local dates.
- **Prevention:** Unit tests with the TZ pinned to Asia/Beirut, including the DST change dates.
- **Evidence (confirmed 2026-11-30):** Rendered in Chromium with `timezoneId: Asia/Beirut`, `dd(0)` returns `2026-11-29T08:00` for an intended `10:00`, and booking HAR-1001 shows 08:00. With `UTC` the values are correct. See preview screenshot 07 (pickups at 08:00).

### L-007 Rental-day rounding is undefined
- **Problem:** `days()` uses `ceil(hours/24)` with a minimum of 1. Whether a 1-hour overrun is charged as a full day is a business rule nobody has decided.
- **Fix:** The owner defines the grace period and day boundary. It is implemented once, server-side, with tests.

### L-008 Broken WhatsApp action
- **Problem:** The settings `wa` value is empty by default, so the button links to `https://wa.me/`.
- **Fix:** Validate the number in E.164 format and hide the button if it is missing.

### L-009 Form fields are not saved or not bound
- **Problem:** The location select in booking step 1 is not bound, the home-page location is not carried into the booking, and the booking's phone and email are not stored with it.
- **Fix:** Each field maps to a DB column. E2E tests assert that the persisted values match the input.

### L-010 Odd side effect on status change
- **Problem:** `setb(...,'active')` sets the vehicle status to `ok`. This is meaningless and could hide maintenance status.
- **Fix:** A dedicated transition table, `pending→confirmed|rejected`, `confirmed→active|cancelled`, `active→completed`, enforced in the RPC or a trigger. Vehicle maintenance status stays independent.

### L-011 Accessibility gaps
- **Problem:** Navigation uses `<a>` with no `href` (not focusable). Calendar cells and thumbnails are clickable `div`s. Labels are not tied to inputs. Modals lack `role="dialog"` and a focus trap. The toast is not `aria-live`. The ☰ button has no label. The calendar's ‹ › arrows do not flip in RTL.
- **Fix:** Semantic elements, accessible dialog primitives, and axe checks in CI.
- **Ref:** WCAG 2.2; WAI-ARIA Authoring Practices.

### L-012 Success messages shown without persistence
- **Problem:** "Vehicle saved" and "Settings saved" appear for in-memory changes. The notification toggles do nothing.
- **Fix:** Show the toast only after the server confirms. Remove or label any control that has no effect.

### L-013 Translation key collision mislabels an admin KPI (found 2026-11-30, from a screenshot)
- **Problem:** The admin overview shows "Company details: 1" where it should say "Confirmed: 1".
- **Root cause:** `D.en.co` = "Confirmed" is overwritten by a later `Object.assign(D.en, {co: "Company details"})`. The same happens in AR.
- **Why:** A flat translation namespace with two-letter keys, and no check for duplicates.
- **Fix:** Namespaced keys (`admin.kpi.confirmed`, `settings.company.title`).
- **Prevention:** A unit test that fails on duplicate keys and on keys missing in either language.
- **Evidence:** preview/07-admin-overview-en.png; runtime check `D.en.co === "Company details"`.

### L-014 Booking reference skips numbers
- **Problem:** The first new booking gets `HAR-1011` (seed data ends at 1005).
- **Root cause:** The reference is `1006 + BK.length`, not a sequence.
- **Fix:** A Postgres sequence or identity column for the reference, generated server-side and unique.
- **Evidence:** preview/06a-booking-confirmation-en.png.

### L-015 NULL logic let customer B cancel customer A's request (found in OUR OWN draft, 2026-11-30)
- **Problem:** In `cancel_my_rental_request`, the ownership check `IF NOT (owner_a OR owner_b) THEN raise` did not raise for a signed-in user who had no customer record.
- **Root cause:** `current_customer_id()` returned NULL, so the condition evaluated to `false OR NULL` = NULL, and `NOT NULL` = NULL. PL/pgSQL treats an `IF NULL` as false, so the rejection was skipped and the cancellation went ahead.
- **Why it happened:** The authorization check was written as "deny if not allowed" with three-valued logic, instead of "allow only if definitely true".
- **Fix:** `IF NOT COALESCE(<ownership expression>, false)`.
- **Prevention:** (1) Every authorization test must assert that the target row is **unchanged** afterwards, not only that an error appeared (test C17 originally passed for the wrong reason, because it used a non-existent ID). (2) Wrap boolean permission expressions in `COALESCE(..., false)`, or use `EXISTS`, which is never NULL. (3) Test with users who have *no* related rows, not only with "other user" fixtures.
- **Ref:** PostgreSQL docs, *Logical Operators* (three-valued logic); PL/pgSQL `IF` semantics.
- **Evidence:** evidence/db-test-run-2026-11-30.txt (C17, C17b now pass).

### L-016 Revoking from PUBLIC does not remove Supabase's default function grants
- **Problem:** `REVOKE ... FROM PUBLIC` left functions executable by `anon`/`authenticated`, because Supabase-style default privileges grant to those roles **directly**.
- **Fix:** Revoke from `public, anon, authenticated`, then grant explicitly. Verified by tests A5, A6 and B11.

### L-017 Same-statement snapshot made correct code look broken (tests E9 and M9)
- **Problem:** A test called a modifying function and checked the table **in the same SQL statement**. The check read the snapshot taken *before* the change, so it failed even though the change was correct.
- **Root cause:** PostgreSQL statement snapshots. Subqueries in one statement don't see changes made by a volatile function called in that same statement.
- **Fix / prevention:** Always verify in a **separate statement**. The investigation step stays mandatory: the debug run proved the data was right before the test was changed, and the test was **split, not loosened**.

### L-018 Direct column updates would have desynchronized reservations (found in design review v1.0 → v1.1)
- **Problem:** In v1.0, staff could `UPDATE` a request's vehicle or dates directly. On an approved request this would leave the vehicle block on the old car or dates (a stale block → a double-booking risk).
- **Root cause:** A "convenience" column grant on fields that have dependent state.
- **Fix:** Revoked those column privileges. All changes go through `modify_rental_request` (atomic swap), backed by a unique index, an immutability trigger and a **deferred commit-time invariant** (tests W9, M*, I1–I8, G2–G4).
- **Prevention:** For every column with dependent state elsewhere, ask: "what else must change atomically with it?" If the answer isn't "nothing", it gets a function, not a column grant.

### L-019 Website rate limits don't protect a database that the public can call directly
- **Problem:** With Supabase, the browser talks to the Data API directly using the publishable key. Rate limits in Next.js or Vercel are skipped by any caller who uses the API directly.
- **Fix:** Session-gated submission (CAPTCHA at Supabase Auth) plus **database-enforced** per-session and per-phone limits. Client-side checks are labelled UX only.
- **Prevention:** For every protection, write down *where it is enforced* and *whether a direct API caller can skip it* (SECURITY.md §4a table).

---

## Environment lessons

### E-001 Pasted artifact link didn't resolve
- **Problem:** The link in the master prompt (`/artifact/XZoGJnvaR81tT3TAnvhZhT`) returned "not found". The prototype was found by title at `/artifact/9aAR5Qh2L94Uw3zpaWRjhC`.
- **Prevention:** Confirm the canonical prototype link with the owner, and record it in CLAUDE.md.
