# Unity-Agents.md — UNX account (UnityAuth) guide for humans and AI agents

Canonical host: `https://auth.unx.ng`. Public guide: `/docs/`. Full guide (sign-in required): `/account/docs/`.
This file is the portable summary: give it to a developer or load it into an AI coding agent as context.

---

## 1. What this is

UnityAuth is the identity service behind every UNX site. One account (email + optional username) signs a person in to
UNX apps and to partner sites ("Sign in with UNX"). Organisations are called **tenants** and are identified by a `tid`.

| Concept | Meaning |
| --- | --- |
| User | A person. Has `id`, `email`, optional `username` (3–10 chars `a-z0-9`), `emailVerified`, platform `role`. |
| Session | Server-side; the browser holds an HttpOnly cookie (`unx.session_token`). Lasts 7 days, renewed at most daily. |
| Tenant | An organisation/app. `tid`: 3–64 chars of `a-z 0-9 - _`, permanent. Default tenant `unityx` (UnityHUB) has every user. |
| Tenant role | `owner` > `admin` > `member`. Applies only inside that tenant. |
| App role | A tenant-defined label such as `editor` or `lga:imo/oguta` (`name` or `name:scope`), from the tenant's role catalogue. |
| API key | `unx_live_…` secret for one tenant, shown once. For servers only. |
| Key pair | Public `unx_kid_…` id + `unx_sec_…` secret for one tenant. The secret is shown once. For servers only. |
| Authorized host | A site/domain enrolled in Unity auth (Admin → Domains) and linked to a tenant. Only enrolled hosts may use sign-in, receive handoffs, be OAuth redirect targets or send a browser origin with a tenant credential. |
| Platform role | `user`, `support`, `admin`, `super-admin` (permission keys like `tenant:manage`). |

## 2. For people (short version)

1. **Create an account:** `https://auth.unx.ng/?view=signup` → name, email, password (8+ chars) → enter the 6-digit email code (valid 5 minutes, 3 attempts).
2. **Sign in:** email or username + password, or "Email me a sign-in code", or Google when linked.
3. **Forgot password:** "Forgot password?" on the sign-in page → emailed link or 6-digit code.
4. **Manage:** `/account/` — Profile, Security (password, linked accounts), Devices (sign out sessions), Files, Organisations.
5. **Safety:** UNX never asks for your password or a code by chat or phone. Only type codes into `auth.unx.ng`.
6. **Own tenants:** create them at `https://developer.unx.ng/console/`. Default limit is **10 owned tenants** per user; an admin can raise or lower it per user.

## 3. For developers

### 3.1 Choose how to authenticate

| Situation | Use |
| --- | --- |
| Your **website** with signed-in users | Same-origin `/v1` proxy to UnityAuth + session cookie. Your host must be **enrolled** (Admin → Domains, super-admin). |
| Your **server** acting for your tenant, simple | **API key**: `Authorization: Bearer unx_live_…` or `X-API-Key`. |
| Your **server**, separate id and secret | **Key pair**: `Authorization: Basic base64(unx_kid_…:unx_sec_…)` or `X-Key-Id` + `X-Key-Secret`. |
| A **third-party app** signing users in | **OAuth 2.1 / OIDC**: authorization code + PKCE. |
| A **machine** with no user | **OAuth** `client_credentials`. |
| A **TV / CLI / device** with no browser | **OAuth** device grant (RFC 8628). |

Rules that apply to all of them:
- **Authorized hosts.** A tenant credential is a server secret. If a request carries an `Origin` or `Referer`, that host must be enrolled and linked to the key's tenant (or be the tenant's own site); otherwise `403 host_not_authorized`. Calls with no `Origin` (real server-to-server) are unaffected. OAuth redirect URIs must also be on enrolled hosts (`pnpm oauth:client` enforces it).
- A pair's secret is **not** a bearer key on its own; always send it with its key id.
- Create credentials in the developer console or `POST /v1/tenants/:id/api-keys` with `{"name":"…","type":"key"|"pair"}`. A pair answers `{keyId, secret, apiKey}`; the secret is shown once.

### 3.2 Send users to sign-up and bring them back (server side)

```bash
curl -X POST https://auth.unx.ng/v1/integration/signup \
  -H "Authorization: Bearer unx_live_…" -H "Content-Type: application/json" \
  -d '{"callback":"https://example.com/welcome"}'
# → { "tenant": {...}, "callback": "...", "signupUrl": "https://auth.unx.ng/?view=signup&tenant=<tid>&callback=..." }
```

Hand `signupUrl` to the user (it holds no secret). The callback must be on the tenant's website or a linked domain.

### 3.3 Endpoints

Errors are `{ "error": { "code", "message", "requestId", "details" } }`. ~100 requests/minute/client; 3 sign-in code emails/minute.

**Sign-in (Better Auth, prefix `/v1/auth`)**

