# HATEM AUTO RENTAL — Database & Rental Request Workflow Proposal (v1.1, design review)

**Status: DESIGN REVIEW. NOT approved for implementation.** No migration has been applied to any Supabase project, no application code exists, nothing is deployed, and the prototype is unchanged.
Revised 2026-11-30 in response to the owner's review of v1.0. The v1.0 files are preserved in `evidence/v1.0-snapshot/`.

| File | What it is |
|---|---|
| `supabase/migrations_draft/…0100_core_schema.sql` | Tables, constraints, indexes, invariants, audit |
| `…0200_rls_policies.sql` | Privileges + RLS |
| `…0300_workflow_functions.sql` | Submit (guest/customer), transition (incl. approval), **modify**, cancel, availability |
| `…0400_reference_data.sql` | Tripoli branch, status definitions, allowed transitions |
| `…0500_storage_policies.sql` | **New:** vehicle-photos bucket + Storage policies |
| `supabase/tests/` | Shim (test-only), 2 SQL test files, runner with multi-session tests |
| `evidence/db-test-run-v1.1-2026-11-30.txt` | Actual output: **178 SQL + 6 multi-session = 184 passed, 0 failed** |
| `evidence/test-id-continuity-v1.0-to-v1.1.txt` | Proof that all 103 v1.0 tests are kept and pass |

---

## 0. Change summary (v1.0 → v1.1) and why

| # | Change | Why (owner requirement) |
|---|---|---|
| 1 | **`approved` now means "agreement reached = confirmed reservation"**, labelled *Confirmed / مؤكَّد* in the UI (the code stays `approved`). Approval **requires** a specific vehicle, an agreed price, a future pickup, an active vehicle and an **agreement note**. It records `agreed_at`/`agreed_by` and **creates the vehicle block in the same atomic step**. | §1: a block only after agreement; a precise meaning for "approved" and for "confirmed reservation" |
| 2 | Staff can **no longer create reservation blocks by hand** or release them directly. Only approval, modification and closing do that. Staff still manage maintenance / owner-use blocks. | §1, §3: no stale or duplicate blocks |
| 3 | **New `modify_rental_request()`**: vehicle / pickup / return changes. For an approved request it releases the old block and creates the new one atomically; any conflict or error rolls **everything** back. Direct `UPDATE` of vehicle and dates is revoked. | §3 |
| 4 | **Database-enforced invariants**: one active block per request at most (unique index); blocks are immutable (release, then create; no re-targeting or re-activation); an approved request must carry its agreement data (CHECK); and, **at every COMMIT**, an approved request must have exactly its matching block while open or closed requests have none (deferred constraint trigger, which also binds the superuser). | §3: "no stale or duplicate blocks may remain" |
| 5 | **Guest requests without an account**, through a **Supabase anonymous session** (CAPTCHA + IP limits enforced by Supabase Auth). The `anon` role (no session) **can no longer call submit**; v1.0 allowed it. | §2 |
| 6 | Abuse limits in the DB: per **session** (3 per 24 h), per **phone across sessions** (5 per 24 h), **blocked customer's phone** rejected even as a guest, **idempotency key bound to its session**. | §2 |
| 7 | **Storage policies** for the `vehicle-photos` bucket (staff-only write, UUID image names, no listing for the public). | §5: storage access |
| 8 | Block release time, actor and reason are **stamped by the database** (client values ignored). | §5: audit integrity |
| 9 | Request edits are now **audited**. `business_settings.updated_by` was removed, since the audit log already records it, and it was visible to the public. | §4 simplification, §5 |
| 10 | **Tests: 103 → 184.** Every v1.0 test is kept; 81 were added (§9). | §6 |

---

## 1. Rental Request status workflow

### 1.1 Exact meaning of each status

