Admin SPA, 3-Tier RBAC, Cost Accounting & Moderation
Architecture of the /admin SPA, 3-tier staff RBAC, DB-backed login rate limiting, paidCny vs. estimateCny financial reporting, prompt batch ops, and share privacy.
The Slloy Administration Console (/admin) is a standalone React SPA (frontend/admin/) built with shadcn/ui (Radix), Tailwind CSS, and TanStack Router/Query. It is completely isolated from the public site's bundle, routing table, sitemap, and i18n dictionary build.
1. /admin SPA Architecture & Entry Point
- HTML Shell:
admin.htmlcontains only the SPA mount root,<meta name="robots" content="noindex, nofollow">, and hashed entry assets injected bytools/build.mts. - Worker Routing:
GET /adminandGET /admin/*serveadmin.htmlwithCache-Control: no-storeandX-Robots-Tag: noindex, nofollow.- Legacy
GET /admin.htmlreturns a302redirect to/admin.
- Sub-Routes:
/admin(Overview +opsHealthmonitor +DAT-01preset funnel analytics)/admin/users(Search, pagination, read-only contact info, ban/unban with automatic Stripe subscription cancellation viacancelSubscriptionForBan)/admin/staff(Super-admin staff creation, role assignment, enable/disable)/admin/generations(Filter byuser_id,kind,status, media preview)/admin/community(Prompt library CRUD/batch ops, public showcase review queue, abuse reports)/admin/cost(Cash revenue vs. channel cost, margin audit, daily credit valuation chart)/admin/settings(Liveapp_settingsvideo spending caps and feature switches)
[!IMPORTANT] Decommissioned High-Risk Admin Actions: Following the
2026-09-30backend security audit, manual credit adjustment and user email/phone modification endpoints and UI controls have been permanently removed from/admin. Credits can only enter a user account via signup, daily check-in, verified Stripe webhooks, or automated generation refunds.
2. 3-Tier Role-Based Access Control (RBAC)
Staff accounts live in staff_accounts (id, username, password_hash, role, status, token_version). Permissions are enforced on every /api/admin/* route by server/src/http/middleware/admin.ts (requireAdmin, requireOperator, requireSuper) and re-validated on window focus via GET /api/admin/session:
Role (StaffRole) | Middleware Guard | Permitted Modules & Operations |
|---|---|---|
reviewer | requireAdmin | Community Moderation Only: Review pending public showcase submissions (/admin/community), approve/reject works, and handle user abuse reports. |
operator | requireOperator | All reviewer permissions plus: Overview & preset funnel analytics (/overview, /analytics), User search & ban/unban (/users), Generation logs (/generations), Prompt Library creation/editing/reordering/batch updates (/prompts), and Email domain blocklist (/blocked-domains). |
admin (Super Admin) | requireSuper | All operator permissions plus: Financial cost & revenue dashboard (/cost), Runtime app_settings safeguards (/settings), and Staff account management (/staff). |
Staff Governance Rules
- Password Policy: Initial staff passwords must be at least
12characters (WEAK_PASSWORDif< 12), hashed withbcrypt(cost = 10). - Self-Lockout Prevention (
staffTarget): A super-admin (admin) cannot change their own role (CANNOT_CHANGE_SELF_ROLE) or disable their own account (CANNOT_DISABLE_SELF), guaranteeing the last super-admin can never lock themselves out. - Immediate Session Revocation & Audit Log: Disabling a staff account (
status = 'disabled') incrementstoken_versioninstaff_accounts(instantly invalidating any existing JWT) and records the actor, target, and state transition instaff_audit_log.
3. Dual-Layer DB-Backed Login Rate Limiting (POST /api/admin/login)
Because Cloudflare Workers run across multiple stateless isolates, in-memory Map rate limiters are ineffective. /api/admin/login enforces two independent database-backed locks before verifying credentials:
- IP-Level Rate Limit (
rate_limitstable,scope: "admin-login"):- Caps login attempts at
10attempts per15minutes per client IP (cf-connecting-ip). - Stops attackers who rotate usernames against a single IP.
- Caps login attempts at
- Username-Level Lockout (
staff_login_attemptstable,adminAuth.attempt(username)):- Tracks consecutive failed logins per
usernamein PostgreSQL. - After
5failed attempts within15minutes, the6thattempt immediately returnsHTTP 429 LOCKED("失败次数过多,请 15 分钟后再试") without runningbcrypt.compare. - Disabled accounts (
status !== "active") and wrong passwords return the exact sameHTTP 401 BAD_CREDENTIALSresponse to prevent username/password oracle leaks. - A successful login calls
adminAuth.clear(username)to reset the failure counter and updateslast_login_at(markStaffLogin).
- Tracks consecutive failed logins per
4. Financial Metrics in /admin/cost: paidCny vs. estimateCny
Prior to 2026-09-29, the cost dashboard had two critical accounting bugs:
- It treated Stripe
orders.amount_cents(USD cents) directly as RMB fen (cents / 100), overstating cash revenue by~7x. - It added
netCredits * BASE_UNIT_CNY(credit valuation) on top of paid order cash (paidCny), double-counting every purchased credit once when bought and again when spent.
GET /api/admin/cost (server/src/http/routes/admin.ts) strictly separates Cash Revenue, Internal Credit Valuation, and Real Upstream Cost:
| Metric Field | Formula | Accounting Meaning |
|---|---|---|
revenue.paidCny (revenue.realCny) | SUM(orders.amount_cents / 100) * FX_USD_CNY (7.15) for settled orders in window | Actual Cash Revenue (RMB). The sole revenue figure used to compute gross profit (grossCny). |
revenue.netCredits | SUM(generations.credits_charged - generations.refunded) | Net credits consumed by completed/failed generations in the window. |
revenue.estimateCny | revenue.netCredits * BASE_UNIT_CNY (¥0.0571) | Internal Credit Consumption Valuation (valued at pro_monthly benchmark unit price, including free signup/check-in credits burned). Displayed for reference and daily bar charts only; never added to paidCny. |
revenue.creditedCny | revenue.netCredits * CREDIT_CNY (¥0.011) | Historical nominal cost anchor reference. |
cost.totalCny | cost.image.cny + cost.video.cny | Actual Upstream Channel Cost (RMB). Uses row-level cost_cny, measured usage_tokens (pricing.videoCny), or est_tokens fallback. (pending tasks count as 0 until settled). |
margin.grossCny | revenue.paidCny - cost.totalCny | Net Cash Gross Profit (RMB). Free trial compute cost is absorbed here, reflecting true P&L. |
Automated Cost Dashboard Alerts (alerts)
/api/admin/cost automatically surfaces actionable banners when:
MARGIN_NEGATIVE(bad):cost.totalCny > revenue.paidCny(cash cost exceeds cash revenue over the selected window).VIDEO_INVERSION(bad/warn): Any video model hascny / (credits * BASE_UNIT_CNY) > 1.0(upstream cost exceedspro_monthlycredit valuation).TOKENS_UNMEASURED/TWO_KINDS_OF_VIDEO_COST(warn): Video records mix measuredusage_tokenswith unmeasuredest_tokensestimates.PRICE_ESTIMATED(warn): Active catalog includes models whose unit price inpricing.tsis still markedestimated: true.
5. Prompt Batch Operations & Share Privacy (shareLibrary.ts)
Prompt Batch Operations & Reordering
- Atomic Reordering (
POST /api/admin/prompts/reorder): Accepts the full ordered array of prompt IDs; returnsHTTP 409 STALE_ORDERif the ID set does not match the current database state, and callspromptsChanged()to invalidate the 60-second isolate cache immediately. - Batch Update (
POST /api/admin/prompts/batch): Updatesstatus(published/archived),use,family, orseasonacross1..200prompt IDs in a single transaction. Ifstatus: "published"is requested, every target record is validated againstpublishProblem(merged)(including all 6 compliance redlines); if any record fails validation, the entire batch rolls back withHTTP 400.
Private Share Page Data Projection (server/src/shareLibrary.ts)
When a user generates a share link (/s/<token> where SHARE_TOKEN_RE = /^[A-Za-z0-9_-]{16,32}$/), createShareReader(repo) projects the generations row into a strict public whitelist (PublicShare: mediaType, src, ogImage, ogVideo, ogW, ogH, canonical).
Privacy Redline: shareLibrary.ts never exposes prompt, generation.id, user_id, or task_id in the /api/share/:token JSON or SSR dehydrated HTML.
Customer Authentication, Registration Guard & Session Security
Strict separation between customer Better Auth and staff_accounts, disposable email and DoH MX registration guards, Turnstile verification, and CSRF/session protection.
Cloudflare Access Zero Trust & Edge JWT Isolation
Dual-layer Cloudflare Access architecture (Zero Trust edge gate + Worker RS256 JWT verification) protecting staging.slloy.com, /admin, and docs.slloy.com.