Platform: Multi-tenant Enterprise SaaS — Central Hub with Slug-Based Tenant Routing Domain:
burhan.ainux.onlineStack: Nuxt 4 + Tailwind CSS + Supabase (PostgreSQL) + Cloudflare Pages Languages: Arabic (primary) / English Status: Hub→Org Grid, Tenant Landing Redesign (FAB Speed Dial, Gold Hero, 8/4 Grid), Audio Content Type
- System Design Blueprint
- Database & RLS Manifest
- Nuxt 4 Directory Structure
- Routing & Middleware Strategy
- i18n & Multilingual Architecture
- Video Fallback Engine
- Premium Gating Layer
- UI Design System — Ainux Signature
- Edge Deployment (Cloudflare)
- Development Cheat Sheet
- Organization Dashboard
- Floating Sidebar — Interaction Model
- Entity CRUD — Full Lifecycle
- Rich Text Editor
- Caching & Locale Path Strategy
- i18n Audit — Rule Enforcement
- Migration History
- Series / Courses Management
- FAB + Side Drawer Navigation Pattern
- Supabase Schema Reference
- Digital Intellectual Observatory
- Decentralized AI (DeAI) Architecture & Job Lifecycle
- Multi-Tenant Subscriptions & Entitlements Engine
- BYOK & Cryptographic Subsystem
- Atomic Tenant Provisioning Engine & Auth OTP Gate
- Decoupled Editorial Generation Engine & Golden Closure Rule
- Cross-Tenant Public Series Access & RTL UI Hardening
Super Admin (super_admin) — Manages the Hub, all orgs, all entities
└── Org Owner (owner) — Owns a specific organization, full access
└── Manager (manager) — Content manager for an entire organization
└── Member (member) — Basic authenticated user, read-only access
Managed via a PostgreSQL user_role ENUM:
CREATE TYPE user_role AS ENUM ('super_admin', 'owner', 'manager', 'member');burhan.ainux.online
├── / → Hub: global public entities feed
├── /:org_slug → Tenant: isolated org-specific view
└── /:org_slug/branches/:id → Tenant: isolated branch detail
- Hub fetches all orgs via
/api/orgs(with content counts) and renders a glassmorphic grid of organization cards - Tenant routes are locked to their
org_slugvia global middleware (org.global.ts) - RLS enforces row-level tenant isolation at the database level — every policy is scoped to
organization_id
| Table | Purpose | Key Fields |
|---|---|---|
organizations |
Tenant/brand owner | id UUID PK, org_slug TEXT UNIQUE, settings JSONB |
branches |
Modular sub-sections | id UUID PK, organization_id FK, name JSONB {ar,en}, module_type ENUM |
profiles |
Extends auth.users | id UUID PK FK→auth.users, organization_id FK, role user_role ENUM |
entities |
Dynamic content engine | id UUID PK, branch_id FK, organization_id FK, series_id FK→series NULL, sort_order INT, content_type TEXT CHECK('video','article','audio'), title JSONB {ar,en}, content JSONB {ar,en}, is_public_to_hub BOOLEAN, video fields, audio fields, premium fields |
series |
Course/series grouping | id UUID PK, organization_id FK, branch_id FK, title JSONB {ar,en}, description JSONB {ar,en}, cover_url TEXT, is_active BOOLEAN |
video_id TEXT, -- ID from the video platform
primary_source TEXT DEFAULT 'youtube', -- 'youtube' | 'cloudflare_stream'
fallback_source TEXT, -- 'cloudflare_stream' | etc.
fallback_url TEXT, -- Generic fallback URL if sources failcontent_type TEXT DEFAULT 'article', -- 'video' | 'article' | 'audio'
audio_url TEXT, -- External streaming link for podcast/audio
audio_file TEXT, -- Path to .mp3 in organization_assets bucketThe content_type column classifies every entity. When content_type = 'audio':
video_idandprimary_sourceare NULL- Either
audio_url(external streaming) oraudio_file(self-hosted MP3) must be set - The UI renders an audio player with a dark waveform visual + purple/coral badge
- Storage path convention:
{orgId}/audio/{uuid}.mp3
is_premium BOOLEAN DEFAULT false,
price DECIMAL(10,2), -- NULL if free{
"ar": "...",
"en": "..."
}Applied to: branches.name, profiles.full_name, entities.title, entities.content
On every auth.users INSERT, a trigger (handle_new_user()) auto-creates a corresponding profiles row with role = 'member'. No manual profile creation needed.
| Table | Policy | Scope |
|---|---|---|
organizations |
SELECT | Everyone (true) |
organizations |
INSERT/UPDATE/DELETE | super_admin only |
branches |
SELECT | Org members + super_admin |
branches |
INSERT/UPDATE | Owner, manager, super_admin |
branches |
DELETE | Owner, super_admin |
profiles |
SELECT | Own profile + org members + super_admin |
profiles |
UPDATE | Self + org owner + super_admin |
entities |
SELECT (Hub) | is_public_to_hub = true AND is_premium = false |
entities |
SELECT (Org) | Org members see org entities; basic members blocked from premium; owners/managers see all |
entities |
SELECT (Super) | super_admin sees everything |
entities |
INSERT | Owner, manager, super_admin |
entities |
UPDATE | Owner, manager (org-wide), super_admin |
entities |
DELETE | Owner, manager, super_admin |
After code review, the manager role is organization-wide, not branch-specific. The profiles table has no assigned_branch_id. The UPDATE policy was simplified from:
-- OLD: misleading branch-level separation
EXISTS (... role = 'manager') OR EXISTS (... role = 'owner')
-- NEW: honest org-wide scope
EXISTS (... role IN ('owner', 'manager'))The original entities_select_public_hub policy was:
USING (is_public_to_hub = true)This leaked premium content to unauthenticated users. Fixed to:
USING (is_public_to_hub = true AND is_premium = false)The entities_select_org_member policy also nests a premium check: basic members see only is_premium = false, while owners/managers bypass the gate.
idx_organizations_org_slug ON organizations (org_slug)
idx_branches_organization_id ON branches (organization_id)
idx_profiles_organization_id ON profiles (organization_id)
idx_entities_branch_id ON entities (branch_id)
idx_entities_organization_id ON entities (organization_id)
idx_entities_public_to_hub ON entities (is_public_to_hub) WHERE is_public_to_hub = true
idx_entities_premium ON entities (is_premium)
idx_entities_series_id ON entities (series_id) WHERE series_id IS NOT NULL
idx_entities_series_sort ON entities (series_id, sort_order, created_at) WHERE series_id IS NOT NULL
idx_series_organization_id ON series (organization_id)burhan/
├── app/ ← srcDir (Nuxt 4 convention)
│ ├── app.vue ← Root: head, fonts, layout wrapper
│ ├── assets/css/main.css ← Tailwind directives + glass/gradient utilities
│ ├── i18n.config.ts ← vue-i18n config (imports JSONs, replaces langDir)
│ ├── layouts/
│ │ ├── default.vue ← Ainux navbar + footer + mobile menu
│ │ └── dashboard.vue ← Sidebar layout with glassmorphic nav
│ ├── pages/
│ │ ├── index.vue ← Hub: org grid with glassmorphic cards (FAB speed dial, layout: false)
│ │ ├── login.vue ← Email/password sign-in form
│ │ ├── signup.vue ← 2-step: account → org creation
│ │ ├── dashboard/
│ │ │ ├── index.vue ← Stats grid (videos, branches, revenue, subs)
│ │ │ ├── branches.vue ← Branch CRUD (419 lines)
│ │ │ ├── entities/
│ │ │ │ ├── index.vue ← Entity list + inline modal CRUD (820 lines)
│ │ │ │ ├── [id].vue ← Article edit page with RichTextEditor (343 lines)
│ │ │ │ └── new.vue ← Article create page (315 lines)
│ │ │ └── series/
│ │ │ ├── index.vue ← Grid list of all series with cover cards (184 lines)
│ │ │ ├── [id].vue ← Detail workspace: episodes, reorder, add/remove (563 lines)
│ │ │ └── new.vue ← Create series with cover upload & bilingual form (315 lines)
│ │ └── [org_slug]/
│ │ ├── index.vue ← Tenant: FAB speed dial, gold-gradient hero, 8/4 asymmetric grid (series+activity)
│ │ └── branches/[branch_id].vue ← Branch detail with featured video
│ ├── middleware/
│ │ ├── org.global.ts ← Global: validates org_slug, 404 if missing, fallback to profile org
│ │ └── dashboard-auth.ts ← Route guard: blocks member/unauthenticated from /dashboard
│ ├── components/
│ │ ├── hub/
│ │ │ ├── EntityCard.vue ← Glass card with localized title/content
│ │ │ └── CategorySection.vue ← Section with grid + loading/empty states
│ │ ├── tenant/
│ │ │ ├── OrgHeader.vue ← Dynamic org name + logo + branch badges
│ │ │ ├── BranchNav.vue ← Branch filter buttons with active state
│ │ │ └── VideoPlayer.vue ← Multi-source fallback state machine
│ │ ├── premium/
│ │ │ └── PremiumGate.vue ← Lock overlay with blurred preview
│ │ ├── dashboard/
│ │ │ ├── FloatingSidebar.vue ← 60px→280px expandable, pin@dblclick (223 lines)
│ │ │ └── RichTextEditor.vue ← Tiptap-based WYSIWYG with full toolbar (446 lines)
│ │ └── ui/
│ │ ├── Button.vue ← 4 variants, 3 sizes, loading state
│ │ ├── GlassCard.vue ← Glassmorphic container
│ │ ├── Avatar.vue ← Image/fallback initials
│ │ └── Badge.vue ← Variants: default, premium, success, warning, info
│ ├── composables/
│ │ ├── useOrg.ts ← Fetch + cache org by slug
│ │ ├── useEntities.ts ← CRUD entities via Supabase
│ │ ├── useUser.ts ← Auth + profile + role helpers
│ │ └── useLocale.ts ← i18n bridge + extractLocalized()
│ ├── i18n/
│ │ ├── ar.json ← Arabic UI (~200 keys)
│ │ └── en.json ← English UI (~200 keys)
│ └── types/database.ts ← Full Supabase type definitions
├── server/
│ ├── utils/supabase.ts ← Server client + admin factories
│ ├── api/
│ │ ├── auth/register-tenant.post.ts ← Service-role: creates org + branch + owner profile
│ │ ├── orgs/index.ts ← GET all orgs with content counts (entities, branches, series)
│ │ ├── orgs/[slug].ts ← GET org with branches
│ │ └── entities/public.ts ← GET hub feed (public, non-premium)
├── supabase/migrations/
│ ├── 00001_initial_schema.sql
│ ├── 00002_fix_branches_rls.sql
│ ├── 00003_fix_profiles_rls_recursion.sql
│ ├── 00004_add_branch_slug_is_active.sql
│ ├── 00005_storage_bucket_policies.sql
│ ├── 00006_series_and_playlists.sql
│ └── 00007_add_content_type_audio.sql
├── nuxt.config.ts
├── tailwind.config.ts
├── tsconfig.json
├── package.json
└── .env
nuxt.config.ts → tailwindcss.configPath: './tailwind.config.ts'
→ tailwindcss.cssPath: './app/assets/css/main.css'
| Path | Page | Guard |
|---|---|---|
/ |
app/pages/index.vue |
None (Hub — org grid, layout: false) |
/login |
app/pages/login.vue |
None |
/signup |
app/pages/signup.vue |
None |
/dashboard |
app/pages/dashboard/index.vue |
dashboard-auth.ts |
/dashboard/branches |
app/pages/dashboard/branches.vue |
dashboard-auth.ts |
/dashboard/entities |
app/pages/dashboard/entities/index.vue |
dashboard-auth.ts |
/dashboard/entities/new |
app/pages/dashboard/entities/new.vue |
dashboard-auth.ts |
/dashboard/entities/:id |
app/pages/dashboard/entities/[id].vue |
dashboard-auth.ts |
/dashboard/series |
app/pages/dashboard/series/index.vue |
dashboard-auth.ts |
/dashboard/series/new |
app/pages/dashboard/series/new.vue |
dashboard-auth.ts |
/dashboard/series/:id |
app/pages/dashboard/series/[id].vue |
dashboard-auth.ts |
/:org_slug |
app/pages/[org_slug]/index.vue |
org.global.ts (FAB speed dial, layout: false) |
/:org_slug/branches/:branch_id |
app/pages/[org_slug]/branches/[branch_id].vue |
org.global.ts |
Route with :org_slug param
→ fetchOrg(slug) via $fetch('/api/orgs/:slug')
→ Error & path is dashboard/auth? → skip (return early)
→ Error & user has profile.org? → fallback: load org from profile
→ Error & no fallback? → throw fatal 404
→ Success? → useHead({ title: org.name, canonical link })
→ Continue rendering
The middleware:
- Public route bypass:
/login,/signup,/dashboardare matched byisPublicRoute()and skipped immediately - Caches the org in
useState('org')so subsequent navigations to the same org skip the fetch - Is idempotent —
useOrg().fetchOrg()returns early iflastSlugmatches - Fallback resolution: If the URL slug fails (wrong org or missing), falls back to fetching the authenticated user's
organization_idfromprofilesand loading that org instead - Is
fatal: true— ensures the error page renders cleanly with zero partial org state
/dashboard route
→ useSupabaseUser() exists?
→ NO → navigateTo('/login')
→ YES → fetch profile.role from DB
→ role === 'member' or null? → navigateTo('/')
→ role === 'owner'|'manager'|'super_admin'? → pass
Applied via definePageMeta({ middleware: 'dashboard-auth' }) in /dashboard/index.vue. Protects all dashboard sub-routes from unauthorized access.
Signup (/signup): Two-step glassmorphic form:
- Account step: Full name, email, password, confirm password
- Organization step: Org name + URL-friendly slug (auto-generated from name)
On submit:
supabase.auth.signUp(email, password)
→ data.session exists? (email confirmation OFF)
→ YES → POST /api/auth/register-tenant with access_token
→ Server verifies JWT via admin.auth.getUser(accessToken)
→ Inserts organizations row (service role bypasses RLS)
→ Inserts default branch (module_type: 'content')
→ Updates profiles row: role='owner', organization_id=org.id
→ Returns { org, branch }
→ Client: navigateTo('/' + org.org_slug)
→ NO → Show "verify email" message
Login (/login): Single-step form with auth.signInWithPassword(). On success → navigateTo('/').
Server route POST /api/auth/register-tenant:
- Accepts
{ accessToken, orgName, orgSlug }in body - Uses
getSupabaseAdmin()(service role key) for all DB operations - Verifies JWT via
admin.auth.getUser(accessToken)— no cookie/session dependency - Atomic waterfall: org → branch → profile. Each step validates
?.idbefore proceeding - Slug uniqueness enforced with 409 Conflict on duplicate
- Slug sanitized: lowercase,
/[^a-z0-9-]/gstripped, min 2 chars
Set dynamically per tenant in the middleware:
useHead({
link: [{ rel: 'canonical', href: `https://burhan.ainux.online/${org.org_slug}` }],
})The i18n module switched from the legacy langDir/lazy/file approach to the vueI18n config file approach to eliminate persistent ../i18n/i18n/ double-path build artifacts.
In nuxt.config.ts:
i18n: {
restructureDir: false, // Stops module from resolving inside project-root/i18n/
locales: [
{ code: 'ar', iso: 'ar-EG', dir: 'rtl' }, // No `file` key — messages are in vueI18n config
{ code: 'en', iso: 'en-US', dir: 'ltr' },
],
defaultLocale: 'ar',
strategy: 'prefix_except_default',
vueI18n: './app/i18n.config.ts', // Path to vue-i18n config (relative to project root)
}In app/i18n.config.ts:
import ar from './i18n/ar.json'
import en from './i18n/en.json'
export default defineI18nConfig(() => ({
legacy: false,
locale: 'ar',
messages: { ar, en },
}))Critical: restructureDir: false — Without this, the module defaults to restructureDir: "i18n" and resolves vueI18n relative to /project-root/i18n/ instead of the project root, making the file unfindable and producing the warning:
Vue I18n configuration file not found in /project-root/i18n. Skipping...
Do NOT use langDir + lazy + file — These were the root cause of the ../i18n/i18n/ar.json double-path bug. The .nuxt/i18n.options.mjs virtual module baked the absolute resolve(__dirname, 'app/i18n') path, which the module then double-resolved relative to .nuxt/ (resulting in ../i18n/i18n/). Even after removing the absolute path and switching to langDir: 'i18n/', the stale .nuxt/ cache persisted the double-path. Full rm -rf .nuxt was required after every config change during debugging.
Browser detection removed — detectBrowserLanguage block was removed to simplify the configuration. Locale is set via URL prefix only (prefix_except_default).
bundle.optimizeTranslationDirective deprecation — The module emits a deprecation warning about this option. It was removed from config per the module's recommendation to stop using file-based lazy loading entirely.
The critical function that bridges the database's { ar, en } JSONB structure to the UI:
// app/composables/useLocale.ts
function extractLocalized<T = string>(
jsonb: LocalizedJson<T> | null | undefined,
fallback: T | null = null
): T | null {
if (!jsonb) return fallback
return jsonb[currentLocale.value] ?? jsonb.en ?? fallback ?? null
}Resolution chain: currentLocale → en → fallback → null
Usage pattern:
const title = extractLocalized<string>(entity.title, 'Untitled')
// Returns entity.title.ar on Arabic site
// Returns entity.title.en on English site (or fallback)
// Returns 'Untitled' if both are null- Every visual text in
<template>uses$t('key')— with 2 exceptions:- Content-language placeholders (e.g., "عنوان المقال..." is always Arabic regardless of UI locale)
- Format examples (e.g.,
placeholder="0.00")
- Every DB-origin text passes through
extractLocalized()— no raw.ar/.enaccess - Locale switching (
toggleLocale()) updates<html dir>,<html lang>, and CSS direction class simultaneously - See §16 for full audit of ~22 hardcoded strings that were converted to i18n
The navbar breadcrumb arrow flips with locale:
<path v-if="currentLocale === 'ar'" d="M9 5l7 7-7 7" /> <!-- points right -->
<path v-else d="M15 19l-7-7 7-7" /> <!-- points left -->| Priority | Source | How |
|---|---|---|
| 1° | YouTube | https://www.youtube.com/embed/{videoId}?autoplay=1&rel=0&playsinline=1 |
| 2° | Cloudflare Stream | https://iframe.videodelivery.net/{videoId}?autoplay=true |
| 3° | Generic fallback | Direct fallback_url |
┌──────────────────────────────────────────────┐
│ │
∨ │
[no_video] ← onMounted → [loading] ── iframe load success ──→ [playing]
│ ↑
│ 10s timeout │
∨ │
[primary_error] [retry]
/ \ ↑
has_fallback no_fallback │
│ │ │
∨ └──── stay on screen ──────┘
[loading_fallback]
│
10s timeout
∨
[fallback_error] ← retry ───────────────┘
- Iframe
@errorevent — Browser fires this when the embed URL fails - 10-second timeout (
FALLBACK_TIMEOUT_MS = 10000) — Auto-triggers if no@loadfires - Manual switch — User clicks "Switch to alternative source" button
| State | Overlay | Actions |
|---|---|---|
loading |
Gold spinner + "Loading video..." | None |
playing |
No overlay (video visible) | None |
primary_error |
Warning icon + error message | Retry + Switch to fallback |
loading_fallback |
Gold spinner + "Loading from fallback..." | None |
fallback_error |
Error icon + "All sources exhausted" | Retry |
no_video |
Muted video icon + "No video" | None |
A Badge variant="warning" appears in the top-left when fallback mode is active.
entity.is_premium?
→ NO → Show content (always accessible)
→ YES →
isOrgStaff? (owner/manager/super_admin)
→ YES → Show content (bypass gate)
→ NO → Show locked overlay
┌──────────────────────────────────┐
│ [blurred content preview] │ ← blur-sm opacity-30 (teaser)
│ ┌────────────────────────────┐ │
│ │ ⭐ Premium │ │ ← Gold Badge
│ │ 🔒 │ │ ← Lock icon in gold circle
│ │ This content is exclusive │ │
│ │ to premium members │ │
│ │ │ │
│ │ Price: $29.99 │ │ ← Gold price tag (if set)
│ │ │ │
│ │ ┌──────────────────────┐ │ │
│ │ │ Subscribe Now │ │ │ ← Gold CTA Button
│ │ └──────────────────────┘ │ │
│ │ Learn more ˃ │ │ ← Muted link
│ └────────────────────────────┘ │
└──────────────────────────────────┘
- Unauthenticated user: CTA links to
/signup - Authenticated non-paying user: CTA triggers purchase flow (placeholder for Stripe/Paddle integration)
- Org staff (owner/manager/super_admin): Content is automatically unlocked — no purchase needed
- Database (RLS): The
entities_select_public_hubpolicy excludesis_premium = true. Theentities_select_org_memberpolicy blocks basic members from premium rows. - UI (Component):
PremiumGate.vueenforces a second layer. Even if RLS failed, the UI would still lock the content.
| Token | Hex | Usage |
|---|---|---|
onyx |
#0a0a0a |
Primary background |
onyx-50 |
#1a1a1a |
Elevated surfaces |
onyx-100 |
#2a2a2a |
Card borders |
gold |
#d4af37 |
Primary accent, CTAs |
gold-100 → gold-900 |
#f9eac1 → #48350d |
Gold spectrum |
.glass { @apply backdrop-blur-xl bg-white/5 border border-white/10 shadow-glass; }
.glass-hover { @apply hover:bg-white/10 hover:border-gold/30 transition-all duration-300; }
.gradient-gold { @apply bg-gradient-to-r from-gold-400 to-gold-200 bg-clip-text text-transparent; }
.gold-border { @apply border border-gold/30; }| Script | Font Stack |
|---|---|
| Latin | Inter, system-ui, sans-serif |
| Arabic | Noto Naskh Arabic, Tajawal, system-ui, sans-serif |
Font switching is automatic via html[lang='ar'] body in CSS.
- All interactive elements use
transition-all duration-200/300 - Glass cards use
rounded-2xlwithp-4/6/8variants - Buttons: 4 variants (
primary/secondary/ghost/outline), 3 sizes (sm/md/lg) - Badges: 5 variants (
default/premium/success/warning/info) - Loading skeletons use
animate-pulsewithbg-white/5andbg-white/10
// nuxt.config.ts
nitro: {
preset: 'cloudflare-pages',
}routeRules: {
'/': { prerender: true }, // Hub static at build time
'/**': { ssr: true }, // Dynamic tenant routes via SSR
}SUPABASE_SERVICE_KEY and SUPABASE_KEY are deprecated. Current names:
| Variable | Value Pattern | Source | Purpose |
|---|---|---|---|
SUPABASE_URL |
https://*.supabase.co |
Supabase dashboard > API | Project endpoint |
SUPABASE_KEY |
sb_publishable_* |
Supabase dashboard > API > anon/public | Anon key (client-safe, starts with sb_publishable_) |
SUPABASE_SECRET_KEY |
sb_secret_* |
Supabase dashboard > API > service_role | Service role key (server-only, starts with sb_secret_) |
NUXT_PUBLIC_SITE_URL |
https://* |
Custom | Canonical base URL |
NUXT_PUBLIC_SITE_NAME |
Burhan |
Custom | Site name for SEO |
Runtime Config Mapping: @nuxtjs/supabase stores config at nested paths, NOT flat:
SUPABASE_URL→runtimeConfig.public.supabase.urlSUPABASE_KEY→runtimeConfig.public.supabase.keySUPABASE_SECRET_KEY→ NU does NOT auto-map toruntimeConfig.supabase.serviceKey
Fix: Pass explicitly in nuxt.config.ts:
supabase: {
serviceKey: process.env.SUPABASE_SECRET_KEY, // Maps project env var to module's expected key
...
}Do NOT rely on serverSupabaseClient(event) auto-import — It throws ReferenceError: serverSupabaseClient is not defined. The auto-import declared in .nuxt/types/supabase.d.ts is unreliable. Instead, use the explicit factory in server/utils/supabase.ts:
import { createClient } from '@supabase/supabase-js'
export function getSupabaseClient() {
const config = useRuntimeConfig()
const url = config.public.supabase?.url as string // ← nested, NOT config.public.supabaseUrl
const key = config.public.supabase?.key as string // ← nested, NOT config.public.supabaseKey
return createClient(url, key)
}Env var fallback for service key: getSupabaseAdmin() reads config.supabase?.serviceKey. If SUPABASE_SERVICE_KEY is not set at build time, the module's runtimeConfig.supabase.serviceKey is undefined. The fix is serviceKey: process.env.SUPABASE_SECRET_KEY in nuxt.config.ts (as shown above), which reads the actual env var at build time from .env.
# CORRECT — these are the current Supabase key names (2025+)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_KEY=your-anon-key
SUPABASE_SECRET_KEY=your-service-role-key
# DO NOT use — these are deprecated/renamed:
# SUPABASE_SERVICE_KEY=xxx ← old name for secret key
# NUXT_PUBLIC_SUPABASE_URL=xxx ← old Nuxt 3 convention
# NUXT_PUBLIC_SUPABASE_KEY=xxx ← old Nuxt 3 conventionnpm run dev # Start dev server (http://localhost:3000)
npm run build # Production build (Cloudflare Pages)
npm run generate # Static generation
npm run preview # Preview production build
npm run typecheck # TypeScript check
npm run postinstall # nuxt prepare (run after clone)- Nuxt config + Tailwind (scaffolding)
- Supabase migration (database)
- i18n JSONs (translations)
- Server utils + API (backend)
- Composables (logic layer)
- Middleware (route guard)
- UI primitives (atoms)
- Feature components (molecules)
- Pages (organisms)
- Layout + app.vue (shell)
cp .env.example .env
# Fill in SUPABASE_URL, SUPABASE_KEY, SUPABASE_SECRET_KEY
npm install
npm run dev# Run the unified setup script in the Supabase SQL Editor:
# File: supabase/schema.sql
# Or push migrations using Supabase CLI:
# supabase db push/dashboard ← dashboard.vue layout + dashboard-auth middleware
├── index.vue → Overview: 4 stat cards (existing)
├── branches.vue → Branch CRUD: list / create / edit / delete (419 lines)
├── entities/
│ ├── index.vue → Entity list: search, filter, inline modal CRUD (820 lines)
│ ├── new.vue → Article creation: slug gen, RichTextEditor, cover upload (315 lines)
│ └── [id].vue → Article editing: same layout as new + cover image (343 lines)
└── series/
├── index.vue → Series grid: cover cards, active toggle, "إدارة المحتوى" CTA (184 lines)
├── new.vue → Series creation: bilingual form, cover upload, branch selector (315 lines)
└── [id].vue → Series detail: metadata inline edit, episodes list, add/remove/reorder (563 lines)
Layout (app/layouts/dashboard.vue): Minimal shell that renders <FloatingSidebar /> + main content slot. The content area dynamically adjusts margin based on pin state and locale:
<div
class="flex flex-col min-h-screen transition-all duration-300"
:class="isPinned ? (locale === 'ar' ? 'lg:mr-[380px]' : 'lg:ml-[380px]') : ''"
>4 glassmorphic stat cards in a responsive grid (1→2→4 columns):
| Stat | Mock Value | i18n Key |
|---|---|---|
| Total Videos | 1,284 |
dashboard.total_videos |
| Active Branches | 8 |
dashboard.active_branches |
| Premium Revenue | $12,450 |
dashboard.premium_revenue |
| Total Subscribers | 342 |
dashboard.total_subscribers |
Each card: gold icon container → change badge (green/red pill) → large value → stat label → description.
- List: Table with columns (name, slug, module type, status, items count, actions)
- Create/Edit: Glass modal form with
name_ar/name_en, slug auto-generation from English name, module type selector (content/media/forum), active toggle - Delete: Confirm dialog with
window.confirm(t(...)) - Validation: All fields required →
t('dashboard.validation.required_fields'), org guard →t('common.org_not_found') - Data:
supabase.from('branches')scoped toorganization_id
The default.vue layout shows nav.dashboard ("لوحة التحكم") linking to /dashboard when the user is authenticated. The old /profile link was removed because it clashed with the [slug].ts dynamic route.
| State | Width | Trigger |
|---|---|---|
| Collapsed (idle) | 60px |
Default — shows only icon bubbles |
| Expanded (hover) | 280px |
@mouseenter on the bubble zone |
| Pinned (locked open) | 280px |
Double-click anywhere OR click pin icon |
- Position:
fixed,z-50, anchored to bottom of viewport (bottom: 1rem) - Flips sides with locale:
locale === 'ar' ? 'right-4' : 'left-4' - Pinned state:
useState('sidebar-pinned')— shared with dashboard layout for margin adjustment - CSS transition:
width .4s cubic-bezier(.4,0,.2,1)withgrid-template-rowsfor content reveal - Dark background:
rgba(10, 10, 10, 0.96)with white/5 borders — no glass blur (performance)
┌─────────────────────────────┐
│ Logo + Org Name [pin 🔗] │ ← Header
├─────────────────────────────┤
│ 🏠 Overview │
│ 📂 Branches │ ← Navigation (NuxtLink)
│ 📄 Entities │
├─────────────────────────────┤
│ ← System Hub │ ← Back to tenant site
├─────────────────────────────┤
│ 👤 user@email [🌐] [🚪] │ ← Footer: locale + logout
└─────────────────────────────┘
- Logo: 10×10 gold rounded box with 4-square grid icon
- Navigation:
NuxtLinkwith:to="localePath(...)"— locale-aware - Active state:
route.path === localePath(path)— handles locale prefix matching - Locale toggle: Globe icon button →
setLocale(locale.value === 'ar' ? 'en' : 'ar') - Logout:
supabase.auth.signOut()→navigateTo('/login') - Pin icon: 45° rotated pushpin SVG when pinned, shows gold color
function togglePin() {
isPinned.value = !isPinned.value
}Bound to:
@dblclickon the sidebar container@clickon the pin icon button in the header
The layout consumes isPinned to adjust content margin (mr-[380px] for Arabic / ml-[380px] for English).
type Entity = {
id: string
organization_id: string
branch_id: string
title: { ar: string, en: string } // JSONB
content: { ar: string, en: string } // JSONB (editor HTML)
content_type: 'video' | 'article' | 'audio' // 🎙️ Audio: 3rd core type
video_id: string | null
primary_source: string | null
audio_url: string | null // External streaming link
audio_file: string | null // Self-hosted .mp3 path
cover_url: string | null
slug: string | null // URL-safe (articles only)
is_premium: boolean
price: number | null
is_public_to_hub: boolean
created_at: string
}- Data:
useFetch-style fetch viasupabase.from('entities').select('*').eq('organization_id', id) - List: Glass cards with title (localized), branch badge, premium/free badge
- Search: Filter by
title.arortitle.en(case-insensitive) - Filter: Branch selector dropdown
- Actions per entity: Edit (opens inline modal) / Delete (confirm + remove)
- Inline modal: Create + edit in a single modal form — title (ar/en), content (ar/en), content type, video ID, premium toggle, hub visibility
- Bulk actions: "Article" button navigates to
new.vuefor full editor - Navigation uses
localePath():navigateTo(localePath('/dashboard/entities/new')) - Error messages translated:
t('dashboard.validation.title_branch_required'),t('common.org_not_found')
- Route:
/dashboard/entities/new(dashboard layout, dashboard-auth middleware) - Language tabs:
currentLangtoggle (ar ↔ en) with$t('locale.switch_to_*') - Cover image: Upload via
useSupabaseStorage().uploadFile()withcompressImage()utility - Slug: Auto-generated from English title via
@click="generateSlug()"— lowercased, spaces→hyphens, stripped special chars - Content editor:
RichTextEditorcomponent — separate instance per language - Sub-fields per language: Title input + RichTextEditor HTML content
- Metadata: Branch selector, premium toggle + price input, hub visibility toggle
- Save:
supabase.from('entities').insert(payload)→navigateTo(localePath('/dashboard/entities')) - Validation: Title (both), branch, slug required →
t('dashboard.validation.title_branch_slug_required')
- Route:
/dashboard/entities/:id— same structure asnew.vueplus cover image management - Load:
useFetch()withuseRoute().params.id— 404 if not found - Cover:
coverUrlpreview +changeCover()/removeCover()— uploads to Supabase storage - Save:
supabase.from('entities').update(payload).eq('id', entityId) - Cancel/Back:
navigateTo(localePath('/dashboard/entities'))
A Tiptap-powered WYSIWYG editor (using contenteditable with manual execCommands — no Tiptap package dependency).
446 lines — Template: 105 | Script: 145 | Style: 196
| Button | Action | i18n Key |
|---|---|---|
| ↩️ Undo | document.execCommand('undo') |
dashboard.editor.toolbar.undo |
| ↪️ Redo | document.execCommand('redo') |
dashboard.editor.toolbar.redo |
| H2 | execCommand('formatBlock', 'h2') |
dashboard.editor.toolbar.heading_2 |
| H3 | execCommand('formatBlock', 'h3') |
dashboard.editor.toolbar.heading_3 |
| B Bold | execCommand('bold') |
dashboard.editor.toolbar.bold |
| I Italic | execCommand('italic') |
dashboard.editor.toolbar.italic |
| U Underline | execCommand('underline') |
dashboard.editor.toolbar.underline |
| ≡ Bullet List | execCommand('insertUnorderedList') |
dashboard.editor.toolbar.bullet_list |
| 🔗 Link | Opens link modal (prompt-based) |
dashboard.editor.toolbar.insert_link |
| ✕ Clear | execCommand('removeFormat') |
dashboard.editor.toolbar.remove_format |
All toolbar title attributes use $t() — translated live with locale switch.
- History stack: Custom
history[]array withhistoryIndexpointer, max 50 states - Placeholder: CSS pseudo-element shown when content is empty
- Cover image: Separate upload section (not inline) — uses Supabase storage
- Link modal: Simple
window.prompt()for URL input - Image upload: Emits
'image-upload'event for parent to handle
- Printed content area uses
[contenteditable]with custom prose styles - Prose spacing:
space-y-4between block elements,leading-relaxedfor paragraphs - Links styled gold:
text-gold hover:underline - Headings: H2 →
text-xl font-bold, H3 →text-lg font-bold - Lists:
list-disc list-inside - Background:
bg-black/20withrounded-2xland white/5 border
In app.vue, <NuxtPage /> was updated to <NuxtPage keepalive />. This keeps dashboard page components alive when navigating between them (e.g., entities list → entities/new → back), preventing redundant Supabase re-fetches on every route change.
- Same-locale navigation: Pages are cached — zero re-fetch
- Cross-locale navigation: Route changes (prefix added/removed), so cache is naturally bypassed
All dashboard navigation links must preserve the locale prefix to prevent "first click goes to Arabic" bug:
Problem: With prefix_except_default strategy, switching locale via setLocale('en') navigates to /en/dashboard/.... But hardcoded <NuxtLink to="/dashboard/entities"> points to Arabic (no prefix), so the first nav click after switching to English goes back to Arabic.
Solution: Every <NuxtLink> and navigateTo() call in dashboard files uses localePath():
const localePath = useLocalePath()
// Template
<NuxtLink :to="localePath('/dashboard/entities')" />
// Script
navigateTo(localePath('/dashboard/entities/new'))Files fixed (12 total occurrences):
FloatingSidebar.vue— all navigation links + Hub linkentities/index.vue—navigateTofor new + edit routesentities/[id].vue—NuxtLinkback + cancel buttonentities/new.vue—NuxtLinkback + cancel button
The isActive() helper was also fixed to use localePath():
// Before (broken with English locale):
const isActive = (path: string) => route.path === path
// After (works with any locale):
const isActive = (path: string) => route.path === localePath(path)| Section | Keys | Status |
|---|---|---|
nav |
11 | ✅ Documented |
hub |
14 | ✅ Documented (org grid cards, CTA, view all) |
menu |
8 | ✅ New (about, services, contact, branches, social) |
brand / layout / footer |
9 | ✅ Documented |
tenant / org_header |
16 | ✅ Documented (welcome, hero subtitle, about section) |
entities |
17 | ✅ Documented |
video |
12 | ✅ Documented |
premium |
12 | ✅ Documented |
auth |
34 | ✅ Documented |
dashboard |
65+ | ✅ Documented |
dashboard.editor.* |
4 sub-keys | ✅ Documented |
dashboard.editor.toolbar.* |
10 keys | ✅ New |
dashboard.validation.* |
4 keys | ✅ New |
locale |
3 | ✅ Documented |
common |
23 | ✅ Documented |
errors |
7 | ✅ Documented |
empty |
6 | ✅ Documented |
seo |
8 | ✅ Documented |
| File | Lines | Issues Fixed |
|---|---|---|
FloatingSidebar.vue |
223 | Hub label, Pin/Unpin titles, locale button title |
branches.vue |
419 | "All fields are required" + "Organization not found" |
entities/index.vue |
535 | 3 error strings, 2 content labels |
entities/[id].vue |
343 | 2 error strings, language tab labels |
entities/new.vue |
315 | 2 error strings, language tab labels |
RichTextEditor.vue |
446 | 10 toolbar titles |
| Total | 2,281 | ~22 hardcoded strings → i18n |
- All visible template text uses
$t('key') - All script error/success messages use
t('key') - Placeholders that depend on content language (not UI language) are exempt (e.g., "عنوان المقال..." is always Arabic regardless of UI locale)
- Format examples like
placeholder="0.00"are exempt
Full initial schema: organizations, branches, entities, profiles tables with RLS policies, triggers, and indexes.
Fixed branches RLS to use auth.uid() pattern correctly. Added missing policies for owner/manager operations.
Fixed infinite recursion in profiles RLS caused by self-referential policies. Used auth.jwt() claims instead of querying profiles within profiles policies.
Added branches.slug and branches.is_active columns. Branch slugs enable clean URL resolution per tenant branch. Active toggle allows soft-hiding branches without data loss.
Added RLS policies for the organization_assets storage bucket: authenticated users can CRUD files scoped to their organization_id prefix path. Used by entity cover images and series cover uploads.
Added series table (id, organization_id, branch_id, title JSONB, description JSONB, cover_url, is_active, created_at) with RLS and indexes. Added series_id FK and sort_order INT to entities table. Enables course/series grouping with ordered lessons.
Added 'audio' to the valid_content_type CHECK constraint on entities.content_type. Enables the audio/podcast content type alongside video and article. No new columns needed — uses existing audio_url and audio_file fields.
Addressed Supabase security linter findings: pinned search_path = '' on triggers and functions, hardened public schema privileges, and revoked anonymous access to internal tables.
Added Digital Intellectual Observatory schema: observatory_analysts and observatory_threats tables with RLS policies, indexes, and auto_detect_platform() trigger.
Enterprise DeAI inference engine: ai_jobs table (5 lifecycle states, immutable terminal states, heartbeat, last_heartbeat_at), ai_usage table (PK org + period_month, atomic quota accounting), 13 SECURITY DEFINER RPCs with explicit p_user_id, lazy stale-job reaper, and crash-window recovery sweep. Client SELECT-own only; direct mutations revoked.
Restored public anonymous read access on entities and branches tables, ensuring non-premium content renders smoothly on public tenant pages.
Hardened storage bucket security: enforced strict prefix path validation (storage.foldername(name))[1] = organization_id for all uploads in org-assets.
Standardized bucket naming to org-assets and locked allowed MIME types to web-safe images and audio files.
Idempotently restored the valid_content_type CHECK constraint on entities.content_type for clean database re-runs.
Multi-tenant subscription engine: plans (community unlimited vs pro tier) and subscriptions tables with default plan seeds, RLS mutation guards, and is_org_subscription_active evaluation function.
Enforced branch creation limits at database level via check_branch_limit() trigger. Supports canonical -1 unlimited community branches and strict positive limits on paid plans.
Hardened tenant profile security via enforce_profile_security() trigger: blocked self-assignment, prevented cross-tenant reassignment, prevented self-role escalation, and gated super-admin reassignment behind destination active subscription checks.
BYOK subsystem: tenant_ai_credentials encrypted vault (AES-256-GCM keys, IVs, tags, key versioning, custom base_url). PostgREST client access completely revoked; server-only service_role execution.
Atomic tenant provisioning engine: public.provision_tenant(p_user_id, p_org_name, p_org_slug) RPC executing organization creation, community subscription, canonical main branch, and owner profile upgrade in a single atomic transaction with SELECT FOR UPDATE concurrency locks and fail-closed automatic rollbacks.
Security hardening for the Digital Observatory: explicit search_path enforcement on auto_detect_platform trigger function, restrictive RLS review, and strict non-escalation grants.
Cross-tenant public access fix: dropped restrictive series_select_public (which targeted only anon), recreating it with TO anon, authenticated USING (is_active = true). Allows authenticated cross-tenant visitors to browse published courses and series without violating tenant draft isolation.
| Route | Page | Purpose |
|---|---|---|
/dashboard/series |
series/index.vue |
Grid list — 16:9 glass cards with cover, branch badge, active toggle, and "إدارة المحتوى" CTA |
/dashboard/series/new |
series/new.vue |
Create form — bilingual title/description, branch selector, cover upload via Supabase storage |
/dashboard/series/:id |
series/[id].vue |
Detail workspace — metadata edit, episodes list with sort order, add/remove episodes |
series (
id UUID PK DEFAULT gen_random_uuid(),
organization_id UUID FK → organizations NOT NULL,
branch_id UUID FK → branches NOT NULL,
title JSONB NOT NULL CHECK (title ? 'ar' AND title ? 'en'),
description JSONB DEFAULT '{}',
cover_url TEXT,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now()
)
-- entities additions (migration 00006):
ALTER TABLE entities ADD COLUMN series_id UUID REFERENCES series(id) ON DELETE SET NULL;
ALTER TABLE entities ADD COLUMN sort_order INT NOT NULL DEFAULT 0;- Fetches all series for the org, plus branches for name resolution
- Grid:
1→2→3→4columns responsive layout - Each card: 16:9 cover image → bilingual title → description →
localizedValue| branch badge overlay → active toggle switch - "إدارة المحتوى" button on each card navigates to
/dashboard/series/:id - Active toggle calls
supabase.from('series').update({ is_active })directly
Metadata Header:
- Cover thumbnail (click to replace via
useSupabaseStorage+compressImage) - Localized title + description, branch badge, episode count, active status badge
- "تعديل البيانات" button expands inline form: bilingual title/description, branch selector
Episodes Section:
- Fetches
entitieswhereseries_id = :id, ordered bysort_order ASC, created_at ASC - Each row: sort-order badge → content type icon (🎬 فيديو / 🎙️ صوتيات / 📝 مقال) → title → reorder arrows ↕ → delete button
- Audio episodes show a waveform SVG placeholder when no custom cover is set
- Reorder:
moveUp/moveDownswapssort_ordervalues atomically via two sequential Supabase updates - Delete confirmation popover: "حذف كلي" (DELETE entity) vs "فصل فقط" (SET series_id = NULL)
Add Episode:
- "+ إضافة حلقة / مادة للسلسلة" toggle button reveals inline form
- Fields: bilingual title, content type selector (📝 مقال | 🎬 فيديو | 🎙️ صوتيات/بودكاست), premium toggle, hub visibility toggle
- When
audioselected: shows audio URL input + optional MP3 file upload toorganization_assetsbucket - When
videoselected: shows video URL/ID input sort_orderauto-calculated asmax(episodes.sort_order) + 1- Inserts new entity with
series_idpre-bound andcontent_typeset accordingly
- Full-page form matching
entities/new.vueaesthetic - Cover upload →
compressImage→uploadFiletoorganization_assetsbucket - Bilingual title (side-by-side grid) + bilingual description (side-by-side textareas)
- Branch selector dropdown
- Sidebar summary card showing active status and cover upload state
- Save: inserts into
seriestable, redirects to/dashboard/series
Replaces the traditional top navbar on public-facing pages (Hub + Tenant Landing) with a minimalist floating action button (FAB) and a speed dial — when tapped, small glassmorphic pill buttons fan upward from the FAB with staggered animation. No side drawer. Sleek, compact, and immersive.
| Page | File | Layout |
|---|---|---|
| Hub (Org Grid) | app/pages/index.vue |
layout: false — self-contained FAB + footer |
| Tenant Landing | app/pages/[org_slug]/index.vue |
layout: false — self-contained FAB + hero + grid + footer |
Both pages are fully self-contained with layout: false — no shared navbar/footer. The speed dial HTML is inlined in each page (not extracted to a component).
┌─────────────────────────────────────┐
│ Hero / Content / Grid (full view) │
│ │
│ ┌───┐ │
│ │ ⊕ │ ← FAB (fixed, bottom-right, z-50)
│ └───┘ │
└─────────────────────────────────────┘
↓ click FAB
┌─────────────────────────────────────┐
│ ┌─────────────────────────────┐ │
│ │ 🏠 الرئيسية │ │ ← Glass pill buttons rise from
│ ├─────────────────────────────┤ │ FAB position with staggered
│ │ 📚 السلسلات │ │ 0.04s delay each (top → bottom)
│ ├─────────────────────────────┤ │
│ │ ⚡ أحدث المحتوى │ │ ← Each: SVG icon + translated label
│ ├─────────────────────────────┤ │
│ │ ℹ️ عن المنصة │ │ ← hover:bg-gold/10, hover:text-gold
│ ├─────────────────────────────┤ │
│ │ 🌐 English │ │ ← Locale toggle
│ └─────────────────────────────┘ │
│ ┌───┐ │
│ │ ✕ │ │
│ └───┘ │
└─────────────────────────────────────┘
Speed dial items are defined as a computed array in the script. Items dynamically change based on auth state:
- Authenticated: Shows Dashboard + Logout (red) instead of Login/Signup
- Guest: Shows Login instead of Dashboard/Logout
- Position:
fixed bottom-6 z-50in a flex-col wrapper atlocale === 'ar' ? left-6 : right-6 - Style: Glassmorphic square (
w-14 h-14 glass rounded-2xl) with gold SVG icon - Toggle: ⊕ hamburger (closed) ↔ ✕ close (open), with
rotate-90transition - Animations:
hover:shadow-glow,transition-all duration-300
- Container:
TransitionGroupwithflex-col items-center gap-3 mb-4above the FAB - Each item:
glass backdrop-blur-2xl rounded-xl border border-white/10 px-4 py-2.5— pill-shaped with icon + label - Enter/Leave animation:
opacity 0→1+translateY(12px)→0+scale(0.95)→1over 0.25s cubic-bezier - Stagger:
transitionDelay: (length - 1 - i) * 0.04s— top button fades in last (reversed index) - Close: items disappear in reverse order (top leaves first)
- Backdrop:
fixed inset-0 z-40 bg-black/30— clicking anywhere closes the speed dial
| Variant | Classes | Usage |
|---|---|---|
| Default | text-gray-300 hover:text-gold hover:bg-gold/10 hover:border-gold/30 |
Navigation, locale |
| Danger | text-red-400 hover:bg-red-500/10 hover:border-red-500/30 |
Logout |
| Key | Action |
|---|---|
home |
scrollToSection('hub-hero') |
orgs |
scrollToSection('orgs-grid') |
dashboard |
navigateTo('/dashboard') (auth only) |
locale |
toggleLocale() |
login |
navigateTo('/login') (guest only) |
logout |
signOut() (auth only, red variant) |
| Key | Action |
|---|---|
home |
scrollToSection('org-hero') |
series |
scrollToSection('org-series') |
latest |
scrollToSection('org-latest') |
about |
scrollToSection('about') + sets showAbout = true |
locale |
toggleLocale() |
dashboard |
navigateTo('/dashboard') (auth only) |
login |
navigateTo('/login') (guest only) |
logout |
signOut() (auth only, red variant) |
Both Hub and Tenant pages have their own inline footer (not from default.vue):
┌──────────────────────────────────────┐
│ © 2026 Burhan. All rights reserved. │
│ Built with ❤️ by Ainux │
└──────────────────────────────────────┘
No layout dependency — the page is fully portable.
- All tables use
UUID PKwithcreated_at TIMESTAMPTZ DEFAULT now() - JSONB fields:
branches.name,series.title,series.description,entities.title,entities.content— always{ ar, en } - Storage bucket:
organization_assetsfor entity/series cover images (public-read, authenticated-write)
The Digital Intellectual Observatory (المرصد الرقمي الفكري) is a global cross-tenant monitoring module integrated into the Burhan Platform. It provides public-facing interfaces for reporting intellectual misconceptions and threats, combined with an isolated administrative workflow for scholarly refutation.
/observatory → Public intake grid & neutralized defenses list
/observatory/dashboard → Analyst Command Center (Review queue + Scholar assignment + Response links)
- Intake Form (
/observatory): Built with glowing neon grid aesthetics. Allows users to submit threat URLs (TikTok, YouTube, Facebook, X, etc.) with title, danger classification, type tag, and visually graded spread level. - Defense Feed: Displays neutralized threats that have a registered counter-measure (response URL), providing immediate access to scientific refutations.
- Command Center (
/observatory/dashboard): Real-time reactive counters showing total threats, active reviews, and neutralized threats. Allows managers to assign scholars, change status flags, inject counter-measure URLs, and add/remove analysts.
To preserve security and ease SaaS monetization, the Observatory operates on an independent role management layer:
observatory_manager: Full CRUD permissions on threat queues, and management capabilities for the analyst team.observatory_analyst: Read access to threats, with limited update rights (status flag, Counter-Measure URLs, assigned scholars).super_admin: Bypasses all controls and maintains global override capabilities.
Managed via the observatory_analysts table. Users must pass the observatory-auth.ts middleware guard to access the dashboard.
The public submission endpoint (POST /api/observatory/report) is protected by Cloudflare Turnstile to prevent robotic abuse.
- Validation is performed server-side by checking the Turnstile token against
challenges.cloudflare.com/turnstile/v0/siteverifyusing Nitros' fetch wrapper. - Controlled by
NUXT_PUBLIC_TURNSTILE_SITE_KEYandNUXT_TURNSTILE_SECRET_KEYenvironment variables. If these variables are not configured in runtime config, the validation is skipped silently for testing.
The Burhan DeAI subsystem provides an un-censorable, privacy-preserving AI writing and research engine backed by decentralized GPU networks (Nosana) and secure BYOK execution pipelines.
[Client / UI]
│ POST /api/ai/generate (prompt, systemPrompt, lang)
▼
[Quota Admission Gate] ──(exceeded?)──► HTTP 429 quota_exceeded
│
▼ (Atomic reserve_ai_job_quota RPC)
[pending] (requests_used + 1, tokens_reserved + estimated)
│
▼ (Nosana Worker Stream / event.waitUntil)
[processing] ──(every ~3s)──► heartbeat_ai_job()
│
├─► [completed] (tokens_reserved released, tokens_used charged, immutable)
├─► [failed] (tokens_reserved released, tokens_used = 0, requests_used persists)
└─► [cancelled] (client explicit abort, reservation refunded)
- Watchdog Liveness: Long-running jobs update
last_heartbeat_atevery ~3 seconds. - Lazy Stale-Job Reaper (
reap_stale_ai_job): Triggered on status polling (GET /api/ai/jobs/:id). If a worker drops without completing for > 90 seconds, the job is transitioned tofailedand quota reservations are safely released. - Crash-Window Recovery (
reconcile_abandoned_terminal_ai_jobs): Background sweep ensuring any terminal job whose worker terminated before delta reconciliation is processed cleanly without double-charging. - Frontend Assistant Modal (
EntityAiAssistantModal.vue): Embedded directly in the article and entity workspace (new.vueand[id].vue), allowing content creators to stream ideas and choose insertion mode (insert,append,replace).
Burhan implements an authoritative database-enforced subscription tiering system to govern multi-tenant resource limits and monetization.
- Community Plan (
slug = 'community'): Perpetual free tier assigned automatically to all newly provisioned tenants. Includes unlimited branches (limits: { "branches": -1 }) to support grassroots scholarly proliferation. - Pro Plan (
slug = 'pro'): Tiered plan with quota caps (limits: { "branches": 10 }) and premium feature flags (features: { "custom_domain": true, "ai_generate": true }).
- Branch Creation Gate (
check_branch_limit()): PostgreSQL trigger interceptsBEFORE INSERT ON branches. If active subscription limits are exceeded, it raisesbranch_limit_exceeded. Super admins bypass this check automatically. - Graceful Degradation (Read-Only Mode): If a tenant's subscription expires or lapses (
isReadOnly = true), public visitors can still view articles and media, but dashboard content creation (POST/PUT/PATCH) is guarded and disabled with visual badges (SubscriptionBanner.vue).
The BYOK (Bring Your Own Key) subsystem enables tenants to connect their proprietary LLM credentials (OpenAI, OpenRouter, Anthropic, or custom private inference endpoints) without exposing plaintext secrets.
- Algorithm: AES-256-GCM (Authenticated Encryption).
- Master Key: 256-bit key (
BYOK_ENCRYPTION_KEY, 64 hex characters) kept exclusively on the server runtime. - Per-Key Entropy: Every encryption operation generates a cryptographically secure 12-byte initialization vector (
IV) and produces a 16-byte authentication tag (TAG). - Database Vault (
tenant_ai_credentials): Storesencrypted_key,key_iv,key_tag,key_version, and a public non-sensitivekey_suffix(last 4 characters). Direct PostgREST access is unconditionally revoked foranonandauthenticatedroles.
To prevent server-side request forgery when tenants configure custom API endpoints:
- Private IP Blocking: Blocks IPv4/IPv6 loopbacks (
127.0.0.1,::1), RFC1918 private subnets (10.0.0.0/8,172.16.0.0/12,192.168.0.0/16), link-local addresses (169.254.0.0/16), carrier-grade NAT, and AWS/GCP/Azure instance metadata endpoints. - DNS Rebinding Defense: Validates IP addresses resolved at request dispatch time and prohibits redirect followings (
redirect: 'manual'). - Strict Protocol Enforcement: Only
https:protocols are permitted in production environments.
Tenant onboarding in Burhan is governed by an atomic, transactional state machine engineered to eliminate partial registration states, slug collisions, and orphaned database records.
A single SECURITY DEFINER PostgreSQL RPC orchestrates four mandatory pillars:
- Organization Creation: Inserts
organizationsrow, trapping PostgreSQLunique_violationto return clean domain errors (slug_already_taken). - Community Subscription: Inserts an active perpetual
subscriptionsrow pointing to the defaultcommunityplan. - Canonical Main Branch: Automatically creates the root branch (
slug = 'main') with bilingual default names (الفرع الرئيسي/Main Branch). - Profile Ownership Upgrade: Elevates the user's profile row to
role = 'owner'and associates it with the neworganization_id.
- Serialization Lock: Executes
SELECT id FROM profiles WHERE id = p_user_id FOR UPDATEat function entry, serializing concurrent requests for the same user and eliminating duplicate tenant race conditions. - Four-Pillar Idempotency: If the same user retries provisioning with their existing slug, the RPC returns the existing tenant without creating duplicates.
- Email Verification Gate: Supabase Auth 6-digit email OTP (
auth.verifyOtp) must be verified before the server invokesprovision_tenant. Unconfirmed email attempts are rejected with HTTP 403. - Post-Provisioning Routing: Upon successful provisioning and verification, the tenant owner is immediately routed to
/dashboard.
The editorial workspace (entities/new.vue and entities/[id].vue) features an autonomous AI drafting and translation pipeline engineered for bilingual parity and deterministic markup safety.
-
Single-Shot Removal: Legacy single-shot bilingual generation is strictly deprecated in favor of decoupled, directional workflows (Source Tab
$\rightarrow$ Destination Tab). -
Active Tab Authority: Translation targeting is bound authoritatively to the currently active UI language tab (
activeTab: 'ar' | 'en'). - Translation Protection Guard: An explicit verification modal guards against accidental source content loss when initiating translations into non-empty tabs.
- Independent Field Injection: The AI stream can target single fields (Title or Description or Content) independently without overwriting the rest of the draft.
LLM token streams frequently terminate abruptly, leaving unclosed tags (<p>, <strong>, <blockquote>, <ul>). When injected into contenteditable or rendered dynamically, unclosed tags corrupt the DOM hierarchy.
- The Engine: An automated stack-based parser inspects the buffered stream on completion.
- Deterministic Auto-Balance: Unmatched opening tags are identified and closed in reverse chronological order before emitting to the reactive state.
- SSE Stream Reasoning Parser: Server-sent events (
/api/ai/generate) unpack<think>...</think>tokens into collapsible reasoning telemetry, streaming only finalized clean HTML to the editor buffer.
- Problem: Supabase policy
series_select_publicwas originally scopedTO anon. When an authenticated member of Tenant A browsed Tenant B's public showcase, PostgreSQL bypassed theanonpolicy and defaulted toseries_select_org, which evaluatedorganization_id IN (profiles.organization_id), hiding all public courses from authenticated cross-tenant visitors. - Solution: Re-scoped
series_select_publictoTO anon, authenticated USING (is_active = true). Authenticated cross-tenant visitors now see published series globally, while draft series (is_active = false) remain strictly isolated to the owning tenant staff.
- Root Cause: Standard CSS transform utilities (
translate-x-6,translate-x-[18px]) invert direction when placed under document-leveldir="rtl". As a result, switch knobs (like active/inactive toggles on series and branches) were translated out of bounds in Arabic mode. - Surgical Remedy: Enforced
dir="ltr"andtype="button"directly on the toggle switch wrapper element, locking the Cartesian coordinate system regardless of the parent document direction.