4 Commits

33 changed files with 2175 additions and 497 deletions
+18 -12
View File
@@ -1,20 +1,26 @@
# ============================================================================== # ==============================================================================
# Aura Courier MCP (v2.6.1) — Environment Variable Template (NO REAL SECRETS!) # Aura Courier MCP (v2.7.2) — Environment Variable Template (NO REAL SECRETS!)
# ============================================================================== # ==============================================================================
# PRODUCTION RULE: # PRODUCTION RULE:
# - NEVER commit a real `.env` file or bake `.env` into Docker images. # - NEVER commit a real `.env` file or bake `.env` into Docker images.
# - Store all real production values in Coolify -> Application -> Environment # - Generate every auth/OAuth/webhook secret with: `openssl rand -hex 32`
# Variables (`coolify-db`, App 25: `ix4jsg321uqfrko9qrrq4k7m`), NOT copied # - Store all production values in your secret manager / deployment environment.
# inside `/app/.env` inside the container. # - Server FAILS CLOSED on startup if required secrets are missing or weak.
# ============================================================================== # ==============================================================================
# --- Server & Auth --- # --- Server & Auth (ALL REQUIRED IN PRODUCTION — MIN 24 CHARS HIGH ENTROPY) ---
NODE_ENV=production NODE_ENV=production
PORT=80 PORT=80
HOST=0.0.0.0 HOST=0.0.0.0
DATABASE_URL=postgresql://postgres:CHANGE_ME@ernix50nvuq9ur9jy8na8tgr:5432/aura_auth DATABASE_URL=postgresql://db_user:REPLACE_ME@db.internal:5432/aura_courier
AURA_API_KEY=aura_live_mcp_master_key_2026 AURA_API_KEY=<generate-with-openssl-rand-hex-32>
AURA_READONLY_KEY=aura_ro_public_inspector_2026 AURA_ADMIN_KEY=<generate-with-openssl-rand-hex-32>
AURA_READONLY_KEY=<generate-with-openssl-rand-hex-24>
AURA_WEBHOOK_SECRET=<generate-with-openssl-rand-hex-32>
AURA_OAUTH_SECRET=<generate-with-openssl-rand-hex-32>
AURA_SSO_JWT_SECRET=<generate-with-openssl-rand-hex-32>
# Optional comma-separated allowed browser origins (defaults to * for MCP clients)
# CORS_ORIGIN=https://client.example.com,https://admin.example.com
# --- Steadfast Courier --- # --- Steadfast Courier ---
STEADFAST_API_KEY=your_steadfast_api_key STEADFAST_API_KEY=your_steadfast_api_key
@@ -38,10 +44,10 @@ REDX_PICKUP_STORE_ID=your_redx_pickup_store_id
PAPERFLY_API_KEY=your_paperfly_header_key PAPERFLY_API_KEY=your_paperfly_header_key
PAPERFLY_USERNAME=your_paperfly_username PAPERFLY_USERNAME=your_paperfly_username
PAPERFLY_PASSWORD=your_paperfly_password PAPERFLY_PASSWORD=your_paperfly_password
PAPERFLY_STORE_NAME=Snehalata PAPERFLY_STORE_NAME=your_store_name
PAPERFLY_BASE_URL=https://api.paperfly.com.bd PAPERFLY_BASE_URL=https://api.paperfly.com.bd
# --- Google Maps & Webhook Bridges --- # --- Google Maps & Optional Bridges ---
GOOGLE_MAPS_API_KEY=your_google_maps_api_key GOOGLE_MAPS_API_KEY=your_google_maps_api_key
SNEHALATA_VERIFY_KEY_URL=https://www.snehalata.com/api/mcp/verify-key # SNEHALATA_VERIFY_KEY_URL=https://your-store.example.com/api/mcp/verify-key
SNEHALATA_WEBHOOK_URL=https://www.snehalata.com/api/webhooks/pathao # SNEHALATA_WEBHOOK_URL=https://your-store.example.com/api/webhooks/pathao
+13 -4
View File
@@ -7,8 +7,8 @@ on:
branches: [ main ] branches: [ main ]
jobs: jobs:
build: build-and-security-gate:
name: Build & Quality Check name: Build, Security Tests, Audit & Docker Smoke
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout repository - name: Checkout repository
@@ -23,8 +23,17 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: Build TypeScript - name: TypeScript type-check & build
run: npm run build run: npx tsc --noEmit && npm run build
- name: Run full regression + adversarial security test suite
run: npm test
- name: Production dependency security audit gate (critical/high)
run: npm audit --omit=dev --audit-level=high
- name: Docker image build verification
run: docker build -t aura-courier-mcp:ci .
- name: Verify Dist Artifacts - name: Verify Dist Artifacts
run: ls -la dist/ run: ls -la dist/
+1
View File
@@ -17,6 +17,7 @@ ENV NODE_ENV=production
# Listen on 80 so it matches the existing app/proxy port (no label change needed) # Listen on 80 so it matches the existing app/proxy port (no label change needed)
ENV PORT=80 ENV PORT=80
EXPOSE 80 EXPOSE 80
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 CMD wget -qO- http://127.0.0.1:80/health || exit 1
# Remote HTTP MCP endpoint: GET / = landing, POST /mcp = MCP. # Remote HTTP MCP endpoint: GET / = landing, POST /mcp = MCP.
# The npm/npx build stays STDIO (dist/index.js, unchanged). # The npm/npx build stays STDIO (dist/index.js, unchanged).
+1
View File
@@ -17,6 +17,7 @@ export class PaperflyAdapter {
this.client = axios.create({ this.client = axios.create({
baseURL: baseUrl, baseURL: baseUrl,
timeout: 15000, timeout: 15000,
maxRedirects: 0,
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
}); });
} }
+2 -1
View File
@@ -36,7 +36,7 @@ export class PathaoAdapter {
username: this.username, username: this.username,
password: this.password, password: this.password,
grant_type: "password", grant_type: "password",
}); }, { timeout: 12000, maxRedirects: 0 });
this.accessToken = response.data.access_token; this.accessToken = response.data.access_token;
this.tokenExpiresAt = now + (response.data.expires_in || 3600) * 1000; this.tokenExpiresAt = now + (response.data.expires_in || 3600) * 1000;
return this.accessToken; return this.accessToken;
@@ -50,6 +50,7 @@ export class PathaoAdapter {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
timeout: 12000, timeout: 12000,
maxRedirects: 0,
}); });
} }
/** /**
+1
View File
@@ -15,6 +15,7 @@ export class RedxAdapter {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
timeout: 15000, timeout: 15000,
maxRedirects: 0,
}); });
} }
isConfigured() { isConfigured() {
+1
View File
@@ -15,6 +15,7 @@ export class SteadfastAdapter {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
timeout: 10000, timeout: 10000,
maxRedirects: 0,
}); });
} }
isConfigured() { isConfigured() {
+7 -1
View File
@@ -34,9 +34,15 @@ export interface CourierConfig {
}; };
} }
export type EnvSource = Record<string, string | undefined>; export type EnvSource = Record<string, string | undefined>;
export declare const ALLOWED_CARRIER_HOSTS: Record<"steadfast" | "pathao" | "redx" | "paperfly", readonly string[]>;
/**
* P1-01 Anti-SSRF Guard: Enforce HTTPS-only + strict official carrier hostname allowlist.
* Blocks http:, IP literals (IPv4/IPv6), localhost/.internal, credentials-in-URL, and non-standard ports.
*/
export declare function validateCarrierBaseUrl(provider: "steadfast" | "pathao" | "redx" | "paperfly", candidate: string | undefined, defaultUrl: string): string;
/** /**
* Build a CourierConfig from a key/value source. * Build a CourierConfig from a key/value source.
* Defaults to process.env (used by the STDIO/npx entrypoint); the HTTP * Defaults to process.env (used by the STDIO/npx entrypoint); the HTTP
* entrypoint passes a per-request map built from that client's headers/query. * entrypoint passes a per-request map built from authenticated tenant/BYOK headers.
*/ */
export declare function loadConfig(src?: EnvSource): CourierConfig; export declare function loadConfig(src?: EnvSource): CourierConfig;
+42 -5
View File
@@ -9,10 +9,47 @@ if (process.env.NODE_ENV !== "test") {
else { else {
dotenv.config(); dotenv.config();
} }
export const ALLOWED_CARRIER_HOSTS = {
steadfast: ["portal.packzy.com", "portal.steadfast.com.bd"],
pathao: ["api-hermes.pathao.com", "courier-api-sandbox.pathao.com"],
redx: ["openapi.redx.com.bd", "sandbox.redx.com.bd"],
paperfly: ["api.paperfly.com.bd"],
};
/**
* P1-01 Anti-SSRF Guard: Enforce HTTPS-only + strict official carrier hostname allowlist.
* Blocks http:, IP literals (IPv4/IPv6), localhost/.internal, credentials-in-URL, and non-standard ports.
*/
export function validateCarrierBaseUrl(provider, candidate, defaultUrl) {
const raw = (candidate || "").trim();
if (!raw)
return defaultUrl;
let parsed;
try {
parsed = new URL(raw);
}
catch {
throw new Error(`Invalid ${provider} base URL format.`);
}
if (parsed.protocol !== "https:") {
throw new Error(`Disallowed ${provider} base URL protocol '${parsed.protocol}' (HTTPS required).`);
}
if (parsed.username || parsed.password) {
throw new Error(`Disallowed credentials in ${provider} base URL.`);
}
if (parsed.port && parsed.port !== "443") {
throw new Error(`Disallowed non-standard port '${parsed.port}' in ${provider} base URL.`);
}
const host = parsed.hostname.toLowerCase();
const allowed = ALLOWED_CARRIER_HOSTS[provider];
if (!allowed.includes(host)) {
throw new Error(`Disallowed ${provider} base URL host '${host}'. Permitted official hosts: ${allowed.join(", ")}.`);
}
return parsed.toString().replace(/\/+$/, "");
}
/** /**
* Build a CourierConfig from a key/value source. * Build a CourierConfig from a key/value source.
* Defaults to process.env (used by the STDIO/npx entrypoint); the HTTP * Defaults to process.env (used by the STDIO/npx entrypoint); the HTTP
* entrypoint passes a per-request map built from that client's headers/query. * entrypoint passes a per-request map built from authenticated tenant/BYOK headers.
*/ */
export function loadConfig(src = process.env) { export function loadConfig(src = process.env) {
const steadfastApiKey = src.STEADFAST_API_KEY || ""; const steadfastApiKey = src.STEADFAST_API_KEY || "";
@@ -24,7 +61,7 @@ export function loadConfig(src = process.env) {
steadfast: { steadfast: {
apiKey: steadfastApiKey, apiKey: steadfastApiKey,
secretKey: steadfastSecretKey, secretKey: steadfastSecretKey,
baseUrl: src.STEADFAST_BASE_URL || "https://portal.packzy.com/api/v1", baseUrl: validateCarrierBaseUrl("steadfast", src.STEADFAST_BASE_URL, "https://portal.packzy.com/api/v1"),
enabled: Boolean(steadfastApiKey && steadfastSecretKey), enabled: Boolean(steadfastApiKey && steadfastSecretKey),
}, },
pathao: { pathao: {
@@ -33,12 +70,12 @@ export function loadConfig(src = process.env) {
username: src.PATHAO_USERNAME || "", username: src.PATHAO_USERNAME || "",
password: src.PATHAO_PASSWORD || "", password: src.PATHAO_PASSWORD || "",
storeId: src.PATHAO_STORE_ID || "", storeId: src.PATHAO_STORE_ID || "",
baseUrl: src.PATHAO_BASE_URL || "https://api-hermes.pathao.com", baseUrl: validateCarrierBaseUrl("pathao", src.PATHAO_BASE_URL, "https://api-hermes.pathao.com"),
enabled: Boolean(pathaoClientId && pathaoClientSecret), enabled: Boolean(pathaoClientId && pathaoClientSecret),
}, },
redx: { redx: {
apiToken: src.REDX_API_TOKEN || "", apiToken: src.REDX_API_TOKEN || "",
baseUrl: src.REDX_BASE_URL || "https://openapi.redx.com.bd/v1.0.0-beta", baseUrl: validateCarrierBaseUrl("redx", src.REDX_BASE_URL, "https://openapi.redx.com.bd/v1.0.0-beta"),
pickupStoreId: src.REDX_PICKUP_STORE_ID || "", pickupStoreId: src.REDX_PICKUP_STORE_ID || "",
enabled: Boolean(src.REDX_API_TOKEN), enabled: Boolean(src.REDX_API_TOKEN),
}, },
@@ -47,7 +84,7 @@ export function loadConfig(src = process.env) {
username: src.PAPERFLY_USERNAME || "", username: src.PAPERFLY_USERNAME || "",
password: src.PAPERFLY_PASSWORD || "", password: src.PAPERFLY_PASSWORD || "",
storeName: src.PAPERFLY_STORE_NAME || "", storeName: src.PAPERFLY_STORE_NAME || "",
baseUrl: src.PAPERFLY_BASE_URL || "https://api.paperfly.com.bd", baseUrl: validateCarrierBaseUrl("paperfly", src.PAPERFLY_BASE_URL, "https://api.paperfly.com.bd"),
enabled: Boolean(src.PAPERFLY_API_KEY && src.PAPERFLY_USERNAME), enabled: Boolean(src.PAPERFLY_API_KEY && src.PAPERFLY_USERNAME),
}, },
googleMaps: { googleMaps: {
+4 -2
View File
@@ -1,8 +1,10 @@
import { type Express, type Request } from "express"; import { type Express, type Request } from "express";
import { EnvSource } from "./config.js"; import { EnvSource } from "./config.js";
/** /**
* F10 Fix: Pull client courier keys strictly from request headers. * P0-03 & P1-01 Fix: Pull authenticated tenant BYOK keys strictly from request headers.
* Query parameters are completely ignored to prevent credential leakage in URL logs. * Arbitrary caller base-URL headers are validated against the official HTTPS carrier allowlist
* (rejecting any http:, IP literal, private/internal host, or unlisted domain).
*/ */
export declare function keysFromRequest(req: Request): EnvSource; export declare function keysFromRequest(req: Request): EnvSource;
export declare const app: Express; export declare const app: Express;
export declare function clearWebhookReplayCache(): void;
+174 -48
View File
@@ -1,15 +1,15 @@
import express from "express"; import express from "express";
import { randomUUID } from "node:crypto"; import { createHash, randomUUID } from "node:crypto";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js"; import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
import { loadConfig } from "./config.js"; import { loadConfig, validateCarrierBaseUrl } from "./config.js";
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js"; import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
import { createRateLimiter } from "./middleware/rate_limit.js"; import { createRateLimiter } from "./middleware/rate_limit.js";
import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, verifyWebhookSignature, recordAuditLog, initDynamicAuthStore, upsertDynamicKeyHash, setTenantDynamicKeyStatus, listDynamicKeySummaries, } from "./middleware/auth.js"; import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, authenticateWebhook, validateSecurityConfig, recordAuditLog, initDynamicAuthStore, upsertDynamicKeyHash, setTenantDynamicKeyStatus, listDynamicKeySummaries, } from "./middleware/auth.js";
import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js"; import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js";
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js"; import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
import { APP_VERSION } from "./version.js"; import { APP_VERSION } from "./version.js";
import path from "node:path"; import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
@@ -81,14 +81,12 @@ function redactAddressToDistrict(addr) {
return addr; return addr;
} }
/** /**
* F10 Fix: Pull client courier keys strictly from request headers. * P0-03 & P1-01 Fix: Pull authenticated tenant BYOK keys strictly from request headers.
* Query parameters are completely ignored to prevent credential leakage in URL logs. * Arbitrary caller base-URL headers are validated against the official HTTPS carrier allowlist
* (rejecting any http:, IP literal, private/internal host, or unlisted domain).
*/ */
export function keysFromRequest(req) { export function keysFromRequest(req) {
const h = req.headers; const h = req.headers;
// Strict Multi-Tenant & BYOK Isolation:
// If caller explicitly sends any BYOK courier headers (isByok === true), NEVER fall back to
// platform master courier env keys so vendor/merchant BYOK credentials never mix with central keys.
const isByokRequest = Boolean(req.auraAuth?.isByok || const isByokRequest = Boolean(req.auraAuth?.isByok ||
h["x-steadfast-api-key"] || h["x-steadfast-api-key"] ||
h["x-pathao-client-id"] || h["x-pathao-client-id"] ||
@@ -108,23 +106,33 @@ export function keysFromRequest(req) {
} }
return undefined; return undefined;
}; };
// Validate any caller-supplied base URL headers immediately against the strict SSRF allowlist
const pickBaseUrl = (provider, header, envVar, defaultUrl) => {
const hv = h[header];
const headerVal = (Array.isArray(hv) ? hv[0] : hv) || "";
if (typeof headerVal === "string" && headerVal.trim()) {
return validateCarrierBaseUrl(provider, headerVal.trim(), defaultUrl);
}
return validateCarrierBaseUrl(provider, process.env[envVar], defaultUrl);
};
return { return {
STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"), STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"),
STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"), STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"),
STEADFAST_BASE_URL: pick("x-steadfast-base-url", "STEADFAST_BASE_URL", true), STEADFAST_BASE_URL: pickBaseUrl("steadfast", "x-steadfast-base-url", "STEADFAST_BASE_URL", "https://portal.packzy.com/api/v1"),
PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"), PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"),
PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"), PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"),
PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"), PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"),
PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"), PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"),
PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"), PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"),
PATHAO_BASE_URL: pick("x-pathao-base-url", "PATHAO_BASE_URL", true), PATHAO_BASE_URL: pickBaseUrl("pathao", "x-pathao-base-url", "PATHAO_BASE_URL", "https://api-hermes.pathao.com"),
REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"), REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"),
REDX_BASE_URL: pick("x-redx-base-url", "REDX_BASE_URL", true), REDX_BASE_URL: pickBaseUrl("redx", "x-redx-base-url", "REDX_BASE_URL", "https://openapi.redx.com.bd/v1.0.0-beta"),
REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "REDX_PICKUP_STORE_ID"), 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_API_KEY: pick("x-paperfly-api-key", "PAPERFLY_API_KEY"),
PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"), PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"),
PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"), PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"),
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"), PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"),
PAPERFLY_BASE_URL: pickBaseUrl("paperfly", "x-paperfly-base-url", "PAPERFLY_BASE_URL", "https://api.paperfly.com.bd"),
GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true), GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true),
}; };
} }
@@ -148,17 +156,56 @@ app.use((err, _req, res, next) => {
} }
next(err); next(err);
}); });
// Allow browser-based and cross-origin MCP clients. // Controlled CORS policy: respects CORS_ORIGIN allowlist when configured; excludes arbitrary carrier base-URL headers.
app.use((req, res, next) => { app.use((req, res, next) => {
const configuredOrigins = (process.env.CORS_ORIGIN || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const reqOrigin = req.headers.origin;
if (configuredOrigins.length > 0) {
if (reqOrigin && configuredOrigins.includes(reqOrigin)) {
res.header("Access-Control-Allow-Origin", reqOrigin);
res.header("Vary", "Origin");
}
}
else {
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
}
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT"); 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-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-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-redx-api-token, 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-Expose-Headers", "mcp-session-id, WWW-Authenticate"); res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate");
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
return res.sendStatus(204); return res.sendStatus(204);
} }
next(); next();
}); });
// P1-01 Early Anti-SSRF Header Guard: reject any disallowed carrier base-URL header before routing
app.use((req, res, next) => {
const checks = [
["steadfast", "x-steadfast-base-url", "https://portal.packzy.com/api/v1"],
["pathao", "x-pathao-base-url", "https://api-hermes.pathao.com"],
["redx", "x-redx-base-url", "https://openapi.redx.com.bd/v1.0.0-beta"],
["paperfly", "x-paperfly-base-url", "https://api.paperfly.com.bd"],
];
for (const [prov, hdr, def] of checks) {
const hv = req.headers[hdr];
const val = Array.isArray(hv) ? hv[0] : hv;
if (typeof val === "string" && val.trim()) {
try {
validateCarrierBaseUrl(prov, val.trim(), def);
}
catch (err) {
return res.status(400).json(wrapError(new McpToolError({
code: "INVALID_INPUT",
message: err?.message || `Disallowed ${prov} base URL header.`,
retryable: false,
}), "validator"));
}
}
}
next();
});
// Static assets (official logo, favicons, branding) & agent MCP configs // Static assets (official logo, favicons, branding) & agent MCP configs
app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" })); app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" }));
app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" })); app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" }));
@@ -395,9 +442,9 @@ app.delete("/mcp", requireMcpAuth, async (req, res) => {
await entry.transport.handleRequest(req, res); await entry.transport.handleRequest(req, res);
}); });
/** /**
* GET /sse - Standard MCP Server-Sent Events Endpoint for AI Agent Connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) * GET /sse - Authenticated MCP Server-Sent Events Endpoint for AI Agent Connectors
*/ */
app.get("/sse", mcpLimiter, async (req, res) => { app.get("/sse", mcpLimiter, requireMcpAuth, async (req, res) => {
const tenantId = req.auraAuth?.tenantId || "default"; const tenantId = req.auraAuth?.tenantId || "default";
const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key; const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key;
const endpointUrl = token const endpointUrl = token
@@ -414,16 +461,16 @@ app.get("/sse", mcpLimiter, async (req, res) => {
await server.connect(transport); await server.connect(transport);
}); });
/** /**
* POST /messages - Standard MCP JSON-RPC Message Ingestion Endpoint for SSE Transports * POST /messages - Authenticated MCP JSON-RPC Message Ingestion Endpoint for SSE Transports
*/ */
app.post("/messages", mcpLimiter, async (req, res) => { app.post("/messages", mcpLimiter, requireMcpAuth, async (req, res) => {
const sessionId = (req.query.sessionId || req.headers["mcp-session-id"]); const sessionId = (req.query.sessionId || req.headers["mcp-session-id"]);
if (!sessionId || !sseSessions.has(sessionId)) { if (!sessionId || !sseSessions.has(sessionId)) {
return res.status(400).send("Invalid or missing sessionId"); return res.status(400).send("Invalid or missing sessionId");
} }
const entry = sseSessions.get(sessionId); const entry = sseSessions.get(sessionId);
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId; const callerTenant = req.auraAuth?.tenantId || "anonymous";
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") { if (entry.tenantId !== callerTenant && callerTenant !== "master") {
return res.status(403).json(wrapError(new McpToolError({ return res.status(403).json(wrapError(new McpToolError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "SSE Session belongs to another tenant.", message: "SSE Session belongs to another tenant.",
@@ -433,13 +480,39 @@ app.post("/messages", mcpLimiter, async (req, res) => {
entry.lastActiveAt = Date.now(); entry.lastActiveAt = Date.now();
await entry.transport.handlePostMessage(req, res, req.body); await entry.transport.handlePostMessage(req, res, req.body);
}); });
// P0-02 Replay Protection Cache (10-minute sliding window, bounded size)
const WEBHOOK_REPLAY_TTL_MS = 10 * 60 * 1000;
const webhookReplayCache = new Map();
export function clearWebhookReplayCache() {
webhookReplayCache.clear();
}
function checkAndMarkWebhookReplay(key) {
const now = Date.now();
const prev = webhookReplayCache.get(key);
if (prev && now - prev < WEBHOOK_REPLAY_TTL_MS) {
return true;
}
webhookReplayCache.set(key, now);
if (webhookReplayCache.size > 5000) {
for (const [k, ts] of webhookReplayCache.entries()) {
if (now - ts >= WEBHOOK_REPLAY_TTL_MS || webhookReplayCache.size > 4000) {
webhookReplayCache.delete(k);
}
}
}
return false;
}
/** /**
* Task T1 & T8 — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly * P0-02 Hardened — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly
* - Rejects unauthenticated/arbitrary merchant_token path segments with 401
* - Never discloses PATHAO_CLIENT_SECRET or AURA_WEBHOOK_SECRET in any response header
* - Derives tenantId strictly from server-side authenticated identity
* - Enforces optional timestamp skew guard (±10 min) and event replay deduplication (409)
*/ */
function handleCourierWebhook(provider) { function handleCourierWebhook(provider) {
return (req, res) => { return (req, res) => {
const isValidSig = verifyWebhookSignature(req, provider); const whAuth = authenticateWebhook(req, provider);
if (!isValidSig) { if (!whAuth.valid) {
return res.status(401).json(wrapError(new McpToolError({ return res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: `Unauthorized ${provider} webhook request: missing or invalid signature/secret.`, message: `Unauthorized ${provider} webhook request: missing or invalid signature/secret.`,
@@ -447,11 +520,24 @@ function handleCourierWebhook(provider) {
retryable: false, retryable: false,
}), "validator")); }), "validator"));
} }
// Optional webhook timestamp freshness check (±10 minutes)
const rawTs = (req.headers["x-webhook-timestamp"] || req.headers["x-timestamp"] || "");
if (rawTs) {
const parsedMs = /^\d+$/.test(rawTs.trim())
? (rawTs.trim().length <= 10 ? Number(rawTs.trim()) * 1000 : Number(rawTs.trim()))
: Date.parse(rawTs.trim());
if (!Number.isFinite(parsedMs) || Math.abs(Date.now() - parsedMs) > WEBHOOK_REPLAY_TTL_MS) {
return res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "Stale or invalid webhook timestamp (outside ±10 minute replay window).",
courier: provider,
retryable: false,
}), "validator"));
}
}
const payload = req.body || {}; const payload = req.body || {};
if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") { if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") {
const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || ""; // P0-02 Fix: NEVER return PATHAO_CLIENT_SECRET or AURA_WEBHOOK_SECRET in any HTTP response.
if (secret)
res.setHeader("X-Pathao-Merchant-Webhook-Integration-Secret", secret);
return res.status(202).json({ ok: true, status: "webhook_verified" }); return res.status(202).json({ ok: true, status: "webhook_verified" });
} }
const consignmentId = payload.consignment_id || const consignmentId = payload.consignment_id ||
@@ -469,8 +555,29 @@ function handleCourierWebhook(provider) {
const status = String(payload.status || payload.order_status || payload.event || "received"); const status = String(payload.status || payload.order_status || payload.event || "received");
const eventType = String(payload.notification_type || payload.event || "delivery_status"); const eventType = String(payload.notification_type || payload.event || "delivery_status");
const invoice = payload.invoice || payload.merchant_order_id; const invoice = payload.invoice || payload.merchant_order_id;
const paramMerchantToken = req.params?.merchant_token ? String(req.params.merchant_token).trim() : ""; // P0-02 Fix: Tenant identity comes STRICTLY from server-side verified webhook auth, never arbitrary URL path.
const tenantId = String(paramMerchantToken || req.query.tenant || req.headers["x-tenant-id"] || "default"); const tenantId = whAuth.tenantId;
// Replay deduplication check (header event-id or payload body fingerprint)
const explicitEventId = String(req.headers["x-webhook-id"] ||
req.headers["x-event-id"] ||
payload.event_id ||
payload.webhook_event_id ||
"").trim();
const rawBodyHash = createHash("sha256")
.update(req.rawBody ? String(req.rawBody) : JSON.stringify(payload))
.digest("hex")
.slice(0, 24);
const replayKey = explicitEventId
? `${provider}:${tenantId}:id:${explicitEventId}`
: `${provider}:${tenantId}:hash:${consignmentId || "none"}:${status}:${eventType}:${rawBodyHash}`;
if (checkAndMarkWebhookReplay(replayKey)) {
return res.status(409).json({
ok: false,
duplicate: true,
courier: provider,
message: "Duplicate webhook event ignored (replay protection).",
});
}
const record = { const record = {
id: randomUUID(), id: randomUUID(),
courier: provider, courier: provider,
@@ -481,12 +588,12 @@ function handleCourierWebhook(provider) {
received_at: new Date().toISOString(), received_at: new Date().toISOString(),
payload, payload,
}; };
// F06: Record webhook event scoped by tenantId // F06: Record webhook event scoped by server-verified tenantId
recordWebhookEvent(record, tenantId); recordWebhookEvent(record, tenantId);
// Forward verified Pathao financial events best-effort to Snehalata Financial Manager // Forward verified Pathao financial events best-effort to Snehalata Financial Manager
if (provider === "pathao" && process.env.NODE_ENV !== "test" && /deliver|return|paid|settlement|invoice/i.test(`${status} ${eventType}`)) { if (provider === "pathao" && process.env.NODE_ENV !== "test" && /deliver|return|paid|settlement|invoice/i.test(`${status} ${eventType}`)) {
const fwdUrl = process.env.SNEHALATA_WEBHOOK_URL || "https://www.snehalata.com/api/webhooks/pathao"; const fwdUrl = process.env.SNEHALATA_WEBHOOK_URL || "https://www.snehalata.com/api/webhooks/pathao";
const sig = String(req.headers["x-pathao-signature"] || process.env.PATHAO_CLIENT_SECRET || ""); const sig = String(req.headers["x-pathao-signature"] || "");
if (fwdUrl && sig) { if (fwdUrl && sig) {
fetch(fwdUrl, { fetch(fwdUrl, {
method: "POST", method: "POST",
@@ -555,41 +662,52 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
const isOwner = isAuth && (callerTenant === "master" || callerTenant === dbParcel?.tenant_id || callerTenant === dbParcel?.tenant); const isOwner = isAuth && (callerTenant === "master" || callerTenant === dbParcel?.tenant_id || callerTenant === dbParcel?.tenant);
if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) { if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) {
if (trackResult) { if (trackResult) {
let sanitized = trackResult;
if (!isOwner) { if (!isOwner) {
sanitized = { // P1-02 Fix: Minimal public DTO — strips raw_response, phone, full address, customer name, and COD value
...trackResult, const publicDto = {
recipient_phone: trackResult.recipient_phone ? maskPhone(trackResult.recipient_phone) : undefined, success: true,
recipient_address: trackResult.recipient_address ? redactAddressToDistrict(trackResult.recipient_address) : undefined, courier: trackResult.courier,
tracking_code: trackResult.tracking_code || code,
status: trackResult.status,
updated_at: trackResult.updated_at,
destination_area: trackResult.recipient_address
? redactAddressToDistrict(trackResult.recipient_address)
: "Bangladesh",
privacy_mode: "public_masked",
}; };
return res.json(wrapSuccess(publicDto, "live_api"));
} }
return res.json(wrapSuccess(sanitized, "live_api")); return res.json(wrapSuccess(trackResult, "live_api"));
} }
if (dbParcel) { if (dbParcel) {
let safeParcel = dbParcel;
if (!isOwner) { if (!isOwner) {
safeParcel = { const publicDbDto = {
...dbParcel, success: true,
recipient_phone: maskPhone(dbParcel.recipient_phone || dbParcel.phone || ""), parcel: {
recipient_address: redactAddressToDistrict(dbParcel.recipient_address || dbParcel.address || ""), courier: dbParcel.courier || courier,
customer_name: dbParcel.customer_name ? dbParcel.customer_name.charAt(0) + "***" : "Customer", tracking_code: dbParcel.tracking_code || code,
status: dbParcel.status || "booked",
updated_at: dbParcel.updated_at || dbParcel.created_at,
destination_area: redactAddressToDistrict(dbParcel.recipient_address || dbParcel.address || ""),
privacy_mode: "public_masked",
},
}; };
return res.json(wrapSuccess(publicDbDto, "cache"));
} }
return res.json(wrapSuccess({ success: true, parcel: safeParcel }, "cache")); return res.json(wrapSuccess({ success: true, parcel: dbParcel }, "cache"));
} }
return res.status(404).json(wrapError(errorObj || new Error("Consignment not found"), "live_api")); 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 raw = trackResult?.raw_response?.data || trackResult?.raw_response || (dbParcel?.raw?.data || dbParcel?.raw) || {};
let recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer"; 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"; let recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh";
// F03: Mask PII for public web tracker view // P1-02 Fix: Strict PII & COD redaction for unauthenticated/non-owner HTML tracker view
if (!isOwner) { if (!isOwner) {
recipientAddress = redactAddressToDistrict(recipientAddress); recipientAddress = redactAddressToDistrict(recipientAddress);
if (recipientName && recipientName.length > 2) { recipientName = "Verified Recipient";
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 codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0;
const codDisplay = isOwner ? `৳ ${Number(codAmount).toLocaleString()}` : "Protected (Merchant Only)";
const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found"); const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found");
const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase(); const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase();
const carrierName = resolvedCourier === "pathao" ? "Pathao Express" : (resolvedCourier === "steadfast" ? "Steadfast Courier" : resolvedCourier === "redx" ? "RedX Delivery" : resolvedCourier === "paperfly" ? "Paperfly Go" : resolvedCourier.toUpperCase()); const carrierName = resolvedCourier === "pathao" ? "Pathao Express" : (resolvedCourier === "steadfast" ? "Steadfast Courier" : resolvedCourier === "redx" ? "RedX Delivery" : resolvedCourier === "paperfly" ? "Paperfly Go" : resolvedCourier.toUpperCase());
@@ -664,7 +782,7 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
</div> </div>
<div class="info-grid"> <div class="info-grid">
<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">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 class="info-item"><div class="info-item-label">Cash on Delivery (COD)</div><div class="info-item-val">${escapeHtml(codDisplay)}</div></div>
</div> </div>
<div class="actions"> <div class="actions">
${shortLink ? `<a href="${escapeHtml(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>` : ""}
@@ -765,6 +883,14 @@ app.get("/", (_req, res) => {
}); });
}); });
if (process.env.NODE_ENV !== "test") { if (process.env.NODE_ENV !== "test") {
const sec = validateSecurityConfig();
if (!sec.ok) {
console.error("[FATAL SECURITY CONFIG] Refusing to start Aura Courier MCP without strong secrets:");
for (const e of sec.errors) {
console.error(` - ${e}`);
}
process.exit(1);
}
app.listen(PORT, () => { app.listen(PORT, () => {
console.log(`Aura Courier MCP v${APP_VERSION} (HTTP) listening on :${PORT} — POST /mcp`); console.log(`Aura Courier MCP v${APP_VERSION} (HTTP) listening on :${PORT} — POST /mcp`);
}); });
+30 -7
View File
@@ -26,10 +26,26 @@ export interface AuditEntry {
outcome: "ok" | "denied" | "error"; outcome: "ok" | "denied" | "error";
} }
export declare const auditLogBuffer: AuditEntry[]; export declare const auditLogBuffer: AuditEntry[];
export declare const FORBIDDEN_WEAK_SECRETS: Set<string>;
export declare function isStrongSecret(val: string | undefined, minLen?: number): boolean;
export declare function getMasterKey(): string;
export declare function getAdminKey(): string;
export declare function getReadOnlyKey(): string;
export declare function getWebhookSecret(): string;
export declare function validateSecurityConfig(): {
ok: boolean;
errors: string[];
};
/** /**
* F10 Fix: Accept BYOK credentials STRICTLY from request headers. * P0-03 Fix: Detect and validate BYOK carrier credential bundles strictly from request headers.
* Query parameters are completely ignored to avoid leaking secrets in proxy/access logs. * Every BYOK provider supplied must include its complete required credential set.
* BYOK NEVER bypasses Aura authentication or tool scopes.
*/ */
export declare function validateByokHeaders(req: Request): {
isByok: boolean;
valid: boolean;
reason?: string;
};
export declare function hasByokCredentials(req: Request): boolean; export declare function hasByokCredentials(req: Request): boolean;
export declare function extractBearerToken(req: Request): string | undefined; export declare function extractBearerToken(req: Request): string | undefined;
/** /**
@@ -66,8 +82,8 @@ export declare function listDynamicKeySummaries(): {
}[]; }[];
export declare function registerApiKey(token: string, tenantId: string, scopes?: AuthScope[], isAdmin?: boolean): void; export declare function registerApiKey(token: string, tenantId: string, scopes?: AuthScope[], isAdmin?: boolean): void;
/** /**
* F01 Fix: Cryptographic Token Resolution without prefix bypass. * P0-01 Fix: Fail-Closed Cryptographic Token Resolution.
* Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished. * Zero hardcoded fallback keys; zero prefix bypasses.
*/ */
export declare function resolveAuthContext(req: Request): AuraAuthContext; export declare function resolveAuthContext(req: Request): AuraAuthContext;
/** /**
@@ -92,9 +108,16 @@ export declare function isActionPermitted(req: Request, toolName: string, args?:
* Record privacy-safe audit log: hashes sanitized arguments; NEVER logs raw phone numbers or addresses. * Record privacy-safe audit log: hashes sanitized arguments; NEVER logs raw phone numbers or addresses.
*/ */
export declare function recordAuditLog(tenant: string, tool: string, args: Record<string, any> | undefined, outcome: "ok" | "denied" | "error"): void; export declare function recordAuditLog(tenant: string, tool: string, args: Record<string, any> | undefined, outcome: "ok" | "denied" | "error"): void;
export interface WebhookAuthResult {
valid: boolean;
tenantId: string;
authMethod?: string;
}
/** /**
* F09 Fix: Native Carrier Webhook HMAC-SHA256 & Token Verification. * P0-02 Fix: Fail-Closed Carrier Webhook Authentication & Server-Side Tenant Resolution.
* Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body. * - Abolishes arbitrary >=8-char URL path token acceptance.
* Steadfast uses secret key header comparison. * - Abolishes hardcoded webhook secret fallbacks.
* - Resolves tenantId strictly from server-side verified key/provider bindings (never attacker-supplied URL paths).
*/ */
export declare function authenticateWebhook(req: Request, provider: string): WebhookAuthResult;
export declare function verifyWebhookSignature(req: Request, provider: string): boolean; export declare function verifyWebhookSignature(req: Request, provider: string): boolean;
+244 -77
View File
@@ -21,16 +21,132 @@ const WRITE_TOOLS = new Set([
// Per-key sliding-window rate limiter store // Per-key sliding-window rate limiter store
const keyRateStore = new Map(); const keyRateStore = new Map();
export const auditLogBuffer = []; export const auditLogBuffer = [];
export const FORBIDDEN_WEAK_SECRETS = new Set([
"aura_live_mcp_master_key_2026",
"aura_ro_public_inspector_2026",
"aura_webhook_secret_2026",
"change_me",
"changeme",
"secret",
"password",
"default",
"test",
]);
export function isStrongSecret(val, minLen = 20) {
if (!val || typeof val !== "string")
return false;
const v = val.trim();
if (v.length < minLen)
return false;
const low = v.toLowerCase();
if (FORBIDDEN_WEAK_SECRETS.has(low))
return false;
if (low.startsWith("your_") || low.includes("<generate") || low.includes("replace_me"))
return false;
return true;
}
export function getMasterKey() {
const candidate = (process.env.AURA_API_KEY || process.env.COURIER_AUTH_TOKEN || "").trim();
return isStrongSecret(candidate, 20) ? candidate : "";
}
export function getAdminKey() {
const explicit = (process.env.AURA_ADMIN_KEY || "").trim();
if (explicit)
return isStrongSecret(explicit, 20) ? explicit : "";
return getMasterKey();
}
export function getReadOnlyKey() {
const candidate = (process.env.AURA_READONLY_KEY || "").trim();
return isStrongSecret(candidate, 16) ? candidate : "";
}
export function getWebhookSecret() {
const candidate = (process.env.AURA_WEBHOOK_SECRET || "").trim();
return isStrongSecret(candidate, 20) ? candidate : "";
}
export function validateSecurityConfig() {
const errors = [];
if (!getMasterKey()) {
errors.push("AURA_API_KEY (or COURIER_AUTH_TOKEN) is missing, weak (<20 chars), or uses a forbidden default value.");
}
if (process.env.AURA_ADMIN_KEY && !isStrongSecret(process.env.AURA_ADMIN_KEY, 20)) {
errors.push("AURA_ADMIN_KEY is weak (<20 chars) or uses a forbidden default value.");
}
if (process.env.AURA_READONLY_KEY && !isStrongSecret(process.env.AURA_READONLY_KEY, 16)) {
errors.push("AURA_READONLY_KEY is weak (<16 chars) or uses a forbidden default value.");
}
if (!getWebhookSecret()) {
errors.push("AURA_WEBHOOK_SECRET is missing, weak (<20 chars), or uses a forbidden default value.");
}
const oauthSecret = (process.env.AURA_OAUTH_SECRET || "").trim();
if (oauthSecret && !isStrongSecret(oauthSecret, 24)) {
errors.push("AURA_OAUTH_SECRET is weak (<24 chars) or uses a forbidden default value.");
}
else if (!oauthSecret && !getMasterKey()) {
errors.push("AURA_OAUTH_SECRET (or strong AURA_API_KEY) is required for OAuth 2.1 token signing.");
}
return { ok: errors.length === 0, errors };
}
function headerStr(req, name) {
const v = req.headers[name];
if (Array.isArray(v))
return String(v[0] || "").trim();
return typeof v === "string" ? v.trim() : "";
}
/** /**
* F10 Fix: Accept BYOK credentials STRICTLY from request headers. * P0-03 Fix: Detect and validate BYOK carrier credential bundles strictly from request headers.
* Query parameters are completely ignored to avoid leaking secrets in proxy/access logs. * Every BYOK provider supplied must include its complete required credential set.
* BYOK NEVER bypasses Aura authentication or tool scopes.
*/ */
export function validateByokHeaders(req) {
const sfKey = headerStr(req, "x-steadfast-api-key");
const sfSec = headerStr(req, "x-steadfast-secret-key");
const pId = headerStr(req, "x-pathao-client-id");
const pSec = headerStr(req, "x-pathao-client-secret");
const pUser = headerStr(req, "x-pathao-username");
const pPass = headerStr(req, "x-pathao-password");
const rxTok = headerStr(req, "x-redx-api-token");
const pfKey = headerStr(req, "x-paperfly-api-key");
const pfUser = headerStr(req, "x-paperfly-username");
const pfPass = headerStr(req, "x-paperfly-password");
const hasSf = Boolean(sfKey || sfSec);
const hasPathao = Boolean(pId || pSec || pUser || pPass);
const hasRx = Boolean(rxTok);
const hasPf = Boolean(pfKey || pfUser || pfPass);
const isByok = hasSf || hasPathao || hasRx || hasPf;
if (!isByok)
return { isByok: false, valid: true };
if (hasSf && (sfKey.length < 6 || sfSec.length < 6)) {
return {
isByok: true,
valid: false,
reason: "Incomplete Steadfast BYOK bundle: both x-steadfast-api-key and x-steadfast-secret-key (>=6 chars) are required.",
};
}
if (hasPathao && (!pId || !pSec || !pUser || !pPass)) {
return {
isByok: true,
valid: false,
reason: "Incomplete Pathao BYOK bundle: x-pathao-client-id, x-pathao-client-secret, x-pathao-username, and x-pathao-password are all required.",
};
}
if (hasRx && rxTok.length < 12) {
return {
isByok: true,
valid: false,
reason: "Invalid RedX BYOK bundle: x-redx-api-token must be at least 12 characters.",
};
}
if (hasPf && (!pfKey || !pfUser || !pfPass)) {
return {
isByok: true,
valid: false,
reason: "Incomplete Paperfly BYOK bundle: x-paperfly-api-key, x-paperfly-username, and x-paperfly-password are all required.",
};
}
return { isByok: true, valid: true };
}
export function hasByokCredentials(req) { export function hasByokCredentials(req) {
const h = req.headers; return validateByokHeaders(req).isByok;
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) { export function extractBearerToken(req) {
const authHeader = req.headers["authorization"] || req.headers["Authorization"]; const authHeader = req.headers["authorization"] || req.headers["Authorization"];
@@ -179,17 +295,15 @@ export function registerApiKey(token, tenantId, scopes = ["read", "write"], isAd
registeredKeyHashes.set(hash, { tenantId, scopes, isAdmin }); registeredKeyHashes.set(hash, { tenantId, scopes, isAdmin });
} }
/** /**
* F01 Fix: Cryptographic Token Resolution without prefix bypass. * P0-01 Fix: Fail-Closed Cryptographic Token Resolution.
* Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished. * Zero hardcoded fallback keys; zero prefix bypasses.
*/ */
export function resolveAuthContext(req) { export function resolveAuthContext(req) {
const token = extractBearerToken(req); const token = extractBearerToken(req);
const isByok = hasByokCredentials(req); const isByok = hasByokCredentials(req);
const masterKey = process.env.AURA_API_KEY || const masterKey = getMasterKey();
process.env.COURIER_AUTH_TOKEN || const readOnlyKey = getReadOnlyKey();
"aura_live_mcp_master_key_2026"; const adminKey = getAdminKey();
const readOnlyKey = process.env.AURA_READONLY_KEY || "aura_ro_public_inspector_2026";
const adminKey = process.env.AURA_ADMIN_KEY || masterKey;
if (!token) { if (!token) {
return { return {
authenticated: false, authenticated: false,
@@ -199,6 +313,16 @@ export function resolveAuthContext(req) {
isAdmin: false, isAdmin: false,
}; };
} }
// Reject known leaked/default weak tokens unconditionally
if (FORBIDDEN_WEAK_SECRETS.has(token.toLowerCase())) {
return {
authenticated: false,
tenantId: "invalid",
scopes: [],
isByok,
isAdmin: false,
};
}
// 0. Standard MCP OAuth 2.1 JWT Access Token (Google Gemini, ChatGPT, Claude Web) // 0. Standard MCP OAuth 2.1 JWT Access Token (Google Gemini, ChatGPT, Claude Web)
if (token.startsWith("eyJ") && token.split(".").length === 3) { if (token.startsWith("eyJ") && token.split(".").length === 3) {
const oauthClaims = verifyOAuthAccessToken(token); const oauthClaims = verifyOAuthAccessToken(token);
@@ -213,8 +337,8 @@ export function resolveAuthContext(req) {
}; };
} }
} }
// 1. Master / Admin Key (Full Read + Write across all tenants) // 1. Master / Admin Key (Full Read + Write across all tenants — strictly from strong env secret)
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) { if ((masterKey && safeCompare(token, masterKey)) || (adminKey && safeCompare(token, adminKey))) {
return { return {
authenticated: true, authenticated: true,
tenantId: "master", tenantId: "master",
@@ -224,8 +348,8 @@ export function resolveAuthContext(req) {
callerToken: token, callerToken: token,
}; };
} }
// 2. Read-Only Gateway Discovery Key // 2. Read-Only Gateway Discovery Key (strictly from strong env secret)
if (safeCompare(token, readOnlyKey) || safeCompare(token, "aura_ro_public_inspector_2026")) { if (readOnlyKey && safeCompare(token, readOnlyKey)) {
return { return {
authenticated: true, authenticated: true,
tenantId: "public_ro", tenantId: "public_ro",
@@ -330,10 +454,9 @@ export async function resolveAuthContextAsync(req) {
return resolveAuthContext(req); return resolveAuthContext(req);
} }
const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key"; const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key";
const syncSecret = process.env.AURA_MCP_SYNC_SECRET || const syncSecret = (process.env.AURA_MCP_SYNC_SECRET || getMasterKey()).trim();
process.env.AURA_API_KEY || if (!syncSecret)
process.env.COURIER_AUTH_TOKEN || return local;
"aura_live_mcp_master_key_2026";
const ctrl = new AbortController(); const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 3500); const timer = setTimeout(() => ctrl.abort(), 3500);
try { try {
@@ -410,15 +533,22 @@ export function requireMcpAuth(req, res, next) {
if (isDiscovery) { if (isDiscovery) {
return next(); return next();
} }
// BYOK headers (x-steadfast-api-key, etc.) allow tool execution with caller's carrier credentials // P0-03 Fix: NEVER bypass Aura auth on BYOK headers. Authenticate caller first, then validate BYOK bundle.
if (ctx.isByok) {
return next();
}
if (!ctx.authenticated) { if (!ctx.authenticated) {
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, false)); res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, false));
res.status(401).json(wrapError(new McpToolError({ res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Authenticate via MCP OAuth 2.1 or provide your API key / BYOK carrier keys.", message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Authenticate via MCP OAuth 2.1 or provide a valid tenant API key (BYOK headers require authentication too).",
retryable: false,
source: "validator",
})));
return;
}
const byokCheck = validateByokHeaders(req);
if (byokCheck.isByok && !byokCheck.valid) {
res.status(400).json(wrapError(new McpToolError({
code: "INVALID_INPUT",
message: byokCheck.reason || "Incomplete BYOK carrier credential bundle.",
retryable: false, retryable: false,
source: "validator", source: "validator",
}))); })));
@@ -458,21 +588,28 @@ export function isActionPermitted(req, toolName, args) {
reason: "Unauthorized: invalid or forged Authorization token.", reason: "Unauthorized: invalid or forged Authorization token.",
}; };
} }
// F14: list_couriers is allowed for discovery // P0-03 Fix: Every tool invocation (including BYOK) MUST be authenticated and pass scope checks.
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) { if (!ctx.authenticated) {
recordAuditLog(ctx.tenantId, toolName, args, "denied"); recordAuditLog(ctx.tenantId, toolName, args, "denied");
return { return {
permitted: false, permitted: false,
reason: "Unauthorized: valid Authorization: Bearer <key> required.", reason: "Unauthorized: valid Authorization: Bearer <key> or OAuth 2.1 token required.",
}; };
} }
if (ctx.isByok) {
const byokCheck = validateByokHeaders(req);
if (!byokCheck.valid) {
recordAuditLog(ctx.tenantId, toolName, args, "denied");
return {
permitted: false,
reason: byokCheck.reason || "Incomplete BYOK carrier credential bundle.",
};
}
}
// F14: list_couriers is allowed for any authenticated caller (read discovery)
if (toolName === "list_couriers") {
return { permitted: true };
}
const requiredScope = WRITE_TOOLS.has(toolName) || !READ_TOOLS.has(toolName) ? "write" : "read"; const requiredScope = WRITE_TOOLS.has(toolName) || !READ_TOOLS.has(toolName) ? "write" : "read";
if (!ctx.scopes.includes(requiredScope)) { if (!ctx.scopes.includes(requiredScope)) {
recordAuditLog(ctx.tenantId, toolName, args, "denied"); recordAuditLog(ctx.tenantId, toolName, args, "denied");
@@ -513,73 +650,103 @@ export function recordAuditLog(tenant, tool, args, outcome) {
} }
} }
/** /**
* F09 Fix: Native Carrier Webhook HMAC-SHA256 & Token Verification. * P0-02 Fix: Fail-Closed Carrier Webhook Authentication & Server-Side Tenant Resolution.
* Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body. * - Abolishes arbitrary >=8-char URL path token acceptance.
* Steadfast uses secret key header comparison. * - Abolishes hardcoded webhook secret fallbacks.
* - Resolves tenantId strictly from server-side verified key/provider bindings (never attacker-supplied URL paths).
*/ */
export function verifyWebhookSignature(req, provider) { export function authenticateWebhook(req, provider) {
const prov = (provider || "").toLowerCase(); const prov = (provider || "").toLowerCase();
// 1. Pathao Webhook: Verify X-Pathao-Signature via HMAC-SHA256 const webhookMasterSecret = getWebhookSecret();
// 1. Pathao Webhook: Verify X-Pathao-Signature via HMAC-SHA256 over raw body
const pathaoSig = (req.headers["x-pathao-signature"] || req.headers["x-signature"]); const pathaoSig = (req.headers["x-pathao-signature"] || req.headers["x-signature"]);
if (prov === "pathao" && pathaoSig) { if (prov === "pathao" && pathaoSig && typeof pathaoSig === "string") {
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 rawBody = req.rawBody ? String(req.rawBody) : JSON.stringify(req.body || {});
const candidateSecrets = [
(process.env.PATHAO_WEBHOOK_SECRET || "").trim(),
(process.env.PATHAO_CLIENT_SECRET || "").trim(),
webhookMasterSecret,
].filter(Boolean);
for (const secret of candidateSecrets) {
const expected = createHmac("sha256", secret).update(rawBody).digest("hex"); const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
if (safeCompare(pathaoSig, expected)) if (safeCompare(pathaoSig.trim(), expected)) {
return true; return {
valid: true,
tenantId: (process.env.PATHAO_WEBHOOK_TENANT || "default").trim() || "default",
authMethod: "pathao_hmac",
};
} }
} }
// 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 // 2. Steadfast Webhook: Verify X-Steadfast-Signature or secret header against STEADFAST_SECRET_KEY
const sfSig = (req.headers["x-steadfast-signature"] || req.headers["x-webhook-secret"]);
if (prov === "steadfast" && sfSig && typeof sfSig === "string") {
const sfSecret = (process.env.STEADFAST_SECRET_KEY || "").trim();
if (sfSecret && safeCompare(sfSig.trim(), sfSecret)) {
return { valid: true, tenantId: "default", authMethod: "steadfast_secret" };
}
}
// 3. RedX & Paperfly Provider Secrets
const rxSig = (req.headers["x-redx-signature"] || req.headers["x-webhook-secret"]); const rxSig = (req.headers["x-redx-signature"] || req.headers["x-webhook-secret"]);
if (prov === "redx" && rxSig) { if (prov === "redx" && rxSig && typeof rxSig === "string") {
const rxSecret = process.env.REDX_API_TOKEN || process.env.AURA_WEBHOOK_SECRET || ""; const rxSecret = (process.env.REDX_API_TOKEN || "").trim();
if (rxSecret && safeCompare(rxSig, rxSecret)) if (rxSecret && safeCompare(rxSig.trim(), rxSecret)) {
return true; return { valid: true, tenantId: "default", authMethod: "redx_secret" };
}
} }
const pfSig = (req.headers["x-paperfly-signature"] || req.headers["x-webhook-secret"]); const pfSig = (req.headers["x-paperfly-signature"] || req.headers["x-webhook-secret"]);
if (prov === "paperfly" && pfSig) { if (prov === "paperfly" && pfSig && typeof pfSig === "string") {
const pfSecret = process.env.PAPERFLY_API_KEY || process.env.AURA_WEBHOOK_SECRET || ""; const pfSecret = (process.env.PAPERFLY_API_KEY || "").trim();
if (pfSecret && safeCompare(pfSig, pfSecret)) if (pfSecret && safeCompare(pfSig.trim(), pfSecret)) {
return true; return { valid: true, tenantId: "default", authMethod: "paperfly_secret" };
} }
// 4. Universal master secret, registered tenant key, or merchant_token URL parameter fallback }
const masterSecret = process.env.AURA_WEBHOOK_SECRET || process.env.AURA_API_KEY || "aura_webhook_secret_2026"; // 4. Platform Webhook Master Secret or Cryptographically Registered Tenant Key ONLY
const paramToken = (req.params && req.params.merchant_token) ? String(req.params.merchant_token).trim() : undefined; const paramToken = (req.params && req.params.merchant_token)
const candidate = paramToken || ? String(req.params.merchant_token).trim()
: undefined;
const candidate = req.headers["x-webhook-secret"] ||
extractBearerToken(req) || extractBearerToken(req) ||
req.headers["x-webhook-secret"] || paramToken;
req.query["token"] ||
req.query["secret"];
if (candidate && typeof candidate === "string") { if (candidate && typeof candidate === "string") {
const trimmed = candidate.trim(); const trimmed = candidate.trim();
if (safeCompare(trimmed, masterSecret)) { if (!trimmed || FORBIDDEN_WEAK_SECRETS.has(trimmed.toLowerCase())) {
return true; return { valid: false, tenantId: "unauthorized" };
} }
// 4a. Platform Webhook Master Secret (server-trusted caller may specify tenant scope via query/header)
if (webhookMasterSecret && safeCompare(trimmed, webhookMasterSecret)) {
const requestedTenant = String((req.query && req.query.tenant) ||
req.headers["x-tenant-id"] ||
"default").trim();
const safeTenant = /^[a-zA-Z0-9_\-]{1,64}$/.test(requestedTenant) ? requestedTenant : "default";
return { valid: true, tenantId: safeTenant, authMethod: "webhook_master_secret" };
}
// 4b. Registered Static / Dynamic Tenant Key (SHA-256 lookup — tenant strictly bound server-side)
const tokenHash = createHash("sha256").update(trimmed).digest("hex"); const tokenHash = createHash("sha256").update(trimmed).digest("hex");
if (registeredKeyHashes.has(tokenHash)) { if (registeredKeyHashes.has(tokenHash)) {
return true; const reg = registeredKeyHashes.get(tokenHash);
return { valid: true, tenantId: reg.tenantId, authMethod: "registered_tenant_key" };
} }
if (dynamicKeyHashes.has(tokenHash)) {
const dyn = dynamicKeyHashes.get(tokenHash);
if (dyn.status === "ACTIVE") {
return { valid: true, tenantId: dyn.tenantId, authMethod: "dynamic_tenant_key" };
}
return { valid: false, tenantId: "unauthorized" };
}
// 4c. Env-configured Tenant Keys (strictly compare against secret key tKey, NEVER tenant ID tId)
const envTenants = process.env.AURA_TENANT_KEYS; const envTenants = process.env.AURA_TENANT_KEYS;
if (envTenants) { if (envTenants) {
for (const pair of envTenants.split(",")) { for (const pair of envTenants.split(",")) {
const [tId, tKey] = pair.split(":"); const [tId, tKey] = pair.split(":");
if ((tKey && safeCompare(trimmed, tKey.trim())) || (tId && safeCompare(trimmed, tId.trim()))) { if (tId && tKey && isStrongSecret(tKey.trim(), 16) && safeCompare(trimmed, tKey.trim())) {
return true; return { valid: true, tenantId: tId.trim(), authMethod: "env_tenant_key" };
} }
} }
} }
// Accept non-empty merchant_token path identifier (>= 8 chars) for dedicated merchant webhook endpoints
if (paramToken && paramToken.length >= 8 && /^[a-zA-Z0-9_\-]+$/.test(paramToken)) {
return true;
} }
return { valid: false, tenantId: "unauthorized" };
} }
return false; export function verifyWebhookSignature(req, provider) {
return authenticateWebhook(req, provider).valid;
} }
+14 -2
View File
@@ -22,11 +22,23 @@ setInterval(() => {
revokedTokenIds.delete(k); revokedTokenIds.delete(k);
} }
}, 5 * 60 * 1000).unref(); }, 5 * 60 * 1000).unref();
const OAUTH_FORBIDDEN_DEFAULTS = new Set([
"aura_live_mcp_master_key_2026",
"aura_ro_public_inspector_2026",
"aura_webhook_secret_2026",
"change_me",
"changeme",
"secret",
]);
function getRootSecret() { function getRootSecret() {
return (process.env.AURA_OAUTH_SECRET || const raw = (process.env.AURA_OAUTH_SECRET ||
process.env.AURA_API_KEY || process.env.AURA_API_KEY ||
process.env.COURIER_AUTH_TOKEN || process.env.COURIER_AUTH_TOKEN ||
"aura_live_mcp_master_key_2026"); "").trim();
if (raw.length < 20 || OAUTH_FORBIDDEN_DEFAULTS.has(raw.toLowerCase())) {
throw new Error("AURA_OAUTH_SECRET (or strong AURA_API_KEY >=20 chars) must be configured; predictable defaults are forbidden.");
}
return raw;
} }
function deriveKey(purpose) { function deriveKey(purpose) {
return createHash("sha256") return createHash("sha256")
+158 -5
View File
@@ -12,11 +12,15 @@ export function setRegistryDbPool(pool) {
registryDbPool = pool; registryDbPool = pool;
} }
/** /**
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8). * Process-wide Atomic & Durable Idempotency Store keyed by `${tenantId}:${invoice}` (P1-03 & P1-04).
*/ */
const idempotencyStore = new Map(); const idempotencyStore = new Map();
const inFlightBookings = new Map();
const pendingReconciliationStore = new Map();
export function clearIdempotencyStore() { export function clearIdempotencyStore() {
idempotencyStore.clear(); idempotencyStore.clear();
inFlightBookings.clear();
pendingReconciliationStore.clear();
} }
/** /**
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8). * Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
@@ -57,6 +61,32 @@ function isNetworkTimeout(err) {
msg.includes("network error") || msg.includes("network error") ||
msg.includes("socket hang up")); msg.includes("socket hang up"));
} }
/**
* P1-04 Fix: Only cascade to a fallback courier on a DEFINITE pre-booking rejection
* (4xx client/validation/auth/unconfigured errors). Any 5xx, timeout, network drop, or
* malformed response after dispatch is AMBIGUOUS and halts cascade to prevent duplicates.
*/
function isDefinitePreBookingRejection(err) {
if (!err)
return false;
if (isNetworkTimeout(err))
return false;
const status = Number(err?.response?.status || err?.status || err?.statusCode || 0);
if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
return true;
}
if (err instanceof McpToolError) {
return ["INVALID_INPUT", "UNCONFIGURED", "NO_COVERAGE", "UNAUTHORIZED", "CONSIGNMENT_NOT_FOUND"].includes(err.code);
}
const msg = String(err.message || "").toLowerCase();
return (msg.includes("not configured") ||
msg.includes("credentials") ||
msg.includes("could not match a delivery area") ||
msg.includes("store name is required") ||
msg.includes("store_id") ||
msg.includes("invalid phone") ||
msg.includes("validation failed"));
}
export class CourierRegistry { export class CourierRegistry {
adapters = new Map(); adapters = new Map();
googleMaps; googleMaps;
@@ -188,7 +218,7 @@ export class CourierRegistry {
}, },
}; };
} }
// Task T8: Idempotency by (tenant_id, invoice) // P1-03 & P1-04 Fix: Atomic in-flight reservation + durable PostgreSQL idempotency by (tenant_id, invoice)
const tenantKey = String(req.tenant_id || "default"); const tenantKey = String(req.tenant_id || "default");
const idemKey = `${tenantKey}:${invoice}`; const idemKey = `${tenantKey}:${invoice}`;
const existing = idempotencyStore.get(idemKey); const existing = idempotencyStore.get(idemKey);
@@ -198,6 +228,60 @@ export class CourierRegistry {
idempotent_replay: true, idempotent_replay: true,
}; };
} }
const pendingRecon = pendingReconciliationStore.get(idemKey);
if (pendingRecon) {
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `Invoice '${invoice}' has an unresolved ambiguous booking attempt on '${pendingRecon.courier}'. Halting duplicate creation until reconciled.`,
courier: pendingRecon.courier,
retryable: true,
extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION",
ambiguous_outcome: true,
courier_attempted: pendingRecon.courier,
invoice,
},
});
}
// Coalesce concurrent identical (tenant, invoice) requests onto ONE single upstream call
const inFlight = inFlightBookings.get(idemKey);
if (inFlight) {
const sharedResult = await inFlight;
return {
...sharedResult,
idempotent_replay: true,
};
}
const bookingPromise = (async () => {
// Check durable PostgreSQL ledger before hitting upstream carrier (survives restarts/redeployments)
if (registryDbPool) {
try {
const dbHit = await registryDbPool.query(`SELECT courier, tracking_code, status, cod_amount, raw
FROM courier_parcels
WHERE tenant = $1 AND (raw->>'invoice' = $2 OR raw->>'idempotency_key' = $3)
ORDER BY created_at DESC LIMIT 1`, [tenantKey, invoice, idemKey]);
if (dbHit?.rows && dbHit.rows.length > 0) {
const row = dbHit.rows[0];
const recovered = {
success: true,
courier: (row.courier || candidates[0]),
tracking_code: String(row.tracking_code || ""),
consignment_id: row.raw?.consignment_id || row.tracking_code,
invoice,
status: String(row.status || "booked"),
cod_amount: Number(row.cod_amount ?? codAmount),
idempotent_replay: true,
routing_reason: `Recovered existing booking from durable PostgreSQL ledger for invoice '${invoice}'.`,
cancellable_via_api: false,
};
idempotencyStore.set(idemKey, recovered);
return recovered;
}
}
catch (dbErr) {
console.warn("[Registry] Durable idempotency lookup skipped:", dbErr?.message);
}
}
let lastErr = null; let lastErr = null;
for (const courierName of candidates) { for (const courierName of candidates) {
try { try {
@@ -227,8 +311,56 @@ export class CourierRegistry {
}, },
}; };
idempotencyStore.set(idemKey, enriched); idempotencyStore.set(idemKey, enriched);
// Persist durably in PostgreSQL if connected
if (registryDbPool && enriched.tracking_code) {
try {
await registryDbPool.query(`INSERT INTO courier_parcels
(tenant, source, courier, tracking_code, customer_name, phone, address, cod_amount, item_description, status, raw)
VALUES ($1, 'mcp', $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb)
ON CONFLICT (tenant, tracking_code) DO NOTHING`, [
tenantKey,
courierName,
String(enriched.tracking_code),
String(req.recipient_name || ""),
cleanPhone,
addrStr,
Number(codAmount || 0),
String(req.note || req.item_type || ""),
String(enriched.status || "booked"),
JSON.stringify({
invoice,
idempotency_key: idemKey,
consignment_id: enriched.consignment_id,
}),
]);
}
catch (persistErr) {
console.warn("[Registry] Durable parcel persist skipped:", persistErr?.message);
}
}
return enriched; return enriched;
} }
// Ambiguous non-error response missing tracking_code/consignment_id -> HALT cascade (P1-04)
if (res && res.success !== false) {
pendingReconciliationStore.set(idemKey, {
courier: courierName,
invoice,
reason: "Ambiguous upstream response without tracking_code/consignment_id",
timestamp: new Date().toISOString(),
});
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `Carrier ${courierName} returned an ambiguous response without tracking_code/consignment_id. Halting cascade to prevent duplicate booking. State is UNKNOWN_PENDING_RECONCILIATION.`,
courier: courierName,
retryable: true,
extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION",
ambiguous_outcome: true,
courier_attempted: courierName,
invoice,
},
});
}
lastErr = new McpToolError({ lastErr = new McpToolError({
code: "COURIER_UPSTREAM_ERROR", code: "COURIER_UPSTREAM_ERROR",
message: res?.message || res?.error || `${courierName} rejected parcel booking.`, message: res?.message || res?.error || `${courierName} rejected parcel booking.`,
@@ -236,16 +368,29 @@ export class CourierRegistry {
}); });
} }
catch (err) { catch (err) {
if (err instanceof McpToolError && err.extraFields?.status === "UNKNOWN_PENDING_RECONCILIATION") {
throw err;
}
lastErr = err; lastErr = err;
if (isNetworkTimeout(err)) { if (!isDefinitePreBookingRejection(err)) {
const isTimeout = isNetworkTimeout(err);
pendingReconciliationStore.set(idemKey, {
courier: courierName,
invoice,
reason: err?.message || "Ambiguous upstream failure",
timestamp: new Date().toISOString(),
});
throw new McpToolError({ throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR", 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.", message: isTimeout
? `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.`
: `Carrier ${courierName} returned an ambiguous upstream outcome (${err?.message || "unknown error"}). Halting cascade to prevent duplicate parcel creation. State is UNKNOWN_PENDING_RECONCILIATION.`,
courier: courierName, courier: courierName,
retryable: true, retryable: true,
extraFields: { extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION", status: "UNKNOWN_PENDING_RECONCILIATION",
timeout_uncertain: true, timeout_uncertain: isTimeout,
ambiguous_outcome: true,
courier_attempted: courierName, courier_attempted: courierName,
invoice, invoice,
}, },
@@ -260,6 +405,14 @@ export class CourierRegistry {
code: "COURIER_UPSTREAM_ERROR", code: "COURIER_UPSTREAM_ERROR",
message: lastErr?.message || "All configured courier gateways failed to book parcel.", message: lastErr?.message || "All configured courier gateways failed to book parcel.",
}); });
})();
inFlightBookings.set(idemKey, bookingPromise);
try {
return await bookingPromise;
}
finally {
inFlightBookings.delete(idemKey);
}
} }
async trackParcel(trackingCode, courierName) { async trackParcel(trackingCode, courierName) {
const cleanCode = String(trackingCode || "").trim(); const cleanCode = String(trackingCode || "").trim();
+1 -1
View File
@@ -11,6 +11,6 @@ function readPackageVersion() {
catch { catch {
// Fallback if package.json is unavailable at runtime // Fallback if package.json is unavailable at runtime
} }
return "2.7.1"; return "2.7.2";
} }
export const APP_VERSION = readPackageVersion(); export const APP_VERSION = readPackageVersion();
+2 -2
View File
@@ -1735,7 +1735,7 @@
}, },
"aura-courier-local": { "aura-courier-local": {
"command": "npx", "command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"], "args": ["-y", "aura-courier-mcp@2.7.1"],
"env": { "PORT": "8080" } "env": { "PORT": "8080" }
} }
} }
@@ -1752,7 +1752,7 @@
}, },
"aura-courier-stdio": { "aura-courier-stdio": {
"command": "npx", "command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"] "args": ["-y", "aura-courier-mcp@2.7.1"]
} }
} }
}, null, 2) }, null, 2)
+14 -6
View File
@@ -401,7 +401,7 @@
</div> </div>
<div class="metric-card"> <div class="metric-card">
<div class="metric-label">Registered Tools</div> <div class="metric-label">Registered Tools</div>
<div class="metric-val" id="metric-tools">9</div> <div class="metric-val" id="metric-tools">13</div>
<div class="metric-sub">Spatial, Fraud &amp; Courier</div> <div class="metric-sub">Spatial, Fraud &amp; Courier</div>
</div> </div>
<div class="metric-card"> <div class="metric-card">
@@ -522,12 +522,14 @@
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
document.getElementById('metric-tools').textContent = data.tools_count || 9; document.getElementById('metric-tools').textContent = data.tools_count || 13;
document.getElementById('metric-uptime').textContent = formatUptime(data.performance?.uptime_seconds || 0); const upSec = data.performance?.uptime_seconds;
document.getElementById('metric-uptime').textContent = typeof upSec === 'number' ? formatUptime(upSec) : '24/7 Online';
const heapUsed = data.performance?.heap_used_mb || 0; if (data.performance) {
const heapTotal = data.performance?.heap_total_mb || 1; const heapUsed = data.performance.heap_used_mb || 0;
const rss = data.performance?.rss_mb || 0; const heapTotal = data.performance.heap_total_mb || 1;
const rss = data.performance.rss_mb || 0;
document.getElementById('mem-heap-text').textContent = `${heapUsed} MB / ${heapTotal} MB`; document.getElementById('mem-heap-text').textContent = `${heapUsed} MB / ${heapTotal} MB`;
const heapPct = Math.min(Math.round((heapUsed / heapTotal) * 100), 100); const heapPct = Math.min(Math.round((heapUsed / heapTotal) * 100), 100);
@@ -535,6 +537,12 @@
document.getElementById('mem-rss-text').textContent = `${rss} MB`; document.getElementById('mem-rss-text').textContent = `${rss} MB`;
document.getElementById('mem-rss-bar').style.width = `${Math.min(Math.round((rss / 256) * 100), 100)}%`; document.getElementById('mem-rss-bar').style.width = `${Math.min(Math.round((rss / 256) * 100), 100)}%`;
} else {
document.getElementById('mem-heap-text').textContent = 'Protected (Admin Auth)';
document.getElementById('mem-heap-bar').style.width = '18%';
document.getElementById('mem-rss-text').textContent = 'Protected (Admin Auth)';
document.getElementById('mem-rss-bar').style.width = '24%';
}
document.getElementById('raw-json').textContent = JSON.stringify(data, null, 2); document.getElementById('raw-json').textContent = JSON.stringify(data, null, 2);
} }
+66 -46
View File
@@ -1,12 +1,12 @@
{ {
"name": "aura-courier-mcp", "name": "aura-courier-mcp",
"version": "2.7.1", "version": "2.7.2",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "aura-courier-mcp", "name": "aura-courier-mcp",
"version": "2.7.1", "version": "2.7.2",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "^1.12.0", "@modelcontextprotocol/sdk": "^1.12.0",
@@ -14,7 +14,7 @@
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"express": "^4.21.2", "express": "^4.21.2",
"pg": "^8.13.1", "pg": "^8.13.1",
"zod": "^3.24.2" "zod": "^4.6.7"
}, },
"bin": { "bin": {
"aura-courier-mcp": "dist/index.js" "aura-courier-mcp": "dist/index.js"
@@ -470,21 +470,21 @@
} }
}, },
"node_modules/@hono/node-server": { "node_modules/@hono/node-server": {
"version": "2.1.1", "version": "2.1.11",
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.1.tgz", "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.11.tgz",
"integrity": "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg==", "integrity": "sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=20" "node": ">=20"
}, },
"peerDependencies": { "peerDependencies": {
"hono": "^4" "hono": "^4 || ^5.0.0-0"
} }
}, },
"node_modules/@modelcontextprotocol/sdk": { "node_modules/@modelcontextprotocol/sdk": {
"version": "1.30.0", "version": "1.32.2",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.2.tgz",
"integrity": "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==", "integrity": "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@hono/node-server": "^1.19.9 || ^2.0.5", "@hono/node-server": "^1.19.9 || ^2.0.5",
@@ -535,18 +535,18 @@
} }
}, },
"node_modules/@modelcontextprotocol/sdk/node_modules/body-parser": { "node_modules/@modelcontextprotocol/sdk/node_modules/body-parser": {
"version": "2.3.0", "version": "2.4.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz",
"integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"bytes": "^3.1.2", "bytes": "^3.1.2",
"content-type": "^2.0.0", "content-type": "^2.1.0",
"debug": "^4.4.3", "debug": "^4.4.3",
"http-errors": "^2.0.1", "http-errors": "^2.0.1",
"iconv-lite": "^0.7.2", "iconv-lite": "^0.7.3",
"on-finished": "^2.4.1", "on-finished": "^2.4.1",
"qs": "^6.15.2", "qs": "^6.16.1",
"raw-body": "^3.0.2", "raw-body": "^3.0.2",
"type-is": "^2.1.0" "type-is": "^2.1.0"
}, },
@@ -745,6 +745,22 @@
"url": "https://opencollective.com/express" "url": "https://opencollective.com/express"
} }
}, },
"node_modules/@modelcontextprotocol/sdk/node_modules/qs": {
"version": "6.17.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz",
"integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==",
"license": "BSD-3-Clause",
"dependencies": {
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/@modelcontextprotocol/sdk/node_modules/send": { "node_modules/@modelcontextprotocol/sdk/node_modules/send": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
@@ -1034,9 +1050,9 @@
} }
}, },
"node_modules/body-parser": { "node_modules/body-parser": {
"version": "1.20.6", "version": "1.20.9",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz",
"integrity": "sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==", "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"bytes": "~3.1.2", "bytes": "~3.1.2",
@@ -1047,7 +1063,7 @@
"http-errors": "~2.0.1", "http-errors": "~2.0.1",
"iconv-lite": "~0.4.24", "iconv-lite": "~0.4.24",
"on-finished": "~2.4.1", "on-finished": "~2.4.1",
"qs": "~6.15.1", "qs": "~6.16.0",
"raw-body": "~2.5.3", "raw-body": "~2.5.3",
"type-is": "~1.6.18", "type-is": "~1.6.18",
"unpipe": "~1.0.0" "unpipe": "~1.0.0"
@@ -1426,9 +1442,9 @@
} }
}, },
"node_modules/express": { "node_modules/express": {
"version": "4.22.2", "version": "4.22.3",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz", "resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz",
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==", "integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==",
"license": "MIT", "license": "MIT",
"peer": true, "peer": true,
"dependencies": { "dependencies": {
@@ -1451,9 +1467,9 @@
"methods": "~1.1.2", "methods": "~1.1.2",
"on-finished": "~2.4.1", "on-finished": "~2.4.1",
"parseurl": "~1.3.3", "parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12", "path-to-regexp": "~0.1.13",
"proxy-addr": "~2.0.7", "proxy-addr": "~2.0.7",
"qs": "~6.15.1", "qs": "~6.16.0",
"range-parser": "~1.2.1", "range-parser": "~1.2.1",
"safe-buffer": "5.2.1", "safe-buffer": "5.2.1",
"send": "~0.19.0", "send": "~0.19.0",
@@ -1513,9 +1529,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/fast-uri": { "node_modules/fast-uri": {
"version": "3.1.6", "version": "3.1.9",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.6.tgz", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz",
"integrity": "sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q==", "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==",
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -1562,9 +1578,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/follow-redirects": { "node_modules/follow-redirects": {
"version": "1.16.0", "version": "1.16.3",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz",
"integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==",
"funding": [ "funding": [
{ {
"type": "individual", "type": "individual",
@@ -1728,9 +1744,9 @@
} }
}, },
"node_modules/hono": { "node_modules/hono": {
"version": "4.13.5", "version": "4.13.22",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.5.tgz", "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.22.tgz",
"integrity": "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw==", "integrity": "sha512-wncKd5/40Pj8grx0RZ2fgNIicFEmVFwIHT5UFLTnphR8I6AQWFf9c2JoM6ZJ9g8y4pMzg3sNlCVNe0m2Yclg0Q==",
"license": "MIT", "license": "MIT",
"peer": true, "peer": true,
"engines": { "engines": {
@@ -1793,9 +1809,9 @@
"license": "ISC" "license": "ISC"
}, },
"node_modules/ip-address": { "node_modules/ip-address": {
"version": "10.7.0", "version": "10.7.6",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.0.tgz", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz",
"integrity": "sha512-BGFsyJd5mpXp3rK6jIdADLNgpJUK1jnjzvYF8lK+VyDab9JAmqN0YOKDdP17HlgKb2+ehPgDc8EtnRLbGCAMhA==", "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 12" "node": ">= 12"
@@ -2132,9 +2148,9 @@
} }
}, },
"node_modules/proxy-addr": { "node_modules/proxy-addr": {
"version": "2.0.7", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"forwarded": "0.2.0", "forwarded": "0.2.0",
@@ -2142,6 +2158,10 @@
}, },
"engines": { "engines": {
"node": ">= 0.10" "node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
} }
}, },
"node_modules/proxy-from-env": { "node_modules/proxy-from-env": {
@@ -2154,9 +2174,9 @@
} }
}, },
"node_modules/qs": { "node_modules/qs": {
"version": "6.15.3", "version": "6.16.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz",
"integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", "integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
"es-define-property": "^1.0.1", "es-define-property": "^1.0.1",
@@ -2545,9 +2565,9 @@
} }
}, },
"node_modules/zod": { "node_modules/zod": {
"version": "3.25.76", "version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"license": "MIT", "license": "MIT",
"peer": true, "peer": true,
"funding": { "funding": {
+6 -6
View File
@@ -1,6 +1,6 @@
{ {
"name": "aura-courier-mcp", "name": "aura-courier-mcp",
"version": "2.7.1", "version": "2.7.2",
"description": "Universal Bangladesh courier MCP server for Steadfast, Pathao, RedX, and Paperfly with zero-mock fraud risk, Google Maps routing, enterprise privacy, and token-bucket rate limiting.", "description": "Universal Bangladesh courier MCP server for Steadfast, Pathao, RedX, and Paperfly with zero-mock fraud risk, Google Maps routing, enterprise privacy, and token-bucket rate limiting.",
"main": "dist/index.js", "main": "dist/index.js",
"type": "module", "type": "module",
@@ -16,7 +16,7 @@
}, },
"scripts": { "scripts": {
"build": "tsc", "build": "tsc",
"test": "node --test test/v260.test.mjs test/oauth21.test.mjs", "test": "node --test test/v260.test.mjs test/oauth21.test.mjs test/security_hardening.test.mjs",
"prepublishOnly": "npm run test && npm run build", "prepublishOnly": "npm run test && npm run build",
"start": "node dist/index.js", "start": "node dist/index.js",
"start:http": "node dist/http.js", "start:http": "node dist/http.js",
@@ -47,15 +47,15 @@
"axios": "^1.7.9", "axios": "^1.7.9",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"express": "^4.21.2", "express": "^4.21.2",
"zod": "^3.24.2", "pg": "^8.13.1",
"pg": "^8.13.1" "zod": "^4.6.7"
}, },
"devDependencies": { "devDependencies": {
"@types/express": "^4.17.21", "@types/express": "^4.17.21",
"@types/node": "^22.13.0", "@types/node": "^22.13.0",
"@types/pg": "^8.11.11",
"tsx": "^4.19.2", "tsx": "^4.19.2",
"typescript": "^5.7.3", "typescript": "^5.7.3"
"@types/pg": "^8.11.11"
}, },
"mcpName": "io.github.auraajenticai/aura-courier-mcp" "mcpName": "io.github.auraajenticai/aura-courier-mcp"
} }
+2 -2
View File
@@ -3,7 +3,7 @@
"name": "io.github.auraajenticai/aura-courier-mcp", "name": "io.github.auraajenticai/aura-courier-mcp",
"title": "Aura Courier MCP", "title": "Aura Courier MCP",
"description": "Bangladesh courier connector: Steadfast, Pathao, RedX, Paperfly normalized delivery and tracking.", "description": "Bangladesh courier connector: Steadfast, Pathao, RedX, Paperfly normalized delivery and tracking.",
"version": "2.7.1", "version": "2.7.2",
"websiteUrl": "https://courier.auraajenticai.cloud", "websiteUrl": "https://courier.auraajenticai.cloud",
"repository": { "repository": {
"url": "https://github.com/auraajenticai/aura-courier-mcp", "url": "https://github.com/auraajenticai/aura-courier-mcp",
@@ -19,7 +19,7 @@
{ {
"registryType": "npm", "registryType": "npm",
"identifier": "aura-courier-mcp", "identifier": "aura-courier-mcp",
"version": "2.7.1", "version": "2.7.2",
"transport": { "transport": {
"type": "stdio" "type": "stdio"
}, },
+2 -2
View File
@@ -1706,7 +1706,7 @@
}, },
"aura-courier-local": { "aura-courier-local": {
"command": "npx", "command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"], "args": ["-y", "aura-courier-mcp@2.7.1"],
"env": { "PORT": "8080" } "env": { "PORT": "8080" }
} }
} }
@@ -1723,7 +1723,7 @@
}, },
"aura-courier-stdio": { "aura-courier-stdio": {
"command": "npx", "command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"] "args": ["-y", "aura-courier-mcp@2.7.1"]
} }
} }
}, null, 2) }, null, 2)
+1
View File
@@ -27,6 +27,7 @@ export class PaperflyAdapter implements CourierAdapter {
this.client = axios.create({ this.client = axios.create({
baseURL: baseUrl, baseURL: baseUrl,
timeout: 15000, timeout: 15000,
maxRedirects: 0,
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
}); });
} }
+7 -2
View File
@@ -52,13 +52,17 @@ export class PathaoAdapter implements CourierAdapter {
return this.accessToken; return this.accessToken;
} }
const response = await axios.post(`${this.baseUrl}/aladdin/api/v1/issue-token`, { const response = await axios.post(
`${this.baseUrl}/aladdin/api/v1/issue-token`,
{
client_id: this.clientId, client_id: this.clientId,
client_secret: this.clientSecret, client_secret: this.clientSecret,
username: this.username, username: this.username,
password: this.password, password: this.password,
grant_type: "password", grant_type: "password",
}); },
{ timeout: 12000, maxRedirects: 0 }
);
this.accessToken = response.data.access_token; this.accessToken = response.data.access_token;
this.tokenExpiresAt = now + (response.data.expires_in || 3600) * 1000; this.tokenExpiresAt = now + (response.data.expires_in || 3600) * 1000;
@@ -74,6 +78,7 @@ export class PathaoAdapter implements CourierAdapter {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
timeout: 12000, timeout: 12000,
maxRedirects: 0,
}); });
} }
+1
View File
@@ -25,6 +25,7 @@ export class RedxAdapter implements CourierAdapter {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
timeout: 15000, timeout: 15000,
maxRedirects: 0,
}); });
} }
+1
View File
@@ -25,6 +25,7 @@ export class SteadfastAdapter implements CourierAdapter {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
timeout: 10000, timeout: 10000,
maxRedirects: 0,
}); });
} }
+48 -5
View File
@@ -48,10 +48,53 @@ export interface CourierConfig {
export type EnvSource = Record<string, string | undefined>; export type EnvSource = Record<string, string | undefined>;
export const ALLOWED_CARRIER_HOSTS: Record<"steadfast" | "pathao" | "redx" | "paperfly", readonly string[]> = {
steadfast: ["portal.packzy.com", "portal.steadfast.com.bd"],
pathao: ["api-hermes.pathao.com", "courier-api-sandbox.pathao.com"],
redx: ["openapi.redx.com.bd", "sandbox.redx.com.bd"],
paperfly: ["api.paperfly.com.bd"],
};
/**
* P1-01 Anti-SSRF Guard: Enforce HTTPS-only + strict official carrier hostname allowlist.
* Blocks http:, IP literals (IPv4/IPv6), localhost/.internal, credentials-in-URL, and non-standard ports.
*/
export function validateCarrierBaseUrl(
provider: "steadfast" | "pathao" | "redx" | "paperfly",
candidate: string | undefined,
defaultUrl: string
): string {
const raw = (candidate || "").trim();
if (!raw) return defaultUrl;
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
throw new Error(`Invalid ${provider} base URL format.`);
}
if (parsed.protocol !== "https:") {
throw new Error(`Disallowed ${provider} base URL protocol '${parsed.protocol}' (HTTPS required).`);
}
if (parsed.username || parsed.password) {
throw new Error(`Disallowed credentials in ${provider} base URL.`);
}
if (parsed.port && parsed.port !== "443") {
throw new Error(`Disallowed non-standard port '${parsed.port}' in ${provider} base URL.`);
}
const host = parsed.hostname.toLowerCase();
const allowed = ALLOWED_CARRIER_HOSTS[provider];
if (!allowed.includes(host)) {
throw new Error(
`Disallowed ${provider} base URL host '${host}'. Permitted official hosts: ${allowed.join(", ")}.`
);
}
return parsed.toString().replace(/\/+$/, "");
}
/** /**
* Build a CourierConfig from a key/value source. * Build a CourierConfig from a key/value source.
* Defaults to process.env (used by the STDIO/npx entrypoint); the HTTP * Defaults to process.env (used by the STDIO/npx entrypoint); the HTTP
* entrypoint passes a per-request map built from that client's headers/query. * entrypoint passes a per-request map built from authenticated tenant/BYOK headers.
*/ */
export function loadConfig(src: EnvSource = process.env): CourierConfig { export function loadConfig(src: EnvSource = process.env): CourierConfig {
const steadfastApiKey = src.STEADFAST_API_KEY || ""; const steadfastApiKey = src.STEADFAST_API_KEY || "";
@@ -66,7 +109,7 @@ export function loadConfig(src: EnvSource = process.env): CourierConfig {
steadfast: { steadfast: {
apiKey: steadfastApiKey, apiKey: steadfastApiKey,
secretKey: steadfastSecretKey, secretKey: steadfastSecretKey,
baseUrl: src.STEADFAST_BASE_URL || "https://portal.packzy.com/api/v1", baseUrl: validateCarrierBaseUrl("steadfast", src.STEADFAST_BASE_URL, "https://portal.packzy.com/api/v1"),
enabled: Boolean(steadfastApiKey && steadfastSecretKey), enabled: Boolean(steadfastApiKey && steadfastSecretKey),
}, },
pathao: { pathao: {
@@ -75,12 +118,12 @@ export function loadConfig(src: EnvSource = process.env): CourierConfig {
username: src.PATHAO_USERNAME || "", username: src.PATHAO_USERNAME || "",
password: src.PATHAO_PASSWORD || "", password: src.PATHAO_PASSWORD || "",
storeId: src.PATHAO_STORE_ID || "", storeId: src.PATHAO_STORE_ID || "",
baseUrl: src.PATHAO_BASE_URL || "https://api-hermes.pathao.com", baseUrl: validateCarrierBaseUrl("pathao", src.PATHAO_BASE_URL, "https://api-hermes.pathao.com"),
enabled: Boolean(pathaoClientId && pathaoClientSecret), enabled: Boolean(pathaoClientId && pathaoClientSecret),
}, },
redx: { redx: {
apiToken: src.REDX_API_TOKEN || "", apiToken: src.REDX_API_TOKEN || "",
baseUrl: src.REDX_BASE_URL || "https://openapi.redx.com.bd/v1.0.0-beta", baseUrl: validateCarrierBaseUrl("redx", src.REDX_BASE_URL, "https://openapi.redx.com.bd/v1.0.0-beta"),
pickupStoreId: src.REDX_PICKUP_STORE_ID || "", pickupStoreId: src.REDX_PICKUP_STORE_ID || "",
enabled: Boolean(src.REDX_API_TOKEN), enabled: Boolean(src.REDX_API_TOKEN),
}, },
@@ -89,7 +132,7 @@ export function loadConfig(src: EnvSource = process.env): CourierConfig {
username: src.PAPERFLY_USERNAME || "", username: src.PAPERFLY_USERNAME || "",
password: src.PAPERFLY_PASSWORD || "", password: src.PAPERFLY_PASSWORD || "",
storeName: src.PAPERFLY_STORE_NAME || "", storeName: src.PAPERFLY_STORE_NAME || "",
baseUrl: src.PAPERFLY_BASE_URL || "https://api.paperfly.com.bd", baseUrl: validateCarrierBaseUrl("paperfly", src.PAPERFLY_BASE_URL, "https://api.paperfly.com.bd"),
enabled: Boolean(src.PAPERFLY_API_KEY && src.PAPERFLY_USERNAME), enabled: Boolean(src.PAPERFLY_API_KEY && src.PAPERFLY_USERNAME),
}, },
googleMaps: { googleMaps: {
+197 -46
View File
@@ -1,10 +1,10 @@
import express, { type Express, type Request, type Response } from "express"; import express, { type Express, type Request, type Response } from "express";
import { randomUUID } from "node:crypto"; import { createHash, randomUUID } from "node:crypto";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js"; import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
import { loadConfig, EnvSource } from "./config.js"; import { loadConfig, EnvSource, validateCarrierBaseUrl } from "./config.js";
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js"; import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
import { createRateLimiter } from "./middleware/rate_limit.js"; import { createRateLimiter } from "./middleware/rate_limit.js";
import { import {
@@ -12,7 +12,8 @@ import {
requireMcpAuth, requireMcpAuth,
isActionPermitted, isActionPermitted,
resolveAuthContext, resolveAuthContext,
verifyWebhookSignature, authenticateWebhook,
validateSecurityConfig,
recordAuditLog, recordAuditLog,
initDynamicAuthStore, initDynamicAuthStore,
upsertDynamicKeyHash, upsertDynamicKeyHash,
@@ -97,14 +98,12 @@ function redactAddressToDistrict(addr: string): string {
} }
/** /**
* F10 Fix: Pull client courier keys strictly from request headers. * P0-03 & P1-01 Fix: Pull authenticated tenant BYOK keys strictly from request headers.
* Query parameters are completely ignored to prevent credential leakage in URL logs. * Arbitrary caller base-URL headers are validated against the official HTTPS carrier allowlist
* (rejecting any http:, IP literal, private/internal host, or unlisted domain).
*/ */
export function keysFromRequest(req: Request): EnvSource { export function keysFromRequest(req: Request): EnvSource {
const h = req.headers; const h = req.headers;
// Strict Multi-Tenant & BYOK Isolation:
// If caller explicitly sends any BYOK courier headers (isByok === true), NEVER fall back to
// platform master courier env keys so vendor/merchant BYOK credentials never mix with central keys.
const isByokRequest = Boolean( const isByokRequest = Boolean(
req.auraAuth?.isByok || req.auraAuth?.isByok ||
h["x-steadfast-api-key"] || h["x-steadfast-api-key"] ||
@@ -129,23 +128,39 @@ export function keysFromRequest(req: Request): EnvSource {
return undefined; return undefined;
}; };
// Validate any caller-supplied base URL headers immediately against the strict SSRF allowlist
const pickBaseUrl = (
provider: "steadfast" | "pathao" | "redx" | "paperfly",
header: string,
envVar: string,
defaultUrl: string
): string => {
const hv = h[header];
const headerVal = (Array.isArray(hv) ? hv[0] : hv) || "";
if (typeof headerVal === "string" && headerVal.trim()) {
return validateCarrierBaseUrl(provider, headerVal.trim(), defaultUrl);
}
return validateCarrierBaseUrl(provider, process.env[envVar], defaultUrl);
};
return { return {
STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"), STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"),
STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"), STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"),
STEADFAST_BASE_URL: pick("x-steadfast-base-url", "STEADFAST_BASE_URL", true), STEADFAST_BASE_URL: pickBaseUrl("steadfast", "x-steadfast-base-url", "STEADFAST_BASE_URL", "https://portal.packzy.com/api/v1"),
PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"), PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"),
PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"), PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"),
PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"), PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"),
PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"), PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"),
PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"), PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"),
PATHAO_BASE_URL: pick("x-pathao-base-url", "PATHAO_BASE_URL", true), PATHAO_BASE_URL: pickBaseUrl("pathao", "x-pathao-base-url", "PATHAO_BASE_URL", "https://api-hermes.pathao.com"),
REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"), REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"),
REDX_BASE_URL: pick("x-redx-base-url", "REDX_BASE_URL", true), REDX_BASE_URL: pickBaseUrl("redx", "x-redx-base-url", "REDX_BASE_URL", "https://openapi.redx.com.bd/v1.0.0-beta"),
REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "REDX_PICKUP_STORE_ID"), 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_API_KEY: pick("x-paperfly-api-key", "PAPERFLY_API_KEY"),
PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"), PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"),
PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"), PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"),
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"), PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"),
PAPERFLY_BASE_URL: pickBaseUrl("paperfly", "x-paperfly-base-url", "PAPERFLY_BASE_URL", "https://api.paperfly.com.bd"),
GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true), GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true),
}; };
} }
@@ -177,16 +192,28 @@ app.use((err: any, _req: Request, res: Response, next: any) => {
next(err); next(err);
}); });
// Allow browser-based and cross-origin MCP clients. // Controlled CORS policy: respects CORS_ORIGIN allowlist when configured; excludes arbitrary carrier base-URL headers.
app.use((req, res, next) => { app.use((req, res, next) => {
const configuredOrigins = (process.env.CORS_ORIGIN || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const reqOrigin = req.headers.origin;
if (configuredOrigins.length > 0) {
if (reqOrigin && configuredOrigins.includes(reqOrigin)) {
res.header("Access-Control-Allow-Origin", reqOrigin);
res.header("Vary", "Origin");
}
} else {
res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Origin", "*");
}
res.header( res.header(
"Access-Control-Allow-Methods", "Access-Control-Allow-Methods",
"GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT" "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT"
); );
res.header( res.header(
"Access-Control-Allow-Headers", "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" "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-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-redx-api-token, 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-Expose-Headers", "mcp-session-id, WWW-Authenticate"); res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate");
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
@@ -195,6 +222,37 @@ app.use((req, res, next) => {
next(); next();
}); });
// P1-01 Early Anti-SSRF Header Guard: reject any disallowed carrier base-URL header before routing
app.use((req, res, next) => {
const checks: Array<["steadfast" | "pathao" | "redx" | "paperfly", string, string]> = [
["steadfast", "x-steadfast-base-url", "https://portal.packzy.com/api/v1"],
["pathao", "x-pathao-base-url", "https://api-hermes.pathao.com"],
["redx", "x-redx-base-url", "https://openapi.redx.com.bd/v1.0.0-beta"],
["paperfly", "x-paperfly-base-url", "https://api.paperfly.com.bd"],
];
for (const [prov, hdr, def] of checks) {
const hv = req.headers[hdr];
const val = Array.isArray(hv) ? hv[0] : hv;
if (typeof val === "string" && val.trim()) {
try {
validateCarrierBaseUrl(prov, val.trim(), def);
} catch (err: any) {
return res.status(400).json(
wrapError(
new McpToolError({
code: "INVALID_INPUT",
message: err?.message || `Disallowed ${prov} base URL header.`,
retryable: false,
}),
"validator"
)
);
}
}
}
next();
});
// Static assets (official logo, favicons, branding) & agent MCP configs // Static assets (official logo, favicons, branding) & agent MCP configs
app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" })); app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" }));
app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" })); app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" }));
@@ -489,9 +547,9 @@ app.delete("/mcp", requireMcpAuth, async (req: Request, res: Response) => {
}); });
/** /**
* GET /sse - Standard MCP Server-Sent Events Endpoint for AI Agent Connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) * GET /sse - Authenticated MCP Server-Sent Events Endpoint for AI Agent Connectors
*/ */
app.get("/sse", mcpLimiter, async (req: Request, res: Response) => { app.get("/sse", mcpLimiter, requireMcpAuth, async (req: Request, res: Response) => {
const tenantId = req.auraAuth?.tenantId || "default"; const tenantId = req.auraAuth?.tenantId || "default";
const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key; const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key;
const endpointUrl = token const endpointUrl = token
@@ -516,16 +574,16 @@ app.get("/sse", mcpLimiter, async (req: Request, res: Response) => {
}); });
/** /**
* POST /messages - Standard MCP JSON-RPC Message Ingestion Endpoint for SSE Transports * POST /messages - Authenticated MCP JSON-RPC Message Ingestion Endpoint for SSE Transports
*/ */
app.post("/messages", mcpLimiter, async (req: Request, res: Response) => { app.post("/messages", mcpLimiter, requireMcpAuth, async (req: Request, res: Response) => {
const sessionId = (req.query.sessionId || req.headers["mcp-session-id"]) as string | undefined; const sessionId = (req.query.sessionId || req.headers["mcp-session-id"]) as string | undefined;
if (!sessionId || !sseSessions.has(sessionId)) { if (!sessionId || !sseSessions.has(sessionId)) {
return res.status(400).send("Invalid or missing sessionId"); return res.status(400).send("Invalid or missing sessionId");
} }
const entry = sseSessions.get(sessionId)!; const entry = sseSessions.get(sessionId)!;
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId; const callerTenant = req.auraAuth?.tenantId || "anonymous";
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") { if (entry.tenantId !== callerTenant && callerTenant !== "master") {
return res.status(403).json( return res.status(403).json(
wrapError( wrapError(
new McpToolError({ new McpToolError({
@@ -542,13 +600,42 @@ app.post("/messages", mcpLimiter, async (req: Request, res: Response) => {
await entry.transport.handlePostMessage(req, res, req.body); await entry.transport.handlePostMessage(req, res, req.body);
}); });
// P0-02 Replay Protection Cache (10-minute sliding window, bounded size)
const WEBHOOK_REPLAY_TTL_MS = 10 * 60 * 1000;
const webhookReplayCache = new Map<string, number>();
export function clearWebhookReplayCache(): void {
webhookReplayCache.clear();
}
function checkAndMarkWebhookReplay(key: string): boolean {
const now = Date.now();
const prev = webhookReplayCache.get(key);
if (prev && now - prev < WEBHOOK_REPLAY_TTL_MS) {
return true;
}
webhookReplayCache.set(key, now);
if (webhookReplayCache.size > 5000) {
for (const [k, ts] of webhookReplayCache.entries()) {
if (now - ts >= WEBHOOK_REPLAY_TTL_MS || webhookReplayCache.size > 4000) {
webhookReplayCache.delete(k);
}
}
}
return false;
}
/** /**
* Task T1 & T8 — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly * P0-02 Hardened — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly
* - Rejects unauthenticated/arbitrary merchant_token path segments with 401
* - Never discloses PATHAO_CLIENT_SECRET or AURA_WEBHOOK_SECRET in any response header
* - Derives tenantId strictly from server-side authenticated identity
* - Enforces optional timestamp skew guard (±10 min) and event replay deduplication (409)
*/ */
function handleCourierWebhook(provider: SupportedCourier) { function handleCourierWebhook(provider: SupportedCourier) {
return (req: Request, res: Response) => { return (req: Request, res: Response) => {
const isValidSig = verifyWebhookSignature(req, provider); const whAuth = authenticateWebhook(req, provider);
if (!isValidSig) { if (!whAuth.valid) {
return res.status(401).json( return res.status(401).json(
wrapError( wrapError(
new McpToolError({ new McpToolError({
@@ -562,10 +649,30 @@ function handleCourierWebhook(provider: SupportedCourier) {
); );
} }
// Optional webhook timestamp freshness check (±10 minutes)
const rawTs = (req.headers["x-webhook-timestamp"] || req.headers["x-timestamp"] || "") as string;
if (rawTs) {
const parsedMs = /^\d+$/.test(rawTs.trim())
? (rawTs.trim().length <= 10 ? Number(rawTs.trim()) * 1000 : Number(rawTs.trim()))
: Date.parse(rawTs.trim());
if (!Number.isFinite(parsedMs) || Math.abs(Date.now() - parsedMs) > WEBHOOK_REPLAY_TTL_MS) {
return res.status(401).json(
wrapError(
new McpToolError({
code: "UNAUTHORIZED",
message: "Stale or invalid webhook timestamp (outside ±10 minute replay window).",
courier: provider,
retryable: false,
}),
"validator"
)
);
}
}
const payload = req.body || {}; const payload = req.body || {};
if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") { if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") {
const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || ""; // P0-02 Fix: NEVER return PATHAO_CLIENT_SECRET or AURA_WEBHOOK_SECRET in any HTTP response.
if (secret) res.setHeader("X-Pathao-Merchant-Webhook-Integration-Secret", secret);
return res.status(202).json({ ok: true, status: "webhook_verified" }); return res.status(202).json({ ok: true, status: "webhook_verified" });
} }
@@ -592,8 +699,33 @@ function handleCourierWebhook(provider: SupportedCourier) {
const status = String(payload.status || payload.order_status || payload.event || "received"); const status = String(payload.status || payload.order_status || payload.event || "received");
const eventType = String(payload.notification_type || payload.event || "delivery_status"); const eventType = String(payload.notification_type || payload.event || "delivery_status");
const invoice = payload.invoice || payload.merchant_order_id; const invoice = payload.invoice || payload.merchant_order_id;
const paramMerchantToken = req.params?.merchant_token ? String(req.params.merchant_token).trim() : ""; // P0-02 Fix: Tenant identity comes STRICTLY from server-side verified webhook auth, never arbitrary URL path.
const tenantId = String(paramMerchantToken || req.query.tenant || req.headers["x-tenant-id"] || "default"); const tenantId = whAuth.tenantId;
// Replay deduplication check (header event-id or payload body fingerprint)
const explicitEventId = String(
req.headers["x-webhook-id"] ||
req.headers["x-event-id"] ||
payload.event_id ||
payload.webhook_event_id ||
""
).trim();
const rawBodyHash = createHash("sha256")
.update(req.rawBody ? String(req.rawBody) : JSON.stringify(payload))
.digest("hex")
.slice(0, 24);
const replayKey = explicitEventId
? `${provider}:${tenantId}:id:${explicitEventId}`
: `${provider}:${tenantId}:hash:${consignmentId || "none"}:${status}:${eventType}:${rawBodyHash}`;
if (checkAndMarkWebhookReplay(replayKey)) {
return res.status(409).json({
ok: false,
duplicate: true,
courier: provider,
message: "Duplicate webhook event ignored (replay protection).",
});
}
const record = { const record = {
id: randomUUID(), id: randomUUID(),
@@ -606,13 +738,13 @@ function handleCourierWebhook(provider: SupportedCourier) {
payload, payload,
}; };
// F06: Record webhook event scoped by tenantId // F06: Record webhook event scoped by server-verified tenantId
recordWebhookEvent(record, tenantId); recordWebhookEvent(record, tenantId);
// Forward verified Pathao financial events best-effort to Snehalata Financial Manager // Forward verified Pathao financial events best-effort to Snehalata Financial Manager
if (provider === "pathao" && process.env.NODE_ENV !== "test" && /deliver|return|paid|settlement|invoice/i.test(`${status} ${eventType}`)) { if (provider === "pathao" && process.env.NODE_ENV !== "test" && /deliver|return|paid|settlement|invoice/i.test(`${status} ${eventType}`)) {
const fwdUrl = process.env.SNEHALATA_WEBHOOK_URL || "https://www.snehalata.com/api/webhooks/pathao"; const fwdUrl = process.env.SNEHALATA_WEBHOOK_URL || "https://www.snehalata.com/api/webhooks/pathao";
const sig = String(req.headers["x-pathao-signature"] || process.env.PATHAO_CLIENT_SECRET || ""); const sig = String(req.headers["x-pathao-signature"] || "");
if (fwdUrl && sig) { if (fwdUrl && sig) {
fetch(fwdUrl, { fetch(fwdUrl, {
method: "POST", method: "POST",
@@ -688,27 +820,39 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) { if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) {
if (trackResult) { if (trackResult) {
let sanitized = trackResult;
if (!isOwner) { if (!isOwner) {
sanitized = { // P1-02 Fix: Minimal public DTO — strips raw_response, phone, full address, customer name, and COD value
...trackResult, const publicDto = {
recipient_phone: trackResult.recipient_phone ? maskPhone(trackResult.recipient_phone) : undefined, success: true,
recipient_address: trackResult.recipient_address ? redactAddressToDistrict(trackResult.recipient_address) : undefined, courier: trackResult.courier,
tracking_code: trackResult.tracking_code || code,
status: trackResult.status,
updated_at: trackResult.updated_at,
destination_area: trackResult.recipient_address
? redactAddressToDistrict(trackResult.recipient_address)
: "Bangladesh",
privacy_mode: "public_masked",
}; };
return res.json(wrapSuccess(publicDto, "live_api"));
} }
return res.json(wrapSuccess(sanitized, "live_api")); return res.json(wrapSuccess(trackResult, "live_api"));
} }
if (dbParcel) { if (dbParcel) {
let safeParcel = dbParcel;
if (!isOwner) { if (!isOwner) {
safeParcel = { const publicDbDto = {
...dbParcel, success: true,
recipient_phone: maskPhone(dbParcel.recipient_phone || dbParcel.phone || ""), parcel: {
recipient_address: redactAddressToDistrict(dbParcel.recipient_address || dbParcel.address || ""), courier: dbParcel.courier || courier,
customer_name: dbParcel.customer_name ? dbParcel.customer_name.charAt(0) + "***" : "Customer", tracking_code: dbParcel.tracking_code || code,
status: dbParcel.status || "booked",
updated_at: dbParcel.updated_at || dbParcel.created_at,
destination_area: redactAddressToDistrict(dbParcel.recipient_address || dbParcel.address || ""),
privacy_mode: "public_masked",
},
}; };
return res.json(wrapSuccess(publicDbDto, "cache"));
} }
return res.json(wrapSuccess({ success: true, parcel: safeParcel }, "cache")); return res.json(wrapSuccess({ success: true, parcel: dbParcel }, "cache"));
} }
return res.status(404).json(wrapError(errorObj || new Error("Consignment not found"), "live_api")); return res.status(404).json(wrapError(errorObj || new Error("Consignment not found"), "live_api"));
} }
@@ -717,15 +861,14 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
let recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer"; 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"; let recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh";
// F03: Mask PII for public web tracker view // P1-02 Fix: Strict PII & COD redaction for unauthenticated/non-owner HTML tracker view
if (!isOwner) { if (!isOwner) {
recipientAddress = redactAddressToDistrict(recipientAddress); recipientAddress = redactAddressToDistrict(recipientAddress);
if (recipientName && recipientName.length > 2) { recipientName = "Verified Recipient";
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 codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0;
const codDisplay = isOwner ? `৳ ${Number(codAmount).toLocaleString()}` : "Protected (Merchant Only)";
const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found"); const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found");
const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase(); const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase();
const carrierName = resolvedCourier === "pathao" ? "Pathao Express" : (resolvedCourier === "steadfast" ? "Steadfast Courier" : resolvedCourier === "redx" ? "RedX Delivery" : resolvedCourier === "paperfly" ? "Paperfly Go" : resolvedCourier.toUpperCase()); const carrierName = resolvedCourier === "pathao" ? "Pathao Express" : (resolvedCourier === "steadfast" ? "Steadfast Courier" : resolvedCourier === "redx" ? "RedX Delivery" : resolvedCourier === "paperfly" ? "Paperfly Go" : resolvedCourier.toUpperCase());
@@ -802,7 +945,7 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
</div> </div>
<div class="info-grid"> <div class="info-grid">
<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">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 class="info-item"><div class="info-item-label">Cash on Delivery (COD)</div><div class="info-item-val">${escapeHtml(codDisplay)}</div></div>
</div> </div>
<div class="actions"> <div class="actions">
${shortLink ? `<a href="${escapeHtml(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>` : ""}
@@ -914,6 +1057,14 @@ app.get("/", (_req, res) => {
}); });
if (process.env.NODE_ENV !== "test") { if (process.env.NODE_ENV !== "test") {
const sec = validateSecurityConfig();
if (!sec.ok) {
console.error("[FATAL SECURITY CONFIG] Refusing to start Aura Courier MCP without strong secrets:");
for (const e of sec.errors) {
console.error(` - ${e}`);
}
process.exit(1);
}
app.listen(PORT, () => { app.listen(PORT, () => {
console.log(`Aura Courier MCP v${APP_VERSION} (HTTP) listening on :${PORT} — POST /mcp`); console.log(`Aura Courier MCP v${APP_VERSION} (HTTP) listening on :${PORT} — POST /mcp`);
}); });
+269 -81
View File
@@ -57,18 +57,137 @@ export interface AuditEntry {
} }
export const auditLogBuffer: AuditEntry[] = []; export const auditLogBuffer: AuditEntry[] = [];
export const FORBIDDEN_WEAK_SECRETS = new Set([
"aura_live_mcp_master_key_2026",
"aura_ro_public_inspector_2026",
"aura_webhook_secret_2026",
"change_me",
"changeme",
"secret",
"password",
"default",
"test",
]);
export function isStrongSecret(val: string | undefined, minLen = 20): boolean {
if (!val || typeof val !== "string") return false;
const v = val.trim();
if (v.length < minLen) return false;
const low = v.toLowerCase();
if (FORBIDDEN_WEAK_SECRETS.has(low)) return false;
if (low.startsWith("your_") || low.includes("<generate") || low.includes("replace_me")) return false;
return true;
}
export function getMasterKey(): string {
const candidate = (process.env.AURA_API_KEY || process.env.COURIER_AUTH_TOKEN || "").trim();
return isStrongSecret(candidate, 20) ? candidate : "";
}
export function getAdminKey(): string {
const explicit = (process.env.AURA_ADMIN_KEY || "").trim();
if (explicit) return isStrongSecret(explicit, 20) ? explicit : "";
return getMasterKey();
}
export function getReadOnlyKey(): string {
const candidate = (process.env.AURA_READONLY_KEY || "").trim();
return isStrongSecret(candidate, 16) ? candidate : "";
}
export function getWebhookSecret(): string {
const candidate = (process.env.AURA_WEBHOOK_SECRET || "").trim();
return isStrongSecret(candidate, 20) ? candidate : "";
}
export function validateSecurityConfig(): { ok: boolean; errors: string[] } {
const errors: string[] = [];
if (!getMasterKey()) {
errors.push("AURA_API_KEY (or COURIER_AUTH_TOKEN) is missing, weak (<20 chars), or uses a forbidden default value.");
}
if (process.env.AURA_ADMIN_KEY && !isStrongSecret(process.env.AURA_ADMIN_KEY, 20)) {
errors.push("AURA_ADMIN_KEY is weak (<20 chars) or uses a forbidden default value.");
}
if (process.env.AURA_READONLY_KEY && !isStrongSecret(process.env.AURA_READONLY_KEY, 16)) {
errors.push("AURA_READONLY_KEY is weak (<16 chars) or uses a forbidden default value.");
}
if (!getWebhookSecret()) {
errors.push("AURA_WEBHOOK_SECRET is missing, weak (<20 chars), or uses a forbidden default value.");
}
const oauthSecret = (process.env.AURA_OAUTH_SECRET || "").trim();
if (oauthSecret && !isStrongSecret(oauthSecret, 24)) {
errors.push("AURA_OAUTH_SECRET is weak (<24 chars) or uses a forbidden default value.");
} else if (!oauthSecret && !getMasterKey()) {
errors.push("AURA_OAUTH_SECRET (or strong AURA_API_KEY) is required for OAuth 2.1 token signing.");
}
return { ok: errors.length === 0, errors };
}
function headerStr(req: Request, name: string): string {
const v = req.headers[name];
if (Array.isArray(v)) return String(v[0] || "").trim();
return typeof v === "string" ? v.trim() : "";
}
/** /**
* F10 Fix: Accept BYOK credentials STRICTLY from request headers. * P0-03 Fix: Detect and validate BYOK carrier credential bundles strictly from request headers.
* Query parameters are completely ignored to avoid leaking secrets in proxy/access logs. * Every BYOK provider supplied must include its complete required credential set.
* BYOK NEVER bypasses Aura authentication or tool scopes.
*/ */
export function validateByokHeaders(req: Request): { isByok: boolean; valid: boolean; reason?: string } {
const sfKey = headerStr(req, "x-steadfast-api-key");
const sfSec = headerStr(req, "x-steadfast-secret-key");
const pId = headerStr(req, "x-pathao-client-id");
const pSec = headerStr(req, "x-pathao-client-secret");
const pUser = headerStr(req, "x-pathao-username");
const pPass = headerStr(req, "x-pathao-password");
const rxTok = headerStr(req, "x-redx-api-token");
const pfKey = headerStr(req, "x-paperfly-api-key");
const pfUser = headerStr(req, "x-paperfly-username");
const pfPass = headerStr(req, "x-paperfly-password");
const hasSf = Boolean(sfKey || sfSec);
const hasPathao = Boolean(pId || pSec || pUser || pPass);
const hasRx = Boolean(rxTok);
const hasPf = Boolean(pfKey || pfUser || pfPass);
const isByok = hasSf || hasPathao || hasRx || hasPf;
if (!isByok) return { isByok: false, valid: true };
if (hasSf && (sfKey.length < 6 || sfSec.length < 6)) {
return {
isByok: true,
valid: false,
reason: "Incomplete Steadfast BYOK bundle: both x-steadfast-api-key and x-steadfast-secret-key (>=6 chars) are required.",
};
}
if (hasPathao && (!pId || !pSec || !pUser || !pPass)) {
return {
isByok: true,
valid: false,
reason: "Incomplete Pathao BYOK bundle: x-pathao-client-id, x-pathao-client-secret, x-pathao-username, and x-pathao-password are all required.",
};
}
if (hasRx && rxTok.length < 12) {
return {
isByok: true,
valid: false,
reason: "Invalid RedX BYOK bundle: x-redx-api-token must be at least 12 characters.",
};
}
if (hasPf && (!pfKey || !pfUser || !pfPass)) {
return {
isByok: true,
valid: false,
reason: "Incomplete Paperfly BYOK bundle: x-paperfly-api-key, x-paperfly-username, and x-paperfly-password are all required.",
};
}
return { isByok: true, valid: true };
}
export function hasByokCredentials(req: Request): boolean { export function hasByokCredentials(req: Request): boolean {
const h = req.headers; return validateByokHeaders(req).isByok;
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: Request): string | undefined { export function extractBearerToken(req: Request): string | undefined {
@@ -246,19 +365,16 @@ export function registerApiKey(token: string, tenantId: string, scopes: AuthScop
} }
/** /**
* F01 Fix: Cryptographic Token Resolution without prefix bypass. * P0-01 Fix: Fail-Closed Cryptographic Token Resolution.
* Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished. * Zero hardcoded fallback keys; zero prefix bypasses.
*/ */
export function resolveAuthContext(req: Request): AuraAuthContext { export function resolveAuthContext(req: Request): AuraAuthContext {
const token = extractBearerToken(req); const token = extractBearerToken(req);
const isByok = hasByokCredentials(req); const isByok = hasByokCredentials(req);
const masterKey = const masterKey = getMasterKey();
process.env.AURA_API_KEY || const readOnlyKey = getReadOnlyKey();
process.env.COURIER_AUTH_TOKEN || const adminKey = getAdminKey();
"aura_live_mcp_master_key_2026";
const readOnlyKey = process.env.AURA_READONLY_KEY || "aura_ro_public_inspector_2026";
const adminKey = process.env.AURA_ADMIN_KEY || masterKey;
if (!token) { if (!token) {
return { return {
@@ -270,6 +386,17 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
}; };
} }
// Reject known leaked/default weak tokens unconditionally
if (FORBIDDEN_WEAK_SECRETS.has(token.toLowerCase())) {
return {
authenticated: false,
tenantId: "invalid",
scopes: [],
isByok,
isAdmin: false,
};
}
// 0. Standard MCP OAuth 2.1 JWT Access Token (Google Gemini, ChatGPT, Claude Web) // 0. Standard MCP OAuth 2.1 JWT Access Token (Google Gemini, ChatGPT, Claude Web)
if (token.startsWith("eyJ") && token.split(".").length === 3) { if (token.startsWith("eyJ") && token.split(".").length === 3) {
const oauthClaims = verifyOAuthAccessToken(token); const oauthClaims = verifyOAuthAccessToken(token);
@@ -285,8 +412,8 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
} }
} }
// 1. Master / Admin Key (Full Read + Write across all tenants) // 1. Master / Admin Key (Full Read + Write across all tenants — strictly from strong env secret)
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) { if ((masterKey && safeCompare(token, masterKey)) || (adminKey && safeCompare(token, adminKey))) {
return { return {
authenticated: true, authenticated: true,
tenantId: "master", tenantId: "master",
@@ -297,8 +424,8 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
}; };
} }
// 2. Read-Only Gateway Discovery Key // 2. Read-Only Gateway Discovery Key (strictly from strong env secret)
if (safeCompare(token, readOnlyKey) || safeCompare(token, "aura_ro_public_inspector_2026")) { if (readOnlyKey && safeCompare(token, readOnlyKey)) {
return { return {
authenticated: true, authenticated: true,
tenantId: "public_ro", tenantId: "public_ro",
@@ -414,11 +541,8 @@ export async function resolveAuthContextAsync(req: Request): Promise<AuraAuthCon
} }
const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key"; const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key";
const syncSecret = const syncSecret = (process.env.AURA_MCP_SYNC_SECRET || getMasterKey()).trim();
process.env.AURA_MCP_SYNC_SECRET || if (!syncSecret) return local;
process.env.AURA_API_KEY ||
process.env.COURIER_AUTH_TOKEN ||
"aura_live_mcp_master_key_2026";
const ctrl = new AbortController(); const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 3500); const timer = setTimeout(() => ctrl.abort(), 3500);
@@ -509,18 +633,29 @@ export function requireMcpAuth(req: Request, res: Response, next: NextFunction):
return next(); return next();
} }
// BYOK headers (x-steadfast-api-key, etc.) allow tool execution with caller's carrier credentials // P0-03 Fix: NEVER bypass Aura auth on BYOK headers. Authenticate caller first, then validate BYOK bundle.
if (ctx.isByok) {
return next();
}
if (!ctx.authenticated) { if (!ctx.authenticated) {
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, false)); res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, false));
res.status(401).json( res.status(401).json(
wrapError( wrapError(
new McpToolError({ new McpToolError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Authenticate via MCP OAuth 2.1 or provide your API key / BYOK carrier keys.", message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Authenticate via MCP OAuth 2.1 or provide a valid tenant API key (BYOK headers require authentication too).",
retryable: false,
source: "validator",
})
)
);
return;
}
const byokCheck = validateByokHeaders(req);
if (byokCheck.isByok && !byokCheck.valid) {
res.status(400).json(
wrapError(
new McpToolError({
code: "INVALID_INPUT",
message: byokCheck.reason || "Incomplete BYOK carrier credential bundle.",
retryable: false, retryable: false,
source: "validator", source: "validator",
}) })
@@ -574,24 +709,31 @@ export function isActionPermitted(
}; };
} }
// F14: list_couriers is allowed for discovery // P0-03 Fix: Every tool invocation (including BYOK) MUST be authenticated and pass scope checks.
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) { if (!ctx.authenticated) {
recordAuditLog(ctx.tenantId, toolName, args, "denied"); recordAuditLog(ctx.tenantId, toolName, args, "denied");
return { return {
permitted: false, permitted: false,
reason: "Unauthorized: valid Authorization: Bearer <key> required.", reason: "Unauthorized: valid Authorization: Bearer <key> or OAuth 2.1 token required.",
}; };
} }
if (ctx.isByok) {
const byokCheck = validateByokHeaders(req);
if (!byokCheck.valid) {
recordAuditLog(ctx.tenantId, toolName, args, "denied");
return {
permitted: false,
reason: byokCheck.reason || "Incomplete BYOK carrier credential bundle.",
};
}
}
// F14: list_couriers is allowed for any authenticated caller (read discovery)
if (toolName === "list_couriers") {
return { permitted: true };
}
const requiredScope: AuthScope = WRITE_TOOLS.has(toolName) || !READ_TOOLS.has(toolName) ? "write" : "read"; const requiredScope: AuthScope = WRITE_TOOLS.has(toolName) || !READ_TOOLS.has(toolName) ? "write" : "read";
if (!ctx.scopes.includes(requiredScope)) { if (!ctx.scopes.includes(requiredScope)) {
recordAuditLog(ctx.tenantId, toolName, args, "denied"); recordAuditLog(ctx.tenantId, toolName, args, "denied");
@@ -637,78 +779,124 @@ export function recordAuditLog(
} }
} }
export interface WebhookAuthResult {
valid: boolean;
tenantId: string;
authMethod?: string;
}
/** /**
* F09 Fix: Native Carrier Webhook HMAC-SHA256 & Token Verification. * P0-02 Fix: Fail-Closed Carrier Webhook Authentication & Server-Side Tenant Resolution.
* Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body. * - Abolishes arbitrary >=8-char URL path token acceptance.
* Steadfast uses secret key header comparison. * - Abolishes hardcoded webhook secret fallbacks.
* - Resolves tenantId strictly from server-side verified key/provider bindings (never attacker-supplied URL paths).
*/ */
export function verifyWebhookSignature(req: Request, provider: string): boolean { export function authenticateWebhook(req: Request, provider: string): WebhookAuthResult {
const prov = (provider || "").toLowerCase(); const prov = (provider || "").toLowerCase();
const webhookMasterSecret = getWebhookSecret();
// 1. Pathao Webhook: Verify X-Pathao-Signature via HMAC-SHA256 // 1. Pathao Webhook: Verify X-Pathao-Signature via HMAC-SHA256 over raw body
const pathaoSig = (req.headers["x-pathao-signature"] || req.headers["x-signature"]) as string | undefined; const pathaoSig = (req.headers["x-pathao-signature"] || req.headers["x-signature"]) as string | undefined;
if (prov === "pathao" && pathaoSig) { if (prov === "pathao" && pathaoSig && typeof pathaoSig === "string") {
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 rawBody = req.rawBody ? String(req.rawBody) : JSON.stringify(req.body || {});
const candidateSecrets = [
(process.env.PATHAO_WEBHOOK_SECRET || "").trim(),
(process.env.PATHAO_CLIENT_SECRET || "").trim(),
webhookMasterSecret,
].filter(Boolean);
for (const secret of candidateSecrets) {
const expected = createHmac("sha256", secret).update(rawBody).digest("hex"); const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
if (safeCompare(pathaoSig, expected)) return true; if (safeCompare(pathaoSig.trim(), expected)) {
return {
valid: true,
tenantId: (process.env.PATHAO_WEBHOOK_TENANT || "default").trim() || "default",
authMethod: "pathao_hmac",
};
}
} }
} }
// 2. Steadfast Webhook: Verify X-Steadfast-Signature or secret token // 2. Steadfast Webhook: Verify X-Steadfast-Signature or secret header against STEADFAST_SECRET_KEY
const sfSig = (req.headers["x-steadfast-signature"] || req.headers["x-webhook-secret"] || req.query["token"]) as string | undefined; const sfSig = (req.headers["x-steadfast-signature"] || req.headers["x-webhook-secret"]) as string | undefined;
if (prov === "steadfast" && sfSig) { if (prov === "steadfast" && sfSig && typeof sfSig === "string") {
const sfSecret = process.env.STEADFAST_SECRET_KEY || process.env.AURA_WEBHOOK_SECRET || ""; const sfSecret = (process.env.STEADFAST_SECRET_KEY || "").trim();
if (sfSecret && safeCompare(sfSig, sfSecret)) return true; if (sfSecret && safeCompare(sfSig.trim(), sfSecret)) {
return { valid: true, tenantId: "default", authMethod: "steadfast_secret" };
}
} }
// 3. RedX & Paperfly Webhook Headers // 3. RedX & Paperfly Provider Secrets
const rxSig = (req.headers["x-redx-signature"] || req.headers["x-webhook-secret"]) as string | undefined; const rxSig = (req.headers["x-redx-signature"] || req.headers["x-webhook-secret"]) as string | undefined;
if (prov === "redx" && rxSig) { if (prov === "redx" && rxSig && typeof rxSig === "string") {
const rxSecret = process.env.REDX_API_TOKEN || process.env.AURA_WEBHOOK_SECRET || ""; const rxSecret = (process.env.REDX_API_TOKEN || "").trim();
if (rxSecret && safeCompare(rxSig, rxSecret)) return true; if (rxSecret && safeCompare(rxSig.trim(), rxSecret)) {
return { valid: true, tenantId: "default", authMethod: "redx_secret" };
}
} }
const pfSig = (req.headers["x-paperfly-signature"] || req.headers["x-webhook-secret"]) as string | undefined; const pfSig = (req.headers["x-paperfly-signature"] || req.headers["x-webhook-secret"]) as string | undefined;
if (prov === "paperfly" && pfSig) { if (prov === "paperfly" && pfSig && typeof pfSig === "string") {
const pfSecret = process.env.PAPERFLY_API_KEY || process.env.AURA_WEBHOOK_SECRET || ""; const pfSecret = (process.env.PAPERFLY_API_KEY || "").trim();
if (pfSecret && safeCompare(pfSig, pfSecret)) return true; if (pfSecret && safeCompare(pfSig.trim(), pfSecret)) {
return { valid: true, tenantId: "default", authMethod: "paperfly_secret" };
}
} }
// 4. Universal master secret, registered tenant key, or merchant_token URL parameter fallback // 4. Platform Webhook Master Secret or Cryptographically Registered Tenant Key ONLY
const masterSecret = process.env.AURA_WEBHOOK_SECRET || process.env.AURA_API_KEY || "aura_webhook_secret_2026"; const paramToken = (req.params && (req.params as any).merchant_token)
const paramToken = (req.params && (req.params as any).merchant_token) ? String((req.params as any).merchant_token).trim() : undefined; ? String((req.params as any).merchant_token).trim()
: undefined;
const candidate = const candidate =
paramToken ||
extractBearerToken(req) ||
(req.headers["x-webhook-secret"] as string | undefined) || (req.headers["x-webhook-secret"] as string | undefined) ||
(req.query["token"] as string | undefined) || extractBearerToken(req) ||
(req.query["secret"] as string | undefined); paramToken;
if (candidate && typeof candidate === "string") { if (candidate && typeof candidate === "string") {
const trimmed = candidate.trim(); const trimmed = candidate.trim();
if (safeCompare(trimmed, masterSecret)) { if (!trimmed || FORBIDDEN_WEAK_SECRETS.has(trimmed.toLowerCase())) {
return true; return { valid: false, tenantId: "unauthorized" };
} }
// 4a. Platform Webhook Master Secret (server-trusted caller may specify tenant scope via query/header)
if (webhookMasterSecret && safeCompare(trimmed, webhookMasterSecret)) {
const requestedTenant = String(
(req.query && (req.query as any).tenant) ||
req.headers["x-tenant-id"] ||
"default"
).trim();
const safeTenant = /^[a-zA-Z0-9_\-]{1,64}$/.test(requestedTenant) ? requestedTenant : "default";
return { valid: true, tenantId: safeTenant, authMethod: "webhook_master_secret" };
}
// 4b. Registered Static / Dynamic Tenant Key (SHA-256 lookup — tenant strictly bound server-side)
const tokenHash = createHash("sha256").update(trimmed).digest("hex"); const tokenHash = createHash("sha256").update(trimmed).digest("hex");
if (registeredKeyHashes.has(tokenHash)) { if (registeredKeyHashes.has(tokenHash)) {
return true; const reg = registeredKeyHashes.get(tokenHash)!;
return { valid: true, tenantId: reg.tenantId, authMethod: "registered_tenant_key" };
} }
if (dynamicKeyHashes.has(tokenHash)) {
const dyn = dynamicKeyHashes.get(tokenHash)!;
if (dyn.status === "ACTIVE") {
return { valid: true, tenantId: dyn.tenantId, authMethod: "dynamic_tenant_key" };
}
return { valid: false, tenantId: "unauthorized" };
}
// 4c. Env-configured Tenant Keys (strictly compare against secret key tKey, NEVER tenant ID tId)
const envTenants = process.env.AURA_TENANT_KEYS; const envTenants = process.env.AURA_TENANT_KEYS;
if (envTenants) { if (envTenants) {
for (const pair of envTenants.split(",")) { for (const pair of envTenants.split(",")) {
const [tId, tKey] = pair.split(":"); const [tId, tKey] = pair.split(":");
if ((tKey && safeCompare(trimmed, tKey.trim())) || (tId && safeCompare(trimmed, tId.trim()))) { if (tId && tKey && isStrongSecret(tKey.trim(), 16) && safeCompare(trimmed, tKey.trim())) {
return true; return { valid: true, tenantId: tId.trim(), authMethod: "env_tenant_key" };
} }
} }
} }
// Accept non-empty merchant_token path identifier (>= 8 chars) for dedicated merchant webhook endpoints
if (paramToken && paramToken.length >= 8 && /^[a-zA-Z0-9_\-]+$/.test(paramToken)) {
return true;
}
} }
return false; return { valid: false, tenantId: "unauthorized" };
}
export function verifyWebhookSignature(req: Request, provider: string): boolean {
return authenticateWebhook(req, provider).valid;
} }
+16 -3
View File
@@ -81,13 +81,26 @@ interface AuraSsoUser {
role: "owner" | "admin" | "client" | "team_member"; role: "owner" | "admin" | "client" | "team_member";
} }
const OAUTH_FORBIDDEN_DEFAULTS = new Set([
"aura_live_mcp_master_key_2026",
"aura_ro_public_inspector_2026",
"aura_webhook_secret_2026",
"change_me",
"changeme",
"secret",
]);
function getRootSecret(): string { function getRootSecret(): string {
return ( const raw = (
process.env.AURA_OAUTH_SECRET || process.env.AURA_OAUTH_SECRET ||
process.env.AURA_API_KEY || process.env.AURA_API_KEY ||
process.env.COURIER_AUTH_TOKEN || process.env.COURIER_AUTH_TOKEN ||
"aura_live_mcp_master_key_2026" ""
); ).trim();
if (raw.length < 20 || OAUTH_FORBIDDEN_DEFAULTS.has(raw.toLowerCase())) {
throw new Error("AURA_OAUTH_SECRET (or strong AURA_API_KEY >=20 chars) must be configured; predictable defaults are forbidden.");
}
return raw;
} }
function deriveKey(purpose: string): Buffer { function deriveKey(purpose: string): Buffer {
+173 -5
View File
@@ -33,12 +33,19 @@ export function setRegistryDbPool(pool: any): void {
} }
/** /**
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8). * Process-wide Atomic & Durable Idempotency Store keyed by `${tenantId}:${invoice}` (P1-03 & P1-04).
*/ */
const idempotencyStore = new Map<string, ParcelResponse>(); const idempotencyStore = new Map<string, ParcelResponse>();
const inFlightBookings = new Map<string, Promise<ParcelResponse>>();
const pendingReconciliationStore = new Map<
string,
{ courier: SupportedCourier; invoice: string; reason: string; timestamp: string }
>();
export function clearIdempotencyStore(): void { export function clearIdempotencyStore(): void {
idempotencyStore.clear(); idempotencyStore.clear();
inFlightBookings.clear();
pendingReconciliationStore.clear();
} }
/** /**
@@ -84,6 +91,33 @@ function isNetworkTimeout(err: any): boolean {
); );
} }
/**
* P1-04 Fix: Only cascade to a fallback courier on a DEFINITE pre-booking rejection
* (4xx client/validation/auth/unconfigured errors). Any 5xx, timeout, network drop, or
* malformed response after dispatch is AMBIGUOUS and halts cascade to prevent duplicates.
*/
function isDefinitePreBookingRejection(err: any): boolean {
if (!err) return false;
if (isNetworkTimeout(err)) return false;
const status = Number(err?.response?.status || err?.status || err?.statusCode || 0);
if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
return true;
}
if (err instanceof McpToolError) {
return ["INVALID_INPUT", "UNCONFIGURED", "NO_COVERAGE", "UNAUTHORIZED", "CONSIGNMENT_NOT_FOUND"].includes(err.code);
}
const msg = String(err.message || "").toLowerCase();
return (
msg.includes("not configured") ||
msg.includes("credentials") ||
msg.includes("could not match a delivery area") ||
msg.includes("store name is required") ||
msg.includes("store_id") ||
msg.includes("invalid phone") ||
msg.includes("validation failed")
);
}
export class CourierRegistry { export class CourierRegistry {
private adapters: Map<SupportedCourier, CourierAdapter> = new Map(); private adapters: Map<SupportedCourier, CourierAdapter> = new Map();
private googleMaps: GoogleMapsAdapter; private googleMaps: GoogleMapsAdapter;
@@ -253,9 +287,10 @@ export class CourierRegistry {
}; };
} }
// Task T8: Idempotency by (tenant_id, invoice) // P1-03 & P1-04 Fix: Atomic in-flight reservation + durable PostgreSQL idempotency by (tenant_id, invoice)
const tenantKey = String(req.tenant_id || "default"); const tenantKey = String(req.tenant_id || "default");
const idemKey = `${tenantKey}:${invoice}`; const idemKey = `${tenantKey}:${invoice}`;
const existing = idempotencyStore.get(idemKey); const existing = idempotencyStore.get(idemKey);
if (existing) { if (existing) {
return { return {
@@ -264,6 +299,65 @@ export class CourierRegistry {
}; };
} }
const pendingRecon = pendingReconciliationStore.get(idemKey);
if (pendingRecon) {
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `Invoice '${invoice}' has an unresolved ambiguous booking attempt on '${pendingRecon.courier}'. Halting duplicate creation until reconciled.`,
courier: pendingRecon.courier,
retryable: true,
extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION",
ambiguous_outcome: true,
courier_attempted: pendingRecon.courier,
invoice,
},
});
}
// Coalesce concurrent identical (tenant, invoice) requests onto ONE single upstream call
const inFlight = inFlightBookings.get(idemKey);
if (inFlight) {
const sharedResult = await inFlight;
return {
...sharedResult,
idempotent_replay: true,
};
}
const bookingPromise = (async (): Promise<ParcelResponse> => {
// Check durable PostgreSQL ledger before hitting upstream carrier (survives restarts/redeployments)
if (registryDbPool) {
try {
const dbHit = await registryDbPool.query(
`SELECT courier, tracking_code, status, cod_amount, raw
FROM courier_parcels
WHERE tenant = $1 AND (raw->>'invoice' = $2 OR raw->>'idempotency_key' = $3)
ORDER BY created_at DESC LIMIT 1`,
[tenantKey, invoice, idemKey]
);
if (dbHit?.rows && dbHit.rows.length > 0) {
const row = dbHit.rows[0];
const recovered: ParcelResponse = {
success: true,
courier: (row.courier || candidates[0]) as SupportedCourier,
tracking_code: String(row.tracking_code || ""),
consignment_id: row.raw?.consignment_id || row.tracking_code,
invoice,
status: String(row.status || "booked"),
cod_amount: Number(row.cod_amount ?? codAmount),
idempotent_replay: true,
routing_reason: `Recovered existing booking from durable PostgreSQL ledger for invoice '${invoice}'.`,
cancellable_via_api: false,
};
idempotencyStore.set(idemKey, recovered);
return recovered;
}
} catch (dbErr: any) {
console.warn("[Registry] Durable idempotency lookup skipped:", dbErr?.message);
}
}
let lastErr: any = null; let lastErr: any = null;
for (const courierName of candidates) { for (const courierName of candidates) {
try { try {
@@ -293,24 +387,90 @@ export class CourierRegistry {
}, },
}; };
idempotencyStore.set(idemKey, enriched); idempotencyStore.set(idemKey, enriched);
// Persist durably in PostgreSQL if connected
if (registryDbPool && enriched.tracking_code) {
try {
await registryDbPool.query(
`INSERT INTO courier_parcels
(tenant, source, courier, tracking_code, customer_name, phone, address, cod_amount, item_description, status, raw)
VALUES ($1, 'mcp', $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb)
ON CONFLICT (tenant, tracking_code) DO NOTHING`,
[
tenantKey,
courierName,
String(enriched.tracking_code),
String(req.recipient_name || ""),
cleanPhone,
addrStr,
Number(codAmount || 0),
String(req.note || req.item_type || ""),
String(enriched.status || "booked"),
JSON.stringify({
invoice,
idempotency_key: idemKey,
consignment_id: enriched.consignment_id,
}),
]
);
} catch (persistErr: any) {
console.warn("[Registry] Durable parcel persist skipped:", persistErr?.message);
}
}
return enriched; return enriched;
} }
// Ambiguous non-error response missing tracking_code/consignment_id -> HALT cascade (P1-04)
if (res && res.success !== false) {
pendingReconciliationStore.set(idemKey, {
courier: courierName,
invoice,
reason: "Ambiguous upstream response without tracking_code/consignment_id",
timestamp: new Date().toISOString(),
});
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `Carrier ${courierName} returned an ambiguous response without tracking_code/consignment_id. Halting cascade to prevent duplicate booking. State is UNKNOWN_PENDING_RECONCILIATION.`,
courier: courierName,
retryable: true,
extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION",
ambiguous_outcome: true,
courier_attempted: courierName,
invoice,
},
});
}
lastErr = new McpToolError({ lastErr = new McpToolError({
code: "COURIER_UPSTREAM_ERROR", code: "COURIER_UPSTREAM_ERROR",
message: (res as any)?.message || (res as any)?.error || `${courierName} rejected parcel booking.`, message: (res as any)?.message || (res as any)?.error || `${courierName} rejected parcel booking.`,
courier: courierName, courier: courierName,
}); });
} catch (err: any) { } catch (err: any) {
if (err instanceof McpToolError && err.extraFields?.status === "UNKNOWN_PENDING_RECONCILIATION") {
throw err;
}
lastErr = err; lastErr = err;
if (isNetworkTimeout(err)) { if (!isDefinitePreBookingRejection(err)) {
const isTimeout = isNetworkTimeout(err);
pendingReconciliationStore.set(idemKey, {
courier: courierName,
invoice,
reason: err?.message || "Ambiguous upstream failure",
timestamp: new Date().toISOString(),
});
throw new McpToolError({ throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR", 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.", message: isTimeout
? `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.`
: `Carrier ${courierName} returned an ambiguous upstream outcome (${err?.message || "unknown error"}). Halting cascade to prevent duplicate parcel creation. State is UNKNOWN_PENDING_RECONCILIATION.`,
courier: courierName, courier: courierName,
retryable: true, retryable: true,
extraFields: { extraFields: {
status: "UNKNOWN_PENDING_RECONCILIATION", status: "UNKNOWN_PENDING_RECONCILIATION",
timeout_uncertain: true, timeout_uncertain: isTimeout,
ambiguous_outcome: true,
courier_attempted: courierName, courier_attempted: courierName,
invoice, invoice,
}, },
@@ -326,6 +486,14 @@ export class CourierRegistry {
code: "COURIER_UPSTREAM_ERROR", code: "COURIER_UPSTREAM_ERROR",
message: lastErr?.message || "All configured courier gateways failed to book parcel.", message: lastErr?.message || "All configured courier gateways failed to book parcel.",
}); });
})();
inFlightBookings.set(idemKey, bookingPromise);
try {
return await bookingPromise;
} finally {
inFlightBookings.delete(idemKey);
}
} }
async trackParcel(trackingCode: string, courierName?: SupportedCourier): Promise<TrackingResponse> { async trackParcel(trackingCode: string, courierName?: SupportedCourier): Promise<TrackingResponse> {
+1 -1
View File
@@ -11,7 +11,7 @@ function readPackageVersion(): string {
} catch { } catch {
// Fallback if package.json is unavailable at runtime // Fallback if package.json is unavailable at runtime
} }
return "2.7.1"; return "2.7.2";
} }
export const APP_VERSION: string = readPackageVersion(); export const APP_VERSION: string = readPackageVersion();
+533
View File
@@ -0,0 +1,533 @@
import test from "node:test";
import assert from "node:assert/strict";
import http from "node:http";
import { createHmac } from "node:crypto";
import { spawnSync } from "node:child_process";
process.env.NODE_ENV = "test";
process.env.AURA_API_KEY = "aura_sec_master_key_9f8e7d6c5b4a3210fedcba987654";
process.env.AURA_ADMIN_KEY = "aura_sec_admin_key_1234567890abcdef1234567890ab";
process.env.AURA_READONLY_KEY = "aura_sec_ro_key_abcdef1234567890";
process.env.AURA_WEBHOOK_SECRET = "aura_sec_webhook_key_0123456789abcdef0123456789";
process.env.AURA_OAUTH_SECRET = "aura_sec_oauth_root_fedcba9876543210fedcba987654";
process.env.PATHAO_CLIENT_ID = "pathao_test_id";
process.env.PATHAO_CLIENT_SECRET = "pathao_super_secret_do_not_leak_9999999999";
process.env.STEADFAST_API_KEY = "sf_test_key_valid";
process.env.STEADFAST_SECRET_KEY = "sf_test_secret_valid";
const { app, clearWebhookReplayCache } = await import("../dist/http.js");
const {
resolveAuthContext,
validateSecurityConfig,
registerApiKey,
authenticateWebhook,
} = await import("../dist/middleware/auth.js");
const { validateCarrierBaseUrl } = await import("../dist/config.js");
const {
clearIdempotencyStore,
clearWebhookEvents,
setRegistryDbPool,
} = await import("../dist/registry.js");
const { SteadfastAdapter } = await import("../dist/adapters/steadfast.js");
const { PathaoAdapter } = await import("../dist/adapters/pathao.js");
let server;
let baseUrl;
test.before(async () => {
server = http.createServer(app);
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const addr = server.address();
baseUrl = `http://127.0.0.1:${addr.port}`;
});
test.after(async () => {
setRegistryDbPool(null);
if (server) {
await new Promise((resolve) => server.close(resolve));
}
});
test("P0-01: Predictable hardcoded fallback keys are ALWAYS rejected & startup fails closed without strong secrets", async () => {
// 1. Live server rejects old default master & readonly keys
for (const leakedKey of ["aura_live_mcp_master_key_2026", "aura_ro_public_inspector_2026", "aura_webhook_secret_2026"]) {
const res = await fetch(`${baseUrl}/admin/tokens`, {
headers: { Authorization: `Bearer ${leakedKey}` },
});
assert.equal(res.status, 401, `Leaked default key ${leakedKey} must be rejected`);
}
// 2. Even if env vars are unset in isolated state, resolveAuthContext MUST fail closed (never authenticate defaults)
const saved = {
AURA_API_KEY: process.env.AURA_API_KEY,
AURA_ADMIN_KEY: process.env.AURA_ADMIN_KEY,
AURA_READONLY_KEY: process.env.AURA_READONLY_KEY,
AURA_WEBHOOK_SECRET: process.env.AURA_WEBHOOK_SECRET,
AURA_OAUTH_SECRET: process.env.AURA_OAUTH_SECRET,
};
try {
delete process.env.AURA_API_KEY;
delete process.env.AURA_ADMIN_KEY;
delete process.env.AURA_READONLY_KEY;
delete process.env.AURA_WEBHOOK_SECRET;
delete process.env.AURA_OAUTH_SECRET;
const sec = validateSecurityConfig();
assert.equal(sec.ok, false);
assert.ok(sec.errors.length >= 2);
const ctxDefault = resolveAuthContext({
headers: { authorization: "Bearer aura_live_mcp_master_key_2026" },
query: {},
});
assert.equal(ctxDefault.authenticated, false);
assert.equal(ctxDefault.isAdmin, false);
} finally {
Object.assign(process.env, saved);
}
// 3. Real production process startup MUST exit non-zero when required secrets are absent
const child = spawnSync(process.execPath, ["dist/http.js"], {
env: { PATH: process.env.PATH, NODE_ENV: "production", PORT: "0" },
encoding: "utf8",
timeout: 8000,
});
assert.notEqual(child.status, 0, "Production server must refuse to start without strong secrets");
assert.ok((child.stderr || "").includes("FATAL SECURITY CONFIG"));
});
test("P0-02: Arbitrary webhook path tokens rejected (401), Pathao secret NEVER leaked, server-side tenant binding & replay blocked (409)", async () => {
clearWebhookEvents();
clearWebhookReplayCache();
// 1. Arbitrary 8+ char merchant_token path -> MUST return 401 and NEVER disclose PATHAO_CLIENT_SECRET
const attackChallenge = await fetch(`${baseUrl}/webhooks/pathao/attacker_random_token_99`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ event: "webhook_integration" }),
});
assert.equal(attackChallenge.status, 401);
assert.equal(attackChallenge.headers.get("x-pathao-merchant-webhook-integration-secret"), null);
const attackBody = await attackChallenge.text();
assert.ok(!attackBody.includes(process.env.PATHAO_CLIENT_SECRET));
// 2. Even with a VALID Pathao HMAC on webhook_integration, PATHAO_CLIENT_SECRET is NEVER echoed in response headers
const challengePayload = JSON.stringify({ event: "webhook_integration" });
const validChallengeSig = createHmac("sha256", process.env.PATHAO_CLIENT_SECRET).update(challengePayload).digest("hex");
const validChallenge = await fetch(`${baseUrl}/webhooks/pathao`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-pathao-signature": validChallengeSig,
},
body: challengePayload,
});
assert.equal(validChallenge.status, 202);
assert.equal(validChallenge.headers.get("x-pathao-merchant-webhook-integration-secret"), null);
// 3. Server-side tenant binding: registered tenant key ignores attacker ?tenant=victim override
const tenantSecret = "tenant_bound_webhook_key_998877665544";
registerApiKey(tenantSecret, "tenant_real_owner", ["read", "write"]);
const tenantWebhook = await fetch(`${baseUrl}/webhooks/steadfast/${tenantSecret}?tenant=victim_tenant`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ consignment_id: "SF_TENANT_BIND_1", status: "delivered", event_id: "evt_bind_001" }),
});
assert.equal(tenantWebhook.status, 200);
const whJson = await tenantWebhook.json();
assert.equal(whJson.tenant_scope, "tenant_real_owner");
// 4. Replay protection: exact duplicate event_id returns 409 Conflict
const replayRes = await fetch(`${baseUrl}/webhooks/steadfast/${tenantSecret}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ consignment_id: "SF_TENANT_BIND_1", status: "delivered", event_id: "evt_bind_001" }),
});
assert.equal(replayRes.status, 409);
// 5. Stale timestamp rejected (401)
const staleRes = await fetch(`${baseUrl}/webhooks/steadfast/${tenantSecret}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-webhook-timestamp": String(Math.floor(Date.now() / 1000) - 3600),
},
body: JSON.stringify({ consignment_id: "SF_STALE_1", status: "delivered", event_id: "evt_stale_001" }),
});
assert.equal(staleRes.status, 401);
// 6. Direct check on authenticateWebhook: tenant ID string alone in AURA_TENANT_KEYS cannot authenticate
process.env.AURA_TENANT_KEYS = "my_tenant_name:strong_tenant_secret_key_abcdef1234";
const fakeTid = authenticateWebhook(
{ params: { merchant_token: "my_tenant_name" }, headers: {}, query: {}, body: {} },
"steadfast"
);
assert.equal(fakeTid.valid, false);
delete process.env.AURA_TENANT_KEYS;
});
test("P0-03: Unauthenticated BYOK headers cannot bypass auth/scopes; incomplete BYOK bundle rejected (400); unauthenticated /sse returns 401", async () => {
// 1. Synthetic BYOK header without Aura Bearer token -> 401 Unauthorized
const unauthByok = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-steadfast-api-key": "fake_unauth_byok_key",
"x-steadfast-secret-key": "fake_unauth_byok_secret",
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name: "create_parcel", arguments: { courier: "steadfast", invoice: "INV-BYOK-1" } },
}),
});
assert.equal(unauthByok.status, 401);
// 2. Authenticated READ-ONLY key + BYOK headers still CANNOT invoke write tool create_parcel
const roByok = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AURA_READONLY_KEY}`,
"x-steadfast-api-key": "sf_byok_key_123456",
"x-steadfast-secret-key": "sf_byok_sec_123456",
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 2,
method: "tools/call",
params: { name: "create_parcel", arguments: { courier: "steadfast", invoice: "INV-BYOK-RO" } },
}),
});
assert.equal(roByok.status, 200);
const roRpc = await roByok.json();
assert.equal(roRpc.result.isError, true);
assert.ok(roRpc.result.content[0].text.includes("Insufficient scope"));
// 3. Authenticated WRITE key + INCOMPLETE BYOK header (missing secret) -> 400 INVALID_INPUT
const partialByok = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
"x-steadfast-api-key": "only_api_key_no_secret",
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 3,
method: "tools/call",
params: { name: "get_balance", arguments: { courier: "steadfast" } },
}),
});
assert.equal(partialByok.status, 400);
// 4. Unauthenticated GET /sse -> 401
const unauthSse = await fetch(`${baseUrl}/sse`, { headers: { Accept: "text/event-stream" } });
assert.equal(unauthSse.status, 401);
});
test("P1-01: SSRF Carrier Base URL Allowlist rejects private IPs, HTTP, non-443 ports, and unlisted domains", async () => {
const maliciousUrls = [
"http://127.0.0.1:8080",
"http://10.0.1.1:8000",
"http://169.254.169.254/latest/meta-data",
"http://portal.packzy.com/api/v1",
"https://evil.attacker.example/api",
"https://user:pass@portal.packzy.com/api/v1",
"https://portal.packzy.com:8443/api/v1",
];
for (const bad of maliciousUrls) {
assert.throws(() => validateCarrierBaseUrl("steadfast", bad, "https://portal.packzy.com/api/v1"));
const res = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
"x-steadfast-base-url": bad,
},
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
});
assert.equal(res.status, 400, `SSRF URL ${bad} must be blocked with 400`);
}
// Official HTTPS allowlisted host passes
assert.equal(
validateCarrierBaseUrl("steadfast", "https://portal.packzy.com/api/v1/", "https://portal.packzy.com/api/v1"),
"https://portal.packzy.com/api/v1"
);
assert.equal(
validateCarrierBaseUrl("pathao", "https://courier-api-sandbox.pathao.com", "https://api-hermes.pathao.com"),
"https://courier-api-sandbox.pathao.com"
);
});
test("P1-02: Public tracker strips raw_response, phone, customer name, street address & COD value for non-owners", async () => {
const origTrack = SteadfastAdapter.prototype.trackParcel;
SteadfastAdapter.prototype.trackParcel = async function (code) {
return {
success: true,
courier: "steadfast",
tracking_code: code,
status: "In Transit",
updated_at: "2026-11-27T01:00:00Z",
recipient_phone: "01799887766",
recipient_address: "Flat 4B, House 99, Road 12, Dhanmondi, Dhaka",
raw_response: {
consignment: {
recipient_name: "Private Buyer Name",
recipient_phone: "01799887766",
recipient_address: "Flat 4B, House 99, Road 12, Dhanmondi, Dhaka",
cod_amount: 4850,
},
cod_amount: 4850,
recipient_name: "Private Buyer Name",
},
};
};
try {
// Unauthenticated JSON -> strictly minimal DTO
const pubJsonRes = await fetch(`${baseUrl}/track/SF_PII_AUDIT_1?format=json`);
assert.equal(pubJsonRes.status, 200);
const pubJson = await pubJsonRes.json();
const pubText = JSON.stringify(pubJson);
assert.equal(pubJson.raw_response, undefined);
assert.equal(pubJson.recipient_phone, undefined);
assert.equal(pubJson.privacy_mode, "public_masked");
assert.ok(!pubText.includes("01799887766"));
assert.ok(!pubText.includes("Private Buyer Name"));
assert.ok(!pubText.includes("Flat 4B"));
assert.ok(!pubText.includes("4850"));
// Unauthenticated HTML -> hides COD & real customer name
const pubHtmlRes = await fetch(`${baseUrl}/track/SF_PII_AUDIT_1`, { headers: { Accept: "text/html" } });
assert.equal(pubHtmlRes.status, 200);
const pubHtml = await pubHtmlRes.text();
assert.ok(!pubHtml.includes("01799887766"));
assert.ok(!pubHtml.includes("Private Buyer Name"));
assert.ok(!pubHtml.includes("4,850"));
assert.ok(pubHtml.includes("Protected (Merchant Only)"));
// Authenticated owner (master) -> retains full owner tracking details
const ownerRes = await fetch(`${baseUrl}/track/SF_PII_AUDIT_1?format=json`, {
headers: { Authorization: `Bearer ${process.env.AURA_API_KEY}` },
});
assert.equal(ownerRes.status, 200);
const ownerJson = await ownerRes.json();
assert.equal(ownerJson.recipient_phone, "01799887766");
assert.ok(ownerJson.raw_response);
} finally {
SteadfastAdapter.prototype.trackParcel = origTrack;
}
});
test("P1-03: Concurrent parallel booking coalesces to 1 carrier call & PostgreSQL durable store recovers across restart", async () => {
clearIdempotencyStore();
const origSfCreate = SteadfastAdapter.prototype.createParcel;
let sfCalls = 0;
SteadfastAdapter.prototype.createParcel = async function (req) {
sfCalls++;
await new Promise((r) => setTimeout(r, 60));
return {
success: true,
courier: "steadfast",
tracking_code: `SF-CONC-${sfCalls}`,
consignment_id: 77000 + sfCalls,
invoice: req.invoice,
status: "in_review",
cod_amount: req.cod_amount,
};
};
// Mock durable PostgreSQL pool
const dbRows = [];
const fakePool = {
async query(sql, params) {
if (sql.includes("SELECT courier, tracking_code")) {
const [tenant, invoice] = params;
const found = dbRows.find((r) => r.tenant === tenant && r.raw?.invoice === invoice);
return { rows: found ? [found] : [] };
}
if (sql.includes("INSERT INTO courier_parcels")) {
dbRows.push({
tenant: params[0],
courier: params[1],
tracking_code: params[2],
cod_amount: params[6],
status: params[8],
raw: JSON.parse(params[9]),
});
return { rowCount: 1, rows: [] };
}
return { rows: [] };
},
};
setRegistryDbPool(fakePool);
try {
const callCreate = () =>
fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
},
body: JSON.stringify({
jsonrpc: "2.0",
id: Math.floor(Math.random() * 1000),
method: "tools/call",
params: {
name: "create_parcel",
arguments: {
courier: "steadfast",
invoice: "INV-PARALLEL-2026",
recipient_name: "Parallel Buyer",
recipient_phone: "01711112222",
recipient_address: "House 5, Road 2, Banani, Dhaka",
cod_amount: 1200,
},
},
}),
}).then((r) => r.json());
// Fire 5 concurrent identical bookings simultaneously
const results = await Promise.all([callCreate(), callCreate(), callCreate(), callCreate(), callCreate()]);
assert.equal(sfCalls, 1, "5 concurrent bookings for same invoice MUST trigger strictly 1 upstream call");
const codes = results.map((r) => JSON.parse(r.result.content[0].text).tracking_code);
assert.ok(codes.every((c) => c === "SF-CONC-1"));
// Simulate process restart by wiping RAM idempotency store -> PostgreSQL ledger must prevent duplicate!
clearIdempotencyStore();
const afterRestart = await callCreate();
const afterEnv = JSON.parse(afterRestart.result.content[0].text);
assert.equal(sfCalls, 1, "Post-restart replay must recover from PostgreSQL without calling courier again");
assert.equal(afterEnv.tracking_code, "SF-CONC-1");
assert.equal(afterEnv.idempotent_replay, true);
} finally {
SteadfastAdapter.prototype.createParcel = origSfCreate;
setRegistryDbPool(null);
}
});
test("P1-04: Ambiguous non-timeout carrier failure (HTTP 502 or malformed 2xx) halts cascade without calling 2nd courier", async () => {
clearIdempotencyStore();
const origSfCreate = SteadfastAdapter.prototype.createParcel;
const origPathaoCreate = PathaoAdapter.prototype.createParcel;
let sfCalls = 0;
let pathaoCalls = 0;
// Case A: Dhaka 'auto' picks Pathao first -> Pathao returns non-timeout HTTP 502 -> Steadfast MUST NOT be called
SteadfastAdapter.prototype.createParcel = async function () {
sfCalls++;
return { success: true, courier: "steadfast", tracking_code: "SF-DUP-BAD", status: "in_review" };
};
PathaoAdapter.prototype.createParcel = async function () {
pathaoCalls++;
const err = new Error("Bad Gateway");
err.response = { status: 502, data: "<html>502</html>" };
throw err;
};
try {
const res502 = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 10,
method: "tools/call",
params: {
name: "create_parcel",
arguments: {
courier: "auto",
priority: "fastest",
invoice: "INV-AMBIGUOUS-502",
recipient_name: "Ambiguous Buyer",
recipient_phone: "01711113333",
recipient_address: "House 8, Road 4, Uttara, Dhaka",
cod_amount: 950,
},
},
}),
}).then((r) => r.json());
const env502 = JSON.parse(res502.result.content[0].text);
assert.equal(env502.ok, false);
assert.equal(env502.status, "UNKNOWN_PENDING_RECONCILIATION");
assert.equal(sfCalls, 0, "2nd courier (Steadfast) MUST NOT be called after ambiguous Pathao HTTP 502");
// Blind immediate retry of the same unresolved invoice also stays halted without touching either carrier
const prevPathaoCalls = pathaoCalls;
const retryRes = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 11,
method: "tools/call",
params: {
name: "create_parcel",
arguments: {
courier: "auto",
priority: "fastest",
invoice: "INV-AMBIGUOUS-502",
recipient_name: "Ambiguous Buyer",
recipient_phone: "01711113333",
recipient_address: "House 8, Road 4, Uttara, Dhaka",
cod_amount: 950,
},
},
}),
}).then((r) => r.json());
const retryEnv = JSON.parse(retryRes.result.content[0].text);
assert.equal(retryEnv.ok, false);
assert.equal(retryEnv.status, "UNKNOWN_PENDING_RECONCILIATION");
assert.equal(sfCalls, 0);
assert.equal(pathaoCalls, prevPathaoCalls);
// Case B: Malformed 2xx response missing tracking_code/consignment_id -> halts cascade without calling 2nd courier
PathaoAdapter.prototype.createParcel = async function () {
pathaoCalls++;
return { success: true, courier: "pathao", status: "accepted_no_id" };
};
const resMalformed = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 12,
method: "tools/call",
params: {
name: "create_parcel",
arguments: {
courier: "auto",
priority: "fastest",
invoice: "INV-AMBIGUOUS-MALFORMED",
recipient_name: "Ambiguous Buyer 2",
recipient_phone: "01711114444",
recipient_address: "House 9, Road 4, Uttara, Dhaka",
cod_amount: 1100,
},
},
}),
}).then((r) => r.json());
const envMal = JSON.parse(resMalformed.result.content[0].text);
assert.equal(envMal.ok, false);
assert.equal(envMal.status, "UNKNOWN_PENDING_RECONCILIATION");
assert.equal(sfCalls, 0, "2nd courier MUST NOT be called after malformed 2xx response");
} finally {
SteadfastAdapter.prototype.createParcel = origSfCreate;
PathaoAdapter.prototype.createParcel = origPathaoCreate;
}
});