| Code (UI label EN / AR) | Business meaning | Vehicle blocked? | Is it a reservation? |
|---|---|---|---|
| `submitted` (Submitted / تم الإرسال) | The request was received. HATEM has promised nothing. | **No** | No |
| `in_review` (In review / قيد المراجعة) | Staff are checking the vehicle, dates and person (often by WhatsApp). | **No** | No |
| `awaiting_customer` (Awaiting customer / بانتظار ردّ العميل) | Staff sent terms (vehicle, dates, price) or a question and are waiting for the customer's answer. | **No** | No |
| `approved` (**Confirmed / مؤكَّد**) | **HATEM and the customer have agreed on vehicle, dates and price.** The vehicle is blocked for exactly those dates. | **Yes: exactly one block** | **Yes, a confirmed reservation** |
| `completed` (Completed / مكتمل) | The rental took place and the vehicle was returned. The block is kept as history. | Kept (history) | Fulfilled |
| `declined` (Declined / مرفوض) | HATEM could not accept. Reason required. | No (released) | No |
| `cancelled` (Cancelled / ملغى) | Withdrawn by the customer (before agreement) or cancelled by staff. Reason required. | No (released) | No longer |
| `expired` (Expired / منتهي الصلاحية) | No answer within the expiry window (**window pending, D-10**). | No (released) | No |

**When does a request become a confirmed reservation?** At the moment the staff action *Approve* (`transition_rental_request(…, 'approved', note)`) **commits successfully**. That single atomic step:
1. verifies the request is `in_review` or `awaiting_customer`, so review is mandatory;
2. verifies a **specific vehicle** is assigned, so category-only requests can't be approved;
3. verifies the **agreed price** is recorded (staff quote);
4. verifies an **agreement note** exists (how and when the customer agreed, e.g. "accepted on WhatsApp 30/11 10:12");
5. verifies pickup is in the future and the vehicle is `active`;
6. sets `agreed_at` and `agreed_by` (database time, database-known staff identity);
7. creates the **only** vehicle block for those dates.

If the vehicle is already blocked for overlapping dates, the whole step fails and **nothing changes** (tests W10, W11). Before this moment, no screen, message or email may call the request "confirmed".

*What "agreement" means in practice is a business definition the owner confirms (D-17):* for example, the customer accepted the vehicle, dates and price in writing on WhatsApp. The system records it but cannot verify it.

### 1.2 Transition table (enforced from data in `request_status_transitions` + function rules)

| From → To | Who may do it | Preconditions | Automatic effects |
|---|---|---|---|
| (new) → `submitted` | Guest session or signed-in customer | Valid fields; abuse limits (§2) | History event; **no block** |
| `submitted` → `in_review` | Staff / owner | — | Event |
| `submitted` → `declined` | Staff / owner | Reason | Event |
| `submitted` → `cancelled` | Staff / owner, **or the submitter** | Reason | Event |
| `submitted` → `expired` | Staff / owner, or a future scheduled job | — | Event |
| `in_review` → `awaiting_customer` | Staff / owner | — | Event |
| `in_review` → `approved` | Staff / owner | **Vehicle + agreed price + agreement note + future pickup + active vehicle + no conflict** | `agreed_at/by`; **block created atomically** |
| `in_review` → `declined` / `cancelled` | Staff / owner (cancel also the submitter) | Reason | Event |
| `awaiting_customer` → `in_review` | Staff / owner | — | Event |
| `awaiting_customer` → `approved` | Staff / owner | Same as above | Same as above |
| `awaiting_customer` → `declined` / `cancelled` / `expired` | Staff / owner (cancel also the submitter; expired also the system) | Reason for declined/cancelled | Event |
| `approved` → `completed` | Staff / owner | — | Block **kept** as history |
| `approved` → `cancelled` | **Staff / owner only** (the customer must contact HATEM; policy D-04 pending) | Reason | Block **released** (`request_closed`) |
| `completed`, `declined`, `cancelled`, `expired` → anything | **No one** | — | Final (W14, C21) |
| `submitted` → `approved` directly | **No one** | Review is mandatory | (W1) |

