# Hosted version (SaaS): many ISPs on one server

One codebase, **one database and one encryption key per ISP**. The billing app itself is unchanged and still thinks it serves a single ISP; a thin platform layer decides which ISP a request belongs to (from the web address), connects to that ISP's own database and key, and handles signup, subscriptions and the console.

Why this design: see "One ISP per installation" in [DESIGN.md](DESIGN.md). Putting a `tenant_id` on every table was tried and dropped. Here an ISP's data can never be read by another ISP's code path, because the other database is simply not connected.

## What you get

- **Paid signup, no free trial.** The page on your main domain asks for the business name, a web address (`isp1.yourdomain`, checked live), their own password, email and phone. A 6-digit code goes to the **phone by WhatsApp** (your Meta Cloud API settings) and another to the **email**; both must be confirmed. Then they pay your plan price (M-Pesa prompt, or Paybill with the account code shown). **The ISP's database and panel are created only after both codes are confirmed and the price is paid**; they sign in with the password they chose. The address is reserved while the signup waits (48 hours by default, never dropped once money has come in). Part payments add up; payment before confirmation is kept and used once both codes are in. Console → *Signups* shows who is waiting, with *Record payment*, *Create now* and *Remove*.
- You set the plan prices in the console; the amount paid at signup buys time in 30-day months, as for renewals. "Free days" applies only to ISPs you add by hand (default 0).
- **Console** (`admin.yourdomain`): all ISPs with status, plan, paid-until date, customers and routers; add days, suspend, resume, delete, record manual payments, see every receipt and unmatched payment, edit plans and your own M-Pesa settings.
- **M-Pesa auto-renewal of the monthly fee.** The ISP pays your Paybill with its **account code** as the account number (or presses *Pay now* for an STK prompt). The subscription extends itself, safely against retries. Payment buys time in 30-day months at the plan price (half the price buys 15 days). An unknown account code is kept as *unmatched* and you can give it to the right ISP later.
- **Active → grace → locked.** After the end date an ISP has a few grace days (3 by default), then its staff panel closes. **Customer payments keep being recorded** (callbacks and the customer portal stay open) so no money is lost. Paying reopens it at once. Suspended ISPs are only reopened by you.
- **Reminders** a few days before the end, and a banner in the ISP's panel with your Paybill and its account code.
- **Plan limits** (customers and routers per plan; 0 = unlimited).
- **Customer money goes to each ISP's own Paybill or Till.** Only the SaaS fee comes to you.
- Routers: each router is either RADIUS or direct RouterOS API, as in the single-ISP version. **One RADIUS daemon and one WireGuard interface serve every ISP** (see "Shared RADIUS and WireGuard").

## Install

