# Sign in with UnityX on 1Network

UnityX (auth.unx.ng) is the shared sign-in for UNX sites. 1Network uses its first-party hand-off: the browser goes to UnityX, comes back with a one-time code, and the 1Network API trades the code for a normal 1Network session.

## How it works
1. The sign-in page asks `GET /api/auth/unityx/status` whether UnityX is switched on, and where to send the person.
2. The page makes a random `verifier` (kept in the browser) and sends the person to
   `https://auth.unx.ng/?callback=<site>/auth/sign-in/&state=<random>&challenge=<SHA-256 of verifier>`.
3. UnityX signs the person in and returns to the callback with `?unx_code=…&unx_state=…`.
4. The page checks `state`, then calls `POST /api/auth/unityx/exchange { code, codeVerifier }`.
5. The API asks UnityAuth (`/v1/auth/handoff/exchange`) for the UnityX user, as the 1Network site. It matches the user by email, creates the account on first sign-in, links UnityX to it, and starts a Better Auth session (cookie, and a bearer token for mobile apps).

UnityX only signs in people whose email is verified, so matching by email is safe.

## Switching it on (once)
In UnityAuth (a UnityX admin does this):
- Add the site `ngx.1network.com.ng` as a domain, and add `https://ngx.1network.com.ng` to the trusted origins and `ngx.1network.com.ng` to the allowed hosts.

On the 1Network server (`/vx/app/1network/.env`, then restart `1network-backend`):
```
UNITYX_ENABLED=1
# optional, these are the defaults:
# UNITY_AUTH_URL=http://127.0.0.1:4420
# UNITYX_SITE_ORIGIN=https://ngx.1network.com.ng
# UNITYX_AUTH_PUBLIC_URL=https://auth.unx.ng
```

## Endpoints
| | |
|---|---|
| `GET /api/auth/unityx/status` | `{ enabled, authUrl }` |
| `POST /api/auth/unityx/exchange` | `{ code, codeVerifier }` → `{ token, user }` and the session cookie |

## Local testing
`dev/mock-unityauth.mjs` stands in for UnityAuth on port 4420; run the backend with `UNITYX_ENABLED=1`.
