Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.16): admin console — users, traffic analytics, AI provider & feature configuration (A1)

Ashiq Hussain Mira6c13d5468b8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f86f0e1..0e6582e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,60 @@
All notable changes to Canvix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+## [0.16.0] — 2026-11-07
+
+### Added
+
+- **Admin console, part 1 (A1).** `/admin` — the operator surface for
+ a self-hosted instance, with **zero new dependencies** (Prisma
+ models, hand-rolled SVG charts, the existing stack). Operator guide
+ and full decision record: `docs/ADMIN.md`. The highlights:
+ - **Fail-closed admin access.** Two paths only: the
+ `CANVIX_ADMIN_USERS` env bootstrap (set it, restart, sign in —
+ also the lockout recovery path) or a `User.role = 'admin'` granted
+ by another admin from the console. No first-user-is-admin, no
+ secret URL. The API re-checks every call independently of the UI
+ (401 unsigned / 403 non-admin); mutations are same-origin guarded;
+ self-role-change is refused.
+ - **Traffic analytics.** Every API request (all routes already pass
+ through the `withLogging` wrapper) increments a per-day aggregate:
+ route template, method, status, count — **never ids, IPs or query
+ strings**. The Overview page shows 14-day traffic, daily-active
+ users (userIds + hashed anon keys from dashboard/editor opens),
+ signups and AI calls (teal ok / red failed), plus top routes and
+ AI usage by feature. 90-day lazy retention; `CANVIX_TRAFFIC=0`
+ opts out; the workerd fire-and-forget caveat is documented.
+ - **User directory.** Searchable, paginated, with design counts,
+ active sessions and last activity per user; admin grant/revoke
+ with a two-step inline confirm; force sign-out (one bounded
+ DELETE on `Session`).
+ - **AI provider & model configuration.** A console override that
+ wins over `ZAI_BASE_URL`/`ZAI_API_KEY` (write-only key, masked
+ echo, half-configured states rejected), configurable
+ text/vision/image model ids validated before use, a live
+ connection test (1 per 10 s, 15 s circuit breaker), and seven
+ per-feature kill switches that gate the routes *and* the public
+ capabilities endpoint — a switched-off feature greys out in the
+ editor and answers 503 before any provider work.
+ - **Instance settings.** "Allow new sign-ups" answers
+ `503 SIGNUPS_CLOSED` — checked *before* the rate limiter so a
+ closed instance burns none of a visitor's attempt budget.
+ "Anonymous editing" gates anonymous design creation/saves only;
+ reading, sharing and exporting never break.
+ - **Honest e2e without registrations.** The acceptance spec seeds
+ its fixture users and sessions straight into Postgres (the `pg`
+ driver already in the tree) — the suite stays inside the 5/h/IP
+ register budget while proving the full path: gating, role
+ round-trip, switches reaching `/api/ai/capabilities`, counters
+ landing in the overview.
+
+### Changed
+
+- Prisma migration `0009_admin_console` (additive): `User.role`
+ default `'user'`, `AppConfig`, `TrafficStat`, `DailyActive`.
+- The Word Cloud plugin's `engines.canvix` range widened to
+ `>=0.13.4 <0.17.0` for this minor series.
+
## [0.15.5] — 2026-11-07
### Added
diff --git a/README.md b/README.md
index f96262b..66fddcc 100644
--- a/README.md
+++ b/README.md
@@ -636,6 +636,30 @@ are the self-hoster's to read:
timestamp. 5-second timeout, fire-and-forget — a broken webhook
never takes the error path down with it.
+### 🛡 Admin console (v0.16 A1)
+
+Set `CANVIX_ADMIN_USERS="your-username"`, restart, sign in — a shield
+icon on the dashboard opens `/admin`:
+
+- **Overview** — users, designs, media, sessions and comments totals;
+ 14-day API-traffic, daily-active, signup and AI-call charts (hand-
+ rolled SVG, zero new dependencies); top routes; AI usage by feature;
+ DB latency and provider status
+- **Users** — searchable directory with design counts, active sessions
+ and last activity; grant/revoke admin rights (two-step confirm,
+ self-change refused); force sign-out everywhere
+- **AI & models** — a provider override that wins over the env vars
+ (write-only API key, masked echo), configurable text/vision/image
+ model ids, seven per-feature kill switches that actually gate the
+ routes, and a live connection test
+- **Settings** — allow new sign-ups (503 before the rate limiter),
+ anonymous editing on/off (gates writes, never reads), instance facts
+
+Traffic counters are per-day aggregates — counts only, never ids, IPs
+or query strings; 90-day retention; `CANVIX_TRAFFIC=0` opts out. The
+operator guide and the full decision record live in
+[`docs/ADMIN.md`](docs/ADMIN.md).
+
## 🛠 Tech stack
| Layer | Choice |
@@ -1132,6 +1156,16 @@ tool descriptions so agents pick the right format.
into exports. Zero new dependencies; tested against recorded
provider fixtures + a local mock-provider acceptance suite
wired into CI. *(v0.15.5)*
+- [x] Admin console (v0.16 A1) — the operator surface: fail-closed
+ admin access (`CANVIX_ADMIN_USERS` env bootstrap + DB roles, no
+ first-user-is-admin), traffic analytics from per-day aggregate
+ counters (counts only — never ids, IPs or query strings; 90-day
+ retention, `CANVIX_TRAFFIC=0` opts out), a user directory with
+ role management and force sign-out, AI provider/model/feature
+ configuration (write-only keys, seven kill switches that gate
+ the routes *and* the capabilities endpoint), and instance
+ settings (sign-ups, anonymous editing). Zero new dependencies;
+ decisions on record in `docs/ADMIN.md`. *(v0.16.0)*
- [ ] Mobile editor polish — touch-first selection handles, gesture
zoom/pan without modifier keys, bottom-sheet property panels
(the responsive groundwork from v0.11.3 makes this tractable)
diff --git a/docs/ADMIN.md b/docs/ADMIN.md
new file mode 100644
index 0000000..910915b
--- /dev/null
+++ b/docs/ADMIN.md
@@ -0,0 +1,205 @@
+# Admin console (v0.16 A1)
+
+> **TL;DR** — set `CANVIX_ADMIN_USERS="your-username"`, restart, sign in:
+> the shield icon on the dashboard opens `/admin`. Everything below is
+> operable from those four pages; this document is the operator guide and
+> the decision record.
+
+The admin console is the operator surface for a Canvix instance:
+
+| Page | What it shows / does |
+| --- | --- |
+| **Overview** (`/admin`) | totals (users, designs, media, sessions, comments), 14-day traffic / daily-active / signup / AI-call charts, top routes, AI usage by feature, newest accounts, DB latency, provider status |
+| **Users** (`/admin/users`) | searchable directory with per-user design counts, active sessions, last activity; grant/revoke admin rights; force sign-out |
+| **AI & models** (`/admin/ai`) | provider override (base URL + write-only API key), model ids (text / vision / image), per-feature kill switches, live connection test |
+| **Settings** (`/admin/settings`) | allow new sign-ups, anonymous editing, instance facts, privacy posture |
+
+---
+
+## 1. Turning it on — the first administrator
+
+Admin access is **fail-closed**. Two paths, no others:
+
+1. **Env bootstrap** — `CANVIX_ADMIN_USERS` is a comma-separated username
+ list that is admin on every request:
+
+ ```bash
+ CANVIX_ADMIN_USERS="alice,bob" # lowercase; case-insensitive match
+ ```
+
+ No DB write needed — set it, restart, sign in as one of those users.
+ This is also the recovery path if console-managed admins are ever
+ locked out.
+
+2. **DB role** — `User.role = 'admin'`, granted by another administrator
+ from the Users page. This is what the console itself manages.
+
+There is deliberately **no "first registered user is admin"** rule: on a
+public instance that would silently hand the keys to whoever happens to
+register first. No config-table flag, no secret URL — if neither path
+grants admin, `/admin` and every `/api/admin/*` route refuse everyone.
+
+The Users page shows where each admin's rights come from (`admin`,
+`admin · env`) — an env-blessed username stays admin even if its DB role
+is changed; the env always wins, and the badge says so.
+
+## 2. The pages in detail
+
+### Overview
+
+- **API requests** counts every request through the `withLogging`
+ wrapper all API routes already use — per UTC day, so "24h" means
+ "today (UTC) so far". See §3 for what is and isn't recorded.
+- **Daily active users** = distinct actors (userIds for accounts, the
+ *hashed* anonymous cookie key for anonymous browsers) that opened the
+ dashboard or the editor that day.
+- **AI calls** are split teal (succeeded) / red (failed) from the
+ `AIUsage` accounting that has existed since v0.5.
+- **Top routes / usage by feature** cover the last 7 days.
+
+### Users
+
+- Search is a username substring (usernames are stored lowercase).
+- **make admin / revoke** uses a two-step inline confirm. The route
+ refuses self-modification (`SELF_ROLE_CHANGE`) — an admin can never
+ lock themselves out of the only page that undoes role changes.
+- **sign out** revokes every session of that user (a single bounded
+ `DELETE` on `Session`; designs and uploads are untouched). Works on
+ your own rows too — it just signs you out.
+
+### AI & models
+
+**Provider precedence** (highest wins):
+
+1. the **console override** stored in `AppConfig` (`ai.provider`),
+2. `ZAI_BASE_URL` + `ZAI_API_KEY` environment variables,
+3. the `.z-ai-config` file (local development convenience),
+4. unconfigured — local-only features keep working (the F2b pattern).
+
+The override needs **both** fields; sending `provider: null` clears it
+and restores the env/file fallback. The page always shows which layer is
+currently answering (`console / environment / config file`) and the
+effective base URL — but **never the key**: it is stored once and echoed
+back only as a mask (`sk-1…wxyz`). Same posture as the env var it
+overrides.
+
+**Models** — `text` (Magic Write, Translate, Assistant), `vision`
+(Magic Layers, default `glm-4.5v`) and `image` ids. Empty = the SDK
+default, exactly the pre-console behaviour. Ids are validated
+(`[A-Za-z0-9._:+-]{1,120}`) before they can reach the provider.
+
+**Feature switches** — seven kill switches (Magic Write, image
+generation, image editing, Magic Layers, translation, Assistant, photo
+search). A switched-off feature:
+
+- reports `false` in the public `/api/ai/capabilities` (panels grey out),
+- answers `503 FEATURE_DISABLED` from its route — before rate limiting
+ or any provider work,
+- local features (background removal, colour palette, layout
+ suggestions) are never affected.
+
+**Test connection** — one minimal chat completion (thinking disabled,
+one-word reply, 15 s circuit breaker), rate-limited to one probe per
+10 s. It is the only console action that spends provider quota.
+
+### Settings
+
+- **Allow new sign-ups** — off means `POST /api/auth/register` answers
+ `503 SIGNUPS_CLOSED`. The check runs *before* the 5/hour rate limiter,
+ so a closed instance burns none of an honest visitor's attempt budget.
+ Existing accounts sign in as usual.
+- **Anonymous editing** — off means only signed-in accounts can create
+ or save designs. Reading, sharing and exporting existing designs
+ (including the anonymous commons) is untouched — the switch gates
+ writes, not reads.
+
+## 3. Traffic & activity recording — the model
+
+- One `TrafficStat` row per **(UTC day, route template, method,
+ status)**, incremented fire-and-forget by the `withLogging` wrapper.
+ **Counts only** — no ids, no IPs, no query strings (the same stance as
+ `/api/health?v=2`). Cardinality is bounded by the route table × days
+ × status codes.
+- One `DailyActive` row per (UTC day, actor) — actor = userId or the
+ sha256 anonymous-cookie hash (already a hash when it arrives).
+- Retention: rows older than **90 days** are swept lazily
+ (~1 % of writes trigger the bounded delete).
+- Opt-out: `CANVIX_TRAFFIC=0` disables recording entirely (the console
+ then shows zeros).
+- **Cloudflare caveat** — counters are written fire-and-forget after the
+ response; on workerd a cancelled evicted request can drop the write,
+ so counts may under-report there. Self-hosted Node (the primary
+ target) is exact. Improving this needs `waitUntil` plumbing through
+ every route — deliberately out of scope for A1.
+
+Config reads (feature switches, settings, provider) are cached
+in-process for **10 s** and invalidated on write — one tiny indexed
+`findMany` per window per instance. A failed config read falls back to
+defaults (= pre-A1 behaviour): these toggles are additive restrictions
+and a flapping read must not brick design autosave.
+
+## 4. API surface (for scripts)
+
+All `/api/admin/*` routes re-check the session independently of the UI
+(401 unsigned, 403 non-admin) and mutations enforce same-origin:
+
+```
+GET /api/admin/overview — everything the Overview page shows
+GET /api/admin/users?q=&page= — directory + per-user aggregates
+POST /api/admin/users/<id>/role — { role: "admin" | "user" }
+POST /api/admin/users/<id>/sessions — revoke all sessions of one user
+GET /api/admin/config — sanitized config (masked key)
+PUT /api/admin/config — { provider?|models?|features?|settings? }
+POST /api/admin/config/ai-test — live provider probe (1 / 10 s)
+```
+
+`PUT` accepts any subset of the four sections; `features` and `settings`
+merge over current values, `models` replaces, `provider` follows §2.
+
+## 5. Dependency & design decisions — on record
+
+- **D1 — zero new dependencies.** Prisma models for storage
+ (`AppConfig`, `TrafficStat`, `DailyActive` + `User.role`), hand-rolled
+ SVG charts (the same discipline as the GIF LZW encoder and the WebM
+ muxer), the existing `pg` driver only inside the e2e seed. No
+ analytics SDK, no charting library, no admin framework.
+- **D2 — admin resolution is DB role OR env list.** Fail-closed both
+ ways; no implicit first-user admin; the env list doubles as the
+ lockout recovery path.
+- **D3 — provider injection via `process.env`.** `ZAI.create()` takes
+ no arguments and resolves its own config from env/file (verified
+ against the SDK typings). A console-set provider is therefore
+ injected into `process.env.ZAI_BASE_URL`/`ZAI_API_KEY` before
+ instantiation — server-side, in-memory, the exact variables the
+ documented env setup uses.
+- **D4 — API keys are write-only.** Stored in `AppConfig`, returned
+ only as `maskApiKey()` output; GET responses never contain a full
+ key (unit-tested).
+- **D5 — traffic is aggregate-only and opt-out-able.** Counts, never
+ identities; `CANVIX_TRAFFIC=0` for instances that want none of it;
+ 90-day retention; the workerd under-count caveat documented above.
+- **D6 — config reads are cached, failures fall back to defaults.**
+ Availability trumps restriction-consistency here; the DB being truly
+ down breaks the app elsewhere anyway.
+- **D7 — the sign-ups gate runs before the rate limiter.** A closed
+ instance consumes none of a visitor's registration budget.
+- **D8 — the migration is purely additive.** `User.role` defaults to
+ `'user'`; no config rows exist until an admin writes them; an
+ instance that never opens `/admin` behaves exactly as before.
+- **D9 — the e2e suite spends zero registrations.** Fixture users and
+ sessions are seeded straight into the database (the app's own Postgres
+ via the `pg` driver), keeping the suite inside the 5/h/IP budget the
+ other specs honor.
+- **D10 — self-role-change is refused** (`SELF_ROLE_CHANGE`), so the
+ console cannot be used to lock out its only operator.
+
+## 6. Database changes (migration `0009_admin_console`)
+
+```sql
+ALTER TABLE "User" ADD COLUMN "role" TEXT NOT NULL DEFAULT 'user';
+CREATE TABLE "AppConfig" (key TEXT PRIMARY KEY, value JSONB NOT NULL, …);
+CREATE TABLE "TrafficStat" (… UNIQUE(day, route, method, status));
+CREATE TABLE "DailyActive" (… UNIQUE(day, actor));
+```
+
+`npm run db:setup` applies it; nothing else changes.
diff --git a/package.json b/package.json
index a54e91c..1eb9c4d 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,8 @@
{
"name": "canvix",
- "version": "0.15.5",
+ "version": "0.16.0",
"private": false,
- "description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",
+ "description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
"dev": "next dev -p 3000 2>&1 | tee dev.log",
"build": "node scripts/build.mjs",
diff --git a/prisma/migrations/0009_admin_console/migration.sql b/prisma/migrations/0009_admin_console/migration.sql
new file mode 100644
index 0000000..3d8b803
--- /dev/null
+++ b/prisma/migrations/0009_admin_console/migration.sql
@@ -0,0 +1,52 @@
+-- v0.16 (A1): admin console
+-- Three tables + one column:
+-- User.role — "user" | "admin"; effective admin ALSO honours the
+-- CANVIX_ADMIN_USERS env bootstrap (fail-closed both ways).
+-- AppConfig — instance-wide operator config (AI provider, models,
+-- feature flags, app settings) written from /admin.
+-- TrafficStat — per-day aggregate API counters (counts only, never
+-- ids/IPs/query strings) fed by the withLogging wrapper.
+-- DailyActive — one row per (UTC day, actor) for the DAU chart.
+-- Everything is additive: an instance that never opens /admin behaves
+-- exactly as before (role defaults to "user", no config rows, counters
+-- simply accumulate and can be switched off with CANVIX_TRAFFIC=0).
+
+-- AddColumn: User.role (default keeps every existing account a plain user)
+ALTER TABLE "User" ADD COLUMN "role" TEXT NOT NULL DEFAULT 'user';
+
+-- CreateTable: instance configuration store
+CREATE TABLE "AppConfig" (
+ "key" TEXT NOT NULL,
+ "value" JSONB NOT NULL,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "AppConfig_pkey" PRIMARY KEY ("key")
+);
+
+-- CreateTable: aggregate traffic counters
+CREATE TABLE "TrafficStat" (
+ "id" BIGSERIAL NOT NULL,
+ "day" TIMESTAMP(3) NOT NULL,
+ "route" TEXT NOT NULL,
+ "method" TEXT NOT NULL,
+ "status" INTEGER NOT NULL,
+ "hits" INTEGER NOT NULL DEFAULT 0,
+
+ CONSTRAINT "TrafficStat_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex: one upsert target + the day-range scans the console runs
+CREATE UNIQUE INDEX "TrafficStat_day_route_method_status_key" ON "TrafficStat"("day", "route", "method", "status");
+CREATE INDEX "TrafficStat_day_idx" ON "TrafficStat"("day");
+
+-- CreateTable: daily active actors
+CREATE TABLE "DailyActive" (
+ "id" BIGSERIAL NOT NULL,
+ "day" TIMESTAMP(3) NOT NULL,
+ "actor" TEXT NOT NULL,
+
+ CONSTRAINT "DailyActive_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex: the (day, actor) upsert target
+CREATE UNIQUE INDEX "DailyActive_day_actor_key" ON "DailyActive"("day", "actor");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index aff0d4e..655a16f 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -36,6 +36,11 @@ model User {
// lowercase, 3–32 chars, [a-z0-9_-] (enforced in src/lib/auth/validate.ts)
username String @unique
passwordHash String
+ // v0.16 (A1): admin console access. "user" | "admin". Effective admin ALSO
+ // honours the CANVIX_ADMIN_USERS env bootstrap (src/lib/admin/guard.ts) so
+ // the first admin exists without CLI surgery; this column is what the
+ // console manages afterwards.
+ role String @default("user")
createdAt DateTime @default(now())
designs Design[] @relation("DesignOwner")
folders Folder[] @relation("FolderOwner")
@@ -280,3 +285,47 @@ model PluginAsset {
@@unique([installId, path])
}
+
+// ── v0.16 (A1): admin console ─────────────────────────────────────────────────
+
+// Instance-wide configuration, written from /admin (AI provider,
+// models, feature flags, app settings). Small key→JSON rows; reads go
+// through the typed accessor + short-TTL cache in src/lib/admin/config.ts.
+// Nothing user-scoped ever lives here — operator config only.
+model AppConfig {
+ key String @id
+ value Json
+ updatedAt DateTime @updatedAt
+}
+
+// Per-day aggregate API traffic counters — the "see all the traffic"
+// side of the console. Written fire-and-forget by the withLogging wrapper
+// every API route already passes through (src/lib/observability.ts):
+// COUNTS ONLY — never ids, never IPs, never query strings. One row per
+// (UTC day, route, method, status); cardinality is bounded by the route
+// table × days × status codes. Rows older than 90 days are swept lazily.
+// CANVIX_TRAFFIC=0 opts an instance out entirely.
+model TrafficStat {
+ id BigInt @id @default(autoincrement())
+ day DateTime // UTC midnight
+ route String // logical route name, e.g. "GET /api/designs"
+ method String
+ status Int
+ hits Int @default(0)
+
+ @@unique([day, route, method, status])
+ @@index([day])
+}
+
+// Daily active actors for the DAU chart: one row per (UTC day, actor),
+// actor = userId for accounts or the already-hashed anonymous cookie key
+// for anonymous browsers. First-party, admin-visible only; recorded from
+// the two surfaces that mean "someone used Canvix today" (design list /
+// editor open), so it adds no extra auth resolution anywhere.
+model DailyActive {
+ id BigInt @id @default(autoincrement())
+ day DateTime
+ actor String
+
+ @@unique([day, actor])
+}
diff --git a/public/plugins/wordcloud/manifest.json b/public/plugins/wordcloud/manifest.json
index 2217f57..6761d29 100644
--- a/public/plugins/wordcloud/manifest.json
+++ b/public/plugins/wordcloud/manifest.json
@@ -9,7 +9,7 @@
"url": "https://github.com/mir-ashiq/canvix"
},
"engines": {
- "canvix": ">=0.13.4 <0.16.0"
+ "canvix": ">=0.13.4 <0.17.0"
},
"entry": {
"panel": "panel.html",
diff --git a/src/app/admin/ai/page.tsx b/src/app/admin/ai/page.tsx
new file mode 100644
index 0000000..f7309e1
--- /dev/null
+++ b/src/app/admin/ai/page.tsx
@@ -0,0 +1,7 @@
+'use client'
+
+import { AdminAiConfig } from '@/components/admin/ai-config'
+
+export default function AdminAiPage() {
+ return <AdminAiConfig />
+}
diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx
new file mode 100644
index 0000000..be547f3
--- /dev/null
+++ b/src/app/admin/layout.tsx
@@ -0,0 +1,19 @@
+import { cookies } from 'next/headers'
+import { getSessionUserFromToken, SESSION_COOKIE } from '@/lib/auth/session'
+import { isAdminUser } from '@/lib/admin/guard'
+import { AdminShell } from '@/components/admin/AdminShell'
+import { AdminDenied } from '@/components/admin/AdminDenied'
+
+// The server-side gate (v0.16 A1). Every /admin page renders inside
+// this layout, so the check runs before any child fetch; the API
+// routes re-check independently (defense in depth — the layout is
+// convenience, the API is the boundary).
+export const dynamic = 'force-dynamic'
+
+export default async function AdminLayout({ children }: { children: React.ReactNode }) {
+ const token = (await cookies()).get(SESSION_COOKIE)?.value
+ const user = await getSessionUserFromToken(token)
+ if (!user) return <AdminDenied signedIn={false} />
+ if (!isAdminUser(user)) return <AdminDenied signedIn username={user.username} />
+ return <AdminShell username={user.username}>{children}</AdminShell>
+}
diff --git a/src/app/admin/page.tsx b/src/app/admin/page.tsx
new file mode 100644
index 0000000..0e31a29
--- /dev/null
+++ b/src/app/admin/page.tsx
@@ -0,0 +1,7 @@
+'use client'
+
+import { AdminOverview } from '@/components/admin/overview'
+
+export default function AdminOverviewPage() {
+ return <AdminOverview />
+}
diff --git a/src/app/admin/settings/page.tsx b/src/app/admin/settings/page.tsx
new file mode 100644
index 0000000..e22af74
--- /dev/null
+++ b/src/app/admin/settings/page.tsx
@@ -0,0 +1,7 @@
+'use client'
+
+import { AdminSettings } from '@/components/admin/settings'
+
+export default function AdminSettingsPage() {
+ return <AdminSettings />
+}
diff --git a/src/app/admin/users/page.tsx b/src/app/admin/users/page.tsx
new file mode 100644
index 0000000..f9644b4
--- /dev/null
+++ b/src/app/admin/users/page.tsx
@@ -0,0 +1,7 @@
+'use client'
+
+import { AdminUsers } from '@/components/admin/users'
+
+export default function AdminUsersPage() {
+ return <AdminUsers />
+}
diff --git a/src/app/api/admin/config/ai-test/route.ts b/src/app/api/admin/config/ai-test/route.ts
new file mode 100644
index 0000000..3558c9d
--- /dev/null
+++ b/src/app/api/admin/config/ai-test/route.ts
@@ -0,0 +1,68 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { requireAdmin } from '@/lib/admin/guard'
+import { resolveProvider, getZAI, getTextModel, rateLimit } from '@/lib/ai/provider'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// POST /api/admin/config/ai-test — "does the provider actually answer?"
+// One minimal chat completion (thinking disabled, one-word reply) with a
+// 15 s circuit breaker. Admin-only and rate-limited to one probe per 10 s
+// — it is the one console action that spends real provider quota, and it
+// must never become a proxy for chatty automation.
+
+const TEST_TIMEOUT_MS = 15_000
+
+async function __canvix_post(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const guard = await requireAdmin(req)
+ if (!guard.ok) return guard.res
+
+ const rl = rateLimit('admin:ai-test', req, 1, 10)
+ if (!rl.ok) {
+ return NextResponse.json(
+ { ok: false, error: `Wait ${rl.retryAfterSec}s between provider tests.` },
+ { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } }
+ )
+ }
+
+ const provider = await resolveProvider()
+ if (!provider) {
+ return NextResponse.json(
+ { ok: false, error: 'No AI provider is configured — set one on this page or via ZAI_BASE_URL/ZAI_API_KEY.' },
+ { status: 503 }
+ )
+ }
+
+ try {
+ const zai = await getZAI()
+ if (!zai) return NextResponse.json({ ok: false, error: 'Provider initialization failed.' }, { status: 502 })
+ const model = await getTextModel()
+ const completion = await Promise.race([
+ zai.chat.completions.create({
+ ...(model ? { model } : {}),
+ messages: [{ role: 'user', content: 'Reply with the single word: ok' }],
+ thinking: { type: 'disabled' },
+ }),
+ new Promise<never>((_, reject) =>
+ setTimeout(() => reject(new Error('provider timed out')), TEST_TIMEOUT_MS)
+ ),
+ ])
+ const reply = String(
+ (completion as { choices?: { message?: { content?: string } }[] }).choices?.[0]?.message?.content ?? ''
+ ).slice(0, 120)
+ return NextResponse.json({
+ ok: true,
+ source: provider.source,
+ model: model ?? 'sdk-default',
+ reply: reply || '(empty reply)',
+ })
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ return NextResponse.json({ ok: false, error: message.slice(0, 300) }, { status: 502 })
+ }
+}
+
+export const POST = withLogging('POST /api/admin/config/ai-test', __canvix_post)
diff --git a/src/app/api/admin/config/route.ts b/src/app/api/admin/config/route.ts
new file mode 100644
index 0000000..579ff0d
--- /dev/null
+++ b/src/app/api/admin/config/route.ts
@@ -0,0 +1,136 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { requireAdmin } from '@/lib/admin/guard'
+import {
+ getModels,
+ getFeatures,
+ getSettings,
+ getProviderOverride,
+ setProvider,
+ clearProvider,
+ setModels,
+ setFeatures,
+ setSettings,
+ validateProvider,
+ validateModels,
+ validateFeatures,
+ validateSettings,
+ maskApiKey,
+} from '@/lib/admin/config'
+import { resolveProvider } from '@/lib/ai/provider'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// GET/PUT /api/admin/config — the console's configuration surface.
+//
+// GET is sanitized by construction: the stored API key only ever comes
+// back as a mask, env vars as presence booleans, and the effective base
+// URL (whatever layer it came from) — enough to operate on, never a
+// credential. PUT validates section by section and returns the same
+// sanitized shape back.
+
+async function sanitizedView() {
+ const [provider, stored, models, features, settings] = await Promise.all([
+ resolveProvider(),
+ getProviderOverride(),
+ getModels(),
+ getFeatures(),
+ getSettings(),
+ ])
+ return {
+ provider: {
+ configured: provider !== null,
+ source: provider?.source ?? null, // db | env | file | null
+ activeBaseUrl: provider?.baseUrl ?? null,
+ stored: stored ? { baseUrl: stored.baseUrl, keyMasked: maskApiKey(stored.apiKey) } : null,
+ env: {
+ urlSet: Boolean(process.env.ZAI_BASE_URL?.trim()),
+ keySet: Boolean(process.env.ZAI_API_KEY?.trim()),
+ },
+ },
+ models,
+ features,
+ settings,
+ }
+}
+
+async function __canvix_get(req: NextRequest) {
+ const guard = await requireAdmin(req)
+ if (!guard.ok) return guard.res
+ try {
+ return NextResponse.json(await sanitizedView())
+ } catch (error) {
+ console.error('GET /api/admin/config failed', error)
+ return NextResponse.json({ error: 'Configuration unavailable — database unreachable.' }, { status: 503 })
+ }
+}
+
+async function __canvix_put(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const guard = await requireAdmin(req)
+ if (!guard.ok) return guard.res
+
+ try {
+ const body = (await req.json().catch(() => ({}))) as Record<string, unknown>
+
+ // ── provider section ────────────────────────────────────────
+ // null clears the override (fall back to env/file). An object sets
+ // it: both fields together activate, both empty clears, half-empty
+ // is a 400 — the operator always gets an explicit error instead of
+ // a silently half-configured provider.
+ if (body.provider !== undefined) {
+ if (body.provider === null) {
+ await clearProvider()
+ } else if (typeof body.provider === 'object' && body.provider !== null) {
+ const raw = body.provider as Record<string, unknown>
+ const baseUrl = typeof raw.baseUrl === 'string' ? raw.baseUrl.trim() : ''
+ const apiKey = typeof raw.apiKey === 'string' ? raw.apiKey : ''
+ if (!baseUrl && !apiKey) {
+ await clearProvider()
+ } else if (!baseUrl || !apiKey) {
+ return NextResponse.json(
+ { error: 'A provider override needs both baseUrl and apiKey. Send null to clear it.' },
+ { status: 400 }
+ )
+ } else {
+ const check = validateProvider({ baseUrl, apiKey })
+ if (!check.ok) return NextResponse.json({ error: check.error }, { status: 400 })
+ await setProvider(check.value)
+ }
+ } else {
+ return NextResponse.json({ error: 'provider must be an object or null.' }, { status: 400 })
+ }
+ }
+
+ // ── models section (full replace) ───────────────────────────
+ if (body.models !== undefined) {
+ const check = validateModels(body.models)
+ if (!check.ok) return NextResponse.json({ error: check.error }, { status: 400 })
+ await setModels(check.value)
+ }
+
+ // ── features section (partial merge over current) ───────────
+ if (body.features !== undefined) {
+ const check = validateFeatures(body.features)
+ if (!check.ok) return NextResponse.json({ error: check.error }, { status: 400 })
+ await setFeatures({ ...(await getFeatures()), ...check.value })
+ }
+
+ // ── settings section (partial merge over current) ───────────
+ if (body.settings !== undefined) {
+ const check = validateSettings(body.settings)
+ if (!check.ok) return NextResponse.json({ error: check.error }, { status: 400 })
+ await setSettings({ ...(await getSettings()), ...check.value })
+ }
+
+ return NextResponse.json(await sanitizedView())
+ } catch (error) {
+ console.error('PUT /api/admin/config failed', error)
+ return NextResponse.json({ error: 'Could not save the configuration. Please try again.' }, { status: 500 })
+ }
+}
+
+export const GET = withLogging('GET /api/admin/config', __canvix_get)
+export const PUT = withLogging('PUT /api/admin/config', __canvix_put)
diff --git a/src/app/api/admin/overview/route.ts b/src/app/api/admin/overview/route.ts
new file mode 100644
index 0000000..022f96a
--- /dev/null
+++ b/src/app/api/admin/overview/route.ts
@@ -0,0 +1,142 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { requireAdmin, isAdminUser, adminSource } from '@/lib/admin/guard'
+import { resolveProvider } from '@/lib/ai/provider'
+import { fillDays, sumSeries, dayKey, type DayPoint } from '@/lib/admin/series'
+import { APP_VERSION, withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// GET /api/admin/overview — everything the console's landing page shows:
+// totals, 14-day traffic/DAU/signup/AI series, top routes, AI usage by
+// feature, the ten newest accounts and which layer answers as the AI
+// provider. Aggregate counts only — the same stance as /api/health?v=2.
+
+const DAYS = 14
+
+interface RawDayRow {
+ day: Date
+ n: number
+}
+interface RawTrafficRow {
+ day: Date
+ hits: number
+}
+interface RawAiDayRow {
+ day: Date
+ n: number
+ ok: number
+}
+
+async function __canvix_get(req: NextRequest) {
+ const guard = await requireAdmin(req)
+ if (!guard.ok) return guard.res
+
+ const probeStart = Date.now()
+ try {
+ const since = new Date(Date.now() - (DAYS - 1) * 24 * 60 * 60 * 1000)
+ const since7 = new Date(Date.now() - 6 * 24 * 60 * 60 * 1000)
+
+ const [
+ users,
+ designs,
+ templates,
+ mediaAgg,
+ comments,
+ aiTotal,
+ activeSessions,
+ trafficRows,
+ dauRows,
+ signupRows,
+ aiDayRows,
+ topRoutes,
+ aiByFeature,
+ recentUsers,
+ provider,
+ ] = await Promise.all([
+ db.user.count(),
+ db.design.count({ where: { deletedAt: null } }),
+ db.template.count(),
+ db.media.aggregate({ _count: true, _sum: { size: true } }),
+ db.comment.count(),
+ db.aIUsage.count(),
+ db.session.count({ where: { expiresAt: { gt: new Date() } } }),
+ db.$queryRaw<RawTrafficRow[]>`
+ SELECT "day", SUM("hits")::int AS hits FROM "TrafficStat"
+ WHERE "day" >= ${since} GROUP BY "day" ORDER BY "day"`,
+ db.$queryRaw<RawDayRow[]>`
+ SELECT "day", COUNT(*)::int AS n FROM "DailyActive"
+ WHERE "day" >= ${since} GROUP BY "day" ORDER BY "day"`,
+ db.$queryRaw<RawDayRow[]>`
+ SELECT date_trunc('day', "createdAt") AS day, COUNT(*)::int AS n FROM "User"
+ WHERE "createdAt" >= ${since} GROUP BY 1 ORDER BY 1`,
+ db.$queryRaw<RawAiDayRow[]>`
+ SELECT date_trunc('day', "createdAt") AS day, COUNT(*)::int AS n,
+ COUNT(*) FILTER (WHERE "ok")::int AS ok
+ FROM "AIUsage" WHERE "createdAt" >= ${since} GROUP BY 1 ORDER BY 1`,
+ db.$queryRaw<{ route: string; method: string; hits: number }[]>`
+ SELECT "route", "method", SUM("hits")::int AS hits FROM "TrafficStat"
+ WHERE "day" >= ${since7} GROUP BY "route", "method" ORDER BY 3 DESC LIMIT 10`,
+ db.$queryRaw<{ feature: string; n: number; ok: number }[]>`
+ SELECT "feature", COUNT(*)::int AS n, COUNT(*) FILTER (WHERE "ok")::int AS ok
+ FROM "AIUsage" WHERE "createdAt" >= ${since7} GROUP BY "feature" ORDER BY 2 DESC`,
+ db.user.findMany({
+ orderBy: { createdAt: 'desc' },
+ take: 10,
+ select: { id: true, username: true, role: true, createdAt: true },
+ }),
+ resolveProvider(),
+ ])
+ const dbLatencyMs = Date.now() - probeStart
+
+ // sparse SQL rows → gap-free UTC day series
+ const traffic: DayPoint[] = fillDays(trafficRows.map((r) => [dayKey(new Date(r.day)), r.hits]), DAYS)
+ const dau: DayPoint[] = fillDays(dauRows.map((r) => [dayKey(new Date(r.day)), r.n]), DAYS)
+ const signups: DayPoint[] = fillDays(signupRows.map((r) => [dayKey(new Date(r.day)), r.n]), DAYS)
+ // fillDays reorders/drops rows — rebuild ok counts from a keyed map
+ const okByKey = new Map(aiDayRows.map((r) => [dayKey(new Date(r.day)), Number(r.ok)]))
+ const aiCalls: { day: string; value: number; ok: number }[] = fillDays(
+ aiDayRows.map((r) => [dayKey(new Date(r.day)), r.n]),
+ DAYS
+ ).map((p) => ({ ...p, ok: okByKey.get(p.day) ?? 0 }))
+
+ return NextResponse.json({
+ version: APP_VERSION,
+ dbLatencyMs,
+ totals: {
+ users,
+ designs,
+ templates,
+ mediaCount: mediaAgg._count,
+ mediaBytes: mediaAgg._sum.size ?? 0,
+ comments,
+ aiCalls: aiTotal,
+ activeSessions,
+ },
+ windows: {
+ requests24h: sumSeries(traffic, 1),
+ requests7d: sumSeries(traffic, 7),
+ ai7d: sumSeries(aiCalls, 7),
+ dauToday: dau[dau.length - 1]?.value ?? 0,
+ },
+ series: { traffic, dau, signups, aiCalls },
+ topRoutes: topRoutes.map((r) => ({ route: r.route, method: r.method, hits: r.hits })),
+ aiByFeature: aiByFeature.map((r) => ({ feature: r.feature, calls: r.n, ok: r.ok })),
+ recentUsers: recentUsers.map((u) => ({
+ id: u.id,
+ username: u.username,
+ role: u.role,
+ createdAt: u.createdAt,
+ admin: isAdminUser(u),
+ adminSource: adminSource(u),
+ })),
+ provider: { configured: provider !== null, source: provider?.source ?? null },
+ })
+ } catch (error) {
+ console.error('GET /api/admin/overview failed', error)
+ return NextResponse.json({ error: 'Overview unavailable — database unreachable.' }, { status: 503 })
+ }
+}
+
+export const GET = withLogging('GET /api/admin/overview', __canvix_get)
diff --git a/src/app/api/admin/users/[id]/role/route.ts b/src/app/api/admin/users/[id]/role/route.ts
new file mode 100644
index 0000000..f89fc74
--- /dev/null
+++ b/src/app/api/admin/users/[id]/role/route.ts
@@ -0,0 +1,60 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { requireAdmin, isAdminUser, adminSource } from '@/lib/admin/guard'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// POST /api/admin/users/[id]/role — grant or revoke console access.
+// body: { role: "admin" | "user" }
+//
+// Guards:
+// • self-change is refused — an admin must never be able to lock
+// themselves out of the only page that can undo the change. (An
+// env-bootstrap admin can always recover a pure-DB lockout; this
+// guard removes the footgun entirely.)
+// • changing a username that CANVIX_ADMIN_USERS blesses is allowed
+// but pointless — the env wins by design. The UI shows an "env"
+// badge so nobody is surprised.
+
+async function __canvix_post(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const guard = await requireAdmin(req)
+ if (!guard.ok) return guard.res
+
+ try {
+ const { id } = await params
+ const body = await req.json().catch(() => ({}))
+ const role = (body as { role?: unknown })?.role
+ if (role !== 'admin' && role !== 'user') {
+ return NextResponse.json({ error: 'role must be "admin" or "user".' }, { status: 400 })
+ }
+ if (id === guard.user.id) {
+ return NextResponse.json(
+ { error: 'You cannot change your own role — ask another administrator.', code: 'SELF_ROLE_CHANGE' },
+ { status: 400 }
+ )
+ }
+ const target = await db.user.findUnique({
+ where: { id },
+ select: { id: true, username: true, role: true },
+ })
+ if (!target) return NextResponse.json({ error: 'User not found.' }, { status: 404 })
+
+ const updated = await db.user.update({
+ where: { id },
+ data: { role },
+ select: { id: true, username: true, role: true, createdAt: true },
+ })
+ return NextResponse.json({
+ user: { ...updated, admin: isAdminUser(updated), adminSource: adminSource(updated) },
+ })
+ } catch (error) {
+ console.error('POST /api/admin/users/[id]/role failed', error)
+ return NextResponse.json({ error: 'Could not update the role. Please try again.' }, { status: 500 })
+ }
+}
+
+export const POST = withLogging('POST /api/admin/users/[id]/role', __canvix_post)
diff --git a/src/app/api/admin/users/[id]/sessions/route.ts b/src/app/api/admin/users/[id]/sessions/route.ts
new file mode 100644
index 0000000..9cb156b
--- /dev/null
+++ b/src/app/api/admin/users/[id]/sessions/route.ts
@@ -0,0 +1,33 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { requireAdmin } from '@/lib/admin/guard'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// POST /api/admin/users/[id]/sessions — revoke every session of one
+// user ("sign out everywhere"). Sessions are opaque server-side rows,
+// so this is a single bounded DELETE; the user's designs and uploads
+// are untouched. Works on the admin's own rows too (an explicit sign-
+// out of the console session itself, nothing more dramatic).
+
+async function __canvix_post(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const guard = await requireAdmin(req)
+ if (!guard.ok) return guard.res
+
+ try {
+ const { id } = await params
+ const target = await db.user.findUnique({ where: { id }, select: { id: true } })
+ if (!target) return NextResponse.json({ error: 'User not found.' }, { status: 404 })
+ const { count } = await db.session.deleteMany({ where: { userId: id } })
+ return NextResponse.json({ revoked: count })
+ } catch (error) {
+ console.error('POST /api/admin/users/[id]/sessions failed', error)
+ return NextResponse.json({ error: 'Could not revoke sessions. Please try again.' }, { status: 500 })
+ }
+}
+
+export const POST = withLogging('POST /api/admin/users/[id]/sessions', __canvix_post)
diff --git a/src/app/api/admin/users/route.ts b/src/app/api/admin/users/route.ts
new file mode 100644
index 0000000..9b133cf
--- /dev/null
+++ b/src/app/api/admin/users/route.ts
@@ -0,0 +1,73 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { requireAdmin, isAdminUser, adminSource } from '@/lib/admin/guard'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// GET /api/admin/users — the console's user directory.
+// ?q=<username substring> · ?page=<0-based> (25 per page).
+// Aggregate columns (designs owned, active sessions, last active) are
+// fetched with two GROUP BY queries over the page's ids — never per-row.
+
+const PAGE_SIZE = 25
+
+async function __canvix_get(req: NextRequest) {
+ const guard = await requireAdmin(req)
+ if (!guard.ok) return guard.res
+
+ try {
+ const q = (req.nextUrl.searchParams.get('q') ?? '').trim().toLowerCase().slice(0, 64)
+ const page = Math.max(0, Math.min(Number(req.nextUrl.searchParams.get('page')) || 0, 500))
+ const where = q ? { username: { contains: q } } : {}
+
+ const [total, users] = await Promise.all([
+ db.user.count({ where }),
+ db.user.findMany({
+ where,
+ orderBy: [{ createdAt: 'desc' }, { id: 'asc' }],
+ skip: page * PAGE_SIZE,
+ take: PAGE_SIZE,
+ select: { id: true, username: true, role: true, createdAt: true },
+ }),
+ ])
+
+ const ids = users.map((u) => u.id)
+ const designCounts = new Map<string, number>()
+ const sessionInfo = new Map<string, { active: number; last: Date | null }>()
+ if (ids.length) {
+ const [dRows, sRows] = await Promise.all([
+ db.$queryRaw<{ id: string; n: number }[]>`
+ SELECT "ownerId" AS id, COUNT(*)::int AS n FROM "Design"
+ WHERE "ownerId" = ANY(${ids}::text[]) AND "deletedAt" IS NULL GROUP BY "ownerId"`,
+ db.$queryRaw<{ id: string; active: number; last: Date | null }[]>`
+ SELECT "userId" AS id,
+ COUNT(*) FILTER (WHERE "expiresAt" > now())::int AS active,
+ MAX("createdAt") AS last
+ FROM "Session" WHERE "userId" = ANY(${ids}::text[]) GROUP BY "userId"`,
+ ])
+ for (const r of dRows) designCounts.set(r.id, r.n)
+ for (const r of sRows) sessionInfo.set(r.id, { active: r.active, last: r.last })
+ }
+
+ return NextResponse.json({
+ total,
+ page,
+ pageSize: PAGE_SIZE,
+ users: users.map((u) => ({
+ ...u,
+ admin: isAdminUser(u),
+ adminSource: adminSource(u),
+ designs: designCounts.get(u.id) ?? 0,
+ activeSessions: sessionInfo.get(u.id)?.active ?? 0,
+ lastActiveAt: sessionInfo.get(u.id)?.last ?? null,
+ })),
+ })
+ } catch (error) {
+ console.error('GET /api/admin/users failed', error)
+ return NextResponse.json({ error: 'User directory unavailable — database unreachable.' }, { status: 503 })
+ }
+}
+
+export const GET = withLogging('GET /api/admin/users', __canvix_get)
diff --git a/src/app/api/ai/assistant/route.ts b/src/app/api/ai/assistant/route.ts
index 9721b7b..8e71d67 100644
--- a/src/app/api/ai/assistant/route.ts
+++ b/src/app/api/ai/assistant/route.ts
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
-import { withProvider } from '@/lib/ai/provider'
+import { withProvider, getTextModel } from '@/lib/ai/provider'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
@@ -295,6 +295,7 @@ async function __canvix_post(req: NextRequest) {
.map((m) => ({ role: m.role, content: m.content.slice(0, 1000) }))
const completion = await zai.chat.completions.create({
+ model: await getTextModel(),
messages: [
{ role: 'assistant', content: system },
{ role: 'assistant', content: `Current design context:\n${designContext}` },
diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.ts
index e4c77c3..97e1966 100644
--- a/src/app/api/ai/capabilities/route.ts
+++ b/src/app/api/ai/capabilities/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server'
import { hasProvider } from '@/lib/ai/provider'
+import { getFeatures } from '@/lib/admin/config'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
@@ -12,17 +13,21 @@ export const dynamic = 'force-dynamic'
* Only ever exposes which capabilities exist — never config, never keys.
*/
async function __canvix_get() {
- const configured = hasProvider()
+ // v0.16 (A1): a capability is available when a provider answers AND
+ // the admin console has not switched the feature off. Still booleans
+ // only — never config, never keys, never which layer answered.
+ const configured = await hasProvider()
+ const flags = await getFeatures()
return NextResponse.json({
configured,
capabilities: {
- magicWrite: configured,
- imageGeneration: configured,
- imageEditing: configured,
- vision: configured, // Magic Layers
- translation: configured,
- assistant: configured,
- photoSearch: configured,
+ magicWrite: configured && flags.magicWrite,
+ imageGeneration: configured && flags.imageGeneration,
+ imageEditing: configured && flags.imageEditing,
+ vision: configured && flags.vision, // Magic Layers
+ translation: configured && flags.translation,
+ assistant: configured && flags.assistant,
+ photoSearch: configured && flags.photoSearch,
backgroundRemoval: true, // local ONNX — always available
colorPalette: true, // local deterministic
layoutSuggestions: true, // local deterministic
diff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.ts
index ba54d69..421982c 100644
--- a/src/app/api/ai/image-edit/route.ts
+++ b/src/app/api/ai/image-edit/route.ts
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
-import { withProvider } from '@/lib/ai/provider'
+import { withProvider, getImageModel } from '@/lib/ai/provider'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
diff --git a/src/app/api/ai/image/route.ts b/src/app/api/ai/image/route.ts
index a723fc9..5133a0d 100644
--- a/src/app/api/ai/image/route.ts
+++ b/src/app/api/ai/image/route.ts
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
-import { withProvider } from '@/lib/ai/provider'
+import { withProvider, getImageModel } from '@/lib/ai/provider'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
@@ -27,6 +27,7 @@ async function __canvix_post(req: NextRequest) {
return withProvider('image', req, { limit: 5, windowSec: 60 }, async (zai) => {
const response = await zai.images.generations.create({
+ model: await getImageModel(),
prompt,
size,
})
diff --git a/src/app/api/ai/magic-layers/route.ts b/src/app/api/ai/magic-layers/route.ts
index e242e35..cd34c3e 100644
--- a/src/app/api/ai/magic-layers/route.ts
+++ b/src/app/api/ai/magic-layers/route.ts
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
-import { withProvider, VISION_MODEL } from '@/lib/ai/provider'
+import { withProvider, getVisionModel } from '@/lib/ai/provider'
import { validateAnalysis } from '@/lib/magic-layers/validate'
import { withLogging } from '@/lib/observability'
@@ -56,7 +56,7 @@ async function __canvix_post(req: NextRequest) {
'10. notes = one short sentence about what the reconstruction will approximate (e.g. "illustration left of title will become a cropped image region").'
const completion = await zai.chat.completions.createVision({
- model: VISION_MODEL,
+ model: await getVisionModel(),
messages: [
{ role: 'system', content: system },
{
diff --git a/src/app/api/ai/translate/route.ts b/src/app/api/ai/translate/route.ts
index 570c7ab..7a4cfee 100644
--- a/src/app/api/ai/translate/route.ts
+++ b/src/app/api/ai/translate/route.ts
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
-import { withProvider } from '@/lib/ai/provider'
+import { withProvider, getTextModel } from '@/lib/ai/provider'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
@@ -57,6 +57,7 @@ async function __canvix_post(req: NextRequest) {
return withProvider('translate', req, { limit: 15, windowSec: 60 }, async (zai) => {
const completion = await zai.chat.completions.create({
+ model: await getTextModel(),
messages: [
{ role: 'assistant', content: system },
{ role: 'user', content: user },
diff --git a/src/app/api/ai/write/route.ts b/src/app/api/ai/write/route.ts
index 05cf5de..6db883c 100644
--- a/src/app/api/ai/write/route.ts
+++ b/src/app/api/ai/write/route.ts
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
-import { withProvider } from '@/lib/ai/provider'
+import { withProvider, getTextModel } from '@/lib/ai/provider'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
@@ -33,6 +33,7 @@ async function __canvix_post(req: NextRequest) {
return withProvider('write', req, { limit: 20, windowSec: 60 }, async (zai) => {
const completion = await zai.chat.completions.create({
+ model: await getTextModel(),
messages: [
{
role: 'assistant',
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
index bdb38ae..e122f4f 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -1,12 +1,24 @@
import { NextRequest, NextResponse } from 'next/server'
import { getSessionUser } from '@/lib/auth/session'
+import { isAdminUser } from '@/lib/admin/guard'
import { withLogging } from '@/lib/observability'
// GET /api/auth/me — the signed-in user (or null). Public endpoint the
// dashboard/editor use to decide between account mode and anonymous mode.
async function __canvix_get(req: NextRequest) {
const user = await getSessionUser(req)
- return NextResponse.json({ user: user ? { id: user.id, username: user.username, createdAt: user.createdAt } : null })
+ return NextResponse.json({
+ user: user
+ ? {
+ id: user.id,
+ username: user.username,
+ createdAt: user.createdAt,
+ // v0.16 (A1): drives the dashboard's Admin link. Env-bootstrap
+ // admins (CANVIX_ADMIN_USERS) resolve true here too.
+ admin: isAdminUser(user),
+ }
+ : null,
+ })
}
// v0.12.5 (H7): opt-in request logging wrapper — passthrough
diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.ts
index 820d449..cfca439 100644
--- a/src/app/api/auth/register/route.ts
+++ b/src/app/api/auth/register/route.ts
@@ -8,6 +8,7 @@ import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
import { withLogging } from '@/lib/observability'
import { claimAnonMedia } from '@/lib/auth/claim-media'
import { claimAnonFolders } from '@/lib/auth/claim-folders'
+import { getSettings } from '@/lib/admin/config'
// POST /api/auth/register — create an account (username + password).
// Free forever: no email, no verification, no external provider — a
@@ -15,6 +16,15 @@ import { claimAnonFolders } from '@/lib/auth/claim-folders'
// v0.9.1: same-origin enforced (blocks cross-site forced sign-ups).
async function __canvix_post(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ // v0.16 (A1): the admin console's "allow new sign-ups" switch. Checked
+ // BEFORE the rate limiter so a closed instance burns none of an honest
+ // visitor's 5/hour attempts on a doomed request.
+ if (!(await getSettings()).signupsOpen) {
+ return NextResponse.json(
+ { error: 'Sign-ups are currently closed on this instance.', code: 'SIGNUPS_CLOSED' },
+ { status: 503 }
+ )
+ }
const rl = rateLimit('auth:register', req, 5, 3600)
if (!rl.ok) {
return NextResponse.json(
diff --git a/src/app/api/designs/[id]/route.ts b/src/app/api/designs/[id]/route.ts
index d79f71e..197e3c8 100644
--- a/src/app/api/designs/[id]/route.ts
+++ b/src/app/api/designs/[id]/route.ts
@@ -7,6 +7,10 @@ import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
import { mergePages } from '@/lib/collab/merge'
import type { PageData } from '@/lib/types'
import { withLogging } from '@/lib/observability'
+import { getSessionUser } from '@/lib/auth/session'
+import { anonHashFrom } from '@/lib/auth/anon'
+import { recordActive } from '@/lib/admin/traffic'
+import { getSettings } from '@/lib/admin/config'
// Normalise incoming pages payload (accepts object or legacy JSON string)
// into a value suitable for the Postgres jsonb column.
@@ -34,6 +38,8 @@ async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id
const access = await resolveDesignAccess(req, id)
if (!access) return NextResponse.json({ error: 'Not found' }, { status: 404 })
const design = access.design
+ // v0.16 (A1): opening the editor counts as daily activity
+ void recordActive((await getSessionUser(req))?.id ?? anonHashFrom(req))
const maxEvent = await db.designEvent
.aggregate({ where: { designId: id }, _max: { id: true } })
.catch(() => null)
@@ -70,6 +76,17 @@ async function __canvix_put(req: NextRequest, { params }: { params: Promise<{ id
if (!access) return NextResponse.json({ error: 'Not found' }, { status: 404 })
if (!access.canEdit) return NextResponse.json(NOT_YOUR_DESIGN, { status: 403 })
+ // v0.16 (A1): anonymous saves are refused when the console disables
+ // anonymous editing (the ownerless commons included). The session is
+ // only resolved on the disabled path — the default path costs one
+ // cached config read and nothing else.
+ if (!(await getSettings()).anonymousEditing && !(await getSessionUser(req))) {
+ return NextResponse.json(
+ { error: 'Anonymous editing is disabled on this instance. Sign in to save changes.', code: 'ANON_DISABLED' },
+ { status: 403 }
+ )
+ }
+
const body = await req.json()
const data: Record<string, unknown> = {}
if (typeof body.name === 'string' && body.name.trim()) data.name = body.name.trim().slice(0, 120)
diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.ts
index 241fb7d..eaa018a 100644
--- a/src/app/api/designs/route.ts
+++ b/src/app/api/designs/route.ts
@@ -7,6 +7,8 @@ import { readAnonToken, newAnonToken, anonKeyHash, setAnonCookie, anonHashFrom }
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
import { withLogging } from '@/lib/observability'
+import { recordActive } from '@/lib/admin/traffic'
+import { getSettings } from '@/lib/admin/config'
/** v0.14 (D6): resolve a ?folder= id / POST folderId to a folder the
* CALLER owns, or null. Foreign and absent ids are indistinguishable
@@ -76,6 +78,10 @@ async function __canvix_get(req: NextRequest) {
const cursorId = req.nextUrl.searchParams.get('id')
const user = await getSessionUser(req)
+ // v0.16 (A1): opening the dashboard counts as daily activity
+ // (userId for accounts, the pre-hashed anon cookie key otherwise)
+ void recordActive(user?.id ?? anonHashFrom(req))
+
// v0.14 (D6): ?folder=<id> — one of the caller's own folders, or a
// flat 404. Absent param = "All designs" (unchanged behaviour).
let folderFilter: string | null = null
@@ -160,6 +166,20 @@ async function __canvix_post(req: NextRequest) {
if (!limit.ok) return rateLimitResponse(limit)
try {
const user = await getSessionUser(req)
+
+ // v0.16 (A1): the console's "anonymous editing" switch — anonymous
+ // design CREATION is refused when off. Reading, sharing and exporting
+ // existing designs is untouched; the check is one cached config read.
+ if (!user) {
+ const settings = await getSettings()
+ if (!settings.anonymousEditing) {
+ return NextResponse.json(
+ { error: 'Anonymous editing is disabled on this instance. Sign in to create designs.', code: 'ANON_DISABLED' },
+ { status: 403 }
+ )
+ }
+ }
+
const body = await req.json()
// v0.14 (D6): optional folderId — a design can be born filed into
diff --git a/src/components/admin/AdminDenied.tsx b/src/components/admin/AdminDenied.tsx
new file mode 100644
index 0000000..d9ade06
--- /dev/null
+++ b/src/components/admin/AdminDenied.tsx
@@ -0,0 +1,42 @@
+import Link from 'next/link'
+import { LogIn, ShieldAlert } from 'lucide-react'
+
+/**
+ * Rendered by the admin layout when the visitor is not an admin
+ * (v0.16 A1). No detail about WHO is admin leaks — just the two states:
+ * not signed in, or signed in without access.
+ */
+export function AdminDenied({ signedIn, username }: { signedIn: boolean; username?: string }) {
+ return (
+ <div className="flex min-h-screen items-center justify-center bg-background px-4 text-foreground">
+ <div className="w-full max-w-md rounded-xl border bg-card p-8 text-center">
+ <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
+ {signedIn ? <ShieldAlert size={22} className="text-muted-foreground" /> : <LogIn size={22} className="text-muted-foreground" />}
+ </div>
+ <h1 className="text-lg font-semibold">
+ {signedIn ? 'No administrator access' : 'Sign in required'}
+ </h1>
+ <p className="mt-2 text-sm text-muted-foreground">
+ {signedIn ? (
+ <>
+ The account <span className="font-medium text-foreground">{username}</span> does not have admin rights on
+ this instance.
+ </>
+ ) : (
+ 'The admin console needs a signed-in administrator account.'
+ )}
+ </p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Administrators are granted via the <code className="rounded bg-muted px-1">CANVIX_ADMIN_USERS</code> environment
+ variable or by another administrator.
+ </p>
+ <Link
+ href="/"
+ className="mt-6 inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:opacity-90"
+ >
+ Back to Canvix
+ </Link>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/admin/AdminShell.tsx b/src/components/admin/AdminShell.tsx
new file mode 100644
index 0000000..1db2868
--- /dev/null
+++ b/src/components/admin/AdminShell.tsx
@@ -0,0 +1,77 @@
+'use client'
+
+import { usePathname } from 'next/navigation'
+import Link from 'next/link'
+import type { ReactNode } from 'react'
+import { LayoutDashboard, Users, Sparkles, Settings, ArrowLeft } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import { Logo } from '@/components/logo'
+
+const NAV = [
+ { href: '/admin', label: 'Overview', icon: LayoutDashboard, exact: true },
+ { href: '/admin/users', label: 'Users', icon: Users, exact: false },
+ { href: '/admin/ai', label: 'AI & models', icon: Sparkles, exact: false },
+ { href: '/admin/settings', label: 'Settings', icon: Settings, exact: false },
+] as const
+
+/**
+ * The console chrome (v0.16 A1): brand bar + section nav + back link.
+ * Server-side gating already happened in the layout — this component
+ * never renders for non-admins, and every API it calls re-checks anyway
+ * (defense in depth).
+ */
+export function AdminShell({
+ username,
+ children,
+}: {
+ username: string
+ children: ReactNode
+}) {
+ const pathname = usePathname()
+ return (
+ <div className="min-h-screen bg-background text-foreground">
+ <div className="cv-topbar-gradient h-1.5 w-full" />
+ <div className="mx-auto flex max-w-6xl flex-col gap-0 px-4 pb-16 md:px-6">
+ <header className="flex flex-wrap items-center justify-between gap-3 py-5">
+ <div className="flex items-center gap-3">
+ <Logo size={30} />
+ <div>
+ <h1 className="text-lg font-bold leading-tight">Admin console</h1>
+ <p className="text-xs text-muted-foreground">
+ signed in as <span className="font-medium text-foreground">{username}</span>
+ </p>
+ </div>
+ </div>
+ <Link
+ href="/"
+ className="inline-flex items-center gap-1.5 rounded-lg border bg-card px-3 py-1.5 text-sm font-medium text-card-foreground transition-colors hover:bg-muted"
+ >
+ <ArrowLeft size={15} /> Back to Canvix
+ </Link>
+ </header>
+
+ <nav className="mb-6 flex gap-1 overflow-x-auto rounded-xl border bg-card p-1" aria-label="Admin sections">
+ {NAV.map((item) => {
+ const active = item.exact ? pathname === item.href : pathname.startsWith(item.href)
+ return (
+ <Link
+ key={item.href}
+ href={item.href}
+ aria-current={active ? 'page' : undefined}
+ className={cn(
+ 'flex shrink-0 items-center gap-2 rounded-lg px-3.5 py-2 text-sm font-medium transition-colors',
+ active ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:bg-muted hover:text-foreground'
+ )}
+ >
+ <item.icon size={16} />
+ {item.label}
+ </Link>
+ )
+ })}
+ </nav>
+
+ <main className="flex flex-col gap-5">{children}</main>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/admin/ai-config.tsx b/src/components/admin/ai-config.tsx
new file mode 100644
index 0000000..7499d5a
--- /dev/null
+++ b/src/components/admin/ai-config.tsx
@@ -0,0 +1,238 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+import { Zap } from 'lucide-react'
+import { getJson, sendJson } from './fetch'
+import { Card, Toggle, Chip } from './bits'
+
+interface ConfigView {
+ provider: {
+ configured: boolean
+ source: string | null
+ activeBaseUrl: string | null
+ stored: { baseUrl: string; keyMasked: string } | null
+ env: { urlSet: boolean; keySet: boolean }
+ }
+ models: { text?: string; vision?: string; image?: string }
+ features: Record<string, boolean>
+ settings: { signupsOpen: boolean; anonymousEditing: boolean }
+}
+
+const FEATURE_INFO: { key: string; label: string; hint: string }[] = [
+ { key: 'magicWrite', label: 'Magic Write', hint: 'AI copy suggestions in the text toolbar' },
+ { key: 'imageGeneration', label: 'Image generation', hint: 'Text-to-image in the Photos panel' },
+ { key: 'imageEditing', label: 'Image editing', hint: 'Magic Eraser / Enhance on selected images' },
+ { key: 'vision', label: 'Magic Layers', hint: 'Image understanding that rebuilds layered designs' },
+ { key: 'translation', label: 'Translate', hint: 'Text translation in the text toolbar' },
+ { key: 'assistant', label: 'Assistant', hint: 'The chat assistant that edits designs' },
+ { key: 'photoSearch', label: 'Photo search', hint: 'Stock photo search in the Photos panel' },
+]
+
+const SOURCE_LABEL: Record<string, string> = { db: 'console override', env: 'environment variables', file: '.z-ai-config file' }
+
+export function AdminAiConfig() {
+ const [view, setView] = useState<ConfigView | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [notice, setNotice] = useState<string | null>(null)
+
+ const [baseUrl, setBaseUrl] = useState('')
+ const [apiKey, setApiKey] = useState('')
+ const [models, setModels] = useState<{ text: string; vision: string; image: string }>({ text: '', vision: '', image: '' })
+ const [features, setFeatures] = useState<Record<string, boolean>>({})
+ const [busy, setBusy] = useState(false)
+ const [test, setTest] = useState<{ ok: boolean; message: string } | null>(null)
+
+ useEffect(() => {
+ getJson<ConfigView>('/api/admin/config').then((res) => {
+ if (res.ok) {
+ setView(res.data)
+ setBaseUrl(res.data.provider.stored?.baseUrl ?? '')
+ setModels({
+ text: res.data.models.text ?? '',
+ vision: res.data.models.vision ?? '',
+ image: res.data.models.image ?? '',
+ })
+ setFeatures(res.data.features)
+ setError(null)
+ } else {
+ setError(res.data?.error ?? `Request failed (${res.status})`)
+ }
+ })
+ }, [])
+
+ async function put(body: unknown, message: string) {
+ setBusy(true)
+ const res = await sendJson<ConfigView & { error?: string }>('/api/admin/config', 'PUT', body)
+ setBusy(false)
+ if (!res.ok) {
+ setNotice(null)
+ setError(res.data?.error ?? `Could not save (${res.status}).`)
+ return
+ }
+ setError(null)
+ setNotice(message)
+ setView(res.data)
+ setApiKey('')
+ setTimeout(() => setNotice(null), 4000)
+ }
+
+ async function testProvider() {
+ setBusy(true)
+ setTest(null)
+ const res = await sendJson<{ ok: boolean; model?: string; reply?: string; error?: string }>('/api/admin/config/ai-test', 'POST', {})
+ setBusy(false)
+ if (res.ok && res.data.ok) {
+ setTest({ ok: true, message: `Provider answered (model ${res.data.model}): “${res.data.reply}”` })
+ } else {
+ setTest({ ok: false, message: (res.data.error as string) ?? `Test failed (${res.status})` })
+ }
+ }
+
+ if (error && !view) {
+ return (
+ <Card title="AI configuration">
+ <p className="text-sm text-destructive">{error}</p>
+ </Card>
+ )
+ }
+ if (!view) {
+ return <div className="h-40 animate-pulse rounded-xl bg-muted" />
+ }
+
+ const providerSectionReady = Boolean(baseUrl.trim()) === Boolean(apiKey.trim()) || (!baseUrl && !apiKey)
+
+ return (
+ <>
+ {error && <div className="rounded-xl border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{error}</div>}
+ {notice && <div className="rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-700">{notice}</div>}
+
+ <Card
+ title="AI provider"
+ right={
+ view.provider.configured ? (
+ <Chip tone="good">configured · {SOURCE_LABEL[view.provider.source ?? ''] ?? view.provider.source}</Chip>
+ ) : (
+ <Chip tone="bad">not configured</Chip>
+ )
+ }
+ >
+ <p className="mb-4 text-sm text-muted-foreground">
+ Canvix runs its AI features through one provider. An override set here wins over the{' '}
+ <code className="rounded bg-muted px-1">ZAI_BASE_URL</code> /{' '}
+ <code className="rounded bg-muted px-1">ZAI_API_KEY</code> environment variables; clear it to fall back. The key
+ is write-only — it is stored, never displayed again.
+ </p>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <label className="text-sm">
+ <span className="mb-1 block font-medium">Base URL</span>
+ <input
+ value={baseUrl}
+ onChange={(e) => setBaseUrl(e.target.value)}
+ placeholder="https://api.example.com/v1"
+ className="h-9 w-full rounded-lg border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring"
+ />
+ </label>
+ <label className="text-sm">
+ <span className="mb-1 block font-medium">API key</span>
+ <input
+ type="password"
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ placeholder={view.provider.stored ? `stored: ${view.provider.stored.keyMasked}` : 'provider API key'}
+ autoComplete="off"
+ className="h-9 w-full rounded-lg border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-ring"
+ />
+ </label>
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <span>
+ env: {view.provider.env.urlSet ? 'base URL set' : 'no base URL'} · {view.provider.env.keySet ? 'key set' : 'no key'}
+ </span>
+ {view.provider.activeBaseUrl && <span className="break-all">active: {view.provider.activeBaseUrl}</span>}
+ </div>
+ <div className="mt-4 flex flex-wrap gap-2">
+ <button
+ onClick={() =>
+ baseUrl.trim() && apiKey.trim()
+ ? void put({ provider: { baseUrl, apiKey } }, 'Provider override saved.')
+ : void put({ provider: null }, 'Provider override cleared — env/file fallback restored.')
+ }
+ disabled={busy || !providerSectionReady}
+ className="rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"
+ >
+ {baseUrl.trim() && apiKey.trim() ? 'Save override' : 'Clear override'}
+ </button>
+ <button
+ onClick={() => void testProvider()}
+ disabled={busy || !view.provider.configured}
+ className="inline-flex items-center gap-1.5 rounded-lg border px-3.5 py-1.5 text-sm font-medium transition-colors hover:bg-muted disabled:opacity-50"
+ >
+ <Zap size={14} /> Test connection
+ </button>
+ </div>
+ {test && (
+ <p className={`mt-3 text-sm ${test.ok ? 'text-emerald-600' : 'text-destructive'}`}>{test.message}</p>
+ )}
+ </Card>
+
+ <Card title="Models">
+ <p className="mb-4 text-sm text-muted-foreground">
+ Which model ids the AI features request. Leave a field empty to use the SDK default — exactly the pre-console
+ behaviour.
+ </p>
+ <div className="grid gap-3 sm:grid-cols-3">
+ {(['text', 'vision', 'image'] as const).map((key) => (
+ <label key={key} className="text-sm">
+ <span className="mb-1 block font-medium capitalize">
+ {key} {key === 'text' && <span className="text-muted-foreground">(write · translate · assistant)</span>}
+ {key === 'vision' && <span className="text-muted-foreground">(Magic Layers)</span>}
+ </span>
+ <input
+ value={models[key]}
+ onChange={(e) => setModels((m) => ({ ...m, [key]: e.target.value }))}
+ placeholder={key === 'vision' ? 'glm-4.5v (default)' : 'SDK default'}
+ className="h-9 w-full rounded-lg border bg-background px-3 font-mono text-sm outline-none focus:ring-2 focus:ring-ring"
+ />
+ </label>
+ ))}
+ </div>
+ <button
+ onClick={() => void put({ models }, 'Models saved.')}
+ disabled={busy}
+ className="mt-4 rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"
+ >
+ Save models
+ </button>
+ </Card>
+
+ <Card title="AI features">
+ <p className="mb-4 text-sm text-muted-foreground">
+ Kill switches per feature. A switched-off feature reports as unavailable everywhere (panels grey out, the
+ capabilities endpoint says no) and its API route refuses work — even with a provider configured.
+ </p>
+ <ul className="divide-y">
+ {FEATURE_INFO.map((f) => (
+ <li key={f.key} className="flex items-center justify-between gap-4 py-3">
+ <div>
+ <p className="text-sm font-medium">{f.label}</p>
+ <p className="text-xs text-muted-foreground">{f.hint}</p>
+ </div>
+ <Toggle
+ label={f.label}
+ checked={features[f.key] ?? true}
+ onChange={(next) => setFeatures((s) => ({ ...s, [f.key]: next }))}
+ />
+ </li>
+ ))}
+ </ul>
+ <button
+ onClick={() => void put({ features }, 'Feature switches saved.')}
+ disabled={busy}
+ className="mt-4 rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"
+ >
+ Save features
+ </button>
+ </Card>
+ </>
+ )
+}
diff --git a/src/components/admin/bits.tsx b/src/components/admin/bits.tsx
new file mode 100644
index 0000000..5674c97
--- /dev/null
+++ b/src/components/admin/bits.tsx
@@ -0,0 +1,110 @@
+import type { ReactNode } from 'react'
+import { cn } from '@/lib/utils'
+
+/** One big number on the overview grid. */
+export function StatCard({
+ label,
+ value,
+ sub,
+ className,
+}: {
+ label: string
+ value: ReactNode
+ sub?: ReactNode
+ className?: string
+}) {
+ return (
+ <div className={cn('rounded-xl border bg-card p-4', className)}>
+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">{label}</p>
+ <p className="mt-1 text-2xl font-semibold tabular-nums text-card-foreground">{value}</p>
+ {sub !== undefined && <p className="mt-0.5 text-xs text-muted-foreground">{sub}</p>}
+ </div>
+ )
+}
+
+/** The console's section card. */
+export function Card({
+ title,
+ right,
+ children,
+ className,
+}: {
+ title?: ReactNode
+ right?: ReactNode
+ children: ReactNode
+ className?: string
+}) {
+ return (
+ <section className={cn('rounded-xl border bg-card p-5', className)}>
+ {(title || right) && (
+ <header className="mb-4 flex items-center justify-between gap-3">
+ <h2 className="text-sm font-semibold text-card-foreground">{title}</h2>
+ {right}
+ </header>
+ )}
+ {children}
+ </section>
+ )
+}
+
+/** Accessible switch, zero new dependencies. */
+export function Toggle({
+ checked,
+ onChange,
+ label,
+ disabled,
+}: {
+ checked: boolean
+ onChange: (next: boolean) => void
+ label: string
+ disabled?: boolean
+}) {
+ return (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={checked}
+ aria-label={label}
+ disabled={disabled}
+ onClick={() => onChange(!checked)}
+ className={cn(
+ 'relative h-6 w-11 shrink-0 rounded-full transition-colors',
+ checked ? 'bg-[var(--cv-teal)]' : 'bg-muted-foreground/30',
+ disabled && 'cursor-not-allowed opacity-50'
+ )}
+ >
+ <span
+ className={cn(
+ 'absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-all',
+ checked ? 'left-[22px]' : 'left-0.5'
+ )}
+ />
+ </button>
+ )
+}
+
+/** Where admin rights come from — shown next to usernames. */
+export function RoleBadge({ admin, source }: { admin: boolean; source: string | null }) {
+ if (!admin) return <span className="text-xs text-muted-foreground">user</span>
+ return (
+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--cv-teal)]/15 px-2 py-0.5 text-xs font-medium text-[var(--cv-teal)]">
+ admin{source === 'env' ? ' · env' : source === 'both' ? ' · env+db' : ''}
+ </span>
+ )
+}
+
+/** Small pill for provider status etc. */
+export function Chip({ children, tone = 'neutral' }: { children: ReactNode; tone?: 'neutral' | 'good' | 'bad' }) {
+ return (
+ <span
+ className={cn(
+ 'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',
+ tone === 'good' && 'bg-emerald-500/15 text-emerald-600',
+ tone === 'bad' && 'bg-destructive/10 text-destructive',
+ tone === 'neutral' && 'bg-muted text-muted-foreground'
+ )}
+ >
+ {children}
+ </span>
+ )
+}
diff --git a/src/components/admin/charts.tsx b/src/components/admin/charts.tsx
new file mode 100644
index 0000000..2197950
--- /dev/null
+++ b/src/components/admin/charts.tsx
@@ -0,0 +1,186 @@
+// Zero-dependency chart primitives for the admin console (v0.16 A1).
+// Hand-rolled SVG — the same "no new dependency" discipline the GIF
+// muxer and WebM writer follow. Accessible: every bar/point carries a
+// <title> tooltip; axes are decorative text, values live in the DOM
+// tables next to the charts.
+
+import { cn } from '@/lib/utils'
+
+export interface Bar {
+ label: string
+ value: number
+ /** stacked secondary segment (e.g. failed AI calls) */
+ alt?: number
+}
+
+/** 1.2k / 3.4M compact formatting for stat cards and axes. */
+export function fmt(n: number): string {
+ if (!Number.isFinite(n)) return '—'
+ if (Math.abs(n) >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
+ if (Math.abs(n) >= 1_000) return `${(n / 1_000).toFixed(1)}k`
+ return String(Math.round(n))
+}
+
+export function fmtBytes(n: number): string {
+ if (!Number.isFinite(n) || n <= 0) return '0 B'
+ if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`
+ if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`
+ if (n >= 1024) return `${(n / 1024).toFixed(1)} kB`
+ return `${Math.round(n)} B`
+}
+
+/** Vertical bars, optional stacked second color, ~4 x labels. */
+export function BarChart({
+ bars,
+ height = 150,
+ color = 'var(--cv-teal)',
+ altColor = 'var(--destructive)',
+ className,
+}: {
+ bars: Bar[]
+ height?: number
+ color?: string
+ altColor?: string
+ className?: string
+}) {
+ const W = Math.max(bars.length * 26, 120)
+ const H = height
+ const padBottom = 18
+ const max = Math.max(1, ...bars.map((b) => b.value + (b.alt ?? 0)))
+ const slot = W / Math.max(bars.length, 1)
+ const barW = Math.min(16, slot * 0.6)
+ const labelIdx = new Set(
+ bars.length <= 5
+ ? bars.map((_, i) => i)
+ : [0, Math.floor((bars.length - 1) / 3), Math.floor(((bars.length - 1) * 2) / 3), bars.length - 1]
+ )
+ return (
+ <svg
+ viewBox={`0 0 ${W} ${H}`}
+ preserveAspectRatio="none"
+ className={cn('w-full', className)}
+ style={{ height }}
+ role="img"
+ aria-label={`bar chart, ${bars.length} days`}
+ >
+ {bars.map((b, i) => {
+ const total = b.value + (b.alt ?? 0)
+ const h = (total / max) * (H - padBottom)
+ const x = i * slot + (slot - barW) / 2
+ const altH = b.alt ? (b.alt / max) * (H - padBottom) : 0
+ const mainH = h - altH
+ return (
+ <g key={b.label}>
+ <title>{`${b.label}: ${b.value}${b.alt ? ` (+${b.alt} failed)` : ''}`}</title>
+ <rect x={x} y={H - padBottom - mainH} width={barW} height={Math.max(mainH, 0)} rx={2} fill={color} opacity={0.9} />
+ {altH > 0.5 && (
+ <rect x={x} y={H - padBottom - h} width={barW} height={altH} rx={2} fill={altColor} opacity={0.55} />
+ )}
+ {labelIdx.has(i) && (
+ <text x={i * slot + slot / 2} y={H - 5} textAnchor="middle" fontSize="9" fill="currentColor" opacity="0.55">
+ {b.label.slice(5)}
+ </text>
+ )}
+ </g>
+ )
+ })}
+ {bars.every((b) => b.value === 0 && !b.alt) && (
+ <text x={W / 2} y={H / 2} textAnchor="middle" fontSize="11" fill="currentColor" opacity="0.4">
+ no data yet
+ </text>
+ )}
+ </svg>
+ )
+}
+
+/** Smooth-ish line + soft area fill. */
+export function LineChart({
+ points,
+ height = 150,
+ color = 'var(--cv-violet)',
+ className,
+}: {
+ points: { label: string; value: number }[]
+ height?: number
+ color?: string
+ className?: string
+}) {
+ const W = Math.max(points.length * 26, 120)
+ const H = height
+ const padBottom = 18
+ const max = Math.max(1, ...points.map((p) => p.value))
+ const step = W / Math.max(points.length - 1, 1)
+ const xy = points.map((p, i) => [i * step, H - padBottom - (p.value / max) * (H - padBottom - 6)] as const)
+ const line = xy.map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ')
+ const area = `${line} L${W},${H - padBottom} L0,${H - padBottom} Z`
+ const labelIdx = new Set(
+ points.length <= 5
+ ? points.map((_, i) => i)
+ : [0, Math.floor((points.length - 1) / 2), points.length - 1]
+ )
+ return (
+ <svg
+ viewBox={`0 0 ${W} ${H}`}
+ preserveAspectRatio="none"
+ className={cn('w-full', className)}
+ style={{ height }}
+ role="img"
+ aria-label={`line chart, ${points.length} days`}
+ >
+ <defs>
+ <linearGradient id="cv-admin-line-fill" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor={color} stopOpacity="0.25" />
+ <stop offset="100%" stopColor={color} stopOpacity="0.02" />
+ </linearGradient>
+ </defs>
+ <path d={area} fill="url(#cv-admin-line-fill)" />
+ <path d={line} fill="none" stroke={color} strokeWidth="2" vectorEffect="non-scaling-stroke" />
+ {points.map((p, i) => (
+ <g key={p.label}>
+ <title>{`${p.label}: ${p.value}`}</title>
+ <rect x={i * step - step / 2} y={0} width={Math.max(step, 8)} height={H - padBottom} fill="transparent" />
+ </g>
+ ))}
+ {[...labelIdx].map((i) => (
+ <text key={i} x={i * step} y={H - 5} textAnchor={i === 0 ? 'start' : i === points.length - 1 ? 'end' : 'middle'} fontSize="9" fill="currentColor" opacity="0.55">
+ {points[i].label.slice(5)}
+ </text>
+ ))}
+ {points.every((p) => p.value === 0) && (
+ <text x={W / 2} y={H / 2} textAnchor="middle" fontSize="11" fill="currentColor" opacity="0.4">
+ no data yet
+ </text>
+ )}
+ </svg>
+ )
+}
+
+/** Horizontal labelled bars — plain divs, crisp text, no measuring. */
+export function HBars({
+ rows,
+ color = 'var(--cv-teal)',
+}: {
+ rows: { label: string; value: number; hint?: string }[]
+ color?: string
+}) {
+ const max = Math.max(1, ...rows.map((r) => r.value))
+ return (
+ <div className="space-y-2">
+ {rows.length === 0 && <p className="text-sm text-muted-foreground">no data yet</p>}
+ {rows.map((r) => (
+ <div key={r.label} className="flex items-center gap-3" title={r.hint}>
+ <span className="w-28 shrink-0 truncate text-xs text-muted-foreground" title={r.label}>
+ {r.label}
+ </span>
+ <span className="h-2.5 flex-1 overflow-hidden rounded-full bg-muted">
+ <span
+ className="block h-full rounded-full"
+ style={{ width: `${Math.max((r.value / max) * 100, r.value > 0 ? 2 : 0)}%`, background: color }}
+ />
+ </span>
+ <span className="w-12 shrink-0 text-right text-xs tabular-nums text-foreground">{fmt(r.value)}</span>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/src/components/admin/fetch.ts b/src/components/admin/fetch.ts
new file mode 100644
index 0000000..8b507b8
--- /dev/null
+++ b/src/components/admin/fetch.ts
@@ -0,0 +1,40 @@
+// Admin console shared fetch helpers (v0.16 A1). Tiny on purpose —
+// the console has four pages, not a framework.
+
+export interface ApiResult<T> {
+ ok: boolean
+ status: number
+ data: T & { error?: string }
+}
+
+async function parse<T>(res: Response): Promise<ApiResult<T>> {
+ let data: T & { error?: string }
+ try {
+ data = (await res.json()) as T & { error?: string }
+ } catch {
+ data = {} as T & { error?: string }
+ }
+ return { ok: res.ok, status: res.status, data }
+}
+
+export async function getJson<T>(url: string): Promise<ApiResult<T>> {
+ try {
+ return parse<T>(await fetch(url, { cache: 'no-store' }))
+ } catch {
+ return { ok: false, status: 0, data: {} as T & { error?: string } }
+ }
+}
+
+export async function sendJson<T>(url: string, method: 'POST' | 'PUT', body: unknown): Promise<ApiResult<T>> {
+ try {
+ return parse<T>(
+ await fetch(url, {
+ method,
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ )
+ } catch {
+ return { ok: false, status: 0, data: {} as T & { error?: string } }
+ }
+}
diff --git a/src/components/admin/overview.tsx b/src/components/admin/overview.tsx
new file mode 100644
index 0000000..894f547
--- /dev/null
+++ b/src/components/admin/overview.tsx
@@ -0,0 +1,181 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+import { getJson } from './fetch'
+import { StatCard, Card, Chip } from './bits'
+import { BarChart, LineChart, HBars, fmt, fmtBytes } from './charts'
+
+interface DayPoint {
+ day: string
+ value: number
+}
+interface AiDayPoint extends DayPoint {
+ ok: number
+}
+interface Overview {
+ version: string
+ dbLatencyMs: number
+ totals: {
+ users: number
+ designs: number
+ templates: number
+ mediaCount: number
+ mediaBytes: number
+ comments: number
+ aiCalls: number
+ activeSessions: number
+ }
+ windows: { requests24h: number; requests7d: number; ai7d: number; dauToday: number }
+ series: { traffic: DayPoint[]; dau: DayPoint[]; signups: DayPoint[]; aiCalls: AiDayPoint[] }
+ topRoutes: { route: string; method: string; hits: number }[]
+ aiByFeature: { feature: string; calls: number; ok: number }[]
+ recentUsers: { id: string; username: string; role: string; createdAt: string; admin: boolean }[]
+ provider: { configured: boolean; source: string | null }
+}
+
+const SOURCE_LABEL: Record<string, string> = {
+ db: 'console',
+ env: 'environment',
+ file: 'config file',
+}
+
+export function AdminOverview() {
+ const [data, setData] = useState<Overview | null>(null)
+ const [error, setError] = useState<string | null>(null)
+
+ useEffect(() => {
+ let alive = true
+ getJson<Overview>('/api/admin/overview').then((res) => {
+ if (!alive) return
+ if (res.ok) setData(res.data)
+ else setError(res.data?.error ?? `Request failed (${res.status})`)
+ })
+ return () => {
+ alive = false
+ }
+ }, [])
+
+ if (error) {
+ return (
+ <Card title="Overview">
+ <p className="text-sm text-destructive">{error}</p>
+ </Card>
+ )
+ }
+ if (!data) {
+ return (
+ <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
+ {Array.from({ length: 8 }).map((_, i) => (
+ <div key={i} className="h-24 animate-pulse rounded-xl bg-muted" />
+ ))}
+ </div>
+ )
+ }
+
+ const aiFail7d = Math.max(
+ 0,
+ data.series.aiCalls.slice(-7).reduce((a, p) => a + Math.max(0, p.value - p.ok), 0)
+ )
+
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
+ <StatCard label="Users" value={fmt(data.totals.users)} sub={`${data.windows.dauToday} active today`} />
+ <StatCard label="Designs" value={fmt(data.totals.designs)} sub={`${fmt(data.totals.templates)} templates`} />
+ <StatCard label="API requests" value={fmt(data.windows.requests24h)} sub={`${fmt(data.windows.requests7d)} in 7 days`} />
+ <StatCard
+ label="AI calls"
+ value={fmt(data.windows.ai7d)}
+ sub={`7d · ${aiFail7d > 0 ? `${fmt(aiFail7d)} failed` : 'no failures'}`}
+ />
+ <StatCard label="Active sessions" value={fmt(data.totals.activeSessions)} sub="unexpired" />
+ <StatCard label="Media stored" value={fmtBytes(data.totals.mediaBytes)} sub={`${fmt(data.totals.mediaCount)} files`} />
+ <StatCard label="Comments" value={fmt(data.totals.comments)} sub="all designs" />
+ <StatCard
+ label="AI provider"
+ value={data.provider.configured ? 'configured' : 'none'}
+ sub={data.provider.configured ? `via ${SOURCE_LABEL[data.provider.source ?? ''] ?? data.provider.source}` : 'local features only'}
+ />
+ </div>
+
+ <div className="grid gap-5 lg:grid-cols-2">
+ <Card
+ title="API traffic — last 14 days"
+ right={<Chip>{fmt(data.series.traffic.reduce((a, p) => a + p.value, 0))} total</Chip>}
+ >
+ <BarChart bars={data.series.traffic.map((p) => ({ label: p.day, value: p.value }))} />
+ </Card>
+ <Card title="Daily active users — last 14 days" right={<Chip tone={data.windows.dauToday > 0 ? 'good' : 'neutral'}>{data.windows.dauToday} today</Chip>}>
+ <LineChart points={data.series.dau.map((p) => ({ label: p.day, value: p.value }))} />
+ </Card>
+ <Card title="New sign-ups — last 14 days">
+ <BarChart bars={data.series.signups.map((p) => ({ label: p.day, value: p.value }))} color="var(--cv-violet)" />
+ </Card>
+ <Card title="AI calls — last 14 days" right={<Chip tone={aiFail7d > 0 ? 'bad' : 'good'}>teal = ok · red = failed</Chip>}>
+ <BarChart
+ bars={data.series.aiCalls.map((p) => ({
+ label: p.day,
+ value: Math.max(0, p.value - Math.max(0, p.value - p.ok)),
+ alt: Math.max(0, p.value - p.ok),
+ }))}
+ />
+ </Card>
+ </div>
+
+ <div className="grid gap-5 lg:grid-cols-2">
+ <Card title="Top routes — last 7 days">
+ <HBars
+ rows={data.topRoutes.map((r) => ({
+ label: `${r.method} ${r.route.replace('/api/', '')}`,
+ value: r.hits,
+ hint: `${r.method} ${r.route}`,
+ }))}
+ />
+ </Card>
+ <Card title="AI usage by feature — last 7 days">
+ <HBars
+ rows={data.aiByFeature.map((f) => ({
+ label: f.feature,
+ value: f.calls,
+ hint: `${f.calls} calls · ${f.ok} succeeded`,
+ }))}
+ color="var(--cv-violet)"
+ />
+ </Card>
+ </div>
+
+ <div className="grid gap-5 lg:grid-cols-2">
+ <Card title="Newest accounts">
+ <ul className="divide-y">
+ {data.recentUsers.length === 0 && <li className="py-2 text-sm text-muted-foreground">no accounts yet</li>}
+ {data.recentUsers.map((u) => (
+ <li key={u.id} className="flex items-center justify-between py-2 text-sm">
+ <span className="font-medium">{u.username}</span>
+ <span className="flex items-center gap-2 text-xs text-muted-foreground">
+ {u.admin && <Chip tone="good">admin</Chip>}
+ {new Date(u.createdAt).toLocaleDateString()}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </Card>
+ <Card title="Instance">
+ <dl className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
+ <dt className="text-muted-foreground">Canvix version</dt>
+ <dd className="text-right font-medium tabular-nums">{data.version}</dd>
+ <dt className="text-muted-foreground">Database latency</dt>
+ <dd className="text-right font-medium tabular-nums">{data.dbLatencyMs} ms</dd>
+ <dt className="text-muted-foreground">AI provider</dt>
+ <dd className="text-right font-medium">
+ {data.provider.configured ? `configured · ${SOURCE_LABEL[data.provider.source ?? ''] ?? data.provider.source}` : 'not configured'}
+ </dd>
+ </dl>
+ <p className="mt-4 text-xs text-muted-foreground">
+ Traffic counters are aggregate counts only — no ids, no IPs, no query strings. 90-day retention. Disable with{' '}
+ <code className="rounded bg-muted px-1">CANVIX_TRAFFIC=0</code>.
+ </p>
+ </Card>
+ </div>
+ </>
+ )
+}
diff --git a/src/components/admin/settings.tsx b/src/components/admin/settings.tsx
new file mode 100644
index 0000000..fee2c24
--- /dev/null
+++ b/src/components/admin/settings.tsx
@@ -0,0 +1,131 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+import { getJson, sendJson } from './fetch'
+import { Card, Toggle, Chip } from './bits'
+import { fmt, fmtBytes } from './charts'
+
+interface ConfigView {
+ provider: { configured: boolean; source: string | null }
+ settings: { signupsOpen: boolean; anonymousEditing: boolean }
+}
+interface OverviewLite {
+ version: string
+ dbLatencyMs: number
+ totals: { mediaCount: number; mediaBytes: number; designs: number; comments: number }
+}
+
+export function AdminSettings() {
+ const [view, setView] = useState<ConfigView | null>(null)
+ const [instance, setInstance] = useState<OverviewLite | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [notice, setNotice] = useState<string | null>(null)
+ const [busy, setBusy] = useState(false)
+
+ useEffect(() => {
+ void (async () => {
+ const [cfg, ov] = await Promise.all([
+ getJson<ConfigView>('/api/admin/config'),
+ getJson<OverviewLite>('/api/admin/overview'),
+ ])
+ if (cfg.ok) setView(cfg.data)
+ else setError(cfg.data?.error ?? `Request failed (${cfg.status})`)
+ if (ov.ok) setInstance(ov.data)
+ })()
+ }, [])
+
+ async function save(next: { signupsOpen: boolean; anonymousEditing: boolean }) {
+ setBusy(true)
+ const res = await sendJson<ConfigView & { error?: string }>('/api/admin/config', 'PUT', { settings: next })
+ setBusy(false)
+ if (!res.ok) {
+ setNotice(null)
+ setError(res.data?.error ?? `Could not save (${res.status}).`)
+ return
+ }
+ setError(null)
+ setView(res.data)
+ setNotice('Settings saved.')
+ setTimeout(() => setNotice(null), 4000)
+ }
+
+ if (!view) {
+ return <div className="h-40 animate-pulse rounded-xl bg-muted" />
+ }
+
+ return (
+ <>
+ {error && <div className="rounded-xl border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{error}</div>}
+ {notice && <div className="rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-700">{notice}</div>}
+
+ <Card title="Access">
+ <ul className="divide-y">
+ <li className="flex items-center justify-between gap-4 py-4">
+ <div className="max-w-lg">
+ <p className="text-sm font-medium">Allow new sign-ups</p>
+ <p className="text-xs text-muted-foreground">
+ When off, <code className="rounded bg-muted px-1">POST /api/auth/register</code> answers 503 with a
+ friendly message — before the rate limiter, so a closed instance burns none of a visitor&apos;s attempt
+ budget. Existing accounts sign in as usual.
+ </p>
+ </div>
+ <Toggle
+ label="Allow new sign-ups"
+ checked={view.settings.signupsOpen}
+ disabled={busy}
+ onChange={(next) => void save({ ...view.settings, signupsOpen: next })}
+ />
+ </li>
+ <li className="flex items-center justify-between gap-4 py-4">
+ <div className="max-w-lg">
+ <p className="text-sm font-medium">Anonymous editing</p>
+ <p className="text-xs text-muted-foreground">
+ When off, only signed-in accounts can create or save designs. Reading, sharing and exporting existing
+ designs (including the anonymous commons) keeps working — this gates writes, not reads.
+ </p>
+ </div>
+ <Toggle
+ label="Anonymous editing"
+ checked={view.settings.anonymousEditing}
+ disabled={busy}
+ onChange={(next) => void save({ ...view.settings, anonymousEditing: next })}
+ />
+ </li>
+ </ul>
+ </Card>
+
+ <Card title="Instance">
+ <dl className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
+ <dt className="text-muted-foreground">Canvix version</dt>
+ <dd className="text-right font-medium tabular-nums">{instance?.version ?? '—'}</dd>
+ <dt className="text-muted-foreground">Database latency</dt>
+ <dd className="text-right font-medium tabular-nums">{instance ? `${instance.dbLatencyMs} ms` : '—'}</dd>
+ <dt className="text-muted-foreground">Designs</dt>
+ <dd className="text-right font-medium tabular-nums">{instance ? fmt(instance.totals.designs) : '—'}</dd>
+ <dt className="text-muted-foreground">Media</dt>
+ <dd className="text-right font-medium tabular-nums">
+ {instance ? `${fmt(instance.totals.mediaCount)} files · ${fmtBytes(instance.totals.mediaBytes)}` : '—'}
+ </dd>
+ <dt className="text-muted-foreground">AI provider</dt>
+ <dd className="text-right">
+ {view.provider.configured ? <Chip tone="good">{view.provider.source}</Chip> : <Chip tone="bad">none</Chip>}
+ </dd>
+ </dl>
+ <p className="mt-4 text-xs text-muted-foreground">
+ First administrator: set{' '}
+ <code className="rounded bg-muted px-1">CANVIX_ADMIN_USERS=&quot;your-username&quot;</code> and sign in — the
+ Admin link appears on the dashboard. Everything else is operable from these pages.
+ </p>
+ </Card>
+
+ <Card title="Privacy posture">
+ <ul className="list-disc space-y-1.5 pl-4 text-xs text-muted-foreground">
+ <li>Traffic counters are per-day aggregates: route, method, status, count. No ids, no IPs, no query strings.</li>
+ <li>Daily-active records store a userId or the hashed anonymous cookie key — first-party, admin-visible only.</li>
+ <li>Counters can be switched off entirely with <code className="rounded bg-muted px-1">CANVIX_TRAFFIC=0</code>; rows older than 90 days are swept automatically.</li>
+ <li>Provider API keys are write-only: stored once, echoed back only as a mask.</li>
+ </ul>
+ </Card>
+ </>
+ )
+}
diff --git a/src/components/admin/users.tsx b/src/components/admin/users.tsx
new file mode 100644
index 0000000..1a33401
--- /dev/null
+++ b/src/components/admin/users.tsx
@@ -0,0 +1,248 @@
+'use client'
+
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { Search, ChevronLeft, ChevronRight, ShieldCheck, ShieldOff, LogOut } from 'lucide-react'
+import { getJson, sendJson } from './fetch'
+import { Card, RoleBadge } from './bits'
+import { fmt } from './charts'
+
+interface AdminUserRow {
+ id: string
+ username: string
+ role: string
+ createdAt: string
+ admin: boolean
+ adminSource: string | null
+ designs: number
+ activeSessions: number
+ lastActiveAt: string | null
+}
+interface UsersPage {
+ total: number
+ page: number
+ pageSize: number
+ users: AdminUserRow[]
+}
+
+/** Two-step inline confirm — no native dialogs, works headless in e2e. */
+type Action = { kind: 'role'; row: AdminUserRow; next: 'admin' | 'user' } | { kind: 'sessions'; row: AdminUserRow } | null
+
+export function AdminUsers() {
+ const [data, setData] = useState<UsersPage | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [q, setQ] = useState('')
+ const [page, setPage] = useState(0)
+ const [pending, setPending] = useState<Action>(null)
+ const [busy, setBusy] = useState(false)
+ const debounce = useRef<ReturnType<typeof setTimeout> | null>(null)
+
+ const load = useCallback(async (query: string, pageNo: number) => {
+ const res = await getJson<UsersPage>(`/api/admin/users?q=${encodeURIComponent(query)}&page=${pageNo}`)
+ if (res.ok) {
+ setData(res.data)
+ setError(null)
+ } else {
+ setError(res.data?.error ?? `Request failed (${res.status})`)
+ }
+ }, [])
+
+ useEffect(() => {
+ if (debounce.current) clearTimeout(debounce.current)
+ debounce.current = setTimeout(() => void load(q, page), q ? 300 : 0)
+ return () => {
+ if (debounce.current) clearTimeout(debounce.current)
+ }
+ }, [q, page, load])
+
+ async function runRole(row: AdminUserRow, next: 'admin' | 'user') {
+ setBusy(true)
+ const res = await sendJson<{ error?: string }>(`/api/admin/users/${row.id}/role`, 'POST', { role: next })
+ setBusy(false)
+ setPending(null)
+ if (!res.ok) {
+ setError(res.data?.error ?? `Could not update the role (${res.status}).`)
+ return
+ }
+ setError(null)
+ void load(q, page)
+ }
+
+ async function runSessions(row: AdminUserRow) {
+ setBusy(true)
+ const res = await sendJson<{ revoked?: number; error?: string }>(`/api/admin/users/${row.id}/sessions`, 'POST', {})
+ setBusy(false)
+ setPending(null)
+ if (!res.ok) {
+ setError(res.data?.error ?? `Could not revoke sessions (${res.status}).`)
+ return
+ }
+ setError(null)
+ void load(q, page)
+ }
+
+ const pages = data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1
+
+ return (
+ <>
+ {error && (
+ <div className="rounded-xl border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">{error}</div>
+ )}
+ <Card
+ title={data ? `${fmt(data.total)} account${data.total === 1 ? '' : 's'}` : 'Accounts'}
+ right={
+ <div className="relative">
+ <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground" />
+ <input
+ value={q}
+ onChange={(e) => {
+ setQ(e.target.value)
+ setPage(0)
+ }}
+ placeholder="Search username…"
+ aria-label="Search users by username"
+ className="h-8 w-44 rounded-lg border bg-background pl-8 pr-2 text-sm outline-none focus:ring-2 focus:ring-ring sm:w-56"
+ />
+ </div>
+ }
+ >
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b text-left text-[11px] uppercase tracking-wide text-muted-foreground">
+ <th className="py-2 pr-3 font-medium">Username</th>
+ <th className="py-2 pr-3 font-medium">Role</th>
+ <th className="py-2 pr-3 text-right font-medium">Designs</th>
+ <th className="py-2 pr-3 text-right font-medium">Sessions</th>
+ <th className="py-2 pr-3 font-medium">Last active</th>
+ <th className="py-2 pr-3 font-medium">Joined</th>
+ <th className="py-2 text-right font-medium">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {!data && (
+ <tr>
+ <td colSpan={7} className="py-8 text-center text-muted-foreground">
+ loading…
+ </td>
+ </tr>
+ )}
+ {data?.users.length === 0 && (
+ <tr>
+ <td colSpan={7} className="py-8 text-center text-muted-foreground">
+ no accounts match “{q}”
+ </td>
+ </tr>
+ )}
+ {data?.users.map((row) => {
+ const isPending =
+ pending && ((pending.kind === 'role' && pending.row.id === row.id) || (pending.kind === 'sessions' && pending.row.id === row.id))
+ return (
+ <tr key={row.id} className="border-b last:border-0">
+ <td className="py-2.5 pr-3 font-medium">{row.username}</td>
+ <td className="py-2.5 pr-3">
+ <RoleBadge admin={row.admin} source={row.adminSource} />
+ </td>
+ <td className="py-2.5 pr-3 text-right tabular-nums">{fmt(row.designs)}</td>
+ <td className="py-2.5 pr-3 text-right tabular-nums">{row.activeSessions}</td>
+ <td className="py-2.5 pr-3 text-xs text-muted-foreground">
+ {row.lastActiveAt ? new Date(row.lastActiveAt).toLocaleString() : '—'}
+ </td>
+ <td className="py-2.5 pr-3 text-xs text-muted-foreground">{new Date(row.createdAt).toLocaleDateString()}</td>
+ <td className="py-2.5 text-right">
+ <div className="flex justify-end gap-1.5">
+ {isPending && pending?.kind === 'role' ? (
+ <>
+ <button
+ onClick={() => void runRole(row, pending.next)}
+ disabled={busy}
+ className="rounded-lg bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground disabled:opacity-50"
+ >
+ confirm
+ </button>
+ <button
+ onClick={() => setPending(null)}
+ disabled={busy}
+ className="rounded-lg border px-2.5 py-1 text-xs font-medium disabled:opacity-50"
+ >
+ cancel
+ </button>
+ </>
+ ) : (
+ <>
+ <button
+ onClick={() => setPending({ kind: 'role', row, next: row.admin ? 'user' : 'admin' })}
+ disabled={busy}
+ title={row.admin ? 'Remove admin rights' : 'Grant admin rights'}
+ className="inline-flex items-center gap-1 rounded-lg border px-2.5 py-1 text-xs font-medium transition-colors hover:bg-muted disabled:opacity-50"
+ >
+ {row.admin ? <ShieldOff size={13} /> : <ShieldCheck size={13} />}
+ {row.admin ? 'revoke' : 'make admin'}
+ </button>
+ <button
+ onClick={() => setPending({ kind: 'sessions', row })}
+ disabled={busy}
+ title="Sign this user out everywhere"
+ className="inline-flex items-center gap-1 rounded-lg border px-2.5 py-1 text-xs font-medium transition-colors hover:bg-muted disabled:opacity-50"
+ >
+ <LogOut size={13} /> sign out
+ </button>
+ </>
+ )}
+ {isPending && pending?.kind === 'sessions' && (
+ <>
+ <button
+ onClick={() => void runSessions(row)}
+ disabled={busy}
+ className="rounded-lg bg-destructive px-2.5 py-1 text-xs font-medium text-white disabled:opacity-50"
+ >
+ confirm sign-out
+ </button>
+ <button
+ onClick={() => setPending(null)}
+ disabled={busy}
+ className="rounded-lg border px-2.5 py-1 text-xs font-medium disabled:opacity-50"
+ >
+ cancel
+ </button>
+ </>
+ )}
+ </div>
+ </td>
+ </tr>
+ )
+ })}
+ </tbody>
+ </table>
+ </div>
+ {data && data.total > data.pageSize && (
+ <div className="mt-4 flex items-center justify-between text-sm">
+ <span className="text-muted-foreground">
+ page {data.page + 1} / {pages}
+ </span>
+ <div className="flex gap-2">
+ <button
+ onClick={() => setPage((p) => Math.max(0, p - 1))}
+ disabled={data.page === 0}
+ className="inline-flex items-center gap-1 rounded-lg border px-2.5 py-1 text-xs font-medium disabled:opacity-40"
+ >
+ <ChevronLeft size={13} /> prev
+ </button>
+ <button
+ onClick={() => setPage((p) => Math.min(pages - 1, p + 1))}
+ disabled={data.page >= pages - 1}
+ className="inline-flex items-center gap-1 rounded-lg border px-2.5 py-1 text-xs font-medium disabled:opacity-40"
+ >
+ next <ChevronRight size={13} />
+ </button>
+ </div>
+ </div>
+ )}
+ </Card>
+ <p className="text-xs text-muted-foreground">
+ Admin rights come from the <code className="rounded bg-muted px-1">CANVIX_ADMIN_USERS</code> environment variable
+ (always wins, shown as <span className="font-medium">· env</span>) or from this table. Role changes refuse
+ self-modification — a second administrator or the env variable is the recovery path.
+ </p>
+ </>
+ )
+}
diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsx
index fa45552..7745493 100644
--- a/src/components/dashboard/Dashboard.tsx
+++ b/src/components/dashboard/Dashboard.tsx
@@ -18,6 +18,7 @@ import {
Square,
FileImage,
Github,
+ Shield,
LayoutGrid,
LayoutTemplate,
FolderOpen,
@@ -409,6 +410,16 @@ export function Dashboard() {
</button>
))}
<div className="mt-auto flex flex-col items-center gap-2">
+ {user?.admin && (
+ <a
+ href="/admin"
+ className="w-9 h-9 rounded-full text-white/50 hover:text-white hover:bg-white/10 flex items-center justify-center transition-colors"
+ aria-label="Admin console"
+ title="Admin console"
+ >
+ <Shield size={18} />
+ </a>
+ )}
<a
href="https://github.com/mir-ashiq/canvix"
target="_blank"
diff --git a/src/lib/admin/config.test.ts b/src/lib/admin/config.test.ts
new file mode 100644
index 0000000..471cf65
--- /dev/null
+++ b/src/lib/admin/config.test.ts
@@ -0,0 +1,167 @@
+// Unit tests for the instance config module (v0.16 A1): validators,
+// masking, defaults merge and the cached read path against a mocked db.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const findMany = vi.hoisted(() => vi.fn())
+const upsert = vi.hoisted(() => vi.fn())
+const dbMock = vi.hoisted(() => ({ appConfig: { findMany, upsert } }))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+import {
+ validateProvider,
+ validateModels,
+ validateFeatures,
+ validateSettings,
+ maskApiKey,
+ getFeatures,
+ getSettings,
+ getProviderOverride,
+ getModels,
+ setFeatures,
+ clearProvider,
+ DEFAULT_FEATURES,
+} from './config'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ findMany.mockResolvedValue([])
+ // each test starts from a cold cache
+ return import('./config').then((m) => m.invalidateAdminConfig())
+})
+
+describe('validateProvider (v0.16 A1)', () => {
+ it('accepts a clean http(s) URL + key and normalizes the URL', () => {
+ const out = validateProvider({ baseUrl: 'https://api.example.com/v1/', apiKey: 'sk-123' })
+ expect(out.ok).toBe(true)
+ if (out.ok) expect(out.value.baseUrl).toBe('https://api.example.com/v1/')
+ })
+
+ it('rejects non-http(s) schemes', () => {
+ expect(validateProvider({ baseUrl: 'ftp://x', apiKey: 'k' }).ok).toBe(false)
+ expect(validateProvider({ baseUrl: 'javascript:alert(1)', apiKey: 'k' }).ok).toBe(false)
+ })
+
+ it('rejects credentials embedded in the URL', () => {
+ expect(validateProvider({ baseUrl: 'https://user:[email protected]', apiKey: 'k' }).ok).toBe(false)
+ })
+
+ it('rejects missing pieces and oversize values', () => {
+ expect(validateProvider({ baseUrl: '', apiKey: 'k' }).ok).toBe(false)
+ expect(validateProvider({ baseUrl: 'https://x.io', apiKey: '' }).ok).toBe(false)
+ expect(validateProvider({ baseUrl: 'https://x.io', apiKey: 'k'.repeat(4097) }).ok).toBe(false)
+ expect(validateProvider({ baseUrl: `https://x.io/${'a'.repeat(2100)}`, apiKey: 'k' }).ok).toBe(false)
+ expect(validateProvider(null).ok).toBe(false)
+ })
+})
+
+describe('validateModels (v0.16 A1)', () => {
+ it('keeps well-formed ids and drops empty/cleared ones', () => {
+ expect(validateModels({ text: 'glm-4.6', vision: '', image: undefined })).toEqual({
+ ok: true,
+ value: { text: 'glm-4.6' },
+ })
+ })
+
+ it('rejects garbage model ids and unknown junk only warns by ignoring', () => {
+ expect(validateModels({ text: 'bad model!' }).ok).toBe(false)
+ expect(validateModels({ text: '../etc/passwd' }).ok).toBe(false)
+ const out = validateModels({ evil: 'x', text: 'glm-4.6' })
+ expect(out.ok).toBe(true)
+ if (out.ok) expect(out.value).toEqual({ text: 'glm-4.6' })
+ expect(validateModels('nope').ok).toBe(false)
+ })
+})
+
+describe('validateFeatures (v0.16 A1)', () => {
+ it('keeps booleans, ignores unknown keys', () => {
+ const out = validateFeatures({ magicWrite: false, nope: true })
+ expect(out.ok).toBe(true)
+ if (out.ok) expect(out.value).toEqual({ magicWrite: false })
+ })
+
+ it('rejects non-boolean values', () => {
+ expect(validateFeatures({ vision: 'off' }).ok).toBe(false)
+ expect(validateFeatures({ vision: 0 }).ok).toBe(false)
+ })
+})
+
+describe('validateSettings (v0.16 A1)', () => {
+ it('keeps booleans, ignores unknown keys, rejects the rest', () => {
+ expect(validateSettings({ signupsOpen: false })).toEqual({ ok: true, value: { signupsOpen: false } })
+ expect(validateSettings({ anonymousEditing: 'no' }).ok).toBe(false)
+ expect(validateSettings([]).ok).toBe(false)
+ })
+})
+
+describe('maskApiKey (v0.16 A1)', () => {
+ it('never reveals the middle of a key', () => {
+ const masked = maskApiKey('sk-abcdef1234567890wxyz')
+ expect(masked).toBe('sk-a…wxyz')
+ expect(masked).not.toContain('1234567890')
+ })
+
+ it('fully masks short keys', () => {
+ expect(maskApiKey('short')).toBe('••••••••')
+ })
+})
+
+describe('cached reads (v0.16 A1)', () => {
+ it('defaults when the table is empty', async () => {
+ expect(await getFeatures()).toEqual(DEFAULT_FEATURES)
+ expect(await getSettings()).toEqual({ signupsOpen: true, anonymousEditing: true })
+ expect(await getProviderOverride()).toBeNull()
+ expect(await getModels()).toEqual({})
+ })
+
+ it('merges stored partial sections over defaults', async () => {
+ findMany.mockResolvedValue([
+ { key: 'ai.features', value: { magicWrite: false } },
+ { key: 'app.settings', value: { signupsOpen: false } },
+ ])
+ expect((await getFeatures()).magicWrite).toBe(false)
+ expect((await getFeatures()).assistant).toBe(true)
+ expect((await getSettings()).signupsOpen).toBe(false)
+ expect((await getSettings()).anonymousEditing).toBe(true)
+ })
+
+ it('ignores a corrupt provider row (fails back to env behaviour)', async () => {
+ findMany.mockResolvedValue([{ key: 'ai.provider', value: { baseUrl: 'not a url' } }])
+ expect(await getProviderOverride()).toBeNull()
+ })
+
+ it('DB read failure falls back to defaults, never throws', async () => {
+ findMany.mockRejectedValue(new Error('connection refused'))
+ await expect(getFeatures()).resolves.toEqual(DEFAULT_FEATURES)
+ })
+
+ it('one findMany serves repeated reads inside the TTL', async () => {
+ await getFeatures()
+ await getSettings()
+ await getModels()
+ expect(findMany).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('writers (v0.16 A1)', () => {
+ it('setFeatures upserts the merged flags and invalidates the cache', async () => {
+ findMany.mockResolvedValue([{ key: 'ai.features', value: { magicWrite: false } }])
+ await getFeatures() // warm cache with magicWrite:false
+ upsert.mockResolvedValue({})
+ await setFeatures({ ...DEFAULT_FEATURES, magicWrite: false })
+ expect(upsert).toHaveBeenCalledWith(
+ expect.objectContaining({ where: { key: 'ai.features' } })
+ )
+ // cache was dropped → next read hits the db again
+ await getFeatures()
+ expect(findMany).toHaveBeenCalledTimes(2)
+ })
+
+ it('clearProvider writes the empty override', async () => {
+ upsert.mockResolvedValue({})
+ await clearProvider()
+ expect(upsert).toHaveBeenCalledWith(
+ expect.objectContaining({ where: { key: 'ai.provider' }, update: { value: {} } })
+ )
+ })
+})
diff --git a/src/lib/admin/config.ts b/src/lib/admin/config.ts
new file mode 100644
index 0000000..dee4a84
--- /dev/null
+++ b/src/lib/admin/config.ts
@@ -0,0 +1,271 @@
+// ─────────────────────────────────────────────────────────────
+// Instance configuration (v0.16 A1) — the store behind /admin's
+// AI + settings pages.
+//
+// Four small AppConfig rows (key → JSON):
+// ai.provider { baseUrl, apiKey } — console-set provider, wins over env
+// ai.models { text?, vision?, image? } — model ids passed to the SDK
+// ai.features { magicWrite, … } — per-feature kill switches
+// app.settings { signupsOpen, anonymousEditing }
+//
+// Design decisions (documented in docs/ADMIN.md):
+// • Precedence for the provider: DB (console) → env → .z-ai-config
+// file → unconfigured. The console never shows a stored API key
+// back — only a mask (write-only credential, same posture as the
+// env vars it overrides).
+// • Reads are cached in-process for 10 s (config sits on every AI
+// request path; one tiny indexed findMany per 10 s per instance is
+// the whole cost). Writes invalidate immediately — the same server
+// process sees its own change on the next request, other processes
+// within the TTL.
+// • DB read failures fall back to defaults (= pre-A1 env behaviour),
+// because these toggles are additive restrictions and a flapping
+// config read must not brick design autosave. The DB being truly
+// down breaks the app elsewhere anyway.
+//
+// CONTRACT: server-only. Contains credentials in memory.
+// ─────────────────────────────────────────────────────────────
+
+import type { Prisma } from '@/generated/prisma/client'
+
+// ── keys & shapes ─────────────────────────────────────────────
+
+export const CONFIG_KEYS = {
+ provider: 'ai.provider',
+ models: 'ai.models',
+ features: 'ai.features',
+ settings: 'app.settings',
+} as const
+
+export const AI_FEATURES = [
+ 'magicWrite',
+ 'imageGeneration',
+ 'imageEditing',
+ 'vision', // Magic Layers
+ 'translation',
+ 'assistant',
+ 'photoSearch',
+] as const
+export type AiFeature = (typeof AI_FEATURES)[number]
+
+export interface StoredProvider {
+ baseUrl: string
+ apiKey: string
+}
+export interface StoredModels {
+ text?: string
+ vision?: string
+ image?: string
+}
+export type StoredFeatures = Record<AiFeature, boolean>
+export interface StoredSettings {
+ signupsOpen: boolean
+ anonymousEditing: boolean
+}
+
+export const DEFAULT_FEATURES: StoredFeatures = {
+ magicWrite: true,
+ imageGeneration: true,
+ imageEditing: true,
+ vision: true,
+ translation: true,
+ assistant: true,
+ photoSearch: true,
+}
+
+export const DEFAULT_SETTINGS: StoredSettings = {
+ signupsOpen: true,
+ anonymousEditing: true,
+}
+
+const BASEURL_MAX = 2048
+const APIKEY_MAX = 4096
+const MODEL_RE = /^[A-Za-z0-9._:+-]{1,120}$/
+
+// ── validation (pure, unit-tested) ────────────────────────────
+
+export type Check<T> = { ok: true; value: T } | { ok: false; error: string }
+
+/** A usable provider override: an http(s) base URL without credentials + a non-empty key. */
+export function validateProvider(input: unknown): Check<StoredProvider> {
+ if (typeof input !== 'object' || input === null) return { ok: false, error: 'provider must be an object.' }
+ const raw = input as Record<string, unknown>
+ if (typeof raw.baseUrl !== 'string' || !raw.baseUrl.trim()) return { ok: false, error: 'baseUrl is required.' }
+ if (typeof raw.apiKey !== 'string' || !raw.apiKey) return { ok: false, error: 'apiKey is required.' }
+ const baseUrl = raw.baseUrl.trim()
+ if (baseUrl.length > BASEURL_MAX) return { ok: false, error: `baseUrl must be at most ${BASEURL_MAX} characters.` }
+ if (raw.apiKey.length > APIKEY_MAX) return { ok: false, error: `apiKey must be at most ${APIKEY_MAX} characters.` }
+ let parsed: URL
+ try {
+ parsed = new URL(baseUrl)
+ } catch {
+ return { ok: false, error: 'baseUrl must be a valid URL.' }
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ return { ok: false, error: 'baseUrl must use http(s).' }
+ }
+ if (parsed.username || parsed.password) {
+ return { ok: false, error: 'baseUrl must not embed credentials — put the key in the apiKey field.' }
+ }
+ return { ok: true, value: { baseUrl: parsed.toString(), apiKey: raw.apiKey } }
+}
+
+/** Optional model ids; unknown keys are dropped, each value must look like a model id. */
+export function validateModels(input: unknown): Check<Partial<StoredModels>> {
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) return { ok: false, error: 'models must be an object.' }
+ const raw = input as Record<string, unknown>
+ const out: Partial<StoredModels> = {}
+ for (const key of ['text', 'vision', 'image'] as const) {
+ const v = raw[key]
+ if (v === undefined || v === null || v === '') continue // clearing a model = omit it
+ if (typeof v !== 'string' || !MODEL_RE.test(v)) {
+ return { ok: false, error: `models.${key} must be a model id (letters, digits, . _ : + -).` }
+ }
+ out[key] = v
+ }
+ return { ok: true, value: out }
+}
+
+/** Feature flags: booleans only, unknown keys ignored. Returns only the provided subset. */
+export function validateFeatures(input: unknown): Check<Partial<StoredFeatures>> {
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) return { ok: false, error: 'features must be an object.' }
+ const raw = input as Record<string, unknown>
+ const out: Partial<StoredFeatures> = {}
+ for (const key of AI_FEATURES) {
+ const v = raw[key]
+ if (v === undefined) continue
+ if (typeof v !== 'boolean') return { ok: false, error: `features.${key} must be true or false.` }
+ out[key] = v
+ }
+ return { ok: true, value: out }
+}
+
+/** App settings: booleans only, unknown keys ignored. */
+export function validateSettings(input: unknown): Check<Partial<StoredSettings>> {
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) return { ok: false, error: 'settings must be an object.' }
+ const raw = input as Record<string, unknown>
+ const out: Partial<StoredSettings> = {}
+ for (const key of ['signupsOpen', 'anonymousEditing'] as const) {
+ const v = raw[key]
+ if (v === undefined) continue
+ if (typeof v !== 'boolean') return { ok: false, error: `settings.${key} must be true or false.` }
+ out[key] = v
+ }
+ return { ok: true, value: out }
+}
+
+/** Never echo a stored key — `sk-1…wxyz` shape with the length for a sanity check. */
+export function maskApiKey(key: string): string {
+ if (key.length <= 8) return '••••••••'
+ return `${key.slice(0, 4)}…${key.slice(-4)}`
+}
+
+// ── cache + access ────────────────────────────────────────────
+
+interface CacheEntry {
+ rows: Map<string, unknown>
+ at: number
+}
+
+const CACHE_TTL_MS = 10_000
+let cache: CacheEntry | null = null
+
+/** Test hook — drop the in-process cache. */
+export function invalidateAdminConfig(): void {
+ cache = null
+}
+
+async function readRows(): Promise<Map<string, unknown>> {
+ if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache.rows
+ const rows = new Map<string, unknown>()
+ try {
+ const { db } = await import('@/lib/db')
+ const found = await db.appConfig.findMany({
+ where: { key: { in: Object.values(CONFIG_KEYS) } },
+ select: { key: true, value: true },
+ })
+ for (const row of found) rows.set(row.key, row.value)
+ } catch {
+ // fall back to whatever we cached before, else defaults
+ if (cache) return cache.rows
+ }
+ cache = { rows, at: Date.now() }
+ return rows
+}
+
+async function writeRow(key: string, value: Prisma.InputJsonValue): Promise<void> {
+ const { db } = await import('@/lib/db')
+ await db.appConfig.upsert({
+ where: { key },
+ create: { key, value },
+ update: { value },
+ })
+ invalidateAdminConfig()
+}
+
+function asRecord(v: unknown): Record<string, unknown> {
+ return typeof v === 'object' && v !== null ? (v as Record<string, unknown>) : {}
+}
+
+// ── typed readers ─────────────────────────────────────────────
+
+/** Console-set provider, when BOTH parts survive validation. Null = no override. */
+export async function getProviderOverride(): Promise<StoredProvider | null> {
+ const rows = await readRows()
+ const raw = asRecord(rows.get(CONFIG_KEYS.provider))
+ if (!raw.baseUrl && !raw.apiKey) return null
+ const check = validateProvider({ baseUrl: raw.baseUrl, apiKey: raw.apiKey })
+ return check.ok ? check.value : null
+}
+
+/** Model ids (empty strings omitted) — {} = SDK defaults. */
+export async function getModels(): Promise<StoredModels> {
+ const rows = await readRows()
+ const raw = asRecord(rows.get(CONFIG_KEYS.models))
+ const check = validateModels(raw)
+ return check.ok ? check.value : {}
+}
+
+/** All seven flags, defaults for anything unset. */
+export async function getFeatures(): Promise<StoredFeatures> {
+ const rows = await readRows()
+ const raw = asRecord(rows.get(CONFIG_KEYS.features))
+ const check = validateFeatures(raw)
+ return { ...DEFAULT_FEATURES, ...(check.ok ? check.value : {}) }
+}
+
+export async function aiFeatureEnabled(feature: AiFeature): Promise<boolean> {
+ const flags = await getFeatures()
+ return flags[feature]
+}
+
+export async function getSettings(): Promise<StoredSettings> {
+ const rows = await readRows()
+ const raw = asRecord(rows.get(CONFIG_KEYS.settings))
+ const check = validateSettings(raw)
+ return { ...DEFAULT_SETTINGS, ...(check.ok ? check.value : {}) }
+}
+
+// ── typed writers (console PUT) ───────────────────────────────
+
+/** Write the full provider override (both fields required together). */
+export async function setProvider(value: StoredProvider): Promise<void> {
+ await writeRow(CONFIG_KEYS.provider, value as unknown as Prisma.InputJsonValue)
+}
+
+/** Clear the override — provider resolution falls back to env / config file. */
+export async function clearProvider(): Promise<void> {
+ await writeRow(CONFIG_KEYS.provider, {})
+}
+
+export async function setModels(value: StoredModels): Promise<void> {
+ await writeRow(CONFIG_KEYS.models, value as unknown as Prisma.InputJsonValue)
+}
+
+export async function setFeatures(value: StoredFeatures): Promise<void> {
+ await writeRow(CONFIG_KEYS.features, value as unknown as Prisma.InputJsonValue)
+}
+
+export async function setSettings(value: StoredSettings): Promise<void> {
+ await writeRow(CONFIG_KEYS.settings, value as unknown as Prisma.InputJsonValue)
+}
diff --git a/src/lib/admin/guard.test.ts b/src/lib/admin/guard.test.ts
new file mode 100644
index 0000000..0908e83
--- /dev/null
+++ b/src/lib/admin/guard.test.ts
@@ -0,0 +1,66 @@
+// Unit tests for the admin guard (v0.16 A1): env bootstrap parsing,
+// effective-admin resolution and the fail-closed default.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+
+const user = (username: string, role = 'user') => ({ username, role })
+
+beforeEach(() => {
+ vi.unstubAllEnvs()
+})
+
+describe('envAdminUsernames (v0.16 A1)', () => {
+ it('parses a comma list, trimming and lowercasing', async () => {
+ const { envAdminUsernames } = await import('./guard')
+ vi.stubEnv('CANVIX_ADMIN_USERS', ' Alice , BOB, carol_1 ')
+ expect(envAdminUsernames()).toEqual(new Set(['alice', 'bob', 'carol_1']))
+ })
+
+ it('empty / unset → empty set (fail-closed)', async () => {
+ const { envAdminUsernames } = await import('./guard')
+ vi.stubEnv('CANVIX_ADMIN_USERS', '')
+ expect(envAdminUsernames().size).toBe(0)
+ delete process.env.CANVIX_ADMIN_USERS
+ expect(envAdminUsernames().size).toBe(0)
+ })
+
+ it('drops blank segments', async () => {
+ const { envAdminUsernames } = await import('./guard')
+ vi.stubEnv('CANVIX_ADMIN_USERS', 'alice,,bob,')
+ expect(envAdminUsernames()).toEqual(new Set(['alice', 'bob']))
+ })
+})
+
+describe('isAdminUser (v0.16 A1)', () => {
+ it('DB role admin wins', async () => {
+ const { isAdminUser } = await import('./guard')
+ expect(isAdminUser(user('alice', 'admin'))).toBe(true)
+ })
+
+ it('env bootstrap matches by username, case-insensitively', async () => {
+ const { isAdminUser } = await import('./guard')
+ vi.stubEnv('CANVIX_ADMIN_USERS', 'Alice')
+ expect(isAdminUser(user('alice'))).toBe(true)
+ expect(isAdminUser(user('bob'))).toBe(false)
+ })
+
+ it('plain users and missing users are never admin', async () => {
+ const { isAdminUser } = await import('./guard')
+ delete process.env.CANVIX_ADMIN_USERS
+ expect(isAdminUser(user('alice'))).toBe(false)
+ expect(isAdminUser(null)).toBe(false)
+ expect(isAdminUser(undefined)).toBe(false)
+ })
+})
+
+describe('adminSource (v0.16 A1)', () => {
+ it('distinguishes db / env / both / none', async () => {
+ const { adminSource } = await import('./guard')
+ vi.stubEnv('CANVIX_ADMIN_USERS', 'alice')
+ expect(adminSource(user('alice', 'admin'))).toBe('both')
+ expect(adminSource(user('alice'))).toBe('env')
+ expect(adminSource(user('bob', 'admin'))).toBe('db')
+ expect(adminSource(user('bob'))).toBeNull()
+ expect(adminSource(null)).toBeNull()
+ })
+})
diff --git a/src/lib/admin/guard.ts b/src/lib/admin/guard.ts
new file mode 100644
index 0000000..2b3a84c
--- /dev/null
+++ b/src/lib/admin/guard.ts
@@ -0,0 +1,79 @@
+// ─────────────────────────────────────────────────────────────
+// Admin guard (v0.16 A1) — who may open /admin and its API.
+//
+// Two paths to admin, both fail-closed:
+// 1. DB role: User.role === 'admin' — granted by another admin from
+// the console (POST /api/admin/users/[id]/role).
+// 2. Env bootstrap: CANVIX_ADMIN_USERS="alice,bob" — usernames that
+// are admin on EVERY request, no DB write needed. This is the
+// self-hoster's zero-friction first-admin path: set the env var,
+// log in, the console link appears.
+//
+// There is no third path — no config-table flag, no secret URL, and
+// deliberately no "first registered user is admin" (on a public
+// instance that would silently hand the keys to whoever happens to
+// register first).
+//
+// CONTRACT: server-only (reads sessions + env).
+// ─────────────────────────────────────────────────────────────
+
+import { NextResponse, type NextRequest } from 'next/server'
+import { getSessionUser, type SessionUser } from '@/lib/auth/session'
+
+/** Parse CANVIX_ADMIN_USERS into a lowercase username set. */
+export function envAdminUsernames(): Set<string> {
+ const raw = process.env.CANVIX_ADMIN_USERS ?? ''
+ const out = new Set<string>()
+ for (const part of raw.split(',')) {
+ const name = part.trim().toLowerCase()
+ if (name) out.add(name)
+ }
+ return out
+}
+
+/** Anything with a username shape we can compare against (lowercased). */
+type NameLike = Pick<SessionUser, 'username' | 'role'>
+
+/** True when this user is an admin by either path. */
+export function isAdminUser(user: NameLike | null | undefined): boolean {
+ if (!user) return false
+ if (user.role === 'admin') return true
+ return envAdminUsernames().has(user.username)
+}
+
+/** Where a user's admin status comes from — surfaced as a badge in the console. */
+export function adminSource(user: NameLike | null | undefined): 'db' | 'env' | 'both' | null {
+ if (!user) return null
+ const db = user.role === 'admin'
+ const env = envAdminUsernames().has(user.username)
+ if (db && env) return 'both'
+ if (db) return 'db'
+ if (env) return 'env'
+ return null
+}
+
+export const ADMIN_REQUIRED = {
+ error: 'Administrator access is required.',
+ code: 'ADMIN_REQUIRED',
+} as const
+
+/**
+ * Resolve + authorize in one call — every /api/admin route starts with
+ * this. Returns the session user when the request carries an admin
+ * session, else a ready-to-return response:
+ * 401 — not signed in at all
+ * 403 — signed in but not an admin
+ * (the console UI shows different copy for each case).
+ */
+export async function requireAdmin(
+ req: NextRequest
+): Promise<{ ok: true; user: SessionUser } | { ok: false; res: NextResponse }> {
+ const user = await getSessionUser(req)
+ if (!user) {
+ return { ok: false, res: NextResponse.json({ ...ADMIN_REQUIRED, signedIn: false }, { status: 401 }) }
+ }
+ if (!isAdminUser(user)) {
+ return { ok: false, res: NextResponse.json({ ...ADMIN_REQUIRED, signedIn: true }, { status: 403 }) }
+ }
+ return { ok: true, user }
+}
diff --git a/src/lib/admin/routes.test.ts b/src/lib/admin/routes.test.ts
new file mode 100644
index 0000000..e4b7407
--- /dev/null
+++ b/src/lib/admin/routes.test.ts
@@ -0,0 +1,209 @@
+// Route-level unit tests for the admin API (v0.16 A1) — the guards,
+// the validation and the sanitized echo, all against a mocked db.
+// Pattern: claim-media.test.ts (vi.hoisted db mock; routes import the
+// same module). The withLogging wrapper's fire-and-forget traffic
+// recording silently no-ops against the mock — by design.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { NextRequest } from 'next/server'
+
+const dbMock = vi.hoisted(() => ({
+ session: { findUnique: vi.fn(), deleteMany: vi.fn() },
+ user: { findUnique: vi.fn(), update: vi.fn() },
+ appConfig: { findMany: vi.fn(), upsert: vi.fn() },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+import { POST as roleRoute } from '@/app/api/admin/users/[id]/role/route'
+import { POST as sessionsRoute } from '@/app/api/admin/users/[id]/sessions/route'
+import { GET as configGet, PUT as configPut } from '@/app/api/admin/config/route'
+import { POST as registerRoute } from '@/app/api/auth/register/route'
+import { invalidateAdminConfig } from './config'
+
+const ADMIN_SESSION = {
+ id: 'sess-admin',
+ expiresAt: new Date(Date.now() + 86_400_000),
+ user: { id: 'u-admin', username: 'root', role: 'admin', createdAt: new Date('2026-01-01T00:00:00Z') },
+}
+const PLAIN_SESSION = {
+ id: 'sess-plain',
+ expiresAt: new Date(Date.now() + 86_400_000),
+ user: { id: 'u-plain', username: 'mallory', role: 'user', createdAt: new Date('2026-01-01T00:00:00Z') },
+}
+
+function req(url: string, init: { method?: string; body?: unknown; cookie?: string | null; origin?: string } = {}) {
+ const headers: Record<string, string> = { 'content-type': 'application/json' }
+ if (init.cookie !== null) headers.cookie = init.cookie ?? 'canvix_session=tok'
+ if (init.origin) headers.origin = init.origin
+ return new NextRequest(url, {
+ method: init.method ?? 'GET',
+ headers,
+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
+ })
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ invalidateAdminConfig()
+ dbMock.appConfig.findMany.mockResolvedValue([])
+ dbMock.appConfig.upsert.mockResolvedValue({})
+})
+
+describe('POST /api/admin/users/[id]/role (v0.16 A1)', () => {
+ it('no session → 401, plain user → 403 (fail-closed)', async () => {
+ // 401: a cookie token that resolves to no session row
+ dbMock.session.findUnique.mockResolvedValueOnce(null)
+ const res1 = await roleRoute(req('http://localhost/api/admin/users/u-1/role', { method: 'POST', body: { role: 'admin' } }), { params: Promise.resolve({ id: 'u-1' }) })
+ expect(res1.status).toBe(401)
+
+ dbMock.session.findUnique.mockResolvedValueOnce(PLAIN_SESSION)
+ const res2 = await roleRoute(req('http://localhost/api/admin/users/u-1/role', { method: 'POST', body: { role: 'admin' } }), { params: Promise.resolve({ id: 'u-1' }) })
+ expect(res2.status).toBe(403)
+ })
+
+ it('cross-origin mutation → CSRF 403 before any db work', async () => {
+ dbMock.session.findUnique.mockResolvedValueOnce(ADMIN_SESSION)
+ const res = await roleRoute(
+ req('http://localhost/api/admin/users/u-1/role', { method: 'POST', body: { role: 'admin' }, origin: 'https://evil.io' }),
+ { params: Promise.resolve({ id: 'u-1' }) }
+ )
+ expect(res.status).toBe(403)
+ expect(dbMock.user.findUnique).not.toHaveBeenCalled()
+ })
+
+ it('rejects garbage roles and self-changes', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ const bad = await roleRoute(req('http://localhost/api/admin/users/u-1/role', { method: 'POST', body: { role: 'superadmin' } }), { params: Promise.resolve({ id: 'u-1' }) })
+ expect(bad.status).toBe(400)
+
+ const self = await roleRoute(req('http://localhost/api/admin/users/u-admin/role', { method: 'POST', body: { role: 'user' } }), { params: Promise.resolve({ id: 'u-admin' }) })
+ expect(self.status).toBe(400)
+ expect(((await self.json()) as { code: string }).code).toBe('SELF_ROLE_CHANGE')
+ })
+
+ it('promotes a user and echoes the effective admin state', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ dbMock.user.findUnique.mockResolvedValueOnce({ id: 'u-1', username: 'alice', role: 'user' })
+ dbMock.user.update.mockResolvedValueOnce({ id: 'u-1', username: 'alice', role: 'admin', createdAt: new Date('2026-02-02T00:00:00Z') })
+ const res = await roleRoute(req('http://localhost/api/admin/users/u-1/role', { method: 'POST', body: { role: 'admin' } }), { params: Promise.resolve({ id: 'u-1' }) })
+ expect(res.status).toBe(200)
+ expect(dbMock.user.update).toHaveBeenCalledWith(
+ expect.objectContaining({ where: { id: 'u-1' }, data: { role: 'admin' } })
+ )
+ const body = (await res.json()) as { user: { admin: boolean; adminSource: string } }
+ expect(body.user.admin).toBe(true)
+ expect(body.user.adminSource).toBe('db')
+ })
+
+ it('unknown target → 404', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ dbMock.user.findUnique.mockResolvedValueOnce(null)
+ const res = await roleRoute(req('http://localhost/api/admin/users/nope/role', { method: 'POST', body: { role: 'admin' } }), { params: Promise.resolve({ id: 'nope' }) })
+ expect(res.status).toBe(404)
+ })
+})
+
+describe('POST /api/admin/users/[id]/sessions (v0.16 A1)', () => {
+ it('revokes every session of the target', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ dbMock.user.findUnique.mockResolvedValueOnce({ id: 'u-1' })
+ dbMock.session.deleteMany.mockResolvedValueOnce({ count: 4 })
+ const res = await sessionsRoute(req('http://localhost/api/admin/users/u-1/sessions', { method: 'POST', body: {} }), { params: Promise.resolve({ id: 'u-1' }) })
+ expect(res.status).toBe(200)
+ expect(((await res.json()) as { revoked: number }).revoked).toBe(4)
+ expect(dbMock.session.deleteMany).toHaveBeenCalledWith({ where: { userId: 'u-1' } })
+ })
+})
+
+describe('GET/PUT /api/admin/config (v0.16 A1)', () => {
+ it('GET never echoes the stored key — only a mask', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ dbMock.appConfig.findMany.mockResolvedValue([
+ { key: 'ai.provider', value: { baseUrl: 'https://api.example.com/v1', apiKey: 'sk-secret-abcdef-wxyz' } },
+ ])
+ const res = await configGet(req('http://localhost/api/admin/config'))
+ expect(res.status).toBe(200)
+ const text = await res.text()
+ expect(text).not.toContain('sk-secret-abcdef-wxyz')
+ const body = JSON.parse(text)
+ expect(body.provider.source).toBe('db')
+ expect(body.provider.stored.keyMasked).toBe('sk-s…wxyz')
+ expect(body.provider.activeBaseUrl).toBe('https://api.example.com/v1')
+ })
+
+ it('PUT rejects a half-configured provider override', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { provider: { baseUrl: 'https://x.io' } } }))
+ expect(res.status).toBe(400)
+ })
+
+ it('PUT rejects a scheme-invalid provider override', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { provider: { baseUrl: 'javascript:alert(1)', apiKey: 'k' } } }))
+ expect(res.status).toBe(400)
+ })
+
+ it('PUT provider null clears the override (env fallback returns)', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { provider: null } }))
+ expect(res.status).toBe(200)
+ expect(dbMock.appConfig.upsert).toHaveBeenCalledWith(
+ expect.objectContaining({ where: { key: 'ai.provider' }, update: { value: {} } })
+ )
+ })
+
+ it('PUT features merges over the current flags', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ // read #1 (merge base) sees defaults; read #2 (post-write echo) sees the stored row
+ dbMock.appConfig.findMany
+ .mockResolvedValueOnce([])
+ .mockResolvedValue([{ key: 'ai.features', value: { magicWrite: false } }])
+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { features: { magicWrite: false } } }))
+ expect(res.status).toBe(200)
+ const arg = dbMock.appConfig.upsert.mock.calls.find((c) => c[0].where.key === 'ai.features')?.[0]
+ expect(arg.update.value).toMatchObject({ magicWrite: false, assistant: true })
+ const body = (await res.json()) as { features: Record<string, boolean> }
+ expect(body.features.magicWrite).toBe(false)
+ })
+
+ it('PUT settings merges and sanitizes the echo', async () => {
+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)
+ dbMock.appConfig.findMany
+ .mockResolvedValueOnce([])
+ .mockResolvedValue([{ key: 'app.settings', value: { signupsOpen: false } }])
+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { settings: { signupsOpen: false } } }))
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as { settings: { signupsOpen: boolean; anonymousEditing: boolean } }
+ expect(body.settings.signupsOpen).toBe(false)
+ expect(body.settings.anonymousEditing).toBe(true)
+ })
+
+ it('non-admins never see the config', async () => {
+ dbMock.session.findUnique.mockResolvedValueOnce(PLAIN_SESSION)
+ const res = await configGet(req('http://localhost/api/admin/config'))
+ expect(res.status).toBe(403)
+ })
+})
+
+describe('POST /api/auth/register × signups switch (v0.16 A1)', () => {
+ it('closed signups → 503 SIGNUPS_CLOSED before validation or rate limiting', async () => {
+ dbMock.appConfig.findMany.mockResolvedValue([{ key: 'app.settings', value: { signupsOpen: false } }])
+ const res = await registerRoute(
+ req('http://localhost/api/auth/register', { method: 'POST', body: { username: 'somebody', password: 'longenough1' }, cookie: null })
+ )
+ expect(res.status).toBe(503)
+ expect(((await res.json()) as { code: string }).code).toBe('SIGNUPS_CLOSED')
+ // nothing past the gate ran — no user lookups
+ expect(dbMock.user.findUnique).not.toHaveBeenCalled()
+ })
+
+ it('open signups (default) → the route proceeds to normal validation', async () => {
+ dbMock.appConfig.findMany.mockResolvedValue([])
+ const res = await registerRoute(
+ req('http://localhost/api/auth/register', { method: 'POST', body: { username: 'x', password: 'short' }, cookie: null })
+ )
+ // reached validation and failed on the username (not on the gate)
+ expect(res.status).toBe(400)
+ expect(((await res.json()) as { code?: string }).code).toBeUndefined()
+ })
+})
diff --git a/src/lib/admin/series.test.ts b/src/lib/admin/series.test.ts
new file mode 100644
index 0000000..2403ca1
--- /dev/null
+++ b/src/lib/admin/series.test.ts
@@ -0,0 +1,63 @@
+// Unit tests for the day-series helpers (v0.16 A1).
+
+import { describe, it, expect } from 'vitest'
+import { dayKey, recentDayKeys, fillDays, sumSeries } from './series'
+
+const NOW = new Date('2026-11-07T18:30:00Z')
+
+describe('dayKey / recentDayKeys (v0.16 A1)', () => {
+ it('formats UTC YYYY-MM-DD', () => {
+ expect(dayKey(NOW)).toBe('2026-11-07')
+ })
+
+ it('returns `days` keys ending today, oldest first', () => {
+ expect(recentDayKeys(3, NOW)).toEqual(['2026-11-05', '2026-11-06', '2026-11-07'])
+ })
+})
+
+describe('fillDays (v0.16 A1)', () => {
+ it('fills gaps with zeros and drops out-of-window days', () => {
+ const series = fillDays(
+ [
+ ['2026-11-07', 12],
+ ['2026-11-05', 4],
+ ['2026-10-01', 999], // outside the 3-day window
+ ],
+ 3,
+ NOW
+ )
+ expect(series).toEqual([
+ { day: '2026-11-05', value: 4 },
+ { day: '2026-11-06', value: 0 },
+ { day: '2026-11-07', value: 12 },
+ ])
+ })
+
+ it('newest duplicate wins', () => {
+ const series = fillDays(
+ [
+ ['2026-11-07', 1],
+ ['2026-11-07', 5],
+ ],
+ 1,
+ NOW
+ )
+ expect(series).toEqual([{ day: '2026-11-07', value: 5 }])
+ })
+})
+
+describe('sumSeries (v0.16 A1)', () => {
+ it('sums the last N points only', () => {
+ const series = fillDays(
+ [
+ ['2026-11-05', 100],
+ ['2026-11-06', 2],
+ ['2026-11-07', 3],
+ ],
+ 3,
+ NOW
+ )
+ expect(sumSeries(series, 2)).toBe(5)
+ expect(sumSeries(series, 7)).toBe(105)
+ })
+})
diff --git a/src/lib/admin/series.ts b/src/lib/admin/series.ts
new file mode 100644
index 0000000..b615cb4
--- /dev/null
+++ b/src/lib/admin/series.ts
@@ -0,0 +1,47 @@
+// ─────────────────────────────────────────────────────────────
+// Day-series helpers (v0.16 A1) — pure functions the admin
+// overview route uses to turn sparse SQL group-bys into gap-free
+// chart series. Unit-tested; no I/O.
+// ─────────────────────────────────────────────────────────────
+
+export interface DayPoint {
+ /** UTC date, YYYY-MM-DD */
+ day: string
+ value: number
+}
+
+/** Format a Date as a UTC YYYY-MM-DD key. */
+export function dayKey(d: Date): string {
+ return d.toISOString().slice(0, 10)
+}
+
+/** The last `days` UTC day keys, oldest first, ending today. */
+export function recentDayKeys(days: number, now: Date = new Date()): string[] {
+ const out: string[] = []
+ const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ for (let i = days - 1; i >= 0; i--) {
+ out.push(dayKey(new Date(today - i * 24 * 60 * 60 * 1000)))
+ }
+ return out
+}
+
+/**
+ * Merge a sparse {day→value} map onto the last `days` day keys.
+ * Missing days become 0 — charts stay continuous across idle days.
+ * Input days outside the window are dropped; the newest value wins
+ * on duplicate keys.
+ */
+export function fillDays(
+ values: Iterable<[string, number]>,
+ days: number,
+ now: Date = new Date()
+): DayPoint[] {
+ const map = new Map<string, number>()
+ for (const [k, v] of values) map.set(k, v)
+ return recentDayKeys(days, now).map((day) => ({ day, value: map.get(day) ?? 0 }))
+}
+
+/** Total over a filled series — for the "last N days" stat cards. */
+export function sumSeries(series: DayPoint[], lastN: number): number {
+ return series.slice(-lastN).reduce((acc, p) => acc + p.value, 0)
+}
diff --git a/src/lib/admin/traffic.test.ts b/src/lib/admin/traffic.test.ts
new file mode 100644
index 0000000..ef60683
--- /dev/null
+++ b/src/lib/admin/traffic.test.ts
@@ -0,0 +1,101 @@
+// Unit tests for traffic + activity recording (v0.16 A1): day
+// bucketing, route-name parsing, the opt-out flag and the
+// fire-and-forget contract, against a mocked db.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const upsert = vi.hoisted(() => vi.fn())
+const deleteMany = vi.hoisted(() => vi.fn())
+const dbMock = vi.hoisted(() => ({ trafficStat: { upsert, deleteMany }, dailyActive: { upsert } }))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+import { utcDay, parseRouteName, recordTraffic, recordActive, trafficRecordingEnabled } from './traffic'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.unstubAllEnvs()
+ upsert.mockResolvedValue({})
+ deleteMany.mockResolvedValue({ count: 0 })
+})
+
+describe('utcDay (v0.16 A1)', () => {
+ it('truncates to UTC midnight', () => {
+ expect(utcDay(new Date('2026-11-07T13:44:59.999Z')).toISOString()).toBe('2026-11-07T00:00:00.000Z')
+ })
+
+ it('late-UTC local times land on the next UTC day', () => {
+ expect(utcDay(new Date('2026-11-07T23:30:00Z')).toISOString()).toBe('2026-11-07T00:00:00.000Z')
+ expect(utcDay(new Date('2026-11-08T00:01:00Z')).toISOString()).toBe('2026-11-08T00:00:00.000Z')
+ })
+})
+
+describe('parseRouteName (v0.16 A1)', () => {
+ it('splits "METHOD /route" wrapper names', () => {
+ expect(parseRouteName('GET /api/designs', 'POST')).toEqual({ route: '/api/designs', method: 'GET' })
+ })
+
+ it('odd shapes fall back to the request method and the whole name', () => {
+ expect(parseRouteName('weird', 'POST')).toEqual({ route: 'weird', method: 'POST' })
+ expect(parseRouteName(' ', 'GET')).toEqual({ route: ' ', method: 'GET' })
+ expect(parseRouteName('GET ', 'GET')).toEqual({ route: 'GET ', method: 'GET' })
+ })
+})
+
+describe('trafficRecordingEnabled (v0.16 A1)', () => {
+ it('on by default, off only on the explicit opt-out', () => {
+ delete process.env.CANVIX_TRAFFIC
+ expect(trafficRecordingEnabled()).toBe(true)
+ vi.stubEnv('CANVIX_TRAFFIC', '0')
+ expect(trafficRecordingEnabled()).toBe(false)
+ })
+})
+
+describe('recordTraffic (v0.16 A1)', () => {
+ it('upserts the day aggregate with an increment', async () => {
+ await recordTraffic('GET /api/health', 'GET', 200)
+ expect(upsert).toHaveBeenCalledTimes(1)
+ const arg = upsert.mock.calls[0][0]
+ expect(arg.where.day_route_method_status).toMatchObject({ route: '/api/health', method: 'GET', status: 200 })
+ expect(arg.update).toEqual({ hits: { increment: 1 } })
+ expect(arg.create.hits).toBe(1)
+ })
+
+ it('honors the opt-out with zero db calls', async () => {
+ vi.stubEnv('CANVIX_TRAFFIC', '0')
+ await recordTraffic('GET /api/health', 'GET', 200)
+ expect(upsert).not.toHaveBeenCalled()
+ })
+
+ it('db failures are swallowed (accounting never breaks the request)', async () => {
+ upsert.mockRejectedValue(new Error('down'))
+ await expect(recordTraffic('GET /api/health', 'GET', 500)).resolves.toBeUndefined()
+ })
+
+ it('occasionally sweeps rows past the retention window', async () => {
+ const rand = vi.spyOn(Math, 'random').mockReturnValue(0)
+ await recordTraffic('GET /api/health', 'GET', 200)
+ expect(deleteMany).toHaveBeenCalledTimes(1)
+ const where = deleteMany.mock.calls[0][0].where
+ // cutoff ≈ today - 90d
+ const cutoff = where.day.lt as Date
+ const days = (Date.now() - cutoff.getTime()) / 86_400_000
+ expect(days).toBeGreaterThan(89)
+ expect(days).toBeLessThan(91)
+ rand.mockRestore()
+ })
+})
+
+describe('recordActive (v0.16 A1)', () => {
+ it('upserts (day, actor) idempotently', async () => {
+ await recordActive('user-1')
+ expect(dbMock.dailyActive.upsert).toHaveBeenCalledWith(
+ expect.objectContaining({ update: {} })
+ )
+ })
+
+ it('null actors are a no-op', async () => {
+ await recordActive(null)
+ await recordActive(undefined)
+ expect(dbMock.dailyActive.upsert).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/admin/traffic.ts b/src/lib/admin/traffic.ts
new file mode 100644
index 0000000..da305f5
--- /dev/null
+++ b/src/lib/admin/traffic.ts
@@ -0,0 +1,94 @@
+// ─────────────────────────────────────────────────────────────
+// Traffic + activity recording (v0.16 A1) — the counters behind
+// the console's Traffic and DAU charts.
+//
+// TrafficStat: one fire-and-forget upsert per API request from the
+// withLogging wrapper every route already uses. Aggregate counts only
+// (route template, method, status, day) — the same no-ids/no-IPs/no-
+// query-strings stance as /api/health?v=2. CANVIX_TRAFFIC=0 opts out.
+//
+// DailyActive: one upsert per (day, actor) from the two surfaces that
+// mean "someone used Canvix today" (design list / editor open). The
+// actor is a userId or the already-hashed anonymous cookie key.
+//
+// Both are best-effort by design (the pattern recordUsage set in
+// v0.5): accounting must never break the request it accounts for.
+// On serverless/workerd runtimes a fire-and-forget write can be
+// cancelled after the response — documented in docs/ADMIN.md; the
+// self-hosted Node runtime this app primarily targets is exact.
+//
+// CONTRACT: server-only; every entry point swallows its own errors.
+// ─────────────────────────────────────────────────────────────
+
+/** CANVIX_TRAFFIC=0 is the explicit opt-out. Counting is on by default. */
+export function trafficRecordingEnabled(): boolean {
+ return process.env.CANVIX_TRAFFIC !== '0'
+}
+
+/** UTC midnight of the given instant — the day bucket for both tables. */
+export function utcDay(d: Date = new Date()): Date {
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()))
+}
+
+/**
+ * withLogging names look like "GET /api/designs". Split into the stored
+ * pair; anything without the expected shape is stored whole as the route
+ * with the request's method, so a misnamed wrapper never crashes accounting.
+ */
+export function parseRouteName(name: string, fallbackMethod: string): { route: string; method: string } {
+ const space = name.indexOf(' ')
+ if (space === -1 || space === 0 || space === name.length - 1) {
+ return { route: name, method: fallbackMethod }
+ }
+ return { route: name.slice(space + 1), method: name.slice(0, space) }
+}
+
+/** Counters older than this are swept lazily. */
+export const TRAFFIC_RETENTION_DAYS = 90
+
+/** Bounded route/status text — defense against a misbehaving wrapper name. */
+const ROUTE_MAX = 160
+
+/**
+ * Record one API request into the day's aggregate. Fire-and-forget:
+ * call sites `void` this; it never rejects. Also lazily sweeps rows
+ * past the retention window (1% of calls — amortized, bounded).
+ */
+export async function recordTraffic(name: string, method: string, status: number): Promise<void> {
+ if (!trafficRecordingEnabled()) return
+ try {
+ const { route, method: m } = parseRouteName(name, method)
+ const day = utcDay()
+ const { db } = await import('@/lib/db')
+ await db.trafficStat.upsert({
+ where: { day_route_method_status: { day, route: route.slice(0, ROUTE_MAX), method: m.slice(0, 10), status } },
+ create: { day, route: route.slice(0, ROUTE_MAX), method: m.slice(0, 10), status, hits: 1 },
+ update: { hits: { increment: 1 } },
+ })
+ if (Math.random() < 0.01) {
+ const cutoff = new Date(day.getTime() - TRAFFIC_RETENTION_DAYS * 24 * 60 * 60 * 1000)
+ await db.trafficStat.deleteMany({ where: { day: { lt: cutoff } } })
+ }
+ } catch {
+ /* accounting must never break the request */
+ }
+}
+
+/**
+ * Record a daily-active actor (a userId or the pre-hashed anon key).
+ * Null actors (no session, no anon cookie yet) are a no-op.
+ */
+export async function recordActive(actor: string | null | undefined): Promise<void> {
+ if (!actor) return
+ try {
+ const day = utcDay()
+ const { db } = await import('@/lib/db')
+ await db.dailyActive.upsert({
+ where: { day_actor: { day, actor: actor.slice(0, 80) } },
+ create: { day, actor: actor.slice(0, 80) },
+ update: {},
+ })
+ } catch {
+ /* best-effort by design */
+ }
+}
diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.ts
index f65c4e7..0c27202 100644
--- a/src/lib/ai/provider.ts
+++ b/src/lib/ai/provider.ts
@@ -1,6 +1,7 @@
import { NextResponse, type NextRequest } from 'next/server'
import { existsSync, readFileSync } from 'fs'
import { CSRF_REJECTED } from '@/lib/auth/csrf'
+import { getProviderOverride, aiFeatureEnabled, getModels, type AiFeature } from '@/lib/admin/config'
/**
* Canvix AI provider abstraction (v0.5).
@@ -26,8 +27,24 @@ export interface AIProviderConfig {
apiKey: string
}
-/** VISION_MODEL — the multimodal model used for Magic Layers analysis. */
-export const VISION_MODEL = 'glm-4.5v'
+/** Default multimodal model for Magic Layers analysis (v0.16 A1: overridable from /admin). */
+export const DEFAULT_VISION_MODEL = 'glm-4.5v'
+
+// ── v0.16 (A1): model selection from the admin console ──────────
+// Stored in AppConfig (ai.models), validated by src/lib/admin/config.ts.
+// Undefined = let the SDK pick its own default — the pre-A1 behaviour.
+
+export async function getTextModel(): Promise<string | undefined> {
+ return (await getModels()).text
+}
+
+export async function getVisionModel(): Promise<string> {
+ return (await getModels()).vision ?? DEFAULT_VISION_MODEL
+}
+
+export async function getImageModel(): Promise<string | undefined> {
+ return (await getModels()).image
+}
/**
* Resolve the provider configuration.
@@ -69,9 +86,27 @@ export function resolveProviderConfig(): AIProviderConfig | null {
return null
}
-/** Quick boolean probe used by /api/ai/capabilities and route guards. */
-export function hasProvider(): boolean {
- return resolveProviderConfig() !== null
+/**
+ * Full resolution with provenance (v0.16 A1): console DB override → env
+ * vars → .z-ai-config file → null. The console-set override wins so an
+ * operator can point the instance at a different provider without a
+ * redeploy; `source` is surfaced in /admin (which layer answered —
+ * never the secret itself).
+ */
+export async function resolveProvider(): Promise<{ baseUrl: string; apiKey: string; source: 'db' | 'env' | 'file' } | null> {
+ const fromDb = await getProviderOverride()
+ if (fromDb) return { ...fromDb, source: 'db' }
+ const envUrl = process.env.ZAI_BASE_URL?.trim()
+ const envKey = process.env.ZAI_API_KEY?.trim()
+ if (envUrl && envKey) return { baseUrl: envUrl, apiKey: envKey, source: 'env' }
+ const fromFile = resolveProviderConfig()
+ if (fromFile) return { ...fromFile, source: 'file' }
+ return null
+}
+
+/** Async probe used by /api/ai/capabilities, MCP tools and route guards. */
+export async function hasProvider(): Promise<boolean> {
+ return (await resolveProvider()) !== null
}
/**
@@ -79,9 +114,20 @@ export function hasProvider(): boolean {
* never lands in a client bundle. Returns null when unconfigured.
*/
export async function getZAI(): Promise<import('z-ai-web-dev-sdk').default | null> {
- const cfg = resolveProviderConfig()
+ const cfg = await resolveProvider()
if (!cfg) return null
try {
+ // The SDK's ZAI.create() takes no arguments and resolves its own
+ // config from ZAI_BASE_URL/ZAI_API_KEY env or the .z-ai-config file
+ // (verified against the SDK's typings). A console-set (DB) provider
+ // is therefore injected through process.env before instantiation —
+ // server-side, in-memory, and exactly the variable the documented
+ // env setup uses, so the SDK keeps one consistent config surface.
+ // Decision recorded in docs/ADMIN.md.
+ if (cfg.source === 'db') {
+ process.env.ZAI_BASE_URL = cfg.baseUrl
+ process.env.ZAI_API_KEY = cfg.apiKey
+ }
const { default: ZAI } = await import('z-ai-web-dev-sdk')
return await ZAI.create()
} catch (err) {
@@ -184,12 +230,35 @@ function isFromApp(req: NextRequest): boolean {
}
}
+/** withProvider feature name → admin console flag (src/lib/admin/config.ts). */
+const FEATURE_FLAGS: Record<string, AiFeature> = {
+ write: 'magicWrite',
+ image: 'imageGeneration',
+ 'image-edit': 'imageEditing',
+ 'magic-layers': 'vision',
+ translate: 'translation',
+ assistant: 'assistant',
+ search: 'photoSearch',
+}
+
+export const FEATURE_DISABLED = {
+ error: 'This AI feature is disabled by the administrator.',
+ code: 'FEATURE_DISABLED',
+} as const
+
export async function withProvider(
feature: string,
req: NextRequest,
limits: { limit: number; windowSec: number },
fn: (zai: NonNullable<Awaited<ReturnType<typeof getZAI>>>) => Promise<NextResponse>
): Promise<NextResponse> {
+ // v0.16 (A1): per-feature kill switch from the admin console. Checked
+ // before the abuse guard, rate limiting and any provider work — a
+ // disabled feature costs nothing and answers like an unconfigured one.
+ const flag = FEATURE_FLAGS[feature]
+ if (flag && !(await aiFeatureEnabled(flag))) {
+ return NextResponse.json(FEATURE_DISABLED, { status: 503 })
+ }
// v0.9.2 abuse guard: every AI route is only ever called by the app's own
// pages (same origin). Cross-origin or Origin-less POSTs — the signature
// of a bot hitting the public endpoint directly — are rejected before any
diff --git a/src/lib/auth/client.ts b/src/lib/auth/client.ts
index 0e77d1a..4a5d365 100644
--- a/src/lib/auth/client.ts
+++ b/src/lib/auth/client.ts
@@ -12,6 +12,8 @@ export interface AuthUser {
id: string
username: string
createdAt: string
+ /** v0.16 (A1): true when /api/auth/me resolved an admin (DB role or env bootstrap). */
+ admin?: boolean
}
export interface AuthState {
diff --git a/src/lib/auth/session.ts b/src/lib/auth/session.ts
index 445a471..0f9b92d 100644
--- a/src/lib/auth/session.ts
+++ b/src/lib/auth/session.ts
@@ -22,6 +22,8 @@ export const SESSION_TTL_DAYS = 30
export interface SessionUser {
id: string
username: string
+ /** v0.16 (A1): 'user' | 'admin' (effective admin also honours CANVIX_ADMIN_USERS). */
+ role: string
createdAt: Date
}
@@ -72,13 +74,16 @@ export async function destroySession(req: NextRequest, res: NextResponse): Promi
* Resolve the signed-in user from the request cookie.
* Returns null when absent, expired, or dangling (user deleted).
*/
-export async function getSessionUser(req: NextRequest): Promise<SessionUser | null> {
- const token = req.cookies.get(SESSION_COOKIE)?.value
+/**
+ * Resolve the signed-in user from a raw session token — shared by the
+ * request-cookie path and the RSC cookies() path (the admin layout).
+ */
+export async function getSessionUserFromToken(token: string | null | undefined): Promise<SessionUser | null> {
if (!token || token.length > 128) return null
try {
const row = await db.session.findUnique({
where: { id: sessionIdFor(token) },
- include: { user: { select: { id: true, username: true, createdAt: true } } },
+ include: { user: { select: { id: true, username: true, role: true, createdAt: true } } },
})
if (!row) return null
if (row.expiresAt.getTime() < Date.now()) {
@@ -91,3 +96,8 @@ export async function getSessionUser(req: NextRequest): Promise<SessionUser | nu
return null
}
}
+
+/** Request-cookie wrapper — the usual API-route entry point. */
+export async function getSessionUser(req: NextRequest): Promise<SessionUser | null> {
+ return getSessionUserFromToken(req.cookies.get(SESSION_COOKIE)?.value)
+}
diff --git a/src/lib/mcp/tools.ts b/src/lib/mcp/tools.ts
index 0f61916..422d8b3 100644
--- a/src/lib/mcp/tools.ts
+++ b/src/lib/mcp/tools.ts
@@ -1178,7 +1178,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {
return ok({
server: 'canvix',
version: SERVER_VERSION,
- aiProvider: hasProvider() ? 'available (generate_design works)' : 'not configured (generate_design unavailable; all other tools work)',
+ aiProvider: (await hasProvider()) ? 'available (generate_design works)' : 'not configured (generate_design unavailable; all other tools work)',
transport: 'streamable-http (stateless)',
auth: 'bearer token via CANVIX_MCP_TOKEN',
})
diff --git a/src/lib/observability.ts b/src/lib/observability.ts
index c8f38ce..70e5889 100644
--- a/src/lib/observability.ts
+++ b/src/lib/observability.ts
@@ -21,6 +21,7 @@
// ─────────────────────────────────────────────────────────────
import type { NextRequest } from 'next/server'
+import { recordTraffic } from '@/lib/admin/traffic'
/** The app version answering requests — from package.json at build time. */
export const APP_VERSION = process.env.npm_package_version ?? 'unknown'
@@ -67,9 +68,11 @@ export function logApiRequest(entry: ApiRequestLog): void {
}
/**
- * Wrap an API route handler with opt-in request logging. Zero-cost
- * passthrough when CANVIX_LOG is unset (the default): the wrapper
- * checks once per call and never touches the response otherwise.
+ * Wrap an API route handler with opt-in request logging AND always-on
+ * aggregate traffic counters (v0.16 A1 — CANVIX_TRAFFIC=0 opts out;
+ * counts only, never ids/IPs/query strings). The stdout log side stays
+ * a zero-cost passthrough when CANVIX_LOG is unset (the default): the
+ * wrapper checks once per call and never touches the response otherwise.
* Never mutates the response — the handler's headers, streams and
* status codes pass through untouched (the SSE route included).
*/
@@ -78,24 +81,33 @@ export function withLogging<A extends unknown[]>(
handler: (req: NextRequest, ...args: A) => Promise<Response>,
): (req: NextRequest, ...args: A) => Promise<Response> {
return async (req, ...args) => {
- if (!requestLoggingEnabled()) return handler(req, ...args)
+ // v0.16 (A1): aggregate traffic counters — independent of the stdout
+ // switch above. Fire-and-forget by contract (recordTraffic swallows
+ // its own errors); counting must never delay or break the response
+ // it counts.
const start = now()
try {
const res = await handler(req, ...args)
- logApiRequest({
- method: req.method,
- path: new URL(req.url).pathname,
- status: res.status,
- durationMs: now() - start,
- })
+ if (requestLoggingEnabled()) {
+ logApiRequest({
+ method: req.method,
+ path: new URL(req.url).pathname,
+ status: res.status,
+ durationMs: now() - start,
+ })
+ }
+ void recordTraffic(name, req.method, res.status)
return res
} catch (error) {
- logApiRequest({
- method: req.method,
- path: new URL(req.url).pathname,
- status: 500,
- durationMs: now() - start,
- })
+ if (requestLoggingEnabled()) {
+ logApiRequest({
+ method: req.method,
+ path: new URL(req.url).pathname,
+ status: 500,
+ durationMs: now() - start,
+ })
+ }
+ void recordTraffic(name, req.method, 500)
throw error
}
}
diff --git a/tests/e2e/admin-console.spec.ts b/tests/e2e/admin-console.spec.ts
new file mode 100644
index 0000000..49312c6
--- /dev/null
+++ b/tests/e2e/admin-console.spec.ts
@@ -0,0 +1,188 @@
+// Admin console acceptance (v0.16 A1).
+//
+// Zero registrations by construction: the two fixture users (one admin,
+// one plain) and their sessions are seeded straight into the database
+// the server runs on — the same Postgres the app uses, reached through
+// the `pg` driver already present in node_modules (@prisma/adapter-pg's
+// dependency; ambiently typed in ./pg-shim.d.ts, imported directly so
+// no createRequire/import.meta gymnastics are needed) — keeping the
+// suite inside the 5/h/IP register budget the other specs honor.
+//
+// What is proven here, end to end:
+// 1. /admin is invisible to anonymous visitors and refuses plain users.
+// 2. An admin session renders the console with live aggregate numbers.
+// 3. Role management round-trips through the real UI (two-step confirm).
+// 4. AI feature switches actually reach /api/ai/capabilities.
+// 5. The sign-ups switch actually refuses /api/auth/register.
+// 6. Traffic counters really capture API requests.
+
+import { test, expect, type Browser } from '@playwright/test'
+import { createHash } from 'node:crypto'
+import { Client } from 'pg'
+
+const ADMIN = { id: 'u_e2e_admin_a1', username: 'e2e_admin_a1', token: 'e2e-admin-token-a1' }
+const PLAIN = { id: 'u_e2e_user_a1', username: 'e2e_user_a1', token: 'e2e-plain-token-a1' }
+
+function sessionId(token: string): string {
+ return createHash('sha256').update(token).digest('hex')
+}
+
+let client: InstanceType<typeof Client>
+
+test.beforeAll(async () => {
+ client = new Client({ connectionString: process.env.DATABASE_URL })
+ await client.connect()
+ for (const u of [ADMIN, PLAIN]) {
+ await client.query(`DELETE FROM "Session" WHERE "userId" IN (SELECT "id" FROM "User" WHERE "username" = $1)`, [u.username])
+ await client.query(`DELETE FROM "User" WHERE "username" = $1`, [u.username])
+ await client.query(
+ `INSERT INTO "User" ("id", "username", "passwordHash", "role", "createdAt")
+ VALUES ($1, $2, 'seed-no-login', $3, now())`,
+ [u.id, u.username, u.id === ADMIN.id ? 'admin' : 'user']
+ )
+ await client.query(
+ `INSERT INTO "Session" ("id", "userId", "createdAt", "expiresAt")
+ VALUES ($1, $2, now(), now() + interval '2 hours')`,
+ [sessionId(u.token), u.id]
+ )
+ }
+})
+
+test.afterAll(async () => {
+ if (client) {
+ for (const u of [ADMIN, PLAIN]) {
+ await client.query(`DELETE FROM "Session" WHERE "userId" IN (SELECT "id" FROM "User" WHERE "username" = $1)`, [u.username])
+ await client.query(`DELETE FROM "User" WHERE "username" = $1`, [u.username])
+ }
+ await client.end().catch(() => {})
+ }
+})
+
+/** A browser context carrying one of the seeded session cookies. */
+async function contextWithToken(browser: Browser, token: string | null) {
+ const ctx = await browser.newContext()
+ if (token) {
+ await ctx.addCookies([
+ { name: 'canvix_session', value: token, url: process.env.BASE_URL ?? 'http://localhost:3000' },
+ ])
+ }
+ return ctx
+}
+
+test.describe('admin console (A1)', () => {
+ test('anonymous visitors and plain accounts cannot open /admin', async ({ browser }) => {
+ const anonCtx = await contextWithToken(browser, null)
+ const anonPage = await anonCtx.newPage()
+ await anonPage.goto('/admin')
+ await expect(anonPage.getByText('Sign in required')).toBeVisible()
+ await anonCtx.close()
+
+ const plainCtx = await contextWithToken(browser, PLAIN.token)
+ const plainPage = await plainCtx.newPage()
+ await plainPage.goto('/admin')
+ await expect(plainPage.getByText('No administrator access')).toBeVisible()
+ await plainCtx.close()
+ })
+
+ test('the admin API refuses non-admins at the boundary', async ({ browser }) => {
+ const plainCtx = await contextWithToken(browser, PLAIN.token)
+ const res = await plainCtx.request.get('/api/admin/overview')
+ expect(res.status()).toBe(403)
+ const body = (await res.json()) as { code: string }
+ expect(body.code).toBe('ADMIN_REQUIRED')
+ await plainCtx.close()
+ })
+
+ test('an admin sees the console overview with live totals', async ({ browser }) => {
+ const ctx = await contextWithToken(browser, ADMIN.token)
+ const page = await ctx.newPage()
+ await page.goto('/admin')
+ await expect(page.getByRole('heading', { name: 'Admin console' })).toBeVisible()
+ // the stat cards render real numbers (>= 2 seeded users)
+ await expect(page.getByText('Users', { exact: true })).toBeVisible()
+ await expect(page.getByText('Designs', { exact: true })).toBeVisible()
+ await expect
+ .poll(async () => {
+ const res = await ctx.request.get('/api/admin/overview')
+ const data = (await res.json()) as { totals?: { users?: number }; windows?: { requests24h?: number } }
+ return data.totals?.users ?? 0
+ })
+ .toBeGreaterThanOrEqual(2)
+ // section nav reaches the other pages
+ await expect(page.getByRole('link', { name: 'Users' })).toBeVisible()
+ await expect(page.getByRole('link', { name: 'AI & models' })).toBeVisible()
+ await expect(page.getByRole('link', { name: 'Settings' })).toBeVisible()
+ await ctx.close()
+ })
+
+ test('role management round-trips through the real UI', async ({ browser }) => {
+ const ctx = await contextWithToken(browser, ADMIN.token)
+ const page = await ctx.newPage()
+ await page.goto('/admin/users')
+ const row = page.locator('tr', { hasText: PLAIN.username })
+ await expect(row).toBeVisible()
+ // two-step confirm: make admin → confirm
+ await row.getByRole('button', { name: /make admin/ }).click()
+ await row.getByRole('button', { name: 'confirm', exact: true }).click()
+ await expect(row.getByRole('button', { name: /revoke/ })).toBeVisible({ timeout: 10_000 })
+ // and the DB really changed
+ const dbRow = (await client.query(`SELECT "role" FROM "User" WHERE "username" = $1`, [PLAIN.username])).rows[0]
+ expect(dbRow?.['role']).toBe('admin')
+ // revert through the API (also covers the route)
+ const res = await ctx.request.post(`/api/admin/users/${PLAIN.id}/role`, { data: { role: 'user' } })
+ expect(res.status()).toBe(200)
+ await ctx.close()
+ })
+
+ test('AI feature switches reach the public capabilities endpoint', async ({ browser }) => {
+ const ctx = await contextWithToken(browser, ADMIN.token)
+ const put = await ctx.request.put('/api/admin/config', { data: { features: { magicWrite: false } } })
+ expect(put.status()).toBe(200)
+ const caps = (await (await ctx.request.get('/api/ai/capabilities')).json()) as {
+ capabilities: Record<string, boolean>
+ }
+ expect(caps.capabilities.magicWrite).toBe(false)
+ expect(caps.capabilities.backgroundRemoval).toBe(true) // local feature untouched
+ // restore
+ const restore = await ctx.request.put('/api/admin/config', { data: { features: { magicWrite: true } } })
+ expect(restore.status()).toBe(200)
+ await ctx.close()
+ })
+
+ test('closing sign-ups refuses registration with 503 SIGNUPS_CLOSED', async ({ browser }) => {
+ const ctx = await contextWithToken(browser, ADMIN.token)
+ const put = await ctx.request.put('/api/admin/config', { data: { settings: { signupsOpen: false } } })
+ expect(put.status()).toBe(200)
+ // a fresh anonymous registration attempt is refused…
+ const anonCtx = await contextWithToken(browser, null)
+ const res = await anonCtx.request.post('/api/auth/register', {
+ data: { username: `closed_${Date.now() % 100000}`, password: 'longenough1' },
+ })
+ expect(res.status()).toBe(503)
+ expect(((await res.json()) as { code: string }).code).toBe('SIGNUPS_CLOSED')
+ await anonCtx.close()
+ // …and reopening restores normal behaviour
+ const reopen = await ctx.request.put('/api/admin/config', { data: { settings: { signupsOpen: true } } })
+ expect(reopen.status()).toBe(200)
+ await ctx.close()
+ })
+
+ test('API traffic is counted and surfaces in the overview', async ({ browser }) => {
+ const ctx = await contextWithToken(browser, ADMIN.token)
+ for (let i = 0; i < 3; i++) {
+ await ctx.request.get('/api/health')
+ }
+ // fire-and-forget counters — poll until the day aggregate shows them
+ await expect
+ .poll(
+ async () => {
+ const res = await ctx.request.get('/api/admin/overview')
+ const data = (await res.json()) as { windows?: { requests24h?: number } }
+ return data.windows?.requests24h ?? 0
+ },
+ { timeout: 20_000 }
+ )
+ .toBeGreaterThan(0)
+ await ctx.close()
+ })
+})
diff --git a/tests/e2e/pg-shim.d.ts b/tests/e2e/pg-shim.d.ts
new file mode 100644
index 0000000..048e32d
--- /dev/null
+++ b/tests/e2e/pg-shim.d.ts
@@ -0,0 +1,15 @@
+// Ambient typing for the `pg` driver inside e2e specs (v0.16 A1).
+//
+// `pg` is a transitive dependency (@prisma/adapter-pg) with no bundled
+// types and no @types/pg in the tree — declaring exactly the surface
+// the specs use keeps `npm run typecheck` green without adding a
+// dependency for tests only. Playwright resolves the real module from
+// node_modules at runtime.
+declare module 'pg' {
+ export class Client {
+ constructor(config: { connectionString?: string })
+ connect(): Promise<void>
+ end(): Promise<void>
+ query(sql: string, params?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>
+ }
+}