"Staff / owner" means an active `admin_users` row (roles `staff` or `owner`); deactivation takes effect immediately (E1, E2). Whether approval should be **owner-only** is decision **D-18**; it is a one-line change.

### 1.3 Modifying a request (vehicle, pickup, return)
- Only staff/owner, only through `modify_rental_request`, only for open or approved requests (not completed or closed), and a **reason is required** (it goes into the history).
- **Not yet approved:** the fields change and no block is created (M9, M9b).
- **Approved:** in one transaction, the request row is locked (serializing concurrent edits), the current block is released (`request_modified`), the request is updated, and a new block is created for the new vehicle and dates. If the new block conflicts, or any validation fails, **all three steps are undone**: the request, the old block and the history are exactly as before (M4, M4b, M5, M5b).
- Extending a reservation into its own old dates works, because the old block is released first in the same transaction (M3).

---

## 2. Guest requests and anti-spam

### 2.1 Flow
1. A visitor opens the request form. The website (Next.js) calls Supabase Auth **anonymous sign-in** with an **invisible CAPTCHA (Cloudflare Turnstile)** token. Supabase's documentation says it is *strongly recommended* to enable invisible CAPTCHA or Turnstile for anonymous sign-ins, and that anonymous sign-ins are limited to **30 per hour per IP** (configurable). Source: https://supabase.com/docs/guides/auth/auth-anonymous (checked 2026-11-30).
2. The guest now has a **session** (Postgres role `authenticated`, JWT claim `is_anonymous = true`). No account, password or email is needed.
3. The guest submits through `submit_rental_request` with an idempotency key (generated once per form). The database validates and applies the limits (§2.2), creates the request with a **contact snapshot**, and **never links it to an existing customer record**, so typing someone else's phone number gains nothing (S6, B25).
4. The confirmation shows the reference and the **"Continue on WhatsApp"** prepared message.
5. In the same browser session the guest can see their request's status and withdraw it while it is still open (not after approval). If the session is lost, they continue by WhatsApp using the reference.
6. Staff verify the person on WhatsApp/phone before approving. Linking the request to a customer record is a staff action.

### 2.2 Where each protection is enforced

| # | Protection | Enforced by | Trusted? | Status |
|---|---|---|---|---|
| 1 | **CAPTCHA** (Turnstile) on anonymous sign-in | **Supabase Auth server** (secret key in the dashboard) | Yes | ⏳ **Supabase-pending:** Supabase's CAPTCHA page lists sign-in, sign-up and password reset but does **not explicitly confirm** anonymous sign-in. Must be verified on the dev project. If it is not enforced, fall back to option B (§2.4). |
| 2 | **IP rate limit** on new guest sessions (30/h/IP by default) | Supabase Auth | Yes | ⏳ Supabase-pending (configure + verify) |
| 3 | **Session required to submit**: the `anon` role cannot call submit | DB privileges | Yes | ✅ B24, S1 |
| 4 | **Per-session limit** of 3 requests per 24 h | DB function | Yes | ✅ F2 |
| 5 | **Per-phone limit across all sessions** of 5 per 24 h | DB function | Yes | ✅ F1 (6 separate sessions) |
| 6 | **Blocked person's phone rejected**, even from a guest session | DB function | Yes | ✅ F3, C25 |
| 7 | **Idempotency**: unique key, bound to its session; a retry returns the same request, and another session's key is refused without revealing anything | DB unique constraint + function | Yes | ✅ B13, B28 |
| 8 | **Validation**: E.164 phone, name/message length, future pickup, return after pickup, published and active vehicle, active branch | DB constraints + function | Yes | ✅ B14–B20 |
| 9 | **Website rate limiting** (Vercel Firewall rule on the request page) | Vercel edge | Yes, **but** browser→Supabase calls don't pass through it | Optional defence in depth |
| 10 | Honeypot field, disabled double-click, client-side checks | Browser | **No. UX only, not security.** | App phase |
| 11 | Human verification before approval (WhatsApp/phone) | Staff | — | Workflow |