| Method + path | Notes |
| --- | --- |
| `POST /sign-up/email` | `name,email,password,username?` |
| `POST /sign-in/email` · `POST /sign-in/username` | `…,password,rememberMe?` |
| `POST /email-otp/send-verification-otp` | `email,type: sign-in \| email-verification \| forget-password` |
| `POST /sign-in/email-otp` | `email,otp,name?` |
| `POST /sign-in/social` | `provider:"google",callbackURL` |
| `GET /get-session` · `POST /sign-out` | |
| `GET /list-sessions` · `POST /revoke-session` · `POST /revoke-other-sessions` | |
| `POST /change-password` · `GET /list-accounts` · `POST /unlink-account` | |
| `GET /v1/me/permissions` | platform role(s) and permission keys |

**Tenants (session cookie)**

| Method + path | Notes |
| --- | --- |
| `GET /v1/me/tenants` · `GET /v1/me/tenant-limit` | memberships · `{limit,custom,owned}` |
| `POST /v1/tenants` | `name,tid?,description?,url?,contactEmail?` (email must be verified; blocked at the limit with `limit_reached`) |
| `GET/PATCH/DELETE /v1/tenants/:id` | read (member) · edit (admin+) · delete (owner) |
| `GET /v1/tenants/:id/members` | |
| `GET/POST /v1/tenants/:id/api-keys` · `DELETE …/:keyId` | body `{name,type?:"key"\|"pair",expiresInDays?}`; max 20 active; secret returned once (`{key}` or `{keyId,secret}`) |
| `GET/PUT /v1/tenants/:id/role-catalogue` · `PUT …/members/:userId/roles` | app roles |

