System Architecture (HUB-ARCH-001)
| Field | Value |
|---|---|
| Document ID | HUB-ARCH-001 |
| Pillar | Design |
| Standard Alignment | ISO/IEC/IEEE 42010 & IEEE 1016 |
| Status | Active / Synchronized with Codebase |
| Last Updated | 2026-11-21 |
| Source of Truth | package.json, vite.config.js, src/main.js, src/App.vue, src/router/index.js, src/store/portal.js, src/lib/supabase.js, src/lib/offlineQueue.js, src/lib/attendancePhotoCache.js, src/lib/p3mdi-sso.js, public/sw.js, public/manifest.webmanifest, ops/p3mdi-sso/index.ts, ops/p3mdi-sso/core.ts, ops/p3mdi-sso/compose.yaml, ops/authentik/p3mdi_hub/permissions.py, google-apps-script/Code.gs, nginx.conf, docker-compose.yml, vercel.json, docs/assets/architecture-flow.svg |
1. Architectural Purpose & Scope
Section titled “1. Architectural Purpose & Scope”Soedirman Hub (p3md-portal-vue v1.0.0) is the unified internal Progressive Web App (PWA) for P3MD Batch 1 (Angkatan Soedirman). It supports daily command-and-control, roll-call attendance with live photo and GPS verification, gate pass and overnight leave (Izin Keluar & IB) governance, room tidiness (Kerapian Kamar) monitoring, hierarchical 17-unit Corps & 21-instructor TNI reporting (Laporan Korps), mentoring (Pendampingan), digital incident reporting (Info Digital), academic tracking (Pendidikan & Learning Rabuan), and batch member coordination.
For companion specifications, see DESIGN_SYSTEM.md, DATA_MODEL.md, SECURITY_AND_PRIVACY.md, API_AND_INTERFACES.md, ENGINEERING_AND_TESTING.md, and OPERATIONS_AND_DEPLOYMENT.md. A static overview graphic is also stored in architecture-flow.svg.
2. System Context
Section titled “2. System Context”Soedirman Hub operates as a zero-custom-application-server SPA/PWA for core batch operations—communicating directly with Supabase Cloud over PostgREST (REST + SECURITY DEFINER RPCs)—paired with a small Deno SSO & Core Broker sidecar (ops/p3mdi-sso/) for privileged Identity Provider (Authentik) and Core Directory mutations, and a Google Apps Script webhook (google-apps-script/Code.gs) for authorized Google Drive media uploads.
flowchart LR
U["Browser / Installed PWA (Serdik, Komandan, Pengasuh, Admin)"] -->|"HTTPS Static Assets + SPA"| NGINX["Edge Proxy + Nginx Container (app.p3mdi.id / Vercel)"]
NGINX -->|"/api/sso/* (Traefik route)"| SSO["Deno SSO & Core Broker (ops/p3mdi-sso :8000)"]
U -->|"HTTPS PostgREST + x-portal-token"| SUPA["Supabase Cloud (PostgreSQL + RLS + RPCs)"]
U -->|"OIDC PKCE Redirects"| AUTH["P3MDI Authentik IdP (auth.p3mdi.id)"]
U -->|"HTTPS POST JSON (base64 JPEG + token)"| GAS["Google Apps Script Webhook (Code.gs)"]
U -.->|"Optional Reverse Geocoding"| NOM["Nominatim Endpoint (VITE_NOMINATIM_REVERSE_URL)"]
SSO -->|"OIDC Token Exchange + Core Users API v3"| AUTH
SSO -->|"service_role + x-portal-token RPCs"| SUPA
SSO -->|"Bearer Bridge API (/v1/bridge/members/*)"| CORE["P3MDI Core Directory (core.p3mdi.id)"]
GAS -->|"Token Verification (POST /rest/v1/rpc/portal_me)"| SUPA
GAS -->|"DriveApp Upload (P3MD_Grup1_Dokumentasi)"| GDRIVE["Google Drive Shared Media"]
External System Boundaries
Section titled “External System Boundaries”- Browser PWA Client (
src/): Vue 3.5 + Vite 6 SPA served statically. Holds no Supabase service keys and no Authentik API tokens; relies strictly onVITE_SUPABASE_ANON_KEY(publishable/anon key) plus an opaque 32-byte (64-hex)x-portal-tokenissued byportal_loginorportal_login_p3mdi. - Supabase Cloud (
supabase/migrations/): Authoritative relational store (public,portal_private,core_cacheschemas) enforcing fail-closed Row-Level Security (RLS) policies, bcrypt PIN verification (pgcrypto), IP/account login throttling, masked views (public.portal_serdik_directory), andSECURITY DEFINERworkflows. - Deno SSO & Core Broker (
ops/p3mdi-sso/): Stateless HTTP microservice running on Deno (hostname: '0.0.0.0',port: 8000) behind Traefik (maxRequestBodyBytes: "8192"). Bridges OIDC PKCE callback exchanges, first-login guided onboarding, self-service Authentik profile updates, super-admin Authentik user lifecycle CRUD, and P3MDI Core Directory member cache updates. - P3MDI Authentik IdP (
ops/authentik/p3mdi_hub): Identity Provider athttps://auth.p3mdi.idissuing RS256 OIDCid_tokens under issuerhttps://auth.p3mdi.id/application/o/soedirman-hub/. Includes the custom Django appp3mdi_hubthat automatically assigns object-level Guardian permissions (RoleObjectPermission) solely for non-superuser internal users in groupSoedirman Hub Serdik. - Google Apps Script Webhook (
google-apps-script/Code.gs): Media ingress endpoint verifying live Hub sessions viaPOST /rest/v1/rpc/portal_mebefore uploading JPEGs (<= 8 MB) into Google Drive.
3. Container & Component Architecture
Section titled “3. Container & Component Architecture”3.1 Frontend Module Topology
Section titled “3.1 Frontend Module Topology”- Entry & Fault Containment (
src/main.js,src/App.vue): Mounts the Vue app and attaches bothapp.config.errorHandlerandonErrorCapturedto trap uncaught render errors into a recoverable reload banner instead of crashing silently to a blank screen. Renders<router-view />,<InstallPwaBanner />, and global<AppDialog />. - Route Guard & Lazy Splitting (
src/router/index.js): 33 child/standalone route definitions backed by 30 dynamically imported views (() => import('@/views/...')) insideDashboardLayout.vue, plusInfoDigitalView.vuemounted insidePamView.vue. Enforces 12-hour session expiry, server-verifiedportal_me,must_change_pinonboarding redirect (/ganti-pin), role fallbacks (getFallbackRouteForUser), conditional roster loading (meta.requiresDirectory), and automatic single-retry reload on stale deployment chunk fetch failures (sessionStorage['soedirman_chunk_reload']). - Reactive State Store (
src/store/portal.js): Central state singleton backed by throttledlocalStoragepersistence (p3md_portal_vue_state_v6),localStoragesession metadata (p3md_portal_session_v1), transactional offline queue (src/lib/offlineQueue.js), IndexedDB photo cache (src/lib/attendancePhotoCache.js), cross-tabstorageevent synchronization, periodic background sync (SYNC_INTERVAL_MS), and interactive stakeholder demo sandbox (?demo=true). - Backend & Domain Services (
src/lib/):- Core PostgREST & RPC adapter:
src/lib/supabase.js(BackendAPI,rpc,isSupabaseConfigured). - Specialized RPC service modules:
korpsReports.js,pengasuhReportsService.js,kerapianKamarService.js,pendampinganService.js,infoDigitalService.js(+ pure rules ininfoDigitalRules.js). - Client-persisted workflow stores (with matching schema/migration readiness):
perizinanService.js,poldikService.js,operasionalService.js. - OIDC transaction & callback staging:
src/lib/p3mdi-sso.js. - Client helpers & utilities (
src/utils/):constants.js,helpers.js(Permissions, WIB time helpers, PIN validation),attendance.js,livePhotoLocation.js,xlsxExport.js(zero-dependency OpenXML generator),textDiff.js,korpsDeadline.js,korpsStepper.js,dailyCondition.js,sparkline.js.
- Core PostgREST & RPC adapter:
flowchart TD
Router["src/router/index.js (33 Route Definitions, Lazy Chunks)"] -->|"Guards: Auth, 12h TTL, must_change_pin, RBAC"| Layout["src/layouts/DashboardLayout.vue"]
Layout --> Views["30 Routed Views + InfoDigitalView (src/views/)"]
Views --> Store["src/store/portal.js (Reactive Singleton + Sync Engine)"]
Views --> Services["Domain Services (src/lib/*Service.js)"]
Store --> Outbox["src/lib/offlineQueue.js (localStorage + navigator.locks)"]
Store --> IDB["src/lib/attendancePhotoCache.js (IndexedDB Sessions Store)"]
Store --> API["src/lib/supabase.js (BackendAPI + Demo Sandbox Interceptor)"]
Services --> API
Views --> SSOClient["src/lib/p3mdi-sso.js (PKCE S256 + sessionStorage)"]
API -->|"Live Mode"| PostgREST["Supabase /rest/v1/* and /rest/v1/rpc/*"]
API -->|"Demo Mode (?demo=true)"| DemoMem["src/data/demoData.js (In-Memory Sandbox)"]
SSOClient -->|"HTTPS /api/sso/*"| Broker["Deno SSO Broker (ops/p3mdi-sso)"]
3.2 Bundle Splitting & Service Worker Versioning (vite.config.js, public/sw.js)
Section titled “3.2 Bundle Splitting & Service Worker Versioning (vite.config.js, public/sw.js)”Vite splits production dependencies into dedicated long-cached vendor chunks (vue-vendor for vue and vue-router; icons for lucide-vue-next), while a custom build plugin (versionServiceWorker()) hashes every emitted bundle file plus public/sw.js with SHA-256 and injects the first 16 hex characters into __PORTAL_BUILD__ inside dist/sw.js:
- Navigation & App Shell (
/andAPP_SHELL): Network-first (fetch), caching successful200 OKsame-origin responses undersoedirman-hub-shell-<hash>with offline fallback to cached shell assets. - Hashed Bundles (
/assets/*): Cache-first served alongsideCache-Control: public, max-age=31536000, immutablefrom Nginx. - Safety Guarantees: Never intercepts cross-origin calls (Supabase, GAS, Authentik, Nominatim) or non-
GETrequests; activates new releases cleanly viaSKIP_WAITINGand deletes oldsoedirman-hub-shell-*caches onactivate; restricts Web Pushnotificationclicknavigation strictly toself.location.origin.
4. Key Runtime Architecture Flows
Section titled “4. Key Runtime Architecture Flows”4.1 Offline-First Operational Outbox & IndexedDB Photo Pipeline
Section titled “4.1 Offline-First Operational Outbox & IndexedDB Photo Pipeline”Field commanders frequently record roll-call attendance or operational entries under degraded barracks/field connectivity. Instead of losing mutations or bloating localStorage with base64 images:
- IndexedDB Photo Offloading (
src/lib/attendancePhotoCache.js): Before cachingliveAttendancePhotosmetadata inlocalStorage(p3md_portal_vue_state_v6),stripPhotoPayloads()removesphotoUrl,thumbnailUrl,gps, andlocationName, persisting full binary/base64 payloads cleanly inside IndexedDB databasesoedirman-attendance-photos(storesessions, keyed by<scope>::photo::<sessionKey>::<nosis>+::index). In-memory hydrated photo payloads are capped to an LRU window of 2 sessions. - Scoped Offline Outbox (
src/lib/offlineQueue.js): Operational mutations (upsert/update/deleteon the 9 JSONB tables inOPERATIONAL_TABLESminus read-onlynotifications, plusrundown_harian) are enqueued undersoedirman-outbox-v1:<encodeURIComponent(scope)>:<uuid>. - Cross-Tab Locking & Idempotent Drain:
flush()acquires a Web Lock (navigator.locks.request) on the scope key to prevent concurrent drain races. Only HTTP408,429,5xx, Abort/timeout (15s), or network errors are retried (up tomaxAttempts = 8).4xxRLS rejections are discarded cleanly and surfaced to the user. Creates usePOST ?on_conflict=idwithPrefer: resolution=ignore-duplicates,return=representationfollowed by idempotentPATCHso retried flushes never create duplicate rows.
sequenceDiagram
participant UI as "Vue View / Action"
participant Store as "portal.js Store"
participant Queue as "offlineQueue (localStorage)"
participant IDB as "IndexedDB (attendancePhotoCache)"
participant API as "Supabase PostgREST"
UI->>Store: "Trigger Operational / Photo Mutation"
Store->>IDB: "Persist full photo payload (if live photo)"
Store->>Store: "Strip photoUrl/gps from state cache"
Store->>Queue: "enqueue({ table, key, action, payload })"
Queue->>Queue: "Acquire navigator.locks(scope)"
alt Online & Server Reachable
Queue->>API: "PATCH ?id=eq.{key} or POST ?on_conflict=id"
API-->>Queue: "200/201/204 OK (or 4xx permanent reject)"
Queue->>Queue: "Remove entry & invoke onResult"
else Network Timeout / 408 / 429 / 5xx
API-->>Queue: "retryable: true"
Queue->>Queue: "Increment attempts (< 8) and pause drain"
end
Note over Queue,API: "On browser online event or manual sync, flush() resumes drain"
4.2 Dual Authentication & First-Login Onboarding Sequence
Section titled “4.2 Dual Authentication & First-Login Onboarding Sequence”Every authenticated request attaches x-portal-token (64 hex chars derived from 32 random bytes stored as a SHA-256 digest in portal_private.sessions). Users can sign in either via NOSIS/NRP + 6-digit PIN (portal_login) or via P3MDI OIDC PKCE (beginP3mdiLogin -> /api/sso -> portal_login_p3mdi). If the user carries must_change_pin = true, portal_private.current_session() blocks all operational tables and routes until guided onboarding (ForcePinView -> AccountSetupModal -> /api/sso/setup) completes.
sequenceDiagram
participant U as "Browser (LoginView / Settings)"
participant Auth as "Authentik IdP (auth.p3mdi.id)"
participant Broker as "Deno SSO Broker (/api/sso*)"
participant Supa as "Supabase DB (portal_private + RPCs)"
alt Credential Login (NOSIS/NRP + PIN)
U->>Supa: "POST /rest/v1/rpc/portal_login"
Supa-->>U: "{ ok, token (32B hex), user (must_change_pin) }"
else OIDC PKCE Login
U->>Auth: "GET /application/o/authorize/ (S256 challenge, state, nonce)"
Auth-->>U: "Redirect /login?code=...&state=..."
U->>Broker: "POST /api/sso { code, verifier, nonce }"
Broker->>Auth: "POST /application/o/token/ -> verify RS256 id_token via JWKS"
Broker->>Supa: "POST /rest/v1/rpc/portal_login_p3mdi (service_role apikey)"
Supa-->>Broker: "{ ok, token, user }"
Broker-->>U: "{ ok, token, user }"
end
U->>U: "Store token in localStorage (12h TTL) & redirect / or /ganti-pin"
4.3 Interactive Demo Sandbox (?demo=true)
Section titled “4.3 Interactive Demo Sandbox (?demo=true)”Appending ?demo=true (optionally &role=<personaId> from 901 to 912 in src/data/demoData.js) activates demoSandboxActive inside src/lib/supabase.js and persists only the persona ID inside sessionStorage['soedirman_demo_mode_v1']:
- Network Isolation:
supabaseRequest()short-circuits tohandleDemoRequest(), serving filtered/ordered slices of synthetic arrays and storing mutations inside the in-memorydemoOperationalmap.uploadToGoogleDrive()returns synthetic placeholder URIs without network calls. - Storage Isolation: Persistent
localStoragecaches (STORAGE_KEY,SESSION_KEY, outbox keys) andAdminRoleSwitcherpreview switching are bypassed or blocked in demo mode. - Safe Exit: Navigating with
?demo=falseor callingexitDemoMode()clearsdemoSandboxActive, resets demo state, and restores/login.
5. Non-Functional Requirements & Architectural Constraints
Section titled “5. Non-Functional Requirements & Architectural Constraints”| Concern | Implementation / Target | Mechanism / Source |
|---|---|---|
| Session Security & TTL | 12-hour client & DB expiration, fail-closed | SESSION_TTL_MS = 12 * 60 * 60 * 1000 in src/store/portal.js; expires_at in portal_private.sessions; missing Supabase env vars disable backend requests (isSupabaseConfigured === false). |
| Brute-Force Protection | IP + account throttling | 20261116_session_boundaries.sql: locks out after 5 failed attempts per code + cf-connecting-ip or 50 attempts per IP for 15 minutes (portal_private.login_attempts). |
| Indonesian Data Protection | Direct PII masking & server stripping | Phone/email/address/DOB columns revoked on public.serdik; reads routed via portal_serdik_directory; GPS accuracy <= 100 m & fix age <= 15 s checks (livePhotoLocation.js + 20261130030000); JPEG EXIF stripped server-side for info_digital_screenshots. |
| Availability & Rollback | Atomic VM container swap + health checks | ops/release-on-vm.sh locks via flock, builds legacy-batch-p3md:release-<sha>, verifies /healthz, /login, and JS chunk integrity, or auto-rolls back to legacy-batch-p3md:last-good. |
| Client Memory & Perf | Deferred roster & capped hydration | Routes needing full cohort directory carry meta.requiresDirectory; IndexedDB offloads attendance photos (<= 2 active hydrated sessions); bundle splits vue-vendor & icons. |
| Known Architectural Constraint | Dual local/SQL state on legacy modules | Three domain services (perizinanService.js for izin_keluar, poldikService.js, operasionalService.js) still persist primarily in localStorage despite SQL tables added in 20261116_perizinan_ib.sql and 20261116_poldik_operasional.sql (whose initial RLS policies referenced auth.uid() rather than current_session(), while IB check-ins were migrated to SECURITY DEFINER RPCs in 20261130020000_ib_retention.sql). See DATA_MODEL.md. |