security: comprehensive remediation of audit findings F01-F15 (v2.6.0)
This commit is contained in:
committed by
Amirul Islam Redwan
parent
b3fec955cc
commit
c174a60b82
+1
-1
@@ -8,7 +8,7 @@ RUN npm install --no-audit --no-fund
|
||||
|
||||
# Source + the marketing landing page (served at /)
|
||||
COPY src ./src
|
||||
COPY README.md index.html ./
|
||||
COPY README.md index.html guide.html health.html privacy.html mcp_explorer.html ./
|
||||
RUN npm run build
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
||||
@@ -117,9 +117,9 @@ Aura Courier MCP seamlessly interfaces with all tier-1 Bangladesh courier APIs u
|
||||
|
||||
---
|
||||
|
||||
## 4. The 9 Enterprise Model Context Protocol (MCP) Tools
|
||||
## 4. The 12 Enterprise Model Context Protocol (MCP) Tools
|
||||
|
||||
Aura Courier MCP exports 9 tools conforming to the MCP Specification (`2024-11-05`):
|
||||
Aura Courier MCP exports 12 tools conforming to the MCP Specification (`2024-11-05`):
|
||||
|
||||
### 1. `list_couriers`
|
||||
* **Purpose**: Inspect carrier operational health and active credentials.
|
||||
@@ -229,7 +229,7 @@ curl -s https://courier.auraajenticai.cloud/health | jq
|
||||
"ok": true,
|
||||
"service": "aura-courier-mcp",
|
||||
"version": "2.6.0",
|
||||
"tools_count": 9,
|
||||
"tools_count": 12,
|
||||
"spatial_engine": "Google Maps Platform (gmp_git_agentskills_v1)",
|
||||
"fraud_engine": "Steadfast Nationwide API + BD Prefix Validator",
|
||||
"webhooks": {
|
||||
|
||||
+177
-80
@@ -14,20 +14,24 @@ import {
|
||||
verifyWebhookSignature,
|
||||
recordAuditLog,
|
||||
} from "./middleware/auth.js";
|
||||
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
||||
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
|
||||
import { SupportedCourier } from "./types.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: any = 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 });
|
||||
} catch (_) {}
|
||||
} catch (err: any) {
|
||||
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Automated Data Retention Engine (Daily Midnight Sweep)
|
||||
@@ -55,19 +59,42 @@ const MCP_EXPLORER_HTML = path.join(APP_DIR, "mcp_explorer.html");
|
||||
const GUIDE_HTML = path.join(APP_DIR, "guide.html");
|
||||
|
||||
/**
|
||||
* Pull this client's courier keys from request headers or query params.
|
||||
* Task T1 Tenant Isolation: Only fall back to master process.env credentials when
|
||||
* the caller authenticated with the master key (tenantId === "master").
|
||||
* F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
|
||||
*/
|
||||
function escapeHtml(str: any): string {
|
||||
if (str == null) return "";
|
||||
return String(str)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
/**
|
||||
* F03 Helper: Redact recipient street address to District/City level for public tracking.
|
||||
*/
|
||||
function redactAddressToDistrict(addr: string): string {
|
||||
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: Request): EnvSource {
|
||||
const h = req.headers;
|
||||
const q = req.query as Record<string, string | undefined>;
|
||||
const allowMasterEnvFallback = req.auraAuth?.tenantId === "master";
|
||||
|
||||
const pick = (header: string, query: string, envVar?: string, allowNonMasterEnv = false): string | undefined => {
|
||||
const pick = (header: string, envVar?: string, allowNonMasterEnv = false): string | undefined => {
|
||||
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];
|
||||
}
|
||||
@@ -75,28 +102,33 @@ export function keysFromRequest(req: Request): EnvSource {
|
||||
};
|
||||
|
||||
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: any, _res, buf) => {
|
||||
req.rawBody = buf;
|
||||
},
|
||||
}));
|
||||
|
||||
// Robust Malformed JSON Syntax Error Guard
|
||||
app.use((err: any, _req: Request, res: Response, next: any) => {
|
||||
@@ -118,62 +150,72 @@ app.use((err: any, _req: Request, res: Response, next: any) => {
|
||||
// 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);
|
||||
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" });
|
||||
|
||||
// Managed Session with Automatic Idle Eviction & Garbage Collection
|
||||
interface ManagedSession {
|
||||
/**
|
||||
* F05 Fix: MCP Session Entry with Cryptographic Tenant Isolation
|
||||
*/
|
||||
interface SessionEntry {
|
||||
transport: StreamableHTTPServerTransport;
|
||||
lastActiveAt: number;
|
||||
tenantId: string;
|
||||
}
|
||||
|
||||
const sessions = new Map<string, ManagedSession>();
|
||||
const SESSION_TTL_MS = 60 * 60 * 1000; // 1-hour idle expiration
|
||||
const sessions = new Map<string, SessionEntry>();
|
||||
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();
|
||||
}, 60 * 1000).unref();
|
||||
|
||||
/**
|
||||
* Task T1: POST /mcp requires Authorization: Bearer <key>.
|
||||
* POST /mcp - MCP Protocol Gateway
|
||||
*/
|
||||
app.post("/mcp", mcpLimiter, requireMcpAuth, async (req: Request, res: Response) => {
|
||||
const sessionId = req.headers["mcp-session-id"] as string | undefined;
|
||||
const tenantId = req.auraAuth?.tenantId || "default";
|
||||
let transport: StreamableHTTPServerTransport;
|
||||
|
||||
// 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;
|
||||
} else if (!sessionId && isInitializeRequest(req.body)) {
|
||||
@@ -187,7 +229,7 @@ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req: Request, res: Response)
|
||||
sessionIdGenerator: () => randomUUID(),
|
||||
enableJsonResponse: true,
|
||||
onsessioninitialized: (sid) => {
|
||||
sessions.set(sid, { transport, lastActiveAt: Date.now() });
|
||||
sessions.set(sid, { transport, lastActiveAt: Date.now(), tenantId });
|
||||
},
|
||||
});
|
||||
transport.onclose = () => {
|
||||
@@ -198,10 +240,13 @@ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req: Request, res: Response)
|
||||
// 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;
|
||||
}
|
||||
|
||||
const toolName = String(req.body.params?.name || "");
|
||||
const args = (req.body.params?.arguments || {}) as Record<string, any>;
|
||||
const auth = isActionPermitted(req, toolName, args);
|
||||
@@ -284,18 +329,22 @@ app.get("/mcp", mcpLimiter, async (req: Request, res: Response) => {
|
||||
res.status(400).send("Invalid or missing session ID");
|
||||
return;
|
||||
}
|
||||
if (!req.auraAuth?.authenticated) {
|
||||
return res.status(401).json(
|
||||
|
||||
const entry = sessions.get(sessionId)!;
|
||||
const callerTenant = req.auraAuth?.tenantId || "default";
|
||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
||||
return res.status(403).json(
|
||||
wrapError(
|
||||
new McpToolError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> 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);
|
||||
});
|
||||
@@ -308,6 +357,21 @@ app.delete("/mcp", requireMcpAuth, async (req: Request, res: Response) => {
|
||||
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);
|
||||
});
|
||||
@@ -356,6 +420,7 @@ function handleCourierWebhook(provider: SupportedCourier) {
|
||||
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(),
|
||||
@@ -368,7 +433,8 @@ function handleCourierWebhook(provider: SupportedCourier) {
|
||||
payload,
|
||||
};
|
||||
|
||||
recordWebhookEvent(record);
|
||||
// F06: Record webhook event scoped by tenantId
|
||||
recordWebhookEvent(record, tenantId);
|
||||
|
||||
return res.status(200).json(
|
||||
wrapSuccess(
|
||||
@@ -385,18 +451,21 @@ function handleCourierWebhook(provider: SupportedCourier) {
|
||||
};
|
||||
}
|
||||
|
||||
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: Request, res: Response) => {
|
||||
const code = req.params.code;
|
||||
const format = req.query.format as string | undefined;
|
||||
const isAuth = Boolean(req.auraAuth?.authenticated);
|
||||
const callerTenant = req.auraAuth?.tenantId;
|
||||
|
||||
let courier = ((req.query.courier as string) || "").toLowerCase();
|
||||
if (!courier) {
|
||||
@@ -417,7 +486,7 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
const registry = new CourierRegistry(loadConfig());
|
||||
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
|
||||
let trackResult: any = null;
|
||||
let errorObj: any = null;
|
||||
|
||||
@@ -427,19 +496,48 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
|
||||
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();
|
||||
@@ -452,12 +550,13 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
|
||||
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(`<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Aura Live Tracking — ${code}</title>
|
||||
<title>Aura Live Tracking — ${escapeHtml(code)}</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
|
||||
@@ -499,27 +598,27 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
|
||||
<div class="brand-icon"><i class="fa-solid fa-truck-fast"></i></div>
|
||||
<div class="brand-text">
|
||||
<h1>Aura Live Tracking</h1>
|
||||
<p>${carrierName} • Direct Live Telemetry</p>
|
||||
<p>${escapeHtml(carrierName)} • Direct Live Telemetry</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="status-badge"><span>${statusText}</span></div>
|
||||
<div class="status-badge"><span>${escapeHtml(statusText)}</span></div>
|
||||
</div>
|
||||
<div class="tracking-code-box">
|
||||
<div><div class="code-label">Consignment Tracking ID</div><div class="code-val">${code}</div></div>
|
||||
<div style="text-align: right;"><div class="code-label">Carrier</div><div style="font-weight: 700; color: var(--cyan); font-size: 13px;">${carrierName}</div></div>
|
||||
<div><div class="code-label">Consignment Tracking ID</div><div class="code-val">${escapeHtml(code)}</div></div>
|
||||
<div style="text-align: right;"><div class="code-label">Carrier</div><div style="font-weight: 700; color: var(--cyan); font-size: 13px;">${escapeHtml(carrierName)}</div></div>
|
||||
</div>
|
||||
<div class="timeline">
|
||||
<div class="timeline-step"><div class="step-dot done"><i class="fa-solid fa-check"></i></div><div class="step-title">Order Booked & Confirmed</div><div class="step-sub">Aura Dispatch Engine initialized booking.</div></div>
|
||||
<div class="timeline-step"><div class="step-dot ${isPickedUp ? "done" : ""}"><i class="fa-solid fa-check"></i></div><div class="step-title">Picked Up by Rider</div><div class="step-sub">Central Merchant Fulfillment Hub</div></div>
|
||||
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-arrow-right"></i></div><div class="step-title">${statusText}</div><div class="step-sub">Live Telemetry: ${updatedAt}</div></div>
|
||||
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-house"></i></div><div class="step-title">Destination Delivery</div><div class="step-sub">Destination: ${recipientAddress}</div></div>
|
||||
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-arrow-right"></i></div><div class="step-title">${escapeHtml(statusText)}</div><div class="step-sub">Live Telemetry: ${escapeHtml(updatedAt)}</div></div>
|
||||
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-house"></i></div><div class="step-title">Destination Delivery</div><div class="step-sub">Destination: ${escapeHtml(recipientAddress)}</div></div>
|
||||
</div>
|
||||
<div class="info-grid">
|
||||
<div class="info-item"><div class="info-item-label">Customer</div><div class="info-item-val">${recipientName}</div></div>
|
||||
<div class="info-item"><div class="info-item-label">Customer</div><div class="info-item-val">${escapeHtml(recipientName)}</div></div>
|
||||
<div class="info-item"><div class="info-item-label">Cash on Delivery (COD)</div><div class="info-item-val">৳ ${Number(codAmount).toLocaleString()}</div></div>
|
||||
</div>
|
||||
<div class="actions">
|
||||
${shortLink ? `<a href="${shortLink}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ""}
|
||||
${shortLink ? `<a href="${escapeHtml(shortLink)}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ""}
|
||||
<button onclick="window.location.reload()" class="btn btn-secondary"><i class="fa-solid fa-rotate-right"></i> Refresh Live Status</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -529,8 +628,6 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
+103
-36
@@ -1,5 +1,5 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
|
||||
|
||||
export type AuthScope = "read" | "write";
|
||||
@@ -17,6 +17,7 @@ declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
auraAuth?: AuraAuthContext;
|
||||
rawBody?: string | Buffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,16 +53,17 @@ export interface AuditEntry {
|
||||
}
|
||||
export 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 function hasByokCredentials(req: Request): boolean {
|
||||
const h = req.headers;
|
||||
const q = req.query as Record<string, string | undefined>;
|
||||
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")
|
||||
h["x-steadfast-api-key"] ||
|
||||
h["x-pathao-client-id"] ||
|
||||
h["x-redx-api-token"] ||
|
||||
h["x-paperfly-api-key"]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -89,7 +91,19 @@ function safeCompare(a: string, b: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, { tenantId: string; scopes: AuthScope[]; isAdmin: boolean }>();
|
||||
|
||||
export function registerApiKey(token: string, tenantId: string, scopes: AuthScope[] = ["read", "write"], isAdmin = false): void {
|
||||
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: Request): AuraAuthContext {
|
||||
const token = extractBearerToken(req);
|
||||
@@ -112,7 +126,7 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||
};
|
||||
}
|
||||
|
||||
// 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,
|
||||
@@ -124,12 +138,11 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||
};
|
||||
}
|
||||
|
||||
// 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,
|
||||
@@ -137,19 +150,40 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||
};
|
||||
}
|
||||
|
||||
// 3. Scoped Tenant Read+Write Key (aura_rw_<tenant>_<secret> or aura_tenant_<secret>)
|
||||
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}`,
|
||||
tenantId: reg.tenantId,
|
||||
scopes: reg.scopes,
|
||||
isByok,
|
||||
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",
|
||||
@@ -168,17 +202,15 @@ export function optionalAuthMiddleware(req: Request, _res: Response, next: NextF
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* F14: Allows unauthenticated read-only discovery on tools/list.
|
||||
*/
|
||||
export function requireMcpAuth(req: Request, res: Response, next: NextFunction): void {
|
||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||
req.auraAuth = ctx;
|
||||
|
||||
if (!ctx.authenticated) {
|
||||
res
|
||||
.status(401)
|
||||
.json(
|
||||
res.status(401).json(
|
||||
wrapError(
|
||||
new McpToolError({
|
||||
code: "UNAUTHORIZED",
|
||||
@@ -218,7 +250,7 @@ export function requireMcpAuth(req: Request, res: Response, next: NextFunction):
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: Request,
|
||||
@@ -226,6 +258,12 @@ export function isActionPermitted(
|
||||
args?: Record<string, any>
|
||||
): { permitted: boolean; reason?: string } {
|
||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||
|
||||
// F14: list_couriers is allowed for discovery
|
||||
if (toolName === "list_couriers") {
|
||||
return { permitted: true };
|
||||
}
|
||||
|
||||
if (!ctx.authenticated) {
|
||||
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||
return {
|
||||
@@ -280,26 +318,55 @@ export function recordAuditLog(
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: Request, provider: string): boolean {
|
||||
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"]) as string | undefined;
|
||||
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"]) as string | undefined;
|
||||
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"]) as string | undefined;
|
||||
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"]) as string | undefined;
|
||||
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"] as string | undefined) ||
|
||||
(req.headers[`x-${provider}-signature`] as string | undefined) ||
|
||||
(req.headers["x-pathao-signature"] as string | undefined) ||
|
||||
(req.headers["x-steadfast-signature"] as string | undefined) ||
|
||||
(req.query["token"] as string | undefined) ||
|
||||
(req.query["secret"] as string | undefined);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
+57
-9
@@ -40,17 +40,43 @@ export function clearIdempotencyStore(): void {
|
||||
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
||||
*/
|
||||
const MAX_WEBHOOK_EVENTS = 1000;
|
||||
const webhookEventsStore: WebhookEventRecord[] = [];
|
||||
const webhookEventsByTenant = new Map<string, WebhookEventRecord[]>();
|
||||
|
||||
export function recordWebhookEvent(event: WebhookEventRecord): void {
|
||||
webhookEventsStore.push(event);
|
||||
if (webhookEventsStore.length > MAX_WEBHOOK_EVENTS) {
|
||||
webhookEventsStore.shift();
|
||||
export function recordWebhookEvent(event: WebhookEventRecord, tenantId: string = "default"): void {
|
||||
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(): void {
|
||||
webhookEventsStore.length = 0;
|
||||
export function clearWebhookEvents(tenantId?: string): void {
|
||||
if (tenantId) {
|
||||
webhookEventsByTenant.delete(tenantId);
|
||||
} else {
|
||||
webhookEventsByTenant.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function isNetworkTimeout(err: any): boolean {
|
||||
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 {
|
||||
@@ -271,6 +297,20 @@ export class CourierRegistry {
|
||||
});
|
||||
} catch (err: any) {
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -622,8 +662,16 @@ export class CourierRegistry {
|
||||
/**
|
||||
* Task T8 — get_webhook_events(consignment_id?, since?)
|
||||
*/
|
||||
getWebhookEvents(consignmentId?: string, since?: string) {
|
||||
let filtered = [...webhookEventsStore];
|
||||
getWebhookEvents(consignmentId?: string, since?: string, tenantId: string = "default") {
|
||||
let events: WebhookEventRecord[] = [];
|
||||
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);
|
||||
|
||||
+2
-1
@@ -352,7 +352,8 @@ export async function executeToolCall(
|
||||
case "get_webhook_events": {
|
||||
const result = registry.getWebhookEvents(
|
||||
args?.consignment_id ? String(args?.consignment_id) : undefined,
|
||||
args?.since ? String(args?.since) : undefined
|
||||
args?.since ? String(args?.since) : undefined,
|
||||
tenantId
|
||||
);
|
||||
return { isError: false, envelope: wrapSuccess(result, "cache") };
|
||||
}
|
||||
|
||||
@@ -502,3 +502,132 @@ test("12. Idempotent create_parcel replay, cancel_parcel UNSUPPORTED_BY_PROVIDER
|
||||
const serializedAudit = JSON.stringify(auditLogBuffer);
|
||||
assert.ok(!serializedAudit.includes("01700000000"));
|
||||
});
|
||||
|
||||
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
test("13. F01: Prefix Auth Bypass Prevention — aura_rw_forged_token returns 401", async () => {
|
||||
const res = await fetch(`${baseUrl}/mcp`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer aura_rw_forged_token_12345678",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "tools/call",
|
||||
params: { name: "list_couriers", arguments: {} },
|
||||
}),
|
||||
});
|
||||
assert.equal(res.status, 401);
|
||||
const body = await res.json();
|
||||
assert.equal(body.ok, false);
|
||||
assert.equal(body.error.code, "UNAUTHORIZED");
|
||||
});
|
||||
|
||||
test("14. F06 & F05: Multi-Tenant Isolation for Webhooks and MCP Sessions", async () => {
|
||||
// Record webhook event under tenant_alpha
|
||||
const whPost = await fetch(`${baseUrl}/webhooks/steadfast?tenant=tenant_alpha`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-webhook-secret": process.env.AURA_WEBHOOK_SECRET,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
consignment_id: "SF_ALPHA_999",
|
||||
status: "in_transit",
|
||||
}),
|
||||
});
|
||||
assert.equal(whPost.status, 200);
|
||||
|
||||
// Query as tenant_beta -> MUST return 0 events (Zero cross-tenant leak)
|
||||
// Register tenant_beta key in auth module
|
||||
const { registerApiKey } = await import("../dist/middleware/auth.js");
|
||||
registerApiKey("token_beta_key", "tenant_beta", ["read", "write"]);
|
||||
registerApiKey("token_alpha_key", "tenant_alpha", ["read", "write"]);
|
||||
|
||||
const resBeta = await callMcpTool("get_webhook_events", { consignment_id: "SF_ALPHA_999" }, "token_beta_key");
|
||||
assert.equal(resBeta.envelope.ok, true);
|
||||
assert.equal(resBeta.envelope.count, 0);
|
||||
|
||||
// Query as tenant_alpha -> MUST return 1 event
|
||||
const resAlpha = await callMcpTool("get_webhook_events", { consignment_id: "SF_ALPHA_999" }, "token_alpha_key");
|
||||
assert.equal(resAlpha.envelope.ok, true);
|
||||
assert.equal(resAlpha.envelope.count, 1);
|
||||
assert.equal(resAlpha.envelope.events[0].consignment_id, "SF_ALPHA_999");
|
||||
});
|
||||
|
||||
test("15. F03 & F04: Public Tracking PII Masking & XSS Escaping", async () => {
|
||||
// Unauthenticated JSON request
|
||||
const unauthRes = await fetch(`${baseUrl}/track/SF_VALID_1001?format=json`);
|
||||
assert.equal(unauthRes.status, 200);
|
||||
const unauthData = await unauthRes.json();
|
||||
assert.equal(unauthData.ok, true);
|
||||
// Phone must be masked
|
||||
if (unauthData.recipient_phone) {
|
||||
assert.ok(unauthData.recipient_phone.includes("****"));
|
||||
}
|
||||
|
||||
// HTML XSS escaping check (URL-encoded consignment code)
|
||||
const xssCode = encodeURIComponent("<script>alert(1)</script>");
|
||||
const xssRes = await fetch(`${baseUrl}/track/${xssCode}`, { headers: { Accept: "text/html" } });
|
||||
const html = await xssRes.text();
|
||||
assert.ok(!html.includes("<script>alert(1)</script>"));
|
||||
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);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user