**What the database can NOT do:**
- It cannot verify a CAPTCHA (that needs a secret plus a call to the provider).
- It cannot reliably see the real client IP.
- It cannot prove the phone belongs to the person; that would need SMS or WhatsApp OTP, which costs money and is **not proposed** (D-16).

Those belong to Supabase Auth (layers 1–2) or another trusted server. The database **can and does** enforce everything else, and because Supabase exposes functions directly through the Data API, **only database-level limits are guaranteed** for every caller.

### 2.3 Phone validation
- **Database:** the strict E.164 format `+<country><number>`, 8–15 digits.
- **Website:** `libphonenumber`-style validation for Lebanese and international numbers, for good error messages. This is UX only, not security.
- **Restricting to +961 numbers only:** not imposed, because visitors and tourists may use foreign numbers (**D-16**).
- **Ownership:** verified by staff during the WhatsApp/phone conversation.

### 2.4 Fallback if CAPTCHA can't be enforced on anonymous sign-in (option B, not recommended unless needed)
Disable anonymous sign-ins. The website posts to a **Supabase Edge Function or Next.js route** that verifies the Turnstile token server-side, applies IP limits, then inserts through the same `app_private` function using a **server-only secret key**. The cost: a privileged key on a server, more code, and that path bypasses RLS (the function still validates everything). This will be decided only after the Supabase-pending check (layer 1).

### 2.5 Safe handling of anonymous submissions
- Names and messages are **untrusted text**: stored as data (B23), and must be rendered escaped. There is an E2E test for this, and the AI tools never read production data (prompt-injection risk).
- Guests see **only their own** requests, in their own session (B25–B27); never customers, notes, staff data or other guests (B30).
- Anonymous sessions never create customer records (S6).
- Retention and clean-up of old guest sessions and requests: **D-11**.

---

## 3. Approved-request modifications: design and proof

| Requirement | Mechanism | Tests (all passing locally) |
|---|---|---|
| Vehicle change | Release old block, update request, create new block, in one statement | M1, M1b, M1c |
| Pickup-date change | Same | M2, M2b |
| Return-date change (incl. extension over its own old period) | Same | M3, M3b |
| Conflicting vehicle block | Exclusion constraint → `VEHICLE_CONFLICT` → full rollback | M4, M4b, M5, M5b |
| Invalid input | Validation before changes; rollback | M6, M7, M13, M14, M16 |
| Failed update & rollback | Request, old block and history unchanged; no new block | M4b, M5b, W11 |
| Concurrent modifications of one request | `SELECT … FOR UPDATE` serializes; both applied in order; one matching block | **G2** (2 real sessions) |
| Concurrent approvals for the same car/dates | Exclusion constraint: one wins, the other is unchanged | **G3** |
| Modification racing an approval | One wins; no stale block | **G4** |
| No stale or duplicate blocks, ever | Unique index (one active per request); immutable blocks; **deferred invariant checked at COMMIT, even for the superuser** | I1–I8 |
| Closed and completed requests | Cannot be modified | M10, M15 |
| Customers or guests | Cannot modify | M8 |

---

## 4. Database architecture review (table by table)

Sensitivity: 🔴 personal data · 🟠 internal / operational · 🟢 public.

