import express from "express"; import { randomUUID } from "node:crypto"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; import { CourierRegistry, recordWebhookEvent } from "./registry.js"; import { loadConfig } from "./config.js"; import { buildMcpServer, executeToolCall, TOOLS } from "./server.js"; import { createRateLimiter } from "./middleware/rate_limit.js"; import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, verifyWebhookSignature, recordAuditLog, } from "./middleware/auth.js"; import { McpToolError, wrapError, wrapSuccess } from "./envelope.js"; import path from "node:path"; import { fileURLToPath } from "node:url"; import pg from "pg"; const dbUrl = process.env.DATABASE_URL || "postgresql://postgres:AMeyaNUsvKN9GR4zs33YZFQw2ZjeBXRacp5K09bz4vwDMsLejuO1KxBGIZtDLVCw@ernix50nvuq9ur9jy8na8tgr:5432/aura_auth"; let dbPool = null; if (process.env.NODE_ENV !== "test") { try { dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 }); } catch (_) { } } // Automated Data Retention Engine (Daily Midnight Sweep) setInterval(async () => { if (dbPool) { try { const pruneRes = await dbPool.query(`UPDATE courier_parcels SET recipient_name = 'ANONYMIZED', recipient_phone = 'ANONYMIZED', recipient_address = 'ANONYMIZED' WHERE created_at < NOW() - INTERVAL '90 days' AND recipient_name != 'ANONYMIZED'`); if (pruneRes.rowCount && pruneRes.rowCount > 0) { console.log(`[Data Retention Engine] Anonymized ${pruneRes.rowCount} legacy order records older than 90 days.`); } } catch (_) { } } }, 24 * 60 * 60 * 1000).unref(); const PORT = Number(process.env.PORT || 8080); const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const LANDING = path.join(APP_DIR, "index.html"); const PRIVACY_HTML = path.join(APP_DIR, "privacy.html"); const HEALTH_HTML = path.join(APP_DIR, "health.html"); const MCP_EXPLORER_HTML = path.join(APP_DIR, "mcp_explorer.html"); const GUIDE_HTML = path.join(APP_DIR, "guide.html"); /** * Pull this client's courier keys from request headers or query params. * Task T1 Tenant Isolation: Only fall back to master process.env credentials when * the caller authenticated with the master key (tenantId === "master"). */ export function keysFromRequest(req) { const h = req.headers; const q = req.query; const allowMasterEnvFallback = req.auraAuth?.tenantId === "master"; const pick = (header, query, envVar, allowNonMasterEnv = false) => { const hv = h[header]; const v = (Array.isArray(hv) ? hv[0] : hv) ?? q[query]; if (v) return String(v); if (envVar && (allowMasterEnvFallback || allowNonMasterEnv)) { return process.env[envVar]; } return undefined; }; return { STEADFAST_API_KEY: pick("x-steadfast-api-key", "steadfast_key", "STEADFAST_API_KEY"), STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "steadfast_secret", "STEADFAST_SECRET_KEY"), STEADFAST_BASE_URL: pick("x-steadfast-base-url", "steadfast_base_url", "STEADFAST_BASE_URL", true), PATHAO_CLIENT_ID: pick("x-pathao-client-id", "pathao_client_id", "PATHAO_CLIENT_ID"), PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "pathao_client_secret", "PATHAO_CLIENT_SECRET"), PATHAO_USERNAME: pick("x-pathao-username", "pathao_username", "PATHAO_USERNAME"), PATHAO_PASSWORD: pick("x-pathao-password", "pathao_password", "PATHAO_PASSWORD"), PATHAO_STORE_ID: pick("x-pathao-store-id", "pathao_store_id", "PATHAO_STORE_ID"), PATHAO_BASE_URL: pick("x-pathao-base-url", "pathao_base_url", "PATHAO_BASE_URL", true), REDX_API_TOKEN: pick("x-redx-api-token", "redx_token", "REDX_API_TOKEN"), REDX_BASE_URL: pick("x-redx-base-url", "redx_base_url", "REDX_BASE_URL", true), REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "redx_pickup_store_id", "REDX_PICKUP_STORE_ID"), PAPERFLY_API_KEY: pick("x-paperfly-api-key", "paperfly_key", "PAPERFLY_API_KEY"), PAPERFLY_USERNAME: pick("x-paperfly-username", "paperfly_username", "PAPERFLY_USERNAME"), PAPERFLY_PASSWORD: pick("x-paperfly-password", "paperfly_password", "PAPERFLY_PASSWORD"), PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "paperfly_store", "PAPERFLY_STORE_NAME"), GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "google_maps_key", "GOOGLE_MAPS_API_KEY", true), }; } export const app = express(); app.use(express.json({ limit: "1mb" })); // Robust Malformed JSON Syntax Error Guard app.use((err, _req, res, next) => { if (err && (err.type === "entity.parse.failed" || err.status === 400)) { return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "Malformed JSON payload in request body.", retryable: false, }), "validator")); } next(err); }); // Allow browser-based and cross-origin MCP clients. app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key"); res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"); res.header("Access-Control-Expose-Headers", "mcp-session-id"); if (req.method === "OPTIONS") { res.sendStatus(204); return; } next(); }); // Enterprise Sliding-Window Rate Limiters const generalLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "General Gateway" }); const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" }); const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 30, name: "Live Tracking Hub" }); const webhookLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Courier Webhook Gateway" }); app.use(generalLimiter); app.use(optionalAuthMiddleware); // Static brand assets (app icons, favicons, logos) app.use("/assets", express.static(path.join(APP_DIR, "assets"))); const sessions = new Map(); const SESSION_TTL_MS = 60 * 60 * 1000; // 1-hour idle expiration setInterval(() => { const now = Date.now(); for (const [sid, entry] of sessions.entries()) { if (now - entry.lastActiveAt > SESSION_TTL_MS) { try { entry.transport.close?.(); } catch { } sessions.delete(sid); } } }, 15 * 60 * 1000).unref(); /** * Task T1: POST /mcp requires Authorization: Bearer . */ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => { const sessionId = req.headers["mcp-session-id"]; const tenantId = req.auraAuth?.tenantId || "default"; let transport; if (sessionId && sessions.has(sessionId)) { const entry = sessions.get(sessionId); entry.lastActiveAt = Date.now(); transport = entry.transport; } else if (!sessionId && isInitializeRequest(req.body)) { const registry = new CourierRegistry(loadConfig(keysFromRequest(req))); const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName), tenantId); transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), enableJsonResponse: true, onsessioninitialized: (sid) => { sessions.set(sid, { transport, lastActiveAt: Date.now() }); }, }); transport.onclose = () => { if (transport.sessionId) sessions.delete(transport.sessionId); }; await server.connect(transport); } else if (req.body && (req.body.method === "tools/list" || req.body.method === "tools/call")) { // Stateless JSON-RPC 2.0 Direct Execution Mode const rpcId = req.body.id ?? 1; const registry = new CourierRegistry(loadConfig(keysFromRequest(req))); if (req.body.method === "tools/list") { res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { tools: TOOLS } }); return; } const toolName = String(req.body.params?.name || ""); const args = (req.body.params?.arguments || {}); const auth = isActionPermitted(req, toolName, args); if (!auth.permitted) { const errEnvelope = wrapError(new McpToolError({ code: "UNAUTHORIZED", message: auth.reason || "Unauthorized tool invocation.", retryable: false, }), "validator"); res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { isError: true, content: [{ type: "text", text: JSON.stringify(errEnvelope, null, 2) }], }, }); return; } const { isError, envelope } = await executeToolCall(registry, toolName, args, tenantId); recordAuditLog(tenantId, toolName, args, isError ? "error" : "ok"); res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { isError, content: [{ type: "text", text: JSON.stringify(envelope, null, 2) }], }, }); return; } else { res.status(400).json({ jsonrpc: "2.0", error: { code: -32000, message: "Bad Request: missing or invalid session. Send an initialize request first." }, id: null, }); return; } try { await transport.handleRequest(req, res, req.body); } catch (err) { if (!res.headersSent) { res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: `Internal error: ${err?.message || String(err)}` }, id: null, }); } } }); // GET (server->client SSE stream or Browser Explorer) app.get("/mcp", mcpLimiter, async (req, res) => { const sessionId = req.headers["mcp-session-id"]; if (!sessionId || !sessions.has(sessionId)) { if (req.headers.accept?.includes("text/html")) { return res.sendFile(MCP_EXPLORER_HTML, (err) => { if (err && !res.headersSent) { res.status(400).send("Invalid or missing session ID. Visit https://courier.auraajenticai.cloud for instructions."); } }); } if (!req.auraAuth?.authenticated) { return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Missing or invalid Authorization: Bearer header.", }), "validator")); } res.status(400).send("Invalid or missing session ID"); return; } if (!req.auraAuth?.authenticated) { return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Missing or invalid Authorization: Bearer header.", }), "validator")); } const entry = sessions.get(sessionId); entry.lastActiveAt = Date.now(); await entry.transport.handleRequest(req, res); }); // DELETE (end session) for an existing session. app.delete("/mcp", requireMcpAuth, async (req, res) => { const sessionId = req.headers["mcp-session-id"]; if (!sessionId || !sessions.has(sessionId)) { res.status(400).send("Invalid or missing session ID"); return; } const entry = sessions.get(sessionId); entry.lastActiveAt = Date.now(); await entry.transport.handleRequest(req, res); }); /** * Task T1 & T8 — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly */ function handleCourierWebhook(provider) { return (req, res) => { const isValidSig = verifyWebhookSignature(req, provider); if (!isValidSig) { return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: `Unauthorized ${provider} webhook request: missing or invalid signature/secret.`, courier: provider, retryable: false, }), "validator")); } const payload = req.body || {}; const consignmentId = payload.consignment_id || payload.merchant_order_id || payload.tracking_code || payload.tracking_id || payload.order_id; if (provider === "steadfast" && !consignmentId) { return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "Invalid or missing consignment_id in webhook payload.", courier: provider, }), "validator")); } const status = String(payload.status || payload.order_status || payload.event || "received"); const eventType = String(payload.notification_type || payload.event || "delivery_status"); const invoice = payload.invoice || payload.merchant_order_id; const record = { id: randomUUID(), courier: provider, consignment_id: String(consignmentId || "UNKNOWN"), invoice: invoice ? String(invoice) : undefined, status, event_type: eventType, received_at: new Date().toISOString(), payload, }; recordWebhookEvent(record); return res.status(200).json(wrapSuccess({ status: "success", courier: provider, consignment_id: record.consignment_id, event_id: record.id, message: `${provider} webhook verified and recorded.`, }, "live_api")); }; } app.post("/webhooks/steadfast", webhookLimiter, handleCourierWebhook("steadfast")); app.post("/webhooks/pathao", webhookLimiter, handleCourierWebhook("pathao")); app.post("/webhooks/redx", webhookLimiter, handleCourierWebhook("redx")); app.post("/webhooks/paperfly", webhookLimiter, handleCourierWebhook("paperfly")); /** * Live Consumer & Merchant Cyber-Dark Tracking Hub * GET /track/:code */ app.get("/track/:code", trackingLimiter, async (req, res) => { const code = req.params.code; const format = req.query.format; let courier = (req.query.courier || "").toLowerCase(); if (!courier) { if (code.toUpperCase().startsWith("DS") || code.toUpperCase().startsWith("DB")) courier = "pathao"; else if (code.toUpperCase().startsWith("SF") || /^\d{8,12}$/.test(code)) courier = "steadfast"; else if (code.toUpperCase().startsWith("REDX") || code.toUpperCase().startsWith("RX")) courier = "redx"; else if (code.toUpperCase().startsWith("PF")) courier = "paperfly"; else courier = "pathao"; } let dbParcel = null; if (dbPool) { try { const qRes = await dbPool.query("SELECT * FROM courier_parcels WHERE tracking_code = $1 LIMIT 1", [code]); if (qRes.rows && qRes.rows.length > 0) { dbParcel = qRes.rows[0]; } } catch (_) { } } const registry = new CourierRegistry(loadConfig()); let trackResult = null; let errorObj = null; try { trackResult = await registry.trackParcel(code, courier); } catch (err) { errorObj = err; } if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) { if (trackResult) { return res.json(wrapSuccess(trackResult, "live_api")); } if (dbParcel) { return res.json(wrapSuccess({ success: true, parcel: dbParcel }, "cache")); } return res.status(404).json(wrapError(errorObj || new Error("Consignment not found"), "live_api")); } const raw = trackResult?.raw_response?.data || trackResult?.raw_response || (dbParcel?.raw?.data || dbParcel?.raw) || {}; const recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer"; const recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh"; const codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0; const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found"); const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase(); const carrierName = resolvedCourier === "pathao" ? "Pathao Express" : (resolvedCourier === "steadfast" ? "Steadfast Courier" : resolvedCourier === "redx" ? "RedX Delivery" : resolvedCourier === "paperfly" ? "Paperfly Go" : resolvedCourier.toUpperCase()); const shortLink = raw.short_link || (carrierName.toLowerCase().includes("pathao") ? `https://merchant.pathao.com/tracking?consignment_id=${code}` : (carrierName.toLowerCase().includes("steadfast") ? `https://steadfast.com.bd/t/${code}` : "")); const updatedAt = raw.order_status_updated_at || raw.updated_at || trackResult?.updated_at || (dbParcel?.updated_at ? new Date(dbParcel.updated_at).toLocaleString("en-GB") : new Date().toLocaleString()); const isDelivered = String(statusText).toLowerCase().includes("deliv"); const isAtHub = String(statusText).toLowerCase().includes("hub"); const isTransit = String(statusText).toLowerCase().includes("way") || String(statusText).toLowerCase().includes("transit") || String(statusText).toLowerCase().includes("progress"); const isPickedUp = isDelivered || isAtHub || isTransit || String(statusText).toLowerCase().includes("pick"); res.type("html").send(` Aura Live Tracking — ${code}

