aura-courier-mcp 2.3.2 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +192 -21
  2. package/README.md +359 -26
  3. package/README.md.metadata.json +4 -0
  4. package/dist/adapters/base.d.ts +1 -0
  5. package/dist/adapters/base.js.map +1 -0
  6. package/dist/adapters/fraud_engine.d.ts +8 -1
  7. package/dist/adapters/fraud_engine.js +137 -21
  8. package/dist/adapters/google_maps.d.ts +25 -0
  9. package/dist/adapters/google_maps.js +334 -0
  10. package/dist/adapters/paperfly.d.ts +14 -0
  11. package/dist/adapters/paperfly.js +102 -22
  12. package/dist/adapters/pathao.d.ts +37 -1
  13. package/dist/adapters/pathao.js +247 -31
  14. package/dist/adapters/pathao.js.map +1 -0
  15. package/dist/adapters/redx.d.ts +14 -0
  16. package/dist/adapters/redx.js +81 -12
  17. package/dist/adapters/registry.d.ts +20 -0
  18. package/dist/adapters/registry.js +34 -0
  19. package/dist/adapters/registry.js.map +1 -0
  20. package/dist/adapters/steadfast.d.ts +17 -0
  21. package/dist/adapters/steadfast.js +121 -12
  22. package/dist/adapters/steadfast.js.map +1 -0
  23. package/dist/config.d.ts +4 -0
  24. package/dist/config.js +16 -2
  25. package/dist/config.js.map +1 -0
  26. package/dist/envelope.d.ts +55 -0
  27. package/dist/envelope.js +159 -0
  28. package/dist/http.d.ts +8 -1
  29. package/dist/http.js +699 -58
  30. package/dist/http.js.map +1 -0
  31. package/dist/index.js +2 -1
  32. package/dist/index.js.map +1 -0
  33. package/dist/middleware/auth.d.ts +100 -0
  34. package/dist/middleware/auth.js +585 -0
  35. package/dist/middleware/oauth.d.ts +19 -0
  36. package/dist/middleware/oauth.js +1376 -0
  37. package/dist/middleware/rate_limit.d.ts +9 -0
  38. package/dist/middleware/rate_limit.js +71 -0
  39. package/dist/pages.d.ts +8 -0
  40. package/dist/pages.js +317 -0
  41. package/dist/pages.js.map +1 -0
  42. package/dist/registry.d.ts +51 -6
  43. package/dist/registry.js +625 -28
  44. package/dist/server.d.ts +11 -1
  45. package/dist/server.js +407 -51
  46. package/dist/server.js.map +1 -0
  47. package/dist/tariffs.d.ts +46 -0
  48. package/dist/tariffs.js +153 -0
  49. package/dist/test_zero_risk.js +49 -25
  50. package/dist/tools/index.d.ts +3 -0
  51. package/dist/tools/index.js +162 -0
  52. package/dist/tools/index.js.map +1 -0
  53. package/dist/types.d.ts +188 -4
  54. package/dist/types.js.map +1 -0
  55. package/dist/version.d.ts +1 -0
  56. package/dist/version.js +16 -0
  57. package/package.json +12 -9
package/dist/http.js CHANGED
@@ -1,83 +1,325 @@
1
1
  import express from "express";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
4
5
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
5
- import { CourierRegistry } from "./registry.js";
6
+ import { CourierRegistry, recordWebhookEvent, setRegistryDbPool } from "./registry.js";
6
7
  import { loadConfig } from "./config.js";
7
- import { buildMcpServer } from "./server.js";
8
+ import { buildMcpServer, executeToolCall, TOOLS } from "./server.js";
9
+ import { createRateLimiter } from "./middleware/rate_limit.js";
10
+ import { optionalAuthMiddleware, requireMcpAuth, isActionPermitted, resolveAuthContext, verifyWebhookSignature, recordAuditLog, initDynamicAuthStore, upsertDynamicKeyHash, setTenantDynamicKeyStatus, listDynamicKeySummaries, } from "./middleware/auth.js";
11
+ import { registerOAuthRoutes, buildWwwAuthenticateHeader } from "./middleware/oauth.js";
12
+ import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
13
+ import { APP_VERSION } from "./version.js";
8
14
  import path from "node:path";
9
15
  import { fileURLToPath } from "node:url";
16
+ import pg from "pg";
17
+ /**
18
+ * F02 Fix: Remove hardcoded plaintext password.
19
+ * Connection string is read strictly from process.env.DATABASE_URL.
20
+ */
21
+ const dbUrl = process.env.DATABASE_URL;
22
+ let dbPool = null;
23
+ if (process.env.NODE_ENV !== "test" && dbUrl) {
24
+ try {
25
+ dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
26
+ setRegistryDbPool(dbPool);
27
+ initDynamicAuthStore(dbPool).catch(() => { });
28
+ }
29
+ catch (err) {
30
+ console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
31
+ }
32
+ }
33
+ // Automated Data Retention Engine (Daily Midnight Sweep)
34
+ setInterval(async () => {
35
+ if (dbPool) {
36
+ try {
37
+ const pruneRes = await dbPool.query(`UPDATE courier_parcels
38
+ SET recipient_name = 'ANONYMIZED', recipient_phone = 'ANONYMIZED', recipient_address = 'ANONYMIZED'
39
+ WHERE created_at < NOW() - INTERVAL '90 days' AND recipient_name != 'ANONYMIZED'`);
40
+ if (pruneRes.rowCount && pruneRes.rowCount > 0) {
41
+ console.log(`[Data Retention Engine] Anonymized ${pruneRes.rowCount} legacy order records older than 90 days.`);
42
+ }
43
+ }
44
+ catch (_) { }
45
+ }
46
+ }, 24 * 60 * 60 * 1000).unref();
10
47
  const PORT = Number(process.env.PORT || 8080);
