MaahirAI Lab site API
This site (khi.maahirai.com) is the membership, referral and admin hub for MaahirAI Lab. The app (planned at https://app.khi.maahirai.com) talks to it through a small signed HTTP API:
- it reports AI usage so admins see tokens, costs, latency and errors per user and model;
- it reads config: which AI providers, models and feature modules are switched on for each mode, plan and role;
- it checks members and codes, and later signs members in with their site account (SSO).
Base URL: https://khi.maahirai.com/api/v1. All bodies are JSON (Content-Type: application/json).
Keys and signing
An admin creates a key in Admin → API keys and picks scopes. The secret is shown once.
| Scope | Allows |
|---|---|
usage:write |
POST /usage, GET /quota |
config:read |
GET /config |
config:secrets |
GET /config?include_secrets=1 returns decrypted provider keys (audited) |
users:read |
POST /codes/validate, GET /users/lookup, GET /quota |
sso |
GET /sso/authorize client, POST /sso/token |
Every request carries three headers:
X-KHI-Key: khk_xxxxxxxxxxxx
X-KHI-Timestamp: 1764000000 (unix seconds, within ±5 minutes)
X-KHI-Signature: hex(HMAC_SHA256(secret, ts + "\n" + METHOD + "\n" + path_with_query + "\n" + hex(SHA256(raw_body))))
path_with_query is exactly what you request, e.g. /api/v1/quota?user_email=a%40b.com. For GET requests the body is the empty string.
Node.js example
import crypto from 'node:crypto';
const KEY = process.env.KHI_KEY_ID, SECRET = process.env.KHI_SECRET;
export async function khi(method, path, body) {
const raw = body ? JSON.stringify(body) : '';
const ts = Math.floor(Date.now() / 1000).toString();
const base = `${ts}\n${method}\n${path}\n${crypto.createHash('sha256').update(raw).digest('hex')}`;
const sig = crypto.createHmac('sha256', SECRET).update(base).digest('hex');
const r = await fetch('https://khi.maahirai.com' + path, { method, body: raw || undefined,
headers: { 'Content-Type': 'application/json', 'X-KHI-Key': KEY, 'X-KHI-Timestamp': ts, 'X-KHI-Signature': sig } });
return r.json();
}
curl example
BODY='{"events":[{"id":"evt_0001","provider":"dialagram","model":"qwen-3.8-max","user_email":"a@b.com","prompt_tokens":120,"completion_tokens":300,"latency_ms":1800}]}'
TS=$(date +%s)
SIG=$(printf '%s\n%s\n%s\n%s' "$TS" POST /api/v1/usage "$(printf '%s' "$BODY" | sha256sum | cut -d' ' -f1)" | openssl dgst -sha256 -hmac "$KHI_SECRET" -hex | awk '{print $NF}')
curl -s https://khi.maahirai.com/api/v1/usage -H 'Content-Type: application/json' \
-H "X-KHI-Key: $KHI_KEY_ID" -H "X-KHI-Timestamp: $TS" -H "X-KHI-Signature: $SIG" -d "$BODY"
Errors: 401 missing_signature | stale_timestamp | unknown_key | bad_signature, 403 missing_scope, 429 rate_limited (600 requests a minute per IP).
POST /usage
Send one event, a list, or { "events": [...] } (up to 1,000 per call). Send events in batches every few seconds rather than one call per message.
| Field | Required | Notes |
|---|---|---|
id |
yes | Your unique event ID (6–100 chars). Re-sending the same ID is ignored, so retries are safe. |
provider, model |
yes | e.g. dialagram, qwen-3.8-max |
user_email or user |
recommended | Matched to site members by email |
prompt_tokens, completion_tokens |
recommended | Or usage: {prompt_tokens, completion_tokens} |
cost_usd |
optional | If missing, estimated from the model's prices in Admin → AI modules |
latency_ms |
optional | Time to the full reply |
status |
optional | ok, error, timeout, blocked, rate_limited |
error |
optional | Short error text |
mode |
optional | kids, basic, lab (the app's older internal key for Lab is accepted too), pro |
feature |
optional | e.g. chat, council, arena, voice, computer |
ts |
optional | ISO time; defaults to now |
Response:
{ "accepted": 1, "duplicates": 0, "errors": [],
"quotas": { "a@b.com": { "daily_tokens_limit": 200000, "tokens_today": 420, "over_quota": false, "monthly_cost_limit_usd": null, "cost_this_month_usd": 0.0012 } } }
The site does not block anything itself. The app should check over_quota and decide what to do (for example, switch to a cheaper model or pause).
GET /quota?user_email=…
Returns the same quota object for one user.
GET /config
{ "brand": { "name": "MaahirAI Lab", "...": "..." }, "product_url": "https://app.khi.maahirai.com",
"signup_mode": "invite", "mode_labels": { "kids": "Kids", "basic": "Basic", "lab": "Lab", "pro": "Pro" },
"plans": [{ "id": "beta", "name": "Beta" }],
"modules": [{ "key": "council", "enabled": true, "status": "live", "plans": ["all"], "roles": ["all"], "modes": ["pro","lab"] }],
"providers": [{ "name": "Dialagram", "base_url": "https://dialagram.me/router/v1", "has_key": true, "tags": ["main"],
"modes": ["kids","basic","lab","pro"], "plans": ["all"], "health": "ok",
"models": [{ "id": "qwen-3.8-max", "best_for": ["general"], "modes": ["basic","lab","pro"], "plans": ["all"], "price_per_mtok": { "input": 0.4, "output": 1.2 } }] }] }
Only enabled providers and enabled models are listed. Poll every 1–5 minutes and cache. With the config:secrets scope and ?include_secrets=1, each provider also has api_key; every such read is written to the audit trail. Prefer keeping provider keys in the app's own .env unless you want central key management.
Module keys: council, arena, voice, computer, projects, scheduler, qa_bot, office, inclusive_portal. A module is usable when enabled is true and the user's plan, role and mode are in its lists ("all" matches everything).
POST /codes/validate
{ "code": "SCHOOL-ABC123" } → { "valid": true, "type": "invite|admin|referral", "role": "user|parent|instructor|admin", ... } or { "valid": false, "reason": "..." }. It does not use up the code.
GET /users/lookup?email=…
Returns { user: { id, email, name, role, status, plan, tier, email_verified, referral_code, referred_by, created_at }, quota: {...} }, or 404.
Sign-in with a site account (SSO)
A standard authorization-code flow. Allowed return addresses default to https://app.khi.maahirai.com/; admins can add more in Admin → Settings.
- The app sends the browser to
https://khi.maahirai.com/sso/authorize?client_id=&redirect_uri=https://app.khi.maahirai.com/auth/khi/callback&state=. - The member logs in here if needed (with two-step sign-in if they turned it on). The site redirects back with
?code=…&state=…. The code works once, for 60 seconds. - The app's server calls
POST /api/v1/sso/token(signed,ssoscope) with{ "code": "…", "redirect_uri": "" }and gets{ "user": { ... } }. - The app checks
state, then creates or updates its own local user by email and role, and starts its own session.
Integration plan for the app
This is how the app should use the site later. Nothing in the app has been changed yet.
- Accounts: replace the app's own invite-code sign-up with "Sign in with MaahirAI Lab" (SSO above). Map
roleto app permissions:admin→ app admin;parent→ parent dashboard;instructor→ teacher tools;user→ normal member. A suspended site account should be refused at the next sign-in, and the app should re-check/users/lookupat least daily. - Referral codes: the app's sign-up screen (if kept) calls
/codes/validate. Member referral links are alwayshttps://khi.maahirai.com/r/. - Usage: after each model call, queue
{id, provider, model, user_email, tokens, latency_ms, status, mode, feature}and flush to/usageevery 5 seconds. Use the returnedquotasto enforce limits. - Config: read
/configat start-up and every few minutes, and hide modules and models the user's plan, role or mode cannot use. - Keys: create one key for the app with
usage:write, config:read, users:read, sso. StoreKHI_KEY_IDandKHI_SECRETin the app's.env(chmod 600).
Health
GET /api/v1/health and GET /healthz need no key.