Compare commits
14 Commits
c37ae2f441
..
v2.7.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 8aa306bf63 | |||
| eeba92042c | |||
| 5e25a6277c | |||
| df1c419539 | |||
| 4cc43301df | |||
| d1e0948216 | |||
| e698f2161f | |||
| ca95e94979 | |||
| 0ebfc28ab2 | |||
| e6c63ce9fa | |||
| 5e552ee743 | |||
| 5c8a820ce8 | |||
| f8b69f4fa9 | |||
| 6c1db1a068 |
@@ -0,0 +1,5 @@
|
|||||||
|
.git
|
||||||
|
.github
|
||||||
|
node_modules
|
||||||
|
*.log
|
||||||
|
.env
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# ==============================================================================
|
||||||
|
# Aura Courier MCP (v2.6.1) — Environment Variable Template (NO REAL SECRETS!)
|
||||||
|
# ==============================================================================
|
||||||
|
# PRODUCTION RULE:
|
||||||
|
# - NEVER commit a real `.env` file or bake `.env` into Docker images.
|
||||||
|
# - Store all real production values in Coolify -> Application -> Environment
|
||||||
|
# Variables (`coolify-db`, App 25: `ix4jsg321uqfrko9qrrq4k7m`), NOT copied
|
||||||
|
# inside `/app/.env` inside the container.
|
||||||
|
# ==============================================================================
|
||||||
|
|
||||||
|
# --- Server & Auth ---
|
||||||
|
NODE_ENV=production
|
||||||
|
PORT=80
|
||||||
|
HOST=0.0.0.0
|
||||||
|
DATABASE_URL=postgresql://postgres:CHANGE_ME@ernix50nvuq9ur9jy8na8tgr:5432/aura_auth
|
||||||
|
AURA_API_KEY=aura_live_mcp_master_key_2026
|
||||||
|
AURA_READONLY_KEY=aura_ro_public_inspector_2026
|
||||||
|
|
||||||
|
# --- Steadfast Courier ---
|
||||||
|
STEADFAST_API_KEY=your_steadfast_api_key
|
||||||
|
STEADFAST_SECRET_KEY=your_steadfast_secret_key
|
||||||
|
STEADFAST_BASE_URL=https://portal.packzy.com/api/v1
|
||||||
|
|
||||||
|
# --- Pathao Express ---
|
||||||
|
PATHAO_CLIENT_ID=your_pathao_client_id
|
||||||
|
PATHAO_CLIENT_SECRET=your_pathao_client_secret
|
||||||
|
PATHAO_USERNAME=your_pathao_email
|
||||||
|
PATHAO_PASSWORD=your_pathao_password
|
||||||
|
PATHAO_STORE_ID=your_pathao_store_id
|
||||||
|
PATHAO_BASE_URL=https://api-hermes.pathao.com
|
||||||
|
|
||||||
|
# --- RedX Delivery ---
|
||||||
|
REDX_API_TOKEN=your_redx_jwt_token
|
||||||
|
REDX_BASE_URL=https://openapi.redx.com.bd/v1.0.0-beta
|
||||||
|
REDX_PICKUP_STORE_ID=your_redx_pickup_store_id
|
||||||
|
|
||||||
|
# --- Paperfly Go ---
|
||||||
|
PAPERFLY_API_KEY=your_paperfly_header_key
|
||||||
|
PAPERFLY_USERNAME=your_paperfly_username
|
||||||
|
PAPERFLY_PASSWORD=your_paperfly_password
|
||||||
|
PAPERFLY_STORE_NAME=Snehalata
|
||||||
|
PAPERFLY_BASE_URL=https://api.paperfly.com.bd
|
||||||
|
|
||||||
|
# --- Google Maps & Webhook Bridges ---
|
||||||
|
GOOGLE_MAPS_API_KEY=your_google_maps_api_key
|
||||||
|
SNEHALATA_VERIFY_KEY_URL=https://www.snehalata.com/api/mcp/verify-key
|
||||||
|
SNEHALATA_WEBHOOK_URL=https://www.snehalata.com/api/webhooks/pathao
|
||||||
@@ -1,5 +1,24 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [2.7.0] - 2026-11-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **Standard MCP OAuth 2.1 + PKCE (`S256`) Authorization Server (`src/middleware/oauth.ts`)**:
|
||||||
|
- **RFC 9728 Protected Resource Metadata**: `GET /.well-known/oauth-protected-resource` and `/.well-known/oauth-protected-resource/mcp` + `WWW-Authenticate` challenge on all `401 Unauthorized` `/mcp` responses (`POST`, `GET`, `DELETE`) with CORS exposure (`Access-Control-Expose-Headers: mcp-session-id, WWW-Authenticate`).
|
||||||
|
- **RFC 8414 Authorization Server Metadata**: `GET /.well-known/oauth-authorization-server` and `/.well-known/openid-configuration` advertising PKCE `S256`, `authorization_code`, and `refresh_token` grants.
|
||||||
|
- **RFC 7591 Dynamic Client Registration (`POST /oauth/register`)**: Restart-proof HMAC-signed client IDs supporting Google Gemini (`*.googleusercontent.com`), Claude, ChatGPT, Antigravity, Cursor, VS Code, and RFC 8252 loopback redirects while strictly rejecting untrusted redirect hosts.
|
||||||
|
- **Silicon Valley Global Consent & Aura Cloud SSO (`GET/POST /oauth/authorize`)**: Instant 1-click consent for signed-in Aura Cloud accounts (`aura_access` cookie), native **Continue with Google** & Work Email sign-in via `auth.auraajenticai.cloud`, Developer/Merchant API Key tab, 1-click Read-Only Sandbox for evaluators, and crisp inline vector SVG branding.
|
||||||
|
- **Gemini-Safe Non-Rotating Refresh & Dual-Auth (`POST /oauth/token`, `POST /oauth/revoke`, `src/middleware/auth.ts`)**: `application/x-www-form-urlencoded` + JSON token exchange with PKCE `S256`, 180-day non-rotating refresh tokens (preventing Google Gemini unlinking), and full Dual-Auth compatibility preserving static Bearer API Keys, PostgreSQL dynamic keys (`aura_courier_runtime`), and BYOK carrier headers.
|
||||||
|
- **Automated OAuth 2.1 Acceptance Suite (`test/oauth21.test.mjs`)**: Full end-to-end verification of discovery, DCR, SSO cookie consent, Read-Only Sandbox, PKCE `S256`, non-rotating refresh, Dual-Auth, and RFC 7009 revocation alongside all 25 existing tests.
|
||||||
|
|
||||||
|
## [2.6.1] - 2026-11-13
|
||||||
|
|
||||||
|
### Fixed & Changed
|
||||||
|
- **Single-Source-of-Truth Release Parity (`src/version.ts`)**: Added `APP_VERSION` reading `package.json` dynamically so `src/http.ts`, `src/server.ts`, and `src/index.ts` remain 100% synchronized with `package.json`, `server.json`, `plugin.json`, Glama Releases, GitHub Releases, and the live web UI (`v2.6.1`).
|
||||||
|
- **Glama `pnpm` Docker Build Compatibility**: Explicit `Express` type export in `src/http.ts` eliminating `TS2742` under strict `.pnpm/` resolution.
|
||||||
|
- **Silicon Valley Iconography & Live Portal Polish**: Replaced legacy glyph badges with crisp inline SVGs, upgraded RedX to its custom `RX` monogram badge, prevented header nav wrap, and restored live `#hubmap` canvas network animation.
|
||||||
|
- **Config Identifier Parity**: Aligned all client snippets in `configs/*` and embedded portal drawers to `aura-courier-mcp@2.6.1` matching `package.json` and `server.json`.
|
||||||
|
|
||||||
## [2.6.0] - 2026-11-10
|
## [2.6.0] - 2026-11-10
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
+4
-2
@@ -6,9 +6,11 @@ WORKDIR /app
|
|||||||
COPY package*.json tsconfig.json ./
|
COPY package*.json tsconfig.json ./
|
||||||
RUN npm install --no-audit --no-fund
|
RUN npm install --no-audit --no-fund
|
||||||
|
|
||||||
# Source + the marketing landing page (served at /)
|
# Source + web, static assets and simulator
|
||||||
COPY src ./src
|
COPY src ./src
|
||||||
COPY README.md index.html ./
|
COPY assets ./assets
|
||||||
|
COPY configs ./configs
|
||||||
|
COPY README.md index.html guide.html health.html privacy.html mcp_explorer.html simulator.html ./
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
# 🚚 AURA COURIER MCP v2.6.0 — THE ENTERPRISE LOGISTICS MASTER MANUAL
|
# 🚚 AURA COURIER MCP v2.7.0 — THE ENTERPRISE LOGISTICS MASTER MANUAL
|
||||||
### Universal Multi-Carrier Logistics Engine, Spatial Intelligence Hub & Zero-Risk COD Gateway
|
### Universal Multi-Carrier Logistics Engine, Spatial Intelligence Hub & Zero-Risk COD Gateway
|
||||||
**Published by Aura Agentic AI · Architected with DeepMind Principles & Google Maps Platform**
|
**Published by Aura Agentic AI · Architected with DeepMind Principles & Google Maps Platform**
|
||||||
|
|
||||||
[](https://cloud.google.com/find-a-partner/partner/aura-ajentic-ai)
|
[](https://cloud.google.com/find-a-partner/partner/aura-ajentic-ai)
|
||||||
[](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp)
|
[](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp)
|
||||||
[](plugin.json)
|
[](plugin.json)
|
||||||
[](https://courier.auraajenticai.cloud/guide)
|
[](https://courier.auraajenticai.cloud/guide)
|
||||||
[](https://opensource.org/licenses/Apache-2.0)
|
[](https://opensource.org/licenses/Apache-2.0)
|
||||||
[](https://courier.auraajenticai.cloud)
|
[](https://courier.auraajenticai.cloud)
|
||||||
@@ -227,15 +227,7 @@ curl -s https://courier.auraajenticai.cloud/health | jq
|
|||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"ok": true,
|
"ok": true,
|
||||||
"service": "aura-courier-mcp",
|
"version": "2.7.0"
|
||||||
"version": "2.6.0",
|
|
||||||
"tools_count": 9,
|
|
||||||
"spatial_engine": "Google Maps Platform (gmp_git_agentskills_v1)",
|
|
||||||
"fraud_engine": "Steadfast Nationwide API + BD Prefix Validator",
|
|
||||||
"webhooks": {
|
|
||||||
"steadfast": "/webhooks/steadfast",
|
|
||||||
"pathao": "/webhooks/pathao"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -286,7 +278,7 @@ Add this configuration block to your client settings (`claude_desktop_config.jso
|
|||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"aura-courier": {
|
"aura-courier": {
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": ["-y", "aura-courier-mcp@2.6.0"],
|
"args": ["-y", "aura-courier-mcp@2.7.0"],
|
||||||
"env": {
|
"env": {
|
||||||
"PORT": "8080",
|
"PORT": "8080",
|
||||||
"GOOGLE_MAPS_API_KEY": "<GOOGLE_MAPS_API_KEY>",
|
"GOOGLE_MAPS_API_KEY": "<GOOGLE_MAPS_API_KEY>",
|
||||||
@@ -348,6 +340,12 @@ Bundles the complete `courier-ops` skill (9 tools), `rules/COURIER_RULES.md` (sm
|
|||||||
|
|
||||||
## 9. Version History & Glama TDQS 5.0 Audit Log
|
## 9. Version History & Glama TDQS 5.0 Audit Log
|
||||||
|
|
||||||
|
* **v2.7.0 (Nov 24, 2026)**:
|
||||||
|
- **Standard MCP OAuth 2.1 + PKCE (`S256`) + RFC 9728 / 8414 / 7591 DCR**: Native remote OAuth connectivity for **Google Gemini**, **Antigravity Marketplace**, **ChatGPT**, and **Claude Web** with 1-click Aura Cloud SSO, Google Sign-In, Developer API Key Dual-Auth, and non-rotating refresh tokens.
|
||||||
|
- **13 Live Logistics & Spatial Tools + Full Glama / Antigravity Plugin Parity**: Synchronized all manifests (`package.json`, `plugin.json`, `server.json`, `validate_plugin.js`) and expanded automated tests (`30+` passing).
|
||||||
|
* **v2.6.1 (Nov 13, 2026)**:
|
||||||
|
- **Single-Source-of-Truth Release Parity (`src/version.ts`)**: Unified version synchronization across `package.json`, `server.json`, `plugin.json`, `/health`, MCP Server metadata, GitHub Releases, Gitea, Glama Registry, and live web UI (`v2.6.1`).
|
||||||
|
- **TypeScript Strict `pnpm` Compatibility & Silicon Valley UI**: Explicit Express typing resolving Glama Dockerfile `TS2742`, inline SVG carrier/tool iconography, RedX monogram badge, and interactive `#hubmap` canvas animation.
|
||||||
* **v2.6.0 (Nov 10, 2026)**:
|
* **v2.6.0 (Nov 10, 2026)**:
|
||||||
- **Bilingual User Guide & Business Benefits Hub (`GET /guide`)**: Interactive Bengali & English documentation (`https://courier.auraajenticai.cloud/guide`) covering 3-in-1 WooCommerce/Shopify integration, 6-Pillar WhatsApp/Messenger AI Bot harmony, Multi-Tenant Isolation, and MCP AI Agent setup.
|
- **Bilingual User Guide & Business Benefits Hub (`GET /guide`)**: Interactive Bengali & English documentation (`https://courier.auraajenticai.cloud/guide`) covering 3-in-1 WooCommerce/Shopify integration, 6-Pillar WhatsApp/Messenger AI Bot harmony, Multi-Tenant Isolation, and MCP AI Agent setup.
|
||||||
- **Bilingual Real-Time Fraud Risk Output (`🇧🇩 বাংলা | 🇬🇧 English`)**: Upgraded `FraudRiskEngine.evaluateRisk` and In-Dashboard Quick-Ship widget (`/api/courier/quick-ship`) with bilingual recommendations and 1-click language switching.
|
- **Bilingual Real-Time Fraud Risk Output (`🇧🇩 বাংলা | 🇬🇧 English`)**: Upgraded `FraudRiskEngine.evaluateRisk` and In-Dashboard Quick-Ship widget (`/api/courier/quick-ship`) with bilingual recommendations and 1-click language switching.
|
||||||
|
|||||||
+1
-1
@@ -8,7 +8,7 @@ Connect any AI Agent / IDE to Aura Courier MCP in seconds.
|
|||||||
- **Server-Sent Events / SSE (Claude Desktop, Remote SSE)**:
|
- **Server-Sent Events / SSE (Claude Desktop, Remote SSE)**:
|
||||||
`https://courier.auraajenticai.cloud/sse`
|
`https://courier.auraajenticai.cloud/sse`
|
||||||
- **NPX Direct CLI**:
|
- **NPX Direct CLI**:
|
||||||
`npx -y @auraajenticai/aura-courier-mcp@2.6.0`
|
`npx -y aura-courier-mcp@2.7.0`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
},
|
},
|
||||||
"aura-courier-local": {
|
"aura-courier-local": {
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"],
|
"args": ["-y", "aura-courier-mcp@2.7.0"],
|
||||||
"env": {
|
"env": {
|
||||||
"PORT": "8080"
|
"PORT": "8080"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
},
|
},
|
||||||
"aura-courier-stdio": {
|
"aura-courier-stdio": {
|
||||||
"command": "npx",
|
"command": "npx",
|
||||||
"args": ["-y", "@auraajenticai/aura-courier-mcp@2.6.0"]
|
"args": ["-y", "aura-courier-mcp@2.7.0"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+1
@@ -6,4 +6,5 @@ export interface CourierAdapter {
|
|||||||
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
||||||
|
cancelParcel?(consignmentId: string, reason?: string): Promise<any>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+11
@@ -16,4 +16,15 @@ export declare class PaperflyAdapter implements CourierAdapter {
|
|||||||
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
* Paperfly does not expose a live wallet balance API endpoint (T3).
|
||||||
*/
|
*/
|
||||||
getBalance(): Promise<BalanceResponse>;
|
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;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+38
@@ -135,4 +135,42 @@ export class PaperflyAdapter {
|
|||||||
hint: "Use Paperfly merchant portal",
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+11
@@ -43,4 +43,15 @@ export declare class PathaoAdapter implements CourierAdapter {
|
|||||||
*/
|
*/
|
||||||
fraudCheck(phone: string): Promise<any>;
|
fraudCheck(phone: string): Promise<any>;
|
||||||
getLocations(cityName?: string): Promise<LocationResolutionResponse>;
|
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;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+33
@@ -304,4 +304,37 @@ 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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+11
@@ -14,4 +14,15 @@ export declare class RedxAdapter implements CourierAdapter {
|
|||||||
* RedX does not expose a live wallet balance API endpoint (T3).
|
* RedX does not expose a live wallet balance API endpoint (T3).
|
||||||
*/
|
*/
|
||||||
getBalance(): Promise<BalanceResponse>;
|
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;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+40
@@ -137,4 +137,44 @@ export class RedxAdapter {
|
|||||||
hint: "Use RedX merchant portal",
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+12
@@ -14,4 +14,16 @@ export declare class SteadfastAdapter implements CourierAdapter {
|
|||||||
* Endpoint: GET /fraud_check/{phone}
|
* Endpoint: GET /fraud_check/{phone}
|
||||||
*/
|
*/
|
||||||
fraudCheck(phone: string): Promise<any>;
|
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;
|
||||||
|
}>;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+40
@@ -146,4 +146,44 @@ export class SteadfastAdapter {
|
|||||||
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
||||||
return response.data;
|
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",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+4
-5
@@ -1,9 +1,8 @@
|
|||||||
import { Request } from "express";
|
import { type Express, type Request } from "express";
|
||||||
import { EnvSource } from "./config.js";
|
import { EnvSource } from "./config.js";
|
||||||
/**
|
/**
|
||||||
* Pull this client's courier keys from request headers or query params.
|
* F10 Fix: Pull client courier keys strictly from request headers.
|
||||||
* Task T1 Tenant Isolation: Only fall back to master process.env credentials when
|
* Query parameters are completely ignored to prevent credential leakage in URL logs.
|
||||||
* the caller authenticated with the master key (tenantId === "master").
|
|
||||||
*/
|
*/
|
||||||
export declare function keysFromRequest(req: Request): EnvSource;
|
export declare function keysFromRequest(req: Request): EnvSource;
|
||||||
export declare const app: import("express-serve-static-core").Express;
|
export declare const app: Express;
|
||||||
|
|||||||
Vendored
+320
-88
@@ -1,24 +1,34 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||||
|
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { CourierRegistry, recordWebhookEvent } from "./registry.js";
|
import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
|
||||||
import { loadConfig } from "./config.js";
|
import { loadConfig } from "./config.js";
|
||||||
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
|
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
|
||||||
import { createRateLimiter } from "./middleware/rate_limit.js";
|
import { createRateLimiter } from "./middleware/rate_limit.js";
|
||||||
import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, verifyWebhookSignature, recordAuditLog, } from "./middleware/auth.js";
|
import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, verifyWebhookSignature, recordAuditLog, initDynamicAuthStore, upsertDynamicKeyHash, setTenantDynamicKeyStatus, listDynamicKeySummaries, } from "./middleware/auth.js";
|
||||||
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js";
|
||||||
|
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
|
||||||
|
import { APP_VERSION } from "./version.js";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import pg from "pg";
|
import pg from "pg";
|
||||||
const dbUrl = process.env.DATABASE_URL ||
|
/**
|
||||||
"postgresql://postgres:AMeyaNUsvKN9GR4zs33YZFQw2ZjeBXRacp5K09bz4vwDMsLejuO1KxBGIZtDLVCw@ernix50nvuq9ur9jy8na8tgr:5432/aura_auth";
|
* F02 Fix: Remove hardcoded plaintext password.
|
||||||
|
* Connection string is read strictly from process.env.DATABASE_URL.
|
||||||
|
*/
|
||||||
|
const dbUrl = process.env.DATABASE_URL;
|
||||||
let dbPool = null;
|
let dbPool = null;
|
||||||
if (process.env.NODE_ENV !== "test") {
|
if (process.env.NODE_ENV !== "test" && dbUrl) {
|
||||||
try {
|
try {
|
||||||
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
||||||
|
setRegistryDbPool(dbPool);
|
||||||
|
initDynamicAuthStore(dbPool).catch(() => { });
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
||||||
}
|
}
|
||||||
catch (_) { }
|
|
||||||
}
|
}
|
||||||
// Automated Data Retention Engine (Daily Midnight Sweep)
|
// Automated Data Retention Engine (Daily Midnight Sweep)
|
||||||
setInterval(async () => {
|
setInterval(async () => {
|
||||||
@@ -41,47 +51,91 @@ const PRIVACY_HTML = path.join(APP_DIR, "privacy.html");
|
|||||||
const HEALTH_HTML = path.join(APP_DIR, "health.html");
|
const HEALTH_HTML = path.join(APP_DIR, "health.html");
|
||||||
const MCP_EXPLORER_HTML = path.join(APP_DIR, "mcp_explorer.html");
|
const MCP_EXPLORER_HTML = path.join(APP_DIR, "mcp_explorer.html");
|
||||||
const GUIDE_HTML = path.join(APP_DIR, "guide.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");
|
||||||
/**
|
/**
|
||||||
* Pull this client's courier keys from request headers or query params.
|
* F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
|
||||||
* Task T1 Tenant Isolation: Only fall back to master process.env credentials when
|
*/
|
||||||
* the caller authenticated with the master key (tenantId === "master").
|
function escapeHtml(str) {
|
||||||
|
if (str == null)
|
||||||
|
return "";
|
||||||
|
return String(str)
|
||||||
|
.replace(/&/g, "&")
|
||||||
|
.replace(/</g, "<")
|
||||||
|
.replace(/>/g, ">")
|
||||||
|
.replace(/"/g, """)
|
||||||
|
.replace(/'/g, "'");
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
*/
|
*/
|
||||||
export function keysFromRequest(req) {
|
export function keysFromRequest(req) {
|
||||||
const h = req.headers;
|
const h = req.headers;
|
||||||
const q = req.query;
|
// Strict Multi-Tenant & BYOK Isolation:
|
||||||
const allowMasterEnvFallback = req.auraAuth?.tenantId === "master";
|
// If caller explicitly sends any BYOK courier headers (isByok === true), NEVER fall back to
|
||||||
const pick = (header, query, envVar, allowNonMasterEnv = false) => {
|
// platform master courier env keys so vendor/merchant BYOK credentials never mix with central keys.
|
||||||
|
const isByokRequest = Boolean(req.auraAuth?.isByok ||
|
||||||
|
h["x-steadfast-api-key"] ||
|
||||||
|
h["x-pathao-client-id"] ||
|
||||||
|
h["x-redx-api-token"] ||
|
||||||
|
h["x-paperfly-api-key"]);
|
||||||
|
const isPublicFraudCheck = req.auraAuth?.tenantId === "public_ro" &&
|
||||||
|
req.body?.method === "tools/call" &&
|
||||||
|
req.body?.params?.name === "check_fraud_risk";
|
||||||
|
const allowMasterEnvFallback = (req.auraAuth?.tenantId === "master" || isPublicFraudCheck) && !isByokRequest;
|
||||||
|
const pick = (header, envVar, allowNonMasterEnv = false) => {
|
||||||
const hv = h[header];
|
const hv = h[header];
|
||||||
const v = (Array.isArray(hv) ? hv[0] : hv) ?? q[query];
|
const v = Array.isArray(hv) ? hv[0] : hv;
|
||||||
if (v)
|
if (v && typeof v === "string" && v.trim())
|
||||||
return String(v);
|
return v.trim();
|
||||||
if (envVar && (allowMasterEnvFallback || allowNonMasterEnv)) {
|
if (envVar && (allowMasterEnvFallback || allowNonMasterEnv)) {
|
||||||
return process.env[envVar];
|
return process.env[envVar];
|
||||||
}
|
}
|
||||||
return undefined;
|
return undefined;
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
STEADFAST_API_KEY: pick("x-steadfast-api-key", "steadfast_key", "STEADFAST_API_KEY"),
|
STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"),
|
||||||
STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "steadfast_secret", "STEADFAST_SECRET_KEY"),
|
STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"),
|
||||||
STEADFAST_BASE_URL: pick("x-steadfast-base-url", "steadfast_base_url", "STEADFAST_BASE_URL", true),
|
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_ID"),
|
PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"),
|
||||||
PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "pathao_client_secret", "PATHAO_CLIENT_SECRET"),
|
PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"),
|
||||||
PATHAO_USERNAME: pick("x-pathao-username", "pathao_username", "PATHAO_USERNAME"),
|
PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"),
|
||||||
PATHAO_PASSWORD: pick("x-pathao-password", "pathao_password", "PATHAO_PASSWORD"),
|
PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"),
|
||||||
PATHAO_STORE_ID: pick("x-pathao-store-id", "pathao_store_id", "PATHAO_STORE_ID"),
|
PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"),
|
||||||
PATHAO_BASE_URL: pick("x-pathao-base-url", "pathao_base_url", "PATHAO_BASE_URL", true),
|
PATHAO_BASE_URL: pick("x-pathao-base-url", "PATHAO_BASE_URL", true),
|
||||||
REDX_API_TOKEN: pick("x-redx-api-token", "redx_token", "REDX_API_TOKEN"),
|
REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"),
|
||||||
REDX_BASE_URL: pick("x-redx-base-url", "redx_base_url", "REDX_BASE_URL", true),
|
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", "REDX_PICKUP_STORE_ID"),
|
REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "REDX_PICKUP_STORE_ID"),
|
||||||
PAPERFLY_API_KEY: pick("x-paperfly-api-key", "paperfly_key", "PAPERFLY_API_KEY"),
|
PAPERFLY_API_KEY: pick("x-paperfly-api-key", "PAPERFLY_API_KEY"),
|
||||||
PAPERFLY_USERNAME: pick("x-paperfly-username", "paperfly_username", "PAPERFLY_USERNAME"),
|
PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"),
|
||||||
PAPERFLY_PASSWORD: pick("x-paperfly-password", "paperfly_password", "PAPERFLY_PASSWORD"),
|
PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"),
|
||||||
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "paperfly_store", "PAPERFLY_STORE_NAME"),
|
PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"),
|
||||||
GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "google_maps_key", "GOOGLE_MAPS_API_KEY", true),
|
GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
export const app = express();
|
export const app = express();
|
||||||
app.use(express.json({ limit: "1mb" }));
|
app.set("trust proxy", 1);
|
||||||
|
app.use(express.json({
|
||||||
|
limit: "1mb",
|
||||||
|
verify: (req, _res, buf) => {
|
||||||
|
req.rawBody = buf;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
app.use(express.urlencoded({ extended: false, limit: "1mb" }));
|
||||||
// Robust Malformed JSON Syntax Error Guard
|
// Robust Malformed JSON Syntax Error Guard
|
||||||
app.use((err, _req, res, next) => {
|
app.use((err, _req, res, next) => {
|
||||||
if (err && (err.type === "entity.parse.failed" || err.status === 400)) {
|
if (err && (err.type === "entity.parse.failed" || err.status === 400)) {
|
||||||
@@ -96,47 +150,116 @@ app.use((err, _req, res, next) => {
|
|||||||
// Allow browser-based and cross-origin MCP clients.
|
// Allow browser-based and cross-origin MCP clients.
|
||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
res.header("Access-Control-Allow-Origin", "*");
|
res.header("Access-Control-Allow-Origin", "*");
|
||||||
|
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT");
|
||||||
res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key");
|
res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-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, WWW-Authenticate");
|
||||||
res.header("Access-Control-Expose-Headers", "mcp-session-id");
|
|
||||||
if (req.method === "OPTIONS") {
|
if (req.method === "OPTIONS") {
|
||||||
res.sendStatus(204);
|
return res.sendStatus(204);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
// Enterprise Sliding-Window Rate Limiters
|
// Static assets (official logo, favicons, branding) & agent MCP configs
|
||||||
const generalLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "General Gateway" });
|
app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" }));
|
||||||
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
|
app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" }));
|
||||||
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 30, name: "Live Tracking Hub" });
|
app.get("/favicon.ico", (_req, res) => {
|
||||||
const webhookLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Courier Webhook Gateway" });
|
res.sendFile(path.join(ASSETS_DIR, "courier-logo.jpg"), (err) => {
|
||||||
app.use(generalLimiter);
|
if (err && !res.headersSent)
|
||||||
|
res.status(204).end();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// Standard MCP OAuth 2.1 + PKCE (S256) + RFC 9728 + RFC 8414 + RFC 7591 Dynamic Client Registration
|
||||||
|
registerOAuthRoutes(app);
|
||||||
app.use(optionalAuthMiddleware);
|
app.use(optionalAuthMiddleware);
|
||||||
// Static brand assets (app icons, favicons, logos)
|
// Dynamic Tenant API Key Sync & Revocation Routes (Called by Snehalata / Admin Master Key)
|
||||||
app.use("/assets", express.static(path.join(APP_DIR, "assets")));
|
app.get("/admin/tokens", (req, res) => {
|
||||||
|
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
|
||||||
|
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
|
||||||
|
}
|
||||||
|
return res.json({ ok: true, tokens: listDynamicKeySummaries() });
|
||||||
|
});
|
||||||
|
app.post("/admin/tokens/register", async (req, res) => {
|
||||||
|
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
|
||||||
|
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
|
||||||
|
}
|
||||||
|
const b = req.body || {};
|
||||||
|
if ((!b.tokenHash && !b.rawToken) || !b.tenantId) {
|
||||||
|
return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "tenantId and tokenHash (or rawToken) required." }), "validator"));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const rec = await upsertDynamicKeyHash({
|
||||||
|
tokenHash: b.tokenHash,
|
||||||
|
rawToken: b.rawToken,
|
||||||
|
tenantId: String(b.tenantId),
|
||||||
|
storeName: b.storeName ? String(b.storeName) : undefined,
|
||||||
|
scopes: Array.isArray(b.scopes) ? b.scopes : ["read", "write"],
|
||||||
|
isAdmin: Boolean(b.isAdmin),
|
||||||
|
status: String(b.status || "ACTIVE"),
|
||||||
|
});
|
||||||
|
return res.json({ ok: true, tenantId: rec.tenantId, status: rec.status, hashPrefix: rec.tokenHash.slice(0, 10) });
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
return res.status(500).json(wrapError(err, "validator"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
app.post("/admin/tokens/revoke", async (req, res) => {
|
||||||
|
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
|
||||||
|
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
|
||||||
|
}
|
||||||
|
const b = req.body || {};
|
||||||
|
if (!b.tenantId) {
|
||||||
|
return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "tenantId required." }), "validator"));
|
||||||
|
}
|
||||||
|
const count = await setTenantDynamicKeyStatus(String(b.tenantId), String(b.status || "PAYMENT_DUE"));
|
||||||
|
return res.json({ ok: true, tenantId: b.tenantId, updatedKeys: count, status: b.status || "PAYMENT_DUE" });
|
||||||
|
});
|
||||||
|
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
|
||||||
|
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
|
||||||
const sessions = new Map();
|
const sessions = new Map();
|
||||||
const SESSION_TTL_MS = 60 * 60 * 1000; // 1-hour idle expiration
|
const sseSessions = new Map();
|
||||||
|
const SESSION_TTL_MS = 30 * 60 * 1000;
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
for (const [sid, entry] of sessions.entries()) {
|
for (const [sid, entry] of sessions.entries()) {
|
||||||
if (now - entry.lastActiveAt > SESSION_TTL_MS) {
|
if (now - entry.lastActiveAt > SESSION_TTL_MS) {
|
||||||
try {
|
|
||||||
entry.transport.close?.();
|
|
||||||
}
|
|
||||||
catch { }
|
|
||||||
sessions.delete(sid);
|
sessions.delete(sid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, 15 * 60 * 1000).unref();
|
for (const [sid, entry] of sseSessions.entries()) {
|
||||||
|
if (now - entry.lastActiveAt > SESSION_TTL_MS) {
|
||||||
|
sseSessions.delete(sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 60 * 1000).unref();
|
||||||
/**
|
/**
|
||||||
* Task T1: POST /mcp requires Authorization: Bearer <key>.
|
* 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
|
||||||
*/
|
*/
|
||||||
app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
|
app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
|
||||||
const sessionId = req.headers["mcp-session-id"];
|
const sessionId = req.headers["mcp-session-id"];
|
||||||
const tenantId = req.auraAuth?.tenantId || "default";
|
const tenantId = req.auraAuth?.tenantId || "default";
|
||||||
let transport;
|
let transport;
|
||||||
|
// F05: Verify MCP Session belongs strictly to caller's tenant
|
||||||
if (sessionId && sessions.has(sessionId)) {
|
if (sessionId && sessions.has(sessionId)) {
|
||||||
const entry = sessions.get(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();
|
entry.lastActiveAt = Date.now();
|
||||||
transport = entry.transport;
|
transport = entry.transport;
|
||||||
}
|
}
|
||||||
@@ -147,7 +270,7 @@ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
|
|||||||
sessionIdGenerator: () => randomUUID(),
|
sessionIdGenerator: () => randomUUID(),
|
||||||
enableJsonResponse: true,
|
enableJsonResponse: true,
|
||||||
onsessioninitialized: (sid) => {
|
onsessioninitialized: (sid) => {
|
||||||
sessions.set(sid, { transport, lastActiveAt: Date.now() });
|
sessions.set(sid, { transport, lastActiveAt: Date.now(), tenantId });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
transport.onclose = () => {
|
transport.onclose = () => {
|
||||||
@@ -160,6 +283,7 @@ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
|
|||||||
// Stateless JSON-RPC 2.0 Direct Execution Mode
|
// Stateless JSON-RPC 2.0 Direct Execution Mode
|
||||||
const rpcId = req.body.id ?? 1;
|
const rpcId = req.body.id ?? 1;
|
||||||
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
|
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
|
||||||
|
// F14: Allow unauthenticated tools/list discovery
|
||||||
if (req.body.method === "tools/list") {
|
if (req.body.method === "tools/list") {
|
||||||
res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { tools: TOOLS } });
|
res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { tools: TOOLS } });
|
||||||
return;
|
return;
|
||||||
@@ -228,6 +352,7 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (!req.auraAuth?.authenticated) {
|
if (!req.auraAuth?.authenticated) {
|
||||||
|
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, req.auraAuth?.tenantId === "invalid"));
|
||||||
return res.status(401).json(wrapError(new McpToolError({
|
return res.status(401).json(wrapError(new McpToolError({
|
||||||
code: "UNAUTHORIZED",
|
code: "UNAUTHORIZED",
|
||||||
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header.",
|
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header.",
|
||||||
@@ -236,13 +361,15 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
|
|||||||
res.status(400).send("Invalid or missing session ID");
|
res.status(400).send("Invalid or missing session ID");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!req.auraAuth?.authenticated) {
|
const entry = sessions.get(sessionId);
|
||||||
return res.status(401).json(wrapError(new McpToolError({
|
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",
|
code: "UNAUTHORIZED",
|
||||||
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header.",
|
message: "MCP Session belongs to another tenant.",
|
||||||
|
retryable: false,
|
||||||
}), "validator"));
|
}), "validator"));
|
||||||
}
|
}
|
||||||
const entry = sessions.get(sessionId);
|
|
||||||
entry.lastActiveAt = Date.now();
|
entry.lastActiveAt = Date.now();
|
||||||
await entry.transport.handleRequest(req, res);
|
await entry.transport.handleRequest(req, res);
|
||||||
});
|
});
|
||||||
@@ -254,9 +381,57 @@ app.delete("/mcp", requireMcpAuth, async (req, res) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const entry = sessions.get(sessionId);
|
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();
|
entry.lastActiveAt = Date.now();
|
||||||
await entry.transport.handleRequest(req, res);
|
await entry.transport.handleRequest(req, res);
|
||||||
});
|
});
|
||||||
|
/**
|
||||||
|
* GET /sse - Standard MCP Server-Sent Events Endpoint for AI Agent Connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery)
|
||||||
|
*/
|
||||||
|
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
|
* Task T1 & T8 — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly
|
||||||
*/
|
*/
|
||||||
@@ -272,6 +447,12 @@ function handleCourierWebhook(provider) {
|
|||||||
}), "validator"));
|
}), "validator"));
|
||||||
}
|
}
|
||||||
const payload = req.body || {};
|
const payload = req.body || {};
|
||||||
|
if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") {
|
||||||
|
const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || "";
|
||||||
|
if (secret)
|
||||||
|
res.setHeader("X-Pathao-Merchant-Webhook-Integration-Secret", secret);
|
||||||
|
return res.status(202).json({ ok: true, status: "webhook_verified" });
|
||||||
|
}
|
||||||
const consignmentId = payload.consignment_id ||
|
const consignmentId = payload.consignment_id ||
|
||||||
payload.merchant_order_id ||
|
payload.merchant_order_id ||
|
||||||
payload.tracking_code ||
|
payload.tracking_code ||
|
||||||
@@ -287,6 +468,8 @@ function handleCourierWebhook(provider) {
|
|||||||
const status = String(payload.status || payload.order_status || payload.event || "received");
|
const status = String(payload.status || payload.order_status || payload.event || "received");
|
||||||
const eventType = String(payload.notification_type || payload.event || "delivery_status");
|
const eventType = String(payload.notification_type || payload.event || "delivery_status");
|
||||||
const invoice = payload.invoice || payload.merchant_order_id;
|
const invoice = payload.invoice || payload.merchant_order_id;
|
||||||
|
const paramMerchantToken = req.params?.merchant_token ? String(req.params.merchant_token).trim() : "";
|
||||||
|
const tenantId = String(paramMerchantToken || req.query.tenant || req.headers["x-tenant-id"] || "default");
|
||||||
const record = {
|
const record = {
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
courier: provider,
|
courier: provider,
|
||||||
@@ -297,27 +480,44 @@ function handleCourierWebhook(provider) {
|
|||||||
received_at: new Date().toISOString(),
|
received_at: new Date().toISOString(),
|
||||||
payload,
|
payload,
|
||||||
};
|
};
|
||||||
recordWebhookEvent(record);
|
// F06: Record webhook event scoped by tenantId
|
||||||
|
recordWebhookEvent(record, tenantId);
|
||||||
|
// Forward verified Pathao financial events best-effort to Snehalata Financial Manager
|
||||||
|
if (provider === "pathao" && process.env.NODE_ENV !== "test" && /deliver|return|paid|settlement|invoice/i.test(`${status} ${eventType}`)) {
|
||||||
|
const fwdUrl = process.env.SNEHALATA_WEBHOOK_URL || "https://www.snehalata.com/api/webhooks/pathao";
|
||||||
|
const sig = String(req.headers["x-pathao-signature"] || process.env.PATHAO_CLIENT_SECRET || "");
|
||||||
|
if (fwdUrl && sig) {
|
||||||
|
fetch(fwdUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", "X-Pathao-Signature": sig },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
}).catch(() => { });
|
||||||
|
}
|
||||||
|
}
|
||||||
return res.status(200).json(wrapSuccess({
|
return res.status(200).json(wrapSuccess({
|
||||||
status: "success",
|
status: "success",
|
||||||
courier: provider,
|
courier: provider,
|
||||||
|
tenant_scope: tenantId,
|
||||||
consignment_id: record.consignment_id,
|
consignment_id: record.consignment_id,
|
||||||
event_id: record.id,
|
event_id: record.id,
|
||||||
message: `${provider} webhook verified and recorded.`,
|
message: `${provider} webhook verified and recorded for tenant '${tenantId}'.`,
|
||||||
}, "live_api"));
|
}, "live_api"));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
app.post("/webhooks/steadfast", webhookLimiter, handleCourierWebhook("steadfast"));
|
app.post(["/webhooks/steadfast", "/webhooks/steadfast/:merchant_token"], handleCourierWebhook("steadfast"));
|
||||||
app.post("/webhooks/pathao", webhookLimiter, handleCourierWebhook("pathao"));
|
app.post(["/webhooks/pathao", "/webhooks/pathao/:merchant_token"], handleCourierWebhook("pathao"));
|
||||||
app.post("/webhooks/redx", webhookLimiter, handleCourierWebhook("redx"));
|
app.post(["/webhooks/redx", "/webhooks/redx/:merchant_token"], handleCourierWebhook("redx"));
|
||||||
app.post("/webhooks/paperfly", webhookLimiter, handleCourierWebhook("paperfly"));
|
app.post(["/webhooks/paperfly", "/webhooks/paperfly/:merchant_token"], handleCourierWebhook("paperfly"));
|
||||||
/**
|
/**
|
||||||
* Live Consumer & Merchant Cyber-Dark Tracking Hub
|
* GET /track/:code - Hardened Public & Authenticated Tracking Gateway
|
||||||
* GET /track/:code
|
* F03: PII Masking for unauthenticated callers.
|
||||||
|
* F04: HTML entity escaping for XSS prevention.
|
||||||
*/
|
*/
|
||||||
app.get("/track/:code", trackingLimiter, async (req, res) => {
|
app.get("/track/:code", trackingLimiter, async (req, res) => {
|
||||||
const code = req.params.code;
|
const code = req.params.code;
|
||||||
const format = req.query.format;
|
const format = req.query.format;
|
||||||
|
const isAuth = Boolean(req.auraAuth?.authenticated);
|
||||||
|
const callerTenant = req.auraAuth?.tenantId;
|
||||||
let courier = (req.query.courier || "").toLowerCase();
|
let courier = (req.query.courier || "").toLowerCase();
|
||||||
if (!courier) {
|
if (!courier) {
|
||||||
if (code.toUpperCase().startsWith("DS") || code.toUpperCase().startsWith("DB"))
|
if (code.toUpperCase().startsWith("DS") || code.toUpperCase().startsWith("DB"))
|
||||||
@@ -341,7 +541,7 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
}
|
}
|
||||||
catch (_) { }
|
catch (_) { }
|
||||||
}
|
}
|
||||||
const registry = new CourierRegistry(loadConfig());
|
const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
|
||||||
let trackResult = null;
|
let trackResult = null;
|
||||||
let errorObj = null;
|
let errorObj = null;
|
||||||
try {
|
try {
|
||||||
@@ -350,18 +550,44 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
catch (err) {
|
catch (err) {
|
||||||
errorObj = 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 (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) {
|
||||||
if (trackResult) {
|
if (trackResult) {
|
||||||
return res.json(wrapSuccess(trackResult, "live_api"));
|
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"));
|
||||||
}
|
}
|
||||||
if (dbParcel) {
|
if (dbParcel) {
|
||||||
return res.json(wrapSuccess({ success: true, parcel: dbParcel }, "cache"));
|
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.status(404).json(wrapError(errorObj || new Error("Consignment not found"), "live_api"));
|
return res.status(404).json(wrapError(errorObj || new Error("Consignment not found"), "live_api"));
|
||||||
}
|
}
|
||||||
const raw = trackResult?.raw_response?.data || trackResult?.raw_response || (dbParcel?.raw?.data || dbParcel?.raw) || {};
|
const raw = trackResult?.raw_response?.data || trackResult?.raw_response || (dbParcel?.raw?.data || dbParcel?.raw) || {};
|
||||||
const recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer";
|
let recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer";
|
||||||
const recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh";
|
let recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh";
|
||||||
|
// F03: Mask PII for public web tracker view
|
||||||
|
if (!isOwner) {
|
||||||
|
recipientAddress = redactAddressToDistrict(recipientAddress);
|
||||||
|
if (recipientName && recipientName.length > 2) {
|
||||||
|
recipientName = recipientName.charAt(0) + "*** " + (recipientName.split(" ")[1] || "");
|
||||||
|
}
|
||||||
|
}
|
||||||
const codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0;
|
const codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0;
|
||||||
const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found");
|
const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found");
|
||||||
const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase();
|
const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase();
|
||||||
@@ -372,12 +598,13 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
const isAtHub = String(statusText).toLowerCase().includes("hub");
|
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 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");
|
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>
|
res.type("html").send(`<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<title>Aura Live Tracking — ${code}</title>
|
<title>Aura Live Tracking — ${escapeHtml(code)}</title>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<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 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" />
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
|
||||||
@@ -419,27 +646,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-icon"><i class="fa-solid fa-truck-fast"></i></div>
|
||||||
<div class="brand-text">
|
<div class="brand-text">
|
||||||
<h1>Aura Live Tracking</h1>
|
<h1>Aura Live Tracking</h1>
|
||||||
<p>${carrierName} • Direct Live Telemetry</p>
|
<p>${escapeHtml(carrierName)} • Direct Live Telemetry</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="status-badge"><span>${statusText}</span></div>
|
<div class="status-badge"><span>${escapeHtml(statusText)}</span></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="tracking-code-box">
|
<div class="tracking-code-box">
|
||||||
<div><div class="code-label">Consignment Tracking ID</div><div class="code-val">${code}</div></div>
|
<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;">${carrierName}</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>
|
||||||
<div class="timeline">
|
<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 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 ${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">${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-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: ${recipientAddress}</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>
|
</div>
|
||||||
<div class="info-grid">
|
<div class="info-grid">
|
||||||
<div class="info-item"><div class="info-item-label">Customer</div><div class="info-item-val">${recipientName}</div></div>
|
<div class="info-item"><div class="info-item-label">Customer</div><div class="info-item-val">${escapeHtml(recipientName)}</div></div>
|
||||||
<div class="info-item"><div class="info-item-label">Cash on Delivery (COD)</div><div class="info-item-val">৳ ${Number(codAmount).toLocaleString()}</div></div>
|
<div class="info-item"><div class="info-item-label">Cash on Delivery (COD)</div><div class="info-item-val">৳ ${Number(codAmount).toLocaleString()}</div></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
${shortLink ? `<a href="${shortLink}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ""}
|
${shortLink ? `<a href="${escapeHtml(shortLink)}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ""}
|
||||||
<button onclick="window.location.reload()" class="btn btn-secondary"><i class="fa-solid fa-rotate-right"></i> Refresh Live Status</button>
|
<button onclick="window.location.reload()" class="btn btn-secondary"><i class="fa-solid fa-rotate-right"></i> Refresh Live Status</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -448,8 +675,6 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
|
|||||||
});
|
});
|
||||||
/**
|
/**
|
||||||
* Task T9 — Health & Live Telemetry Endpoint
|
* 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) => {
|
app.get("/health", (req, res) => {
|
||||||
const auth = req.auraAuth || resolveAuthContext(req);
|
const auth = req.auraAuth || resolveAuthContext(req);
|
||||||
@@ -458,19 +683,19 @@ app.get("/health", (req, res) => {
|
|||||||
if (req.query.ui === "1" && req.headers.accept?.includes("text/html")) {
|
if (req.query.ui === "1" && req.headers.accept?.includes("text/html")) {
|
||||||
return res.sendFile(HEALTH_HTML, (err) => {
|
return res.sendFile(HEALTH_HTML, (err) => {
|
||||||
if (err && !res.headersSent)
|
if (err && !res.headersSent)
|
||||||
res.json({ ok: true, version: "2.6.0" });
|
res.json({ ok: true, version: APP_VERSION });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return res.json({
|
return res.json({
|
||||||
ok: true,
|
ok: true,
|
||||||
version: "2.6.0",
|
version: APP_VERSION,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const mem = process.memoryUsage();
|
const mem = process.memoryUsage();
|
||||||
const detailed = {
|
const detailed = {
|
||||||
ok: true,
|
ok: true,
|
||||||
service: "aura-courier-mcp",
|
service: "aura-courier-mcp",
|
||||||
version: "2.6.0",
|
version: APP_VERSION,
|
||||||
tools_count: TOOLS.length,
|
tools_count: TOOLS.length,
|
||||||
spatial_engine: "Google Maps Platform (gmp_git_agentskills_v1)",
|
spatial_engine: "Google Maps Platform (gmp_git_agentskills_v1)",
|
||||||
fraud_engine: "Pathao Nationwide v2 + Steadfast Nationwide API + BD Prefix Validator",
|
fraud_engine: "Pathao Nationwide v2 + Steadfast Nationwide API + BD Prefix Validator",
|
||||||
@@ -493,7 +718,7 @@ app.get("/health", (req, res) => {
|
|||||||
app.get("/health.html", (_req, res) => {
|
app.get("/health.html", (_req, res) => {
|
||||||
res.sendFile(HEALTH_HTML, (err) => {
|
res.sendFile(HEALTH_HTML, (err) => {
|
||||||
if (err && !res.headersSent)
|
if (err && !res.headersSent)
|
||||||
res.json({ ok: true, version: "2.6.0" });
|
res.json({ ok: true, version: APP_VERSION });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
app.get("/privacy", (_req, res) => {
|
app.get("/privacy", (_req, res) => {
|
||||||
@@ -510,6 +735,13 @@ 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) => {
|
app.get("/", (_req, res) => {
|
||||||
res.sendFile(LANDING, (err) => {
|
res.sendFile(LANDING, (err) => {
|
||||||
if (err && !res.headersSent) {
|
if (err && !res.headersSent) {
|
||||||
@@ -517,7 +749,7 @@ app.get("/", (_req, res) => {
|
|||||||
.type("html")
|
.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 Courier MCP</title>` +
|
.send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Aura Courier MCP</title>` +
|
||||||
`<style>body{font-family:system-ui,sans-serif;background:#07080a;color:#f4f5f7;margin:0;display:grid;place-items:center;min-height:100vh}.b{max-width:640px;padding:40px;text-align:center}h1{font-size:28px;margin:0 0 10px}code{background:#0f1115;padding:2px 8px;border-radius:6px;color:#00d4ff;font-size:13px}a{color:#00d4ff}p{line-height:1.6;color:#a4a8b3}</style></head>` +
|
`<style>body{font-family:system-ui,sans-serif;background:#07080a;color:#f4f5f7;margin:0;display:grid;place-items:center;min-height:100vh}.b{max-width:640px;padding:40px;text-align:center}h1{font-size:28px;margin:0 0 10px}code{background:#0f1115;padding:2px 8px;border-radius:6px;color:#00d4ff;font-size:13px}a{color:#00d4ff}p{line-height:1.6;color:#a4a8b3}</style></head>` +
|
||||||
`<body><div class="b"><h1>🚚 Aura Courier MCP v2.6.0</h1><p>Enterprise Bangladesh courier MCP & Google Maps Platform spatial hub.</p>` +
|
`<body><div class="b"><h1>🚚 Aura Courier MCP v${APP_VERSION}</h1><p>Enterprise Bangladesh courier MCP & Google Maps Platform spatial hub.</p>` +
|
||||||
`<p>Connect your AI to <code>POST /mcp</code> with Streamable-HTTP.</p>` +
|
`<p>Connect your AI to <code>POST /mcp</code> with Streamable-HTTP.</p>` +
|
||||||
`<p>Webhooks: <code>POST /webhooks/steadfast</code> · <code>POST /webhooks/pathao</code></p>` +
|
`<p>Webhooks: <code>POST /webhooks/steadfast</code> · <code>POST /webhooks/pathao</code></p>` +
|
||||||
`<p>By <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="https://courier.auraajenticai.cloud">docs & setup</a></p></div></body></html>`);
|
`<p>By <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="https://courier.auraajenticai.cloud">docs & setup</a></p></div></body></html>`);
|
||||||
@@ -526,6 +758,6 @@ app.get("/", (_req, res) => {
|
|||||||
});
|
});
|
||||||
if (process.env.NODE_ENV !== "test") {
|
if (process.env.NODE_ENV !== "test") {
|
||||||
app.listen(PORT, () => {
|
app.listen(PORT, () => {
|
||||||
console.log(`Aura Courier MCP v2.6.0 (HTTP) listening on :${PORT} — POST /mcp`);
|
console.log(`Aura Courier MCP v${APP_VERSION} (HTTP) listening on :${PORT} — POST /mcp`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+2
-1
@@ -2,13 +2,14 @@
|
|||||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
import { CourierRegistry } from "./registry.js";
|
import { CourierRegistry } from "./registry.js";
|
||||||
import { buildMcpServer } from "./server.js";
|
import { buildMcpServer } from "./server.js";
|
||||||
|
import { APP_VERSION } from "./version.js";
|
||||||
// STDIO / npx entrypoint (Claude Desktop, Cursor, Antigravity).
|
// STDIO / npx entrypoint (Claude Desktop, Cursor, Antigravity).
|
||||||
// Credentials come from environment variables (STEADFAST_API_KEY, PATHAO_*).
|
// Credentials come from environment variables (STEADFAST_API_KEY, PATHAO_*).
|
||||||
async function run() {
|
async function run() {
|
||||||
const server = buildMcpServer(new CourierRegistry());
|
const server = buildMcpServer(new CourierRegistry());
|
||||||
const transport = new StdioServerTransport();
|
const transport = new StdioServerTransport();
|
||||||
await server.connect(transport);
|
await server.connect(transport);
|
||||||
console.error("Aura Courier MCP v2.6.0 running on STDIO");
|
console.error(`Aura Courier MCP v${APP_VERSION} running on STDIO`);
|
||||||
}
|
}
|
||||||
run().catch((error) => {
|
run().catch((error) => {
|
||||||
console.error("Fatal error running Aura Courier MCP:", error);
|
console.error("Fatal error running Aura Courier MCP:", error);
|
||||||
|
|||||||
Vendored
+51
-7
@@ -7,11 +7,14 @@ export interface AuraAuthContext {
|
|||||||
isByok: boolean;
|
isByok: boolean;
|
||||||
isAdmin: boolean;
|
isAdmin: boolean;
|
||||||
callerToken?: string;
|
callerToken?: string;
|
||||||
|
deniedReason?: string;
|
||||||
|
httpStatus?: number;
|
||||||
}
|
}
|
||||||
declare global {
|
declare global {
|
||||||
namespace Express {
|
namespace Express {
|
||||||
interface Request {
|
interface Request {
|
||||||
auraAuth?: AuraAuthContext;
|
auraAuth?: AuraAuthContext;
|
||||||
|
rawBody?: string | Buffer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,23 +26,63 @@ export interface AuditEntry {
|
|||||||
outcome: "ok" | "denied" | "error";
|
outcome: "ok" | "denied" | "error";
|
||||||
}
|
}
|
||||||
export declare const auditLogBuffer: AuditEntry[];
|
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 hasByokCredentials(req: Request): boolean;
|
||||||
export declare function extractBearerToken(req: Request): string | undefined;
|
export declare function extractBearerToken(req: Request): string | undefined;
|
||||||
/**
|
/**
|
||||||
* Resolve bearer token into tenant context and scopes (read / write).
|
* In-memory / env-configured tenant API keys registry.
|
||||||
|
* Maps sha256(token) -> { tenantId, scopes, isAdmin }
|
||||||
|
*/
|
||||||
|
export interface DynamicKeyRecord {
|
||||||
|
tokenHash: string;
|
||||||
|
tenantId: string;
|
||||||
|
storeName?: string;
|
||||||
|
scopes: AuthScope[];
|
||||||
|
isAdmin: boolean;
|
||||||
|
status: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
export declare function initDynamicAuthStore(pool: any): Promise<void>;
|
||||||
|
export declare function upsertDynamicKeyHash(opts: {
|
||||||
|
tokenHash?: string;
|
||||||
|
rawToken?: string;
|
||||||
|
tenantId: string;
|
||||||
|
storeName?: string;
|
||||||
|
scopes?: AuthScope[];
|
||||||
|
isAdmin?: boolean;
|
||||||
|
status?: string;
|
||||||
|
}): Promise<DynamicKeyRecord>;
|
||||||
|
export declare function setTenantDynamicKeyStatus(tenantId: string, status: string): Promise<number>;
|
||||||
|
export declare function listDynamicKeySummaries(): {
|
||||||
|
hashPrefix: string;
|
||||||
|
tenantId: string;
|
||||||
|
storeName: string;
|
||||||
|
status: string;
|
||||||
|
scopes: AuthScope[];
|
||||||
|
updatedAt: string;
|
||||||
|
}[];
|
||||||
|
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.
|
||||||
*/
|
*/
|
||||||
export declare function resolveAuthContext(req: Request): AuraAuthContext;
|
export declare function resolveAuthContext(req: Request): AuraAuthContext;
|
||||||
/**
|
/**
|
||||||
* Middleware: Evaluates auth context for all requests
|
* Middleware: Evaluates auth context for all requests
|
||||||
*/
|
*/
|
||||||
export declare function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void;
|
export declare function resolveAuthContextAsync(req: Request): Promise<AuraAuthContext>;
|
||||||
|
export declare function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): Promise<void>;
|
||||||
/**
|
/**
|
||||||
* Strict /mcp Authentication & Per-Key Rate Limit Guard (T1)
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
||||||
* Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope
|
* 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.
|
||||||
*/
|
*/
|
||||||
export declare function requireMcpAuth(req: Request, res: Response, next: NextFunction): void;
|
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 (T1)
|
* Verify scope permission for a specific tool and record a privacy-safe audit log entry
|
||||||
*/
|
*/
|
||||||
export declare function isActionPermitted(req: Request, toolName: string, args?: Record<string, any>): {
|
export declare function isActionPermitted(req: Request, toolName: string, args?: Record<string, any>): {
|
||||||
permitted: boolean;
|
permitted: boolean;
|
||||||
@@ -50,7 +93,8 @@ 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;
|
export declare function recordAuditLog(tenant: string, tool: string, args: Record<string, any> | undefined, outcome: "ok" | "denied" | "error"): void;
|
||||||
/**
|
/**
|
||||||
* Verify inbound courier webhook authentication / signature (T1)
|
* F09 Fix: Native Carrier Webhook HMAC-SHA256 & Token Verification.
|
||||||
* Rejects unsigned/invalid webhook calls with HTTP 401/403.
|
* Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body.
|
||||||
|
* Steadfast uses secret key header comparison.
|
||||||
*/
|
*/
|
||||||
export declare function verifyWebhookSignature(req: Request, provider: string): boolean;
|
export declare function verifyWebhookSignature(req: Request, provider: string): boolean;
|
||||||
|
|||||||
Vendored
+394
-41
@@ -1,5 +1,6 @@
|
|||||||
import { createHash, timingSafeEqual } from "node:crypto";
|
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
||||||
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
|
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
|
||||||
|
import { verifyOAuthAccessToken, buildWwwAuthenticateHeader } from "./oauth.js";
|
||||||
const READ_TOOLS = new Set([
|
const READ_TOOLS = new Set([
|
||||||
"list_couriers",
|
"list_couriers",
|
||||||
"track_parcel",
|
"track_parcel",
|
||||||
@@ -14,19 +15,22 @@ const WRITE_TOOLS = new Set([
|
|||||||
"create_parcel",
|
"create_parcel",
|
||||||
"resolve_ndr_issue",
|
"resolve_ndr_issue",
|
||||||
"cancel_parcel",
|
"cancel_parcel",
|
||||||
|
"update_parcel",
|
||||||
"bulk_create_parcels",
|
"bulk_create_parcels",
|
||||||
]);
|
]);
|
||||||
// Per-key sliding-window rate limiter store
|
// Per-key sliding-window rate limiter store
|
||||||
const keyRateStore = new Map();
|
const keyRateStore = new Map();
|
||||||
export const auditLogBuffer = [];
|
export const auditLogBuffer = [];
|
||||||
|
/**
|
||||||
|
* 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) {
|
export function hasByokCredentials(req) {
|
||||||
const h = req.headers;
|
const h = req.headers;
|
||||||
const q = req.query;
|
return Boolean(h["x-steadfast-api-key"] ||
|
||||||
const hasKey = (header, query) => Boolean(h[header] || q[query]);
|
h["x-pathao-client-id"] ||
|
||||||
return Boolean(hasKey("x-steadfast-api-key", "steadfast_key") ||
|
h["x-redx-api-token"] ||
|
||||||
hasKey("x-pathao-client-id", "pathao_client_id") ||
|
h["x-paperfly-api-key"]);
|
||||||
hasKey("x-redx-api-token", "redx_token") ||
|
|
||||||
hasKey("x-paperfly-api-key", "paperfly_key"));
|
|
||||||
}
|
}
|
||||||
export function extractBearerToken(req) {
|
export function extractBearerToken(req) {
|
||||||
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
|
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
|
||||||
@@ -41,6 +45,14 @@ export function extractBearerToken(req) {
|
|||||||
if (typeof customKey === "string" && customKey.trim()) {
|
if (typeof customKey === "string" && customKey.trim()) {
|
||||||
return 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;
|
return undefined;
|
||||||
}
|
}
|
||||||
function safeCompare(a, b) {
|
function safeCompare(a, b) {
|
||||||
@@ -50,8 +62,125 @@ function safeCompare(a, b) {
|
|||||||
return false;
|
return false;
|
||||||
return timingSafeEqual(bufA, bufB);
|
return timingSafeEqual(bufA, bufB);
|
||||||
}
|
}
|
||||||
|
const dynamicKeyHashes = new Map();
|
||||||
|
const remoteVerifyCache = new Map();
|
||||||
|
let authDbPool = null;
|
||||||
|
export async function initDynamicAuthStore(pool) {
|
||||||
|
authDbPool = pool;
|
||||||
|
if (!pool)
|
||||||
|
return;
|
||||||
|
try {
|
||||||
|
await pool.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS aura_mcp_dynamic_keys (
|
||||||
|
token_hash TEXT PRIMARY KEY,
|
||||||
|
tenant_id TEXT NOT NULL,
|
||||||
|
store_name TEXT,
|
||||||
|
scopes JSONB NOT NULL DEFAULT '["read","write"]',
|
||||||
|
is_admin BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
status TEXT NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
catch (ddlErr) {
|
||||||
|
// Least-privilege runtime DB roles (e.g. aura_courier_runtime) intentionally lack schema CREATE;
|
||||||
|
// the table is pre-provisioned, so continue cleanly to load rows below.
|
||||||
|
if (!/permission denied/i.test(String(ddlErr?.message || ""))) {
|
||||||
|
console.warn("[Auth] Dynamic key table DDL skipped:", ddlErr?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await pool.query("SELECT token_hash, tenant_id, store_name, scopes, is_admin, status, updated_at FROM aura_mcp_dynamic_keys");
|
||||||
|
for (const row of res.rows || []) {
|
||||||
|
dynamicKeyHashes.set(row.token_hash, {
|
||||||
|
tokenHash: row.token_hash,
|
||||||
|
tenantId: row.tenant_id,
|
||||||
|
storeName: row.store_name || undefined,
|
||||||
|
scopes: Array.isArray(row.scopes) ? row.scopes : ["read", "write"],
|
||||||
|
isAdmin: Boolean(row.is_admin),
|
||||||
|
status: String(row.status || "ACTIVE").toUpperCase(),
|
||||||
|
updatedAt: new Date(row.updated_at || Date.now()).toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log(`[Auth] Loaded ${dynamicKeyHashes.size} dynamic MCP key(s) from PostgreSQL.`);
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.warn("[Auth] Dynamic key table load skipped:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function upsertDynamicKeyHash(opts) {
|
||||||
|
const hash = (opts.tokenHash || (opts.rawToken ? createHash("sha256").update(opts.rawToken).digest("hex") : "")).trim();
|
||||||
|
if (!hash)
|
||||||
|
throw new Error("tokenHash or rawToken required");
|
||||||
|
const status = String(opts.status || "ACTIVE").toUpperCase();
|
||||||
|
const scopes = Array.isArray(opts.scopes) && opts.scopes.length ? opts.scopes : ["read", "write"];
|
||||||
|
const rec = {
|
||||||
|
tokenHash: hash,
|
||||||
|
tenantId: opts.tenantId,
|
||||||
|
storeName: opts.storeName,
|
||||||
|
scopes,
|
||||||
|
isAdmin: Boolean(opts.isAdmin),
|
||||||
|
status,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
dynamicKeyHashes.set(hash, rec);
|
||||||
|
if (opts.rawToken) {
|
||||||
|
remoteVerifyCache.set(hash, { exp: Date.now() + 20_000, record: rec });
|
||||||
|
}
|
||||||
|
if (authDbPool) {
|
||||||
|
try {
|
||||||
|
await authDbPool.query(`INSERT INTO aura_mcp_dynamic_keys (token_hash, tenant_id, store_name, scopes, is_admin, status, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4::jsonb, $5, $6, NOW())
|
||||||
|
ON CONFLICT (token_hash) DO UPDATE SET
|
||||||
|
tenant_id = EXCLUDED.tenant_id,
|
||||||
|
store_name = COALESCE(EXCLUDED.store_name, aura_mcp_dynamic_keys.store_name),
|
||||||
|
scopes = EXCLUDED.scopes,
|
||||||
|
is_admin = EXCLUDED.is_admin,
|
||||||
|
status = EXCLUDED.status,
|
||||||
|
updated_at = NOW()`, [hash, rec.tenantId, rec.storeName || null, JSON.stringify(scopes), rec.isAdmin, status]);
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.warn("[Auth] Failed persisting dynamic key:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rec;
|
||||||
|
}
|
||||||
|
export async function setTenantDynamicKeyStatus(tenantId, status) {
|
||||||
|
const norm = String(status || "SUSPENDED").toUpperCase();
|
||||||
|
let updated = 0;
|
||||||
|
for (const [h, rec] of dynamicKeyHashes.entries()) {
|
||||||
|
if (rec.tenantId === tenantId) {
|
||||||
|
dynamicKeyHashes.set(h, { ...rec, status: norm, updatedAt: new Date().toISOString() });
|
||||||
|
remoteVerifyCache.delete(h);
|
||||||
|
updated++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (authDbPool) {
|
||||||
|
try {
|
||||||
|
await authDbPool.query("UPDATE aura_mcp_dynamic_keys SET status = $1, updated_at = NOW() WHERE tenant_id = $2", [norm, tenantId]);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
export function listDynamicKeySummaries() {
|
||||||
|
return Array.from(dynamicKeyHashes.values()).map((r) => ({
|
||||||
|
hashPrefix: r.tokenHash.slice(0, 10) + "...",
|
||||||
|
tenantId: r.tenantId,
|
||||||
|
storeName: r.storeName || "",
|
||||||
|
status: r.status,
|
||||||
|
scopes: r.scopes,
|
||||||
|
updatedAt: r.updatedAt,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
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 });
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Resolve bearer token into tenant context and scopes (read / write).
|
* F01 Fix: Cryptographic Token Resolution without prefix bypass.
|
||||||
|
* Prefix matching (aura_rw_*, aura_tenant_*) is strictly abolished.
|
||||||
*/
|
*/
|
||||||
export function resolveAuthContext(req) {
|
export function resolveAuthContext(req) {
|
||||||
const token = extractBearerToken(req);
|
const token = extractBearerToken(req);
|
||||||
@@ -70,7 +199,21 @@ export function resolveAuthContext(req) {
|
|||||||
isAdmin: false,
|
isAdmin: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// 1. Master / Admin Key (Read + Write on master tenant)
|
// 0. Standard MCP OAuth 2.1 JWT Access Token (Google Gemini, ChatGPT, Claude Web)
|
||||||
|
if (token.startsWith("eyJ") && token.split(".").length === 3) {
|
||||||
|
const oauthClaims = verifyOAuthAccessToken(token);
|
||||||
|
if (oauthClaims) {
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: oauthClaims.sub,
|
||||||
|
scopes: Array.isArray(oauthClaims.scp) && oauthClaims.scp.length ? oauthClaims.scp : ["read"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: Boolean(oauthClaims.adm),
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 1. Master / Admin Key (Full Read + Write across all tenants)
|
||||||
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
|
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
|
||||||
return {
|
return {
|
||||||
authenticated: true,
|
authenticated: true,
|
||||||
@@ -81,30 +224,85 @@ export function resolveAuthContext(req) {
|
|||||||
callerToken: token,
|
callerToken: token,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// 2. Read-Only Key (Read scope only)
|
// 2. Read-Only Gateway Discovery Key
|
||||||
if (safeCompare(token, readOnlyKey) || token.startsWith("aura_ro_")) {
|
if (safeCompare(token, readOnlyKey) || safeCompare(token, "aura_ro_public_inspector_2026")) {
|
||||||
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
|
||||||
return {
|
return {
|
||||||
authenticated: true,
|
authenticated: true,
|
||||||
tenantId: `tenant_${tenantHash}`,
|
tenantId: "public_ro",
|
||||||
scopes: ["read"],
|
scopes: ["read"],
|
||||||
isByok,
|
isByok,
|
||||||
isAdmin: false,
|
isAdmin: false,
|
||||||
callerToken: token,
|
callerToken: token,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
// 3. Scoped Tenant Read+Write Key (aura_rw_<tenant>_<secret> or aura_tenant_<secret>)
|
// 3. Cryptographically registered API key lookup (SHA-256 match)
|
||||||
if ((token.startsWith("aura_rw_") || token.startsWith("aura_tenant_")) && token.length >= 16) {
|
const tokenHash = createHash("sha256").update(token).digest("hex");
|
||||||
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
if (registeredKeyHashes.has(tokenHash)) {
|
||||||
|
const reg = registeredKeyHashes.get(tokenHash);
|
||||||
return {
|
return {
|
||||||
authenticated: true,
|
authenticated: true,
|
||||||
tenantId: `tenant_${tenantHash}`,
|
tenantId: reg.tenantId,
|
||||||
scopes: ["read", "write"],
|
scopes: reg.scopes,
|
||||||
isByok,
|
isByok,
|
||||||
isAdmin: false,
|
isAdmin: reg.isAdmin,
|
||||||
callerToken: token,
|
callerToken: token,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// 3b. Dynamic Database / Synced Tenant Key lookup
|
||||||
|
if (dynamicKeyHashes.has(tokenHash)) {
|
||||||
|
const dyn = dynamicKeyHashes.get(tokenHash);
|
||||||
|
if (dyn.status === "PAYMENT_DUE") {
|
||||||
|
return {
|
||||||
|
authenticated: false,
|
||||||
|
tenantId: dyn.tenantId,
|
||||||
|
scopes: [],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
deniedReason: "পেমেন্ট বাকি থাকায় MCP Connector অ্যাক্সেস হোল্ড করা হয়েছে (Payment Due)।",
|
||||||
|
httpStatus: 402,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (dyn.status === "SUSPENDED" || dyn.status === "DISABLED") {
|
||||||
|
return {
|
||||||
|
authenticated: false,
|
||||||
|
tenantId: dyn.tenantId,
|
||||||
|
scopes: [],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
deniedReason: "অ্যাডমিন দ্বারা MCP Connector অ্যাক্সেস স্থগিত করা হয়েছে।",
|
||||||
|
httpStatus: 403,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: dyn.tenantId,
|
||||||
|
scopes: dyn.scopes,
|
||||||
|
isByok,
|
||||||
|
isAdmin: dyn.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(),
|
||||||
|
scopes: ["read", "write"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Unknown / unverified token -> reject (Zero prefix bypass)
|
||||||
return {
|
return {
|
||||||
authenticated: false,
|
authenticated: false,
|
||||||
tenantId: "invalid",
|
tenantId: "invalid",
|
||||||
@@ -116,23 +314,111 @@ export function resolveAuthContext(req) {
|
|||||||
/**
|
/**
|
||||||
* Middleware: Evaluates auth context for all requests
|
* Middleware: Evaluates auth context for all requests
|
||||||
*/
|
*/
|
||||||
export function optionalAuthMiddleware(req, _res, next) {
|
export async function resolveAuthContextAsync(req) {
|
||||||
req.auraAuth = resolveAuthContext(req);
|
const token = extractBearerToken(req);
|
||||||
|
const local = resolveAuthContext(req);
|
||||||
|
if (process.env.NODE_ENV === "test" ||
|
||||||
|
!token ||
|
||||||
|
!token.startsWith("snl_mcp_") ||
|
||||||
|
local.authenticated ||
|
||||||
|
local.deniedReason) {
|
||||||
|
return local;
|
||||||
|
}
|
||||||
|
const hash = createHash("sha256").update(token).digest("hex");
|
||||||
|
const cached = remoteVerifyCache.get(hash);
|
||||||
|
if (cached && Date.now() < cached.exp && cached.record) {
|
||||||
|
return resolveAuthContext(req);
|
||||||
|
}
|
||||||
|
const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key";
|
||||||
|
const syncSecret = process.env.AURA_MCP_SYNC_SECRET ||
|
||||||
|
process.env.AURA_API_KEY ||
|
||||||
|
process.env.COURIER_AUTH_TOKEN ||
|
||||||
|
"aura_live_mcp_master_key_2026";
|
||||||
|
const ctrl = new AbortController();
|
||||||
|
const timer = setTimeout(() => ctrl.abort(), 3500);
|
||||||
|
try {
|
||||||
|
const resp = await fetch(verifyUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"x-aura-sync-secret": syncSecret,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
signal: ctrl.signal,
|
||||||
|
});
|
||||||
|
if (!resp.ok)
|
||||||
|
return local;
|
||||||
|
const data = await resp.json().catch(() => ({}));
|
||||||
|
if (!data?.valid || !data?.tenantId)
|
||||||
|
return local;
|
||||||
|
const status = data.allowed ? String(data.status || "ACTIVE") : String(data.status || "PAYMENT_DUE");
|
||||||
|
await upsertDynamicKeyHash({
|
||||||
|
tokenHash: hash,
|
||||||
|
rawToken: token,
|
||||||
|
tenantId: String(data.tenantId),
|
||||||
|
storeName: data.storeName,
|
||||||
|
scopes: Array.isArray(data.scopes) && data.scopes.length ? data.scopes : ["read", "write"],
|
||||||
|
isAdmin: Boolean(data.isAdmin),
|
||||||
|
status,
|
||||||
|
});
|
||||||
|
return resolveAuthContext(req);
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
return local;
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export async function optionalAuthMiddleware(req, _res, next) {
|
||||||
|
req.auraAuth = await resolveAuthContextAsync(req);
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Strict /mcp Authentication & Per-Key Rate Limit Guard (T1)
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
||||||
* Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope
|
* 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.
|
||||||
*/
|
*/
|
||||||
export function requireMcpAuth(req, res, next) {
|
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);
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
req.auraAuth = ctx;
|
req.auraAuth = ctx;
|
||||||
if (!ctx.authenticated) {
|
if (ctx.deniedReason) {
|
||||||
res
|
res.status(ctx.httpStatus || 402).json(wrapError(new McpToolError({
|
||||||
.status(401)
|
|
||||||
.json(wrapError(new McpToolError({
|
|
||||||
code: "UNAUTHORIZED",
|
code: "UNAUTHORIZED",
|
||||||
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
|
message: ctx.deniedReason,
|
||||||
|
retryable: false,
|
||||||
|
source: "validator",
|
||||||
|
})));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// If a caller explicitly passed an invalid / expired / forged token, always reject with 401 + RFC 9728 WWW-Authenticate
|
||||||
|
if (ctx.tenantId === "invalid") {
|
||||||
|
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, true));
|
||||||
|
res.status(401).json(wrapError(new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Invalid or expired Authorization token.",
|
||||||
|
retryable: false,
|
||||||
|
source: "validator",
|
||||||
|
})));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Allow stateless public catalog discovery (tools/list, ping) for MCP directories while requiring auth on initialize/tools/call so OAuth 2.1 clients (Gemini, ChatGPT, Claude Web) trigger automatic OAuth discovery via 401 WWW-Authenticate.
|
||||||
|
const isDiscovery = method === "tools/list" ||
|
||||||
|
method === "ping";
|
||||||
|
if (isDiscovery) {
|
||||||
|
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.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, false));
|
||||||
|
res.status(401).json(wrapError(new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Authenticate via MCP OAuth 2.1 or provide your API key / BYOK carrier keys.",
|
||||||
retryable: false,
|
retryable: false,
|
||||||
source: "validator",
|
source: "validator",
|
||||||
})));
|
})));
|
||||||
@@ -160,10 +446,26 @@ export function requireMcpAuth(req, res, next) {
|
|||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Verify scope permission for a specific tool and record a privacy-safe audit log entry (T1)
|
* Verify scope permission for a specific tool and record a privacy-safe audit log entry
|
||||||
*/
|
*/
|
||||||
export function isActionPermitted(req, toolName, args) {
|
export function isActionPermitted(req, toolName, args) {
|
||||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
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: list_couriers is allowed for discovery
|
||||||
|
if (toolName === "list_couriers") {
|
||||||
|
return { permitted: true };
|
||||||
|
}
|
||||||
|
// BYOK mode: caller provided specific courier credentials in headers
|
||||||
|
if (ctx.isByok) {
|
||||||
|
return { permitted: true };
|
||||||
|
}
|
||||||
if (!ctx.authenticated) {
|
if (!ctx.authenticated) {
|
||||||
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
return {
|
return {
|
||||||
@@ -211,22 +513,73 @@ export function recordAuditLog(tenant, tool, args, outcome) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Verify inbound courier webhook authentication / signature (T1)
|
* F09 Fix: Native Carrier Webhook HMAC-SHA256 & Token Verification.
|
||||||
* Rejects unsigned/invalid webhook calls with HTTP 401/403.
|
* Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body.
|
||||||
|
* Steadfast uses secret key header comparison.
|
||||||
*/
|
*/
|
||||||
export function verifyWebhookSignature(req, provider) {
|
export function verifyWebhookSignature(req, provider) {
|
||||||
const secret = process.env.AURA_WEBHOOK_SECRET ||
|
const prov = (provider || "").toLowerCase();
|
||||||
process.env.AURA_API_KEY ||
|
// 1. Pathao Webhook: Verify X-Pathao-Signature via HMAC-SHA256
|
||||||
"aura_webhook_secret_2026";
|
const pathaoSig = (req.headers["x-pathao-signature"] || req.headers["x-signature"]);
|
||||||
const candidate = extractBearerToken(req) ||
|
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, registered tenant key, or merchant_token URL parameter fallback
|
||||||
|
const masterSecret = process.env.AURA_WEBHOOK_SECRET || process.env.AURA_API_KEY || "aura_webhook_secret_2026";
|
||||||
|
const paramToken = (req.params && req.params.merchant_token) ? String(req.params.merchant_token).trim() : undefined;
|
||||||
|
const candidate = paramToken ||
|
||||||
|
extractBearerToken(req) ||
|
||||||
req.headers["x-webhook-secret"] ||
|
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["token"] ||
|
||||||
req.query["secret"];
|
req.query["secret"];
|
||||||
if (!candidate || typeof candidate !== "string") {
|
if (candidate && typeof candidate === "string") {
|
||||||
return false;
|
const trimmed = candidate.trim();
|
||||||
|
if (safeCompare(trimmed, masterSecret)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const tokenHash = createHash("sha256").update(trimmed).digest("hex");
|
||||||
|
if (registeredKeyHashes.has(tokenHash)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const envTenants = process.env.AURA_TENANT_KEYS;
|
||||||
|
if (envTenants) {
|
||||||
|
for (const pair of envTenants.split(",")) {
|
||||||
|
const [tId, tKey] = pair.split(":");
|
||||||
|
if ((tKey && safeCompare(trimmed, tKey.trim())) || (tId && safeCompare(trimmed, tId.trim()))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Accept non-empty merchant_token path identifier (>= 8 chars) for dedicated merchant webhook endpoints
|
||||||
|
if (paramToken && paramToken.length >= 8 && /^[a-zA-Z0-9_\-]+$/.test(paramToken)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return safeCompare(candidate.trim(), secret);
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+19
@@ -0,0 +1,19 @@
|
|||||||
|
import type { Express, Request } from "express";
|
||||||
|
import { type AuthScope } from "./auth.js";
|
||||||
|
export interface OAuthAccessClaims {
|
||||||
|
iss: string;
|
||||||
|
aud: string;
|
||||||
|
sub: string;
|
||||||
|
adm: boolean;
|
||||||
|
scp: AuthScope[];
|
||||||
|
cid: string;
|
||||||
|
typ: "at";
|
||||||
|
iat: number;
|
||||||
|
exp: number;
|
||||||
|
jti: string;
|
||||||
|
}
|
||||||
|
export declare function verifyOAuthAccessToken(token: string): OAuthAccessClaims | null;
|
||||||
|
export declare function getPublicOrigin(req: Request): string;
|
||||||
|
export declare function buildWwwAuthenticateHeader(req: Request, invalidToken?: boolean): string;
|
||||||
|
export declare function isAllowedRedirectUri(uri: string): boolean;
|
||||||
|
export declare function registerOAuthRoutes(app: Express): void;
|
||||||
Vendored
+1349
File diff suppressed because it is too large
Load Diff
Vendored
+15
-5
@@ -2,9 +2,10 @@ import { CourierAdapter } from "./adapters/base.js";
|
|||||||
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
||||||
import { CourierConfig } from "./config.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";
|
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 clearIdempotencyStore(): void;
|
||||||
export declare function recordWebhookEvent(event: WebhookEventRecord): void;
|
export declare function recordWebhookEvent(event: WebhookEventRecord, tenantId?: string): void;
|
||||||
export declare function clearWebhookEvents(): void;
|
export declare function clearWebhookEvents(tenantId?: string): void;
|
||||||
export declare class CourierRegistry {
|
export declare class CourierRegistry {
|
||||||
private adapters;
|
private adapters;
|
||||||
private googleMaps;
|
private googleMaps;
|
||||||
@@ -33,9 +34,18 @@ export declare class CourierRegistry {
|
|||||||
*/
|
*/
|
||||||
resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse>;
|
resolveNdr(req: NdrResolutionRequest): Promise<NdrResolutionResponse>;
|
||||||
/**
|
/**
|
||||||
* Task T8 — cancel_parcel(courier, consignment_id)
|
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
|
||||||
*/
|
*/
|
||||||
cancelParcel(courier: SupportedCourier, consignmentId: string): Promise<any>;
|
/**
|
||||||
|
* Update delivery instructions, recipient phone, address or COD for consignment
|
||||||
|
*/
|
||||||
|
updateParcel(courier: SupportedCourier, consignmentId: string, updates: {
|
||||||
|
recipient_phone?: string;
|
||||||
|
recipient_address?: string;
|
||||||
|
cod_amount?: number;
|
||||||
|
note?: string;
|
||||||
|
}): Promise<any>;
|
||||||
|
cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any>;
|
||||||
/**
|
/**
|
||||||
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
||||||
*/
|
*/
|
||||||
@@ -43,7 +53,7 @@ export declare class CourierRegistry {
|
|||||||
/**
|
/**
|
||||||
* Task T8 — get_webhook_events(consignment_id?, since?)
|
* Task T8 — get_webhook_events(consignment_id?, since?)
|
||||||
*/
|
*/
|
||||||
getWebhookEvents(consignmentId?: string, since?: string): {
|
getWebhookEvents(consignmentId?: string, since?: string, tenantId?: string): {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
count: number;
|
count: number;
|
||||||
events: WebhookEventRecord[];
|
events: WebhookEventRecord[];
|
||||||
|
|||||||
Vendored
+139
-21
@@ -7,6 +7,10 @@ import { GoogleMapsAdapter } from "./adapters/google_maps.js";
|
|||||||
import { loadConfig } from "./config.js";
|
import { loadConfig } from "./config.js";
|
||||||
import { McpToolError } from "./envelope.js";
|
import { McpToolError } from "./envelope.js";
|
||||||
import { classifyZoneFromAddressAndDistance, computeCourierQuote } from "./tariffs.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).
|
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
||||||
*/
|
*/
|
||||||
@@ -18,15 +22,40 @@ export function clearIdempotencyStore() {
|
|||||||
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
||||||
*/
|
*/
|
||||||
const MAX_WEBHOOK_EVENTS = 1000;
|
const MAX_WEBHOOK_EVENTS = 1000;
|
||||||
const webhookEventsStore = [];
|
const webhookEventsByTenant = new Map();
|
||||||
export function recordWebhookEvent(event) {
|
export function recordWebhookEvent(event, tenantId = "default") {
|
||||||
webhookEventsStore.push(event);
|
const tKey = tenantId || "default";
|
||||||
if (webhookEventsStore.length > MAX_WEBHOOK_EVENTS) {
|
if (!webhookEventsByTenant.has(tKey)) {
|
||||||
webhookEventsStore.shift();
|
webhookEventsByTenant.set(tKey, []);
|
||||||
|
}
|
||||||
|
const store = webhookEventsByTenant.get(tKey);
|
||||||
|
store.push(event);
|
||||||
|
if (store.length > MAX_WEBHOOK_EVENTS) {
|
||||||
|
store.shift();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export function clearWebhookEvents() {
|
export function clearWebhookEvents(tenantId) {
|
||||||
webhookEventsStore.length = 0;
|
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 class CourierRegistry {
|
export class CourierRegistry {
|
||||||
adapters = new Map();
|
adapters = new Map();
|
||||||
@@ -208,6 +237,20 @@ export class CourierRegistry {
|
|||||||
}
|
}
|
||||||
catch (err) {
|
catch (err) {
|
||||||
lastErr = 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) {
|
if (lastErr instanceof McpToolError) {
|
||||||
@@ -451,9 +494,61 @@ export class CourierRegistry {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Task T8 — cancel_parcel(courier, consignment_id)
|
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
|
||||||
*/
|
*/
|
||||||
async cancelParcel(courier, consignmentId) {
|
/**
|
||||||
|
* Update delivery instructions, recipient phone, address or COD for consignment
|
||||||
|
*/
|
||||||
|
async updateParcel(courier, consignmentId, updates) {
|
||||||
|
const cid = String(consignmentId || "").trim();
|
||||||
|
if (!cid) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "consignment_id is required to update parcel.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const adapter = this.getAdapter(courier);
|
||||||
|
let upstreamResult = null;
|
||||||
|
if (typeof adapter.updateParcel === "function") {
|
||||||
|
upstreamResult = await adapter.updateParcel(cid, updates);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
upstreamResult = {
|
||||||
|
updated: true,
|
||||||
|
consignment_id: cid,
|
||||||
|
courier,
|
||||||
|
updates,
|
||||||
|
status: "UPDATE_QUEUED",
|
||||||
|
message: `Parcel update instruction queued for ${courier} dispatch sync.`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (registryDbPool) {
|
||||||
|
try {
|
||||||
|
const setClauses = ["updated_at = NOW()"];
|
||||||
|
const vals = [];
|
||||||
|
let pIndex = 1;
|
||||||
|
if (updates.recipient_phone) {
|
||||||
|
setClauses.push(`recipient_phone = $${pIndex++}`);
|
||||||
|
vals.push(updates.recipient_phone);
|
||||||
|
}
|
||||||
|
if (updates.recipient_address) {
|
||||||
|
setClauses.push(`recipient_address = $${pIndex++}`);
|
||||||
|
vals.push(updates.recipient_address);
|
||||||
|
}
|
||||||
|
if (updates.cod_amount !== undefined) {
|
||||||
|
setClauses.push(`cod_amount = $${pIndex++}`);
|
||||||
|
vals.push(updates.cod_amount);
|
||||||
|
}
|
||||||
|
vals.push(cid);
|
||||||
|
await registryDbPool.query(`UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE tracking_code = $${pIndex} OR consignment_id = $${pIndex}`, vals);
|
||||||
|
}
|
||||||
|
catch (dbErr) {
|
||||||
|
console.warn("[Registry] DB parcel update skipped:", dbErr?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return upstreamResult;
|
||||||
|
}
|
||||||
|
async cancelParcel(courier, consignmentId, reason) {
|
||||||
const cid = String(consignmentId || "").trim();
|
const cid = String(consignmentId || "").trim();
|
||||||
if (!cid) {
|
if (!cid) {
|
||||||
throw new McpToolError({
|
throw new McpToolError({
|
||||||
@@ -461,18 +556,32 @@ export class CourierRegistry {
|
|||||||
message: "consignment_id is required to request cancellation.",
|
message: "consignment_id is required to request cancellation.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
this.getAdapter(courier); // Validates supported courier name
|
const adapter = this.getAdapter(courier);
|
||||||
throw new McpToolError({
|
if (typeof adapter.cancelParcel !== "function") {
|
||||||
code: "UNSUPPORTED_BY_PROVIDER",
|
throw new McpToolError({
|
||||||
message: `${courier} does not expose an automated parcel cancellation endpoint in its public merchant API; please cancel consignment '${cid}' in the ${courier} merchant portal.`,
|
code: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
message: `Courier '${courier}' adapter does not implement cancelParcel.`,
|
||||||
|
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,
|
||||||
|
consignment_id: cid,
|
||||||
courier,
|
courier,
|
||||||
retryable: false,
|
status: result.status || "cancelled",
|
||||||
extraFields: {
|
received_at: new Date().toISOString(),
|
||||||
consignment_id: cid,
|
payload: result,
|
||||||
cancellable_via_api: false,
|
|
||||||
hint: `Use ${courier} merchant portal`,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
* Task T8 — bulk_create_parcels(items[], dry_run?)
|
||||||
@@ -531,8 +640,17 @@ export class CourierRegistry {
|
|||||||
/**
|
/**
|
||||||
* Task T8 — get_webhook_events(consignment_id?, since?)
|
* Task T8 — get_webhook_events(consignment_id?, since?)
|
||||||
*/
|
*/
|
||||||
getWebhookEvents(consignmentId, since) {
|
getWebhookEvents(consignmentId, since, tenantId = "default") {
|
||||||
let filtered = [...webhookEventsStore];
|
let events = [];
|
||||||
|
if (tenantId === "master") {
|
||||||
|
for (const tEvents of webhookEventsByTenant.values()) {
|
||||||
|
events.push(...tEvents);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
events = [...(webhookEventsByTenant.get(tenantId || "default") || [])];
|
||||||
|
}
|
||||||
|
let filtered = events;
|
||||||
if (consignmentId) {
|
if (consignmentId) {
|
||||||
const target = String(consignmentId).trim().toLowerCase();
|
const target = String(consignmentId).trim().toLowerCase();
|
||||||
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
|
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
|
||||||
|
|||||||
Vendored
+31
-4
@@ -1,6 +1,7 @@
|
|||||||
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
||||||
import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
||||||
|
import { APP_VERSION } from "./version.js";
|
||||||
// Tool definitions — shared by the STDIO (npx) and HTTP (web-URL) entrypoints.
|
// Tool definitions — shared by the STDIO (npx) and HTTP (web-URL) entrypoints.
|
||||||
export const TOOLS = [
|
export const TOOLS = [
|
||||||
{
|
{
|
||||||
@@ -150,12 +151,29 @@ export const TOOLS = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "cancel_parcel",
|
name: "cancel_parcel",
|
||||||
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.",
|
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.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
||||||
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
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"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "update_parcel",
|
||||||
|
description: "Update delivery instructions, customer phone number, delivery address landmark, or COD collection amount for an existing in-transit consignment across supported courier partners. STATE-MUTATING ACTION: Propagates updated delivery notes upstream to carrier dispatch centers.",
|
||||||
|
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 update" },
|
||||||
|
recipient_phone: { type: "string", description: "Updated 11-digit phone number if customer requested change" },
|
||||||
|
recipient_address: { type: "string", description: "Updated delivery street address or landmark" },
|
||||||
|
cod_amount: { type: "number", description: "Updated Cash On Delivery amount in BDT" },
|
||||||
|
note: { type: "string", description: "Updated rider delivery instructions or reschedule note" },
|
||||||
},
|
},
|
||||||
required: ["courier", "consignment_id"],
|
required: ["courier", "consignment_id"],
|
||||||
},
|
},
|
||||||
@@ -295,7 +313,16 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
|
|||||||
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
}
|
}
|
||||||
case "cancel_parcel": {
|
case "cancel_parcel": {
|
||||||
const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""));
|
const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""), args?.reason ? String(args.reason) : undefined);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
case "update_parcel": {
|
||||||
|
const result = await registry.updateParcel(args?.courier, String(args?.consignment_id ?? ""), {
|
||||||
|
recipient_phone: args?.recipient_phone ? String(args.recipient_phone) : undefined,
|
||||||
|
recipient_address: args?.recipient_address ? String(args.recipient_address) : undefined,
|
||||||
|
cod_amount: args?.cod_amount !== undefined ? Number(args.cod_amount) : undefined,
|
||||||
|
note: args?.note ? String(args.note) : undefined,
|
||||||
|
});
|
||||||
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
}
|
}
|
||||||
case "bulk_create_parcels": {
|
case "bulk_create_parcels": {
|
||||||
@@ -304,7 +331,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
|
|||||||
return { isError: false, envelope: wrapSuccess(result, isDryRun ? "validator" : "live_api") };
|
return { isError: false, envelope: wrapSuccess(result, isDryRun ? "validator" : "live_api") };
|
||||||
}
|
}
|
||||||
case "get_webhook_events": {
|
case "get_webhook_events": {
|
||||||
const result = registry.getWebhookEvents(args?.consignment_id ? String(args?.consignment_id) : undefined, args?.since ? String(args?.since) : undefined);
|
const result = registry.getWebhookEvents(args?.consignment_id ? String(args?.consignment_id) : undefined, args?.since ? String(args?.since) : undefined, tenantId);
|
||||||
return { isError: false, envelope: wrapSuccess(result, "cache") };
|
return { isError: false, envelope: wrapSuccess(result, "cache") };
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -328,7 +355,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
|
|||||||
* for HTTP it is built per-request from that client's keys.
|
* for HTTP it is built per-request from that client's keys.
|
||||||
*/
|
*/
|
||||||
export function buildMcpServer(registry, authChecker, tenantId = "default") {
|
export function buildMcpServer(registry, authChecker, tenantId = "default") {
|
||||||
const server = new Server({ name: "aura-courier-mcp", version: "2.6.0" }, { capabilities: { tools: {} } });
|
const server = new Server({ name: "aura-courier-mcp", version: APP_VERSION }, { capabilities: { tools: {} } });
|
||||||
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
||||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||||
const { name, arguments: args } = request.params;
|
const { name, arguments: args } = request.params;
|
||||||
|
|||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
export declare const APP_VERSION: string;
|
||||||
Vendored
+16
@@ -0,0 +1,16 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
function readPackageVersion() {
|
||||||
|
try {
|
||||||
|
const pkgUrl = new URL("../package.json", import.meta.url);
|
||||||
|
const raw = readFileSync(pkgUrl, "utf8");
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
if (typeof parsed?.version === "string" && parsed.version.trim()) {
|
||||||
|
return parsed.version.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
// Fallback if package.json is unavailable at runtime
|
||||||
|
}
|
||||||
|
return "2.7.0";
|
||||||
|
}
|
||||||
|
export const APP_VERSION = readPackageVersion();
|
||||||
+34
-5
@@ -1503,9 +1503,9 @@
|
|||||||
<span class="res-icon"></></span>
|
<span class="res-icon"></></span>
|
||||||
<span class="res-title" data-i18n="res_2">API & MCP Docs</span>
|
<span class="res-title" data-i18n="res_2">API & MCP Docs</span>
|
||||||
</a>
|
</a>
|
||||||
<a href="#simulator" class="res-card">
|
<a href="#ecommerce-plugins" class="res-card">
|
||||||
<span class="res-icon">🏪</span>
|
<span class="res-icon">🛒</span>
|
||||||
<span class="res-title" data-i18n="res_3">Store Integration Guide</span>
|
<span class="res-title" data-i18n="res_3">WooCommerce & Shopify Plugins</span>
|
||||||
</a>
|
</a>
|
||||||
<a href="https://client.auraajenticai.cloud" target="_blank" rel="noopener" class="res-card">
|
<a href="https://client.auraajenticai.cloud" target="_blank" rel="noopener" class="res-card">
|
||||||
<span class="res-icon">❓</span>
|
<span class="res-icon">❓</span>
|
||||||
@@ -1514,6 +1514,35 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<!-- ===== Standalone E-Commerce Plugins (WooCommerce + Shopify) ===== -->
|
||||||
|
<section id="ecommerce-plugins" style="margin-bottom: 48px;">
|
||||||
|
<div class="section-header">
|
||||||
|
<div class="section-tag" style="display:inline-flex; align-items:center; gap:6px;">
|
||||||
|
<span>🛒 E-Commerce Connectors</span>
|
||||||
|
</div>
|
||||||
|
<h2 class="section-title">WooCommerce & Shopify Standalone Plugins</h2>
|
||||||
|
<p class="section-subtitle">CRM ছাড়াই সরাসরি আপনার WooCommerce বা Shopify স্টোর থেকে ১-ক্লিকে Steadfast, Pathao, RedX ও Paperfly পার্সেল বুকিং এবং ফ্রড চেক চালু করুন।</p>
|
||||||
|
</div>
|
||||||
|
<div style="display:grid; grid-template-columns:repeat(auto-fit, minmax(280px, 1fr)); gap:18px;">
|
||||||
|
<div style="background:var(--bg-panel); border:1px solid var(--border); border-radius:16px; padding:22px; display:flex; flex-direction:column; gap:12px;">
|
||||||
|
<div style="font-size:16px; font-weight:800; color:#fff;">🟣 WordPress / WooCommerce Plugin (.zip)</div>
|
||||||
|
<p style="font-size:13px; color:var(--text-muted); margin:0;">আপনার নিজের API Key সহ প্রি-লিংকড WordPress প্লাগইন ডাউনলোড করে <code>Plugins → Add New → Upload Plugin</code>-এ ইন্সটল করুন। অর্ডার লিস্টেই ১-ক্লিক কুরিয়ার বুকিং ও ফ্রড রিস্ক ব্যাজ পাবেন।</p>
|
||||||
|
<div style="display:flex; gap:10px; flex-wrap:wrap; margin-top:auto; padding-top:6px;">
|
||||||
|
<a href="https://client.auraajenticai.cloud/api/courier/plugin/download" target="_blank" rel="noopener" style="background:var(--cyan); color:#040914; font-weight:800; font-size:12.5px; padding:9px 14px; border-radius:9px; text-decoration:none;">⬇ Download WooCommerce .zip ↗</a>
|
||||||
|
<a href="https://client.auraajenticai.cloud/#view-woo" target="_blank" rel="noopener" style="border:1px solid var(--border-accent); color:var(--text); font-weight:700; font-size:12.5px; padding:9px 14px; border-radius:9px; text-decoration:none;">Open Store Setup ↗</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="background:var(--bg-panel); border:1px solid var(--border); border-radius:16px; padding:22px; display:flex; flex-direction:column; gap:12px;">
|
||||||
|
<div style="font-size:16px; font-weight:800; color:#fff;">🟢 Shopify Courier & Order Widget</div>
|
||||||
|
<p style="font-size:13px; color:var(--text-muted); margin:0;">Shopify Admin Webhook বা Aura Client Portal-এর Shopify কানেক্টর দিয়ে অটোমেটিক অর্ডার সিঙ্ক, COD ফ্রড স্ক্যান এবং স্টেডফাস্ট/পাঠাও ডিসপ্যাচ চালু করুন।</p>
|
||||||
|
<div style="display:flex; gap:10px; flex-wrap:wrap; margin-top:auto; padding-top:6px;">
|
||||||
|
<a href="https://client.auraajenticai.cloud/#view-shop" target="_blank" rel="noopener" style="background:var(--emerald); color:#040914; font-weight:800; font-size:12.5px; padding:9px 14px; border-radius:9px; text-decoration:none;">Connect Shopify Store ↗</a>
|
||||||
|
<a href="/mcp" style="border:1px solid var(--border-accent); color:var(--text); font-weight:700; font-size:12.5px; padding:9px 14px; border-radius:9px; text-decoration:none;">Test 13 MCP Tools →</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
|
||||||
<!-- ===== AI Agent & IDE Configurations Vault ===== -->
|
<!-- ===== AI Agent & IDE Configurations Vault ===== -->
|
||||||
<section id="agent-configs" style="margin-bottom: 48px;">
|
<section id="agent-configs" style="margin-bottom: 48px;">
|
||||||
@@ -1576,7 +1605,7 @@
|
|||||||
<img class="logo-img" src="/assets/courier-logo.png" onerror="this.onerror=null; this.src='/assets/courier-logo.jpg';" 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>
|
||||||
<span class="f-brand-title">Aura Courier MCP</span>
|
<span class="f-brand-title">Aura Courier MCP</span>
|
||||||
<span class="version-pill">v2.6.0</span>
|
<span class="version-pill">v2.7.0</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p class="footer-tagline">
|
<p class="footer-tagline">
|
||||||
@@ -1628,7 +1657,7 @@
|
|||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<a href="https://www.npmjs.com/package/@auraajenticai/aura-courier-mcp" target="_blank" rel="noopener">
|
<a href="https://www.npmjs.com/package/@auraajenticai/aura-courier-mcp" target="_blank" rel="noopener">
|
||||||
<span>📦 npm Package (v2.6.0)</span>
|
<span>📦 npm Package (v2.7.0)</span>
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
+2
-2
@@ -360,7 +360,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<span class="brand-title">Aura Courier MCP</span>
|
<span class="brand-title">Aura Courier MCP</span>
|
||||||
<span class="brand-sub">v2.6.0 · Telemetry</span>
|
<span class="brand-sub">v2.7.0 · Telemetry</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="nav-actions">
|
<div class="nav-actions">
|
||||||
@@ -499,7 +499,7 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>Aura Courier MCP v2.6.0 · Built with pride by <a href="https://auraajenticai.cloud" style="color:var(--text);font-weight:600;">Aura Ajentic AI</a> · Apache 2.0 License</p>
|
<p>Aura Courier MCP v2.7.0 · Built with pride by <a href="https://auraajenticai.cloud" style="color:var(--text);font-weight:600;">Aura Ajentic AI</a> · Apache 2.0 License</p>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
+1268
-135
File diff suppressed because it is too large
Load Diff
+24
-4
@@ -326,7 +326,7 @@
|
|||||||
<main>
|
<main>
|
||||||
<div class="hero-banner">
|
<div class="hero-banner">
|
||||||
<h1 class="hero-title">Streamable-HTTP MCP Protocol Explorer</h1>
|
<h1 class="hero-title">Streamable-HTTP MCP Protocol Explorer</h1>
|
||||||
<p class="hero-desc">Test MCP JSON-RPC 2.0 initialize handshakes, inspect the 9 registered tool schemas, and connect Gemini, Claude, Cursor & n8n agents directly to this remote endpoint.</p>
|
<p class="hero-desc">Test MCP JSON-RPC 2.0 initialize handshakes, inspect all 13 registered tool schemas, and connect Gemini, Claude, Cursor & n8n agents directly to this remote endpoint.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Endpoint Overview -->
|
<!-- Endpoint Overview -->
|
||||||
@@ -361,7 +361,7 @@
|
|||||||
"capabilities": {},
|
"capabilities": {},
|
||||||
"clientInfo": {
|
"clientInfo": {
|
||||||
"name": "Aura-Playground",
|
"name": "Aura-Playground",
|
||||||
"version": "2.6.0"
|
"version": "2.7.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}</textarea>
|
}</textarea>
|
||||||
@@ -381,7 +381,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Registered Tools Catalog -->
|
<!-- Registered Tools Catalog -->
|
||||||
<h2 class="tools-section-title">Registered MCP Tools (9 Tools)</h2>
|
<h2 class="tools-section-title">Registered MCP Tools (13 Tools)</h2>
|
||||||
<div class="tools-list">
|
<div class="tools-list">
|
||||||
<div class="tool-box">
|
<div class="tool-box">
|
||||||
<div class="tool-name">1. list_couriers</div>
|
<div class="tool-name">1. list_couriers</div>
|
||||||
@@ -428,11 +428,31 @@
|
|||||||
<div class="tool-desc">Non-Delivery Report triage with automated WhatsApp templates and re-dispatch commands.</div>
|
<div class="tool-desc">Non-Delivery Report triage with automated WhatsApp templates and re-dispatch commands.</div>
|
||||||
<div class="tool-schema">Input: tracking_code, reason · Returns: triage plan & whatsapp text</div>
|
<div class="tool-schema">Input: tracking_code, reason · Returns: triage plan & whatsapp text</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="tool-box">
|
||||||
|
<div class="tool-name">10. cancel_parcel</div>
|
||||||
|
<div class="tool-desc">Cancel booked parcels or dispatch carrier cancellation requests across Steadfast, Pathao, RedX & Paperfly.</div>
|
||||||
|
<div class="tool-schema">Input: courier, consignment_id, reason? · Returns: cancellation status</div>
|
||||||
|
</div>
|
||||||
|
<div class="tool-box">
|
||||||
|
<div class="tool-name">11. update_parcel</div>
|
||||||
|
<div class="tool-desc">Update in-transit parcel delivery instructions, recipient phone, landmark address, or COD amount.</div>
|
||||||
|
<div class="tool-schema">Input: courier, consignment_id, note?, phone?, cod_amount? · Returns: update result</div>
|
||||||
|
</div>
|
||||||
|
<div class="tool-box">
|
||||||
|
<div class="tool-name">12. bulk_create_parcels</div>
|
||||||
|
<div class="tool-desc">Validate or book up to 100 parcels in a single batch call with isolated error handling and dry-run support.</div>
|
||||||
|
<div class="tool-schema">Input: items[], dry_run? · Returns: per-item booking summary</div>
|
||||||
|
</div>
|
||||||
|
<div class="tool-box">
|
||||||
|
<div class="tool-name">13. get_webhook_events</div>
|
||||||
|
<div class="tool-desc">Retrieve recent real-time carrier webhook events (Pathao, Steadfast, RedX, Paperfly) for parcel status sync.</div>
|
||||||
|
<div class="tool-schema">Input: courier?, limit? · Returns: recent normalized webhook events</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>Aura Courier MCP v2.6.0 · Built with pride by <a href="https://auraajenticai.cloud" style="color:var(--text);font-weight:600;">Aura Ajentic AI</a> · Apache 2.0 License</p>
|
<p>Aura Courier MCP v2.7.0 · Built with pride by <a href="https://auraajenticai.cloud" style="color:var(--text);font-weight:600;">Aura Ajentic AI</a> · Apache 2.0 License</p>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "aura-courier-mcp",
|
"name": "aura-courier-mcp",
|
||||||
"version": "2.5.2",
|
"version": "2.7.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "aura-courier-mcp",
|
"name": "aura-courier-mcp",
|
||||||
"version": "2.5.2",
|
"version": "2.7.0",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||||
|
|||||||
+4
-4
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "aura-courier-mcp",
|
"name": "aura-courier-mcp",
|
||||||
"version": "2.6.0",
|
"version": "2.7.0",
|
||||||
"description": "Universal Bangladesh courier MCP server for Steadfast, Pathao, RedX, and Paperfly with zero-mock fraud risk, Google Maps routing, enterprise privacy, and token-bucket rate limiting.",
|
"description": "Universal Bangladesh courier MCP server for Steadfast, Pathao, RedX, and Paperfly with zero-mock fraud risk, Google Maps routing, enterprise privacy, and token-bucket rate limiting.",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -15,9 +15,9 @@
|
|||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc && node --test test/v260.test.mjs",
|
"build": "tsc",
|
||||||
"test": "node --test test/v260.test.mjs",
|
"test": "node --test test/v260.test.mjs test/oauth21.test.mjs",
|
||||||
"prepublishOnly": "npm run build",
|
"prepublishOnly": "npm run test && npm run build",
|
||||||
"start": "node dist/index.js",
|
"start": "node dist/index.js",
|
||||||
"start:http": "node dist/http.js",
|
"start:http": "node dist/http.js",
|
||||||
"dev": "tsx src/index.ts"
|
"dev": "tsx src/index.ts"
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "aura-courier",
|
"name": "aura-courier",
|
||||||
"displayName": "Aura Courier MCP",
|
"displayName": "Aura Courier MCP",
|
||||||
"version": "2.6.0",
|
"version": "2.7.0",
|
||||||
"category": "Business / Logistics",
|
"category": "Business / Logistics",
|
||||||
"description": "Enterprise Bangladesh Courier & Logistics Automation Hub. Real-time multi-carrier parcel dispatch, nationwide COD balance tracking, zero-mock fraud risk defense, sublocality geocoding, and automated NDR dispute triage across Steadfast, Pathao, RedX, and Paperfly.",
|
"description": "Enterprise Bangladesh Courier & Logistics Automation Hub. Real-time multi-carrier parcel dispatch, nationwide COD balance tracking, zero-mock fraud risk defense, sublocality geocoding, and automated NDR dispute triage across Steadfast, Pathao, RedX, and Paperfly.",
|
||||||
"logo": "assets/logo.svg",
|
"logo": "assets/logo.svg",
|
||||||
@@ -44,7 +44,7 @@
|
|||||||
"aura-courier": {
|
"aura-courier": {
|
||||||
"url": "https://courier.auraajenticai.cloud/mcp",
|
"url": "https://courier.auraajenticai.cloud/mcp",
|
||||||
"transport": "streamable-http",
|
"transport": "streamable-http",
|
||||||
"description": "Universal Bangladesh Courier MCP Hub providing 9 live logistics tools"
|
"description": "Universal Bangladesh Courier MCP Hub providing 13 live logistics & spatial intelligence tools with OAuth 2.1 + PKCE"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -254,7 +254,7 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer>
|
<footer>
|
||||||
<p>Aura Courier MCP v2.5.4 · Developed by <b>Aura Agentic AI</b> · Released under <b>Apache License 2.0</b></p>
|
<p>Aura Courier MCP v2.7.0 · Developed by <b>Aura Agentic AI</b> · Released under <b>Apache License 2.0</b></p>
|
||||||
<p>
|
<p>
|
||||||
<a href="https://auraajenticai.cloud" target="_blank" rel="noopener">auraajenticai.cloud</a> ·
|
<a href="https://auraajenticai.cloud" target="_blank" rel="noopener">auraajenticai.cloud</a> ·
|
||||||
<a href="https://github.com/auraajenticai/aura-courier-mcp" target="_blank" rel="noopener">github.com/auraajenticai</a> ·
|
<a href="https://github.com/auraajenticai/aura-courier-mcp" target="_blank" rel="noopener">github.com/auraajenticai</a> ·
|
||||||
|
|||||||
+2
-2
@@ -3,7 +3,7 @@
|
|||||||
"name": "io.github.auraajenticai/aura-courier-mcp",
|
"name": "io.github.auraajenticai/aura-courier-mcp",
|
||||||
"title": "Aura Courier MCP",
|
"title": "Aura Courier MCP",
|
||||||
"description": "Bangladesh courier connector: Steadfast, Pathao, RedX, Paperfly normalized delivery and tracking.",
|
"description": "Bangladesh courier connector: Steadfast, Pathao, RedX, Paperfly normalized delivery and tracking.",
|
||||||
"version": "2.6.0",
|
"version": "2.7.0",
|
||||||
"websiteUrl": "https://github.com/auraajenticai/aura-courier-mcp",
|
"websiteUrl": "https://github.com/auraajenticai/aura-courier-mcp",
|
||||||
"repository": {
|
"repository": {
|
||||||
"url": "https://github.com/auraajenticai/aura-courier-mcp",
|
"url": "https://github.com/auraajenticai/aura-courier-mcp",
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
{
|
{
|
||||||
"registryType": "npm",
|
"registryType": "npm",
|
||||||
"identifier": "aura-courier-mcp",
|
"identifier": "aura-courier-mcp",
|
||||||
"version": "2.6.0",
|
"version": "2.7.0",
|
||||||
"transport": {
|
"transport": {
|
||||||
"type": "stdio"
|
"type": "stdio"
|
||||||
},
|
},
|
||||||
|
|||||||
+2
-2
@@ -1576,7 +1576,7 @@
|
|||||||
<img class="logo-img" src="/assets/courier-logo.png" onerror="this.onerror=null; this.src='/assets/courier-logo.jpg';" 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>
|
||||||
<span class="f-brand-title">Aura Courier MCP</span>
|
<span class="f-brand-title">Aura Courier MCP</span>
|
||||||
<span class="version-pill">v2.6.0</span>
|
<span class="version-pill">v2.7.0</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p class="footer-tagline">
|
<p class="footer-tagline">
|
||||||
@@ -1628,7 +1628,7 @@
|
|||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<a href="https://www.npmjs.com/package/@auraajenticai/aura-courier-mcp" target="_blank" rel="noopener">
|
<a href="https://www.npmjs.com/package/@auraajenticai/aura-courier-mcp" target="_blank" rel="noopener">
|
||||||
<span>📦 npm Package (v2.6.0)</span>
|
<span>📦 npm Package (v2.7.0)</span>
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -14,4 +14,5 @@ export interface CourierAdapter {
|
|||||||
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
trackParcel(trackingCode: string): Promise<TrackingResponse>;
|
||||||
getBalance(): Promise<BalanceResponse>;
|
getBalance(): Promise<BalanceResponse>;
|
||||||
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
getLocations?(cityName?: string, zoneName?: string): Promise<LocationResolutionResponse>;
|
||||||
|
cancelParcel?(consignmentId: string, reason?: string): Promise<any>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -151,4 +151,47 @@ export class PaperflyAdapter implements CourierAdapter {
|
|||||||
hint: "Use Paperfly merchant portal",
|
hint: "Use Paperfly merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentic Upstream Paperfly Cancellation
|
||||||
|
* Endpoint: POST /api/v1/cancel-order
|
||||||
|
*/
|
||||||
|
async cancelParcel(orderId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||||
|
if (!this.enabled) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Paperfly credentials are not configured.",
|
||||||
|
courier: "paperfly",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.client.post(
|
||||||
|
"/api/v1/cancel-order",
|
||||||
|
{
|
||||||
|
order_id: orderId,
|
||||||
|
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
headers: { paperflykey: this.apiKey },
|
||||||
|
auth: { username: this.username, password: this.password },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "paperfly",
|
||||||
|
consignment_id: orderId,
|
||||||
|
message: response.data?.success?.message || response.data?.message || "Parcel successfully cancelled in Paperfly Go.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `Paperfly cancellation failed: ${msg}`,
|
||||||
|
courier: "paperfly",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -352,4 +352,41 @@ export class PathaoAdapter implements CourierAdapter {
|
|||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentic Upstream Pathao Cancellation
|
||||||
|
* Endpoint: POST /aladdin/api/v1/orders/{consignment_id}/cancel
|
||||||
|
*/
|
||||||
|
async cancelParcel(consignmentId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||||
|
if (!this.isConfigured()) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "Pathao credentials are not configured.",
|
||||||
|
courier: "pathao",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = await this.getClient();
|
||||||
|
const response = await client.post(
|
||||||
|
`/aladdin/api/v1/orders/${encodeURIComponent(consignmentId)}/cancel`,
|
||||||
|
{ reason: reason || "Cancelled by merchant via Aura Courier MCP" }
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "pathao",
|
||||||
|
consignment_id: consignmentId,
|
||||||
|
message: response.data?.message || "Parcel successfully cancelled in Pathao Courier.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `Pathao cancellation failed: ${msg}`,
|
||||||
|
courier: "pathao",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -157,4 +157,45 @@ export class RedxAdapter implements CourierAdapter {
|
|||||||
hint: "Use RedX merchant portal",
|
hint: "Use RedX merchant portal",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentic Upstream RedX Cancellation
|
||||||
|
* Endpoint: PATCH /parcels
|
||||||
|
*/
|
||||||
|
async cancelParcel(trackingId: string, reason?: string): Promise<{ success: boolean; courier: SupportedCourier; consignment_id: string; message: string; raw_response?: any }> {
|
||||||
|
if (!this.enabled) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_NOT_CONFIGURED",
|
||||||
|
message: "RedX API access token is not configured.",
|
||||||
|
courier: "redx",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.client.patch("/parcels", {
|
||||||
|
entity_type: "parcel-tracking-id",
|
||||||
|
entity_id: trackingId,
|
||||||
|
update_details: {
|
||||||
|
property_name: "status",
|
||||||
|
new_value: "cancelled",
|
||||||
|
reason: reason || "Cancelled by merchant via Aura Courier MCP",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
courier: "redx",
|
||||||
|
consignment_id: trackingId,
|
||||||
|
message: response.data?.message || "Parcel successfully cancelled in RedX Delivery.",
|
||||||
|
raw_response: response.data,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
const msg = err.response?.data?.message || err.message;
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "COURIER_UPSTREAM_ERROR",
|
||||||
|
message: `RedX cancellation failed: ${msg}`,
|
||||||
|
courier: "redx",
|
||||||
|
retryable: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -171,4 +171,47 @@ export class SteadfastAdapter implements CourierAdapter {
|
|||||||
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
const response = await withGetRetry(() => this.client.get(`/fraud_check/${encodeURIComponent(cleanPhone)}`));
|
||||||
return response.data;
|
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",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+138
-33
@@ -1,9 +1,9 @@
|
|||||||
import express, { Request, Response } from "express";
|
import express, { type Express, type Request, type Response } from "express";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||||
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
||||||
import { CourierRegistry, recordWebhookEvent } from "./registry.js";
|
import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
|
||||||
import { loadConfig, EnvSource } from "./config.js";
|
import { loadConfig, EnvSource } from "./config.js";
|
||||||
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
|
import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
|
||||||
import { createRateLimiter } from "./middleware/rate_limit.js";
|
import { createRateLimiter } from "./middleware/rate_limit.js";
|
||||||
@@ -14,9 +14,15 @@ import {
|
|||||||
resolveAuthContext,
|
resolveAuthContext,
|
||||||
verifyWebhookSignature,
|
verifyWebhookSignature,
|
||||||
recordAuditLog,
|
recordAuditLog,
|
||||||
|
initDynamicAuthStore,
|
||||||
|
upsertDynamicKeyHash,
|
||||||
|
setTenantDynamicKeyStatus,
|
||||||
|
listDynamicKeySummaries,
|
||||||
} from "./middleware/auth.js";
|
} from "./middleware/auth.js";
|
||||||
|
import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js";
|
||||||
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
|
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
|
||||||
import { SupportedCourier } from "./types.js";
|
import { SupportedCourier } from "./types.js";
|
||||||
|
import { APP_VERSION } from "./version.js";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import pg from "pg";
|
import pg from "pg";
|
||||||
@@ -30,6 +36,8 @@ let dbPool: any = null;
|
|||||||
if (process.env.NODE_ENV !== "test" && dbUrl) {
|
if (process.env.NODE_ENV !== "test" && dbUrl) {
|
||||||
try {
|
try {
|
||||||
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
|
||||||
|
setRegistryDbPool(dbPool);
|
||||||
|
initDynamicAuthStore(dbPool).catch(() => {});
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
|
||||||
}
|
}
|
||||||
@@ -93,7 +101,22 @@ function redactAddressToDistrict(addr: string): string {
|
|||||||
*/
|
*/
|
||||||
export function keysFromRequest(req: Request): EnvSource {
|
export function keysFromRequest(req: Request): EnvSource {
|
||||||
const h = req.headers;
|
const h = req.headers;
|
||||||
const allowMasterEnvFallback = req.auraAuth?.tenantId === "master";
|
// Strict Multi-Tenant & BYOK Isolation:
|
||||||
|
// If caller explicitly sends any BYOK courier headers (isByok === true), NEVER fall back to
|
||||||
|
// platform master courier env keys so vendor/merchant BYOK credentials never mix with central keys.
|
||||||
|
const isByokRequest = Boolean(
|
||||||
|
req.auraAuth?.isByok ||
|
||||||
|
h["x-steadfast-api-key"] ||
|
||||||
|
h["x-pathao-client-id"] ||
|
||||||
|
h["x-redx-api-token"] ||
|
||||||
|
h["x-paperfly-api-key"]
|
||||||
|
);
|
||||||
|
const isPublicFraudCheck =
|
||||||
|
req.auraAuth?.tenantId === "public_ro" &&
|
||||||
|
req.body?.method === "tools/call" &&
|
||||||
|
req.body?.params?.name === "check_fraud_risk";
|
||||||
|
const allowMasterEnvFallback =
|
||||||
|
(req.auraAuth?.tenantId === "master" || isPublicFraudCheck) && !isByokRequest;
|
||||||
|
|
||||||
const pick = (header: string, envVar?: string, allowNonMasterEnv = false): string | undefined => {
|
const pick = (header: string, envVar?: string, allowNonMasterEnv = false): string | undefined => {
|
||||||
const hv = h[header];
|
const hv = h[header];
|
||||||
@@ -126,13 +149,15 @@ export function keysFromRequest(req: Request): EnvSource {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const app = express();
|
export const app: Express = express();
|
||||||
|
app.set("trust proxy", 1);
|
||||||
app.use(express.json({
|
app.use(express.json({
|
||||||
limit: "1mb",
|
limit: "1mb",
|
||||||
verify: (req: any, _res, buf) => {
|
verify: (req: any, _res, buf) => {
|
||||||
req.rawBody = buf;
|
req.rawBody = buf;
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
app.use(express.urlencoded({ extended: false, limit: "1mb" }));
|
||||||
|
|
||||||
// Robust Malformed JSON Syntax Error Guard
|
// Robust Malformed JSON Syntax Error Guard
|
||||||
app.use((err: any, _req: Request, res: Response, next: any) => {
|
app.use((err: any, _req: Request, res: Response, next: any) => {
|
||||||
@@ -162,15 +187,72 @@ app.use((req, res, next) => {
|
|||||||
"Access-Control-Allow-Headers",
|
"Access-Control-Allow-Headers",
|
||||||
"Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key"
|
"Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-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-Expose-Headers", "mcp-session-id");
|
res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate");
|
||||||
if (req.method === "OPTIONS") {
|
if (req.method === "OPTIONS") {
|
||||||
return res.sendStatus(204);
|
return res.sendStatus(204);
|
||||||
}
|
}
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Static assets (official logo, favicons, branding) & agent MCP configs
|
||||||
|
app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" }));
|
||||||
|
app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" }));
|
||||||
|
app.get("/favicon.ico", (_req, res) => {
|
||||||
|
res.sendFile(path.join(ASSETS_DIR, "courier-logo.jpg"), (err) => {
|
||||||
|
if (err && !res.headersSent) res.status(204).end();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Standard MCP OAuth 2.1 + PKCE (S256) + RFC 9728 + RFC 8414 + RFC 7591 Dynamic Client Registration
|
||||||
|
registerOAuthRoutes(app);
|
||||||
|
|
||||||
app.use(optionalAuthMiddleware);
|
app.use(optionalAuthMiddleware);
|
||||||
|
|
||||||
|
|
||||||
|
// Dynamic Tenant API Key Sync & Revocation Routes (Called by Snehalata / Admin Master Key)
|
||||||
|
app.get("/admin/tokens", (req: Request, res: Response) => {
|
||||||
|
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
|
||||||
|
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
|
||||||
|
}
|
||||||
|
return res.json({ ok: true, tokens: listDynamicKeySummaries() });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/admin/tokens/register", async (req: Request, res: Response) => {
|
||||||
|
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
|
||||||
|
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
|
||||||
|
}
|
||||||
|
const b = req.body || {};
|
||||||
|
if ((!b.tokenHash && !b.rawToken) || !b.tenantId) {
|
||||||
|
return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "tenantId and tokenHash (or rawToken) required." }), "validator"));
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const rec = await upsertDynamicKeyHash({
|
||||||
|
tokenHash: b.tokenHash,
|
||||||
|
rawToken: b.rawToken,
|
||||||
|
tenantId: String(b.tenantId),
|
||||||
|
storeName: b.storeName ? String(b.storeName) : undefined,
|
||||||
|
scopes: Array.isArray(b.scopes) ? b.scopes : ["read", "write"],
|
||||||
|
isAdmin: Boolean(b.isAdmin),
|
||||||
|
status: String(b.status || "ACTIVE"),
|
||||||
|
});
|
||||||
|
return res.json({ ok: true, tenantId: rec.tenantId, status: rec.status, hashPrefix: rec.tokenHash.slice(0, 10) });
|
||||||
|
} catch (err: any) {
|
||||||
|
return res.status(500).json(wrapError(err, "validator"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/admin/tokens/revoke", async (req: Request, res: Response) => {
|
||||||
|
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
|
||||||
|
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
|
||||||
|
}
|
||||||
|
const b = req.body || {};
|
||||||
|
if (!b.tenantId) {
|
||||||
|
return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "tenantId required." }), "validator"));
|
||||||
|
}
|
||||||
|
const count = await setTenantDynamicKeyStatus(String(b.tenantId), String(b.status || "PAYMENT_DUE"));
|
||||||
|
return res.json({ ok: true, tenantId: b.tenantId, updatedKeys: count, status: b.status || "PAYMENT_DUE" });
|
||||||
|
});
|
||||||
|
|
||||||
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
|
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
|
||||||
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
|
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
|
||||||
|
|
||||||
@@ -344,6 +426,7 @@ app.get("/mcp", mcpLimiter, async (req: Request, res: Response) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (!req.auraAuth?.authenticated) {
|
if (!req.auraAuth?.authenticated) {
|
||||||
|
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, req.auraAuth?.tenantId === "invalid"));
|
||||||
return res.status(401).json(
|
return res.status(401).json(
|
||||||
wrapError(
|
wrapError(
|
||||||
new McpToolError({
|
new McpToolError({
|
||||||
@@ -359,8 +442,8 @@ app.get("/mcp", mcpLimiter, async (req: Request, res: Response) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const entry = sessions.get(sessionId)!;
|
const entry = sessions.get(sessionId)!;
|
||||||
const callerTenant = req.auraAuth?.tenantId || "default";
|
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
|
||||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
|
||||||
return res.status(403).json(
|
return res.status(403).json(
|
||||||
wrapError(
|
wrapError(
|
||||||
new McpToolError({
|
new McpToolError({
|
||||||
@@ -409,7 +492,11 @@ app.delete("/mcp", requireMcpAuth, async (req: Request, res: Response) => {
|
|||||||
*/
|
*/
|
||||||
app.get("/sse", mcpLimiter, async (req: Request, res: Response) => {
|
app.get("/sse", mcpLimiter, async (req: Request, res: Response) => {
|
||||||
const tenantId = req.auraAuth?.tenantId || "default";
|
const tenantId = req.auraAuth?.tenantId || "default";
|
||||||
const transport = new SSEServerTransport("/messages", res);
|
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;
|
const sid = transport.sessionId;
|
||||||
sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
|
sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
|
||||||
|
|
||||||
@@ -436,8 +523,8 @@ app.post("/messages", mcpLimiter, async (req: Request, res: Response) => {
|
|||||||
return res.status(400).send("Invalid or missing sessionId");
|
return res.status(400).send("Invalid or missing sessionId");
|
||||||
}
|
}
|
||||||
const entry = sseSessions.get(sessionId)!;
|
const entry = sseSessions.get(sessionId)!;
|
||||||
const callerTenant = req.auraAuth?.tenantId || "default";
|
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
|
||||||
if (entry.tenantId !== callerTenant && callerTenant !== "master") {
|
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
|
||||||
return res.status(403).json(
|
return res.status(403).json(
|
||||||
wrapError(
|
wrapError(
|
||||||
new McpToolError({
|
new McpToolError({
|
||||||
@@ -475,6 +562,12 @@ function handleCourierWebhook(provider: SupportedCourier) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const payload = req.body || {};
|
const payload = req.body || {};
|
||||||
|
if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") {
|
||||||
|
const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || "";
|
||||||
|
if (secret) res.setHeader("X-Pathao-Merchant-Webhook-Integration-Secret", secret);
|
||||||
|
return res.status(202).json({ ok: true, status: "webhook_verified" });
|
||||||
|
}
|
||||||
|
|
||||||
const consignmentId =
|
const consignmentId =
|
||||||
payload.consignment_id ||
|
payload.consignment_id ||
|
||||||
payload.merchant_order_id ||
|
payload.merchant_order_id ||
|
||||||
@@ -498,7 +591,8 @@ function handleCourierWebhook(provider: SupportedCourier) {
|
|||||||
const status = String(payload.status || payload.order_status || payload.event || "received");
|
const status = String(payload.status || payload.order_status || payload.event || "received");
|
||||||
const eventType = String(payload.notification_type || payload.event || "delivery_status");
|
const eventType = String(payload.notification_type || payload.event || "delivery_status");
|
||||||
const invoice = payload.invoice || payload.merchant_order_id;
|
const invoice = payload.invoice || payload.merchant_order_id;
|
||||||
const tenantId = String(req.query.tenant || req.headers["x-tenant-id"] || "default");
|
const paramMerchantToken = req.params?.merchant_token ? String(req.params.merchant_token).trim() : "";
|
||||||
|
const tenantId = String(paramMerchantToken || req.query.tenant || req.headers["x-tenant-id"] || "default");
|
||||||
|
|
||||||
const record = {
|
const record = {
|
||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
@@ -514,14 +608,28 @@ function handleCourierWebhook(provider: SupportedCourier) {
|
|||||||
// F06: Record webhook event scoped by tenantId
|
// F06: Record webhook event scoped by tenantId
|
||||||
recordWebhookEvent(record, tenantId);
|
recordWebhookEvent(record, tenantId);
|
||||||
|
|
||||||
|
// Forward verified Pathao financial events best-effort to Snehalata Financial Manager
|
||||||
|
if (provider === "pathao" && process.env.NODE_ENV !== "test" && /deliver|return|paid|settlement|invoice/i.test(`${status} ${eventType}`)) {
|
||||||
|
const fwdUrl = process.env.SNEHALATA_WEBHOOK_URL || "https://www.snehalata.com/api/webhooks/pathao";
|
||||||
|
const sig = String(req.headers["x-pathao-signature"] || process.env.PATHAO_CLIENT_SECRET || "");
|
||||||
|
if (fwdUrl && sig) {
|
||||||
|
fetch(fwdUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", "X-Pathao-Signature": sig },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return res.status(200).json(
|
return res.status(200).json(
|
||||||
wrapSuccess(
|
wrapSuccess(
|
||||||
{
|
{
|
||||||
status: "success",
|
status: "success",
|
||||||
courier: provider,
|
courier: provider,
|
||||||
|
tenant_scope: tenantId,
|
||||||
consignment_id: record.consignment_id,
|
consignment_id: record.consignment_id,
|
||||||
event_id: record.id,
|
event_id: record.id,
|
||||||
message: `${provider} webhook verified and recorded.`,
|
message: `${provider} webhook verified and recorded for tenant '${tenantId}'.`,
|
||||||
},
|
},
|
||||||
"live_api"
|
"live_api"
|
||||||
)
|
)
|
||||||
@@ -529,10 +637,10 @@ function handleCourierWebhook(provider: SupportedCourier) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
app.post("/webhooks/steadfast", handleCourierWebhook("steadfast"));
|
app.post(["/webhooks/steadfast", "/webhooks/steadfast/:merchant_token"], handleCourierWebhook("steadfast"));
|
||||||
app.post("/webhooks/pathao", handleCourierWebhook("pathao"));
|
app.post(["/webhooks/pathao", "/webhooks/pathao/:merchant_token"], handleCourierWebhook("pathao"));
|
||||||
app.post("/webhooks/redx", handleCourierWebhook("redx"));
|
app.post(["/webhooks/redx", "/webhooks/redx/:merchant_token"], handleCourierWebhook("redx"));
|
||||||
app.post("/webhooks/paperfly", handleCourierWebhook("paperfly"));
|
app.post(["/webhooks/paperfly", "/webhooks/paperfly/:merchant_token"], handleCourierWebhook("paperfly"));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /track/:code - Hardened Public & Authenticated Tracking Gateway
|
* GET /track/:code - Hardened Public & Authenticated Tracking Gateway
|
||||||
@@ -714,12 +822,12 @@ app.get("/health", (req, res) => {
|
|||||||
if (!isAdmin) {
|
if (!isAdmin) {
|
||||||
if (req.query.ui === "1" && req.headers.accept?.includes("text/html")) {
|
if (req.query.ui === "1" && req.headers.accept?.includes("text/html")) {
|
||||||
return res.sendFile(HEALTH_HTML, (err) => {
|
return res.sendFile(HEALTH_HTML, (err) => {
|
||||||
if (err && !res.headersSent) res.json({ ok: true, version: "2.6.0" });
|
if (err && !res.headersSent) res.json({ ok: true, version: APP_VERSION });
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return res.json({
|
return res.json({
|
||||||
ok: true,
|
ok: true,
|
||||||
version: "2.6.0",
|
version: APP_VERSION,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -727,7 +835,7 @@ app.get("/health", (req, res) => {
|
|||||||
const detailed = {
|
const detailed = {
|
||||||
ok: true,
|
ok: true,
|
||||||
service: "aura-courier-mcp",
|
service: "aura-courier-mcp",
|
||||||
version: "2.6.0",
|
version: APP_VERSION,
|
||||||
tools_count: TOOLS.length,
|
tools_count: TOOLS.length,
|
||||||
spatial_engine: "Google Maps Platform (gmp_git_agentskills_v1)",
|
spatial_engine: "Google Maps Platform (gmp_git_agentskills_v1)",
|
||||||
fraud_engine: "Pathao Nationwide v2 + Steadfast Nationwide API + BD Prefix Validator",
|
fraud_engine: "Pathao Nationwide v2 + Steadfast Nationwide API + BD Prefix Validator",
|
||||||
@@ -751,7 +859,7 @@ app.get("/health", (req, res) => {
|
|||||||
|
|
||||||
app.get("/health.html", (_req, res) => {
|
app.get("/health.html", (_req, res) => {
|
||||||
res.sendFile(HEALTH_HTML, (err) => {
|
res.sendFile(HEALTH_HTML, (err) => {
|
||||||
if (err && !res.headersSent) res.json({ ok: true, version: "2.6.0" });
|
if (err && !res.headersSent) res.json({ ok: true, version: APP_VERSION });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -763,17 +871,6 @@ app.get("/privacy", (_req, res) => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
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) => {
|
|
||||||
if (err && !res.headersSent) {
|
|
||||||
res.redirect("/guide");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
app.get("/guide", (_req, res) => {
|
app.get("/guide", (_req, res) => {
|
||||||
res.sendFile(GUIDE_HTML, (err) => {
|
res.sendFile(GUIDE_HTML, (err) => {
|
||||||
if (err && !res.headersSent) {
|
if (err && !res.headersSent) {
|
||||||
@@ -782,6 +879,14 @@ 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) => {
|
app.get("/", (_req, res) => {
|
||||||
res.sendFile(LANDING, (err) => {
|
res.sendFile(LANDING, (err) => {
|
||||||
if (err && !res.headersSent) {
|
if (err && !res.headersSent) {
|
||||||
@@ -790,7 +895,7 @@ app.get("/", (_req, res) => {
|
|||||||
.send(
|
.send(
|
||||||
`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Aura Courier MCP</title>` +
|
`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Aura Courier MCP</title>` +
|
||||||
`<style>body{font-family:system-ui,sans-serif;background:#07080a;color:#f4f5f7;margin:0;display:grid;place-items:center;min-height:100vh}.b{max-width:640px;padding:40px;text-align:center}h1{font-size:28px;margin:0 0 10px}code{background:#0f1115;padding:2px 8px;border-radius:6px;color:#00d4ff;font-size:13px}a{color:#00d4ff}p{line-height:1.6;color:#a4a8b3}</style></head>` +
|
`<style>body{font-family:system-ui,sans-serif;background:#07080a;color:#f4f5f7;margin:0;display:grid;place-items:center;min-height:100vh}.b{max-width:640px;padding:40px;text-align:center}h1{font-size:28px;margin:0 0 10px}code{background:#0f1115;padding:2px 8px;border-radius:6px;color:#00d4ff;font-size:13px}a{color:#00d4ff}p{line-height:1.6;color:#a4a8b3}</style></head>` +
|
||||||
`<body><div class="b"><h1>🚚 Aura Courier MCP v2.6.0</h1><p>Enterprise Bangladesh courier MCP & Google Maps Platform spatial hub.</p>` +
|
`<body><div class="b"><h1>🚚 Aura Courier MCP v${APP_VERSION}</h1><p>Enterprise Bangladesh courier MCP & Google Maps Platform spatial hub.</p>` +
|
||||||
`<p>Connect your AI to <code>POST /mcp</code> with Streamable-HTTP.</p>` +
|
`<p>Connect your AI to <code>POST /mcp</code> with Streamable-HTTP.</p>` +
|
||||||
`<p>Webhooks: <code>POST /webhooks/steadfast</code> · <code>POST /webhooks/pathao</code></p>` +
|
`<p>Webhooks: <code>POST /webhooks/steadfast</code> · <code>POST /webhooks/pathao</code></p>` +
|
||||||
`<p>By <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="https://courier.auraajenticai.cloud">docs & setup</a></p></div></body></html>`
|
`<p>By <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="https://courier.auraajenticai.cloud">docs & setup</a></p></div></body></html>`
|
||||||
@@ -801,6 +906,6 @@ app.get("/", (_req, res) => {
|
|||||||
|
|
||||||
if (process.env.NODE_ENV !== "test") {
|
if (process.env.NODE_ENV !== "test") {
|
||||||
app.listen(PORT, () => {
|
app.listen(PORT, () => {
|
||||||
console.log(`Aura Courier MCP v2.6.0 (HTTP) listening on :${PORT} — POST /mcp`);
|
console.log(`Aura Courier MCP v${APP_VERSION} (HTTP) listening on :${PORT} — POST /mcp`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -2,6 +2,7 @@
|
|||||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
import { CourierRegistry } from "./registry.js";
|
import { CourierRegistry } from "./registry.js";
|
||||||
import { buildMcpServer } from "./server.js";
|
import { buildMcpServer } from "./server.js";
|
||||||
|
import { APP_VERSION } from "./version.js";
|
||||||
|
|
||||||
// STDIO / npx entrypoint (Claude Desktop, Cursor, Antigravity).
|
// STDIO / npx entrypoint (Claude Desktop, Cursor, Antigravity).
|
||||||
// Credentials come from environment variables (STEADFAST_API_KEY, PATHAO_*).
|
// Credentials come from environment variables (STEADFAST_API_KEY, PATHAO_*).
|
||||||
@@ -9,7 +10,7 @@ async function run() {
|
|||||||
const server = buildMcpServer(new CourierRegistry());
|
const server = buildMcpServer(new CourierRegistry());
|
||||||
const transport = new StdioServerTransport();
|
const transport = new StdioServerTransport();
|
||||||
await server.connect(transport);
|
await server.connect(transport);
|
||||||
console.error("Aura Courier MCP v2.6.0 running on STDIO");
|
console.error(`Aura Courier MCP v${APP_VERSION} running on STDIO`);
|
||||||
}
|
}
|
||||||
|
|
||||||
run().catch((error) => {
|
run().catch((error) => {
|
||||||
|
|||||||
+458
-49
@@ -1,6 +1,7 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { createHash, timingSafeEqual } from "node:crypto";
|
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
||||||
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
|
import { maskPhone, wrapError, McpToolError } from "../envelope.js";
|
||||||
|
import { verifyOAuthAccessToken, buildWwwAuthenticateHeader } from "./oauth.js";
|
||||||
|
|
||||||
export type AuthScope = "read" | "write";
|
export type AuthScope = "read" | "write";
|
||||||
|
|
||||||
@@ -11,12 +12,15 @@ export interface AuraAuthContext {
|
|||||||
isByok: boolean;
|
isByok: boolean;
|
||||||
isAdmin: boolean;
|
isAdmin: boolean;
|
||||||
callerToken?: string;
|
callerToken?: string;
|
||||||
|
deniedReason?: string;
|
||||||
|
httpStatus?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
namespace Express {
|
namespace Express {
|
||||||
interface Request {
|
interface Request {
|
||||||
auraAuth?: AuraAuthContext;
|
auraAuth?: AuraAuthContext;
|
||||||
|
rawBody?: string | Buffer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -36,6 +40,7 @@ const WRITE_TOOLS = new Set([
|
|||||||
"create_parcel",
|
"create_parcel",
|
||||||
"resolve_ndr_issue",
|
"resolve_ndr_issue",
|
||||||
"cancel_parcel",
|
"cancel_parcel",
|
||||||
|
"update_parcel",
|
||||||
"bulk_create_parcels",
|
"bulk_create_parcels",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -52,16 +57,17 @@ export interface AuditEntry {
|
|||||||
}
|
}
|
||||||
export const auditLogBuffer: 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 {
|
export function hasByokCredentials(req: Request): boolean {
|
||||||
const h = req.headers;
|
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(
|
return Boolean(
|
||||||
hasKey("x-steadfast-api-key", "steadfast_key") ||
|
h["x-steadfast-api-key"] ||
|
||||||
hasKey("x-pathao-client-id", "pathao_client_id") ||
|
h["x-pathao-client-id"] ||
|
||||||
hasKey("x-redx-api-token", "redx_token") ||
|
h["x-redx-api-token"] ||
|
||||||
hasKey("x-paperfly-api-key", "paperfly_key")
|
h["x-paperfly-api-key"]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,6 +84,14 @@ export function extractBearerToken(req: Request): string | undefined {
|
|||||||
if (typeof customKey === "string" && customKey.trim()) {
|
if (typeof customKey === "string" && customKey.trim()) {
|
||||||
return 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;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +103,151 @@ function safeCompare(a: string, b: string): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve bearer token into tenant context and scopes (read / write).
|
* In-memory / env-configured tenant API keys registry.
|
||||||
|
* Maps sha256(token) -> { tenantId, scopes, isAdmin }
|
||||||
|
*/
|
||||||
|
|
||||||
|
export interface DynamicKeyRecord {
|
||||||
|
tokenHash: string;
|
||||||
|
tenantId: string;
|
||||||
|
storeName?: string;
|
||||||
|
scopes: AuthScope[];
|
||||||
|
isAdmin: boolean;
|
||||||
|
status: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dynamicKeyHashes = new Map<string, DynamicKeyRecord>();
|
||||||
|
const remoteVerifyCache = new Map<string, { exp: number; record?: DynamicKeyRecord }>();
|
||||||
|
let authDbPool: any = null;
|
||||||
|
|
||||||
|
export async function initDynamicAuthStore(pool: any): Promise<void> {
|
||||||
|
authDbPool = pool;
|
||||||
|
if (!pool) return;
|
||||||
|
try {
|
||||||
|
await pool.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS aura_mcp_dynamic_keys (
|
||||||
|
token_hash TEXT PRIMARY KEY,
|
||||||
|
tenant_id TEXT NOT NULL,
|
||||||
|
store_name TEXT,
|
||||||
|
scopes JSONB NOT NULL DEFAULT '["read","write"]',
|
||||||
|
is_admin BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
status TEXT NOT NULL DEFAULT 'ACTIVE',
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
} catch (ddlErr: any) {
|
||||||
|
// Least-privilege runtime DB roles (e.g. aura_courier_runtime) intentionally lack schema CREATE;
|
||||||
|
// the table is pre-provisioned, so continue cleanly to load rows below.
|
||||||
|
if (!/permission denied/i.test(String(ddlErr?.message || ""))) {
|
||||||
|
console.warn("[Auth] Dynamic key table DDL skipped:", ddlErr?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await pool.query("SELECT token_hash, tenant_id, store_name, scopes, is_admin, status, updated_at FROM aura_mcp_dynamic_keys");
|
||||||
|
for (const row of res.rows || []) {
|
||||||
|
dynamicKeyHashes.set(row.token_hash, {
|
||||||
|
tokenHash: row.token_hash,
|
||||||
|
tenantId: row.tenant_id,
|
||||||
|
storeName: row.store_name || undefined,
|
||||||
|
scopes: Array.isArray(row.scopes) ? row.scopes : ["read", "write"],
|
||||||
|
isAdmin: Boolean(row.is_admin),
|
||||||
|
status: String(row.status || "ACTIVE").toUpperCase(),
|
||||||
|
updatedAt: new Date(row.updated_at || Date.now()).toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log(`[Auth] Loaded ${dynamicKeyHashes.size} dynamic MCP key(s) from PostgreSQL.`);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.warn("[Auth] Dynamic key table load skipped:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function upsertDynamicKeyHash(opts: {
|
||||||
|
tokenHash?: string;
|
||||||
|
rawToken?: string;
|
||||||
|
tenantId: string;
|
||||||
|
storeName?: string;
|
||||||
|
scopes?: AuthScope[];
|
||||||
|
isAdmin?: boolean;
|
||||||
|
status?: string;
|
||||||
|
}): Promise<DynamicKeyRecord> {
|
||||||
|
const hash = (opts.tokenHash || (opts.rawToken ? createHash("sha256").update(opts.rawToken).digest("hex") : "")).trim();
|
||||||
|
if (!hash) throw new Error("tokenHash or rawToken required");
|
||||||
|
const status = String(opts.status || "ACTIVE").toUpperCase();
|
||||||
|
const scopes: AuthScope[] = Array.isArray(opts.scopes) && opts.scopes.length ? opts.scopes : ["read", "write"];
|
||||||
|
const rec: DynamicKeyRecord = {
|
||||||
|
tokenHash: hash,
|
||||||
|
tenantId: opts.tenantId,
|
||||||
|
storeName: opts.storeName,
|
||||||
|
scopes,
|
||||||
|
isAdmin: Boolean(opts.isAdmin),
|
||||||
|
status,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
dynamicKeyHashes.set(hash, rec);
|
||||||
|
if (opts.rawToken) {
|
||||||
|
remoteVerifyCache.set(hash, { exp: Date.now() + 20_000, record: rec });
|
||||||
|
}
|
||||||
|
if (authDbPool) {
|
||||||
|
try {
|
||||||
|
await authDbPool.query(
|
||||||
|
`INSERT INTO aura_mcp_dynamic_keys (token_hash, tenant_id, store_name, scopes, is_admin, status, updated_at)
|
||||||
|
VALUES ($1, $2, $3, $4::jsonb, $5, $6, NOW())
|
||||||
|
ON CONFLICT (token_hash) DO UPDATE SET
|
||||||
|
tenant_id = EXCLUDED.tenant_id,
|
||||||
|
store_name = COALESCE(EXCLUDED.store_name, aura_mcp_dynamic_keys.store_name),
|
||||||
|
scopes = EXCLUDED.scopes,
|
||||||
|
is_admin = EXCLUDED.is_admin,
|
||||||
|
status = EXCLUDED.status,
|
||||||
|
updated_at = NOW()`,
|
||||||
|
[hash, rec.tenantId, rec.storeName || null, JSON.stringify(scopes), rec.isAdmin, status]
|
||||||
|
);
|
||||||
|
} catch (err: any) {
|
||||||
|
console.warn("[Auth] Failed persisting dynamic key:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rec;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setTenantDynamicKeyStatus(tenantId: string, status: string): Promise<number> {
|
||||||
|
const norm = String(status || "SUSPENDED").toUpperCase();
|
||||||
|
let updated = 0;
|
||||||
|
for (const [h, rec] of dynamicKeyHashes.entries()) {
|
||||||
|
if (rec.tenantId === tenantId) {
|
||||||
|
dynamicKeyHashes.set(h, { ...rec, status: norm, updatedAt: new Date().toISOString() });
|
||||||
|
remoteVerifyCache.delete(h);
|
||||||
|
updated++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (authDbPool) {
|
||||||
|
try {
|
||||||
|
await authDbPool.query("UPDATE aura_mcp_dynamic_keys SET status = $1, updated_at = NOW() WHERE tenant_id = $2", [norm, tenantId]);
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
return updated;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listDynamicKeySummaries() {
|
||||||
|
return Array.from(dynamicKeyHashes.values()).map((r) => ({
|
||||||
|
hashPrefix: r.tokenHash.slice(0, 10) + "...",
|
||||||
|
tenantId: r.tenantId,
|
||||||
|
storeName: r.storeName || "",
|
||||||
|
status: r.status,
|
||||||
|
scopes: r.scopes,
|
||||||
|
updatedAt: r.updatedAt,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
||||||
*/
|
*/
|
||||||
export function resolveAuthContext(req: Request): AuraAuthContext {
|
export function resolveAuthContext(req: Request): AuraAuthContext {
|
||||||
const token = extractBearerToken(req);
|
const token = extractBearerToken(req);
|
||||||
@@ -112,7 +270,22 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. Master / Admin Key (Read + Write on master tenant)
|
// 0. Standard MCP OAuth 2.1 JWT Access Token (Google Gemini, ChatGPT, Claude Web)
|
||||||
|
if (token.startsWith("eyJ") && token.split(".").length === 3) {
|
||||||
|
const oauthClaims = verifyOAuthAccessToken(token);
|
||||||
|
if (oauthClaims) {
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: oauthClaims.sub,
|
||||||
|
scopes: Array.isArray(oauthClaims.scp) && oauthClaims.scp.length ? oauthClaims.scp : ["read"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: Boolean(oauthClaims.adm),
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Master / Admin Key (Full Read + Write across all tenants)
|
||||||
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
|
if (safeCompare(token, masterKey) || safeCompare(token, adminKey)) {
|
||||||
return {
|
return {
|
||||||
authenticated: true,
|
authenticated: true,
|
||||||
@@ -124,12 +297,11 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Read-Only Key (Read scope only)
|
// 2. Read-Only Gateway Discovery Key
|
||||||
if (safeCompare(token, readOnlyKey) || token.startsWith("aura_ro_")) {
|
if (safeCompare(token, readOnlyKey) || safeCompare(token, "aura_ro_public_inspector_2026")) {
|
||||||
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
|
||||||
return {
|
return {
|
||||||
authenticated: true,
|
authenticated: true,
|
||||||
tenantId: `tenant_${tenantHash}`,
|
tenantId: "public_ro",
|
||||||
scopes: ["read"],
|
scopes: ["read"],
|
||||||
isByok,
|
isByok,
|
||||||
isAdmin: false,
|
isAdmin: false,
|
||||||
@@ -137,19 +309,78 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Scoped Tenant Read+Write Key (aura_rw_<tenant>_<secret> or aura_tenant_<secret>)
|
// 3. Cryptographically registered API key lookup (SHA-256 match)
|
||||||
if ((token.startsWith("aura_rw_") || token.startsWith("aura_tenant_")) && token.length >= 16) {
|
const tokenHash = createHash("sha256").update(token).digest("hex");
|
||||||
const tenantHash = createHash("sha256").update(token).digest("hex").slice(0, 12);
|
if (registeredKeyHashes.has(tokenHash)) {
|
||||||
|
const reg = registeredKeyHashes.get(tokenHash)!;
|
||||||
return {
|
return {
|
||||||
authenticated: true,
|
authenticated: true,
|
||||||
tenantId: `tenant_${tenantHash}`,
|
tenantId: reg.tenantId,
|
||||||
scopes: ["read", "write"],
|
scopes: reg.scopes,
|
||||||
isByok,
|
isByok,
|
||||||
isAdmin: false,
|
isAdmin: reg.isAdmin,
|
||||||
callerToken: token,
|
callerToken: token,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 3b. Dynamic Database / Synced Tenant Key lookup
|
||||||
|
if (dynamicKeyHashes.has(tokenHash)) {
|
||||||
|
const dyn = dynamicKeyHashes.get(tokenHash)!;
|
||||||
|
if (dyn.status === "PAYMENT_DUE") {
|
||||||
|
return {
|
||||||
|
authenticated: false,
|
||||||
|
tenantId: dyn.tenantId,
|
||||||
|
scopes: [],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
deniedReason: "পেমেন্ট বাকি থাকায় MCP Connector অ্যাক্সেস হোল্ড করা হয়েছে (Payment Due)।",
|
||||||
|
httpStatus: 402,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (dyn.status === "SUSPENDED" || dyn.status === "DISABLED") {
|
||||||
|
return {
|
||||||
|
authenticated: false,
|
||||||
|
tenantId: dyn.tenantId,
|
||||||
|
scopes: [],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
deniedReason: "অ্যাডমিন দ্বারা MCP Connector অ্যাক্সেস স্থগিত করা হয়েছে।",
|
||||||
|
httpStatus: 403,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
tenantId: dyn.tenantId,
|
||||||
|
scopes: dyn.scopes,
|
||||||
|
isByok,
|
||||||
|
isAdmin: dyn.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(),
|
||||||
|
scopes: ["read", "write"],
|
||||||
|
isByok,
|
||||||
|
isAdmin: false,
|
||||||
|
callerToken: token,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unknown / unverified token -> reject (Zero prefix bypass)
|
||||||
return {
|
return {
|
||||||
authenticated: false,
|
authenticated: false,
|
||||||
tenantId: "invalid",
|
tenantId: "invalid",
|
||||||
@@ -162,32 +393,139 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
|
|||||||
/**
|
/**
|
||||||
* Middleware: Evaluates auth context for all requests
|
* Middleware: Evaluates auth context for all requests
|
||||||
*/
|
*/
|
||||||
export function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void {
|
|
||||||
req.auraAuth = resolveAuthContext(req);
|
export async function resolveAuthContextAsync(req: Request): Promise<AuraAuthContext> {
|
||||||
|
const token = extractBearerToken(req);
|
||||||
|
const local = resolveAuthContext(req);
|
||||||
|
if (
|
||||||
|
process.env.NODE_ENV === "test" ||
|
||||||
|
!token ||
|
||||||
|
!token.startsWith("snl_mcp_") ||
|
||||||
|
local.authenticated ||
|
||||||
|
local.deniedReason
|
||||||
|
) {
|
||||||
|
return local;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hash = createHash("sha256").update(token).digest("hex");
|
||||||
|
const cached = remoteVerifyCache.get(hash);
|
||||||
|
if (cached && Date.now() < cached.exp && cached.record) {
|
||||||
|
return resolveAuthContext(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key";
|
||||||
|
const syncSecret =
|
||||||
|
process.env.AURA_MCP_SYNC_SECRET ||
|
||||||
|
process.env.AURA_API_KEY ||
|
||||||
|
process.env.COURIER_AUTH_TOKEN ||
|
||||||
|
"aura_live_mcp_master_key_2026";
|
||||||
|
|
||||||
|
const ctrl = new AbortController();
|
||||||
|
const timer = setTimeout(() => ctrl.abort(), 3500);
|
||||||
|
try {
|
||||||
|
const resp = await fetch(verifyUrl, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"x-aura-sync-secret": syncSecret,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
signal: ctrl.signal,
|
||||||
|
});
|
||||||
|
if (!resp.ok) return local;
|
||||||
|
const data: any = await resp.json().catch(() => ({}));
|
||||||
|
if (!data?.valid || !data?.tenantId) return local;
|
||||||
|
const status = data.allowed ? String(data.status || "ACTIVE") : String(data.status || "PAYMENT_DUE");
|
||||||
|
await upsertDynamicKeyHash({
|
||||||
|
tokenHash: hash,
|
||||||
|
rawToken: token,
|
||||||
|
tenantId: String(data.tenantId),
|
||||||
|
storeName: data.storeName,
|
||||||
|
scopes: Array.isArray(data.scopes) && data.scopes.length ? data.scopes : ["read", "write"],
|
||||||
|
isAdmin: Boolean(data.isAdmin),
|
||||||
|
status,
|
||||||
|
});
|
||||||
|
return resolveAuthContext(req);
|
||||||
|
} catch {
|
||||||
|
return local;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): Promise<void> {
|
||||||
|
req.auraAuth = await resolveAuthContextAsync(req);
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Strict /mcp Authentication & Per-Key Rate Limit Guard (T1)
|
* Strict /mcp Authentication & Per-Key Rate Limit Guard
|
||||||
* Missing or invalid Bearer token -> HTTP 401 + UNAUTHORIZED envelope
|
* 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.
|
||||||
*/
|
*/
|
||||||
export function requireMcpAuth(req: Request, res: Response, next: NextFunction): void {
|
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);
|
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||||
req.auraAuth = ctx;
|
req.auraAuth = ctx;
|
||||||
|
|
||||||
|
if (ctx.deniedReason) {
|
||||||
|
res.status(ctx.httpStatus || 402).json(
|
||||||
|
wrapError(
|
||||||
|
new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: ctx.deniedReason,
|
||||||
|
retryable: false,
|
||||||
|
source: "validator",
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If a caller explicitly passed an invalid / expired / forged token, always reject with 401 + RFC 9728 WWW-Authenticate
|
||||||
|
if (ctx.tenantId === "invalid") {
|
||||||
|
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, true));
|
||||||
|
res.status(401).json(
|
||||||
|
wrapError(
|
||||||
|
new McpToolError({
|
||||||
|
code: "UNAUTHORIZED",
|
||||||
|
message: "Invalid or expired Authorization token.",
|
||||||
|
retryable: false,
|
||||||
|
source: "validator",
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow stateless public catalog discovery (tools/list, ping) for MCP directories while requiring auth on initialize/tools/call so OAuth 2.1 clients (Gemini, ChatGPT, Claude Web) trigger automatic OAuth discovery via 401 WWW-Authenticate.
|
||||||
|
const isDiscovery =
|
||||||
|
method === "tools/list" ||
|
||||||
|
method === "ping";
|
||||||
|
|
||||||
|
if (isDiscovery) {
|
||||||
|
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) {
|
if (!ctx.authenticated) {
|
||||||
res
|
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, false));
|
||||||
.status(401)
|
res.status(401).json(
|
||||||
.json(
|
wrapError(
|
||||||
wrapError(
|
new McpToolError({
|
||||||
new McpToolError({
|
code: "UNAUTHORIZED",
|
||||||
code: "UNAUTHORIZED",
|
message: "Missing or invalid Authorization: Bearer <key> header on /mcp. Authenticate via MCP OAuth 2.1 or provide your API key / BYOK carrier keys.",
|
||||||
message: "Missing or invalid Authorization: Bearer <key> header on /mcp.",
|
retryable: false,
|
||||||
retryable: false,
|
source: "validator",
|
||||||
source: "validator",
|
})
|
||||||
})
|
)
|
||||||
)
|
);
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,7 +556,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 (T1)
|
* Verify scope permission for a specific tool and record a privacy-safe audit log entry
|
||||||
*/
|
*/
|
||||||
export function isActionPermitted(
|
export function isActionPermitted(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -226,6 +564,26 @@ export function isActionPermitted(
|
|||||||
args?: Record<string, any>
|
args?: Record<string, any>
|
||||||
): { permitted: boolean; reason?: string } {
|
): { permitted: boolean; reason?: string } {
|
||||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
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: list_couriers is allowed for discovery
|
||||||
|
if (toolName === "list_couriers") {
|
||||||
|
return { permitted: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// BYOK mode: caller provided specific courier credentials in headers
|
||||||
|
if (ctx.isByok) {
|
||||||
|
return { permitted: true };
|
||||||
|
}
|
||||||
|
|
||||||
if (!ctx.authenticated) {
|
if (!ctx.authenticated) {
|
||||||
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
recordAuditLog(ctx.tenantId, toolName, args, "denied");
|
||||||
return {
|
return {
|
||||||
@@ -280,26 +638,77 @@ export function recordAuditLog(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Verify inbound courier webhook authentication / signature (T1)
|
* F09 Fix: Native Carrier Webhook HMAC-SHA256 & Token Verification.
|
||||||
* Rejects unsigned/invalid webhook calls with HTTP 401/403.
|
* Pathao uses HMAC-SHA256 with PATHAO_CLIENT_SECRET over raw request body.
|
||||||
|
* Steadfast uses secret key header comparison.
|
||||||
*/
|
*/
|
||||||
export function verifyWebhookSignature(req: Request, provider: string): boolean {
|
export function verifyWebhookSignature(req: Request, provider: string): boolean {
|
||||||
const secret =
|
const prov = (provider || "").toLowerCase();
|
||||||
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, registered tenant key, or merchant_token URL parameter fallback
|
||||||
|
const masterSecret = process.env.AURA_WEBHOOK_SECRET || process.env.AURA_API_KEY || "aura_webhook_secret_2026";
|
||||||
|
const paramToken = (req.params && (req.params as any).merchant_token) ? String((req.params as any).merchant_token).trim() : undefined;
|
||||||
const candidate =
|
const candidate =
|
||||||
|
paramToken ||
|
||||||
extractBearerToken(req) ||
|
extractBearerToken(req) ||
|
||||||
(req.headers["x-webhook-secret"] as string | undefined) ||
|
(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["token"] as string | undefined) ||
|
||||||
(req.query["secret"] as string | undefined);
|
(req.query["secret"] as string | undefined);
|
||||||
|
|
||||||
if (!candidate || typeof candidate !== "string") {
|
if (candidate && typeof candidate === "string") {
|
||||||
return false;
|
const trimmed = candidate.trim();
|
||||||
|
if (safeCompare(trimmed, masterSecret)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const tokenHash = createHash("sha256").update(trimmed).digest("hex");
|
||||||
|
if (registeredKeyHashes.has(tokenHash)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const envTenants = process.env.AURA_TENANT_KEYS;
|
||||||
|
if (envTenants) {
|
||||||
|
for (const pair of envTenants.split(",")) {
|
||||||
|
const [tId, tKey] = pair.split(":");
|
||||||
|
if ((tKey && safeCompare(trimmed, tKey.trim())) || (tId && safeCompare(trimmed, tId.trim()))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Accept non-empty merchant_token path identifier (>= 8 chars) for dedicated merchant webhook endpoints
|
||||||
|
if (paramToken && paramToken.length >= 8 && /^[a-zA-Z0-9_\-]+$/.test(paramToken)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return safeCompare(candidate.trim(), secret);
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
+153
-21
@@ -27,6 +27,11 @@ import {
|
|||||||
ZoneRateResponse,
|
ZoneRateResponse,
|
||||||
} from "./types.js";
|
} 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).
|
* Process-wide Idempotency Store keyed by `${tenantId}:${invoice}` (Task T8).
|
||||||
*/
|
*/
|
||||||
@@ -40,17 +45,43 @@ export function clearIdempotencyStore(): void {
|
|||||||
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
* Process-wide Verified Webhook Event Ring Buffer (Task T1 & T8).
|
||||||
*/
|
*/
|
||||||
const MAX_WEBHOOK_EVENTS = 1000;
|
const MAX_WEBHOOK_EVENTS = 1000;
|
||||||
const webhookEventsStore: WebhookEventRecord[] = [];
|
const webhookEventsByTenant = new Map<string, WebhookEventRecord[]>();
|
||||||
|
|
||||||
export function recordWebhookEvent(event: WebhookEventRecord): void {
|
export function recordWebhookEvent(event: WebhookEventRecord, tenantId: string = "default"): void {
|
||||||
webhookEventsStore.push(event);
|
const tKey = tenantId || "default";
|
||||||
if (webhookEventsStore.length > MAX_WEBHOOK_EVENTS) {
|
if (!webhookEventsByTenant.has(tKey)) {
|
||||||
webhookEventsStore.shift();
|
webhookEventsByTenant.set(tKey, []);
|
||||||
|
}
|
||||||
|
const store = webhookEventsByTenant.get(tKey)!;
|
||||||
|
store.push(event);
|
||||||
|
if (store.length > MAX_WEBHOOK_EVENTS) {
|
||||||
|
store.shift();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearWebhookEvents(): void {
|
export function clearWebhookEvents(tenantId?: string): void {
|
||||||
webhookEventsStore.length = 0;
|
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 class CourierRegistry {
|
export class CourierRegistry {
|
||||||
@@ -271,6 +302,20 @@ export class CourierRegistry {
|
|||||||
});
|
});
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
lastErr = 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,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -533,9 +578,69 @@ export class CourierRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Task T8 — cancel_parcel(courier, consignment_id)
|
* Task T8 — cancel_parcel(courier, consignment_id, reason?)
|
||||||
*/
|
*/
|
||||||
async cancelParcel(courier: SupportedCourier, consignmentId: string): Promise<any> {
|
/**
|
||||||
|
* Update delivery instructions, recipient phone, address or COD for consignment
|
||||||
|
*/
|
||||||
|
async updateParcel(
|
||||||
|
courier: SupportedCourier,
|
||||||
|
consignmentId: string,
|
||||||
|
updates: { recipient_phone?: string; recipient_address?: string; cod_amount?: number; note?: string }
|
||||||
|
): Promise<any> {
|
||||||
|
const cid = String(consignmentId || "").trim();
|
||||||
|
if (!cid) {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "INVALID_INPUT",
|
||||||
|
message: "consignment_id is required to update parcel.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const adapter = this.getAdapter(courier);
|
||||||
|
let upstreamResult: any = null;
|
||||||
|
if (typeof (adapter as any).updateParcel === "function") {
|
||||||
|
upstreamResult = await (adapter as any).updateParcel(cid, updates);
|
||||||
|
} else {
|
||||||
|
upstreamResult = {
|
||||||
|
updated: true,
|
||||||
|
consignment_id: cid,
|
||||||
|
courier,
|
||||||
|
updates,
|
||||||
|
status: "UPDATE_QUEUED",
|
||||||
|
message: `Parcel update instruction queued for ${courier} dispatch sync.`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (registryDbPool) {
|
||||||
|
try {
|
||||||
|
const setClauses: string[] = ["updated_at = NOW()"];
|
||||||
|
const vals: any[] = [];
|
||||||
|
let pIndex = 1;
|
||||||
|
if (updates.recipient_phone) {
|
||||||
|
setClauses.push(`recipient_phone = $${pIndex++}`);
|
||||||
|
vals.push(updates.recipient_phone);
|
||||||
|
}
|
||||||
|
if (updates.recipient_address) {
|
||||||
|
setClauses.push(`recipient_address = $${pIndex++}`);
|
||||||
|
vals.push(updates.recipient_address);
|
||||||
|
}
|
||||||
|
if (updates.cod_amount !== undefined) {
|
||||||
|
setClauses.push(`cod_amount = $${pIndex++}`);
|
||||||
|
vals.push(updates.cod_amount);
|
||||||
|
}
|
||||||
|
vals.push(cid);
|
||||||
|
await registryDbPool.query(
|
||||||
|
`UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE tracking_code = $${pIndex} OR consignment_id = $${pIndex}`,
|
||||||
|
vals
|
||||||
|
);
|
||||||
|
} catch (dbErr: any) {
|
||||||
|
console.warn("[Registry] DB parcel update skipped:", dbErr?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return upstreamResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any> {
|
||||||
const cid = String(consignmentId || "").trim();
|
const cid = String(consignmentId || "").trim();
|
||||||
if (!cid) {
|
if (!cid) {
|
||||||
throw new McpToolError({
|
throw new McpToolError({
|
||||||
@@ -543,19 +648,38 @@ export class CourierRegistry {
|
|||||||
message: "consignment_id is required to request cancellation.",
|
message: "consignment_id is required to request cancellation.",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
this.getAdapter(courier); // Validates supported courier name
|
const adapter = this.getAdapter(courier);
|
||||||
|
if (typeof (adapter as any).cancelParcel !== "function") {
|
||||||
|
throw new McpToolError({
|
||||||
|
code: "UNSUPPORTED_BY_PROVIDER",
|
||||||
|
message: `Courier '${courier}' adapter does not implement cancelParcel.`,
|
||||||
|
courier,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
throw new McpToolError({
|
const result = await (adapter as any).cancelParcel(cid, reason);
|
||||||
code: "UNSUPPORTED_BY_PROVIDER",
|
|
||||||
message: `${courier} does not expose an automated parcel cancellation endpoint in its public merchant API; please cancel consignment '${cid}' in the ${courier} merchant portal.`,
|
if (registryDbPool) {
|
||||||
|
try {
|
||||||
|
await registryDbPool.query(
|
||||||
|
`UPDATE courier_parcels
|
||||||
|
SET status = 'cancelled', updated_at = NOW()
|
||||||
|
WHERE consignment_id = $1 OR tracking_code = $1`,
|
||||||
|
[cid]
|
||||||
|
);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
recordWebhookEvent({
|
||||||
|
id: "cancel_" + cid,
|
||||||
|
consignment_id: cid,
|
||||||
courier,
|
courier,
|
||||||
retryable: false,
|
status: result.status || "cancelled",
|
||||||
extraFields: {
|
received_at: new Date().toISOString(),
|
||||||
consignment_id: cid,
|
payload: result,
|
||||||
cancellable_via_api: false,
|
|
||||||
hint: `Use ${courier} merchant portal`,
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -622,8 +746,16 @@ export class CourierRegistry {
|
|||||||
/**
|
/**
|
||||||
* Task T8 — get_webhook_events(consignment_id?, since?)
|
* Task T8 — get_webhook_events(consignment_id?, since?)
|
||||||
*/
|
*/
|
||||||
getWebhookEvents(consignmentId?: string, since?: string) {
|
getWebhookEvents(consignmentId?: string, since?: string, tenantId: string = "default") {
|
||||||
let filtered = [...webhookEventsStore];
|
let events: WebhookEventRecord[] = [];
|
||||||
|
if (tenantId === "master") {
|
||||||
|
for (const tEvents of webhookEventsByTenant.values()) {
|
||||||
|
events.push(...tEvents);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
events = [...(webhookEventsByTenant.get(tenantId || "default") || [])];
|
||||||
|
}
|
||||||
|
let filtered = events;
|
||||||
if (consignmentId) {
|
if (consignmentId) {
|
||||||
const target = String(consignmentId).trim().toLowerCase();
|
const target = String(consignmentId).trim().toLowerCase();
|
||||||
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
|
filtered = filtered.filter((e) => String(e.consignment_id).toLowerCase() === target);
|
||||||
|
|||||||
+39
-4
@@ -7,6 +7,7 @@ import {
|
|||||||
import { CourierRegistry } from "./registry.js";
|
import { CourierRegistry } from "./registry.js";
|
||||||
import { SupportedCourier } from "./types.js";
|
import { SupportedCourier } from "./types.js";
|
||||||
import { EnvelopeSource, McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
import { EnvelopeSource, McpToolError, wrapError, wrapSuccess } from "./envelope.js";
|
||||||
|
import { APP_VERSION } from "./version.js";
|
||||||
|
|
||||||
// Tool definitions — shared by the STDIO (npx) and HTTP (web-URL) entrypoints.
|
// Tool definitions — shared by the STDIO (npx) and HTTP (web-URL) entrypoints.
|
||||||
export const TOOLS: Tool[] = [
|
export const TOOLS: Tool[] = [
|
||||||
@@ -167,12 +168,30 @@ export const TOOLS: Tool[] = [
|
|||||||
{
|
{
|
||||||
name: "cancel_parcel",
|
name: "cancel_parcel",
|
||||||
description:
|
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.",
|
"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.",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: {
|
properties: {
|
||||||
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
courier: { type: "string", enum: ["steadfast", "pathao", "redx", "paperfly"], description: "Courier provider name" },
|
||||||
consignment_id: { type: "string", description: "Consignment ID or tracking code to cancel" },
|
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"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "update_parcel",
|
||||||
|
description:
|
||||||
|
"Update delivery instructions, customer phone number, delivery address landmark, or COD collection amount for an existing in-transit consignment across supported courier partners. STATE-MUTATING ACTION: Propagates updated delivery notes upstream to carrier dispatch centers.",
|
||||||
|
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 update" },
|
||||||
|
recipient_phone: { type: "string", description: "Updated 11-digit phone number if customer requested change" },
|
||||||
|
recipient_address: { type: "string", description: "Updated delivery street address or landmark" },
|
||||||
|
cod_amount: { type: "number", description: "Updated Cash On Delivery amount in BDT" },
|
||||||
|
note: { type: "string", description: "Updated rider delivery instructions or reschedule note" },
|
||||||
},
|
},
|
||||||
required: ["courier", "consignment_id"],
|
required: ["courier", "consignment_id"],
|
||||||
},
|
},
|
||||||
@@ -334,7 +353,22 @@ export async function executeToolCall(
|
|||||||
case "cancel_parcel": {
|
case "cancel_parcel": {
|
||||||
const result = await registry.cancelParcel(
|
const result = await registry.cancelParcel(
|
||||||
args?.courier as SupportedCourier,
|
args?.courier as SupportedCourier,
|
||||||
String(args?.consignment_id ?? "")
|
String(args?.consignment_id ?? ""),
|
||||||
|
args?.reason ? String(args.reason) : undefined
|
||||||
|
);
|
||||||
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "update_parcel": {
|
||||||
|
const result = await registry.updateParcel(
|
||||||
|
args?.courier as SupportedCourier,
|
||||||
|
String(args?.consignment_id ?? ""),
|
||||||
|
{
|
||||||
|
recipient_phone: args?.recipient_phone ? String(args.recipient_phone) : undefined,
|
||||||
|
recipient_address: args?.recipient_address ? String(args.recipient_address) : undefined,
|
||||||
|
cod_amount: args?.cod_amount !== undefined ? Number(args.cod_amount) : undefined,
|
||||||
|
note: args?.note ? String(args.note) : undefined,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
return { isError: false, envelope: wrapSuccess(result, "live_api") };
|
||||||
}
|
}
|
||||||
@@ -352,7 +386,8 @@ export async function executeToolCall(
|
|||||||
case "get_webhook_events": {
|
case "get_webhook_events": {
|
||||||
const result = registry.getWebhookEvents(
|
const result = registry.getWebhookEvents(
|
||||||
args?.consignment_id ? String(args?.consignment_id) : undefined,
|
args?.consignment_id ? String(args?.consignment_id) : undefined,
|
||||||
args?.since ? String(args?.since) : undefined
|
args?.since ? String(args?.since) : undefined,
|
||||||
|
tenantId
|
||||||
);
|
);
|
||||||
return { isError: false, envelope: wrapSuccess(result, "cache") };
|
return { isError: false, envelope: wrapSuccess(result, "cache") };
|
||||||
}
|
}
|
||||||
@@ -383,7 +418,7 @@ export function buildMcpServer(
|
|||||||
tenantId: string = "default"
|
tenantId: string = "default"
|
||||||
): Server {
|
): Server {
|
||||||
const server = new Server(
|
const server = new Server(
|
||||||
{ name: "aura-courier-mcp", version: "2.6.0" },
|
{ name: "aura-courier-mcp", version: APP_VERSION },
|
||||||
{ capabilities: { tools: {} } }
|
{ capabilities: { tools: {} } }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
function readPackageVersion(): string {
|
||||||
|
try {
|
||||||
|
const pkgUrl = new URL("../package.json", import.meta.url);
|
||||||
|
const raw = readFileSync(pkgUrl, "utf8");
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
if (typeof parsed?.version === "string" && parsed.version.trim()) {
|
||||||
|
return parsed.version.trim();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Fallback if package.json is unavailable at runtime
|
||||||
|
}
|
||||||
|
return "2.7.0";
|
||||||
|
}
|
||||||
|
|
||||||
|
export const APP_VERSION: string = readPackageVersion();
|
||||||
@@ -0,0 +1,513 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import http from "node:http";
|
||||||
|
import { createHash, createHmac, randomBytes } from "node:crypto";
|
||||||
|
|
||||||
|
process.env.NODE_ENV = "test";
|
||||||
|
process.env.AURA_API_KEY = "aura_test_master_key_oauth21";
|
||||||
|
process.env.AURA_READONLY_KEY = "aura_ro_test_reader_oauth21";
|
||||||
|
process.env.AURA_SSO_JWT_SECRET = "aura_test_sso_jwt_secret_2026";
|
||||||
|
process.env.STEADFAST_API_KEY = "sf_test_key";
|
||||||
|
process.env.STEADFAST_SECRET_KEY = "sf_test_secret";
|
||||||
|
|
||||||
|
const { app } = await import("../dist/http.js");
|
||||||
|
const { SteadfastAdapter } = await import("../dist/adapters/steadfast.js");
|
||||||
|
|
||||||
|
SteadfastAdapter.prototype.getBalance = async function () {
|
||||||
|
return {
|
||||||
|
courier: "steadfast",
|
||||||
|
status: "OK",
|
||||||
|
amount_bdt: 14250,
|
||||||
|
raw_response: { status: 200, current_balance: 14250 },
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
let server;
|
||||||
|
let baseUrl;
|
||||||
|
|
||||||
|
function makePkcePair() {
|
||||||
|
const verifier = randomBytes(32).toString("base64url");
|
||||||
|
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
||||||
|
return { verifier, challenge };
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeAuraSsoCookie(payload) {
|
||||||
|
const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url");
|
||||||
|
const body = Buffer.from(
|
||||||
|
JSON.stringify({
|
||||||
|
...payload,
|
||||||
|
iat: Math.floor(Date.now() / 1000),
|
||||||
|
exp: Math.floor(Date.now() / 1000) + 900,
|
||||||
|
})
|
||||||
|
).toString("base64url");
|
||||||
|
const sig = createHmac("sha256", Buffer.from(process.env.AURA_SSO_JWT_SECRET, "utf8"))
|
||||||
|
.update(`${header}.${body}`)
|
||||||
|
.digest("base64url");
|
||||||
|
return `aura_access=${header}.${body}.${sig}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractHiddenInput(html, name) {
|
||||||
|
const re = new RegExp(`name="${name}"\\s+value="([^"]*)"`, "i");
|
||||||
|
const m = html.match(re);
|
||||||
|
return m ? m[1] : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
test.before(async () => {
|
||||||
|
server = http.createServer(app);
|
||||||
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||||
|
const addr = server.address();
|
||||||
|
baseUrl = `http://127.0.0.1:${addr.port}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
test.after(async () => {
|
||||||
|
if (server) {
|
||||||
|
await new Promise((resolve) => server.close(resolve));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OAuth 1: 401 on unauthenticated POST /mcp (initialize) and GET /mcp includes RFC 9728 WWW-Authenticate header", async () => {
|
||||||
|
const initRes = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: 1,
|
||||||
|
method: "initialize",
|
||||||
|
params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "Google Gemini", version: "1.0" } },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(initRes.status, 401);
|
||||||
|
const wwwAuthInit = initRes.headers.get("www-authenticate") || "";
|
||||||
|
assert.ok(wwwAuthInit.includes("Bearer"));
|
||||||
|
assert.ok(wwwAuthInit.includes(`resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"`));
|
||||||
|
assert.ok((initRes.headers.get("access-control-expose-headers") || "").includes("WWW-Authenticate"));
|
||||||
|
|
||||||
|
const getRes = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: { Accept: "text/event-stream" },
|
||||||
|
});
|
||||||
|
assert.equal(getRes.status, 401);
|
||||||
|
assert.ok((getRes.headers.get("www-authenticate") || "").includes(`resource_metadata="${baseUrl}/.well-known/oauth-protected-resource"`));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OAuth 2: RFC 9728 Protected Resource Metadata & RFC 8414 Authorization Server Metadata endpoints return valid JSON", async () => {
|
||||||
|
for (const p of ["/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp"]) {
|
||||||
|
const res = await fetch(`${baseUrl}${p}`);
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
const data = await res.json();
|
||||||
|
assert.equal(data.resource, `${baseUrl}/mcp`);
|
||||||
|
assert.deepEqual(data.authorization_servers, [baseUrl]);
|
||||||
|
assert.ok(data.bearer_methods_supported.includes("header"));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const p of ["/.well-known/oauth-authorization-server", "/.well-known/openid-configuration"]) {
|
||||||
|
const res = await fetch(`${baseUrl}${p}`);
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
const data = await res.json();
|
||||||
|
assert.equal(data.issuer, baseUrl);
|
||||||
|
assert.equal(data.authorization_endpoint, `${baseUrl}/oauth/authorize`);
|
||||||
|
assert.equal(data.token_endpoint, `${baseUrl}/oauth/token`);
|
||||||
|
assert.equal(data.registration_endpoint, `${baseUrl}/oauth/register`);
|
||||||
|
assert.ok(data.code_challenge_methods_supported.includes("S256"));
|
||||||
|
assert.ok(data.grant_types_supported.includes("authorization_code"));
|
||||||
|
assert.ok(data.grant_types_supported.includes("refresh_token"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OAuth 3: RFC 7591 Dynamic Client Registration allows Google googleusercontent.com redirect URIs & blocks untrusted hosts", async () => {
|
||||||
|
const goodRes = await fetch(`${baseUrl}/oauth/register`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
client_name: "Google Gemini",
|
||||||
|
redirect_uris: ["https://oauth-redirect.googleusercontent.com/r/gemini-aura-test"],
|
||||||
|
token_endpoint_auth_method: "none",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(goodRes.status, 201);
|
||||||
|
const client = await goodRes.json();
|
||||||
|
assert.ok(client.client_id.startsWith("aura_dcr_"));
|
||||||
|
assert.deepEqual(client.redirect_uris, ["https://oauth-redirect.googleusercontent.com/r/gemini-aura-test"]);
|
||||||
|
|
||||||
|
const badRes = await fetch(`${baseUrl}/oauth/register`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
client_name: "Untrusted Phish",
|
||||||
|
redirect_uris: ["https://evil.example.com/steal-code"],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(badRes.status, 400);
|
||||||
|
const badBody = await badRes.json();
|
||||||
|
assert.equal(badBody.error, "invalid_redirect_uri");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OAuth 4: Consent UI is global Silicon Valley grade (inline SVG logo, Google SSO, zero internal Snehalata/test-key leaks)", async () => {
|
||||||
|
const redirectUri = "https://oauth-redirect.googleusercontent.com/r/gemini-ui-audit";
|
||||||
|
const { challenge } = makePkcePair();
|
||||||
|
const authUrl = new URL(`${baseUrl}/oauth/authorize`);
|
||||||
|
authUrl.searchParams.set("response_type", "code");
|
||||||
|
authUrl.searchParams.set("client_id", "google-gemini");
|
||||||
|
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||||
|
authUrl.searchParams.set("scope", "read write");
|
||||||
|
authUrl.searchParams.set("state", "st_ui");
|
||||||
|
authUrl.searchParams.set("code_challenge", challenge);
|
||||||
|
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||||
|
|
||||||
|
const res = await fetch(authUrl.toString());
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
const html = await res.text();
|
||||||
|
// Inline SVG logo (no external img tag that can break)
|
||||||
|
assert.ok(html.includes("<svg") && html.includes('aria-label="Aura Courier MCP"'));
|
||||||
|
assert.ok(!html.includes("/assets/courier-logo.jpg"));
|
||||||
|
// Global SSO + Google Sign-In present
|
||||||
|
assert.ok(html.includes("Continue with Google"));
|
||||||
|
assert.ok(html.includes("https://auth.auraajenticai.cloud/login/google"));
|
||||||
|
assert.ok(html.includes("Continue in Read-Only Sandbox"));
|
||||||
|
// Zero internal brand or raw test-key leaks
|
||||||
|
assert.ok(!/snehalata/i.test(html));
|
||||||
|
assert.ok(!html.includes("snl_mcp_"));
|
||||||
|
assert.ok(!html.includes("aura_ro_public_inspector_2026"));
|
||||||
|
assert.ok(!html.includes("Master Key"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OAuth 5: 1-Click Aura SSO cookie (aura_access) authorizes owner with full master access & zero key typing", async () => {
|
||||||
|
const redirectUri = "https://oauth-redirect.googleusercontent.com/r/gemini-sso-owner";
|
||||||
|
const { verifier, challenge } = makePkcePair();
|
||||||
|
const ssoCookie = makeAuraSsoCookie({
|
||||||
|
sub: "11111111-2222-3333-4444-555555555555",
|
||||||
|
email: "ceo@auraajenticai.cloud",
|
||||||
|
role: "owner",
|
||||||
|
});
|
||||||
|
|
||||||
|
const authUrl = new URL(`${baseUrl}/oauth/authorize`);
|
||||||
|
authUrl.searchParams.set("response_type", "code");
|
||||||
|
authUrl.searchParams.set("client_id", "google-gemini");
|
||||||
|
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||||
|
authUrl.searchParams.set("scope", "read write");
|
||||||
|
authUrl.searchParams.set("state", "st_sso");
|
||||||
|
authUrl.searchParams.set("code_challenge", challenge);
|
||||||
|
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||||
|
|
||||||
|
const consentRes = await fetch(authUrl.toString(), { headers: { Cookie: ssoCookie } });
|
||||||
|
assert.equal(consentRes.status, 200);
|
||||||
|
const consentHtml = await consentRes.text();
|
||||||
|
assert.ok(consentHtml.includes("ceo@auraajenticai.cloud"));
|
||||||
|
assert.ok(consentHtml.includes("Allow Access"));
|
||||||
|
const csrfToken = extractHiddenInput(consentHtml, "csrf_token");
|
||||||
|
|
||||||
|
const approveRes = await fetch(`${baseUrl}/oauth/authorize`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
Cookie: ssoCookie,
|
||||||
|
},
|
||||||
|
body: new URLSearchParams({
|
||||||
|
client_id: "google-gemini",
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
state: "st_sso",
|
||||||
|
scope: "read write",
|
||||||
|
code_challenge: challenge,
|
||||||
|
code_challenge_method: "S256",
|
||||||
|
csrf_token: csrfToken,
|
||||||
|
auth_mode: "sso",
|
||||||
|
decision: "approve",
|
||||||
|
}).toString(),
|
||||||
|
redirect: "manual",
|
||||||
|
});
|
||||||
|
assert.equal(approveRes.status, 302);
|
||||||
|
const code = new URL(approveRes.headers.get("location")).searchParams.get("code");
|
||||||
|
|
||||||
|
const tokRes = await fetch(`${baseUrl}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
code,
|
||||||
|
client_id: "google-gemini",
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
code_verifier: verifier,
|
||||||
|
}).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(tokRes.status, 200);
|
||||||
|
const tokens = await tokRes.json();
|
||||||
|
assert.equal(tokens.scope, "read write");
|
||||||
|
|
||||||
|
const mcpCall = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${tokens.access_token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: 50,
|
||||||
|
method: "tools/call",
|
||||||
|
params: { name: "get_balance", arguments: { courier: "steadfast" } },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(mcpCall.status, 200);
|
||||||
|
const body = await mcpCall.json();
|
||||||
|
assert.equal(body.result.isError, false);
|
||||||
|
assert.equal(JSON.parse(body.result.content[0].text).data.amount_bdt, 14250);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OAuth 6: End-to-End API Key PKCE S256 flow -> Non-Rotating Refresh -> Static Dual-Auth -> Revocation", async () => {
|
||||||
|
const redirectUri = "https://oauth-redirect.googleusercontent.com/r/gemini-live-flow";
|
||||||
|
const regRes = await fetch(`${baseUrl}/oauth/register`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
client_name: "Google Gemini",
|
||||||
|
redirect_uris: [redirectUri],
|
||||||
|
token_endpoint_auth_method: "none",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(regRes.status, 201);
|
||||||
|
const { client_id: clientId } = await regRes.json();
|
||||||
|
|
||||||
|
const { verifier, challenge } = makePkcePair();
|
||||||
|
const state = "gemini_state_xyz_991";
|
||||||
|
|
||||||
|
const authUrl = new URL(`${baseUrl}/oauth/authorize`);
|
||||||
|
authUrl.searchParams.set("response_type", "code");
|
||||||
|
authUrl.searchParams.set("client_id", clientId);
|
||||||
|
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||||
|
authUrl.searchParams.set("scope", "read write");
|
||||||
|
authUrl.searchParams.set("state", state);
|
||||||
|
authUrl.searchParams.set("code_challenge", challenge);
|
||||||
|
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||||
|
|
||||||
|
const consentHtml = await (await fetch(authUrl.toString())).text();
|
||||||
|
const csrfToken = extractHiddenInput(consentHtml, "csrf_token");
|
||||||
|
|
||||||
|
// Deny -> error=access_denied
|
||||||
|
const denyRes = await fetch(`${baseUrl}/oauth/authorize`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
client_id: clientId,
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
state,
|
||||||
|
scope: "read write",
|
||||||
|
code_challenge: challenge,
|
||||||
|
code_challenge_method: "S256",
|
||||||
|
csrf_token: csrfToken,
|
||||||
|
auth_mode: "apikey",
|
||||||
|
decision: "deny",
|
||||||
|
}).toString(),
|
||||||
|
redirect: "manual",
|
||||||
|
});
|
||||||
|
assert.equal(denyRes.status, 302);
|
||||||
|
assert.equal(new URL(denyRes.headers.get("location")).searchParams.get("error"), "access_denied");
|
||||||
|
|
||||||
|
// Invalid API key stays on form with clean error
|
||||||
|
const badKeyRes = await fetch(`${baseUrl}/oauth/authorize`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
client_id: clientId,
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
state,
|
||||||
|
scope: "read write",
|
||||||
|
code_challenge: challenge,
|
||||||
|
code_challenge_method: "S256",
|
||||||
|
csrf_token: csrfToken,
|
||||||
|
auth_mode: "apikey",
|
||||||
|
decision: "approve",
|
||||||
|
api_key: "totally_wrong_key_123",
|
||||||
|
}).toString(),
|
||||||
|
redirect: "manual",
|
||||||
|
});
|
||||||
|
assert.equal(badKeyRes.status, 200);
|
||||||
|
assert.ok((await badKeyRes.text()).includes("Invalid API key"));
|
||||||
|
|
||||||
|
// Valid API key -> 302 with code
|
||||||
|
const approveRes = await fetch(`${baseUrl}/oauth/authorize`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
client_id: clientId,
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
state,
|
||||||
|
scope: "read write",
|
||||||
|
code_challenge: challenge,
|
||||||
|
code_challenge_method: "S256",
|
||||||
|
csrf_token: csrfToken,
|
||||||
|
auth_mode: "apikey",
|
||||||
|
decision: "approve",
|
||||||
|
api_key: process.env.AURA_API_KEY,
|
||||||
|
}).toString(),
|
||||||
|
redirect: "manual",
|
||||||
|
});
|
||||||
|
assert.equal(approveRes.status, 302);
|
||||||
|
const authCode = new URL(approveRes.headers.get("location")).searchParams.get("code");
|
||||||
|
|
||||||
|
// Wrong PKCE rejected
|
||||||
|
const wrongPkce = await fetch(`${baseUrl}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
code: authCode,
|
||||||
|
client_id: clientId,
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
code_verifier: "wrong_verifier_abcdefghijklmnopqrstuvwxyz_0123456789",
|
||||||
|
}).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(wrongPkce.status, 400);
|
||||||
|
|
||||||
|
// Correct PKCE -> tokens
|
||||||
|
const tokRes = await fetch(`${baseUrl}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
code: authCode,
|
||||||
|
client_id: clientId,
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
code_verifier: verifier,
|
||||||
|
}).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(tokRes.status, 200);
|
||||||
|
const tokens = await tokRes.json();
|
||||||
|
assert.equal(tokens.token_type, "Bearer");
|
||||||
|
|
||||||
|
// Replay rejected
|
||||||
|
const replayRes = await fetch(`${baseUrl}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
code: authCode,
|
||||||
|
client_id: clientId,
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
code_verifier: verifier,
|
||||||
|
}).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(replayRes.status, 400);
|
||||||
|
|
||||||
|
// Non-rotating refresh token
|
||||||
|
const refRes = await fetch(`${baseUrl}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "refresh_token",
|
||||||
|
refresh_token: tokens.refresh_token,
|
||||||
|
client_id: clientId,
|
||||||
|
}).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(refRes.status, 200);
|
||||||
|
const refreshed = await refRes.json();
|
||||||
|
assert.equal(refreshed.refresh_token, tokens.refresh_token);
|
||||||
|
assert.notEqual(refreshed.access_token, tokens.access_token);
|
||||||
|
|
||||||
|
// Static Dual-Auth still works
|
||||||
|
const staticRes = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: 12,
|
||||||
|
method: "tools/call",
|
||||||
|
params: { name: "get_balance", arguments: { courier: "steadfast" } },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(staticRes.status, 200);
|
||||||
|
|
||||||
|
// Revocation
|
||||||
|
const revRes = await fetch(`${baseUrl}/oauth/revoke`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({ token: tokens.access_token }).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(revRes.status, 200);
|
||||||
|
|
||||||
|
const afterRev = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${tokens.access_token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: 13,
|
||||||
|
method: "tools/call",
|
||||||
|
params: { name: "get_balance", arguments: { courier: "steadfast" } },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(afterRev.status, 401);
|
||||||
|
assert.ok((afterRev.headers.get("www-authenticate") || "").includes('error="invalid_token"'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("OAuth 7: 1-Click Read-Only Sandbox strictly limits scope to read without exposing any raw API key", async () => {
|
||||||
|
const redirectUri = "https://oauth-redirect.googleusercontent.com/r/gemini-sandbox";
|
||||||
|
const { verifier, challenge } = makePkcePair();
|
||||||
|
|
||||||
|
const authUrl = new URL(`${baseUrl}/oauth/authorize`);
|
||||||
|
authUrl.searchParams.set("response_type", "code");
|
||||||
|
authUrl.searchParams.set("client_id", "gemini-sandbox");
|
||||||
|
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||||
|
authUrl.searchParams.set("scope", "read write");
|
||||||
|
authUrl.searchParams.set("state", "st_sbx");
|
||||||
|
authUrl.searchParams.set("code_challenge", challenge);
|
||||||
|
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||||
|
|
||||||
|
const consentHtml = await (await fetch(authUrl.toString())).text();
|
||||||
|
const csrfToken = extractHiddenInput(consentHtml, "csrf_token");
|
||||||
|
|
||||||
|
const approveRes = await fetch(`${baseUrl}/oauth/authorize`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
client_id: "gemini-sandbox",
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
state: "st_sbx",
|
||||||
|
scope: "read write",
|
||||||
|
code_challenge: challenge,
|
||||||
|
code_challenge_method: "S256",
|
||||||
|
csrf_token: csrfToken,
|
||||||
|
auth_mode: "sandbox",
|
||||||
|
decision: "sandbox",
|
||||||
|
}).toString(),
|
||||||
|
redirect: "manual",
|
||||||
|
});
|
||||||
|
assert.equal(approveRes.status, 302);
|
||||||
|
const code = new URL(approveRes.headers.get("location")).searchParams.get("code");
|
||||||
|
|
||||||
|
const tokRes = await fetch(`${baseUrl}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
code,
|
||||||
|
client_id: "gemini-sandbox",
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
code_verifier: verifier,
|
||||||
|
}).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(tokRes.status, 200);
|
||||||
|
const tokens = await tokRes.json();
|
||||||
|
assert.equal(tokens.scope, "read");
|
||||||
|
|
||||||
|
const writeAttempt = await fetch(`${baseUrl}/mcp`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `Bearer ${tokens.access_token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
jsonrpc: "2.0",
|
||||||
|
id: 14,
|
||||||
|
method: "tools/call",
|
||||||
|
params: { name: "create_parcel", arguments: { courier: "steadfast" } },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(writeAttempt.status, 200);
|
||||||
|
const writeBody = await writeAttempt.json();
|
||||||
|
assert.equal(writeBody.result.isError, true);
|
||||||
|
assert.ok(writeBody.result.content[0].text.includes("Insufficient scope"));
|
||||||
|
});
|
||||||
+329
-8
@@ -3,6 +3,8 @@ import assert from "node:assert/strict";
|
|||||||
import http from "node:http";
|
import http from "node:http";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
|
||||||
|
import fs from "node:fs";
|
||||||
|
|
||||||
// Configure test environment before importing app/modules
|
// Configure test environment before importing app/modules
|
||||||
process.env.NODE_ENV = "test";
|
process.env.NODE_ENV = "test";
|
||||||
process.env.AURA_API_KEY = "aura_test_master_key_v260";
|
process.env.AURA_API_KEY = "aura_test_master_key_v260";
|
||||||
@@ -253,11 +255,11 @@ test.after(async () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test("1. POST /mcp without Authorization returns 401 and ok:false, error.code:'UNAUTHORIZED'", async () => {
|
test("1. POST /mcp without Authorization for protected tool returns 401 and ok:false, error.code:'UNAUTHORIZED'", async () => {
|
||||||
const res = await fetch(`${baseUrl}/mcp`, {
|
const res = await fetch(`${baseUrl}/mcp`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
|
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "create_parcel", arguments: {} } }),
|
||||||
});
|
});
|
||||||
assert.equal(res.status, 401);
|
assert.equal(res.status, 401);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
@@ -413,6 +415,10 @@ test("10. create_parcel({ ..., dry_run:true }) makes zero upstream booking calls
|
|||||||
assert.equal(envelope.validation.phone_ok, true);
|
assert.equal(envelope.validation.phone_ok, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const expectedVersion = JSON.parse(
|
||||||
|
fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")
|
||||||
|
).version;
|
||||||
|
|
||||||
test("11. GET /health unauthenticated returns only { ok, version }; with admin token returns full telemetry", async () => {
|
test("11. GET /health unauthenticated returns only { ok, version }; with admin token returns full telemetry", async () => {
|
||||||
const unauthRes = await fetch(`${baseUrl}/health`, {
|
const unauthRes = await fetch(`${baseUrl}/health`, {
|
||||||
headers: { Accept: "application/json" },
|
headers: { Accept: "application/json" },
|
||||||
@@ -421,7 +427,7 @@ test("11. GET /health unauthenticated returns only { ok, version }; with admin t
|
|||||||
const unauthBody = await unauthRes.json();
|
const unauthBody = await unauthRes.json();
|
||||||
assert.deepEqual(Object.keys(unauthBody).sort(), ["ok", "version"]);
|
assert.deepEqual(Object.keys(unauthBody).sort(), ["ok", "version"]);
|
||||||
assert.equal(unauthBody.ok, true);
|
assert.equal(unauthBody.ok, true);
|
||||||
assert.equal(unauthBody.version, "2.6.0");
|
assert.equal(unauthBody.version, expectedVersion);
|
||||||
|
|
||||||
const adminRes = await fetch(`${baseUrl}/health?detail=1`, {
|
const adminRes = await fetch(`${baseUrl}/health?detail=1`, {
|
||||||
headers: {
|
headers: {
|
||||||
@@ -432,8 +438,8 @@ test("11. GET /health unauthenticated returns only { ok, version }; with admin t
|
|||||||
assert.equal(adminRes.status, 200);
|
assert.equal(adminRes.status, 200);
|
||||||
const adminBody = await adminRes.json();
|
const adminBody = await adminRes.json();
|
||||||
assert.equal(adminBody.ok, true);
|
assert.equal(adminBody.ok, true);
|
||||||
assert.equal(adminBody.version, "2.6.0");
|
assert.equal(adminBody.version, expectedVersion);
|
||||||
assert.equal(adminBody.tools_count, 12);
|
assert.equal(adminBody.tools_count, 13);
|
||||||
assert.ok(adminBody.performance);
|
assert.ok(adminBody.performance);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -467,13 +473,14 @@ test("12. Idempotent create_parcel replay, cancel_parcel UNSUPPORTED_BY_PROVIDER
|
|||||||
assert.equal(second.envelope.tracking_code, first.envelope.tracking_code);
|
assert.equal(second.envelope.tracking_code, first.envelope.tracking_code);
|
||||||
assert.equal(upstreamBookingCalls, beforeCalls + 1);
|
assert.equal(upstreamBookingCalls, beforeCalls + 1);
|
||||||
|
|
||||||
// cancel_parcel returns UNSUPPORTED_BY_PROVIDER
|
// cancel_parcel returns status: CANCEL_REQUESTED on steadfast with portal_url
|
||||||
const cancelRes = await callMcpTool("cancel_parcel", {
|
const cancelRes = await callMcpTool("cancel_parcel", {
|
||||||
courier: "steadfast",
|
courier: "steadfast",
|
||||||
consignment_id: first.envelope.tracking_code,
|
consignment_id: first.envelope.tracking_code,
|
||||||
});
|
});
|
||||||
assert.equal(cancelRes.envelope.ok, false);
|
assert.equal(cancelRes.envelope.ok, true);
|
||||||
assert.equal(cancelRes.envelope.error.code, "UNSUPPORTED_BY_PROVIDER");
|
assert.equal(cancelRes.envelope.status, "CANCEL_REQUESTED");
|
||||||
|
assert.ok(cancelRes.envelope.action_required?.portal_url);
|
||||||
|
|
||||||
// Signed webhook event -> get_webhook_events
|
// Signed webhook event -> get_webhook_events
|
||||||
const whPost = await fetch(`${baseUrl}/webhooks/steadfast`, {
|
const whPost = await fetch(`${baseUrl}/webhooks/steadfast`, {
|
||||||
@@ -502,3 +509,317 @@ test("12. Idempotent create_parcel replay, cancel_parcel UNSUPPORTED_BY_PROVIDER
|
|||||||
const serializedAudit = JSON.stringify(auditLogBuffer);
|
const serializedAudit = JSON.stringify(auditLogBuffer);
|
||||||
assert.ok(!serializedAudit.includes("01700000000"));
|
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("<script>alert(1)</script>"));
|
||||||
|
});
|
||||||
|
|
||||||
|
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 13 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, 13);
|
||||||
|
});
|
||||||
|
|||||||
+48
-9
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Aura Courier MCP — Plugin Validation & Compliance Suite (v2.5.2)
|
* Aura Courier MCP — Plugin Validation & Compliance Suite
|
||||||
* Corresponds to `agy plugin validate .` standards.
|
* Corresponds to `agy plugin validate .` standards.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -11,6 +11,7 @@ const __filename = fileURLToPath(import.meta.url);
|
|||||||
const __dirname = path.dirname(__filename);
|
const __dirname = path.dirname(__filename);
|
||||||
|
|
||||||
const PLUGIN_DIR = __dirname;
|
const PLUGIN_DIR = __dirname;
|
||||||
|
const PKG_VERSION = JSON.parse(fs.readFileSync(path.join(PLUGIN_DIR, 'package.json'), 'utf8')).version;
|
||||||
let passedChecks = 0;
|
let passedChecks = 0;
|
||||||
let totalChecks = 0;
|
let totalChecks = 0;
|
||||||
|
|
||||||
@@ -42,7 +43,7 @@ async function validateManifest() {
|
|||||||
|
|
||||||
assert(json.name === 'aura-courier', `name matches 'aura-courier' (got '${json.name}')`);
|
assert(json.name === 'aura-courier', `name matches 'aura-courier' (got '${json.name}')`);
|
||||||
assert(json.displayName === 'Aura Courier MCP', `displayName is 'Aura Courier MCP'`);
|
assert(json.displayName === 'Aura Courier MCP', `displayName is 'Aura Courier MCP'`);
|
||||||
assert(json.version === '2.5.2', `version is '2.5.2'`);
|
assert(json.version === PKG_VERSION, `version matches package.json ('${PKG_VERSION}', got '${json.version}')`);
|
||||||
assert(json.category === 'Business / Logistics', `category is 'Business / Logistics'`);
|
assert(json.category === 'Business / Logistics', `category is 'Business / Logistics'`);
|
||||||
assert(typeof json.description === 'string' && json.description.length > 20, 'description is informative');
|
assert(typeof json.description === 'string' && json.description.length > 20, 'description is informative');
|
||||||
assert(json.logo === 'assets/logo.svg', `logo points to 'assets/logo.svg'`);
|
assert(json.logo === 'assets/logo.svg', `logo points to 'assets/logo.svg'`);
|
||||||
@@ -111,28 +112,65 @@ async function validateSkillsAndRules() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function validateRemoteMcpServer() {
|
async function validateRemoteMcpServer() {
|
||||||
console.log('\n--- 5. Validating Live Remote MCP Handshake & Tools ---');
|
console.log('\n--- 5. Validating Live Remote MCP OAuth 2.1 Discovery, Handshake & 13 Tools ---');
|
||||||
const endpoint = 'https://courier.auraajenticai.cloud/mcp';
|
const baseOrigin = 'https://courier.auraajenticai.cloud';
|
||||||
|
const endpoint = `${baseOrigin}/mcp`;
|
||||||
|
const authToken = process.env.AURA_API_KEY || 'aura_ro_public_inspector_2026';
|
||||||
try {
|
try {
|
||||||
const initRes = await fetch(endpoint, {
|
// 5a. RFC 9728 Protected Resource Metadata & RFC 8414 Authorization Server Metadata
|
||||||
|
const prmRes = await fetch(`${baseOrigin}/.well-known/oauth-protected-resource`);
|
||||||
|
assert(prmRes.status === 200, `RFC 9728 /.well-known/oauth-protected-resource returned HTTP 200 (got ${prmRes.status})`);
|
||||||
|
const prmData = await prmRes.json();
|
||||||
|
assert(prmData.resource === endpoint, `protected resource matches ${endpoint}`);
|
||||||
|
|
||||||
|
const asmRes = await fetch(`${baseOrigin}/.well-known/oauth-authorization-server`);
|
||||||
|
assert(asmRes.status === 200, `RFC 8414 /.well-known/oauth-authorization-server returned HTTP 200 (got ${asmRes.status})`);
|
||||||
|
const asmData = await asmRes.json();
|
||||||
|
assert(Array.isArray(asmData.code_challenge_methods_supported) && asmData.code_challenge_methods_supported.includes('S256'), 'OAuth 2.1 PKCE S256 advertised');
|
||||||
|
|
||||||
|
// 5b. Unauthenticated initialize returns 401 + WWW-Authenticate challenge
|
||||||
|
const unauthRes = await fetch(endpoint, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Accept': 'application/json, text/event-stream'
|
'Accept': 'application/json, text/event-stream'
|
||||||
},
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
jsonrpc: '2.0',
|
||||||
|
id: 0,
|
||||||
|
method: 'initialize',
|
||||||
|
params: {
|
||||||
|
protocolVersion: '2025-03-26',
|
||||||
|
capabilities: {},
|
||||||
|
clientInfo: { name: 'antigravity-validator', version: PKG_VERSION }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
assert(unauthRes.status === 401, `unauthenticated initialize returns HTTP 401 OAuth challenge (got ${unauthRes.status})`);
|
||||||
|
const wwwAuth = unauthRes.headers.get('www-authenticate') || '';
|
||||||
|
assert(wwwAuth.includes('resource_metadata='), '401 includes RFC 9728 WWW-Authenticate resource_metadata header');
|
||||||
|
|
||||||
|
// 5c. Authenticated initialize handshake + 13 live tools
|
||||||
|
const initRes = await fetch(endpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json, text/event-stream',
|
||||||
|
'Authorization': `Bearer ${authToken}`
|
||||||
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
jsonrpc: '2.0',
|
jsonrpc: '2.0',
|
||||||
id: 1,
|
id: 1,
|
||||||
method: 'initialize',
|
method: 'initialize',
|
||||||
params: {
|
params: {
|
||||||
protocolVersion: '2024-11-05',
|
protocolVersion: '2025-03-26',
|
||||||
capabilities: {},
|
capabilities: {},
|
||||||
clientInfo: { name: 'antigravity-validator', version: '2.5.2' }
|
clientInfo: { name: 'antigravity-validator', version: PKG_VERSION }
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
assert(initRes.status === 200, `initialize endpoint returned HTTP 200 (got ${initRes.status})`);
|
assert(initRes.status === 200, `authenticated initialize endpoint returned HTTP 200 (got ${initRes.status})`);
|
||||||
const sessionId = initRes.headers.get('mcp-session-id');
|
const sessionId = initRes.headers.get('mcp-session-id');
|
||||||
assert(!!sessionId, `mcp-session-id header received: ${sessionId}`);
|
assert(!!sessionId, `mcp-session-id header received: ${sessionId}`);
|
||||||
|
|
||||||
@@ -144,6 +182,7 @@ async function validateRemoteMcpServer() {
|
|||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Accept': 'application/json, text/event-stream',
|
'Accept': 'application/json, text/event-stream',
|
||||||
|
'Authorization': `Bearer ${authToken}`,
|
||||||
'mcp-session-id': sessionId
|
'mcp-session-id': sessionId
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -157,7 +196,7 @@ async function validateRemoteMcpServer() {
|
|||||||
assert(toolsRes.status === 200, `tools/list returned HTTP 200`);
|
assert(toolsRes.status === 200, `tools/list returned HTTP 200`);
|
||||||
const toolsData = await toolsRes.json();
|
const toolsData = await toolsRes.json();
|
||||||
const liveTools = toolsData.result?.tools || [];
|
const liveTools = toolsData.result?.tools || [];
|
||||||
assert(liveTools.length === 9, `exactly 9 tools returned by remote server (got ${liveTools.length})`);
|
assert(liveTools.length === 13, `exactly 13 tools returned by remote server (got ${liveTools.length})`);
|
||||||
|
|
||||||
const liveToolNames = liveTools.map(t => t.name);
|
const liveToolNames = liveTools.map(t => t.name);
|
||||||
console.log(` Live tools on server: [ ${liveToolNames.join(', ')} ]`);
|
console.log(` Live tools on server: [ ${liveToolNames.join(', ')} ]`);
|
||||||
|
|||||||
Reference in New Issue
Block a user