| Table | Purpose | Relationships | Sensitive fields | Access | Why it stays separate |
|---|---|---|---|---|---|
| `admin_users` | Who is staff or owner | → `auth.users` (1:1) | Role 🟠 | Owner manages; staff see own row | Authorization must never live in user-editable metadata or in `customers` |
| `branches` | Pickup/return places (today: Tripoli) | ← vehicles, requests | — 🟢 | Public read (active); owner edits | Foreign key target for pickup/return; adding delivery points later needs no rewrite. *Cost: one row.* |
| `vehicle_categories` | Bilingual category labels | ← vehicles, requests | — 🟢 | Public read; managed directly by the owner | A lookup keeps AR/EN labels in one place |
| `vehicles` | Public listing data | → branch, category; ← photos, rates, blocks, requests | `details_verified_by` (admin UUID, see §5 F9) 🟢/🟠 | Public: published only; staff all; **owner-only verification** | Kept free of private data so it can be public |
| `vehicle_private_details` | Plate, VIN, internal notes | 1:1 → vehicles | Plate / VIN 🟠 | **Staff only** | Supabase/PostgREST reads whole rows (`select *`); a separate table is the reliable way to hide columns from the public |
| `vehicle_photos` | Photo metadata (file in Storage) | → vehicles | — 🟢 | Public: published photos of published vehicles; staff write/delete | Many photos per vehicle |
| `vehicle_rates` | **Owner-verified** prices, when they exist | → vehicles | — 🟢 | Public: published + verified only; **owner-only write** | ⚠️ **Simplification candidate:** unused by the current workflow (prices come from staff quotes). Keep, or defer until D-01 is decided. **Owner choice (D-19).** |
| `customers` | Known people (signed-in or staff-verified) | → `auth.users` (optional); ← requests, notes | 🔴 Name, phone, email; `is_blocked` 🟠 | Own row (limited columns); staff all | Guests are **not** customers until verified; prevents profile hijacking |
| `customer_notes` | Internal notes about a person | → customers, admin_users | 🔴 Free text | **Staff only** | Customers can read their own `customers` row, so internal notes can't live there |
| `request_statuses` | Status definitions + labels | ← requests, transitions, events | — 🟢 | Public read | The workflow is data, not code |
| `request_status_transitions` | Allowed moves and who may make them | → statuses | — 🟢 | Read (authenticated) | Lets the owner change the workflow without a rewrite. *Small, fully tested; keep.* |
| `rental_requests` | **The core object** | → customer (optional), vehicle, category, branches, status, admin_users | 🔴 Contact snapshot, message; quote 🟠 | Submitter / linked customer: own; staff all. **No direct insert, status, vehicle or date updates.** | — |
| `rental_request_events` | Append-only history | → requests, statuses | 🔴 Notes may contain personal data | Staff all; customer: own and customer-visible only | Immutable history must not be overwritable with the request |
| `vehicle_unavailability` | **The only source of "vehicle blocked"** (reservations + maintenance + owner use) | → vehicles, requests (optional), admin_users | 🟠 | Staff read; staff create/release **operational** blocks only; **reservation blocks only through the workflow functions** | Requests don't reserve; one exclusion constraint protects every kind of block, and future bookings can reuse it |
| `business_settings` | Single row: names, WhatsApp, phone, email, timezone | — | Public contact data 🟢 | Public read; owner edits | Single source for the WhatsApp number (fixes L-008) |
| `audit_log` | Who changed what (vehicles, rates, prices, settings, customers, requests, blocks, admins) | — | 🔴 Full row copies | **Owner only**; written only by trigger | Must be outside the reach of the people it audits |
| `storage.objects` (`vehicle-photos`) | Photo files | ↔ `vehicle_photos.storage_path` | — 🟢 | Public download by exact URL; **staff-only upload/update/delete/list** | Supabase Storage |

**Complexity review:**
- **Removed:** `business_settings.updated_by`, since the audit log already records it.
- **Candidates for the owner to decide:**
  - D-19: defer `vehicle_rates`.
  - D-15: drop *category-only* requests (`requested_category`) if customers always pick a specific car. That removes the "assign a vehicle before approval" step.
- **Considered and kept:**
  - Merging `customer_notes` into request events: rejected, because the subjects differ (person vs request).
  - Merging `vehicle_private_details` into `vehicles`: rejected, because the column could then be exposed.
  - Replacing the transitions table with code: rejected, because it is small and lets you change the workflow without code.