11
- // Marketing landing (index.html) sits at the repo root, one level above dist/.
12
- const LANDING = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "index.html");
13
- // Pull this client's courier keys from request headers or query params.
14
- // Captured once per session (on the initialize request) and bound to that session's server.
15
- function keysFromRequest(req) {
48
+ const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
49
+ const LANDING = path.join(APP_DIR, "index.html");
50
+ const PRIVACY_HTML = path.join(APP_DIR, "privacy.html");
51
+ const TERMS_HTML = path.join(APP_DIR, "terms.html");
52
+ const HEALTH_HTML = path.join(APP_DIR, "health.html");
53
+ const MCP_EXPLORER_HTML = path.join(APP_DIR, "mcp_explorer.html");
54
+ const GUIDE_HTML = path.join(APP_DIR, "guide.html");
55
+ const SIMULATOR_HTML = path.join(APP_DIR, "simulator.html");
56
+ const ASSETS_DIR = path.join(APP_DIR, "assets");
57
+ const CONFIGS_DIR = path.join(APP_DIR, "configs");
58
+ /**
59
+ * F04 Helper: HTML entity escaping to prevent stored/reflected XSS.
60
+ */
61
+ function escapeHtml(str) {
62
+ if (str == null)
63
+ return "";
64
+ return String(str)
65
+ .replace(/&/g, "&amp;")
66
+ .replace(/</g, "&lt;")
67
+ .replace(/>/g, "&gt;")
68
+ .replace(/"/g, "&quot;")
69
+ .replace(/'/g, "&#39;");
70
+ }
71
+ /**
72
+ * F03 Helper: Redact recipient street address to District/City level for public tracking.
73
+ */
74
+ function redactAddressToDistrict(addr) {
75
+ if (!addr)
76
+ return "Bangladesh";
77
+ const parts = addr.split(",").map((p) => p.trim()).filter(Boolean);
78
+ if (parts.length > 1) {
79
+ return parts.slice(-2).join(", ");
80
+ }
81
+ return addr;
82
+ }
83
+ /**
84
+ * F10 Fix: Pull client courier keys strictly from request headers.
85
+ * Query parameters are completely ignored to prevent credential leakage in URL logs.
86
+ */
87
+ export function keysFromRequest(req) {
16
88
  const h = req.headers;
17
- const q = req.query;
18
- const pick = (header, query) => {
89
+ // Strict Multi-Tenant & BYOK Isolation:
90
+ // If caller explicitly sends any BYOK courier headers (isByok === true), NEVER fall back to
91
+ // platform master courier env keys so vendor/merchant BYOK credentials never mix with central keys.
92
+ const isByokRequest = Boolean(req.auraAuth?.isByok ||
93
+ h["x-steadfast-api-key"] ||
94
+ h["x-pathao-client-id"] ||
95
+ h["x-redx-api-token"] ||
96
+ h["x-paperfly-api-key"]);
97
+ const isPublicFraudCheck = req.auraAuth?.tenantId === "public_ro" &&
98
+ req.body?.method === "tools/call" &&
99
+ req.body?.params?.name === "check_fraud_risk";
100
+ const allowMasterEnvFallback = (req.auraAuth?.tenantId === "master" || isPublicFraudCheck) && !isByokRequest;
101
+ const pick = (header, envVar, allowNonMasterEnv = false) => {
19
102
  const hv = h[header];
20
- const v = (Array.isArray(hv) ? hv[0] : hv) ?? q[query];
21
- return v ? String(v) : undefined;
103
+ const v = Array.isArray(hv) ? hv[0] : hv;
104
+ if (v && typeof v === "string" && v.trim())
105
+ return v.trim();
106
+ if (envVar && (allowMasterEnvFallback || allowNonMasterEnv)) {
107
+ return process.env[envVar];
108
+ }
109
+ return undefined;
22
110
  };
23
111
  return {
24
- STEADFAST_API_KEY: pick("x-steadfast-api-key", "steadfast_key"),
25
- STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "steadfast_secret"),
26
- STEADFAST_BASE_URL: pick("x-steadfast-base-url", "steadfast_base_url"),
27
- PATHAO_CLIENT_ID: pick("x-pathao-client-id", "pathao_client_id"),
28
- PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "pathao_client_secret"),
29
- PATHAO_USERNAME: pick("x-pathao-username", "pathao_username"),
30
- PATHAO_PASSWORD: pick("x-pathao-password", "pathao_password"),
31
- PATHAO_STORE_ID: pick("x-pathao-store-id", "pathao_store_id"),
32
- PATHAO_BASE_URL: pick("x-pathao-base-url", "pathao_base_url"),
33
- REDX_API_TOKEN: pick("x-redx-api-token", "redx_token"),
34
- REDX_BASE_URL: pick("x-redx-base-url", "redx_base_url"),
35
- REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "redx_pickup_store_id"),
36
- PAPERFLY_API_KEY: pick("x-paperfly-api-key", "paperfly_key"),
37
- PAPERFLY_USERNAME: pick("x-paperfly-username", "paperfly_username"),
38
- PAPERFLY_PASSWORD: pick("x-paperfly-password", "paperfly_password"),
39
- PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "paperfly_store"),
112
+ STEADFAST_API_KEY: pick("x-steadfast-api-key", "STEADFAST_API_KEY"),
113
+ STEADFAST_SECRET_KEY: pick("x-steadfast-secret-key", "STEADFAST_SECRET_KEY"),
114
+ STEADFAST_BASE_URL: pick("x-steadfast-base-url", "STEADFAST_BASE_URL", true),
115
+ PATHAO_CLIENT_ID: pick("x-pathao-client-id", "PATHAO_CLIENT_ID"),
116
+ PATHAO_CLIENT_SECRET: pick("x-pathao-client-secret", "PATHAO_CLIENT_SECRET"),
117
+ PATHAO_USERNAME: pick("x-pathao-username", "PATHAO_USERNAME"),
118
+ PATHAO_PASSWORD: pick("x-pathao-password", "PATHAO_PASSWORD"),
119
+ PATHAO_STORE_ID: pick("x-pathao-store-id", "PATHAO_STORE_ID"),
120
+ PATHAO_BASE_URL: pick("x-pathao-base-url", "PATHAO_BASE_URL", true),
121
+ REDX_API_TOKEN: pick("x-redx-api-token", "REDX_API_TOKEN"),
122
+ REDX_BASE_URL: pick("x-redx-base-url", "REDX_BASE_URL", true),
123
+ REDX_PICKUP_STORE_ID: pick("x-redx-pickup-store-id", "REDX_PICKUP_STORE_ID"),
124
+ PAPERFLY_API_KEY: pick("x-paperfly-api-key", "PAPERFLY_API_KEY"),
125
+ PAPERFLY_USERNAME: pick("x-paperfly-username", "PAPERFLY_USERNAME"),
126
+ PAPERFLY_PASSWORD: pick("x-paperfly-password", "PAPERFLY_PASSWORD"),
127
+ PAPERFLY_STORE_NAME: pick("x-paperfly-store-name", "PAPERFLY_STORE_NAME"),
128
+ GOOGLE_MAPS_API_KEY: pick("x-google-maps-key", "GOOGLE_MAPS_API_KEY", true),
40
129
  };
41
130
  }
