Skip to Content
Slloy Docs
Auth, Admin & Security

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.html contains only the SPA mount root, <meta name="robots" content="noindex, nofollow">, and hashed entry assets injected by tools/build.mts.
  • Worker Routing:
    • GET /admin and GET /admin/* serve admin.html with Cache-Control: no-store and X-Robots-Tag: noindex, nofollow.
    • Legacy GET /admin.html returns a 302 redirect to /admin.
  • Sub-Routes:
    • /admin (Overview + opsHealth monitor + DAT-01 preset funnel analytics)
    • /admin/users (Search, pagination, read-only contact info, ban/unban with automatic Stripe subscription cancellation via cancelSubscriptionForBan)
    • /admin/staff (Super-admin staff creation, role assignment, enable/disable)
    • /admin/generations (Filter by user_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 (Live app_settings video spending caps and feature switches)

[!IMPORTANT] Decommissioned High-Risk Admin Actions: Following the 2026-09-30 backend 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 GuardPermitted Modules & Operations
reviewerrequireAdminCommunity Moderation Only: Review pending public showcase submissions (/admin/community), approve/reject works, and handle user abuse reports.
operatorrequireOperatorAll 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)requireSuperAll 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 12 characters (WEAK_PASSWORD if < 12), hashed with bcrypt (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') increments token_version in staff_accounts (instantly invalidating any existing JWT) and records the actor, target, and state transition in staff_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:

  1. IP-Level Rate Limit (rate_limits table, scope: "admin-login"):
    • Caps login attempts at 10 attempts per 15 minutes per client IP (cf-connecting-ip).
    • Stops attackers who rotate usernames against a single IP.
  2. Username-Level Lockout (staff_login_attempts table, adminAuth.attempt(username)):
    • Tracks consecutive failed logins per username in PostgreSQL.
    • After 5 failed attempts within 15 minutes, the 6th attempt immediately returns HTTP 429 LOCKED ("失败次数过多,请 15 分钟后再试") without running bcrypt.compare.
    • Disabled accounts (status !== "active") and wrong passwords return the exact same HTTP 401 BAD_CREDENTIALS response to prevent username/password oracle leaks.
    • A successful login calls adminAuth.clear(username) to reset the failure counter and updates last_login_at (markStaffLogin).

4. Financial Metrics in /admin/cost: paidCny vs. estimateCny

Prior to 2026-09-29, the cost dashboard had two critical accounting bugs:

  1. It treated Stripe orders.amount_cents (USD cents) directly as RMB fen (cents / 100), overstating cash revenue by ~7x.
  2. 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 FieldFormulaAccounting Meaning
revenue.paidCny (revenue.realCny)SUM(orders.amount_cents / 100) * FX_USD_CNY (7.15) for settled orders in windowActual Cash Revenue (RMB). The sole revenue figure used to compute gross profit (grossCny).
revenue.netCreditsSUM(generations.credits_charged - generations.refunded)Net credits consumed by completed/failed generations in the window.
revenue.estimateCnyrevenue.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.creditedCnyrevenue.netCredits * CREDIT_CNY (¥0.011)Historical nominal cost anchor reference.
cost.totalCnycost.image.cny + cost.video.cnyActual 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.grossCnyrevenue.paidCny - cost.totalCnyNet 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 has cny / (credits * BASE_UNIT_CNY) > 1.0 (upstream cost exceeds pro_monthly credit valuation).
  • TOKENS_UNMEASURED / TWO_KINDS_OF_VIDEO_COST (warn): Video records mix measured usage_tokens with unmeasured est_tokens estimates.
  • PRICE_ESTIMATED (warn): Active catalog includes models whose unit price in pricing.ts is still marked estimated: 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; returns HTTP 409 STALE_ORDER if the ID set does not match the current database state, and calls promptsChanged() to invalidate the 60-second isolate cache immediately.
  • Batch Update (POST /api/admin/prompts/batch): Updates status (published / archived), use, family, or season across 1..200 prompt IDs in a single transaction. If status: "published" is requested, every target record is validated against publishProblem(merged) (including all 6 compliance redlines); if any record fails validation, the entire batch rolls back with HTTP 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.

On this page