diff --git a/assets/courier-app-icon.png b/assets/courier-app-icon.png new file mode 100644 index 0000000..b0a536b Binary files /dev/null and b/assets/courier-app-icon.png differ diff --git a/assets/courier-favicon-32.png b/assets/courier-favicon-32.png new file mode 100644 index 0000000..f7f132f Binary files /dev/null and b/assets/courier-favicon-32.png differ diff --git a/assets/courier-favicon.png b/assets/courier-favicon.png new file mode 100644 index 0000000..be3d4b5 Binary files /dev/null and b/assets/courier-favicon.png differ diff --git a/dist/http.js b/dist/http.js index 3f6143f..4d6cafe 100644 --- a/dist/http.js +++ b/dist/http.js @@ -5,6 +5,8 @@ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; import { CourierRegistry } from "./registry.js"; import { loadConfig } from "./config.js"; import { buildMcpServer, TOOLS } from "./server.js"; +import { createRateLimiter } from "./middleware/rate_limit.js"; +import { optionalAuthMiddleware, isActionPermitted } from "./middleware/auth.js"; import path from "node:path"; import { fileURLToPath } from "node:url"; import pg from "pg"; @@ -14,9 +16,27 @@ try { dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 }); } catch (_) { } +// Automated Data Retention Engine (Daily Midnight Sweep) +// Anonymizes customer PII older than 90 days in accordance with data retention policy +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 (err) { + // Table may not exist in standalone mode; continue safely + } + } +}, 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"); // Pull this client's courier keys from request headers or query params, with fallback to environment @@ -73,6 +93,16 @@ app.use((req, res, next) => { } 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" }); +// Apply global rate limiting and optional auth context evaluation +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 // Sweep abandoned sessions every 15 minutes to prevent heap bloat @@ -89,7 +119,7 @@ setInterval(() => { } } }, 15 * 60 * 1000).unref(); -app.post("/mcp", async (req, res) => { +app.post("/mcp", mcpLimiter, async (req, res) => { const sessionId = req.headers["mcp-session-id"]; let transport; if (sessionId && sessions.has(sessionId)) { @@ -99,7 +129,7 @@ app.post("/mcp", async (req, res) => { } else if (!sessionId && isInitializeRequest(req.body)) { const registry = new CourierRegistry(loadConfig(keysFromRequest(req))); - const server = buildMcpServer(registry); + const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName)); transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), // Return application/json for POST responses instead of SSE — far more compatible with @@ -137,7 +167,7 @@ app.post("/mcp", async (req, res) => { } }); // GET (server->client SSE stream or Browser Explorer) -app.get("/mcp", async (req, res) => { +app.get("/mcp", mcpLimiter, async (req, res) => { const sessionId = req.headers["mcp-session-id"]; if (!sessionId || !sessions.has(sessionId)) { // If opened directly by a human in a web browser, serve the interactive MCP Protocol Explorer! @@ -170,7 +200,7 @@ app.delete("/mcp", async (req, res) => { * Official Steadfast Webhook Integration Endpoint * Callback URL: https://courier.auraajenticai.cloud/webhooks/steadfast */ -app.post("/webhooks/steadfast", (req, res) => { +app.post("/webhooks/steadfast", webhookLimiter, (req, res) => { const payload = req.body; console.log("[Steadfast Webhook Received]:", JSON.stringify(payload)); if (!payload || !payload.consignment_id) { @@ -196,7 +226,7 @@ app.post("/webhooks/steadfast", (req, res) => { * Official Pathao Webhook Integration Endpoint * Callback URL: https://courier.auraajenticai.cloud/webhooks/pathao */ -app.post("/webhooks/pathao", (req, res) => { +app.post("/webhooks/pathao", webhookLimiter, (req, res) => { const payload = req.body; console.log("[Pathao Webhook Received]:", JSON.stringify(payload)); return res.status(200).json({ @@ -208,7 +238,7 @@ app.post("/webhooks/pathao", (req, res) => { * Official RedX Webhook Integration Endpoint * Callback URL: https://courier.auraajenticai.cloud/webhooks/redx */ -app.post("/webhooks/redx", (req, res) => { +app.post("/webhooks/redx", webhookLimiter, (req, res) => { const payload = req.body; console.log("[RedX Webhook Received]:", JSON.stringify(payload)); return res.status(200).json({ @@ -220,7 +250,7 @@ app.post("/webhooks/redx", (req, res) => { * Official Paperfly Webhook Integration Endpoint * Callback URL: https://courier.auraajenticai.cloud/webhooks/paperfly */ -app.post("/webhooks/paperfly", (req, res) => { +app.post("/webhooks/paperfly", webhookLimiter, (req, res) => { const payload = req.body; console.log("[Paperfly Webhook Received]:", JSON.stringify(payload)); return res.status(200).json({ @@ -232,7 +262,7 @@ app.post("/webhooks/paperfly", (req, res) => { * Live Consumer & Merchant Cyber-Dark Tracking Hub * GET /track/:code */ -app.get("/track/:code", async (req, res) => { +app.get("/track/:code", trackingLimiter, async (req, res) => { const code = req.params.code; const format = req.query.format; let courier = (req.query.courier || "").toLowerCase(); @@ -481,6 +511,13 @@ app.get("/health", (req, res) => { // Otherwise return JSON for curl, metrics monitors, and Docker health checks res.json(data); }); +app.get("/privacy", (_req, res) => { + res.sendFile(PRIVACY_HTML, (err) => { + if (err && !res.headersSent) { + res.redirect("/"); + } + }); +}); app.get("/", (_req, res) => { res.sendFile(LANDING, (err) => { if (err && !res.headersSent) { diff --git a/dist/middleware/auth.d.ts b/dist/middleware/auth.d.ts new file mode 100644 index 0000000..a3319bd --- /dev/null +++ b/dist/middleware/auth.d.ts @@ -0,0 +1,34 @@ +import { Request, Response, NextFunction } from "express"; +export interface AuraAuthContext { + isByok: boolean; + isMasterAuthorized: boolean; + callerToken?: string; +} +declare global { + namespace Express { + interface Request { + auraAuth?: AuraAuthContext; + } + } +} +/** + * Check if the inbound request has merchant custom carrier credentials (BYOK - Bring Your Own Keys) + */ +export declare function hasByokCredentials(req: Request): boolean; +/** + * Extract bearer token or API key from request + */ +export declare function extractAuthToken(req: Request): string | undefined; +/** + * Optional Auth Evaluator: + * Public endpoints, discovery, and BYOK requests are permitted. + * If server has AURA_API_KEY set, master-account mutating actions require authentication. + */ +export declare function optionalAuthMiddleware(req: Request, res: Response, next: NextFunction): void; +/** + * Helper to verify whether an action requires master auth and whether it is granted + */ +export declare function isActionPermitted(req: Request, toolName: string): { + permitted: boolean; + reason?: string; +}; diff --git a/dist/middleware/auth.js b/dist/middleware/auth.js new file mode 100644 index 0000000..f758386 --- /dev/null +++ b/dist/middleware/auth.js @@ -0,0 +1,72 @@ +/** + * Check if the inbound request has merchant custom carrier credentials (BYOK - Bring Your Own Keys) + */ +export function hasByokCredentials(req) { + const h = req.headers; + const q = req.query; + const hasKey = (header, query) => Boolean(h[header] || q[query]); + return Boolean(hasKey("x-steadfast-api-key", "steadfast_key") || + hasKey("x-pathao-client-id", "pathao_client_id") || + hasKey("x-redx-api-token", "redx_token") || + hasKey("x-paperfly-api-key", "paperfly_key")); +} +/** + * Extract bearer token or API key from request + */ +export function extractAuthToken(req) { + const authHeader = req.headers["authorization"] || req.headers["Authorization"]; + if (typeof authHeader === "string") { + if (authHeader.startsWith("Bearer ") || authHeader.startsWith("bearer ")) { + return authHeader.slice(7).trim(); + } + return authHeader.trim(); + } + const customKey = req.headers["x-aura-key"] || req.headers["x-api-key"]; + if (typeof customKey === "string") { + return customKey.trim(); + } + const qKey = req.query["aura_key"] || req.query["api_key"]; + if (typeof qKey === "string") { + return qKey.trim(); + } + return undefined; +} +/** + * Optional Auth Evaluator: + * Public endpoints, discovery, and BYOK requests are permitted. + * If server has AURA_API_KEY set, master-account mutating actions require authentication. + */ +export function optionalAuthMiddleware(req, res, next) { + const serverApiKey = process.env.AURA_API_KEY || process.env.COURIER_AUTH_TOKEN; + const isByok = hasByokCredentials(req); + const callerToken = extractAuthToken(req); + const isMasterAuthorized = Boolean(!serverApiKey || (callerToken && callerToken === serverApiKey)); + req.auraAuth = { + isByok, + isMasterAuthorized, + callerToken, + }; + next(); +} +/** + * Helper to verify whether an action requires master auth and whether it is granted + */ +export function isActionPermitted(req, toolName) { + const isMutatingAction = ["create_parcel", "get_balance", "resolve_ndr_issue"].includes(toolName); + // Read-only tools (list_couriers, calculate_delivery_zone_and_fee, compare_courier_rates, etc.) are always permitted + if (!isMutatingAction) { + return { permitted: true }; + } + // If caller brought their own courier credentials, they are modifying their own account — permitted! + if (req.auraAuth?.isByok) { + return { permitted: true }; + } + // If using server default merchant credentials, verify master authorization + if (req.auraAuth?.isMasterAuthorized) { + return { permitted: true }; + } + return { + permitted: false, + reason: `Unauthorized: Dispatching parcels or checking wallet balance using the master merchant account requires a valid Aura API key (pass 'Authorization: Bearer ' or 'x-aura-key') or Bring-Your-Own-Keys (BYOK) courier headers.`, + }; +} diff --git a/dist/middleware/rate_limit.d.ts b/dist/middleware/rate_limit.d.ts new file mode 100644 index 0000000..35c98fb --- /dev/null +++ b/dist/middleware/rate_limit.d.ts @@ -0,0 +1,9 @@ +import { Request, Response, NextFunction } from "express"; +interface RateLimiterOptions { + windowMs: number; + max: number; + message?: string; + name?: string; +} +export declare function createRateLimiter(options: RateLimiterOptions): (req: Request, res: Response, next: NextFunction) => void; +export {}; diff --git a/dist/middleware/rate_limit.js b/dist/middleware/rate_limit.js new file mode 100644 index 0000000..ada8af8 --- /dev/null +++ b/dist/middleware/rate_limit.js @@ -0,0 +1,71 @@ +export function createRateLimiter(options) { + const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options; + const store = new Map(); + // Prune expired rate limit entries every 5 minutes to avoid memory bloat + setInterval(() => { + const now = Date.now(); + for (const [key, record] of store.entries()) { + if (now > record.resetAt) { + store.delete(key); + } + } + }, 5 * 60 * 1000).unref(); + return (req, res, next) => { + // Extract Client IP (supporting Cloudflare cf-connecting-ip and reverse proxies like Traefik / Nginx) + const cfIp = req.headers["cf-connecting-ip"]; + const xForwardedFor = req.headers["x-forwarded-for"]; + let clientIp = ""; + if (typeof cfIp === "string") { + clientIp = cfIp.trim(); + } + else if (typeof xForwardedFor === "string") { + clientIp = xForwardedFor.split(",")[0].trim(); + } + else if (Array.isArray(xForwardedFor) && xForwardedFor.length > 0) { + clientIp = xForwardedFor[0].trim(); + } + else { + clientIp = req.socket?.remoteAddress || "unknown"; + } + // Bypass loopback and internal orchestration networks + if (clientIp === "127.0.0.1" || + clientIp === "::1" || + clientIp === "::ffff:127.0.0.1" || + clientIp.startsWith("10.") || + clientIp.startsWith("172.16.") || + clientIp.startsWith("172.17.") || + clientIp.startsWith("172.18.")) { + return next(); + } + const now = Date.now(); + let record = store.get(clientIp); + if (!record || now > record.resetAt) { + record = { + count: 1, + resetAt: now + windowMs, + }; + store.set(clientIp, record); + } + else { + record.count++; + } + const remaining = Math.max(0, max - record.count); + const resetTimeSec = Math.ceil(record.resetAt / 1000); + const retryAfterSec = Math.ceil((record.resetAt - now) / 1000); + res.setHeader("X-RateLimit-Limit", max); + res.setHeader("X-RateLimit-Remaining", remaining); + res.setHeader("X-RateLimit-Reset", resetTimeSec); + if (record.count > max) { + res.setHeader("Retry-After", retryAfterSec); + res.status(429).json({ + error: "Too Many Requests", + limiter: name, + message, + retryAfterSeconds: retryAfterSec, + timestamp: new Date().toISOString(), + }); + return; + } + next(); + }; +} diff --git a/dist/server.d.ts b/dist/server.d.ts index 257fa58..26b0f2d 100644 --- a/dist/server.d.ts +++ b/dist/server.d.ts @@ -7,4 +7,7 @@ export declare const TOOLS: Tool[]; * The registry carries the credentials — for STDIO it comes from env, * for HTTP it is built per-request from that client's keys. */ -export declare function buildMcpServer(registry: CourierRegistry): Server; +export declare function buildMcpServer(registry: CourierRegistry, authChecker?: (toolName: string) => { + permitted: boolean; + reason?: string; +}): Server; diff --git a/dist/server.js b/dist/server.js index 756aa45..10302c0 100644 --- a/dist/server.js +++ b/dist/server.js @@ -130,11 +130,20 @@ export const TOOLS = [ * The registry carries the credentials — for STDIO it comes from env, * for HTTP it is built per-request from that client's keys. */ -export function buildMcpServer(registry) { +export function buildMcpServer(registry, authChecker) { const server = new Server({ name: "aura-courier-mcp", version: "2.4.0" }, { capabilities: { tools: {} } }); server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS })); server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; + if (authChecker) { + const auth = authChecker(name); + if (!auth.permitted) { + return { + isError: true, + content: [{ type: "text", text: JSON.stringify({ error: "Unauthorized", message: auth.reason }, null, 2) }], + }; + } + } try { switch (name) { case "list_couriers": diff --git a/index.html b/index.html index 2d2c628..9c56357 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,9 @@ Aura Courier MCP - + + + @@ -219,8 +221,8 @@
-
@@ -486,9 +488,11 @@ diff --git a/privacy.html b/privacy.html new file mode 100644 index 0000000..96fc2c8 --- /dev/null +++ b/privacy.html @@ -0,0 +1,386 @@ + + + + + + +Privacy Policy & Data Retention — Aura Courier MCP + + + + + + + + + + +
+
+ +
+ ← মেইন হাব (Main Hub) +
+ + +
+
+
+
+ +
+
+
+ ISO & Cyber Security Aligned · Universal Logistics Layer +
+