42
- const app = express();
43
- app.use(express.json({ limit: "1mb" }));
131
+ export const app = express();
132
+ app.set("trust proxy", 1);
133
+ app.use(express.json({
134
+ limit: "1mb",
135
+ verify: (req, _res, buf) => {
136
+ req.rawBody = buf;
137
+ },
138
+ }));
139
+ app.use(express.urlencoded({ extended: false, limit: "1mb" }));
140
+ // Robust Malformed JSON Syntax Error Guard
141
+ app.use((err, _req, res, next) => {
142
+ if (err && (err.type === "entity.parse.failed" || err.status === 400)) {
143
+ return res.status(400).json(wrapError(new McpToolError({
144
+ code: "INVALID_INPUT",
145
+ message: "Malformed JSON payload in request body.",
146
+ retryable: false,
147
+ }), "validator"));
148
+ }
149
+ next(err);
150
+ });
44
151
  // Allow browser-based and cross-origin MCP clients.
45
152
  app.use((req, res, next) => {
46
153
  res.header("Access-Control-Allow-Origin", "*");
47
- res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name");
48
- res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
49
- res.header("Access-Control-Expose-Headers", "mcp-session-id");
154
+ res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS, HEAD, PATCH, PUT");
155
+ res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, mcp-session-id, mcp-protocol-version, x-aura-signature, x-steadfast-signature, x-pathao-signature, x-redx-signature, x-paperfly-signature, x-webhook-secret, x-steadfast-api-key, x-steadfast-secret-key, x-steadfast-base-url, x-pathao-client-id, x-pathao-client-secret, x-pathao-username, x-pathao-password, x-pathao-store-id, x-pathao-base-url, x-redx-api-token, x-redx-base-url, x-redx-pickup-store-id, x-paperfly-api-key, x-paperfly-username, x-paperfly-password, x-paperfly-store-name, x-google-maps-key");
156
+ res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate");
50
157
  if (req.method === "OPTIONS") {
51
- res.sendStatus(204);
52
- return;
158
+ return res.sendStatus(204);
53
159
  }
54
160
  next();
55
161
  });
