release(v2.7.3): tenant SQL scoping, spoof-proof rate limits, safe fraud demo, non-root Docker & full parity

This commit is contained in:
Amirul Islam Redwan71
2026-11-27 04:47:06 +06:00
parent c827fdfee6
commit a3392ae69f
65 changed files with 911 additions and 1228 deletions
+4
View File
@@ -1,5 +1,9 @@
import { type Express, type Request } from "express";
import { EnvSource } from "./config.js";
/**
* NEW-01 Fix: Automated Data Retention Engine (Daily Sweep) aligned to live PostgreSQL `courier_parcels` schema.
*/
export declare function runDataRetentionSweep(pool: any): Promise<number>;
/**
* 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
+71 -11
View File
@@ -9,7 +9,7 @@ import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
import { createRateLimiter } from "./middleware/rate_limit.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 } from "./envelope.js";
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
import { APP_VERSION } from "./version.js";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -30,18 +30,33 @@ if (process.env.NODE_ENV !== "test" && dbUrl) {
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
}
}
// Automated Data Retention Engine (Daily Midnight Sweep)
/**
* NEW-01 Fix: Automated Data Retention Engine (Daily Sweep) aligned to live PostgreSQL `courier_parcels` schema.
*/
export async function runDataRetentionSweep(pool) {
if (!pool)
return 0;
const pruneRes = await pool.query(`UPDATE courier_parcels
SET customer_name = 'ANONYMIZED',
phone = 'ANONYMIZED',
address = 'ANONYMIZED'
WHERE created_at < NOW() - INTERVAL '90 days'
AND (customer_name IS DISTINCT FROM 'ANONYMIZED'
OR phone IS DISTINCT FROM 'ANONYMIZED'
OR address IS DISTINCT FROM 'ANONYMIZED')`);
return pruneRes?.rowCount || 0;
}
setInterval(async () => {
if (dbPool) {
try {
const pruneRes = await dbPool.query(`UPDATE courier_parcels
SET recipient_name = 'ANONYMIZED', recipient_phone = 'ANONYMIZED', recipient_address = 'ANONYMIZED'
WHERE created_at < NOW() - INTERVAL '90 days' AND recipient_name != 'ANONYMIZED'`);
if (pruneRes.rowCount && pruneRes.rowCount > 0) {
console.log(`[Data Retention Engine] Anonymized ${pruneRes.rowCount} legacy order records older than 90 days.`);
const pruned = await runDataRetentionSweep(dbPool);
if (pruned > 0) {
console.log(`[Data Retention Engine] Anonymized ${pruned} legacy order records older than 90 days.`);
}
}
catch (_) { }
catch (err) {
console.warn("[Data Retention Engine] Sweep error:", err?.message);
}
}
}, 24 * 60 * 60 * 1000).unref();
const PORT = Number(process.env.PORT || 8080);
@@ -175,6 +190,8 @@ app.use((req, res, next) => {
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-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("Referrer-Policy", "no-referrer");
res.header("X-Content-Type-Options", "nosniff");
if (req.method === "OPTIONS") {
return res.sendStatus(204);
}
@@ -260,8 +277,9 @@ app.post("/admin/tokens/revoke", async (req, res) => {
const count = await setTenantDynamicKeyStatus(String(b.tenantId), String(b.status || "PAYMENT_DUE"));
return res.json({ ok: true, tenantId: b.tenantId, updatedKeys: count, status: b.status || "PAYMENT_DUE" });
});
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "MCP Protocol Gateway" });
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
const publicDemoLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 10, name: "Public Fraud Demo" });
const sessions = new Map();
const sseSessions = new Map();
const SESSION_TTL_MS = 30 * 60 * 1000;
@@ -409,9 +427,16 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
res.status(400).send("Invalid or missing session ID");
return;
}
if (!req.auraAuth?.authenticated) {
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, req.auraAuth?.tenantId === "invalid"));
return res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header for active MCP session.",
}), "validator"));
}
const entry = sessions.get(sessionId);
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
const callerTenant = req.auraAuth.tenantId;
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
return res.status(403).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "MCP Session belongs to another tenant.",
@@ -792,6 +817,41 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
</body>
</html>`);
});
/**
* NEW-03 Fix: Safe Server-Side Public Fraud Demo Endpoint (Zero Browser API Key Exposure).
* Strictly limited to 10 requests/minute/IP and scoped exclusively to check_fraud_risk on valid BD mobile numbers.
*/
app.post("/api/public/fraud-demo", publicDemoLimiter, async (req, res) => {
const rawPhone = String(req.body?.phone || "").trim().replace(/[\s\-()]/g, "").replace(/^\+?88/, "");
if (!/^01[3-9]\d{8}$/.test(rawPhone)) {
return res.status(400).json(wrapError(new McpToolError({
code: "INVALID_INPUT",
message: "Valid 11-digit Bangladesh mobile number (013-019) is required.",
retryable: false,
}), "validator"));
}
try {
const registry = new CourierRegistry(loadConfig(process.env));
const result = await registry.checkFraudRisk(rawPhone);
const safeDto = {
phone_masked: maskPhone(rawPhone),
risk_level: result.risk_level,
delivery_success_rate: result.delivery_success_rate,
cancellation_rate: result.cancellation_rate,
is_verified_buyer: result.is_verified_buyer,
total_parcels: result.total_parcels,
total_delivered: result.total_delivered,
total_cancelled: result.total_cancelled,
sample_size: result.sample_size,
data_sources: result.data_sources,
recommendation: result.recommendation,
};
return res.json(wrapSuccess(safeDto, "live_api"));
}
catch (err) {
return res.status(502).json(wrapError(err, "live_api"));
}
});
/**
* Task T9 — Health & Live Telemetry Endpoint
*/
+31 -6
View File
@@ -149,6 +149,10 @@ export function hasByokCredentials(req) {
return validateByokHeaders(req).isByok;
}
export function extractBearerToken(req) {
const cachedQueryTok = req._extractedQueryToken;
if (typeof cachedQueryTok === "string" && cachedQueryTok) {
return cachedQueryTok;
}
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
if (typeof authHeader === "string") {
const trimmed = authHeader.trim();
@@ -161,12 +165,33 @@ export function extractBearerToken(req) {
if (typeof customKey === "string" && customKey.trim()) {
return customKey.trim();
}
// Support query parameter tokens for remote AI agent connectors (Claude Desktop, Cursor, Glama, Zapier, Custom GPTs)
const q = req.query;
if (q) {
const candidate = q.token || q.key || q.apiKey || q.api_key;
if (typeof candidate === "string" && candidate.trim()) {
return candidate.trim();
// NEW-05 Fix: Restrict query-parameter tokens strictly to MCP/SSE connector endpoints (never /admin, /track, /webhooks, /oauth)
// and scrub secret query parameters from req.url / req.originalUrl immediately to prevent downstream log exposure.
if (process.env.ALLOW_QUERY_TOKEN !== "false") {
const reqPath = (req.path || (req.url ? req.url.split("?")[0] : "")).trim();
if (reqPath === "/mcp" || reqPath === "/sse" || reqPath === "/messages") {
const q = req.query;
if (q) {
const candidate = q.token || q.key || q.apiKey || q.api_key;
if (typeof candidate === "string" && candidate.trim()) {
const cleanTok = candidate.trim();
req._extractedQueryToken = cleanTok;
req._usedQueryToken = true;
delete q.token;
delete q.key;
delete q.apiKey;
delete q.api_key;
if (typeof req.url === "string" && req.url.includes("?")) {
req.url = req.url.replace(/([?&])(token|key|apiKey|api_key)=[^&]*/gi, "$1[REDACTED]").replace(/\?&/, "?");
}
if (typeof req.originalUrl === "string" && req.originalUrl.includes("?")) {
req.originalUrl = req.originalUrl
.replace(/([?&])(token|key|apiKey|api_key)=[^&]*/gi, "$1[REDACTED]")
.replace(/\?&/, "?");
}
return cleanTok;
}
}
}
}
return undefined;
+10 -3
View File
@@ -1,5 +1,12 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { resolveAuthContextAsync } from "./auth.js";
import { createRateLimiter } from "./rate_limit.js";
const oauthLimiter = createRateLimiter({
windowMs: 60 * 1000,
max: 20,
name: "OAuth 2.1 Security Gateway",
message: "Too many OAuth authentication or registration attempts. Please retry in a minute.",
});
const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour
const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability)
const AUTH_CODE_TTL_SEC = 300; // 5 minutes
@@ -978,7 +985,7 @@ export function registerOAuthRoutes(app) {
app.get("/.well-known/oauth-authorization-server/mcp", authServerMetadataHandler);
app.get("/.well-known/openid-configuration", authServerMetadataHandler);
// 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof)
app.post("/oauth/register", (req, res) => {
app.post("/oauth/register", oauthLimiter, (req, res) => {
res.setHeader("Cache-Control", "no-store");
const body = (req.body || {});
const rawUris = body.redirect_uris;
@@ -1086,7 +1093,7 @@ export function registerOAuthRoutes(app) {
}));
});
// 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission)
app.post("/oauth/authorize", async (req, res) => {
app.post("/oauth/authorize", oauthLimiter, async (req, res) => {
res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
@@ -1217,7 +1224,7 @@ export function registerOAuthRoutes(app) {
return res.redirect(302, callback.toString());
});
// 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token)
app.post("/oauth/token", (req, res) => {
app.post("/oauth/token", oauthLimiter, (req, res) => {
res.setHeader("Cache-Control", "no-store");
res.setHeader("Pragma", "no-cache");
const b = (req.body || {});
+7
View File
@@ -5,5 +5,12 @@ interface RateLimiterOptions {
message?: string;
name?: string;
}
/**
* NEW-02 Fix: Spoof-resistant client IP resolution.
* - Never trusts client-prepended leftmost X-Forwarded-For entries or private/loopback header spoofs.
* - Only accepts CF-Connecting-IP when accompanied by CF-Ray AND when CF-Connecting-IP is a valid public IP.
* - Otherwise relies on Express req.ip (with `trust proxy = 1`, which resolves the single trusted reverse-proxy hop).
*/
export declare function resolveRateLimitIp(req: Request): string;
export declare function createRateLimiter(options: RateLimiterOptions): (req: Request, res: Response, next: NextFunction) => void;
export {};
+48 -24
View File
@@ -1,3 +1,48 @@
import { isIP } from "node:net";
function normalizeIpLiteral(raw) {
const trimmed = raw.trim();
if (trimmed.startsWith("::ffff:")) {
return trimmed.slice(7);
}
return trimmed;
}
function isPrivateOrLoopbackIp(ip) {
const norm = normalizeIpLiteral(ip).toLowerCase();
if (!norm || norm === "127.0.0.1" || norm === "::1" || norm === "0.0.0.0")
return true;
if (norm.startsWith("127.") || norm.startsWith("10.") || norm.startsWith("192.168.") || norm.startsWith("169.254.")) {
return true;
}
if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(norm)) {
return true;
}
if (norm.startsWith("fc") || norm.startsWith("fd") || norm.startsWith("fe80:")) {
return true;
}
return false;
}
/**
* NEW-02 Fix: Spoof-resistant client IP resolution.
* - Never trusts client-prepended leftmost X-Forwarded-For entries or private/loopback header spoofs.
* - Only accepts CF-Connecting-IP when accompanied by CF-Ray AND when CF-Connecting-IP is a valid public IP.
* - Otherwise relies on Express req.ip (with `trust proxy = 1`, which resolves the single trusted reverse-proxy hop).
*/
export function resolveRateLimitIp(req) {
const cfIpRaw = req.headers["cf-connecting-ip"];
const cfRay = req.headers["cf-ray"];
if (typeof cfIpRaw === "string" && typeof cfRay === "string" && cfRay.trim().length > 0) {
const cfIp = normalizeIpLiteral(cfIpRaw);
if (isIP(cfIp) !== 0 && !isPrivateOrLoopbackIp(cfIp)) {
return cfIp;
}
}
const expressIp = typeof req.ip === "string" && req.ip.trim() ? normalizeIpLiteral(req.ip) : "";
if (expressIp && isIP(expressIp) !== 0) {
return expressIp;
}
const socketIp = req.socket?.remoteAddress ? normalizeIpLiteral(req.socket.remoteAddress) : "";
return socketIp || "unknown";
}
export function createRateLimiter(options) {
const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options;
const store = new Map();
@@ -11,32 +56,11 @@ export function createRateLimiter(options) {
}
}, 5 * 60 * 1000).unref();
return (req, res, next) => {
// Extract Client IP (supporting Cloudflare cf-connecting-ip and reverse proxies like Traefik / Nginx)
const cfIp = req.headers["cf-connecting-ip"];
const xForwardedFor = req.headers["x-forwarded-for"];
let clientIp = "";
if (typeof cfIp === "string") {
clientIp = cfIp.trim();
}
else if (typeof xForwardedFor === "string") {
clientIp = xForwardedFor.split(",")[0].trim();
}
else if (Array.isArray(xForwardedFor) && xForwardedFor.length > 0) {
clientIp = xForwardedFor[0].trim();
}
else {
clientIp = req.socket?.remoteAddress || "unknown";
}
// Bypass loopback and internal orchestration networks
if (clientIp === "127.0.0.1" ||
clientIp === "::1" ||
clientIp === "::ffff:127.0.0.1" ||
clientIp.startsWith("10.") ||
clientIp.startsWith("172.16.") ||
clientIp.startsWith("172.17.") ||
clientIp.startsWith("172.18.")) {
// Allow high-speed local test execution unless test explicitly requests rate-limit enforcement
if (process.env.NODE_ENV === "test" && req.headers["x-test-enforce-ratelimit"] !== "1") {
return next();
}
const clientIp = resolveRateLimitIp(req);
const now = Date.now();
let record = store.get(clientIp);
if (!record || now > record.resetAt) {
+2 -2
View File
@@ -44,8 +44,8 @@ export declare class CourierRegistry {
recipient_address?: string;
cod_amount?: number;
note?: string;
}): Promise<any>;
cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any>;
}, tenantId?: string): Promise<any>;
cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string, tenantId?: string): Promise<any>;
/**
* Task T8 — bulk_create_parcels(items[], dry_run?)
*/
+32 -10
View File
@@ -652,7 +652,7 @@ export class CourierRegistry {
/**
* Update delivery instructions, recipient phone, address or COD for consignment
*/
async updateParcel(courier, consignmentId, updates) {
async updateParcel(courier, consignmentId, updates, tenantId) {
const cid = String(consignmentId || "").trim();
if (!cid) {
throw new McpToolError({
@@ -677,23 +677,35 @@ export class CourierRegistry {
}
if (registryDbPool) {
try {
const effectiveTenant = String(tenantId || "default").trim() || "default";
const setClauses = ["updated_at = NOW()"];
const vals = [];
let pIndex = 1;
if (updates.recipient_phone) {
setClauses.push(`recipient_phone = $${pIndex++}`);
setClauses.push(`phone = $${pIndex++}`);
vals.push(updates.recipient_phone);
}
if (updates.recipient_address) {
setClauses.push(`recipient_address = $${pIndex++}`);
setClauses.push(`address = $${pIndex++}`);
vals.push(updates.recipient_address);
}
if (updates.cod_amount !== undefined) {
setClauses.push(`cod_amount = $${pIndex++}`);
vals.push(updates.cod_amount);
}
if (updates.note !== undefined) {
setClauses.push(`raw = jsonb_set(COALESCE(raw, '{}'::jsonb), '{delivery_note}', to_jsonb($${pIndex++}::text), true)`);
vals.push(String(updates.note));
}
const cidIdx = pIndex++;
vals.push(cid);
await registryDbPool.query(`UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE tracking_code = $${pIndex} OR consignment_id = $${pIndex}`, vals);
let whereClause = `(tracking_code = $${cidIdx} OR raw->>'consignment_id' = $${cidIdx})`;
if (effectiveTenant !== "master") {
const tenantIdx = pIndex++;
vals.push(effectiveTenant);
whereClause += ` AND tenant = $${tenantIdx}`;
}
await registryDbPool.query(`UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE ${whereClause}`, vals);
}
catch (dbErr) {
console.warn("[Registry] DB parcel update skipped:", dbErr?.message);
@@ -701,7 +713,7 @@ export class CourierRegistry {
}
return upstreamResult;
}
async cancelParcel(courier, consignmentId, reason) {
async cancelParcel(courier, consignmentId, reason, tenantId) {
const cid = String(consignmentId || "").trim();
if (!cid) {
throw new McpToolError({
@@ -718,13 +730,23 @@ export class CourierRegistry {
});
}
const result = await adapter.cancelParcel(cid, reason);
const effectiveTenant = String(tenantId || "default").trim() || "default";
if (registryDbPool) {
try {
await registryDbPool.query(`UPDATE courier_parcels
SET status = 'cancelled', updated_at = NOW()
WHERE consignment_id = $1 OR tracking_code = $1`, [cid]);
if (effectiveTenant === "master") {
await registryDbPool.query(`UPDATE courier_parcels
SET status = 'cancelled', updated_at = NOW()
WHERE (tracking_code = $1 OR raw->>'consignment_id' = $1)`, [cid]);
}
else {
await registryDbPool.query(`UPDATE courier_parcels
SET status = 'cancelled', updated_at = NOW()
WHERE (tracking_code = $1 OR raw->>'consignment_id' = $1) AND tenant = $2`, [cid, effectiveTenant]);
}
}
catch (dbErr) {
console.warn("[Registry] DB parcel cancellation update skipped:", dbErr?.message);
}
catch (_) { }
}
recordWebhookEvent({
id: "cancel_" + cid,
@@ -733,7 +755,7 @@ export class CourierRegistry {
status: result.status || "cancelled",
received_at: new Date().toISOString(),
payload: result,
});
}, effectiveTenant);
return result;
}
/**
+2 -2
View File
@@ -404,7 +404,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
return { isError: false, envelope: wrapSuccess(result, "live_api") };
}
case "cancel_parcel": {
const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""), args?.reason ? String(args.reason) : undefined);
const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""), args?.reason ? String(args.reason) : undefined, tenantId);
return { isError: false, envelope: wrapSuccess(result, "live_api") };
}
case "update_parcel": {
@@ -413,7 +413,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
recipient_address: args?.recipient_address ? String(args.recipient_address) : undefined,
cod_amount: args?.cod_amount !== undefined ? Number(args.cod_amount) : undefined,
note: args?.note ? String(args.note) : undefined,
});
}, tenantId);
return { isError: false, envelope: wrapSuccess(result, "live_api") };
}
case "bulk_create_parcels": {
+1 -1
View File
@@ -11,6 +11,6 @@ function readPackageVersion() {
catch {
// Fallback if package.json is unavailable at runtime
}
return "2.7.2";
return "2.7.3";
}
export const APP_VERSION = readPackageVersion();