1 Commits

65 changed files with 911 additions and 1228 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
# ============================================================================== # ==============================================================================
# Aura Courier MCP (v2.7.2) — Environment Variable Template (NO REAL SECRETS!) # Aura Courier MCP (v2.7.3) — Environment Variable Template (NO REAL SECRETS!)
# ============================================================================== # ==============================================================================
# PRODUCTION RULE: # PRODUCTION RULE:
# - NEVER commit a real `.env` file or bake `.env` into Docker images. # - NEVER commit a real `.env` file or bake `.env` into Docker images.
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Updated .env with official packzy baseUrl",
"updatedAt": "2026-09-01T18:43:06.999339600Z"
}
+6 -3
View File
@@ -23,8 +23,11 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: npm ci run: npm ci
- name: TypeScript type-check & build - name: TypeScript type-check, build & dist parity check
run: npx tsc --noEmit && npm run build run: |
npx tsc --noEmit
npm run build
git diff --exit-code dist/
- name: Run full regression + adversarial security test suite - name: Run full regression + adversarial security test suite
run: npm test run: npm test
@@ -32,7 +35,7 @@ jobs:
- name: Production dependency security audit gate (critical/high) - name: Production dependency security audit gate (critical/high)
run: npm audit --omit=dev --audit-level=high run: npm audit --omit=dev --audit-level=high
- name: Docker image build verification - name: Docker multi-stage non-root build verification
run: docker build -t aura-courier-mcp:ci . run: docker build -t aura-courier-mcp:ci .
- name: Verify Dist Artifacts - name: Verify Dist Artifacts
+1
View File
@@ -2,4 +2,5 @@ node_modules/
.env .env
.env.local .env.local
*.log *.log
*.metadata.json
.system_generated/ .system_generated/
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Gitignore for Aura Courier MCP",
"updatedAt": "2026-09-01T21:33:31.832380100Z"
}
-215
View File
@@ -1,215 +0,0 @@
# AGENTS.md — aura-courier-mcp v2.5.4 → v2.6.0 hardening
> Works for any coding agent (Claude Code, Codex, Antigravity/Gemini, Cursor).
> Save as `AGENTS.md` in the repo root (Claude Code: also copy/symlink to `CLAUDE.md`; Antigravity/Gemini: `GEMINI.md` if it does not read `AGENTS.md`). Then prompt: **"Read AGENTS.md and execute it end to end."**
Repo: https://github.com/auraajenticai/aura-courier-mcp (Apache-2.0, Node, Streamable-HTTP MCP, protocol 2024-11-05)
---
## 0. Ground rules (read first, obey always)
1. **Discover before editing.** Read the repo (entrypoint, tool registry, courier adapters, webhook handlers, config, existing tests, package.json) and write a 10-line "repo map" at the start of your report. Do not assume file names; the ones used below are placeholders.
2. **Never invent facts.** Anything marked `OBSERVED` below was seen in live behavior. Anything marked `UNVERIFIED` you must confirm from code or by running it, then state the result. If you cannot confirm, say so; do not guess.
3. **Never create real shipments or move money.** Do not call real courier booking, cancel, or payout endpoints. Use mocks/nock/fixtures for upstream APIs. No real customer phone numbers in tests; use `01700000000`-style synthetic values only.
4. **No secrets in code, logs, tests, or the report.** Redact API keys, tokens, and merchant IDs.
5. **Backward compatibility.** Do not rename or remove existing tools or existing response fields. Add new fields. Deprecate loudly in descriptions.
6. **Small, reviewable commits** (one per task ID). Run the full test suite before each commit.
7. **Stop and ask** (end your turn with a question) only if a decision cannot be derived from code or this file, e.g. choosing a hosting secret store. Otherwise decide, document in the report, and continue.
8. **Honest reporting.** If a task is partly done, say exactly which acceptance tests pass and which fail.
---
## 1. Global response envelope (all tools)
```json
{
"ok": true,
"data": {},
"error": null,
"meta": {
"request_id": "uuid",
"source": "live_api | static_tariff | cache | validator",
"as_of": "ISO-8601"
}
}
```
On failure: `ok:false`, `data:null`, `error:{code,message,retryable,courier?}`.
Error codes: `UNAUTHORIZED`, `INVALID_INPUT`, `CONSIGNMENT_NOT_FOUND`, `COURIER_NOT_CONFIGURED`, `COURIER_UPSTREAM_ERROR`, `UNSUPPORTED_BY_PROVIDER`, `DUPLICATE_INVOICE`.
Never leak raw axios/HTTP error text. Existing top-level fields (e.g. `success`) stay in place alongside the envelope.
---
## 2. Tasks
### T1 — Authentication on `/mcp` and webhooks (P0)
- **Status:** `UNVERIFIED`. The published client config contains only a URL with no credential. First determine from code whether `/mcp` enforces auth. Write the answer into your report.
- **Required:**
- `Authorization: Bearer <key>` required on `/mcp`. Missing/invalid → HTTP 401 + `UNAUTHORIZED`.
- Key → tenant → that tenant's courier credentials (no shared global credentials across tenants).
- Scopes: `read` (track, compare, fraud, geocode, zone, list, balance), `write` (create_parcel, resolve_ndr_issue, and any new write tool).
- Per-key rate limiting and an audit log (tool, tenant, hash of args, outcome). Do not log raw phone numbers or addresses; hash or mask them.
- Webhooks `/webhooks/{steadfast,pathao,redx,paperfly}`: verify each courier's secret/signature per its documented scheme; reject unsigned/invalid with 401/403. If a courier does not offer signatures, require a per-tenant secret token in the URL or header and document the limitation.
- Update README, homepage config snippet, and `/guide` to show the header.
- **Acceptance:** unauthenticated `POST /mcp tools/list` → 401; valid key → tool list; unsigned webhook → rejected.
### T2 — `resolve_ndr_issue` must not claim actions it did not take (P0)
- **OBSERVED:** the tool is documented as generation-only (sends nothing). For input `{consignment_id:"TEST-0000", courier:"steadfast", issue_type:"customer_phone_off"}` it returned `resolution_status:"CUSTOMER_REENGAGED"`, an action text saying a WhatsApp message "has been sent" (`পাঠানো হয়েছে`), and `carrier_instruction:"HOLD_FOR_CONTACT: Reached customer via messaging… on hold at local hub. Do not RTO."` Nothing was sent, and the consignment does not exist (no validation).
- **Required:** verify the consignment exists using the same logic as `track_parcel` (`CONSIGNMENT_NOT_FOUND` if not). Response `data`:
```json
{
"status": "DRAFT_GENERATED",
"consignment_verified": true,
"actions_executed": [],
"whatsapp_draft": { "language": "bn", "text": "..." },
"courier_ticket_draft": { "subject": "...", "body": "..." },
"recommended_carrier_action": "HOLD | RESCHEDULE | CORRECT_ADDRESS | RETURN",
"requires_manual_execution": true
}
```
- Remove `CUSTOMER_REENGAGED` and any past-tense claims ("sent", "reached", "on hold"). Use suggestive wording only ("প্রস্তাবিত" / "Suggested"). `actions_executed` is non-empty only if a real upstream API call was actually made.
- **Acceptance:** unknown ID → `CONSIGNMENT_NOT_FOUND`; valid ID → `actions_executed == []`, no `CUSTOMER_REENGAGED` anywhere in output.
### T3 — `get_balance` must not return fake zero (P0)
- **OBSERVED:** `get_balance(courier:"pathao")` → `success:true, current_balance:0, raw_response.message:"Pathao payout balance managed via merchant portal"`.
- **Required:** if the provider has no balance API, return:
```json
{ "courier": "pathao", "amount_bdt": null, "pending_bdt": null,
"status": "UNSUPPORTED_BY_PROVIDER", "hint": "Use Pathao merchant portal" }
```
Keep `current_balance` only when it is a real number (otherwise `null`). Steadfast returns real numbers plus `as_of`.
- **Acceptance:** Pathao → `amount_bdt: null` and `status: UNSUPPORTED_BY_PROVIDER`.
### T4 — Single pricing source of truth (P1)
- **OBSERVED:**
- `calculate_delivery_zone_and_fee` uses flat zone fees (Dhaka ≤22 km ৳80, 22–45 km ৳100, >45 km ৳150).
- `compare_courier_rates` returns per-courier fees (Dhanmondi 0.5 kg: Steadfast 70, Pathao 60, RedX 80, Paperfly 80 + COD 15/15/15/23).
- SLA inconsistencies: homepage "24–48h"; tool description "24–72h"; Sylhet (236 km) and Chattogram (255 km) return "৭২–৯৬ ঘণ্টা"; Savar returns "৪৮–৭২ ঘণ্টা".
- Weight surcharges (+20 at 2 kg etc.) match the homepage static table; Chattogram Pathao quote carries a Dhaka-only coverage note.
- **UNVERIFIED (inference):** rates come from a hardcoded table, not live courier rate APIs. Confirm in code.
- **Required:**
- Create one tariff module (courier × zone × weight slab × COD% × SLA hours). Both tools read it. Generate homepage tables and tool descriptions from it.
- `meta.source = "static_tariff"` unless a live courier rate API is genuinely called. Remove "real-time rate" wording where false.
- Use consistent, realistic SLA ranges per zone/courier (propose: inside Dhaka 12–48h, sub-Dhaka 24–72h, outside 48–96h; adjust if courier docs say otherwise and cite the source).
- `coverage_notes` must be route-specific.
- `calculate_delivery_zone_and_fee` data: `{zone, distance_km, standard_fee_bdt, cod_percent, sla_hours:{min,max}, route_summary}` (keep old fields too).
- **Acceptance:** for the same address, both tools report the same `zone` and `sla_hours`; Chattogram quote has no Dhaka-only note.
### T5 — `validate_and_geocode_address` quality flags (P1)
- **OBSERVED:**
- Input `"Road 11, House 24, Dhanmondi, Dhaka"` → `formatted_address:"11, house, 24 Dhanmondi Bridge, Dhaka 1209"`, `location_type:"RANGE_INTERPOLATED"`, `thana:""`, `confidence_score:85`, `is_deliverable:true`.
- Input with `thana:"Uttara"` returned `thana:"Uttara"` (echo of the input), `ROOFTOP`, confidence 98.
- So `thana` appears to be echoed, not resolved.
- **Required** response data:
```json
{
"formatted_address": "...",
"thana_input": "Uttara|null",
"thana_resolved": "string|null",
"district": "...", "division": "...",
"coordinates": {"lat": 0, "lng": 0},
"location_type": "ROOFTOP|RANGE_INTERPOLATED|GEOMETRIC_CENTER|APPROXIMATE",
"confidence_score": 0,
"match_quality": {"road": true, "house": true, "area": true},
"needs_review": false,
"warnings": []
}
```
- Derive `thana_resolved` from Google `address_components` (sublocality / administrative_area_level_3 or equivalent); `null` if absent. Never copy `thana_input` into `thana_resolved`.
- Cap `confidence_score` at 60 when `location_type != ROOFTOP`.
- `needs_review = true` when confidence < 70, `thana_resolved` is null, or road/house tokens from the input are missing in `formatted_address`; add a human-readable `warnings` entry.
- Keep legacy `thana` field but populate it from `thana_resolved` (or `thana_input` marked in `warnings` as unverified).
- **Acceptance:** the Dhanmondi example → `needs_review:true`, `confidence_score <= 60`; thana never equals input unless Google also resolved it.
### T6 — `check_fraud_risk` semantics (P1)
- **OBSERVED:** `check_fraud_risk("01000000000")` → `risk_level:"CRITICAL"`, `delivery_success_rate:"0% (অবৈধ নম্বর / Invalid BD Number)"`, `cancellation_rate:"100%"`, `carrier_source:"operator_prefix_validator"`. `/health` reports `fraud_engine: "Steadfast Nationwide API + BD Prefix Validator"` while the tool description claims "millions of historical consignments nationwide".
- **Required:**
- `risk_level` enum: `INVALID_NUMBER | NO_HISTORY | LOW | MEDIUM | HIGH | CRITICAL`.
- Invalid prefix/length → `INVALID_NUMBER`, `delivery_success_rate: null`, `cancellation_rate: null` (not 0%/100%).
- Add `data_sources: ["steadfast_nationwide","prefix_validator"]` (reflecting what was actually queried), `sample_size`, `coverage_note`.
- Correct the tool description to match the real data sources (confirm in code which providers are queried).
- Never log the full phone number; mask as `017****1234` in logs.
- **Acceptance:** invalid number → `INVALID_NUMBER` with null rates; valid number with no history → `NO_HISTORY`.
### T7 — `track_parcel` and uniform error mapping (P1)
- **OBSERVED:** `track_parcel("SF00000000")` → `Aura Courier MCP Error: Request failed with status code 404`.
- **Required:** if `courier` omitted, auto-detect by prefix, then try all configured couriers. If none match → `ok:false`, `error.code:"CONSIGNMENT_NOT_FOUND"`, plus `couriers_checked:[...]`. Map upstream 401 → `COURIER_UPSTREAM_ERROR` (credential issue, non-retryable), 429/5xx/timeout → `COURIER_UPSTREAM_ERROR` with `retryable:true`. Add timeouts and bounded retry with backoff for GETs only (never auto-retry `create_parcel`).
- **Acceptance:** no raw axios text in any tool output.
### T8 — `create_parcel` safety + missing tools (P2)
- **Required:**
- `dry_run` (default false) returns `{would_book_with, estimated_cost_bdt, validation:{phone_ok,address_ok,needs_review}}` without any upstream booking call.
- Idempotency by `invoice` (per tenant): repeat call returns the existing consignment with `idempotent_replay:true`; never books twice. Persist the mapping.
- Real response data: `{consignment_id, tracking_code, courier, routing_reason, cost_estimate_bdt, cancellable_via_api}`.
- Auto routing (`courier:"auto"`) must record why a courier was chosen.
- New tools (additive): `cancel_parcel(courier, consignment_id)` where the provider API supports it, else `UNSUPPORTED_BY_PROVIDER`; `bulk_create_parcels(items[], dry_run)` with per-item results; `get_webhook_events(consignment_id?, since?)` over stored webhook events.
- Update the tool count in `/health`, homepage and README.
- **Acceptance (mocked upstream only):** two identical invoices → one upstream call, second returns `idempotent_replay:true`; `dry_run` makes zero upstream booking calls.
### T9 — `/health` exposure (P2)
- **OBSERVED:** `/health` publicly returns heap/rss/uptime, active sessions, engine names, webhook paths.
- **Required:** public `GET /health` → `{ok, version}` only. Detailed telemetry only with an admin key.
- **Acceptance:** unauthenticated `/health` has no heap/session/engine fields.
---
## 3. Test plan (all must pass in CI; mock every upstream)
| # | Test |
|---|---|
| 1 | No/invalid bearer → 401 on `/mcp`; unsigned webhook rejected |
| 2 | `resolve_ndr_issue` unknown id → `CONSIGNMENT_NOT_FOUND`; valid id → `actions_executed == []` and no `CUSTOMER_REENGAGED` |
| 3 | `get_balance` pathao → `amount_bdt:null`, `UNSUPPORTED_BY_PROVIDER` |
| 4 | Same address: zone-fee tool and compare tool agree on `zone` and `sla_hours` |
| 5 | Geocode Dhanmondi example → `needs_review:true`, confidence ≤ 60 when not ROOFTOP; thana not echoed as resolved |
| 6 | `check_fraud_risk("01000000000")` → `INVALID_NUMBER`, null rates |
| 7 | `track_parcel("SF00000000")` → `CONSIGNMENT_NOT_FOUND`, no raw axios text |
| 8 | `create_parcel` same invoice twice → one upstream call; second `idempotent_replay:true` |
| 9 | Chattogram 2 kg quote has no Dhaka-only coverage note |
| 10 | Public `/health` exposes only `ok` and `version` |
| 11 | Snapshot test: every tool response validates against the envelope schema |
---
## 4. Order of work
T1 → T2 → T3 → (T4, T5, T6, T7 in any order) → T8 → T9 → tests green → bump to **v2.6.0** → CHANGELOG.md → update README, homepage, `/guide`, tool descriptions.
---
## 5. Out of scope
- Adding new couriers or changing business pricing numbers (only unify and cite them).
- Touching production credentials or running anything against live courier production APIs.
- Rewriting the project in another language/framework.
---
## 6. Final report format (required)
1. **Repo map** (≤10 lines).
2. **Per task:** status (done / partial / blocked), files changed, commit hash, which acceptance tests pass.
3. **Resolved UNVERIFIED items:** T1 auth status before your change (enforced or not), whether rates were static or live, which providers the fraud engine really queries.
4. **Breaking or behavioral changes** a client must know about.
5. **Manual follow-ups** for the owner (key rotation, secret store, courier webhook reconfiguration).
6. **Test output summary** (counts, failures).
If any of the above could not be done, state it plainly instead of omitting it.
+17
View File
@@ -1,5 +1,22 @@
# Changelog # Changelog
## [2.7.3] - 2026-11-27
### Security, Reliability & Parity Hardening
- **PostgreSQL Schema Alignment & Tenant SQL Isolation (`src/registry.ts`, `src/server.ts`, `src/http.ts`)**: Aligned `update_parcel`, `cancel_parcel`, and the 90-day PII retention sweep with live `courier_parcels` columns (`customer_name`, `phone`, `address`, `raw->>'consignment_id'`) and enforced `AND tenant = $...` isolation across updates, cancellations, and synthetic cancellation webhook events.
- **Spoof-Resistant Rate Limiter & OAuth Throttling (`src/middleware/rate_limit.ts`, `src/middleware/oauth.ts`)**: Eliminated `X-Forwarded-For` / `CF-Connecting-IP` private-IP bypasses, validated `CF-Connecting-IP` only with `CF-Ray` + public IP checks, and added dedicated rate limiting on `POST /oauth/register`, `POST /oauth/authorize`, and `POST /oauth/token`.
- **Safe Zero-Token Public Fraud Demo & Explorer (`src/http.ts`, `index.html`, `mcp_explorer.html`)**: Replaced legacy browser demo tokens with a strictly rate-limited server-side `POST /api/public/fraud-demo` endpoint (`10 req/min/IP`, zero token exposure in HTML) and updated `/mcp` browser explorer for clean `tools/list` discovery and optional user-supplied Bearer tokens.
- **Defense-in-Depth `GET /mcp` Auth & Query-Token Scrubbing (`src/http.ts`, `src/middleware/auth.ts`)**: Enforced `req.auraAuth.authenticated` on `GET /mcp` SSE stream resumption, restricted query-string tokens strictly to `/mcp` & `/sse` with immediate URL redaction and `Referrer-Policy: no-referrer`.
- **Multi-Stage Non-Root Docker Runtime & Full `2.7.3` npm/Manifest Parity (`Dockerfile`, `.github/workflows/ci.yml`)**: Converted `Dockerfile` to a deterministic 2-stage `npm ci --omit=dev` non-root (`USER node`) runtime, added `git diff --exit-code dist/` in CI, cleaned repository metadata clutter, and synchronized `package.json`, `server.json`, `plugin.json`, HTML docs, and `npmjs.org` to `v2.7.3`.
## [2.7.2] - 2026-11-27
### Critical Security & Idempotency Remediation
- **Fail-Closed Secret Validation (`P0-01`)**: Removed all fallback default keys; enforced strong minimum-entropy secrets on startup.
- **Webhook Signature & Replay Defense (`P0-02`)**: Removed path-token bypass and secret header echo; added timing-safe secret validation, `±10m` timestamp check, and `HTTP 409` duplicate event replay guard.
- **Auth-First BYOK & Anti-SSRF Carrier Host Allowlist (`P0-03`, `P1-01`)**: Enforced authentication before BYOK evaluation, complete per-carrier credential bundles, `/sse` auth, official `https:` carrier host allowlist, and `maxRedirects: 0`.
- **Public Tracking Redaction & Durable Idempotency (`P1-02`, `P1-03`, `P1-04`, `P1-05`)**: Sanitized public `/track/:code` DTOs, added concurrent in-flight + PostgreSQL durable `invoice` idempotency, halted auto-cascade on ambiguous `5xx`/malformed upstream responses, and upgraded dependencies (`0` npm vulnerabilities).
## [2.7.1] - 2026-11-24 ## [2.7.1] - 2026-11-24
### Added & Improved (Global AI Partner Directory Readiness) ### Added & Improved (Global AI Partner Directory Readiness)
-215
View File
@@ -1,215 +0,0 @@
# AGENTS.md — aura-courier-mcp v2.5.4 → v2.6.0 hardening
> Works for any coding agent (Claude Code, Codex, Antigravity/Gemini, Cursor).
> Save as `AGENTS.md` in the repo root (Claude Code: also copy/symlink to `CLAUDE.md`; Antigravity/Gemini: `GEMINI.md` if it does not read `AGENTS.md`). Then prompt: **"Read AGENTS.md and execute it end to end."**
Repo: https://github.com/auraajenticai/aura-courier-mcp (Apache-2.0, Node, Streamable-HTTP MCP, protocol 2024-11-05)
---
## 0. Ground rules (read first, obey always)
1. **Discover before editing.** Read the repo (entrypoint, tool registry, courier adapters, webhook handlers, config, existing tests, package.json) and write a 10-line "repo map" at the start of your report. Do not assume file names; the ones used below are placeholders.
2. **Never invent facts.** Anything marked `OBSERVED` below was seen in live behavior. Anything marked `UNVERIFIED` you must confirm from code or by running it, then state the result. If you cannot confirm, say so; do not guess.
3. **Never create real shipments or move money.** Do not call real courier booking, cancel, or payout endpoints. Use mocks/nock/fixtures for upstream APIs. No real customer phone numbers in tests; use `01700000000`-style synthetic values only.
4. **No secrets in code, logs, tests, or the report.** Redact API keys, tokens, and merchant IDs.
5. **Backward compatibility.** Do not rename or remove existing tools or existing response fields. Add new fields. Deprecate loudly in descriptions.
6. **Small, reviewable commits** (one per task ID). Run the full test suite before each commit.
7. **Stop and ask** (end your turn with a question) only if a decision cannot be derived from code or this file, e.g. choosing a hosting secret store. Otherwise decide, document in the report, and continue.
8. **Honest reporting.** If a task is partly done, say exactly which acceptance tests pass and which fail.
---
## 1. Global response envelope (all tools)
```json
{
"ok": true,
"data": {},
"error": null,
"meta": {
"request_id": "uuid",
"source": "live_api | static_tariff | cache | validator",
"as_of": "ISO-8601"
}
}
```
On failure: `ok:false`, `data:null`, `error:{code,message,retryable,courier?}`.
Error codes: `UNAUTHORIZED`, `INVALID_INPUT`, `CONSIGNMENT_NOT_FOUND`, `COURIER_NOT_CONFIGURED`, `COURIER_UPSTREAM_ERROR`, `UNSUPPORTED_BY_PROVIDER`, `DUPLICATE_INVOICE`.
Never leak raw axios/HTTP error text. Existing top-level fields (e.g. `success`) stay in place alongside the envelope.
---
## 2. Tasks
### T1 — Authentication on `/mcp` and webhooks (P0)
- **Status:** `UNVERIFIED`. The published client config contains only a URL with no credential. First determine from code whether `/mcp` enforces auth. Write the answer into your report.
- **Required:**
- `Authorization: Bearer <key>` required on `/mcp`. Missing/invalid → HTTP 401 + `UNAUTHORIZED`.
- Key → tenant → that tenant's courier credentials (no shared global credentials across tenants).
- Scopes: `read` (track, compare, fraud, geocode, zone, list, balance), `write` (create_parcel, resolve_ndr_issue, and any new write tool).
- Per-key rate limiting and an audit log (tool, tenant, hash of args, outcome). Do not log raw phone numbers or addresses; hash or mask them.
- Webhooks `/webhooks/{steadfast,pathao,redx,paperfly}`: verify each courier's secret/signature per its documented scheme; reject unsigned/invalid with 401/403. If a courier does not offer signatures, require a per-tenant secret token in the URL or header and document the limitation.
- Update README, homepage config snippet, and `/guide` to show the header.
- **Acceptance:** unauthenticated `POST /mcp tools/list` → 401; valid key → tool list; unsigned webhook → rejected.
### T2 — `resolve_ndr_issue` must not claim actions it did not take (P0)
- **OBSERVED:** the tool is documented as generation-only (sends nothing). For input `{consignment_id:"TEST-0000", courier:"steadfast", issue_type:"customer_phone_off"}` it returned `resolution_status:"CUSTOMER_REENGAGED"`, an action text saying a WhatsApp message "has been sent" (`পাঠানো হয়েছে`), and `carrier_instruction:"HOLD_FOR_CONTACT: Reached customer via messaging… on hold at local hub. Do not RTO."` Nothing was sent, and the consignment does not exist (no validation).
- **Required:** verify the consignment exists using the same logic as `track_parcel` (`CONSIGNMENT_NOT_FOUND` if not). Response `data`:
```json
{
"status": "DRAFT_GENERATED",
"consignment_verified": true,
"actions_executed": [],
"whatsapp_draft": { "language": "bn", "text": "..." },
"courier_ticket_draft": { "subject": "...", "body": "..." },
"recommended_carrier_action": "HOLD | RESCHEDULE | CORRECT_ADDRESS | RETURN",
"requires_manual_execution": true
}
```
- Remove `CUSTOMER_REENGAGED` and any past-tense claims ("sent", "reached", "on hold"). Use suggestive wording only ("প্রস্তাবিত" / "Suggested"). `actions_executed` is non-empty only if a real upstream API call was actually made.
- **Acceptance:** unknown ID → `CONSIGNMENT_NOT_FOUND`; valid ID → `actions_executed == []`, no `CUSTOMER_REENGAGED` anywhere in output.
### T3 — `get_balance` must not return fake zero (P0)
- **OBSERVED:** `get_balance(courier:"pathao")` → `success:true, current_balance:0, raw_response.message:"Pathao payout balance managed via merchant portal"`.
- **Required:** if the provider has no balance API, return:
```json
{ "courier": "pathao", "amount_bdt": null, "pending_bdt": null,
"status": "UNSUPPORTED_BY_PROVIDER", "hint": "Use Pathao merchant portal" }
```
Keep `current_balance` only when it is a real number (otherwise `null`). Steadfast returns real numbers plus `as_of`.
- **Acceptance:** Pathao → `amount_bdt: null` and `status: UNSUPPORTED_BY_PROVIDER`.
### T4 — Single pricing source of truth (P1)
- **OBSERVED:**
- `calculate_delivery_zone_and_fee` uses flat zone fees (Dhaka ≤22 km ৳80, 22–45 km ৳100, >45 km ৳150).
- `compare_courier_rates` returns per-courier fees (Dhanmondi 0.5 kg: Steadfast 70, Pathao 60, RedX 80, Paperfly 80 + COD 15/15/15/23).
- SLA inconsistencies: homepage "24–48h"; tool description "24–72h"; Sylhet (236 km) and Chattogram (255 km) return "৭২–৯৬ ঘণ্টা"; Savar returns "৪৮–৭২ ঘণ্টা".
- Weight surcharges (+20 at 2 kg etc.) match the homepage static table; Chattogram Pathao quote carries a Dhaka-only coverage note.
- **UNVERIFIED (inference):** rates come from a hardcoded table, not live courier rate APIs. Confirm in code.
- **Required:**
- Create one tariff module (courier × zone × weight slab × COD% × SLA hours). Both tools read it. Generate homepage tables and tool descriptions from it.
- `meta.source = "static_tariff"` unless a live courier rate API is genuinely called. Remove "real-time rate" wording where false.
- Use consistent, realistic SLA ranges per zone/courier (propose: inside Dhaka 12–48h, sub-Dhaka 24–72h, outside 48–96h; adjust if courier docs say otherwise and cite the source).
- `coverage_notes` must be route-specific.
- `calculate_delivery_zone_and_fee` data: `{zone, distance_km, standard_fee_bdt, cod_percent, sla_hours:{min,max}, route_summary}` (keep old fields too).
- **Acceptance:** for the same address, both tools report the same `zone` and `sla_hours`; Chattogram quote has no Dhaka-only note.
### T5 — `validate_and_geocode_address` quality flags (P1)
- **OBSERVED:**
- Input `"Road 11, House 24, Dhanmondi, Dhaka"` → `formatted_address:"11, house, 24 Dhanmondi Bridge, Dhaka 1209"`, `location_type:"RANGE_INTERPOLATED"`, `thana:""`, `confidence_score:85`, `is_deliverable:true`.
- Input with `thana:"Uttara"` returned `thana:"Uttara"` (echo of the input), `ROOFTOP`, confidence 98.
- So `thana` appears to be echoed, not resolved.
- **Required** response data:
```json
{
"formatted_address": "...",
"thana_input": "Uttara|null",
"thana_resolved": "string|null",
"district": "...", "division": "...",
"coordinates": {"lat": 0, "lng": 0},
"location_type": "ROOFTOP|RANGE_INTERPOLATED|GEOMETRIC_CENTER|APPROXIMATE",
"confidence_score": 0,
"match_quality": {"road": true, "house": true, "area": true},
"needs_review": false,
"warnings": []
}
```
- Derive `thana_resolved` from Google `address_components` (sublocality / administrative_area_level_3 or equivalent); `null` if absent. Never copy `thana_input` into `thana_resolved`.
- Cap `confidence_score` at 60 when `location_type != ROOFTOP`.
- `needs_review = true` when confidence < 70, `thana_resolved` is null, or road/house tokens from the input are missing in `formatted_address`; add a human-readable `warnings` entry.
- Keep legacy `thana` field but populate it from `thana_resolved` (or `thana_input` marked in `warnings` as unverified).
- **Acceptance:** the Dhanmondi example → `needs_review:true`, `confidence_score <= 60`; thana never equals input unless Google also resolved it.
### T6 — `check_fraud_risk` semantics (P1)
- **OBSERVED:** `check_fraud_risk("01000000000")` → `risk_level:"CRITICAL"`, `delivery_success_rate:"0% (অবৈধ নম্বর / Invalid BD Number)"`, `cancellation_rate:"100%"`, `carrier_source:"operator_prefix_validator"`. `/health` reports `fraud_engine: "Steadfast Nationwide API + BD Prefix Validator"` while the tool description claims "millions of historical consignments nationwide".
- **Required:**
- `risk_level` enum: `INVALID_NUMBER | NO_HISTORY | LOW | MEDIUM | HIGH | CRITICAL`.
- Invalid prefix/length → `INVALID_NUMBER`, `delivery_success_rate: null`, `cancellation_rate: null` (not 0%/100%).
- Add `data_sources: ["steadfast_nationwide","prefix_validator"]` (reflecting what was actually queried), `sample_size`, `coverage_note`.
- Correct the tool description to match the real data sources (confirm in code which providers are queried).
- Never log the full phone number; mask as `017****1234` in logs.
- **Acceptance:** invalid number → `INVALID_NUMBER` with null rates; valid number with no history → `NO_HISTORY`.
### T7 — `track_parcel` and uniform error mapping (P1)
- **OBSERVED:** `track_parcel("SF00000000")` → `Aura Courier MCP Error: Request failed with status code 404`.
- **Required:** if `courier` omitted, auto-detect by prefix, then try all configured couriers. If none match → `ok:false`, `error.code:"CONSIGNMENT_NOT_FOUND"`, plus `couriers_checked:[...]`. Map upstream 401 → `COURIER_UPSTREAM_ERROR` (credential issue, non-retryable), 429/5xx/timeout → `COURIER_UPSTREAM_ERROR` with `retryable:true`. Add timeouts and bounded retry with backoff for GETs only (never auto-retry `create_parcel`).
- **Acceptance:** no raw axios text in any tool output.
### T8 — `create_parcel` safety + missing tools (P2)
- **Required:**
- `dry_run` (default false) returns `{would_book_with, estimated_cost_bdt, validation:{phone_ok,address_ok,needs_review}}` without any upstream booking call.
- Idempotency by `invoice` (per tenant): repeat call returns the existing consignment with `idempotent_replay:true`; never books twice. Persist the mapping.
- Real response data: `{consignment_id, tracking_code, courier, routing_reason, cost_estimate_bdt, cancellable_via_api}`.
- Auto routing (`courier:"auto"`) must record why a courier was chosen.
- New tools (additive): `cancel_parcel(courier, consignment_id)` where the provider API supports it, else `UNSUPPORTED_BY_PROVIDER`; `bulk_create_parcels(items[], dry_run)` with per-item results; `get_webhook_events(consignment_id?, since?)` over stored webhook events.
- Update the tool count in `/health`, homepage and README.
- **Acceptance (mocked upstream only):** two identical invoices → one upstream call, second returns `idempotent_replay:true`; `dry_run` makes zero upstream booking calls.
### T9 — `/health` exposure (P2)
- **OBSERVED:** `/health` publicly returns heap/rss/uptime, active sessions, engine names, webhook paths.
- **Required:** public `GET /health` → `{ok, version}` only. Detailed telemetry only with an admin key.
- **Acceptance:** unauthenticated `/health` has no heap/session/engine fields.
---
## 3. Test plan (all must pass in CI; mock every upstream)
| # | Test |
|---|---|
| 1 | No/invalid bearer → 401 on `/mcp`; unsigned webhook rejected |
| 2 | `resolve_ndr_issue` unknown id → `CONSIGNMENT_NOT_FOUND`; valid id → `actions_executed == []` and no `CUSTOMER_REENGAGED` |
| 3 | `get_balance` pathao → `amount_bdt:null`, `UNSUPPORTED_BY_PROVIDER` |
| 4 | Same address: zone-fee tool and compare tool agree on `zone` and `sla_hours` |
| 5 | Geocode Dhanmondi example → `needs_review:true`, confidence ≤ 60 when not ROOFTOP; thana not echoed as resolved |
| 6 | `check_fraud_risk("01000000000")` → `INVALID_NUMBER`, null rates |
| 7 | `track_parcel("SF00000000")` → `CONSIGNMENT_NOT_FOUND`, no raw axios text |
| 8 | `create_parcel` same invoice twice → one upstream call; second `idempotent_replay:true` |
| 9 | Chattogram 2 kg quote has no Dhaka-only coverage note |
| 10 | Public `/health` exposes only `ok` and `version` |
| 11 | Snapshot test: every tool response validates against the envelope schema |
---
## 4. Order of work
T1 → T2 → T3 → (T4, T5, T6, T7 in any order) → T8 → T9 → tests green → bump to **v2.6.0** → CHANGELOG.md → update README, homepage, `/guide`, tool descriptions.
---
## 5. Out of scope
- Adding new couriers or changing business pricing numbers (only unify and cite them).
- Touching production credentials or running anything against live courier production APIs.
- Rewriting the project in another language/framework.
---
## 6. Final report format (required)
1. **Repo map** (≤10 lines).
2. **Per task:** status (done / partial / blocked), files changed, commit hash, which acceptance tests pass.
3. **Resolved UNVERIFIED items:** T1 auth status before your change (enforced or not), whether rates were static or live, which providers the fraud engine really queries.
4. **Breaking or behavioral changes** a client must know about.
5. **Manual follow-ups** for the owner (key rotation, secret store, courier webhook reconfiguration).
6. **Test output summary** (counts, failures).
If any of the above could not be done, state it plainly instead of omitting it.
+21 -10
View File
@@ -1,24 +1,35 @@
FROM node:20-alpine FROM node:20-alpine AS builder
WORKDIR /build
COPY package*.json tsconfig.json ./
RUN npm ci --no-audit --no-fund
COPY src ./src
RUN npm run build
FROM node:20-alpine AS runtime
WORKDIR /app WORKDIR /app
# Install deps (incl. dev deps for the TypeScript build) # Grant non-root node binary permission to bind port 80 cleanly on any container runtime
COPY package*.json tsconfig.json ./ RUN apk add --no-cache libcap && setcap 'cap_net_bind_service=+ep' /usr/local/bin/node
RUN npm install --no-audit --no-fund
# Source + web, static assets and simulator COPY package*.json ./
COPY src ./src RUN npm ci --omit=dev --ignore-scripts --no-audit --no-fund && npm cache clean --force
COPY --from=builder /build/dist ./dist
COPY assets ./assets COPY assets ./assets
COPY configs ./configs COPY configs ./configs
COPY README.md index.html guide.html health.html privacy.html terms.html mcp_explorer.html simulator.html ./ COPY README.md index.html guide.html health.html privacy.html terms.html mcp_explorer.html simulator.html ./
RUN npm run build
RUN chown -R node:node /app
USER node
ENV NODE_ENV=production ENV NODE_ENV=production
# Listen on 80 so it matches the existing app/proxy port (no label change needed)
ENV PORT=80 ENV PORT=80
EXPOSE 80 EXPOSE 80
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 CMD wget -qO- http://127.0.0.1:80/health || exit 1 HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 CMD wget -qO- http://127.0.0.1:80/health || exit 1
# Remote HTTP MCP endpoint: GET / = landing, POST /mcp = MCP.
# The npm/npx build stays STDIO (dist/index.js, unchanged).
CMD ["node", "dist/http.js"] CMD ["node", "dist/http.js"]
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Dockerfile for Nginx serving the showcase index.html",
"updatedAt": "2026-09-01T21:33:08.518584300Z"
}
-215
View File
@@ -1,215 +0,0 @@
# AGENTS.md — aura-courier-mcp v2.5.4 → v2.6.0 hardening
> Works for any coding agent (Claude Code, Codex, Antigravity/Gemini, Cursor).
> Save as `AGENTS.md` in the repo root (Claude Code: also copy/symlink to `CLAUDE.md`; Antigravity/Gemini: `GEMINI.md` if it does not read `AGENTS.md`). Then prompt: **"Read AGENTS.md and execute it end to end."**
Repo: https://github.com/auraajenticai/aura-courier-mcp (Apache-2.0, Node, Streamable-HTTP MCP, protocol 2024-11-05)
---
## 0. Ground rules (read first, obey always)
1. **Discover before editing.** Read the repo (entrypoint, tool registry, courier adapters, webhook handlers, config, existing tests, package.json) and write a 10-line "repo map" at the start of your report. Do not assume file names; the ones used below are placeholders.
2. **Never invent facts.** Anything marked `OBSERVED` below was seen in live behavior. Anything marked `UNVERIFIED` you must confirm from code or by running it, then state the result. If you cannot confirm, say so; do not guess.
3. **Never create real shipments or move money.** Do not call real courier booking, cancel, or payout endpoints. Use mocks/nock/fixtures for upstream APIs. No real customer phone numbers in tests; use `01700000000`-style synthetic values only.
4. **No secrets in code, logs, tests, or the report.** Redact API keys, tokens, and merchant IDs.
5. **Backward compatibility.** Do not rename or remove existing tools or existing response fields. Add new fields. Deprecate loudly in descriptions.
6. **Small, reviewable commits** (one per task ID). Run the full test suite before each commit.
7. **Stop and ask** (end your turn with a question) only if a decision cannot be derived from code or this file, e.g. choosing a hosting secret store. Otherwise decide, document in the report, and continue.
8. **Honest reporting.** If a task is partly done, say exactly which acceptance tests pass and which fail.
---
## 1. Global response envelope (all tools)
```json
{
"ok": true,
"data": {},
"error": null,
"meta": {
"request_id": "uuid",
"source": "live_api | static_tariff | cache | validator",
"as_of": "ISO-8601"
}
}
```
On failure: `ok:false`, `data:null`, `error:{code,message,retryable,courier?}`.
Error codes: `UNAUTHORIZED`, `INVALID_INPUT`, `CONSIGNMENT_NOT_FOUND`, `COURIER_NOT_CONFIGURED`, `COURIER_UPSTREAM_ERROR`, `UNSUPPORTED_BY_PROVIDER`, `DUPLICATE_INVOICE`.
Never leak raw axios/HTTP error text. Existing top-level fields (e.g. `success`) stay in place alongside the envelope.
---
## 2. Tasks
### T1 — Authentication on `/mcp` and webhooks (P0)
- **Status:** `UNVERIFIED`. The published client config contains only a URL with no credential. First determine from code whether `/mcp` enforces auth. Write the answer into your report.
- **Required:**
- `Authorization: Bearer <key>` required on `/mcp`. Missing/invalid → HTTP 401 + `UNAUTHORIZED`.
- Key → tenant → that tenant's courier credentials (no shared global credentials across tenants).
- Scopes: `read` (track, compare, fraud, geocode, zone, list, balance), `write` (create_parcel, resolve_ndr_issue, and any new write tool).
- Per-key rate limiting and an audit log (tool, tenant, hash of args, outcome). Do not log raw phone numbers or addresses; hash or mask them.
- Webhooks `/webhooks/{steadfast,pathao,redx,paperfly}`: verify each courier's secret/signature per its documented scheme; reject unsigned/invalid with 401/403. If a courier does not offer signatures, require a per-tenant secret token in the URL or header and document the limitation.
- Update README, homepage config snippet, and `/guide` to show the header.
- **Acceptance:** unauthenticated `POST /mcp tools/list` → 401; valid key → tool list; unsigned webhook → rejected.
### T2 — `resolve_ndr_issue` must not claim actions it did not take (P0)
- **OBSERVED:** the tool is documented as generation-only (sends nothing). For input `{consignment_id:"TEST-0000", courier:"steadfast", issue_type:"customer_phone_off"}` it returned `resolution_status:"CUSTOMER_REENGAGED"`, an action text saying a WhatsApp message "has been sent" (`পাঠানো হয়েছে`), and `carrier_instruction:"HOLD_FOR_CONTACT: Reached customer via messaging… on hold at local hub. Do not RTO."` Nothing was sent, and the consignment does not exist (no validation).
- **Required:** verify the consignment exists using the same logic as `track_parcel` (`CONSIGNMENT_NOT_FOUND` if not). Response `data`:
```json
{
"status": "DRAFT_GENERATED",
"consignment_verified": true,
"actions_executed": [],
"whatsapp_draft": { "language": "bn", "text": "..." },
"courier_ticket_draft": { "subject": "...", "body": "..." },
"recommended_carrier_action": "HOLD | RESCHEDULE | CORRECT_ADDRESS | RETURN",
"requires_manual_execution": true
}
```
- Remove `CUSTOMER_REENGAGED` and any past-tense claims ("sent", "reached", "on hold"). Use suggestive wording only ("প্রস্তাবিত" / "Suggested"). `actions_executed` is non-empty only if a real upstream API call was actually made.
- **Acceptance:** unknown ID → `CONSIGNMENT_NOT_FOUND`; valid ID → `actions_executed == []`, no `CUSTOMER_REENGAGED` anywhere in output.
### T3 — `get_balance` must not return fake zero (P0)
- **OBSERVED:** `get_balance(courier:"pathao")` → `success:true, current_balance:0, raw_response.message:"Pathao payout balance managed via merchant portal"`.
- **Required:** if the provider has no balance API, return:
```json
{ "courier": "pathao", "amount_bdt": null, "pending_bdt": null,
"status": "UNSUPPORTED_BY_PROVIDER", "hint": "Use Pathao merchant portal" }
```
Keep `current_balance` only when it is a real number (otherwise `null`). Steadfast returns real numbers plus `as_of`.
- **Acceptance:** Pathao → `amount_bdt: null` and `status: UNSUPPORTED_BY_PROVIDER`.
### T4 — Single pricing source of truth (P1)
- **OBSERVED:**
- `calculate_delivery_zone_and_fee` uses flat zone fees (Dhaka ≤22 km ৳80, 22–45 km ৳100, >45 km ৳150).
- `compare_courier_rates` returns per-courier fees (Dhanmondi 0.5 kg: Steadfast 70, Pathao 60, RedX 80, Paperfly 80 + COD 15/15/15/23).
- SLA inconsistencies: homepage "24–48h"; tool description "24–72h"; Sylhet (236 km) and Chattogram (255 km) return "৭২–৯৬ ঘণ্টা"; Savar returns "৪৮–৭২ ঘণ্টা".
- Weight surcharges (+20 at 2 kg etc.) match the homepage static table; Chattogram Pathao quote carries a Dhaka-only coverage note.
- **UNVERIFIED (inference):** rates come from a hardcoded table, not live courier rate APIs. Confirm in code.
- **Required:**
- Create one tariff module (courier × zone × weight slab × COD% × SLA hours). Both tools read it. Generate homepage tables and tool descriptions from it.
- `meta.source = "static_tariff"` unless a live courier rate API is genuinely called. Remove "real-time rate" wording where false.
- Use consistent, realistic SLA ranges per zone/courier (propose: inside Dhaka 12–48h, sub-Dhaka 24–72h, outside 48–96h; adjust if courier docs say otherwise and cite the source).
- `coverage_notes` must be route-specific.
- `calculate_delivery_zone_and_fee` data: `{zone, distance_km, standard_fee_bdt, cod_percent, sla_hours:{min,max}, route_summary}` (keep old fields too).
- **Acceptance:** for the same address, both tools report the same `zone` and `sla_hours`; Chattogram quote has no Dhaka-only note.
### T5 — `validate_and_geocode_address` quality flags (P1)
- **OBSERVED:**
- Input `"Road 11, House 24, Dhanmondi, Dhaka"` → `formatted_address:"11, house, 24 Dhanmondi Bridge, Dhaka 1209"`, `location_type:"RANGE_INTERPOLATED"`, `thana:""`, `confidence_score:85`, `is_deliverable:true`.
- Input with `thana:"Uttara"` returned `thana:"Uttara"` (echo of the input), `ROOFTOP`, confidence 98.
- So `thana` appears to be echoed, not resolved.
- **Required** response data:
```json
{
"formatted_address": "...",
"thana_input": "Uttara|null",
"thana_resolved": "string|null",
"district": "...", "division": "...",
"coordinates": {"lat": 0, "lng": 0},
"location_type": "ROOFTOP|RANGE_INTERPOLATED|GEOMETRIC_CENTER|APPROXIMATE",
"confidence_score": 0,
"match_quality": {"road": true, "house": true, "area": true},
"needs_review": false,
"warnings": []
}
```
- Derive `thana_resolved` from Google `address_components` (sublocality / administrative_area_level_3 or equivalent); `null` if absent. Never copy `thana_input` into `thana_resolved`.
- Cap `confidence_score` at 60 when `location_type != ROOFTOP`.
- `needs_review = true` when confidence < 70, `thana_resolved` is null, or road/house tokens from the input are missing in `formatted_address`; add a human-readable `warnings` entry.
- Keep legacy `thana` field but populate it from `thana_resolved` (or `thana_input` marked in `warnings` as unverified).
- **Acceptance:** the Dhanmondi example → `needs_review:true`, `confidence_score <= 60`; thana never equals input unless Google also resolved it.
### T6 — `check_fraud_risk` semantics (P1)
- **OBSERVED:** `check_fraud_risk("01000000000")` → `risk_level:"CRITICAL"`, `delivery_success_rate:"0% (অবৈধ নম্বর / Invalid BD Number)"`, `cancellation_rate:"100%"`, `carrier_source:"operator_prefix_validator"`. `/health` reports `fraud_engine: "Steadfast Nationwide API + BD Prefix Validator"` while the tool description claims "millions of historical consignments nationwide".
- **Required:**
- `risk_level` enum: `INVALID_NUMBER | NO_HISTORY | LOW | MEDIUM | HIGH | CRITICAL`.
- Invalid prefix/length → `INVALID_NUMBER`, `delivery_success_rate: null`, `cancellation_rate: null` (not 0%/100%).
- Add `data_sources: ["steadfast_nationwide","prefix_validator"]` (reflecting what was actually queried), `sample_size`, `coverage_note`.
- Correct the tool description to match the real data sources (confirm in code which providers are queried).
- Never log the full phone number; mask as `017****1234` in logs.
- **Acceptance:** invalid number → `INVALID_NUMBER` with null rates; valid number with no history → `NO_HISTORY`.
### T7 — `track_parcel` and uniform error mapping (P1)
- **OBSERVED:** `track_parcel("SF00000000")` → `Aura Courier MCP Error: Request failed with status code 404`.
- **Required:** if `courier` omitted, auto-detect by prefix, then try all configured couriers. If none match → `ok:false`, `error.code:"CONSIGNMENT_NOT_FOUND"`, plus `couriers_checked:[...]`. Map upstream 401 → `COURIER_UPSTREAM_ERROR` (credential issue, non-retryable), 429/5xx/timeout → `COURIER_UPSTREAM_ERROR` with `retryable:true`. Add timeouts and bounded retry with backoff for GETs only (never auto-retry `create_parcel`).
- **Acceptance:** no raw axios text in any tool output.
### T8 — `create_parcel` safety + missing tools (P2)
- **Required:**
- `dry_run` (default false) returns `{would_book_with, estimated_cost_bdt, validation:{phone_ok,address_ok,needs_review}}` without any upstream booking call.
- Idempotency by `invoice` (per tenant): repeat call returns the existing consignment with `idempotent_replay:true`; never books twice. Persist the mapping.
- Real response data: `{consignment_id, tracking_code, courier, routing_reason, cost_estimate_bdt, cancellable_via_api}`.
- Auto routing (`courier:"auto"`) must record why a courier was chosen.
- New tools (additive): `cancel_parcel(courier, consignment_id)` where the provider API supports it, else `UNSUPPORTED_BY_PROVIDER`; `bulk_create_parcels(items[], dry_run)` with per-item results; `get_webhook_events(consignment_id?, since?)` over stored webhook events.
- Update the tool count in `/health`, homepage and README.
- **Acceptance (mocked upstream only):** two identical invoices → one upstream call, second returns `idempotent_replay:true`; `dry_run` makes zero upstream booking calls.
### T9 — `/health` exposure (P2)
- **OBSERVED:** `/health` publicly returns heap/rss/uptime, active sessions, engine names, webhook paths.
- **Required:** public `GET /health` → `{ok, version}` only. Detailed telemetry only with an admin key.
- **Acceptance:** unauthenticated `/health` has no heap/session/engine fields.
---
## 3. Test plan (all must pass in CI; mock every upstream)
| # | Test |
|---|---|
| 1 | No/invalid bearer → 401 on `/mcp`; unsigned webhook rejected |
| 2 | `resolve_ndr_issue` unknown id → `CONSIGNMENT_NOT_FOUND`; valid id → `actions_executed == []` and no `CUSTOMER_REENGAGED` |
| 3 | `get_balance` pathao → `amount_bdt:null`, `UNSUPPORTED_BY_PROVIDER` |
| 4 | Same address: zone-fee tool and compare tool agree on `zone` and `sla_hours` |
| 5 | Geocode Dhanmondi example → `needs_review:true`, confidence ≤ 60 when not ROOFTOP; thana not echoed as resolved |
| 6 | `check_fraud_risk("01000000000")` → `INVALID_NUMBER`, null rates |
| 7 | `track_parcel("SF00000000")` → `CONSIGNMENT_NOT_FOUND`, no raw axios text |
| 8 | `create_parcel` same invoice twice → one upstream call; second `idempotent_replay:true` |
| 9 | Chattogram 2 kg quote has no Dhaka-only coverage note |
| 10 | Public `/health` exposes only `ok` and `version` |
| 11 | Snapshot test: every tool response validates against the envelope schema |
---
## 4. Order of work
T1 → T2 → T3 → (T4, T5, T6, T7 in any order) → T8 → T9 → tests green → bump to **v2.6.0** → CHANGELOG.md → update README, homepage, `/guide`, tool descriptions.
---
## 5. Out of scope
- Adding new couriers or changing business pricing numbers (only unify and cite them).
- Touching production credentials or running anything against live courier production APIs.
- Rewriting the project in another language/framework.
---
## 6. Final report format (required)
1. **Repo map** (≤10 lines).
2. **Per task:** status (done / partial / blocked), files changed, commit hash, which acceptance tests pass.
3. **Resolved UNVERIFIED items:** T1 auth status before your change (enforced or not), whether rates were static or live, which providers the fraud engine really queries.
4. **Breaking or behavioral changes** a client must know about.
5. **Manual follow-ups** for the owner (key rotation, secret store, courier webhook reconfiguration).
6. **Test output summary** (counts, failures).
If any of the above could not be done, state it plainly instead of omitting it.
+2 -2
View File
@@ -1,4 +1,4 @@
# 🚚 AURA COURIER MCP v2.5.0 — THE ENTERPRISE LOGISTICS MASTER MANUAL # 🚚 AURA COURIER MCP v2.7.3 — 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**
@@ -11,7 +11,7 @@
### Core Architectural Pillars ### Core Architectural Pillars
```mermaid ```mermaid
graph TD graph TD
AI[AI Agent / Vertex AI / Dashboard] -->|Streamable-HTTP / MCP| MCP[Aura Courier MCP Server v2.4] AI[AI Agent / Vertex AI / Dashboard] -->|Streamable-HTTP / MCP| MCP[Aura Courier MCP Server v2.7.3]
subgraph "Intelligent Logic Engines" subgraph "Intelligent Logic Engines"
MCP --> ROUTER[Multi-Carrier Smart Router] MCP --> ROUTER[Multi-Carrier Smart Router]
+27 -14
View File
@@ -1,10 +1,10 @@
# 🚚 AURA COURIER MCP v2.7.1 — THE ENTERPRISE LOGISTICS MASTER MANUAL # 🚚 AURA COURIER MCP v2.7.3 — 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**
[![Google Cloud Partner Advantage](https://img.shields.io/badge/Google_Cloud_Partner-Aura_Ajentic_AI-4285F4?logo=google-cloud&logoColor=white)](https://cloud.google.com/find-a-partner/partner/aura-ajentic-ai) [![Google Cloud Partner Advantage](https://img.shields.io/badge/Google_Cloud_Partner-Aura_Ajentic_AI-4285F4?logo=google-cloud&logoColor=white)](https://cloud.google.com/find-a-partner/partner/aura-ajentic-ai)
[![auraajenticai/aura-courier-mcp MCP server](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp/badges/score.svg)](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp) [![auraajenticai/aura-courier-mcp MCP server](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp/badges/score.svg)](https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp)
[![Antigravity Plugin](https://img.shields.io/badge/Antigravity_Plugin-v2.7.1-0676FF?logo=google&logoColor=white)](plugin.json) [![Antigravity Plugin](https://img.shields.io/badge/Antigravity_Plugin-v2.7.3-0676FF?logo=google&logoColor=white)](plugin.json)
[![User Guide BN/EN](https://img.shields.io/badge/User_Guide-বাংলা_%26_English-f59e0b)](https://courier.auraajenticai.cloud/guide) [![User Guide BN/EN](https://img.shields.io/badge/User_Guide-বাংলা_%26_English-f59e0b)](https://courier.auraajenticai.cloud/guide)
[![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![License: Apache-2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Status](https://img.shields.io/badge/Status-Production%20Active-success.svg)](https://courier.auraajenticai.cloud) [![Status](https://img.shields.io/badge/Status-Production%20Active-success.svg)](https://courier.auraajenticai.cloud)
@@ -24,7 +24,7 @@
### Core Architectural Pillars ### Core Architectural Pillars
```mermaid ```mermaid
graph TD graph TD
AI[AI Agent / Vertex AI / Dashboard] -->|Streamable-HTTP / MCP| MCP[Aura Courier MCP Server v2.4] AI[AI Agent / Vertex AI / Dashboard] -->|Streamable-HTTP / MCP| MCP[Aura Courier MCP Server v2.7.3]
subgraph "Intelligent Logic Engines" subgraph "Intelligent Logic Engines"
MCP --> ROUTER[Multi-Carrier Smart Router] MCP --> ROUTER[Multi-Carrier Smart Router]
@@ -117,9 +117,9 @@ Aura Courier MCP seamlessly interfaces with all tier-1 Bangladesh courier APIs u
--- ---
## 4. The 9 Enterprise Model Context Protocol (MCP) Tools ## 4. The 13 Enterprise Model Context Protocol (MCP) Tools
Aura Courier MCP exports 9 tools conforming to the MCP Specification (`2024-11-05`): Aura Courier MCP exports 13 tools conforming to the MCP Specification (`2025-03-26` / `2024-11-05`):
### 1. `list_couriers` ### 1. `list_couriers`
* **Purpose**: Inspect carrier operational health and active credentials. * **Purpose**: Inspect carrier operational health and active credentials.
@@ -184,13 +184,22 @@ Aura Courier MCP exports 9 tools conforming to the MCP Specification (`2024-11-0
``` ```
* **Returns**: Best recommended courier, savings rationale, and 4 detailed carrier quotes. * **Returns**: Best recommended courier, savings rationale, and 4 detailed carrier quotes.
### 9. `resolve_ndr_issue` *(v2.4 New)* ### 9. `resolve_ndr_issue`
* **Purpose**: Non-Delivery Report (NDR) triage and automated dispute resolution. * **Purpose**: Non-Delivery Report (NDR) triage and automated dispute draft generation.
* **Issues Handled**: `fake_attempt`, `customer_phone_off`, `reschedule_requested`, `wrong_address`, `customer_refused`. * **Issues Handled**: `fake_attempt`, `customer_phone_off`, `reschedule_requested`, `wrong_address`, `customer_refused`.
* **Output**: * **Output**: `customer_whatsapp_message`, `carrier_instruction`, and `resolution_status: "DRAFT_GENERATED"`.
- `customer_whatsapp_message`: Ready-to-send empathetic resolution text in Bengali.
- `carrier_instruction`: Official escalation dispatch ticket preventing Return-To-Origin (RTO). ### 10. `cancel_parcel`
- `resolution_status`: `DISPUTE_FILED`, `RESCHEDULE_QUEUED`, `ADDRESS_UPDATED`, `CUSTOMER_REENGAGED`. * **Purpose**: Request parcel cancellation with strict tenant isolation (`courier`, `consignment_id`, `reason?`).
### 11. `update_parcel`
* **Purpose**: Update delivery instructions, phone, address, or COD amount for an active parcel (`courier`, `consignment_id`, `recipient_phone?`, `recipient_address?`, `cod_amount?`, `note?`).
### 12. `bulk_create_parcels`
* **Purpose**: Validate (`dry_run: true`) or book up to 100 parcels in a batch with isolated per-item error handling and durable idempotency.
### 13. `get_webhook_events`
* **Purpose**: Retrieve normalized tenant-scoped carrier webhook updates (`consignment_id?`, `since?`).
--- ---
@@ -227,7 +236,7 @@ curl -s https://courier.auraajenticai.cloud/health | jq
```json ```json
{ {
"ok": true, "ok": true,
"version": "2.7.1" "version": "2.7.3"
} }
``` ```
@@ -278,7 +287,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.7.1"], "args": ["-y", "aura-courier-mcp@2.7.3"],
"env": { "env": {
"PORT": "8080", "PORT": "8080",
"GOOGLE_MAPS_API_KEY": "<GOOGLE_MAPS_API_KEY>", "GOOGLE_MAPS_API_KEY": "<GOOGLE_MAPS_API_KEY>",
@@ -324,7 +333,7 @@ Or declare in your Antigravity `plugins.json`:
} }
} }
``` ```
Bundles the complete `courier-ops` skill (9 tools), `rules/COURIER_RULES.md` (smart auto-routing cascade & zero-mock policies), and `mcp_config.json`. Bundles the complete `courier-ops` skill (13 tools), `rules/COURIER_RULES.md` (smart auto-routing cascade & zero-mock policies), and `mcp_config.json`.
--- ---
@@ -340,6 +349,10 @@ 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.3 (Nov 27, 2026)**:
- **Zero-Defect Security, SQL Schema & Registry Parity Release**: Fixed `courier_parcels` SQL column alignment & strict `AND tenant = $...` isolation across `update_parcel`, `cancel_parcel`, and 90-day PII retention; hardened `rate_limit.ts` against `X-Forwarded-For`/`CF-Connecting-IP` spoofing and added OAuth endpoint rate limits; replaced legacy browser demo keys with safe server-side `/api/public/fraud-demo`; enforced `GET /mcp` SSE session auth & query-token URL redaction; upgraded `Dockerfile` to multi-stage non-root (`USER node`); published `2.7.3` to `npmjs.org`.
* **v2.7.2 (Nov 27, 2026)**:
- **Enterprise Security Hardening**: Fail-closed startup secret validation, timing-safe webhook verification + `409` replay defense, auth-first BYOK + official HTTPS carrier host allowlist (`maxRedirects: 0`), public tracking PII/COD redaction, concurrent + PostgreSQL durable `invoice` idempotency, and ambiguous-outcome cascade halt (`0` npm vulnerabilities).
* **v2.7.1 (Nov 24, 2026)**: * **v2.7.1 (Nov 24, 2026)**:
- **Global AI Agent Partner Directory Certification Ready**: Added MCP 2025-03-26 tool annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) on all 13 tools, `claude.com` + global AI/automation OAuth partner redirects, official Antigravity `$schema` + `serverUrl` + 13-tool `SKILL.md`, Official MCP Registry `remotes` in `server.json`, live `/terms` Terms of Service, and npm `2.7.1` sync. - **Global AI Agent Partner Directory Certification Ready**: Added MCP 2025-03-26 tool annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) on all 13 tools, `claude.com` + global AI/automation OAuth partner redirects, official Antigravity `$schema` + `serverUrl` + 13-tool `SKILL.md`, Official MCP Registry `remotes` in `server.json`, live `/terms` Terms of Service, and npm `2.7.1` sync.
* **v2.7.0 (Nov 24, 2026)**: * **v2.7.0 (Nov 24, 2026)**:
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Production README.md for Aura Courier MCP on GitHub",
"updatedAt": "2026-09-01T21:33:17.243703500Z"
}
+9 -8
View File
@@ -4,16 +4,17 @@
| Version | Supported | | Version | Supported |
| ------- | ------------------ | | ------- | ------------------ |
| 2.5.x | :white_check_mark: | | 2.7.x | :white_check_mark: |
| 2.4.x | :white_check_mark: | | 2.6.x | :white_check_mark: |
| < 2.4.0 | :x: | | < 2.6.0 | :x: |
## Zero-Knowledge AES-256 Credential Vault Guarantee ## Zero-Knowledge & Fail-Closed Security Architecture
**Aura Courier MCP** enforces strict **Zero-Knowledge Cryptographic Isolation** for all merchant courier and e-commerce store credentials: **Aura Courier MCP** enforces strict cryptographic isolation, fail-closed startup validation, and defense-in-depth protections:
1. **AES-256-CBC Encryption at Rest**: Whenever a merchant connects Steadfast, Pathao, RedX, Paperfly, WooCommerce, or Shopify API keys, credentials are immediately encrypted using AES-256-CBC before being stored in the isolated tenant vault. 1. **Fail-Closed Secret Validation**: Production startup refuses weak, short, or placeholder secrets across `AURA_API_KEY`, `AURA_ADMIN_KEY`, `AURA_READONLY_KEY`, `AURA_WEBHOOK_SECRET`, and `AURA_OAUTH_SECRET`.
2. **Zero Admin Visibility**: Platform administrators and engineers cannot view, inspect, or export any client's raw courier API keys. 2. **AES-256-GCM / SHA-256 Tenant Vault Isolation**: Dynamic tenant credentials and API key hashes are isolated per tenant in PostgreSQL (`aura_courier_runtime` least-privilege DB role) with strict `AND tenant = $...` SQL enforcement.
3. **Transient In-Memory Execution**: Direct MCP header credentials (`x-steadfast-api-key`, `x-pathao-client-id`, etc.) exist strictly in isolated request memory for the duration of the tool call and are never written to disk or application logs. 3. **Transient Authenticated BYOK & Anti-SSRF Allowlist**: Direct MCP header credentials (`x-steadfast-api-key`, `x-pathao-client-id`, etc.) require prior Aura authentication, enforce complete credential bundles, exist strictly in isolated request memory, and restrict carrier base URLs to official HTTPS carrier hostnames (`maxRedirects: 0`).
4. **OAuth 2.1 + PKCE (`S256`) & Replay-Protected Webhooks**: Supports RFC 9728 / RFC 8414 / RFC 7591 OAuth 2.1 with PKCE `S256`, spoof-resistant IP rate limiting, and timing-safe webhook verification with `±10m` replay protection (`HTTP 409`).
## Reporting a Vulnerability ## Reporting a Vulnerability
+1 -1
View File
@@ -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 aura-courier-mcp@2.7.1` `npx -y aura-courier-mcp@2.7.3`
--- ---
+1 -1
View File
@@ -9,7 +9,7 @@
}, },
"aura-courier-local": { "aura-courier-local": {
"command": "npx", "command": "npx",
"args": ["-y", "aura-courier-mcp@2.7.1"], "args": ["-y", "aura-courier-mcp@2.7.3"],
"env": { "env": {
"PORT": "8080" "PORT": "8080"
} }
+1 -1
View File
@@ -6,7 +6,7 @@
}, },
"aura-courier-stdio": { "aura-courier-stdio": {
"command": "npx", "command": "npx",
"args": ["-y", "aura-courier-mcp@2.7.1"] "args": ["-y", "aura-courier-mcp@2.7.3"]
} }
} }
} }
+4
View File
@@ -1,5 +1,9 @@
import { type Express, type Request } from "express"; import { type Express, type Request } from "express";
import { EnvSource } from "./config.js"; import { EnvSource } from "./config.js";
/**
* NEW-01 Fix: Automated Data Retention Engine (Daily Sweep) aligned to live PostgreSQL `courier_parcels` schema.
*/
export declare function runDataRetentionSweep(pool: any): Promise<number>;
/** /**
* P0-03 & P1-01 Fix: Pull authenticated tenant BYOK keys strictly from request headers. * P0-03 & P1-01 Fix: Pull authenticated tenant BYOK keys strictly from request headers.
* Arbitrary caller base-URL headers are validated against the official HTTPS carrier allowlist * Arbitrary caller base-URL headers are validated against the official HTTPS carrier allowlist
+71 -11
View File
@@ -9,7 +9,7 @@ import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
import { createRateLimiter } from "./middleware/rate_limit.js"; import { createRateLimiter } from "./middleware/rate_limit.js";
import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, authenticateWebhook, validateSecurityConfig, recordAuditLog, initDynamicAuthStore, upsertDynamicKeyHash, setTenantDynamicKeyStatus, listDynamicKeySummaries, } from "./middleware/auth.js"; import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, authenticateWebhook, validateSecurityConfig, recordAuditLog, initDynamicAuthStore, upsertDynamicKeyHash, setTenantDynamicKeyStatus, listDynamicKeySummaries, } from "./middleware/auth.js";
import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js"; import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js";
import { McpToolError, wrapError, wrapSuccess } from "./envelope.js"; import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
import { APP_VERSION } from "./version.js"; import { 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";
@@ -30,18 +30,33 @@ if (process.env.NODE_ENV !== "test" && dbUrl) {
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message); console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
} }
} }
// Automated Data Retention Engine (Daily Midnight Sweep) /**
* NEW-01 Fix: Automated Data Retention Engine (Daily Sweep) aligned to live PostgreSQL `courier_parcels` schema.
*/
export async function runDataRetentionSweep(pool) {
if (!pool)
return 0;
const pruneRes = await pool.query(`UPDATE courier_parcels
SET customer_name = 'ANONYMIZED',
phone = 'ANONYMIZED',
address = 'ANONYMIZED'
WHERE created_at < NOW() - INTERVAL '90 days'
AND (customer_name IS DISTINCT FROM 'ANONYMIZED'
OR phone IS DISTINCT FROM 'ANONYMIZED'
OR address IS DISTINCT FROM 'ANONYMIZED')`);
return pruneRes?.rowCount || 0;
}
setInterval(async () => { setInterval(async () => {
if (dbPool) { if (dbPool) {
try { try {
const pruneRes = await dbPool.query(`UPDATE courier_parcels const pruned = await runDataRetentionSweep(dbPool);
SET recipient_name = 'ANONYMIZED', recipient_phone = 'ANONYMIZED', recipient_address = 'ANONYMIZED' if (pruned > 0) {
WHERE created_at < NOW() - INTERVAL '90 days' AND recipient_name != 'ANONYMIZED'`); console.log(`[Data Retention Engine] Anonymized ${pruned} legacy order records older than 90 days.`);
if (pruneRes.rowCount && pruneRes.rowCount > 0) {
console.log(`[Data Retention Engine] Anonymized ${pruneRes.rowCount} legacy order records older than 90 days.`);
} }
} }
catch (_) { } catch (err) {
console.warn("[Data Retention Engine] Sweep error:", err?.message);
}
} }
}, 24 * 60 * 60 * 1000).unref(); }, 24 * 60 * 60 * 1000).unref();
const PORT = Number(process.env.PORT || 8080); const PORT = Number(process.env.PORT || 8080);
@@ -175,6 +190,8 @@ app.use((req, res, next) => {
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT"); res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT");
res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-redx-api-token, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key"); res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-redx-api-token, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key");
res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate"); res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate");
res.header("Referrer-Policy", "no-referrer");
res.header("X-Content-Type-Options", "nosniff");
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
return res.sendStatus(204); return res.sendStatus(204);
} }
@@ -260,8 +277,9 @@ app.post("/admin/tokens/revoke", async (req, res) => {
const count = await setTenantDynamicKeyStatus(String(b.tenantId), String(b.status || "PAYMENT_DUE")); 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" }); return res.json({ ok: true, tenantId: b.tenantId, updatedKeys: count, status: b.status || "PAYMENT_DUE" });
}); });
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" }); const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "MCP Protocol Gateway" });
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" }); const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
const publicDemoLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 10, name: "Public Fraud Demo" });
const sessions = new Map(); const sessions = new Map();
const sseSessions = new Map(); const sseSessions = new Map();
const SESSION_TTL_MS = 30 * 60 * 1000; const SESSION_TTL_MS = 30 * 60 * 1000;
@@ -409,9 +427,16 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
res.status(400).send("Invalid or missing session ID"); res.status(400).send("Invalid or missing session ID");
return; return;
} }
if (!req.auraAuth?.authenticated) {
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, req.auraAuth?.tenantId === "invalid"));
return res.status(401).json(wrapError(new McpToolError({
code: "UNAUTHORIZED",
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header for active MCP session.",
}), "validator"));
}
const entry = sessions.get(sessionId); const entry = sessions.get(sessionId);
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId; const callerTenant = req.auraAuth.tenantId;
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") { if (entry.tenantId !== callerTenant && callerTenant !== "master") {
return res.status(403).json(wrapError(new McpToolError({ return res.status(403).json(wrapError(new McpToolError({
code: "UNAUTHORIZED", code: "UNAUTHORIZED",
message: "MCP Session belongs to another tenant.", message: "MCP Session belongs to another tenant.",
@@ -792,6 +817,41 @@ app.get("/track/:code", trackingLimiter, async (req, res) => {
</body> </body>
</html>`); </html>`);
}); });
/**
* NEW-03 Fix: Safe Server-Side Public Fraud Demo Endpoint (Zero Browser API Key Exposure).
* Strictly limited to 10 requests/minute/IP and scoped exclusively to check_fraud_risk on valid BD mobile numbers.
*/
app.post("/api/public/fraud-demo", publicDemoLimiter, async (req, res) => {
const rawPhone = String(req.body?.phone || "").trim().replace(/[\s\-()]/g, "").replace(/^\+?88/, "");
if (!/^01[3-9]\d{8}$/.test(rawPhone)) {
return res.status(400).json(wrapError(new McpToolError({
code: "INVALID_INPUT",
message: "Valid 11-digit Bangladesh mobile number (013-019) is required.",
retryable: false,
}), "validator"));
}
try {
const registry = new CourierRegistry(loadConfig(process.env));
const result = await registry.checkFraudRisk(rawPhone);
const safeDto = {
phone_masked: maskPhone(rawPhone),
risk_level: result.risk_level,
delivery_success_rate: result.delivery_success_rate,
cancellation_rate: result.cancellation_rate,
is_verified_buyer: result.is_verified_buyer,
total_parcels: result.total_parcels,
total_delivered: result.total_delivered,
total_cancelled: result.total_cancelled,
sample_size: result.sample_size,
data_sources: result.data_sources,
recommendation: result.recommendation,
};
return res.json(wrapSuccess(safeDto, "live_api"));
}
catch (err) {
return res.status(502).json(wrapError(err, "live_api"));
}
});
/** /**
* Task T9 — Health & Live Telemetry Endpoint * Task T9 — Health & Live Telemetry Endpoint
*/ */
+31 -6
View File
@@ -149,6 +149,10 @@ export function hasByokCredentials(req) {
return validateByokHeaders(req).isByok; return validateByokHeaders(req).isByok;
} }
export function extractBearerToken(req) { export function extractBearerToken(req) {
const cachedQueryTok = req._extractedQueryToken;
if (typeof cachedQueryTok === "string" && cachedQueryTok) {
return cachedQueryTok;
}
const authHeader = req.headers["authorization"] || req.headers["Authorization"]; const authHeader = req.headers["authorization"] || req.headers["Authorization"];
if (typeof authHeader === "string") { if (typeof authHeader === "string") {
const trimmed = authHeader.trim(); const trimmed = authHeader.trim();
@@ -161,12 +165,33 @@ 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) // NEW-05 Fix: Restrict query-parameter tokens strictly to MCP/SSE connector endpoints (never /admin, /track, /webhooks, /oauth)
const q = req.query; // and scrub secret query parameters from req.url / req.originalUrl immediately to prevent downstream log exposure.
if (q) { if (process.env.ALLOW_QUERY_TOKEN !== "false") {
const candidate = q.token || q.key || q.apiKey || q.api_key; const reqPath = (req.path || (req.url ? req.url.split("?")[0] : "")).trim();
if (typeof candidate === "string" && candidate.trim()) { if (reqPath === "/mcp" || reqPath === "/sse" || reqPath === "/messages") {
return candidate.trim(); const q = req.query;
if (q) {
const candidate = q.token || q.key || q.apiKey || q.api_key;
if (typeof candidate === "string" && candidate.trim()) {
const cleanTok = candidate.trim();
req._extractedQueryToken = cleanTok;
req._usedQueryToken = true;
delete q.token;
delete q.key;
delete q.apiKey;
delete q.api_key;
if (typeof req.url === "string" && req.url.includes("?")) {
req.url = req.url.replace(/([?&])(token|key|apiKey|api_key)=[^&]*/gi, "$1[REDACTED]").replace(/\?&/, "?");
}
if (typeof req.originalUrl === "string" && req.originalUrl.includes("?")) {
req.originalUrl = req.originalUrl
.replace(/([?&])(token|key|apiKey|api_key)=[^&]*/gi, "$1[REDACTED]")
.replace(/\?&/, "?");
}
return cleanTok;
}
}
} }
} }
return undefined; return undefined;
+10 -3
View File
@@ -1,5 +1,12 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { resolveAuthContextAsync } from "./auth.js"; import { resolveAuthContextAsync } from "./auth.js";
import { createRateLimiter } from "./rate_limit.js";
const oauthLimiter = createRateLimiter({
windowMs: 60 * 1000,
max: 20,
name: "OAuth 2.1 Security Gateway",
message: "Too many OAuth authentication or registration attempts. Please retry in a minute.",
});
const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour
const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability) const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability)
const AUTH_CODE_TTL_SEC = 300; // 5 minutes const AUTH_CODE_TTL_SEC = 300; // 5 minutes
@@ -978,7 +985,7 @@ export function registerOAuthRoutes(app) {
app.get("/.well-known/oauth-authorization-server/mcp", authServerMetadataHandler); app.get("/.well-known/oauth-authorization-server/mcp", authServerMetadataHandler);
app.get("/.well-known/openid-configuration", authServerMetadataHandler); app.get("/.well-known/openid-configuration", authServerMetadataHandler);
// 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof) // 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof)
app.post("/oauth/register", (req, res) => { app.post("/oauth/register", oauthLimiter, (req, res) => {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
const body = (req.body || {}); const body = (req.body || {});
const rawUris = body.redirect_uris; const rawUris = body.redirect_uris;
@@ -1086,7 +1093,7 @@ export function registerOAuthRoutes(app) {
})); }));
}); });
// 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission) // 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission)
app.post("/oauth/authorize", async (req, res) => { app.post("/oauth/authorize", oauthLimiter, async (req, res) => {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Frame-Options", "DENY"); res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'"); res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
@@ -1217,7 +1224,7 @@ export function registerOAuthRoutes(app) {
return res.redirect(302, callback.toString()); return res.redirect(302, callback.toString());
}); });
// 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token) // 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token)
app.post("/oauth/token", (req, res) => { app.post("/oauth/token", oauthLimiter, (req, res) => {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
res.setHeader("Pragma", "no-cache"); res.setHeader("Pragma", "no-cache");
const b = (req.body || {}); const b = (req.body || {});
+7
View File
@@ -5,5 +5,12 @@ interface RateLimiterOptions {
message?: string; message?: string;
name?: string; name?: string;
} }
/**
* NEW-02 Fix: Spoof-resistant client IP resolution.
* - Never trusts client-prepended leftmost X-Forwarded-For entries or private/loopback header spoofs.
* - Only accepts CF-Connecting-IP when accompanied by CF-Ray AND when CF-Connecting-IP is a valid public IP.
* - Otherwise relies on Express req.ip (with `trust proxy = 1`, which resolves the single trusted reverse-proxy hop).
*/
export declare function resolveRateLimitIp(req: Request): string;
export declare function createRateLimiter(options: RateLimiterOptions): (req: Request, res: Response, next: NextFunction) => void; export declare function createRateLimiter(options: RateLimiterOptions): (req: Request, res: Response, next: NextFunction) => void;
export {}; export {};
+48 -24
View File
@@ -1,3 +1,48 @@
import { isIP } from "node:net";
function normalizeIpLiteral(raw) {
const trimmed = raw.trim();
if (trimmed.startsWith("::ffff:")) {
return trimmed.slice(7);
}
return trimmed;
}
function isPrivateOrLoopbackIp(ip) {
const norm = normalizeIpLiteral(ip).toLowerCase();
if (!norm || norm === "127.0.0.1" || norm === "::1" || norm === "0.0.0.0")
return true;
if (norm.startsWith("127.") || norm.startsWith("10.") || norm.startsWith("192.168.") || norm.startsWith("169.254.")) {
return true;
}
if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(norm)) {
return true;
}
if (norm.startsWith("fc") || norm.startsWith("fd") || norm.startsWith("fe80:")) {
return true;
}
return false;
}
/**
* NEW-02 Fix: Spoof-resistant client IP resolution.
* - Never trusts client-prepended leftmost X-Forwarded-For entries or private/loopback header spoofs.
* - Only accepts CF-Connecting-IP when accompanied by CF-Ray AND when CF-Connecting-IP is a valid public IP.
* - Otherwise relies on Express req.ip (with `trust proxy = 1`, which resolves the single trusted reverse-proxy hop).
*/
export function resolveRateLimitIp(req) {
const cfIpRaw = req.headers["cf-connecting-ip"];
const cfRay = req.headers["cf-ray"];
if (typeof cfIpRaw === "string" && typeof cfRay === "string" && cfRay.trim().length > 0) {
const cfIp = normalizeIpLiteral(cfIpRaw);
if (isIP(cfIp) !== 0 && !isPrivateOrLoopbackIp(cfIp)) {
return cfIp;
}
}
const expressIp = typeof req.ip === "string" && req.ip.trim() ? normalizeIpLiteral(req.ip) : "";
if (expressIp && isIP(expressIp) !== 0) {
return expressIp;
}
const socketIp = req.socket?.remoteAddress ? normalizeIpLiteral(req.socket.remoteAddress) : "";
return socketIp || "unknown";
}
export function createRateLimiter(options) { export function createRateLimiter(options) {
const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options; const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options;
const store = new Map(); const store = new Map();
@@ -11,32 +56,11 @@ export function createRateLimiter(options) {
} }
}, 5 * 60 * 1000).unref(); }, 5 * 60 * 1000).unref();
return (req, res, next) => { return (req, res, next) => {
// Extract Client IP (supporting Cloudflare cf-connecting-ip and reverse proxies like Traefik / Nginx) // Allow high-speed local test execution unless test explicitly requests rate-limit enforcement
const cfIp = req.headers["cf-connecting-ip"]; if (process.env.NODE_ENV === "test" && req.headers["x-test-enforce-ratelimit"] !== "1") {
const xForwardedFor = req.headers["x-forwarded-for"];
let clientIp = "";
if (typeof cfIp === "string") {
clientIp = cfIp.trim();
}
else if (typeof xForwardedFor === "string") {
clientIp = xForwardedFor.split(",")[0].trim();
}
else if (Array.isArray(xForwardedFor) && xForwardedFor.length > 0) {
clientIp = xForwardedFor[0].trim();
}
else {
clientIp = req.socket?.remoteAddress || "unknown";
}
// Bypass loopback and internal orchestration networks
if (clientIp === "127.0.0.1" ||
clientIp === "::1" ||
clientIp === "::ffff:127.0.0.1" ||
clientIp.startsWith("10.") ||
clientIp.startsWith("172.16.") ||
clientIp.startsWith("172.17.") ||
clientIp.startsWith("172.18.")) {
return next(); return next();
} }
const clientIp = resolveRateLimitIp(req);
const now = Date.now(); const now = Date.now();
let record = store.get(clientIp); let record = store.get(clientIp);
if (!record || now > record.resetAt) { if (!record || now > record.resetAt) {
+2 -2
View File
@@ -44,8 +44,8 @@ export declare class CourierRegistry {
recipient_address?: string; recipient_address?: string;
cod_amount?: number; cod_amount?: number;
note?: string; note?: string;
}): Promise<any>; }, tenantId?: string): Promise<any>;
cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any>; cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string, tenantId?: string): Promise<any>;
/** /**
* Task T8 — bulk_create_parcels(items[], dry_run?) * Task T8 — bulk_create_parcels(items[], dry_run?)
*/ */
+32 -10
View File
@@ -652,7 +652,7 @@ export class CourierRegistry {
/** /**
* Update delivery instructions, recipient phone, address or COD for consignment * Update delivery instructions, recipient phone, address or COD for consignment
*/ */
async updateParcel(courier, consignmentId, updates) { async updateParcel(courier, consignmentId, updates, tenantId) {
const cid = String(consignmentId || "").trim(); const cid = String(consignmentId || "").trim();
if (!cid) { if (!cid) {
throw new McpToolError({ throw new McpToolError({
@@ -677,23 +677,35 @@ export class CourierRegistry {
} }
if (registryDbPool) { if (registryDbPool) {
try { try {
const effectiveTenant = String(tenantId || "default").trim() || "default";
const setClauses = ["updated_at = NOW()"]; const setClauses = ["updated_at = NOW()"];
const vals = []; const vals = [];
let pIndex = 1; let pIndex = 1;
if (updates.recipient_phone) { if (updates.recipient_phone) {
setClauses.push(`recipient_phone = $${pIndex++}`); setClauses.push(`phone = $${pIndex++}`);
vals.push(updates.recipient_phone); vals.push(updates.recipient_phone);
} }
if (updates.recipient_address) { if (updates.recipient_address) {
setClauses.push(`recipient_address = $${pIndex++}`); setClauses.push(`address = $${pIndex++}`);
vals.push(updates.recipient_address); vals.push(updates.recipient_address);
} }
if (updates.cod_amount !== undefined) { if (updates.cod_amount !== undefined) {
setClauses.push(`cod_amount = $${pIndex++}`); setClauses.push(`cod_amount = $${pIndex++}`);
vals.push(updates.cod_amount); vals.push(updates.cod_amount);
} }
if (updates.note !== undefined) {
setClauses.push(`raw = jsonb_set(COALESCE(raw, '{}'::jsonb), '{delivery_note}', to_jsonb($${pIndex++}::text), true)`);
vals.push(String(updates.note));
}
const cidIdx = pIndex++;
vals.push(cid); vals.push(cid);
await registryDbPool.query(`UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE tracking_code = $${pIndex} OR consignment_id = $${pIndex}`, vals); let whereClause = `(tracking_code = $${cidIdx} OR raw->>'consignment_id' = $${cidIdx})`;
if (effectiveTenant !== "master") {
const tenantIdx = pIndex++;
vals.push(effectiveTenant);
whereClause += ` AND tenant = $${tenantIdx}`;
}
await registryDbPool.query(`UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE ${whereClause}`, vals);
} }
catch (dbErr) { catch (dbErr) {
console.warn("[Registry] DB parcel update skipped:", dbErr?.message); console.warn("[Registry] DB parcel update skipped:", dbErr?.message);
@@ -701,7 +713,7 @@ export class CourierRegistry {
} }
return upstreamResult; return upstreamResult;
} }
async cancelParcel(courier, consignmentId, reason) { async cancelParcel(courier, consignmentId, reason, tenantId) {
const cid = String(consignmentId || "").trim(); const cid = String(consignmentId || "").trim();
if (!cid) { if (!cid) {
throw new McpToolError({ throw new McpToolError({
@@ -718,13 +730,23 @@ export class CourierRegistry {
}); });
} }
const result = await adapter.cancelParcel(cid, reason); const result = await adapter.cancelParcel(cid, reason);
const effectiveTenant = String(tenantId || "default").trim() || "default";
if (registryDbPool) { if (registryDbPool) {
try { try {
await registryDbPool.query(`UPDATE courier_parcels if (effectiveTenant === "master") {
SET status = 'cancelled', updated_at = NOW() await registryDbPool.query(`UPDATE courier_parcels
WHERE consignment_id = $1 OR tracking_code = $1`, [cid]); SET status = 'cancelled', updated_at = NOW()
WHERE (tracking_code = $1 OR raw->>'consignment_id' = $1)`, [cid]);
}
else {
await registryDbPool.query(`UPDATE courier_parcels
SET status = 'cancelled', updated_at = NOW()
WHERE (tracking_code = $1 OR raw->>'consignment_id' = $1) AND tenant = $2`, [cid, effectiveTenant]);
}
}
catch (dbErr) {
console.warn("[Registry] DB parcel cancellation update skipped:", dbErr?.message);
} }
catch (_) { }
} }
recordWebhookEvent({ recordWebhookEvent({
id: "cancel_" + cid, id: "cancel_" + cid,
@@ -733,7 +755,7 @@ export class CourierRegistry {
status: result.status || "cancelled", status: result.status || "cancelled",
received_at: new Date().toISOString(), received_at: new Date().toISOString(),
payload: result, payload: result,
}); }, effectiveTenant);
return result; return result;
} }
/** /**
+2 -2
View File
@@ -404,7 +404,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
return { isError: false, envelope: wrapSuccess(result, "live_api") }; 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 ?? ""), args?.reason ? String(args.reason) : undefined); const result = await registry.cancelParcel(args?.courier, String(args?.consignment_id ?? ""), args?.reason ? String(args.reason) : undefined, tenantId);
return { isError: false, envelope: wrapSuccess(result, "live_api") }; return { isError: false, envelope: wrapSuccess(result, "live_api") };
} }
case "update_parcel": { case "update_parcel": {
@@ -413,7 +413,7 @@ export async function executeToolCall(registry, name, args = {}, tenantId = "def
recipient_address: args?.recipient_address ? String(args.recipient_address) : undefined, recipient_address: args?.recipient_address ? String(args.recipient_address) : undefined,
cod_amount: args?.cod_amount !== undefined ? Number(args.cod_amount) : undefined, cod_amount: args?.cod_amount !== undefined ? Number(args.cod_amount) : undefined,
note: args?.note ? String(args.note) : undefined, note: args?.note ? String(args.note) : undefined,
}); }, tenantId);
return { isError: false, envelope: wrapSuccess(result, "live_api") }; return { isError: false, envelope: wrapSuccess(result, "live_api") };
} }
case "bulk_create_parcels": { case "bulk_create_parcels": {
+1 -1
View File
@@ -11,6 +11,6 @@ function readPackageVersion() {
catch { catch {
// Fallback if package.json is unavailable at runtime // Fallback if package.json is unavailable at runtime
} }
return "2.7.2"; return "2.7.3";
} }
export const APP_VERSION = readPackageVersion(); export const APP_VERSION = readPackageVersion();
+4 -4
View File
@@ -1605,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.7.1</span> <span class="version-pill">v2.7.3</span>
</div> </div>
</div> </div>
<p class="footer-tagline"> <p class="footer-tagline">
@@ -1657,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.7.1)</span> <span>📦 npm Package (v2.7.3)</span>
</a> </a>
</li> </li>
</ul> </ul>
@@ -1735,7 +1735,7 @@
}, },
"aura-courier-local": { "aura-courier-local": {
"command": "npx", "command": "npx",
"args": ["-y", "aura-courier-mcp@2.7.1"], "args": ["-y", "aura-courier-mcp@2.7.3"],
"env": { "PORT": "8080" } "env": { "PORT": "8080" }
} }
} }
@@ -1752,7 +1752,7 @@
}, },
"aura-courier-stdio": { "aura-courier-stdio": {
"command": "npx", "command": "npx",
"args": ["-y", "aura-courier-mcp@2.7.1"] "args": ["-y", "aura-courier-mcp@2.7.3"]
} }
} }
}, null, 2) }, null, 2)
+2 -2
View File
@@ -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.7.1 · Telemetry</span> <span class="brand-sub">v2.7.3 · 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.7.1 · 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.3 · 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>
+14 -24
View File
@@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Aura Courier MCP v2.7.1 — Multi-Courier Integration for Developers</title> <title>Aura Courier MCP v2.7.3 — Multi-Courier Integration for Developers</title>
<meta name="description" content="Aura Courier MCP — এক কানেক্টরেই ৪ কুরিয়ার (Steadfast, Pathao, RedX, Paperfly) + Google Maps Spatial AI। Model Context Protocol (MCP) server for AI Agents and E-commerce." /> <meta name="description" content="Aura Courier MCP — এক কানেক্টরেই ৪ কুরিয়ার (Steadfast, Pathao, RedX, Paperfly) + Google Maps Spatial AI। Model Context Protocol (MCP) server for AI Agents and E-commerce." />
<link rel="icon" type="image/jpeg" href="/assets/courier-logo.jpg" /> <link rel="icon" type="image/jpeg" href="/assets/courier-logo.jpg" />
@@ -1201,7 +1201,7 @@
<div class="logo-text-wrap"> <div class="logo-text-wrap">
<div class="logo-title"> <div class="logo-title">
<span>Aura Courier MCP</span> <span>Aura Courier MCP</span>
<span class="version-pill">v2.7.1</span> <span class="version-pill">v2.7.3</span>
</div> </div>
<span class="logo-sub">Multi-Courier Integration for Developers</span> <span class="logo-sub">Multi-Courier Integration for Developers</span>
</div> </div>
@@ -2046,7 +2046,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.7.1</span> <span class="version-pill">v2.7.3</span>
</div> </div>
</div> </div>
<p class="footer-tagline"> <p class="footer-tagline">
@@ -2098,7 +2098,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">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg><span>npm Package (v2.7.1)</span> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg><span>npm Package (v2.7.3)</span>
</a> </a>
</li> </li>
</ul> </ul>
@@ -2176,7 +2176,7 @@
</nav> </nav>
<!-- ===== Background Animation Canvas Script ===== --> <!-- ===== Background Animation Canvas Script ===== -->
<script src="/assets/courier-canvas.js?v=2.7.1"></script> <script src="/assets/courier-canvas.js?v=2.7.3"></script>
<script> <script>
if (typeof initCourierCanvas === 'function') { if (typeof initCourierCanvas === 'function') {
initCourierCanvas('hubmap'); initCourierCanvas('hubmap');
@@ -3134,30 +3134,20 @@
operatorEl.style.color = 'var(--cyan)'; operatorEl.style.color = 'var(--cyan)';
} }
fetch('/mcp', { fetch('/api/public/fraud-demo', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Accept': 'application/json', 'Accept': 'application/json'
'Authorization': 'Bearer aura_ro_public_inspector_2026'
}, },
body: JSON.stringify({ body: JSON.stringify({ phone: ph })
jsonrpc: '2.0',
id: Date.now(),
method: 'tools/call',
params: {
name: 'check_fraud_risk',
arguments: { phone: ph }
}
})
}) })
.then(r => r.json()) .then(r => r.json())
.then(rpc => { .then(rpc => {
let payload = {}; const payload = rpc || {};
try { if (payload.ok === false && payload.error) {
const rawText = rpc?.result?.content?.[0]?.text; throw new Error(payload.error.message || 'Fraud check temporarily unavailable');
payload = rawText ? JSON.parse(rawText) : (rpc?.result || {}); }
} catch (_) {}
const d = payload?.data || payload || {}; const d = payload?.data || payload || {};
const total = Number(d.total_parcels || 0); const total = Number(d.total_parcels || 0);
const delivered = Number(d.total_delivered || 0); const delivered = Number(d.total_delivered || 0);
@@ -3210,7 +3200,7 @@
const ms = Math.round(performance.now() - t0); const ms = Math.round(performance.now() - t0);
const pill = document.querySelector('.health-pill'); const pill = document.querySelector('.health-pill');
if (pill && data.ok) { if (pill && data.ok) {
pill.innerHTML = `<span class="health-dot"></span><span>Health OK (v${data.version || '2.7.1'} · ${ms}ms)</span>`; pill.innerHTML = `<span class="health-dot"></span><span>Health OK (v${data.version || '2.7.3'} · ${ms}ms)</span>`;
} }
const sbStatus = document.querySelector('.sandbox-status'); const sbStatus = document.querySelector('.sandbox-status');
if (sbStatus) { if (sbStatus) {
@@ -3220,7 +3210,7 @@
.catch(() => { .catch(() => {
const pill = document.querySelector('.health-pill'); const pill = document.querySelector('.health-pill');
if (pill) { if (pill) {
pill.innerHTML = `<span class="health-dot" style="background:var(--emerald);"></span><span>Health OK (v2.7.1)</span>`; pill.innerHTML = `<span class="health-dot" style="background:var(--emerald);"></span><span>Health OK (v2.7.3)</span>`;
} }
}); });
} }
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Updated index.html for courier-mcp-site with 4 live couriers, Glama badge, and Multi-Client configuration switcher",
"updatedAt": "2026-09-01T21:32:53.270266Z"
}
+25 -20
View File
@@ -349,23 +349,17 @@
<div class="panel"> <div class="panel">
<div class="panel-head"> <div class="panel-head">
<span>Client Request Payload (JSON-RPC 2.0)</span> <span>Client Request Payload (JSON-RPC 2.0)</span>
<span style="font-size:11px;font-family:var(--font-mono);color:var(--cyan);">method: initialize</span> <span style="font-size:11px;font-family:var(--font-mono);color:var(--cyan);">method: tools/list</span>
</div> </div>
<div class="panel-body"> <div class="panel-body">
<input id="auth-token" type="password" autocomplete="off" placeholder="Optional: Paste Bearer API Key or OAuth Token (leave empty for tools/list)" style="width:100%;margin-bottom:10px;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.12);background:rgba(0,0,0,0.35);color:var(--text);font-family:var(--font-mono);font-size:12px;" />
<textarea id="req-body">{ <textarea id="req-body">{
"jsonrpc": "2.0", "jsonrpc": "2.0",
"id": 1, "id": 1,
"method": "initialize", "method": "tools/list",
"params": { "params": {}
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {
"name": "Aura-Playground",
"version": "2.7.1"
}
}
}</textarea> }</textarea>
<button class="action-btn" id="run-btn" onclick="executeHandshake()">Send JSON-RPC Handshake ⚡</button> <button class="action-btn" id="run-btn" onclick="executeHandshake()">Send JSON-RPC Request ⚡</button>
</div> </div>
</div> </div>
@@ -452,7 +446,7 @@
</main> </main>
<footer> <footer>
<p>Aura Courier MCP v2.7.1 · 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.3 · 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>
@@ -474,25 +468,36 @@
try { try {
const t0 = performance.now(); const t0 = performance.now();
const tokenInput = (document.getElementById('auth-token')?.value || '').trim();
const reqHeaders = {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream'
};
if (tokenInput) {
reqHeaders['Authorization'] = tokenInput.toLowerCase().startsWith('bearer ')
? tokenInput
: `Bearer ${tokenInput}`;
}
const res = await fetch('/mcp', { const res = await fetch('/mcp', {
method: 'POST', method: 'POST',
headers: { headers: reqHeaders,
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
'Authorization': 'Bearer aura_ro_public_inspector_2026'
},
body: bodyText body: bodyText
}); });
const elapsed = Math.round(performance.now() - t0); const elapsed = Math.round(performance.now() - t0);
const sid = res.headers.get('mcp-session-id') || 'Generated by server'; const sid = res.headers.get('mcp-session-id') || 'Stateless / None';
const wwwAuth = res.headers.get('www-authenticate') || '';
const contentType = res.headers.get('content-type') || ''; const contentType = res.headers.get('content-type') || '';
const resText = await res.text(); const resText = await res.text();
statusEl.textContent = `${res.status} ${res.statusText} (${elapsed}ms)`; statusEl.textContent = `${res.status} ${res.statusText} (${elapsed}ms)`;
statusEl.style.color = res.ok ? 'var(--good)' : 'var(--danger)'; statusEl.style.color = res.ok ? 'var(--good)' : 'var(--danger)';
let formattedOutput = `// HTTP Status: ${res.status} ${res.statusText}\n// Roundtrip: ${elapsed}ms\n// mcp-session-id: ${sid}\n// content-type: ${contentType}\n\n`; let formattedOutput = `// HTTP Status: ${res.status} ${res.statusText}\n// Roundtrip: ${elapsed}ms\n// mcp-session-id: ${sid}\n// content-type: ${contentType}\n`;
if (wwwAuth) {
formattedOutput += `// WWW-Authenticate: ${wwwAuth}\n`;
}
formattedOutput += '\n';
try { try {
const parsed = JSON.parse(resText); const parsed = JSON.parse(resText);
@@ -508,7 +513,7 @@
viewEl.textContent = `Error: ${err.message}`; viewEl.textContent = `Error: ${err.message}`;
} finally { } finally {
btn.disabled = false; btn.disabled = false;
btn.textContent = 'Send JSON-RPC Handshake ⚡'; btn.textContent = 'Send JSON-RPC Request ⚡';
} }
} }
</script> </script>
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "aura-courier-mcp", "name": "aura-courier-mcp",
"version": "2.7.2", "version": "2.7.3",
"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",
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Package.json for Aura Courier MCP v2.0",
"updatedAt": "2026-09-01T18:29:09.951872800Z"
}
+1 -1
View File
@@ -2,7 +2,7 @@
"$schema": "https://antigravity.google/schemas/v1/plugin.json", "$schema": "https://antigravity.google/schemas/v1/plugin.json",
"name": "aura-courier", "name": "aura-courier",
"displayName": "Aura Courier MCP", "displayName": "Aura Courier MCP",
"version": "2.7.1", "version": "2.7.3",
"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",
+1 -1
View File
@@ -254,7 +254,7 @@
</main> </main>
<footer> <footer>
<p>Aura Courier MCP v2.7.1 · Developed by <b>Aura Agentic AI</b> · Released under <b>Apache License 2.0</b></p> <p>Aura Courier MCP v2.7.3 · 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
View File
@@ -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.7.2", "version": "2.7.3",
"websiteUrl": "https://courier.auraajenticai.cloud", "websiteUrl": "https://courier.auraajenticai.cloud",
"repository": { "repository": {
"url": "https://github.com/auraajenticai/aura-courier-mcp", "url": "https://github.com/auraajenticai/aura-courier-mcp",
@@ -19,7 +19,7 @@
{ {
"registryType": "npm", "registryType": "npm",
"identifier": "aura-courier-mcp", "identifier": "aura-courier-mcp",
"version": "2.7.2", "version": "2.7.3",
"transport": { "transport": {
"type": "stdio" "type": "stdio"
}, },
+4 -4
View File
@@ -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.7.1</span> <span class="version-pill">v2.7.3</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.7.1)</span> <span>📦 npm Package (v2.7.3)</span>
</a> </a>
</li> </li>
</ul> </ul>
@@ -1706,7 +1706,7 @@
}, },
"aura-courier-local": { "aura-courier-local": {
"command": "npx", "command": "npx",
"args": ["-y", "aura-courier-mcp@2.7.1"], "args": ["-y", "aura-courier-mcp@2.7.3"],
"env": { "PORT": "8080" } "env": { "PORT": "8080" }
} }
} }
@@ -1723,7 +1723,7 @@
}, },
"aura-courier-stdio": { "aura-courier-stdio": {
"command": "npx", "command": "npx",
"args": ["-y", "aura-courier-mcp@2.7.1"] "args": ["-y", "aura-courier-mcp@2.7.3"]
} }
} }
}, null, 2) }, null, 2)
-191
View File
@@ -1,191 +0,0 @@
<!doctype html>
<html lang="bn">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Aura Courier MCP — One unified Model Context Protocol connector for every Bangladesh courier. Book, track parcels, check balances, and analyze return fraud from Claude, Antigravity, Cursor, and n8n.">
<title>Aura Courier MCP — Bangladesh's 1st Universal Courier MCP</title>
<style>
:root{
--bg:#09090f; --bg2:#0c0d15; --surface:#13141d; --surface2:#191b27;
--ink:#edeff5; --muted:#969db4; --faint:#5c6482; --line:#23283a;
--blue:#4d7cff; --violet:#8b5cf6; --cyan:#38bdf8;
--green:#46d17f; --green-bg:#0f2a1d; --amber:#e0a341; --amber-bg:#2a2110;
--code-ink:#c8d0e6; --shadow:0 1px 2px rgba(0,0,0,.5),0 20px 50px rgba(0,0,0,.45);
--grad:linear-gradient(100deg,var(--blue),var(--violet));
}
*{box-sizing:border-box}
body{margin:0; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,system-ui,sans-serif; background:var(--bg); color:var(--ink); line-height:1.6; -webkit-font-smoothing:antialiased}
.page{max-width:1000px; margin:0 auto; padding:0 24px}
.mono{font-family:"SF Mono",ui-monospace,"Cascadia Code","JetBrains Mono",Menlo,Consolas,monospace}
a{color:var(--blue); text-decoration:none}
a:hover{text-decoration:underline}
h1,h2,h3{line-height:1.2; margin:0; text-wrap:balance}
.eyebrow{font-family:"SF Mono",monospace; font-size:12px; letter-spacing:.14em; text-transform:uppercase; color:var(--blue); font-weight:600}
/* Header / Nav */
header{display:flex; justify-content:space-between; align-items:center; padding:20px 0; border-bottom:1px solid var(--line)}
.logo{display:flex; align-items:center; gap:10px; font-weight:800; font-size:17px; color:var(--ink)}
.logo-badge{font-size:11px; padding:3px 8px; border-radius:99px; background:var(--surface2); color:var(--cyan); border:1px solid var(--line)}
.nav-links{display:flex; gap:18px; align-items:center; font-size:14px; font-weight:600}
/* Hero */
.hero{text-align:center; padding:70px 0 50px; position:relative; overflow:hidden}
.badge-row{display:flex; justify-content:center; gap:10px; flex-wrap:wrap; margin-bottom:20px}
.badge-glama{display:inline-flex; align-items:center; gap:7px; font-size:12.5px; font-weight:700; color:#38bdf8; background:rgba(56,189,248,0.12); border:1px solid rgba(56,189,248,0.3); padding:6px 14px; border-radius:999px}
.badge-live{display:inline-flex; align-items:center; gap:7px; font-size:12.5px; font-weight:700; color:var(--green); background:var(--green-bg); border:1px solid color-mix(in srgb,var(--green) 30%,transparent); padding:6px 14px; border-radius:999px}
.badge-live .d{width:8px; height:8px; border-radius:50%; background:var(--green); box-shadow:0 0 10px var(--green)}
.hero h1{font-size:clamp(34px,6.5vw,58px); font-weight:900; letter-spacing:-.03em; margin:16px 0}
.hero h1 span{background:var(--grad); -webkit-background-clip:text; -webkit-text-fill-color:transparent}
.hero .tagline{font-size:clamp(16px,2.2vw,20px); color:var(--muted); max-width:44ch; margin:0 auto 30px}
.cta-row{display:flex; gap:14px; justify-content:center; flex-wrap:wrap}
.btn{display:inline-flex; align-items:center; gap:8px; font-weight:700; font-size:15px; padding:12px 24px; border-radius:10px; text-decoration:none; transition:all .15s ease; border:1px solid transparent}
.btn:hover{transform:translateY(-2px); text-decoration:none}
.btn-primary{background:var(--grad); color:#fff; box-shadow:0 8px 24px rgba(77,124,255,0.35)}
.btn-glama{background:#0c171c; color:#38bdf8; border-color:#1e3a47}
.btn-ghost{background:var(--surface); color:var(--ink); border-color:var(--line)}
/* Config Tabs */
.config-box{margin:50px 0; background:var(--surface); border:1px solid var(--line); border-radius:14px; overflow:hidden; box-shadow:var(--shadow)}
.tab-header{display:flex; background:var(--bg2); border-bottom:1px solid var(--line); overflow-x:auto}
.tab-btn{padding:12px 20px; font-family:"SF Mono",monospace; font-size:13px; font-weight:600; color:var(--muted); background:none; border:none; border-bottom:2px solid transparent; cursor:pointer; display:flex; align-items:center; gap:8px}
.tab-btn.active{color:var(--cyan); border-bottom-color:var(--cyan); background:var(--surface)}
.code-body{padding:20px; font-family:"SF Mono",monospace; font-size:13px; color:var(--code-ink); position:relative; overflow-x:auto; margin:0; line-height:1.6}
.copy-btn{position:absolute; top:14px; right:14px; background:var(--surface2); border:1px solid var(--line); color:var(--muted); font-size:12px; font-weight:600; padding:6px 12px; border-radius:6px; cursor:pointer; transition:all .15s ease}
.copy-btn:hover{color:var(--ink); background:var(--bg2)}
/* Features Grid */
.grid{display:grid; grid-template-columns:repeat(auto-fit, minmax(280px,1fr)); gap:20px; margin:40px 0}
.card{background:var(--surface); border:1px solid var(--line); padding:24px; border-radius:14px; transition:border-color .2s ease}
.card:hover{border-color:var(--blue)}
.card h3{font-size:18px; margin:10px 0; font-weight:700}
.card p{font-size:14px; color:var(--muted); margin:0}
.card-icon{font-size:24px}
/* Footer */
footer{padding:40px 0; border-top:1px solid var(--line); text-align:center; font-size:13px; color:var(--faint)}
</style>
</head>
<body>
<div class="page">
<header>
<div class="logo">
<span>🚀 Aura Agentic AI</span>
<span class="logo-badge">MCP Bangladesh</span>
</div>
<div class="nav-links">
<a href="https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp" target="_blank">Glama Registry ↗</a>
<a href="https://github.com/auraajenticai/courier-mcp-site" target="_blank">GitHub ↗</a>
</div>
</header>
<main>
<section class="hero">
<div class="badge-row">
<div class="badge-glama">✓ Verified on Glama.ai Registry</div>
<div class="badge-live"><span class="d"></span> Live on Steadfast & Pathao</div>
</div>
<h1>Aura <span>Courier MCP</span> v2.0</h1>
<p class="tagline">এক unified connector — বাংলাদেশের সব কুরিয়ার। Claude, Antigravity, Cursor এবং n8n AI Agents থেকে ১-ক্লিকে পার্সেল বুক, ট্র্যাক ও ব্যালেন্স চেক করুন।</p>
<div class="cta-row">
<a href="https://glama.ai/mcp/servers/auraajenticai/aura-courier-mcp" target="_blank" class="btn btn-glama">
<span>⚡ View on Glama.ai</span>
</a>
<a href="https://github.com/auraajenticai/courier-mcp-site" target="_blank" class="btn btn-ghost">
<span>★ GitHub Repository</span>
</a>
</div>
</section>
<!-- Multi-Client Configuration Tabs -->
<section class="config-box">
<div class="tab-header">
<button class="tab-btn active" onclick="switchTab('antigravity')">🪐 Antigravity / Gemini</button>
<button class="tab-btn" onclick="switchTab('claude')">⚡ Claude Desktop</button>
<button class="tab-btn" onclick="switchTab('cursor')">💻 Cursor / VS Code</button>
<button class="tab-btn" onclick="switchTab('n8n')">🔄 n8n AI Agent</button>
</div>
<div style="position:relative;">
<button class="copy-btn" onclick="copyCode()">Copy Config</button>
<pre id="code-snippet" class="code-body">{
"mcpServers": {
"aura-courier": {
"command": "npx.cmd",
"args": ["-y", "aura-courier-mcp@latest"],
"env": {
"STEADFAST_API_KEY": "YOUR_STEADFAST_API_KEY",
"STEADFAST_SECRET_KEY": "YOUR_STEADFAST_SECRET_KEY"
}
}
}
}</pre>
</div>
</section>
<!-- Features & Tools -->
<section>
<div class="eyebrow">// POWERED TOOLS</div>
<h2 style="font-size:26px; margin:8px 0 20px;">Included Universal Tools</h2>
<div class="grid">
<div class="card">
<div class="card-icon">🧠</div>
<h3>create_parcel (Smart Auto-Route)</h3>
<p>ঠিকানা অনুযায়ী স্বয়ংক্রিয়ভাবে Steadfast বা Pathao বেছে নিয়ে পার্সেল বুকিং নিশ্চিত করে।</p>
</div>
<div class="card">
<div class="card-icon">📦</div>
<h3>track_parcel (Universal Tracking)</h3>
<p>ইনভয়েস বা কনসাইনমেন্ট আইডি দিয়ে যেকোনো কুরিয়ারের রিয়েল-টাইম ডেলিভারি স্ট্যাটাস ট্র্যাকিং।</p>
</div>
<div class="card">
<div class="card-icon">💰</div>
<h3>get_balance (Merchant Payouts)</h3>
<p>আপনার মার্চেন্ট একাউন্টে কত টাকা জমে আছে এবং পেআউট স্ট্যাটাস মুহূর্তেই জেনে নিন।</p>
</div>
<div class="card">
<div class="card-icon">🛡️</div>
<h3>check_fraud_risk (BD Phone Fraud AI)</h3>
<p>পার্সেল বুক করার আগেই কাস্টমারের ফোন নম্বরের রিটার্ন ও ফ্রড রিস্ক স্কোর যাচাই করুন।</p>
</div>
</div>
</section>
</main>
<footer>
<p>Built with ❤️ for Bangladesh eCommerce by <b>Aura Agentic AI</b> · Licensed under MIT</p>
<p><a href="https://auraajenticai.cloud">auraajenticai.cloud</a> · <a href="https://git.auraajenticai.cloud">git.auraajenticai.cloud</a></p>
</footer>
</div>
<script>
const configs = {
antigravity: `{\n "mcpServers": {\n "aura-courier": {\n "command": "npx.cmd",\n "args": ["-y", "aura-courier-mcp@latest"],\n "env": {\n "STEADFAST_API_KEY": "YOUR_STEADFAST_API_KEY",\n "STEADFAST_SECRET_KEY": "YOUR_STEADFAST_SECRET_KEY"\n }\n }\n }\n}`,
claude: `{\n "mcpServers": {\n "aura-courier": {\n "command": "npx",\n "args": ["-y", "aura-courier-mcp@latest"],\n "env": {\n "STEADFAST_API_KEY": "YOUR_STEADFAST_API_KEY",\n "STEADFAST_SECRET_KEY": "YOUR_STEADFAST_SECRET_KEY"\n }\n }\n }\n}`,
cursor: `{\n "mcpServers": {\n "aura-courier": {\n "command": "npx",\n "args": ["-y", "aura-courier-mcp@latest"],\n "env": {\n "STEADFAST_API_KEY": "YOUR_STEADFAST_API_KEY",\n "STEADFAST_SECRET_KEY": "YOUR_STEADFAST_SECRET_KEY"\n }\n }\n }\n}`,
n8n: `{\n "node": "n8n-nodes-mcp.mcpTool",\n "parameters": {\n "server": "stdio",\n "command": "npx -y aura-courier-mcp@latest"\n }\n}`
};
function switchTab(key) {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
event.currentTarget.classList.add('active');
document.getElementById('code-snippet').textContent = configs[key];
}
function copyCode() {
const code = document.getElementById('code-snippet').textContent;
navigator.clipboard.writeText(code);
const btn = document.querySelector('.copy-btn');
btn.textContent = 'Copied! ✓';
setTimeout(() => btn.textContent = 'Copy Config', 2000);
}
</script>
</body>
</html>
-5
View File
@@ -1,5 +0,0 @@
{
"summary": "Upgraded Aura Courier MCP showcase landing page with Glama Verified badge, Multi-Client copy-paste tabs (Antigravity, Claude, Cursor, n8n), and live tool inspection",
"updatedAt": "2026-09-01T18:30:41.693357500Z",
"userFacing": true
}
+1 -1
View File
@@ -7,7 +7,7 @@ description: >-
carrier rates, or resolving NDR delivery issues across Steadfast, Pathao, RedX, and Paperfly. carrier rates, or resolving NDR delivery issues across Steadfast, Pathao, RedX, and Paperfly.
--- ---
# Bangladesh Courier Operations & Zero-Risk COD Hub (v2.7.1) # Bangladesh Courier Operations & Zero-Risk COD Hub (v2.7.3)
This skill provides complete operational runbooks, tool execution patterns, and domain intelligence for managing nationwide e-commerce logistics across Bangladesh via the **Aura Courier MCP** remote server (`https://courier.auraajenticai.cloud/mcp`, OAuth 2.1 + PKCE `S256` & Dual-Auth). This skill provides complete operational runbooks, tool execution patterns, and domain intelligence for managing nationwide e-commerce logistics across Bangladesh via the **Aura Courier MCP** remote server (`https://courier.auraajenticai.cloud/mcp`, OAuth 2.1 + PKCE `S256` & Dual-Auth).
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Base adapter interface for courier integrations",
"updatedAt": "2026-09-01T18:29:30.582488300Z"
}
@@ -1,4 +0,0 @@
{
"summary": "Smart Fraud Risk and Return Rate Analyzer for Bangladesh eCommerce",
"updatedAt": "2026-09-01T18:29:48.161143100Z"
}
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Paperfly Courier Adapter implementation for Bangladesh",
"updatedAt": "2026-09-01T21:07:50.654097400Z"
}
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Pathao Courier Adapter implementation with OAuth support",
"updatedAt": "2026-09-01T18:29:42.917341500Z"
}
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "RedX Courier Adapter implementation for Bangladesh",
"updatedAt": "2026-09-01T21:07:45.032585700Z"
}
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Steadfast Courier Adapter implementation",
"updatedAt": "2026-09-01T18:29:36.397120200Z"
}
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Updated config.ts supporting Steadfast, Pathao, RedX, and Paperfly",
"updatedAt": "2026-09-01T21:07:56.667963Z"
}
+83 -12
View File
@@ -44,19 +44,34 @@ if (process.env.NODE_ENV !== "test" && dbUrl) {
} }
} }
// Automated Data Retention Engine (Daily Midnight Sweep) /**
* NEW-01 Fix: Automated Data Retention Engine (Daily Sweep) aligned to live PostgreSQL `courier_parcels` schema.
*/
export async function runDataRetentionSweep(pool: any): Promise<number> {
if (!pool) return 0;
const pruneRes = await pool.query(
`UPDATE courier_parcels
SET customer_name = 'ANONYMIZED',
phone = 'ANONYMIZED',
address = 'ANONYMIZED'
WHERE created_at < NOW() - INTERVAL '90 days'
AND (customer_name IS DISTINCT FROM 'ANONYMIZED'
OR phone IS DISTINCT FROM 'ANONYMIZED'
OR address IS DISTINCT FROM 'ANONYMIZED')`
);
return pruneRes?.rowCount || 0;
}
setInterval(async () => { setInterval(async () => {
if (dbPool) { if (dbPool) {
try { try {
const pruneRes = await dbPool.query( const pruned = await runDataRetentionSweep(dbPool);
`UPDATE courier_parcels if (pruned > 0) {
SET recipient_name = 'ANONYMIZED', recipient_phone = 'ANONYMIZED', recipient_address = 'ANONYMIZED' console.log(`[Data Retention Engine] Anonymized ${pruned} legacy order records older than 90 days.`);
WHERE created_at < NOW() - INTERVAL '90 days' AND recipient_name != 'ANONYMIZED'`
);
if (pruneRes.rowCount && pruneRes.rowCount > 0) {
console.log(`[Data Retention Engine] Anonymized ${pruneRes.rowCount} legacy order records older than 90 days.`);
} }
} catch (_) {} } catch (err: any) {
console.warn("[Data Retention Engine] Sweep error:", err?.message);
}
} }
}, 24 * 60 * 60 * 1000).unref(); }, 24 * 60 * 60 * 1000).unref();
@@ -216,6 +231,8 @@ app.use((req, res, next) => {
"Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-redx-api-token, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key" "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-redx-api-token, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key"
); );
res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate"); res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate");
res.header("Referrer-Policy", "no-referrer");
res.header("X-Content-Type-Options", "nosniff");
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
return res.sendStatus(204); return res.sendStatus(204);
} }
@@ -312,8 +329,9 @@ app.post("/admin/tokens/revoke", async (req: Request, res: Response) => {
return res.json({ ok: true, tenantId: b.tenantId, updatedKeys: count, status: b.status || "PAYMENT_DUE" }); return res.json({ ok: true, tenantId: b.tenantId, updatedKeys: count, status: b.status || "PAYMENT_DUE" });
}); });
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" }); const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "MCP Protocol Gateway" });
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" }); const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
const publicDemoLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 10, name: "Public Fraud Demo" });
/** /**
* F05 Fix: MCP Session Entry with Cryptographic Tenant Isolation * F05 Fix: MCP Session Entry with Cryptographic Tenant Isolation
@@ -500,9 +518,22 @@ app.get("/mcp", mcpLimiter, async (req: Request, res: Response) => {
return; return;
} }
if (!req.auraAuth?.authenticated) {
res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, req.auraAuth?.tenantId === "invalid"));
return res.status(401).json(
wrapError(
new McpToolError({
code: "UNAUTHORIZED",
message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header for active MCP session.",
}),
"validator"
)
);
}
const entry = sessions.get(sessionId)!; const entry = sessions.get(sessionId)!;
const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId; const callerTenant = req.auraAuth.tenantId;
if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") { if (entry.tenantId !== callerTenant && callerTenant !== "master") {
return res.status(403).json( return res.status(403).json(
wrapError( wrapError(
new McpToolError({ new McpToolError({
@@ -956,6 +987,46 @@ app.get("/track/:code", trackingLimiter, async (req: Request, res: Response) =>
</html>`); </html>`);
}); });
/**
* NEW-03 Fix: Safe Server-Side Public Fraud Demo Endpoint (Zero Browser API Key Exposure).
* Strictly limited to 10 requests/minute/IP and scoped exclusively to check_fraud_risk on valid BD mobile numbers.
*/
app.post("/api/public/fraud-demo", publicDemoLimiter, async (req: Request, res: Response) => {
const rawPhone = String(req.body?.phone || "").trim().replace(/[\s\-()]/g, "").replace(/^\+?88/, "");
if (!/^01[3-9]\d{8}$/.test(rawPhone)) {
return res.status(400).json(
wrapError(
new McpToolError({
code: "INVALID_INPUT",
message: "Valid 11-digit Bangladesh mobile number (013-019) is required.",
retryable: false,
}),
"validator"
)
);
}
try {
const registry = new CourierRegistry(loadConfig(process.env as EnvSource));
const result = await registry.checkFraudRisk(rawPhone);
const safeDto = {
phone_masked: maskPhone(rawPhone),
risk_level: result.risk_level,
delivery_success_rate: result.delivery_success_rate,
cancellation_rate: result.cancellation_rate,
is_verified_buyer: result.is_verified_buyer,
total_parcels: result.total_parcels,
total_delivered: result.total_delivered,
total_cancelled: result.total_cancelled,
sample_size: result.sample_size,
data_sources: result.data_sources,
recommendation: result.recommendation,
};
return res.json(wrapSuccess(safeDto, "live_api"));
} catch (err: any) {
return res.status(502).json(wrapError(err, "live_api"));
}
});
/** /**
* Task T9 — Health & Live Telemetry Endpoint * Task T9 — Health & Live Telemetry Endpoint
*/ */
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Updated MCP server entrypoint supporting Steadfast, Pathao, RedX, and Paperfly",
"updatedAt": "2026-09-01T21:08:16.984548700Z"
}
+31 -6
View File
@@ -191,6 +191,10 @@ export function hasByokCredentials(req: Request): boolean {
} }
export function extractBearerToken(req: Request): string | undefined { export function extractBearerToken(req: Request): string | undefined {
const cachedQueryTok = (req as any)._extractedQueryToken;
if (typeof cachedQueryTok === "string" && cachedQueryTok) {
return cachedQueryTok;
}
const authHeader = req.headers["authorization"] || req.headers["Authorization"]; const authHeader = req.headers["authorization"] || req.headers["Authorization"];
if (typeof authHeader === "string") { if (typeof authHeader === "string") {
const trimmed = authHeader.trim(); const trimmed = authHeader.trim();
@@ -203,12 +207,33 @@ 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) // NEW-05 Fix: Restrict query-parameter tokens strictly to MCP/SSE connector endpoints (never /admin, /track, /webhooks, /oauth)
const q = req.query as Record<string, any> | undefined; // and scrub secret query parameters from req.url / req.originalUrl immediately to prevent downstream log exposure.
if (q) { if (process.env.ALLOW_QUERY_TOKEN !== "false") {
const candidate = q.token || q.key || q.apiKey || q.api_key; const reqPath = (req.path || (req.url ? req.url.split("?")[0] : "")).trim();
if (typeof candidate === "string" && candidate.trim()) { if (reqPath === "/mcp" || reqPath === "/sse" || reqPath === "/messages") {
return candidate.trim(); 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()) {
const cleanTok = candidate.trim();
(req as any)._extractedQueryToken = cleanTok;
(req as any)._usedQueryToken = true;
delete q.token;
delete q.key;
delete q.apiKey;
delete q.api_key;
if (typeof req.url === "string" && req.url.includes("?")) {
req.url = req.url.replace(/([?&])(token|key|apiKey|api_key)=[^&]*/gi, "$1[REDACTED]").replace(/\?&/, "?");
}
if (typeof (req as any).originalUrl === "string" && (req as any).originalUrl.includes("?")) {
(req as any).originalUrl = (req as any).originalUrl
.replace(/([?&])(token|key|apiKey|api_key)=[^&]*/gi, "$1[REDACTED]")
.replace(/\?&/, "?");
}
return cleanTok;
}
}
} }
} }
return undefined; return undefined;
+11 -3
View File
@@ -1,6 +1,14 @@
import type { Express, Request, Response } from "express"; import type { Express, Request, Response } from "express";
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { resolveAuthContextAsync, type AuthScope } from "./auth.js"; import { resolveAuthContextAsync, type AuthScope } from "./auth.js";
import { createRateLimiter } from "./rate_limit.js";
const oauthLimiter = createRateLimiter({
windowMs: 60 * 1000,
max: 20,
name: "OAuth 2.1 Security Gateway",
message: "Too many OAuth authentication or registration attempts. Please retry in a minute.",
});
const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour
const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability) const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability)
@@ -1102,7 +1110,7 @@ export function registerOAuthRoutes(app: Express): void {
app.get("/.well-known/openid-configuration", authServerMetadataHandler); app.get("/.well-known/openid-configuration", authServerMetadataHandler);
// 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof) // 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof)
app.post("/oauth/register", (req: Request, res: Response) => { app.post("/oauth/register", oauthLimiter, (req: Request, res: Response) => {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
const body = (req.body || {}) as Record<string, any>; const body = (req.body || {}) as Record<string, any>;
const rawUris = body.redirect_uris; const rawUris = body.redirect_uris;
@@ -1249,7 +1257,7 @@ export function registerOAuthRoutes(app: Express): void {
}); });
// 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission) // 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission)
app.post("/oauth/authorize", async (req: Request, res: Response) => { app.post("/oauth/authorize", oauthLimiter, async (req: Request, res: Response) => {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Frame-Options", "DENY"); res.setHeader("X-Frame-Options", "DENY");
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'"); res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
@@ -1407,7 +1415,7 @@ export function registerOAuthRoutes(app: Express): void {
}); });
// 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token) // 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token)
app.post("/oauth/token", (req: Request, res: Response) => { app.post("/oauth/token", oauthLimiter, (req: Request, res: Response) => {
res.setHeader("Cache-Control", "no-store"); res.setHeader("Cache-Control", "no-store");
res.setHeader("Pragma", "no-cache"); res.setHeader("Pragma", "no-cache");
+52 -24
View File
@@ -1,4 +1,5 @@
import { Request, Response, NextFunction } from "express"; import { Request, Response, NextFunction } from "express";
import { isIP } from "node:net";
interface RateLimiterOptions { interface RateLimiterOptions {
windowMs: number; windowMs: number;
@@ -12,6 +13,54 @@ interface ClientRecord {
resetAt: number; resetAt: number;
} }
function normalizeIpLiteral(raw: string): string {
const trimmed = raw.trim();
if (trimmed.startsWith("::ffff:")) {
return trimmed.slice(7);
}
return trimmed;
}
function isPrivateOrLoopbackIp(ip: string): boolean {
const norm = normalizeIpLiteral(ip).toLowerCase();
if (!norm || norm === "127.0.0.1" || norm === "::1" || norm === "0.0.0.0") return true;
if (norm.startsWith("127.") || norm.startsWith("10.") || norm.startsWith("192.168.") || norm.startsWith("169.254.")) {
return true;
}
if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(norm)) {
return true;
}
if (norm.startsWith("fc") || norm.startsWith("fd") || norm.startsWith("fe80:")) {
return true;
}
return false;
}
/**
* NEW-02 Fix: Spoof-resistant client IP resolution.
* - Never trusts client-prepended leftmost X-Forwarded-For entries or private/loopback header spoofs.
* - Only accepts CF-Connecting-IP when accompanied by CF-Ray AND when CF-Connecting-IP is a valid public IP.
* - Otherwise relies on Express req.ip (with `trust proxy = 1`, which resolves the single trusted reverse-proxy hop).
*/
export function resolveRateLimitIp(req: Request): string {
const cfIpRaw = req.headers["cf-connecting-ip"];
const cfRay = req.headers["cf-ray"];
if (typeof cfIpRaw === "string" && typeof cfRay === "string" && cfRay.trim().length > 0) {
const cfIp = normalizeIpLiteral(cfIpRaw);
if (isIP(cfIp) !== 0 && !isPrivateOrLoopbackIp(cfIp)) {
return cfIp;
}
}
const expressIp = typeof req.ip === "string" && req.ip.trim() ? normalizeIpLiteral(req.ip) : "";
if (expressIp && isIP(expressIp) !== 0) {
return expressIp;
}
const socketIp = req.socket?.remoteAddress ? normalizeIpLiteral(req.socket.remoteAddress) : "";
return socketIp || "unknown";
}
export function createRateLimiter(options: RateLimiterOptions) { export function createRateLimiter(options: RateLimiterOptions) {
const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options; const { windowMs, max, message = "Too Many Requests. Rate limit exceeded, please retry later.", name = "Default" } = options;
const store = new Map<string, ClientRecord>(); const store = new Map<string, ClientRecord>();
@@ -27,33 +76,12 @@ export function createRateLimiter(options: RateLimiterOptions) {
}, 5 * 60 * 1000).unref(); }, 5 * 60 * 1000).unref();
return (req: Request, res: Response, next: NextFunction): void => { return (req: Request, res: Response, next: NextFunction): void => {
// Extract Client IP (supporting Cloudflare cf-connecting-ip and reverse proxies like Traefik / Nginx) // Allow high-speed local test execution unless test explicitly requests rate-limit enforcement
const cfIp = req.headers["cf-connecting-ip"]; if (process.env.NODE_ENV === "test" && req.headers["x-test-enforce-ratelimit"] !== "1") {
const xForwardedFor = req.headers["x-forwarded-for"];
let clientIp = "";
if (typeof cfIp === "string") {
clientIp = cfIp.trim();
} else if (typeof xForwardedFor === "string") {
clientIp = xForwardedFor.split(",")[0].trim();
} else if (Array.isArray(xForwardedFor) && xForwardedFor.length > 0) {
clientIp = xForwardedFor[0].trim();
} else {
clientIp = req.socket?.remoteAddress || "unknown";
}
// Bypass loopback and internal orchestration networks
if (
clientIp === "127.0.0.1" ||
clientIp === "::1" ||
clientIp === "::ffff:127.0.0.1" ||
clientIp.startsWith("10.") ||
clientIp.startsWith("172.16.") ||
clientIp.startsWith("172.17.") ||
clientIp.startsWith("172.18.")
) {
return next(); return next();
} }
const clientIp = resolveRateLimitIp(req);
const now = Date.now(); const now = Date.now();
let record = store.get(clientIp); let record = store.get(clientIp);
+53 -20
View File
@@ -754,7 +754,8 @@ export class CourierRegistry {
async updateParcel( async updateParcel(
courier: SupportedCourier, courier: SupportedCourier,
consignmentId: string, consignmentId: string,
updates: { recipient_phone?: string; recipient_address?: string; cod_amount?: number; note?: string } updates: { recipient_phone?: string; recipient_address?: string; cod_amount?: number; note?: string },
tenantId?: string
): Promise<any> { ): Promise<any> {
const cid = String(consignmentId || "").trim(); const cid = String(consignmentId || "").trim();
if (!cid) { if (!cid) {
@@ -780,24 +781,36 @@ export class CourierRegistry {
if (registryDbPool) { if (registryDbPool) {
try { try {
const effectiveTenant = String(tenantId || "default").trim() || "default";
const setClauses: string[] = ["updated_at = NOW()"]; const setClauses: string[] = ["updated_at = NOW()"];
const vals: any[] = []; const vals: any[] = [];
let pIndex = 1; let pIndex = 1;
if (updates.recipient_phone) { if (updates.recipient_phone) {
setClauses.push(`recipient_phone = $${pIndex++}`); setClauses.push(`phone = $${pIndex++}`);
vals.push(updates.recipient_phone); vals.push(updates.recipient_phone);
} }
if (updates.recipient_address) { if (updates.recipient_address) {
setClauses.push(`recipient_address = $${pIndex++}`); setClauses.push(`address = $${pIndex++}`);
vals.push(updates.recipient_address); vals.push(updates.recipient_address);
} }
if (updates.cod_amount !== undefined) { if (updates.cod_amount !== undefined) {
setClauses.push(`cod_amount = $${pIndex++}`); setClauses.push(`cod_amount = $${pIndex++}`);
vals.push(updates.cod_amount); vals.push(updates.cod_amount);
} }
if (updates.note !== undefined) {
setClauses.push(`raw = jsonb_set(COALESCE(raw, '{}'::jsonb), '{delivery_note}', to_jsonb($${pIndex++}::text), true)`);
vals.push(String(updates.note));
}
const cidIdx = pIndex++;
vals.push(cid); vals.push(cid);
let whereClause = `(tracking_code = $${cidIdx} OR raw->>'consignment_id' = $${cidIdx})`;
if (effectiveTenant !== "master") {
const tenantIdx = pIndex++;
vals.push(effectiveTenant);
whereClause += ` AND tenant = $${tenantIdx}`;
}
await registryDbPool.query( await registryDbPool.query(
`UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE tracking_code = $${pIndex} OR consignment_id = $${pIndex}`, `UPDATE courier_parcels SET ${setClauses.join(", ")} WHERE ${whereClause}`,
vals vals
); );
} catch (dbErr: any) { } catch (dbErr: any) {
@@ -808,7 +821,12 @@ export class CourierRegistry {
return upstreamResult; return upstreamResult;
} }
async cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: string): Promise<any> { async cancelParcel(
courier: SupportedCourier,
consignmentId: string,
reason?: string,
tenantId?: string
): Promise<any> {
const cid = String(consignmentId || "").trim(); const cid = String(consignmentId || "").trim();
if (!cid) { if (!cid) {
throw new McpToolError({ throw new McpToolError({
@@ -826,26 +844,41 @@ async cancelParcel(courier: SupportedCourier, consignmentId: string, reason?: st
} }
const result = await (adapter as any).cancelParcel(cid, reason); const result = await (adapter as any).cancelParcel(cid, reason);
const effectiveTenant = String(tenantId || "default").trim() || "default";
if (registryDbPool) { if (registryDbPool) {
try { try {
await registryDbPool.query( if (effectiveTenant === "master") {
`UPDATE courier_parcels await registryDbPool.query(
SET status = 'cancelled', updated_at = NOW() `UPDATE courier_parcels
WHERE consignment_id = $1 OR tracking_code = $1`, SET status = 'cancelled', updated_at = NOW()
[cid] WHERE (tracking_code = $1 OR raw->>'consignment_id' = $1)`,
); [cid]
} catch (_) {} );
} else {
await registryDbPool.query(
`UPDATE courier_parcels
SET status = 'cancelled', updated_at = NOW()
WHERE (tracking_code = $1 OR raw->>'consignment_id' = $1) AND tenant = $2`,
[cid, effectiveTenant]
);
}
} catch (dbErr: any) {
console.warn("[Registry] DB parcel cancellation update skipped:", dbErr?.message);
}
} }
recordWebhookEvent({ recordWebhookEvent(
id: "cancel_" + cid, {
consignment_id: cid, id: "cancel_" + cid,
courier, consignment_id: cid,
status: result.status || "cancelled", courier,
received_at: new Date().toISOString(), status: result.status || "cancelled",
payload: result, received_at: new Date().toISOString(),
}); payload: result,
},
effectiveTenant
);
return result; return result;
} }
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Courier registry supporting Steadfast, Pathao, RedX, and Paperfly with AI smart routing",
"updatedAt": "2026-09-01T21:08:10.019847900Z"
}
+4 -2
View File
@@ -445,7 +445,8 @@ export async function executeToolCall(
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 args?.reason ? String(args.reason) : undefined,
tenantId
); );
return { isError: false, envelope: wrapSuccess(result, "live_api") }; return { isError: false, envelope: wrapSuccess(result, "live_api") };
} }
@@ -459,7 +460,8 @@ export async function executeToolCall(
recipient_address: args?.recipient_address ? String(args.recipient_address) : undefined, recipient_address: args?.recipient_address ? String(args.recipient_address) : undefined,
cod_amount: args?.cod_amount !== undefined ? Number(args.cod_amount) : undefined, cod_amount: args?.cod_amount !== undefined ? Number(args.cod_amount) : undefined,
note: args?.note ? String(args.note) : undefined, note: args?.note ? String(args.note) : undefined,
} },
tenantId
); );
return { isError: false, envelope: wrapSuccess(result, "live_api") }; return { isError: false, envelope: wrapSuccess(result, "live_api") };
} }
-83
View File
@@ -1,83 +0,0 @@
import { CourierRegistry } from "./registry.js";
import dotenv from "dotenv";
dotenv.config();
async function runZeroRiskTest() {
console.log("==================================================");
console.log(" AURA COURIER MCP v2.4 — ZERO-RISK TEST SUITE ");
console.log(" 100% Real APIs · Zero Mock Data · Multi-Carrier");
console.log("==================================================");
const registry = new CourierRegistry();
// Test 1: Courier List & Spatial Engine
console.log("\n[TEST 1] Listing Couriers & Spatial Engine Status:");
const list = registry.listCouriers();
console.log(JSON.stringify(list, null, 2));
// Test 2: Steadfast Live Balance Check (Read-Only)
console.log("\n[TEST 2] Testing Steadfast Live Account Balance (Read-Only):");
try {
const balance = await registry.getBalance("steadfast");
console.log("✅ SUCCESS! Steadfast Live Balance Response:");
console.log(JSON.stringify(balance, null, 2));
} catch (err: any) {
console.log("⚠️ Balance check note:", err.message);
}
// Test 3: Fraud Risk Engine Test (100% Authentic API Evaluation)
console.log("\n[TEST 3] Testing BD Phone Fraud Risk Analyzer (Steadfast Real DB):");
const testPhone = "01712345678";
const fraudScore = await registry.checkFraudRisk(testPhone);
console.log("✅ Fraud Score Result (100% Authentic):");
console.log(JSON.stringify(fraudScore, null, 2));
// Test 4: Google Maps Platform Address Validation & Geocoding
console.log("\n[TEST 4] Testing Address Validation & Geocoding (Google Maps Platform):");
const addressResult = await registry.validateAddress({
address: "House 32, Road 11, Block D, Banani",
thana: "Banani",
district: "Dhaka",
});
console.log("✅ Address Validation & Geocoding Result:");
console.log(JSON.stringify(addressResult, null, 2));
// Test 5: Google Maps Delivery Zone & Shipping Fee Calculation
console.log("\n[TEST 5] Testing Delivery Zone & Rate Calculation:");
const zoneResult = await registry.calculateZoneAndRate({
recipient_address: "Dhanmondi 27, Dhaka",
weight_kg: 0.5,
});
console.log("✅ Zone & Rate Calculation Result:");
console.log(JSON.stringify(zoneResult, null, 2));
// Test 6: Multi-Carrier Rate Comparison (Steadfast vs Pathao vs RedX vs Paperfly)
console.log("\n[TEST 6] Multi-Carrier Rate & SLA Comparison:");
const quotesResult = await registry.compareRates({
recipient_address: "Chittagong GEC Circle, Chittagong",
weight_kg: 1.5,
cod_amount: 2500,
priority: "cheapest",
});
console.log("✅ Carrier Comparison Quotes:");
console.log(JSON.stringify(quotesResult, null, 2));
// Test 7: NDR Auto-Resolution Workflow
console.log("\n[TEST 7] NDR Auto-Resolution Engine Test:");
const ndrResult = await registry.resolveNdr({
consignment_id: "SF-8891234",
courier: "steadfast",
issue_type: "fake_attempt",
customer_phone: "01712345678",
customer_name: "Rafiqul Islam",
});
console.log("✅ NDR Resolution Workflow Result:");
console.log(JSON.stringify(ndrResult, null, 2));
console.log("\n==================================================");
console.log(" ALL 7 v2.4 ZERO-RISK TESTS PASSED PERFECTLY! ");
console.log("==================================================");
}
runZeroRiskTest().catch(console.error);
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Zero-risk live test script for Steadfast courier integration",
"updatedAt": "2026-09-01T18:42:44.981586100Z"
}
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "Updated types.ts with RedX and Paperfly courier models",
"updatedAt": "2026-09-01T21:07:38.988525200Z"
}
+1 -1
View File
@@ -11,7 +11,7 @@ function readPackageVersion(): string {
} catch { } catch {
// Fallback if package.json is unavailable at runtime // Fallback if package.json is unavailable at runtime
} }
return "2.7.2"; return "2.7.3";
} }
export const APP_VERSION: string = readPackageVersion(); export const APP_VERSION: string = readPackageVersion();
+2 -2
View File
@@ -83,7 +83,7 @@
</header> </header>
<main class="wrap"> <main class="wrap">
<div class="pill">Effective: November 24, 2026 · v2.7.1</div> <div class="pill">Effective: November 24, 2026 · v2.7.3</div>
<h1>Terms of Service</h1> <h1>Terms of Service</h1>
<p class="meta">Published by <strong>Aura Ajentic AI</strong> (Google Cloud Partner Advantage) · Contact: <a href="mailto:ceo@auraajenticai.cloud">ceo@auraajenticai.cloud</a></p> <p class="meta">Published by <strong>Aura Ajentic AI</strong> (Google Cloud Partner Advantage) · Contact: <a href="mailto:ceo@auraajenticai.cloud">ceo@auraajenticai.cloud</a></p>
@@ -132,7 +132,7 @@
</main> </main>
<footer> <footer>
<p>Aura Courier MCP v2.7.1 · Operated by <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="/privacy">Privacy Policy</a> · <a href="/terms">Terms of Service</a></p> <p>Aura Courier MCP v2.7.3 · Operated by <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="/privacy">Privacy Policy</a> · <a href="/terms">Terms of Service</a></p>
</footer> </footer>
</body> </body>
</html> </html>
+255 -1
View File
@@ -15,15 +15,19 @@ process.env.PATHAO_CLIENT_SECRET = "pathao_super_secret_do_not_leak_9999999999";
process.env.STEADFAST_API_KEY = "sf_test_key_valid"; process.env.STEADFAST_API_KEY = "sf_test_key_valid";
process.env.STEADFAST_SECRET_KEY = "sf_test_secret_valid"; process.env.STEADFAST_SECRET_KEY = "sf_test_secret_valid";
const { app, clearWebhookReplayCache } = await import("../dist/http.js"); import fs from "node:fs";
import path from "node:path";
const { app, clearWebhookReplayCache, runDataRetentionSweep } = await import("../dist/http.js");
const { const {
resolveAuthContext, resolveAuthContext,
validateSecurityConfig, validateSecurityConfig,
registerApiKey, registerApiKey,
authenticateWebhook, authenticateWebhook,
} = await import("../dist/middleware/auth.js"); } = await import("../dist/middleware/auth.js");
const { resolveRateLimitIp } = await import("../dist/middleware/rate_limit.js");
const { validateCarrierBaseUrl } = await import("../dist/config.js"); const { validateCarrierBaseUrl } = await import("../dist/config.js");
const { const {
CourierRegistry,
clearIdempotencyStore, clearIdempotencyStore,
clearWebhookEvents, clearWebhookEvents,
setRegistryDbPool, setRegistryDbPool,
@@ -531,3 +535,253 @@ test("P1-04: Ambiguous non-timeout carrier failure (HTTP 502 or malformed 2xx) h
PathaoAdapter.prototype.createParcel = origPathaoCreate; PathaoAdapter.prototype.createParcel = origPathaoCreate;
} }
}); });
test("NEW-01: update_parcel, cancel_parcel & 90-day PII retention use real courier_parcels columns and strict tenant SQL scoping", async () => {
clearWebhookEvents();
const executedQueries = [];
const mockPool = {
async query(sql, params) {
executedQueries.push({ sql: String(sql), params: params || [] });
return { rowCount: 2, rows: [] };
},
};
setRegistryDbPool(mockPool);
const tenantAlphaKey = "tenant_alpha_sql_scope_key_1234567890";
const tenantBetaKey = "tenant_beta_sql_scope_key_0987654321";
registerApiKey(tenantAlphaKey, "tenant_alpha", ["read", "write"]);
registerApiKey(tenantBetaKey, "tenant_beta", ["read", "write"]);
const origCancel = PathaoAdapter.prototype.cancelParcel;
PathaoAdapter.prototype.cancelParcel = async function (cid) {
return { success: true, consignment_id: cid, status: "cancelled" };
};
try {
// 1. update_parcel scopes UPDATE to tenant_alpha & uses real columns (phone, address, raw->>'consignment_id')
const updRes = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${tenantAlphaKey}`,
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 21,
method: "tools/call",
params: {
name: "update_parcel",
arguments: {
courier: "steadfast",
consignment_id: "SF-UPD-9001",
recipient_phone: "01712340000",
recipient_address: "Banani Road 11, Dhaka",
cod_amount: 1850,
note: "Call before arrival",
},
},
}),
}).then((r) => r.json());
assert.equal(updRes.result.isError, false);
const updSql = executedQueries[0];
assert.ok(updSql, "update_parcel executed SQL query");
assert.ok(!updSql.sql.includes("recipient_phone") && !updSql.sql.includes("recipient_address"));
assert.ok(!/\bOR\s+consignment_id\s*=/.test(updSql.sql), "Must not reference non-existent consignment_id column");
assert.ok(updSql.sql.includes("raw->>'consignment_id'"));
assert.ok(updSql.sql.includes("AND tenant ="));
assert.ok(updSql.params.includes("tenant_alpha"));
// 2. cancel_parcel scopes SQL UPDATE + webhook event to tenant_alpha (invisible to tenant_beta)
const cancelRes = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${tenantAlphaKey}`,
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 22,
method: "tools/call",
params: {
name: "cancel_parcel",
arguments: { courier: "pathao", consignment_id: "PT-CAN-9002", reason: "Customer changed mind" },
},
}),
}).then((r) => r.json());
assert.equal(cancelRes.result.isError, false);
const canSql = executedQueries[1];
assert.ok(canSql.sql.includes("raw->>'consignment_id'"));
assert.ok(canSql.sql.includes("AND tenant = $2"));
assert.deepEqual(canSql.params, ["PT-CAN-9002", "tenant_alpha"]);
// Verify webhook event isolation: tenant_alpha sees cancel_PT-CAN-9002, tenant_beta sees 0 events
const alphaEvRes = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${tenantAlphaKey}` },
body: JSON.stringify({
jsonrpc: "2.0",
id: 23,
method: "tools/call",
params: { name: "get_webhook_events", arguments: { consignment_id: "PT-CAN-9002" } },
}),
}).then((r) => r.json());
const alphaEv = JSON.parse(alphaEvRes.result.content[0].text);
assert.equal(alphaEv.data.count, 1);
const betaEvRes = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${tenantBetaKey}` },
body: JSON.stringify({
jsonrpc: "2.0",
id: 24,
method: "tools/call",
params: { name: "get_webhook_events", arguments: { consignment_id: "PT-CAN-9002" } },
}),
}).then((r) => r.json());
const betaEv = JSON.parse(betaEvRes.result.content[0].text);
assert.equal(betaEv.data.count, 0);
// 3. 90-day PII retention sweep updates customer_name, phone, address (real schema)
const pruned = await runDataRetentionSweep(mockPool);
assert.equal(pruned, 2);
const retSql = executedQueries[2];
assert.ok(retSql.sql.includes("SET customer_name = 'ANONYMIZED'"));
assert.ok(retSql.sql.includes("phone = 'ANONYMIZED'"));
assert.ok(retSql.sql.includes("address = 'ANONYMIZED'"));
assert.ok(!retSql.sql.includes("recipient_name"));
} finally {
PathaoAdapter.prototype.cancelParcel = origCancel;
setRegistryDbPool(null);
}
});
test("NEW-02: Spoofed CF-Connecting-IP / X-Forwarded-For private IPs cannot bypass rate limiter & OAuth endpoints are throttled", async () => {
// 1. Unit check on resolveRateLimitIp: spoofed loopback/RFC1918 CF-Connecting-IP is ignored
const spoofedReq = {
headers: {
"cf-connecting-ip": "127.0.0.1",
"cf-ray": "fake-ray-id",
"x-forwarded-for": "10.0.0.1, 198.51.100.77",
},
ip: "198.51.100.77",
socket: { remoteAddress: "127.0.0.1" },
};
assert.equal(resolveRateLimitIp(spoofedReq), "198.51.100.77");
// Legitimate public CF-Connecting-IP + CF-Ray resolves cleanly
const legitCfReq = {
headers: {
"cf-connecting-ip": "203.0.113.88",
"cf-ray": "8e123456789abcde-SIN",
},
ip: "172.18.0.2",
socket: { remoteAddress: "172.18.0.2" },
};
assert.equal(resolveRateLimitIp(legitCfReq), "203.0.113.88");
// 2. OAuth /oauth/register enforces 20 req/min rate limit even when attacker spoofs CF-Connecting-IP: 10.0.0.1
let lastStatus = 201;
for (let i = 0; i < 22; i++) {
const res = await fetch(`${baseUrl}/oauth/register`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-test-enforce-ratelimit": "1",
"cf-connecting-ip": "10.0.0.9",
"cf-ray": "spoofed-private-cf",
"x-forwarded-for": "127.0.0.1, 198.51.100.200",
},
body: JSON.stringify({
client_name: `Flood-${i}`,
redirect_uris: ["http://127.0.0.1:44123/cb"],
}),
});
lastStatus = res.status;
if (lastStatus === 429) break;
}
assert.equal(lastStatus, 429, "OAuth register flood must be throttled with HTTP 429 despite private-IP header spoofing");
});
test("NEW-03, NEW-04 & NEW-05: Zero revoked tokens in HTML, safe /api/public/fraud-demo, GET /mcp session auth, and /admin query-token block", async () => {
const repoDir = path.resolve(process.cwd());
for (const rel of ["index.html", "mcp_explorer.html", "validate_plugin.js"]) {
const content = fs.readFileSync(path.join(repoDir, rel), "utf8");
assert.ok(!content.includes("aura_ro_public_inspector_2026"), `${rel} must not contain revoked hardcoded token`);
}
// 1. Safe server-side public fraud demo validates BD mobile & masks phone
const badPhoneRes = await fetch(`${baseUrl}/api/public/fraud-demo`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone: "12345" }),
});
assert.equal(badPhoneRes.status, 400);
const origFraud = CourierRegistry.prototype.checkFraudRisk;
CourierRegistry.prototype.checkFraudRisk = async function (ph) {
return {
phone: ph,
risk_level: "LOW",
risk_score: 8,
delivery_success_rate: 96.4,
total_parcels: 28,
total_delivered: 27,
total_cancelled: 1,
sample_size: 28,
data_sources: ["Steadfast Nationwide DB"],
recommendation: "Safe for COD dispatch.",
};
};
try {
const okDemoRes = await fetch(`${baseUrl}/api/public/fraud-demo`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ phone: "+8801712345678" }),
});
assert.equal(okDemoRes.status, 200);
assert.equal(okDemoRes.headers.get("referrer-policy"), "no-referrer");
const demoJson = await okDemoRes.json();
assert.equal(demoJson.ok, true);
assert.equal(demoJson.data.risk_level, "LOW");
assert.equal(demoJson.data.phone_masked, "017****5678");
assert.ok(!JSON.stringify(demoJson).includes("01712345678"), "Raw phone number must be masked in public demo DTO");
} finally {
CourierRegistry.prototype.checkFraudRisk = origFraud;
}
// 2. NEW-04: Initialize MCP session, then unauthenticated GET /mcp with valid mcp-session-id MUST return 401
const initRes = await fetch(`${baseUrl}/mcp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json, text/event-stream",
Authorization: `Bearer ${process.env.AURA_API_KEY}`,
},
body: JSON.stringify({
jsonrpc: "2.0",
id: 31,
method: "initialize",
params: {
protocolVersion: "2025-03-26",
capabilities: {},
clientInfo: { name: "sec-test", version: "2.7.3" },
},
}),
});
assert.equal(initRes.status, 200);
const sid = initRes.headers.get("mcp-session-id");
assert.ok(sid);
const unauthGetSse = await fetch(`${baseUrl}/mcp`, {
method: "GET",
headers: {
Accept: "text/event-stream",
"mcp-session-id": sid,
},
});
assert.equal(unauthGetSse.status, 401, "Unauthenticated GET /mcp with stolen session ID must return 401");
// 3. NEW-05: Query-parameter ?token= MUST NOT authenticate /admin/* endpoints
const adminQueryRes = await fetch(`${baseUrl}/admin/tokens?token=${process.env.AURA_ADMIN_KEY}`);
assert.equal(adminQueryRes.status, 401, "Query-string ?token= must be rejected on /admin/tokens");
});
-4
View File
@@ -1,4 +0,0 @@
{
"summary": "TypeScript configuration for Aura Courier MCP",
"updatedAt": "2026-09-01T18:29:15.078426500Z"
}
+69 -1
View File
@@ -5,6 +5,7 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import crypto from 'crypto';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
@@ -117,11 +118,76 @@ async function validateSkillsAndRules() {
assert(ruleContent.includes('Google Maps Platform'), 'Google Maps geocoding policy is defined'); assert(ruleContent.includes('Google Maps Platform'), 'Google Maps geocoding policy is defined');
} }
async function mintSandboxOAuthToken(baseOrigin, endpoint) {
const dcrRes = await fetch(`${baseOrigin}/oauth/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_name: 'Antigravity Validator',
redirect_uris: ['http://127.0.0.1:54321/callback'],
token_endpoint_auth_method: 'none'
})
});
const dcr = await dcrRes.json();
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
const authUrl = new URL(`${baseOrigin}/oauth/authorize`);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', dcr.client_id);
authUrl.searchParams.set('redirect_uri', 'http://127.0.0.1:54321/callback');
authUrl.searchParams.set('code_challenge', challenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
authUrl.searchParams.set('scope', 'read');
authUrl.searchParams.set('state', 'validator');
authUrl.searchParams.set('resource', endpoint);
const consentGet = await fetch(authUrl.toString());
const html = await consentGet.text();
const csrfMatch = html.match(/name="csrf_token"\s+value="([^"]+)"/);
if (!csrfMatch) throw new Error('Could not extract OAuth CSRF token');
const form = new URLSearchParams({
client_id: dcr.client_id,
redirect_uri: 'http://127.0.0.1:54321/callback',
state: 'validator',
scope: 'read',
code_challenge: challenge,
code_challenge_method: 'S256',
resource: endpoint,
csrf_token: csrfMatch[1],
decision: 'sandbox',
auth_mode: 'sandbox'
});
const consentPost = await fetch(`${baseOrigin}/oauth/authorize`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: form.toString(),
redirect: 'manual'
});
const loc = consentPost.headers.get('location') || '';
const code = new URL(loc).searchParams.get('code');
if (!code) throw new Error('OAuth sandbox did not issue authorization code');
const tokRes = await fetch(`${baseOrigin}/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: dcr.client_id,
redirect_uri: 'http://127.0.0.1:54321/callback',
code_verifier: verifier
}).toString()
});
const tokJson = await tokRes.json();
if (!tokJson.access_token) throw new Error('OAuth token endpoint did not return access_token');
return tokJson.access_token;
}
async function validateRemoteMcpServer() { async function validateRemoteMcpServer() {
console.log('\n--- 5. Validating Live Remote MCP OAuth 2.1 Discovery, Handshake & 13 Tools ---'); console.log('\n--- 5. Validating Live Remote MCP OAuth 2.1 Discovery, Handshake & 13 Tools ---');
const baseOrigin = 'https://courier.auraajenticai.cloud'; const baseOrigin = 'https://courier.auraajenticai.cloud';
const endpoint = `${baseOrigin}/mcp`; const endpoint = `${baseOrigin}/mcp`;
const authToken = process.env.AURA_API_KEY || 'aura_ro_public_inspector_2026';
try { try {
// 5a. RFC 9728 Protected Resource Metadata & RFC 8414 Authorization Server Metadata // 5a. RFC 9728 Protected Resource Metadata & RFC 8414 Authorization Server Metadata
const prmRes = await fetch(`${baseOrigin}/.well-known/oauth-protected-resource`); const prmRes = await fetch(`${baseOrigin}/.well-known/oauth-protected-resource`);
@@ -156,6 +222,8 @@ async function validateRemoteMcpServer() {
const wwwAuth = unauthRes.headers.get('www-authenticate') || ''; const wwwAuth = unauthRes.headers.get('www-authenticate') || '';
assert(wwwAuth.includes('resource_metadata='), '401 includes RFC 9728 WWW-Authenticate resource_metadata header'); assert(wwwAuth.includes('resource_metadata='), '401 includes RFC 9728 WWW-Authenticate resource_metadata header');
const authToken = process.env.AURA_API_KEY || await mintSandboxOAuthToken(baseOrigin, endpoint);
// 5c. Authenticated initialize handshake + 13 live tools // 5c. Authenticated initialize handshake + 13 live tools
const initRes = await fetch(endpoint, { const initRes = await fetch(endpoint, {
method: 'POST', method: 'POST',