1. A server as in [INSTALL.md](INSTALL.md) (PHP 8.1+, MariaDB, Apache, php-sodium, php-curl, php-mbstring).
2. DNS and certificates with **Cloudflare**:
   - `A yourdomain`, `A admin` and a wildcard `A *` all pointing at the server, **proxied (orange cloud)**. Universal SSL covers `yourdomain` and `*.yourdomain` (one level), which is all `isp1.yourdomain` needs.
   - SSL/TLS mode **Full (strict)**, with a Cloudflare **Origin CA certificate** for `yourdomain` and `*.yourdomain` installed on the server (replace the Let's Encrypt paths in `deploy/apache-saas.conf`).
   - Real visitor IP: enable the `remoteip` module block in `deploy/apache-saas.conf` and refresh the ranges with `deploy/cloudflare-ips.sh`. Without it every staff login and rate limit sees a Cloudflare address.
   - WireGuard (when phase 2 is in): its public host name must be a **DNS-only (grey cloud)** record such as `vpn.yourdomain`, because Cloudflare does not proxy UDP.
   - WAF / Bot Fight: add a skip rule for paths `/provision/`, `/api/router_backup` and the Safaricom callbacks `/mpesa/` so routers and Safaricom are not challenged.
   - Another domain per ISP is not set up (see below).
3. WhatsApp and email for the codes: console → Settings → WhatsApp (phone-number id, token, mode; a template with one body variable is needed for numbers that have not messaged you in 24 hours) and the mail settings. Use the **Send test** buttons before opening signup.
4. A MariaDB user that can create databases named `isp_%` (this is what creates each ISP's database) and owns the platform database:
   ```sql
   CREATE DATABASE platform CHARACTER SET utf8mb4;
   CREATE USER 'saas'@'127.0.0.1' IDENTIFIED BY '...';
   GRANT ALL ON platform.* TO 'saas'@'127.0.0.1';
   GRANT ALL ON `isp\_%`.* TO 'saas'@'127.0.0.1';
   GRANT CREATE, DROP ON *.* TO 'saas'@'127.0.0.1';   -- only if you want the console to create and delete databases itself
   ```
5. `config/config.php`: copy `config/config.sample.php` and add the hosted block:
   ```php
   'saas' => [
     'base_domain'  => 'yourdomain',
     'platform_host'=> 'admin.yourdomain',
     'master_key'   => 'base64 of 32 random bytes',   // seals every ISP's own key; back it up with the platform database
     'platform_db'  => ['dsn' => 'mysql:host=127.0.0.1;dbname=platform;charset=utf8mb4', 'user' => 'saas', 'pass' => '...'],
     'tenant_db'    => ['dsn' => 'mysql:host=127.0.0.1;dbname=x;charset=utf8mb4', 'user' => 'saas', 'pass' => '...'],   // dbname is replaced per ISP
     'db_admin'     => ['dsn' => 'mysql:host=127.0.0.1;charset=utf8mb4', 'user' => 'saas', 'pass' => '...'],
     'db_prefix'    => 'isp_',
     'wg_base'      => '10.99',
   ],
   ```
   plus `'db'` (the platform database again), `'app_key'` (the platform's own) and `'public_url'` (`https://admin.yourdomain`).
6. Create the platform tables and the first platform admin:
   `php bin/platform.php install you@example.com 'a-strong-password' "Your Name"`
7. Web server: `deploy/apache-saas.conf` (two virtual hosts: `public/platform/` for signup and console, `public/` for every ISP).
8. Cron: `deploy/billing-saas.cron` (every ISP job runs through `bin/tenants_run.php`, one process per ISP, plus `platform.php tick` and `count`).
9. In the console → Settings: enter **your** Paybill/Till, Daraja key, secret and passkey, and register the confirmation and validation URLs shown there with Safaricom. Set grace days, signup hours and the plans (name, monthly price, customer and router limits).

## Daily use

```
php bin/platform.php list
php bin/platform.php create isp1 "ISP One Ltd" owner@isp1.co.ke 0712345678
php bin/platform.php extend isp1 30
php bin/platform.php suspend isp1     # or: resume isp1
php bin/platform.php delete isp1 --drop-data     # cannot be undone
SB_TENANT=isp1 php bin/migrate.php --status      # run any ISP command against one ISP
```

**Updating everyone:** `git pull && php bin/platform.php upgrade-all` applies the new database migrations to every ISP, one by one. Take a backup first.

## Shared RADIUS and WireGuard

One WireGuard server (the one already on the machine) and one RADIUS daemon serve every ISP.

- **Tunnel ranges.** ISP number *n* owns `10.99.<n>.0/24`; a router's tunnel address and RADIUS source address are in that range. The ISP whose database is used for a RADIUS packet is decided **only by the packet's source address**, then the packet is handled with that ISP's own database, routers and customers. Another ISP's customers and router secrets are never consulted. Sources outside the tunnel network, or in an unused or suspended ISP's range, get no answer.
- **Status.** Active, grace and locked ISPs keep RADIUS service (their customers keep their internet and payments keep activating them). Suspended ISPs get none. Changes apply within 30 seconds.
- **`bin/radius_server.php`** (service file `deploy/radius.service`, unchanged): in hosted mode it serves all ISPs, writes a RADIUS heartbeat into each ISP's own settings (so each panel shows "RADIUS running"), and closes stale sessions and prunes logs per ISP.
- **`bin/wg_sync.php`** (root, every minute; it replaces the single-ISP wg_sync cron): rebuilds the peer list from all ISPs' routers. Each peer has **only its own /32**. A router whose address is outside its ISP's `/24`, or whose public key or address is claimed twice (by one ISP or two) is left out and reported on stderr. A suspended ISP's routers are not peers. It also loads an nftables table `sb_iso` that drops forwarding from the tunnel back into the tunnel, so one ISP's routers can never reach another's.
- **Not offered in hosted mode:** radio-network routes (Devices page) and the router remote-access ports, because their addresses and ports could collide between ISPs.
- **Taking over the install that is already running.** Register its database as ISP number 0, which owns `10.99.0.0/24` (the range the old server address `10.99.0.1` lives in):
  ```
  php bin/platform.php adopt eazy "Your ISP" you@example.com <its_db_name> '<app_key from its old config.php>' --domain=system.eazyradius.co.ke
  ```
  Then stop the old `radius` service and the old wg_sync cron, start this repo's, and point `system.eazyradius.co.ke` at the hosted Apache vhost (or leave the old web copy running; only RADIUS and WireGuard need to move). It warns about any router whose tunnel address is outside `10.99.0.0/24`: move those into the range first, or they get no service. Take a database backup before this.
- Config keys: `radius.map_refresh` (seconds between reading the ISP list, default 30), `wireguard.isolation_nft` (where the generated rule file is kept).

## What is not done yet

- Radio-network routes and remote-access ports in hosted mode (see above).
- ISP custom domains: the column works for routing (`adopt --domain`), but there is no console screen yet.
- Impersonating an ISP's admin from the console.
- Everything was tested against a local MariaDB and **mock M-Pesa, WhatsApp, SMTP and a mock RADIUS client**, not against Safaricom, Meta, Cloudflare, a real WireGuard interface or real routers. `wg syncconf` and the nft rule were checked only as generated text.
