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.

fix(admin): console audit — 3 defects fixed + BYOK adoption stat (#75)

Ashiq Hussain Mir9d63355f502d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ff735cf..ca95368 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
+- **Admin: BYOK adoption stat** — the console overview now answers
+ "how many users added their own API keys": a new **Own API keys**
+ stat card (distinct accounts with ≥1 `UserAIProvider` row, key
+ count, how many of the five capability slots user keys cover —
+ the CSV `slots` column parsed per-slot in SQL). Aggregate-only:
+ no usernames ride along. `/api/admin/overview` gains a matching
+ `byok` block.
- **WebP export** (Wave 5 remainder, roadmap §4.3) — the fourth raster
format in the export dialog, riding the browser-native encoder (zero
new dependencies, the §8 discipline): the format card is
@@ -110,6 +117,28 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed
+- **Admin console audit (2026-11-19)** — a full sweep of all five
+ console pages (zero runtime errors: console, page, HTTP) found and
+ fixed three defects:
+ - the **Model slots** card's chip read `X/4 wired` with five slots
+ configured — the v0.19 video slot never reached the hardcoded
+ denominator, so a fully-wired instance displayed "5/4 wired".
+ The chip now counts from the slot list itself.
+ - the overview's **AI providers** card counted *stored* slot
+ bindings, not slots that actually *resolve* — a stale binding
+ (provider removed from the list) overstated the wiring, and
+ `providersSummary()` now resolves each of the five slots before
+ counting.
+ - the **user search** lowercased the query while the database
+ `contains` stayed case-sensitive, so any username stored with
+ uppercase letters was unfindable in any case. Registration
+ lowercases usernames, so this mostly bit instances with seeded
+ or imported rows — the search is now genuinely case-insensitive
+ (`mode: 'insensitive'`), and `docs/ADMIN.md` no longer claims
+ "usernames are stored lowercase" as the reason it worked.
+ Verified by a new regression spec (`admin-audit-regressions.spec.ts`:
+ mixed-case search in both cases, the BYOK block, the 5-slot chip)
+ and the existing 7-test admin suite.
- **"Test video generation" answered "Unknown slot"** — the video
slot joined `SLOT_ENDPOINT` and the probe set. The admin console's
per-slot Test buttons (v0.16.3 A3) guard against a slot map that
diff --git a/docs/ADMIN.md b/docs/ADMIN.md
index ed44d44..632f9e1 100644
--- a/docs/ADMIN.md
+++ b/docs/ADMIN.md
@@ -56,10 +56,17 @@ is changed; the env always wins, and the badge says so.
- **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.
+- **Own API keys** (v0.23) is the BYOK adoption stat: distinct accounts
+ with at least one row in `UserAIProvider`, how many keys they stored,
+ and how many of the five capability slots those keys cover. Keys are
+ never shown — this is the same aggregate-only posture as the rest of
+ the page (no usernames ride along).
### Users
-- Search is a username substring (usernames are stored lowercase).
+- Search is a case-insensitive username substring. (Registration
+ lowercases usernames, but rows seeded or imported by other means may
+ carry mixed case — the search matches those too.)
- **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.
diff --git a/src/app/api/admin/overview/route.ts b/src/app/api/admin/overview/route.ts
index 9ac0e15..77aa26d 100644
--- a/src/app/api/admin/overview/route.ts
+++ b/src/app/api/admin/overview/route.ts
@@ -54,6 +54,8 @@ async function __canvix_get(req: NextRequest) {
aiByFeature,
recentUsers,
provider,
+ byokRows,
+ byokSlotRows,
] = await Promise.all([
db.user.count(),
db.design.count({ where: { deletedAt: null } }),
@@ -87,6 +89,19 @@ async function __canvix_get(req: NextRequest) {
select: { id: true, username: true, role: true, createdAt: true },
}),
providersSummary(),
+ // BYOK adoption (v0.23): who brought their own key. Distinct users
+ // with at least one UserAIProvider row, total provider rows, and
+ // per-slot coverage — the slots column is a CSV string ("text,vision"),
+ // so coverage is the count of rows whose CSV contains the slot name.
+ // Aggregate-only posture: usernames never ride along.
+ db.$queryRaw<{ users: number; providers: number }[]>`
+ SELECT COUNT(DISTINCT "userId")::int AS users, COUNT(*)::int AS providers
+ FROM "UserAIProvider"`,
+ db.$queryRaw<{ slot: string; n: number }[]>`
+ SELECT s.slot, COUNT(*)::int AS n FROM "UserAIProvider" p,
+ unnest(ARRAY['text','vision','image','imageEdit','video']) AS s(slot)
+ WHERE ',' || p.slots || ',' LIKE '%,' || s.slot || ',%'
+ GROUP BY s.slot`,
])
const dbLatencyMs = Date.now() - probeStart
@@ -137,6 +152,12 @@ async function __canvix_get(req: NextRequest) {
providerCount: provider.providerCount,
slotsSet: provider.slotsSet,
},
+ // v0.23 BYOK adoption — "how many users added their own API keys"
+ byok: {
+ users: byokRows[0]?.users ?? 0,
+ providers: byokRows[0]?.providers ?? 0,
+ slots: Object.fromEntries(byokSlotRows.map((r) => [r.slot, r.n])),
+ },
})
} catch (error) {
console.error('GET /api/admin/overview failed', error)
diff --git a/src/app/api/admin/users/route.ts b/src/app/api/admin/users/route.ts
index 9b133cf..3a2a92a 100644
--- a/src/app/api/admin/users/route.ts
+++ b/src/app/api/admin/users/route.ts
@@ -18,9 +18,13 @@ async function __canvix_get(req: NextRequest) {
if (!guard.ok) return guard.res
try {
- const q = (req.nextUrl.searchParams.get('q') ?? '').trim().toLowerCase().slice(0, 64)
+ // case-insensitive on purpose: usernames are stored as-typed, so a
+ // case-sensitive `contains` made every mixed-case username
+ // unfindable (searching "JohnDoe" or "johndoe" both missed) —
+ // mode: 'insensitive' is the honest fix, no lowercasing games.
+ const q = (req.nextUrl.searchParams.get('q') ?? '').trim().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 where = q ? { username: { contains: q, mode: 'insensitive' as const } } : {}
const [total, users] = await Promise.all([
db.user.count({ where }),
diff --git a/src/components/admin/ai-config.tsx b/src/components/admin/ai-config.tsx
index d2f4d83..97fedd3 100644
--- a/src/components/admin/ai-config.tsx
+++ b/src/components/admin/ai-config.tsx
@@ -493,7 +493,9 @@ export function AdminAiConfig() {
title="Model slots"
right={
<Chip tone={Object.values(view.providers.resolved).some((r) => r !== null) ? 'good' : 'neutral'}>
- {Object.values(view.providers.resolved).filter((r) => r !== null).length}/4 wired
+ {/* SLOT_INFO, not a literal — the v0.19 video slot made this
+ read "5/4 wired" until the count came from the source */}
+ {Object.values(view.providers.resolved).filter((r) => r !== null).length}/{SLOT_INFO.length} wired
</Chip>
}
>
diff --git a/src/components/admin/overview.tsx b/src/components/admin/overview.tsx
index f10fcba..c6fa7db 100644
--- a/src/components/admin/overview.tsx
+++ b/src/components/admin/overview.tsx
@@ -32,6 +32,12 @@ interface Overview {
aiByFeature: { feature: string; calls: number; ok: number }[]
recentUsers: { id: string; username: string; role: string; createdAt: string; admin: boolean }[]
provider: { configured: boolean; source: string | null; providerCount: number; slotsSet: number }
+ /** v0.23: BYOK adoption — users who added their own API keys */
+ byok: {
+ users: number
+ providers: number
+ slots: Record<string, number>
+ }
}
const SOURCE_LABEL: Record<string, string> = {
@@ -106,6 +112,18 @@ export function AdminOverview() {
: 'local features only'
}
/>
+ {/* v0.23 BYOK adoption: how many users brought their own key.
+ users = distinct accounts with ≥1 UserAIProvider row; the sub
+ line counts how many of the five slots user keys cover. */}
+ <StatCard
+ label="Own API keys"
+ value={data.byok.users > 0 ? fmt(data.byok.users) : 'none'}
+ sub={
+ data.byok.users > 0
+ ? `${fmt(data.byok.providers)} key${data.byok.providers === 1 ? '' : 's'} · ${Object.values(data.byok.slots).filter((n) => n > 0).length}/5 slots covered`
+ : 'no user-added keys (BYOK)'
+ }
+ />
</div>
<div className="grid gap-5 lg:grid-cols-2">
diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.ts
index 25890c2..eba7fac 100644
--- a/src/lib/ai/provider.ts
+++ b/src/lib/ai/provider.ts
@@ -313,16 +313,23 @@ export interface ProvidersSummary {
configured: boolean
source: SlotSource | null
providerCount: number
+ /** how many of the five capability slots actually RESOLVE (a stored
+ * binding whose provider vanished resolves to nothing — counting
+ * stored entries overstated the wiring; the console's "X/5 wired"
+ * is only honest if X is the resolved count) */
slotsSet: number
}
export async function providersSummary(): Promise<ProvidersSummary> {
const multi = await getProviders()
if (multi && multi.providers.length) {
+ const resolved = await Promise.all(
+ (['text', 'vision', 'image', 'imageEdit', 'video'] as const).map((slot) => resolveSlot(slot)),
+ )
return {
configured: true,
source: 'multi',
providerCount: multi.providers.length,
- slotsSet: Object.keys(multi.slots).length,
+ slotsSet: resolved.filter((r) => r !== null).length,
}
}
const text = await resolveSlot('text')
diff --git a/tests/e2e/admin-audit-regressions.spec.ts b/tests/e2e/admin-audit-regressions.spec.ts
new file mode 100644
index 0000000..b461671
--- /dev/null
+++ b/tests/e2e/admin-audit-regressions.spec.ts
@@ -0,0 +1,144 @@
+import { test, expect, type Browser } from '@playwright/test'
+import { createHash } from 'node:crypto'
+import { Client } from 'pg'
+
+// Admin console regression suite (post-audit, 2026-11-19):
+//
+// 1. user search finds MIXED-CASE usernames typed in any case — the
+// audit found the route lowercased the query while Prisma's
+// `contains` stayed case-sensitive, making every mixed-case
+// username unfindable (both "JohnDoe" and "johndoe" missed).
+// 2. the overview carries the BYOK adoption stat — how many users
+// added their own API keys (UserAIProvider), with per-slot
+// coverage (the slots column is CSV: "text,vision").
+// 3. the Model-slots card counts against 5 slots, not the stale
+// v0.16-era 4 (video joined in v0.19 — the chip read "5/4 wired").
+//
+// Zero registrations: fixtures seeded straight into the DB (the
+// admin-console.spec.ts pattern).
+
+const ADMIN = { id: 'u_e2e_admin_a1', username: 'e2e_admin_a1', token: 'e2e-admin-token-a1' }
+const MIXED = { id: 'u_e2e_mixedsearch', username: 'JohnDoe_MixedCase' }
+
+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()
+ // the shared admin fixture (created by admin-console.spec.ts when it
+ // runs first; ensure it exists for standalone runs too)
+ const admin = await client.query(`SELECT "id" FROM "User" WHERE "username" = $1`, [ADMIN.username])
+ const adminId = (admin.rows[0]?.['id'] as string | undefined) ?? ADMIN.id
+ if (admin.rows.length === 0) {
+ await client.query(
+ `INSERT INTO "User" ("id", "username", "passwordHash", "role", "createdAt")
+ VALUES ($1, $2, 'seed-no-login', 'admin', now())`,
+ [ADMIN.id, ADMIN.username]
+ )
+ await client.query(
+ `INSERT INTO "Session" ("id", "userId", "createdAt", "expiresAt")
+ VALUES ($1, $2, now(), now() + interval '2 hours')`,
+ [sessionId(ADMIN.token), ADMIN.id]
+ )
+ } else {
+ // refresh the session row regardless (expiry from older runs)
+ await client.query(
+ `INSERT INTO "Session" ("id", "userId", "createdAt", "expiresAt")
+ VALUES ($1, $2, now(), now() + interval '2 hours')
+ ON CONFLICT ("id") DO UPDATE SET "expiresAt" = now() + interval '2 hours'`,
+ [sessionId(ADMIN.token), adminId]
+ )
+ ADMIN.id = adminId
+ }
+ // the mixed-case search fixture + one BYOK provider row for it
+ await client.query(`DELETE FROM "UserAIProvider" WHERE "userId" = $1`, [MIXED.id])
+ await client.query(`DELETE FROM "User" WHERE "username" = $1`, [MIXED.username])
+ await client.query(
+ `INSERT INTO "User" ("id", "username", "passwordHash", "role", "createdAt")
+ VALUES ($1, $2, 'seed-no-login', 'user', now())`,
+ [MIXED.id, MIXED.username]
+ )
+ await client.query(
+ `INSERT INTO "UserAIProvider" ("id", "userId", "label", "baseUrl", "apiKey", "slots", "models", "createdAt", "updatedAt")
+ VALUES ('byok_e2e_1', $1, 'e2e own key', 'https://api.example.com/v1', 'sk-e2e', 'text,vision', '{}', now(), now())`,
+ [MIXED.id]
+ )
+})
+
+test.afterAll(async () => {
+ if (client) {
+ await client.query(`DELETE FROM "UserAIProvider" WHERE "userId" = $1`, [MIXED.id])
+ await client.query(`DELETE FROM "User" WHERE "username" = $1`, [MIXED.username])
+ await client.end().catch(() => {})
+ }
+})
+
+async function adminContext(browser: Browser) {
+ const ctx = await browser.newContext()
+ await ctx.addCookies([
+ { name: 'canvix_session', value: ADMIN.token, url: process.env.BASE_URL ?? 'http://localhost:3000' },
+ ])
+ return ctx
+}
+
+test.describe('admin console — audit regressions', () => {
+ test('user search finds mixed-case usernames in any case', async ({ browser }) => {
+ const ctx = await adminContext(browser)
+ const page = await ctx.newPage()
+ await page.goto('/admin/users')
+
+ // type the username in LOWER case — the bug: route lowercased the
+ // query but `contains` matched case-sensitively → 0 rows
+ const box = page.getByLabel('Search users by username')
+ await box.fill('johndoe')
+ await expect(page.locator('tr', { hasText: MIXED.username })).toBeVisible({ timeout: 10_000 })
+
+ // and in the EXACT mixed case — also broken before (lowercased away)
+ await box.fill('JohnDoe_MixedCase')
+ await expect(page.locator('tr', { hasText: MIXED.username })).toBeVisible()
+
+ // the API agrees in both directions
+ const lower = await ctx.request.get('/api/admin/users?q=johndoe')
+ expect(((await lower.json()) as { total: number }).total).toBeGreaterThanOrEqual(1)
+ const upper = await ctx.request.get('/api/admin/users?q=JOHNDOE')
+ expect(((await upper.json()) as { total: number }).total).toBeGreaterThanOrEqual(1)
+ await ctx.close()
+ })
+
+ test('overview reports BYOK adoption — users with their own API keys', async ({ browser }) => {
+ const ctx = await adminContext(browser)
+
+ // the API block: the seeded fixture counts (≥1 user, ≥1 provider,
+ // text+vision covered by the CSV parse)
+ const res = await ctx.request.get('/api/admin/overview')
+ expect(res.status()).toBe(200)
+ const byok = ((await res.json()) as { byok: { users: number; providers: number; slots: Record<string, number> } }).byok
+ expect(byok.users).toBeGreaterThanOrEqual(1)
+ expect(byok.providers).toBeGreaterThanOrEqual(1)
+ expect(byok.slots.text ?? 0).toBeGreaterThanOrEqual(1)
+ expect(byok.slots.vision ?? 0).toBeGreaterThanOrEqual(1)
+
+ // the stat card renders it on the page (label <p> → parent StatCard)
+ const page = await ctx.newPage()
+ await page.goto('/admin')
+ await expect(page.getByText('Own API keys', { exact: true })).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByText(/keys? · [0-5]\/5 slots covered/)).toBeVisible()
+ await ctx.close()
+ })
+
+ test('the Model-slots card counts against 5 slots (video included)', async ({ browser }) => {
+ const ctx = await adminContext(browser)
+ const page = await ctx.newPage()
+ await page.goto('/admin/ai')
+ // whatever the wiring state, the chip denominator is 5 — never "5/4"
+ const chip = page.getByText(/\/5 wired/)
+ await expect(chip.first()).toBeVisible({ timeout: 15_000 })
+ const text = await chip.first().textContent()
+ expect(text).toMatch(/^[0-5]\/5 wired$/)
+ await ctx.close()
+ })
+})