- **No security or integrity control was removed to simplify.**

```mermaid
erDiagram
  AUTH_USERS ||--o| ADMIN_USERS : "staff/owner"
  AUTH_USERS ||--o| CUSTOMERS : "optional login"
  BRANCHES ||--o{ VEHICLES : "home branch"
  VEHICLE_CATEGORIES ||--o{ VEHICLES : categorises
  VEHICLES ||--o| VEHICLE_PRIVATE_DETAILS : "staff-only"
  VEHICLES ||--o{ VEHICLE_PHOTOS : has
  VEHICLES ||--o{ VEHICLE_RATES : "owner-verified"
  VEHICLES ||--o{ VEHICLE_UNAVAILABILITY : "blocked periods"
  CUSTOMERS |o--o{ RENTAL_REQUESTS : "linked after verification"
  CUSTOMERS ||--o{ CUSTOMER_NOTES : "staff notes"
  VEHICLES |o--o{ RENTAL_REQUESTS : requested
  BRANCHES ||--o{ RENTAL_REQUESTS : "pickup/return"
  REQUEST_STATUSES ||--o{ RENTAL_REQUESTS : status
  REQUEST_STATUSES ||--o{ REQUEST_STATUS_TRANSITIONS : "from/to"
  RENTAL_REQUESTS ||--o{ RENTAL_REQUEST_EVENTS : history
  RENTAL_REQUESTS |o--o{ VEHICLE_UNAVAILABILITY : "0..1 ACTIVE block, only when approved"
```

---

## 5. Security review (v1.1)

### 5.1 Findings

| # | Area | Finding | Severity | Status |
|---|---|---|---|---|
| F1 | Anonymous access / Data API | v1.0 let the `anon` role call `submit_rental_request` directly, so a bot could skip any website protection | High | **Fixed:** session required; anon can execute only `check_vehicle_availability` (S1, B24) |
| F2 | Data integrity | v1.0 let staff `UPDATE` a request's vehicle and dates directly, leaving a stale block | High | **Fixed:** column privilege revoked (W9, W9b); `modify_rental_request` + invariants |
| F3 | Data integrity | Staff could insert or release reservation blocks by hand | High | **Fixed:** RLS limits staff to operational blocks (W7, W8) |
| F4 | Audit integrity | Release time and actor were client-supplied | Medium | **Fixed:** server-stamped (W11b, W11c) |
| F5 | Data integrity | Blocks could be re-targeted or re-activated in place | Medium | **Fixed:** immutability trigger (I4, I5) |
| F6 | Abuse | A blocked customer could submit as a guest | Medium | **Fixed:** phone check (F3) |
| F7 | Information disclosure | A reused idempotency key returned another session's reference | Low | **Fixed:** bound to session (B28) |
| F8 | Information disclosure | `business_settings.updated_by` (admin UUID) readable by the public | Low | **Fixed:** column removed |
| F9 | Information disclosure | `vehicles.details_verified_by` and `vehicle_rates.verified_by` (admin UUIDs) are readable by the public | Low | **Accepted (documented).** UUIDs are not credentials, and RLS prevents any use of them. Option: column-level grants, at the cost of explicit column lists in every query. |
| F10 | Information disclosure | `check_vehicle_availability` lets anyone probe a published car's blocked periods (yes/no, range ≤ 366 days) | Low | **Accepted.** Needed on public pages. Option: require a guest session. |
| F11 | Data API surface | `pg_graphql` (if enabled on the project) exposes tables under the same grants and RLS | Low | ⏳ Supabase-pending: **disable GraphQL** if unused |
| F12 | Storage | Public bucket: anyone with an exact URL can download an *unpublished* photo | Low | **Mitigated:** UUID file names (S9), no public listing (S16). Staff must not upload non-public images. |
| F13 | Storage | Size and MIME limits are enforced by the Storage API, not SQL | Medium | ⏳ Supabase-pending test |
| F14 | Audit / privacy | The audit log stores full row copies, including personal data | Medium | Owner-only (D18, E4). **Retention D-11.** |
| F15 | Anonymous users | Supabase warns that policies combine permissively and anonymous users share the `authenticated` role | Medium | **Reviewed:** every `TO authenticated` policy also requires ownership or staff; the only role-wide reads are public reference data (statuses, transitions, settings). Tested: B25–B30, S6. |
| F16 | Stored XSS | Customer text is stored raw (correct); the risk is in rendering | High if mishandled | DB part ✅ (B23). ⏳ E2E: escaped rendering in the admin UI; also guard spreadsheet **formula injection** if admin exports are added. |
| F17 | Sessions | A deleted or demoted user's JWT stays valid until it expires | Medium | Staff deactivation takes effect immediately at DB level (E1, E2). Recommend short JWT expiry + session revocation (Supabase-pending configuration). |
| F18 | Connected tools | The Supabase connector on your claude.ai account is **account-wide** (not limited to one project, not read-only) | Medium | ⚠️ Operational: reconnect it scoped to the **dev** project, read-only. Nothing was run with it. |

