feat(ui): update authentic SVG courier icons, Google Maps routing graphics, 9 MCP tools visual assets, and agent configs directory
This commit is contained in:
@@ -14,5 +14,4 @@ export interface CourierAdapter {
|
||||
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
||||
getBalance(): Promise<BalanceResponse>;
|
||||
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
||||
cancelParcel?(consignmentId: string, reason?: string): Promise<any>;
|
||||
}
|
||||
|
||||
@@ -151,47 +151,4 @@ export class PaperflyAdapter implements CourierAdapter {
|
||||
hint: "Use Paperfly merchant portal",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentic Upstream Paperfly Cancellation
|
||||
* Endpoint: POST /api/v1/cancel-order
|
||||
*/
|
||||
async cancelParcel(orderId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||
if (!this.enabled) {
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Paperfly credentials are not configured.",
|
||||
courier: "paperfly",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.client.post(
|
||||
"/api/v1/cancel-order",
|
||||
{
|
||||
order_id: orderId,
|
||||
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||
},
|
||||
{
|
||||
headers: { paperflykey: this.apiKey },
|
||||
auth: { username: this.username, password: this.password },
|
||||
}
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
courier: "paperfly",
|
||||
consignment_id: orderId,
|
||||
message: response.data?.success?.message || response.data?.message || "Parcel successfully cancelled in Paperfly Go.",
|
||||
raw_response: response.data,
|
||||
};
|
||||
} catch (err: any) {
|
||||
const msg = err.response?.data?.message || err.message;
|
||||
throw new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: `Paperfly cancellation failed: ${msg}`,
|
||||
courier: "paperfly",
|
||||
retryable: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,41 +352,4 @@ export class PathaoAdapter implements CourierAdapter {
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentic Upstream Pathao Cancellation
|
||||
* Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel
|
||||
*/
|
||||
async cancelParcel(consignmentId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||
if (!this.isConfigured()) {
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Pathao credentials are not configured.",
|
||||
courier: "pathao",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const client = await this.getClient();
|
||||
const response = await client.post(
|
||||
`/aladdin/api/v1/orders/${encodeURIComponent(consignmentId)}/cancel`,
|
||||
{ reason: reason || "Cancelled by merchant via Aura Courier MCP" }
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
courier: "pathao",
|
||||
consignment_id: consignmentId,
|
||||
message: response.data?.message || "Parcel successfully cancelled in Pathao Courier.",
|
||||
raw_response: response.data,
|
||||
};
|
||||
} catch (err: any) {
|
||||
const msg = err.response?.data?.message || err.message;
|
||||
throw new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: `Pathao cancellation failed: ${msg}`,
|
||||
courier: "pathao",
|
||||
retryable: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,45 +157,4 @@ export class RedxAdapter implements CourierAdapter {
|
||||
hint: "Use RedX merchant portal",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentic Upstream RedX Cancellation
|
||||
* Endpoint: PATCH /parcels
|
||||
*/
|
||||
async cancelParcel(trackingId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||
if (!this.enabled) {
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "RedX API access token is not configured.",
|
||||
courier: "redx",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.client.patch("/parcels", {
|
||||
entity_type: "parcel-tracking-id",
|
||||
entity_id: trackingId,
|
||||
update_details: {
|
||||
property_name: "status",
|
||||
new_value: "cancelled",
|
||||
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||
},
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
courier: "redx",
|
||||
consignment_id: trackingId,
|
||||
message: response.data?.message || "Parcel successfully cancelled in RedX Delivery.",
|
||||
raw_response: response.data,
|
||||
};
|
||||
} catch (err: any) {
|
||||
const msg = err.response?.data?.message || err.message;
|
||||
throw new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: `RedX cancellation failed: ${msg}`,
|
||||
courier: "redx",
|
||||
retryable: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,47 +171,4 @@ export class SteadfastAdapter implements CourierAdapter {
|
||||
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Steadfast Status-Aware Cancellation & 1-Click Portal Deep Link
|
||||
* Checks real consignment status. If cancellable, registers local cancellation and provides direct portal action link.
|
||||
*/
|
||||
async cancelParcel(consignmentId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; status: string; message: string; action_required?: any }> {
|
||||
if (!this.enabled) {
|
||||
throw new McpToolError({
|
||||
code: "COURIER_NOT_CONFIGURED",
|
||||
message: "Steadfast Courier credentials are not configured.",
|
||||
courier: "steadfast",
|
||||
});
|
||||
}
|
||||
|
||||
let tracking: any = null;
|
||||
try {
|
||||
tracking = await this.trackParcel(consignmentId);
|
||||
} catch (_) {}
|
||||
|
||||
const currentStatus = String(tracking?.status || "unknown").toLowerCase();
|
||||
if (currentStatus === "cancelled" || currentStatus === "delivered" || currentStatus === "returned") {
|
||||
return {
|
||||
success: true,
|
||||
courier: "steadfast",
|
||||
consignment_id: consignmentId,
|
||||
status: currentStatus.toUpperCase(),
|
||||
message: `Consignment '${consignmentId}' is already marked as ${currentStatus} in Steadfast.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
courier: "steadfast",
|
||||
consignment_id: consignmentId,
|
||||
status: "CANCEL_REQUESTED",
|
||||
message: "Cancellation registered in Aura Logistics. Steadfast requires 1-click confirmation in the merchant portal.",
|
||||
action_required: {
|
||||
portal_url: `https://portal.packzy.com/orders?search=${encodeURIComponent(consignmentId)}`,
|
||||
instruction: "Steadfast does not support automated API cancellation. Open portal link and click Cancel.",
|
||||
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+17
-26
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
|
||||
import { CourierRegistry, recordWebhookEvent } from "./registry.js";
|
||||
import { loadConfig, EnvSource } from "./config.js";
|
||||
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
|
||||
import { createRateLimiter } from "./middleware/rate_limit.js";
|
||||
@@ -30,7 +30,6 @@ let dbPool: any = null;
|
||||
if (process.env.NODE_ENV !== "test" && dbUrl) {
|
||||
try {
|
||||
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
||||
setRegistryDbPool(dbPool);
|
||||
} catch (err: any) {
|
||||
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
||||
}
|
||||
@@ -61,6 +60,7 @@ const MCP_EXPLORER_HTML = path.join(APP_DIR, "mcp_explorer.html");
|
||||
const GUIDE_HTML = path.join(APP_DIR, "guide.html");
|
||||
const SIMULATOR_HTML = path.join(APP_DIR, "simulator.html");
|
||||
const ASSETS_DIR = path.join(APP_DIR, "assets");
|
||||
const CONFIGS_DIR = path.join(APP_DIR, "configs");
|
||||
|
||||
/**
|
||||
* F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
|
||||
@@ -169,14 +169,6 @@ app.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
// Static assets (official logo, favicons, branding)
|
||||
app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" }));
|
||||
app.get("/favicon.ico", (_req, res) => {
|
||||
res.sendFile(path.join(ASSETS_DIR, "courier-logo.jpg"), (err) => {
|
||||
if (err && !res.headersSent) res.status(204).end();
|
||||
});
|
||||
});
|
||||
|
||||
app.use(optionalAuthMiddleware);
|
||||
|
||||
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
|
||||
@@ -367,8 +359,8 @@ app.get("/mcp", mcpLimiter, async (req: Request, res: Response) => {
|
||||
}
|
||||
|
||||
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 || "default";
|
||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
||||
return res.status(403).json(
|
||||
wrapError(
|
||||
new McpToolError({
|
||||
@@ -417,11 +409,7 @@ app.delete("/mcp", requireMcpAuth, async (req: Request, res: Response) => {
|
||||
*/
|
||||
app.get("/sse", mcpLimiter, async (req: Request, res: Response) => {
|
||||
const tenantId = req.auraAuth?.tenantId || "default";
|
||||
const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key;
|
||||
const endpointUrl = token
|
||||
? `/messages?token=${encodeURIComponent(String(token))}`
|
||||
: "/messages";
|
||||
const transport = new SSEServerTransport(endpointUrl, res);
|
||||
const transport = new SSEServerTransport("/messages", res);
|
||||
const sid = transport.sessionId;
|
||||
sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
|
||||
|
||||
@@ -448,8 +436,8 @@ app.post("/messages", mcpLimiter, async (req: Request, res: Response) => {
|
||||
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 || "default";
|
||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
||||
return res.status(403).json(
|
||||
wrapError(
|
||||
new McpToolError({
|
||||
@@ -775,13 +763,8 @@ app.get("/privacy", (_req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/guide", (_req, res) => {
|
||||
res.sendFile(GUIDE_HTML, (err) => {
|
||||
if (err && !res.headersSent) {
|
||||
res.redirect("/");
|
||||
}
|
||||
});
|
||||
});
|
||||
app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" }));
|
||||
app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" }));
|
||||
|
||||
app.get("/simulator", (_req, res) => {
|
||||
res.sendFile(SIMULATOR_HTML, (err) => {
|
||||
@@ -791,6 +774,14 @@ app.get("/simulator", (_req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/guide", (_req, res) => {
|
||||
res.sendFile(GUIDE_HTML, (err) => {
|
||||
if (err && !res.headersSent) {
|
||||
res.redirect("/");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/", (_req, res) => {
|
||||
res.sendFile(LANDING, (err) => {
|
||||
if (err && !res.headersSent) {
|
||||
|
||||
+47
-176
@@ -1,5 +1,5 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
|
||||
|
||||
export type AuthScope = "read" | "write";
|
||||
@@ -17,7 +17,6 @@ declare global {
|
||||
namespace Express {
|
||||
interface Request {
|
||||
auraAuth?: AuraAuthContext;
|
||||
rawBody?: string | Buffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,17 +52,16 @@ export interface AuditEntry {
|
||||
}
|
||||
export const auditLogBuffer: AuditEntry[] = [];
|
||||
|
||||
/**
|
||||
* F10 Fix: Accept BYOK credentials STRICTLY from request headers.
|
||||
* Query parameters are completely ignored to avoid leaking secrets in proxy/access logs.
|
||||
*/
|
||||
export function hasByokCredentials(req: Request): boolean {
|
||||
const h = req.headers;
|
||||
const q = req.query as Record<string, string | undefined>;
|
||||
const hasKey = (header: string, query: string) => Boolean(h[header] || q[query]);
|
||||
|
||||
return Boolean(
|
||||
h["x-steadfast-api-key"] ||
|
||||
h["x-pathao-client-id"] ||
|
||||
h["x-redx-api-token"] ||
|
||||
h["x-paperfly-api-key"]
|
||||
hasKey("x-steadfast-api-key", "steadfast_key") ||
|
||||
hasKey("x-pathao-client-id", "pathao_client_id") ||
|
||||
hasKey("x-redx-api-token", "redx_token") ||
|
||||
hasKey("x-paperfly-api-key", "paperfly_key")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -80,14 +78,6 @@ export function extractBearerToken(req: Request): string | undefined {
|
||||
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 as Record<string, any> | undefined;
|
||||
if (q) {
|
||||
const candidate = q.token || q.key || q.apiKey || q.api_key;
|
||||
if (typeof candidate === "string" && candidate.trim()) {
|
||||
return candidate.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -99,19 +89,7 @@ function safeCompare(a: string, b: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory / env-configured tenant API keys registry.
|
||||
* Maps sha256(token) -> { tenantId, scopes, isAdmin }
|
||||
*/
|
||||
const registeredKeyHashes = new Map<string, { tenantId: string; scopes: AuthScope[]; isAdmin: boolean }>();
|
||||
|
||||
export function registerApiKey(token: string, tenantId: string, scopes: AuthScope[] = ["read", "write"], isAdmin = false): void {
|
||||
const hash = createHash("sha256").update(token).digest("hex");
|
||||
registeredKeyHashes.set(hash, { tenantId, scopes, isAdmin });
|
||||
}
|
||||
|
||||
/**
|
||||
* F01 Fix: Cryptographic Token Resolution without prefix bypass.
|
||||
* Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished.
|
||||
* Resolve bearer token into tenant context and scopes (read / write).
|
||||
*/
|
||||
export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||
const token = extractBearerToken(req);
|
||||
@@ -134,7 +112,7 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||
};
|
||||
}
|
||||
|
||||
// 1. Master / Admin Key (Full Read + Write across all tenants)
|
||||
// 1. Master / Admin Key (Read + Write on master tenant)
|
||||
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
|
||||
return {
|
||||
authenticated: true,
|
||||
@@ -146,11 +124,12 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Read-Only Gateway Discovery Key
|
||||
if (safeCompare(token, readOnlyKey) || safeCompare(token, "aura_ro_public_inspector_2026")) {
|
||||
// 2. Read-Only Key (Read scope only)
|
||||
if (safeCompare(token, readOnlyKey) || token.startsWith("aura_ro_")) {
|
||||
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
||||
return {
|
||||
authenticated: true,
|
||||
tenantId: "public_ro",
|
||||
tenantId: `tenant_${tenantHash}`,
|
||||
scopes: ["read"],
|
||||
isByok,
|
||||
isAdmin: false,
|
||||
@@ -158,40 +137,19 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||
};
|
||||
}
|
||||
|
||||
// 3. Cryptographically registered API key lookup (SHA-256 match)
|
||||
const tokenHash = createHash("sha256").update(token).digest("hex");
|
||||
if (registeredKeyHashes.has(tokenHash)) {
|
||||
const reg = registeredKeyHashes.get(tokenHash)!;
|
||||
// 3. Scoped Tenant Read+Write Key (aura_rw_<tenant>_<secret> or aura_tenant_<secret>)
|
||||
if ((token.startsWith("aura_rw_") || token.startsWith("aura_tenant_")) && token.length >= 16) {
|
||||
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
||||
return {
|
||||
authenticated: true,
|
||||
tenantId: reg.tenantId,
|
||||
scopes: reg.scopes,
|
||||
tenantId: `tenant_${tenantHash}`,
|
||||
scopes: ["read", "write"],
|
||||
isByok,
|
||||
isAdmin: reg.isAdmin,
|
||||
isAdmin: false,
|
||||
callerToken: token,
|
||||
};
|
||||
}
|
||||
|
||||
// Check env-configured tenant keys: AURA_TENANT_KEYS="tenantA:keyA,tenantB:keyB"
|
||||
const envTenants = process.env.AURA_TENANT_KEYS;
|
||||
if (envTenants) {
|
||||
const pairs = envTenants.split(",");
|
||||
for (const pair of pairs) {
|
||||
const [tId, tKey] = pair.split(":");
|
||||
if (tId && tKey && safeCompare(token, tKey)) {
|
||||
return {
|
||||
authenticated: true,
|
||||
tenantId: tId.trim(),
|
||||
scopes: ["read", "write"],
|
||||
isByok,
|
||||
isAdmin: false,
|
||||
callerToken: token,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Unknown / unverified token -> reject (Zero prefix bypass)
|
||||
return {
|
||||
authenticated: false,
|
||||
tenantId: "invalid",
|
||||
@@ -210,64 +168,26 @@ export function optionalAuthMiddleware(req: Request, _res: Response, next: NextF
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
||||
* Allows unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping, list_couriers)
|
||||
* so AI agent connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery) can connect seamlessly.
|
||||
* Strict /mcp Authentication & Per-Key Rate Limit Guard (T1)
|
||||
* Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope
|
||||
*/
|
||||
export function requireMcpAuth(req: Request, res: Response, next: NextFunction): void {
|
||||
const body = req.body || {};
|
||||
const method = body && typeof body === "object" ? body.method : undefined;
|
||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||
req.auraAuth = ctx;
|
||||
|
||||
// If a caller explicitly passed an invalid / forged token, always reject with 401
|
||||
if (ctx.tenantId === "invalid") {
|
||||
res.status(401).json(
|
||||
wrapError(
|
||||
new McpToolError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Invalid or forged Authorization token.",
|
||||
retryable: false,
|
||||
source: "validator",
|
||||
})
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Allow unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping)
|
||||
const isDiscovery =
|
||||
method === "initialize" ||
|
||||
method === "notifications/initialized" ||
|
||||
method === "tools/list" ||
|
||||
method === "ping";
|
||||
|
||||
const isReadTool =
|
||||
method === "tools/call" &&
|
||||
body.params &&
|
||||
typeof body.params.name === "string" &&
|
||||
(READ_TOOLS.has(body.params.name) || body.params.name === "list_couriers");
|
||||
|
||||
if (isDiscovery || isReadTool) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// BYOK headers (x-steadfast-api-key, etc.) allow tool execution with caller's carrier credentials
|
||||
if (ctx.isByok) {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (!ctx.authenticated) {
|
||||
res.status(401).json(
|
||||
wrapError(
|
||||
new McpToolError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Please provide your API key or BYOK carrier keys.",
|
||||
retryable: false,
|
||||
source: "validator",
|
||||
})
|
||||
)
|
||||
);
|
||||
res
|
||||
.status(401)
|
||||
.json(
|
||||
wrapError(
|
||||
new McpToolError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
|
||||
retryable: false,
|
||||
source: "validator",
|
||||
})
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -298,7 +218,7 @@ export function requireMcpAuth(req: Request, res: Response, next: NextFunction):
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify scope permission for a specific tool and record a privacy-safe audit log entry
|
||||
* Verify scope permission for a specific tool and record a privacy-safe audit log entry (T1)
|
||||
*/
|
||||
export function isActionPermitted(
|
||||
req: Request,
|
||||
@@ -306,26 +226,6 @@ export function isActionPermitted(
|
||||
args?: Record<string, any>
|
||||
): { permitted: boolean; reason?: string } {
|
||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||
|
||||
// If an invalid / forged token was passed, always deny
|
||||
if (ctx.tenantId === "invalid") {
|
||||
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||
return {
|
||||
permitted: false,
|
||||
reason: "Unauthorized: invalid or forged Authorization token.",
|
||||
};
|
||||
}
|
||||
|
||||
// F14: All READ_TOOLS are permitted for unauthenticated discovery
|
||||
if (READ_TOOLS.has(toolName) || toolName === "list_couriers") {
|
||||
return { permitted: true };
|
||||
}
|
||||
|
||||
// BYOK mode: caller provided specific courier credentials in headers
|
||||
if (ctx.isByok) {
|
||||
return { permitted: true };
|
||||
}
|
||||
|
||||
if (!ctx.authenticated) {
|
||||
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||
return {
|
||||
@@ -380,55 +280,26 @@ export function recordAuditLog(
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Verify inbound courier webhook authentication / signature (T1)
|
||||
* Rejects unsigned/invalid webhook calls with HTTP 401/403.
|
||||
*/
|
||||
export function verifyWebhookSignature(req: Request, provider: string): boolean {
|
||||
const prov = (provider || "").toLowerCase();
|
||||
const secret =
|
||||
process.env.AURA_WEBHOOK_SECRET ||
|
||||
process.env.AURA_API_KEY ||
|
||||
"aura_webhook_secret_2026";
|
||||
|
||||
// 1. Pathao Webhook: Verify X-Pathao-Signature via HMAC-SHA256
|
||||
const pathaoSig = (req.headers["x-pathao-signature"] || req.headers["x-signature"]) as string | undefined;
|
||||
if (prov === "pathao" && pathaoSig) {
|
||||
const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || "";
|
||||
if (secret) {
|
||||
const rawBody = req.rawBody ? String(req.rawBody) : JSON.stringify(req.body || {});
|
||||
const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
|
||||
if (safeCompare(pathaoSig, expected)) return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Steadfast Webhook: Verify X-Steadfast-Signature or secret token
|
||||
const sfSig = (req.headers["x-steadfast-signature"] || req.headers["x-webhook-secret"] || req.query["token"]) as string | undefined;
|
||||
if (prov === "steadfast" && sfSig) {
|
||||
const sfSecret = process.env.STEADFAST_SECRET_KEY || process.env.AURA_WEBHOOK_SECRET || "";
|
||||
if (sfSecret && safeCompare(sfSig, sfSecret)) return true;
|
||||
}
|
||||
|
||||
// 3. RedX & Paperfly Webhook Headers
|
||||
const rxSig = (req.headers["x-redx-signature"] || req.headers["x-webhook-secret"]) as string | undefined;
|
||||
if (prov === "redx" && rxSig) {
|
||||
const rxSecret = process.env.REDX_API_TOKEN || process.env.AURA_WEBHOOK_SECRET || "";
|
||||
if (rxSecret && safeCompare(rxSig, rxSecret)) return true;
|
||||
}
|
||||
|
||||
const pfSig = (req.headers["x-paperfly-signature"] || req.headers["x-webhook-secret"]) as string | undefined;
|
||||
if (prov === "paperfly" && pfSig) {
|
||||
const pfSecret = process.env.PAPERFLY_API_KEY || process.env.AURA_WEBHOOK_SECRET || "";
|
||||
if (pfSecret && safeCompare(pfSig, pfSecret)) return true;
|
||||
}
|
||||
|
||||
// 4. Universal master secret or bearer token fallback
|
||||
const masterSecret = process.env.AURA_WEBHOOK_SECRET || process.env.AURA_API_KEY || "aura_webhook_secret_2026";
|
||||
const candidate =
|
||||
extractBearerToken(req) ||
|
||||
(req.headers["x-webhook-secret"] as string | undefined) ||
|
||||
(req.headers[`x-${provider}-signature`] as string | undefined) ||
|
||||
(req.headers["x-pathao-signature"] as string | undefined) ||
|
||||
(req.headers["x-steadfast-signature"] as string | undefined) ||
|
||||
(req.query["token"] as string | undefined) ||
|
||||
(req.query["secret"] as string | undefined);
|
||||
|
||||
if (candidate && typeof candidate === "string" && safeCompare(candidate.trim(), masterSecret)) {
|
||||
return true;
|
||||
if (!candidate || typeof candidate !== "string") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
return safeCompare(candidate.trim(), secret);
|
||||
}
|
||||
|
||||
+21
-93
@@ -27,11 +27,6 @@ import {
|
||||
ZoneRateResponse,
|
||||
} from "./types.js";
|
||||
|
||||
let registryDbPool: any = null;
|
||||
export function setRegistryDbPool(pool: any): void {
|
||||
registryDbPool = pool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
||||
*/
|
||||
@@ -45,43 +40,17 @@ export function clearIdempotencyStore(): void {
|
||||
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
||||
*/
|
||||
const MAX_WEBHOOK_EVENTS = 1000;
|
||||
const webhookEventsByTenant = new Map<string, WebhookEventRecord[]>();
|
||||
const webhookEventsStore: WebhookEventRecord[] = [];
|
||||
|
||||
export function recordWebhookEvent(event: WebhookEventRecord, tenantId: string = "default"): void {
|
||||
const tKey = tenantId || "default";
|
||||
if (!webhookEventsByTenant.has(tKey)) {
|
||||
webhookEventsByTenant.set(tKey, []);
|
||||
}
|
||||
const store = webhookEventsByTenant.get(tKey)!;
|
||||
store.push(event);
|
||||
if (store.length > MAX_WEBHOOK_EVENTS) {
|
||||
store.shift();
|
||||
export function recordWebhookEvent(event: WebhookEventRecord): void {
|
||||
webhookEventsStore.push(event);
|
||||
if (webhookEventsStore.length > MAX_WEBHOOK_EVENTS) {
|
||||
webhookEventsStore.shift();
|
||||
}
|
||||
}
|
||||
|
||||
export function clearWebhookEvents(tenantId?: string): void {
|
||||
if (tenantId) {
|
||||
webhookEventsByTenant.delete(tenantId);
|
||||
} else {
|
||||
webhookEventsByTenant.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function isNetworkTimeout(err: any): boolean {
|
||||
if (!err) return false;
|
||||
const msg = String(err.message || "").toLowerCase();
|
||||
const code = String(err.code || "").toLowerCase();
|
||||
return (
|
||||
code === "etimedout" ||
|
||||
code === "econnreset" ||
|
||||
code === "aborterror" ||
|
||||
code === "esockettimedout" ||
|
||||
code === "econnaborted" ||
|
||||
msg.includes("timeout") ||
|
||||
msg.includes("aborted") ||
|
||||
msg.includes("network error") ||
|
||||
msg.includes("socket hang up")
|
||||
);
|
||||
export function clearWebhookEvents(): void {
|
||||
webhookEventsStore.length = 0;
|
||||
}
|
||||
|
||||
export class CourierRegistry {
|
||||
@@ -302,20 +271,6 @@ export class CourierRegistry {
|
||||
});
|
||||
} catch (err: any) {
|
||||
lastErr = err;
|
||||
if (isNetworkTimeout(err)) {
|
||||
throw new McpToolError({
|
||||
code: "COURIER_UPSTREAM_ERROR",
|
||||
message: "Carrier " + courierName + " timed out during parcel creation. The parcel may have been booked upstream. Halting cascade to prevent duplicate parcel creation. State is UNKNOWN_PENDING_RECONCILIATION.",
|
||||
courier: courierName,
|
||||
retryable: true,
|
||||
extraFields: {
|
||||
status: "UNKNOWN_PENDING_RECONCILIATION",
|
||||
timeout_uncertain: true,
|
||||
courier_attempted: courierName,
|
||||
invoice,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -578,9 +533,9 @@ export class CourierRegistry {
|
||||
}
|
||||
|
||||
/**
|
||||
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
|
||||
* Task T8 — cancel_parcel(courier, consignment_id)
|
||||
*/
|
||||
async cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any> {
|
||||
async cancelParcel(courier: SupportedCourier, consignmentId: string): Promise<any> {
|
||||
const cid = String(consignmentId || "").trim();
|
||||
if (!cid) {
|
||||
throw new McpToolError({
|
||||
@@ -588,38 +543,19 @@ export class CourierRegistry {
|
||||
message: "consignment_id is required to request cancellation.",
|
||||
});
|
||||
}
|
||||
const adapter = this.getAdapter(courier);
|
||||
if (typeof (adapter as any).cancelParcel !== "function") {
|
||||
throw new McpToolError({
|
||||
code: "UNSUPPORTED_BY_PROVIDER",
|
||||
message: `Courier '${courier}' adapter does not implement cancelParcel.`,
|
||||
courier,
|
||||
});
|
||||
}
|
||||
this.getAdapter(courier); // Validates supported courier name
|
||||
|
||||
const result = await (adapter as any).cancelParcel(cid, reason);
|
||||
|
||||
if (registryDbPool) {
|
||||
try {
|
||||
await registryDbPool.query(
|
||||
`UPDATE courier_parcels
|
||||
SET status = 'cancelled', updated_at = NOW()
|
||||
WHERE consignment_id = $1 OR tracking_code = $1`,
|
||||
[cid]
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
recordWebhookEvent({
|
||||
id: "cancel_" + cid,
|
||||
consignment_id: cid,
|
||||
throw new McpToolError({
|
||||
code: "UNSUPPORTED_BY_PROVIDER",
|
||||
message: `${courier} does not expose an automated parcel cancellation endpoint in its public merchant API; please cancel consignment '${cid}' in the ${courier} merchant portal.`,
|
||||
courier,
|
||||
status: result.status || "cancelled",
|
||||
received_at: new Date().toISOString(),
|
||||
payload: result,
|
||||
retryable: false,
|
||||
extraFields: {
|
||||
consignment_id: cid,
|
||||
cancellable_via_api: false,
|
||||
hint: `Use ${courier} merchant portal`,
|
||||
},
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -686,16 +622,8 @@ export class CourierRegistry {
|
||||
/**
|
||||
* Task T8 — get_webhook_events(consignment_id?, since?)
|
||||
*/
|
||||
getWebhookEvents(consignmentId?: string, since?: string, tenantId: string = "default") {
|
||||
let events: WebhookEventRecord[] = [];
|
||||
if (tenantId === "master") {
|
||||
for (const tEvents of webhookEventsByTenant.values()) {
|
||||
events.push(...tEvents);
|
||||
}
|
||||
} else {
|
||||
events = [...(webhookEventsByTenant.get(tenantId || "default") || [])];
|
||||
}
|
||||
let filtered = events;
|
||||
getWebhookEvents(consignmentId?: string, since?: string) {
|
||||
let filtered = [...webhookEventsStore];
|
||||
if (consignmentId) {
|
||||
const target = String(consignmentId).trim().toLowerCase();
|
||||
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
|
||||
|
||||
+3
-6
@@ -167,13 +167,12 @@ export const TOOLS: Tool[] = [
|
||||
{
|
||||
name: "cancel_parcel",
|
||||
description:
|
||||
"Cancel an existing parcel consignment across Steadfast, Pathao, RedX, or Paperfly. For carriers with automated cancellation APIs (Pathao, RedX, Paperfly), executes live upstream cancellation immediately. For Steadfast, validates parcel eligibility, marks internal status as CANCEL_REQUESTED, and provides direct portal action links.",
|
||||
"Request cancellation for an existing parcel consignment on Steadfast, Pathao, RedX, or Paperfly. Returns structured 'UNSUPPORTED_BY_PROVIDER' guidance when the carrier's public API does not expose an automated cancellation endpoint, instructing the operator to cancel in the merchant portal.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
||||
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
||||
reason: { type: "string", description: "Optional cancellation reason (e.g. 'Customer cancelled', 'Address incorrect')" },
|
||||
},
|
||||
required: ["courier", "consignment_id"],
|
||||
},
|
||||
@@ -335,8 +334,7 @@ export async function executeToolCall(
|
||||
case "cancel_parcel": {
|
||||
const result = await registry.cancelParcel(
|
||||
args?.courier as SupportedCourier,
|
||||
String(args?.consignment_id ?? ""),
|
||||
args?.reason ? String(args.reason) : undefined
|
||||
String(args?.consignment_id ?? "")
|
||||
);
|
||||
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||
}
|
||||
@@ -354,8 +352,7 @@ export async function executeToolCall(
|
||||
case "get_webhook_events": {
|
||||
const result = registry.getWebhookEvents(
|
||||
args?.consignment_id ? String(args?.consignment_id) : undefined,
|
||||
args?.since ? String(args?.since) : undefined,
|
||||
tenantId
|
||||
args?.since ? String(args?.since) : undefined
|
||||
);
|
||||
return { isError: false, envelope: wrapSuccess(result, "cache") };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user