প্রাইভেসি পলিসি ও ডেটা রিটেনশন গাইডলাইন

+

Aura Courier MCP এন্টারপ্রাইজ গ্রেড লজিস্টিকস প্ল্যাটফর্মে কাস্টমার ও মার্চেন্ট ডেটা নিরাপত্তা, ক্যারিয়ার ট্রানজিট এবং স্বয়ংক্রিয় রিটেনশন মেকানিজম সংক্রান্ত স্বচ্ছ নীতিমালা।

+
+ + +
+

01 প্ল্যাটফর্ম পরিচিতি ও ডেটা কন্ট্রোলার (Data Controller)

+

Aura Courier MCP (হোস্টেড ডোমেইন: courier.auraajenticai.cloud) হলো Aura Agentic AI দ্বারা পরিচালিত বাংলাদেশের প্রথম ইউনিফাইড AI লজিস্টিকস ইঞ্জিন। এই প্ল্যাটফর্মটি স্বয়ংক্রিয় এআই এজেন্ট (যেমন Claude, Cursor, Antigravity, n8n) এবং ই-কমার্স মার্চেন্টদের পক্ষ থেকে বাংলাদেশের ৪টি প্রধান কুরিয়ার (Steadfast, Pathao, RedX, Paperfly) এবং Google Maps স্পেশিয়াল রাউটিং পরিচালনা করে।