**Integration (API key; acts only on the key's own tenant)**

| Method + path | Notes |
| --- | --- |
| `GET /v1/integration/whoami` | verify a key or pair (`apiKey.type` is `key` or `pair`) |
| `GET /v1/integration/members` · `POST` `{email}` · `DELETE …/:userId` | membership |
| `GET/PUT /v1/integration/members/:userId/roles` | `{roles:["editor","lga:imo/oguta"]}` |
| `POST /v1/integration/signup` | see 3.2 |

**Files (session cookie)** — `/v1/files`: `POST /uploads?name=&visibility=private|public&purpose=general|avatar|document` (raw bytes), `GET /`, `GET /usage`, `GET /:id/content`, `PATCH /:id`, `DELETE /:id`. Images ≤ 5 MB, documents ≤ 20 MB, 200 MB per account.

**Admin console** — `https://auth.unx.ng/account/` → Admin (also `/admin`). Tabs: Users, Developers, Tenants, Domains, Sign-ins, Audit log. Every row opens a detail page (`?tab=tenants&id=…`): user (devices, tenants, keys, sign-ins), tenant (members, hosts, keys, OAuth apps, sign-ins, suspend/reactivate), domain (tenant, sign-ins to the host), audit event.
*Sign-ins* record, for each login, the date/time, the portal / site host / OAuth app, the tenant, the IP and approximate location (`GET /v1/admin/login-events`, `audit:read`). "Developers" = people who own a tenant, issued a key or registered an OAuth app.

**Staff (permission-gated)**

| Method + path | Permission |
| --- | --- |
| `GET /v1/admin/tenant-limits?q=&page=` | `tenant:manage` |
| `GET/PUT /v1/admin/tenant-limit-defaults` — platform default and per-role defaults | `tenant:manage` |
| `PATCH /v1/admin/tenant-limits/:userId` body `{limit:number\|null}` (null = default 10) | `tenant:manage` |
| `GET/POST /v1/admin/domains` · `PATCH/DELETE /v1/admin/domains/:id` | `domain:read` / `domain:manage` |
| `GET /v1/admin/audit-logs` · `GET /v1/admin/audit-logs/:id` · `GET /v1/admin/login-events?userId=&tenantId=&host=&clientId=&kind=` | `audit:read` |
| `GET /v1/admin/tenants?q=&page=` · `GET /v1/admin/tenants/:id` · `GET /v1/admin/developers?q=&page=` | `tenant:read` |
| `PATCH /v1/admin/tenants/:id` body `{status:"active"\|"suspended"\|"pending"}` | `tenant:manage` |
| `GET /v1/admin/users/:id` | `user:get` |

### 3.4 OAuth 2.1 / OpenID Connect

Issuer `https://auth.unx.ng/v1/auth`. Enabled per deployment (`OAUTH_PROVIDER_ENABLED=true`); check discovery first.

| Capability | Endpoint / how |
| --- | --- |
| Discovery | `/.well-known/openid-configuration` (OIDC) · `/.well-known/oauth-authorization-server` (RFC 8414) |
| Authorization code + **PKCE (S256, required)** | `/oauth2/authorize` → `/oauth2/token` (`grant_type=authorization_code`) |
| Refresh token | `grant_type=refresh_token` (scope `offline_access`) |
| Client credentials (machine-to-machine) | `grant_type=client_credentials`, client created with that grant |
| Device grant (RFC 8628) | `POST /device/code` → person approves at `https://auth.unx.ng/device/` → poll `/oauth2/token` with `grant_type=urn:ietf:params:oauth:grant-type:device_code` |
| Pushed authorization requests (PAR) | supported by the provider; use `request_uri` at `/oauth2/authorize` |
| DPoP-bound tokens (RFC 9449) | client `dpop_bound_access_tokens` or send a DPoP proof |
| Client authentication | `client_secret_basic`, `client_secret_post`, `private_key_jwt` (client `jwks`/`jwks_uri`), `none` (public + PKCE) |
| UserInfo · JWKS · Introspect · Revoke | `/oauth2/userinfo` · `/jwks` · `/oauth2/introspect` (RFC 7662) · `/oauth2/revoke` (RFC 7009) |
| Logout | `/oauth2/end-session` (RP-initiated) |
| Dynamic registration (RFC 7591) | `POST /oauth2/register` — only for a signed-in UNX admin; never anonymous |

Scopes: `openid profile email offline_access read write` (`admin` is never offered). Not supported: implicit and password grants (removed in OAuth 2.1), mTLS client auth, token exchange (RFC 8693).
Create a client: `pnpm oauth:client --name "App" --redirect https://app.example/cb [--grants authorization_code,refresh_token,client_credentials,device_code] [--public] [--jwks-uri …] [--tenant tid]`; prints `client_id` / `client_secret` once.
Old `/oauth/*` and `/.well-known/*` paths map to these when legacy routes are on.

## 4. Rules for AI agents

Follow these when acting on UNX systems or writing code against them.

**Always**
- Keep API keys, key-pair secrets, OAuth client secrets, refresh tokens and session cookies in server-side configuration. Never print them, commit them, put them in URLs or client-side code.
- Use a key pair or OAuth client_credentials rather than sharing one key across services; prefer `POST /v1/integration/signup` (server side) over putting a key in a browser link.
- Treat the HttpOnly cookie as opaque; never copy it into localStorage/sessionStorage.
- Use the tenant's role catalogue; do not invent role names.
- Quote the `requestId` from error responses when reporting problems.
- Check `GET /v1/integration/whoami` before bulk changes to confirm which tenant a key controls.

**Never**
- Ask a user for their password, one-time code or API key, or type them on their behalf.
- Create tenants, raise limits, change roles or add trusted domains unless the human operator explicitly asked for that exact change.
- Bypass rate limits, the tenant limit, email verification or origin checks.
- Delete tenants, revoke keys or remove members without explicit confirmation naming the target.
- Disable or work around security headers, CORS/trusted origins or audit logging.

**Ask first (outward-facing or hard to undo):** deleting a tenant, revoking an API key in use, removing a member, changing a user's tenant limit, adding or disabling a trusted domain, changing platform roles.

**Typical agent tasks**
1. *Add "Sign in with UNX" to a site:* create tenant + key in the developer console → ask a super-admin to add the domain and link it to the tenant → proxy `/v1` to UnityAuth → send visitors to `https://auth.unx.ng/?callback=https://your-site/…`.
2. *Give someone access:* `POST /v1/integration/members {email}` then `PUT …/members/:userId/roles`.
3. *Call UNX from a backend:* create a key pair for the tenant, send `Basic base64(keyId:secret)` from the server only, confirm with `GET /v1/integration/whoami`.
4. *Raise a user's tenant limit (staff):* `PATCH /v1/admin/tenant-limits/:userId {"limit":25}`; undo with `{"limit":null}`.

## 5. Troubleshooting

| Symptom | Cause / fix |
| --- | --- |
| `401 unauthorized` | No session cookie or key. Sign in, or send `Authorization: Bearer unx_live_…`. |
| `invalid_api_key` | Key or pair is wrong, revoked or expired. A pair secret sent alone is also rejected. Create a new one. |
| `host_not_authorized` | The request's `Origin`/`Referer` host is not enrolled for this tenant. Enrol it under Admin → Domains, or call from your server without an Origin. |
| `invalid_grant` / `authorization_pending` | Code or PKCE verifier wrong/expired; for the device grant keep polling at the returned `interval`. |
| `email_not_verified` | Verify the account email, then retry. |
| `limit_reached` | User owns the maximum number of tenants. A staff member can raise the limit. |
| `forbidden` / `not_found` on a tenant | Not a member with enough role (unknown tenants answer 404 on purpose). |
| `invalid_role` | Role is not in the tenant's role catalogue. |
| Sign-in loops on your site | Domain not trusted yet, or `/v1` is not proxied to UnityAuth. |
| No email code | Check spam, wait a minute, resend (3 per minute). |

---

*Generated for auth.unx.ng. If this file disagrees with the live API, the API wins; read `/account/docs/` for the current guide.*
