# Ring2All Platform - Full Technical Documentation Dump Generated for Large Language Models, AI Agents, and Retrieval-Augmented Generation (RAG). Total documents included: 304 ================================================================================ ================================================================================ DOCUMENT: 01-introduction/concepts TITLE: Basic Telephony Concepts URL: https://docs.ring2all.com/01-introduction/concepts.md ================================================================================ ## 📖 Introduction Before configuring Ring2All, it helps to understand basic telephony terms and concepts. --- ## 📞 Key Terms ### Extensions An **extension** is a phone line inside your organization. Usually a 3-4 digit number like 1001, 1002, etc. | Property | Example | |----------|---------| | Extension Number | 1001 | | User | John Smith | | Device | Desk phone, softphone | ### DID (Direct Inward Dialing) A **DID** is an external phone number that people dial to reach you. | DID | Routes To | |-----|-----------| | +1-555-123-4567 | Main IVR | | +1-555-123-4568 | John's Extension (1001) | ### SIP Trunk / Gateway A **SIP Trunk** (also called Gateway) connects your PBX to the outside world through a VoIP provider like Twilio or Telnyx. ```mermaid sequenceDiagram autonumber actor Caller as 👤 Caller (External PSTN) participant Carrier as 🌐 SIP Carrier participant SBC as 🛡️ Ring2All SBC participant Engine as ⚙️ Ring2All PBX Engine actor Extension as 🎧 Extension 1001 Caller->>Carrier: Dial +1-555-123-4567 Carrier->>SBC: SIP INVITE Note over SBC: Validate IP, Pike Anti-flood & ACL SBC->>Engine: Authenticated SIP INVITE Engine->>Extension: Ringing (SIP 180) Extension-->>Engine: Answer (SIP 200 OK) Engine-->>SBC: 200 OK SBC-->>Carrier: 200 OK Note over Caller,Extension: 🎙️ Active RTP Media Session (2-Way Audio) ``` ### IVR (Interactive Voice Response) An **IVR** is an automated phone menu: - "Press 1 for Sales" - "Press 2 for Support" - "Press 0 for Operator" ### Queue A **Queue** holds callers until an agent is available. Used for support lines, sales teams, etc. ### Ring Group A **Ring Group** rings multiple extensions simultaneously or sequentially until someone answers. --- ## 📊 Call Flow Example ```mermaid flowchart TD Call["📞 Incoming Call (+1-555-123-4567)"] --> Route["🔀 Inbound Route (Matches DID)"] Route --> Time{"⏰ Time Condition (Business Hours?)"} Time -->|Yes| IVR["🗣️ Main IVR Menu"] Time -->|No| Closed["🌙 After Hours Announcement"] --> VM["📼 Voicemail"] IVR -->|"Press 1"| Sales["👥 Sales Queue"] --> Agent1["🎧 Sales Agent"] IVR -->|"Press 2"| Support["🛠️ Support Queue"] --> Agent2["🎧 Support Tech"] IVR -->|"Press 0"| Reception["🛎️ Operator (Ext 1000)"] ``` --- ## 🔗 SIP Basics ### SIP (Session Initiation Protocol) The protocol that makes VoIP calls work. You'll see these terms: | Term | Meaning | |------|---------| | **SIP Server** | The PBX IP address | | **SIP Port** | Usually 5060 (UDP) or 5061 (TLS) | | **Username** | Extension number | | **Password** | SIP password | | **Register** | Phone connects to server | ### Registration When a phone "registers," it tells the PBX: - "I'm extension 1001" - "Reach me at this IP address" This allows the PBX to route calls to the phone. --- ## 📞 Call Types | Type | Description | |------|-------------| | **Internal** | Extension to Extension (1001 → 1002) | | **Inbound** | Outside caller → Extension | | **Outbound** | Extension → Outside number | --- ## 💡 Tips > [!TIP] > **Test internally first**: Make extension-to-extension calls before testing external calls. > [!TIP] > **Check registration**: Most problems are phone registration issues. --- ## 🔗 Related - [Getting Started](getting-started.md) - [Extensions](../pbx/extensions/extensions.md) - [Gateways](../pbx/routing/gateways.md) ================================================================================ DOCUMENT: 01-introduction/dashboard TITLE: Dashboard URL: https://docs.ring2all.com/01-introduction/dashboard.md ================================================================================ ## 📖 Introduction The Dashboard is your central overview of PBX activity. Monitor calls, system health, and key metrics at a glance with customizable widgets. --- ## 🖥️ Accessing the Module **Navigation:** `Dashboard` (home page) ![Dashboard Overview](/screenshots/general/dashboard-list.png) --- ## 📊 Dashboard Widgets ### Call Activity | Widget | Shows | |--------|-------| | **Active Calls** | Current live calls | | **Calls Today** | Total calls today | | **Call Volume Graph** | Hourly call chart | | **Missed Calls** | Missed call count | ### System Health | Widget | Shows | |--------|-------| | **System Status** | Service health | | **CPU/Memory** | Resource usage | | **Disk Space** | Storage status | | **Gateway Status** | Trunk registrations | ### Queue Statistics | Widget | Shows | |--------|-------| | **Queue Summary** | Calls waiting per queue | | **Agent Status** | Available/busy agents | | **Avg Wait Time** | Queue performance | | **Abandoned Rate** | Queue efficiency | --- ## ⚙️ Customization ### Adding Widgets 1. Click **⚙️ Customize** button 2. Select widgets to display 3. Drag widgets to arrange 4. Click **Save** ### Widget Sizes - Small (1x1) - Medium (2x1) - Large (2x2) --- ## 💡 Tips > [!TIP] > **Pin important widgets**: Keep critical stats visible. > [!TIP] > **Set refresh rate**: Auto-update for real-time monitoring. --- ## 🔗 Related Modules - [Active Calls](../reports/pbx/active-calls.md) — Detailed call monitor - [System Status](../admin/system/telephony-servers.md) — System health ================================================================================ DOCUMENT: 01-introduction/getting-started TITLE: Getting Started URL: https://docs.ring2all.com/01-introduction/getting-started.md ================================================================================ ## 📖 Welcome to Ring2All Platform Ring2All is an **AI company building the future of enterprise and carrier-grade communications**. Unlike legacy telecommunications software designed decades ago and retrofitted with external plugins, Ring2All is **AI-native from day zero**. We design communications infrastructure around what artificial intelligence makes possible: autonomous voice agents with sub-second streaming, Model Context Protocol (MCP) diagnostic copilots, cognitive perimeter defense, and real-time converged billing. --- ## 🎯 What is the Ring2All Platform? Ring2All unifies four core pillars into a single, cohesive communications nervous system: | Pillar | Subsystem | Core Capabilities | | :--- | :--- | :--- | | **Class 5 Communications** | **Ring2All PBX** | Multi-tenant cloud communications, autonomous voice agents, queues, IVR, conferences, and WebRTC integration. | | **Class 4 Perimeter** | **Ring2All SBC** | Perimeter Session Border Controller with cognitive Pike/htable anti-flood protection, LCR routing, and RTPEngine 12.5 media relay. | | **Monetization & OCS** | **Ring2All BSS** | Real-time Online Charging System (OCS), automated prepaid wallet debit, package plans, and customer self-care. | | **Agentic Intelligence** | **AI Service Hub & MCP** | Embedded Model Context Protocol servers enabling AI models and copilots to govern, inspect, and optimize communications. | --- ## 🏢 Modular Topologies: Autonomous PBX vs. Full Ecosystem Ring2All is engineered with a **composable, decoupled architecture**: 1. **Autonomous Standalone PBX (100% Self-Sufficient)**: Ring2All PBX does **not** require Ring2All SBC or Ring2All BSS to function as a complete, enterprise-grade cloud PBX. In standalone mode, Ring2All PBX directly manages SIP trunks and carrier gateways, registers WebRTC and SIP deskphones, runs OpenAI Realtime voice agents, routes calls through IVRs and queues, and records internal CDRs. This topology is ideal for single-server enterprise deployments, on-premise appliances, or private cloud environments. 2. **Full Distributed Carrier Ecosystem**: When scaling to telecom operator (ITSP) or carrier volume, Ring2All PBX seamlessly federates with: - **Ring2All SBC**: For perimeter security (Pike anti-flood), carrier least-cost routing (LCR), WebRTC proxying, and RTPEngine 12.5 media transcoding. - **Ring2All BSS**: For real-time OCS prepaid rating, automated customer invoicing, prepaid wallet top-ups, and customer self-service portals. --- ## 🚀 First Steps ### 1. Access the Admin Panel Open your browser and go to: ``` https://your-pbx-server.com/admin ``` Login with your administrator credentials. ![Login Screen](/screenshots/general/login-screen.png) ### 2. Understand the Interface | Area | Purpose | |------|---------| | **Sidebar** | Navigation menu | | **Top Bar** | Search, user menu, notifications | | **Main Area** | Configuration forms and data | | **Dashboard** | Overview and statistics | ![Admin Interface Overview](/screenshots/general/dashboard-list.png) ### 3. Basic Setup Order For a new installation, configure in this order: 1. **General Settings** — Company info, timezone 2. **Extensions** — Create user phone lines 3. **Gateways** — Connect SIP trunks 4. **Inbound Routes** — Route incoming calls 5. **Outbound Routes** — Enable outgoing calls 6. **IVRs** — Create phone menus --- ## 📞 Making Your First Call After basic setup: 1. Register a phone or softphone to an extension 2. Dial another extension number 3. Call should connect! If it doesn't work, check: - Extension Status (is phone registered?) - SIP credentials (extension/password correct?) - Network (can phone reach server?) --- ## 🔗 Next Steps - [Navigating the Interface](navigation.md) - [Basic Telephony Concepts](concepts.md) - [Extensions Guide](../pbx/extensions/extensions.md) --- *Welcome to Ring2All! Let's get started.* ================================================================================ DOCUMENT: 01-introduction/navigation TITLE: Navigating the Workspace & Interface URL: https://docs.ring2all.com/01-introduction/navigation.md ================================================================================ ## Table of Contents 1. [Overview](#1-overview) 2. [Layout & Structure](#2-layout--structure) 3. [Multi-Tab Workspace Navigation Mode](#3-multi-tab-workspace-navigation-mode) - [Keep-Alive State Preservation](#keep-alive-state-preservation) - [Drag-and-Drop Tab Organization](#drag-and-drop-tab-organization) - [Compact Density Selector](#compact-density-selector) 4. [Universal UI Hierarchy: Level 1 vs Level 2](#4-universal-ui-hierarchy-level-1-vs-level-2) - [Level 1: Root Data Grids](#level-1-root-data-grids) - [Level 2: Form Views & Headers](#level-2-form-views--headers) - [Bottom Fixed Action Bar & Cancel Behavior](#bottom-fixed-action-bar--cancel-behavior) 5. [Sidebar Accordion & Navigation Controls](#5-sidebar-accordion--navigation-controls) 6. [Global Search & Breadcrumbs](#6-global-search--breadcrumbs) 7. [AI Copilot Integrated Assistant](#7-ai-copilot-integrated-assistant) --- ## 1. Overview The **SoftSwitch Platform** delivers a high-productivity, web-based workspace designed for enterprise telecom administration, NOC engineers, and multi-tenant operators. The interface combines: - **Zero Page Refreshes**: Single-Page Application (SPA) with optimistic UI updates. - **Multi-Tab Workspace Navigation**: Open multiple modules simultaneously without losing unsaved form fields or pagination filters. - **Strict Visual Alignment**: Universal 56px headers, 4-column responsive form grids, and standardized bottom action bars. --- ## 2. Layout & Structure ``` ┌────────────────────────────────────────────────────────────────────────────────────────┐ │ [Logo] [Domain Selector ▼] [🔍 Search ( / )] [🌙] [🔔] [Copilot AI] [User Menu ▼]│ ├───────────────┬────────────────────────────────────────────────────────────────────────┤ │ SIDEBAR │ WORKSPACE TABS BAR │ │ │ [Extensions ×] [Domain: pbx.corp.com ×] [CDR Reports ×] [+ New Tab] │ │ 📁 PBX ├────────────────────────────────────────────────────────────────────────┤ │ ├─ Extensions│ LEVEL 1 / LEVEL 2 VIEW CONTAINER │ │ ├─ IVR │ │ │ ├─ Queues │ ┌────────────────────────────────────────────────────────────────────┐ │ │ └─ Routes │ │ Fixed Header (56px) [< List] Title: Edit Domain - pbx.corp.com │ │ │ │ ├────────────────────────────────────────────────────────────────────┤ │ │ 📁 Reports │ │ Tabs: [General] [Telephony Limits] [Retention] [Domain Aliases] │ │ │ ├─ CDR Logs │ │ │ │ │ └─ Live Calls│ │ FormBox (4-Column Form Grid) │ │ │ │ │ ┌──────────────────┬─────────────────┬──────────────┬────────────┐ │ │ │ 📁 Admin │ │ │ Label 1 (40px) │ Input 1 (38px) │ Label 2 │ Input 2 │ │ │ │ ├─ Tenants │ │ └──────────────────┴─────────────────┴──────────────┴────────────┘ │ │ │ └─ Security │ │ │ │ │ │ └────────────────────────────────────────────────────────────────────┘ │ │ ├────────────────────────────────────────────────────────────────────────┤ │ │ BOTTOM FIXED ACTION BAR: [Cancel Changes] [Save Changes] │ └───────────────┴────────────────────────────────────────────────────────────────────────┘ ``` --- ## 3. Multi-Tab Workspace Navigation Mode The workspace navigation mode transforms the single-view portal into a powerful multi-tasking desktop console. ### Keep-Alive State Preservation When working with complex telephony infrastructure, administrators frequently need to look up information in another module while editing a configuration (e.g. checking an Inbound Route or Extension while creating a new Queue). - **No Data Loss**: Switching between open tabs preserves all dirty form inputs, unsaved edits, and active validation errors. - **State Caching**: Data grid pagination, search query strings, and active filters remain in memory across tab switches. - **Tab Memory Management**: Closing a tab (`×`) frees its cached component state and unsubscribes real-time WebSocket listeners. ### Drag-and-Drop Tab Organization - Reorder tabs dynamically along the top tab bar by clicking and dragging. - Right-click or tab options menu allows: - **Close Tab**: Closes the current module. - **Close Other Tabs**: Retains only the focused module. - **Close Tabs to the Right**: Prunes trailing tabs. ### Compact Density Selector For operations center monitoring and high-density laptops, the workspace includes a compact mode switch in the top toolbar: - **Comfortable Mode (Default)**: Generous whitespace and standard padding for touch and desktop use. - **Compact Mode**: Reduces table row heights (`36px`), tightens form grid margins, and maximizes information density for large CDR and extension listings. --- ## 4. Universal UI Hierarchy: Level 1 vs Level 2 To maintain consistent user experience and prevent navigation disorientation, the platform strictly enforces Level 1 and Level 2 view semantics. ### Level 1: Root Data Grids Level 1 represents the root list of an entity (e.g., Extensions, Inbound Routes, Telephony Domains, Users). - **No Back Button**: Root views never display a `< Back` button because they sit at the top of their navigation hierarchy. - **Toolbar (`DataGridToolbar`)**: Features global table search, tenant filter, column visibility toggles, CSV export, and primary action buttons (e.g. `+ Add Extension`). - **Standardized Actions**: Each row features uniform action buttons: View, Edit, and Delete with referential integrity safeguards. ### Level 2: Form Views & Headers Level 2 represents item creation, inspection, or editing views. - **Fixed Header (`ModuleFormHeader`)**: Fixed 56px height (`min-h-[56px] py-2 px-4`) containing: - `< List` navigation button with direct return link to the parent Level 1 list. - 20px primary icon inside a subtle background container (`p-1 bg-primary/10 rounded-md`). - Clear, single-line title (e.g., `Edit Domain - pbx.company.com`) without redundant subtitles. - Contextual action icons (Duplicate, Quick List switcher, Add New). - **Pure Text Tabs**: Form tabs (``) contain text only (e.g. `{t('telephonyDomains.tabs.limits')}`). Graphic icons or images are prohibited in tabs to ensure uniform aesthetic cleanliness. - **4-Column Form Grid**: All form boxes utilize standard 4-column responsive layout (`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-x-6 gap-y-3 items-start`). All field labels maintain a minimum height of `40px` (`min-h-[40px] flex items-center`) to anchor visual alignment across columns. ### Bottom Fixed Action Bar & Cancel Behavior Every Level 2 form view includes a bottom fixed bar (`FixedActionBar`): - **Cancel Button**: > [!IMPORTANT] > **Strict Cancel Button Standard:** > Clicking **Cancel** serves **only to revert uncommitted edits and restore the form to its original loaded values** (or default blank state during creation) while keeping the user on the form. > To leave the form and return to the list, the user clicks the `< List` button located in the top header. - **Save / Update Button**: Validates all active tabs, executes backend mutation via Fastify API, displays toast confirmation, and updates local state. --- ## 5. Sidebar Accordion & Navigation Controls - **Single-Open Accordion**: Expanding any module group in the sidebar (e.g., expanding *PBX Applications*) automatically collapses any other currently open group, preventing vertical sidebar clutter. - **Active Module Highlighting**: The active module is clearly highlighted with primary brand accent colors. - **Tenant Context Indicator**: Displays current tenant scope. System administrators can toggle tenant contexts on-the-fly. --- ## 6. Global Search & Breadcrumbs - **Global Quick Search**: Press `/` from anywhere in the application to summon the modal search palette: - Jump directly to extensions by typing an extension number (e.g. `1001`). - Search routes, DIDs, queues, users, or settings modules. - **Breadcrumb Trail**: Displays hierarchical location (e.g. `PBX → Inbound Routing → VIP PIN Routing`). --- ## 7. AI Copilot Integrated Assistant Accessible via the floating AI button or header icon: - **Platform Copilot**: Embedded conversational assistant powered by the Model Context Protocol (MCP). - **Context-Aware Assistance**: Automatically understands your active tenant, domain, and loaded form. - **Live Tool Execution**: Can query CDR logs, configure extensions, analyze SIP error codes, and suggest optimal queue configurations without leaving your active workspace. --- *Documentation updated: September 2026* ================================================================================ DOCUMENT: 02-installation/bss-deployment TITLE: 💳 Ring2All BSS (Billing & OCS) Deployment Guide URL: https://docs.ring2all.com/02-installation/bss-deployment.md ================================================================================ > Complete step-by-step guide for installing and configuring **Ring2All BSS** on Debian 13 (Trixie), decoupling back-office carrier rating from the public customer self-care store. --- ## 🏗️ Architecture Overview The **Ring2All BSS (Business Support System)** serves as the monetization and commercial intelligence engine for telecom operators. It translates raw network events (SIP INVITEs, Call Detail Records, active media sessions) into billed transactions, manages prepaid customer wallets in real time, and exposes self-service purchasing for virtual DIDs, trunks, and extensions. ```mermaid flowchart TB subgraph DMZ["Public Edge / DMZ (Customer Storefront)"] ClientWeb["Customer Self-Care Store
(softswitch-bss-client)
store.carrier.com"] EdgeProxy["Nginx DMZ Reverse Proxy / WAF
(Passes ONLY /api/client/*)"] end subgraph InternalLAN["Internal Management LAN (Zero Direct Public Exposure)"] AdminWeb["Back-Office Admin Portal
(softswitch-bss-web)
bss-admin.carrier.com"] BssApi["BSS & Real-Time OCS Engine
(softswitch-bss-api :3002)
Fastify 5 / Node.js 22"] DB[("PostgreSQL 17 HA Cluster
(customers, wallets, rates, ocs_cdrs)")] Redis[("Redis In-Memory Cache
(Sub-millisecond Rate Lookups)")] end subgraph TelecomNodes["Telecom Execution Nodes"] SBC["Ring2All SBC Gateway
(Kamailio 6.1)"] PBX["Ring2All PBX Cluster
(FreeSWITCH 1.11+)"] end ClientWeb -->|HTTPS| EdgeProxy EdgeProxy -->|Passes /api/client/*| BssApi AdminWeb -->|Internal HTTPS / VPN| BssApi BssApi <--> DB BssApi <--> Redis SBC <-->|Sub-millisecond OCS Auth / Balance Check| BssApi PBX <-->|Real-Time CDR & Balance Updates| BssApi ``` ### Core Tenets of the BSS Architecture: 1. **Strict Separation of Admin and Storefront**: - **Back-Office Admin (`softswitch-bss-web`)**: Confined to internal management LANs or secure VPNs. Telecom administrators manage rate decks, carrier costs, customer accounts, and telecom nodes. - **Customer Self-Care Store (`softswitch-bss-client`)**: Exposed to the public internet. Subscribers purchase subscription plans, order virtual DID numbers, manage autodialer campaigns, top up wallets, and review CDR usage. 2. **Zero Database Exposure at the Perimeter**: - The customer store is a client-side React 18 Single Page Application. It has zero direct access to PostgreSQL. 3. **DMZ Perimeter Reverse Proxy Filtering**: - The customer edge reverse proxy passes only authenticated customer endpoints (`/api/client/*`) while aggressively returning `403 Forbidden` for administrative routes (`/api/v1/users`, `/api/v1/telecom-nodes`, `/api/v1/firewall`). 4. **Sub-Millisecond Online Charging System (OCS)**: - Evaluates call authorization, balance verification, and destination pricing using high-speed caching and sub-millisecond PostgreSQL rating queries before an outbound call is established. --- ## 📦 Modular Debian Package Breakdown Ring2All BSS is distributed via four decoupled Debian packages: | Package Name | Function | Staging Path | Dependencies | | :--- | :--- | :--- | :--- | | **`softswitch-bss-api`** | Fastify 5 / Node.js 22 OCS rating engine, customer API, billing daemon, background CDR synchronizer | `/var/www/softswitch/bss/api` | `nodejs (>= 22)`, `postgresql-client` | | **`softswitch-bss-web`** | React 18 administrative back-office web application | `/var/www/softswitch/bss/web` | `nginx` | | **`softswitch-bss-client`** | React 18 customer-facing self-care store & billing portal | `/var/www/softswitch/bss/client` | `nginx` | | **`softswitch-bss-all`** | Metapackage for single-server all-in-one deployments | N/A | Depends on all 3 packages above | --- ## 🚀 Deployment Topologies ### Topology A: Single-Server All-in-One Ideal for small to mid-sized telecom operators. The API daemon, Admin UI, and Customer Store run on the same Debian 13 host: - **Admin UI**: Accessed at `https://bss.carrier.com` (or port 443). - **Customer Store**: Accessed at `https://store.carrier.com` (or dedicated port `:8443`). - **BSS API**: Runs locally on `127.0.0.1:3002`, reverse-proxied by Nginx. ### Topology B: Distributed Multi-Server DMZ Deployment Recommended for enterprise carriers and public cloud environments: - **Server 1 (Internal LAN / Billing Core)**: - Runs `softswitch-bss-api`, `softswitch-bss-web`, and PostgreSQL 17. - Not reachable directly from the public internet. Accessible only via corporate VPN or WireGuard tunnel. - **Server 2 (Public Edge / DMZ Store)**: - Runs `softswitch-bss-client` and Nginx. - Serves static assets for the Customer Store and proxies `/api/client/` across the internal network to Server 1. --- ## 🛠️ Step-by-Step Installation (Debian 13) ### Step 1: System Preparation & Prerequisites On your target Debian 13 server, install foundational dependencies: ```bash apt-get update apt-get install -y curl wget gnupg2 openssl nginx postgresql-client ``` Ensure Node.js 22 LTS is registered: ```bash curl -fsSL https://deb.nodesource.com/setup_22.x | bash - apt-get install -y nodejs build-essential ``` Register the Ring2All APT repository: ```bash curl -fsSL https://repo.softswitchone.com/apt/setup_repo | bash apt-get update ``` --- ### Step 2: Database Setup & Schemas If using a dedicated PostgreSQL host or local database, create the `ss_bss` database and user: ```bash sudo -u postgres psql << 'EOF' CREATE DATABASE ss_bss; CREATE USER bss_user WITH ENCRYPTED PASSWORD 'StrongBssPassword2026!'; GRANT ALL PRIVILEGES ON DATABASE ss_bss TO bss_user; ALTER DATABASE ss_bss OWNER TO bss_user; EOF ``` --- ### Step 3: Install BSS Packages #### For All-in-One Deployment: ```bash apt-get install -y -o Dpkg::Options::="--force-overwrite" softswitch-bss-all ``` #### For Distributed DMZ Deployment: - On **Internal Core Server**: ```bash apt-get install -y -o Dpkg::Options::="--force-overwrite" softswitch-bss-api softswitch-bss-web ``` - On **Public DMZ Edge Server**: ```bash apt-get install -y -o Dpkg::Options::="--force-overwrite" softswitch-bss-client ``` --- ### Step 4: Configure Environment Variables Edit `/etc/softswitch/bss-api.env`: ```ini NODE_ENV=production PORT=3002 HOST=127.0.0.1 # Database Configuration DATABASE_URL=postgresql://bss_user:StrongBssPassword2026!@127.0.0.1:5432/ss_bss # JWT Security JWT_SECRET=super-secret-hex-key-minimum-32-chars-long JWT_EXPIRES_IN=7d # Telecom Nodes Sync (Ring2All SBC / PBX) SBC_API_URL=http://127.0.0.1:3003 SBC_API_KEY=sbc_internal_bearer_token # Stripe Payment Gateway (Optional / Recommended) STRIPE_SECRET_KEY=sk_live_YourStripeSecretKeyHere STRIPE_WEBHOOK_SECRET=whsec_YourStripeWebhookSecretHere STRIPE_CURRENCY=usd # OCS Real-Time Rating Cache REDIS_URL=redis://127.0.0.1:6379 ``` Secure permissions and restart the API daemon: ```bash chmod 600 /etc/softswitch/bss-api.env systemctl daemon-reload systemctl enable --now softswitch-bss-api systemctl status softswitch-bss-api ``` --- ### Step 5: Configure Nginx Virtual Hosts #### 1. Back-Office Administrative Portal (`/etc/nginx/sites-available/bss-admin`) ```nginx server { listen 80; server_name bss-admin.carrier.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name bss-admin.carrier.com; ssl_certificate /etc/ssl/certs/bss-admin.crt; ssl_certificate_key /etc/ssl/private/bss-admin.key; root /var/www/softswitch/bss/web; index index.html; location / { try_files $uri $uri/ /index.html; } # Internal REST API proxy location /api/ { proxy_pass http://127.0.0.1:3002/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } ``` #### 2. Public Customer Storefront & DMZ Proxy (`/etc/nginx/sites-available/bss-store`) ```nginx server { listen 80; server_name store.carrier.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name store.carrier.com; ssl_certificate /etc/ssl/certs/bss-store.crt; ssl_certificate_key /etc/ssl/private/bss-store.key; root /var/www/softswitch/bss/client; index index.html; location / { try_files $uri $uri/ /index.html; } # DMZ Filtering: ONLY allow customer-facing endpoints location /api/client/ { proxy_pass http://127.0.0.1:3002/api/client/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # Block administrative routes from public store edge location /api/v1/ { return 403; } } ``` Enable and reload Nginx: ```bash ln -sf /etc/nginx/sites-available/bss-admin /etc/nginx/sites-enabled/ ln -sf /etc/nginx/sites-available/bss-store /etc/nginx/sites-enabled/ nginx -t && systemctl reload nginx ``` --- ## 💳 Stripe Payment Gateway Integration Ring2All BSS includes native Stripe integration for automated prepaid wallet recharges and recurring monthly DID/line subscriptions. ### 1. Webhook Endpoint Registration In the Stripe Developer Dashboard (`https://dashboard.stripe.com/webhooks`), create an endpoint: - **URL**: `https://store.carrier.com/api/client/payments/webhook` - **Events to listen for**: - `checkout.session.completed` - `payment_intent.succeeded` - `invoice.paid` - `customer.subscription.deleted` ### 2. Auto-Top-Up Flow When a customer tops up their prepaid balance via credit card or Apple Pay, Stripe sends an authenticated webhook payload signed with `STRIPE_WEBHOOK_SECRET`. The BSS API atomically increments the customer's wallet balance in PostgreSQL and refreshes the in-memory OCS balance cache instantly. --- ## ⚡ Interconnecting OCS with Ring2All SBC & PBX To enforce real-time prepaid balance limits on outbound calling: 1. In the **Ring2All BSS Admin** (`https://bss-admin.carrier.com`), go to **Telecom Nodes** and register your Ring2All SBC: - **Node Type**: `Ring2All SBC (Kamailio)` - **Internal Host**: `10.9.0.1` (or private LAN IP) - **Shared API Token**: Generate a secure bearer token. 2. In **Ring2All SBC**, configure Kamailio's HTTP client module (`http_client`) to query BSS before routing external PSTN calls: ```c # Kamailio OCS Pre-Call Authorization Hook http_client_query("http://192.168.10.50:3002/api/ocs/authorize?caller=$fU&callee=$rU", "$var(ocs_res)"); if ($rc != 200) { sl_send_reply("402", "Payment Required - Insufficient Funds"); exit; } ``` 3. If balance is sufficient, the call proceeds without noticeable setup latency (< 5ms). When the call ends, Kamailio or FreeSWITCH transmits the final duration to `/api/ocs/cdr`, deducting the exact cost from the prepaid wallet. --- ## 🔍 Verification & Health Checks ### 1. Service Status ```bash systemctl status softswitch-bss-api systemctl status nginx ``` ### 2. API Health Check ```bash curl -s http://127.0.0.1:3002/health # Expected: {"status":"ok","service":"softswitch-bss-api","version":"1.0.0"} ``` ### 3. DMZ Reverse Proxy Security Validation ```bash # Permitted customer endpoint (should return 401 Unauthorized or 200 OK) curl -I https://store.carrier.com/api/client/auth/me # Prohibited administrative endpoint (MUST return 403 Forbidden) curl -I https://store.carrier.com/api/v1/users # Expected: HTTP/1.1 403 Forbidden ``` --- ## 🔧 Production Troubleshooting ### 1. Customers see "Network Error" when browsing store - **Cause**: Nginx reverse proxy configuration for `/api/client/` is misconfigured or `softswitch-bss-api` is stopped. - **Solution**: Check API service status and Nginx error logs: ```bash systemctl status softswitch-bss-api tail -f /var/log/nginx/error.log ``` ### 2. Wallet does not update after successful Stripe payment - **Cause**: Stripe webhook secret mismatch or endpoint not receiving POST requests. - **Solution**: Check `journalctl -u softswitch-bss-api -f` while testing a webhook event in the Stripe CLI. Verify `STRIPE_WEBHOOK_SECRET` matches your Stripe dashboard. --- ## 🚀 Next Steps - **[Web Cluster & Load Balancing Guide](web-cluster-load-balancing.md)**: Scale your web frontends. - **[Ring2All SBC Deployment](sbc-deployment.md)**: Secure your perimeter signaling. - **[Distributed PBX Cluster Guide](distributed-cluster.md)**: Scale out telephony core nodes. ================================================================================ DOCUMENT: 02-installation/distributed-cluster TITLE: 🏢 Distributed Multi-Server Cluster Installation Guide URL: https://docs.ring2all.com/02-installation/distributed-cluster.md ================================================================================ > Enterprise step-by-step installation guide for deploying a high-availability, horizontally scalable Ring2All PBX cluster on Debian 13 (Trixie). --- ## 🏛️ Architecture Overview In a distributed deployment, every platform layer is decoupled across dedicated nodes to eliminate single points of failure, provide high availability, and support horizontal scaling up to **100,000+ extensions** and **15,000+ concurrent calls**. ```mermaid flowchart TD subgraph Clients["Clients & Edge Network"] SIP[SIP Endpoints & Hardphones] WebRTC[WebRTC Softphones] Trunks[Carrier SIP Trunks] end subgraph Edge["Edge Perimeter"] SBC["Ring2All SBC Gateway
(Kamailio 6.1 + RTPEngine)"] end subgraph LoadBalancer["Internal DB Routing & Dynamic Proxy"] HAP["Local HAProxy Proxy (:5000 write / :5001 read)
(Auto-tracks Patroni Leader)"] end subgraph TelephonyCore["Telephony Nodes (N+1 FreeSWITCH Cluster)"] FS1["Ring2All PBX Node 01
192.168.10.41"] FS2["Ring2All PBX Node 02
192.168.10.42"] FSN["Ring2All PBX Node N
192.168.10.4x"] end subgraph WebApps["Web & API Layer"] Admin["Admin Server (:443)
192.168.10.40"] API["Platform API (:3001) & Monitoring (:3500)"] Portal["User Portal (:443/portal)"] Switchboard["Switchboard (:443/switchboard)"] end subgraph DataStore["High-Availability Data & Storage Layer"] DB["PostgreSQL 17 HA Cluster
(3 Nodes + Patroni + Etcd)"] Storage["GlusterFS / S3 Cluster
(3 Nodes Replicated Storage)"] end SIP --> SBC WebRTC --> SBC Trunks --> SBC SBC -->|Encrypted WireGuard Mesh / SIP| FS1 SBC -->|Encrypted WireGuard Mesh / SIP| FS2 SBC -->|Encrypted WireGuard Mesh / SIP| FSN Admin --> API Portal --> API Switchboard --> API API --> HAP FS1 --> HAP FS2 --> HAP FSN --> HAP HAP -->|Port 5000 (Write)| DB HAP -->|Port 5001 (Read)| DB FS1 --> Storage FS2 --> Storage FSN --> Storage Admin --> Storage ``` --- ## 🖥️ Server Roles & Lab Topology The following reference topology assumes a private management network on `192.168.10.0/24`: | Role | Hostname | IP Address | Target Packages | Hardware Sizing | | :--- | :--- | :--- | :--- | :--- | | **DB Node 1** | `pg-node-01` | `192.168.10.34` | PostgreSQL 17 + Patroni + Etcd | 4 vCPU, 16 GB RAM, 250 GB NVMe | | **DB Node 2** | `pg-node-02` | `192.168.10.35` | PostgreSQL 17 + Patroni + Etcd | 4 vCPU, 16 GB RAM, 250 GB NVMe | | **DB Node 3** | `pg-node-03` | `192.168.10.36` | PostgreSQL 17 + Patroni + Etcd | 4 vCPU, 16 GB RAM, 250 GB NVMe | | **Storage Node 1** | `fs-node-01` | `192.168.10.37` | `glusterfs-server` | 2 vCPU, 4 GB RAM, 1+ TB HDD/SSD | | **Storage Node 2** | `fs-node-02` | `192.168.10.38` | `glusterfs-server` | 2 vCPU, 4 GB RAM, 1+ TB HDD/SSD | | **Storage Node 3** | `fs-node-03` | `192.168.10.39` | `glusterfs-server` | 2 vCPU, 4 GB RAM, 1+ TB HDD/SSD | | **Admin & API** | `admin` | `192.168.10.40` | `softswitch-admin`, `softswitch-api`, `softswitch-monitoring-api` | 4 vCPU, 8 GB RAM, 100 GB SSD | | **Telephony Node 1** | `fs-01` | `192.168.10.41` | `softswitch-telephony` (FreeSWITCH 1.11+) | 8-16 vCPU, 16-32 GB RAM, 100 GB SSD | | **Telephony Node 2** | `fs-02` | `192.168.10.42` | `softswitch-telephony` (FreeSWITCH 1.11+) | 8-16 vCPU, 16-32 GB RAM, 100 GB SSD | | **Telephony Node N** | `fs-0N` | `192.168.10.4x` | `softswitch-telephony` (N+1 expansion) | 8-16 vCPU, 16-32 GB RAM, 100 GB SSD | | **Portal Node** *(Optional)* | `portal` | `192.168.10.51` | `softswitch-portal`, `nginx` | 2 vCPU, 2 GB RAM, 30 GB SSD | | **Switchboard Node** *(Optional)* | `switchboard` | `192.168.10.52` | `softswitch-switchboard`, `nginx` | 2 vCPU, 2 GB RAM, 30 GB SSD | --- ## 🛠️ Step-by-Step Installation Phases ### Phase 1: High-Availability Database Cluster (Patroni + Etcd) Instead of relying on a single database host, we deploy a 3-node PostgreSQL 17 cluster managed by Patroni and Etcd for Raft consensus. #### 1.1 Hostname & Resolution Mapping On all three DB nodes (`pg-node-01`, `pg-node-02`, `pg-node-03`), configure `/etc/hosts`: ```bash cat << 'EOF' >> /etc/hosts 192.168.10.34 pg-node-01 192.168.10.35 pg-node-02 192.168.10.36 pg-node-03 EOF ``` #### 1.2 Install PostgreSQL 17, Etcd, and Patroni Run on each DB node: ```bash apt-get update apt-get install -y curl gnupg2 lsb-release postgresql-17 patroni etcd-server etcd-client systemctl stop postgresql systemctl disable postgresql ``` #### 1.3 Configure Etcd Cluster On each node, configure `/etc/default/etcd` with its respective IP and peer list, then start the service: ```bash systemctl enable --now etcd etcdctl endpoint health ``` #### 1.4 Configure Patroni & Initialize Schema Create `/etc/patroni/config.yml` on each node specifying the Etcd endpoints and replication slots. Start Patroni on the primary node (`pg-node-01`), allow it to bootstrap the cluster, and start Patroni on standby nodes. Once the leader is elected, install `softswitch-db` on the primary node to create the required Ring2All schemas: ```bash # Add Ring2All APT repository curl -fsSL https://repo.softswitchone.com/apt/setup_repo | bash # Install database schemas and seed data apt-get install -y softswitch-db ``` Verify cluster status on `pg-node-01`: ```bash patronictl -c /etc/patroni/config.yml list ``` --- ### Phase 2: High-Availability Shared Storage (GlusterFS) To share voicemail greetings, tenant call recordings, custom music-on-hold, and uploaded branding assets across all telephony and web nodes, deploy a 3-way replicated GlusterFS volume pool. #### 2.1 Prepare Storage Nodes On `fs-node-01`, `fs-node-02`, and `fs-node-03`: ```bash apt-get update && apt-get install -y glusterfs-server systemctl enable --now glusterd ``` #### 2.2 Peer Probe & Volume Creation From `fs-node-01`: ```bash gluster peer probe 192.168.10.38 gluster peer probe 192.168.10.39 gluster peer status # Create replicated storage volumes mkdir -p /data/glusterfs/brick1/{recordings,uploads,music} gluster volume create ss-recordings replica 3 \ fs-node-01:/data/glusterfs/brick1/recordings \ fs-node-02:/data/glusterfs/brick1/recordings \ fs-node-03:/data/glusterfs/brick1/recordings force gluster volume create ss-uploads replica 3 \ fs-node-01:/data/glusterfs/brick1/uploads \ fs-node-02:/data/glusterfs/brick1/uploads \ fs-node-03:/data/glusterfs/brick1/uploads force gluster volume create ss-music replica 3 \ fs-node-01:/data/glusterfs/brick1/music \ fs-node-02:/data/glusterfs/brick1/music \ fs-node-03:/data/glusterfs/brick1/music force # Start volumes gluster volume start ss-recordings gluster volume start ss-uploads gluster volume start ss-music gluster volume info ``` --- ### Phase 3: Admin & API Server Setup Log in to the Admin Server (`192.168.10.40`). #### 3.1 Install & Configure Local HAProxy To route SQL queries dynamically to the active Patroni leader without hardcoding IPs, install HAProxy locally: ```bash apt-get update apt-get install -y haproxy make curl gnupg2 wget sudo systemctl enable haproxy ``` Write `/etc/haproxy/haproxy.cfg`: ```haproxy global log /dev/log local0 chroot /var/lib/haproxy stats socket /run/haproxy/admin.sock mode 660 level admin stats timeout 30s user haproxy group haproxy daemon defaults log global mode tcp option tcplog timeout connect 5000ms timeout client 50000ms timeout server 50000ms # Port 5000: Write queries dynamically routed to active Patroni Leader frontend pg_write bind 127.0.0.1:5000 default_backend pg_primary backend pg_primary mode tcp option httpchk GET /primary http-check expect status 200 default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions server pg-node-01 192.168.10.34:5432 maxconn 100 maxqueue 10 check port 8008 server pg-node-02 192.168.10.35:5432 maxconn 100 maxqueue 10 check port 8008 server pg-node-03 192.168.10.36:5432 maxconn 100 maxqueue 10 check port 8008 # Port 5001: Read queries load balanced across Standby replicas frontend pg_read bind 127.0.0.1:5001 default_backend pg_replicas backend pg_replicas mode tcp balance roundrobin option httpchk GET /replica http-check expect status 200 default-server inter 3s fall 3 rise 2 server pg-node-01 192.168.10.34:5432 check port 8008 server pg-node-02 192.168.10.35:5432 check port 8008 server pg-node-03 192.168.10.36:5432 check port 8008 ``` Restart and verify: ```bash haproxy -c -f /etc/haproxy/haproxy.cfg systemctl restart haproxy ss -ltn | grep -E '5000|5001' ``` #### 3.2 Sync Database Credentials ```bash mkdir -p /etc/softswitch scp root@192.168.10.34:/etc/softswitch/db-credentials /etc/softswitch/db-credentials chmod 600 /etc/softswitch/db-credentials ``` #### 3.3 Register Repositories & Install API Packages ```bash curl -fsSL https://repo.softswitchone.com/apt/setup_repo | bash apt-get update apt-get install -y nodejs build-essential python3 postgresql-client # Install Ring2All API & telemetry daemons apt-get install -y -o Dpkg::Options::="--force-overwrite" softswitch-api softswitch-monitoring-api ``` #### 3.4 Mount Shared Storage Volumes ```bash apt-get install -y glusterfs-client mkdir -p /var/www/softswitch/uploads # Mount with backup failover servers mount -t glusterfs -o backup-volfile-servers=fs-node-02:fs-node-03 fs-node-01:/ss-uploads /var/www/softswitch/uploads # Add fstab entry cat << 'EOF' >> /etc/fstab fs-node-01:/ss-uploads /var/www/softswitch/uploads glusterfs defaults,_netdev,backup-volfile-servers=fs-node-02:fs-node-03 0 0 EOF ``` #### 3.5 Install Frontend Admin Dashboard ```bash apt-get install -y -o Dpkg::Options::="--force-overwrite" softswitch-admin nginx -t && systemctl reload nginx ``` --- ### Phase 4: User Portal & Switchboard Setup You can host the User Portal and Switchboard on the Admin Server or on dedicated frontend hosts. #### Option A: Co-located on the Admin Server ```bash apt-get install -y -o Dpkg::Options::="--force-overwrite" softswitch-portal softswitch-switchboard nginx -t && systemctl reload nginx ``` The portals will be accessible at `https://admin.example.com/portal` and `https://admin.example.com/switchboard`. #### Option B: Dedicated Servers (e.g., `portal` on `192.168.10.51`) On the dedicated server: ```bash apt-get update && apt-get install -y nginx curl -fsSL https://repo.softswitchone.com/apt/setup_repo | bash apt-get install -y softswitch-portal ``` Configure Nginx reverse proxy at `/etc/nginx/sites-available/softswitch-portal`: ```nginx server { listen 80; server_name portal.example.com; root /var/www/softswitch/portal; index index.html; location / { try_files $uri $uri/ /index.html; } location /api { proxy_pass http://192.168.10.40:3001; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /uploads/ { proxy_pass http://192.168.10.40/uploads/; proxy_http_version 1.1; proxy_set_header Host $host; expires 7d; } } ``` Enable and reload: ```bash ln -sf /etc/nginx/sites-available/softswitch-portal /etc/nginx/sites-enabled/ nginx -t && systemctl reload nginx ``` --- ### Phase 5: Telephony Nodes Setup (FreeSWITCH N+1 Cluster) Repeat these steps on each Telephony node (`fs-01`, `fs-02`, ..., `fs-0N`). #### 5.1 Base Setup & Local HAProxy ```bash apt-get update && apt-get install -y curl gnupg2 wget make sudo haproxy curl -fsSL https://repo.softswitchone.com/apt/setup_repo | bash ``` Deploy `/etc/haproxy/haproxy.cfg` (identical to the Admin node HAProxy configuration in Phase 3.1) so FreeSWITCH queries `127.0.0.1:5000` for writes and `127.0.0.1:5001` for reads. ```bash systemctl restart haproxy ss -ltn | grep 5000 ``` #### 5.2 Copy Database Credentials ```bash mkdir -p /etc/softswitch scp root@192.168.10.34:/etc/softswitch/db-credentials /etc/softswitch/db-credentials chmod 600 /etc/softswitch/db-credentials ``` #### 5.3 (Optional High-Scale) Deploy PgBouncer Connection Pooler (:6432) For nodes handling **>500 concurrent calls** or high CPS bursts, deploy PgBouncer to multiplex thousands of Lua/ODBC queries into 20–30 persistent PostgreSQL connections: ```bash apt-get install -y pgbouncer ``` Configure `/etc/pgbouncer/pgbouncer.ini`: ```ini [databases] ss_telephony = host=127.0.0.1 port=5000 dbname=ss_telephony ring2all = host=127.0.0.1 port=5000 dbname=ring2all kamailio = host=127.0.0.1 port=5000 dbname=kamailio [pgbouncer] logfile = /var/log/postgresql/pgbouncer.log pidfile = /var/run/postgresql/pgbouncer.pid listen_addr = 127.0.0.1 listen_port = 6432 auth_type = md5 auth_file = /etc/pgbouncer/userlist.txt admin_users = postgres, ss_db_user pool_mode = transaction max_client_conn = 5000 default_pool_size = 25 reserve_pool_size = 5 ignore_startup_parameters = extra_float_digits, search_path, application_name ``` Create `/etc/pgbouncer/userlist.txt` with credentials and start: ```bash source /etc/softswitch/db-credentials echo "\"ss_db_user\" \"$DB_PASSWORD\"" > /etc/pgbouncer/userlist.txt chown postgres:postgres /etc/pgbouncer/userlist.txt && chmod 640 /etc/pgbouncer/userlist.txt systemctl enable --now pgbouncer ss -ltn | grep 6432 ``` #### 5.4 Mount Shared Recordings & Music ```bash apt-get install -y glusterfs-client mkdir -p /var/lib/freeswitch/recordings mkdir -p /usr/share/freeswitch/sounds/music mount -t glusterfs -o backup-volfile-servers=fs-node-02:fs-node-03 fs-node-01:/ss-recordings /var/lib/freeswitch/recordings mount -t glusterfs -o backup-volfile-servers=fs-node-02:fs-node-03 fs-node-01:/ss-music /usr/share/freeswitch/sounds/music cat << 'EOF' >> /etc/fstab fs-node-01:/ss-recordings /var/lib/freeswitch/recordings glusterfs defaults,_netdev,backup-volfile-servers=fs-node-02:fs-node-03 0 0 fs-node-01:/ss-music /usr/share/freeswitch/sounds/music glusterfs defaults,_netdev,backup-volfile-servers=fs-node-02:fs-node-03 0 0 EOF ``` #### 5.5 Install FreeSWITCH & Ring2All Telephony Engine ```bash apt-get update apt-get install -y -o Dpkg::Options::="--force-overwrite" softswitch-telephony ``` The post-install script automatically detects the local HAProxy/PgBouncer port and configures `/etc/odbc.ini` and `/etc/freeswitch/autoload_configs/switch.conf.xml`. Verify telephony service: ```bash systemctl status freeswitch fs_cli -x "sofia status" ``` #### 5.6 Register Telephony Node in Admin Web UI In the Admin Dashboard (`https://admin.example.com/admin`), navigate to **Telephony > Telephony Servers** and click **+ Add Telephony Node**: - **Node Name**: `FS-01` - **Internal IP**: `192.168.10.41` - **ESL Port**: `8021` - **Capacity**: `10,000` extensions / `1,500` concurrent calls. --- ### Phase 6: Automated Credentials Distribution Script To simplify cluster maintenance and credential rotation, run this helper script from the DB Leader node: ```bash cat << 'EOF' > /root/distribute-credentials.sh #!/bin/bash set -euo pipefail # Nodes requiring synced db-credentials NODES=( "192.168.10.40" # Admin API Node "192.168.10.41" # Telephony Node 01 "192.168.10.42" # Telephony Node 02 ) echo "Distributing /etc/softswitch/db-credentials across cluster..." for node in "${NODES[@]}"; do echo "Syncing to $node..." ssh root@"$node" "mkdir -p /etc/softswitch" scp /etc/softswitch/db-credentials root@"$node":/etc/softswitch/db-credentials ssh root@"$node" "chmod 600 /etc/softswitch/db-credentials" done echo "Credential sync complete." EOF chmod +x /root/distribute-credentials.sh ``` --- ## 🔍 Cluster Verification Checklist | Layer | Verification Command | Expected Result | | :--- | :--- | :--- | | **Patroni DB** | `patronictl -c /etc/patroni/config.yml list` | 1 Leader (Running), 2 Replicas (Running) | | **Local HAProxy** | `ss -ltn \| grep -E '5000\|5001'` | Ports 5000 and 5001 listening on `127.0.0.1` | | **Shared Storage** | `gluster volume status` | All bricks reported online and active | | **Recordings Sync** | `touch /var/lib/freeswitch/recordings/test.txt` | File appears instantly on other nodes | | **Telephony Core** | `fs_cli -x "sofia status"` | Internal & External profiles `RUNNING` | | **Platform API** | `curl -s http://127.0.0.1:3001/health` | `{"status":"ok"}` | | **ESL Monitoring** | `systemctl status softswitch-monitoring-api` | `active (running)` connected to all nodes | --- ## 🔧 Production Troubleshooting ### 1. FreeSWITCH fails with "CORE DATABASE INITIALIZATION FAILURE" - **Cause**: FreeSWITCH cannot reach the database on `127.0.0.1:5000` or `/etc/odbc.ini` credentials mismatch. - **Solution**: Test ODBC directly: ```bash isql -v ss_telephony ss_db_user "$(grep DB_PASSWORD /etc/softswitch/db-credentials | cut -d= -f2)" ``` Ensure local HAProxy is active (`systemctl restart haproxy`). ### 2. GlusterFS volume reports "Transport endpoint is not connected" - **Cause**: Network interruption or one of the brick processes restarted. - **Solution**: Remount with failover parameters: ```bash mount -a gluster volume heal ss-recordings ``` --- ## 🚀 Next Steps - **[Web Cluster & Load Balancing Guide](web-cluster-load-balancing.md)**: Scale multiple Web Admin and API nodes behind Cloudflare. - **[Ring2All SBC Deployment](sbc-deployment.md)**: Deploy the perimeter SIP gateway with Kamailio 6.1 and RTPEngine. - **[Ring2All BSS Deployment](bss-deployment.md)**: Connect carrier billing, real-time OCS, and the customer store. ================================================================================ DOCUMENT: 02-installation/distributed-overview TITLE: 🏗️ Distributed Deployment Overview URL: https://docs.ring2all.com/02-installation/distributed-overview.md ================================================================================ > Enterprise-grade multi-server deployment for maximum scalability and high availability --- ## 📋 Introduction For enterprise environments, Ring2All PBX can be deployed across multiple servers to achieve: | Goal | Solution | |------|----------| | **High Availability** | No single point of failure | | **Horizontal Scaling** | Add servers as capacity grows | | **Performance Isolation** | Separate workloads across servers | | **Disaster Recovery** | Data replication across nodes | --- ## 🏛️ Architecture Diagram ```mermaid flowchart TD subgraph Clients["Clients & Edge Network"] SIP[SIP Endpoints / Hardphones] WebRTC[WebRTC / Softphones] Trunks[Carrier SIP Trunks] end subgraph Perimeter["Perimeter & Load Balancing"] SBC["Ring2All SBC Cluster
(Kamailio 6.1 + RTPEngine)"] end subgraph TelephonyCore["Telephony Application Core (N+1)"] FS1["Ring2All PBX Node 01
(10,000 Ext / 1,500 Calls)"] FS2["Ring2All PBX Node 02
(10,000 Ext / 1,500 Calls)"] FSN["Ring2All PBX Node N
(Horizontal Scale)"] end subgraph StorageData["Distributed Storage & Database Layer"] DB[("PostgreSQL 17 HA Cluster
(Patroni + Raft Consensus)")] Gluster[("GlusterFS / S3 Cluster
(Voicemail & Call Recordings)")] end subgraph Management["Management & Billing Subsystems"] Admin["Ring2All Web Admin"] Portal["User Portal"] Switchboard["Switchboard Console"] BSS["Ring2All BSS (Carrier Billing)"] end SIP --> SBC WebRTC --> SBC Trunks --> SBC SBC --> FS1 SBC --> FS2 SBC --> FSN FS1 --> DB FS2 --> DB FSN --> DB FS1 --> Gluster FS2 --> Gluster FSN --> Gluster Admin --> DB Portal --> DB Switchboard --> DB BSS --> DB ``` --- ## 📊 Server Roles & Requirements ### Infrastructure Servers | Role | Hostname | IP (Example) | vCPU | RAM | Storage | Packages | |------|----------|--------------|------|-----|---------|----------| | **Database Node 1** | pg-node-01 | 192.168.10.31 | 4 | 16GB | 500GB SSD | PostgreSQL 17 + Patroni + Etcd | | **Database Node 2** | pg-node-02 | 192.168.10.32 | 4 | 16GB | 500GB SSD | PostgreSQL 17 + Patroni + Etcd | | **Database Node 3** | pg-node-03 | 192.168.10.33 | 4 | 16GB | 500GB SSD | PostgreSQL 17 + Patroni + Etcd | | **File Server 1** | fs-node-01 | 192.168.10.34 | 2 | 4GB | 1TB+ HDD/SSD | GlusterFS Server | | **File Server 2** | fs-node-02 | 192.168.10.35 | 2 | 4GB | 1TB+ HDD/SSD | GlusterFS Server | | **File Server 3** | fs-node-03 | 192.168.10.36 | 2 | 4GB | 1TB+ HDD/SSD | GlusterFS Server | ### Application Servers | Role | Hostname | IP (Example) | vCPU | RAM | Storage | Packages | |------|----------|--------------|------|-----|---------|----------| | **Admin** | admin-node-01 | 192.168.10.10 | 4 | 8GB | 50GB | `softswitch-admin` | | **Portal** | portal-node-01 | 192.168.10.20 | 2 | 2GB | 20GB | `softswitch-portal` | | **Switchboard** | switch-node-01 | 192.168.10.30 | 2 | 2GB | 20GB | `softswitch-switchboard` | | **API** | api-node-01 | 192.168.10.40 | 4 | 8GB | 50GB | `softswitch-api` | ### Telephony Servers (N+1) | Role | Hostname | IP (Example) | vCPU | RAM | Storage | Capacity | |------|----------|--------------|------|-----|---------|----------| | **Telephony 1** | tele-node-01 | 192.168.10.51 | 4-16 | 8-32GB | 100GB | 10,000 ext / 1,500 calls | | **Telephony 2** | tele-node-02 | 192.168.10.52 | 4-16 | 8-32GB | 100GB | 10,000 ext / 1,500 calls | | **Telephony N** | tele-node-N | 192.168.10.5N | 4-16 | 8-32GB | 100GB | 10,000 ext / 1,500 calls | --- ## 📈 Scaling Reference ### Telephony Horizontal Scaling | Servers | Total Extensions | Concurrent Calls | Use Case | |---------|-----------------|------------------|----------| | 1 | 10,000 | 1,500 | Medium Enterprise | | 2 | 20,000 | 3,000 | Large Enterprise | | 3 | 30,000 | 4,500 | Enterprise+ | | 5 | 50,000 | 7,500 | Service Provider | | 10 | 100,000 | 15,000 | Carrier Grade | | 20+ | 200,000+ | 30,000+ | Large Carrier | > 💡 **Key Insight:** Each telephony server is independent and connects to the shared database cluster. Add servers as capacity grows without reconfiguration. --- ## 🔄 High Availability Features ### Database Cluster (PostgreSQL + Patroni) | Feature | Description | |---------|-------------| | **Automatic Failover** | If primary fails, replica promotes in <30 seconds | | **Streaming Replication** | Real-time data sync (RPO ≈ 0) | | **Consensus (Etcd)** | Distributed leader election | | **Self-Healing** | Automatic replica recovery | ### File Server Cluster (GlusterFS) | Feature | Description | |---------|-------------| | **Replica 3** | Every file stored on 3 nodes | | **Self-Healing** | Automatic sync after node recovery | | **Active-Active** | All nodes serve traffic | | **Client Failover** | Automatic redirection if node fails | ### Application Layer | Feature | Description | |---------|-------------| | **Stateless Design** | Any API server can handle any request | | **Load Balancing** | HAProxy distributes traffic | | **Health Checks** | Automatic removal of failed nodes | --- ## 📖 Distributed Installation Guides Follow these comprehensive guides for each phase of your distributed infrastructure: | Guide | Description | | :--- | :--- | | 📖 **[Distributed Cluster Step-by-Step Guide](distributed-cluster.md)** | Complete walkthrough: Patroni PostgreSQL 17, GlusterFS, Web/API, and FreeSWITCH N+1 telephony cluster | | 📖 **[Web Cluster & Load Balancing Guide](web-cluster-load-balancing.md)** | Multi-server Web GUI and API high availability behind Cloudflare and HAProxy | | 📖 **[Ring2All SBC Deployment Guide](sbc-deployment.md)** | Perimeter SIP gateway (Kamailio 6.1 + RTPEngine) with WireGuard mesh to PBX nodes | | 📖 **[Ring2All BSS Deployment Guide](bss-deployment.md)** | Carrier billing engine, real-time OCS rating, and public customer self-care store | --- ## 🔗 Network Requirements ### Internal Network (Private LAN / WireGuard Subnet) | Port | Protocol | Service | Between | |------|----------|---------|---------| | 5432 | TCP | PostgreSQL 17 | DB nodes ↔ App/Telephony servers | | 8008 | TCP | Patroni REST API | DB nodes ↔ HAProxy leader check | | 2379/2380 | TCP | Etcd Raft Consensus | DB nodes (peer sync) | | 5000 | TCP | HAProxy Local Write Proxy | Local apps/FreeSWITCH ↔ Patroni Leader | | 5001 | TCP | HAProxy Local Read Proxy | Local apps ↔ Patroni Standby Replicas | | 6432 | TCP | PgBouncer Connection Pooler | FreeSWITCH/ODBC ↔ Local HAProxy | | 24007-24008 | TCP | GlusterFS Daemon | Storage nodes | | 49152-49251 | TCP | GlusterFS Bricks | Storage nodes ↔ Clients (Recordings/Music) | | 51820 | UDP | WireGuard VPN Mesh | Core PBX Nodes ↔ Ring2All SBC | ### External Network (Perimeter Edge) | Port | Protocol | Service | |------|----------|---------| | 80/443 | TCP | HTTP/HTTPS (Web UI & APIs) | | 5060 | UDP/TCP | SIP Signaling (Kamailio SBC) | | 5061 | TCP | SIP TLS (Kamailio SBC) | | 16384-32768 | UDP | RTP Media Relay (RTPEngine) | --- ## 🚀 Quick Start Checklist - [ ] **Network:** Private network configured between all servers (`192.168.10.0/24`) - [ ] **DNS/Hosts:** All servers can resolve each other by hostname - [ ] **Firewall:** Required ports open between servers in `nftables` - [ ] **Storage:** Dedicated NVMe/SSD disks for databases and distributed recordings - [ ] **OS:** Debian 13 (Trixie) installed on all servers --- *Next: 📖 [Distributed Multi-Server Cluster Step-by-Step Guide](distributed-cluster.md)* ================================================================================ DOCUMENT: 02-installation/readme TITLE: 📦 Ring2All Platform - Deployment Topologies & Integrator Roadmap URL: https://docs.ring2all.com/02-installation/readme.md ================================================================================ > Complete master deployment guide and roadmap for system integrators deploying the **Ring2All Platform** (PBX, SBC, and BSS) across all supported architectures on Debian 13 (Trixie). --- ## 🗺️ Integrator Deployment Suite Ring2All provides modular, production-ready installation paths tailored to each organizational tier: ```mermaid flowchart TD subgraph Suite["Ring2All Production Topologies"] Single["🖥️ Single Server All-in-One
(Small Business & Lab Deployments)"] Dist["🏢 Distributed Multi-Server Cluster
(Patroni PostgreSQL 17 + FreeSWITCH N+1)"] WebLB["🌐 Web Cluster & Load Balancing
(Cloudflare Orange Cloud + HAProxy)"] SBC["🛡️ Ring2All SBC Deployment
(Kamailio 6.1 + RTPEngine 12.5 + WireGuard)"] BSS["💳 Ring2All BSS (Carrier Billing)
(Real-Time OCS + Customer Storefront)"] end Single -.->|Scale Out| Dist Dist <--> WebLB SBC <==|Encrypted WireGuard Mesh| Dist SBC <-->|Sub-millisecond OCS Auth| BSS Dist <-->|CDR & Balance Sync| BSS ``` --- ## 📚 Dedicated Step-by-Step Installation Guides | Deployment Environment | Target Scope | Key Components | Direct Link | | :--- | :--- | :--- | :--- | | **🖥️ Single Server (All-in-One)** | POC, Lab, Small & Mid Businesses (up to 2,500 ext / 400 calls) | All 11 PBX packages, PostgreSQL 17, FreeSWITCH 1.11+, Nginx, Let's Encrypt | 📖 **[Single Server Guide](single-server.mdx)** | | **🏢 Distributed Multi-Server Cluster** | Large Enterprise & Telco (10,000–100,000+ ext / 15,000+ calls) | 3-node Patroni DB, GlusterFS/S3 shared recordings, FreeSWITCH N+1 cluster, local HAProxy | 📖 **[Distributed Cluster Guide](distributed-cluster.md)** | | **🌐 Web Cluster & Load Balancing** | High-availability Web GUIs & REST APIs | Decoupled Web nodes, Cloudflare Load Balancers, SSL termination, Sticky Session routing | 📖 **[Web Cluster Guide](web-cluster-load-balancing.md)** | | **🛡️ Ring2All SBC Deployment** | Perimeter SIP Security & NAT Traversal Gateway | Kamailio 6.1+, RTPEngine 12.5+, Pike anti-flood, WireGuard mesh to PBX core | 📖 **[Ring2All SBC Guide](sbc-deployment.md)** | | **💳 Ring2All BSS (Billing & OCS)** | Carrier Monetization, Real-time Rating & Customer Store | Fastify 5 OCS engine, prepaid customer wallets, Stripe payments, customer self-care portal | 📖 **[Ring2All BSS Guide](bss-deployment.md)** | --- ## 🏛️ Architectural Topologies at a Glance ### 1. Single Server All-in-One All softswitch applications, FreeSWITCH telephony core, and PostgreSQL 17 database run on a single machine. Nginx acts as the front-facing reverse proxy dispatching traffic to Web frontends (`/admin`, `/portal`, `/switchboard`), REST API (`:3000`), and WebSocket telemetry (`:3001`). - **Best For**: Rapid deployments, lab testing, small businesses (< 500 extensions). - **Setup Time**: < 10 minutes via the one-command automated script `install-softswitch.sh`. ### 2. Enterprise Distributed Multi-Server Cluster Every functional layer is decoupled across dedicated physical or cloud virtual machines: - **Database Layer**: 3-node PostgreSQL 17 cluster orchestrated by Patroni and Etcd for Raft consensus with automatic sub-30s failovers. - **Shared Storage Layer**: 3-way replicated GlusterFS pool (or S3-compatible object storage) ensuring tenant recordings and audio prompts are instantly synchronized across all nodes. - **Telephony Execution Layer (N+1)**: Stateless FreeSWITCH 1.11+ nodes connecting to the database via local HAProxy / PgBouncer loopback proxies. Add nodes horizontally as call volumes scale without modifying tenant configs. ### 3. Ring2All SBC Perimeter Gateway Shields your core telephony cluster with zero public IP exposure: - **Kamailio 6.1+**: Handles SIP registration, RFC 3263 SRV/NAPTR discovery, dispatcher load balancing across PBX nodes, and DDoS protection via the Pike module. - **RTPEngine 12.5+**: High-performance kernel-based media proxy handling symmetric NAT traversal and WebRTC transcoding without CPU strain. - **WireGuard Mesh**: PBX nodes connect from private subnets (`192.168.10.x`) to the SBC via encrypted WireGuard transit tunnels (`10.9.0.0/24`), preventing internet SIP scanners from reaching FreeSWITCH. ### 4. Ring2All BSS Carrier Billing & Customer Storefront Provides the commercial monetization layer: - **Separation of Concerns**: Back-office rate decks and margins (`softswitch-bss-web`) remain on internal management networks, while the customer storefront (`softswitch-bss-client`) is exposed to the public DMZ edge. - **Real-Time OCS**: Queries prepaid balances and rate tables in < 2ms, authorizing outbound calls via Kamailio or FreeSWITCH before bridge establishment. --- ## 📋 Hardware Sizing Matrix | Deployment Tier | Extensions | Concurrent Calls | vCPU | RAM | Storage | Topology Recommendation | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | **Small / Lab** | < 500 | ~50 | 4 vCPU | 8 GB | 100 GB SSD | Single Server All-in-One | | **Medium Business** | ~2,500 | ~400 | 8 vCPU | 16 GB | 250 GB SSD | High-Spec Single Server or 2-Node | | **Enterprise** | ~10,000 | ~1,500 | 16 vCPU | 32 GB | 500 GB NVMe | 3-Node Distributed Cluster | | **Service Provider** | ~50,000 | ~7,500 | Distributed | Distributed | 1+ TB SAN/S3 | Full Distributed (5+ Telephony Nodes + SBC Cluster) | | **Carrier Grade** | 100,000+ | 15,000+ | Distributed | Distributed | Multi-TB | Patroni DB HA + N+1 PBX Nodes + Dual Active-Active SBCs + BSS DMZ | --- import { Tabs, TabItem } from '@astrojs/starlight/components'; ## 📦 Official System Repository Setup All Ring2All packages are distributed through official, cryptographically signed APT repositories: ```bash # Install system prerequisites apt update && apt install -y curl gnupg2 lsb-release # Add Ring2All GPG signing key mkdir -p /etc/apt/keyrings curl -fsSL https://repo.softswitchone.com/gpg.key | gpg --dearmor -o /etc/apt/keyrings/ring2all.gpg # Register official repository echo "deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt trixie main" > /etc/apt/sources.list.d/ring2all.list # Update package index apt update ``` ```bash apt update && apt install -y curl gnupg2 lsb-release mkdir -p /etc/apt/keyrings curl -fsSL https://repo.softswitchone.com/gpg.key | gpg --dearmor -o /etc/apt/keyrings/ring2all.gpg echo "deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt bookworm main" > /etc/apt/sources.list.d/ring2all.list apt update ``` ```bash sudo apt update && sudo apt install -y curl gnupg2 lsb-release sudo mkdir -p /etc/apt/keyrings curl -fsSL https://repo.softswitchone.com/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/ring2all.gpg echo "deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt noble main" | sudo tee /etc/apt/sources.list.d/ring2all.list sudo apt update ``` --- ## 📦 Modular Debian Package Catalog The Ring2All ecosystem is packaged into distinct, modular components: ### 1. Ring2All PBX Packages - **`softswitch-all`**: Master metapackage deploying the complete PBX platform. - **`softswitch-db`**: PostgreSQL 17 database schemas, default migrations, and seed data. - **`softswitch-api`**: Fastify 5 REST API daemon (Port 3000/3001). - **`softswitch-monitoring-api`**: Real-time ESL telemetry & WebSocket hub (Port 3001/3500). - **`softswitch-admin`**: Static React 18 administration portal + authoritative Nginx configuration. - **`softswitch-portal`**: Static React 18 end-user self-service portal. - **`softswitch-switchboard`**: Static React 18 operator console. - **`softswitch-telephony`**: FreeSWITCH 1.11+ configuration, Lua routing scripts, dialplans, and AI engine. - **`softswitch-music`**: Multi-rate Music on Hold WAV audio packages. - **`softswitch-voiceguide-emma`**: English (US) system audio prompts. - **`softswitch-voiceguide-paloma`**: Spanish (US/LATAM) system audio prompts. ### 2. Ring2All SBC Packages - **`softswitch-sbc`**: Unified perimeter gateway package pulling Kamailio 6.1+, RTPEngine 12.5+, `sbc-api` (Port 3003), Nginx web console, WireGuard VPN hub, and nftables rulesets. ### 3. Ring2All BSS Packages - **`softswitch-bss-all`**: Metapackage for single-server billing deployments. - **`softswitch-bss-api`**: Fastify 5 OCS engine, customer REST API, Stripe webhooks, and billing daemon (Port 3002). - **`softswitch-bss-web`**: React 18 back-office billing administrative console. - **`softswitch-bss-client`**: React 18 customer-facing self-care store & wallet portal. --- ## 🔒 Master Network & Firewall Matrix | Port | Protocol | Layer / Service | Scope | Allowed Sources | | :--- | :--- | :--- | :--- | :--- | | **22** | TCP | SSH Administration | Perimeter / Management | Restricted Admin IPs / VPN | | **80 / 443** | TCP | HTTP / HTTPS (Web Portals & APIs) | Public / Edge | Public Internet (or Cloudflare Orange Cloud ☁️🧡) | | **5060** | UDP/TCP | SIP Signaling (Kamailio SBC) | Public Edge | Public Internet (Cloudflare Grey Cloud ☁️🩶 Only) | | **5061** | TCP | SIP TLS Signaling (Kamailio SBC) | Public Edge | Public Internet (Cloudflare Grey Cloud ☁️🩶 Only) | | **16384–32768** | UDP | RTP Audio Media (RTPEngine) | Public Edge | Public Internet / Carrier IP ranges | | **51820** | UDP | WireGuard Transit Mesh (`wg0`) | Inter-Server | PBX Telephony Nodes ↔ SBC Hub | | **5432** | TCP | PostgreSQL 17 Core | Internal LAN | Patroni Peers, DB Clients, HAProxy | | **8008** | TCP | Patroni Health & REST API | Internal LAN | HAProxy Leader Checks | | **2379 / 2380**| TCP | Etcd Raft Consensus | Internal LAN | PostgreSQL DB Nodes Only | | **5000** | TCP | HAProxy Local Leader Write Proxy | Loopback (`127.0.0.1`) | Local API & FreeSWITCH Instances | | **5001** | TCP | HAProxy Local Replica Read Proxy | Loopback (`127.0.0.1`) | Local API Instances | | **6432** | TCP | PgBouncer Transaction Pooler | Loopback (`127.0.0.1`) | FreeSWITCH ODBC Connection Pool | | **24007–24008**| TCP | GlusterFS Management Daemon | Internal LAN | Storage Nodes & Client Mounts | | **49152–49251**| TCP | GlusterFS Storage Bricks | Internal LAN | Storage Nodes & Client Mounts | --- ## 🚀 Getting Started Select the installation guide suited for your infrastructure: - 🖥️ **[Single Server All-in-One Installation](single-server.mdx)** - 🏢 **[Distributed Multi-Server Cluster Step-by-Step Guide](distributed-cluster.md)** - 🌐 **[Web Cluster & Load Balancing Guide](web-cluster-load-balancing.md)** - 🛡️ **[Ring2All SBC Perimeter Deployment Guide](sbc-deployment.md)** - 💳 **[Ring2All BSS (Billing & OCS) Deployment Guide](bss-deployment.md)** ================================================================================ DOCUMENT: 02-installation/sbc-deployment TITLE: 🛡️ Ring2All SBC (Session Border Controller) Deployment Guide URL: https://docs.ring2all.com/02-installation/sbc-deployment.md ================================================================================ > Complete step-by-step guide for installing and configuring **Ring2All SBC** on Debian 13 (Trixie), shielding your core telephony cluster with perimeter security, NAT traversal, and encrypted WireGuard mesh. --- ## 🏛️ Architecture Overview The **Ring2All SBC (Session Border Controller)** serves as the hardened security perimeter between untrusted public networks (internet subscribers, remote softphones, PSTN carrier trunks) and your private core telephony cluster (Ring2All PBX nodes). ```mermaid flowchart TB subgraph PublicInternet["Public Internet & Carrier Networks"] Subscribers["Remote SIP & WebRTC Clients
(Hardphones, Softphones, Mobile Apps)"] Carriers["Upstream PSTN Carrier Trunks
(Inbound DIDs & Outbound Termination)"] end subgraph SBCPerimeter["Ring2All SBC Gateway (Public IP: 203.0.113.10)"] Firewall["nftables + Pike Anti-Flood Shield"] Kamailio["Kamailio 6.1+ SIP Signaling Engine
(Dispatcher Load Balancing, LCR, Topology Hiding)"] RTPEngine["Sipwise RTPEngine 12.5+ Media Relay
(NAT Traversal, SRTP-to-RTP Transcoding)"] SbcApi["SBC REST API (Fastify 5 :3003)"] SbcWeb["Nginx Reverse Proxy & Admin Web UI (:443)"] WGGateway["WireGuard Mesh Hub (wg0: 10.9.0.1)"] end subgraph PrivateCore["Private Core Network (Zero Public IP Exposure)"] direction TB FS1["Ring2All PBX Node 01
(wg0: 10.9.0.2 / LAN: 192.168.10.41)"] FS2["Ring2All PBX Node 02
(wg0: 10.9.0.3 / LAN: 192.168.10.42)"] BSS["Ring2All BSS (Real-Time OCS Engine)
(LAN: 192.168.10.50)"] end Subscribers -->|Public SIP :5060 / :5061| Firewall Carriers -->|Public SIP :5060| Firewall Subscribers -.->|Public Audio RTP 16384-32768| RTPEngine Carriers -.->|Public Audio RTP 16384-32768| RTPEngine Firewall --> Kamailio Kamailio <--> RTPEngine Kamailio <--> SbcApi SbcWeb <--> SbcApi Kamailio <-->|Encrypted SIP via wg0| WGGateway WGGateway <==|Encrypted WireGuard Mesh (UDP 51820)|==> FS1 WGGateway <==|Encrypted WireGuard Mesh (UDP 51820)|==> FS2 Kamailio <-->|Sub-millisecond OCS Auth| BSS ``` ### Core Responsibilities: 1. **Topology Hiding & Complete Shielding**: Internal FreeSWITCH PBX nodes have **zero public IP exposure**. They sit safely in private subnets, reachable only via encrypted WireGuard tunnels (`10.9.0.0/24`). 2. **High-Performance Media Relay (RTPEngine 12.5+)**: Seamlessly traverses aggressive symmetric NATs, bridges WebRTC (DTLS-SRTP) with legacy carrier RTP, and handles audio streams without CPU overhead. 3. **Perimeter Defense (Pike & nftables)**: Identifies and bans SIP brute-force scanners, floods, and malformed packets in real time. 4. **Dispatcher Load Balancing & LCR**: Evenly distributes SIP calls across the PBX cluster using round-robin or hash-based dispatchers with active SIP OPTIONS health-checks. --- ## 🖥️ System Requirements | Specification | Minimum | Recommended | High Volume / Carrier | | :--- | :--- | :--- | :--- | | **Operating System** | Debian 13 (Trixie) 64-bit | Debian 13 (Trixie) 64-bit | Debian 13 (Trixie) 64-bit | | **CPU** | 4 vCPU | 8 vCPU | 16+ vCPU | | **RAM** | 8 GB | 16 GB | 32 GB | | **Storage** | 80 GB SSD | 160 GB NVMe | 300+ GB NVMe | | **Network Interfaces** | 1 Public IPv4 + 1 Private LAN | 1 Public IPv4 + 1 Private LAN | 10 Gbps redundant NICs | | **Concurrent Calls** | ~500 | ~2,500 | ~10,000+ | --- ## ⚡ Option 1: Automated One-Touch Installation (Recommended) Ring2All provides an automated one-touch installer that provisions Kamailio 6.1, RTPEngine 12.5, PostgreSQL 17, WireGuard VPN, Nginx reverse proxies, and the SBC management API in a single run. Execute the following command as `root` on your clean Debian 13 server: ```bash wget -O- https://repo.softswitchone.com/apt/install-sbc.sh | bash ``` ### What the Automated Script Configures: 1. Installs base utilities (`curl`, `gnupg2`, `openssl`, `nginx`, `postgresql`, `wireguard`, `fail2ban`, `nftables`). 2. Registers the official Node.js 22 LTS runtime. 3. Installs Kamailio 6.1+ (`kamailio`, `kamailio-postgres-modules`, `kamailio-tls-modules`, `kamailio-websocket-modules`, `kamcli`). 4. Bootstraps the `kamailio` database schema and sets up default domains. 5. Installs the unified `softswitch-sbc` package from the Ring2All repository. 6. Deploys the Fastify-based REST API service (`sbc-api.service`) listening on loopback port `3003`. 7. Configures Nginx virtual host at `/etc/nginx/sites-available/softswitch-sbc` with TLS and WebSocket proxies. 8. Initializes the WireGuard VPN hub interface (`wg0` on `10.9.0.1/24`, UDP port `51820`). 9. Deploys secure `nftables` firewall rules protecting administrative ports while opening SIP and media ports. --- ## 🛠️ Option 2: Step-by-Step Manual Installation If your infrastructure requires fine-grained control, follow this manual step-by-step process. ### Step 1: System Packages & Repositories ```bash # Update and install base tools apt-get update && apt-get install -y curl wget gnupg2 openssl nginx unixodbc odbc-postgresql fail2ban nftables wireguard # Setup Node.js 22 LTS curl -fsSL https://deb.nodesource.com/setup_22.x | bash - apt-get install -y nodejs build-essential # Add Ring2All Official Repository curl -fsSL https://repo.softswitchone.com/apt/setup_repo | bash apt-get update ``` ### Step 2: Database Initialization ```bash apt-get install -y postgresql-17 # Create SBC administrative database and user sudo -u postgres psql << 'EOF' CREATE DATABASE sbc_admin; CREATE USER sbc_user WITH ENCRYPTED PASSWORD 'ChangeMeSecurely123!'; GRANT ALL PRIVILEGES ON DATABASE sbc_admin TO sbc_user; ALTER DATABASE sbc_admin OWNER TO sbc_user; EOF ``` ### Step 3: Install Kamailio 6.1 & RTPEngine ```bash # Install Kamailio core and modules apt-get install -y kamailio kamailio-postgres-modules kamailio-tls-modules \ kamailio-websocket-modules kamailio-json-modules kamailio-presence-modules kamcli # Install Sipwise RTPEngine apt-get install -y rtpengine rtpengine-daemon rtpengine-iptables ``` Initialize the Kamailio PostgreSQL schema: ```bash kamdbctl create # Enter your PostgreSQL credentials when prompted to initialize 'kamailio' database. ``` ### Step 4: Install Ring2All SBC Core Package ```bash apt-get install -y -o Dpkg::Options::="--force-overwrite" softswitch-sbc ``` This installs: - `/var/www/softswitch-sbc/api` (SBC Management REST API) - `/var/www/softswitch-sbc/web` (React Administrative Web Console) - `/etc/softswitch/sbc-api.env` (Environment variables) - `/etc/systemd/system/sbc-api.service` Enable and start the API service: ```bash systemctl daemon-reload systemctl enable --now sbc-api systemctl status sbc-api ``` ### Step 5: Nginx Reverse Proxy Configuration Verify `/etc/nginx/sites-available/softswitch-sbc`: ```nginx server { listen 80; server_name sbc.example.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name sbc.example.com; ssl_certificate /etc/ssl/certs/softswitch-sbc.crt; ssl_certificate_key /etc/ssl/private/softswitch-sbc.key; # Static Web UI root /var/www/softswitch-sbc/web; index index.html; location / { try_files $uri $uri/ /index.html; } # SBC REST API location /api/ { proxy_pass http://127.0.0.1:3003/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # Real-Time WebSocket Telemetry location /ws { proxy_pass http://127.0.0.1:3003/ws; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_read_timeout 86400; } } ``` Enable and reload: ```bash ln -sf /etc/nginx/sites-available/softswitch-sbc /etc/nginx/sites-enabled/ nginx -t && systemctl reload nginx ``` --- ## 🔒 Connecting Core Telephony via WireGuard Mesh In production multi-datacenter environments, your FreeSWITCH PBX nodes must **never be directly exposed to the public internet**. Instead, they connect to Ring2All SBC via an encrypted WireGuard VPN mesh. ``` ┌────────────────────────────────────────────────────────┐ │ RING2ALL SBC (Server Hub) │ │ Public IP: 203.0.113.10 │ WireGuard IP: 10.9.0.1 │ └───────────────────────────┬────────────────────────────┘ │ 🔒 WireGuard Transit (UDP 51820) │ ┌───────────────────────────┴────────────────────────────┐ │ RING2ALL PBX NODE (Client Spoke) │ │ LAN Only: 192.168.10.41 │ WireGuard IP: 10.9.0.2 │ │ FreeSWITCH bound to: local_ip_v4 = 10.9.0.2 │ └────────────────────────────────────────────────────────┘ ``` ### Method A: Automated via Ring2All SBC Web UI (Recommended) 1. Log in to the SBC Web Console (`https://sbc.example.com`). 2. Navigate to **Network > WireGuard > Peers** and click **+ Add Peer**: - **Peer Name**: `PBX-Node-01` - **Assigned IP**: `10.9.0.2/32` - **Allowed IPs**: `10.9.0.2/32` 3. Click **Generate Keys & Configuration**. 4. Download or copy the generated client configuration snippet. 5. On the FreeSWITCH PBX node, paste the content into `/etc/wireguard/wg0.conf`: ```bash apt-get install -y wireguard nano /etc/wireguard/wg0.conf systemctl enable --now wg-quick@wg0 ``` 6. Verify tunnel connectivity from the PBX node: ```bash ping 10.9.0.1 ``` ### Method B: Manual WireGuard Server Configuration On the Ring2All SBC server, `/etc/wireguard/wg0.conf` should look like this: ```ini [Interface] Address = 10.9.0.1/24 ListenPort = 51820 PrivateKey = PostUp = nft add rule inet filter input iifname "wg0" accept PostDown = nft delete rule inet filter input iifname "wg0" accept # PBX Node 01 [Peer] PublicKey = AllowedIPs = 10.9.0.2/32 # PBX Node 02 [Peer] PublicKey = AllowedIPs = 10.9.0.3/32 ``` Restart WireGuard: ```bash systemctl restart wg-quick@wg0 wg show ``` ### WireGuard Audio Performance & Capacity WireGuard executes as an in-kernel module (`wireguard.ko`) utilizing modern ChaCha20-Poly1305 cryptography. It delivers **3 to 5+ Gbps throughput** with near-zero CPU footprint: - 1,000 simultaneous G.711 PCMU calls require only **~80 Mbps** and ~50,000 pps. - WireGuard introduces **< 0.1 ms latency**, completely undetectable in voice audio quality. --- ## 🌐 DNS & Cloudflare Architecture (Crucial) When configuring DNS for Ring2All SBC, keep in mind that **Cloudflare standard proxy (Orange Cloud ☁️🧡) supports ONLY HTTP/HTTPS traffic. Cloudflare DOES NOT proxy UDP SIP traffic on port 5060**. ### 1. SIP Signaling DNS Records (Mandatory Grey Cloud ☁️🩶) For SIP registration and carrier trunking, you must create a DNS record with the **Cloudflare proxy disabled** (Grey Cloud ☁️🩶) pointing directly to the SBC public IP: | Type | Name | Content | Proxy Status | Purpose | | :--- | :--- | :--- | :--- | :--- | | **A** | `sbc.example.com` | `203.0.113.10` | **DNS Only (Grey Cloud ☁️🩶)** | SIP UDP/TCP Signaling | | **A** | `sip.example.com` | `203.0.113.10` | **DNS Only (Grey Cloud ☁️🩶)** | Hardphone Registrar | ### 2. SIP Auto-Discovery via SRV Records (RFC 3263) To enable zero-touch provisioning and allow phones to discover the SBC without typing port numbers: ```dns _sip._udp.example.com. IN SRV 10 50 5060 sbc.example.com. _sips._tcp.example.com. IN SRV 10 50 5061 sbc.example.com. ``` ### 3. Web Admin Console DNS Records (Orange Cloud ☁️🧡) The web administration interface can safely use Cloudflare's CDN and WAF (Orange Cloud ☁️🧡): | Type | Name | Content | Proxy Status | Purpose | | :--- | :--- | :--- | :--- | :--- | | **CNAME** | `sbc-admin.example.com` | `sbc.example.com` | **Proxied (Orange Cloud ☁️🧡)** | Web Dashboard & WAF | --- ## 🔍 Verification & Health Checks Run these commands to verify that Ring2All SBC is operating correctly: ### 1. Service Status ```bash systemctl status kamailio systemctl status rtpengine systemctl status sbc-api systemctl status nginx systemctl status wg-quick@wg0 ``` ### 2. Local API Health Check ```bash curl -s http://127.0.0.1:3003/health # Expected: {"status":"ok","service":"sbc-api","version":"1.0.0"} ``` ### 3. Active Port Listeners ```bash ss -ulnp | grep -E '5060|51820' # Expected: Kamailio listening on 0.0.0.0:5060 and 10.9.0.1:5060; WireGuard on 0.0.0.0:51820 ``` ### 4. Kamailio Runtime Inspection ```bash # Check loaded modules kamcmd system.listMethods # Check dispatcher status (PBX cluster nodes) kamcmd dispatcher.list # Inspect active RTPEngine media sessions rtpengine-ctl list sessions ``` --- ## 🔧 Production Troubleshooting ### 1. Phones fail to register with "Request Timeout (408)" - **Cause**: DNS is pointing through Cloudflare Orange Cloud (which drops UDP port 5060) or `nftables` is dropping inbound SIP packets. - **Solution**: Set DNS record to **Grey Cloud (DNS Only)** in Cloudflare. Check firewall rules: ```bash nft list ruleset | grep 5060 ``` ### 2. One-Way Audio on Calls Traversing SBC - **Cause**: RTPEngine is advertising an internal IP instead of the public IP in SDP headers. - **Solution**: Verify `/etc/rtpengine/rtpengine.conf` interface configuration: ```ini interface = external/203.0.113.10;internal/10.9.0.1 ``` Ensure RTP port range `16384-32768/udp` is permitted through the cloud security group. --- ## 🚀 Next Steps - **[Web Cluster & Load Balancing Guide](web-cluster-load-balancing.md)**: Scale your frontend interfaces. - **[Distributed PBX Cluster Guide](distributed-cluster.md)**: Scale out N+1 FreeSWITCH telephony nodes behind this SBC. - **[Ring2All BSS Deployment](bss-deployment.md)**: Connect carrier billing, OCS rating, and customer self-care portals. ================================================================================ DOCUMENT: 02-installation/single-server TITLE: 🖥️ Single Server Installation Guide URL: https://docs.ring2all.com/02-installation/single-server.md ================================================================================ > Complete step-by-step guide for installing Ring2All PBX on a single server --- ## 🏛️ Architecture Diagram ```mermaid flowchart TB subgraph External["External Network"] Endpoints[SIP Phones & WebRTC Clients] PSTN[Carrier SIP Trunk Provider] end subgraph SingleServer["Single Server Infrastructure (Debian 13)"] Nginx["Reverse Proxy (Nginx 1.26+ SSL/TLS)"] subgraph Apps["Web Applications"] Admin["Ring2All Admin Web (:443)"] Portal["User Portal (:443/portal)"] Switch["Switchboard (:443/switchboard)"] BSS["Ring2All BSS (:443/billing)"] end subgraph BackendServices["Backend Services (Node.js 22 & Fastify 5)"] Api["Platform API (:3000)"] MonitorApi["Monitoring API (:3001)"] end subgraph Telephony["Telephony Core (FreeSWITCH 1.11+)"] Sofia["Sofia SIP Profile (UDP/TCP/TLS :5060)"] RTP["RTP Audio Media (UDP 16384-32768)"] Lua["Lua Routing Engine"] end subgraph Data["Database & Storage"] PG[("PostgreSQL 17 DB Engine")] Recordings[("Local Audio & Recordings (/var/lib/softswitch)")] end end Endpoints -->|SIP / WebRTC| Sofia Endpoints -->|HTTPS| Nginx PSTN -->|SIP Inbound/Outbound| Sofia PSTN -.->|Audio RTP| RTP Endpoints -.->|Audio RTP| RTP Nginx --> Admin Nginx --> Portal Nginx --> Switch Nginx --> BSS Nginx --> Api Nginx --> MonitorApi Admin --> Api Portal --> Api Switch --> MonitorApi BSS --> Api Api --> PG MonitorApi --> PG Telephony --> PG Telephony --> Recordings ``` --- ## 📋 Prerequisites ### Hardware Requirements | Component | Minimum | Recommended | High Performance | |-----------|---------|-------------|------------------| | **CPU** | 4 vCPU | 8 vCPU | 16+ vCPU | | **RAM** | 8 GB | 16 GB | 32+ GB | | **Storage** | 100 GB SSD | 250 GB SSD | 500+ GB NVMe | | **Network** | 100 Mbps | 1 Gbps | 10 Gbps | ### Software Requirements - **Operating System:** Debian 13 (Trixie) - 64-bit - **Network:** Static IP address configured - **Root Access:** Required for installation ### Capacity Reference | Configuration | Extensions | Concurrent Calls | |---------------|------------|------------------| | Minimum (4 vCPU, 8GB) | ~500 | ~50 | | Recommended (8 vCPU, 16GB) | ~2,500 | ~400 | | High Performance (16+ vCPU, 32GB+) | ~10,000 | ~1,500 | --- import { Tabs, TabItem } from '@astrojs/starlight/components'; ## ⚡ Option 1: Automated One-Command Installation (Recommended) For rapid all-in-one deployment on a clean Debian 13 (Trixie) server, run the official bootstrap installer as `root`: ```bash wget -O- https://repo.softswitchone.com/apt/install-softswitch.sh | bash ``` ### What this script performs automatically: 1. Configures Debian system prerequisites and DNS settings. 2. Installs Node.js 22 LTS, PostgreSQL 17, and security packages (`fail2ban`, `nftables`). 3. Registers the official Ring2All APT repository components (`base`, `core`, `devel`, `extras`, `audios`). 4. Installs the `softswitch-all` orchestrator meta-package, deploying all 10 core packages in correct dependency order. 5. Bootstraps databases, initializes system DSNs, and starts systemd services. --- ## 🛠️ Option 2: Step-by-Step Package Installation If you prefer installing individual packages or customizing dependencies: ### Step 1: Add Ring2All Repository ```bash # Install prerequisites apt update && apt install -y curl gnupg2 lsb-release # Add GPG key mkdir -p /etc/apt/keyrings curl -fsSL https://repo.softswitchone.com/gpg.key | gpg --dearmor -o /etc/apt/keyrings/ring2all.gpg # Add repository echo "deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt trixie main" > /etc/apt/sources.list.d/ring2all.list # Update package list apt update ``` ```bash # Install prerequisites apt update && apt install -y curl gnupg2 lsb-release # Add GPG key mkdir -p /etc/apt/keyrings curl -fsSL https://repo.softswitchone.com/gpg.key | gpg --dearmor -o /etc/apt/keyrings/ring2all.gpg # Add repository echo "deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt bookworm main" > /etc/apt/sources.list.d/ring2all.list # Update package list apt update ``` ```bash # Install prerequisites sudo apt update && sudo apt install -y curl gnupg2 lsb-release # Add GPG key sudo mkdir -p /etc/apt/keyrings curl -fsSL https://repo.softswitchone.com/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/ring2all.gpg # Add repository echo "deb [signed-by=/etc/apt/keyrings/ring2all.gpg] https://repo.softswitchone.com/apt noble main" | sudo tee /etc/apt/sources.list.d/ring2all.list # Update package list sudo apt update ``` ### Step 2: Install Packages #### Quick Method (AIO Meta-Package): ```bash apt install -y softswitch-all ``` #### Granular Method (Individual Packages): ```bash # 1. Database (creates schemas, users, tables) apt install -y softswitch-db # 2. API Backend & Telemetry apt install -y softswitch-api softswitch-monitoring-api # 3. Web Frontends (Admin, Portal, Switchboard) & Authoritative Nginx config apt install -y softswitch-admin softswitch-portal softswitch-switchboard # 4. Telephony Core (FreeSWITCH 1.11+ & Lua Routing) apt install -y softswitch-telephony # 5. Audio Assets & Multilingual Voice Prompts apt install -y softswitch-music softswitch-voiceguide-emma softswitch-voiceguide-paloma # 6. (Optional) Ring2All BSS Carrier Billing & Storefront on same node apt install -y softswitch-bss-all ``` ### Step 3: Enable & Start Services ```bash # Database systemctl enable --now postgresql # Telephony Core systemctl enable --now freeswitch # Backend APIs systemctl enable --now softswitch-api systemctl enable --now softswitch-monitoring-api # Web Server (Nginx) systemctl enable --now nginx ``` **That's it!** 🎉 Your Ring2All PBX is now running. --- ## ✅ Post-Installation Verification ### Check Services Status ```bash # All services should show "active (running)" systemctl status postgresql systemctl status freeswitch systemctl status softswitch-api systemctl status softswitch-monitoring-api systemctl status nginx ``` ### Check Database Connection ```bash # Read generated credentials cat /etc/softswitch/db-credentials # Test connection (should show 6 databases) sudo -u postgres psql -c "\l" # Expected: ss_admin, ss_telephony, ss_cdr, ss_cc, ss_logs, freeswitch ``` ### Check Telephony Server ```bash # Enter Telephony Server CLI fs_cli # Check status (should show internal and external profiles) sofia status # Exit /exit ``` ### Access Web Interfaces | Interface | URL | Description | |-----------|-----|-------------| | **Admin Dashboard** | `https://your-server/admin` | System administration | | **User Portal** | `https://your-server/portal` | End-user self-service | | **Switchboard** | `https://your-server/switchboard` | Operator console | Default login: `admin` / *(check setup wizard or database)* --- ## 🔒 Firewall Configuration ```bash # Allow essential ports ufw allow 22/tcp # SSH ufw allow 80/tcp # HTTP (redirect to HTTPS) ufw allow 443/tcp # HTTPS ufw allow 5060/udp # SIP ufw allow 5060/tcp # SIP over TCP ufw allow 5061/tcp # SIP TLS ufw allow 16384:32768/udp # RTP media # Enable firewall ufw enable ``` --- ## 🔐 SSL Certificate (Let's Encrypt) ```bash # Install certbot apt install certbot python3-certbot-nginx # Obtain certificate (replace with your domain) certbot --nginx -d pbx.example.com # Auto-renewal is configured automatically systemctl status certbot.timer ``` --- ## ⚙️ Nginx Configuration The `softswitch-admin` package includes a default Nginx configuration. For customization: ```bash nano /etc/nginx/sites-available/softswitch ``` ```nginx server { listen 80; server_name _; # Redirect all HTTP to HTTPS return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name _; # SSL Certificates ssl_certificate /etc/ssl/certs/softswitch.crt; ssl_certificate_key /etc/ssl/private/softswitch.key; # Security headers add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; # API Backend (Node.js) location /api { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # WebSocket (Monitoring API) location /ws { proxy_pass http://127.0.0.1:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_read_timeout 86400; } # Admin Dashboard location /admin { alias /var/www/softswitch/web; try_files $uri $uri/ /admin/index.html; } # User Portal location /portal { alias /var/www/softswitch/portal; try_files $uri $uri/ /portal/index.html; } # Switchboard Console location /switchboard { alias /var/www/softswitch/switchboard; try_files $uri $uri/ /switchboard/index.html; } # Root redirect to Admin location = / { return 302 /admin; } } ``` Apply changes: ```bash ln -sf /etc/nginx/sites-available/softswitch /etc/nginx/sites-enabled/ nginx -t && systemctl reload nginx ``` --- ## 📁 Credentials & Configuration Files | File | Description | |------|-------------| | `/etc/softswitch/db-credentials` | Database username and password | | `/etc/softswitch/api.env` | API environment variables | | `/etc/odbc.ini` | ODBC connections for Telephony Server | | `/etc/freeswitch/` | Telephony Server configuration | ### View Credentials ```bash cat /etc/softswitch/db-credentials ``` ``` # Softswitch Database Credentials # Generated: 2026-01-27 15:00:00 DB_USER=ss_db_user DB_PASSWORD=Xk9mN2pQ4rT7 DB_HOST=127.0.0.1 DB_PORT=5432 ``` --- ## 🔧 Resource Optimization Since all services share the same server, optimize resource allocation: ### PostgreSQL Tuning ```bash nano /etc/postgresql/17/main/postgresql.conf ``` ```ini # Memory (adjust based on available RAM) shared_buffers = 2GB # 25% of RAM effective_cache_size = 6GB # 75% of RAM work_mem = 32MB maintenance_work_mem = 512MB # Connections max_connections = 200 # WAL wal_buffers = 64MB checkpoint_completion_target = 0.9 ``` ### Telephony Server Tuning ```bash nano /etc/freeswitch/autoload_configs/switch.conf.xml ``` ```xml ``` --- ## 💾 Backup Strategy ### Automated Daily Backup Script Create `/opt/softswitch-backup.sh`: ```bash #!/bin/bash # Softswitch Single Server Backup Script BACKUP_DIR="/var/backups/softswitch" DATE=$(date +%Y%m%d_%H%M%S) RETENTION_DAYS=7 mkdir -p $BACKUP_DIR # Backup all databases for db in ss_admin ss_telephony ss_cdr ss_cc ss_logs ss_switchboard; do sudo -u postgres pg_dump $db | gzip > "$BACKUP_DIR/${db}_${DATE}.sql.gz" done # Backup Telephony Server configs tar -czf "$BACKUP_DIR/freeswitch_config_${DATE}.tar.gz" /etc/freeswitch # Backup recordings (if any) if [ -d "/var/lib/freeswitch/recordings" ]; then tar -czf "$BACKUP_DIR/recordings_${DATE}.tar.gz" /var/lib/freeswitch/recordings fi # Backup credentials cp /etc/softswitch/db-credentials "$BACKUP_DIR/db-credentials_${DATE}" # Remove old backups find $BACKUP_DIR -type f -mtime +$RETENTION_DAYS -delete echo "Backup completed: $BACKUP_DIR" ``` Enable and schedule: ```bash chmod +x /opt/softswitch-backup.sh # Add to cron (daily at 2 AM) echo "0 2 * * * root /opt/softswitch-backup.sh" >> /etc/crontab ``` --- ## 🔍 Troubleshooting ### Service Not Starting ```bash # Check logs journalctl -u softswitch-api -f journalctl -u freeswitch -f # Check ports ss -tlnp | grep -E '3000|3001|5060|5432' ``` ### Database Connection Issues ```bash # Test PostgreSQL sudo -u postgres psql -c "SELECT 1" # Check ODBC isql -v ss_telephony ss_db_user YOUR_PASSWORD ``` ### Telephony Server SIP Issues ```bash # Check SIP profiles fs_cli -x "sofia status" # Check registrations fs_cli -x "sofia status profile internal reg" # Debug SIP traffic fs_cli -x "sofia profile internal siptrace on" ``` ### Nginx 502 Bad Gateway ```bash # Check if API is running curl http://127.0.0.1:3000/api/health # Check API logs journalctl -u softswitch-api --since "5 minutes ago" ``` --- ## 📈 Scaling Up When your single server reaches capacity, consider: 1. **Vertical Scaling:** Upgrade CPU/RAM 2. **Database Separation:** Move PostgreSQL to dedicated server 3. **Distributed Deployment:** See [Distributed Installation Guide](distributed-overview.md) ### Capacity Indicators (Time to Scale) | Metric | Warning | Critical | |--------|---------|----------| | CPU Usage | > 70% sustained | > 85% | | RAM Usage | > 80% | > 90% | | Concurrent Calls | > 100 | > 150 | | Database Connections | > 150 | > 180 | --- ## 📊 Installation Summary | Component | Location | Port | |-----------|----------|------| | Admin Dashboard | `/var/www/softswitch/web` | 443 (/admin) | | User Portal | `/var/www/softswitch/portal` | 443 (/portal) | | Switchboard | `/var/www/softswitch/switchboard` | 443 (/switchboard) | | API | `/var/www/softswitch/api` | 3000 | | Monitoring WS | `/var/www/softswitch/monitoring-api` | 3001 | | PostgreSQL | System service | 5432 | | Telephony Server | `/etc/freeswitch` | 5060/5061 | | Credentials | `/etc/softswitch/db-credentials` | - | --- *Next: [Distributed Deployment Overview](distributed-overview.md)* ================================================================================ DOCUMENT: 02-installation/web-cluster-load-balancing TITLE: 🌐 Multi-Server Web Cluster & Load Balancing URL: https://docs.ring2all.com/02-installation/web-cluster-load-balancing.md ================================================================================ > Enterprise guide for deploying multiple Ring2All Web and API nodes behind Cloudflare and Nginx for high availability, zero-downtime maintenance, and horizontal scaling. --- ## Table of Contents 1. [Architectural Overview](#1-architectural-overview) 2. [Why Ring2All is 100% Stateless](#2-why-ring2all-is-100-stateless) 3. [Cloudflare Load Balancing Options](#3-cloudflare-load-balancing-options) 4. [Step-by-Step Multi-Node Deployment](#4-step-by-step-multi-node-deployment) 5. [Nginx Configuration on Web Nodes](#5-nginx-configuration-on-web-nodes) 6. [Database & Redis Clustering Requirements](#6-database--redis-clustering-requirements) 7. [Operational Verification & Failover Testing](#7-operational-verification--failover-testing) 8. [Summary & Key Advantages](#8-summary--key-advantages) --- ## 1. Architectural Overview In high-density service provider environments, the web management layer (Ring2All PBX Admin, User Portal, Switchboard Console, and BSS Client Portal) can be scaled horizontally across multiple independent Linux instances without requiring distinct domain names. A single canonical domain (e.g., `*.ring2all.com` or `app.ring2all.com`) serves all web traffic, distributed intelligently across backend nodes by **Cloudflare Edge Load Balancing**: ```mermaid flowchart TD subgraph Clients["Global Ingress (Internet)"] Browser1["Client Browser A
mycompany.ring2all.com"] Browser2["Client Browser B
acme.ring2all.com"] MobileApp["User Portal Mobile PWA"] end subgraph Edge["Cloudflare Anycast Global Edge Network"] CF_WAF["Cloudflare WAF & DDoS Shield"] CF_SSL["Universal SSL Termination (*.ring2all.com)"] CF_LB["Cloudflare Load Balancer / Round-Robin Pool"] end subgraph WebCluster["Stateless Web & API Tier (Port 443 / 80)"] Node1["Web Node 01 (198.51.100.20)
Nginx + softswitch-web + softswitch-api"] Node2["Web Node 02 (198.51.100.21)
Nginx + softswitch-web + softswitch-api"] NodeN["Web Node N (198.51.100.2N)
Horizontal Scale on Demand"] end subgraph DataTier["Centralized State & Storage Layer"] PG[("PostgreSQL 17 HA Cluster
ss_admin | ss_telephony | ss_billing")] Redis[("Redis Cluster / PubSub
Session Cache & WebSocket Broker")] end subgraph TelephonyTier["Perimeter VoIP (Bypasses Web Proxy)"] SBC["Ring2All SBC (Kamailio 6.1)
sbc.ring2all.com (Port 5060/5061)"] end Browser1 --> CF_WAF Browser2 --> CF_WAF MobileApp --> CF_WAF CF_WAF --> CF_SSL CF_SSL --> CF_LB CF_LB -- "Round-Robin / Health Check" --> Node1 CF_LB -- "Round-Robin / Health Check" --> Node2 CF_LB -- "Round-Robin / Health Check" --> NodeN Node1 --> PG Node2 --> PG NodeN --> PG Node1 --> Redis Node2 --> Redis NodeN --> Redis ``` --- ## 2. Why Ring2All is 100% Stateless Unlike legacy PBX platforms that store web sessions in server memory files (`/tmp/sess_*`), Ring2All's application tier is designed with **zero in-memory session lock-in**: 1. **Cryptographic JWT Authentication (Stateless)**: * When an administrator or tenant user logs in, the API issues a signed JSON Web Token (JWT). * **Any Web Node** can decode and cryptographically verify the token using the shared cluster secret key (`JWT_SECRET`). * Request #1 can hit **Web Node 01** and Request #2 can hit **Web Node 02** without requiring sticky sessions or session re-authentication. 2. **Single Page Application (SPA) Decoupling**: * The frontend interfaces (`softswitch-web`, `softswitch-portal`, `softswitch-switchboard`, `softswitch-bss-client`) compile into static HTML5, CSS3, and JavaScript bundles. * Static assets are heavily cached across Cloudflare's 300+ Edge data centers. Over 80% of asset requests never reach your origin servers. 3. **Centralized Data & Cache Tier**: * Real-time events, WebSockets, and database transactions are offloaded to **PostgreSQL 17** and **Redis**, leaving the Node.js Fastify API threads free to execute sub-millisecond JSON operations. --- ## 3. Cloudflare Load Balancing Options You can implement multi-server web distribution using either of the following two Cloudflare configurations: ### Option A: Cloudflare Anycast Round-Robin (100% Free on all Cloudflare Plans) By creating multiple `A` records with the same hostname pointing to distinct server IPs, Cloudflare distributes incoming HTTPS connections evenly across your origins: | Record Type | Host / Name | Origin Server IP | Cloudflare Proxy Status | | :--- | :--- | :--- | :--- | | **A** | `*` *(Wildcard)* | `198.51.100.20` *(Web Node 01)* | **☁️ Proxied (Orange Cloud)** | | **A** | `*` *(Wildcard)* | `198.51.100.21` *(Web Node 02)* | **☁️ Proxied (Orange Cloud)** | | **A** | `*` *(Wildcard)* | `198.51.100.22` *(Web Node 03)* | **☁️ Proxied (Orange Cloud)** | * **How it works:** Cloudflare Anycast automatically balances client HTTP sessions among the configured origin IPs. * **Cost:** Included at zero additional charge in standard Cloudflare accounts. --- ### Option B: Cloudflare Load Balancer (With Active Health Checks & Auto-Failover) For mission-critical telecom carriers, the **Cloudflare Load Balancing** add-on provides automated health monitoring and sub-3-second failover: 1. **Origin Pool Configuration**: * Create pool: `ring2all-web-cluster`. * Add Origins: `node-01` (`198.51.100.20`), `node-02` (`198.51.100.21`). * Weight: `1:1` (or customized by server capacity). 2. **Health Monitor**: * Path: `/health` (or `/api/health`). * Expected Response Code: `200 OK`. * Interval: Every `15 seconds`. * Timeout: `3 seconds`. 3. **Autonomous Failover**: * If `node-01` fails or undergoes routine OS maintenance, Cloudflare automatically stops routing requests to it within 3 seconds. * **Zero User Interruption:** 100% of traffic immediately routes to `node-02` without connection dropouts or 502 Bad Gateway errors. --- ## 4. Step-by-Step Multi-Node Deployment ### Step 1: Provision Web Server Instances Deploy 2 or more Linux servers (Debian 13 or Ubuntu 24.04 LTS) with standard system specs: * **vCPU:** 4 cores. * **RAM:** 8 GB. * **Disk:** 50 GB NVMe SSD. ### Step 2: Install Ring2All Web & API Packages On **each** web node, install the system packages: ```bash # Update repository and install application packages sudo apt update sudo apt install -y softswitch-web softswitch-api softswitch-portal softswitch-switchboard nginx ``` ### Step 3: Synchronize Cluster Secrets in `.env` Ensure that `/opt/softswitch-api/.env` on **all web nodes** contains identical cryptographic and database credentials: ```ini # /opt/softswitch-api/.env (Must match across ALL Web Nodes) NODE_ENV=production PORT=3000 HOST=127.0.0.1 # Shared Cryptographic JWT Key (CRITICAL: Must be identical) JWT_SECRET="r2a_prod_super_secret_cluster_token_98374291834" # Centralized PostgreSQL 17 Cluster Connection DATABASE_URL="postgres://ring2all_app:SecureClusterPass@192.168.10.31:5432/ss_telephony" ADMIN_DATABASE_URL="postgres://ring2all_app:SecureClusterPass@192.168.10.31:5432/ss_admin" BILLING_DATABASE_URL="postgres://ring2all_app:SecureClusterPass@192.168.10.31:5432/ss_billing" # Shared Redis Cluster REDIS_HOST="192.168.10.31" REDIS_PORT=6379 REDIS_PASSWORD="ClusterRedisAuthPass2026" ``` ### Step 4: Enable and Start Systemd Services On each web node: ```bash sudo systemctl daemon-reload sudo systemctl enable --now softswitch-api sudo systemctl restart nginx ``` --- ## 5. Nginx Configuration on Web Nodes Every web node runs a lightweight local Nginx reverse proxy that handles incoming traffic forwarded from Cloudflare: ```nginx # /etc/nginx/sites-available/ring2all-cluster-node.conf server { listen 80; listen [::]:80; server_name *.ring2all.com ring2all.com; # Trust Cloudflare proxy IP headers set_real_ip_from 173.245.48.0/20; set_real_ip_from 103.21.244.0/22; set_real_ip_from 103.22.200.0/22; set_real_ip_from 103.31.4.0/22; set_real_ip_from 141.101.64.0/18; set_real_ip_from 108.162.192.0/18; set_real_ip_from 190.93.240.0/20; set_real_ip_from 188.114.96.0/20; set_real_ip_from 197.234.240.0/22; set_real_ip_from 198.41.128.0/17; set_real_ip_from 162.158.0.0/15; set_real_ip_from 104.16.0.0/13; set_real_ip_from 104.24.0.0/14; set_real_ip_from 172.64.0.0/13; set_real_ip_from 131.0.72.0/22; real_ip_header CF-Connecting-IP; # Static Web Frontend root /opt/softswitch-web/dist; index index.html; # Gzip Compression gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml; # Health Check Endpoint for Cloudflare Load Balancer location = /health { access_log off; return 200 "healthy\n"; add_header Content-Type text/plain; } # API Proxy location /api/ { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto; proxy_connect_timeout 3s; proxy_read_timeout 60s; } # SPA Routing Fallback location / { try_files $uri $uri/ /index.html; } } ``` --- ## 6. Database & Redis Clustering Requirements To sustain thousands of concurrent web requests across multiple nodes without connection pool starvation: 1. **PostgreSQL Connection Pool Optimization (`pgbouncer`)**: * Install `pgbouncer` on the PostgreSQL database cluster to manage thousands of lightweight connection handles from all web nodes. * Configure transaction pooling mode (`pool_mode = transaction`) in `pgbouncer.ini`. 2. **Redis Centralized Cache**: * Configure Redis persistence (`appendonly yes`) or Redis Sentinel for high availability. * Real-time WebSocket notifications (active call dashboards, BLF state changes) broadcast over Redis Pub/Sub so that a user connected to **Node 01** instantly receives state updates generated by **Node 02**. --- ## 7. Operational Verification & Failover Testing ### 1. Verify Node Health Locally On each individual web node, execute: ```bash curl -I http://127.0.0.1/health # Expected: HTTP/1.1 200 OK curl -I http://127.0.0.1/api/health # Expected: HTTP/1.1 200 OK ``` ### 2. Verify Cloudflare Edge Load Balancing From an external computer, inspect the HTTP headers: ```bash curl -svo /dev/null https://app.ring2all.com/health # Expected: # < HTTP/2 200 # < cf-ray: ... # < server: cloudflare ``` ### 3. Simulate Node Failure (Zero-Downtime Test) 1. Stop the web service on **Node 01**: ```bash sudo systemctl stop nginx ``` 2. Immediately browse to `https://app.ring2all.com` or send 100 consecutive HTTP requests via `ab` / `wrk`. 3. Cloudflare automatically shunts 100% of traffic to **Node 02**. The user session remains completely active with zero errors. 4. Restart **Node 01**: ```bash sudo systemctl start nginx ``` 5. Cloudflare automatically resumes traffic distribution to Node 01 within 15 seconds. --- ## 8. Summary & Key Advantages | Feature / Benefit | Single Server | Multi-Server with Cloudflare | | :--- | :--- | :--- | | **Domain Management** | 1 Domain | **Identical Single Domain** (`*.ring2all.com`) | | **High Availability** | None (Single Point of Failure) | **Active-Active Cluster (N+1)** | | **DDoS & Web Shield** | Local iptables/nftables only | **Enterprise Cloudflare Global WAF** | | **Maintenance Downtime** | Requires scheduled outages | **Zero-Downtime Rolling Restarts** | | **VoIP Telephony Impact** | Co-located on same box | **VoIP completely isolated on Kamailio SBC** | | **Horizontal Scalability** | Vertical upgrade only | **Add new web nodes in < 5 minutes** | ================================================================================ DOCUMENT: billing/admin/administration/api-keys TITLE: Application Keys Module Documentation URL: https://docs.ring2all.com/billing/admin/administration/api-keys.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Token Cryptography & API Rate Limiting Architecture](#5-token-cryptography--api-rate-limiting-architecture) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Application Keys** module (`public.api_keys`) manages machine-to-machine (M2M) credentials, external programmatic API tokens, and rate-limiting enforcement within **Ring2All Billing**. Designed for secure integration with third-party ERP accounting suites (such as QuickBooks, Odoo, and NetSuite), carrier provisioning portals, automated payment gateways, and CRM systems, Application Keys provide scoped programmatic access without requiring interactive administrative user sessions. ### Data Model & Token Security Architecture ``` ┌────────────────────────────────────────────────────────────────────────┐ │ API Key Entity (public.api_keys) │ │ • id: bigint (Canonical Invariant Numeric Primary Key) │ │ • uuid: uuid (Public Resource Identifier) │ │ • user_id: bigint (Owning Administrative User FK) │ │ • name: VARCHAR(100) (e.g. "ERP Accounting Sync Key") │ │ • description: TEXT (Integration Purpose & Scope) │ │ • key_prefix: VARCHAR(32) (Public Key Identifier, e.g. "r2a_live_..") │ │ • key_hash: VARCHAR(255) (One-Way SHA-256 / Argon2id Token Hash) │ │ • rate_limit_rpm: INTEGER (Requests Per Minute Limiter, e.g. 120, 300)│ │ • expires_at: TIMESTAMP WITH TIME ZONE (Optional Auto-Expiration) │ │ • is_active: BOOLEAN (Operational State Switch) │ │ • last_used_at: TIMESTAMP WITH TIME ZONE (Usage Telemetry) │ └───────────────────────────────────┬────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ One-Time Generation Workflow │ │ 1. Server generates high-entropy CSPRNG secret: │ │ "r2a_live_erp99_f8a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6" │ │ 2. Key prefix is saved in plain text: "r2a_live_erp99" │ │ 3. Full secret is hashed and stored in database: key_hash │ │ 4. Plain secret is returned ONCE to the administrator │ │ 5. Raw secret is NEVER retrievable again from the database │ └────────────────────────────────────────────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture (`public.api_keys`) * **Zero-Cleartext Storage:** Following industry best practices (matching GitHub and Stripe token architectures), the raw secret token is hashed immediately upon generation and never stored in cleartext. * **Key Prefix Lookups:** The `key_prefix` column allows high-speed $O(1)$ database indexing to identify the appropriate key record before evaluating the cryptographic hash, avoiding table-wide hash scans. * **Per-Token Rate Limiting:** Every key includes an independent `rate_limit_rpm` threshold enforced in memory by Redis or the Fastify rate limiter, preventing automated external scripts from overwhelming core billing services. --- ## 2. Module Overview (Commercial & Business Value) * **Seamless Enterprise System Integration:** Enables automated, zero-touch synchronization between Ring2All Billing and external accounting packages (ledger journal postings), billing analytics platforms, and enterprise CRM software. * **Protection Against Token Compromise:** If an integration server or environment file is exposed, administrators can instantly deactivate or revoke the specific compromised key without interrupting other integrations or changing system-wide passwords. * **Automated Expiration & Lifecycle Management:** Supports time-bound tokens for short-term third-party development teams or contractor projects, automatically expiring after a specified date. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`CRUD` on API Keys) | Generates new integration tokens, configures global rate limits, monitors token usage telemetry, and revokes compromised credentials. | | **Integration / DevOps Engineer** | Read & Create | Requests or provisions dedicated API keys for backend microservices, verifies rate-limiting headers, and tests programmatic webhook endpoints. | | **Security Auditor** | Read-Only | Audits active API tokens, verifies that inactive or unused keys are pruned, and validates that expiration policies are properly enforced. | --- ## 4. Visual Interface & Form Structure ### Level 1 — Application Keys List View The list view displays all active programmatic credentials, their public prefixes (with masked secrets), assigned rate limits (RPM), expiration dates, and real-time operational status badges. ![Application Keys List View](/screenshots/billing/admin/administration/api-keys/api-keys-list.png) ### Level 2 — Application Key Creation & Edit Form The form view is divided into **Basic Information** and **Configuration & Limits**, utilizing a standardized 4-column layout for clean, unambiguous configuration. ![Application Key Form View](/screenshots/billing/admin/administration/api-keys/api-keys-form.png) #### Parameters Reference * **Key Name:** Identifier describing the external application or system (e.g., `ERP Accounting Sync Key`). * **Description:** Integration details, owning team, or server hostname. * **Expiration Date:** Optional calendar picker specifying the date after which the token is automatically rejected. * **Rate Limit (RPM):** Maximum allowable requests per minute (e.g., `120` or `300` req/min). * **Enabled:** Operational toggle; disabling immediately cuts off external API access. --- ## 5. Token Cryptography & API Rate Limiting Architecture ``` ┌────────────────────────────────┐ │ External Client / ERP │ └───────────────┬────────────────┘ │ 1. HTTP Request with Header: │ Authorization: Bearer r2a_live_erp99_f8a2... ▼ ┌────────────────────────────────────────────────────────┐ │ Fastify 5 Auth & Rate Guard │ │ • Extract prefix: "r2a_live_erp99" │ │ • Query public.api_keys WHERE key_prefix = prefix │ └───────────────┬────────────────────────────────────────┘ │ ┌─────────┴─────────┐ │ Key Exists & Active? ▼ ▼ NO YES ┌───────────┐ ┌─────────────────────────────────────────────────┐ │ Reject │ │ 2. Verify Cryptographic Hash: │ │ HTTP 401 │ │ hash(incoming_secret) === key_hash │ └───────────┘ └───────────────┬─────────────────────────────────┘ │ ┌─────────┴─────────┐ │ Hash Match? │ ▼ ▼ NO YES ┌───────────┐ ┌───────────────────────────────┐ │ Reject │ │ 3. Check Redis Rate Limiter: │ │ HTTP 401 │ │ requests_this_minute < RPM │ └───────────┘ └───────────────┬───────────────┘ │ ┌─────────┴─────────┐ │ Below Limit? │ ▼ ▼ NO YES ┌───────────┐ ┌─────────────┐ │ Reject │ │ Forward to │ │ HTTP 429 │ │ API Handler │ └───────────┘ └─────────────┘ ``` --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Generating a New Key for an ERP Integration 1. Navigate to **ADMIN > Administration > Application Keys**. 2. Click **+ Add** in the upper toolbar. 3. Enter **Key Name**: `QuickBooks Ledger Sync`. 4. Enter **Description**: `Automated daily sync of closed invoices to corporate accounting ledger.` 5. Set **Rate Limit (RPM)** to `300`. 6. Leave **Expiration Date** empty for perpetual service, or set an annual rotation date. 7. Click **Save and close**. 8. **CRITICAL:** Copy the generated raw API key from the post-creation confirmation banner and securely store it in your application's vault. *The key cannot be viewed again once dismissed.* ### Playbook 2: Emergency Revocation of a Leaked Key 1. Locate the compromised key in the Application Keys list. 2. Option A (Temporary Pause): Click the edit icon, toggle **Enabled** to `Inactive`, and save. 3. Option B (Permanent Revocation): Click the trash/delete icon and confirm deletion in the confirmation modal. 4. *Result:* Any subsequent API request using the revoked key is immediately rejected with `HTTP 401 Unauthorized`. --- ## 7. Troubleshooting & Diagnostic Commands ### Inspecting Active Application Keys via CLI ```bash # Query active API keys, prefixes, and rate limits su - postgres -c "psql -d ss_billing -c ' SELECT id, name, key_prefix, rate_limit_rpm, is_active, last_used_at, expires_at FROM public.api_keys ORDER BY id ASC;'" ``` ### Testing API Key Authentication via cURL ```bash # Test API key authentication against billing status endpoint curl -i -H "Authorization: Bearer " \ https://192.168.10.29/api/v1/billing/status ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Application Keys** module connects directly to the **Ring2All BSS MCP Server**, allowing system administrators and security auditor agents to inspect machine-to-machine integrations, verify prefix identifiers, and track rate limiting thresholds. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_api_keys` | `Super Administrator` | Lists administrative and external API application keys with prefix, rate limit, and status. | `{}` | ### Sample MCP Tool Execution: `list_api_keys` #### Request Payload ```json { "name": "list_api_keys", "arguments": {} } ``` #### Response Payload ```json [ { "id": 1, "name": "QuickBooks ERP Sync", "keyPrefix": "r2a_live_qb9", "rateLimitRpm": 120, "isActive": true, "lastUsedAt": "2026-09-09T04:00:00Z", "expiresAt": null }, { "id": 2, "name": "Customer Portal Integration", "keyPrefix": "r2a_live_cp2", "rateLimitRpm": 300, "isActive": true, "lastUsedAt": "2026-09-09T05:01:22Z", "expiresAt": null } ] ``` ### Conversational AI Prompts for Copilot * *"List all active machine-to-machine API application keys and their rate limits."* * *"Which API keys have not been used in the last 30 days?"* * *"Verify if the QuickBooks ERP Sync key is active."* --- ## 9. Glossary * **M2M (Machine-to-Machine):** Direct automated communication between independent software systems without manual human intervention. * **Bearer Token:** Security credential that grants access to the bearer possessing the token secret. * **CSPRNG (Cryptographically Secure Pseudo-Random Number Generator):** Algorithmic generator producing random numbers suitable for cryptographic secrets. * **Rate Limit (RPM):** Protective threshold restricting the maximum number of requests a client can execute within a 60-second window to prevent system degradation. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/administration/log-profiles TITLE: Log Profiles Module Documentation URL: https://docs.ring2all.com/billing/admin/administration/log-profiles.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Audit Logging Architecture & Retention Lifecycles](#5-audit-logging-architecture--retention-lifecycles) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Log Profiles** module (`public.log_profiles`) defines operational and security audit logging policies within **Ring2All Billing**. By decoupling logging verbosity and retention timelines from individual user accounts, log profiles allow telecommunications organizations to systematically enforce data retention rules, regulatory audit controls, and real-time deletion alerting across their operational teams. ### Data Model & Policy Representation ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Log Profile Entity (public.log_profiles) │ │ • id: bigint (Canonical Invariant Numeric Primary Key) │ │ • uuid: uuid (Public API Identifier) │ │ • name: VARCHAR(100) (e.g. "Default", "Security & Administration") │ │ • description: TEXT (Policy Intent & Compliance Scope) │ │ • retention_days: INTEGER (Historical Storage Window, e.g. 90, 180) │ │ • audit_level: 'minimal' | 'standard' | 'verbose' | 'debug' │ │ • events_config: JSONB (Trigger Switches for Create/Update/Delete) │ │ • is_system: BOOLEAN (Protected Profile Flag) │ │ • is_default: BOOLEAN (Auto-Assignment Flag) │ └───────────────────────────────────┬────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ JSONB Event Configuration (`events_config`) │ │ { │ │ "logCreate": true, // Record insertion of new entities │ │ "logEdit": true, // Record mutations and diffs │ │ "logDelete": true, // Record deletions and record purges │ │ "notifyOnDelete": true // Dispatch immediate security webhook │ │ } │ └────────────────────────────────────────────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture (`public.log_profiles`) * **Primary Key:** Numeric `id` ensures invariant referential linkage with `public.users.log_profile_id`. * **Configurable Retention:** The `retention_days` integer dictates the automated lifecycle purge policy executed by the nightly maintenance worker against `public.audit_logs`. * **Tiered Audit Levels:** * `minimal`: Captures only critical state transitions (logins, wallet balance changes, carrier route overrides). * `standard`: Captures all normal CRUD operations across financial, rating, and customer records. * `verbose`: Captures full request/response payloads, IP headers, and previous vs. new entity diffs. * `debug`: Deep diagnostics capturing transient RPC calls and database query execution times. --- ## 2. Module Overview (Commercial & Business Value) * **Regulatory Compliance & Forensics:** Meets SOX, SOC 2, HIPAA, and GDPR regulatory demands by maintaining an unbroken, tamper-evident record of all administrative operations. * **Storage Cost & Database Performance Optimization:** Prevents audit log tables from bloating indefinitely by automatically enforcing data retention lifecycles based on profile tiers (e.g., 90 days for routine support vs. 365 days for financial controllers). * **Instant Breach & Tamper Detection:** Triggers urgent administrative notifications when sensitive resources (such as active customer contracts, rate cards, or firewall rules) are deleted or voided. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`CRUD` on Log Profiles) | Configures global audit policies, sets retention periods, enables real-time deletion alerting triggers, and manages automated audit log purging jobs. | | **Compliance Officer / Auditor** | Read & Verify | Evaluates active log profiles against corporate governance frameworks, verifies retention schedules, and inspects event capture settings. | | **NOC & Systems Engineer** | Read-Only | Monitors system audit volume, analyzes database storage growth attributed to verbose logging, and configures external log forwarding. | --- ## 4. Visual Interface & Form Structure ### Level 1 — Log Profiles List View The list view summarizes all registered audit profiles, highlighting audit verbosity levels (Standard, Verbose, Minimal), retention day quotas, assigned user counts, and protection status. ![Log Profiles List View](/screenshots/billing/admin/administration/log-profiles/log-profiles-list.png) ### Level 2 — Log Profile Creation & Edit Form The form view is structured into **Profile Information** and **Event Capture & Alerting Triggers**, utilizing standardized inputs and accessible switches. ![Log Profile Form View](/screenshots/billing/admin/administration/log-profiles/log-profiles-form.png) #### Parameters Reference * **Profile Name:** Descriptive label for the audit profile (e.g., `Carrier Operations`, `Critical Actions Only`). * **Description:** Details outlining the compliance or operational purpose of the profile. * **Retention Period (Days):** Storage window after which audit log entries linked to this profile are eligible for automated archival or deletion. * **Audit Verbosity Level:** Dropdown selector choosing between `Minimal`, `Standard`, `Verbose`, and `Debug`. * **Log Record Creations (Create):** Toggle to record the creation of new customers, rate cards, invoices, or system rules. * **Log Record Edits (Update):** Toggle to record field updates and before-and-after data comparisons. * **Log Record Deletions (Delete):** Toggle to record entity removals and void operations. * **Notify Admin on Deletion:** High-priority security toggle; dispatches immediate alerts when deletions occur. --- ## 5. Audit Logging Architecture & Retention Lifecycles ``` ┌────────────────────────────────────────────────────────┐ │ Administrative User Mutation Event │ │ (e.g., UPDATE public.customers SET balance = 500) │ └───────────────────────────┬────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────┐ │ Fastify 5 Audit Logging Hook │ │ • Identify authenticated user_id │ │ • Load user's public.log_profiles policy │ └───────────────────────────┬────────────────────────────┘ │ ┌─────────────────────┴─────────────────────┐ │ Evaluates logEdit & auditLevel │ ▼ ▼ ┌───────────────────────────┐ ┌───────────────────────────┐ │ If Enabled: │ │ If notifyOnDelete = true │ │ Write structured record to│ │ and event = DELETE: │ │ public.audit_logs: │ │ Dispatch security webhook │ │ • timestamp, user_id │ │ or high-priority email │ │ • ip_address, action │ └───────────────────────────┘ │ • entity_id, diff payload │ └─────────────┬─────────────┘ │ ▼ ┌────────────────────────────────────────────────────────┐ │ Nightly Cron Maintenance Worker │ │ • Reads retention_days from log_profiles │ │ • Purges or archives audit_logs older than threshold │ └────────────────────────────────────────────────────────┘ ``` --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Establishing a High-Security Audit Profile for Financial Staff 1. Navigate to **ADMIN > Administration > Log Profiles**. 2. Click **+ Add**. 3. Set **Profile Name** to `Financial Compliance & SOX`. 4. Enter Description: `Verbose audit logging with 365-day retention for accounting personnel handling invoice adjustments.` 5. Set **Retention Period (Days)** to `365`. 6. Select **Audit Verbosity Level** as `Verbose`. 7. Enable **Log Record Creations**, **Log Record Edits**, and **Log Record Deletions**. 8. Enable **Notify Admin on Deletion**. 9. Click **Save**. ### Playbook 2: Adjusting Retention for Routine Support Operations 1. In the Log Profiles list, locate the `Default` profile. 2. Click the edit icon. 3. Modify the **Retention Period (Days)** from `90` to `60` to conserve NVMe storage. 4. Click **Save**. 5. *Result:* The nightly cleanup job will automatically adapt to the 60-day window on its next scheduled run. --- ## 7. Troubleshooting & Diagnostic Commands ### Querying Log Profiles & Configured Rules ```bash # Query all log profiles with audit levels and retention quotas su - postgres -c "psql -d ss_billing -c ' SELECT id, name, audit_level, retention_days, events_config, is_system FROM public.log_profiles ORDER BY id ASC;'" ``` ### Inspecting Recent Audit Records by Profile ```bash # Query recent audit log volume grouped by user and log profile su - postgres -c "psql -d ss_billing -c ' SELECT lp.name AS profile_name, u.username, COUNT(al.id) AS total_events FROM public.audit_logs al JOIN public.users u ON u.id = al.user_id JOIN public.log_profiles lp ON lp.id = u.log_profile_id GROUP BY lp.name, u.username ORDER BY total_events DESC;'" ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Log Profiles** and system audit trail connects directly to the **Ring2All BSS MCP Server**, empowering compliance agents and forensic investigators to query immutable audit event logs and track administrative actions. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_audit_log_records` | `Super Administrator` | Queries immutable system audit logs, administrative actions, and entity change diffs. | `{"entity": "customer", "limit": 10}` | ### Sample MCP Tool Execution: `list_audit_log_records` #### Request Payload ```json { "name": "list_audit_log_records", "arguments": { "entity": "customer", "limit": 5 } } ``` #### Response Payload ```json [ { "id": 1042, "action": "UPDATE", "entity": "customer", "entityId": "1", "userId": 1, "username": "admin", "ipAddress": "192.168.10.5", "createdAt": "2026-09-09T04:30:15Z" } ] ``` ### Conversational AI Prompts for Copilot * *"Show recent administrative modifications made to customer accounts."* * *"List audit records indicating manual balance adjustments in the last 48 hours."* * *"Who performed the last configuration update on the primary rate card?"* --- ## 9. Glossary * **Audit Trail:** Step-by-step chronological record providing documentary evidence of the sequence of activities that have affected a specific transaction or system state. * **Retention Days:** Number of days an event record is retained in active storage before being purged or moved to cold archive. * **Diff Payload:** JSON structure capturing the exact fields modified during an update operation, showing both the prior value and the new value. * **Dunning & Purging Worker:** Background process responsible for scanning time-series audit records and pruning rows that exceed their retention quota. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/administration/mcp-roles TITLE: MCP Tool Roles Module Documentation URL: https://docs.ring2all.com/billing/admin/administration/mcp-roles.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [AI Governance & Model Context Protocol Execution Architecture](#5-ai-governance--model-context-protocol-execution-architecture) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **MCP Tool Roles** module (`public.mcp_roles`) implements enterprise AI governance, fine-grained access control (RBAC), and automated diagnostic safety boundaries for the entire **Ring2All BSS** subsystem. Powered by the open standard **Model Context Protocol (MCP)**, AI Copilots and automated NOC diagnostic agents interact with carrier customer accounts, real-time OCS charging, rating decks, DID routing, firewall rules, and server hardware telemetry exclusively within the strict bounds defined by these profiles. ### Data Model & System Linkage ``` ┌────────────────────────────────────────────────────────────────────────┐ │ MCP Role Entity (public.mcp_roles) │ │ • id: bigint (Canonical Invariant Numeric Primary Key) │ │ • uuid: uuid (Public API & SSO Identifier) │ │ • name: VARCHAR(100) (e.g. "Super Administrator", "Billing Operator")│ │ • description: TEXT (Tool Scope & Risk Classification Narrative) │ │ • tools: JSONB (Explicit Allowed Function Execution Array) │ │ • is_system: BOOLEAN (System Immutability Flag) │ │ • is_default: BOOLEAN (Auto-Assignment Flag for New AI Personas) │ │ • is_active: BOOLEAN (Operational State Flag) │ └───────────────────────────────────┬────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ Managed AI Model Context Protocol Tool Catalog │ │ │ │ [1. Customer Accounts & Wallets] │ │ • list_billing_customers • get_billing_customer │ │ • create_billing_customer • update_billing_customer │ │ • delete_billing_customer • adjust_customer_balance │ │ • update_customer_status • get_customer_wallet_ledger │ │ │ │ [2. Services, Plans & Rate Cards] │ │ • list_billing_plans • get_billing_plan │ │ • create_billing_plan • update_billing_plan │ │ • delete_billing_plan • list_active_subscriptions │ │ • create_customer_subscription • update_customer_subscription │ │ • cancel_customer_subscription • list_rate_cards │ │ • create_rate_card • update_rate_card │ │ • delete_rate_card • create_rate_card_destination │ │ • delete_rate_card_destination • lookup_rate_by_prefix │ │ • simulate_call_rating │ │ │ │ [3. Telecom Nodes & Carrier Providers] │ │ • list_telecom_nodes_status • sync_telecom_node │ │ • create_telecom_node • update_telecom_node │ │ • delete_telecom_node • list_carrier_providers │ │ • get_carrier_provider • create_carrier_provider │ │ • update_carrier_provider • delete_carrier_provider │ │ • list_did_inventory • create_did_number │ │ • update_did_routing • delete_did_number │ │ │ │ [4. Financial Reports & OCS Telephony] │ │ • list_invoices_summary • get_invoice_details │ │ • create_invoice • send_invoice_email │ │ • void_invoice • list_recent_transactions │ │ • get_financial_dashboard_kpis • query_rated_cdrs │ │ • query_rated_mdrs • get_accounting_journal_summary │ │ • get_live_calls_telemetry • disconnect_live_call_ocs │ │ │ │ [5. System Settings & Administration] │ │ • get_branding_settings • update_branding_settings │ │ • get_payment_gateways_status • update_payment_gateway_config │ │ • test_email_delivery • list_billing_users │ │ • create_billing_user • update_billing_user │ │ • delete_billing_user • get_user_audit_logs │ │ • list_role_profiles • create_role_profile │ │ • update_role_profile • delete_role_profile │ │ • list_mcp_tool_roles • create_mcp_tool_role │ │ • update_mcp_tool_role • delete_mcp_tool_role │ │ • list_api_keys • create_api_key │ │ • revoke_api_key │ │ │ │ [6. Firewall, Network & Security] │ │ • get_firewall_status • list_firewall_rules │ │ • create_firewall_rule • update_firewall_rule │ │ • delete_firewall_rule • block_ip_address │ │ • unblock_ip_address • get_ai_security_events │ │ • get_network_server_settings • list_certificates │ │ • list_fraud_alerts • resolve_fraud_alert │ │ │ │ [7. Maintenance & AI Integration] │ │ • get_system_maintenance_status • list_backup_history │ │ • create_system_backup • list_ai_providers │ │ • create_ai_provider • update_ai_provider │ │ • delete_ai_provider • list_ai_profiles │ │ • create_ai_profile • update_ai_profile │ │ • delete_ai_profile │ │ │ │ [8. Diagnostics & System Health] │ │ • analyze_server_health (CPU, RAM, Disks, OCS Telemetry, RCA) │ │ • diagnose_ocs_realtime_pipeline (Rating latency, node heartbeat, OCS)│ │ • diagnose_unrated_cdrs (Unbilled CDRs, zero-cost, revenue leaks) │ │ • diagnose_margin_leakage (Negative margins, carrier arbitrage) │ │ • diagnose_customer_billing_config (Balances, limits, rate cards) │ │ • diagnose_rate_card_coverage (Zero-rate audit, leakage detection) │ │ • diagnose_did_routing (PBX targets, SBC perimeter node sync) │ │ • diagnose_payment_gateways (Stripe API credentials, webhook secrets) │ │ • diagnose_telecom_node_sync (Voice node pings, connectivity checks) │ └────────────────────────────────────────────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture (`public.mcp_roles`) * **Primary Key:** Invariant numeric `id` ensures strict referential integrity with `public.users.mcp_role_id`. * **Wildcard & Array Matching:** The `tools` column stores a JSONB array of approved tool function names or the wildcard `["*"]` granting full system execution. * **Risk Categorization:** Tools are tagged with risk indicators: `LOW` (read-only queries and diagnostic metrics), `MEDIUM` (configuration mutations), and `HIGH` (destructive drops, wallet deductions, IP blocks, and live call disconnects). --- ## 2. Module Overview (Commercial & Business Value) * **Elimination of Financial Hallucinations:** Prevents Large Language Models from executing destructive financial adjustments or balance mutations without explicit human governance. * **Autonomous NOC Root Cause Analysis (RCA):** The `analyze_server_health` tool synthesizes hardware metrics (CPU load, RAM pressure, disk partition utilization) with real-time OCS charging engine status to diagnose voice service degradations in seconds. * **Proactive Toll Leakage Prevention:** The `diagnose_rate_card_coverage` tool inspects destination decks for missing international routes or dangerous $0.000000/min destinations before calls are dispatched. * **Perimeter Synchronization Assurance:** The `diagnose_did_routing` and `diagnose_telecom_node_sync` tools ensure telephone numbers and customer SIP routing policies are perfectly mirrored between Ring2All BSS, Ring2All PBX, and Ring2All SBC. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Capabilities | Core Operational Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Unrestricted Access (`*`) | Manages all MCP tool roles, authorizes high-risk financial and firewall operations, and reviews platform-wide AI audit logs. | | **Billing Operations & Accounts** | Customer, Rating, Invoice, & Diagnostic Tools | Provisions customer subscriptions, executes wallet credit adjustments, simulates call rating, runs invoice billing cycles, and audits rate cards. | | **Telecom & Carrier Engineer (NOC)** | Node, DID, OCS, Firewall, & Diagnostic Tools | Audits voice node synchronization, manages wholesale carrier DID routing, disconnects stuck calls in OCS, and executes server health diagnostics. | | **Read-Only Auditor & Compliance** | Telemetry, Invoices, Logs, & Diagnostic Tools | Reviews financial KPIs, inspects immutable ledger entries, audits user activity logs, and performs read-only system health checks. | --- ## 4. Visual Interface & Form Structure ### Level 1 — MCP Tool Roles List View Displays all registered MCP tool roles, indicating whether they possess wildcard (`*`) access or specific tool counts, assigned user counts, system protection badges, and creation timestamps. ![MCP Tool Roles List View](/screenshots/billing/admin/administration/mcp-roles/mcp-roles-list.png) ### Level 2 — MCP Tool Role Creation & Edit Form The form view combines role metadata with an interactive **Authorized AI MCP Tools Matrix** featuring one-click system presets, risk severity badges, category toggles, real-time tool search, and multi-language localized labels. ![MCP Tool Role Form View](/screenshots/billing/admin/administration/mcp-roles/mcp-roles-form.png) #### Interactive Form Controls Reference * **Role Name:** Unique identifier for the MCP role (e.g., `Telecom & Carrier Engineer (NOC)`). * **Description:** Purpose and scope of the tools granted under this profile. * **Quick Presets:** One-click assignment buttons: * `Full Access (*)`: Grants execution rights for all tools across all categories. * `Billing Operator`: Grants customer management, subscriptions, rating, invoices, and diagnostic tools. * `Telecom & NOC Engineer`: Grants node synchronization, carrier providers, DIDs, OCS supervisor, firewall, and server health tools. * `Read-Only Auditor & Telemetry`: Restricts tools strictly to read-only financial KPIs, logs, and diagnostic evaluations. * **Tool Matrix:** Categorized accordion lists displaying tool name, localized description, risk level badge (`LOW`, `CONFIG`, `DESTRUCTIVE`), and activation toggle. --- ## 5. AI Governance & Model Context Protocol Execution Architecture ``` ┌────────────────────────────────┐ │ Administrative User / Copilot │ └───────────────┬────────────────┘ │ 1. Conversational Prompt: "Diagnose why customer ACC-1002 cannot place calls" ▼ ┌────────────────────────────────┐ │ AI Model (LLM Provider) │ └───────────────┬────────────────┘ │ 2. Propose Tool Call: diagnose_customer_billing_config({ customerId: "1002" }) ▼ ┌────────────────────────────────────────────────────────┐ │ MCP Tool Role Authorization Guard │ │ • Verify Fastify JWT & user session │ │ • Check public.users.mcp_role_id │ │ • Query public.mcp_roles.tools │ └───────────────┬────────────────────────────────────────┘ │ ┌──────────┴──────────┐ │ Authorized? │ ▼ ▼ ┌───────────────┐ ┌─────────────────────────────────────────────────┐ │ YES │ │ NO │ ├───────────────┤ ├─────────────────────────────────────────────────┤ │ Execute Tool │ │ Intercept & Reject: HTTP 403 Forbidden │ │ via Fastify │ │ "Access Denied: Your MCP Tool Role does not │ │ Service Layer │ │ authorize execution of tool '...'." │ └───────────────┘ └─────────────────────────────────────────────────┘ ``` --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Diagnosing Customer Call Failures with AI 1. The billing operator asks the Copilot: *"Customer GlobalTech reports their outbound calls are dropping. Check their billing status."* 2. The AI model invokes `diagnose_customer_billing_config`: ```json { "customerId": "c7a8b9c0-1234-5678-90ab-cdef12345678" } ``` 3. The tool audits the wallet balance, credit limit, assigned rate card, and DID routing, identifying a zero balance on a prepaid account. 4. The Copilot outputs actionable guidance: *"Customer balance is $0.00. Advise customer to top up their wallet or apply a authorized credit adjustment."* ### Playbook 2: Periodic Rate Card Toll Leakage Audit 1. The telecom administrator invokes `diagnose_rate_card_coverage` against the wholesale termination deck. 2. The tool flags 3 destination prefixes with rate `$0.000000/min` and detects missing international prefix definitions. 3. The administrator uses `create_rate_card_destination` via the Copilot to correct the rates immediately. --- ## 7. Troubleshooting & Diagnostic Commands ### Verifying MCP Roles in Database ```bash # Query registered MCP tool roles and active status su - postgres -c "psql -d ss_billing -c ' SELECT id, name, is_system, is_default, jsonb_array_length(tools) AS tool_count, is_active FROM public.mcp_roles ORDER BY id ASC;'" ``` ### Inspecting Specific Allowed Tools for a User ```bash # Check assigned MCP tool permissions for user ID 1 su - postgres -c "psql -d ss_billing -c ' SELECT u.username, m.name AS mcp_role, m.tools FROM public.users u JOIN public.mcp_roles m ON m.id = u.mcp_role_id WHERE u.id = 1;'" ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Ring2All BSS MCP Server** (`ring2all-bss`) exposes over 50 tools across 8 operational categories for AI integration. ### Core Diagnostic Tools Reference | Tool Name | Risk Tier | Primary Function | | :--- | :--- | :--- | | `analyze_server_health` | `LOW` | Returns complete hardware CPU/RAM/Swap, filesystem storage, OS release, Node.js/V8, PostgreSQL latency, and OCS engine metrics. | | `diagnose_customer_billing_config` | `LOW` | Audits customer prepaid/postpaid rules, wallet credit limits, assigned retail rate cards, and DID routing targets. | | `diagnose_rate_card_coverage` | `LOW` | Audits destination prefix coverage, detects $0.00 zero-rates (toll leakage risk), and flags anomalous high rates. | | `diagnose_did_routing` | `LOW` | Validates DID customer association, route target (extension vs SIP URI), SBC perimeter synchronization, and E911 compliance. | | `diagnose_payment_gateways` | `LOW` | Audits Stripe API credentials and webhook signing secret configuration in the environment. | | `diagnose_telecom_node_sync` | `LOW` | Pings all registered FreeSWITCH PBX and Kamailio SBC nodes, reports latency, and verifies cluster connectivity. | --- ### Sample MCP Tool Execution: `analyze_server_health` #### Request Payload ```json { "name": "analyze_server_health", "arguments": {} } ``` #### Response Payload ```json { "system": { "hostname": "billing-prod-01", "platform": "linux", "distribution": "Debian GNU/Linux 13 (trixie)", "architecture": "x64", "uptime": "14 days, 6 hours, 22 minutes", "loadAverage": [0.42, 0.38, 0.35], "cpuCount": 8, "cpuModel": "AMD EPYC 7763 64-Core Processor", "memory": { "total": "32.00 GB", "free": "18.45 GB", "used": "13.55 GB", "usagePercent": "42.3%" }, "storage": [ { "filesystem": "/dev/sda1", "mountPoint": "/", "total": "245.8G", "used": "68.2G", "available": "165.1G", "usagePercent": "29%" } ] }, "runtime": { "nodeVersion": "v22.14.0", "v8Version": "12.4.254.21-node.21", "processUptime": "4 days, 12 hours", "processMemory": { "rss": "184.25 MB", "heapTotal": "112.50 MB", "heapUsed": "88.10 MB" } }, "database": { "status": "ONLINE", "pingLatencyMs": 1.45, "size": "4.82 GB", "activeConnections": 18 }, "telephony": { "subsystem": "Ring2All BSS Convergent Rating & OCS Engine", "activeSupervisedCalls": 24, "ocsEngineStatus": "ONLINE", "totalNodesRegistered": 3, "connectedNodes": 3, "lastPingLatencyMs": 2.1 }, "overallHealth": "HEALTHY", "issues": [], "recommendations": [ "System hardware, database latency, and real-time charging engines are operating within nominal thresholds." ] } ``` --- ### Sample MCP Tool Execution: `diagnose_customer_billing_config` #### Request Payload ```json { "name": "diagnose_customer_billing_config", "arguments": { "customerId": "c7a8b9c0-1234-5678-90ab-cdef12345678" } } ``` #### Response Payload ```json { "status": "WARNING", "customerId": "c7a8b9c0-1234-5678-90ab-cdef12345678", "customerName": "Nexus Communications LLC", "accountStatus": "active", "billingType": "prepaid", "wallet": { "balance": "$4.50", "creditLimit": "$0.00", "currency": "USD" }, "assignedRateCard": "Retail Standard Deck 2026", "activeSubscriptionsCount": 2, "assignedDidsCount": 3, "issues": [ "Low prepaid balance alert: $4.50 remaining.", "DID +13055550199 is not synchronized to the Ring2All SBC perimeter engine." ], "recommendations": [ "Notify customer to recharge before services get suspended.", "Trigger node synchronization for DID +13055550199." ] } ``` --- ### Conversational AI Prompts for Copilot #### English Prompts * *"Analyze the server health and tell me if memory or disk partitions are near capacity."* * *"Diagnose the billing configuration for customer Acme Corp and verify if they have a rate card assigned."* * *"Run a toll leakage audit on rate card 'Wholesale Deck A' to check for zero-rate destinations."* * *"Check if all telephone numbers for customer 104 are properly synced with the Ring2All SBC."* * *"Verify the connectivity and ping latency to all registered Ring2All voice nodes."* #### Spanish Prompts (Español) * *"Analiza la salud del servidor y dime si la memoria o el disco están cerca del límite."* * *"Diagnostica la configuración de facturación del cliente Acme Corp y verifica si tiene tarifario asignado."* * *"Ejecuta una auditoría de fugas de ingresos en el tarifario 'Wholesale Deck A' para buscar tarifas en cero."* * *"Verifica si todos los números telefónicos del cliente 104 están sincronizados con Ring2All SBC."* * *"Comprueba la conectividad y latencia de ping de todos los nodos de voz Ring2All registrados."* --- ## 9. Glossary * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and enterprise telecommunications systems. * **Online Charging System (OCS):** Real-time rating and credit control engine that supervises live telephony sessions, enforcing prepaid balance limits and instantaneous call termination. * **Rate Card Deck:** Collection of destination prefix matching rules and per-minute tariffs used to rate outbound voice calls and SMS messages. * **Toll Leakage:** Financial loss incurred when telecommunications traffic is terminated through wholesale carriers without corresponding retail billing charges (often caused by $0.00 destination rates). * **DID (Direct Inward Dialing):** Public telephone number mapped to an inbound routing target (PBX extension, IVR, Ring Group, or external SIP URI). ================================================================================ DOCUMENT: billing/admin/administration/role-profiles TITLE: Role Profiles Module Documentation URL: https://docs.ring2all.com/billing/admin/administration/role-profiles.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Permissions Matrix & Evaluation Engine](#5-permissions-matrix--evaluation-engine) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Role Profiles** module (`public.role_profiles`) manages the Role-Based Access Control (RBAC) governance framework within **Ring2All Billing**. It abstracts low-level API route permissions and UI view authorizations into cohesive, reusable profiles that can be assigned to multiple administrative users. ### Data Model & Matrix Representation ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Role Profile Entity (public.role_profiles) │ │ • id: bigint (Canonical Invariant Numeric Primary Key) │ │ • uuid: uuid (Public API Identifier) │ │ • name: VARCHAR(100) (e.g. "Billing Manager", "Auditor") │ │ • description: TEXT (Profile Scope & Operational Intent) │ │ • permissions: JSONB (Structured Module Permission Mapping) │ │ • is_system: BOOLEAN (Protected Pre-Seeded Profile Flag) │ │ • is_default: BOOLEAN (Auto-Assignment Flag for New Staff) │ │ • is_active: BOOLEAN (Operational State Flag) │ └───────────────────────────────────┬────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ JSONB Permissions Specification (`permissions`) │ │ { │ │ "rates": "FULL", // Full CRUD on Rate Cards & Tariffs │ │ "plans": "FULL", // Full CRUD on Product Catalog │ │ "invoices": "READ", // Read-Only inspection of Invoices │ │ "accounting": "NONE", // Completely hidden from Navigation & API │ │ "users": "NONE" // Administrative user management hidden │ │ } │ └────────────────────────────────────────────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture (`public.role_profiles`) * **Primary Key:** Numeric `id` guarantees invariant foreign key relationships with `public.users.role_profile_id`. * **Dynamic JSONB Hierarchy:** Permissions are stored as structured JSONB key-value pairs matching module identifiers to one of three access tiers: `FULL` (Create, Read, Update, Delete), `READ` (View & Export only), or `NONE` (Strictly Forbidden). * **System Immutability Protection:** Profiles flagged with `is_system = true` (such as `Administrator`) cannot be deleted, ensuring there is always at least one functioning full-access profile. --- ## 2. Module Overview (Commercial & Business Value) * **Zero-Trust Administrative Access:** Adheres to the principle of least privilege (PoLP), ensuring staff only access modules directly necessary for their functional obligations. * **Risk Reduction in Financial & Tariff Operations:** Prevents tier-1 support representatives or sales staff from accidentally altering wholesale LCR tables, manipulating customer wallet balances, or deleting historical billing invoices. * **Rapid Workforce Onboarding:** Reduces provisioning overhead; new hires are instantly granted the exact required permissions by simply selecting their standardized role profile. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`CRUD` on Role Profiles) | Creates custom organizational role profiles, defines category-level permission overrides, sets default onboarding profiles, and maintains system security boundaries. | | **Security Officer / Compliance Lead** | Read & Audit | Audits the permissions matrix across all active profiles, verifies that sensitive modules (like Accounting, API Keys, and Firewalls) have restricted access, and validates periodic access reviews. | | **Billing Manager** | Read-Only | Inspects the capabilities of team members to confirm that appropriate operational scopes are assigned to billing analysts and rate administrators. | --- ## 4. Visual Interface & Form Structure ### Level 1 — Role Profiles List View The list view displays all configured role profiles, their permission scopes (Full Access vs. custom module counts), assigned user counts, protection badges, and creation dates. ![Role Profiles List View](/screenshots/billing/admin/administration/role-profiles/role-profiles-list.png) ### Level 2 — Role Profile Creation & Edit Form The form view combines standard metadata inputs with an interactive **Permissions Matrix** featuring expandable module categories, batch selectors, and search filtering. ![Role Profile Form View](/screenshots/billing/admin/administration/role-profiles/role-profiles-form.png) #### Sections & Interactive Controls 1. **Basic Information Box:** * **Role Profile Name:** Alphanumeric identifier (e.g., `Billing Manager`, `Telecom Auditor`). * **Description:** Comprehensive narrative explaining the profile's intended operational tier. * **Default Profile Switch:** Marks the profile for automatic selection when onboarding new users. * **Enabled Switch:** Toggles the active status of the profile. 2. **Permissions Matrix Box:** * **Search Filter:** Instant real-time filtering of modules across all functional categories. * **Category Accordions:** Grouped by operational domains (`Rating & Routing`, `Reports & Invoices`, `Customers & Wallets`, `Settings & Admin`). * **Access Level Pills:** Quick toggles for `FULL`, `READ`, or `NONE` per module or applied in batch across entire categories. --- ## 5. Permissions Matrix & Evaluation Engine When an administrative user authenticates and initiates an API request, the Fastify RBAC pre-handler evaluates the user's role profile against the requested route and HTTP method: ``` ┌───────────────────────────────┐ │ Incoming API Request │ │ (e.g., POST /api/v1/rates) │ └───────────────┬───────────────┘ │ ▼ ┌───────────────────────────────┐ │ Extract User Token & Role │ │ (public.users.role_profile)│ └───────────────┬───────────────┘ │ ▼ ┌───────────────────────────────┐ │ Evaluate Module Scope: "rates"│ └───────────────┬───────────────┘ │ ┌───────────────────────┼───────────────────────┐ │ Permission = "FULL" │ Permission = "READ" │ Permission = "NONE" ▼ ▼ ▼ ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │ Allow GET, POST, │ │ Allow GET Only; │ │ Reject Request │ │ PUT, DELETE │ │ Reject Mutations │ │ with HTTP 403 │ │ (HTTP 200/201) │ │ with HTTP 403 │ │ Forbidden │ └───────────────────┘ └───────────────────┘ └───────────────────┘ ``` --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Creating a "Financial Auditor" Profile 1. Navigate to **ADMIN > Administration > Role Profiles**. 2. Click **+ Add** to launch the profile creation form. 3. Set **Role Profile Name** to `Financial Auditor`. 4. Enter Description: `Read-only access to Invoices, CDRs, MDRs, and accounting ledgers for external audit review.` 5. In the **Permissions Matrix**: * Set `Reports & Invoices` to `READ` (all child modules inherit read-only rights). * Set `Customers & Wallets` to `READ`. * Set `Rating & Routing` to `NONE`. * Set `Settings & Admin` to `NONE`. 6. Click **Save and close**. ### Playbook 2: Modifying an Existing Profile's Access Scope 1. In the Role Profiles list, locate the profile to adjust (e.g., `Billing Manager`). 2. Click the edit icon to open the configuration form. 3. Expand the target category accordion (e.g., `Rating & Routing`). 4. Upgrade or downgrade specific module pills (e.g., set `Least Cost Routing` to `READ`). 5. Click **Save and close**. 6. *Result:* All users assigned to this role profile immediately operate under the updated permissions matrix without requiring session re-authentication. --- ## 7. Troubleshooting & Diagnostic Commands ### Querying Configured Role Profiles ```bash # Query all role profiles and assigned user counts su - postgres -c "psql -d ss_billing -c ' SELECT r.id, r.name, r.is_system, r.is_default, COUNT(u.id) AS active_users FROM public.role_profiles r LEFT JOIN public.users u ON u.role_profile_id = r.id GROUP BY r.id, r.name, r.is_system, r.is_default ORDER BY r.id ASC;'" ``` ### Inspecting Granular JSONB Permissions for a Role ```bash # Inspect JSONB permission payload for Role ID 2 su - postgres -c "psql -d ss_billing -c \" SELECT jsonb_pretty(permissions) FROM public.role_profiles WHERE id = 2;\"" ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Role Profiles** module connects directly to the **Ring2All BSS MCP Server**, enabling security administrators and governance copilots to audit active RBAC matrices and user distribution programmatically. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_role_profiles` | `Super Administrator` | Lists RBAC role profiles with permissions summary, system/default flags, and user counts. | `{}` | ### Sample MCP Tool Execution: `list_role_profiles` #### Request Payload ```json { "name": "list_role_profiles", "arguments": {} } ``` #### Response Payload ```json [ { "id": 1, "name": "Super Administrator", "description": "Unrestricted administrative access to all modules and engines", "isSystem": true, "isDefault": false, "usersCount": 1 }, { "id": 2, "name": "Billing Operations", "description": "Standard customer management, invoicing, and rate card maintenance", "isSystem": false, "isDefault": true, "usersCount": 3 } ] ``` ### Conversational AI Prompts for Copilot * *"List all defined role profiles and how many active users belong to each."* * *"Show which roles are marked as protected system profiles."* * *"What is the default role assigned to new operators?"* --- ## 9. Glossary * **RBAC (Role-Based Access Control):** Security mechanism that restricts system access based on user organizational roles rather than individual user identities. * **Principle of Least Privilege (PoLP):** Information security standard requiring that users be granted only the minimum access necessary to perform authorized duties. * **JSONB:** Binary structured JSON format native to PostgreSQL offering indexed querying and high-performance read evaluation. * **System Profile:** Pre-configured baseline profile protected against accidental modification or deletion. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/administration/users TITLE: Users Management Module Documentation URL: https://docs.ring2all.com/billing/admin/administration/users.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Users** module (`public.users`) manages operator and administrative identity, credentials, role inheritance, audit verbosity, and AI assistant capabilities within **Ring2All Billing**. Unlike end-customer portal accounts, administrative users possess direct access to rating engines, customer wallets, invoices, carrier trunking configurations, and security firewall rules. ### Data Model & System Linkage ``` ┌────────────────────────────────────────────────────────────────────────┐ │ User Entity (public.users) │ │ • id: bigint (Canonical Invariant Primary Key) │ │ • uuid: uuid (Public API & SSO Identifier) │ │ • username: VARCHAR(100) (Unique Login Handle) │ │ • email: VARCHAR(255) (Corporate Contact & MFA Notification Target) │ │ • password_hash: VARCHAR(255) (Argon2id Salted Cryptographic Hash) │ │ • role_profile_id: bigint (RBAC Permission Matrix FK) │ │ • log_profile_id: bigint (Audit & Retention Policy FK) │ │ • mcp_role_id: bigint (AI MCP Copilot Tool Execution Matrix FK) │ │ • ai_profile_id: bigint (LLM Model & Provider Association FK) │ │ • status: 'active' | 'inactive' | 'suspended' │ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┼─────────────────────────┐ ▼ ▼ ▼ ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │ role_profiles │ │ log_profiles │ │ mcp_roles │ │ • Module CRUD │ │ • Audit Verbosity │ │ • Rating Tools │ │ • Billing Scopes │ │ • Retention Days │ │ • Invoicing Tools │ │ • Security Matrix │ │ • Alert Webhooks │ │ • Risk Guardrails │ └───────────────────┘ └───────────────────┘ └───────────────────┘ ``` ### PostgreSQL Schema Architecture (`public.users`) * **Primary Key:** `id` (bigserial) provides numeric immutability for foreign keys in audit trails and transaction records. * **Cryptographic Security:** Passwords are never stored in cleartext; they are hashed using `Argon2id` (memory-hard, resistant to GPU/ASIC brute-force attacks). * **Multi-Pillar Governance:** Each user record concurrently references four governance pillars: 1. `role_profile_id`: RBAC permissions restricting UI navigation and API endpoints. 2. `log_profile_id`: Granular audit logging rules dictating what administrative events are recorded. 3. `mcp_role_id`: AI Copilot boundaries dictating which automated Model Context Protocol tools the user can invoke. 4. `ai_profile_id`: Default Large Language Model provider and engine powering AI interactions. * **Primary Admin Protection:** User ID 1 (`admin`) is protected against deletion, status deactivation, and role downgrade to prevent administrative lockout. --- ## 2. Module Overview (Commercial & Business Value) * **Enterprise Separation of Duties (SoD):** Enforces strict boundaries between financial accountants, NOC billing operators, telecommunications engineers, and platform superadministrators, mitigating internal fraud and accidental misconfigurations. * **Auditability & Regulatory Compliance:** Links every customer tariff change, manual credit adjustment, invoice write-off, and carrier route modification directly to an authenticated user ID, meeting SOX, SOC 2, and telecom licensing compliance mandates. * **Streamlined Multi-Tier Operations:** Allows carrier operators to delegate day-to-day rate card ingestion and payment tracking to lower-privileged staff without exposing mission-critical billing infrastructure or database credentials. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`CRUD` on Users & Profiles) | Provisions administrative personnel, assigns role profiles and audit profiles, configures AI Copilot access, resets credentials, and manages master system security. | | **Billing Manager** | Read & Create (Standard Staff) | Enrolls junior billing operators, assigns predetermined operational profiles, and audits user activity across billing and financial reconciliation queues. | | **Security Officer / Auditor** | Read-Only (User Catalog & Logs) | Inspects administrative user catalogs, verifies that former employees are promptly deactivated, and reviews session and login history against compliance standards. | --- ## 4. Visual Interface & Form Structure ### Level 1 — Users List View The administrative users catalog provides a comprehensive inventory of all system operators, their active roles, assigned audit profiles, multi-tenant scopes, and last login timestamps. ![Users List View](/screenshots/billing/admin/administration/users/users-list.png) ### Level 2 — User Creation & Edit Form The user editor adheres to the standardized 4-column layout (`[Label 1] [Control 1] [Label 2] [Control 2]`), cleanly partitioned into **Basic Information** and **Profiles & Configuration**. ![User Form View](/screenshots/billing/admin/administration/users/users-form.png) #### Fields & Parameters Reference * **Username:** Unique alphanumeric login handle used for session authentication. * **Email:** Primary corporate email address for password recovery, billing notifications, and security alerts. * **Full Name:** Formal human-readable name displayed across UI headers and system audit logs. * **Password:** Secure passphrase; masked by default with an optional password reset toggle in edit mode. * **Role Profile:** Dropdown selecting the RBAC permission profile governing UI and API privileges. * **Log Profile:** Dropdown selecting the audit profile defining retention period and event capturing. * **AI Profile (MCP Copilot):** Associates the user with a specific AI provider profile for conversational intelligence. * **MCP Tool Role:** Selects the governance matrix defining which automated AI tools the user can execute. * **Timezone & Locale:** Preferences for localized timestamp presentation and interface language. * **Startup Page:** Landing module displayed immediately upon administrative login. * **Enabled:** Operational toggle; disabling immediately invalidates existing JWT sessions and blocks login. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────┐ 1. POST /api/v1/auth/login ┌────────────────────────┐ │ System Admin ├────────────────────────────────────────►│ Fastify 5 Auth Guard │ └──────────────┘ └───────────┬────────────┘ │ 2. Verify Argon2id │ 3. Fetch User, Roles, Hash & Status │ Audit, & MCP Roles ▼ ┌────────────────────────┐ │ PostgreSQL Engine │ │ (ss_billing database) │ └───────────┬────────────┘ │ 4. Issue Encrypted │ JWT with Scopes │ ▼ ┌──────────────┐ 5. Validated API Requests ┌────────────────────────┐ │ Admin Web UI ├────────────────────────────────────────►│ RBAC & Audit Intercept │ └──────────────┘ (Header: Authorization: Bearer ...) └────────────────────────┘ ``` 1. **Authentication:** The user submits credentials to `/api/v1/auth/login`. 2. **Cryptographic Validation:** The backend verifies the password hash against `public.users.password_hash` using Argon2id. If the user status is not `active`, authentication is rejected with HTTP 403. 3. **Pillar Resolution:** The server retrieves the user's role profile, log profile, and MCP tool role in a single optimized query. 4. **Token Generation:** An encrypted JWT access token is generated containing immutable numeric user ID (`uid`), role profile ID (`rid`), and tenant access boundaries. 5. **Auditing:** Every subsequent HTTP mutation writes an immutable row to `public.audit_logs` referencing `user_id`. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Enrolling a New Billing Operator 1. Navigate to **ADMIN > Administration > Users**. 2. Click **+ Add** in the top-right toolbar. 3. Enter `username`, `email`, and `fullName`. 4. Define a secure initial password complying with complexity standards. 5. Under **Profiles & Configuration**, select `Role Profile: Billing Manager` or `Billing Operator`. 6. Select `Log Profile: Security & Administration` to ensure all rate modifications are logged. 7. Select `MCP Tool Role: Billing Operator (Standard)` to grant AI access to rating calculations and CDR queries. 8. Click **Save and close**. ### Playbook 2: Deprovisioning Departing Staff 1. Locate the departing operator in the users data grid. 2. Click the edit icon to open the **User Form**. 3. Toggle the **Enabled** switch to `Inactive`. 4. Click **Save and close**. 5. *Result:* The user's JWT tokens are rejected on the next request, and all API access is immediately revoked while preserving historical audit trails. --- ## 7. Troubleshooting & Diagnostic Commands ### Inspecting User Accounts via CLI ```bash # Connect to PostgreSQL billing database su - postgres -c "psql -d ss_billing -c ' SELECT u.id, u.username, u.email, u.status, r.name AS role, l.name AS log_profile, m.name AS mcp_role FROM public.users u LEFT JOIN public.role_profiles r ON r.id = u.role_profile_id LEFT JOIN public.log_profiles l ON l.id = u.log_profile_id LEFT JOIN public.mcp_roles m ON m.id = u.mcp_role_id ORDER BY u.id ASC;'" ``` ### Unlocking or Resetting Admin Password ```bash # Reset administrator password to default hash su - postgres -c "psql -d ss_billing -c \" UPDATE public.users SET password_hash = '\\\$argon2id\\\$v=19\\\$m=65536,t=3,p=4\\\$...' WHERE id = 1;\"" ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Users Management** module connects directly to the **Ring2All BSS MCP Server**, enabling security auditors, administrators, and governance agents to query platform operators and verify role assignments programmatically. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_admin_users` | `Super Administrator` | Lists billing platform administrative users with assigned roles, statuses, and last login timestamps. | `{"status": "active", "limit": 10}` | ### Sample MCP Tool Execution: `list_admin_users` #### Request Payload ```json { "name": "list_admin_users", "arguments": { "limit": 5 } } ``` #### Response Payload ```json [ { "id": 1, "username": "admin", "name": "System Administrator", "email": "admin@ring2all.com", "status": "active", "roleName": "Super Administrator", "mcpRoleName": "Super Administrator (Full MCP Access)", "lastLoginAt": "2026-09-09T05:10:00Z" } ] ``` ### Conversational AI Prompts for Copilot * *"List all active platform users and their assigned RBAC and MCP roles."* * *"Are there any inactive or suspended administrative user accounts?"* * *"Verify which users have Super Administrator privileges."* --- ## 9. Glossary * **Argon2id:** The state-of-the-art hybrid memory-hard password hashing algorithm chosen by the Password Hashing Competition (PHC). * **Role Profile (RBAC):** Role-Based Access Control matrix dictating granular view, create, edit, and delete permissions across platform modules. * **Log Profile:** Configuration profile that controls retention windows and event verbosity for operational and security audit logging. * **MCP Tool Role:** Governance policy restricting which automated Model Context Protocol tools an AI agent can execute on behalf of the user. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/ai/ai-agents TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/ai/ai-agents.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/ai/ai-chatbots TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/ai/ai-chatbots.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/ai/ai-profiles TITLE: AI Profiles Module Documentation URL: https://docs.ring2all.com/billing/admin/ai/ai-profiles.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **AI Profiles** module (`public.ai_profiles`) encapsulates specialized behavior, system prompts, inference parameters, and persona definitions for AI workloads in **Ring2All Billing**. While the AI Providers module handles physical connection credentials to cloud engines, AI Profiles define *how* those models interact with telecom operations, accounting ledgers, CDR fraud forensics, and conversational customer support. Each profile couples a designated upstream provider with an exact inference model (e.g., `gpt-4o`, `claude-3-5-sonnet-20241022`, `deepseek-reasoner`), customized temperature and token boundaries, structured system prompts, Text-To-Speech (TTS) voice parameters, and an active operational state. ### Data Model & Architecture Diagram ``` ┌────────────────────────────────────────────────────────────────────────┐ │ AI Profiles (public.ai_profiles) │ │ • id: bigint (Primary Key) │ │ • uuid: UUID (Unique Public Identifier) │ │ • provider_id: bigint (FK to public.ai_providers) │ │ • profile_name: VARCHAR(100) (e.g., 'Billing Copilot Pro') │ │ • type: 'general' | 'chatbot' | 'voice' | 'reasoner' │ │ • model: VARCHAR(100) (e.g., 'gpt-4o', 'deepseek-reasoner') │ │ • temperature: numeric(3,2) (e.g., 0.70) │ │ • max_tokens: integer (e.g., 2048) │ │ • voice_config: jsonb (TTS voice ID, speed, pitch, engine) │ │ • embeddings_model: VARCHAR(100) (e.g., 'text-embedding-3-small') │ │ • system_prompt: text (Domain system instructions) │ │ • is_default_chatbot: boolean │ │ • status: boolean (Active / Inactive) │ └───────────────────────────────────┬────────────────────────────────────┘ │ Directs Workflows ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ Operational AI Workflows │ │ • Interactive Billing Copilot (Portal Assistance & Natural Queries) │ │ • CDR Anomaly & Fraud Reasoner (Explains IRSF & Velocity Spikes) │ │ • Automated Customer Billing Support (Payment & Invoice Inquiries) │ └────────────────────────────────────────────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.ai_profiles`**: * `id`: Numeric primary key (`bigserial`). * `uuid`: Immutable UUID utilized in routing and API endpoints. * `provider_id`: References `public.ai_providers.id`, dictating which upstream credentials and transport to utilize. * `profile_name`: User-facing name describing the specialized role. * `type`: Categorization of operational mode (`general`, `chatbot`, `voice`, `reasoner`). * `model`: Specific model slug passed to the upstream inference API. * `temperature`: Creativity vs determinism parameter (range `0.00` to `2.00`). * `max_tokens`: Upper bound ceiling on tokens generated per single response. * `voice_config`: JSONB payload containing voice synthesis configurations for voice-enabled agents. * `system_prompt`: Foundational context guiding the AI's identity, constraints, and operational guidelines. * `is_default_chatbot`: Boolean designating the default profile assigned to incoming user chat sessions. * `status`: Active/inactive toggle. --- ## 2. Module Overview (Commercial & Business Value) * **Domain-Specific Specialization:** Rather than relying on generic model responses, profiles enforce strict telecom accounting constraints, financial accuracy guidelines, and privacy guards. * **Deterministic Financial Reasoning:** Setting low temperature (`0.1`–`0.2`) for CDR audit profiles prevents hallucination during invoice reconciliation and tax dispute analysis. * **Zero Disruption Model Upgrades:** When newer frontier models release (e.g., GPT-5 or Claude 4), administrators update the profile's model parameter in one location, instantly upgrading all dependent applications across the billing system. * **Contextual Copilot Assistance:** Powers the embedded Ring2All billing assistant, allowing operators to ask complex operational questions (e.g., "Summarize top 5 carrier spend increases this week") in plain English. --- ## 3. 🎯 User Roles & Key Capabilities | Role | Key Capabilities & Permissions in AI Profiles | | :--- | :--- | | **System Administrator** | Full authority to create, edit, duplicate, and delete AI Profiles; configures system prompt templates, sets token limits, and designates the default chatbot. | | **Security Analyst** | Verifies system prompts to prevent prompt injection vulnerabilities and reviews token bounds to prevent accidental financial denial-of-service. | | **Billing Operations Lead** | Tunes temperature settings, tests voice synthesis configurations, and tests model responses against sample rating and invoice data. | | **Customer Support Manager** | Customizes customer-facing persona prompts, greeting messages, and billing query explanation styles. | --- ## 4. Visual Interface & Form Structure The **AI Profiles** module provides an organized list view and an in-depth profile customization form. ### 4.1 AI Profiles Listing ![AI Profiles List](/screenshots/billing/admin/ai-integration/ai-profiles/ai-profiles-list.png) The list view displays all configured AI Profiles: * **Header Controls:** * `Search Input`: Filters profiles by name, model, or provider. * `+ Add`: Navigates to `/ai-profiles/new` to create a profile. * **Data Grid Columns:** * `Profile Name`: Descriptive title (e.g., `Billing Copilot Pro`, `CDR Anomaly & Fraud Reasoner`, `Customer Support Bot (Claude)`). * `Provider`: Upstream provider name with Bot icon (e.g., `OpenAI Official Cloud`, `DeepSeek Telecom Copilot`, `Anthropic Claude Services`). * `Model`: Exact engine string (e.g., `gpt-4o`, `deepseek-reasoner`, `claude-3-5-sonnet-20241022`). * `Status`: Operational state badge (`Active` in green). * `Actions`: Direct inline actions to edit profile (`Pencil`), duplicate configuration (`Copy`), or delete (`Trash`). ### 4.2 Create / Edit AI Profile Form ![Create AI Profile Form](/screenshots/billing/admin/ai-integration/ai-profiles/ai-profiles-form.png) The Level 2 form organizes profile attributes into intuitive configuration cards: * **Header:** * `< List`: Back button returning to the profiles grid. * Title: `Create New` or `Edit AI Profile`. * **Profile Configuration Fields:** * `Profile Name *`: Unique operational title. * `Provider *`: Dropdown selecting one of the active providers configured in the AI Providers module. * `Model *`: Model identifier (e.g., `gpt-4o`, `claude-3-5-sonnet-20241022`). * `Type`: Operational category (`General`, `Chatbot`, `Voice Assistant`, `Forensic Reasoner`). * `Temperature`: Slider or numeric field controlling output variance (`0.0` for strict logic, `0.7` for natural conversation). * `Max Tokens`: Maximum generation limit per turn (e.g., `2048`). * `System Prompt`: Rich multiline text area defining the persona, instructions, and telecom boundaries. * `Active Status`: Switch enabling the profile for platform consumption. * **Sticky Bottom Bar (`FixedActionBar`):** * `Cancel`: Restores original values. * `Save and close`: Persists profile configurations. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────────────┐ │ Portal / Copilot User│ └──────────┬───────────┘ │ ▼ ┌────────────────────────────────────────────────────────┐ │ AI Profile Manager │ │ 1. Loads System Prompt & Temperature parameters │ │ 2. Enforces Max Token limits & context boundaries │ │ 3. Injects sanitized tenant billing data into context │ └──────────────────────────┬─────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────┐ │ AI Provider Gateway │ │ Routes request to authorized cloud or on-prem model │ └────────────────────────────────────────────────────────┘ ``` 1. **Prompt Sanitization:** Customer-specific proprietary data (e.g., credit card numbers, raw passwords) is stripped before prompt assembly. 2. **Deterministic Fallbacks:** If a profile encounters an upstream provider rate limit, the dispatcher can automatically fallback to a secondary profile. 3. **Token Usage Bounds:** Hard limits on `max_tokens` prevent runaway billing costs during complex multi-turn automated interactions. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook A: Deploying a Forensic CDR Fraud Reasoner Profile 1. Navigate to **ADMIN > AI Integration > AI Profiles**. 2. Click **+ Add**. 3. Set **Profile Name** to `CDR Anomaly & Fraud Reasoner`. 4. Select **Provider** as `DeepSeek Telecom Copilot`. 5. Enter **Model** as `deepseek-reasoner`. 6. Set **Temperature** to `0.1` (ensuring rigorous analytical consistency). 7. In **System Prompt**, enter: ``` You are an expert telecommunications fraud investigator. Analyze call detail records, spend velocities, and routing prefixes to identify patterns of IRSF, PBX brute-forcing, and anomalous traffic bursts. Provide concise, bulleted explanations of detected threats. ``` 8. Click **Save and close**. ### Playbook B: Tuning the General Billing Copilot 1. In the **AI Profiles** list, locate `Billing Copilot Pro`. 2. Click the **Edit** (`Pencil`) icon. 3. Adjust **Temperature** to `0.5` for balanced, natural dialogue. 4. Set **Max Tokens** to `4096`. 5. Click **Save and close**. --- ## 7. Troubleshooting & Diagnostic Commands ### Inspecting Profiles & Associated Providers via SQL ```sql SELECT p.id, p.profile_name, prov.name AS provider_name, p.model, p.temperature, p.max_tokens, p.status FROM public.ai_profiles p LEFT JOIN public.ai_providers prov ON prov.id = p.provider_id ORDER BY p.id ASC; ``` ### Validating Profile System Prompts ```sql SELECT id, profile_name, LENGTH(system_prompt) AS prompt_length, substring(system_prompt from 1 for 60) AS prompt_preview FROM public.ai_profiles; ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **AI Profiles** module connects directly to the **Ring2All BSS MCP Server**, providing administrators and cognitive orchestrators with programmatic tools to query profile templates, temperature boundaries, and active LLM model associations. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_ai_profiles` | `Super Administrator` | Lists configured AI persona profiles, system prompts, inference models, and temperature parameters. | `{}` | ### Sample MCP Tool Execution: `list_ai_profiles` #### Request Payload ```json { "name": "list_ai_profiles", "arguments": {} } ``` #### Response Payload ```json [ { "id": 1, "profileName": "Billing Copilot Pro", "providerName": "OpenAI Production", "model": "gpt-4o", "temperature": 0.5, "maxTokens": 4096, "status": "active" }, { "id": 2, "profileName": "NOC Anomaly Analyst", "providerName": "Anthropic Claude Core", "model": "claude-3-5-sonnet-20241022", "temperature": 0.2, "maxTokens": 8192, "status": "active" } ] ``` ### Conversational AI Prompts for Copilot * *"List all configured AI assistant profiles and their inference models."* * *"What is the active model and temperature configured for Billing Copilot Pro?"* * *"Show all profiles utilizing Anthropic Claude Core."* --- ## 9. Glossary * **Temperature:** A parameter between 0 and 2 that governs the randomness of the model's output; lower values make outputs more focused and deterministic. * **Max Tokens:** The maximum number of tokens that can be generated in the model's completion response. * **System Prompt:** The foundational instructions provided to the language model that establish its role, behavioral guidelines, constraints, and format requirements. * **Embeddings Model:** A specialized model that converts text into high-dimensional vector representations for semantic search and retrieval-augmented generation (RAG). * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/ai/ai-providers TITLE: AI Providers Module Documentation URL: https://docs.ring2all.com/billing/admin/ai/ai-providers.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **AI Providers** module (`public.ai_providers`) establishes and governs external upstream connections to Large Language Model (LLM) and Text-To-Speech (TTS) cloud inference engines for **Ring2All Billing**. In modern telecom operations, AI agents assist with billing inquiries, automated CDR fraud explanation, conversational IVRs, and natural language customer support. This module provides a unified abstraction layer connecting to premier AI backends—including **OpenAI**, **Anthropic**, **DeepSeek**, and private OpenAI-compatible inference servers (such as vLLM, Ollama, or LiteLLM gateways)—with credential encryption, capability discovery, base URL overrides, and live connectivity health checks. ### Data Model & Architecture Diagram ``` ┌────────────────────────────────────────────────────────────────────────┐ │ AI Providers (public.ai_providers) │ │ • id: bigint (Primary Key) │ │ • uuid: UUID (Unique Public Identifier) │ │ • tenant_id: bigint / domain_id: bigint │ │ • provider: 'openai' | 'anthropic' | 'deepseek' | 'custom' │ │ • name: text (e.g., 'OpenAI Official Cloud', 'DeepSeek Copilot') │ │ • organization: text (Optional Org ID / Tenant Header) │ │ • api_key: text (Encrypted Upstream Bearer Token) │ │ • base_url: text (Custom Gateway Endpoint e.g., https://api.openai...)│ │ • api_key_type: VARCHAR(50) ('standard', 'managed') │ │ • capabilities: jsonb (Supported features: chat, tts, vision, etc.) │ │ • status: boolean (Active / Inactive) │ └───────────────────────────────────┬────────────────────────────────────┘ │ Upstream Transport Gateway ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ External AI Inference Engines │ │ • OpenAI API (GPT-4o, GPT-4o-mini, Whisper, TTS-1) │ │ • Anthropic API (Claude 3.5 Sonnet, Claude 3.5 Haiku) │ │ • DeepSeek API (DeepSeek-V3, DeepSeek-Reasoner R1) │ │ • Private On-Premise Gateways (vLLM / LiteLLM / Ollama) │ └────────────────────────────────────────────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.ai_providers`**: * `id`: Numeric primary key (`bigserial`). * `uuid`: Immutable UUID utilized in frontend routing and REST APIs. * `provider`: Upstream provider protocol driver (`openai`, `anthropic`, `deepseek`, `custom`). * `name`: Descriptive label assigned by the administrator. * `organization`: Optional organization ID header passed to providers supporting multi-project billing. * `api_key`: API authorization key. * `base_url`: Optional custom endpoint URL, allowing rerouting to private proxies or localized regional endpoints. * `capabilities`: Dynamic JSONB schema storing discovered model lists, token limits, and TTS voice registries. * `status`: Operational toggle enabling or disabling all profiles linked to the provider. --- ## 2. Module Overview (Commercial & Business Value) * **Multi-Provider Resilience & Zero Vendor Lock-In:** Organizations are not tethered to a single AI vendor. If an upstream provider suffers rate limiting or an outage, billing copilots can be switched across providers seamlessly. * **Cost Optimization Across Workload Profiles:** High-reasoning tasks (such as forensic CDR fraud analysis) can leverage DeepSeek Reasoner or Claude 3.5 Sonnet, while high-volume standard customer notifications leverage cost-efficient models. * **Private & On-Premise Compliance:** Financial institutions and telecom carriers with strict data residency laws can direct `base_url` to an internal on-premise vLLM or Ollama cluster, guaranteeing customer billing data never leaves the private perimeter. * **Centralized Key Management:** API tokens are managed in one secure vault rather than distributed across multiple microservices or client applications. --- ## 3. 🎯 User Roles & Key Capabilities | Role | Key Capabilities & Permissions in AI Providers | | :--- | :--- | | **Platform Administrator** | Adds, configures, and tests AI service providers; enters upstream API keys; manages organization tags and custom base URLs. | | **Security Engineer** | Rotates API tokens, reviews outgoing connection security, and ensures private endpoints adhere to TLS encryption standards. | | **NOC Engineer** | Monitors provider connectivity status, executes live test connection probes, and troubleshoots upstream latency or rate limits. | | **Billing Specialist** | Views available providers and supported capabilities when configuring AI Profiles for customer billing support. | --- ## 4. Visual Interface & Form Structure The **AI Providers** module features a clean administrative list view and a dedicated creation/editing surface. ### 4.1 AI Providers Listing ![AI Providers List](/screenshots/billing/admin/ai-integration/ai-providers/ai-providers-list.png) The list view displays all configured AI inference providers: * **Header Controls:** * `Search Input`: Filters providers by name or provider type. * `+ Add`: Navigates to `/ai-providers/new` to register a new provider. * **Data Grid Columns:** * `Name`: Descriptive name of the integration (e.g., `OpenAI Official Cloud`, `Anthropic Claude Services`, `DeepSeek Telecom Copilot`). * `Provider`: Driver engine badge with Bot icon (`openai`, `anthropic`, `deepseek`). * `API Key Type`: Credential type badge (`STANDARD`). * `Enabled`: Operational status badge (`Active` in green). * `Actions`: Direct actions to edit settings (`Pencil`), duplicate configuration (`Copy`), or delete provider (`Trash`). ### 4.2 Create / Edit AI Provider Form ![Create AI Provider Form](/screenshots/billing/admin/ai-integration/ai-providers/ai-providers-form.png) The Level 2 form provides a structured configuration box with immediate verification capabilities: * **Header:** * `< List`: Returns to the main providers grid. * Title: `Create New` or `Edit Provider`. * **Provider Configuration Fields:** * `Name *`: Human-readable label (e.g., `OpenAI Official Cloud`). * `Organization`: Optional organization ID (e.g., `org-xxxxxxxx`). * `Provider *`: Dropdown selection (`OpenAI`, `Anthropic`, `DeepSeek`, `Custom`). * `Base URL`: Endpoint override (e.g., `https://api.openai.com/v1` or custom on-premise proxy). * `API Key *`: Secret token provided by the upstream AI vendor. * `Enabled`: Switch toggling provider availability. * `Test Connection`: Interactive button that initiates an immediate ping to the upstream API to validate credentials before saving. * **Sticky Bottom Bar (`FixedActionBar`):** * `Cancel`: Discards uncommitted changes. * `Save and close`: Validates input and persists configuration. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────────────┐ │ AI Profile Request │ │ (Copilot / Assistant)│ └──────────┬───────────┘ │ ▼ ┌────────────────────────────────────────────────────────┐ │ AI Gateway Dispatcher │ │ 1. Fetches provider credentials from public.ai_providers│ │ 2. Appends auth headers & optional Org ID │ │ 3. Routes HTTP/SSE request to configured Base URL │ └──────────────────────────┬─────────────────────────────┘ │ ┌──────────────┼──────────────┐ ▼ ▼ ▼ [ OpenAI Cloud ] [ Anthropic ] [ DeepSeek / On-Prem ] ``` 1. **Token Protection:** API keys are restricted at the database level and never exposed in plain text in browser client applications. 2. **Dynamic Header Injection:** The gateway dynamically injects vendor-specific headers (e.g., `x-api-key` for Anthropic, `Authorization: Bearer` for OpenAI). 3. **Connection Pre-Flight Checks:** The **Test Connection** button sends a lightweight query (e.g., model listing) to verify authentication without consuming inference credits. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook A: Registering an Official OpenAI Provider 1. Navigate to **ADMIN > AI Integration > Providers**. 2. Click **+ Add**. 3. Set **Name** to `OpenAI Official Cloud`. 4. Select **Provider** as `OpenAI`. 5. Enter the API Key beginning with `sk-...`. 6. Click **Test Connection**. A green success notification confirms API key validity. 7. Click **Save and close**. ### Playbook B: Connecting a Private On-Premise vLLM Server 1. Click **+ Add**. 2. Set **Name** to `Private Datacenter LLM`. 3. Select **Provider** as `Custom` (or `OpenAI Compatible`). 4. In **Base URL**, enter `http://10.10.50.20:8000/v1`. 5. Enter the internal cluster token in **API Key**. 6. Click **Test Connection** and verify reachability. 7. Click **Save and close**. --- ## 7. Troubleshooting & Diagnostic Commands ### Querying Configured Providers in SQL ```sql SELECT id, name, provider, base_url, status, created_at FROM public.ai_providers ORDER BY id ASC; ``` ### Testing Upstream Provider Reachability via Curl ```bash curl -s -X POST https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "ping"}], "max_tokens": 5}' ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **AI Providers** module connects directly to the **Ring2All BSS MCP Server**, providing administrators and cognitive copilots with programmatic visibility into registered neural model inference backends and operational states. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_ai_providers` | `Super Administrator` | Lists upstream Artificial Intelligence (LLM) inference providers with active status and model types. | `{}` | ### Sample MCP Tool Execution: `list_ai_providers` #### Request Payload ```json { "name": "list_ai_providers", "arguments": {} } ``` #### Response Payload ```json [ { "id": 1, "name": "OpenAI Production", "provider": "openai", "status": "active", "baseUrl": "https://api.openai.com/v1", "modelsCount": 4 }, { "id": 2, "name": "Anthropic Claude Core", "provider": "anthropic", "status": "active", "baseUrl": "https://api.anthropic.com", "modelsCount": 3 } ] ``` ### Conversational AI Prompts for Copilot * *"List all active AI inference providers and their configured endpoints."* * *"Is OpenAI Production currently active and accessible?"* * *"Show which AI providers are registered for chatbot operations."* --- ## 9. Glossary * **LLM (Large Language Model):** Advanced neural network models capable of understanding, summarizing, and generating natural language and code. * **Base URL:** The target root URL where REST requests are dispatched, allowing rerouting to local models or enterprise caching proxies. * **Provider Protocol:** The specific API convention implemented by the vendor (OpenAI REST, Anthropic Messages API, etc.). * **Test Connection:** An active probe verifying API authentication and network reachability without committing configuration. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/ai/ai-service-hub TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/ai/ai-service-hub.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/ai/ai-tool-profiles TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/ai/ai-tool-profiles.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/ai/ai-translator-profiles TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/ai/ai-translator-profiles.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/firewall/access-control TITLE: Access Control Module Documentation URL: https://docs.ring2all.com/billing/admin/firewall/access-control.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Access Control** module (`public.firewall_access_control`, `public.firewall_ip_bans`) manages granular IP-level and CIDR subnet authorization lists (Access Control Lists / ACL) for **Ring2All Billing**. While global firewall settings define the overarching state of host packet filtering, Access Control determines which discrete network endpoints are explicitly permitted (whitelisted) or prohibited (blacklisted) from interacting with the billing portal, API listeners, and telecommunications signaling hooks. Access Control records can be permanent or time-bounded (with automated expiration), support specific protocols (TCP, UDP, ICMP, or All), directionality (Input, Output, Forward), priority sequencing, and interface binding (e.g., `eth0`, `wg0`, `tun0`). ### Data Model & System Linkage ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Access Control Entry (public.firewall_access_control) │ │ • id: bigint (Primary Key) │ │ • name: VARCHAR(100) (Descriptive Identifier) │ │ • description: text │ │ • list_type: 'whitelist' | 'blacklist' │ │ • ip_address: VARCHAR(45) (IPv4/IPv6 or CIDR Range) │ │ • protocol: 'all' | 'tcp' | 'udp' | 'icmp' │ │ • direction: 'in' | 'out' | 'forward' │ │ • priority: integer (Execution Evaluation Order, e.g. 50) │ │ • source_port: VARCHAR(50) │ │ • destination_port: VARCHAR(50) │ │ • interface: VARCHAR(50) (Network Interface Binding) │ │ • expires_at: timestamptz (Nullable for Permanent Entries) │ │ • enabled: boolean │ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┴─────────────────────────┐ ▼ ▼ ┌───────────────────────────────────┐ ┌───────────────────────────────────┐ │ nftables / iptables │ │ Fail2Ban Synchronization │ │ • Whitelist: Fast-path bypass │ │ • Pushes manual blacklists to │ │ • Blacklist: Kernel drop at PREROUTING│ │ Fail2Ban jails │ └───────────────────────────────────┘ └───────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.firewall_access_control`**: * `id`: Numeric primary key (`bigserial`). * `name`: Human-readable label for the ACL rule. * `list_type`: Determines policy enforcement: * `whitelist`: Grants immediate ingress pass-through, overriding automated rate limiters. * `blacklist`: Drops packets at the kernel level without responding. * `ip_address`: Single IP address (e.g., `192.168.1.50`) or network subnet in CIDR notation (e.g., `10.10.0.0/16`). * `priority`: Rule ranking; rules with lower numbers are evaluated first in the kernel packet chain. * `interface`: Specific hardware or virtual interface (e.g., `eth0`, `tun0`, `wg0`) where the rule applies. * `expires_at`: Optional timestamp for temporary bans or guest administrative maintenance windows. * `enabled`: Master activation switch for the individual rule. --- ## 2. Module Overview (Commercial & Business Value) * **Trusted Partner & Wholesale Carrier Isolation:** Enforces strict IP whitelisting for wholesale carrier interconnects and external CRM/ERP webhook endpoints, preventing unauthorized third parties from spoofing billing transactions. * **Rapid Threat Quarantine:** Enables network security personnel to isolate an attacking subnet with a single click, instantly cutting off active DDoS or credential stuffing campaigns. * **Temporary Maintenance Windows:** Supports time-expiring whitelists, allowing external contractors or auditing teams to access the platform during maintenance without leaving persistent security holes. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`CRUD` on ACL Entries & Rules) | Whitelists NOC management subnets, provisions permanent carrier interconnect rules, and flushes expired entries. | | **Security Officer / SecOps** | Ban Management & Fail2Ban Sync | Enforces manual IP blacklists, synchronizes active jails with Fail2Ban, and audits whitelist exceptions against security policies. | | **Billing Engineer** | Read & Create (Carrier Whitelists) | Verifies that carrier gateways and payment processor notification IPs (e.g., Stripe webhooks) are correctly whitelisted in access control. | --- ## 4. Visual Interface & Form Structure ### Level 1 — Access Control List View The access control catalog displays all active and expired rules, categorized by list type (Whitelist/Blacklist), IP address/CIDR, protocol, expiration status, and action controls. ![Access Control List View](/screenshots/billing/admin/firewall/access-control/access-control-list.png) ### Level 2 — Add Access Control Entry Modal The modal dialog enables rapid provisioning of IP and CIDR rules with protocol, interface, and port constraints. ![Add Access Control Entry Modal](/screenshots/billing/admin/firewall/access-control/access-control-modal.png) #### Fields & Parameters Reference * **Name:** Descriptive identifier (e.g., "Corporate Head Office Gateway"). * **Description:** Optional administrative notes detailing the purpose or ticket number. * **List Type:** Selects between **Whitelist** (Accept) or **Blacklist** (Drop). * **IP Address:** Target IPv4, IPv6, or CIDR network range (e.g., `198.51.100.0/24`). * **Protocol:** Protocol filtering (`All`, `TCP`, `UDP`, `ICMP`). * **Direction:** Traffic flow (`Input (Incoming)`, `Output (Outgoing)`, `Forward`). * **Priority:** Execution order priority (default `50`; lower numeric values evaluate first). * **Source Port / Destination Port:** Optional port constraints or ranges (e.g., `8000-8010`). * **Interface:** Target network interface (e.g., `eth0`, `tun0`). Leave blank for all interfaces. * **Enabled:** Operational toggle to activate or deactivate the rule. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────┐ 1. POST /api/firewall/access-control ┌────────────────────────┐ │ Administrator├───────────────────────────────────────────────►│ Fastify 5 API Guard │ └──────────────┘ └───────────┬────────────┘ │ 2. Insert ACL Record into ss_billing ▼ ┌──────────────┐ 4. Atomic nftables / iptables Commit ┌────────────────────────┐ │ Linux Kernel ◄────────────────────────────────────────────────┤ Firewall Synchronizer │ │ netfilter │ └────────────────────────┘ └──────────────┘ │ 3. Trigger Sync Event via Redis Pub/Sub ``` 1. **Rule Creation:** The administrator configures an ACL entry in the modal and submits the form. 2. **Database Persistence:** The Fastify backend validates IP formatting and CIDR boundaries, storing the record in `public.firewall_access_control`. 3. **Firewall Sync:** Clicking **Apply Rules** triggers the firewall synchronizer daemon. 4. **Kernel Application:** Rules are translated into `nftables` or `iptables` syntax and injected directly into the appropriate kernel chain without dropping existing active connections. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Whitelisting a Wholesale Carrier Signaling Gateway 1. Navigate to **ADMIN > Firewall > Access Control**. 2. Click **+ Add** in the top-right toolbar. 3. Enter **Name:** `Carrier Interconnect - Alpha Trunk`. 4. Set **List Type:** `Whitelist`. 5. Enter the carrier's signaling IP in **IP Address:** `203.0.113.50`. 6. Set **Protocol:** `UDP`, **Destination Port:** `5060`. 7. Set **Priority:** `10` (high priority). 8. Toggle **Enabled** to `Yes` and click **Save**. 9. Click **Apply Rules** in the toolbar to commit changes to the running Linux kernel firewall. ### Playbook 2: Blacklisting a Persistent Credential Stuffing Subnet 1. Navigate to **ADMIN > Firewall > Access Control**. 2. Click **+ Add**. 3. Enter **Name:** `Malicious Botnet Subnet /24`. 4. Set **List Type:** `Blacklist`. 5. Enter **IP Address:** `198.51.100.0/24`. 6. Set **Protocol:** `All`, **Direction:** `Input (Incoming)`. 7. Click **Save**, then click **Apply Rules**. --- ## 7. Troubleshooting & Diagnostic Commands ### Querying ACL Database Records ```bash # List active access control rules ordered by priority sudo -u postgres psql -d ss_billing -c \ "SELECT id, name, list_type, ip_address, protocol, direction, priority, enabled \ FROM firewall_access_control ORDER BY priority ASC;" ``` ### Checking Kernel Rules ```bash # View active nftables access control chain nft list chain inet filter access_control # For iptables systems: iptables -L ACCESS_CONTROL -n -v --line-numbers ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Access Control** module connects directly to the **Ring2All BSS MCP Server**, enabling security engineers and automated SOC agents to audit IP whitelist and blacklist policies. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_firewall_access_control` | `Super Administrator` | Lists firewall Access Control Entries (whitelist/blacklist, CIDR blocks, protocols, and priority). | `{"listType": "whitelist"}` | ### Sample MCP Tool Execution: `list_firewall_access_control` #### Request Payload ```json { "name": "list_firewall_access_control", "arguments": { "listType": "whitelist" } } ``` #### Response Payload ```json [ { "id": 1, "name": "Office Internal Subnet", "listType": "whitelist", "ipAddress": "192.168.10.0/24", "protocol": "all", "direction": "in", "priority": 10, "enabled": true }, { "id": 2, "name": "Primary SBC Transit", "listType": "whitelist", "ipAddress": "192.168.10.31", "protocol": "all", "direction": "in", "priority": 20, "enabled": true } ] ``` ### Conversational AI Prompts for Copilot * *"List all active whitelist entries configured in the firewall ACL."* * *"Is the corporate IP subnet 192.168.10.0/24 currently whitelisted?"* * *"Show all priority 1 blacklisted IP addresses."* --- ## 9. Glossary * **CIDR (Classless Inter-Domain Routing):** A notation for specifying IP addresses and their associated routing prefix (e.g., `192.168.1.0/24`). * **Whitelist:** An explicit list of authorized entities permitted access while all other entities are denied. * **Blacklist:** An explicit list of forbidden entities blocked from access while others are evaluated normally. * **Kernel Netfilter:** The packet processing subsystem inside the Linux kernel responsible for filtering, NAT, and connection tracking. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/firewall/ai-perimeter-guard TITLE: AI Perimeter Guard Module Documentation URL: https://docs.ring2all.com/billing/admin/firewall/ai-perimeter-guard.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **AI Perimeter Guard** module (`public.ai_security_events`, `public.ai_guard_settings`, `public.firewall_ip_bans`) delivers autonomous, heuristic-driven threat detection and automated IP mitigation for **Ring2All Billing**. In telecommunications environments, billing engines and online charging systems (OCS) are primary targets for International Revenue Share Fraud (IRSF), distributed credential stuffing against customer self-care portals, automated SIP scan floods, and API scraping. The AI Perimeter Guard continuously evaluates telemetry streams from the Fastify API access logs, NGINX perimeter proxies, and telecom signaling nodes, scoring incoming connection vectors against neural anomaly models. When an anomaly threshold is breached, the engine autonomously pushes kernel-level IP bans to Linux `nftables`/`iptables` and Kamailio memory tables (`htable`). ### Data Model & Architecture Diagram ``` ┌────────────────────────────────────────────────────────────────────────┐ │ AI Perimeter Engine & Telemetry Stream │ │ • NGINX HTTPS Reverse Proxy Logs │ │ • Fastify REST API Authentication Requests (/api/v1/auth/login) │ │ • OCS Balance Deduction & Webhook Callbacks │ │ • Kamailio SIP Signaling & Pike Flood Meters │ └───────────────────────────────────┬────────────────────────────────────┘ │ ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ Anomaly & Risk Evaluation Engine │ │ • Entropy Calculation: Header randomness, user-agent fuzzing │ │ • Velocity Metering: Requests/second per IP and ASN │ │ • Toll Fraud Pattern Correlation: Sequential high-cost destination calls│ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┴─────────────────────────┐ ▼ ▼ ┌───────────────────────────────────┐ ┌───────────────────────────────────┐ │ ai_security_events Table │ │ firewall_ip_bans Table │ │ • event_type: 'brute_force' │ │ • ip_address: '198.51.100.44' │ │ • severity: 'critical' │ │ • ban_type: 'kernel_drop' │ │ • ai_confidence: 0.96 │ │ • duration_seconds: 86400 │ │ • mitigation_action: 'ban' │ │ • trigger_rule: 'ai_perimeter' │ └───────────────────────────────────┘ └─────────────────┬─────────────────┘ │ Autonomous Push ▼ ┌───────────────────────────────────┐ │ Linux nftables & iptables Drop │ │ Kamailio htable blacklist ban │ └───────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.ai_security_events`**: * `id`: Numeric primary key (`bigserial`). * `event_type`: Attack category (`'brute_force'`, `'distributed_scan'`, `'toll_fraud'`, `'malformed_sip'`, `'api_abuse'`). * `severity`: Threat ranking (`'low'`, `'medium'`, `'high'`, `'critical'`). * `ip_address`: Offending IPv4 or IPv6 address. * `ai_confidence`: Statistical confidence score generated by the model (`0.00` to `1.00`). * `mitigation_action`: Active countermeasure deployed (`'monitored'`, `'rate_limited'`, `'ban'`, `'diverted'`). * `created_at`: High-resolution microsecond timestamp. * **`public.ai_guard_settings`**: * `enabled`: Master toggle activating autonomous enforcement. * `sensitivity_level`: Operational posture (`'low'`, `'balanced'`, `'aggressive'`). * `auto_ban_threshold`: Confidence cut-off required to trigger immediate kernel drop. * `ban_duration_hours`: Default quarantine period before IP expiration. * `telephony_toll_fraud_guard`: Dedicated toggle correlating rating CDR spikes with origin IPs. --- ## 2. Module Overview (Commercial & Business Value) * **Direct Toll Fraud & IRSF Prevention:** Automated detection of anomalous call surges stops International Revenue Share Fraud in milliseconds, protecting carriers and VoIP providers from multi-thousand-dollar wholesale carrier disputes. * **Elimination of 24/7 Security Burnout:** Autonomous mitigation neutralizes zero-day brute force and botnet floods instantly, freeing Network Operations Center (NOC) engineers from manual IP blocking during off-hours. * **Preservation of Legitimate Customer Traffic:** Machine learning cross-references customer geolocation, historic billing activity, and ASN reputation to avoid false positives, ensuring valid paying customers are never locked out of their self-care portals. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`RW` on AI Defense & Kernel Bans) | Calibrates AI sensitivity parameters, adjusts auto-ban confidence thresholds, overrides kernel bans, and binds AI analysis providers. | | **Security Officer / SecOps** | Forensic Read & Ban Management | Investigates attack vectors, inspects forensic telemetry payloads, validates threat posture, and manually releases mistakenly banned enterprise IPs. | | **Billing & NOC Auditor** | Read-Only (Dashboard & Event Stream) | Reviews security posture metrics, cross-references security incident spikes with customer dispute tickets, and monitors carrier billing integrity. | --- ## 4. Visual Interface & Form Structure ### Level 1 — AI Perimeter Guard Threat Overview The main telemetry dashboard delivers real-time situational awareness, displaying active kernel bans, today's attack volume, toll fraud blocks, top attacking origin countries, 7-day vector distribution, and 24-hour threat velocity. ![AI Perimeter Guard Threat Overview](/screenshots/billing/admin/firewall/ai-perimeter-guard/ai-guard-overview.png) ### Level 2 — Defense Settings Tab The settings view enables granular calibration of detection heuristics, auto-ban triggers, quarantine duration, and telemetry refresh cadences. ![AI Perimeter Guard Defense Settings](/screenshots/billing/admin/firewall/ai-perimeter-guard/ai-guard-settings.png) #### Fields & Parameters Reference * **AI Defense Shield (Master Toggle):** Enables or disables real-time evaluation of perimeter traffic. * **Sensitivity Posture:** Configures detection aggression: * *Balanced (Recommended):* Optimized for standard telecom and billing traffic; minimizes false positives. * *Aggressive:* Lower tolerance for credential retry failures; immediately bans repeated 401/403 responses. * *Permissive:* Observational mode; logs events to database without executing kernel drops. * **Auto-Ban Threshold Score:** Minimum AI model confidence (e.g., `85%`) required before executing an automated kernel ban. * **Quarantine Duration (Hours):** Duration an offending IP remains blocked in `firewall_ip_bans` before automatic expiration. * **Telemetry Refresh Cadence:** Interval (seconds) at which the front-end dashboard polls background metrics. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────┐ 1. Inbound Requests ┌────────────────────────┐ │ Perimeter ├───────────────────────────────────────►│ NGINX / Fastify API │ │ Traffic │ └───────────┬────────────┘ └──────────────┘ │ 2. Asynchronous Telemetry Push via Redis Pub/Sub ▼ ┌──────────────┐ 4. Synchronize Blacklist ┌────────────────────────┐ │ Linux Kernel ◄────────────────────────────────────────┤ AI Perimeter Guard │ │ nftables │ │ Background Evaluator │ └──────────────┘ └───────────┬────────────┘ │ 3. Write Event & Ban ▼ ┌────────────────────────┐ │ ss_billing Database │ │ (ai_security_events, │ │ firewall_ip_bans) │ └────────────────────────┘ ``` 1. **Ingestion:** API authentication calls and web portal traffic pass through the perimeter web server. 2. **Telemetry Dispatch:** Request metadata (IP, headers, ASN, path, response status) is pushed to the evaluator daemon. 3. **Inference & Auditing:** The engine evaluates anomaly scores. If confidence exceeds the threshold, an event is logged in `public.ai_security_events` and an immutable record is inserted into `public.firewall_ip_bans`. 4. **Kernel Drop Execution:** The ban executor executes an atomic rule addition to the Linux kernel firewall (`nftables` set `ring2all_bans`), instantly discarding subsequent TCP/UDP packets from the offender. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Investigating a "Critical" Toll Fraud Alert 1. Open **ADMIN > Firewall > AI Perimeter Guard**. 2. Review the **Attack Vectors (7 Days)** breakdown. 3. Switch to the **Security Incidents** tab to inspect the source IP, destination numbers attempted, and confidence rating. 4. Verify whether the offending IP is already quarantined in **Active Kernel Bans**. 5. If the IP attempted high-cost international destinations (e.g., +232, +252), navigate to **BILLING > Customer Accounts > Customers** to ensure the compromised customer account is temporarily suspended. ### Playbook 2: Whitelisting a False-Positive Corporate Gateway 1. Navigate to **ADMIN > Firewall > Access Control**. 2. Click **+ Add Entry**. 3. Enter the customer's corporate gateway IP/CIDR (e.g., `198.51.100.0/24`). 4. Set Action to **Allow** and toggle **Bypass AI Guard**. 5. Click **Save and close**. 6. If the IP was previously quarantined, navigate to **ADMIN > Firewall > AI Perimeter Guard > IP Forensic Audit** and click **Remove Ban**. --- ## 7. Troubleshooting & Diagnostic Commands ### Verifying AI Guard Database State ```bash # Check recent AI security alerts sudo -u postgres psql -d ss_billing -c \ "SELECT event_type, severity, ip_address, ai_confidence, mitigation_action, created_at \ FROM ai_security_events ORDER BY id DESC LIMIT 5;" # Inspect active IP bans enforced by the system sudo -u postgres psql -d ss_billing -c \ "SELECT id, ip_address, ban_type, reason, expires_at FROM firewall_ip_bans WHERE status = 'active';" ``` ### Inspecting Linux Kernel nftables Sets ```bash # Check if kernel set contains banned IP addresses nft list set inet filter ring2all_bans # Manually test dropping an offending IP via nftables nft add element inet filter ring2all_bans { 198.51.100.44 } ``` ### Checking Daemon Service Logs ```bash # Monitor real-time telemetry processing in Fastify API journalctl -u ring2all-billing-api -f | grep -i "ai-guard" ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **AI Perimeter Guard** module connects directly to the **Ring2All BSS MCP Server**, providing security copilots and autonomous SOC diagnostic tools with real-time threat intelligence, kernel mitigation statuses, and automated IP ban telemetry. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `get_firewall_ai_perimeter_status` | `Super Administrator` | Retrieves AI Perimeter Guard real-time telemetry, active threat bans, and heuristic anomaly scores. | `{}` | ### Sample MCP Tool Execution: `get_firewall_ai_perimeter_status` #### Request Payload ```json { "name": "get_firewall_ai_perimeter_status", "arguments": {} } ``` #### Response Payload ```json { "guardEnabled": true, "neuralModelActive": true, "activeBansCount": 3, "eventsLast24Hours": 142, "highestAnomalyScore": 0.94, "recentBans": [ { "id": 12, "ipAddress": "198.51.100.44", "reason": "Distributed Credential Stuffing & Rate Flood", "aiConfidence": 0.94, "expiresAt": "2026-09-10T04:00:00Z" } ] } ``` ### Conversational AI Prompts for Copilot * *"What is the current status of the AI Perimeter Guard and how many IPs are banned?"* * *"Show all high-confidence security events detected in the last 24 hours."* * *"Verify if kernel nftables drop sets are active and synchronized."* --- ## 9. Glossary * **IRSF (International Revenue Share Fraud):** Telecommunications fraud where attackers route calls to high-cost premium numbers through compromised accounts. * **Confidence Score:** A mathematical value between 0.00 and 1.00 indicating the statistical likelihood that an observed traffic pattern is malicious. * **Kernel Drop:** Dropping network packets directly in Linux kernel netfilter/nftables space before socket allocation, protecting CPU resources. * **Telemetry Vector:** Multidimensional data points (rate, path, entropy, geographic origin) evaluated together to detect anomalous activity. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/firewall/firewall-settings TITLE: Firewall Settings Module Documentation URL: https://docs.ring2all.com/billing/admin/firewall/firewall-settings.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Firewall Settings** module (`public.firewall_settings`) governs the master operating state of host-level packet filtering and daemonized intrusion prevention on the **Ring2All Billing** application server. Operating as the control plane for underlying Linux network utilities (`nftables`/`iptables` and `fail2ban`), this module ensures that telecommunications rating APIs, web interfaces, and administrative ports are protected behind a deterministic, stateful security perimeter. When enabled, the firewall enforces default-deny ingress policies, admitting only traffic explicitly whitelisted by services, rules, or access control entries. Concurrently, the Intrusion Detection subsystem scans log files for authentication abuse, actively applying dynamic jail bans to persistent attackers. ### Data Model & Architecture Diagram ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Firewall Settings Entity (public.firewall_settings) │ │ • id: bigint (Primary Key) │ │ • firewall_enabled: boolean (Master nftables/iptables Ingress Filter) │ │ • fail2ban_enabled: boolean (Daemonized Log Parsing & Jail Monitor) │ │ • default_policy: 'drop' | 'reject' | 'accept' │ │ • log_dropped_packets: boolean │ │ • updated_at: timestamptz │ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┴─────────────────────────┐ ▼ ▼ ┌───────────────────────────────────┐ ┌───────────────────────────────────┐ │ Linux netfilter Subsystem │ │ Fail2Ban Daemon Monitor │ │ • Default Ingress: DROP │ │ • Monitors /var/log/nginx/access │ │ • Established/Related: ACCEPT │ │ • Monitors Fastify auth logs │ │ • Allowed Services: TCP/UDP ports │ │ • Jail: ring2all-billing-auth │ └───────────────────────────────────┘ └───────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.firewall_settings`**: * `id`: Numeric primary key (`bigserial`). * `firewall_enabled`: Master switch. When `true`, systemd service `nftables.service` (or `iptables`) is kept in an active running state with strict chain filtering. * `fail2ban_enabled`: Controls the operational state of `fail2ban.service`. When active, specialized jail filters parse Fastify 401 unauthorized responses and NGINX error streams. * `updated_at`: Timestamp recording when the security posture was modified. --- ## 2. Module Overview (Commercial & Business Value) * **Enterprise Hardening Out of the Box:** Eliminates accidental exposure of internal billing microservices, database listening ports (`5432`), or Redis cache instances (`6379`) to the public Internet. * **Defense-in-Depth Against Infrastructure Takeover:** Combines stateful packet filtering with dynamic log-based intrusion detection to stop automated port scans and brute force attacks before they consume server CPU cycles. * **Operational Simplicity:** Provides telecom system administrators with a simple, high-level control panel to govern host security without requiring manual SSH command-line intervention for core service toggling. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`RW` on Firewall Settings) | Activates or deactivates the host packet filtering engine, enables Fail2Ban intrusion detection, and commits security profile changes. | | **Security Officer / SecOps** | Audit & Verification | Audits current firewall and intrusion detection daemon states, verifies compliance against internal security baselines, and recommends policy updates. | | **Billing Operator** | Read-Only (Status View) | Inspects whether the firewall is active to rule out network filtering issues during third-party payment gateway integration. | --- ## 4. Visual Interface & Form Structure ### Level 1 — Firewall Settings View The interface presents clear, high-contrast operational cards organizing host firewall filtering and daemon intrusion detection controls, with a sticky action bar for committing changes. ![Firewall Settings View](/screenshots/billing/admin/firewall/firewall-settings/firewall-settings.png) #### Fields & Parameters Reference * **Firewall Status (Toggle):** Master switch controlling host packet filtering. * *Active (Yes):* Linux kernel packet filtering rules are applied. All ports not explicitly defined in **Services** or **Rules** are blocked. * *Inactive (No):* Kernel filtering is disabled; incoming traffic reaches listening sockets freely. * **Intrusion Detection (Fail2Ban) (Toggle):** Controls automated log-based banning. * *Active (Yes):* Fail2Ban daemon actively scans authentication logs, automatically banning source IPs that fail authentication repeatedly. * *Inactive (No):* Intrusion monitoring is suspended; no automated bans are initiated. * **Save Button:** Commits the configuration to PostgreSQL and signals the backend security agent to synchronize systemd services. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────┐ 1. PUT /api/firewall/settings ┌────────────────────────┐ │ System Admin ├───────────────────────────────────────────────►│ Fastify 5 API Route │ └──────────────┘ └───────────┬────────────┘ │ 2. Update │ 3. Dispatch System Database │ Command Event ▼ ┌────────────────────────┐ │ ss_billing Database │ │ (firewall_settings) │ └────────────────────────┘ │ ┌────────────────────────────────┴────────────────────────────────┐ ▼ ▼ ┌──────────────────────────┐ ┌──────────────────────────┐ │ systemctl start nftables │ │ systemctl start fail2ban │ └──────────────────────────┘ └──────────────────────────┘ ``` 1. **Administration Trigger:** The administrator toggles the desired subsystem and clicks **Save**. 2. **Atomic Persistence:** The Fastify API validates administrative privileges and records the state in `public.firewall_settings`. 3. **Daemon Synchronization:** The backend security runner triggers the platform orchestration command via `systemctl`, ensuring system services reflect the configured state. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Enabling Production Firewall Protection 1. Navigate to **ADMIN > Firewall > Firewall Settings**. 2. Verify under **ADMIN > Firewall > Services** that essential ports (HTTP: 80, HTTPS: 8443, API: 3003, SSH: 22) are correctly defined. 3. Return to **Firewall Settings**. 4. Toggle **Firewall Status** to **Yes**. 5. Toggle **Intrusion Detection (Fail2Ban)** to **Yes**. 6. Click **Save** in the bottom-right action bar. 7. Verify immediate server responsiveness on active administrative sessions. ### Playbook 2: Temporarily Suspending Filtering for Network Diagnosis 1. Navigate to **ADMIN > Firewall > Firewall Settings**. 2. Toggle **Firewall Status** to **No**. 3. Click **Save**. 4. Perform end-to-end network latency or port reachability diagnosis with the carrier provider. 5. Immediately return to **Firewall Settings**, toggle **Firewall Status** back to **Yes**, and click **Save**. --- ## 7. Troubleshooting & Diagnostic Commands ### Checking Service States via Systemd ```bash # Verify status of Linux packet filter systemctl status nftables || systemctl status iptables # Verify status of Fail2Ban intrusion detection daemon systemctl status fail2ban # Check Fail2Ban active jails and banned IPs fail2ban-client status ``` ### Inspecting Database Settings ```bash sudo -u postgres psql -d ss_billing -c \ "SELECT id, firewall_enabled, fail2ban_enabled, updated_at FROM firewall_settings;" ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Firewall Settings** module connects directly to the **Ring2All BSS MCP Server**, providing security administrators and AI infrastructure assistants with read-only visibility into master firewall operating parameters and intrusion defense states. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `get_firewall_settings` | `Super Administrator` | Retrieves core firewall operating state, default policies, and Fail2Ban service status. | `{}` | ### Sample MCP Tool Execution: `get_firewall_settings` #### Request Payload ```json { "name": "get_firewall_settings", "arguments": {} } ``` #### Response Payload ```json { "firewallEnabled": true, "fail2banEnabled": true, "defaultPolicy": "DROP", "synFloodProtection": true, "pingProtection": false, "backend": "nftables", "updatedAt": "2026-09-08T10:00:00Z" } ``` ### Conversational AI Prompts for Copilot * *"Is the host firewall currently enabled and enforcing default-drop policies?"* * *"What is the status of the Fail2Ban intrusion detection daemon?"* * *"Verify if SYN flood protection is active on the billing server."* --- ## 9. Glossary * **Packet Filtering:** The process of inspecting incoming and outgoing IP packets and either accepting, dropping, or rejecting them based on IP, port, and protocol. * **Fail2Ban:** An open-source intrusion prevention framework that monitors application log files for suspicious activity and creates dynamic firewall rules. * **Default Deny:** A security posture where all network traffic is blocked by default, requiring explicit rules to permit desired communication. * **Stateful Inspection:** Tracking the state of active network connections to automatically permit returning traffic belonging to recognized sessions. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/firewall/geo-firewall TITLE: Geo Firewall Module Documentation URL: https://docs.ring2all.com/billing/admin/firewall/geo-firewall.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Geo Firewall** module (`public.geo_firewall_rules`, `public.geo_ip_ranges`) provides country-level geographical IP filtering for **Ring2All Billing**. In telecommunications and billing operations, malicious connection attempts, credential attacks, and toll fraud schemes frequently originate from specific geographic regions where the operating company maintains no legitimate business presence, carrier interconnects, or customer accounts. By leveraging an integrated MaxMind GeoLite2 / DB-IP database and high-performance Linux kernel sets (`nftables` sets / `ipset`), the Geo Firewall evaluates the geographic origin of every inbound packet at wire speed. Countries can be marked as **Allowed** (emerald green) or **Blocked** (crimson red). Blocked countries are dropped at the kernel `PREROUTING` stage before consuming application server memory or Fastify event-loop cycles. ### Data Model & Architecture Diagram ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Geo Firewall Entity (public.geo_firewall_rules) │ │ • id: bigint (Primary Key) │ │ • country_code: CHAR(2) (ISO 3166-1 Alpha-2, e.g. 'RU', 'CN', 'US') │ │ • country_name: VARCHAR(100) │ │ • action: 'allow' | 'block' │ │ • notes: text │ │ • enabled: boolean │ │ • updated_at: timestamptz │ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┴─────────────────────────┐ ▼ ▼ ┌───────────────────────────────────┐ ┌───────────────────────────────────┐ │ MaxMind GeoIP Database │ │ Linux Kernel nftables Set │ │ • Binary lookup / CIDR blocks │ │ • nft add set inet filter geo_drop│ │ • Updated weekly via cron │ │ • O(1) hash lookup per packet │ └───────────────────────────────────┘ └───────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.geo_firewall_rules`**: * `id`: Numeric primary key (`bigserial`). * `country_code`: Standard ISO 3166-1 Alpha-2 two-character country code. * `country_name`: Full formal geographic name. * `action`: Enforcement directive (`'allow'` or `'block'`). * `enabled`: Active state flag. * `updated_at`: Timestamp recording when the regional policy was modified. --- ## 2. Module Overview (Commercial & Business Value) * **95%+ Attack Surface Reduction:** Blocking countries outside the carrier's operating footprint immediately eliminates the vast majority of automated botnet scans, unauthorized SIP registrations, and SSH brute-force campaigns. * **Toll Fraud & IRSF Mitigation:** Prevents rogue actors in offshore jurisdictions from scanning billing self-care portals or intercepting online rating mechanisms. * **Server Resource Preservation:** Dropping unwanted geographical traffic in the kernel eliminates up to 90% of useless socket allocations, ensuring the Fastify API and OCS balance deduction engines run with minimal latency. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`RW` on Geo-Firewall) | Configures national allow/block lists, toggles regional access policies, and saves changes to kernel netfilter tables. | | **Security Officer / SecOps** | Geographic Threat Analysis | Analyzes attack origins on the AI Perimeter Guard dashboard, identifies malicious clusters, and updates Geo-Firewall rules accordingly. | | **Billing Operations Lead** | Read-Only (Territorial Coverage) | Verifies that countries where new enterprise customers or carrier interconnects are located are properly marked as **Allowed**. | --- ## 4. Visual Interface & Form Structure ### Level 1 — Geo Firewall Interactive World Map The interface presents an interactive vector world map (`WorldMap.tsx` / `jsvectormap`) rendering global geographical boundaries. Allowed countries are rendered in emerald green, while blocked regions illuminate in vivid crimson red. ![Geo Firewall World Map](/screenshots/billing/admin/firewall/geo-firewall/geo-firewall-list.png) #### Controls & Parameters Reference * **Interactive World Map:** Click any nation to toggle its filtering status between **Allowed** and **Blocked**. Hovering displays the country name, two-letter code, and current state. * **Search Country Selector:** Dropdown search box in the header toolbar allowing rapid lookup and centering of any nation. * **Map Zoom Controls:** Bottom-left floating controls providing **Zoom In (+)**, **Zoom Out (-)**, and **Reset View**. * **Sticky Action Bar:** Floating bottom toolbar featuring the **Save** button to persist modified country lists and recompile kernel sets. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────┐ 1. Inbound Network Packet ┌────────────────────────┐ │ Foreign Host ├───────────────────────────────────────────────►│ Linux Kernel Netfilter │ └──────────────┘ └───────────┬────────────┘ │ 2. O(1) Set Lookup Against GeoIP Subnets (nftables) ▼ ┌───────────────────────────────────────────┐ │ Match in Blocked Regional CIDR Set? │ └─────┬───────────────────────────────┬─────┘ │ Yes │ No ▼ ▼ ┌─────────────────────┐ ┌─────────────────────┐ │ Silent Kernel DROP │ │ Fastify 5 API / Web │ │ (0 CPU overhead) │ │ Session Evaluation │ └─────────────────────┘ └─────────────────────┘ ``` 1. **Ingress Arrival:** A packet arrives from an external IP address. 2. **Kernel Set Inspection:** The Linux `nftables` netfilter chain references the compiled `geo_drop` set. 3. **Instant Mitigation:** If the IP belongs to a blocked country's CIDR ranges, the packet is silently dropped at `PREROUTING` before any application code executes. 4. **Allowed Path:** Packets from permitted countries proceed to standard port filtering and authentication. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Blocking High-Risk Jurisdictions Following a Brute-Force Surge 1. Review the **AI Perimeter Guard** telemetry to identify the top attack origins (e.g., Russian Federation, Eastern Asia). 2. Navigate to **ADMIN > Firewall > Geo Firewall**. 3. Use the search selector in the top toolbar to locate the offending country (e.g., `Russian Federation`). 4. Click on the country on the world map to toggle its state from **Allowed** (Green) to **Blocked** (Red). 5. Repeat for any other target regions (e.g., `China`). 6. Click **Save** in the bottom-right action bar. 7. The system regenerates the kernel IP set and applies the block immediately. ### Playbook 2: Unblocking a Country for International Expansion 1. When onboarding a new customer or carrier interconnect in a previously blocked country (e.g., Germany or Brazil): 2. Navigate to **ADMIN > Firewall > Geo Firewall**. 3. Locate the country on the map or type its name in the search bar. 4. Click the territory so it changes to **Allowed** (Green). 5. Click **Save** to commit the changes and remove the country's IP subnets from the kernel drop set. --- ## 7. Troubleshooting & Diagnostic Commands ### Inspecting Configured Geo Rules in Database ```bash sudo -u postgres psql -d ss_billing -c \ "SELECT country_code, country_name, action, enabled, updated_at \ FROM geo_firewall_rules WHERE action = 'block' ORDER BY country_name ASC;" ``` ### Checking Linux nftables Geo Drop Sets ```bash # Count total CIDR elements loaded into the geo drop set nft list set inet filter geo_drop | grep -c "elements" # Verify if a specific IP belongs to a blocked geo set nft "get element inet filter geo_drop { 198.51.100.1 }" ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Geo Firewall** module connects directly to the **Ring2All BSS MCP Server**, providing security copilots and network automation tools with instant visibility into geographic filtering policies and blocked territory counts. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `get_geo_firewall_status` | `Super Administrator` | Retrieves geographical IP blocking status, blocked country count, and database version. | `{}` | ### Sample MCP Tool Execution: `get_geo_firewall_status` #### Request Payload ```json { "name": "get_geo_firewall_status", "arguments": {} } ``` #### Response Payload ```json { "geoFirewallEnabled": true, "blockedCountriesCount": 18, "allowedCountriesCount": 231, "geoDbVersion": "GeoLite2-Country-2026.09", "kernelSetLoaded": true, "topBlockedCountries": ["RU", "CN", "IR", "KP", "NG"] } ``` ### Conversational AI Prompts for Copilot * *"What is the status of the Geo Firewall and how many countries are blocked?"* * *"List the top blocked country codes enforced at the kernel level."* * *"Verify if the GeoIP database is current and loaded into nftables."* --- ## 9. Glossary * **ISO 3166-1 Alpha-2:** Two-letter country codes representing countries and dependent territories (e.g., `US`, `DE`, `MX`). * **GeoIP Database:** A structured mapping table connecting public IPv4 and IPv6 address ranges to geographic countries, cities, and autonomous system numbers (ASNs). * **PREROUTING:** The earliest stage in the Linux network stack where incoming packets can be evaluated before routing decisions are made. * **O(1) Set Lookup:** Constant-time algorithmic lookup provided by kernel hash tables (`nftables` sets / `ipset`), ensuring zero latency impact regardless of table size. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/firewall/rules TITLE: Firewall Rules Module Documentation URL: https://docs.ring2all.com/billing/admin/firewall/rules.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Firewall Rules** module (`public.firewall_rules`) provides the policy orchestration engine for **Ring2All Billing**, enabling system operators to construct complex, multi-variable packet filtering statements. While the **Services** module defines ports and protocols, and **Access Control** manages quick IP whitelists and blacklists, **Firewall Rules** connects services, source subnets, destination interfaces, and evaluation actions into an ordered rule hierarchy. Each firewall rule defines an explicit Action (`Accept`, `Drop`, or `Reject`), directionality (`Input`, `Output`, or `Forward`), an associated named Service, a numeric evaluation Priority, source and destination CIDR boundaries, and optional interface binding. When committed via **Apply Rules**, the platform synchronizes the state directly with the underlying Linux netfilter engine (`nftables`/`iptables`). ### Data Model & System Linkage ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Firewall Rule Entity (public.firewall_rules) │ │ • id: bigint (Primary Key) │ │ • name: VARCHAR(100) (Rule Name, e.g. 'Allow Fastify API from VPN') │ │ • action: 'accept' | 'drop' | 'reject' │ │ • direction: 'input' | 'output' | 'forward' │ │ • service_id: bigint (FK to public.firewall_services) │ │ • priority: integer (Execution Evaluation Order, e.g. 10, 20, 30) │ │ • source_address: VARCHAR(100) (e.g. '10.8.0.0/24', '192.168.10.0/24')│ │ • destination_address: VARCHAR(100) (Optional Local VIP or Interface) │ │ • interface: VARCHAR(50) (e.g. 'eth0', 'tun0', 'wg0') │ │ • enabled: boolean (Active State Toggle) │ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┴─────────────────────────┐ ▼ ▼ ┌───────────────────────────────────┐ ┌───────────────────────────────────┐ │ Service Definition Lookup │ │ Linux Netfilter Pipeline │ │ • Extracts TCP/UDP protocol │ │ • Rules sorted by priority ASC │ │ • Extracts single port or range │ │ • Injected into nftables chain │ └───────────────────────────────────┘ └───────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.firewall_rules`**: * `id`: Numeric primary key (`bigserial`). * `name`: Concise, meaningful label identifying the policy purpose. * `action`: * `accept`: Allows packet traversal immediately. * `drop`: Discards packet silently without ICMP notification. * `reject`: Discards packet and issues an explicit ICMP unreachable response. * `direction`: Traffic vector (`input`, `output`, `forward`). * `service_id`: Foreign key pointing to `public.firewall_services.id`. * `priority`: Numeric weight controlling evaluation sequence. Rules are sorted in ascending order (`ORDER BY priority ASC`). * `source_address`: CIDR notation or specific IP restricting where traffic originates. * `destination_address`: Optional target IP constraint. * `interface`: Restricts policy application to a specific network interface. * `enabled`: Master switch controlling whether the rule is compiled into the running kernel firewall. --- ## 2. Module Overview (Commercial & Business Value) * **Zero-Trust Network Architecture:** Restricts sensitive billing administration and database replication exclusively to authorized corporate subnets, VPN tunnels, and trusted interconnects. * **Carrier SLA Assurance:** Protects carrier rating engines from distributed denial-of-service (DDoS) exhaustion, ensuring high-volume Call Detail Record (CDR) ingestion remains uninterrupted. * **Granular Policy Auditability:** Clean separation of concerns allows compliance auditors to verify that administrative interfaces (SSH, database, API) are never exposed directly to public ingress interfaces. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`CRUD` on Firewall Rules) | Authors enterprise security policies, designs network segregation rules, reorders priority evaluation chains, and applies rules to the kernel. | | **Security Officer / SecOps** | Policy Audit & Optimization | Reviews rule ordering to eliminate shadowing and redundancy, validates source subnet restrictions, and verifies compliance with ISO 27001. | | **Network Engineer** | Read & Test (Routing & Interfaces) | Verifies interface bindings (e.g., ensuring internal telecom nodes communicate across `tun0`/`wg0` while customer portals bind to `eth0`). | --- ## 4. Visual Interface & Form Structure ### Level 1 — Firewall Rules List View The policy catalog displays all active rules ordered by priority, displaying rule names, target services, actions, direction, interface bindings, active statuses, and execution controls. ![Firewall Rules List View](/screenshots/billing/admin/firewall/rules/rules-list.png) ### Level 2 — Add Firewall Rule Modal The policy creation modal provides structured input fields to configure actions, services, priorities, and source/destination addresses. ![Add Firewall Rule Modal](/screenshots/billing/admin/firewall/rules/rules-modal.png) #### Fields & Parameters Reference * **Rule Name:** Descriptive title (e.g., `Allow HTTPS Portal Web`, `Restrict SSH to Management VPN`). * **Action:** Filtering decision (`Accept`, `Drop`, `Reject`). * **Direction:** Flow perspective (`Input`, `Output`, `Forward`). * **Service:** Dropdown selecting a preconfigured definition from the **Services** module. * **Priority:** Numeric execution order (e.g., `10`, `20`, `30`). Lowest numbers evaluate first. * **Source Address:** Origin CIDR subnet or IP address (e.g., `10.8.0.0/24` or `192.168.10.0/24`). Leave blank for any source (`0.0.0.0/0`). * **Destination Address:** Target CIDR subnet or local host IP. Leave blank for any local address. * **Interface:** Hardware or virtual interface binding (e.g., `eth0`, `ens33`, `tun0`, `wg0`). * **Enabled:** Operational toggle. Set to `Yes` to include the rule in kernel compilation. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────┐ 1. POST /api/firewall/rules ┌────────────────────────┐ │ System Admin ├───────────────────────────────────────────────►│ Fastify 5 API Route │ └──────────────┘ └───────────┬────────────┘ │ 2. Insert Rule Record into ss_billing ▼ ┌──────────────┐ 4. Atomic Rule Translation ┌────────────────────────┐ │ Linux Kernel ◄────────────────────────────────────────────────┤ nftables Synchronizer │ │ netfilter │ └────────────────────────┘ └──────────────┘ ▲ │ 3. User Clicks 'Apply Rules' ``` 1. **Rule Configuration:** The administrator defines the policy parameters in the modal dialog. 2. **Database Persistence:** The Fastify API performs boundary validation and records the rule in `public.firewall_rules`. 3. **Compilation Trigger:** The administrator clicks **Apply Rules** in the top-right toolbar. 4. **Kernel Synthesis:** The synchronizer queries all enabled rules ordered by priority, resolves associated service port definitions, generates an atomic `nftables` transaction, and loads it directly into the kernel without interrupting active sessions. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Restricting SSH Access to Management VPN Only 1. Navigate to **ADMIN > Firewall > Rules**. 2. Click **+ Add** in the top-right toolbar. 3. Enter **Rule Name:** `Restrict SSH to OpenVPN Subnet`. 4. Set **Action:** `Accept`. 5. Set **Direction:** `Input`. 6. Select **Service:** `SSH Management` (Port 22). 7. Set **Priority:** `15`. 8. In **Source Address**, enter the VPN pool CIDR: `10.8.0.0/24`. 9. In **Interface**, enter: `tun0`. 10. Toggle **Enabled** to `Yes` and click **Create**. 11. Click **Apply Rules** to commit changes to the kernel. ### Playbook 2: Allowing Public Customer Access to Billing Web Portal 1. Navigate to **ADMIN > Firewall > Rules**. 2. Click **+ Add**. 3. Enter **Rule Name:** `Allow Public HTTPS Web Portal`. 4. Set **Action:** `Accept`. 5. Set **Direction:** `Input`. 6. Select **Service:** `HTTPS Portal Web` (Port 8443). 7. Set **Priority:** `20`. 8. Leave **Source Address** blank (`0.0.0.0/0`) to allow all public traffic. 9. Toggle **Enabled** to `Yes` and click **Create**. 10. Click **Apply Rules**. --- ## 7. Troubleshooting & Diagnostic Commands ### Querying Rules in Database ```bash # Display all rules sorted by priority sudo -u postgres psql -d ss_billing -c \ "SELECT r.priority, r.name, r.action, r.direction, s.name AS service, s.port, r.source_address, r.enabled \ FROM firewall_rules r \ JOIN firewall_services s ON r.service_id = s.id \ ORDER BY r.priority ASC;" ``` ### Inspecting Running Kernel Rules ```bash # View active nftables ruleset in human-readable format nft -a list ruleset | grep -A 5 "chain input" # View rule packet and byte counters nft list table inet filter ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Firewall Rules** module connects directly to the **Ring2All BSS MCP Server**, empowering security copilots and network automation tools to audit ordered rule sets and packet actions safely. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_firewall_rules` | `Super Administrator` | Lists granular packet filtering firewall rules with evaluation priority, action (ACCEPT/DROP), and service associations. | `{}` | ### Sample MCP Tool Execution: `list_firewall_rules` #### Request Payload ```json { "name": "list_firewall_rules", "arguments": {} } ``` #### Response Payload ```json [ { "id": 1, "name": "Allow HTTPS Public Web", "action": "accept", "direction": "in", "priority": 10, "serviceName": "Billing HTTP/HTTPS", "sourceAddress": "any", "enabled": true }, { "id": 2, "name": "Drop Unauthenticated Management", "action": "drop", "direction": "in", "priority": 90, "serviceName": "SSH Management", "sourceAddress": "!192.168.10.0/24", "enabled": true } ] ``` ### Conversational AI Prompts for Copilot * *"List all active firewall rules sorted by evaluation priority."* * *"Show all DROP rules configured in the input chain."* * *"Verify if public access to port 443 is permitted."* --- ## 9. Glossary * **Evaluation Priority:** The chronological order in which the firewall tests incoming packets against rule definitions; first-match semantics terminate evaluation. * **Shadowing:** A configuration error where an overly broad high-priority rule prevents a more specific lower-priority rule from ever being evaluated. * **Interface Binding:** Limiting a firewall policy strictly to traffic flowing through a specific network interface (e.g., `tun0` for OpenVPN). * **ICMP Unreachable:** A reject response informing the client that the destination port or host is administratively filtered. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/firewall/services TITLE: Firewall Services Module Documentation URL: https://docs.ring2all.com/billing/admin/firewall/services.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Firewall Services** module (`public.firewall_services`) defines standard named network services, protocols, and port definitions utilized across **Ring2All Billing**. In high-availability telecommunications and billing environments, exposing explicit TCP/UDP ports for web interfaces, REST APIs, database clustering, and caching must be governed through reusable service abstractions rather than hardcoded firewall port numbers. Services created in this module can be directly referenced by higher-level firewall rules and access control policies. Each service maintains a protocol definition (`TCP`, `UDP`, or `TCP/UDP`), single or ranged port allocations (e.g., `80`, `8443`, `8000-8010`), and an operational toggle that can disable access across all dependent firewall chains simultaneously. ### Data Model & System Linkage ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Firewall Service Entity (public.firewall_services) │ │ • id: bigint (Canonical Primary Key) │ │ • name: VARCHAR(100) (e.g., 'HTTPS Portal Web', 'Fastify Billing API')│ │ • protocol: 'TCP' | 'UDP' | 'BOTH' │ │ • port: VARCHAR(50) (Single '8443' or Port Range '8000-8010') │ │ • description: text (Functional Scope & Service Purpose) │ │ • is_system: boolean (Protects Core OS Services from Deletion) │ │ • enabled: boolean (State Toggle) │ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┴─────────────────────────┐ ▼ ▼ ┌───────────────────────────────────┐ ┌───────────────────────────────────┐ │ Firewall Rules Linkage │ │ Linux Kernel Netfilter │ │ • Referenced by custom rules │ │ • Translates into nftables sets │ │ • Reusable across multiple subnets│ │ • Opens/closes ports in INPUT │ └───────────────────────────────────┘ └───────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.firewall_services`**: * `id`: Numeric primary key (`bigserial`). * `name`: Unique human-readable service identifier. * `protocol`: Transport layer protocol (`'TCP'`, `'UDP'`, `'BOTH'`). * `port`: Comma-separated list or port range string (e.g., `'80'`, `'8443'`, `'3003'`, `'5060-5080'`). * `description`: Explanatory context for operations and NOC teams. * `is_system`: Boolean flag protecting critical services (SSH, HTTP redirect, Web Portal) from accidental deletion. * `enabled`: Master switch controlling whether the port set is included in the active packet filter. --- ## 2. Module Overview (Commercial & Business Value) * **Simplified Security Governance:** Reusable service definitions eliminate human error caused by mistyping port numbers when provisioning firewall policies across multiple environments. * **Rapid Emergency Isolation:** If a specific microservice (e.g., a legacy API listener or unencrypted testing port) exhibits a vulnerability, disabling the service definition immediately closes the port across all firewall rules. * **Audit Transparency:** Provides compliance auditors and telecommunications regulators with a clear, readable inventory of every listening port and its documented business justification. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`CRUD` on Services) | Configures core platform services, binds custom microservice ports, and toggles system service availability. | | **Security Officer / SecOps** | Audit & Port Compliance | Audits listening service inventories, ensures non-TLS cleartext services remain disabled, and verifies port ranges. | | **DevOps / SysAdmin** | Read & Create (Application Ports) | Registers new application endpoints, webhook ingress ports, and metrics exporters (e.g., Prometheus node exporter on port 9100). | --- ## 4. Visual Interface & Form Structure ### Level 1 — Firewall Services List View The services inventory displays all configured network definitions, transport protocols, port assignments, descriptions, active status indicators, and action triggers. ![Firewall Services List View](/screenshots/billing/admin/firewall/services/services-list.png) ### Level 2 — Add Firewall Service Modal The modal dialog provides a clean, validated form to create named network service definitions. ![Add Firewall Service Modal](/screenshots/billing/admin/firewall/services/services-modal.png) #### Fields & Parameters Reference * **Service Name:** Alphanumeric identifier (e.g., `HTTPS Portal Web`, `Fastify Billing API`, `Prometheus Exporter`). * **Protocol:** Transport layer selection (`TCP`, `UDP`, or `Both`). * **Port:** Target port number (e.g., `8443`) or port span (e.g., `8000-8010`). * **Description:** Detailed explanation of the service purpose and underlying software daemon. * **Enabled:** Operational toggle. When set to `Yes`, the service is eligible for inclusion in active firewall chains. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────┐ 1. POST /api/firewall/services ┌────────────────────────┐ │ System Admin ├───────────────────────────────────────────────►│ Fastify 5 API Route │ └──────────────┘ └───────────┬────────────┘ │ 2. Validate │ 3. Store in Port/Proto│ ss_billing ▼ ┌──────────────┐ 4. nftables / iptables Reload ┌────────────────────────┐ │ Linux Kernel ◄────────────────────────────────────────────────┤ Firewall Service Sync │ │ Filter │ └────────────────────────┘ └──────────────┘ ``` 1. **Service Registration:** The administrator inputs service parameters into the modal and clicks **Create**. 2. **Validation:** The Fastify backend validates port ranges (1-65535) and prevents port collisions with reserved operating system processes. 3. **Storage:** The record is inserted into `public.firewall_services`. 4. **Kernel Application:** If the firewall is active, the service definition updates the kernel packet filtering sets to immediately open or close the specified port. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Registering a Metrics Monitoring Service (Prometheus) 1. Navigate to **ADMIN > Firewall > Services**. 2. Click **+ Add** in the top-right toolbar. 3. Enter **Service Name:** `Prometheus Node Exporter`. 4. Select **Protocol:** `TCP`. 5. Enter **Port:** `9100`. 6. Enter **Description:** `Telemetry metrics endpoint for internal Prometheus scrapers`. 7. Set **Enabled** to `Yes`. 8. Click **Create**. 9. The service is now ready to be restricted to the monitoring subnet under **Access Control** or **Rules**. ### Playbook 2: Deactivating an Unused Service Port 1. Navigate to **ADMIN > Firewall > Services**. 2. Locate the row for the service you wish to decommission (e.g., `HTTP Web Redirect` on port 80). 3. Click the **Edit** icon. 4. Toggle **Enabled** to `No`. 5. Click **Save**. 6. The firewall immediately ceases accepting traffic on port 80, enforcing exclusive HTTPS on port 8443. --- ## 7. Troubleshooting & Diagnostic Commands ### Inspecting Configured Services in PostgreSQL ```bash sudo -u postgres psql -d ss_billing -c \ "SELECT id, name, protocol, port, description, enabled FROM firewall_services ORDER BY id ASC;" ``` ### Checking Listening Ports with Linux Utilities ```bash # Verify which applications are actively listening on the configured ports ss -tulnp | grep -E ':(80|8443|3003|22|5432|6379)' # Test socket reachability locally nc -zv 127.0.0.1 3003 ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Firewall Services** module connects directly to the **Ring2All BSS MCP Server**, enabling infrastructure management copilots to inspect named service abstractions and verify port bindings safely. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_firewall_services` | `Super Administrator` | Lists defined firewall network services with port definitions, transport protocols, and enabled status. | `{}` | ### Sample MCP Tool Execution: `list_firewall_services` #### Request Payload ```json { "name": "list_firewall_services", "arguments": {} } ``` #### Response Payload ```json [ { "id": 1, "name": "Billing HTTP/HTTPS", "protocol": "tcp", "port": "80,443", "description": "Public web portal and REST API", "enabled": true, "isSystem": true }, { "id": 2, "name": "SSH Management", "protocol": "tcp", "port": "22", "description": "Encrypted system shell management", "enabled": true, "isSystem": true } ] ``` ### Conversational AI Prompts for Copilot * *"List all defined network services and their port assignments."* * *"Is SSH management enabled as a recognized firewall service?"* * *"Show which ports are opened for the Billing API."* --- ## 9. Glossary * **Transport Protocol:** The layer 4 communications protocol (typically TCP for reliable streams or UDP for low-latency datagrams) used by network packets. * **Port Range:** A continuous block of sequential port numbers (e.g., `10000-20000` for RTP media relay) managed as a single logical entity. * **System Service:** A protected service entry marked `is_system = true` that cannot be deleted to prevent accidental administrative isolation. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/maintenance/backup-restore TITLE: Backup & Restore Module Documentation URL: https://docs.ring2all.com/billing/admin/maintenance/backup-restore.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Backup & Restore** module (`public.backup_jobs`, `public.backup_history`) provides enterprise-grade disaster recovery, state preservation, and automated archive management for **Ring2All Billing**. In telecommunications billing systems, historical rated Call Detail Records (CDRs), tax invoices, customer balance ledgers, TLS/SSL certificates, and carrier rating decks represent legally audited, mission-critical assets. This subsystem provides configurable snapshot definitions, scheduled cron-based executions, modular data scope selection, multi-destination storage targets (Local encrypted filesystem and Amazon S3), and controlled point-in-time restoration. ### Data Model & Architecture Diagram ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Backup Jobs (public.backup_jobs) │ │ • id: bigint (Primary Key) │ │ • name: VARCHAR(255) (e.g., 'Daily Full System Backup') │ │ • schedule_type: 'daily' | 'weekly' | 'monthly' | 'custom_cron' │ │ • schedule_time: '02:00:00' │ │ • retention_count: integer (e.g., 5 or 30 generations) │ │ • storage_destination: 'local' | 's3' │ │ • s3_bucket / s3_region / s3_path / s3_access_key / s3_secret_key │ │ • scope_database / scope_invoices / scope_cdrs / scope_rates │ │ • scope_certificates / scope_openvpn: boolean │ │ • is_active: boolean │ └───────────────────────────────────┬────────────────────────────────────┘ │ Triggered By Cron Daemon / User ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ Backup History (public.backup_history) │ │ • id: bigint (Primary Key) │ │ • job_id: bigint (FK to public.backup_jobs, NULL for manual) │ │ • file_name: VARCHAR(255) (e.g., 'backup-full-2026-09-06.tar.gz') │ │ • file_size: bigint (Bytes) │ │ • storage_destination: 'local' | 's3' │ │ • scope: jsonb (Array of included system components) │ │ • status: 'success' | 'running' | 'failed' │ │ • error_message: text │ │ • created_at: timestamptz │ └────────────────────────────────────────────────────────────────────────┘ ``` ### Modular Data Scope Architecture Administrators can selectively package specific subsystems based on recovery time objectives (RTO) and storage constraints: * **Database (`ss_billing`):** Complete relational schema dump (`pg_dump -Fc`) encompassing customer accounts, wallets, subscriptions, rate tables, users, and audit profiles. * **PDF Invoices & Receipts:** Generated customer billing invoices and receipts stored in local file storage. * **Rated CDRs History:** Historical call detail records and rating transactions. * **Rate Cards & Plans:** Telephony destination rate decks, prefix trees, and catalog plans. * **Certificates & Keys:** NGINX SSL/TLS certificates, intermediate chains, and ACME keys. * **OpenVPN Server:** Server configurations, CA roots, server private keys, and client connection profiles. --- ## 2. Module Overview (Commercial & Business Value) * **Business Continuity & Zero Data Loss:** Protects telecom operations against catastrophic hardware failures, ransomware incidents, accidental administrative deletion, or datacenter outages. * **Regulatory Compliance & Tax Auditing:** Telecommunications carriers are legally bound by national regulatory agencies (e.g., FCC, OFCOM, CRC) to preserve billing CDRs and fiscal invoice records for a statutory period (typically 3 to 7 years). * **Automated Retention Management:** Automatic purging of snapshots exceeding the configured generation threshold (e.g., keep last 5 daily backups) prevents local disk exhaustion. * **Offsite Air-Gapped Archival:** Native integration with Amazon S3 ensures critical billing archives are replicated off-premises to an isolated cloud environment. --- ## 3. 🎯 User Roles & Key Capabilities | Role | Key Capabilities & Permissions in Backup & Restore | | :--- | :--- | | **System Administrator** | Complete control over backup job definitions, S3 storage credentials, retention rules, point-in-time restorations, and emergency manual backups. | | **NOC Engineer** | Monitors scheduled backup job execution, reviews status badges (`Success`, `Failed`), and downloads recent archive bundles for staging testing. | | **Database Administrator (DBA)** | Validates SQL dump integrity, configures database scopes, and oversees restore verification drills. | | **Compliance Officer** | Audits historical backup records, verifies offsite S3 replication compliance, and ensures data retention schedules meet legal requirements. | --- ## 4. Visual Interface & Form Structure The **Backup & Restore** interface provides a comprehensive suite of tools organized across textual tabs: **Backup Jobs**, **Backup History**, **Restore System**, and **System Maintenance**. ### 4.1 Backup Jobs Listing ![Backup Jobs List](/screenshots/billing/admin/maintenance/backup-restore/backup-jobs-list.png) The **Backup Jobs** view lists all configured recurring automated backup tasks: * **Header Controls:** * `Refresh`: Re-queries active backup job schedules and current status. * `Quick Backup`: Immediately triggers a manual on-demand database snapshot without altering scheduled jobs. * `+ Add`: Opens the full Level 2 creation view. * **Data Grid Columns:** * `Job Name`: Name and description of the backup job (e.g., "Daily Full System Backup", "Weekly Offsite S3 Archive"). * `Schedule`: Frequency and execution time (e.g., `Daily @ 02:00`, `Weekly @ 02:00`). * `Storage`: Destination target badge (`Local`, `S3`). * `Scope`: Color-coded pills indicating included components (`DB`, `Invoices`, `CDRs`, `Certs`, `VPN`). * `Last Run`: Timestamp of the most recent execution. * `Status`: Health status badge (`Success`, `Failed`). * `Actions`: Direct inline actions to trigger immediate execution (`Play`), edit configuration (`Pencil`), duplicate job (`Copy`), or delete (`Trash`). ### 4.2 Create / Edit Backup Job Form ![Create Backup Job Form](/screenshots/billing/admin/maintenance/backup-restore/backup-job-form.png) The Level 2 form adheres to the canonical form layout with back navigation (`< List`) and a sticky bottom action bar (`FixedActionBar`): * **Job Information:** * `Job Name *`: Unique identifier (e.g., `Daily Full Billing Backup`). * `Description`: Operational notes. * `Status`: Active checkbox. * **Billing Data Scope & Content (Modular Checkboxes):** * `Database (ss_billing)`: Core PostgreSQL database. * `PDF Invoices & Receipts`: Generated customer invoice PDFs. * `Rated CDRs History`: Call records and rating mediation tables. * `Rate Cards & Plans`: Wholesale rate sheets and customer catalog plans. * `Certificates & Keys`: Web and signaling SSL certificates. * `OpenVPN Server`: VPN configurations and client keys. * **Execution Schedule & Retention:** * `Frequency`: `Daily`, `Weekly`, `Monthly`, or `Custom Cron`. * `Execution Time`: Time of execution (e.g., `02:00 AM`). * `Retention Count`: Maximum archived snapshots retained before auto-purge (e.g., `5`). * **Storage Destination:** * `Storage Destination`: Selection between `Local Server Storage` and `Amazon S3 Storage`. When S3 is selected, fields for bucket name, region, path prefix, Access Key ID, and Secret Access Key appear. ### 4.3 Backup History Listing ![Backup History List](/screenshots/billing/admin/maintenance/backup-restore/backup-history-list.png) The **Backup History** tab provides an immutable audit log of every archive generated: * **Filename:** Exact archive artifact (e.g., `backup-full-2026-09-06.tar.gz`, `backup-db-snapshot-2026-09-07.sql.gz`). * **Job / Task:** Originating job name or manual trigger label. * **Size:** Compressed archive size on disk (e.g., `93.89 MB`, `409.04 MB`, `1.72 GB`). * **Storage:** Storage medium badge (`Local`, `S3`). * **Date:** Timestamp of creation. * **Status:** Execution state badge (`Success`). * **Actions:** Immediate download icon (`Download`) and archive deletion icon (`Trash`). --- ## 5. Architectural Flow & Security Governance ``` ┌───────────────────┐ │ Cron Trigger / │ │ User On-Demand │ └─────────┬─────────┘ │ ▼ ┌────────────────────────────────────────────────────────┐ │ Maintenance Backup Worker │ │ 1. Evaluates scope flags (DB, Invoices, CDRs, etc.) │ │ 2. Executes pg_dump with custom compression (-Fc) │ │ 3. Packages designated filesystem assets into tarball │ │ 4. Calculates SHA256 checksum and file size │ └─────────────────────────┬──────────────────────────────┘ │ ┌─────────────┴─────────────┐ ▼ ▼ [ Destination: Local ] [ Destination: S3 ] │ │ ▼ ▼ Write /var/backups/ Stream to AWS S3 Bucket Enforce Retention Count Write public.backup_history ``` 1. **Isolation & Non-Blocking Dumps:** Database dumps use PostgreSQL's snapshot isolation (`--serializable-deferrable`), ensuring active billing operations and rating queries are never locked during archive creation. 2. **Permission Guardrails:** System files and database dumps are generated with strict `0600` Linux permissions, restricted to the `root` or `postgres` system accounts. 3. **Retention Pruning:** After each successful execution, the worker inspects the count of historical files belonging to the job. Older archives exceeding the retention ceiling are pruned automatically. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook A: Performing a Pre-Upgrade Manual Snapshot 1. Navigate to **Maintenance > Backup & Restore**. 2. In the top toolbar, click **Quick Backup**. 3. The platform initiates an immediate database snapshot. 4. Switch to the **Backup History** tab and confirm that `backup-db-snapshot-[DATE].sql.gz` shows `Success`. ### Playbook B: Configuring Nightly Offsite Disaster Recovery to Amazon S3 1. In **Backup Jobs**, click **+ Add**. 2. Name the job `Weekly Offsite S3 Archive`. 3. Check all scope boxes (`Database`, `Invoices`, `CDRs`, `Rate Cards`, `Certificates`, `OpenVPN`). 4. Set **Frequency** to `Weekly` at `02:00 AM`. 5. Set **Retention Count** to `12` (retaining 3 months of weekly snapshots). 6. Under **Storage Destination**, select `Amazon S3 Storage`. 7. Enter S3 Bucket Name, Region, and IAM credentials with `s3:PutObject` permission. 8. Click **Save**. --- ## 7. Troubleshooting & Diagnostic Commands ### Checking Local Backup Storage Directory ```bash ls -lh /var/backups/billing/ df -h /var/backups/ ``` ### Inspecting Backup Jobs & History via SQL ```sql SELECT id, name, schedule_type, schedule_time, storage_destination, retention_count, is_active FROM public.backup_jobs; SELECT id, file_name, file_size, storage_destination, status, created_at FROM public.backup_history ORDER BY created_at DESC LIMIT 5; ``` ### Manually Testing Database Dump Creation via Terminal ```bash pg_dump -U postgres -d ss_billing -Fc -f /tmp/test_dump.sql.gz ls -lh /tmp/test_dump.sql.gz rm -f /tmp/test_dump.sql.gz ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Backup & Restore** module connects directly to the **Ring2All BSS MCP Server**, enabling automated system administrators and AI maintenance agents to monitor disk usage, query snapshot archives, and initiate on-demand backups before executing configuration updates. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `get_system_maintenance_status` | `Super Administrator` | Retrieves system maintenance status, database disk usage, active background jobs, and uptime. | `{}` | | `list_backup_history` | `Super Administrator` | Lists historical backup archive snapshots, file sizes, and storage locations. | `{"limit": 10}` | | `create_system_backup` | `Super Administrator` | Triggers an immediate system snapshot and backup archive creation. | `{"backupType": "full", "notes": "Pre-upgrade checkpoint"}` | ### Sample MCP Tool Execution: `get_system_maintenance_status` #### Request Payload ```json { "name": "get_system_maintenance_status", "arguments": {} } ``` #### Response Payload ```json { "uptimeSeconds": 1284500, "databaseDiskUsage": "4.2 GB", "totalBackupsCount": 8, "lastBackupAt": "2026-09-08T02:00:00Z", "lastBackupStatus": "completed", "activeJobsCount": 0 } ``` ### Conversational AI Prompts for Copilot * *"Check overall system maintenance health and database disk consumption."* * *"Show the last 5 backup archives created and their storage destinations."* * *"Create an immediate full backup snapshot before applying rate card changes."* --- ## 9. Glossary * **RTO (Recovery Time Objective):** The maximum acceptable duration of platform downtime between a service disruption and full recovery. * **RPO (Recovery Point Objective):** The maximum tolerable age of files or data transactions that may be lost in the event of disaster. * **Point-in-Time Restore (PITR):** The capability to recover a relational database to an exact historical timestamp. * **Retention Count:** The maximum number of historical backup generations preserved before older snapshots are automatically purged. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/maintenance/cron-profiles TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/maintenance/cron-profiles.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/maintenance/custom-tasks TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/maintenance/custom-tasks.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/maintenance/system-cleanup TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/maintenance/system-cleanup.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/network/certificates TITLE: Certificates Module Documentation URL: https://docs.ring2all.com/billing/admin/network/certificates.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Certificates** module (`public.certificates`) manages public key infrastructure (PKI), TLS/SSL certificates, private key storage, and ACME automated renewals for **Ring2All Billing**. In modern telecommunications and billing architectures, robust cryptographic authentication is mandatory across customer self-care portals, carrier REST APIs, payment gateway webhooks, and secure SIP/WebRTC signaling. This module supports three primary certificate acquisition models: 1. **Self-Signed Certificates:** Generated dynamically on-server using OpenSSL with customizable RSA key sizes (2048/4096-bit) and validity periods for lab and private interconnect testing. 2. **Let's Encrypt / ACME:** Fully automated domain verification, certificate issuance, and recurring 60-day renewal via HTTP-01 challenges. 3. **Custom Commercial Certificates:** Secure upload of third-party X.509 PEM certificates, intermediate CA bundles, and encrypted private keys issued by established Certificate Authorities (e.g., DigiCert, Sectigo). ### Data Model & System Linkage ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Certificate Entity (public.certificates) │ │ • id: bigint (Primary Key) │ │ • name: VARCHAR(100) (e.g., 'Billing Production TLS (*.ring2all.com)')│ │ • cert_type: 'SELF_SIGNED' | 'LETS_ENCRYPT' | 'CUSTOM' │ │ • common_name: VARCHAR(255) (e.g., 'bss.ring2all.com') │ │ • sans: text[] (Subject Alternative Names Array) │ │ • certificate_pem: text (Public X.509 Base64 Certificate) │ │ • private_key_pem: text (AES-256 Encrypted Private Key) │ │ • chain_pem: text (Intermediate CA Trust Bundle) │ │ • issuer: VARCHAR(255) (e.g., 'Lets Encrypt Authority R3') │ │ • valid_from: timestamptz │ │ • valid_until: timestamptz │ │ • auto_renew: boolean │ │ • status: 'active' | 'expired' | 'revoked' │ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┼─────────────────────────┐ ▼ ▼ ▼ ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │ NGINX SSL Binding │ │ OpenVPN Server CA │ │ Fastify HTTPS API │ │ • Web Admin UI │ │ • Root CA & Server│ │ • Client Webhooks │ │ • Customer Portal │ │ X.509 Cert │ │ • REST Endpoints │ └───────────────────┘ └───────────────────┘ └───────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.certificates`**: * `id`: Numeric primary key (`bigserial`). * `name`: Descriptive label indicating the domain scope and purpose. * `cert_type`: Origin category (`'SELF_SIGNED'`, `'LETS_ENCRYPT'`, `'CUSTOM'`). * `common_name`: Primary Fully Qualified Domain Name (FQDN) or IP. * `sans`: PostgreSQL array of alternative domain names (`VARCHAR[]`). * `certificate_pem`: Standard ASCII PEM-encoded public certificate block (`-----BEGIN CERTIFICATE-----`). * `private_key_pem`: Encrypted PEM private key block, secured using system master keys. * `issuer`: Organization or authority that signed the certificate. * `valid_until`: Expiration timestamp used for automated renewal triggering and proactive UI alerts. * `status`: Operational state (`'active'`, `'expired'`, `'revoked'`). --- ## 2. Module Overview (Commercial & Business Value) * **Elimination of Browser Security Warnings:** Providing valid CA-signed TLS certificates ensures enterprise customers and prospective clients experience frictionless, trusted access without alarming browser warnings. * **PCI-DSS & SOC 2 Compliance:** Enforces modern cryptographic ciphers (TLS 1.2 / TLS 1.3 with AES-256-GCM), protecting customer credit card numbers, billing addresses, and authentication tokens in transit. * **Automated Expiration Risk Mitigation:** Proactive visual countdown badges (e.g., "81 days left") and automated ACME renewal daemons prevent catastrophic service interruptions caused by forgotten SSL expirations. --- ## 3. 🎯 User Roles & Key Capabilities | User Role | Key Permissions | Core Responsibilities & Workflows | | :--- | :--- | :--- | | **Super Administrator** | Full Control (`CRUD` on Certificates & Keys) | Issues new certificates, uploads commercial CA bundles, configures ACME automated renewals, and deletes deprecated certificates. | | **Security Officer / SecOps** | Cryptographic Audit | Audits key lengths (ensuring minimum 2048-bit RSA or P-256 ECC), inspects certificate chains for weak hashing (SHA-1 deprecation), and tracks expiration dates. | | **DevOps / SysAdmin** | Read & Binding | Binds active certificates to NGINX virtual hosts in **Server Settings** and configures OpenVPN server TLS parameters. | --- ## 4. Visual Interface & Form Structure ### Level 1 — Certificates List View The catalog lists all installed SSL/TLS credentials, displaying certificate names, types (Let's Encrypt, Self-Signed, Custom), status badges, issuers, and precise expiration dates with remaining day counters. ![Certificates List View](/screenshots/billing/admin/network/certificates/certificates-list.png) ### Level 2 — Certificate Provisioning Form The creation view features a clean 4-column layout (`[Label 1] [Control 1] [Label 2] [Control 2]`) organized into **General Certificate Information** and **Self-Signed Parameters** (or manual upload blocks). ![Certificate Provisioning Form](/screenshots/billing/admin/network/certificates/certificates-form.png) #### Fields & Parameters Reference * **General Certificate Information:** * *Certificate Name:* Meaningful label (e.g., `Billing Production TLS (*.ring2all.com)`). * *Certificate Type:* Dropdown selecting `Self-Signed`, `Let's Encrypt`, or `Custom (Upload)`. * *Common Name (FQDN / IP):* Target domain (e.g., `bss.ring2all.com`). * *Subject Alternative Names (SANs):* Comma-delimited additional hostnames (e.g., `ring2all.com, *.ring2all.com`). * **Self-Signed Parameters:** * *Key Size (RSA):* Cryptographic key length (`2048 bits` or `4096 bits`). * *Validity Period:* Certificate lifespan (`1 year`, `2 years`, `5 years`). * **Custom Certificate Parameters (when Custom is selected):** * *Certificate PEM:* Public certificate block. * *Private Key PEM:* Matching private key block. * *CA Chain PEM:* Optional intermediate and root CA bundle. --- ## 5. Architectural Flow & Security Governance ``` ┌──────────────┐ 1. POST /api/v1/settings/certificates ┌────────────────────────┐ │ Administrator├───────────────────────────────────────────────►│ Fastify 5 API Route │ └──────────────┘ └───────────┬────────────┘ │ 2. Generate OpenSSL Key Pair │ 3. Store Encrypted in or Request ACME Challenge │ ss_billing ▼ ┌──────────────┐ 5. NGINX SSL Reload (Zero Downtime) ┌────────────────────────┐ │ NGINX Daemon ◄────────────────────────────────────────────────┤ Certificate Synchronizer│ └──────────────┘ └────────────────────────┘ │ 4. Write to File System: /etc/ssl/ring2all/ ``` 1. **Initiation:** The administrator selects the certificate type, enters domain parameters, and clicks **Save**. 2. **Generation / Verification:** * *Self-Signed:* OpenSSL generates the private key and self-signs the certificate directly. * *Let's Encrypt:* The ACME agent provisions an HTTP-01 challenge under `/.well-known/acme-challenge/`, verifies domain ownership with Let's Encrypt, and receives signed certificates. * *Custom:* The server validates that the public certificate matches the provided private key modulus. 3. **Database Storage:** Certificate assets are written to `public.certificates`. 4. **File System Deployment:** PEM files are written with strict `0600` permissions to `/etc/ssl/ring2all/certs/`. 5. **Web Server Reload:** NGINX executes a seamless configuration reload. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook 1: Generating a Self-Signed Certificate for Lab Testing 1. Navigate to **ADMIN > Network > Certificates**. 2. Click **+ Add** in the top-right toolbar. 3. Enter **Certificate Name:** `Billing Lab Test TLS`. 4. Select **Certificate Type:** `Self-Signed`. 5. In **Common Name (FQDN / IP)**, enter the server's local IP or internal hostname: `192.168.10.29`. 6. Select **Key Size (RSA):** `2048 bits` and **Validity Period:** `1 year`. 7. Click **Save** in the bottom-right action bar. 8. Navigate to **ADMIN > Network > Server Settings** and bind the newly generated certificate to the web portal. ### Playbook 2: Installing a Commercial Wildcard SSL Certificate 1. Procure a wildcard certificate (`*.yourdomain.com`) from a trusted Certificate Authority. 2. Navigate to **ADMIN > Network > Certificates** and click **+ Add**. 3. Enter **Certificate Name:** `Commercial Wildcard TLS 2026`. 4. Set **Certificate Type:** `Custom (Upload)`. 5. In **Common Name**, enter `*.yourdomain.com`. 6. Paste the contents of your certificate into **Certificate PEM**, the private key into **Private Key PEM**, and the intermediate bundle into **CA Chain PEM**. 7. Click **Save**. 8. Verify in the list view that the status displays `Active` and the issuer matches your CA. --- ## 7. Troubleshooting & Diagnostic Commands ### Validating Certificate Modulus Match ```bash # Verify that a public certificate and private key match identically openssl x509 -noout -modulus -in /etc/ssl/ring2all/certs/bundle.crt | openssl md5 openssl rsa -noout -modulus -in /etc/ssl/ring2all/certs/private.key | openssl md5 # Both MD5 checksums must be identical ``` ### Inspecting Certificate Details from Database ```bash sudo -u postgres psql -d ss_billing -c \ "SELECT id, name, cert_type, common_name, issuer, valid_until, status \ FROM certificates ORDER BY id DESC;" ``` ### Verifying TLS Handshake from Remote Terminal ```bash # Test remote SSL connection and inspect served certificate chain openssl s_client -connect 192.168.10.29:8443 -servername bss.example.com ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Certificates** module connects directly to the **Ring2All BSS MCP Server**, providing SSL administrators and security automation agents with tools to audit TLS certificate expiration windows and common names programmatically. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_ssl_certificates` | `Super Administrator` | Lists SSL/TLS certificates, domain names, issuers, expiration dates, and active flags. | `{}` | ### Sample MCP Tool Execution: `list_ssl_certificates` #### Request Payload ```json { "name": "list_ssl_certificates", "arguments": {} } ``` #### Response Payload ```json [ { "id": 1, "name": "Production Wildcard SSL", "commonName": "*.ring2all.com", "certType": "custom", "issuer": "Let's Encrypt Authority X3", "validUntil": "2026-11-30T00:00:00Z", "status": "valid", "isActive": true } ] ``` ### Conversational AI Prompts for Copilot * *"Check if any SSL/TLS certificates will expire in the next 30 days."* * *"List all active certificates and their associated domain names."* * *"Verify the issuer and expiration date of our wildcard certificate."* --- ## 9. Glossary * **ACME (Automated Certificate Management Environment):** A communications protocol for automating interactions between certificate authorities and web servers. * **SAN (Subject Alternative Name):** An extension to X.509 that allows multiple domain names to be protected by a single SSL certificate. * **Modulus:** The mathematical product of two prime numbers used in RSA key generation; the certificate and private key must share the exact same modulus. * **Intermediate CA:** A certificate issued by a root authority used to sign end-user certificates, establishing an unbroken chain of trust. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/admin/network/http-server TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/network/http-server.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/network/network-configuration TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/network/network-configuration.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/network/openvpn-client TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/network/openvpn-client.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/network/openvpn-server TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/network/openvpn-server.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/network/wireguard-client TITLE: Ring2All Billing (BSS/OSS & Customer Portal) Documentation URL: https://docs.ring2all.com/billing/admin/network/wireguard-client.md ================================================================================ > **Official Slogan (Admin):** *"Converged Telecom Rating, Invoicing & Node Orchestration"* > **Official Slogan (Portal):** *"Customer Self-Care & Account Management"* > **Brand Identity:** Amber / Gold (`#F59E0B`) *(Shared Billing Logo)* • Icon: `credit-card` • Component Code: `bss` Welcome to the complete documentation suite for **Ring2All Billing**, encompassing both the operator-grade **Billing Admin Console** and the customer-facing **Client Self-Care Portal**. --- ## 🏛️ Two Applications, One Unified Platform Ring2All Billing is architected as two specialized frontends backed by a shared carrier billing API and PostgreSQL database: ``` ┌──────────────────────────────────────┐ │ Ring2All Billing API │ │ (Fastify 5 + Kysely + PostgreSQL) │ └──────────────────┬───────────────────┘ │ ┌───────────────────────────────┴───────────────────────────────┐ │ │ ▼ ▼ ┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐ │ Ring2All Billing Admin │ │ Ring2All Client Portal │ │ • Target: Telecom Operators & NOC │ │ • Target: End Customers & Tenants │ │ • Slogan: "Converged Rating &..." │ │ • Slogan: "Customer Self-Care &..."│ │ • Scope: Customers, Rates, Plans, │ │ • Scope: Prepaid Wallet, Invoices, │ │ Invoicing, Fraud, Node Config │ │ DIDs, Plan Store, CDR History │ └──────────────────────────────────────┘ └──────────────────────────────────────┘ ``` --- ## 📚 Documentation Directory ### 1. [Billing Admin Console](admin/README.md) * [**Customers & Accounts**](admin/customers.md): Multi-tenant account profiles, canonical IDs, and status lifecycle. * [**Plan Catalog**](admin/catalog-plans.md): Mini-PBX, SIP Trunks, and Bundles product definition. * [**Subscriptions Management**](admin/subscriptions.md): Active contracts, automatic prorated billing, and lifecycle. * [**Rate Cards & LCR Costs**](admin/rates-lcr.md): Wholesale cost decks, retail sell tiers, and prefix matching. * [**Invoicing & Payments**](admin/invoicing-payments.md): Billing cycles, PDF invoices, Stripe auto-pay, and dunning. * [**Real-Time OCS & Live Traffic**](admin/realtime-ocs.md): Online Charging System, live session monitor, and call termination. * [**Fraud Detection & Prevention**](admin/fraud-control.md): Velocity rules, spend thresholds, and automated lockouts. * [**Telecom Infrastructure Nodes**](admin/telecom-nodes.md): Dynamic interconnects to Ring2All PBX and SBC nodes. ### 2. [Customer Self-Care Portal](client/README.md) * [**Dashboard & Wallet**](client/dashboard-wallet.md): Real-time balance, credit limits, minute bundles, and top-up. * [**Plan Store & Checkout**](client/plan-store.md): Self-service store for Mini-PBX and SIP Trunks with instant setup. * [**Telephony & DIDs**](client/telephony-dids.md): Assigned phone numbers, forwarding destinations, and IP endpoints. * [**Invoices & Payment Methods**](client/invoices-payments.md): Invoice history, Stripe credit cards, and PDF receipts. * [**CDRs & Usage Analytics**](client/cdrs-usage.md): Searchable call history, duration, destination, and costs. ================================================================================ DOCUMENT: billing/admin/security/fraud-sentinel TITLE: Fraud Sentinel Module Documentation URL: https://docs.ring2all.com/billing/admin/security/fraud-sentinel.md ================================================================================ ## Table of Contents 1. [Module Overview (Technical)](#1-module-overview-technical) 2. [Module Overview (Commercial & Business Value)](#2-module-overview-commercial--business-value) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Form Structure](#4-visual-interface--form-structure) 5. [Architectural Flow & Security Governance](#5-architectural-flow--security-governance) 6. [Common Scenarios & Operational Playbooks](#6-common-scenarios--operational-playbooks) 7. [Troubleshooting & Diagnostic Commands](#7-troubleshooting--diagnostic-commands) 8. [Model Context Protocol (MCP) AI Integration](#8-model-context-protocol-mcp-ai-integration) 9. [Glossary](#9-glossary) --- ## 1. Module Overview (Technical) The **Fraud Sentinel** module (`public.fraud_rules`, `public.fraud_logs`) delivers automated, real-time fraud mitigation and anomaly detection for **Ring2All Billing**. In high-throughput telecommunications networks, financial loss occurs within minutes during International Revenue Share Fraud (IRSF), PBX credential brute-forcing, or runaway automated dialing attacks. Fraud Sentinel interfaces directly with the Online Charging System (OCS) and CDR mediation pipeline to evaluate active traffic against granular velocity limits and security guardrails. When an anomaly threshold is breached, Sentinel executes immediate policy-driven mitigation—such as shedding rogue call legs with SIP response codes (`486 Busy Here`), freezing international destination routing for compromised accounts, or fully suspending customer SIP trunks—while recording comprehensive incident traces for audit and review. ### Data Model & Architecture Diagram ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Fraud Guardrails (public.fraud_rules) │ │ • id: bigint (Primary Key) │ │ • tenant_id: bigint / domain_id: bigint │ │ • name: VARCHAR(255) (e.g., 'Hourly Spend Velocity Guard') │ │ • rule_type: 'spend_velocity' | 'max_concurrent_calls' | 'daily_spend'│ │ • threshold_value: numeric(12,2) (e.g., 50.00) │ │ • action: 'terminate_calls' | 'freeze_route' | 'suspend_account' │ │ • is_active: boolean │ └───────────────────────────────────┬────────────────────────────────────┘ │ Evaluates Real-Time Traffic ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ Incident Stream (public.fraud_logs) │ │ • id: bigint (Primary Key) │ │ • customer_id: bigint (FK to public.customers) │ │ • rule_name: VARCHAR(255) │ │ • severity: 'low' | 'medium' | 'high' | 'critical' │ │ • anomaly_score: integer (0 - 100) │ │ • details: jsonb (Trigger reasons, spend velocity, destination hops) │ │ • action_taken: VARCHAR(100) (Automated mitigation applied) │ │ • resolved: boolean (Operator review status) │ │ • created_at: timestamptz │ └────────────────────────────────────────────────────────────────────────┘ ``` ### PostgreSQL Schema Architecture * **`public.fraud_rules`**: * `id`: Numeric primary key (`bigserial`). * `name`: Descriptive identifier for the protection rule. * `rule_type`: Metric being monitored (`spend_velocity`, `max_concurrent_calls`, `daily_spend`). * `threshold_value`: Quantitative ceiling triggering mitigation (e.g., `$50.00/hr` or `10 Max Channels`). * `action`: Enforcement directive executed upon breach (`terminate_calls`, `freeze_international_routing`, `suspend_customer_account`). * `is_active`: Operational toggle enabling or pausing the rule. * **`public.fraud_logs`**: * `id`: Numeric primary key (`bigserial`). * `customer_id`: References the evaluated customer entity. * `rule_name`: The specific guardrail triggered. * `severity`: Threat severity categorization (`low`, `medium`, `high`, `critical`). * `anomaly_score`: Normalized risk index between 1 and 100 calculated by the Sentinel engine. * `details`: JSONB payload containing contextual parameters (e.g., hourly spend rate, country codes, call bursts). * `action_taken`: Explicit defense action executed by the platform. * `resolved`: Boolean indicating whether a security engineer has acknowledged and reviewed the event. --- ## 2. Module Overview (Commercial & Business Value) * **Elimination of IRSF Liability:** International Revenue Share Fraud (IRSF) attacks often exploit compromised SIP credentials overnight, generating thousands of dollars in toll charges to premium-rate destinations in under an hour. Sentinel's velocity limits halt unauthorized spend instantly. * **Preservation of Upstream Carrier Credit:** Wholesale carriers enforce strict daily credit lines and fraud indemnification clauses. Unchecked fraudulent bursts can lead to sudden trunk suspension across an entire enterprise. * **Automated 24/7 Threat Neutralization:** By operating autonomously at the database and rating engine layer, Fraud Sentinel provides unyielding perimeter defense without requiring manual NOC intervention outside business hours. * **Customer Trust & Dispute Reduction:** Transparent incident logs with precise anomaly scoring allow billing teams to demonstrate exactly when an account was compromised and confirm that containment was immediate, eliminating contentious billing disputes. --- ## 3. 🎯 User Roles & Key Capabilities | Role | Key Capabilities & Permissions in Fraud Sentinel | | :--- | :--- | | **Security Administrator** | Full authority to configure anti-fraud guardrails, set financial thresholds, define automated containment actions (`freeze_route`, `suspend_account`), and modify risk formulas. | | **NOC Engineer** | Monitors real-time incident streams, analyzes anomaly scores, reviews SIP trigger reasons, and clears reviewed incidents. | | **Billing Operator** | Inspects customer spend spikes, checks affected rated CDRs, and verifies whether accounts were temporarily restricted due to policy enforcement. | | **Compliance Officer** | Audits historical fraud logs, reviews mitigation timelines, and exports forensic evidence for carrier dispute resolution and regulatory filings. | --- ## 4. Visual Interface & Form Structure The **Fraud Sentinel** interface consists of an unified navigation layout with two specialized operating surfaces: **Incident Stream** (real-time stream and metric telemetry) and **Anti-Fraud Guardrails** (policy management and rule creation). ### 4.1 Incident Stream View ![Fraud Sentinel Incident Stream](/screenshots/billing/admin/security/fraud-sentinel/fraud-sentinel-incidents.png) The **Incident Stream** displays high-level operational telemetry alongside a forensic data grid: * **Metric Cards:** * **Sentinel Engine:** Real-time operational state (Live Monitoring active). * **Total Incident Events:** Aggregated count of flagged traffic anomalies. * **High-Risk Threats:** Active incidents with anomaly scores equal to or exceeding 70/100. * **Reviewed & Resolved:** Ratio of incidents investigated and resolved by operations staff. * **Forensic Table Fields:** * `Customer Account`: Identifies the affected organization, tenant, or SIP trunk. * `Anomaly Risk Score`: Color-coded badge displaying calculated risk (Green: Low, Amber: Medium, Red: Critical). * `Incident / Trigger Reason`: Granular rationale (e.g., "Velocity spend spike ($85 in 15min to Sierra Leone)"). * `Mitigation Action Taken`: Automated action enforced (e.g., "Auto-Frozen International Route"). * `Time`: Timestamp of the detection event. * `Resolve Action`: Quick-action button allowing operators to review and mark incidents as resolved. ### 4.2 Anti-Fraud Guardrails Management ![Fraud Sentinel Guardrails](/screenshots/billing/admin/security/fraud-sentinel/fraud-sentinel-guardrails.png) The **Anti-Fraud Guardrails** tab provides policy lifecycle administration: * **Guardrail Listing:** Presents all active policies, monitored metrics (e.g., Max Concurrent Channels, Hourly Spend Velocity, Max Daily Spend), threshold limits, automated mitigation actions, and activation switches. * **Quick Actions:** Edit existing thresholds or delete outdated guardrails with standard confirmation prompts. ### 4.3 Add Guardrail Modal ![Fraud Sentinel Guardrail Modal](/screenshots/billing/admin/security/fraud-sentinel/fraud-sentinel-rule-modal.png) Clicking the **+ Add** button opens the **Add Guardrail** modal: * **Rule Name:** Descriptive title (e.g., `Hourly Spend Velocity Guard`). * **Rule Type:** Selects the monitored metric: * `Spend Velocity ($/hr)` * `Max Concurrent Calls` * `Max Daily Spend ($/day)` * **Threshold Limit Value:** Numeric trigger limit (e.g., `50.00`). * **Mitigation Action:** Action executed automatically upon breach: * `Terminate Calls (486 Busy)` * `Freeze International Routing` * `Suspend Customer Account` * **Enabled Switch:** Active/inactive status toggle. --- ## 5. Architectural Flow & Security Governance ``` ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Incoming Call / │ │ OCS Rating │ │ Sentinel Rule │ │ CDR Mediation │──────▶│ Engine Core │──────▶│ Evaluation │ └─────────────────┘ └─────────────────┘ └────────┬────────┘ │ ┌────────────────────────┴────────────────────────┐ │ Threshold Exceeded? │ ▼ ▼ [ NO - Normal ] [ YES - Anomaly ] │ │ ▼ ▼ Proceed to Carrier Trunk 1. Execute Mitigation Action 2. Write public.fraud_logs 3. Notify Security Team ``` 1. **Ingress Call Valuation:** As active SIP channels establish or rated CDRs generate, the OCS continuously computes cumulative spend velocity and active channel volume. 2. **Deterministic Guardrail Checking:** The Sentinel worker checks current metrics against active rules in `public.fraud_rules`. 3. **Automated Containment:** If a threshold is exceeded, the database issues signaling commands to Telephony Server or the SBC perimeter to drop calls or block subsequent INVITE messages. 4. **Audit Record Persistence:** Details of the breach, including time, affected numbers, and containment codes, are written to `public.fraud_logs`. --- ## 6. Common Scenarios & Operational Playbooks ### Playbook A: Mitigating an Overnight International Toll Fraud Burst 1. **Detection:** Sentinel flags a customer account with an anomaly score of `98/100` due to a sudden `$85` spend in 15 minutes directed towards high-cost African destinations. 2. **Autonomous Action:** Sentinel invokes `Freeze International Routing`. Domestic and inbound calls continue uninterrupted, while high-risk outbound international calls are blocked. 3. **NOC Verification:** In the **Incident Stream**, the NOC engineer inspects the trigger reason and verifies with the customer whether this was legitimate traffic. 4. **Resolution:** If the customer confirms unauthorized usage, the customer credentials are reset, and the NOC engineer marks the incident as **Reviewed & Cleared**. ### Playbook B: Adding a Global Channel Ceiling for New Accounts 1. Navigate to **Security > Fraud Sentinel > Anti-Fraud Guardrails**. 2. Click **+ Add**. 3. Set **Rule Name** to `Max Concurrent Channels Baseline`. 4. Set **Rule Type** to `Max Concurrent Calls`. 5. Enter **Threshold Limit Value** as `10.00`. 6. Select **Mitigation Action** as `Terminate Calls (486 Busy)`. 7. Click **Save**. Any call attempts beyond 10 concurrent channels are immediately released with `486 Busy`. --- ## 7. Troubleshooting & Diagnostic Commands ### Inspecting Recent Fraud Incidents via SQL ```sql SELECT l.id, c.name AS customer_name, l.rule_name, l.severity, l.anomaly_score, l.action_taken, l.resolved, l.created_at FROM public.fraud_logs l LEFT JOIN public.customers c ON c.id = l.customer_id ORDER BY l.created_at DESC LIMIT 10; ``` ### Checking Active Fraud Guardrails ```sql SELECT id, name, rule_type, threshold_value, action, is_active FROM public.fraud_rules ORDER BY id ASC; ``` ### Manually Resolving an Incident via Terminal ```bash curl -k -X POST https://192.168.10.29/api/fraud/logs/3/resolve \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" ``` --- ## 8. Model Context Protocol (MCP) AI Integration The **Fraud Sentinel** module connects directly to the **Ring2All BSS MCP Server**, providing anti-fraud analysts and automated AI copilots with tools to query active alerts, evaluate risk velocity, and mark resolved incidents. ### Available MCP Tools | Tool Name | Access Role | Description & Primary Function | Example Arguments | | :--- | :--- | :--- | :--- | | `list_fraud_alerts` | `Super Administrator` / `NOC` | Lists real-time fraud alerts and velocity violations detected by the Fraud Sentinel engine. | `{"resolved": false, "limit": 10}` | | `resolve_fraud_alert` | `Super Administrator` | Marks an active fraud incident alert as resolved with remediation notes. | `{"alertId": 3, "resolutionNotes": "Verified customer campaign; raised limit."}` | ### Sample MCP Tool Execution: `list_fraud_alerts` #### Request Payload ```json { "name": "list_fraud_alerts", "arguments": { "resolved": false, "limit": 5 } } ``` #### Response Payload ```json [ { "id": 3, "ruleName": "Rapid International Velocity Guard", "ruleType": "hourly_cost_limit", "severity": "CRITICAL", "anomalyScore": 92, "actionTaken": "SUSPEND_ACCOUNT", "resolved": false, "customer": { "id": 1, "name": "Rodrigo Cuadra", "company": "Cuadra Telecom Corp" }, "createdAt": "2026-09-09T04:22:15Z" } ] ``` ### Conversational AI Prompts for Copilot * *"List all unresolved critical fraud alerts detected by Fraud Sentinel."* * *"Show detailed telemetry for fraud alert ID 3."* * *"Resolve fraud alert 3 with notes 'False positive confirmed by customer'."* --- ## 9. Glossary * **IRSF (International Revenue Share Fraud):** An organized telecommunications fraud scheme where attackers artificially inflate traffic volumes to premium-rate international telephone numbers. * **Spend Velocity:** The rate of monetary consumption over a designated period (e.g., dollars consumed per 60-minute rolling window). * **Mitigation Action:** The automated defensive command executed upon policy violation, including call termination, route freezing, or complete trunk suspension. * **Anomaly Score:** An algorithmic confidence index (1–100) indicating the statistical deviation of an observed calling pattern from normal operational baselines. * **Model Context Protocol (MCP):** Open protocol standard that enables secure, controlled integration between Large Language Models and external tools, databases, and telecom rating engines. ================================================================================ DOCUMENT: billing/client/about TITLE: About System & Platform Architecture Module Documentation URL: https://docs.ring2all.com/billing/client/about.md ================================================================================ > **Module Code:** `billing/client/about` > **Trigger:** User Menu -> About > **Dialog Component:** `AboutModal.tsx` > **Brand Purity:** 100% White-Label Compliant (Ring2All Billing) --- ## Table of Contents 1. [Executive Summary & Platform Identity](#1-executive-summary--platform-identity) 2. [Technical Architecture & Component Breakdown](#2-technical-architecture--component-breakdown) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Screen Breakdown](#4-visual-interface--screen-breakdown) 5. [Core Engine Components & Specifications](#5-core-engine-components--specifications) 6. [Security Governance & Tokenization Standards](#6-security-governance--tokenization-standards) 7. [System Diagnostics & Verification](#7-system-diagnostics--verification) 8. [Domain Glossary](#8-domain-glossary) --- ## 1. Executive Summary & Platform Identity The **About System** module provides operators, system integrators, and enterprise subscribers with an instant overview of the underlying BSS architecture powering the Ring2All Billing Customer Portal. ``` +-------------------------------------------------------------------------------+ | COMMERCIAL & OPERATIONAL IMPACT | +-------------------------------------------------------------------------------+ | • Transparent Technical Pedigree: Clearly displays platform software versions| | and production engine specifications to technical auditors. | | • Enterprise Assurance: Highlights carrier-grade PostgreSQL 17 clustering, | | Fastify 5 asynchronous performance, and sub-millisecond OCS latency. | | • PCI-DSS Certified Standards: Documents Stripe vaulted tokenization. | | • Unified Brand Identity: Clean, white-label presentation under the | | Ring2All Billing ecosystem. | +-------------------------------------------------------------------------------+ ``` --- ## 2. Technical Architecture & Component Breakdown The Customer Portal operates as a lightweight, secure satellite application interfacing with the carrier softswitch core: ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Ring2All Billing Customer Portal (Client Edition v1.0.0) │ │ React 18 / Vite / Tailwind CSS / Zustand Store │ └───────────────────────────────────┬────────────────────────────────────┘ │ ┌─────────────────────────┼─────────────────────────┐ │ │ │ ▼ ▼ ▼ ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │ Backend Engine │ │ High-Perf Storage │ │ Real-Time OCS │ │ Fastify 5 │ │ PostgreSQL 17 │ │ Sub-millisecond │ │ Node.js 22 LTS │ │ Kysely Query Bldr │ │ Pre-Auth Engine │ └───────────────────┘ └───────────────────┘ └───────────────────┘ ``` --- ## 3. 🎯 User Roles & Key Capabilities Access to system specification diagnostics is available to all authenticated portal users: | User Role | Access Level | Primary Operational Capabilities | | :--- | :--- | :--- | | **All Portal Subscribers** | Specification Inspection | Verifies active software version, technical capabilities, and compliance standards. | | **Technical Support Engineers** | Diagnostic Baseline | Confirms software release baseline during troubleshooting sessions. | | **Enterprise Security Auditors** | Compliance Review | Verifies that storage, rating, and PCI tokenization adhere to corporate standards. | --- ## 4. Visual Interface & Screen Breakdown ### 4.1 About System & Specifications Modal The modal opens smoothly from the user avatar dropdown menu: ![About System Architecture & Engine Modal](/screenshots/billing/client/about/about-modal.png) * **Header Branding:** Displays the unified Ring2All Billing icon, application title (`Ring2All Billing Customer Portal`), and subtitle (`Carrier Telecom BSS & Self-Care Subsystem`). * **Software Version:** Outlines active production release `v1.0.0 (Client Edition)`. * **Architecture Grid:** Quad-card breakdown covering Backend Engine, Storage, Real-Time OCS, and PCI-DSS Security. * **Overview Summary:** Executive description of automated minute refills, CDR queries, and trunk management. --- ## 5. Core Engine Components & Specifications ### 1. Backend Engine * **Technology:** Fastify 5 running on Node.js 22 LTS. * **Capabilities:** Highly concurrent non-blocking I/O capable of handling over 25,000 JSON requests per second per node. ### 2. High-Performance Storage * **Technology:** PostgreSQL 17 with Kysely Type-Safe Query Builder. * **Capabilities:** Partitioned CDR tables, multi-tenant row-level indexing, and sub-second analytical reporting. ### 3. Real-Time OCS (Online Charging System) * **Technology:** In-memory Kamailio `htable` + Redis balance cache. * **Capabilities:** Sub-millisecond pre-call authorization and mid-call credit floor enforcement. ### 4. PCI-DSS Security * **Technology:** Stripe Tokenization & Vaulted Payment Methods. * **Capabilities:** SAQ-A compliance ensuring zero cardholder data touches application disks or network buffers. --- ## 6. Security Governance & Tokenization Standards * **Zero Plaintext Storage:** Passwords hashed with Argon2id cryptographic salt. * **Secure JWT Lifecycles:** Asymmetrically signed JSON Web Tokens with short expiry windows and automatic sliding refresh. * **Perimeter Hardening:** Protection against automated brute force and Layer 7 flooding via Fail2Ban and AI Perimeter Guard. --- ## 7. System Diagnostics & Verification ### Verify Running Backend Process ```bash # Execute on Billing Server systemctl status ring2all-billing-api.service curl -s http://127.0.0.1:3000/health ``` --- ## 8. Domain Glossary * **BSS (Business Support Systems):** Telecom software managing billing, customer subscriptions, and rating. * **Fastify:** High-performance web framework for Node.js focused on minimal overhead. * **Argon2id:** Winner of the Password Hashing Competition (PHC) providing maximum resistance against GPU/ASIC cracking. ================================================================================ DOCUMENT: billing/client/account-profile TITLE: Account Profile & Company Entity Module Documentation URL: https://docs.ring2all.com/billing/client/account-profile.md ================================================================================ > **Module Code:** `billing/client/account-profile` > **Route:** `/portal/settings` > **Backend Service:** `clientService.ts` (`ring2all-billing-api`) > **Database Table:** `customers` > **Brand Purity:** 100% White-Label Compliant (Ring2All Billing) --- ## Table of Contents 1. [Executive Summary & Corporate Identity](#1-executive-summary--corporate-identity) 2. [Technical Architecture & Profile Sync](#2-technical-architecture--profile-sync) 3. [🎯 User Roles & Key Capabilities](#3--user-roles--key-capabilities) 4. [Visual Interface & Screen Breakdown](#4-visual-interface--screen-breakdown) 5. [Company Details, Tax ID & Invoicing Address](#5-company-details-tax-id--invoicing-address) 6. [FormGrid Standardization & Action Bar Controls](#6-formgrid-standardization--action-bar-controls) 7. [Database Schema & Data Dictionary](#7-database-schema--data-dictionary) 8. [Diagnostic CLI & Operational Playbooks](#8-diagnostic-cli--operational-playbooks) 9. [Domain Glossary](#9-domain-glossary) --- ## 1. Executive Summary & Corporate Identity The **Account Profile & Company Entity** module allows subscribers to manage their official corporate identity, authorized point-of-contact details, national tax registration numbers, and legal billing address used across all generated statements and PDF tax invoices. ``` +-------------------------------------------------------------------------------+ | COMMERCIAL & OPERATIONAL IMPACT | +-------------------------------------------------------------------------------+ | • Automated Tax Accuracy: Changes to company address and tax identification | | are dynamically reflected on subsequent PDF invoices and tax receipts. | | • Emergency Notice Dispatch: Direct maintenance, dunning warnings, and low- | | balance alerts to the verified primary administrative email and phone. | | • Self-Service Governance: Eliminates support tickets for routine corporate | | contact and office relocation updates. | | • Strict Form Standards: Complies with Ring2All Level 2 Form UI guidelines | | with FormGrid alignment and lower FixedActionBar controls. | +-------------------------------------------------------------------------------+ ``` --- ## 2. Technical Architecture & Profile Sync When an administrator saves modifications in `SettingsPage.tsx`, the API validates the payload, updates PostgreSQL, and refreshes the client's session context: ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Client Web Browser (Portal UI) │ │ Route: /portal/settings │ └───────────────────────────────────┬────────────────────────────────────┘ │ PUT /api/client/profile ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ Ring2All Billing API Engine (Fastify 5 / Zod Schema) │ │ • Validates International Phone E.164 & Postal Code Formats │ │ • Sanitizes Tax ID & Legal Company Name │ └───────────────────────────────────┬────────────────────────────────────┘ │ ▼ SQL UPDATE ┌────────────────────────────────────────────────────────────────────────┐ │ PostgreSQL 17 (public.customers) │ │ UPDATE customers SET company_name = ..., │ │ tax_id = ..., billing_address = ..., city = ... │ │ WHERE id = $authCustomerId │ └───────────────────────────────────┬────────────────────────────────────┘ │ 200 OK + Refreshed Profile ▼ ┌────────────────────────────────────────────────────────────────────────┐ │ Client Session Context Hydration │ │ Updates React Context & Header Profile Display │ └────────────────────────────────────────────────────────────────────────┘ ``` --- ## 3. 🎯 User Roles & Key Capabilities Management of corporate identity is restricted to primary tenant officers: | User Role | Access Level | Primary Operational Capabilities | | :--- | :--- | :--- | | **Corporate Tenant Executive** | Full Access | Updates corporate entity name, registers official tax ID, updates headquarters billing address. | | **Accounts Payable Supervisor** | Contact Information | Verifies phone numbers, billing address lines, and accounts payable email recipients. | | **Compliance Officer** | Audit Verification | Ensures legal tax identification matches national registries before high-volume trunk activation. | --- ## 4. Visual Interface & Screen Breakdown ### 4.1 Account & Company Profile Settings The profile form utilizes standardized FormBoxes and responsive FormGrids: ![Account & Company Profile Settings](/screenshots/billing/client/account-profile/account-profile-form.png) * **ModuleFormHeader:** Fixed 56px header displaying the building icon, module title (`Account Profile`), and navigation back button. * **Company Information Card:** Fields for Primary Contact Name, Registered Company Name, Contact Phone, and National Tax ID. * **Billing Address Card:** Fields for Street Address, City, State/Province, Postal Code, and Country dropdown selector. * **FixedActionBar:** Bottom-anchored action bar featuring `Cancel` (resets form to original state without navigating) and `Save Changes` (submits payload). --- ## 5. Company Details, Tax ID & Invoicing Address The profile configuration controls corporate tax calculations: 1. **Tax Exemption Status:** If a valid European VAT ID or US Resale Certificate number is filed and verified, the billing engine automatically applies zero-rated tax rules on invoice generation. 2. **E911 Consistency:** By default, new DID acquisitions can inherit the registered company billing address for emergency dispatch routing. --- ## 6. FormGrid Standardization & Action Bar Controls In accordance with Ring2All UI Rule 8: * **Standard Grid Structure:** All form elements utilize `grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-x-6 gap-y-3 items-start`. * **Label Baseline:** Every `