diff --git a/.env.example b/.env.example index e361a97..0dd7642 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,5 @@ # ============================================================================== -# Aura Courier MCP (v2.7.3) — Environment Variable Template (NO REAL SECRETS!) +# Aura Courier MCP (v2.7.4) — Environment Variable Template (NO REAL SECRETS!) # ============================================================================== # PRODUCTION RULE: # - NEVER commit a real `.env` file or bake `.env` into Docker images. diff --git a/MASTER_OPERATIONS_MANUAL.md b/MASTER_OPERATIONS_MANUAL.md index 37c2e3b..5390462 100644 --- a/MASTER_OPERATIONS_MANUAL.md +++ b/MASTER_OPERATIONS_MANUAL.md @@ -1,4 +1,4 @@ -# 🚚 AURA COURIER MCP v2.7.3 — THE ENTERPRISE LOGISTICS MASTER MANUAL +# 🚚 AURA COURIER MCP v2.7.4 — THE ENTERPRISE LOGISTICS MASTER MANUAL ### Universal Multi-Carrier Logistics Engine, Spatial Intelligence Hub & Zero-Risk COD Gateway **Published by Aura Agentic AI · Architected with DeepMind Principles & Google Maps Platform** @@ -11,7 +11,7 @@ ### Core Architectural Pillars ```mermaid graph TD - AI[AI Agent / Vertex AI / Dashboard] -->|Streamable-HTTP / MCP| MCP[Aura Courier MCP Server v2.7.3] + AI[AI Agent / Vertex AI / Dashboard] -->|Streamable-HTTP / MCP| MCP[Aura Courier MCP Server v2.7.4] subgraph "Intelligent Logic Engines" MCP --> ROUTER[Multi-Carrier Smart Router] diff --git a/README.md b/README.md index 2d755d5..23866a8 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# 🚚 AURA COURIER MCP v2.7.3 — THE ENTERPRISE LOGISTICS MASTER MANUAL +# 🚚 AURA COURIER MCP v2.7.4 — THE ENTERPRISE LOGISTICS MASTER MANUAL ### Universal Multi-Carrier Logistics Engine, Spatial Intelligence Hub & Zero-Risk COD Gateway **Published by Aura Agentic AI · Architected with DeepMind Principles & Google Maps Platform** [![Google Cloud Partner Advantage](https://img.shields.io/badge/Google_Cloud_Partner-Aura_Ajentic_AI-4285F4?logo=google-cloud&logoColor=white)](https://cloud.google.com/find-a-partner/partner/aura-ajentic-ai) [![auraajenticai/aura-courier-mcp MCP server](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp/badges/score.svg)](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp) -[![Antigravity Plugin](https://img.shields.io/badge/Antigravity_Plugin-v2.7.3-0676FF?logo=google&logoColor=white)](plugin.json) +[![Antigravity Plugin](https://img.shields.io/badge/Antigravity_Plugin-v2.7.4-0676FF?logo=google&logoColor=white)](plugin.json) [![User Guide BN/EN](https://img.shields.io/badge/User_Guide-বাংলা_%26_English-f59e0b)](https://courier.auraajenticai.cloud/guide) [![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Status](https://img.shields.io/badge/Status-Production%20Active-success.svg)](https://courier.auraajenticai.cloud) @@ -24,7 +24,7 @@ ### Core Architectural Pillars ```mermaid graph TD - AI[AI Agent / Vertex AI / Dashboard] -->|Streamable-HTTP / MCP| MCP[Aura Courier MCP Server v2.7.3] + AI[AI Agent / Vertex AI / Dashboard] -->|Streamable-HTTP / MCP| MCP[Aura Courier MCP Server v2.7.4] subgraph "Intelligent Logic Engines" MCP --> ROUTER[Multi-Carrier Smart Router] @@ -236,7 +236,7 @@ curl -s https://courier.auraajenticai.cloud/health | jq ```json { "ok": true, - "version": "2.7.3" + "version": "2.7.4" } ``` @@ -287,7 +287,7 @@ Add this configuration block to your client settings (`claude_desktop_config.jso "mcpServers": { "aura-courier": { "command": "npx", - "args": ["-y", "aura-courier-mcp@2.7.3"], + "args": ["-y", "aura-courier-mcp@2.7.4"], "env": { "PORT": "8080", "GOOGLE_MAPS_API_KEY": "", @@ -349,8 +349,8 @@ Bundles the complete `courier-ops` skill (13 tools), `rules/COURIER_RULES.md` (s ## 9. Version History & Glama TDQS 5.0 Audit Log -* **v2.7.3 (Nov 27, 2026)**: - - **Zero-Defect Security, SQL Schema & Registry Parity Release**: Fixed `courier_parcels` SQL column alignment & strict `AND tenant = $...` isolation across `update_parcel`, `cancel_parcel`, and 90-day PII retention; hardened `rate_limit.ts` against `X-Forwarded-For`/`CF-Connecting-IP` spoofing and added OAuth endpoint rate limits; replaced legacy browser demo keys with safe server-side `/api/public/fraud-demo`; enforced `GET /mcp` SSE session auth & query-token URL redaction; upgraded `Dockerfile` to multi-stage non-root (`USER node`); published `2.7.3` to `npmjs.org`. +* **v2.7.4 (Nov 27, 2026)**: + - **Zero-Defect Security, SQL Schema & Registry Parity Release**: Fixed `courier_parcels` SQL column alignment & strict `AND tenant = $...` isolation across `update_parcel`, `cancel_parcel`, and 90-day PII retention; hardened `rate_limit.ts` against `X-Forwarded-For`/`CF-Connecting-IP` spoofing and added OAuth endpoint rate limits; replaced legacy browser demo keys with safe server-side `/api/public/fraud-demo`; enforced `GET /mcp` SSE session auth & query-token URL redaction; upgraded `Dockerfile` to multi-stage non-root (`USER node`); published `2.7.4` to `npmjs.org`. * **v2.7.2 (Nov 27, 2026)**: - **Enterprise Security Hardening**: Fail-closed startup secret validation, timing-safe webhook verification + `409` replay defense, auth-first BYOK + official HTTPS carrier host allowlist (`maxRedirects: 0`), public tracking PII/COD redaction, concurrent + PostgreSQL durable `invoice` idempotency, and ambiguous-outcome cascade halt (`0` npm vulnerabilities). * **v2.7.1 (Nov 24, 2026)**: diff --git a/configs/README.md b/configs/README.md index 8cd0f40..2726ba8 100644 --- a/configs/README.md +++ b/configs/README.md @@ -8,7 +8,7 @@ Connect any AI Agent / IDE to Aura Courier MCP in seconds. - **Server-Sent Events / SSE (Claude Desktop, Remote SSE)**: `https://courier.auraajenticai.cloud/sse` - **NPX Direct CLI**: - `npx -y aura-courier-mcp@2.7.3` + `npx -y aura-courier-mcp@2.7.4` --- diff --git a/configs/antigravity_gemini.json b/configs/antigravity_gemini.json index 38e75e4..a341c79 100644 --- a/configs/antigravity_gemini.json +++ b/configs/antigravity_gemini.json @@ -9,7 +9,7 @@ }, "aura-courier-local": { "command": "npx", - "args": ["-y", "aura-courier-mcp@2.7.3"], + "args": ["-y", "aura-courier-mcp@2.7.4"], "env": { "PORT": "8080" } diff --git a/configs/claude_desktop_config.json b/configs/claude_desktop_config.json index 8f97c5f..fed837a 100644 --- a/configs/claude_desktop_config.json +++ b/configs/claude_desktop_config.json @@ -6,7 +6,7 @@ }, "aura-courier-stdio": { "command": "npx", - "args": ["-y", "aura-courier-mcp@2.7.3"] + "args": ["-y", "aura-courier-mcp@2.7.4"] } } } diff --git a/dist/adapters/fraud_engine.d.ts b/dist/adapters/fraud_engine.d.ts index bf5b66f..fc69418 100644 --- a/dist/adapters/fraud_engine.d.ts +++ b/dist/adapters/fraud_engine.d.ts @@ -1,11 +1,17 @@ import { FraudRiskScoreResponse } from "../types.js"; import { SteadfastAdapter } from "./steadfast.js"; import { PathaoAdapter } from "./pathao.js"; +import { CourierConfig } from "../config.js"; export declare class FraudRiskEngine { + private static checkSteadfastWeb; + private static checkRedxNationwide; + private static checkPaperflySmartCheck; + private static checkCarrybee; + private static checkEcourier; /** - * Real-Time Multi-Carrier Fraud & Delivery Risk Evaluation (T6) - * Queries Pathao Nationwide Customer Delivery Database (/aladdin/api/v1/user/success), - * Steadfast Nationwide Logistics Database (/fraud_check/{phone}), and BD Operator Prefix Validator. + * Real-Time All-Bangladesh Multi-Carrier Fraud & Delivery Risk Evaluation (v2.7.4) + * Executes parallel live lookups across Steadfast, Pathao, RedX, Paperfly, CarryBee, eCourier & ParcelDex. + * Strictly Zero Mock Data: non-connected or inactive carrier accounts return `null` counts with transparent status. */ - static evaluateRisk(phoneNumber: string, steadfastAdapter?: SteadfastAdapter, pathaoAdapter?: PathaoAdapter): Promise; + static evaluateRisk(phoneNumber: string, steadfastAdapter?: SteadfastAdapter, pathaoAdapter?: PathaoAdapter, config?: CourierConfig): Promise; } diff --git a/dist/adapters/fraud_engine.js b/dist/adapters/fraud_engine.js index 8d48b86..71267e1 100644 --- a/dist/adapters/fraud_engine.js +++ b/dist/adapters/fraud_engine.js @@ -1,13 +1,217 @@ +import axios from "axios"; +// Session / token caches (45m TTL) to avoid upstream auth rate limits +const steadfastWebCookieCache = new Map(); +const redxWebTokenCache = new Map(); +const paperflyWebTokenCache = new Map(); +const carrybeeSessionCache = new Map(); +function pct(delivered, total) { + if (total <= 0) + return null; + return Math.round((delivered / total) * 1000) / 10; +} export class FraudRiskEngine { + static async checkSteadfastWeb(cleanPhone, email, password) { + const cacheKey = email.trim().toLowerCase(); + const now = Date.now(); + let cookieHeader = steadfastWebCookieCache.get(cacheKey)?.expiresAt && steadfastWebCookieCache.get(cacheKey).expiresAt > now + ? steadfastWebCookieCache.get(cacheKey).cookieHeader + : ""; + if (!cookieHeader) { + const loginGet = await axios.get("https://steadfast.com.bd/login", { + timeout: 6000, + maxRedirects: 0, + validateStatus: () => true, + headers: { "User-Agent": "Mozilla/5.0" }, + }); + const html = String(loginGet.data || ""); + const m = html.match(/name="_token"\s+value="([^"]+)"/); + if (!m) + return null; + const initCookies = (loginGet.headers["set-cookie"] || []).map((c) => c.split(";")[0]).join("; "); + const body = new URLSearchParams({ _token: m[1], email: email.trim(), password }).toString(); + const loginPost = await axios.post("https://steadfast.com.bd/login", body, { + timeout: 6000, + maxRedirects: 0, + validateStatus: () => true, + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Cookie: initCookies, + "User-Agent": "Mozilla/5.0", + }, + }); + if (loginPost.status !== 302 && loginPost.status !== 200) + return null; + const postCookies = (loginPost.headers["set-cookie"] || []).map((c) => c.split(";")[0]); + if (!postCookies.length) + return null; + cookieHeader = postCookies.join("; "); + steadfastWebCookieCache.set(cacheKey, { cookieHeader, expiresAt: now + 45 * 60 * 1000 }); + } + const checkRes = await axios.get(`https://steadfast.com.bd/user/frauds/check/${encodeURIComponent(cleanPhone)}`, { + timeout: 6000, + maxRedirects: 0, + validateStatus: () => true, + headers: { + Cookie: cookieHeader, + Accept: "application/json", + "User-Agent": "Mozilla/5.0", + }, + }); + if (checkRes.status !== 200 || typeof checkRes.data !== "object" || checkRes.data === null) { + steadfastWebCookieCache.delete(cacheKey); + return null; + } + const delivered = Number(checkRes.data.total_delivered ?? 0); + const cancelled = Number(checkRes.data.total_cancelled ?? 0); + const total = Number(checkRes.data.total_parcels ?? delivered + cancelled); + return { total, delivered, cancelled }; + } + static async checkRedxNationwide(cleanPhone, loginPhone, password) { + const normLogin = loginPhone.replace(/\D/g, "").replace(/^88/, ""); + if (!/^01[3-9]\d{8}$/.test(normLogin) || !password) + return null; + const cacheKey = normLogin; + const now = Date.now(); + let accessToken = redxWebTokenCache.get(cacheKey)?.expiresAt && redxWebTokenCache.get(cacheKey).expiresAt > now + ? redxWebTokenCache.get(cacheKey).token + : ""; + if (!accessToken) { + const loginRes = await axios.post("https://api.redx.com.bd/v4/auth/login", { phone: `88${normLogin}`, password }, { + timeout: 6000, + maxRedirects: 0, + validateStatus: () => true, + headers: { "User-Agent": "Mozilla/5.0", Accept: "application/json" }, + }); + accessToken = String(loginRes.data?.data?.accessToken || "").trim(); + if (loginRes.status !== 200 || !accessToken) + return null; + redxWebTokenCache.set(cacheKey, { token: accessToken, expiresAt: now + 45 * 60 * 1000 }); + } + // CRITICAL ZERO-MOCK INVARIANT: Only accept HTTP 200 (HTTP 400 returns RedX's static demo object) + const statsRes = await axios.get(`https://redx.com.bd/api/redx_se/admin/parcel/customer-success-return-rate?phoneNumber=88${encodeURIComponent(cleanPhone)}`, { + timeout: 6000, + maxRedirects: 0, + validateStatus: () => true, + headers: { + Authorization: `Bearer ${accessToken}`, + Accept: "application/json", + "User-Agent": "Mozilla/5.0", + }, + }); + if (statsRes.status === 401) { + redxWebTokenCache.delete(cacheKey); + return null; + } + if (statsRes.status !== 200 || !statsRes.data?.data) + return null; + const total = Number(statsRes.data.data.totalParcels ?? 0); + const delivered = Number(statsRes.data.data.deliveredParcels ?? 0); + const cancelled = Math.max(0, total - delivered); + return { total, delivered, cancelled }; + } + static async checkPaperflySmartCheck(cleanPhone, username, password) { + const now = Date.now(); + const cacheKey = username.trim(); + let token = paperflyWebTokenCache.get(cacheKey)?.expiresAt && paperflyWebTokenCache.get(cacheKey).expiresAt > now + ? paperflyWebTokenCache.get(cacheKey).token + : ""; + if (!token) { + const loginRes = await axios.post("https://go-app.paperfly.com.bd/merchant/api/react/authentication/login_using_password.php", { username: username.trim(), password }, { timeout: 6000, maxRedirects: 0, validateStatus: () => true }); + token = String(loginRes.data?.token || "").trim(); + if (loginRes.status !== 200 || !token) { + return { status: "UPSTREAM_UNAVAILABLE", total: null, delivered: null, cancelled: null, note: "Paperfly auth unavailable" }; + } + paperflyWebTokenCache.set(cacheKey, { token, expiresAt: now + 45 * 60 * 1000 }); + } + const res = await axios.post("https://go-app.paperfly.com.bd/merchant/api/react/smart-check/list.php", { search_text: cleanPhone, limit: 50, page: 1 }, { + timeout: 6000, + maxRedirects: 0, + validateStatus: () => true, + headers: { Authorization: `Bearer ${token}`, Accept: "application/json" }, + }); + if (res.status !== 200 || typeof res.data !== "object" || res.data === null) { + return { status: "UPSTREAM_UNAVAILABLE", total: null, delivered: null, cancelled: null, note: `Paperfly Smart-Check server HTTP ${res.status}` }; + } + const records = Array.isArray(res.data.records) ? res.data.records : []; + const total = Number(res.data.totalRecords ?? records.length); + let delivered = 0; + let cancelled = 0; + for (const r of records) { + const st = String(r?.status || "").toLowerCase(); + if (st.includes("deliver") || st.includes("success")) + delivered++; + else if (st.includes("return") || st.includes("cancel") || st.includes("fail") || st.includes("close")) + cancelled++; + } + return { status: "LIVE", total, delivered, cancelled }; + } + static async checkCarrybee(cleanPhone, email, password) { + const cacheKey = email.trim().toLowerCase(); + const now = Date.now(); + let sess = carrybeeSessionCache.get(cacheKey); + if (!sess || sess.expiresAt <= now) { + const csrfRes = await axios.get("https://merchant.carrybee.com/api/auth/csrf", { timeout: 6000, validateStatus: () => true }); + const csrfToken = csrfRes.data?.csrfToken; + if (!csrfToken) + return null; + const initCookie = (csrfRes.headers["set-cookie"] || []).map((c) => c.split(";")[0]).join("; "); + const loginRes = await axios.post("https://merchant.carrybee.com/api/auth/callback/login?", new URLSearchParams({ csrfToken, email: email.trim(), password, callbackUrl: "https://merchant.carrybee.com/login", json: "true" }).toString(), { + timeout: 6000, + maxRedirects: 0, + validateStatus: () => true, + headers: { "Content-Type": "application/x-www-form-urlencoded", Cookie: initCookie, Referer: "https://merchant.carrybee.com/login" }, + }); + const loginCookies = [...(csrfRes.headers["set-cookie"] || []), ...(loginRes.headers["set-cookie"] || [])] + .map((c) => c.split(";")[0]) + .join("; "); + const meRes = await axios.get("https://merchant.carrybee.com/api/auth/session", { + timeout: 6000, + validateStatus: () => true, + headers: { Cookie: loginCookies }, + }); + const businessId = String(meRes.data?.user?.businessId || meRes.data?.businessId || ""); + if (!businessId) + return null; + sess = { cookieHeader: loginCookies, businessId, expiresAt: now + 45 * 60 * 1000 }; + carrybeeSessionCache.set(cacheKey, sess); + } + const res = await axios.get(`https://api-merchant.carrybee.com/api/v2/businesses/${encodeURIComponent(sess.businessId)}/fraud-check/${encodeURIComponent(cleanPhone)}`, { timeout: 6000, validateStatus: () => true, headers: { Cookie: sess.cookieHeader, Accept: "application/json" } }); + if (res.status !== 200 || !res.data) + return null; + const d = res.data.data || res.data; + const delivered = Number(d.delivered ?? d.total_delivered ?? d.success ?? 0); + const cancelled = Number(d.returned ?? d.cancelled ?? d.total_cancelled ?? 0); + const total = Number(d.total ?? d.total_parcels ?? delivered + cancelled); + return { total, delivered, cancelled }; + } + static async checkEcourier(cleanPhone, apiKey, apiSecret, userId) { + const res = await axios.post("https://backoffice.ecourier.com.bd/api/fraud-status-check", { number: cleanPhone }, { + timeout: 6000, + maxRedirects: 0, + validateStatus: () => true, + headers: { + "API-KEY": apiKey, + "API-SECRET": apiSecret, + "USER-ID": userId, + "Content-Type": "application/json", + }, + }); + if (res.status !== 200 || !res.data) + return null; + const d = res.data.response || res.data.data || res.data; + const delivered = Number(d.delivered ?? d.success_delivery ?? 0); + const cancelled = Number(d.cancelled ?? d.cancel_delivery ?? d.returned ?? 0); + const total = Number(d.total ?? d.total_delivery ?? delivered + cancelled); + return { total, delivered, cancelled }; + } /** - * Real-Time Multi-Carrier Fraud & Delivery Risk Evaluation (T6) - * Queries Pathao Nationwide Customer Delivery Database (/aladdin/api/v1/user/success), - * Steadfast Nationwide Logistics Database (/fraud_check/{phone}), and BD Operator Prefix Validator. + * Real-Time All-Bangladesh Multi-Carrier Fraud & Delivery Risk Evaluation (v2.7.4) + * Executes parallel live lookups across Steadfast, Pathao, RedX, Paperfly, CarryBee, eCourier & ParcelDex. + * Strictly Zero Mock Data: non-connected or inactive carrier accounts return `null` counts with transparent status. */ - static async evaluateRisk(phoneNumber, steadfastAdapter, pathaoAdapter) { + static async evaluateRisk(phoneNumber, steadfastAdapter, pathaoAdapter, config) { const rawDigits = String(phoneNumber || "").replace(/[^0-9]/g, ""); const cleanPhone = rawDigits.startsWith("880") && rawDigits.length === 13 ? rawDigits.slice(2) : rawDigits; - // Valid BD Mobile format check (11 digits starting with 013, 014, 015, 016, 017, 018, 019) const isValidBDOperator = /^01[3-9]\d{8}$/.test(cleanPhone); if (!isValidBDOperator) { return { @@ -24,52 +228,346 @@ export class FraudRiskEngine { carrier_verified: false, data_sources: ["prefix_validator"], sample_size: 0, + courier_breakdown: [], coverage_note: "Validated against BTRC 11-digit mobile operator prefix rules (013–019).", }; } + const breakdown = []; + const dataSources = []; + let verifiedByCarrier = false; + let customerRating; + // Run all 7 Bangladesh courier checks in parallel for sub-second response + const [sfTask, ptTask, rxTask, pfTask, cbTask, ecTask, pdTask] = await Promise.allSettled([ + // 1. Steadfast (Packzy API first, then Steadfast Web Login fallback if configured) + (async () => { + if (steadfastAdapter && steadfastAdapter.isConfigured()) { + try { + const sfData = await steadfastAdapter.fraudCheck(cleanPhone); + const sfTotal = Number(sfData?.total_parcels ?? sfData?.data?.total_parcels ?? 0); + const sfDelivered = Number(sfData?.total_delivered ?? sfData?.data?.total_delivered ?? 0); + const sfCancelled = Number(sfData?.total_cancelled ?? sfData?.data?.total_cancelled ?? 0); + return { + courier: "steadfast", + courier_name: "Steadfast Courier", + status: "LIVE", + total_parcels: sfTotal, + total_delivered: sfDelivered, + total_cancelled: sfCancelled, + success_rate: pct(sfDelivered, sfTotal), + }; + } + catch (err) { + const sfEmail = config?.steadfast?.email || ""; + const sfPass = config?.steadfast?.password || ""; + if (sfEmail && sfPass) { + const webRes = await FraudRiskEngine.checkSteadfastWeb(cleanPhone, sfEmail, sfPass).catch(() => null); + if (webRes) { + return { + courier: "steadfast", + courier_name: "Steadfast Courier", + status: "LIVE", + total_parcels: webRes.total, + total_delivered: webRes.delivered, + total_cancelled: webRes.cancelled, + success_rate: pct(webRes.delivered, webRes.total), + }; + } + } + const status403 = err?.response?.status === 403 || String(err?.message || "").includes("403"); + return { + courier: "steadfast", + courier_name: "Steadfast Courier", + status: status403 ? "ACCOUNT_INACTIVE" : "UPSTREAM_UNAVAILABLE", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: status403 ? "Packzy API account inactive — add active Steadfast API Key or Portal Email/Password" : "Steadfast API temporarily unreachable", + }; + } + } + const sfEmail = config?.steadfast?.email || ""; + const sfPass = config?.steadfast?.password || ""; + if (sfEmail && sfPass) { + const webRes = await FraudRiskEngine.checkSteadfastWeb(cleanPhone, sfEmail, sfPass).catch(() => null); + if (webRes) { + return { + courier: "steadfast", + courier_name: "Steadfast Courier", + status: "LIVE", + total_parcels: webRes.total, + total_delivered: webRes.delivered, + total_cancelled: webRes.cancelled, + success_rate: pct(webRes.delivered, webRes.total), + }; + } + } + return { + courier: "steadfast", + courier_name: "Steadfast Courier", + status: "NOT_CONNECTED", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "Connect Steadfast API Key or Portal Login", + }; + })(), + // 2. Pathao Courier (Nationwide Aladdin / Merchant user/success DB) + (async () => { + if (pathaoAdapter && pathaoAdapter.isConfigured()) { + try { + const ptRes = await pathaoAdapter.fraudCheck(cleanPhone); + const ptData = ptRes?.data || ptRes || {}; + const cust = ptData.customer || {}; + const ptTotal = Number(cust.total_delivery ?? 0); + const ptDelivered = Number(cust.successful_delivery ?? 0); + const ptCancelled = Math.max(0, ptTotal - ptDelivered); + if (ptData.customer_rating) { + customerRating = String(ptData.customer_rating); + } + return { + courier: "pathao", + courier_name: "Pathao Courier", + status: "LIVE", + total_parcels: ptTotal, + total_delivered: ptDelivered, + total_cancelled: ptCancelled, + success_rate: pct(ptDelivered, ptTotal), + note: ptData.customer_rating ? `Rating: ${ptData.customer_rating}` : undefined, + }; + } + catch (_) { + return { + courier: "pathao", + courier_name: "Pathao Courier", + status: "UPSTREAM_UNAVAILABLE", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "Pathao API unreachable", + }; + } + } + return { + courier: "pathao", + courier_name: "Pathao Courier", + status: "NOT_CONNECTED", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "Connect Pathao credentials", + }; + })(), + // 3. RedX Delivery (Nationwide customer-success-return-rate via RedX merchant login) + (async () => { + const rxPhone = config?.redx?.phone || ""; + const rxPass = config?.redx?.password || ""; + if (rxPhone && rxPass) { + const rxRes = await FraudRiskEngine.checkRedxNationwide(cleanPhone, rxPhone, rxPass).catch(() => null); + if (rxRes) { + return { + courier: "redx", + courier_name: "RedX Delivery", + status: "LIVE", + total_parcels: rxRes.total, + total_delivered: rxRes.delivered, + total_cancelled: rxRes.cancelled, + success_rate: pct(rxRes.delivered, rxRes.total), + }; + } + return { + courier: "redx", + courier_name: "RedX Delivery", + status: "UPSTREAM_UNAVAILABLE", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "RedX login failed or rate-limited", + }; + } + return { + courier: "redx", + courier_name: "RedX Delivery", + status: "NOT_CONNECTED", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "Add RedX Portal Phone + Password in Courier API Keys for nationwide stats", + }; + })(), + // 4. Paperfly Go (Merchant Smart-Check) + (async () => { + const pfUser = config?.paperfly?.username || ""; + const pfPass = config?.paperfly?.password || ""; + if (pfUser && pfPass) { + const pfRes = await FraudRiskEngine.checkPaperflySmartCheck(cleanPhone, pfUser, pfPass).catch(() => ({ + status: "UPSTREAM_UNAVAILABLE", + total: null, + delivered: null, + cancelled: null, + note: "Paperfly Smart-Check unreachable", + })); + return { + courier: "paperfly", + courier_name: "Paperfly Go", + status: pfRes.status, + total_parcels: pfRes.total, + total_delivered: pfRes.delivered, + total_cancelled: pfRes.cancelled, + success_rate: pfRes.total != null && pfRes.delivered != null ? pct(pfRes.delivered, pfRes.total) : null, + note: pfRes.note, + }; + } + return { + courier: "paperfly", + courier_name: "Paperfly Go", + status: "NOT_CONNECTED", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "Connect Paperfly credentials", + }; + })(), + // 5. CarryBee + (async () => { + const cbEmail = config?.extraFraudCreds?.carrybeeEmail || ""; + const cbPass = config?.extraFraudCreds?.carrybeePassword || ""; + if (cbEmail && cbPass) { + const cbRes = await FraudRiskEngine.checkCarrybee(cleanPhone, cbEmail, cbPass).catch(() => null); + if (cbRes) { + return { + courier: "carrybee", + courier_name: "CarryBee", + status: "LIVE", + total_parcels: cbRes.total, + total_delivered: cbRes.delivered, + total_cancelled: cbRes.cancelled, + success_rate: pct(cbRes.delivered, cbRes.total), + }; + } + return { + courier: "carrybee", + courier_name: "CarryBee", + status: "UPSTREAM_UNAVAILABLE", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "CarryBee login failed", + }; + } + return { + courier: "carrybee", + courier_name: "CarryBee", + status: "NOT_CONNECTED", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "Optional: Add CarryBee login in Courier API Keys", + }; + })(), + // 6. eCourier + (async () => { + const ecKey = config?.extraFraudCreds?.ecourierApiKey || ""; + const ecSec = config?.extraFraudCreds?.ecourierApiSecret || ""; + const ecUid = config?.extraFraudCreds?.ecourierUserId || ""; + if (ecKey && ecSec && ecUid) { + const ecRes = await FraudRiskEngine.checkEcourier(cleanPhone, ecKey, ecSec, ecUid).catch(() => null); + if (ecRes) { + return { + courier: "ecourier", + courier_name: "eCourier", + status: "LIVE", + total_parcels: ecRes.total, + total_delivered: ecRes.delivered, + total_cancelled: ecRes.cancelled, + success_rate: pct(ecRes.delivered, ecRes.total), + }; + } + return { + courier: "ecourier", + courier_name: "eCourier", + status: "UPSTREAM_UNAVAILABLE", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "eCourier API unreachable", + }; + } + return { + courier: "ecourier", + courier_name: "eCourier", + status: "NOT_CONNECTED", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "Optional: Add eCourier API keys", + }; + })(), + // 7. ParcelDex + (async () => { + const pdKey = config?.extraFraudCreds?.parceldexApiKey || ""; + if (pdKey) { + try { + const pdRes = await axios.get(`https://parceldex.com.bd/api/v1/fraud-check/${encodeURIComponent(cleanPhone)}`, { + timeout: 6000, + validateStatus: () => true, + headers: { Authorization: `Bearer ${pdKey}`, Accept: "application/json" }, + }); + if (pdRes.status === 200 && pdRes.data) { + const d = pdRes.data.data || pdRes.data; + const del = Number(d.delivered ?? d.total_delivered ?? 0); + const can = Number(d.cancelled ?? d.returned ?? d.total_cancelled ?? 0); + const tot = Number(d.total ?? d.total_parcels ?? del + can); + return { + courier: "parceldex", + courier_name: "ParcelDex", + status: "LIVE", + total_parcels: tot, + total_delivered: del, + total_cancelled: can, + success_rate: pct(del, tot), + }; + } + } + catch (_) { } + } + return { + courier: "parceldex", + courier_name: "ParcelDex", + status: "NOT_CONNECTED", + total_parcels: null, + total_delivered: null, + total_cancelled: null, + success_rate: null, + note: "Optional: Add ParcelDex API key", + }; + })(), + ]); + for (const settled of [sfTask, ptTask, rxTask, pfTask, cbTask, ecTask, pdTask]) { + if (settled.status === "fulfilled" && settled.value) { + breakdown.push(settled.value); + } + } let total = 0; let delivered = 0; let cancelled = 0; - let verifiedByCarrier = false; - const dataSources = []; - let customerRating; - // 1. Query Steadfast Nationwide Fraud Database (GET /fraud_check/{phone}) - if (steadfastAdapter && steadfastAdapter.isConfigured()) { - try { - const sfData = await steadfastAdapter.fraudCheck(cleanPhone); - const sfTotal = Number(sfData?.total_parcels ?? sfData?.data?.total_parcels ?? 0); - const sfDelivered = Number(sfData?.total_delivered ?? sfData?.data?.total_delivered ?? 0); - const sfCancelled = Number(sfData?.total_cancelled ?? sfData?.data?.total_cancelled ?? 0); - total += sfTotal; - delivered += sfDelivered; - cancelled += sfCancelled; + for (const item of breakdown) { + if (item.status === "LIVE" && item.total_parcels !== null) { verifiedByCarrier = true; - dataSources.push("steadfast_nationwide"); - } - catch (_) { - // Continue to Pathao check - } - } - // 2. Query Pathao Nationwide Customer Delivery Database (POST /aladdin/api/v1/user/success) - if (pathaoAdapter && pathaoAdapter.isConfigured()) { - try { - const ptRes = await pathaoAdapter.fraudCheck(cleanPhone); - const ptData = ptRes?.data || ptRes || {}; - const cust = ptData.customer || {}; - const ptTotal = Number(cust.total_delivery ?? 0); - const ptDelivered = Number(cust.successful_delivery ?? 0); - const ptCancelled = Math.max(0, ptTotal - ptDelivered); - total += ptTotal; - delivered += ptDelivered; - cancelled += ptCancelled; - verifiedByCarrier = true; - dataSources.push("pathao_nationwide"); - if (ptData.customer_rating) { - customerRating = String(ptData.customer_rating); - } - } - catch (_) { - // Carrier lookup error handled gracefully + dataSources.push(`${item.courier}_nationwide`); + total += item.total_parcels; + delivered += item.total_delivered || 0; + cancelled += item.total_cancelled || 0; } } dataSources.push("prefix_validator"); @@ -90,7 +588,8 @@ export class FraudRiskEngine { carrier_verified: true, data_sources: dataSources, sample_size: 0, - coverage_note: `Queried ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")} live databases; 0 prior consignments recorded.`, + courier_breakdown: breakdown, + coverage_note: `Queried ${dataSources.filter((s) => s !== "prefix_validator").join(", ")} live databases; 0 prior consignments recorded.`, }; } const successRatio = (delivered / total) * 100; @@ -130,10 +629,10 @@ export class FraudRiskEngine { carrier_verified: true, data_sources: dataSources, sample_size: total, - coverage_note: `Aggregated ${total} historical consignments from ${dataSources.filter((s) => s !== "prefix_validator").join(" and ")}.`, + courier_breakdown: breakdown, + coverage_note: `Aggregated ${total} historical consignments from ${dataSources.filter((s) => s !== "prefix_validator").join(", ")}.`, }; } - // Honest fallback when no carrier database returned history return { phone: cleanPhone, risk_level: "NO_HISTORY", @@ -148,6 +647,7 @@ export class FraudRiskEngine { carrier_verified: false, data_sources: ["prefix_validator"], sample_size: 0, + courier_breakdown: breakdown, coverage_note: "Validated format via BTRC prefix rules only; no upstream carrier history available.", }; } diff --git a/dist/config.d.ts b/dist/config.d.ts index 7c3ebe0..6b3b175 100644 --- a/dist/config.d.ts +++ b/dist/config.d.ts @@ -2,6 +2,8 @@ export interface CourierConfig { steadfast: { apiKey: string; secretKey: string; + email?: string; + password?: string; baseUrl: string; enabled: boolean; }; @@ -16,6 +18,8 @@ export interface CourierConfig { }; redx: { apiToken: string; + phone?: string; + password?: string; baseUrl: string; pickupStoreId: string; enabled: boolean; @@ -32,6 +36,14 @@ export interface CourierConfig { apiKey: string; enabled: boolean; }; + extraFraudCreds?: { + carrybeeEmail: string; + carrybeePassword: string; + ecourierApiKey: string; + ecourierApiSecret: string; + ecourierUserId: string; + parceldexApiKey: string; + }; } export type EnvSource = Record; export declare const ALLOWED_CARRIER_HOSTS: Record<"steadfast" | "pathao" | "redx" | "paperfly", readonly string[]>; diff --git a/dist/config.js b/dist/config.js index bd330c2..40747e3 100644 --- a/dist/config.js +++ b/dist/config.js @@ -61,6 +61,8 @@ export function loadConfig(src = process.env) { steadfast: { apiKey: steadfastApiKey, secretKey: steadfastSecretKey, + email: src.STEADFAST_EMAIL || "", + password: src.STEADFAST_PASSWORD || "", baseUrl: validateCarrierBaseUrl("steadfast", src.STEADFAST_BASE_URL, "https://portal.packzy.com/api/v1"), enabled: Boolean(steadfastApiKey && steadfastSecretKey), }, @@ -75,6 +77,8 @@ export function loadConfig(src = process.env) { }, redx: { apiToken: src.REDX_API_TOKEN || "", + phone: src.REDX_PHONE || "", + password: src.REDX_PASSWORD || "", baseUrl: validateCarrierBaseUrl("redx", src.REDX_BASE_URL, "https://openapi.redx.com.bd/v1.0.0-beta"), pickupStoreId: src.REDX_PICKUP_STORE_ID || "", enabled: Boolean(src.REDX_API_TOKEN), @@ -91,5 +95,13 @@ export function loadConfig(src = process.env) { apiKey: googleMapsKey, enabled: Boolean(googleMapsKey), }, + extraFraudCreds: { + carrybeeEmail: src.CARRYBEE_EMAIL || "", + carrybeePassword: src.CARRYBEE_PASSWORD || "", + ecourierApiKey: src.ECOURIER_API_KEY || "", + ecourierApiSecret: src.ECOURIER_API_SECRET || "", + ecourierUserId: src.ECOURIER_USER_ID || "", + parceldexApiKey: src.PARCELDEX_API_KEY || "", + }, }; } diff --git a/dist/http.js b/dist/http.js index 497c583..4883e81 100644 --- a/dist/http.js +++ b/dist/http.js @@ -133,6 +133,8 @@ export function keysFromRequest(req) { return { STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"), STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"), + STEADFAST_EMAIL: pick("x-steadfast-email", "STEADFAST_EMAIL"), + STEADFAST_PASSWORD: pick("x-steadfast-password", "STEADFAST_PASSWORD"), STEADFAST_BASE_URL: pickBaseUrl("steadfast", "x-steadfast-base-url", "STEADFAST_BASE_URL", "https://portal.packzy.com/api/v1"), PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"), PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"), @@ -141,6 +143,8 @@ export function keysFromRequest(req) { PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"), PATHAO_BASE_URL: pickBaseUrl("pathao", "x-pathao-base-url", "PATHAO_BASE_URL", "https://api-hermes.pathao.com"), REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"), + REDX_PHONE: pick("x-redx-phone", "REDX_PHONE"), + REDX_PASSWORD: pick("x-redx-password", "REDX_PASSWORD"), REDX_BASE_URL: pickBaseUrl("redx", "x-redx-base-url", "REDX_BASE_URL", "https://openapi.redx.com.bd/v1.0.0-beta"), REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "REDX_PICKUP_STORE_ID"), PAPERFLY_API_KEY: pick("x-paperfly-api-key", "PAPERFLY_API_KEY"), @@ -148,6 +152,12 @@ export function keysFromRequest(req) { PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"), PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"), PAPERFLY_BASE_URL: pickBaseUrl("paperfly", "x-paperfly-base-url", "PAPERFLY_BASE_URL", "https://api.paperfly.com.bd"), + CARRYBEE_EMAIL: pick("x-carrybee-email", "CARRYBEE_EMAIL"), + CARRYBEE_PASSWORD: pick("x-carrybee-password", "CARRYBEE_PASSWORD"), + ECOURIER_API_KEY: pick("x-ecourier-api-key", "ECOURIER_API_KEY"), + ECOURIER_API_SECRET: pick("x-ecourier-api-secret", "ECOURIER_API_SECRET"), + ECOURIER_USER_ID: pick("x-ecourier-user-id", "ECOURIER_USER_ID"), + PARCELDEX_API_KEY: pick("x-parceldex-api-key", "PARCELDEX_API_KEY"), GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true), }; } @@ -844,6 +854,7 @@ app.post("/api/public/fraud-demo", publicDemoLimiter, async (req, res) => { total_cancelled: result.total_cancelled, sample_size: result.sample_size, data_sources: result.data_sources, + courier_breakdown: result.courier_breakdown || [], recommendation: result.recommendation, }; return res.json(wrapSuccess(safeDto, "live_api")); diff --git a/dist/registry.d.ts b/dist/registry.d.ts index 80c4669..68dc885 100644 --- a/dist/registry.d.ts +++ b/dist/registry.d.ts @@ -9,6 +9,7 @@ export declare function clearWebhookEvents(tenantId?: string): void; export declare class CourierRegistry { private adapters; private googleMaps; + private config; constructor(config?: CourierConfig); listCouriers(): { couriers: { diff --git a/dist/registry.js b/dist/registry.js index 6eaced3..a48f5e0 100644 --- a/dist/registry.js +++ b/dist/registry.js @@ -90,7 +90,9 @@ function isDefinitePreBookingRejection(err) { export class CourierRegistry { adapters = new Map(); googleMaps; + config; constructor(config = loadConfig()) { + this.config = config; const steadfast = new SteadfastAdapter(config.steadfast.apiKey, config.steadfast.secretKey, config.steadfast.baseUrl); this.adapters.set("steadfast", steadfast); const pathao = new PathaoAdapter(config.pathao.clientId, config.pathao.clientSecret, config.pathao.username, config.pathao.password, config.pathao.storeId, config.pathao.baseUrl); @@ -562,7 +564,7 @@ export class CourierRegistry { async checkFraudRisk(phone) { const steadfast = this.adapters.get("steadfast"); const pathao = this.adapters.get("pathao"); - return await FraudRiskEngine.evaluateRisk(phone, steadfast, pathao); + return await FraudRiskEngine.evaluateRisk(phone, steadfast, pathao, this.config); } async validateAddress(req) { return await this.googleMaps.validateAndGeocode(req); diff --git a/dist/types.d.ts b/dist/types.d.ts index 072dab6..46a3d41 100644 --- a/dist/types.d.ts +++ b/dist/types.d.ts @@ -66,6 +66,16 @@ export interface BalanceResponse { as_of?: string; raw_response?: any; } +export interface CarrierFraudBreakdownItem { + courier: string; + courier_name: string; + status: "LIVE" | "NOT_CONNECTED" | "ACCOUNT_INACTIVE" | "UPSTREAM_UNAVAILABLE"; + total_parcels: number | null; + total_delivered: number | null; + total_cancelled: number | null; + success_rate: number | null; + note?: string; +} export interface FraudRiskScoreResponse { phone: string; risk_level: "INVALID_NUMBER" | "NO_HISTORY" | "LOW" | "MEDIUM" | "MODERATE" | "HIGH" | "CRITICAL" | "NEW_BUYER"; @@ -81,6 +91,7 @@ export interface FraudRiskScoreResponse { data_sources: string[]; sample_size: number; coverage_note: string; + courier_breakdown?: CarrierFraudBreakdownItem[]; multi_signal_factors?: { carrier_score: string; address_confidence?: string; diff --git a/dist/version.js b/dist/version.js index 52b6353..69c27b0 100644 --- a/dist/version.js +++ b/dist/version.js @@ -11,6 +11,6 @@ function readPackageVersion() { catch { // Fallback if package.json is unavailable at runtime } - return "2.7.3"; + return "2.7.4"; } export const APP_VERSION = readPackageVersion(); diff --git a/guide.html b/guide.html index 74caf60..24282d2 100644 --- a/guide.html +++ b/guide.html @@ -1605,7 +1605,7 @@ Aura Courier MCP Logo
Aura Courier MCP - v2.7.3 + v2.7.4
  • - 📦 npm Package (v2.7.3) + 📦 npm Package (v2.7.4)
  • @@ -1735,7 +1735,7 @@ }, "aura-courier-local": { "command": "npx", - "args": ["-y", "aura-courier-mcp@2.7.3"], + "args": ["-y", "aura-courier-mcp@2.7.4"], "env": { "PORT": "8080" } } } @@ -1752,7 +1752,7 @@ }, "aura-courier-stdio": { "command": "npx", - "args": ["-y", "aura-courier-mcp@2.7.3"] + "args": ["-y", "aura-courier-mcp@2.7.4"] } } }, null, 2) diff --git a/health.html b/health.html index 5615951..f143652 100644 --- a/health.html +++ b/health.html @@ -360,7 +360,7 @@
    Aura Courier MCP - v2.7.3 · Telemetry + v2.7.4 · Telemetry