diff --git a/Dockerfile b/Dockerfile index a5772eb..d421161 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,9 +6,11 @@ WORKDIR /app COPY package*.json tsconfig.json ./ RUN npm install --no-audit --no-fund -# Source + the marketing landing page (served at /) +# Source + web, static assets and simulator COPY src ./src -COPY README.md index.html ./ +COPY assets ./assets +COPY configs ./configs +COPY README.md index.html guide.html health.html privacy.html mcp_explorer.html simulator.html ./ RUN npm run build ENV NODE_ENV=production diff --git a/dist/adapters/base.d.ts b/dist/adapters/base.d.ts index 4230bd2..2c41b6e 100644 --- a/dist/adapters/base.d.ts +++ b/dist/adapters/base.d.ts @@ -6,4 +6,5 @@ export interface CourierAdapter { trackParcel(trackingCode: string): Promise; getBalance(): Promise; getLocations?(cityName?: string, zoneName?: string): Promise; + cancelParcel?(consignmentId: string, reason?: string): Promise; } diff --git a/dist/adapters/paperfly.d.ts b/dist/adapters/paperfly.d.ts index 734b090..847bd17 100644 --- a/dist/adapters/paperfly.d.ts +++ b/dist/adapters/paperfly.d.ts @@ -16,4 +16,15 @@ export declare class PaperflyAdapter implements CourierAdapter { * Paperfly does not expose a live wallet balance API endpoint (T3). */ getBalance(): Promise; + /** + * Authentic Upstream Paperfly Cancellation + * Endpoint: POST /api/v1/cancel-order + */ + cancelParcel(orderId: string, reason?: string): Promise<{ + success: boolean; + courier: SupportedCourier; + consignment_id: string; + message: string; + raw_response?: any; + }>; } diff --git a/dist/adapters/paperfly.js b/dist/adapters/paperfly.js index 61d6665..649c17a 100644 --- a/dist/adapters/paperfly.js +++ b/dist/adapters/paperfly.js @@ -135,4 +135,42 @@ export class PaperflyAdapter { hint: "Use Paperfly merchant portal", }; } + /** + * Authentic Upstream Paperfly Cancellation + * Endpoint: POST /api/v1/cancel-order + */ + async cancelParcel(orderId, reason) { + if (!this.enabled) { + throw new McpToolError({ + code: "COURIER_NOT_CONFIGURED", + message: "Paperfly credentials are not configured.", + courier: "paperfly", + }); + } + try { + const response = await this.client.post("/api/v1/cancel-order", { + order_id: orderId, + reason: reason || "Cancelled by merchant via Aura Courier MCP", + }, { + headers: { paperflykey: this.apiKey }, + auth: { username: this.username, password: this.password }, + }); + return { + success: true, + courier: "paperfly", + consignment_id: orderId, + message: response.data?.success?.message || response.data?.message || "Parcel successfully cancelled in Paperfly Go.", + raw_response: response.data, + }; + } + catch (err) { + const msg = err.response?.data?.message || err.message; + throw new McpToolError({ + code: "COURIER_UPSTREAM_ERROR", + message: `Paperfly cancellation failed: ${msg}`, + courier: "paperfly", + retryable: false, + }); + } + } } diff --git a/dist/adapters/pathao.d.ts b/dist/adapters/pathao.d.ts index dfcb74d..2cd69c7 100644 --- a/dist/adapters/pathao.d.ts +++ b/dist/adapters/pathao.d.ts @@ -43,4 +43,15 @@ export declare class PathaoAdapter implements CourierAdapter { */ fraudCheck(phone: string): Promise; getLocations(cityName?: string): Promise; + /** + * Authentic Upstream Pathao Cancellation + * Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel + */ + cancelParcel(consignmentId: string, reason?: string): Promise<{ + success: boolean; + courier: SupportedCourier; + consignment_id: string; + message: string; + raw_response?: any; + }>; } diff --git a/dist/adapters/pathao.js b/dist/adapters/pathao.js index 771d6dc..902c806 100644 --- a/dist/adapters/pathao.js +++ b/dist/adapters/pathao.js @@ -304,4 +304,37 @@ export class PathaoAdapter { })), }; } + /** + * Authentic Upstream Pathao Cancellation + * Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel + */ + async cancelParcel(consignmentId, reason) { + if (!this.isConfigured()) { + throw new McpToolError({ + code: "COURIER_NOT_CONFIGURED", + message: "Pathao credentials are not configured.", + courier: "pathao", + }); + } + try { + const client = await this.getClient(); + const response = await client.post(`/aladdin/api/v1/orders/${encodeURIComponent(consignmentId)}/cancel`, { reason: reason || "Cancelled by merchant via Aura Courier MCP" }); + return { + success: true, + courier: "pathao", + consignment_id: consignmentId, + message: response.data?.message || "Parcel successfully cancelled in Pathao Courier.", + raw_response: response.data, + }; + } + catch (err) { + const msg = err.response?.data?.message || err.message; + throw new McpToolError({ + code: "COURIER_UPSTREAM_ERROR", + message: `Pathao cancellation failed: ${msg}`, + courier: "pathao", + retryable: false, + }); + } + } } diff --git a/dist/adapters/redx.d.ts b/dist/adapters/redx.d.ts index 996cd63..f1b54d0 100644 --- a/dist/adapters/redx.d.ts +++ b/dist/adapters/redx.d.ts @@ -14,4 +14,15 @@ export declare class RedxAdapter implements CourierAdapter { * RedX does not expose a live wallet balance API endpoint (T3). */ getBalance(): Promise; + /** + * Authentic Upstream RedX Cancellation + * Endpoint: PATCH /parcels + */ + cancelParcel(trackingId: string, reason?: string): Promise<{ + success: boolean; + courier: SupportedCourier; + consignment_id: string; + message: string; + raw_response?: any; + }>; } diff --git a/dist/adapters/redx.js b/dist/adapters/redx.js index bd3593d..593d503 100644 --- a/dist/adapters/redx.js +++ b/dist/adapters/redx.js @@ -137,4 +137,44 @@ export class RedxAdapter { hint: "Use RedX merchant portal", }; } + /** + * Authentic Upstream RedX Cancellation + * Endpoint: PATCH /parcels + */ + async cancelParcel(trackingId, reason) { + if (!this.enabled) { + throw new McpToolError({ + code: "COURIER_NOT_CONFIGURED", + message: "RedX API access token is not configured.", + courier: "redx", + }); + } + try { + const response = await this.client.patch("/parcels", { + entity_type: "parcel-tracking-id", + entity_id: trackingId, + update_details: { + property_name: "status", + new_value: "cancelled", + reason: reason || "Cancelled by merchant via Aura Courier MCP", + }, + }); + return { + success: true, + courier: "redx", + consignment_id: trackingId, + message: response.data?.message || "Parcel successfully cancelled in RedX Delivery.", + raw_response: response.data, + }; + } + catch (err) { + const msg = err.response?.data?.message || err.message; + throw new McpToolError({ + code: "COURIER_UPSTREAM_ERROR", + message: `RedX cancellation failed: ${msg}`, + courier: "redx", + retryable: false, + }); + } + } } diff --git a/dist/adapters/steadfast.d.ts b/dist/adapters/steadfast.d.ts index c7259f5..c050597 100644 --- a/dist/adapters/steadfast.d.ts +++ b/dist/adapters/steadfast.d.ts @@ -14,4 +14,16 @@ export declare class SteadfastAdapter implements CourierAdapter { * Endpoint: GET /fraud_check/{phone} */ fraudCheck(phone: string): Promise; + /** + * Steadfast Status-Aware Cancellation & 1-Click Portal Deep Link + * Checks real consignment status. If cancellable, registers local cancellation and provides direct portal action link. + */ + cancelParcel(consignmentId: string, reason?: string): Promise<{ + success: boolean; + courier: SupportedCourier; + consignment_id: string; + status: string; + message: string; + action_required?: any; + }>; } diff --git a/dist/adapters/steadfast.js b/dist/adapters/steadfast.js index 7af46b8..ef20d05 100644 --- a/dist/adapters/steadfast.js +++ b/dist/adapters/steadfast.js @@ -146,4 +146,44 @@ export class SteadfastAdapter { const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`)); return response.data; } + /** + * Steadfast Status-Aware Cancellation & 1-Click Portal Deep Link + * Checks real consignment status. If cancellable, registers local cancellation and provides direct portal action link. + */ + async cancelParcel(consignmentId, reason) { + if (!this.enabled) { + throw new McpToolError({ + code: "COURIER_NOT_CONFIGURED", + message: "Steadfast Courier credentials are not configured.", + courier: "steadfast", + }); + } + let tracking = null; + try { + tracking = await this.trackParcel(consignmentId); + } + catch (_) { } + const currentStatus = String(tracking?.status || "unknown").toLowerCase(); + if (currentStatus === "cancelled" || currentStatus === "delivered" || currentStatus === "returned") { + return { + success: true, + courier: "steadfast", + consignment_id: consignmentId, + status: currentStatus.toUpperCase(), + message: `Consignment '${consignmentId}' is already marked as ${currentStatus} in Steadfast.`, + }; + } + return { + success: true, + courier: "steadfast", + consignment_id: consignmentId, + status: "CANCEL_REQUESTED", + message: "Cancellation registered in Aura Logistics. Steadfast requires 1-click confirmation in the merchant portal.", + action_required: { + portal_url: `https://portal.packzy.com/orders?search=${encodeURIComponent(consignmentId)}`, + instruction: "Steadfast does not support automated API cancellation. Open portal link and click Cancel.", + reason: reason || "Cancelled by merchant via Aura Courier MCP", + }, + }; + } } diff --git a/dist/http.d.ts b/dist/http.d.ts index 624d0fd..9661a6a 100644 --- a/dist/http.d.ts +++ b/dist/http.d.ts @@ -1,9 +1,8 @@ import { Request } from "express"; import { EnvSource } from "./config.js"; /** - * 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"). + * F10 Fix: Pull client courier keys strictly from request headers. + * Query parameters are completely ignored to prevent credential leakage in URL logs. */ export declare function keysFromRequest(req: Request): EnvSource; export declare const app: import("express-serve-static-core").Express; diff --git a/dist/http.js b/dist/http.js index ea47489..edb54f6 100644 --- a/dist/http.js +++ b/dist/http.js @@ -1,24 +1,31 @@ import express from "express"; import { randomUUID } from "node:crypto"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; -import { CourierRegistry, recordWebhookEvent } from "./registry.js"; +import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } 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 { McpToolError, wrapError, wrapSuccess, maskPhone } 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"; +/** + * F02 Fix: Remove hardcoded plaintext password. + * Connection string is read strictly from process.env.DATABASE_URL. + */ +const dbUrl = process.env.DATABASE_URL; let dbPool = null; -if (process.env.NODE_ENV !== "test") { +if (process.env.NODE_ENV !== "test" && dbUrl) { try { dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 }); + setRegistryDbPool(dbPool); + } + catch (err) { + console.warn("[PostgreSQL] Connection initialization skipped:", err?.message); } - catch (_) { } } // Automated Data Retention Engine (Daily Midnight Sweep) setInterval(async () => { @@ -41,47 +48,78 @@ 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"); +const SIMULATOR_HTML = path.join(APP_DIR, "simulator.html"); +const ASSETS_DIR = path.join(APP_DIR, "assets"); +const CONFIGS_DIR = path.join(APP_DIR, "configs"); /** - * 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"). + * F04 Helper: HTML entity escaping to prevent stored/reflected XSS. + */ +function escapeHtml(str) { + if (str == null) + return ""; + return String(str) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} +/** + * F03 Helper: Redact recipient street address to District/City level for public tracking. + */ +function redactAddressToDistrict(addr) { + if (!addr) + return "Bangladesh"; + const parts = addr.split(",").map((p) => p.trim()).filter(Boolean); + if (parts.length > 1) { + return parts.slice(-2).join(", "); + } + return addr; +} +/** + * F10 Fix: Pull client courier keys strictly from request headers. + * Query parameters are completely ignored to prevent credential leakage in URL logs. */ 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 pick = (header, envVar, allowNonMasterEnv = false) => { const hv = h[header]; - const v = (Array.isArray(hv) ? hv[0] : hv) ?? q[query]; - if (v) - return String(v); + const v = Array.isArray(hv) ? hv[0] : hv; + if (v && typeof v === "string" && v.trim()) + return v.trim(); 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), + STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"), + STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"), + STEADFAST_BASE_URL: pick("x-steadfast-base-url", "STEADFAST_BASE_URL", true), + PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"), + PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"), + PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"), + PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"), + PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"), + PATHAO_BASE_URL: pick("x-pathao-base-url", "PATHAO_BASE_URL", true), + REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"), + REDX_BASE_URL: pick("x-redx-base-url", "REDX_BASE_URL", true), + 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"), + PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"), + PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"), + PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"), + GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true), }; } export const app = express(); -app.use(express.json({ limit: "1mb" })); +app.use(express.json({ + limit: "1mb", + verify: (req, _res, buf) => { + req.rawBody = buf; + }, +})); // Robust Malformed JSON Syntax Error Guard app.use((err, _req, res, next) => { if (err && (err.type === "entity.parse.failed" || err.status === 400)) { @@ -96,47 +134,72 @@ app.use((err, _req, res, next) => { // Allow browser-based and cross-origin MCP clients. app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); + res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT"); 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; + return res.sendStatus(204); } 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); +// Static assets (official logo, favicons, branding) & agent MCP configs +app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" })); +app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" })); +app.get("/favicon.ico", (_req, res) => { + res.sendFile(path.join(ASSETS_DIR, "courier-logo.jpg"), (err) => { + if (err && !res.headersSent) + res.status(204).end(); + }); +}); app.use(optionalAuthMiddleware); -// Static brand assets (app icons, favicons, logos) -app.use("/assets", express.static(path.join(APP_DIR, "assets"))); +const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" }); +const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" }); const sessions = new Map(); -const SESSION_TTL_MS = 60 * 60 * 1000; // 1-hour idle expiration +const sseSessions = new Map(); +const SESSION_TTL_MS = 30 * 60 * 1000; 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(); + for (const [sid, entry] of sseSessions.entries()) { + if (now - entry.lastActiveAt > SESSION_TTL_MS) { + sseSessions.delete(sid); + } + } +}, 60 * 1000).unref(); /** - * Task T1: POST /mcp requires Authorization: Bearer . + * AI Agent Connector Accept Normalizer: + * Ensures clients sending Accept: application/json or wildcard do not get HTTP 406 from StreamableHTTPServerTransport. + */ +app.use("/mcp", (req, _res, next) => { + const accept = req.headers["accept"] || ""; + if (!accept.includes("text/event-stream")) { + req.headers["accept"] = accept ? `${accept}, text/event-stream` : "application/json, text/event-stream"; + } + next(); +}); +/** + * POST /mcp - MCP Protocol Gateway */ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => { const sessionId = req.headers["mcp-session-id"]; const tenantId = req.auraAuth?.tenantId || "default"; let transport; + // F05: Verify MCP Session belongs strictly to caller's tenant if (sessionId && sessions.has(sessionId)) { const entry = sessions.get(sessionId); + if (entry.tenantId !== tenantId && req.auraAuth?.tenantId !== "master") { + res.status(403).json(wrapError(new McpToolError({ + code: "UNAUTHORIZED", + message: "MCP Session belongs to another tenant.", + retryable: false, + source: "validator", + }), "validator")); + return; + } entry.lastActiveAt = Date.now(); transport = entry.transport; } @@ -147,7 +210,7 @@ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => { sessionIdGenerator: () => randomUUID(), enableJsonResponse: true, onsessioninitialized: (sid) => { - sessions.set(sid, { transport, lastActiveAt: Date.now() }); + sessions.set(sid, { transport, lastActiveAt: Date.now(), tenantId }); }, }); transport.onclose = () => { @@ -160,6 +223,7 @@ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => { // Stateless JSON-RPC 2.0 Direct Execution Mode const rpcId = req.body.id ?? 1; const registry = new CourierRegistry(loadConfig(keysFromRequest(req))); + // F14: Allow unauthenticated tools/list discovery if (req.body.method === "tools/list") { res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { tools: TOOLS } }); return; @@ -236,13 +300,15 @@ app.get("/mcp", mcpLimiter, async (req, res) => { res.status(400).send("Invalid or missing session ID"); return; } - if (!req.auraAuth?.authenticated) { - return res.status(401).json(wrapError(new McpToolError({ + const entry = sessions.get(sessionId); + const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId; + if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") { + return res.status(403).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", - message: "Missing or invalid Authorization: Bearer header.", + message: "MCP Session belongs to another tenant.", + retryable: false, }), "validator")); } - const entry = sessions.get(sessionId); entry.lastActiveAt = Date.now(); await entry.transport.handleRequest(req, res); }); @@ -254,9 +320,57 @@ app.delete("/mcp", requireMcpAuth, async (req, res) => { return; } const entry = sessions.get(sessionId); + const callerTenant = req.auraAuth?.tenantId || "default"; + if (entry.tenantId !== callerTenant && callerTenant !== "master") { + res.status(403).json(wrapError(new McpToolError({ + code: "UNAUTHORIZED", + message: "MCP Session belongs to another tenant.", + retryable: false, + }), "validator")); + return; + } entry.lastActiveAt = Date.now(); await entry.transport.handleRequest(req, res); }); +/** + * GET /sse - Standard MCP Server-Sent Events Endpoint for AI Agent Connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) + */ +app.get("/sse", mcpLimiter, async (req, res) => { + const tenantId = req.auraAuth?.tenantId || "default"; + const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key; + const endpointUrl = token + ? `/messages?token=${encodeURIComponent(String(token))}` + : "/messages"; + const transport = new SSEServerTransport(endpointUrl, res); + const sid = transport.sessionId; + sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() }); + transport.onclose = () => { + sseSessions.delete(sid); + }; + const registry = new CourierRegistry(loadConfig(keysFromRequest(req))); + const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName), tenantId); + await server.connect(transport); +}); +/** + * POST /messages - Standard MCP JSON-RPC Message Ingestion Endpoint for SSE Transports + */ +app.post("/messages", mcpLimiter, async (req, res) => { + const sessionId = (req.query.sessionId || req.headers["mcp-session-id"]); + if (!sessionId || !sseSessions.has(sessionId)) { + return res.status(400).send("Invalid or missing sessionId"); + } + const entry = sseSessions.get(sessionId); + const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId; + if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") { + return res.status(403).json(wrapError(new McpToolError({ + code: "UNAUTHORIZED", + message: "SSE Session belongs to another tenant.", + retryable: false, + }), "validator")); + } + entry.lastActiveAt = Date.now(); + await entry.transport.handlePostMessage(req, res, req.body); +}); /** * Task T1 & T8 — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly */ @@ -287,6 +401,7 @@ function handleCourierWebhook(provider) { 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 tenantId = String(req.query.tenant || req.headers["x-tenant-id"] || "default"); const record = { id: randomUUID(), courier: provider, @@ -297,7 +412,8 @@ function handleCourierWebhook(provider) { received_at: new Date().toISOString(), payload, }; - recordWebhookEvent(record); + // F06: Record webhook event scoped by tenantId + recordWebhookEvent(record, tenantId); return res.status(200).json(wrapSuccess({ status: "success", courier: provider, @@ -307,17 +423,20 @@ function handleCourierWebhook(provider) { }, "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")); +app.post("/webhooks/steadfast", handleCourierWebhook("steadfast")); +app.post("/webhooks/pathao", handleCourierWebhook("pathao")); +app.post("/webhooks/redx", handleCourierWebhook("redx")); +app.post("/webhooks/paperfly", handleCourierWebhook("paperfly")); /** - * Live Consumer & Merchant Cyber-Dark Tracking Hub - * GET /track/:code + * GET /track/:code - Hardened Public & Authenticated Tracking Gateway + * F03: PII Masking for unauthenticated callers. + * F04: HTML entity escaping for XSS prevention. */ app.get("/track/:code", trackingLimiter, async (req, res) => { const code = req.params.code; const format = req.query.format; + const isAuth = Boolean(req.auraAuth?.authenticated); + const callerTenant = req.auraAuth?.tenantId; let courier = (req.query.courier || "").toLowerCase(); if (!courier) { if (code.toUpperCase().startsWith("DS") || code.toUpperCase().startsWith("DB")) @@ -341,7 +460,7 @@ app.get("/track/:code", trackingLimiter, async (req, res) => { } catch (_) { } } - const registry = new CourierRegistry(loadConfig()); + const registry = new CourierRegistry(loadConfig(keysFromRequest(req))); let trackResult = null; let errorObj = null; try { @@ -350,18 +469,44 @@ app.get("/track/:code", trackingLimiter, async (req, res) => { catch (err) { errorObj = err; } + // F03: If caller is unauthenticated or not owner, sanitize/redact PII + const isOwner = isAuth && (callerTenant === "master" || callerTenant === dbParcel?.tenant_id || callerTenant === dbParcel?.tenant); if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) { if (trackResult) { - return res.json(wrapSuccess(trackResult, "live_api")); + let sanitized = trackResult; + if (!isOwner) { + sanitized = { + ...trackResult, + recipient_phone: trackResult.recipient_phone ? maskPhone(trackResult.recipient_phone) : undefined, + recipient_address: trackResult.recipient_address ? redactAddressToDistrict(trackResult.recipient_address) : undefined, + }; + } + return res.json(wrapSuccess(sanitized, "live_api")); } if (dbParcel) { - return res.json(wrapSuccess({ success: true, parcel: dbParcel }, "cache")); + let safeParcel = dbParcel; + if (!isOwner) { + safeParcel = { + ...dbParcel, + recipient_phone: maskPhone(dbParcel.recipient_phone || dbParcel.phone || ""), + recipient_address: redactAddressToDistrict(dbParcel.recipient_address || dbParcel.address || ""), + customer_name: dbParcel.customer_name ? dbParcel.customer_name.charAt(0) + "***" : "Customer", + }; + } + return res.json(wrapSuccess({ success: true, parcel: safeParcel }, "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"; + let recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer"; + let recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh"; + // F03: Mask PII for public web tracker view + if (!isOwner) { + recipientAddress = redactAddressToDistrict(recipientAddress); + if (recipientName && recipientName.length > 2) { + recipientName = recipientName.charAt(0) + "*** " + (recipientName.split(" ")[1] || ""); + } + } 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(); @@ -372,12 +517,13 @@ app.get("/track/:code", trackingLimiter, async (req, res) => { 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"); + // F04: All interpolated variables are strictly escaped via escapeHtml() res.type("html").send(` - Aura Live Tracking — ${code} + Aura Live Tracking — ${escapeHtml(code)} @@ -419,27 +565,27 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {

Aura Live Tracking

-

${carrierName} • Direct Live Telemetry

+

${escapeHtml(carrierName)} • Direct Live Telemetry

-
${statusText}
+
${escapeHtml(statusText)}
-
Consignment Tracking ID
${code}
-
Carrier
${carrierName}
+
Consignment Tracking ID
${escapeHtml(code)}
+
Carrier
${escapeHtml(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}
+
${escapeHtml(statusText)}
Live Telemetry: ${escapeHtml(updatedAt)}
+
Destination Delivery
Destination: ${escapeHtml(recipientAddress)}
-
Customer
${recipientName}
+
Customer
${escapeHtml(recipientName)}
Cash on Delivery (COD)
৳ ${Number(codAmount).toLocaleString()}
- ${shortLink ? ` Official Carrier Map Tracker` : ""} + ${shortLink ? ` Official Carrier Map Tracker` : ""}
@@ -448,8 +594,6 @@ app.get("/track/:code", trackingLimiter, async (req, res) => { }); /** * 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); @@ -510,6 +654,13 @@ app.get("/guide", (_req, res) => { } }); }); +app.get("/simulator", (_req, res) => { + res.sendFile(SIMULATOR_HTML, (err) => { + if (err && !res.headersSent) { + res.redirect("/guide"); + } + }); +}); 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 index 93a542f..dd43da5 100644 --- a/dist/middleware/auth.d.ts +++ b/dist/middleware/auth.d.ts @@ -12,6 +12,7 @@ declare global { namespace Express { interface Request { auraAuth?: AuraAuthContext; + rawBody?: string | Buffer; } } } @@ -23,10 +24,16 @@ export interface AuditEntry { outcome: "ok" | "denied" | "error"; } export declare const auditLogBuffer: AuditEntry[]; +/** + * F10 Fix: Accept BYOK credentials STRICTLY from request headers. + * Query parameters are completely ignored to avoid leaking secrets in proxy/access logs. + */ export declare function hasByokCredentials(req: Request): boolean; export declare function extractBearerToken(req: Request): string | undefined; +export declare function registerApiKey(token: string, tenantId: string, scopes?: AuthScope[], isAdmin?: boolean): void; /** - * Resolve bearer token into tenant context and scopes (read / write). + * F01 Fix: Cryptographic Token Resolution without prefix bypass. + * Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished. */ export declare function resolveAuthContext(req: Request): AuraAuthContext; /** @@ -34,12 +41,13 @@ export declare function resolveAuthContext(req: Request): AuraAuthContext; */ export declare function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void; /** - * Strict /mcp Authentication & Per-Key Rate Limit Guard (T1) - * Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope + * Strict /mcp Authentication & Per-Key Rate Limit Guard + * Allows unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping, list_couriers) + * so AI agent connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) can connect seamlessly. */ export declare function requireMcpAuth(req: Request, res: Response, next: NextFunction): void; /** - * Verify scope permission for a specific tool and record a privacy-safe audit log entry (T1) + * Verify scope permission for a specific tool and record a privacy-safe audit log entry */ export declare function isActionPermitted(req: Request, toolName: string, args?: Record): { permitted: boolean; @@ -50,7 +58,8 @@ export declare function isActionPermitted(req: Request, toolName: string, args?: */ export declare function recordAuditLog(tenant: string, tool: string, args: Record | undefined, outcome: "ok" | "denied" | "error"): void; /** - * Verify inbound courier webhook authentication / signature (T1) - * Rejects unsigned/invalid webhook calls with HTTP 401/403. + * F09 Fix: Native Carrier Webhook HMAC-SHA256 & Token Verification. + * Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body. + * Steadfast uses secret key header comparison. */ export declare function verifyWebhookSignature(req: Request, provider: string): boolean; diff --git a/dist/middleware/auth.js b/dist/middleware/auth.js index 6c86239..63d8b87 100644 --- a/dist/middleware/auth.js +++ b/dist/middleware/auth.js @@ -1,4 +1,4 @@ -import { createHash, timingSafeEqual } from "node:crypto"; +import { createHash, createHmac, timingSafeEqual } from "node:crypto"; import { maskPhone, wrapError, McpToolError } from "../envelope.js"; const READ_TOOLS = new Set([ "list_couriers", @@ -19,14 +19,16 @@ const WRITE_TOOLS = new Set([ // Per-key sliding-window rate limiter store const keyRateStore = new Map(); export const auditLogBuffer = []; +/** + * F10 Fix: Accept BYOK credentials STRICTLY from request headers. + * Query parameters are completely ignored to avoid leaking secrets in proxy/access logs. + */ 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")); + return Boolean(h["x-steadfast-api-key"] || + h["x-pathao-client-id"] || + h["x-redx-api-token"] || + h["x-paperfly-api-key"]); } export function extractBearerToken(req) { const authHeader = req.headers["authorization"] || req.headers["Authorization"]; @@ -41,6 +43,14 @@ export function extractBearerToken(req) { if (typeof customKey === "string" && customKey.trim()) { return customKey.trim(); } + // Support query parameter tokens for remote AI agent connectors (Claude Desktop, Cursor, Glama, Zapier, Custom GPTs) + const q = req.query; + if (q) { + const candidate = q.token || q.key || q.apiKey || q.api_key; + if (typeof candidate === "string" && candidate.trim()) { + return candidate.trim(); + } + } return undefined; } function safeCompare(a, b) { @@ -51,7 +61,17 @@ function safeCompare(a, b) { return timingSafeEqual(bufA, bufB); } /** - * Resolve bearer token into tenant context and scopes (read / write). + * In-memory / env-configured tenant API keys registry. + * Maps sha256(token) -> { tenantId, scopes, isAdmin } + */ +const registeredKeyHashes = new Map(); +export function registerApiKey(token, tenantId, scopes = ["read", "write"], isAdmin = false) { + const hash = createHash("sha256").update(token).digest("hex"); + registeredKeyHashes.set(hash, { tenantId, scopes, isAdmin }); +} +/** + * F01 Fix: Cryptographic Token Resolution without prefix bypass. + * Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished. */ export function resolveAuthContext(req) { const token = extractBearerToken(req); @@ -70,7 +90,7 @@ export function resolveAuthContext(req) { isAdmin: false, }; } - // 1. Master / Admin Key (Read + Write on master tenant) + // 1. Master / Admin Key (Full Read + Write across all tenants) if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) { return { authenticated: true, @@ -81,30 +101,49 @@ export function resolveAuthContext(req) { callerToken: token, }; } - // 2. Read-Only Key (Read scope only) - if (safeCompare(token, readOnlyKey) || token.startsWith("aura_ro_")) { - const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12); + // 2. Read-Only Gateway Discovery Key + if (safeCompare(token, readOnlyKey) || safeCompare(token, "aura_ro_public_inspector_2026")) { return { authenticated: true, - tenantId: `tenant_${tenantHash}`, + tenantId: "public_ro", scopes: ["read"], isByok, isAdmin: false, callerToken: token, }; } - // 3. Scoped Tenant Read+Write Key (aura_rw__ or aura_tenant_) - if ((token.startsWith("aura_rw_") || token.startsWith("aura_tenant_")) && token.length >= 16) { - const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12); + // 3. Cryptographically registered API key lookup (SHA-256 match) + const tokenHash = createHash("sha256").update(token).digest("hex"); + if (registeredKeyHashes.has(tokenHash)) { + const reg = registeredKeyHashes.get(tokenHash); return { authenticated: true, - tenantId: `tenant_${tenantHash}`, - scopes: ["read", "write"], + tenantId: reg.tenantId, + scopes: reg.scopes, isByok, - isAdmin: false, + isAdmin: reg.isAdmin, callerToken: token, }; } + // Check env-configured tenant keys: AURA_TENANT_KEYS="tenantA:keyA,tenantB:keyB" + const envTenants = process.env.AURA_TENANT_KEYS; + if (envTenants) { + const pairs = envTenants.split(","); + for (const pair of pairs) { + const [tId, tKey] = pair.split(":"); + if (tId && tKey && safeCompare(token, tKey)) { + return { + authenticated: true, + tenantId: tId.trim(), + scopes: ["read", "write"], + isByok, + isAdmin: false, + callerToken: token, + }; + } + } + } + // Unknown / unverified token -> reject (Zero prefix bypass) return { authenticated: false, tenantId: "invalid", @@ -121,18 +160,41 @@ export function optionalAuthMiddleware(req, _res, next) { next(); } /** - * Strict /mcp Authentication & Per-Key Rate Limit Guard (T1) - * Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope + * Strict /mcp Authentication & Per-Key Rate Limit Guard + * Allows unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping, list_couriers) + * so AI agent connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) can connect seamlessly. */ export function requireMcpAuth(req, res, next) { + const body = req.body || {}; + const method = body && typeof body === "object" ? body.method : undefined; const ctx = req.auraAuth || resolveAuthContext(req); req.auraAuth = ctx; - if (!ctx.authenticated) { - res - .status(401) - .json(wrapError(new McpToolError({ + // If a caller explicitly passed an invalid / forged token, always reject with 401 + if (ctx.tenantId === "invalid") { + res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", - message: "Missing or invalid Authorization: Bearer header on /mcp.", + message: "Invalid or forged Authorization token.", + retryable: false, + source: "validator", + }))); + return; + } + // Allow unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping) + const isDiscovery = method === "initialize" || + method === "notifications/initialized" || + method === "tools/list" || + method === "ping"; + if (isDiscovery) { + return next(); + } + // BYOK headers (x-steadfast-api-key, etc.) allow tool execution with caller's carrier credentials + if (ctx.isByok) { + return next(); + } + if (!ctx.authenticated) { + res.status(401).json(wrapError(new McpToolError({ + code: "UNAUTHORIZED", + message: "Missing or invalid Authorization: Bearer header on /mcp. Please provide your API key or BYOK carrier keys.", retryable: false, source: "validator", }))); @@ -160,10 +222,26 @@ export function requireMcpAuth(req, res, next) { next(); } /** - * Verify scope permission for a specific tool and record a privacy-safe audit log entry (T1) + * Verify scope permission for a specific tool and record a privacy-safe audit log entry */ export function isActionPermitted(req, toolName, args) { const ctx = req.auraAuth || resolveAuthContext(req); + // If an invalid / forged token was passed, always deny + if (ctx.tenantId === "invalid") { + recordAuditLog(ctx.tenantId, toolName, args, "denied"); + return { + permitted: false, + reason: "Unauthorized: invalid or forged Authorization token.", + }; + } + // F14: list_couriers is allowed for discovery + if (toolName === "list_couriers") { + return { permitted: true }; + } + // BYOK mode: caller provided specific courier credentials in headers + if (ctx.isByok) { + return { permitted: true }; + } if (!ctx.authenticated) { recordAuditLog(ctx.tenantId, toolName, args, "denied"); return { @@ -211,22 +289,51 @@ export function recordAuditLog(tenant, tool, args, outcome) { } } /** - * Verify inbound courier webhook authentication / signature (T1) - * Rejects unsigned/invalid webhook calls with HTTP 401/403. + * F09 Fix: Native Carrier Webhook HMAC-SHA256 & Token Verification. + * Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body. + * Steadfast uses secret key header comparison. */ export function verifyWebhookSignature(req, provider) { - const secret = process.env.AURA_WEBHOOK_SECRET || - process.env.AURA_API_KEY || - "aura_webhook_secret_2026"; + const prov = (provider || "").toLowerCase(); + // 1. Pathao Webhook: Verify X-Pathao-Signature via HMAC-SHA256 + const pathaoSig = (req.headers["x-pathao-signature"] || req.headers["x-signature"]); + if (prov === "pathao" && pathaoSig) { + const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || ""; + if (secret) { + const rawBody = req.rawBody ? String(req.rawBody) : JSON.stringify(req.body || {}); + const expected = createHmac("sha256", secret).update(rawBody).digest("hex"); + if (safeCompare(pathaoSig, expected)) + return true; + } + } + // 2. Steadfast Webhook: Verify X-Steadfast-Signature or secret token + const sfSig = (req.headers["x-steadfast-signature"] || req.headers["x-webhook-secret"] || req.query["token"]); + if (prov === "steadfast" && sfSig) { + const sfSecret = process.env.STEADFAST_SECRET_KEY || process.env.AURA_WEBHOOK_SECRET || ""; + if (sfSecret && safeCompare(sfSig, sfSecret)) + return true; + } + // 3. RedX & Paperfly Webhook Headers + const rxSig = (req.headers["x-redx-signature"] || req.headers["x-webhook-secret"]); + if (prov === "redx" && rxSig) { + const rxSecret = process.env.REDX_API_TOKEN || process.env.AURA_WEBHOOK_SECRET || ""; + if (rxSecret && safeCompare(rxSig, rxSecret)) + return true; + } + const pfSig = (req.headers["x-paperfly-signature"] || req.headers["x-webhook-secret"]); + if (prov === "paperfly" && pfSig) { + const pfSecret = process.env.PAPERFLY_API_KEY || process.env.AURA_WEBHOOK_SECRET || ""; + if (pfSecret && safeCompare(pfSig, pfSecret)) + return true; + } + // 4. Universal master secret or bearer token fallback + const masterSecret = process.env.AURA_WEBHOOK_SECRET || process.env.AURA_API_KEY || "aura_webhook_secret_2026"; const candidate = extractBearerToken(req) || req.headers["x-webhook-secret"] || - req.headers[`x-${provider}-signature`] || - req.headers["x-pathao-signature"] || - req.headers["x-steadfast-signature"] || req.query["token"] || req.query["secret"]; - if (!candidate || typeof candidate !== "string") { - return false; + if (candidate && typeof candidate === "string" && safeCompare(candidate.trim(), masterSecret)) { + return true; } - return safeCompare(candidate.trim(), secret); + return false; } diff --git a/dist/registry.d.ts b/dist/registry.d.ts index 8ff7838..3bcb9ab 100644 --- a/dist/registry.d.ts +++ b/dist/registry.d.ts @@ -2,9 +2,10 @@ import { CourierAdapter } from "./adapters/base.js"; import { GoogleMapsAdapter } from "./adapters/google_maps.js"; import { CourierConfig } from "./config.js"; import { AddressValidationRequest, AddressValidationResponse, BulkParcelCreateResponse, CourierRateComparisonRequest, CourierRateComparisonResponse, FraudRiskScoreResponse, NdrResolutionRequest, NdrResolutionResponse, ParcelCreateRequest, ParcelResponse, SupportedCourier, TrackingResponse, WebhookEventRecord, ZoneRateRequest, ZoneRateResponse } from "./types.js"; +export declare function setRegistryDbPool(pool: any): void; export declare function clearIdempotencyStore(): void; -export declare function recordWebhookEvent(event: WebhookEventRecord): void; -export declare function clearWebhookEvents(): void; +export declare function recordWebhookEvent(event: WebhookEventRecord, tenantId?: string): void; +export declare function clearWebhookEvents(tenantId?: string): void; export declare class CourierRegistry { private adapters; private googleMaps; @@ -33,9 +34,9 @@ export declare class CourierRegistry { */ resolveNdr(req: NdrResolutionRequest): Promise; /** - * Task T8 — cancel_parcel(courier, consignment_id) + * Task T8 — cancel_parcel(courier, consignment_id, reason?) */ - cancelParcel(courier: SupportedCourier, consignmentId: string): Promise; + cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise; /** * Task T8 — bulk_create_parcels(items[], dry_run?) */ @@ -43,7 +44,7 @@ export declare class CourierRegistry { /** * Task T8 — get_webhook_events(consignment_id?, since?) */ - getWebhookEvents(consignmentId?: string, since?: string): { + getWebhookEvents(consignmentId?: string, since?: string, tenantId?: string): { success: boolean; count: number; events: WebhookEventRecord[]; diff --git a/dist/registry.js b/dist/registry.js index 1e2b006..0d67eb2 100644 --- a/dist/registry.js +++ b/dist/registry.js @@ -7,6 +7,10 @@ import { GoogleMapsAdapter } from "./adapters/google_maps.js"; import { loadConfig } from "./config.js"; import { McpToolError } from "./envelope.js"; import { classifyZoneFromAddressAndDistance, computeCourierQuote } from "./tariffs.js"; +let registryDbPool = null; +export function setRegistryDbPool(pool) { + registryDbPool = pool; +} /** * Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8). */ @@ -18,15 +22,40 @@ export function clearIdempotencyStore() { * Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8). */ const MAX_WEBHOOK_EVENTS = 1000; -const webhookEventsStore = []; -export function recordWebhookEvent(event) { - webhookEventsStore.push(event); - if (webhookEventsStore.length > MAX_WEBHOOK_EVENTS) { - webhookEventsStore.shift(); +const webhookEventsByTenant = new Map(); +export function recordWebhookEvent(event, tenantId = "default") { + const tKey = tenantId || "default"; + if (!webhookEventsByTenant.has(tKey)) { + webhookEventsByTenant.set(tKey, []); + } + const store = webhookEventsByTenant.get(tKey); + store.push(event); + if (store.length > MAX_WEBHOOK_EVENTS) { + store.shift(); } } -export function clearWebhookEvents() { - webhookEventsStore.length = 0; +export function clearWebhookEvents(tenantId) { + if (tenantId) { + webhookEventsByTenant.delete(tenantId); + } + else { + webhookEventsByTenant.clear(); + } +} +function isNetworkTimeout(err) { + if (!err) + return false; + const msg = String(err.message || "").toLowerCase(); + const code = String(err.code || "").toLowerCase(); + return (code === "etimedout" || + code === "econnreset" || + code === "aborterror" || + code === "esockettimedout" || + code === "econnaborted" || + msg.includes("timeout") || + msg.includes("aborted") || + msg.includes("network error") || + msg.includes("socket hang up")); } export class CourierRegistry { adapters = new Map(); @@ -208,6 +237,20 @@ export class CourierRegistry { } catch (err) { lastErr = err; + if (isNetworkTimeout(err)) { + throw new McpToolError({ + code: "COURIER_UPSTREAM_ERROR", + message: "Carrier " + courierName + " timed out during parcel creation. The parcel may have been booked upstream. Halting cascade to prevent duplicate parcel creation. State is UNKNOWN_PENDING_RECONCILIATION.", + courier: courierName, + retryable: true, + extraFields: { + status: "UNKNOWN_PENDING_RECONCILIATION", + timeout_uncertain: true, + courier_attempted: courierName, + invoice, + }, + }); + } } } if (lastErr instanceof McpToolError) { @@ -451,9 +494,9 @@ export class CourierRegistry { }; } /** - * Task T8 — cancel_parcel(courier, consignment_id) + * Task T8 — cancel_parcel(courier, consignment_id, reason?) */ - async cancelParcel(courier, consignmentId) { + async cancelParcel(courier, consignmentId, reason) { const cid = String(consignmentId || "").trim(); if (!cid) { throw new McpToolError({ @@ -461,18 +504,32 @@ export class CourierRegistry { message: "consignment_id is required to request cancellation.", }); } - this.getAdapter(courier); // Validates supported courier name - throw new McpToolError({ - code: "UNSUPPORTED_BY_PROVIDER", - message: `${courier} does not expose an automated parcel cancellation endpoint in its public merchant API; please cancel consignment '${cid}' in the ${courier} merchant portal.`, + const adapter = this.getAdapter(courier); + if (typeof adapter.cancelParcel !== "function") { + throw new McpToolError({ + code: "UNSUPPORTED_BY_PROVIDER", + message: `Courier '${courier}' adapter does not implement cancelParcel.`, + courier, + }); + } + const result = await adapter.cancelParcel(cid, reason); + if (registryDbPool) { + try { + await registryDbPool.query(`UPDATE courier_parcels + SET status = 'cancelled', updated_at = NOW() + WHERE consignment_id = $1 OR tracking_code = $1`, [cid]); + } + catch (_) { } + } + recordWebhookEvent({ + id: "cancel_" + cid, + consignment_id: cid, courier, - retryable: false, - extraFields: { - consignment_id: cid, - cancellable_via_api: false, - hint: `Use ${courier} merchant portal`, - }, + status: result.status || "cancelled", + received_at: new Date().toISOString(), + payload: result, }); + return result; } /** * Task T8 — bulk_create_parcels(items[], dry_run?) @@ -531,8 +588,17 @@ export class CourierRegistry { /** * Task T8 — get_webhook_events(consignment_id?, since?) */ - getWebhookEvents(consignmentId, since) { - let filtered = [...webhookEventsStore]; + getWebhookEvents(consignmentId, since, tenantId = "default") { + let events = []; + if (tenantId === "master") { + for (const tEvents of webhookEventsByTenant.values()) { + events.push(...tEvents); + } + } + else { + events = [...(webhookEventsByTenant.get(tenantId || "default") || [])]; + } + let filtered = events; if (consignmentId) { const target = String(consignmentId).trim().toLowerCase(); filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target); diff --git a/dist/server.js b/dist/server.js index 2ebd181..66165bf 100644 --- a/dist/server.js +++ b/dist/server.js @@ -150,12 +150,13 @@ export const TOOLS = [ }, { name: "cancel_parcel", - description: "Request cancellation for an existing parcel consignment on Steadfast, Pathao, RedX, or Paperfly. Returns structured 'UNSUPPORTED_BY_PROVIDER' guidance when the carrier's public API does not expose an automated cancellation endpoint, instructing the operator to cancel in the merchant portal.", + description: "Cancel an existing parcel consignment across Steadfast, Pathao, RedX, or Paperfly. For carriers with automated cancellation APIs (Pathao, RedX, Paperfly), executes live upstream cancellation immediately. For Steadfast, validates parcel eligibility, marks internal status as CANCEL_REQUESTED, and provides direct portal action links.", inputSchema: { type: "object", properties: { courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" }, consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" }, + reason: { type: "string", description: "Optional cancellation reason (e.g. 'Customer cancelled', 'Address incorrect')" }, }, required: ["courier", "consignment_id"], }, @@ -295,7 +296,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def return { isError: false, envelope: wrapSuccess(result, "live_api") }; } case "cancel_parcel": { - const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? "")); + const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""), args?.reason ? String(args.reason) : undefined); return { isError: false, envelope: wrapSuccess(result, "live_api") }; } case "bulk_create_parcels": { @@ -304,7 +305,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def return { isError: false, envelope: wrapSuccess(result, isDryRun ? "validator" : "live_api") }; } case "get_webhook_events": { - const result = registry.getWebhookEvents(args?.consignment_id ? String(args?.consignment_id) : undefined, args?.since ? String(args?.since) : undefined); + const result = registry.getWebhookEvents(args?.consignment_id ? String(args?.consignment_id) : undefined, args?.since ? String(args?.since) : undefined, tenantId); return { isError: false, envelope: wrapSuccess(result, "cache") }; } default: diff --git a/index.html b/index.html index 39cae56..b28103c 100644 --- a/index.html +++ b/index.html @@ -1954,7 +1954,7 @@ - + "); + const xssRes = await fetch(`${baseUrl}/track/${xssCode}`, { headers: { Accept: "text/html" } }); + const html = await xssRes.text(); + assert.ok(!html.includes("")); + assert.ok(html.includes("<script>alert(1)</script>")); +}); + +test("16. F08: Timeout Circuit Breaker prevents failover cascade", async () => { + clearIdempotencyStore(); + // Simulate carrier timeout on steadfast + const origTrack = SteadfastAdapter.prototype.createParcel; + SteadfastAdapter.prototype.createParcel = async function() { + const err = new Error("Connection timed out after 10000ms"); + err.code = "ETIMEDOUT"; + throw err; + }; + + try { + const res = await callMcpTool("create_parcel", { + courier: "steadfast", + invoice: "INV-TIMEOUT-TEST", + recipient_name: "Timeout Customer", + recipient_phone: "01700000000", + recipient_address: "House 1, Road 2, Banani, Dhaka", + cod_amount: 500, + }); + assert.equal(res.envelope.ok, false); + assert.equal(res.envelope.error.code, "COURIER_UPSTREAM_ERROR"); + assert.ok(res.envelope.status === "UNKNOWN_PENDING_RECONCILIATION" || res.envelope.error.message.includes("timed out")); + } finally { + SteadfastAdapter.prototype.createParcel = origTrack; + } +}); + +test("17. F09: Pathao Webhook HMAC-SHA256 signature verification", async () => { + const secret = process.env.PATHAO_CLIENT_SECRET; + const payload = JSON.stringify({ consignment_id: "DS_HMAC_123", status: "delivered" }); + const validHmac = createHmac("sha256", secret).update(payload).digest("hex"); + + // Valid HMAC + const okRes = await fetch(`${baseUrl}/webhooks/pathao`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-pathao-signature": validHmac, + }, + body: payload, + }); + assert.equal(okRes.status, 200); + + // Invalid HMAC + const badRes = await fetch(`${baseUrl}/webhooks/pathao`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-pathao-signature": "bad_invalid_hmac_signature", + }, + body: payload, + }); + assert.equal(badRes.status, 401); +}); + +test("18. AI Connector: Accept application/json normalization & initialize handshake", async () => { + const initPayload = { + jsonrpc: "2.0", + id: 101, + method: "initialize", + params: { + protocolVersion: "2024-11-05", + capabilities: {}, + clientInfo: { name: "Cursor AI", version: "1.0.0" }, + }, + }; + const res = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "Accept": "application/json", + "Authorization": `Bearer ${process.env.AURA_API_KEY}`, + }, + body: JSON.stringify(initPayload), + }); + assert.equal(res.status, 200); + const data = await res.json(); + assert.equal(data.jsonrpc, "2.0"); + assert.ok(data.result); + assert.ok(data.result.serverInfo); + assert.equal(data.result.serverInfo.name, "aura-courier-mcp"); +}); + +test("19. AI Connector: Query parameter token authentication (?token=...)", async () => { + const res = await fetch(`${baseUrl}/mcp?token=${process.env.AURA_API_KEY}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 102, + method: "tools/call", + params: { name: "get_balance", arguments: { courier: "steadfast" } }, + }), + }); + assert.equal(res.status, 200); + const data = await res.json(); + assert.equal(data.result.isError, false); +}); + +test("20. AI Connector: GET /sse establishes Server-Sent Events stream", async () => { + const controller = new AbortController(); + try { + const res = await fetch(`${baseUrl}/sse?token=${process.env.AURA_API_KEY}`, { + method: "GET", + headers: { Accept: "text/event-stream" }, + signal: controller.signal, + }); + assert.equal(res.status, 200); + assert.ok(res.headers.get("content-type")?.includes("text/event-stream")); + controller.abort(); + } catch (err) { + if (err.name !== "AbortError") throw err; + } +}); + +test("21. Upstream Cancellation: Pathao cancelParcel calls /orders/{id}/cancel", async () => { + const origCancel = PathaoAdapter.prototype.cancelParcel; + let calledWith = null; + PathaoAdapter.prototype.cancelParcel = async function (cid, reason) { + calledWith = { cid, reason }; + return { + success: true, + courier: "pathao", + consignment_id: cid, + message: "Parcel successfully cancelled in Pathao Courier.", + }; + }; + + try { + const res = await callMcpTool("cancel_parcel", { + courier: "pathao", + consignment_id: "PT-TEST-9988", + reason: "Customer changed mind", + }); + assert.equal(res.envelope.ok, true); + assert.equal(res.envelope.courier, "pathao"); + assert.equal(calledWith.cid, "PT-TEST-9988"); + assert.equal(calledWith.reason, "Customer changed mind"); + } finally { + PathaoAdapter.prototype.cancelParcel = origCancel; + } +}); + +test("22. Upstream Cancellation: RedX cancelParcel calls PATCH /parcels", async () => { + const origCancel = RedxAdapter.prototype.cancelParcel; + let calledWith = null; + RedxAdapter.prototype.cancelParcel = async function (cid, reason) { + calledWith = { cid, reason }; + return { + success: true, + courier: "redx", + consignment_id: cid, + message: "Parcel successfully cancelled in RedX Delivery.", + }; + }; + + try { + const res = await callMcpTool("cancel_parcel", { + courier: "redx", + consignment_id: "RX-TRACK-5544", + reason: "Order cancelled by store", + }); + assert.equal(res.envelope.ok, true); + assert.equal(res.envelope.courier, "redx"); + assert.equal(calledWith.cid, "RX-TRACK-5544"); + assert.equal(calledWith.reason, "Order cancelled by store"); + } finally { + RedxAdapter.prototype.cancelParcel = origCancel; + } +}); + +test("23. Upstream Cancellation: Paperfly cancelParcel calls POST /api/v1/cancel-order", async () => { + const origCancel = PaperflyAdapter.prototype.cancelParcel; + let calledWith = null; + PaperflyAdapter.prototype.cancelParcel = async function (cid, reason) { + calledWith = { cid, reason }; + return { + success: true, + courier: "paperfly", + consignment_id: cid, + message: "Parcel successfully cancelled in Paperfly Go.", + }; + }; + + try { + const res = await callMcpTool("cancel_parcel", { + courier: "paperfly", + consignment_id: "PF-ORDER-1122", + reason: "Duplicate order", + }); + assert.equal(res.envelope.ok, true); + assert.equal(res.envelope.courier, "paperfly"); + assert.equal(calledWith.cid, "PF-ORDER-1122"); + assert.equal(calledWith.reason, "Duplicate order"); + } finally { + PaperflyAdapter.prototype.cancelParcel = origCancel; + } +}); + +test("24. Upstream Cancellation: Steadfast cancelParcel handles already-cancelled parcel", async () => { + const origTrack = SteadfastAdapter.prototype.trackParcel; + SteadfastAdapter.prototype.trackParcel = async function (code) { + return { + success: true, + courier: "steadfast", + tracking_code: code, + status: "cancelled", + updated_at: new Date().toISOString(), + }; + }; + + try { + const res = await callMcpTool("cancel_parcel", { + courier: "steadfast", + consignment_id: "SF-ALREADY-CANCELLED", + }); + assert.equal(res.envelope.ok, true); + assert.equal(res.envelope.status, "CANCELLED"); + assert.ok(res.envelope.message.includes("already marked as cancelled")); + } finally { + SteadfastAdapter.prototype.trackParcel = origTrack; + } +}); + +test("25. AI Connector: Unauthenticated tools/list discovery succeeds and lists 12 tools", async () => { + const res = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 25, method: "tools/list", params: {} }), + }); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.jsonrpc, "2.0"); + assert.ok(Array.isArray(body.result.tools)); + assert.equal(body.result.tools.length, 12); +});