docs: auth-service playbook

This commit is contained in:
Saravana Dhandapani 2026-02-14 20:35:26 -08:00
parent b044d3ee39
commit 8cd5f51389

View File

@ -0,0 +1,82 @@
# Auth Service Design (WindSurf)
## Goal
Create a shared authentication microservice under `learning_ai_common_plat/services/auth-service` so all BytelystAI apps (MindLyst, LysnrAI, Windhawk extensions, etc.) rely on one canonical JWT-based auth + licensing stack rather than duplicating logic in each client. This service will become the source of truth for user identity, subscriptions, JWT minting/refreshing, and Azure resource guardianship.
## Section 1: Scope & Constraints
- **Who calls it**: All mobile/web/desktop apps, plus internal backend services that need user context (cloud sync, tracker, platform, bios, etc.).
- **Stack**: FastAPI (TypeScript?). Mirror existing platform stack (Fastify + TypeScript) or re-use Python FastAPI depending on team familiarity; pick whichever aligns with most current services.
- **Secrets**: Must read JWT signing keys, Stripe keys, and Azure connection strings from Key Vault via shared environment (per WindSurf scripts). Avoid hard-coded secrets and integrate with `env.dev` + `keyvault` wrappers.
- **Deployment**: Host inside `rg-mywisprai`. Expose via Traefik under `/api/auth`.
## Section 2: API surface
### Routes
1. `POST /api/auth/register` — accept `name`, `email`, `password`; validate against duplicate; hash password; store user doc in Cosmos `users` container; return JWT pair + user info.
2. `POST /api/auth/login` — accept `email`, `password`; verify password; return `access_token`, `refresh_token`, and `user` (including plan/roles). This token is used by all clients.
3. `POST /api/auth/refresh` — refresh `access_token` using `refresh_token`; rotate tokens.
4. `POST /api/auth/logout` (optional) — optionally blacklist refresh token (maybe via TTL cache) or rotate.
5. `GET /api/auth/me` — validate bearer token; return user + plan info (used by clients to hydrate UI, lubrication). This endpoint is currently used by CloudSync and mobile settings screens.
### Tokens
- Access token: short-lived (~15m) JWT (HMAC-SHA256) signed with secret from Key Vault; contains `sub`, `plan`, `roles`, `prod` flag, `resourceGroup` references for telemetry.
- Refresh token: opaque UUID stored in Cosmos table or Redis; rotate per login; share via `AuthService` for `AuthState`. Provide TTL (7d) and ability to revoke.
### Payload Example
```
{
"sub": "user-id",
"email": "hello@bytelyst.ai",
"plan": "pro",
"roles": ["admin", "beta"],
"resource": "rg-mywisprai",
"iat": 1670000000,
"exp": 1670000900
}
```
## Section 3: Storage & Licensing
- **Cosmos**: `users` container with fields `id`, `email`, `passwordHash`, `plan`, `stripeCustomer`, `licenses`, `settings`, `createdAt`, `updatedAt`.
- **Azure Storage/Blob**: (if storing avatars) keep path; not needed initially.
- **Licenses**: On login/register, query `billing-service`/Stripe via HTTP (shared module) to check active subscription; store plan info in user doc.
- **Auth claims** include `licenseId` so downstream services (tracker, transcripts) can enforce usage.
## Section 4: Shared SDK & Reusable Middleware
- Provide a small `auth` utility package in Plat, consumed by other services:
- `verifyToken(req)` extracts Bearer token, verifies signature, returns user claims.
- `requirePlan('pro')` decorator to guard premium routes.
- `withAuth(api, handler)` plug into FastAPI/Fastify.
- Export an `authClient.postAuth(endpoint, body)` used by mobile apps; all clients share the same base URL.
## Section 5: Integration Checklist for WindSurf Agents
1. Create `services/auth-service` folder with package management + README (copy pattern from `billing-service`).
2. Define `.env.example` with env vars: `JWT_SECRET`, `COSMOS_ENDPOINT`, `COSMOS_KEY`, `API_BASE_URL`, `STRIPE_KEY`, `AZURE_STORAGE_SAS`, etc.
3. Implement FastAPI routes as above; reuse existing Cosmos helpers from other services.
4. Build middleware/commons for other services: place shared logic under `packages/auth` or similar; reference from `platform-service`, `billing-service`, `cloud sync`, etc.
5. Reconfigure mobile apps to call `/api/auth` on new service; update `common/env.dev` to include new `AUTH_BASE_URL` if splitting.
6. Migrate existing auth logic (AuthService/AuthViewModel) to consume new endpoints; keep current local storage strategy (AppStorage+Shared App Group) unchanged.
7. Document onboarding in `docs/WINDSURF/AUTH_SERVICE_DESIGN.md` and mention guardrails for secrets.
## Section 6: Monitoring & Observability
- Send login/register attempts + failures to App Insights (`bytelyst-appinsights`).
- Register alerts in `rg-mywisprai` (via Action Group) for unusual auth failure spikes.
- Log to Grafana/Loki via `loki` service (existing docker stack) to keep consistency.
## Section 7: WindSurf Agent Tasks
1. Scaffold the new service; mirror the structure of `billing-service` (DI, repo, routes).
2. Implement tests: login, refresh, invalid creds, missing tokens.
3. Update `shared packages` (TS) to export middleware/client.
4. Update mobile env documentation and sample dev env.
5. Validate with `pnpm lint`, `pnpm test`, `./gradlew` to keep build green.
Keep this doc with the same tone as existing `WINDSURF` guidance so future agents can pick up the auth refactor. If you need extra detail on request/response shapes or license checks, let me know and Ill add appendices.