Aura Live Tracking

${carrierName} • Direct Live Telemetry

${statusText}
Consignment Tracking ID
${code}
Carrier
${carrierName}
Order Booked & Confirmed
Aura Dispatch Engine initialized booking.
Picked Up by Rider
Central Merchant Fulfillment Hub
${statusText}
Live Telemetry: ${updatedAt}
Destination Delivery
Destination: ${recipientAddress}
Customer
${recipientName}
Cash on Delivery (COD)
৳ ${Number(codAmount).toLocaleString()}
${shortLink ? ` Official Carrier Map Tracker` : ""}
`); }); /** * Task T9 — Health & Live Telemetry Endpoint * Unauthenticated GET /health returns { ok: true, version: "2.6.0" } ONLY. * Requests with a valid admin Bearer token receive full telemetry. */ app.get("/health", (req, res) => { const auth = req.auraAuth || resolveAuthContext(req); const isAdmin = auth.authenticated && auth.isAdmin; if (!isAdmin) { if (req.query.ui === "1" && req.headers.accept?.includes("text/html")) { return res.sendFile(HEALTH_HTML, (err) => { if (err && !res.headersSent) res.json({ ok: true, version: "2.6.0" }); }); } return res.json({ ok: true, version: "2.6.0", }); } const mem = process.memoryUsage(); const detailed = { ok: true, service: "aura-courier-mcp", version: "2.6.0", tools_count: TOOLS.length, spatial_engine: "Google Maps Platform (gmp_git_agentskills_v1)", fraud_engine: "Pathao Nationwide v2 + Steadfast Nationwide API + BD Prefix Validator", webhooks: { steadfast: "/webhooks/steadfast", pathao: "/webhooks/pathao", redx: "/webhooks/redx", paperfly: "/webhooks/paperfly", }, performance: { sessions_active: sessions.size, heap_used_mb: Math.round((mem.heapUsed / 1024 / 1024) * 10) / 10, heap_total_mb: Math.round((mem.heapTotal / 1024 / 1024) * 10) / 10, rss_mb: Math.round((mem.rss / 1024 / 1024) * 10) / 10, uptime_seconds: Math.round(process.uptime()), }, }; return res.json(detailed); }); app.get("/health.html", (_req, res) => { res.sendFile(HEALTH_HTML, (err) => { if (err && !res.headersSent) res.json({ ok: true, version: "2.6.0" }); }); }); app.get("/privacy", (_req, res) => { res.sendFile(PRIVACY_HTML, (err) => { if (err && !res.headersSent) { res.redirect("/"); } }); }); app.get("/guide", (_req, res) => { res.sendFile(GUIDE_HTML, (err) => { if (err && !res.headersSent) { res.redirect("/"); } }); }); app.get("/", (_req, res) => { res.sendFile(LANDING, (err) => { if (err && !res.headersSent) { res .type("html") .send(`Aura Courier MCP` + `` + `

🚚 Aura Courier MCP v2.6.0

Enterprise Bangladesh courier MCP & Google Maps Platform spatial hub.

` + `

Connect your AI to POST /mcp with Streamable-HTTP.

` + `

Webhooks: POST /webhooks/steadfast · POST /webhooks/pathao

` + `

By Aura Ajentic AI · docs & setup

`); } }); }); if (process.env.NODE_ENV !== "test") { app.listen(PORT, () => { console.log(`Aura Courier MCP v2.6.0 (HTTP) listening on :${PORT} — POST /mcp`); }); }