### 5.2 SECURITY DEFINER inventory (all in the non-exposed `app_private` schema, all with `search_path = ''`, tests A2/A3)

| Function | Callable by | Why it needs definer rights | Internal check |
|---|---|---|---|
| `is_staff()` | anon, authenticated | Reads `admin_users` inside policies | `auth.uid()` (anon: always false) |
| `is_owner()`, `current_customer_id()` | authenticated | Same | `auth.uid()` |
| `submit_rental_request()` | authenticated (guest or customer) | Inserts the request + event; creates a customer row | Session required; limits; validation |
| `transition_rental_request()` | authenticated | Status change + block create/release | `is_staff()`; transition table; approval preconditions |
| `modify_rental_request()` | authenticated | Atomic block swap | `is_staff()`; status; validation |
| `cancel_my_rental_request()` | authenticated | Status change by the submitter | Ownership with `COALESCE(…, false)` (L-015) |
| `check_vehicle_availability()` | anon, authenticated | Reads blocks (staff-only table) | Returns only `blocked` / `no_known_conflict` |
| `write_audit()`, `check_request_block_consistency()`, `log_quote_change()` | nobody directly (triggers) | Write audit/events; verify invariants | — |

**What the Data API exposes** (only the `public` schema), pinned by tests:
- `anon`: exactly **1** function (S1).
- `authenticated`: exactly **5** functions (S2).
- `anon` reaches exactly **2** definer functions (S3).
- `anon` has **no** write privilege on any table (S4).
- The only DELETE privilege for API roles is on `vehicle_photos`, for staff (S5).

### 5.3 Storage
One bucket, `vehicle-photos`: public download, 5 MB, JPEG/PNG/WebP/AVIF. Files are named `vehicles/<id>/<uuid>.<ext>`. Upload, update, delete and list are staff-only (S8–S16). **There is no customer-document bucket**, because uploads are pending (D-06).

---

## 6. Vehicle availability logic (unchanged principle, stronger enforcement)
- **Only `approved` requests and staff operational blocks make a car unavailable.**
- One exclusion constraint guarantees no two active blocks overlap for the same car (D9–D11, G1, G3, G4).
- The public hint never says "available" (B21).
- The cleaning gap (D-03) will become a buffer on reservation blocks; the invariant check will then compare against `period + buffer`.

## 7. Future confirmed bookings and payments
`approved` already *is* the confirmed reservation, with agreement data, an agreed price and a block, so a separate `bookings` table is **only needed if** payments, contracts or handover records are added (D-07). Those tables would reference `rental_requests` and reuse `vehicle_unavailability`. No rename or rewrite is needed.

