System Features & Architecture Documentation
Welcome to the comprehensive technical documentation for the Jasika AI Developer Platform. Jasika AI is built as a premium, low-latency, and edge-native AI Gateway integrated with the Maa Saraswati Mentors (MSM Class) educational environment. Deploying serverless logic directly on the Cloudflare edge network, the platform provides OIDC single sign-on authentication, strict daily usage limit controls, and context-aware multi-model routing capabilities.
By positioning computing resources directly at Cloudflare's global edge network across 300+ datacenters, Jasika AI minimizes TTFB (Time To First Byte), eliminates cold starts, and ensures that client operations are processed near the geographical location of the requesting browser. This document provides an exhaustive, multi-layered review of the system's execution pipeline, APIs, state machines, encryption steps, and data schemas.
1. System Overview & Layered Architecture
The Jasika AI architecture is designed around the principles of high concurrency, security, and immediate execution. Rather than relying on legacy virtual machine deployment paradigms that introduce geographical cold-starts and routing overheads, Jasika operates fully as a Serverless Worker. The execution pipeline is divided into five logical layers:
1.1 Core Layers Walkthrough
The system operates in a highly modular fashion, separating display elements from backend routing and database state management. Each layer operates on clean inputs and executes asynchronously:
- Presentation & Portal Layer: Renders visual assets, documentation panels, the plans comparative dashboard, and the ChatGPT-inspired real-time messaging interface. Communicates via REST APIs and server-sent events (SSE).
- Edge Routing & Gateway Layer: Intercepts raw requests at the geographical edge node closest to the client. Handles custom CORS authorization, API routing versioning, static asset mapping, and error reporting.
- Authentication & Security Layer: Enforces JWT session validation. Decrypts underlying Cloudflare API keys from the secure session token using Web Crypto AES-GCM operations to make upstream requests.
- Business Logic & Limit Layer: Queries the daily quota states from Cloudflare KV. Computes metrics separately for text tokens and image quantities based on OIDC role-to-plan mapping.
- Execution & AI Pipeline: Transforms and directs client requests (e.g. streaming prompt context or multi-part documents) to the Cloudflare Workers AI Gateway, handling content rewrite parsing.
1.2 System Execution Lifecycle
Every HTTP request follows a strict lifecycle. When a client performs a request, the Cloudflare Workers runtime initializes a lightweight execution context. The runtime routes the request to `index.js`, where global middleware executes CORS validations. If the request calls a protected version 2 (`/api/v2/`) API endpoint, the worker extracts the `Authorization: Bearer
2. Edge Router & Gateway Pipeline
The gateway serves as the single entry point for all API calls and frontend routes. When a request hits the edge worker, it enters the global routing loop within `index.js`. The edge routing engine evaluates the request URL path and HTTP verb to forward to appropriate subsystems. Crucially, versioning is strictly enforced between `/api/v1/` and `/api/v2/` routes, protecting legacy applications while supporting modern OIDC flows.
This edge routing pipeline is completely stateless. It relies on the environment variables defined within `wrangler.toml` and bound resources (such as KV storage namespaces) to interact with external targets. By avoiding persistent TCP connections and container state, the system is resilient to centralized backend crashes, scaling automatically to handle millions of simultaneous queries.
2.1 Detailed Gateway Pipeline Processing
The router carries out incoming sanitization and headers injection before delegating execution. The following actions occur in sequence:
- CORS Resolution: Verifies the request origin against allowed hostnames. Injects CORS headers to support browser fetch capabilities.
- Environment Validation: Checks that all required server-side bindings (KV storage, API credentials, and signing secrets) are available before processing requests. If any are missing, a descriptive error is returned immediately.
- Static Asset Serving: Matches known static asset paths and serves them directly from memory-embedded bundles, avoiding any external file round-trips.
2.2 Gateway Architecture Overview
The gateway entrypoint acts as the central coordinator for all inbound traffic. It imports subsystems dynamically and maintains a minimal memory footprint — enabling extremely fast cold starts. The routing engine pattern evaluates URL paths and HTTP methods to forward each request to the appropriate handler: static assets, versioned API endpoints, authentication flows, or HTML page templates.
"By executing fully within Cloudflare Workers edge nodes, request latency is minimized. Response headers are injected directly at the edge, reducing typical time-to-first-byte (TTFB) metrics by up to 70%."
3. OIDC SSO Pipeline
Jasika AI delegates OIDC OAuth2 single sign-on credentials to the MSM Class authentication platform at `https://msmclass.in`. The integration follows the strict Authorization Code Grant Flow with PKCE/State validation. When the user initiates a sign-in, the gateway creates a cryptographically random state parameter, stores it to verify against callbacks, and redirects the browser to the authorization endpoint.
By outsourcing authentication to the central MSM Class platform, Jasika AI remains light and avoids managing raw user credentials, credentials databases, or password resets. Security mapping is carried out in transit during OIDC token exchanges, ensuring real-time roles sync between platforms.
3.1 User Plan Assignment
Upon successful authentication, the platform automatically assigns each user to a plan tier based on their profile. The platform administrator can configure and create any number of custom plan tiers from the Admin Dashboard. Plan assignments and individual usage quotas can be overridden per user at any time, providing flexible access control without requiring user re-authentication.
- Platform Administrators: Receive elevated access including the Admin Dashboard, with configurable or unlimited daily quotas.
- All Other Users: Default to the platform's base free plan. Admins may upgrade any user to any custom plan configured in the system.
3.2 Session Token Lifecycle
After a successful token exchange, the platform issues a short-lived, signed session token bound to the authenticated user's identity. This token carries plan tier information and is used to authorize subsequent API calls. Tokens are issued with a configurable expiry window and automatically expire, requiring users to re-authenticate. No sensitive credentials are stored in the browser or accessible from client-side code.
4. Plan Quota Engine & KV Storage
Usage quotas are checked on every API call. The plan quota engine splits checks into text completions and image generation quotas, storing them under distinct keys to prevent locking database tables. The quota check uses a rolling date format, `usage:[type]:[client_id]:[yyyy-mm-dd]`, ensuring daily limits auto-reset at midnight UTC.
This design handles thousands of concurrent increments. The limits check resolves instantly, preventing DB congestion. The admin panel can override these counts for a particular client identifier, adding dynamic allowances without altering default tier configurations.
4.1 Key Storage Structures
All configurations are saved within Cloudflare Key-Value (KV) storage, offering high availability. Key namespaces are structured as follows:
plan:config:[plan_name]: Stores the daily default quotas set by the admin (e.g. `{"text_limit": 50, "image_limit": 5}`).user:plan:[client_id]: Stores user-specific plan overrides configured by an admin. If present, it takes precedence over the default plan tier quotas.usage:[type]:[client_id]:[date]: Real-time counter of current operations carried out today.
4.2 Quota Enforcement Design
On each API request, the quota engine performs a fast read-check against the relevant usage key, compares the value against the plan's configured limit, and atomically increments the counter on success. The check-and-increment pipeline is designed for high concurrency and resolves in single-digit milliseconds, ensuring no significant latency is added to API responses. If the daily quota is exhausted, the gateway returns a 429 Too Many Requests response with clear retry guidance.
5. Document Processor & SSE Stream Engine
To enable tutor-student interactions, Jasika AI implements a document processing system that parses multi-part form-data inputs. It extracts text contents, handles formatting rules, and constructs structured messages. It also includes an SSE (Server-Sent Events) rewrite pipeline that changes references from downstream provider sources to `msmedu` on the fly.
The parser acts as a streaming buffer, processing files chunk by chunk without reading the entire file into memory at once. This avoids memory exhaustion on the serverless node, supporting file uploads up to 10MB directly at the edge.
5.1 Document Splicing Pipeline
When the user uploads a document (PDF, CSV, or XML) along with their question, the file upload handler processes the multi-part request, extracts the raw text contents, and reformats it into the structured system message schema:
[System Context]
Attached Document (${file_name}):
----------------------------------------
${extracted_file_text}
----------------------------------------
User Question: ${user_prompt}
This context is then forwarded to the worker AI completions process, allowing the model to answer questions based directly on the uploaded documents.
6. Cryptography & Web Crypto Security
Jasika AI employs a zero-knowledge approach to secret management — no access credentials or API keys are stored in plain text in any database, session store, or log file. All sensitive values are encrypted server-side using industry-standard AES-GCM symmetric encryption before being embedded in a session token.
This architecture ensures that even if any storage layer is compromised, no usable credentials can be extracted. All decryption occurs exclusively in-memory during active request processing and is never written to disk or forwarded downstream.
6.1 Zero-Knowledge Secret Management
The platform uses industry-standard symmetric encryption to protect access credentials in transit. Server-side API keys are never stored in plain text in any database or session store. Instead, they are encrypted at the point of authentication using a key derived from the server's signing secret, and the encrypted payload is embedded in the session token issued to the user.
Each encryption operation uses a fresh, randomly generated initialization vector (IV), ensuring that no two encryption outputs are identical — even for the same input. This prevents pattern analysis and replay attacks.
The encryption scheme employs AES-GCM with 256-bit keys, providing both confidentiality and integrity guarantees. All cryptographic operations are performed in-memory using the Web Crypto API — a native, audited implementation available in all modern browser and edge runtime environments.
6.2 Runtime Decryption Model
Encrypted credentials are only decrypted in-memory during active request processing. The decrypted value is used exclusively for the duration of that request and is never persisted, logged, or forwarded. If the session token is compromised, the attacker cannot recover the underlying credentials without also having access to the server's signing secret — which is never exposed to clients or included in any response.
7. API Specifications (OpenAPI Spec)
The gateway serves documentation endpoints under `/docs` and the OpenAPI YAML definition directly. Clients can use the following version 2 (V2) routes:
paths:
/api/v2/auth/login:
get:
summary: Redirect to MSM Class SSO Page.
/api/v2/auth/callback:
get:
summary: Exchange code and issue Jasika JWT.
/api/v2/user/limits:
get:
summary: Fetch visitor plan tiers and active KV quotas usage today.
/api/v2/admin/plans:
post:
summary: Create client limit overrides (Admin only).
/api/v2/admin/plan-configs:
post:
summary: Modify baseline default plans quotas configuration (Admin only).
/api/v2/admin/logs:
get:
summary: Retrieve system access logs (Admin only).