security(v2.7.2): remediate all 3 Critical P0 & 5 High P1 audit findings (fail-closed auth, webhook hardening + replay protection, auth-first BYOK + SSRF allowlist, minimal public tracker DTO, atomic+DB idempotency, 0 npm vulnerabilities, CI gate)
This commit is contained in:
Vendored
+1
@@ -17,6 +17,7 @@ export class PaperflyAdapter {
|
||||
this.client = axios.create({
|
||||
baseURL: baseUrl,
|
||||
timeout: 15000,
|
||||
maxRedirects: 0,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
Vendored
+2
-1
@@ -36,7 +36,7 @@ export class PathaoAdapter {
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
grant_type: "password",
|
||||
});
|
||||
}, { timeout: 12000, maxRedirects: 0 });
|
||||
this.accessToken = response.data.access_token;
|
||||
this.tokenExpiresAt = now + (response.data.expires_in || 3600) * 1000;
|
||||
return this.accessToken;
|
||||
@@ -50,6 +50,7 @@ export class PathaoAdapter {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
timeout: 12000,
|
||||
maxRedirects: 0,
|
||||
});
|
||||
}
|
||||
/**
|
||||
|
||||
Vendored
+1
@@ -15,6 +15,7 @@ export class RedxAdapter {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
timeout: 15000,
|
||||
maxRedirects: 0,
|
||||
});
|
||||
}
|
||||
isConfigured() {
|
||||
|
||||
Vendored
+1
@@ -15,6 +15,7 @@ export class SteadfastAdapter {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
timeout: 10000,
|
||||
maxRedirects: 0,
|
||||
});
|
||||
}
|
||||
isConfigured() {
|
||||
|
||||
Vendored
+7
-1
@@ -34,9 +34,15 @@ export interface CourierConfig {
|
||||
};
|
||||
}
|
||||
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.
|
||||
* 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;
|
||||
|
||||
Vendored
+42
-5
@@ -9,10 +9,47 @@ if (process.env.NODE_ENV !== "test") {
|
||||
else {
|
||||
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.
|
||||
* 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) {
|
||||
const steadfastApiKey = src.STEADFAST_API_KEY || "";
|
||||
@@ -24,7 +61,7 @@ export function loadConfig(src = process.env) {
|
||||
steadfast: {
|
||||
apiKey: steadfastApiKey,
|
||||
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),
|
||||
},
|
||||
pathao: {
|
||||
@@ -33,12 +70,12 @@ export function loadConfig(src = process.env) {
|
||||
username: src.PATHAO_USERNAME || "",
|
||||
password: src.PATHAO_PASSWORD || "",
|
||||
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),
|
||||
},
|
||||
redx: {
|
||||
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 || "",
|
||||
enabled: Boolean(src.REDX_API_TOKEN),
|
||||
},
|
||||
@@ -47,7 +84,7 @@ export function loadConfig(src = process.env) {
|
||||
username: src.PAPERFLY_USERNAME || "",
|
||||
password: src.PAPERFLY_PASSWORD || "",
|
||||
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),
|
||||
},
|
||||
googleMaps: {
|
||||
|
||||
Vendored
+4
-2
@@ -1,8 +1,10 @@
|
||||
import { type Express, type Request } from "express";
|
||||
import { EnvSource } from "./config.js";
|
||||
/**
|
||||
* F10 Fix: Pull client courier keys strictly from request headers.
|
||||
* Query parameters are completely ignored to prevent credential leakage in URL logs.
|
||||
* P0-03 & P1-01 Fix: Pull authenticated tenant BYOK keys strictly from request headers.
|
||||
* 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 const app: Express;
|
||||
export declare function clearWebhookReplayCache(): void;
|
||||
|
||||
Vendored
+175
-49
@@ -1,15 +1,15 @@
|
||||
import express from "express";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
|
||||
import { loadConfig } from "./config.js";
|
||||
import { loadConfig, validateCarrierBaseUrl } from "./config.js";
|
||||
import { buildMcpServer, executeToolCall, TOOLS } from "./server.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 { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
|
||||
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
||||
import { APP_VERSION } from "./version.js";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -81,14 +81,12 @@ function redactAddressToDistrict(addr) {
|
||||
return addr;
|
||||
}
|
||||
/**
|
||||
* F10 Fix: Pull client courier keys strictly from request headers.
|
||||
* Query parameters are completely ignored to prevent credential leakage in URL logs.
|
||||
* P0-03 & P1-01 Fix: Pull authenticated tenant BYOK keys strictly from request headers.
|
||||
* 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) {
|
||||
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 ||
|
||||
h["x-steadfast-api-key"] ||
|
||||
h["x-pathao-client-id"] ||
|
||||
@@ -108,23 +106,33 @@ export function keysFromRequest(req) {
|
||||
}
|
||||
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 {
|
||||
STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"),
|
||||
STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"),
|
||||
STEADFAST_BASE_URL: pick("x-steadfast-base-url", "STEADFAST_BASE_URL", true),
|
||||
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_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"),
|
||||
PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"),
|
||||
PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"),
|
||||
PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"),
|
||||
PATHAO_BASE_URL: pick("x-pathao-base-url", "PATHAO_BASE_URL", true),
|
||||
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_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"),
|
||||
PAPERFLY_API_KEY: pick("x-paperfly-api-key", "PAPERFLY_API_KEY"),
|
||||
PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"),
|
||||
PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"),
|
||||
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"),
|
||||
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),
|
||||
};
|
||||
}
|
||||
@@ -148,17 +156,56 @@ app.use((err, _req, res, next) => {
|
||||
}
|
||||
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) => {
|
||||
res.header("Access-Control-Allow-Origin", "*");
|
||||
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-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");
|
||||
if (req.method === "OPTIONS") {
|
||||
return res.sendStatus(204);
|
||||
}
|
||||
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
|
||||
app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" }));
|
||||
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);
|
||||
});
|
||||
/**
|
||||
* 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 token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key;
|
||||
const endpointUrl = token
|
||||
@@ -414,16 +461,16 @@ app.get("/sse", mcpLimiter, async (req, res) => {
|
||||
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"]);
|
||||
if (!sessionId || !sseSessions.has(sessionId)) {
|
||||
return res.status(400).send("Invalid or missing sessionId");
|
||||
}
|
||||
const entry = sseSessions.get(sessionId);
|
||||
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
|
||||
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
|
||||
const callerTenant = req.auraAuth?.tenantId || "anonymous";
|
||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
||||
return res.status(403).json(wrapError(new McpToolError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "SSE Session belongs to another tenant.",
|
||||
@@ -433,13 +480,39 @@ app.post("/messages", mcpLimiter, async (req, res) => {
|
||||
entry.lastActiveAt = Date.now();
|
||||
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) {
|
||||
return (req, res) => {
|
||||
const isValidSig = verifyWebhookSignature(req, provider);
|
||||
if (!isValidSig) {
|
||||
const whAuth = authenticateWebhook(req, provider);
|
||||
if (!whAuth.valid) {
|
||||
return res.status(401).json(wrapError(new McpToolError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: `Unauthorized ${provider} webhook request: missing or invalid signature/secret.`,
|
||||
@@ -447,11 +520,24 @@ function handleCourierWebhook(provider) {
|
||||
retryable: false,
|
||||
}), "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 || {};
|
||||
if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") {
|
||||
const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || "";
|
||||
if (secret)
|
||||
res.setHeader("X-Pathao-Merchant-Webhook-Integration-Secret", secret);
|
||||
// P0-02 Fix: NEVER return PATHAO_CLIENT_SECRET or AURA_WEBHOOK_SECRET in any HTTP response.
|
||||
return res.status(202).json({ ok: true, status: "webhook_verified" });
|
||||
}
|
||||
const consignmentId = payload.consignment_id ||
|
||||
@@ -469,8 +555,29 @@ function handleCourierWebhook(provider) {
|
||||
const status = String(payload.status || payload.order_status || payload.event || "received");
|
||||
const eventType = String(payload.notification_type || payload.event || "delivery_status");
|
||||
const invoice = payload.invoice || payload.merchant_order_id;
|
||||
const paramMerchantToken = req.params?.merchant_token ? String(req.params.merchant_token).trim() : "";
|
||||
const tenantId = String(paramMerchantToken || req.query.tenant || req.headers["x-tenant-id"] || "default");
|
||||
// P0-02 Fix: Tenant identity comes STRICTLY from server-side verified webhook auth, never arbitrary URL path.
|
||||
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 = {
|
||||
id: randomUUID(),
|
||||
courier: provider,
|
||||
@@ -481,12 +588,12 @@ function handleCourierWebhook(provider) {
|
||||
received_at: new Date().toISOString(),
|
||||
payload,
|
||||
};
|
||||
// F06: Record webhook event scoped by tenantId
|
||||
// F06: Record webhook event scoped by server-verified tenantId
|
||||
recordWebhookEvent(record, tenantId);
|
||||
// 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}`)) {
|
||||
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) {
|
||||
fetch(fwdUrl, {
|
||||
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);
|
||||
if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) {
|
||||
if (trackResult) {
|
||||
let sanitized = trackResult;
|
||||
if (!isOwner) {
|
||||
sanitized = {
|
||||
...trackResult,
|
||||
recipient_phone: trackResult.recipient_phone ? maskPhone(trackResult.recipient_phone) : undefined,
|
||||
recipient_address: trackResult.recipient_address ? redactAddressToDistrict(trackResult.recipient_address) : undefined,
|
||||
// P1-02 Fix: Minimal public DTO — strips raw_response, phone, full address, customer name, and COD value
|
||||
const publicDto = {
|
||||
success: true,
|
||||
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) {
|
||||
let safeParcel = dbParcel;
|
||||
if (!isOwner) {
|
||||
safeParcel = {
|
||||
...dbParcel,
|
||||
recipient_phone: maskPhone(dbParcel.recipient_phone || dbParcel.phone || ""),
|
||||
recipient_address: redactAddressToDistrict(dbParcel.recipient_address || dbParcel.address || ""),
|
||||
customer_name: dbParcel.customer_name ? dbParcel.customer_name.charAt(0) + "***" : "Customer",
|
||||
const publicDbDto = {
|
||||
success: true,
|
||||
parcel: {
|
||||
courier: dbParcel.courier || courier,
|
||||
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"));
|
||||
}
|
||||
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 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) {
|
||||
recipientAddress = redactAddressToDistrict(recipientAddress);
|
||||
if (recipientName && recipientName.length > 2) {
|
||||
recipientName = recipientName.charAt(0) + "*** " + (recipientName.split(" ")[1] || "");
|
||||
}
|
||||
recipientName = "Verified Recipient";
|
||||
}
|
||||
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 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());
|
||||
@@ -664,7 +782,7 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
||||
</div>
|
||||
<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">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 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>` : ""}
|
||||
@@ -765,6 +883,14 @@ app.get("/", (_req, res) => {
|
||||
});
|
||||
});
|
||||
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, () => {
|
||||
console.log(`Aura Courier MCP v${APP_VERSION} (HTTP) listening on :${PORT} — POST /mcp`);
|
||||
});
|
||||
|
||||
Vendored
+30
-7
@@ -26,10 +26,26 @@ export interface AuditEntry {
|
||||
outcome: "ok" | "denied" | "error";
|
||||
}
|
||||
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.
|
||||
* Query parameters are completely ignored to avoid leaking secrets in proxy/access logs.
|
||||
* P0-03 Fix: Detect and validate BYOK carrier credential bundles strictly from request headers.
|
||||
* 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 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;
|
||||
/**
|
||||
* F01 Fix: Cryptographic Token Resolution without prefix bypass.
|
||||
* Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished.
|
||||
* P0-01 Fix: Fail-Closed Cryptographic Token Resolution.
|
||||
* Zero hardcoded fallback keys; zero prefix bypasses.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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.
|
||||
* Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body.
|
||||
* Steadfast uses secret key header comparison.
|
||||
* P0-02 Fix: Fail-Closed Carrier Webhook Authentication & Server-Side Tenant Resolution.
|
||||
* - Abolishes arbitrary >=8-char URL path token acceptance.
|
||||
* - 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;
|
||||
|
||||
Vendored
+246
-79
@@ -21,16 +21,132 @@ const WRITE_TOOLS = new Set([
|
||||
// Per-key sliding-window rate limiter store
|
||||
const keyRateStore = new Map();
|
||||
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.
|
||||
* Query parameters are completely ignored to avoid leaking secrets in proxy/access logs.
|
||||
* P0-03 Fix: Detect and validate BYOK carrier credential bundles strictly from request headers.
|
||||
* 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) {
|
||||
const h = req.headers;
|
||||
return Boolean(h["x-steadfast-api-key"] ||
|
||||
h["x-pathao-client-id"] ||
|
||||
h["x-redx-api-token"] ||
|
||||
h["x-paperfly-api-key"]);
|
||||
return validateByokHeaders(req).isByok;
|
||||
}
|
||||
export function extractBearerToken(req) {
|
||||
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 });
|
||||
}
|
||||
/**
|
||||
* F01 Fix: Cryptographic Token Resolution without prefix bypass.
|
||||
* Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished.
|
||||
* P0-01 Fix: Fail-Closed Cryptographic Token Resolution.
|
||||
* Zero hardcoded fallback keys; zero prefix bypasses.
|
||||
*/
|
||||
export function resolveAuthContext(req) {
|
||||
const token = extractBearerToken(req);
|
||||
const isByok = hasByokCredentials(req);
|
||||
const masterKey = process.env.AURA_API_KEY ||
|
||||
process.env.COURIER_AUTH_TOKEN ||
|
||||
"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;
|
||||
const masterKey = getMasterKey();
|
||||
const readOnlyKey = getReadOnlyKey();
|
||||
const adminKey = getAdminKey();
|
||||
if (!token) {
|
||||
return {
|
||||
authenticated: false,
|
||||
@@ -199,6 +313,16 @@ export function resolveAuthContext(req) {
|
||||
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)
|
||||
if (token.startsWith("eyJ") && token.split(".").length === 3) {
|
||||
const oauthClaims = verifyOAuthAccessToken(token);
|
||||
@@ -213,8 +337,8 @@ export function resolveAuthContext(req) {
|
||||
};
|
||||
}
|
||||
}
|
||||
// 1. Master / Admin Key (Full Read + Write across all tenants)
|
||||
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
|
||||
// 1. Master / Admin Key (Full Read + Write across all tenants — strictly from strong env secret)
|
||||
if ((masterKey && safeCompare(token, masterKey)) || (adminKey && safeCompare(token, adminKey))) {
|
||||
return {
|
||||
authenticated: true,
|
||||
tenantId: "master",
|
||||
@@ -224,8 +348,8 @@ export function resolveAuthContext(req) {
|
||||
callerToken: token,
|
||||
};
|
||||
}
|
||||
// 2. Read-Only Gateway Discovery Key
|
||||
if (safeCompare(token, readOnlyKey) || safeCompare(token, "aura_ro_public_inspector_2026")) {
|
||||
// 2. Read-Only Gateway Discovery Key (strictly from strong env secret)
|
||||
if (readOnlyKey && safeCompare(token, readOnlyKey)) {
|
||||
return {
|
||||
authenticated: true,
|
||||
tenantId: "public_ro",
|
||||
@@ -330,10 +454,9 @@ export async function resolveAuthContextAsync(req) {
|
||||
return resolveAuthContext(req);
|
||||
}
|
||||
const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key";
|
||||
const syncSecret = process.env.AURA_MCP_SYNC_SECRET ||
|
||||
process.env.AURA_API_KEY ||
|
||||
process.env.COURIER_AUTH_TOKEN ||
|
||||
"aura_live_mcp_master_key_2026";
|
||||
const syncSecret = (process.env.AURA_MCP_SYNC_SECRET || getMasterKey()).trim();
|
||||
if (!syncSecret)
|
||||
return local;
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 3500);
|
||||
try {
|
||||
@@ -410,15 +533,22 @@ export function requireMcpAuth(req, res, next) {
|
||||
if (isDiscovery) {
|
||||
return next();
|
||||
}
|
||||
// BYOK headers (x-steadfast-api-key, etc.) allow tool execution with caller's carrier credentials
|
||||
if (ctx.isByok) {
|
||||
return next();
|
||||
}
|
||||
// P0-03 Fix: NEVER bypass Aura auth on BYOK headers. Authenticate caller first, then validate BYOK bundle.
|
||||
if (!ctx.authenticated) {
|
||||
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, false));
|
||||
res.status(401).json(wrapError(new McpToolError({
|
||||
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,
|
||||
source: "validator",
|
||||
})));
|
||||
@@ -458,21 +588,28 @@ export function isActionPermitted(req, toolName, args) {
|
||||
reason: "Unauthorized: invalid or forged Authorization token.",
|
||||
};
|
||||
}
|
||||
// F14: list_couriers is allowed for discovery
|
||||
if (toolName === "list_couriers") {
|
||||
return { permitted: true };
|
||||
}
|
||||
// BYOK mode: caller provided specific courier credentials in headers
|
||||
if (ctx.isByok) {
|
||||
return { permitted: true };
|
||||
}
|
||||
// P0-03 Fix: Every tool invocation (including BYOK) MUST be authenticated and pass scope checks.
|
||||
if (!ctx.authenticated) {
|
||||
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||
return {
|
||||
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";
|
||||
if (!ctx.scopes.includes(requiredScope)) {
|
||||
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.
|
||||
* Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body.
|
||||
* Steadfast uses secret key header comparison.
|
||||
* P0-02 Fix: Fail-Closed Carrier Webhook Authentication & Server-Side Tenant Resolution.
|
||||
* - Abolishes arbitrary >=8-char URL path token acceptance.
|
||||
* - 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();
|
||||
// 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"]);
|
||||
if (prov === "pathao" && pathaoSig) {
|
||||
const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || "";
|
||||
if (secret) {
|
||||
const rawBody = req.rawBody ? String(req.rawBody) : JSON.stringify(req.body || {});
|
||||
if (prov === "pathao" && pathaoSig && typeof pathaoSig === "string") {
|
||||
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");
|
||||
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
|
||||
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;
|
||||
// 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 Webhook Headers
|
||||
// 3. RedX & Paperfly Provider Secrets
|
||||
const rxSig = (req.headers["x-redx-signature"] || req.headers["x-webhook-secret"]);
|
||||
if (prov === "redx" && rxSig) {
|
||||
const rxSecret = process.env.REDX_API_TOKEN || process.env.AURA_WEBHOOK_SECRET || "";
|
||||
if (rxSecret && safeCompare(rxSig, rxSecret))
|
||||
return true;
|
||||
if (prov === "redx" && rxSig && typeof rxSig === "string") {
|
||||
const rxSecret = (process.env.REDX_API_TOKEN || "").trim();
|
||||
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"]);
|
||||
if (prov === "paperfly" && pfSig) {
|
||||
const pfSecret = process.env.PAPERFLY_API_KEY || process.env.AURA_WEBHOOK_SECRET || "";
|
||||
if (pfSecret && safeCompare(pfSig, pfSecret))
|
||||
return true;
|
||||
if (prov === "paperfly" && pfSig && typeof pfSig === "string") {
|
||||
const pfSecret = (process.env.PAPERFLY_API_KEY || "").trim();
|
||||
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
|
||||
const masterSecret = process.env.AURA_WEBHOOK_SECRET || process.env.AURA_API_KEY || "aura_webhook_secret_2026";
|
||||
const paramToken = (req.params && req.params.merchant_token) ? String(req.params.merchant_token).trim() : undefined;
|
||||
const candidate = paramToken ||
|
||||
// 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 candidate = req.headers["x-webhook-secret"] ||
|
||||
extractBearerToken(req) ||
|
||||
req.headers["x-webhook-secret"] ||
|
||||
req.query["token"] ||
|
||||
req.query["secret"];
|
||||
paramToken;
|
||||
if (candidate && typeof candidate === "string") {
|
||||
const trimmed = candidate.trim();
|
||||
if (safeCompare(trimmed, masterSecret)) {
|
||||
return true;
|
||||
if (!trimmed || FORBIDDEN_WEAK_SECRETS.has(trimmed.toLowerCase())) {
|
||||
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");
|
||||
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;
|
||||
if (envTenants) {
|
||||
for (const pair of envTenants.split(",")) {
|
||||
const [tId, tKey] = pair.split(":");
|
||||
if ((tKey && safeCompare(trimmed, tKey.trim())) || (tId && safeCompare(trimmed, tId.trim()))) {
|
||||
return true;
|
||||
if (tId && tKey && isStrongSecret(tKey.trim(), 16) && safeCompare(trimmed, tKey.trim())) {
|
||||
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, provider) {
|
||||
return authenticateWebhook(req, provider).valid;
|
||||
}
|
||||
|
||||
Vendored
+14
-2
@@ -22,11 +22,23 @@ setInterval(() => {
|
||||
revokedTokenIds.delete(k);
|
||||
}
|
||||
}, 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() {
|
||||
return (process.env.AURA_OAUTH_SECRET ||
|
||||
const raw = (process.env.AURA_OAUTH_SECRET ||
|
||||
process.env.AURA_API_KEY ||
|
||||
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) {
|
||||
return createHash("sha256")
|
||||
|
||||
Vendored
+210
-57
@@ -12,11 +12,15 @@ export function setRegistryDbPool(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 inFlightBookings = new Map();
|
||||
const pendingReconciliationStore = new Map();
|
||||
export function clearIdempotencyStore() {
|
||||
idempotencyStore.clear();
|
||||
inFlightBookings.clear();
|
||||
pendingReconciliationStore.clear();
|
||||
}
|
||||
/**
|
||||
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
||||
@@ -57,6 +61,32 @@ function isNetworkTimeout(err) {
|
||||
msg.includes("network error") ||
|
||||
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 {
|
||||
adapters = new Map();
|
||||
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 idemKey = `${tenantKey}:${invoice}`;
|
||||
const existing = idempotencyStore.get(idemKey);
|
||||
@@ -198,68 +228,191 @@ export class CourierRegistry {
|
||||
idempotent_replay: true,
|
||||
};
|
||||
}
|
||||
let lastErr = null;
|
||||
for (const courierName of candidates) {
|
||||
try {
|
||||
const adapter = this.getAdapter(courierName);
|
||||
const res = await adapter.createParcel({
|
||||
...req,
|
||||
recipient_phone: cleanPhone,
|
||||
recipient_address: addrStr,
|
||||
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,
|
||||
courier: courierName,
|
||||
});
|
||||
if (res && res.success !== false && (res.tracking_code || res.consignment_id)) {
|
||||
const courierQuote = computeCourierQuote(courierName, zone, weightKg, codAmount);
|
||||
const enriched = {
|
||||
...res,
|
||||
idempotent_replay: false,
|
||||
routing_reason: isAuto
|
||||
? `Auto-selected '${courierName}' for zone='${zone}' with priority='${priority}'.`
|
||||
: `Booked on explicitly requested courier '${courierName}'.`,
|
||||
estimated_cost_bdt: courierQuote.total_cost,
|
||||
cost_estimate_bdt: courierQuote.total_cost,
|
||||
cancellable_via_api: false,
|
||||
validation: {
|
||||
phone_ok: true,
|
||||
address_ok: true,
|
||||
needs_review: needsReview,
|
||||
},
|
||||
};
|
||||
idempotencyStore.set(idemKey, enriched);
|
||||
return enriched;
|
||||
}
|
||||
lastErr = new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: res?.message || res?.error || `${courierName} rejected parcel booking.`,
|
||||
courier: courierName,
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
lastErr = err;
|
||||
if (isNetworkTimeout(err)) {
|
||||
throw new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: "Carrier " + courierName + " timed out during parcel creation. The parcel may have been booked upstream. Halting cascade to prevent duplicate parcel creation. State is UNKNOWN_PENDING_RECONCILIATION.",
|
||||
courier: courierName,
|
||||
retryable: true,
|
||||
extraFields: {
|
||||
status: "UNKNOWN_PENDING_RECONCILIATION",
|
||||
timeout_uncertain: true,
|
||||
courier_attempted: courierName,
|
||||
},
|
||||
});
|
||||
}
|
||||
// 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;
|
||||
for (const courierName of candidates) {
|
||||
try {
|
||||
const adapter = this.getAdapter(courierName);
|
||||
const res = await adapter.createParcel({
|
||||
...req,
|
||||
recipient_phone: cleanPhone,
|
||||
recipient_address: addrStr,
|
||||
invoice,
|
||||
courier: courierName,
|
||||
});
|
||||
if (res && res.success !== false && (res.tracking_code || res.consignment_id)) {
|
||||
const courierQuote = computeCourierQuote(courierName, zone, weightKg, codAmount);
|
||||
const enriched = {
|
||||
...res,
|
||||
idempotent_replay: false,
|
||||
routing_reason: isAuto
|
||||
? `Auto-selected '${courierName}' for zone='${zone}' with priority='${priority}'.`
|
||||
: `Booked on explicitly requested courier '${courierName}'.`,
|
||||
estimated_cost_bdt: courierQuote.total_cost,
|
||||
cost_estimate_bdt: courierQuote.total_cost,
|
||||
cancellable_via_api: false,
|
||||
validation: {
|
||||
phone_ok: true,
|
||||
address_ok: true,
|
||||
needs_review: needsReview,
|
||||
},
|
||||
};
|
||||
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;
|
||||
}
|
||||
// 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({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: res?.message || res?.error || `${courierName} rejected parcel booking.`,
|
||||
courier: courierName,
|
||||
});
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof McpToolError && err.extraFields?.status === "UNKNOWN_PENDING_RECONCILIATION") {
|
||||
throw err;
|
||||
}
|
||||
lastErr = 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({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
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,
|
||||
retryable: true,
|
||||
extraFields: {
|
||||
status: "UNKNOWN_PENDING_RECONCILIATION",
|
||||
timeout_uncertain: isTimeout,
|
||||
ambiguous_outcome: true,
|
||||
courier_attempted: courierName,
|
||||
invoice,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lastErr instanceof McpToolError) {
|
||||
throw lastErr;
|
||||
}
|
||||
throw new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: lastErr?.message || "All configured courier gateways failed to book parcel.",
|
||||
});
|
||||
})();
|
||||
inFlightBookings.set(idemKey, bookingPromise);
|
||||
try {
|
||||
return await bookingPromise;
|
||||
}
|
||||
if (lastErr instanceof McpToolError) {
|
||||
throw lastErr;
|
||||
finally {
|
||||
inFlightBookings.delete(idemKey);
|
||||
}
|
||||
throw new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: lastErr?.message || "All configured courier gateways failed to book parcel.",
|
||||
});
|
||||
}
|
||||
async trackParcel(trackingCode, courierName) {
|
||||
const cleanCode = String(trackingCode || "").trim();
|
||||
|
||||
Vendored
+1
-1
@@ -11,6 +11,6 @@ function readPackageVersion() {
|
||||
catch {
|
||||
// Fallback if package.json is unavailable at runtime
|
||||
}
|
||||
return "2.7.1";
|
||||
return "2.7.2";
|
||||
}
|
||||
export const APP_VERSION = readPackageVersion();
|
||||
|
||||
Reference in New Issue
Block a user