56
- // Active sessions: sessionId -> transport (each bound to one client's keys).
57
- const transports = {};
58
- app.post("/mcp", async (req, res) => {
162
+ // Static assets (official logo, favicons, branding) & agent MCP configs
163
+ app.use("/assets", express.static(ASSETS_DIR, { maxAge: "7d" }));
164
+ app.use("/configs", express.static(CONFIGS_DIR, { maxAge: "1d" }));
165
+ app.get("/favicon.ico", (_req, res) => {
166
+ res.sendFile(path.join(ASSETS_DIR, "courier-logo.jpg"), (err) => {
167
+ if (err && !res.headersSent)
168
+ res.status(204).end();
169
+ });
170
+ });
171
+ // Standard MCP OAuth 2.1 + PKCE (S256) + RFC 9728 + RFC 8414 + RFC 7591 Dynamic Client Registration
172
+ registerOAuthRoutes(app);
173
+ app.use(optionalAuthMiddleware);
174
+ // Dynamic Tenant API Key Sync & Revocation Routes (Called by Snehalata / Admin Master Key)
175
+ app.get("/admin/tokens", (req, res) => {
176
+ if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
177
+ return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
178
+ }
179
+ return res.json({ ok: true, tokens: listDynamicKeySummaries() });
180
+ });
181
+ app.post("/admin/tokens/register", async (req, res) => {
182
+ if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
183
+ return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
184
+ }
185
+ const b = req.body || {};
186
+ if ((!b.tokenHash && !b.rawToken) || !b.tenantId) {
187
+ return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "tenantId and tokenHash (or rawToken) required." }), "validator"));
188
+ }
189
+ try {
190
+ const rec = await upsertDynamicKeyHash({
191
+ tokenHash: b.tokenHash,
192
+ rawToken: b.rawToken,
193
+ tenantId: String(b.tenantId),
194
+ storeName: b.storeName ? String(b.storeName) : undefined,
195
+ scopes: Array.isArray(b.scopes) ? b.scopes : ["read", "write"],
196
+ isAdmin: Boolean(b.isAdmin),
197
+ status: String(b.status || "ACTIVE"),
198
+ });
199
+ return res.json({ ok: true, tenantId: rec.tenantId, status: rec.status, hashPrefix: rec.tokenHash.slice(0, 10) });
200
+ }
201
+ catch (err) {
202
+ return res.status(500).json(wrapError(err, "validator"));
203
+ }
204
+ });
205
+ app.post("/admin/tokens/revoke", async (req, res) => {
206
+ if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
207
+ return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
208
+ }
209
+ const b = req.body || {};
210
+ if (!b.tenantId) {
211
+ return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "tenantId required." }), "validator"));
212
+ }
213
+ const count = await setTenantDynamicKeyStatus(String(b.tenantId), String(b.status || "PAYMENT_DUE"));
214
+ return res.json({ ok: true, tenantId: b.tenantId, updatedKeys: count, status: b.status || "PAYMENT_DUE" });
215
+ });
216
+ const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
217
+ const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
218
+ const sessions = new Map();
219
+ const sseSessions = new Map();
220
+ const SESSION_TTL_MS = 30 * 60 * 1000;
221
+ setInterval(() => {
222
+ const now = Date.now();
223
+ for (const [sid, entry] of sessions.entries()) {
224
+ if (now - entry.lastActiveAt > SESSION_TTL_MS) {
225
+ sessions.delete(sid);
226
+ }
227
+ }
228
+ for (const [sid, entry] of sseSessions.entries()) {
229
+ if (now - entry.lastActiveAt > SESSION_TTL_MS) {
230
+ sseSessions.delete(sid);
231
+ }
232
+ }
233
+ }, 60 * 1000).unref();
234
+ /**
235
+ * AI Agent Connector Accept Normalizer:
236
+ * Ensures clients sending Accept: application/json or wildcard do not get HTTP 406 from StreamableHTTPServerTransport.
237
+ */
238
+ app.use("/mcp", (req, _res, next) => {
239
+ const accept = req.headers["accept"] || "";
240
+ if (!accept.includes("text/event-stream")) {
241
+ req.headers["accept"] = accept ? `${accept}, text/event-stream` : "application/json, text/event-stream";
242
+ }
243
+ next();
244
+ });
245
+ /**
246
+ * POST /mcp - MCP Protocol Gateway
247
+ */
248
+ app.post("/mcp", mcpLimiter, requireMcpAuth, async (req, res) => {
59
249
  const sessionId = req.headers["mcp-session-id"];
250
+ const tenantId = req.auraAuth?.tenantId || "default";
60
251
  let transport;
61
- if (sessionId && transports[sessionId]) {
62
- // Existing session — reuse its server (already holds this client's keys).
63
- transport = transports[sessionId];
252
+ // F05: Verify MCP Session belongs strictly to caller's tenant
253
+ if (sessionId && sessions.has(sessionId)) {
254
+ const entry = sessions.get(sessionId);
255
+ if (entry.tenantId !== tenantId && req.auraAuth?.tenantId !== "master") {
256
+ res.status(403).json(wrapError(new McpToolError({
257
+ code: "UNAUTHORIZED",
258
+ message: "MCP Session belongs to another tenant.",
259
+ retryable: false,
260
+ source: "validator",
261
+ }), "validator"));
262
+ return;
263
+ }
264
+ entry.lastActiveAt = Date.now();
265
+ transport = entry.transport;
64
266
  }
65
267
  else if (!sessionId && isInitializeRequest(req.body)) {
66
- // New session — capture THIS client's courier keys now.
67
268
  const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
68
- const server = buildMcpServer(registry);
269
+ const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName), tenantId);
69
270
  transport = new StreamableHTTPServerTransport({
70
271
  sessionIdGenerator: () => randomUUID(),
272
+ enableJsonResponse: true,
71
273
  onsessioninitialized: (sid) => {
72
- transports[sid] = transport;
274
+ sessions.set(sid, { transport, lastActiveAt: Date.now(), tenantId });
73
275
  },
74
276
  });
75
277
  transport.onclose = () => {
76
278
  if (transport.sessionId)
77
- delete transports[transport.sessionId];
279
+ sessions.delete(transport.sessionId);
78
280
  };
79
281
  await server.connect(transport);
80
282
  }
283
+ else if (req.body && (req.body.method === "tools/list" || req.body.method === "tools/call")) {
284
+ // Stateless JSON-RPC 2.0 Direct Execution Mode
285
+ const rpcId = req.body.id ?? 1;
286
+ const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
287
+ // F14: Allow unauthenticated tools/list discovery
288
+ if (req.body.method === "tools/list") {
289
+ res.status(200).json({ jsonrpc: "2.0", id: rpcId, result: { tools: TOOLS } });
290
+ return;
291
+ }
292
+ const toolName = String(req.body.params?.name || "");
293
+ const args = (req.body.params?.arguments || {});
294
+ const auth = isActionPermitted(req, toolName, args);
295
+ if (!auth.permitted) {
296
+ const errEnvelope = wrapError(new McpToolError({
297
+ code: "UNAUTHORIZED",
298
+ message: auth.reason || "Unauthorized tool invocation.",
299
+ retryable: false,
300
+ }), "validator");
301
+ res.status(200).json({
302
+ jsonrpc: "2.0",
303
+ id: rpcId,
304
+ result: {
305
+ isError: true,
306
+ content: [{ type: "text", text: JSON.stringify(errEnvelope, null, 2) }],
307
+ },
308
+ });
309
+ return;
310
+ }
311
+ const { isError, envelope } = await executeToolCall(registry, toolName, args, tenantId);
312
+ recordAuditLog(tenantId, toolName, args, isError ? "error" : "ok");
313
+ res.status(200).json({
314
+ jsonrpc: "2.0",
315
+ id: rpcId,
316
+ result: {
317
+ isError,
318
+ content: [{ type: "text", text: JSON.stringify(envelope, null, 2) }],
319
+ },
320
+ });
321
+ return;
322
+ }
81
323
  else {
82
324
  res.status(400).json({
83
325
  jsonrpc: "2.0",
@@ -99,32 +341,431 @@ app.post("/mcp", async (req, res) => {
99
341
  }
100
342
  }
101
343
  });
102
- // GET (server->client SSE stream) and DELETE (end session) for an existing session.
103
- async function handleSessionRequest(req, res) {
344
+ // GET (server->client SSE stream or Browser Explorer)
345
+ app.get("/mcp", mcpLimiter, async (req, res) => {
346
+ const sessionId = req.headers["mcp-session-id"];
347
+ if (!sessionId || !sessions.has(sessionId)) {
348
+ if (req.headers.accept?.includes("text/html")) {
349
+ return res.sendFile(MCP_EXPLORER_HTML, (err) => {
350
+ if (err && !res.headersSent) {
351
+ res.status(400).send("Invalid or missing session ID. Visit https://courier.auraajenticai.cloud for instructions.");
352
+ }
353
+ });
354
+ }
355
+ if (!req.auraAuth?.authenticated) {
356
+ res.setHeader("WWW-Authenticate", buildWwwAuthenticateHeader(req, req.auraAuth?.tenantId === "invalid"));
357
+ return res.status(401).json(wrapError(new McpToolError({
358
+ code: "UNAUTHORIZED",
359
+ message: "Missing or invalid Authorization: Bearer <AURA_API_KEY> header.",
360
+ }), "validator"));
361
+ }
362
+ res.status(400).send("Invalid or missing session ID");
363
+ return;
364
+ }
365
+ const entry = sessions.get(sessionId);
366
+ const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
367
+ if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
368
+ return res.status(403).json(wrapError(new McpToolError({
369
+ code: "UNAUTHORIZED",
370
+ message: "MCP Session belongs to another tenant.",
371
+ retryable: false,
372
+ }), "validator"));
373
+ }
374
+ entry.lastActiveAt = Date.now();
375
+ await entry.transport.handleRequest(req, res);
376
+ });
377
+ // DELETE (end session) for an existing session.
378
+ app.delete("/mcp", requireMcpAuth, async (req, res) => {
104
379
  const sessionId = req.headers["mcp-session-id"];
105
- if (!sessionId || !transports[sessionId]) {
380
+ if (!sessionId || !sessions.has(sessionId)) {
106
381
  res.status(400).send("Invalid or missing session ID");
107
382
  return;
108
383
  }
109
- await transports[sessionId].handleRequest(req, res);
384
+ const entry = sessions.get(sessionId);
385
+ const callerTenant = req.auraAuth?.tenantId || "default";
386
+ if (entry.tenantId !== callerTenant && callerTenant !== "master") {
387
+ res.status(403).json(wrapError(new McpToolError({
388
+ code: "UNAUTHORIZED",
389
+ message: "MCP Session belongs to another tenant.",
390
+ retryable: false,
391
+ }), "validator"));
392
+ return;
393
+ }
394
+ entry.lastActiveAt = Date.now();
395
+ await entry.transport.handleRequest(req, res);
396
+ });
397
+ /**
398
+ * GET /sse - Standard MCP Server-Sent Events Endpoint for AI Agent Connectors (Claude Desktop, Cursor, Glama, LibreChat, Smithery)
399
+ */
400
+ app.get("/sse", mcpLimiter, async (req, res) => {
401
+ const tenantId = req.auraAuth?.tenantId || "default";
402
+ const token = req.query.token || req.query.key || req.query.apiKey || req.query.api_key;
403
+ const endpointUrl = token
404
+ ? `/messages?token=${encodeURIComponent(String(token))}`
405
+ : "/messages";
406
+ const transport = new SSEServerTransport(endpointUrl, res);
407
+ const sid = transport.sessionId;
408
+ sseSessions.set(sid, { transport, tenantId, lastActiveAt: Date.now() });
409
+ transport.onclose = () => {
410
+ sseSessions.delete(sid);
411
+ };
412
+ const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
413
+ const server = buildMcpServer(registry, (toolName) => isActionPermitted(req, toolName), tenantId);
414
+ await server.connect(transport);
415
+ });
416
+ /**
417
+ * POST /messages - Standard MCP JSON-RPC Message Ingestion Endpoint for SSE Transports
418
+ */
419
+ app.post("/messages", mcpLimiter, async (req, res) => {
420
+ const sessionId = (req.query.sessionId || req.headers["mcp-session-id"]);
421
+ if (!sessionId || !sseSessions.has(sessionId)) {
422
+ return res.status(400).send("Invalid or missing sessionId");
423
+ }
424
+ const entry = sseSessions.get(sessionId);
425
+ const callerTenant = req.auraAuth?.authenticated ? req.auraAuth.tenantId : entry.tenantId;
426
+ if (entry.tenantId !== callerTenant && callerTenant !== "master" && entry.tenantId !== "default" && entry.tenantId !== "anonymous") {
427
+ return res.status(403).json(wrapError(new McpToolError({
428
+ code: "UNAUTHORIZED",
429
+ message: "SSE Session belongs to another tenant.",
430
+ retryable: false,
431
+ }), "validator"));
432
+ }
433
+ entry.lastActiveAt = Date.now();
434
+ await entry.transport.handlePostMessage(req, res, req.body);
435
+ });
436
+ /**
437
+ * Task T1 & T8 — Unified Authenticated Webhook Handler for Steadfast, Pathao, RedX, and Paperfly
438
+ */
439
+ function handleCourierWebhook(provider) {
440
+ return (req, res) => {
441
+ const isValidSig = verifyWebhookSignature(req, provider);
442
+ if (!isValidSig) {
443
+ return res.status(401).json(wrapError(new McpToolError({
444
+ code: "UNAUTHORIZED",
445
+ message: `Unauthorized ${provider} webhook request: missing or invalid signature/secret.`,
446
+ courier: provider,
447
+ retryable: false,
448
+ }), "validator"));
449
+ }
450
+ const payload = req.body || {};
451
+ if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") {
452
+ const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || "";
453
+ if (secret)
454
+ res.setHeader("X-Pathao-Merchant-Webhook-Integration-Secret", secret);
455
+ return res.status(202).json({ ok: true, status: "webhook_verified" });
456
+ }
457
+ const consignmentId = payload.consignment_id ||
458
+ payload.merchant_order_id ||
459
+ payload.tracking_code ||
460
+ payload.tracking_id ||
461
+ payload.order_id;
462
+ if (provider === "steadfast" && !consignmentId) {
463
+ return res.status(400).json(wrapError(new McpToolError({
464
+ code: "INVALID_INPUT",
465
+ message: "Invalid or missing consignment_id in webhook payload.",
466
+ courier: provider,
467
+ }), "validator"));
468
+ }
469
+ const status = String(payload.status || payload.order_status || payload.event || "received");
470
+ const eventType = String(payload.notification_type || payload.event || "delivery_status");
471
+ const invoice = payload.invoice || payload.merchant_order_id;
472
+ const paramMerchantToken = req.params?.merchant_token ? String(req.params.merchant_token).trim() : "";
473
+ const tenantId = String(paramMerchantToken || req.query.tenant || req.headers["x-tenant-id"] || "default");
474
+ const record = {
475
+ id: randomUUID(),
476
+ courier: provider,
477
+ consignment_id: String(consignmentId || "UNKNOWN"),
478
+ invoice: invoice ? String(invoice) : undefined,
479
+ status,
480
+ event_type: eventType,
481
+ received_at: new Date().toISOString(),
482
+ payload,
483
+ };
484
+ // F06: Record webhook event scoped by tenantId
485
+ recordWebhookEvent(record, tenantId);
486
+ // Forward verified Pathao financial events best-effort to Snehalata Financial Manager
487
+ if (provider === "pathao" && process.env.NODE_ENV !== "test" && /deliver|return|paid|settlement|invoice/i.test(`${status} ${eventType}`)) {
488
+ const fwdUrl = process.env.SNEHALATA_WEBHOOK_URL || "https://www.snehalata.com/api/webhooks/pathao";
489
+ const sig = String(req.headers["x-pathao-signature"] || process.env.PATHAO_CLIENT_SECRET || "");
490
+ if (fwdUrl && sig) {
491
+ fetch(fwdUrl, {
492
+ method: "POST",
493
+ headers: { "Content-Type": "application/json", "X-Pathao-Signature": sig },
494
+ body: JSON.stringify(payload),
495
+ }).catch(() => { });
496
+ }
497
+ }
498
+ return res.status(200).json(wrapSuccess({
499
+ status: "success",
500
+ courier: provider,
501
+ tenant_scope: tenantId,
502
+ consignment_id: record.consignment_id,
503
+ event_id: record.id,
504
+ message: `${provider} webhook verified and recorded for tenant '${tenantId}'.`,
505
+ }, "live_api"));
506
+ };
110
507
  }
111
- app.get("/mcp", handleSessionRequest);
112
- app.delete("/mcp", handleSessionRequest);
113
- app.get("/health", (_req, res) => res.json({ ok: true, service: "aura-courier-mcp", version: "2.1.0", sessions: Object.keys(transports).length }));
508
+ app.post(["/webhooks/steadfast", "/webhooks/steadfast/:merchant_token"], handleCourierWebhook("steadfast"));
509
+ app.post(["/webhooks/pathao", "/webhooks/pathao/:merchant_token"], handleCourierWebhook("pathao"));
510
+ app.post(["/webhooks/redx", "/webhooks/redx/:merchant_token"], handleCourierWebhook("redx"));
511
+ app.post(["/webhooks/paperfly", "/webhooks/paperfly/:merchant_token"], handleCourierWebhook("paperfly"));
512
+ /**
513
+ * GET /track/:code - Hardened Public & Authenticated Tracking Gateway
514
+ * F03: PII Masking for unauthenticated callers.
515
+ * F04: HTML entity escaping for XSS prevention.
516
+ */
517
+ app.get("/track/:code", trackingLimiter, async (req, res) => {
518
+ const code = req.params.code;
519
+ const format = req.query.format;
520
+ const isAuth = Boolean(req.auraAuth?.authenticated);
521
+ const callerTenant = req.auraAuth?.tenantId;
522
+ let courier = (req.query.courier || "").toLowerCase();
523
+ if (!courier) {
524
+ if (code.toUpperCase().startsWith("DS") || code.toUpperCase().startsWith("DB"))
525
+ courier = "pathao";
526
+ else if (code.toUpperCase().startsWith("SF") || /^\d{8,12}$/.test(code))
527
+ courier = "steadfast";
528
+ else if (code.toUpperCase().startsWith("REDX") || code.toUpperCase().startsWith("RX"))
529
+ courier = "redx";
530
+ else if (code.toUpperCase().startsWith("PF"))
531
+ courier = "paperfly";
532
+ else
533
+ courier = "pathao";
534
+ }
535
+ let dbParcel = null;
536
+ if (dbPool) {
537
+ try {
538
+ const qRes = await dbPool.query("SELECT * FROM courier_parcels WHERE tracking_code = $1 LIMIT 1", [code]);
539
+ if (qRes.rows && qRes.rows.length > 0) {
540
+ dbParcel = qRes.rows[0];
541
+ }
542
+ }
543
+ catch (_) { }
544
+ }
545
+ const registry = new CourierRegistry(loadConfig(keysFromRequest(req)));
546
+ let trackResult = null;
547
+ let errorObj = null;
548
+ try {
549
+ trackResult = await registry.trackParcel(code, courier);
550
+ }
551
+ catch (err) {
552
+ errorObj = err;
553
+ }
554
+ // F03: If caller is unauthenticated or not owner, sanitize/redact PII
555
+ const isOwner = isAuth && (callerTenant === "master" || callerTenant === dbParcel?.tenant_id || callerTenant === dbParcel?.tenant);
556
+ if (format === "json" || (!req.headers.accept?.includes("text/html") && format !== "html")) {
557
+ if (trackResult) {
558
+ let sanitized = trackResult;
559
+ if (!isOwner) {
560
+ sanitized = {
561
+ ...trackResult,
562
+ recipient_phone: trackResult.recipient_phone ? maskPhone(trackResult.recipient_phone) : undefined,
563
+ recipient_address: trackResult.recipient_address ? redactAddressToDistrict(trackResult.recipient_address) : undefined,
564
+ };
565
+ }
566
+ return res.json(wrapSuccess(sanitized, "live_api"));
567
+ }
568
+ if (dbParcel) {
569
+ let safeParcel = dbParcel;
570
+ if (!isOwner) {
571
+ safeParcel = {
572
+ ...dbParcel,
573
+ recipient_phone: maskPhone(dbParcel.recipient_phone || dbParcel.phone || ""),
574
+ recipient_address: redactAddressToDistrict(dbParcel.recipient_address || dbParcel.address || ""),
575
+ customer_name: dbParcel.customer_name ? dbParcel.customer_name.charAt(0) + "***" : "Customer",
576
+ };
577
+ }
578
+ return res.json(wrapSuccess({ success: true, parcel: safeParcel }, "cache"));
579
+ }
580
+ return res.status(404).json(wrapError(errorObj || new Error("Consignment not found"), "live_api"));
581
+ }
582
+ const raw = trackResult?.raw_response?.data || trackResult?.raw_response || (dbParcel?.raw?.data || dbParcel?.raw) || {};
583
+ let recipientName = dbParcel?.customer_name || raw.recipient_name || raw.customer_name || raw.name || "Verified Customer";
584
+ let recipientAddress = dbParcel?.address || raw.recipient_address || raw.address || "Bangladesh";
585
+ // F03: Mask PII for public web tracker view
586
+ if (!isOwner) {
587
+ recipientAddress = redactAddressToDistrict(recipientAddress);
588
+ if (recipientName && recipientName.length > 2) {
589
+ recipientName = recipientName.charAt(0) + "*** " + (recipientName.split(" ")[1] || "");
590
+ }
591
+ }
592
+ const codAmount = dbParcel?.cod_amount || raw.order_amount || raw.amount_to_collect || raw.cod_amount || raw.collectable_amount || 0;
593
+ const statusText = trackResult?.status || raw.order_status || (dbParcel?.status ? dbParcel.status.charAt(0).toUpperCase() + dbParcel.status.slice(1) : "Not Found");
594
+ const resolvedCourier = (dbParcel?.courier || courier || "pathao").toLowerCase();
595
+ const carrierName = resolvedCourier === "pathao" ? "Pathao Express" : (resolvedCourier === "steadfast" ? "Steadfast Courier" : resolvedCourier === "redx" ? "RedX Delivery" : resolvedCourier === "paperfly" ? "Paperfly Go" : resolvedCourier.toUpperCase());
596
+ const shortLink = raw.short_link || (carrierName.toLowerCase().includes("pathao") ? `https://merchant.pathao.com/tracking?consignment_id=${code}` : (carrierName.toLowerCase().includes("steadfast") ? `https://steadfast.com.bd/t/${code}` : ""));
597
+ const updatedAt = raw.order_status_updated_at || raw.updated_at || trackResult?.updated_at || (dbParcel?.updated_at ? new Date(dbParcel.updated_at).toLocaleString("en-GB") : new Date().toLocaleString());
598
+ const isDelivered = String(statusText).toLowerCase().includes("deliv");
599
+ const isAtHub = String(statusText).toLowerCase().includes("hub");
600
+ const isTransit = String(statusText).toLowerCase().includes("way") || String(statusText).toLowerCase().includes("transit") || String(statusText).toLowerCase().includes("progress");
601
+ const isPickedUp = isDelivered || isAtHub || isTransit || String(statusText).toLowerCase().includes("pick");
602
+ // F04: All interpolated variables are strictly escaped via escapeHtml()
603
+ res.type("html").send(`<!DOCTYPE html>
604
+ <html lang="en">
605
+ <head>
606
+ <meta charset="utf-8" />
607
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
608
+ <title>Aura Live Tracking — ${escapeHtml(code)}</title>
609
+ <link rel="preconnect" href="https://fonts.googleapis.com">
610
+ <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
611
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
612
+ <style>
613
+ :root { --bg: #07090e; --card: rgba(13, 17, 28, 0.85); --border: rgba(0, 240, 255, 0.18); --cyan: #00f0ff; --purple: #818cf8; --green: #10b981; --text: #f8fafc; --text-dim: #94a3b8; }
614
+ * { box-sizing: border-box; margin: 0; padding: 0; }
615
+ body { background: var(--bg); color: var(--text); font-family: 'Plus Jakarta Sans', sans-serif; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; position: relative; overflow-x: hidden; }
616
+ .track-card { width: 100%; max-width: 580px; background: var(--card); backdrop-filter: blur(20px); border: 1px solid var(--border); border-radius: 28px; padding: 32px; box-shadow: 0 20px 50px rgba(0,0,0,0.5); position: relative; z-index: 10; }
617
+ .header { display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 20px; margin-bottom: 24px; }
618
+ .brand { display: flex; align-items: center; gap: 12px; }
619
+ .brand-icon { width: 44px; height: 44px; border-radius: 14px; background: linear-gradient(135deg, #00f0ff, #818cf8); display: grid; place-items: center; font-size: 20px; color: #07090e; }
620
+ .brand-text h1 { font-size: 18px; font-weight: 800; }
621
+ .brand-text p { font-size: 11px; color: var(--text-dim); }
622
+ .status-badge { display: inline-flex; align-items: center; gap: 8px; padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: 700; background: rgba(0, 240, 255, 0.1); color: var(--cyan); border: 1px solid rgba(0, 240, 255, 0.3); }
623
+ .tracking-code-box { background: rgba(0,0,0,0.35); border: 1px dashed rgba(255,255,255,0.15); border-radius: 16px; padding: 14px 18px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
624
+ .code-label { font-size: 11px; color: var(--text-dim); text-transform: uppercase; font-weight: 700; }
625
+ .code-val { font-family: 'JetBrains Mono', monospace; font-size: 16px; font-weight: 700; color: #fff; }
626
+ .timeline { position: relative; padding-left: 28px; margin-bottom: 24px; }
627
+ .timeline::before { content: ''; position: absolute; left: 8px; top: 8px; bottom: 8px; width: 2px; background: rgba(255,255,255,0.1); }
628
+ .timeline-step { position: relative; margin-bottom: 20px; }
629
+ .step-dot { position: absolute; left: -28px; top: 3px; width: 18px; height: 18px; border-radius: 50%; display: grid; place-items: center; font-size: 10px; background: #1e293b; border: 2px solid #64748b; color: #fff; }
630
+ .step-dot.done { background: var(--cyan); border-color: var(--cyan); color: #07090e; }
631
+ .step-title { font-size: 14px; font-weight: 700; color: #fff; }
632
+ .step-sub { font-size: 12px; color: var(--text-dim); margin-top: 2px; }
633
+ .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 24px; }
634
+ .info-item { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06); border-radius: 14px; padding: 12px 14px; }
635
+ .info-item-label { font-size: 11px; color: var(--text-dim); margin-bottom: 4px; }
636
+ .info-item-val { font-size: 13px; font-weight: 700; color: #fff; }
637
+ .actions { display: flex; gap: 10px; }
638
+ .btn { flex: 1; padding: 12px; border-radius: 14px; font-weight: 700; font-size: 13px; display: flex; align-items: center; justify-content: center; gap: 8px; text-decoration: none; cursor: pointer; }
639
+ .btn-primary { background: linear-gradient(135deg, #00f0ff, #38bdf8); color: #07090e; border: none; font-weight: 800; }
640
+ .btn-secondary { background: rgba(255,255,255,0.06); color: #fff; border: 1px solid rgba(255,255,255,0.12); }
641
+ </style>
642
+ </head>
643
+ <body>
644
+ <div class="track-card">
645
+ <div class="header">
646
+ <div class="brand">
647
+ <div class="brand-icon"><i class="fa-solid fa-truck-fast"></i></div>
648
+ <div class="brand-text">
649
+ <h1>Aura Live Tracking</h1>
650
+ <p>${escapeHtml(carrierName)} • Direct Live Telemetry</p>
651
+ </div>
652
+ </div>
653
+ <div class="status-badge"><span>${escapeHtml(statusText)}</span></div>
654
+ </div>
655
+ <div class="tracking-code-box">
656
+ <div><div class="code-label">Consignment Tracking ID</div><div class="code-val">${escapeHtml(code)}</div></div>
657
+ <div style="text-align: right;"><div class="code-label">Carrier</div><div style="font-weight: 700; color: var(--cyan); font-size: 13px;">${escapeHtml(carrierName)}</div></div>
658
+ </div>
659
+ <div class="timeline">
660
+ <div class="timeline-step"><div class="step-dot done"><i class="fa-solid fa-check"></i></div><div class="step-title">Order Booked & Confirmed</div><div class="step-sub">Aura Dispatch Engine initialized booking.</div></div>
661
+ <div class="timeline-step"><div class="step-dot ${isPickedUp ? "done" : ""}"><i class="fa-solid fa-check"></i></div><div class="step-title">Picked Up by Rider</div><div class="step-sub">Central Merchant Fulfillment Hub</div></div>
662
+ <div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-arrow-right"></i></div><div class="step-title">${escapeHtml(statusText)}</div><div class="step-sub">Live Telemetry: ${escapeHtml(updatedAt)}</div></div>
663
+ <div class="timeline-step"><div class="step-dot ${isDelivered ? "done" : ""}"><i class="fa-solid fa-house"></i></div><div class="step-title">Destination Delivery</div><div class="step-sub">Destination: ${escapeHtml(recipientAddress)}</div></div>
664
+ </div>
665
+ <div class="info-grid">
666
+ <div class="info-item"><div class="info-item-label">Customer</div><div class="info-item-val">${escapeHtml(recipientName)}</div></div>
667
+ <div class="info-item"><div class="info-item-label">Cash on Delivery (COD)</div><div class="info-item-val">৳ ${Number(codAmount).toLocaleString()}</div></div>
668
+ </div>
669
+ <div class="actions">
670
+ ${shortLink ? `<a href="${escapeHtml(shortLink)}" target="_blank" class="btn btn-primary"><i class="fa-solid fa-location-arrow"></i> Official Carrier Map Tracker</a>` : ""}
671
+ <button onclick="window.location.reload()" class="btn btn-secondary"><i class="fa-solid fa-rotate-right"></i> Refresh Live Status</button>
672
+ </div>
673
+ </div>
674
+ </body>
675
+ </html>`);
676
+ });
677
+ /**
678
+ * Task T9 — Health & Live Telemetry Endpoint
679
+ */
680
+ app.get("/health", (req, res) => {
681
+ const auth = req.auraAuth || resolveAuthContext(req);
682
+ const isAdmin = auth.authenticated && auth.isAdmin;
683
+ if (!isAdmin) {
684
+ if (req.query.ui === "1" && req.headers.accept?.includes("text/html")) {
685
+ return res.sendFile(HEALTH_HTML, (err) => {
686
+ if (err && !res.headersSent)
687
+ res.json({ ok: true, version: APP_VERSION });
688
+ });
689
+ }
690
+ return res.json({
691
+ ok: true,
692
+ version: APP_VERSION,
693
+ });
694
+ }
695
+ const mem = process.memoryUsage();
696
+ const detailed = {
697
+ ok: true,
698
+ service: "aura-courier-mcp",
699
+ version: APP_VERSION,
700
+ tools_count: TOOLS.length,
701
+ spatial_engine: "Google Maps Platform (gmp_git_agentskills_v1)",
702
+ fraud_engine: "Pathao Nationwide v2 + Steadfast Nationwide API + BD Prefix Validator",
703
+ webhooks: {
704
+ steadfast: "/webhooks/steadfast",
705
+ pathao: "/webhooks/pathao",
706
+ redx: "/webhooks/redx",
707
+ paperfly: "/webhooks/paperfly",
708
+ },
709
+ performance: {
710
+ sessions_active: sessions.size,
711
+ heap_used_mb: Math.round((mem.heapUsed / 1024 / 1024) * 10) / 10,
712
+ heap_total_mb: Math.round((mem.heapTotal / 1024 / 1024) * 10) / 10,
713
+ rss_mb: Math.round((mem.rss / 1024 / 1024) * 10) / 10,
714
+ uptime_seconds: Math.round(process.uptime()),
715
+ },
716
+ };
717
+ return res.json(detailed);
718
+ });
719
+ app.get("/health.html", (_req, res) => {
720
+ res.sendFile(HEALTH_HTML, (err) => {
721
+ if (err && !res.headersSent)
722
+ res.json({ ok: true, version: APP_VERSION });
723
+ });
724
+ });
725
+ app.get("/privacy", (_req, res) => {
726
+ res.sendFile(PRIVACY_HTML, (err) => {
727
+ if (err && !res.headersSent) {
728
+ res.redirect("/");
729
+ }
730
+ });
731
+ });
732
+ app.get("/terms", (_req, res) => {
733
+ res.sendFile(TERMS_HTML, (err) => {
734
+ if (err && !res.headersSent) {
735
+ res.redirect("/");
736
+ }
737
+ });
738
+ });
739
+ app.get("/guide", (_req, res) => {
740
+ res.sendFile(GUIDE_HTML, (err) => {
741
+ if (err && !res.headersSent) {
742
+ res.redirect("/");
743
+ }
744
+ });
745
+ });
746
+ app.get("/simulator", (_req, res) => {
747
+ res.sendFile(SIMULATOR_HTML, (err) => {
748
+ if (err && !res.headersSent) {
749
+ res.redirect("/guide");
750
+ }
751
+ });
752
+ });
114
753
  app.get("/", (_req, res) => {
115
- // Serve the marketing landing page; fall back to a minimal page if it's missing.
116
754
  res.sendFile(LANDING, (err) => {
117
755
  if (err && !res.headersSent) {
118
756
  res
119
757
  .type("html")
120
758
  .send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Aura Courier MCP</title>` +
121
- `<style>body{font-family:system-ui,sans-serif;background:#0b0f1a;color:#e6ecff;margin:0;display:grid;place-items:center;min-height:100vh}.b{max-width:640px;padding:40px;text-align:center}h1{font-size:28px;margin:0 0 10px}code{background:#141c30;padding:2px 8px;border-radius:6px;color:#7dd3fc;font-size:13px}a{color:#7dd3fc}p{line-height:1.6;color:#9fb0d0}</style></head>` +
122
- `<body><div class="b"><h1>🚚 Aura Courier MCP</h1><p>Live remote MCP endpoint for Bangladesh couriers — Steadfast &amp; Pathao.</p>` +
123
- `<p>Connect your AI to <code>POST /mcp</code> and pass your courier keys as headers (<code>x-steadfast-api-key</code>, <code>x-steadfast-secret-key</code>) or query params (<code>?steadfast_key=…&amp;steadfast_secret=…</code>).</p>` +
759
+ `<style>body{font-family:system-ui,sans-serif;background:#07080a;color:#f4f5f7;margin:0;display:grid;place-items:center;min-height:100vh}.b{max-width:640px;padding:40px;text-align:center}h1{font-size:28px;margin:0 0 10px}code{background:#0f1115;padding:2px 8px;border-radius:6px;color:#00d4ff;font-size:13px}a{color:#00d4ff}p{line-height:1.6;color:#a4a8b3}</style></head>` +
760
+ `<body><div class="b"><h1>🚚 Aura Courier MCP v${APP_VERSION}</h1><p>Enterprise Bangladesh courier MCP &amp; Google Maps Platform spatial hub.</p>` +
761
+ `<p>Connect your AI to <code>POST /mcp</code> with Streamable-HTTP.</p>` +
762
+ `<p>Webhooks: <code>POST /webhooks/steadfast</code> · <code>POST /webhooks/pathao</code></p>` +
124
763
  `<p>By <a href="https://auraajenticai.cloud">Aura Ajentic AI</a> · <a href="https://courier.auraajenticai.cloud">docs &amp; setup</a></p></div></body></html>`);
125
764
  }
126
765
  });
127
766
  });
128
- app.listen(PORT, () => {
129
- console.log(`Aura Courier MCP (HTTP) listening on :${PORT} — POST /mcp`);
130
- });
767
+ if (process.env.NODE_ENV !== "test") {
768
+ app.listen(PORT, () => {
769
+ console.log(`Aura Courier MCP v${APP_VERSION} (HTTP) listening on :${PORT} — POST /mcp`);
770
+ });
771
+ }