## 8. Threat model (summary; details in SECURITY.md)
The main risks are the same as v1.0. The **spam / direct-API threat (T2)** is now addressed in layers (§2.2), and **stale or duplicate reservations** are now a database invariant (§3).

## 9. Testing: what is verified where

| Tier | Status | Count / scope |
|---|---|---|
| **A. Locally verified PostgreSQL tests** (PostgreSQL 16.15 + test-only Supabase shim) | ✅ **184 passed, 0 failed** | 178 SQL assertions (groups A–F from v1.0, plus W, M, I, S) + 6 multi-session tests (G1–G4, I7, I8) |
| **B. Supabase-specific, pending** (needs a dev project) | ⏳ Not run | Re-run the suite on `supabase start` and the dev project · run the security and performance **advisors** · real JWTs: `auth.uid()`, the `is_anonymous` claim · **CAPTCHA enforced on anonymous sign-in** · anonymous sign-in IP limit · `app_private` **not** reachable via `/rpc` · GraphQL exposure · Storage API: public URL download, MIME/size rejection, listing denied · default privileges on a new project · JWT expiry/revocation settings · the Postgres version of the project |
| **C. Browser / E2E, pending** (app phase) | ⏳ Not written | Guest flow with Turnstile on mobile (390 px) in AR-RTL and EN-LTR · double-tap submit gives one request · network failure shows no false success · WhatsApp prepared message (encoding, AR/EN, button hidden without a number) · **XSS payload renders as text in admin** · staff approve/modify UI shows `VEHICLE_CONFLICT` clearly · accessibility (axe, keyboard) · performance |

**Changes to v1.0 tests (none removed or weakened):**
- B12–B20 and B23 now run as a **guest session**, with identical assertions, because the session-less path was deliberately closed. The new B24 proves that path is closed.
- D19/D20 run **before** D7, because approval now requires the agreed price; the assertions are unchanged.
- D8's wording changed from "staff can block the vehicle" to "approval blocked the vehicle (exactly one block)". Manual blocking is now asserted to **fail** (W7).
- F1 is **stronger**: the same phone across 6 different sessions.
- Two new test-harness lessons (L-017) were applied: no same-statement snapshot checks, and numeric comparisons in the runner.

## 10. Migration and backup strategy
Unchanged from v1.0. Supabase daily backups exist only on paid plans and **do not include Storage files**; a logical dump is taken before every production migration, plus a separate photo backup and a restore drill. Source: https://supabase.com/docs/guides/platform/backups. Migration 5 (Storage) inserts the bucket idempotently (`on conflict do nothing`).

## 11. Business decisions pending (never encoded as rules)
D-01 duration and extra-hour pricing · D-02 grace period · D-03 cleaning gap · D-04 cancellation policy (incl. customer self-cancel of confirmed reservations) · D-05 opening hours · D-06 documents · D-07 payment methods and currency · ~~D-08 sign-in required~~ → **owner chose guest requests** · D-09 driver age/licence · D-10 expiry window · D-11 data retention (requests, guests, audit) · D-12 Supabase plan · D-13 status names (owner: keep for now) · D-14 delivery locations · **New:** D-15 keep category-only requests? · D-16 phone rules (+961 only? OTP?) · D-17 what counts as "customer agreement" · D-18 approval owner-only or staff too · D-19 defer `vehicle_rates`?

## 12. Known issues ranking
Unchanged from v1.0 (L-001 … L-014). L-015 to L-019 are design and test lessons found and fixed during this work (see ENGINEERING_LESSONS.md).

## 13. Needed from the owner before implementation
1. Approve or adjust §1 (meanings + transition table) and D-17 / D-18.
2. Approve the guest design (§2), knowing the CAPTCHA layer must be verified on Supabase first.
3. Decide D-15 and D-19 (the simplification candidates).
4. Provide a **Supabase dev project** (scoped, read-only connector) so tiers B and C can start.