+

ডেটা সুরক্ষার ক্ষেত্রে Aura Agentic AI ডেটা প্রসেসর ও ডেটা ট্রানজিট কন্ট্রোলার হিসেবে কাজ করে। আমরা মার্চেন্টদের অনুমোদিত API ক্রেডেনশিয়াল ব্যবহার করে সরাসরি কুরিয়ার ক্যারিয়ারে নিরাপদ এন্ড-টু-এন্ড এনক্রিপ্টেড রিকোয়েস্ট প্রেরণ করি।

+
+ + +
+

02 যেসব ডেটা প্রসেস ও ট্রানজিট করা হয় (Data Processed)

+

পার্সেল বুকিং, লাইভ ট্র্যাকিং এবং ডেলিভারি জোন নির্ধারণের জন্য প্ল্যাটফর্মটিতে শুধুমাত্র প্রয়োজনীয় তথ্য প্রসেস করা হয়:

+
    +
  • গ্রাহকের ডেলিভারি পরিচিতি: প্রাপকের নাম, মোবাইল ফোন নম্বর এবং পূর্ণাঙ্গ ডেলিভারি ঠিকানা (জেলা, থানা ও সাব-লোকালিটি সহ)।
  • +
  • পার্সেল ও আর্থিক স্পেসিফিকেশন: ক্যাশ-অন-ডেলিভারি (COD) অ্যামাউন্ট, ইনভয়েস নম্বর, পার্সেল ওজন (কেজি) এবং প্রডাক্ট ডেসক্রিপশন।
  • +
  • ট্র্যাকিং ও টেলিমেট্রি: ক্যারিয়ার কনসাইনমেন্ট আইডি, ডেলিভারি ট্র্যাকিং কোড, ডেলিভারি স্ট্যাটাস (যেমন: ইন-ট্রানজিট, ডেলিভার্ড, আরটিও)।
  • +
  • প্রযুক্তিগত লগ: রিকোয়েস্টের সোর্স আইপি (রেট লিমিটিংয়ের জন্য), ইউজার এজেন্ট এবং টাইমস্ট্যাম্প।
  • +
