# EJEMMA Bridge API Contract for pay.agbara.ai

## Base URL
`https://api-bridge.ejemma.ugogbe.info/`

## Authentication
Header: `x-api-key: <shared-secret>`  
(Ask the EJEMMA administrator for the current key.)

---

## 1. Provision a chat account

Call **once** when a pay.agbara.ai user first needs chat access.

### Request
`POST /v1/chat/account`

```json
{
  "username": "johndoe",
  "email": "john@pay.agbara.ai",
  "name": "John Doe",
  "external_sub": "pay-agbara-ai-unique-user-id-123",
  "wallet_address": "0x..."
}
```

- `username` becomes the Matrix localpart (`@johndoe:matrix.ugogbe.info`). Must be 3–64 lowercase letters, numbers, `._-`.
- `external_sub` is the **immutable** pay.agbara.ai user id. Store this on your side.
- `email` is used to avoid duplicate Authentik accounts.

### Response
```json
{
  "success": true,
  "matrix_user_id": "@johndoe:matrix.ugogbe.info",
  "username": "johndoe",
  "display_name": "John Doe",
  "created": true,
  "message": "EJEMMA chat account provisioned. Use POST /v1/chat/token to mint access tokens server-side."
}
```

Idempotent: calling again with the same `username` returns `created: false`.

---

## 2. Mint an access token (server-to-server)

Call this **every time** the user opens chat. The token is short-lived and should be used immediately — **do not store it on your server**.

### Request
`POST /v1/chat/token`

```json
{
  "external_sub": "pay-agbara-ai-unique-user-id-123"
}
```

### Response
```json
{
  "success": true,
  "matrix_user_id": "@johndoe:matrix.ugogbe.info",
  "access_token": "mct_...",
  "homeserver_url": "https://matrix.ugogbe.info",
  "device_id": null
}
```

---

## 3. Load chat with the token

Redirect or load:

```
https://ejemma.ugogbe.info/embed/?token=mct_...
```

`embed.html` injects the token into Element Web and loads the chat immediately. No login screen, no consent screen, no redirect.

### Recommended for pay.agbara.ai backend (Python example)

```python
import requests, os

BRIDGE_URL = "https://api-bridge.ejemma.ugogbe.info"
BRIDGE_KEY = os.environ["EJEMMA_BRIDGE_API_KEY"]

def open_ejemma_chat(user):
    # 1. Provision account (idempotent)
    requests.post(
        f"{BRIDGE_URL}/v1/chat/account",
        headers={"x-api-key": BRIDGE_KEY, "Content-Type": "application/json"},
        json={
            "username": user.username,
            "email": user.email,
            "name": user.name,
            "external_sub": user.sub,
        },
        timeout=30,
    )

    # 2. Mint access token now
    token_resp = requests.post(
        f"{BRIDGE_URL}/v1/chat/token",
        headers={"x-api-key": BRIDGE_KEY, "Content-Type": "application/json"},
        json={"external_sub": user.sub},
        timeout=30,
    )
    token_resp.raise_for_status()
    token = token_resp.json()["access_token"]

    # 3. Send user to chat with token (do not store token)
    return f"https://ejemma.ugogbe.info/embed/?token={token}"
```

### Recommended for pay.agbara.ai web app (JavaScript)

```javascript
async function openChat(user) {
  await fetch("/api/ejemma/provision", { method: "POST", body: JSON.stringify(user) });
  const r = await fetch("/api/ejemma/token", { method: "POST", body: JSON.stringify({ external_sub: user.sub }) });
  const { access_token } = await r.json();
  // Top-level navigation works best; iframe is blocked by third-party cookies.
  window.location.href = `https://ejemma.ugogbe.info/embed/?token=${access_token}`;
}
```

---

## 4. Resolve a username to Matrix ID

Used for payments, mentions, or invites by username.

### Request
`POST /v1/chat/resolve`

```json
{ "username": "johndoe" }
```

### Response
```json
{
  "username": "johndoe",
  "matrix_user_id": "@johndoe:matrix.ugogbe.info",
  "matrix_to_url": "https://matrix.to/#/@johndoe:matrix.ugogbe.info"
}
```

---

## How it works

1. pay.agbara.ai user signs up on your platform as usual.
2. On first chat click, your backend calls `POST /v1/chat/account` once.
3. EJEMMA creates an Authentik user + a MAS user + stores encrypted credentials.
4. Each time the user opens chat, your backend calls `POST /v1/chat/token`.
5. EJEMMA mints a Matrix compatibility access token server-side via `mas-cli`.
6. Your app loads `https://ejemma.ugogbe.info/embed/?token=...`.
7. Element Web picks up the token from `localStorage` and shows the conversation list.

No OIDC redirects in the browser. No sign-in screen. No consent screen. Works in full-screen and WebView contexts.

---

## Token storage policy

- **Do not store the minted `access_token` on pay.agbara.ai servers.**
- It is safe to store `external_sub`, `matrix_user_id`, and `username` on your side.
- Call `/v1/chat/token` immediately before opening chat.

---

## User discovery

Inside chat, users can search by username/display name. The localpart matches the pay.agbara.ai username. Use `POST /v1/chat/resolve` to get a Matrix ID from a username for payments or mentions.

---

## Public chat surface

The public `https://matrix.ugogbe.info/chat/` page hides the "Create account" button. Registration only happens through the Bridge API, i.e. only via pay.agbara.ai.
