# unity-dev-agent.md — developer playbook for UNX sign-in (humans and AI coding agents)

Developer site: `https://developer.unx.ng` · Console: `/console/` · API reference: `/doc/` · Identity service: `https://auth.unx.ng`.
Companion file (accounts, endpoints, agent rules): `https://auth.unx.ng/Unity-Agents.md`.

## 1. Goal and vocabulary

You are building an app that lets people "Sign in with UNX". UNX gives you:

- **Tenant** — your organisation in UNX. Has a permanent `tid` (3–64 chars: `a-z 0-9 - _`), members, optional app roles and API keys.
- **API key** — `unx_live_…`, one tenant, shown once, server-side only.
- **Trusted domain** — your website's host, approved by a super-admin so sign-in can return users to it.
- **Tenant limit** — how many tenants one user may own. Default **10**; admins and super-admins can raise or lower it per user, and set defaults per role, at `/admin/`.

## 2. Setup checklist (in order)

1. Sign in at `https://auth.unx.ng` and **verify your email** (required to create tenants).
2. Open `https://developer.unx.ng/console/` → **New tenant**. Pick the `tid` carefully; it cannot change.
   The console shows `You own X of Y tenants`. At the limit, ask a UNX admin to raise it (staff use https://developer.unx.ng/admin/).
3. Open the tenant → **API keys** → create a key. Copy it now; it is never shown again. Store it in server config (`UNX_API_KEY`).
4. Verify the key: `curl -H "Authorization: Bearer $UNX_API_KEY" https://auth.unx.ng/v1/integration/whoami`.
5. Ask a super-admin to add your domain (Admin → Domains) and link it to your tenant. It applies within a minute.
6. Proxy `/v1` on your site to UnityAuth so session cookies are same-origin (Apache example below).
7. Send visitors to sign-in/sign-up (section 3) and read the session (section 4).

```apache
# public/.htaccess on your site
RewriteEngine On
RewriteRule ^v1/(.*)$ https://auth.unx.ng/v1/$1 [P,L]
```

(Developer/PROS sites on UNX proxy to `127.0.0.1:4420` instead; follow the existing `.htaccess`.)

## 3. Sign-in and sign-up links

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

- Give users `signupUrl` (no secret in it). Plain sign-in: `https://auth.unx.ng/?tenant=<tid>&callback=https://example.com/app`.
- `callback` must be on the tenant's website or a linked domain, otherwise the tenant website is used.
- Do **not** put the API key in a browser link; anyone who sees the link can copy it.

## 4. Reading who is signed in

Browser (same-origin proxy, cookie sent automatically):

```js
const r = await fetch("/v1/auth/get-session", { credentials: "include" });
const session = await r.json();            // null when signed out
```

Server (forward the user's cookie, or use OAuth tokens for third-party apps). `GET /v1/me/permissions` returns platform role(s) and permissions.
Never store the session cookie or tokens in localStorage/sessionStorage.

OAuth 2.1 / OIDC (apps outside UNX): discovery `https://auth.unx.ng/v1/auth/.well-known/openid-configuration`, authorization code + PKCE,
scopes `openid profile email offline_access read write`. A UNX admin registers the client (name, redirect URIs, public/confidential).

## 5. Members and roles (server, API key)

| Call | Use |
| --- | --- |
| `GET /v1/integration/members` | Active members and roles of your tenant. |
| `POST /v1/integration/members` `{"email"}` | Add an existing UNX user. |
| `DELETE /v1/integration/members/:userId` | Remove a member (clears roles). |
| `GET/PUT /v1/integration/members/:userId/roles` | `{"roles":["editor","lga:imo/oguta"]}`. |

Roles are `name` or `name:scope`, must be in your tenant's role catalogue (`GET/PUT /v1/tenants/:id/role-catalogue` in the console API), and only count while the user is an active member.
A key can never act on another tenant.

## 6. Tenant limits (staff)

```bash
# with an admin/super-admin session cookie (tenant:manage)
GET   /v1/admin/tenant-limits?q=ada@example.com&page=0
GET   /v1/admin/tenant-limit-defaults
PUT   /v1/admin/tenant-limit-defaults   {"default":10,"roles":{"support":20,"admin":50,"user":null}}
PATCH /v1/admin/tenant-limits/<userId>   {"limit": 25}      # set
PATCH /v1/admin/tenant-limits/<userId>   {"limit": null}    # back to default (10)
```

Effective limit order: the person's own limit, then their role's default (highest if several roles), then the platform default (built-in 10). The UI is `https://developer.unx.ng/admin/`.
Lowering a limit never deletes tenants; it only blocks creating new ones. Changes are audited (`tenant.limit.success`).
Paid extra tenants are not available yet.

## 7. Errors

`{ "error": { "code", "message", "requestId", "details" } }` on `/v1` platform routes; Better Auth routes return `{ "code", "message" }`.
Common: `401 unauthorized`, `invalid_api_key`, `403 email_not_verified`, `403 limit_reached`, `404 not_found` (also for tenants you cannot see), `409 tid_taken|tid_reserved`, `429` (about 100 requests/minute/IP; 3 code emails/minute).
Always include `requestId` when asking for help.

## 8. Rules for AI coding agents

**Do**
- Read the key from environment/secret storage; never write it into source, logs, URLs, client bundles or chat.
- Call `GET /v1/integration/whoami` first to confirm which tenant a key controls.
- Use `signupUrl` from the server call instead of hand-building links with secrets.
- Keep tenant ids lowercase; treat `tid` as permanent.
- Add tests that mock UNX endpoints; do not call production with real users' credentials.

**Do not**
- Ask people for their password or one-time code, or sign in on their behalf.
- Create tenants, raise limits, add trusted domains, change roles, revoke keys or remove members unless the operator explicitly asked for that exact change.
- Work around the tenant limit, rate limits, email verification or origin checks.

**Confirm first:** deleting a tenant, revoking a key that is in use, removing a member, changing a user's limit, adding/disabling a domain.

## 9. Troubleshooting

| Symptom | Fix |
| --- | --- |
| Console says limit reached | Ask a UNX admin to raise your limit (developer.unx.ng/admin). |
| `invalid_api_key` | Key revoked/expired/typo. Create a new one; update server config. |
| Redirect lands on your tenant website, not your callback | Callback host is not the tenant URL host or a linked domain. |
| Sign-in loops | Domain not trusted yet, or `/v1` is not proxied to UnityAuth. |
| `invalid_role` | Role missing from the tenant catalogue. |

*If this file disagrees with the live API, the API wins. See `/doc/`.*