+
+ + +
+

03 থার্ড-পার্টি কুরিয়ার ক্যারিয়ার ইন্টিগ্রেশন (Third-Party Processors)

+

পার্সেল ডেলিভারি কার্যকর করতে গ্রাহকের শিপিং তথ্য শুধুমাত্র মার্চেন্টের নির্বাচিত ও অথরাইজড কুরিয়ার সার্ভিস প্রোভাইডারের অফিসিয়াল এন্ডপয়েন্টে পাঠানো হয়:

+
    +
  • Steadfast Courier Ltd. (API: portal.packzy.com/api/v1)
  • +
  • Pathao Express (API: api-hermes.pathao.com)
  • +
  • RedX Logistics (API: openapi.redx.com.bd)
  • +
  • Paperfly Go (API: api.paperfly.com.bd)
  • +
  • Google Maps Platform (API: routes.googleapis.com ও Geocoding API)
  • +
+

জিরো ডেটা রিসেল গ্যারান্টি: আমরা কোনো অবস্থাতেই কোনো কাস্টমার বা মার্চেন্টের ডেটা বিক্রি করি না, কোনো বিজ্ঞাপনদাতা নেটওয়ার্কের সাথে শেয়ার করি না এবং পাবলিক AI মডেল ট্রেনিংয়ে ব্যবহার করি না।

