feat(auth): token-based admin authentication for Playwright/CI (#105)
Add POST /api/auth/token — validates ADMIN_TOKEN env var, creates a 24h session and sets the sid cookie so automated tools can access the admin panel without Google OAuth. Admin login page gains a token input form. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
26
.env.example
26
.env.example
@@ -10,6 +10,32 @@ API_BASE_URL=http://localhost:3078
|
||||
WEB_BASE_URL=http://localhost:3000
|
||||
ML_SERVING_URL=http://localhost:8000
|
||||
|
||||
# MLflow (mlops profile) — http://localhost:5000/mlflow in dev, https://o.alogins.net/mlflow in prod.
|
||||
# MLFLOW_ADMIN_PASSWORD seeds the admin account on first boot (changing it after first run
|
||||
# requires the MLflow UI or API — see infra/mlflow/basic_auth.ini).
|
||||
MLFLOW_URL=http://localhost:5000
|
||||
MLFLOW_ADMIN_PASSWORD=change-me
|
||||
# Public URL shown as link in the admin sidebar (must be NEXT_PUBLIC_ to reach the browser).
|
||||
NEXT_PUBLIC_MLFLOW_URL=http://localhost:5000
|
||||
|
||||
# Airflow (mlops profile) — http://localhost:8080/airflow in dev.
|
||||
# Start with: docker compose --profile full --profile mlops up
|
||||
AIRFLOW_URL=http://localhost:8080
|
||||
AIRFLOW_ADMIN_PASSWORD=change-me
|
||||
AIRFLOW_DB_PASSWORD=airflow
|
||||
AIRFLOW_SECRET_KEY=change-me-in-prod
|
||||
AIRFLOW_FERNET_KEY=
|
||||
AIRFLOW_BASE_URL=https://o.alogins.net/airflow
|
||||
# Public URL shown as link in the admin sidebar (must be NEXT_PUBLIC_ to reach the browser).
|
||||
NEXT_PUBLIC_AIRFLOW_URL=http://localhost:8080
|
||||
|
||||
# Shared secret for Airflow→API internal callbacks. Generate: openssl rand -hex 32
|
||||
INTERNAL_API_TOKEN=
|
||||
|
||||
# Static token for automated/service access to the admin panel (e.g. Playwright tests).
|
||||
# Leave empty to disable token-based login. Generate: openssl rand -hex 32
|
||||
ADMIN_TOKEN=
|
||||
|
||||
# AI stack — shared Agap services (ollama + litellm + langfuse). Not run from oO.
|
||||
# Prod: https://llm.alogins.net | Dev: http://host.docker.internal:4000 from containers,
|
||||
# http://localhost:4000 from host. Ollama: http://host.docker.internal:11434 / :11434.
|
||||
|
||||
10
CLAUDE.md
10
CLAUDE.md
@@ -112,3 +112,13 @@ Active work: bandit promotion (#99 — offline sim + ADR-0012 pending) and M2 is
|
||||
- Don't call LLMs directly from application code. All LLM calls go through `ml/serving` (Python) via `LITELLM_URL`. The TS recommender never holds a model name.
|
||||
- Don't embed MLflow/Airflow/OpenWebUI in the admin panel. They are external services; link out to them. The admin shell links to `o.alogins.net/mlflow`, `/airflow`, `ai.alogins.net`.
|
||||
- Don't `nats.publish()` directly from feature code. All publishes go through the in-process `Bus` (`services/api/src/events/bus.ts`); the NATS adapter (`events/nats.ts`) bridges every publish to JetStream when `NATS_URL` is set. This keeps subscribers, the ring-buffer tail used by the admin event viewer, and JetStream all in lockstep.
|
||||
|
||||
## Admin app
|
||||
|
||||
`apps/admin` rewrites `/api/*` → `$NEXT_PUBLIC_API_URL/api/*` via `next.config.ts`. So `apiFetch('/admin/stats')` in `apps/admin/src/lib/api.ts` hits the Express backend, not a Next.js route.
|
||||
|
||||
Running `tsc --noEmit -p apps/admin/tsconfig.json` always reports `Cannot find module 'next'` errors — expected outside the Next.js build context; use `next build` for real type errors.
|
||||
|
||||
## Auth / session pattern
|
||||
|
||||
Sessions use an `sid` cookie. Admin routes stack `requireAuth` (sets `req.userId`) then `requireAdmin` (checks `role = 'admin'` in DB). Token-based admin auth: `POST /api/auth/token` with `{ token }` matching `ADMIN_TOKEN` env var sets the `sid` cookie — used by Playwright and CI.
|
||||
|
||||
@@ -8,6 +8,15 @@ Next.js 15 app. Deployed at `admin.o.alogins.net` (dev: `http://localhost:3080`)
|
||||
and checks `role === 'admin'`. First admin is seeded via `ADMIN_SEED_EMAIL` env var at API startup.
|
||||
- Admin write actions are appended to the `admin_actions` audit log in the DB.
|
||||
|
||||
## Authentication
|
||||
|
||||
Two ways to sign in:
|
||||
|
||||
| Method | How |
|
||||
|--------|-----|
|
||||
| Google OAuth | Click "Sign in with Google" on the login page |
|
||||
| Token | `POST /api/auth/token` with `{ token }` matching `ADMIN_TOKEN` env var; sets `sid` cookie valid for 24 h. Used by Playwright tests and CI automation. |
|
||||
|
||||
## Pages
|
||||
|
||||
| Route | Description |
|
||||
|
||||
@@ -1,15 +1,67 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const [token, setToken] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleTokenLogin(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch('/api/auth/token', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setError((data as { error?: string }).error ?? 'Invalid token');
|
||||
return;
|
||||
}
|
||||
router.push('/');
|
||||
} catch {
|
||||
setError('Request failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="text-center space-y-6 w-72">
|
||||
<h1 className="text-2xl font-semibold">oO Admin</h1>
|
||||
<p className="text-gray-400 text-sm">Sign in via the main app first, then return here.</p>
|
||||
|
||||
<a
|
||||
href="/sign-in"
|
||||
className="inline-block px-4 py-2 bg-white text-black rounded text-sm font-medium hover:bg-gray-200 transition-colors"
|
||||
>
|
||||
Sign in with Google
|
||||
</a>
|
||||
|
||||
<form onSubmit={handleTokenLogin} className="space-y-3">
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Admin token"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded text-sm focus:outline-none focus:border-gray-500"
|
||||
/>
|
||||
{error && <p className="text-red-400 text-xs">{error}</p>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !token}
|
||||
className="w-full px-4 py-2 bg-gray-700 text-white rounded text-sm font-medium hover:bg-gray-600 disabled:opacity-40 transition-colors"
|
||||
>
|
||||
{loading ? 'Signing in…' : 'Sign in with token'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ POST /api/auth/login → redirect to Google OAuth
|
||||
GET /api/auth/callback OAuth return URL
|
||||
POST /api/auth/logout
|
||||
GET /api/auth/session → { user? }
|
||||
POST /api/auth/token { token } → set sid cookie (ADMIN_TOKEN auth)
|
||||
|
||||
GET /api/integrations list connected integrations
|
||||
POST /api/integrations/todoist/connect start Todoist OAuth
|
||||
@@ -76,6 +77,7 @@ Sentry error capture is active when `SENTRY_DSN` is set.
|
||||
| `LOG_LEVEL` | `info` | pino log level |
|
||||
| `SENTRY_DSN` | `` | Sentry DSN; empty = Sentry disabled |
|
||||
| `VAPID_*` | | Web push keys |
|
||||
| `ADMIN_TOKEN` | `` | Static token for service/Playwright admin auth; empty = disabled |
|
||||
|
||||
## Health story
|
||||
|
||||
|
||||
@@ -34,6 +34,17 @@ export const config = {
|
||||
ML_SERVING_URL: optional('ML_SERVING_URL', 'http://localhost:8000'),
|
||||
LITELLM_URL: optional('LITELLM_URL', 'http://localhost:4000'),
|
||||
|
||||
MLFLOW_URL: optional('MLFLOW_URL', 'http://localhost:5000'),
|
||||
AIRFLOW_URL: optional('AIRFLOW_URL', 'http://localhost:8080'),
|
||||
AIRFLOW_API_USER: optional('AIRFLOW_API_USER', 'admin'),
|
||||
AIRFLOW_API_PASSWORD: optional('AIRFLOW_API_PASSWORD', 'admin'),
|
||||
|
||||
/** Shared secret for internal Airflow→API callbacks. */
|
||||
INTERNAL_API_TOKEN: optional('INTERNAL_API_TOKEN', ''),
|
||||
|
||||
/** Static token for automated/service access to the admin panel (e.g. Playwright tests). */
|
||||
ADMIN_TOKEN: optional('ADMIN_TOKEN', ''),
|
||||
|
||||
VAPID_PUBLIC_KEY: optional('VAPID_PUBLIC_KEY', ''),
|
||||
VAPID_PRIVATE_KEY: optional('VAPID_PRIVATE_KEY', ''),
|
||||
VAPID_SUBJECT: optional('VAPID_SUBJECT', 'mailto:admin@localhost'),
|
||||
|
||||
@@ -124,6 +124,45 @@ router.get('/callback', async (req: Request, res: Response) => {
|
||||
.redirect(`${config.WEB_BASE_URL}${pending.redirectTo}`);
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/auth/token
|
||||
* Exchange the static ADMIN_TOKEN for a session cookie.
|
||||
* Finds the first admin user in the DB; rejects if ADMIN_TOKEN is not configured.
|
||||
*/
|
||||
router.post('/token', async (req: Request, res: Response) => {
|
||||
const { token } = req.body as { token?: string };
|
||||
if (!config.ADMIN_TOKEN || !token || token !== config.ADMIN_TOKEN) {
|
||||
res.status(401).json({ error: 'Invalid token' });
|
||||
return;
|
||||
}
|
||||
|
||||
const [adminUser] = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.role, 'admin'))
|
||||
.limit(1);
|
||||
|
||||
if (!adminUser) {
|
||||
res.status(403).json({ error: 'No admin user exists' });
|
||||
return;
|
||||
}
|
||||
|
||||
const sid = nanoid(32);
|
||||
const now = new Date().toISOString();
|
||||
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
|
||||
await db.insert(sessions).values({ id: sid, userId: adminUser.id, expiresAt, createdAt: now });
|
||||
|
||||
res
|
||||
.cookie('sid', sid, {
|
||||
httpOnly: true,
|
||||
secure: config.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
expires: new Date(expiresAt),
|
||||
path: '/',
|
||||
})
|
||||
.json({ ok: true });
|
||||
});
|
||||
|
||||
/** POST /api/auth/logout */
|
||||
router.post('/logout', async (req: Request, res: Response) => {
|
||||
const sid = req.cookies?.sid as string | undefined;
|
||||
|
||||
Reference in New Issue
Block a user