Building Akuko: An Enterprise-Grade AI News Briefing Platform Architecture, Security, and Engineering Deep Dive
Executive Summary
Akuko (derived from the Igbo word for stories or news) is an enterprise-grade, full-stack AI platform designed to combat news overload and information fatigue. By continuously aggregating global news feeds, processing articles across curated categories, and leveraging large language models (LLMs), Akuko delivers personalized, tone-customized news digests directly to users via an interactive web application and automated email newsletters.
Building Akuko required solving complex architectural, security, and performance challenges:
- Engineering a multi-tier authentication mechanism with OAuth 2.0 PKCE, short-lived exchange codes, and Refresh Token Rotation (RTR) with automated session revocation upon token theft detection.
- Implementing a Backend-For-Frontend (BFF) proxy architecture in React Router 8 with HTTP-Only cookie encapsulation and transparent, client-resilient token refresh handling.
- Designing a timezone-aware background processing pipeline using BullMQ, Redis, and
node-croncapable of evaluating localized delivery schedules per user. - Integrating payment gateways with HMAC-SHA256 signature verification, raw-body signature validation, and database-backed idempotency guards.
This article details the architectural decisions, design patterns, security controls, and technical implementation choices behind Akuko.
1. System Architecture & High-Level Design
Akuko follows a decoupled multi-tier micro-monolith design. The system is split into an SSR React Router 8 frontend serving as the user interface and API proxy layer, and an Express 5 TypeScript backend executing business logic, queue processing, and integration with third-party APIs.
Core Architecture Components
-
Frontend Layer (React Router 8 & Tailwind CSS v4): The frontend is built on React Router 8 running on Vite, utilizing Server-Side Rendering (SSR) for fast initial load speeds, search engine accessibility, and seamless route state hydration. Client-side state and data fetching are managed via TanStack React Query to provide immediate optimistic UI feedback and automatic background caching. Crucially, the frontend acts as a Backend-For-Frontend (BFF) proxy layer, routeing all application data requests through an encapsulated proxy route. This design hides internal backend endpoints and guarantees that external API credentials are never exposed to browser runtimes.
-
Backend Engine (Express 5 & Node.js): The backend API is built on Express 5 with TypeScript 5.8, utilizing Node.js asynchronous event loops to deliver high throughput and low latency. The application uses a centralized error-handling hierarchy, standard promise rejection handling wrappers, and structured Pino logging. Every incoming request receives a unique UUID correlation identifier, enabling end-to-end request tracing during debugging and incident response. Database interactions are executed using Prisma ORM connected to PostgreSQL via high-performance connection pooling.
-
Background Job & Cron Processing Layer: Long-running tasks such as news harvesting, LLM summarization, and email dispatch are decoupled from the main HTTP request-response lifecycle. Akuko uses BullMQ paired with Redis to manage asynchronous job queues with concurrency limits and exponential backoff retry strategies. A background
node-cronorchestrator triggers news ingestion every 3 hours and evaluates user delivery schedules every 10 minutes.
2. Authentication & Authorization Security Deep-Dive
Authentication security in modern web applications requires balancing user experience with strict defense-in-depth controls. Akuko implements a production-ready authentication flow combining Google OAuth 2.0, state nonces, short-lived exchange codes, JWT access tokens, and Refresh Token Rotation (RTR).
2.1 Google OAuth 2.0 with State Nonce Validation
To eliminate Cross-Site Request Forgery (CSRF) vulnerabilities during the OAuth redirect loop, Akuko implements a state token management system. When a user initiates login, the backend generates a cryptographically random lookup identifier paired with a secret random nonce. These two strings are joined to create a composite state token that is passed to Google during authorization.
Security Controls Implemented:
- Composite State Tokens: State tokens combine a lookup key and a secret nonce. Both parts are required for validation, rendering state token enumeration mathematically impossible.
- Timing-Safe Comparison: Nonce validation is performed using constant-time byte comparisons to eliminate side-channel timing analysis attacks.
- Single-Use Nonce Lifecycle: State nonces are deleted immediately upon consumption, preventing replay attacks.
- Strict Email Verification Enforcement: The OAuth callback explicitly verifies that the account's email address has been verified by Google. Accounts with unverified emails are denied entry.
2.2 Native HTTPS OAuth Request Engine
During backend integration, standard Google Auth libraries relying on high-level HTTP client libraries encountered a critical issue in Node.js 18+ environments: the underlying undici fetch engine intermittently threw premature stream close errors when parsing token endpoint responses from Google.
To resolve this issue without introducing unmaintained third-party dependencies or degrading security, Akuko includes a custom token exchange engine built directly on Node.js native https.request module. By handling the low-level TLS socket stream manually, formatting urlencoded payloads explicitly, and parsing JSON chunks upon stream completion, Akuko completely bypasses fetch engine socket glitches while maintaining strict TLS certificate validation.
2.3 Short-Lived Exchange Code Pattern
Passing JWT access tokens or refresh tokens directly in URL parameters or location hash fragments introduces severe security risks: tokens remain in browser history logs, get captured in web server referer logs, and can be read by rogue browser extensions or third-party scripts.
Akuko solves this problem by using a Short-Lived Exchange Code Pattern:
By keeping token delivery strictly within server-to-server communication channels, sensitive authorization tokens are never exposed in browser address bars or client-side JavaScript scopes.
2.4 Dual-Token Strategy, Hashed Sessions, and Replay Revocation
Akuko implements a robust session management system based on Refresh Token Rotation (RTR):
- Access Token: Short-lived (15-minute expiration), signed with a primary secret key, carrying user identifier, session identifier, and client IP metadata.
- Refresh Token: Long-lived (30-day expiration), signed with a dedicated refresh secret key.
- Database Hash Storage: Plaintext refresh tokens are never persisted to the database. The backend computes SHA-256 digests of refresh tokens and stores only the hex hashes within PostgreSQL session records.
Token Reuse and Theft Detection Mechanism: If a malicious actor steals a refresh token and attempts to use it after the legitimate user has already rotated it, the database hash lookup fails. Because a valid session ID was presented alongside an outdated or invalid token hash, the backend recognizes that a previously issued token was replayed.
In response, Akuko executes an instant security lockout: it updates PostgreSQL to revoke every active session associated with that user account. Both the legitimate user and the attacker are immediately logged out, neutralizing the compromised credentials and requiring a full re-authentication flow.
3. Backend-For-Frontend (BFF) Architecture & Cookie Proxying
The frontend application utilizes React Router 8 SSR to deliver smooth user interactions while isolating client code from direct backend exposure.
3.1 HTTP-Only Cookie Encapsulation
Authentication state is stored in an encrypted session cookie (akuko_session) configured with strict security flags:
httpOnly: true(Prevents client-side scripts from reading or stealing session tokens via Cross-Site Scripting).secure: truein production environments (Transmitted strictly over encrypted HTTPS connections).sameSite: "lax"(Mitigates Cross-Site Request Forgery attacks while supporting standard cross-page navigation).maxAge: 30 days(Matches the maximum lifetime of refresh sessions).
3.2 Transparent Token Refresh Flow
When an SSR loader or action makes an authenticated API call via the backend fetch wrapper (apiFetch), token expiration is handled transparently behind the scenes:
This transparent retry design guarantees that users never experience abrupt session interruptions or technical error prompts while using the application.
4. AI Briefing Engine & News Processing Pipeline
The primary value proposition of Akuko is transforming vast volumes of raw, noisy global news articles into concise, highly relevant daily digests tailored to individual user preferences and reading styles.
4.1 Automated News Feed Harvesting & Deduplication
Every 3 hours, the background scheduler triggers the news ingestion pipeline:
- Category Mapping Matrix: External news categories are mapped bidirectionally to internal database categories, including Politics, Technology, Business, Science, Health, Entertainment, Sports, World, Lifestyle, Environment, Food, Travel, Education, Finance, and Arts & Culture.
- URL Normalization & Tracking Removal: Article links are passed through a URL normalizer that strips tracking query parameters such as
utm_source,utm_medium,utm_campaign, and session identifiers. This guarantees that duplicate links pointing to identical stories are correctly identified. - Multi-Category Story Deduplication: Articles with matching canonical URLs or identical headline strings are merged into single records in PostgreSQL, combining category tags to avoid redundant storage.
4.2 Timezone-Aware Cron Scheduling Engine
Akuko allows users to schedule news digests at specific times (for example, 07:00 AM or 06:00 PM) in their local timezones (such as America/New_York, Europe/London, or Africa/Lagos).
Handling global delivery schedules requires accounting for time offset variations and Daylight Saving Time (DST) shifts without hardcoding fixed UTC offsets. Akuko resolves this by using Node's Intl.DateTimeFormat API within its delivery engine.
Every 10 minutes, the background scheduler inspects all user preference records. It converts the current UTC time into each user's local timezone dynamically, extracting the local hour and minute. If the computed local time falls within a 10-minute window of the user's scheduled preference, a job is added to the BullMQ briefing queue for processing.
4.3 OpenAI GPT Synthesis & Email Dispatch Flow
When a worker picks up a briefing job from BullMQ:
- Credit Allocation Check: The system inspects the user's current credit balance. If 30 days have passed since their last credit refill, their balance is automatically topped up based on their tier (10 credits for Free users, 150 credits for Pro users).
- Unread Article Selection: The worker queries PostgreSQL for recent articles matching the user's preferred categories, cross-referencing past briefing records to select stories that the user has not seen before.
- OpenAI JSON Mode Synthesis: The selected articles are sent to OpenAI GPT models using structured JSON mode prompts. The system instructs the model to craft an engaging master title, a cohesive overall summary, and single-sentence item digests, strictly enforcing the user's chosen tone (
casual,professional,witty,funny, orsarcastic). - Atomic Transaction & Email Dispatch: In a single database transaction, the briefing record is persisted and 1 credit is deducted from the user's balance. Upon transaction commitment, the backend generates an HTML email newsletter template and triggers asynchronous delivery via ZeptoMail.
5. Monetization & Billing Engineering
Akuko integrates with the Bachs payment gateway to process Pro plan subscriptions ($9.00 per month for 150 credits) and credit top-up bundles ($2.00 for 50 credits, $3.50 for 100 credits, and $6.00 for 200 credits).
5.1 Raw Request Body Capture for Webhook Integrity
Validating payment webhooks requires verifying HMAC cryptographic signatures generated over the exact body payload sent by the provider. Standard Express body parsers modify raw request strings during JSON parsing, altering whitespace and character encodings and causing signature verification checks to fail.
Akuko addresses this by registering raw body capture middleware specifically on the webhook path before global JSON parsing middleware runs. The raw binary buffer is saved directly to the request object, preserving the exact payload byte sequence for signature evaluation.
5.2 HMAC-SHA256 Signature Verification & Idempotency Guards
Webhook security relies on a two-step validation process:
This combination of strict timestamp validation, raw-body HMAC signature checking, and database idempotency guards guarantees that payment webhooks cannot be forged, replayed, or processed multiple times.
6. Defense-In-Depth API Gateway & Hardening
Beyond authentication and payment security, Akuko implements strict security controls across its API gateway:
- Framework Fingerprint Obfuscation: Disables identifying HTTP response headers (
x-powered-by) to hide underlying server technology details. - Helmet Security Headers:
contentSecurityPolicy: Enforces strict resource restrictions (default-src: 'none',frame-ancestors: 'none').crossOriginResourcePolicy: Set tosame-siteto block unauthorized cross-origin resource reads.
- Strict Proxy Trust Configuration: Parses
TRUST_PROXYsettings as numeric hop counts to prevent attackers from injecting fake client IP addresses intoX-Forwarded-Forheaders. - Request Body Payload Capping: Limits JSON payload sizes to
100kbto protect against buffer exhaustion Denial-of-Service (DoS) attacks. - Request Correlation Tracking: Generates a unique UUID (
requestId) for every incoming request, appending it to pino log entries for unified audit logging. - Same-Origin BFF Gateway Protection: Validates
RefererandOriginheaders on proxy endpoints to block direct external API access attempts.
7. Database Schema Architecture
The relational database is managed through Prisma ORM with PostgreSQL:
- User: Stores core account details, subscription tier (
freeorpro), credit balance, and credit refill timestamps. Indexed by email. - Session: Tracks active user sessions, storing UUID session keys, SHA-256 refresh token hashes, client IP addresses, user agent strings, and revocation timestamps.
- Preferences: Stores user-selected categories, tone choices, delivery schedules, and local timezone identifiers.
- Category: Defines available news categories mapped to user preference records.
- Articles: Stores harvested news stories, titles, summaries, normalized canonical URLs, image links, and category array tags. Indexed by unique URL.
- Briefings: Stores generated AI digests, master summaries, categories, and JSON arrays of summarized articles linked to specific users.
- Purchase: Tracks payment transactions, Bachs checkout identifiers, charge identifiers, unique webhook event IDs, purchase types, credit amounts, and fulfillment statuses.
8. Summary of Technical Achievements
- Zero-Trust OAuth 2.0 PKCE Architecture: Combined state token validation, short-lived exchange codes, timing-safe checks, and native HTTPS request handling to eliminate CSRF vulnerabilities, token exposure, and socket stream errors.
- Automated Replay Revocation: Implemented Refresh Token Rotation backed by SHA-256 database hashing and instant multi-device session lockouts upon token theft detection.
- Timezone-Aware Delivery Scheduling: Designed an automated scheduler capable of evaluating localized delivery windows per user across global timezones using native internationalization APIs.
- Resilient AI Pipeline: Built structured OpenAI JSON-mode prompt flows paired with BullMQ queue concurrency, exponential backoff retries, and atomic database transactions.
- Secure Payment Gateways: Implemented HMAC-SHA256 signature verification over raw request buffers with timestamp tolerance checks and database idempotency guards.
9. Technical Specifications & Dependencies Matrix
As at last update
| Component | Framework / Library | Version / Detail |
|---|---|---|
| Frontend Framework | React Router | v8.0.0 (SSR + Vite) |
| UI Library & Icons | React + Lucide + Phosphor | React 19, Radix UI Primitives |
| CSS System | Tailwind CSS | v4.2.2 |
| Backend Runtime | Node.js + Express | Express v5.1.0, TypeScript 5.8 |
| Database & ORM | PostgreSQL + Prisma | Prisma v7.8.0 with @prisma/adapter-pg |
| Job Queue & Redis | BullMQ + ioredis | BullMQ v5.79.0, ioredis v5.11 |
| Scheduler | node-cron | v4.4.1 |
| AI LLM Provider | OpenAI Node SDK | v6.44.0 (JSON Mode) |
| Email Service | ZeptoMail API | Transactional HTML Newsletters |
| Payment Gateway | Bachs API | Checkout Sessions & HMAC Webhooks |
| Security & Logging | Helmet + Pino + Rate Limit | Strict CSP, Pino v9.7 |