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:
Amirul Islam Redwan71
2026-11-11 06:10:30 +06:00
parent b4396770c0
commit f496a5316e
39 changed files with 1261 additions and 1695 deletions
+2 -3
View File
@@ -6,10 +6,9 @@ WORKDIR /app
COPY package*.json tsconfig.json ./
RUN npm install --no-audit --no-fund
# Source + web, static assets and simulator
# Source + the marketing landing page (served at /)
COPY src ./src
COPY assets ./assets
COPY README.md index.html guide.html health.html privacy.html mcp_explorer.html simulator.html ./
COPY README.md index.html ./
RUN npm run build
ENV NODE_ENV=production
+3 -3
View File
@@ -117,9 +117,9 @@ Aura Courier MCP seamlessly interfaces with all tier-1 Bangladesh courier APIs u
---
## 4. The 12 Enterprise Model Context Protocol (MCP) Tools
## 4. The 9 Enterprise Model Context Protocol (MCP) Tools
Aura Courier MCP exports 12 tools conforming to the MCP Specification (`2024-11-05`):
Aura Courier MCP exports 9 tools conforming to the MCP Specification (`2024-11-05`):
### 1. `list_couriers`
* **Purpose**: Inspect carrier operational health and active credentials.
@@ -229,7 +229,7 @@ curl -s https://courier.auraajenticai.cloud/health | jq
"ok": true,
"service": "aura-courier-mcp",
"version": "2.6.0",
"tools_count": 12,
"tools_count": 9,
"spatial_engine": "Google Maps Platform (gmp_git_agentskills_v1)",
"fraud_engine": "Steadfast Nationwide API + BD Prefix Validator",
"webhooks": {
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

+40
View File
@@ -0,0 +1,40 @@
# Aura Courier MCP — Agent Configurations Vault
Connect any AI Agent / IDE to Aura Courier MCP in seconds.
## Endpoints:
- **Streamable-HTTP (Cursor, Antigravity, Windsurf, Cline, n8n)**:
`https://courier.auraajenticai.cloud/mcp`
- **Server-Sent Events / SSE (Claude Desktop, Remote SSE)**:
`https://courier.auraajenticai.cloud/sse`
- **NPX Direct CLI**:
`npx -y @auraajenticai/aura-courier-mcp@2.6.0`
---
## 1. Google Antigravity & Gemini CLI
File: `antigravity_gemini.json`
Location:
- Windows: `%USERPROFILE%\.gemini\antigravity\mcp\aura-courier\server.json`
- Linux/macOS: `~/.gemini/antigravity/mcp/aura-courier/server.json`
## 2. Claude Desktop
File: `claude_desktop_config.json`
Location:
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
## 3. Cursor IDE
File: `cursor_mcp.json`
Location:
- Settings -> Features -> MCP -> Add new MCP server -> Type: `http`, URL: `https://courier.auraajenticai.cloud/mcp`
## 4. Windsurf IDE
File: `windsurf_mcp_config.json`
Location:
- `~/.codeium/windsurf/mcp_config.json`
## 5. Cline / Roo Code / VS Code
File: `cline_mcp_settings.json`
Location:
- VS Code Settings -> Extension Settings -> Cline / Roo Code -> Edit in settings.json
+18
View File
@@ -0,0 +1,18 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Aura Courier MCP - Google Antigravity & Gemini CLI Config",
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"type": "http",
"description": "Enterprise Bangladesh Courier MCP & Google Maps Spatial Hub"
},
"aura-courier-local": {
"command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"],
"env": {
"PORT": "8080"
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/sse",
"transport": "sse"
},
"aura-courier-stdio": {
"command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"]
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"autoApprove": [
"list_couriers",
"calculate_delivery_zone_and_fee",
"compare_courier_rates",
"validate_and_geocode_address",
"check_fraud_risk",
"track_parcel"
]
}
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"transport": "http"
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"mcpServers": {
"aura-courier": {
"serverUrl": "https://courier.auraajenticai.cloud/mcp"
}
}
}
-1
View File
@@ -6,5 +6,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>;
}
-11
View File
@@ -16,15 +16,4 @@ export declare class PaperflyAdapter implements CourierAdapter {
* Paperfly does not expose a live wallet balance API endpoint (T3).
*/
getBalance(): Promise<BalanceResponse>;
/**
* Authentic Upstream Paperfly Cancellation
* Endpoint: POST /api/v1/cancel-order
*/
cancelParcel(orderId: string, reason?: string): Promise<{
success: boolean;
courier: SupportedCourier;
consignment_id: string;
message: string;
raw_response?: any;
}>;
}
-38
View File
@@ -135,42 +135,4 @@ export class PaperflyAdapter {
hint: "Use Paperfly merchant portal",
};
}
/**
* Authentic Upstream Paperfly Cancellation
* Endpoint: POST /api/v1/cancel-order
*/
async cancelParcel(orderId, reason) {
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) {
const msg = err.response?.data?.message || err.message;
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `Paperfly cancellation failed: ${msg}`,
courier: "paperfly",
retryable: false,
});
}
}
}
-11
View File
@@ -43,15 +43,4 @@ export declare class PathaoAdapter implements CourierAdapter {
*/
fraudCheck(phone: string): Promise<any>;
getLocations(cityName?: string): Promise<LocationResolutionResponse>;
/**
* Authentic Upstream Pathao Cancellation
* Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel
*/
cancelParcel(consignmentId: string, reason?: string): Promise<{
success: boolean;
courier: SupportedCourier;
consignment_id: string;
message: string;
raw_response?: any;
}>;
}
-33
View File
@@ -304,37 +304,4 @@ export class PathaoAdapter {
})),
};
}
/**
* Authentic Upstream Pathao Cancellation
* Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel
*/
async cancelParcel(consignmentId, reason) {
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) {
const msg = err.response?.data?.message || err.message;
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `Pathao cancellation failed: ${msg}`,
courier: "pathao",
retryable: false,
});
}
}
}
-11
View File
@@ -14,15 +14,4 @@ export declare class RedxAdapter implements CourierAdapter {
* RedX does not expose a live wallet balance API endpoint (T3).
*/
getBalance(): Promise<BalanceResponse>;
/**
* Authentic Upstream RedX Cancellation
* Endpoint: PATCH /parcels
*/
cancelParcel(trackingId: string, reason?: string): Promise<{
success: boolean;
courier: SupportedCourier;
consignment_id: string;
message: string;
raw_response?: any;
}>;
}
-40
View File
@@ -137,44 +137,4 @@ export class RedxAdapter {
hint: "Use RedX merchant portal",
};
}
/**
* Authentic Upstream RedX Cancellation
* Endpoint: PATCH /parcels
*/
async cancelParcel(trackingId, reason) {
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) {
const msg = err.response?.data?.message || err.message;
throw new McpToolError({
code: "COURIER_UPSTREAM_ERROR",
message: `RedX cancellation failed: ${msg}`,
courier: "redx",
retryable: false,
});
}
}
}
-12
View File
@@ -14,16 +14,4 @@ export declare class SteadfastAdapter implements CourierAdapter {
* Endpoint: GET /fraud_check/{phone}
*/
fraudCheck(phone: string): Promise<any>;
/**
* Steadfast Status-Aware Cancellation & 1-Click Portal Deep Link
* Checks real consignment status. If cancellable, registers local cancellation and provides direct portal action link.
*/
cancelParcel(consignmentId: string, reason?: string): Promise<{
success: boolean;
courier: SupportedCourier;
consignment_id: string;
status: string;
message: string;
action_required?: any;
}>;
}
-40
View File
@@ -146,44 +146,4 @@ export class SteadfastAdapter {
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, reason) {
if (!this.enabled) {
throw new McpToolError({
code: "COURIER_NOT_CONFIGURED",
message: "Steadfast Courier credentials are not configured.",
courier: "steadfast",
});
}
let tracking = 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",
},
};
}
}
+3 -2
View File
@@ -1,8 +1,9 @@
import { 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.
* Pull this client's courier keys from request headers or query params.
* Task T1 Tenant Isolation: Only fall back to master process.env credentials when
* the caller authenticated with the master key (tenantId === "master").
*/
export declare function keysFromRequest(req: Request): EnvSource;
export declare const app: import("express-serve-static-core").Express;
+78 -227
View File
@@ -1,31 +1,24 @@
import express from "express";
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 } from "./config.js";
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
import { createRateLimiter } from "./middleware/rate_limit.js";
import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, verifyWebhookSignature, recordAuditLog, } from "./middleware/auth.js";
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
/**
* F02 Fix: Remove hardcoded plaintext password.
* Connection string is read strictly from process.env.DATABASE_URL.
*/
const dbUrl = process.env.DATABASE_URL;
const dbUrl = process.env.DATABASE_URL ||
"postgresql://postgres:AMeyaNUsvKN9GR4zs33YZFQw2ZjeBXRacp5K09bz4vwDMsLejuO1KxBGIZtDLVCw@ernix50nvuq9ur9jy8na8tgr:5432/aura_auth";
let dbPool = null;
if (process.env.NODE_ENV !== "test" && dbUrl) {
if (process.env.NODE_ENV !== "test") {
try {
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
setRegistryDbPool(dbPool);
}
catch (err) {
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
}
catch (_) { }
}
// Automated Data Retention Engine (Daily Midnight Sweep)
setInterval(async () => {
@@ -48,77 +41,47 @@ const PRIVACY_HTML = path.join(APP_DIR, "privacy.html");
const HEALTH_HTML = path.join(APP_DIR, "health.html");
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");
/**
* F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
*/
function escapeHtml(str) {
if (str == null)
return "";
return String(str)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
/**
* F03 Helper: Redact recipient street address to District/City level for public tracking.
*/
function redactAddressToDistrict(addr) {
if (!addr)
return "Bangladesh";
const parts = addr.split(",").map((p) => p.trim()).filter(Boolean);
if (parts.length > 1) {
return parts.slice(-2).join(", ");
}
return addr;
}
/**
* F10 Fix: Pull client courier keys strictly from request headers.
* Query parameters are completely ignored to prevent credential leakage in URL logs.
* Pull this client's courier keys from request headers or query params.
* Task T1 Tenant Isolation: Only fall back to master process.env credentials when
* the caller authenticated with the master key (tenantId === "master").
*/
export function keysFromRequest(req) {
const h = req.headers;
const q = req.query;
const allowMasterEnvFallback = req.auraAuth?.tenantId === "master";
const pick = (header, envVar, allowNonMasterEnv = false) => {
const pick = (header, query, envVar, allowNonMasterEnv = false) => {
const hv = h[header];
const v = Array.isArray(hv) ? hv[0] : hv;
if (v && typeof v === "string" && v.trim())
return v.trim();
const v = (Array.isArray(hv) ? hv[0] : hv) ?? q[query];
if (v)
return String(v);
if (envVar && (allowMasterEnvFallback || allowNonMasterEnv)) {
return process.env[envVar];
}
return undefined;
};
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),
PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"),
PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"),
PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"),
PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"),
PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"),
PATHAO_BASE_URL: pick("x-pathao-base-url", "PATHAO_BASE_URL", true),
REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"),
REDX_BASE_URL: pick("x-redx-base-url", "REDX_BASE_URL", true),
REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "REDX_PICKUP_STORE_ID"),
PAPERFLY_API_KEY: pick("x-paperfly-api-key", "PAPERFLY_API_KEY"),
PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"),
PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"),
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"),
GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true),
STEADFAST_API_KEY: pick("x-steadfast-api-key", "steadfast_key", "STEADFAST_API_KEY"),
STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "steadfast_secret", "STEADFAST_SECRET_KEY"),
STEADFAST_BASE_URL: pick("x-steadfast-base-url", "steadfast_base_url", "STEADFAST_BASE_URL", true),
PATHAO_CLIENT_ID: pick("x-pathao-client-id", "pathao_client_id", "PATHAO_CLIENT_ID"),
PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "pathao_client_secret", "PATHAO_CLIENT_SECRET"),
PATHAO_USERNAME: pick("x-pathao-username", "pathao_username", "PATHAO_USERNAME"),
PATHAO_PASSWORD: pick("x-pathao-password", "pathao_password", "PATHAO_PASSWORD"),
PATHAO_STORE_ID: pick("x-pathao-store-id", "pathao_store_id", "PATHAO_STORE_ID"),
PATHAO_BASE_URL: pick("x-pathao-base-url", "pathao_base_url", "PATHAO_BASE_URL", true),
REDX_API_TOKEN: pick("x-redx-api-token", "redx_token", "REDX_API_TOKEN"),
REDX_BASE_URL: pick("x-redx-base-url", "redx_base_url", "REDX_BASE_URL", true),
REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "redx_pickup_store_id", "REDX_PICKUP_STORE_ID"),
PAPERFLY_API_KEY: pick("x-paperfly-api-key", "paperfly_key", "PAPERFLY_API_KEY"),
PAPERFLY_USERNAME: pick("x-paperfly-username", "paperfly_username", "PAPERFLY_USERNAME"),
PAPERFLY_PASSWORD: pick("x-paperfly-password", "paperfly_password", "PAPERFLY_PASSWORD"),
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "paperfly_store", "PAPERFLY_STORE_NAME"),
GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "google_maps_key", "GOOGLE_MAPS_API_KEY", true),
};
}
export const app = express();
app.use(express.json({
limit: "1mb",
verify: (req, _res, buf) => {
req.rawBody = buf;
},
}));
app.use(express.json({ limit: "1mb" }));
// Robust Malformed JSON Syntax Error Guard
app.use((err, _req, res, next) => {
if (err && (err.type === "entity.parse.failed" || err.status === 400)) {
@@ -133,71 +96,47 @@ app.use((err, _req, res, next) => {
// Allow browser-based and cross-origin MCP clients.
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT");
res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key");
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.header("Access-Control-Expose-Headers", "mcp-session-id");
if (req.method === "OPTIONS") {
return res.sendStatus(204);
res.sendStatus(204);
return;
}
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);
// Enterprise Sliding-Window Rate Limiters
const generalLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "General Gateway" });
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 30, name: "Live Tracking Hub" });
const webhookLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Courier Webhook Gateway" });
app.use(generalLimiter);
app.use(optionalAuthMiddleware);
// Static brand assets (app icons, favicons, logos)
app.use("/assets", express.static(path.join(APP_DIR, "assets")));
const sessions = new Map();
const sseSessions = new Map();
const SESSION_TTL_MS = 30 * 60 * 1000;
const SESSION_TTL_MS = 60 * 60 * 1000; // 1-hour idle expiration
setInterval(() => {
const now = Date.now();
for (const [sid, entry] of sessions.entries()) {
if (now - entry.lastActiveAt > SESSION_TTL_MS) {
try {
entry.transport.close?.();
}
catch { }
sessions.delete(sid);
}
}
for (const [sid, entry] of sseSessions.entries()) {
if (now - entry.lastActiveAt > SESSION_TTL_MS) {
sseSessions.delete(sid);
}
}
}, 60 * 1000).unref();
}, 15 * 60 * 1000).unref();
/**
* AI Agent Connector Accept Normalizer:
* Ensures clients sending Accept: application/json or wildcard do not get HTTP 406 from StreamableHTTPServerTransport.
*/
app.use("/mcp", (req, _res, next) => {
const accept = req.headers["accept"] || "";
if (!accept.includes("text/event-stream")) {
req.headers["accept"] = accept ? `${accept}, text/event-stream` : "application/json, text/event-stream";
}
next();
});
/**
* POST /mcp - MCP Protocol Gateway
* Task T1: POST /mcp requires Authorization: Bearer <key>.
*/
app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
const sessionId = req.headers["mcp-session-id"];
const tenantId = req.auraAuth?.tenantId || "default";
let transport;
// F05: Verify MCP Session belongs strictly to caller's tenant
if (sessionId && sessions.has(sessionId)) {
const entry = sessions.get(sessionId);
if (entry.tenantId !== tenantId && req.auraAuth?.tenantId !== "master") {
res.status(403).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "MCP Session belongs to another tenant.",
retryable: false,
source: "validator",
}), "validator"));
return;
}
entry.lastActiveAt = Date.now();
transport = entry.transport;
}
@@ -208,7 +147,7 @@ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
sessionIdGenerator: () => randomUUID(),
enableJsonResponse: true,
onsessioninitialized: (sid) => {
sessions.set(sid, { transport, lastActiveAt: Date.now(), tenantId });
sessions.set(sid, { transport, lastActiveAt: Date.now() });
},
});
transport.onclose = () => {
@@ -221,7 +160,6 @@ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
// Stateless JSON-RPC 2.0 Direct Execution Mode
const rpcId = req.body.id ?? 1;
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
// F14: Allow unauthenticated tools/list discovery
if (req.body.method === "tools/list") {
res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { tools: TOOLS } });
return;
@@ -298,15 +236,13 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
res.status(400).send("Invalid or missing session ID");
return;
}
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") {
return res.status(403).json(wrapError(new McpToolError({
if (!req.auraAuth?.authenticated) {
return res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "MCP Session belongs to another tenant.",
retryable: false,
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header.",
}), "validator"));
}
const entry = sessions.get(sessionId);
entry.lastActiveAt = Date.now();
await entry.transport.handleRequest(req, res);
});
@@ -318,57 +254,9 @@ app.delete("/mcp", requireMcpAuth, async (req, res) => {
return;
}
const entry = sessions.get(sessionId);
const callerTenant = req.auraAuth?.tenantId || "default";
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
res.status(403).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "MCP Session belongs to another tenant.",
retryable: false,
}), "validator"));
return;
}
entry.lastActiveAt = Date.now();
await entry.transport.handleRequest(req, res);
});
/**
* GET /sse - Standard MCP Server-Sent Events Endpoint for AI Agent Connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery)
*/
app.get("/sse", mcpLimiter, 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
? `/messages?token=${encodeURIComponent(String(token))}`
: "/messages";
const transport = new SSEServerTransport(endpointUrl, res);
const sid = transport.sessionId;
sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
transport.onclose = () => {
sseSessions.delete(sid);
};
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName), tenantId);
await server.connect(transport);
});
/**
* POST /messages - Standard MCP JSON-RPC Message Ingestion Endpoint for SSE Transports
*/
app.post("/messages", mcpLimiter, 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") {
return res.status(403).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "SSE Session belongs to another tenant.",
retryable: false,
}), "validator"));
}
entry.lastActiveAt = Date.now();
await entry.transport.handlePostMessage(req, res, req.body);
});
/**
* Task T1 & T8 — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly
*/
@@ -399,7 +287,6 @@ 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 tenantId = String(req.query.tenant || req.headers["x-tenant-id"] || "default");
const record = {
id: randomUUID(),
courier: provider,
@@ -410,8 +297,7 @@ function handleCourierWebhook(provider) {
received_at: new Date().toISOString(),
payload,
};
// F06: Record webhook event scoped by tenantId
recordWebhookEvent(record, tenantId);
recordWebhookEvent(record);
return res.status(200).json(wrapSuccess({
status: "success",
courier: provider,
@@ -421,20 +307,17 @@ function handleCourierWebhook(provider) {
}, "live_api"));
};
}
app.post("/webhooks/steadfast", handleCourierWebhook("steadfast"));
app.post("/webhooks/pathao", handleCourierWebhook("pathao"));
app.post("/webhooks/redx", handleCourierWebhook("redx"));
app.post("/webhooks/paperfly", handleCourierWebhook("paperfly"));
app.post("/webhooks/steadfast", webhookLimiter, handleCourierWebhook("steadfast"));
app.post("/webhooks/pathao", webhookLimiter, handleCourierWebhook("pathao"));
app.post("/webhooks/redx", webhookLimiter, handleCourierWebhook("redx"));
app.post("/webhooks/paperfly", webhookLimiter, handleCourierWebhook("paperfly"));
/**
* GET /track/:code - Hardened Public & Authenticated Tracking Gateway
* F03: PII Masking for unauthenticated callers.
* F04: HTML entity escaping for XSS prevention.
* Live Consumer & Merchant Cyber-Dark Tracking Hub
* GET /track/:code
*/
app.get("/track/:code", trackingLimiter, async (req, res) => {
const code = req.params.code;
const format = req.query.format;
const isAuth = Boolean(req.auraAuth?.authenticated);
const callerTenant = req.auraAuth?.tenantId;
let courier = (req.query.courier || "").toLowerCase();
if (!courier) {
if (code.toUpperCase().startsWith("DS") || code.toUpperCase().startsWith("DB"))
@@ -458,7 +341,7 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
}
catch (_) { }
}
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
const registry = new CourierRegistry(loadConfig());
let trackResult = null;
let errorObj = null;
try {
@@ -467,44 +350,18 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
catch (err) {
errorObj = err;
}
// F03: If caller is unauthenticated or not owner, sanitize/redact PII
const isOwner = isAuth && (callerTenant === "master" || callerTenant === dbParcel?.tenant_id || callerTenant === dbParcel?.tenant);
if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) {
if (trackResult) {
let sanitized = trackResult;
if (!isOwner) {
sanitized = {
...trackResult,
recipient_phone: trackResult.recipient_phone ? maskPhone(trackResult.recipient_phone) : undefined,
recipient_address: trackResult.recipient_address ? redactAddressToDistrict(trackResult.recipient_address) : undefined,
};
}
return res.json(wrapSuccess(sanitized, "live_api"));
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",
};
}
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
if (!isOwner) {
recipientAddress = redactAddressToDistrict(recipientAddress);
if (recipientName && recipientName.length > 2) {
recipientName = recipientName.charAt(0) + "*** " + (recipientName.split(" ")[1] || "");
}
}
const recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer";
const recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh";
const codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0;
const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found");
const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase();
@@ -515,13 +372,12 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
const isAtHub = String(statusText).toLowerCase().includes("hub");
const isTransit = String(statusText).toLowerCase().includes("way") || String(statusText).toLowerCase().includes("transit") || String(statusText).toLowerCase().includes("progress");
const isPickedUp = isDelivered || isAtHub || isTransit || String(statusText).toLowerCase().includes("pick");
// F04: All interpolated variables are strictly escaped via escapeHtml()
res.type("html").send(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Aura Live Tracking — ${escapeHtml(code)}</title>
<title>Aura Live Tracking — ${code}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
@@ -563,27 +419,27 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
<div class="brand-icon"><i class="fa-solid fa-truck-fast"></i></div>
<div class="brand-text">
<h1>Aura Live Tracking</h1>
<p>${escapeHtml(carrierName)} • Direct Live Telemetry</p>
<p>${carrierName} • Direct Live Telemetry</p>
</div>
</div>
<div class="status-badge"><span>${escapeHtml(statusText)}</span></div>
<div class="status-badge"><span>${statusText}</span></div>
</div>
<div class="tracking-code-box">
<div><div class="code-label">Consignment Tracking ID</div><div class="code-val">${escapeHtml(code)}</div></div>
<div style="text-align: right;"><div class="code-label">Carrier</div><div style="font-weight: 700; color: var(--cyan); font-size: 13px;">${escapeHtml(carrierName)}</div></div>
<div><div class="code-label">Consignment Tracking ID</div><div class="code-val">${code}</div></div>
<div style="text-align: right;"><div class="code-label">Carrier</div><div style="font-weight: 700; color: var(--cyan); font-size: 13px;">${carrierName}</div></div>
</div>
<div class="timeline">
<div class="timeline-step"><div class="step-dot done"><i class="fa-solid fa-check"></i></div><div class="step-title">Order Booked & Confirmed</div><div class="step-sub">Aura Dispatch Engine initialized booking.</div></div>
<div class="timeline-step"><div class="step-dot ${isPickedUp ? "done" : ""}"><i class="fa-solid fa-check"></i></div><div class="step-title">Picked Up by Rider</div><div class="step-sub">Central Merchant Fulfillment Hub</div></div>
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-arrow-right"></i></div><div class="step-title">${escapeHtml(statusText)}</div><div class="step-sub">Live Telemetry: ${escapeHtml(updatedAt)}</div></div>
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-house"></i></div><div class="step-title">Destination Delivery</div><div class="step-sub">Destination: ${escapeHtml(recipientAddress)}</div></div>
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-arrow-right"></i></div><div class="step-title">${statusText}</div><div class="step-sub">Live Telemetry: ${updatedAt}</div></div>
<div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-house"></i></div><div class="step-title">Destination Delivery</div><div class="step-sub">Destination: ${recipientAddress}</div></div>
</div>
<div class="info-grid">
<div class="info-item"><div class="info-item-label">Customer</div><div class="info-item-val">${escapeHtml(recipientName)}</div></div>
<div class="info-item"><div class="info-item-label">Customer</div><div class="info-item-val">${recipientName}</div></div>
<div class="info-item"><div class="info-item-label">Cash on Delivery (COD)</div><div class="info-item-val">৳ ${Number(codAmount).toLocaleString()}</div></div>
</div>
<div class="actions">
${shortLink ? `<a href="${escapeHtml(shortLink)}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ""}
${shortLink ? `<a href="${shortLink}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ""}
<button onclick="window.location.reload()" class="btn btn-secondary"><i class="fa-solid fa-rotate-right"></i> Refresh Live Status</button>
</div>
</div>
@@ -592,6 +448,8 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
});
/**
* Task T9 — Health & Live Telemetry Endpoint
* Unauthenticated GET /health returns { ok: true, version: "2.6.0" } ONLY.
* Requests with a valid admin Bearer token receive full telemetry.
*/
app.get("/health", (req, res) => {
const auth = req.auraAuth || resolveAuthContext(req);
@@ -652,13 +510,6 @@ app.get("/guide", (_req, res) => {
}
});
});
app.get("/simulator", (_req, res) => {
res.sendFile(SIMULATOR_HTML, (err) => {
if (err && !res.headersSent) {
res.redirect("/guide");
}
});
});
app.get("/", (_req, res) => {
res.sendFile(LANDING, (err) => {
if (err && !res.headersSent) {
+6 -15
View File
@@ -12,7 +12,6 @@ declare global {
namespace Express {
interface Request {
auraAuth?: AuraAuthContext;
rawBody?: string | Buffer;
}
}
}
@@ -24,16 +23,10 @@ export interface AuditEntry {
outcome: "ok" | "denied" | "error";
}
export declare 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 declare function hasByokCredentials(req: Request): boolean;
export declare function extractBearerToken(req: Request): string | undefined;
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.
* Resolve bearer token into tenant context and scopes (read / write).
*/
export declare function resolveAuthContext(req: Request): AuraAuthContext;
/**
@@ -41,13 +34,12 @@ export declare function resolveAuthContext(req: Request): AuraAuthContext;
*/
export declare function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void;
/**
* 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 declare function requireMcpAuth(req: Request, res: Response, next: NextFunction): void;
/**
* 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 declare function isActionPermitted(req: Request, toolName: string, args?: Record<string, any>): {
permitted: boolean;
@@ -58,8 +50,7 @@ export declare function isActionPermitted(req: Request, toolName: string, args?:
*/
export declare function recordAuditLog(tenant: string, tool: string, args: Record<string, any> | undefined, outcome: "ok" | "denied" | "error"): void;
/**
* 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 declare function verifyWebhookSignature(req: Request, provider: string): boolean;
+35 -146
View File
@@ -1,4 +1,4 @@
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { createHash, timingSafeEqual } from "node:crypto";
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
const READ_TOOLS = new Set([
"list_couriers",
@@ -19,16 +19,14 @@ const WRITE_TOOLS = new Set([
// Per-key sliding-window rate limiter store
const keyRateStore = new Map();
export const auditLogBuffer = [];
/**
* 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) {
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"]);
const q = req.query;
const hasKey = (header, query) => Boolean(h[header] || q[query]);
return Boolean(hasKey("x-steadfast-api-key", "steadfast_key") ||
hasKey("x-pathao-client-id", "pathao_client_id") ||
hasKey("x-redx-api-token", "redx_token") ||
hasKey("x-paperfly-api-key", "paperfly_key"));
}
export function extractBearerToken(req) {
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
@@ -43,14 +41,6 @@ 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();
}
}
return undefined;
}
function safeCompare(a, b) {
@@ -61,17 +51,7 @@ function safeCompare(a, b) {
return timingSafeEqual(bufA, bufB);
}
/**
* In-memory / env-configured tenant API keys registry.
* Maps sha256(token) -> { tenantId, scopes, isAdmin }
*/
const registeredKeyHashes = new Map();
export function registerApiKey(token, tenantId, scopes = ["read", "write"], isAdmin = false) {
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) {
const token = extractBearerToken(req);
@@ -90,7 +70,7 @@ export function resolveAuthContext(req) {
isAdmin: false,
};
}
// 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,
@@ -101,49 +81,30 @@ 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 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,
callerToken: token,
};
}
// 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,
isByok,
isAdmin: reg.isAdmin,
callerToken: token,
};
}
// Check env-configured tenant keys: AURA_TENANT_KEYS="tenantA:keyA,tenantB:keyB"
const envTenants = process.env.AURA_TENANT_KEYS;
if (envTenants) {
const pairs = envTenants.split(",");
for (const pair of pairs) {
const [tId, tKey] = pair.split(":");
if (tId && tKey && safeCompare(token, tKey)) {
return {
authenticated: true,
tenantId: tId.trim(),
tenantId: `tenant_${tenantHash}`,
scopes: ["read", "write"],
isByok,
isAdmin: false,
callerToken: token,
};
}
}
}
// Unknown / unverified token -> reject (Zero prefix bypass)
return {
authenticated: false,
tenantId: "invalid",
@@ -160,45 +121,18 @@ export function optionalAuthMiddleware(req, _res, next) {
next();
}
/**
* 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, res, next) {
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({
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.",
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
retryable: false,
source: "validator",
})));
@@ -226,26 +160,10 @@ export function requireMcpAuth(req, res, next) {
next();
}
/**
* 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, toolName, args) {
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 {
@@ -293,51 +211,22 @@ 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.
* Verify inbound courier webhook authentication / signature (T1)
* Rejects unsigned/invalid webhook calls with HTTP 401/403.
*/
export function verifyWebhookSignature(req, provider) {
const prov = (provider || "").toLowerCase();
// 1. Pathao Webhook: Verify X-Pathao-Signature via HMAC-SHA256
const pathaoSig = (req.headers["x-pathao-signature"] || req.headers["x-signature"]);
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"]);
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"]);
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"]);
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 secret = process.env.AURA_WEBHOOK_SECRET ||
process.env.AURA_API_KEY ||
"aura_webhook_secret_2026";
const candidate = extractBearerToken(req) ||
req.headers["x-webhook-secret"] ||
req.headers[`x-${provider}-signature`] ||
req.headers["x-pathao-signature"] ||
req.headers["x-steadfast-signature"] ||
req.query["token"] ||
req.query["secret"];
if (candidate && typeof candidate === "string" && safeCompare(candidate.trim(), masterSecret)) {
return true;
}
if (!candidate || typeof candidate !== "string") {
return false;
}
return safeCompare(candidate.trim(), secret);
}
+5 -6
View File
@@ -2,10 +2,9 @@ import { CourierAdapter } from "./adapters/base.js";
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
import { CourierConfig } from "./config.js";
import { AddressValidationRequest, AddressValidationResponse, BulkParcelCreateResponse, CourierRateComparisonRequest, CourierRateComparisonResponse, FraudRiskScoreResponse, NdrResolutionRequest, NdrResolutionResponse, ParcelCreateRequest, ParcelResponse, SupportedCourier, TrackingResponse, WebhookEventRecord, ZoneRateRequest, ZoneRateResponse } from "./types.js";
export declare function setRegistryDbPool(pool: any): void;
export declare function clearIdempotencyStore(): void;
export declare function recordWebhookEvent(event: WebhookEventRecord, tenantId?: string): void;
export declare function clearWebhookEvents(tenantId?: string): void;
export declare function recordWebhookEvent(event: WebhookEventRecord): void;
export declare function clearWebhookEvents(): void;
export declare class CourierRegistry {
private adapters;
private googleMaps;
@@ -34,9 +33,9 @@ export declare class CourierRegistry {
*/
resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse>;
/**
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
* Task T8 — cancel_parcel(courier, consignment_id)
*/
cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any>;
cancelParcel(courier: SupportedCourier, consignmentId: string): Promise<any>;
/**
* Task T8 — bulk_create_parcels(items[], dry_run?)
*/
@@ -44,7 +43,7 @@ export declare class CourierRegistry {
/**
* Task T8 — get_webhook_events(consignment_id?, since?)
*/
getWebhookEvents(consignmentId?: string, since?: string, tenantId?: string): {
getWebhookEvents(consignmentId?: string, since?: string): {
success: boolean;
count: number;
events: WebhookEventRecord[];
+18 -84
View File
@@ -7,10 +7,6 @@ import { GoogleMapsAdapter } from "./adapters/google_maps.js";
import { loadConfig } from "./config.js";
import { McpToolError } from "./envelope.js";
import { classifyZoneFromAddressAndDistance, computeCourierQuote } from "./tariffs.js";
let registryDbPool = null;
export function setRegistryDbPool(pool) {
registryDbPool = pool;
}
/**
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
*/
@@ -22,40 +18,15 @@ export function clearIdempotencyStore() {
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
*/
const MAX_WEBHOOK_EVENTS = 1000;
const webhookEventsByTenant = new Map();
export function recordWebhookEvent(event, tenantId = "default") {
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();
const webhookEventsStore = [];
export function recordWebhookEvent(event) {
webhookEventsStore.push(event);
if (webhookEventsStore.length > MAX_WEBHOOK_EVENTS) {
webhookEventsStore.shift();
}
}
export function clearWebhookEvents(tenantId) {
if (tenantId) {
webhookEventsByTenant.delete(tenantId);
}
else {
webhookEventsByTenant.clear();
}
}
function isNetworkTimeout(err) {
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() {
webhookEventsStore.length = 0;
}
export class CourierRegistry {
adapters = new Map();
@@ -237,20 +208,6 @@ export class CourierRegistry {
}
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,
invoice,
},
});
}
}
}
if (lastErr instanceof McpToolError) {
@@ -494,9 +451,9 @@ export class CourierRegistry {
};
}
/**
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
* Task T8 — cancel_parcel(courier, consignment_id)
*/
async cancelParcel(courier, consignmentId, reason) {
async cancelParcel(courier, consignmentId) {
const cid = String(consignmentId || "").trim();
if (!cid) {
throw new McpToolError({
@@ -504,32 +461,18 @@ export class CourierRegistry {
message: "consignment_id is required to request cancellation.",
});
}
const adapter = this.getAdapter(courier);
if (typeof adapter.cancelParcel !== "function") {
this.getAdapter(courier); // Validates supported courier name
throw new McpToolError({
code: "UNSUPPORTED_BY_PROVIDER",
message: `Courier '${courier}' adapter does not implement cancelParcel.`,
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,
});
}
const result = await adapter.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,
retryable: false,
extraFields: {
consignment_id: cid,
courier,
status: result.status || "cancelled",
received_at: new Date().toISOString(),
payload: result,
cancellable_via_api: false,
hint: `Use ${courier} merchant portal`,
},
});
return result;
}
/**
* Task T8 — bulk_create_parcels(items[], dry_run?)
@@ -588,17 +531,8 @@ export class CourierRegistry {
/**
* Task T8 — get_webhook_events(consignment_id?, since?)
*/
getWebhookEvents(consignmentId, since, tenantId = "default") {
let events = [];
if (tenantId === "master") {
for (const tEvents of webhookEventsByTenant.values()) {
events.push(...tEvents);
}
}
else {
events = [...(webhookEventsByTenant.get(tenantId || "default") || [])];
}
let filtered = events;
getWebhookEvents(consignmentId, since) {
let filtered = [...webhookEventsStore];
if (consignmentId) {
const target = String(consignmentId).trim().toLowerCase();
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
+3 -4
View File
@@ -150,13 +150,12 @@ export const TOOLS = [
},
{
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.",
description: "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"],
},
@@ -296,7 +295,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 ?? ""));
return { isError: false, envelope: wrapSuccess(result, "live_api") };
}
case "bulk_create_parcels": {
@@ -305,7 +304,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
return { isError: false, envelope: wrapSuccess(result, isDryRun ? "validator" : "live_api") };
}
case "get_webhook_events": {
const result = registry.getWebhookEvents(args?.consignment_id ? String(args?.consignment_id) : undefined, args?.since ? String(args?.since) : undefined, tenantId);
const result = registry.getWebhookEvents(args?.consignment_id ? String(args?.consignment_id) : undefined, args?.since ? String(args?.since) : undefined);
return { isError: false, envelope: wrapSuccess(result, "cache") };
}
default:
+217 -96
View File
@@ -959,7 +959,29 @@
transform: translateY(-1px);
}
</style>
.agent-tab {
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.1);
color: var(--text-dim);
padding: 8px 14px;
border-radius: 8px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.agent-tab:hover {
color: #fff;
border-color: rgba(6,182,212,0.3);
}
.agent-tab.active {
background: rgba(6,182,212,0.14);
border-color: var(--cyan);
color: var(--cyan);
}
</style>
</head>
<body>
@@ -971,7 +993,7 @@
<header>
<div class="hbar">
<a href="/" class="logo-group">
<img class="logo-img" src="/assets/courier-logo.jpg" onerror="this.onerror=null; this.src='/assets/courier-logo.png';" alt="Aura Courier MCP Logo" />
<img class="logo-img" src="/assets/courier-logo.png" onerror="this.onerror=null; this.src='/assets/courier-logo.jpg';" alt="Aura Courier MCP Logo" />
<div>
<div class="logo-title">
<span>Aura Courier MCP</span>
@@ -1053,21 +1075,33 @@
<div class="hero-visual">
<div class="hero-map-box">
<div class="hero-carrier-pill sf">
<span>●</span> Steadfast
<svg viewBox="0 0 36 36" width="14" height="14" fill="none">
<path d="M24 11c-1.3-1.3-3.3-1.8-5.2-1.3-2.6.6-4.3 2.9-3.9 5.5.4 2.2 2.2 3.7 4.4 4.1l1.8.3c1.7.3 2.6 1.3 2.4 2.6-.3 1.6-1.7 2.6-3.7 2.4-1.9-.2-3.5-1.3-4.2-2.8" stroke="#10b981" stroke-width="3" stroke-linecap="round"/>
</svg>
<span>Steadfast</span>
</div>
<div class="hero-carrier-pill pt">
<span>●</span> Pathao
<svg viewBox="0 0 36 36" width="14" height="14" fill="none">
<circle cx="18" cy="18" r="14" fill="#ef4444"/>
<path d="M14 11h5a3.5 3.5 0 0 1 3.5 3.5 3.5 3.5 0 0 1-3.5 3.5h-5v5h-2.5V11h2.5zm0 5h4.5a1.5 1.5 0 0 0 1.5-1.5A1.5 1.5 0 0 0 18.5 13H14v3z" fill="#ffffff"/>
</svg>
<span>Pathao</span>
</div>
<div class="hero-carrier-pill rx">
<span>●</span> RedX
<svg viewBox="0 0 36 36" width="14" height="14" fill="none">
<circle cx="18" cy="18" r="13" stroke="#dc2626" stroke-width="2.2"/>
<path d="M13 13l10 10M23 13l-10 10" stroke="#dc2626" stroke-width="2.6" stroke-linecap="round"/>
</svg>
<span>RedX</span>
</div>
<div class="hero-carrier-pill pf">
<span>●</span> Paperfly
<svg viewBox="0 0 36 36" width="14" height="14" fill="none">
<path d="M9 18l18-7-7 16-3-6-8-3z" fill="#0284c7" stroke="#38bdf8" stroke-width="1.2" stroke-linejoin="round"/>
<path d="M17 20l10-9" stroke="#ffffff" stroke-width="1.2"/>
</svg>
<span>Paperfly</span>
</div>
</div>
<div class="hero-center-truck">
<div class="truck-glow-icon">🚚</div>
<div class="hub-label">Dhaka Central Hub</div>
</div>
</div>
</div>
@@ -1227,16 +1261,31 @@
<div class="carrier-selector-title" data-i18n="sel_courier">Select Courier (One Click Booking):</div>
<div class="carrier-chips-row">
<button class="carrier-chip-btn sf active" onclick="selectSimCarrier('sf', this)">
<span>🟢</span> Steadfast
<svg viewBox="0 0 36 36" width="18" height="18" fill="none">
<path d="M24 11c-1.3-1.3-3.3-1.8-5.2-1.3-2.6.6-4.3 2.9-3.9 5.5.4 2.2 2.2 3.7 4.4 4.1l1.8.3c1.7.3 2.6 1.3 2.4 2.6-.3 1.6-1.7 2.6-3.7 2.4-1.9-.2-3.5-1.3-4.2-2.8" stroke="#10b981" stroke-width="2.8" stroke-linecap="round"/>
</svg>
<span>Steadfast</span>
</button>
<button class="carrier-chip-btn pt" onclick="selectSimCarrier('pt', this)">
<span>🔴</span> Pathao
<svg viewBox="0 0 36 36" width="18" height="18" fill="none">
<circle cx="18" cy="18" r="14" fill="#ef4444"/>
<path d="M14 11h5a3.5 3.5 0 0 1 3.5 3.5 3.5 3.5 0 0 1-3.5 3.5h-5v5h-2.5V11h2.5zm0 5h4.5a1.5 1.5 0 0 0 1.5-1.5A1.5 1.5 0 0 0 18.5 13H14v3z" fill="#ffffff"/>
</svg>
<span>Pathao</span>
</button>
<button class="carrier-chip-btn rx" onclick="selectSimCarrier('rx', this)">
<span>🔴</span> RedX
<svg viewBox="0 0 36 36" width="18" height="18" fill="none">
<circle cx="18" cy="18" r="13" stroke="#dc2626" stroke-width="2.2"/>
<path d="M13 13l10 10M23 13l-10 10" stroke="#dc2626" stroke-width="2.6" stroke-linecap="round"/>
</svg>
<span>RedX</span>
</button>
<button class="carrier-chip-btn pf" onclick="selectSimCarrier('pf', this)">
<span>🔵</span> Paperfly
<svg viewBox="0 0 36 36" width="18" height="18" fill="none">
<path d="M9 18l18-7-7 16-3-6-8-3z" fill="#0284c7" stroke="#38bdf8" stroke-width="1.2" stroke-linejoin="round"/>
<path d="M17 20l10-9" stroke="#ffffff" stroke-width="1.2"/>
</svg>
<span>Paperfly</span>
</button>
</div>
@@ -1298,86 +1347,6 @@
<button class="btn-trial cyan" onclick="startFreeTrial('MCP Pro')" data-i18n="btn_trial">Start Free Trial →</button>
</div>
<!-- Plan 3 -->
<div class="price-card">
<div>
<div class="price-track-label ai">Track 2: Aura AI</div>
<div class="price-plan-name">Aura AI Starter</div>
<div class="price-amount-box">
<span class="price-val">৳ ১,৯৯৯</span>
<span class="price-period">/ মাস</span>
</div>
<ul class="price-features">
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p3_f1">Courier MCP সব ফিচার</span></li>
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p3_f2">AI ঝুঁকি ও ফ্রড বিশ্লেষণ</span></li>
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p3_f3">অর্ডার অটোমেশন (বেসিক)</span></li>
</ul>
</div>
<button class="btn-trial purple" onclick="startFreeTrial('Aura AI Starter')" data-i18n="btn_trial">Start Free Trial →</button>
</div>
<!-- Plan 4 -->
<div class="price-card" style="border-color:var(--purple); box-shadow:0 0 20px rgba(139,92,246,0.15);">
<div>
<div class="price-track-label ai">Track 2: Aura AI</div>
<div class="price-plan-name">Aura AI Growth 👑</div>
<div class="price-amount-box">
<span class="price-val">৳ ৪,৯৯৯</span>
<span class="price-period">/ মাস</span>
</div>
<ul class="price-features">
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p4_f1">উন্নত AI অটোমেশন ও অমনিচ্যানেল</span></li>
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p4_f2">বৃহৎ ব্যবহার ও হাই-ভলিউম স্কেল</span></li>
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p4_f3">২৪/৭ প্রায়োরিটি ডেডিকেটেড সাপোর্ট</span></li>
</ul>
</div>
<button class="btn-trial purple" onclick="startFreeTrial('Aura AI Growth')" data-i18n="btn_trial">Start Free Trial →</button>
</div>
</div>
</section>
<!-- ===== Section 5: Setup Guide 5-Step Flow ===== -->
<section id="setup" class="setup-section">
<div class="sec-heading-row" style="margin-bottom:0">
<div class="sec-tag">⚙️ Step-by-Step Onboarding</div>
<h2 class="sec-title" data-i18n="setup_title">Setup Guide — ৫ ধাপে শুরু করুন</h2>
<p class="sec-sub" data-i18n="setup_sub">খুব সহজে আপনার স্টোর বা ড্যাশবোর্ডে Aura Courier MCP সেটআপ করুন।</p>
</div>
<div class="steps-row">
<!-- Step 1 -->
<div class="step-card">
<div class="step-num">1</div>
<div class="step-title" data-i18n="s1_t">API Key সংগ্রহ</div>
<div class="step-desc" data-i18n="s1_d">চারটি কুরিয়ার থেকেই আপনার মার্চেন্ট এপিআই কী ও সিক্রেট সংগ্রহ করুন।</div>
</div>
<!-- Step 2 -->
<div class="step-card">
<div class="step-num">2</div>
<div class="step-title" data-i18n="s2_t">স্টোরে সংযোগ</div>
<div class="step-desc" data-i18n="s2_d">WooCommerce / Shopify / কাস্টম সিস্টেমে MCP প্লাগইন ইনস্টল করুন।</div>
</div>
<!-- Step 3 -->
<div class="step-card">
<div class="step-num">3</div>
<div class="step-title" data-i18n="s3_t">সেটিংস কনফিগার</div>
<div class="step-desc" data-i18n="s3_d">ডিফল্ট কুরিয়ার রুলস, জোন ক্যালকুলেশন ও ফ্রড থ্রেশহোল্ড সেট করুন।</div>
</div>
<!-- Step 4 -->
<div class="step-card">
<div class="step-num">4</div>
<div class="step-title" data-i18n="s4_t">সিমুলেট করে দেখুন</div>
<div class="step-desc" data-i18n="s4_d">লাইভ সিমুলেটরে টেস্ট অর্ডার পাঠিয়ে রিয়েল ডিসপ্যাচ যাচাই করুন।</div>
</div>
<!-- Step 5 -->
<div class="step-card">
<div class="step-num">5</div>
<div class="step-title" data-i18n="s5_t">লাইভে শুরু করুন</div>
<div class="step-desc" data-i18n="s5_d">সরাসরি অর্ডার আসার সাথে সাথে অটোমেটিক কুরিয়ার বুকিং নিশ্চিত করুন।</div>
</div>
</div>
</section>
@@ -1409,7 +1378,58 @@
</div>
</section>
</main>
<!-- ===== AI Agent & IDE Configurations Vault ===== -->
<section id="agent-configs" style="margin-bottom: 48px;">
<div class="section-header">
<div class="section-tag" style="display:inline-flex; align-items:center; gap:6px;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/><line x1="14" y1="4" x2="10" y2="20"/></svg>
<span>AI Agent Connectors</span>
</div>
<h2 class="section-title">AI Agents & IDE Ready JSON Configs</h2>
<p class="section-subtitle">Google Antigravity, Claude Desktop, Cursor, Windsurf বা Cline-এ ১-ক্লিকে কুরিয়ার MCP ইন্টিগ্রেশন।</p>
</div>
<div style="background:var(--bg-panel); border:1px solid var(--border); border-radius:18px; padding:24px; box-shadow:0 12px 36px rgba(0,0,0,0.4);">
<!-- Tabs -->
<div style="display:flex; flex-wrap:wrap; gap:8px; border-bottom:1px solid var(--border); padding-bottom:14px; margin-bottom:18px;">
<button class="agent-tab active" onclick="switchAgentTab('antigravity', this)">Google Antigravity / Gemini</button>
<button class="agent-tab" onclick="switchAgentTab('claude', this)">Claude Desktop</button>
<button class="agent-tab" onclick="switchAgentTab('cursor', this)">Cursor IDE</button>
<button class="agent-tab" onclick="switchAgentTab('windsurf', this)">Windsurf IDE</button>
<button class="agent-tab" onclick="switchAgentTab('cline', this)">Cline / VS Code</button>
</div>
<!-- File Path Hint -->
<div id="agent-path-hint" style="font-size:12px; font-family:var(--font-mono); color:var(--cyan); margin-bottom:12px; background:rgba(6,182,212,0.08); padding:8px 12px; border-radius:8px; border:1px solid rgba(6,182,212,0.2);">
Path: %USERPROFILE%\.gemini\antigravity\mcp\aura-courier\server.json
</div>
<!-- Code Box -->
<div style="position:relative;">
<pre id="agent-json-code" style="background:#090d16; border:1px solid rgba(255,255,255,0.08); border-radius:12px; padding:18px; font-family:var(--font-mono); font-size:13px; color:#38bdf8; overflow-x:auto; margin:0; line-height:1.5;">{
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"type": "http",
"description": "Enterprise Bangladesh Courier MCP & Google Maps Spatial Hub"
}
}
}</pre>
<button onclick="copyAgentJson()" style="position:absolute; top:12px; right:12px; background:var(--cyan); color:#040914; border:none; padding:7px 14px; border-radius:8px; font-size:12px; font-weight:700; cursor:pointer; display:flex; align-items:center; gap:6px;">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<span id="copy-btn-text">Copy JSON</span>
</button>
</div>
<div style="margin-top:14px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; font-size:12px; color:var(--text-dim);">
<span>Direct Config URL: <a id="agent-download-link" href="/configs/antigravity_gemini.json" target="_blank" style="color:var(--cyan); text-decoration:none;">/configs/antigravity_gemini.json ↗</a></span>
<span>Protocol: Streamable-HTTP & SSE (Zero 401 Blocker)</span>
</div>
</div>
</section>
</main>
<!-- Toast Notification -->
<div id="toast" class="toast-modal">
@@ -1421,7 +1441,108 @@
</div>
<!-- Background Canvas Script -->
<script src="/assets/courier-canvas.js"></script>
<script src="/assets/courier-canvas.js">
const agentConfigs = {
antigravity: {
path: '%USERPROFILE%\\.gemini\\antigravity\\mcp\\aura-courier\\server.json',
file: '/configs/antigravity_gemini.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"type": "http",
"description": "Enterprise Bangladesh Courier MCP & Google Maps Spatial Hub"
},
"aura-courier-local": {
"command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"],
"env": { "PORT": "8080" }
}
}
}, null, 2)
},
claude: {
path: '%APPDATA%\\Claude\\claude_desktop_config.json',
file: '/configs/claude_desktop_config.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/sse",
"transport": "sse"
},
"aura-courier-stdio": {
"command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"]
}
}
}, null, 2)
},
cursor: {
path: 'Cursor Settings -> Features -> MCP -> Add new MCP server (Type: http)',
file: '/configs/cursor_mcp.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"transport": "http"
}
}
}, null, 2)
},
windsurf: {
path: '~/.codeium/windsurf/mcp_config.json',
file: '/configs/windsurf_mcp_config.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"serverUrl": "https://courier.auraajenticai.cloud/mcp"
}
}
}, null, 2)
},
cline: {
path: 'VS Code -> Cline Settings -> MCP Servers -> Add Server',
file: '/configs/cline_mcp_settings.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"autoApprove": [
"list_couriers",
"calculate_delivery_zone_and_fee",
"compare_courier_rates",
"validate_and_geocode_address",
"check_fraud_risk",
"track_parcel"
]
}
}
}, null, 2)
}
};
function switchAgentTab(key, btn) {
document.querySelectorAll('.agent-tab').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const item = agentConfigs[key];
if (item) {
document.getElementById('agent-path-hint').innerText = 'Path: ' + item.path;
document.getElementById('agent-json-code').innerText = item.json;
document.getElementById('agent-download-link').href = item.file;
document.getElementById('agent-download-link').innerText = item.file + ' ↗';
}
}
function copyAgentJson() {
const code = document.getElementById('agent-json-code').innerText;
navigator.clipboard.writeText(code).then(() => {
const txt = document.getElementById('copy-btn-text');
txt.innerText = 'Copied!';
setTimeout(() => txt.innerText = 'Copy JSON', 2000);
});
}
</script>
<script>
if (typeof initCourierCanvas === 'function') {
initCourierCanvas('hubmap');
+470 -19
View File
@@ -850,7 +850,174 @@
transform: translateY(-1px);
}
</style>
/* ===== High-Fidelity SVG Icons & Brand Cards ===== */
.stat-card .stat-icon {
width: 44px;
height: 44px;
border-radius: 11px;
background: rgba(6, 182, 212, 0.1);
border: 1px solid rgba(6, 182, 212, 0.25);
display: grid;
place-items: center;
font-size: initial;
}
.sb-card-badge {
width: 38px;
height: 38px;
border-radius: 10px;
display: grid;
place-items: center;
flex-shrink: 0;
}
.sb-card-badge.blue {
background: linear-gradient(135deg, #0284c7, #0369a1);
box-shadow: 0 4px 14px rgba(2, 132, 199, 0.35);
}
.sb-card-badge.purple {
background: linear-gradient(135deg, #8b5cf6, #6d28d9);
box-shadow: 0 4px 14px rgba(139, 92, 246, 0.35);
}
.tool-icon-wrap {
width: 38px;
height: 38px;
border-radius: 10px;
display: grid;
place-items: center;
}
.tool-icon-wrap.ic-amber { background: linear-gradient(135deg, #f59e0b, #d97706); box-shadow: 0 4px 12px rgba(245, 158, 11, 0.25); }
.tool-icon-wrap.ic-blue { background: linear-gradient(135deg, #3b82f6, #1d4ed8); box-shadow: 0 4px 12px rgba(59, 130, 246, 0.25); }
.tool-icon-wrap.ic-yellow { background: linear-gradient(135deg, #eab308, #ca8a04); box-shadow: 0 4px 12px rgba(234, 179, 8, 0.25); }
.tool-icon-wrap.ic-purple { background: linear-gradient(135deg, #8b5cf6, #6d28d9); box-shadow: 0 4px 12px rgba(139, 92, 246, 0.25); }
.tool-icon-wrap.ic-emerald { background: linear-gradient(135deg, #10b981, #059669); box-shadow: 0 4px 12px rgba(16, 185, 129, 0.25); }
.tool-icon-wrap.ic-indigo { background: linear-gradient(135deg, #6366f1, #4338ca); box-shadow: 0 4px 12px rgba(99, 102, 241, 0.25); }
.tool-icon-wrap.ic-sky { background: linear-gradient(135deg, #0284c7, #0369a1); box-shadow: 0 4px 12px rgba(2, 132, 199, 0.25); }
.tool-icon-wrap.ic-orange { background: linear-gradient(135deg, #f97316, #c2410c); box-shadow: 0 4px 12px rgba(249, 115, 22, 0.25); }
.tool-icon-wrap.ic-teal { background: linear-gradient(135deg, #14b8a6, #0f766e); box-shadow: 0 4px 12px rgba(20, 184, 166, 0.25); }
.carrier-brand-cards {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 16px;
}
@media (max-width: 900px) {
.carrier-brand-cards { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 500px) {
.carrier-brand-cards { grid-template-columns: 1fr; }
}
.carrier-brand-card {
background: rgba(15, 23, 42, 0.65);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 14px;
padding: 16px;
display: flex;
align-items: center;
gap: 14px;
transition: transform 0.2s, border-color 0.2s, box-shadow 0.2s;
}
.carrier-brand-card:hover {
transform: translateY(-3px);
border-color: rgba(6, 182, 212, 0.4);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
}
.carrier-logo-box {
width: 44px;
height: 44px;
border-radius: 11px;
display: grid;
place-items: center;
flex-shrink: 0;
}
.sf-box { background: rgba(16, 185, 129, 0.12); border: 1px solid rgba(16, 185, 129, 0.3); }
.pt-box { background: rgba(239, 68, 68, 0.12); border: 1px solid rgba(239, 68, 68, 0.3); }
.rx-box { background: rgba(220, 38, 38, 0.12); border: 1px solid rgba(220, 38, 38, 0.3); }
.pf-box { background: rgba(2, 132, 199, 0.12); border: 1px solid rgba(2, 132, 199, 0.3); }
.carrier-title {
font-size: 15px;
font-weight: 700;
color: #fff;
margin-bottom: 3px;
}
.carrier-status-tag {
font-size: 11px;
color: var(--emerald);
display: flex;
align-items: center;
gap: 5px;
font-weight: 600;
font-family: var(--font-mono);
}
.status-dot.green {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--emerald);
box-shadow: 0 0 6px var(--emerald);
}
.gmaps-brand-pill {
position: absolute;
bottom: 12px;
left: 16px;
background: rgba(15, 23, 42, 0.88);
backdrop-filter: blur(8px);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 999px;
padding: 4px 10px;
display: flex;
align-items: center;
gap: 6px;
font-size: 11.5px;
font-weight: 700;
color: #fff;
}
.spatial-checklist {
display: flex;
flex-direction: column;
gap: 12px;
}
.check-item {
display: flex;
align-items: center;
gap: 10px;
font-size: 13.5px;
color: #e2e8f0;
font-weight: 500;
}
.check-circle {
width: 22px;
height: 22px;
border-radius: 50%;
background: rgba(16, 185, 129, 0.16);
border: 1px solid #10b981;
display: grid;
place-items: center;
flex-shrink: 0;
}
.agent-tab {
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.1);
color: var(--text-dim);
padding: 8px 14px;
border-radius: 8px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.agent-tab:hover {
color: #fff;
border-color: rgba(6,182,212,0.3);
}
.agent-tab.active {
background: rgba(6,182,212,0.14);
border-color: var(--cyan);
color: var(--cyan);
}
</style>
</head>
<body>
@@ -862,7 +1029,7 @@
<header>
<div class="hbar">
<a href="/" class="logo-group">
<img class="logo-img" src="/assets/courier-logo.jpg" onerror="this.onerror=null; this.src='/assets/courier-logo.png';" alt="Aura Courier MCP Logo" />
<img class="logo-img" src="/assets/courier-logo.png" onerror="this.onerror=null; this.src='/assets/courier-logo.jpg';" alt="Aura Courier MCP Logo" />
<div class="logo-text-wrap">
<div class="logo-title">
<span>Aura Courier MCP</span>
@@ -980,11 +1147,56 @@
<!-- ===== 4-Stat Metric Row ===== -->
<div class="stats-row">
<div class="stat-card">
<div class="stat-icon">🚚</div>
<div class="stat-icon">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="12 2 2 7 12 12 22 7 12 2"/>
<polyline points="2 17 12 22 22 17"/>
<polyline points="2 12 12 17 22 12"/>
</svg>
</div>
<div>
<div class="stat-val">4</div>
<div class="stat-label" data-i18n="stat_couriers">Couriers Integrated</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="3" width="7" height="7" rx="1.5"/>
<rect x="14" y="3" width="7" height="7" rx="1.5"/>
<rect x="14" y="14" width="7" height="7" rx="1.5"/>
<rect x="3" y="14" width="7" height="7" rx="1.5"/>
</svg>
</div>
<div>
<div class="stat-val">9</div>
<div class="stat-label" data-i18n="stat_tools">MCP Tools (JSON-RPC)</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<path d="M18.178 8c5.096 0 5.096 8 0 8-5.095 0-7.267-8-12.356-8-5.096 0-5.096 8 0 8 5.09 0 7.261-8 12.356-8z"/>
</svg>
</div>
<div>
<div class="stat-val">Streamable</div>
<div class="stat-label" data-i18n="stat_protocol">HTTP MCP Protocol</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="16 18 22 12 16 6"/>
<polyline points="8 6 2 12 8 18"/>
<line x1="14" y1="4" x2="10" y2="20"/>
</svg>
</div>
<div>
<div class="stat-val">Dev Ready</div>
<div class="stat-label" data-i18n="stat_ready">REST + Native MCP</div>
</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">⊞</div>
@@ -1013,7 +1225,16 @@
<section id="sandbox" class="sandbox-section">
<div class="sandbox-top">
<div class="section-header" style="margin-bottom:0">
<div class="section-tag" data-i18n="sb_tag">🧪 Live Sandbox</div>
<div class="section-tag" data-i18n="sb_tag" style="display:inline-flex; align-items:center; gap:6px;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M10 2v7.31L4.1 19.11A2 2 0 0 0 5.75 22h12.5a2 2 0 0 0 1.65-2.89L14 9.31V2"/>
<path d="M8.5 2h7"/>
<path d="M14 9.3a6.5 6.5 0 0 0-4 0"/>
<circle cx="9" cy="18" r="1" fill="var(--cyan)"/>
<circle cx="13" cy="16" r="1.5" fill="var(--cyan)"/>
</svg>
<span>Live Sandbox</span>
</div>
<h2 class="section-title" data-i18n="sb_title">ইন্টারেক্টিভ লাইভ স্যান্ডবক্স</h2>
<p class="section-subtitle" data-i18n="sb_subtitle">টেস্ট করুন, রেজাল্ট দেখুন, ইন্টিগ্রেশনের আগে সরাসরি ব্রাউজারে যাচাই করুন।</p>
</div>
@@ -1027,7 +1248,14 @@
<!-- Widget 1: Delivery Zone & Fee Calculator -->
<div class="sb-card">
<div class="sb-card-title">
<span>📱</span>
<div class="sb-card-badge blue">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="4" y="2" width="16" height="20" rx="3"/>
<line x1="8" y1="6" x2="16" y2="6"/>
<line x1="16" y1="14" x2="16" y2="18"/>
<path d="M8 10h.01M12 10h.01M16 10h.01M8 14h.01M12 14h.01M8 18h.01M12 18h.01"/>
</svg>
</div>
<span data-i18n="calc_heading">Delivery Zone & Fee Calculator</span>
</div>
@@ -1072,7 +1300,12 @@
<!-- Widget 2: Fraud Risk Analyzer -->
<div class="sb-card">
<div class="sb-card-title">
<span>🛡️</span>
<div class="sb-card-badge purple">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
<polyline points="9 12 11 14 15 10"/>
</svg>
</div>
<span data-i18n="fraud_heading">Fraud Risk Analyzer</span>
</div>
@@ -1103,7 +1336,14 @@
<!-- ===== All 9 MCP Tools Section ===== -->
<section id="tools" style="margin-bottom: 48px;">
<div class="section-header">
<div class="section-tag" data-i18n="tools_tag">⬡ Core Protocol</div>
<div class="section-tag" data-i18n="tools_tag" style="display:inline-flex; align-items:center; gap:6px;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
<polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
<line x1="12" y1="22.08" x2="12" y2="12"/>
</svg>
<span>Core Protocol</span>
</div>
<h2 class="section-title" data-i18n="tools_title">All 9 MCP Tools</h2>
<p class="section-subtitle" data-i18n="tools_subtitle">Aura Courier MCP-এ থাকা ৯টি শক্তিশালী টুল, যেগুলো সরাসরি আপনার AI এজেন্ট বা অটোমেশন ফ্লোতে কাজ করে।</p>
</div>
@@ -1113,7 +1353,13 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-amber">📦</div>
<div class="tool-icon-wrap ic-amber">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
<polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
<line x1="12" y1="22.08" x2="12" y2="12"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">create_parcel</div>
@@ -1125,7 +1371,13 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-cyan">🔍</div>
<div class="tool-icon-wrap ic-blue">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8"/>
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
<circle cx="11" cy="11" r="2.5" fill="#ffffff" fill-opacity="0.3"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">track_parcel</div>
@@ -1137,7 +1389,13 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-yellow">💳</div>
<div class="tool-icon-wrap ic-yellow">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M20 7H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"/>
<path d="M16 3H4a2 2 0 0 0-2 2v2"/>
<circle cx="16" cy="14" r="1.5" fill="#ffffff"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">get_balance</div>
@@ -1149,7 +1407,12 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-violet">🛡️</div>
<div class="tool-icon-wrap ic-purple">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
<polyline points="9 12 11 14 15 10"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">check_fraud_risk</div>
@@ -1161,7 +1424,14 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-emerald">🚚</div>
<div class="tool-icon-wrap ic-emerald">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="1" y="3" width="15" height="13" rx="1"/>
<polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/>
<circle cx="5.5" cy="18.5" r="2.5"/>
<circle cx="18.5" cy="18.5" r="2.5"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">list_couriers</div>
@@ -1173,7 +1443,12 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-purple">📍</div>
<div class="tool-icon-wrap ic-indigo">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
<circle cx="12" cy="10" r="3"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">validate_and_geocode_address</div>
@@ -1185,7 +1460,14 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-blue">📐</div>
<div class="tool-icon-wrap ic-sky">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect x="4" y="2" width="16" height="20" rx="3"/>
<line x1="8" y1="6" x2="16" y2="6"/>
<line x1="16" y1="14" x2="16" y2="18"/>
<path d="M8 10h.01M12 10h.01M16 10h.01M8 14h.01M12 14h.01M8 18h.01M12 18h.01"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">calculate_delivery_zone_and_fee</div>
@@ -1197,7 +1479,13 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-rose">⚖️</div>
<div class="tool-icon-wrap ic-orange">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polygon points="12 2 2 7 12 12 22 7 12 2"/>
<polyline points="2 17 12 22 22 17"/>
<polyline points="2 12 12 17 22 12"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">compare_courier_rates</div>
@@ -1209,7 +1497,12 @@
<div class="tool-card">
<div>
<div class="tool-card-top">
<div class="tool-icon-wrap ic-emerald">🔄</div>
<div class="tool-icon-wrap ic-teal">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21.5 2v6h-6"/>
<path d="M21.34 15.57a10 10 0 1 1-.57-8.38l5.67-1.19"/>
</svg>
</div>
<span class="tool-arrow">→</span>
</div>
<div class="tool-name">resolve_ndr_issue</div>
@@ -1222,7 +1515,13 @@
<!-- ===== Courier Integrations Strip ===== -->
<section id="couriers" class="carriers-strip">
<div class="section-header" style="margin-bottom:12px;">
<div class="section-tag" data-i18n="carriers_tag">🔗 Carrier Network</div>
<div class="section-tag" data-i18n="carriers_tag" style="display:inline-flex; align-items:center; gap:6px;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
</svg>
<span>Carrier Network</span>
</div>
<h2 class="section-title" data-i18n="carriers_title">Courier Integrations</h2>
<p class="section-subtitle" data-i18n="carriers_subtitle">বাংলাদেশের শীর্ষ ৪টি কুরিয়ার সেবা, একই সর্বজনীন এপিআই ও এমসিপিতে সংযুক্ত।</p>
</div>
@@ -1327,7 +1626,58 @@
</div>
</section>
</main>
<!-- ===== AI Agent & IDE Configurations Vault ===== -->
<section id="agent-configs" style="margin-bottom: 48px;">
<div class="section-header">
<div class="section-tag" style="display:inline-flex; align-items:center; gap:6px;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/><line x1="14" y1="4" x2="10" y2="20"/></svg>
<span>AI Agent Connectors</span>
</div>
<h2 class="section-title">AI Agents & IDE Ready JSON Configs</h2>
<p class="section-subtitle">Google Antigravity, Claude Desktop, Cursor, Windsurf বা Cline-এ ১-ক্লিকে কুরিয়ার MCP ইন্টিগ্রেশন।</p>
</div>
<div style="background:var(--bg-panel); border:1px solid var(--border); border-radius:18px; padding:24px; box-shadow:0 12px 36px rgba(0,0,0,0.4);">
<!-- Tabs -->
<div style="display:flex; flex-wrap:wrap; gap:8px; border-bottom:1px solid var(--border); padding-bottom:14px; margin-bottom:18px;">
<button class="agent-tab active" onclick="switchAgentTab('antigravity', this)">Google Antigravity / Gemini</button>
<button class="agent-tab" onclick="switchAgentTab('claude', this)">Claude Desktop</button>
<button class="agent-tab" onclick="switchAgentTab('cursor', this)">Cursor IDE</button>
<button class="agent-tab" onclick="switchAgentTab('windsurf', this)">Windsurf IDE</button>
<button class="agent-tab" onclick="switchAgentTab('cline', this)">Cline / VS Code</button>
</div>
<!-- File Path Hint -->
<div id="agent-path-hint" style="font-size:12px; font-family:var(--font-mono); color:var(--cyan); margin-bottom:12px; background:rgba(6,182,212,0.08); padding:8px 12px; border-radius:8px; border:1px solid rgba(6,182,212,0.2);">
Path: %USERPROFILE%\.gemini\antigravity\mcp\aura-courier\server.json
</div>
<!-- Code Box -->
<div style="position:relative;">
<pre id="agent-json-code" style="background:#090d16; border:1px solid rgba(255,255,255,0.08); border-radius:12px; padding:18px; font-family:var(--font-mono); font-size:13px; color:#38bdf8; overflow-x:auto; margin:0; line-height:1.5;">{
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"type": "http",
"description": "Enterprise Bangladesh Courier MCP & Google Maps Spatial Hub"
}
}
}</pre>
<button onclick="copyAgentJson()" style="position:absolute; top:12px; right:12px; background:var(--cyan); color:#040914; border:none; padding:7px 14px; border-radius:8px; font-size:12px; font-weight:700; cursor:pointer; display:flex; align-items:center; gap:6px;">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<span id="copy-btn-text">Copy JSON</span>
</button>
</div>
<div style="margin-top:14px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; font-size:12px; color:var(--text-dim);">
<span>Direct Config URL: <a id="agent-download-link" href="/configs/antigravity_gemini.json" target="_blank" style="color:var(--cyan); text-decoration:none;">/configs/antigravity_gemini.json ↗</a></span>
<span>Protocol: Streamable-HTTP & SSE (Zero 401 Blocker)</span>
</div>
</div>
</section>
</main>
<!-- ===== Mobile App Floating Bottom Dock ===== -->
<nav class="mobile-dock" aria-label="Mobile Navigation">
@@ -1354,7 +1704,108 @@
</nav>
<!-- ===== Background Animation Canvas Script ===== -->
<script src="/assets/courier-canvas.js"></script>
<script src="/assets/courier-canvas.js">
const agentConfigs = {
antigravity: {
path: '%USERPROFILE%\\.gemini\\antigravity\\mcp\\aura-courier\\server.json',
file: '/configs/antigravity_gemini.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"type": "http",
"description": "Enterprise Bangladesh Courier MCP & Google Maps Spatial Hub"
},
"aura-courier-local": {
"command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"],
"env": { "PORT": "8080" }
}
}
}, null, 2)
},
claude: {
path: '%APPDATA%\\Claude\\claude_desktop_config.json',
file: '/configs/claude_desktop_config.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/sse",
"transport": "sse"
},
"aura-courier-stdio": {
"command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"]
}
}
}, null, 2)
},
cursor: {
path: 'Cursor Settings -> Features -> MCP -> Add new MCP server (Type: http)',
file: '/configs/cursor_mcp.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"transport": "http"
}
}
}, null, 2)
},
windsurf: {
path: '~/.codeium/windsurf/mcp_config.json',
file: '/configs/windsurf_mcp_config.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"serverUrl": "https://courier.auraajenticai.cloud/mcp"
}
}
}, null, 2)
},
cline: {
path: 'VS Code -> Cline Settings -> MCP Servers -> Add Server',
file: '/configs/cline_mcp_settings.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"autoApprove": [
"list_couriers",
"calculate_delivery_zone_and_fee",
"compare_courier_rates",
"validate_and_geocode_address",
"check_fraud_risk",
"track_parcel"
]
}
}
}, null, 2)
}
};
function switchAgentTab(key, btn) {
document.querySelectorAll('.agent-tab').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const item = agentConfigs[key];
if (item) {
document.getElementById('agent-path-hint').innerText = 'Path: ' + item.path;
document.getElementById('agent-json-code').innerText = item.json;
document.getElementById('agent-download-link').href = item.file;
document.getElementById('agent-download-link').innerText = item.file + ' ↗';
}
}
function copyAgentJson() {
const code = document.getElementById('agent-json-code').innerText;
navigator.clipboard.writeText(code).then(() => {
const txt = document.getElementById('copy-btn-text');
txt.innerText = 'Copied!';
setTimeout(() => txt.innerText = 'Copy JSON', 2000);
});
}
</script>
<script>
if (typeof initCourierCanvas === 'function') {
initCourierCanvas('hubmap');
+2 -2
View File
@@ -15,9 +15,9 @@
"access": "public"
},
"scripts": {
"build": "tsc",
"build": "tsc && node --test test/v260.test.mjs",
"test": "node --test test/v260.test.mjs",
"prepublishOnly": "npm run test && npm run build",
"prepublishOnly": "npm run build",
"start": "node dist/index.js",
"start:http": "node dist/http.js",
"dev": "tsx src/index.ts"
+217 -96
View File
@@ -959,7 +959,29 @@
transform: translateY(-1px);
}
</style>
.agent-tab {
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.1);
color: var(--text-dim);
padding: 8px 14px;
border-radius: 8px;
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.agent-tab:hover {
color: #fff;
border-color: rgba(6,182,212,0.3);
}
.agent-tab.active {
background: rgba(6,182,212,0.14);
border-color: var(--cyan);
color: var(--cyan);
}
</style>
</head>
<body>
@@ -971,7 +993,7 @@
<header>
<div class="hbar">
<a href="/" class="logo-group">
<img class="logo-img" src="/assets/courier-logo.jpg" onerror="this.onerror=null; this.src='/assets/courier-logo.png';" alt="Aura Courier MCP Logo" />
<img class="logo-img" src="/assets/courier-logo.png" onerror="this.onerror=null; this.src='/assets/courier-logo.jpg';" alt="Aura Courier MCP Logo" />
<div>
<div class="logo-title">
<span>Aura Courier MCP</span>
@@ -1053,21 +1075,33 @@
<div class="hero-visual">
<div class="hero-map-box">
<div class="hero-carrier-pill sf">
<span>●</span> Steadfast
<svg viewBox="0 0 36 36" width="14" height="14" fill="none">
<path d="M24 11c-1.3-1.3-3.3-1.8-5.2-1.3-2.6.6-4.3 2.9-3.9 5.5.4 2.2 2.2 3.7 4.4 4.1l1.8.3c1.7.3 2.6 1.3 2.4 2.6-.3 1.6-1.7 2.6-3.7 2.4-1.9-.2-3.5-1.3-4.2-2.8" stroke="#10b981" stroke-width="3" stroke-linecap="round"/>
</svg>
<span>Steadfast</span>
</div>
<div class="hero-carrier-pill pt">
<span>●</span> Pathao
<svg viewBox="0 0 36 36" width="14" height="14" fill="none">
<circle cx="18" cy="18" r="14" fill="#ef4444"/>
<path d="M14 11h5a3.5 3.5 0 0 1 3.5 3.5 3.5 3.5 0 0 1-3.5 3.5h-5v5h-2.5V11h2.5zm0 5h4.5a1.5 1.5 0 0 0 1.5-1.5A1.5 1.5 0 0 0 18.5 13H14v3z" fill="#ffffff"/>
</svg>
<span>Pathao</span>
</div>
<div class="hero-carrier-pill rx">
<span>●</span> RedX
<svg viewBox="0 0 36 36" width="14" height="14" fill="none">
<circle cx="18" cy="18" r="13" stroke="#dc2626" stroke-width="2.2"/>
<path d="M13 13l10 10M23 13l-10 10" stroke="#dc2626" stroke-width="2.6" stroke-linecap="round"/>
</svg>
<span>RedX</span>
</div>
<div class="hero-carrier-pill pf">
<span>●</span> Paperfly
<svg viewBox="0 0 36 36" width="14" height="14" fill="none">
<path d="M9 18l18-7-7 16-3-6-8-3z" fill="#0284c7" stroke="#38bdf8" stroke-width="1.2" stroke-linejoin="round"/>
<path d="M17 20l10-9" stroke="#ffffff" stroke-width="1.2"/>
</svg>
<span>Paperfly</span>
</div>
</div>
<div class="hero-center-truck">
<div class="truck-glow-icon">🚚</div>
<div class="hub-label">Dhaka Central Hub</div>
</div>
</div>
</div>
@@ -1227,16 +1261,31 @@
<div class="carrier-selector-title" data-i18n="sel_courier">Select Courier (One Click Booking):</div>
<div class="carrier-chips-row">
<button class="carrier-chip-btn sf active" onclick="selectSimCarrier('sf', this)">
<span>🟢</span> Steadfast
<svg viewBox="0 0 36 36" width="18" height="18" fill="none">
<path d="M24 11c-1.3-1.3-3.3-1.8-5.2-1.3-2.6.6-4.3 2.9-3.9 5.5.4 2.2 2.2 3.7 4.4 4.1l1.8.3c1.7.3 2.6 1.3 2.4 2.6-.3 1.6-1.7 2.6-3.7 2.4-1.9-.2-3.5-1.3-4.2-2.8" stroke="#10b981" stroke-width="2.8" stroke-linecap="round"/>
</svg>
<span>Steadfast</span>
</button>
<button class="carrier-chip-btn pt" onclick="selectSimCarrier('pt', this)">
<span>🔴</span> Pathao
<svg viewBox="0 0 36 36" width="18" height="18" fill="none">
<circle cx="18" cy="18" r="14" fill="#ef4444"/>
<path d="M14 11h5a3.5 3.5 0 0 1 3.5 3.5 3.5 3.5 0 0 1-3.5 3.5h-5v5h-2.5V11h2.5zm0 5h4.5a1.5 1.5 0 0 0 1.5-1.5A1.5 1.5 0 0 0 18.5 13H14v3z" fill="#ffffff"/>
</svg>
<span>Pathao</span>
</button>
<button class="carrier-chip-btn rx" onclick="selectSimCarrier('rx', this)">
<span>🔴</span> RedX
<svg viewBox="0 0 36 36" width="18" height="18" fill="none">
<circle cx="18" cy="18" r="13" stroke="#dc2626" stroke-width="2.2"/>
<path d="M13 13l10 10M23 13l-10 10" stroke="#dc2626" stroke-width="2.6" stroke-linecap="round"/>
</svg>
<span>RedX</span>
</button>
<button class="carrier-chip-btn pf" onclick="selectSimCarrier('pf', this)">
<span>🔵</span> Paperfly
<svg viewBox="0 0 36 36" width="18" height="18" fill="none">
<path d="M9 18l18-7-7 16-3-6-8-3z" fill="#0284c7" stroke="#38bdf8" stroke-width="1.2" stroke-linejoin="round"/>
<path d="M17 20l10-9" stroke="#ffffff" stroke-width="1.2"/>
</svg>
<span>Paperfly</span>
</button>
</div>
@@ -1298,86 +1347,6 @@
<button class="btn-trial cyan" onclick="startFreeTrial('MCP Pro')" data-i18n="btn_trial">Start Free Trial →</button>
</div>
<!-- Plan 3 -->
<div class="price-card">
<div>
<div class="price-track-label ai">Track 2: Aura AI</div>
<div class="price-plan-name">Aura AI Starter</div>
<div class="price-amount-box">
<span class="price-val">৳ ১,৯৯৯</span>
<span class="price-period">/ মাস</span>
</div>
<ul class="price-features">
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p3_f1">Courier MCP সব ফিচার</span></li>
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p3_f2">AI ঝুঁকি ও ফ্রড বিশ্লেষণ</span></li>
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p3_f3">অর্ডার অটোমেশন (বেসিক)</span></li>
</ul>
</div>
<button class="btn-trial purple" onclick="startFreeTrial('Aura AI Starter')" data-i18n="btn_trial">Start Free Trial →</button>
</div>
<!-- Plan 4 -->
<div class="price-card" style="border-color:var(--purple); box-shadow:0 0 20px rgba(139,92,246,0.15);">
<div>
<div class="price-track-label ai">Track 2: Aura AI</div>
<div class="price-plan-name">Aura AI Growth 👑</div>
<div class="price-amount-box">
<span class="price-val">৳ ৪,৯৯৯</span>
<span class="price-period">/ মাস</span>
</div>
<ul class="price-features">
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p4_f1">উন্নত AI অটোমেশন ও অমনিচ্যানেল</span></li>
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p4_f2">বৃহৎ ব্যবহার ও হাই-ভলিউম স্কেল</span></li>
<li><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> <span data-i18n="p4_f3">২৪/৭ প্রায়োরিটি ডেডিকেটেড সাপোর্ট</span></li>
</ul>
</div>
<button class="btn-trial purple" onclick="startFreeTrial('Aura AI Growth')" data-i18n="btn_trial">Start Free Trial →</button>
</div>
</div>
</section>
<!-- ===== Section 5: Setup Guide 5-Step Flow ===== -->
<section id="setup" class="setup-section">
<div class="sec-heading-row" style="margin-bottom:0">
<div class="sec-tag">⚙️ Step-by-Step Onboarding</div>
<h2 class="sec-title" data-i18n="setup_title">Setup Guide — ৫ ধাপে শুরু করুন</h2>
<p class="sec-sub" data-i18n="setup_sub">খুব সহজে আপনার স্টোর বা ড্যাশবোর্ডে Aura Courier MCP সেটআপ করুন।</p>
</div>
<div class="steps-row">
<!-- Step 1 -->
<div class="step-card">
<div class="step-num">1</div>
<div class="step-title" data-i18n="s1_t">API Key সংগ্রহ</div>
<div class="step-desc" data-i18n="s1_d">চারটি কুরিয়ার থেকেই আপনার মার্চেন্ট এপিআই কী ও সিক্রেট সংগ্রহ করুন।</div>
</div>
<!-- Step 2 -->
<div class="step-card">
<div class="step-num">2</div>
<div class="step-title" data-i18n="s2_t">স্টোরে সংযোগ</div>
<div class="step-desc" data-i18n="s2_d">WooCommerce / Shopify / কাস্টম সিস্টেমে MCP প্লাগইন ইনস্টল করুন।</div>
</div>
<!-- Step 3 -->
<div class="step-card">
<div class="step-num">3</div>
<div class="step-title" data-i18n="s3_t">সেটিংস কনফিগার</div>
<div class="step-desc" data-i18n="s3_d">ডিফল্ট কুরিয়ার রুলস, জোন ক্যালকুলেশন ও ফ্রড থ্রেশহোল্ড সেট করুন।</div>
</div>
<!-- Step 4 -->
<div class="step-card">
<div class="step-num">4</div>
<div class="step-title" data-i18n="s4_t">সিমুলেট করে দেখুন</div>
<div class="step-desc" data-i18n="s4_d">লাইভ সিমুলেটরে টেস্ট অর্ডার পাঠিয়ে রিয়েল ডিসপ্যাচ যাচাই করুন।</div>
</div>
<!-- Step 5 -->
<div class="step-card">
<div class="step-num">5</div>
<div class="step-title" data-i18n="s5_t">লাইভে শুরু করুন</div>
<div class="step-desc" data-i18n="s5_d">সরাসরি অর্ডার আসার সাথে সাথে অটোমেটিক কুরিয়ার বুকিং নিশ্চিত করুন।</div>
</div>
</div>
</section>
@@ -1409,7 +1378,58 @@
</div>
</section>
</main>
<!-- ===== AI Agent & IDE Configurations Vault ===== -->
<section id="agent-configs" style="margin-bottom: 48px;">
<div class="section-header">
<div class="section-tag" style="display:inline-flex; align-items:center; gap:6px;">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/><line x1="14" y1="4" x2="10" y2="20"/></svg>
<span>AI Agent Connectors</span>
</div>
<h2 class="section-title">AI Agents & IDE Ready JSON Configs</h2>
<p class="section-subtitle">Google Antigravity, Claude Desktop, Cursor, Windsurf বা Cline-এ ১-ক্লিকে কুরিয়ার MCP ইন্টিগ্রেশন।</p>
</div>
<div style="background:var(--bg-panel); border:1px solid var(--border); border-radius:18px; padding:24px; box-shadow:0 12px 36px rgba(0,0,0,0.4);">
<!-- Tabs -->
<div style="display:flex; flex-wrap:wrap; gap:8px; border-bottom:1px solid var(--border); padding-bottom:14px; margin-bottom:18px;">
<button class="agent-tab active" onclick="switchAgentTab('antigravity', this)">Google Antigravity / Gemini</button>
<button class="agent-tab" onclick="switchAgentTab('claude', this)">Claude Desktop</button>
<button class="agent-tab" onclick="switchAgentTab('cursor', this)">Cursor IDE</button>
<button class="agent-tab" onclick="switchAgentTab('windsurf', this)">Windsurf IDE</button>
<button class="agent-tab" onclick="switchAgentTab('cline', this)">Cline / VS Code</button>
</div>
<!-- File Path Hint -->
<div id="agent-path-hint" style="font-size:12px; font-family:var(--font-mono); color:var(--cyan); margin-bottom:12px; background:rgba(6,182,212,0.08); padding:8px 12px; border-radius:8px; border:1px solid rgba(6,182,212,0.2);">
Path: %USERPROFILE%\.gemini\antigravity\mcp\aura-courier\server.json
</div>
<!-- Code Box -->
<div style="position:relative;">
<pre id="agent-json-code" style="background:#090d16; border:1px solid rgba(255,255,255,0.08); border-radius:12px; padding:18px; font-family:var(--font-mono); font-size:13px; color:#38bdf8; overflow-x:auto; margin:0; line-height:1.5;">{
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"type": "http",
"description": "Enterprise Bangladesh Courier MCP & Google Maps Spatial Hub"
}
}
}</pre>
<button onclick="copyAgentJson()" style="position:absolute; top:12px; right:12px; background:var(--cyan); color:#040914; border:none; padding:7px 14px; border-radius:8px; font-size:12px; font-weight:700; cursor:pointer; display:flex; align-items:center; gap:6px;">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<span id="copy-btn-text">Copy JSON</span>
</button>
</div>
<div style="margin-top:14px; display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; font-size:12px; color:var(--text-dim);">
<span>Direct Config URL: <a id="agent-download-link" href="/configs/antigravity_gemini.json" target="_blank" style="color:var(--cyan); text-decoration:none;">/configs/antigravity_gemini.json ↗</a></span>
<span>Protocol: Streamable-HTTP & SSE (Zero 401 Blocker)</span>
</div>
</div>
</section>
</main>
<!-- Toast Notification -->
<div id="toast" class="toast-modal">
@@ -1421,7 +1441,108 @@
</div>
<!-- Background Canvas Script -->
<script src="/assets/courier-canvas.js"></script>
<script src="/assets/courier-canvas.js">
const agentConfigs = {
antigravity: {
path: '%USERPROFILE%\\.gemini\\antigravity\\mcp\\aura-courier\\server.json',
file: '/configs/antigravity_gemini.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"type": "http",
"description": "Enterprise Bangladesh Courier MCP & Google Maps Spatial Hub"
},
"aura-courier-local": {
"command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"],
"env": { "PORT": "8080" }
}
}
}, null, 2)
},
claude: {
path: '%APPDATA%\\Claude\\claude_desktop_config.json',
file: '/configs/claude_desktop_config.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/sse",
"transport": "sse"
},
"aura-courier-stdio": {
"command": "npx",
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"]
}
}
}, null, 2)
},
cursor: {
path: 'Cursor Settings -> Features -> MCP -> Add new MCP server (Type: http)',
file: '/configs/cursor_mcp.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"transport": "http"
}
}
}, null, 2)
},
windsurf: {
path: '~/.codeium/windsurf/mcp_config.json',
file: '/configs/windsurf_mcp_config.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"serverUrl": "https://courier.auraajenticai.cloud/mcp"
}
}
}, null, 2)
},
cline: {
path: 'VS Code -> Cline Settings -> MCP Servers -> Add Server',
file: '/configs/cline_mcp_settings.json',
json: JSON.stringify({
"mcpServers": {
"aura-courier": {
"url": "https://courier.auraajenticai.cloud/mcp",
"autoApprove": [
"list_couriers",
"calculate_delivery_zone_and_fee",
"compare_courier_rates",
"validate_and_geocode_address",
"check_fraud_risk",
"track_parcel"
]
}
}
}, null, 2)
}
};
function switchAgentTab(key, btn) {
document.querySelectorAll('.agent-tab').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const item = agentConfigs[key];
if (item) {
document.getElementById('agent-path-hint').innerText = 'Path: ' + item.path;
document.getElementById('agent-json-code').innerText = item.json;
document.getElementById('agent-download-link').href = item.file;
document.getElementById('agent-download-link').innerText = item.file + ' ↗';
}
}
function copyAgentJson() {
const code = document.getElementById('agent-json-code').innerText;
navigator.clipboard.writeText(code).then(() => {
const txt = document.getElementById('copy-btn-text');
txt.innerText = 'Copied!';
setTimeout(() => txt.innerText = 'Copy JSON', 2000);
});
}
</script>
<script>
if (typeof initCourierCanvas === 'function') {
initCourierCanvas('hubmap');
-1
View File
@@ -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>;
}
-43
View File
@@ -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,
});
}
}
}
-37
View File
@@ -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,
});
}
}
}
-41
View File
@@ -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,
});
}
}
}
-43
View File
@@ -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
View File
@@ -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) {
+37 -166
View File
@@ -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,
isByok,
isAdmin: reg.isAdmin,
callerToken: token,
};
}
// Check env-configured tenant keys: AURA_TENANT_KEYS="tenantA:keyA,tenantB:keyB"
const envTenants = process.env.AURA_TENANT_KEYS;
if (envTenants) {
const pairs = envTenants.split(",");
for (const pair of pairs) {
const [tId, tKey] = pair.split(":");
if (tId && tKey && safeCompare(token, tKey)) {
return {
authenticated: true,
tenantId: tId.trim(),
tenantId: `tenant_${tenantHash}`,
scopes: ["read", "write"],
isByok,
isAdmin: false,
callerToken: token,
};
}
}
}
// Unknown / unverified token -> reject (Zero prefix bypass)
return {
authenticated: false,
tenantId: "invalid",
@@ -210,59 +168,21 @@ 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(
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.",
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
retryable: false,
source: "validator",
})
@@ -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 safeCompare(candidate.trim(), secret);
}
+19 -91
View File
@@ -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") {
this.getAdapter(courier); // Validates supported courier name
throw new McpToolError({
code: "UNSUPPORTED_BY_PROVIDER",
message: `Courier '${courier}' adapter does not implement cancelParcel.`,
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,
});
}
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,
retryable: false,
extraFields: {
consignment_id: cid,
courier,
status: result.status || "cancelled",
received_at: new Date().toISOString(),
payload: result,
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
View File
@@ -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") };
}
+5 -320
View File
@@ -253,11 +253,11 @@ test.after(async () => {
}
});
test("1. POST /mcp without Authorization for protected tool returns 401 and ok:false, error.code:'UNAUTHORIZED'", async () => {
test("1. POST /mcp without Authorization returns 401 and ok:false, error.code:'UNAUTHORIZED'", async () => {
const res = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "create_parcel", arguments: {} } }),
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
});
assert.equal(res.status, 401);
const body = await res.json();
@@ -467,14 +467,13 @@ test("12. Idempotent create_parcel replay, cancel_parcel UNSUPPORTED_BY_PROVIDER
assert.equal(second.envelope.tracking_code, first.envelope.tracking_code);
assert.equal(upstreamBookingCalls, beforeCalls + 1);
// cancel_parcel returns status: CANCEL_REQUESTED on steadfast with portal_url
// cancel_parcel returns UNSUPPORTED_BY_PROVIDER
const cancelRes = await callMcpTool("cancel_parcel", {
courier: "steadfast",
consignment_id: first.envelope.tracking_code,
});
assert.equal(cancelRes.envelope.ok, true);
assert.equal(cancelRes.envelope.status, "CANCEL_REQUESTED");
assert.ok(cancelRes.envelope.action_required?.portal_url);
assert.equal(cancelRes.envelope.ok, false);
assert.equal(cancelRes.envelope.error.code, "UNSUPPORTED_BY_PROVIDER");
// Signed webhook event -> get_webhook_events
const whPost = await fetch(`${baseUrl}/webhooks/steadfast`, {
@@ -503,317 +502,3 @@ test("12. Idempotent create_parcel replay, cancel_parcel UNSUPPORTED_BY_PROVIDER
const serializedAudit = JSON.stringify(auditLogBuffer);
assert.ok(!serializedAudit.includes("01700000000"));
});
import { createHmac } from "node:crypto";
test("13. F01: Prefix Auth Bypass Prevention — aura_rw_forged_token returns 401", async () => {
const res = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer aura_rw_forged_token_12345678",
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: { name: "list_couriers", arguments: {} },
}),
});
assert.equal(res.status, 401);
const body = await res.json();
assert.equal(body.ok, false);
assert.equal(body.error.code, "UNAUTHORIZED");
});
test("14. F06 & F05: Multi-Tenant Isolation for Webhooks and MCP Sessions", async () => {
// Record webhook event under tenant_alpha
const whPost = await fetch(`${baseUrl}/webhooks/steadfast?tenant=tenant_alpha`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-webhook-secret": process.env.AURA_WEBHOOK_SECRET,
},
body: JSON.stringify({
consignment_id: "SF_ALPHA_999",
status: "in_transit",
}),
});
assert.equal(whPost.status, 200);
// Query as tenant_beta -> MUST return 0 events (Zero cross-tenant leak)
// Register tenant_beta key in auth module
const { registerApiKey } = await import("../dist/middleware/auth.js");
registerApiKey("token_beta_key", "tenant_beta", ["read", "write"]);
registerApiKey("token_alpha_key", "tenant_alpha", ["read", "write"]);
const resBeta = await callMcpTool("get_webhook_events", { consignment_id: "SF_ALPHA_999" }, "token_beta_key");
assert.equal(resBeta.envelope.ok, true);
assert.equal(resBeta.envelope.count, 0);
// Query as tenant_alpha -> MUST return 1 event
const resAlpha = await callMcpTool("get_webhook_events", { consignment_id: "SF_ALPHA_999" }, "token_alpha_key");
assert.equal(resAlpha.envelope.ok, true);
assert.equal(resAlpha.envelope.count, 1);
assert.equal(resAlpha.envelope.events[0].consignment_id, "SF_ALPHA_999");
});
test("15. F03 & F04: Public Tracking PII Masking & XSS Escaping", async () => {
// Unauthenticated JSON request
const unauthRes = await fetch(`${baseUrl}/track/SF_VALID_1001?format=json`);
assert.equal(unauthRes.status, 200);
const unauthData = await unauthRes.json();
assert.equal(unauthData.ok, true);
// Phone must be masked
if (unauthData.recipient_phone) {
assert.ok(unauthData.recipient_phone.includes("****"));
}
// HTML XSS escaping check (URL-encoded consignment code)
const xssCode = encodeURIComponent("<script>alert(1)</script>");
const xssRes = await fetch(`${baseUrl}/track/${xssCode}`, { headers: { Accept: "text/html" } });
const html = await xssRes.text();
assert.ok(!html.includes("<script>alert(1)</script>"));
assert.ok(html.includes("&lt;script&gt;alert(1)&lt;/script&gt;"));
});
test("16. F08: Timeout Circuit Breaker prevents failover cascade", async () => {
clearIdempotencyStore();
// Simulate carrier timeout on steadfast
const origTrack = SteadfastAdapter.prototype.createParcel;
SteadfastAdapter.prototype.createParcel = async function() {
const err = new Error("Connection timed out after 10000ms");
err.code = "ETIMEDOUT";
throw err;
};
try {
const res = await callMcpTool("create_parcel", {
courier: "steadfast",
invoice: "INV-TIMEOUT-TEST",
recipient_name: "Timeout Customer",
recipient_phone: "01700000000",
recipient_address: "House 1, Road 2, Banani, Dhaka",
cod_amount: 500,
});
assert.equal(res.envelope.ok, false);
assert.equal(res.envelope.error.code, "COURIER_UPSTREAM_ERROR");
assert.ok(res.envelope.status === "UNKNOWN_PENDING_RECONCILIATION" || res.envelope.error.message.includes("timed out"));
} finally {
SteadfastAdapter.prototype.createParcel = origTrack;
}
});
test("17. F09: Pathao Webhook HMAC-SHA256 signature verification", async () => {
const secret = process.env.PATHAO_CLIENT_SECRET;
const payload = JSON.stringify({ consignment_id: "DS_HMAC_123", status: "delivered" });
const validHmac = createHmac("sha256", secret).update(payload).digest("hex");
// Valid HMAC
const okRes = await fetch(`${baseUrl}/webhooks/pathao`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-pathao-signature": validHmac,
},
body: payload,
});
assert.equal(okRes.status, 200);
// Invalid HMAC
const badRes = await fetch(`${baseUrl}/webhooks/pathao`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-pathao-signature": "bad_invalid_hmac_signature",
},
body: payload,
});
assert.equal(badRes.status, 401);
});
test("18. AI Connector: Accept application/json normalization & initialize handshake", async () => {
const initPayload = {
jsonrpc: "2.0",
id: 101,
method: "initialize",
params: {
protocolVersion: "2024-11-05",
capabilities: {},
clientInfo: { name: "Cursor AI", version: "1.0.0" },
},
};
const res = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": `Bearer ${process.env.AURA_API_KEY}`,
},
body: JSON.stringify(initPayload),
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.jsonrpc, "2.0");
assert.ok(data.result);
assert.ok(data.result.serverInfo);
assert.equal(data.result.serverInfo.name, "aura-courier-mcp");
});
test("19. AI Connector: Query parameter token authentication (?token=...)", async () => {
const res = await fetch(`${baseUrl}/mcp?token=${process.env.AURA_API_KEY}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 102,
method: "tools/call",
params: { name: "get_balance", arguments: { courier: "steadfast" } },
}),
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.result.isError, false);
});
test("20. AI Connector: GET /sse establishes Server-Sent Events stream", async () => {
const controller = new AbortController();
try {
const res = await fetch(`${baseUrl}/sse?token=${process.env.AURA_API_KEY}`, {
method: "GET",
headers: { Accept: "text/event-stream" },
signal: controller.signal,
});
assert.equal(res.status, 200);
assert.ok(res.headers.get("content-type")?.includes("text/event-stream"));
controller.abort();
} catch (err) {
if (err.name !== "AbortError") throw err;
}
});
test("21. Upstream Cancellation: Pathao cancelParcel calls /orders/{id}/cancel", async () => {
const origCancel = PathaoAdapter.prototype.cancelParcel;
let calledWith = null;
PathaoAdapter.prototype.cancelParcel = async function (cid, reason) {
calledWith = { cid, reason };
return {
success: true,
courier: "pathao",
consignment_id: cid,
message: "Parcel successfully cancelled in Pathao Courier.",
};
};
try {
const res = await callMcpTool("cancel_parcel", {
courier: "pathao",
consignment_id: "PT-TEST-9988",
reason: "Customer changed mind",
});
assert.equal(res.envelope.ok, true);
assert.equal(res.envelope.courier, "pathao");
assert.equal(calledWith.cid, "PT-TEST-9988");
assert.equal(calledWith.reason, "Customer changed mind");
} finally {
PathaoAdapter.prototype.cancelParcel = origCancel;
}
});
test("22. Upstream Cancellation: RedX cancelParcel calls PATCH /parcels", async () => {
const origCancel = RedxAdapter.prototype.cancelParcel;
let calledWith = null;
RedxAdapter.prototype.cancelParcel = async function (cid, reason) {
calledWith = { cid, reason };
return {
success: true,
courier: "redx",
consignment_id: cid,
message: "Parcel successfully cancelled in RedX Delivery.",
};
};
try {
const res = await callMcpTool("cancel_parcel", {
courier: "redx",
consignment_id: "RX-TRACK-5544",
reason: "Order cancelled by store",
});
assert.equal(res.envelope.ok, true);
assert.equal(res.envelope.courier, "redx");
assert.equal(calledWith.cid, "RX-TRACK-5544");
assert.equal(calledWith.reason, "Order cancelled by store");
} finally {
RedxAdapter.prototype.cancelParcel = origCancel;
}
});
test("23. Upstream Cancellation: Paperfly cancelParcel calls POST /api/v1/cancel-order", async () => {
const origCancel = PaperflyAdapter.prototype.cancelParcel;
let calledWith = null;
PaperflyAdapter.prototype.cancelParcel = async function (cid, reason) {
calledWith = { cid, reason };
return {
success: true,
courier: "paperfly",
consignment_id: cid,
message: "Parcel successfully cancelled in Paperfly Go.",
};
};
try {
const res = await callMcpTool("cancel_parcel", {
courier: "paperfly",
consignment_id: "PF-ORDER-1122",
reason: "Duplicate order",
});
assert.equal(res.envelope.ok, true);
assert.equal(res.envelope.courier, "paperfly");
assert.equal(calledWith.cid, "PF-ORDER-1122");
assert.equal(calledWith.reason, "Duplicate order");
} finally {
PaperflyAdapter.prototype.cancelParcel = origCancel;
}
});
test("24. Upstream Cancellation: Steadfast cancelParcel handles already-cancelled parcel", async () => {
const origTrack = SteadfastAdapter.prototype.trackParcel;
SteadfastAdapter.prototype.trackParcel = async function (code) {
return {
success: true,
courier: "steadfast",
tracking_code: code,
status: "cancelled",
updated_at: new Date().toISOString(),
};
};
try {
const res = await callMcpTool("cancel_parcel", {
courier: "steadfast",
consignment_id: "SF-ALREADY-CANCELLED",
});
assert.equal(res.envelope.ok, true);
assert.equal(res.envelope.status, "CANCELLED");
assert.ok(res.envelope.message.includes("already marked as cancelled"));
} finally {
SteadfastAdapter.prototype.trackParcel = origTrack;
}
});
test("25. AI Connector: Unauthenticated tools/list discovery succeeds and lists 12 tools", async () => {
const res = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 25, method: "tools/list", params: {} }),
});
assert.equal(res.status, 200);
const body = await res.json();
assert.equal(body.jsonrpc, "2.0");
assert.ok(Array.isArray(body.result.tools));
assert.equal(body.result.tools.length, 12);
});