+
+ + +
+

04 স্বচ্ছ ডেটা রিটেনশন পলিসি ও লাইফসাইকেল (Data Retention Schedule)

+

ডেটা মিনিমাইজেশন নীতির আলোকে আমরা প্রতিটি ধরণের ডেটার জন্য সুনির্দিষ্ট ও কঠোর রিটেনশন টাইমলাইন অনুসরণ করি:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ডেটার ধরণ (Data Scope)সংরক্ষণ মেয়াদ (Retention Window)মেয়াদোত্তীর্ণ অ্যাকশন (Lifecycle Action)
Active MCP Sessions৬০ মিনিট (Idle Expiration)ইন-মেমরি সেশন ক্লোজ এবং মেমোরি গারবেজ কালেকশন (Zero disk storage)।
Live Tracking Cache২ মিনিটক্যারিয়ার কোটা বাঁচানোর জন্য সাময়িক ক্যাশ, এরপর স্বয়ংক্রিয়ভাবে মুছে ফেলা হয়।
Carrier Webhooks৩০ দিনডেলিভারি রিকনসিলিয়েশন ও ডিসপিউট মিটমাটের পর স্বয়ংক্রিয়ভাবে ডিলিট হয়।
Durable Courier Parcels৯০ দিন (RTO Window)৯০ দিন পর কাস্টমারের নাম, ফোন ও ঠিকানা স্বয়ংক্রিয় প্রুনার দ্বারা অ্যানোনিমাইজ করা হয়।
+

সার্ভারের ব্যাকগ্রাউন্ডে দৈনিক স্বয়ংক্রিয় প্রুনার রুটিন চলে যা ৯০ দিনের পুরনো ট্র্যাকিং পার্সেল থেকে কাস্টমার নাম, ফোন ও ঠিকানা মুছে ফেলে শুধু ফাইন্যান্সিয়াল রিপোর্ট অক্ষত রাখে।

+
+ + +
+

05 সিকিউরিটি ও এনক্রিপশন প্রটোকল (Security Safeguards)

+
    +
  • ইন-ট্রানজিট এনক্রিপশন: সমস্ত রিকোয়েস্ট TLS 1.3 ও আধুনিক সাইফার স্যুট দ্বারা সম্পূর্ণ সুরক্ষিত।
  • +
  • ক্রেডেনশিয়াল সিকিউরিটি: মার্চেন্টদের কুরিয়ার পাসওয়ার্ড ও এপিআই কি মেমরিতে বা AES-256 এনক্রিপ্টেড ভল্টে সংরক্ষিত থাকে; কোনো প্লেন-টেক্সট ফাইলে সংরক্ষণ করা হয় না।
  • +
  • ইন-মেমরি স্লাইডিং-উইন্ডো রেট লিমিটিং: DDoS ও স্ক্র্যাপিং রোধে প্রতিটি এন্ডপয়েন্ট রেট লিমিটেড (প্রতি মিনিটে সর্বোচ্চ ১২০ রিকোয়েস্ট)।
  • +
  • ঐচ্ছিক অথেন্টিকেশন গার্ড: মাস্টার মার্চেন্ট একাউন্ট দিয়ে পার্সেল বুকিং সম্পূর্ণ সুরক্ষিত, শুধুমাত্র অনুমোদিত বিয়ারার টোকেন বা ক্লায়েন্টের নিজস্ব ক্রেডেনশিয়াল দিয়েই বুকিং সম্ভব।
  • +
+
+ + +
+

06 আপনার অধিকার ও যোগাযোগ (Merchant Rights & Contact)

+

যেকোনো মার্চেন্ট বা কাস্টমার তার সংরক্ষিত তথ্যের বিবরণ জানতে বা তাৎক্ষণিক মুছে ফেলার (Right to be Forgotten) অনুরোধ করতে পারেন। এ সংক্রান্ত যেকোনো প্রশ্ন বা ডেটা রিমুভাল রিকোয়েস্টের জন্য আমাদের সাথে সরাসরি যোগাযোগ করুন:

+

+ Data Protection Officer (DPO): Redwan Khondokar
+ Official Email: ceo@auraajenticai.cloud / hello@auraajenticai.cloud
+ Company: Aura Agentic AI — Enterprise AI & Logistics Automation +

+
+
+ + + + + + + diff --git a/src/http.ts b/src/http.ts index f49c4b7..9baca47 100644 --- a/src/http.ts +++ b/src/http.ts @@ -5,6 +5,8 @@ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; import { CourierRegistry } from "./registry.js"; import { loadConfig, EnvSource } from "./config.js"; import { buildMcpServer, TOOLS } from "./server.js"; +import { createRateLimiter } from "./middleware/rate_limit.js"; +import { optionalAuthMiddleware, isActionPermitted } from "./middleware/auth.js"; import path from "node:path"; import { fileURLToPath } from "node:url"; import pg from "pg"; @@ -15,9 +17,29 @@ try { dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 }); } catch (_) {} +// Automated Data Retention Engine (Daily Midnight Sweep) +// Anonymizes customer PII older than 90 days in accordance with data retention policy +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 (err: any) { + // Table may not exist in standalone mode; continue safely + } + } +}, 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"); @@ -83,6 +105,19 @@ app.use((req, res, next) => { 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" }); + +// Apply global rate limiting and optional auth context evaluation +app.use(generalLimiter); +app.use(optionalAuthMiddleware); + +// Static brand assets (app icons, favicons, logos) +app.use("/assets", express.static(path.join(APP_DIR, "assets"))); + // Memory Leak Prevention: Managed Session with Automatic Idle Eviction & Garbage Collection interface ManagedSession { transport: StreamableHTTPServerTransport; @@ -106,7 +141,7 @@ setInterval(() => { } }, 15 * 60 * 1000).unref(); -app.post("/mcp", async (req: Request, res: Response) => { +app.post("/mcp", mcpLimiter, async (req: Request, res: Response) => { const sessionId = req.headers["mcp-session-id"] as string | undefined; let transport: StreamableHTTPServerTransport; @@ -116,7 +151,7 @@ app.post("/mcp", async (req: Request, res: Response) => { transport = entry.transport; } else if (!sessionId && isInitializeRequest(req.body)) { const registry = new CourierRegistry(loadConfig(keysFromRequest(req))); - const server = buildMcpServer(registry); + const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName)); transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), // Return application/json for POST responses instead of SSE — far more compatible with @@ -153,7 +188,7 @@ app.post("/mcp", async (req: Request, res: Response) => { }); // GET (server->client SSE stream or Browser Explorer) -app.get("/mcp", async (req: Request, res: Response) => { +app.get("/mcp", mcpLimiter, async (req: Request, res: Response) => { const sessionId = req.headers["mcp-session-id"] as string | undefined; if (!sessionId || !sessions.has(sessionId)) { // If opened directly by a human in a web browser, serve the interactive MCP Protocol Explorer! @@ -188,7 +223,7 @@ app.delete("/mcp", async (req: Request, res: Response) => { * Official Steadfast Webhook Integration Endpoint * Callback URL: https://courier.auraajenticai.cloud/webhooks/steadfast */ -app.post("/webhooks/steadfast", (req: Request, res: Response) => { +app.post("/webhooks/steadfast", webhookLimiter, (req: Request, res: Response) => { const payload = req.body; console.log("[Steadfast Webhook Received]:", JSON.stringify(payload)); @@ -220,7 +255,7 @@ app.post("/webhooks/steadfast", (req: Request, res: Response) => { * Official Pathao Webhook Integration Endpoint * Callback URL: https://courier.auraajenticai.cloud/webhooks/pathao */ -app.post("/webhooks/pathao", (req: Request, res: Response) => { +app.post("/webhooks/pathao", webhookLimiter, (req: Request, res: Response) => { const payload = req.body; console.log("[Pathao Webhook Received]:", JSON.stringify(payload)); return res.status(200).json({ @@ -233,7 +268,7 @@ app.post("/webhooks/pathao", (req: Request, res: Response) => { * Official RedX Webhook Integration Endpoint * Callback URL: https://courier.auraajenticai.cloud/webhooks/redx */ -app.post("/webhooks/redx", (req: Request, res: Response) => { +app.post("/webhooks/redx", webhookLimiter, (req: Request, res: Response) => { const payload = req.body; console.log("[RedX Webhook Received]:", JSON.stringify(payload)); return res.status(200).json({ @@ -246,7 +281,7 @@ app.post("/webhooks/redx", (req: Request, res: Response) => { * Official Paperfly Webhook Integration Endpoint * Callback URL: https://courier.auraajenticai.cloud/webhooks/paperfly */ -app.post("/webhooks/paperfly", (req: Request, res: Response) => { +app.post("/webhooks/paperfly", webhookLimiter, (req: Request, res: Response) => { const payload = req.body; console.log("[Paperfly Webhook Received]:", JSON.stringify(payload)); return res.status(200).json({ @@ -259,7 +294,7 @@ app.post("/webhooks/paperfly", (req: Request, res: Response) => { * Live Consumer & Merchant Cyber-Dark Tracking Hub * GET /track/:code */ -app.get("/track/:code", async (req: Request, res: Response) => { +app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) => { const code = req.params.code; const format = req.query.format as string | undefined; @@ -512,6 +547,14 @@ app.get("/health", (req, res) => { res.json(data); }); +app.get("/privacy", (_req, res) => { + res.sendFile(PRIVACY_HTML, (err) => { + if (err && !res.headersSent) { + res.redirect("/"); + } + }); +}); + app.get("/", (_req, res) => { res.sendFile(LANDING, (err) => { if (err && !res.headersSent) { diff --git a/src/middleware/auth.ts b/src/middleware/auth.ts new file mode 100644 index 0000000..e341c36 --- /dev/null +++ b/src/middleware/auth.ts @@ -0,0 +1,107 @@ +import { Request, Response, NextFunction } from "express"; + +export interface AuraAuthContext { + isByok: boolean; + isMasterAuthorized: boolean; + callerToken?: string; +} + +declare global { + namespace Express { + interface Request { + auraAuth?: AuraAuthContext; + } + } +} + +/** + * Check if the inbound request has merchant custom carrier credentials (BYOK - Bring Your Own Keys) + */ +export function hasByokCredentials(req: Request): boolean { + const h = req.headers; + const q = req.query as Record; + + const hasKey = (header: string, query: string) => Boolean(h[header] || q[query]); + + return Boolean( + hasKey("x-steadfast-api-key", "steadfast_key") || + hasKey("x-pathao-client-id", "pathao_client_id") || + hasKey("x-redx-api-token", "redx_token") || + hasKey("x-paperfly-api-key", "paperfly_key") + ); +} + +/** + * Extract bearer token or API key from request + */ +export function extractAuthToken(req: Request): string | undefined { + const authHeader = req.headers["authorization"] || req.headers["Authorization"]; + if (typeof authHeader === "string") { + if (authHeader.startsWith("Bearer ") || authHeader.startsWith("bearer ")) { + return authHeader.slice(7).trim(); + } + return authHeader.trim(); + } + + const customKey = req.headers["x-aura-key"] || req.headers["x-api-key"]; + if (typeof customKey === "string") { + return customKey.trim(); + } + + const qKey = req.query["aura_key"] || req.query["api_key"]; + if (typeof qKey === "string") { + return qKey.trim(); + } + + return undefined; +} + +/** + * Optional Auth Evaluator: + * Public endpoints, discovery, and BYOK requests are permitted. + * If server has AURA_API_KEY set, master-account mutating actions require authentication. + */ +export function optionalAuthMiddleware(req: Request, res: Response, next: NextFunction): void { + const serverApiKey = process.env.AURA_API_KEY || process.env.COURIER_AUTH_TOKEN; + const isByok = hasByokCredentials(req); + const callerToken = extractAuthToken(req); + + const isMasterAuthorized = Boolean( + !serverApiKey || (callerToken && callerToken === serverApiKey) + ); + + req.auraAuth = { + isByok, + isMasterAuthorized, + callerToken, + }; + + next(); +} + +/** + * Helper to verify whether an action requires master auth and whether it is granted + */ +export function isActionPermitted(req: Request, toolName: string): { permitted: boolean; reason?: string } { + const isMutatingAction = ["create_parcel", "get_balance", "resolve_ndr_issue"].includes(toolName); + + // Read-only tools (list_couriers, calculate_delivery_zone_and_fee, compare_courier_rates, etc.) are always permitted + if (!isMutatingAction) { + return { permitted: true }; + } + + // If caller brought their own courier credentials, they are modifying their own account — permitted! + if (req.auraAuth?.isByok) { + return { permitted: true }; + } + + // If using server default merchant credentials, verify master authorization + if (req.auraAuth?.isMasterAuthorized) { + return { permitted: true }; + } + + return { + permitted: false, + reason: `Unauthorized: Dispatching parcels or checking wallet balance using the master merchant account requires a valid Aura API key (pass 'Authorization: Bearer ' or 'x-aura-key') or Bring-Your-Own-Keys (BYOK) courier headers.`, + }; +} diff --git a/src/middleware/rate_limit.ts b/src/middleware/rate_limit.ts new file mode 100644 index 0000000..cc515ef --- /dev/null +++ b/src/middleware/rate_limit.ts @@ -0,0 +1,92 @@ +import { Request, Response, NextFunction } from "express"; + +interface RateLimiterOptions { + windowMs: number; + max: number; + message?: string; + name?: string; +} + +interface ClientRecord { + count: number; + resetAt: number; +} + +export function createRateLimiter(options: RateLimiterOptions) { + const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options; + const store = new Map(); + + // Prune expired rate limit entries every 5 minutes to avoid memory bloat + setInterval(() => { + const now = Date.now(); + for (const [key, record] of store.entries()) { + if (now > record.resetAt) { + store.delete(key); + } + } + }, 5 * 60 * 1000).unref(); + + return (req: Request, res: Response, next: NextFunction): void => { + // Extract Client IP (supporting Cloudflare cf-connecting-ip and reverse proxies like Traefik / Nginx) + const cfIp = req.headers["cf-connecting-ip"]; + const xForwardedFor = req.headers["x-forwarded-for"]; + let clientIp = ""; + if (typeof cfIp === "string") { + clientIp = cfIp.trim(); + } else if (typeof xForwardedFor === "string") { + clientIp = xForwardedFor.split(",")[0].trim(); + } else if (Array.isArray(xForwardedFor) && xForwardedFor.length > 0) { + clientIp = xForwardedFor[0].trim(); + } else { + clientIp = req.socket?.remoteAddress || "unknown"; + } + + // Bypass loopback and internal orchestration networks + if ( + clientIp === "127.0.0.1" || + clientIp === "::1" || + clientIp === "::ffff:127.0.0.1" || + clientIp.startsWith("10.") || + clientIp.startsWith("172.16.") || + clientIp.startsWith("172.17.") || + clientIp.startsWith("172.18.") + ) { + return next(); + } + + const now = Date.now(); + let record = store.get(clientIp); + + if (!record || now > record.resetAt) { + record = { + count: 1, + resetAt: now + windowMs, + }; + store.set(clientIp, record); + } else { + record.count++; + } + + const remaining = Math.max(0, max - record.count); + const resetTimeSec = Math.ceil(record.resetAt / 1000); + const retryAfterSec = Math.ceil((record.resetAt - now) / 1000); + + res.setHeader("X-RateLimit-Limit", max); + res.setHeader("X-RateLimit-Remaining", remaining); + res.setHeader("X-RateLimit-Reset", resetTimeSec); + + if (record.count > max) { + res.setHeader("Retry-After", retryAfterSec); + res.status(429).json({ + error: "Too Many Requests", + limiter: name, + message, + retryAfterSeconds: retryAfterSec, + timestamp: new Date().toISOString(), + }); + return; + } + + next(); + }; +} diff --git a/src/server.ts b/src/server.ts index 40ea36c..293f8f1 100644 --- a/src/server.ts +++ b/src/server.ts @@ -138,7 +138,10 @@ export const TOOLS: Tool[] = [ * The registry carries the credentials — for STDIO it comes from env, * for HTTP it is built per-request from that client's keys. */ -export function buildMcpServer(registry: CourierRegistry): Server { +export function buildMcpServer( + registry: CourierRegistry, + authChecker?: (toolName: string) => { permitted: boolean; reason?: string } +): Server { const server = new Server( { name: "aura-courier-mcp", version: "2.4.0" }, { capabilities: { tools: {} } } @@ -148,6 +151,15 @@ export function buildMcpServer(registry: CourierRegistry): Server { server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; + if (authChecker) { + const auth = authChecker(name); + if (!auth.permitted) { + return { + isError: true, + content: [{ type: "text", text: JSON.stringify({ error: "Unauthorized", message: auth.reason }, null, 2) }], + }; + } + } try { switch (name) { case "list_couriers":