feat(auth,webhook): dynamic PostgreSQL + Snehalata MCP key sync & Pathao 202 webhook challenge

This commit is contained in:
Aura Engine
2026-11-16 07:44:55 +00:00
parent e698f2161f
commit d1e0948216
2 changed files with 310 additions and 2 deletions
+69
View File
@@ -14,6 +14,10 @@ import {
resolveAuthContext, resolveAuthContext,
verifyWebhookSignature, verifyWebhookSignature,
recordAuditLog, recordAuditLog,
initDynamicAuthStore,
upsertDynamicKeyHash,
setTenantDynamicKeyStatus,
listDynamicKeySummaries,
} from "./middleware/auth.js"; } from "./middleware/auth.js";
import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js"; import { McpToolError, wrapError, wrapSuccess, maskPhone } from "./envelope.js";
import { SupportedCourier } from "./types.js"; import { SupportedCourier } from "./types.js";
@@ -32,6 +36,7 @@ if (process.env.NODE_ENV !== "test" && dbUrl) {
try { try {
dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 }); dbPool = new pg.Pool({ connectionString: dbUrl, max: 4, idleTimeoutMillis: 30000 });
setRegistryDbPool(dbPool); setRegistryDbPool(dbPool);
initDynamicAuthStore(dbPool).catch(() => {});
} catch (err: any) { } catch (err: any) {
console.warn("[PostgreSQL] Connection initialization skipped:", err?.message); console.warn("[PostgreSQL] Connection initialization skipped:", err?.message);
} }
@@ -197,6 +202,51 @@ app.get("/favicon.ico", (_req, res) => {
app.use(optionalAuthMiddleware); app.use(optionalAuthMiddleware);
// Dynamic Tenant API Key Sync & Revocation Routes (Called by Snehalata / Admin Master Key)
app.get("/admin/tokens", (req: Request, res: Response) => {
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
}
return res.json({ ok: true, tokens: listDynamicKeySummaries() });
});
app.post("/admin/tokens/register", async (req: Request, res: Response) => {
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
}
const b = req.body || {};
if ((!b.tokenHash && !b.rawToken) || !b.tenantId) {
return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "tenantId and tokenHash (or rawToken) required." }), "validator"));
}
try {
const rec = await upsertDynamicKeyHash({
tokenHash: b.tokenHash,
rawToken: b.rawToken,
tenantId: String(b.tenantId),
storeName: b.storeName ? String(b.storeName) : undefined,
scopes: Array.isArray(b.scopes) ? b.scopes : ["read", "write"],
isAdmin: Boolean(b.isAdmin),
status: String(b.status || "ACTIVE"),
});
return res.json({ ok: true, tenantId: rec.tenantId, status: rec.status, hashPrefix: rec.tokenHash.slice(0, 10) });
} catch (err: any) {
return res.status(500).json(wrapError(err, "validator"));
}
});
app.post("/admin/tokens/revoke", async (req: Request, res: Response) => {
if (!req.auraAuth?.authenticated || !req.auraAuth?.isAdmin) {
return res.status(401).json(wrapError(new McpToolError({ code: "UNAUTHORIZED", message: "Master admin token required." }), "validator"));
}
const b = req.body || {};
if (!b.tenantId) {
return res.status(400).json(wrapError(new McpToolError({ code: "INVALID_INPUT", message: "tenantId required." }), "validator"));
}
const count = await setTenantDynamicKeyStatus(String(b.tenantId), String(b.status || "PAYMENT_DUE"));
return res.json({ ok: true, tenantId: b.tenantId, updatedKeys: count, status: b.status || "PAYMENT_DUE" });
});
const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" }); const mcpLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 60, name: "MCP Protocol Gateway" });
const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" }); const trackingLimiter = createRateLimiter({ windowMs: 60 * 1000, max: 120, name: "Tracking Gateway" });
@@ -505,6 +555,12 @@ function handleCourierWebhook(provider: SupportedCourier) {
} }
const payload = req.body || {}; const payload = req.body || {};
if (provider === "pathao" && String(payload.event || "").toLowerCase() === "webhook_integration") {
const secret = process.env.PATHAO_CLIENT_SECRET || process.env.AURA_WEBHOOK_SECRET || "";
if (secret) res.setHeader("X-Pathao-Merchant-Webhook-Integration-Secret", secret);
return res.status(202).json({ ok: true, status: "webhook_verified" });
}
const consignmentId = const consignmentId =
payload.consignment_id || payload.consignment_id ||
payload.merchant_order_id || payload.merchant_order_id ||
@@ -545,6 +601,19 @@ function handleCourierWebhook(provider: SupportedCourier) {
// F06: Record webhook event scoped by tenantId // F06: Record webhook event scoped by tenantId
recordWebhookEvent(record, tenantId); recordWebhookEvent(record, tenantId);
// Forward verified Pathao financial events best-effort to Snehalata Financial Manager
if (provider === "pathao" && process.env.NODE_ENV !== "test" && /deliver|return|paid|settlement|invoice/i.test(`${status} ${eventType}`)) {
const fwdUrl = process.env.SNEHALATA_WEBHOOK_URL || "https://www.snehalata.com/api/webhooks/pathao";
const sig = String(req.headers["x-pathao-signature"] || process.env.PATHAO_CLIENT_SECRET || "");
if (fwdUrl && sig) {
fetch(fwdUrl, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Pathao-Signature": sig },
body: JSON.stringify(payload),
}).catch(() => {});
}
}
return res.status(200).json( return res.status(200).json(
wrapSuccess( wrapSuccess(
{ {
+241 -2
View File
@@ -11,6 +11,8 @@ export interface AuraAuthContext {
isByok: boolean; isByok: boolean;
isAdmin: boolean; isAdmin: boolean;
callerToken?: string; callerToken?: string;
deniedReason?: string;
httpStatus?: number;
} }
declare global { declare global {
@@ -103,6 +105,130 @@ function safeCompare(a: string, b: string): boolean {
* In-memory / env-configured tenant API keys registry. * In-memory / env-configured tenant API keys registry.
* Maps sha256(token) -> { tenantId, scopes, isAdmin } * Maps sha256(token) -> { tenantId, scopes, isAdmin }
*/ */
export interface DynamicKeyRecord {
tokenHash: string;
tenantId: string;
storeName?: string;
scopes: AuthScope[];
isAdmin: boolean;
status: string;
updatedAt: string;
}
const dynamicKeyHashes = new Map<string, DynamicKeyRecord>();
const remoteVerifyCache = new Map<string, { exp: number; record?: DynamicKeyRecord }>();
let authDbPool: any = null;
export async function initDynamicAuthStore(pool: any): Promise<void> {
authDbPool = pool;
if (!pool) return;
try {
await pool.query(`
CREATE TABLE IF NOT EXISTS aura_mcp_dynamic_keys (
token_hash TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
store_name TEXT,
scopes JSONB NOT NULL DEFAULT '["read","write"]',
is_admin BOOLEAN NOT NULL DEFAULT FALSE,
status TEXT NOT NULL DEFAULT 'ACTIVE',
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
const res = await pool.query("SELECT token_hash, tenant_id, store_name, scopes, is_admin, status, updated_at FROM aura_mcp_dynamic_keys");
for (const row of res.rows || []) {
dynamicKeyHashes.set(row.token_hash, {
tokenHash: row.token_hash,
tenantId: row.tenant_id,
storeName: row.store_name || undefined,
scopes: Array.isArray(row.scopes) ? row.scopes : ["read", "write"],
isAdmin: Boolean(row.is_admin),
status: String(row.status || "ACTIVE").toUpperCase(),
updatedAt: new Date(row.updated_at || Date.now()).toISOString(),
});
}
console.log(`[Auth] Loaded ${dynamicKeyHashes.size} dynamic MCP key(s) from PostgreSQL.`);
} catch (err: any) {
console.warn("[Auth] Dynamic key table init skipped:", err?.message);
}
}
export async function upsertDynamicKeyHash(opts: {
tokenHash?: string;
rawToken?: string;
tenantId: string;
storeName?: string;
scopes?: AuthScope[];
isAdmin?: boolean;
status?: string;
}): Promise<DynamicKeyRecord> {
const hash = (opts.tokenHash || (opts.rawToken ? createHash("sha256").update(opts.rawToken).digest("hex") : "")).trim();
if (!hash) throw new Error("tokenHash or rawToken required");
const status = String(opts.status || "ACTIVE").toUpperCase();
const scopes: AuthScope[] = Array.isArray(opts.scopes) && opts.scopes.length ? opts.scopes : ["read", "write"];
const rec: DynamicKeyRecord = {
tokenHash: hash,
tenantId: opts.tenantId,
storeName: opts.storeName,
scopes,
isAdmin: Boolean(opts.isAdmin),
status,
updatedAt: new Date().toISOString(),
};
dynamicKeyHashes.set(hash, rec);
if (opts.rawToken) {
remoteVerifyCache.set(hash, { exp: Date.now() + 20_000, record: rec });
}
if (authDbPool) {
try {
await authDbPool.query(
`INSERT INTO aura_mcp_dynamic_keys (token_hash, tenant_id, store_name, scopes, is_admin, status, updated_at)
VALUES ($1, $2, $3, $4::jsonb, $5, $6, NOW())
ON CONFLICT (token_hash) DO UPDATE SET
tenant_id = EXCLUDED.tenant_id,
store_name = COALESCE(EXCLUDED.store_name, aura_mcp_dynamic_keys.store_name),
scopes = EXCLUDED.scopes,
is_admin = EXCLUDED.is_admin,
status = EXCLUDED.status,
updated_at = NOW()`,
[hash, rec.tenantId, rec.storeName || null, JSON.stringify(scopes), rec.isAdmin, status]
);
} catch (err: any) {
console.warn("[Auth] Failed persisting dynamic key:", err?.message);
}
}
return rec;
}
export async function setTenantDynamicKeyStatus(tenantId: string, status: string): Promise<number> {
const norm = String(status || "SUSPENDED").toUpperCase();
let updated = 0;
for (const [h, rec] of dynamicKeyHashes.entries()) {
if (rec.tenantId === tenantId) {
dynamicKeyHashes.set(h, { ...rec, status: norm, updatedAt: new Date().toISOString() });
remoteVerifyCache.delete(h);
updated++;
}
}
if (authDbPool) {
try {
await authDbPool.query("UPDATE aura_mcp_dynamic_keys SET status = $1, updated_at = NOW() WHERE tenant_id = $2", [norm, tenantId]);
} catch {}
}
return updated;
}
export function listDynamicKeySummaries() {
return Array.from(dynamicKeyHashes.values()).map((r) => ({
hashPrefix: r.tokenHash.slice(0, 10) + "...",
tenantId: r.tenantId,
storeName: r.storeName || "",
status: r.status,
scopes: r.scopes,
updatedAt: r.updatedAt,
}));
}
const registeredKeyHashes = new Map<string, { tenantId: string; scopes: AuthScope[]; isAdmin: boolean }>(); const registeredKeyHashes = new Map<string, { tenantId: string; scopes: AuthScope[]; isAdmin: boolean }>();
export function registerApiKey(token: string, tenantId: string, scopes: AuthScope[] = ["read", "write"], isAdmin = false): void { export function registerApiKey(token: string, tenantId: string, scopes: AuthScope[] = ["read", "write"], isAdmin = false): void {
@@ -173,6 +299,44 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
}; };
} }
// 3b. Dynamic Database / Synced Tenant Key lookup
if (dynamicKeyHashes.has(tokenHash)) {
const dyn = dynamicKeyHashes.get(tokenHash)!;
if (dyn.status === "PAYMENT_DUE") {
return {
authenticated: false,
tenantId: dyn.tenantId,
scopes: [],
isByok,
isAdmin: false,
callerToken: token,
deniedReason: "পেমেন্ট বাকি থাকায় MCP Connector অ্যাক্সেস হোল্ড করা হয়েছে (Payment Due)।",
httpStatus: 402,
};
}
if (dyn.status === "SUSPENDED" || dyn.status === "DISABLED") {
return {
authenticated: false,
tenantId: dyn.tenantId,
scopes: [],
isByok,
isAdmin: false,
callerToken: token,
deniedReason: "অ্যাডমিন দ্বারা MCP Connector অ্যাক্সেস স্থগিত করা হয়েছে।",
httpStatus: 403,
};
}
return {
authenticated: true,
tenantId: dyn.tenantId,
scopes: dyn.scopes,
isByok,
isAdmin: dyn.isAdmin,
callerToken: token,
};
}
// Check env-configured tenant keys: AURA_TENANT_KEYS="tenantA:keyA,tenantB:keyB" // Check env-configured tenant keys: AURA_TENANT_KEYS="tenantA:keyA,tenantB:keyB"
const envTenants = process.env.AURA_TENANT_KEYS; const envTenants = process.env.AURA_TENANT_KEYS;
if (envTenants) { if (envTenants) {
@@ -205,11 +369,72 @@ export function resolveAuthContext(req: Request): AuraAuthContext {
/** /**
* Middleware: Evaluates auth context for all requests * Middleware: Evaluates auth context for all requests
*/ */
export function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): void {
req.auraAuth = resolveAuthContext(req); export async function resolveAuthContextAsync(req: Request): Promise<AuraAuthContext> {
const token = extractBearerToken(req);
const local = resolveAuthContext(req);
if (
process.env.NODE_ENV === "test" ||
!token ||
!token.startsWith("snl_mcp_") ||
local.authenticated ||
local.deniedReason
) {
return local;
}
const hash = createHash("sha256").update(token).digest("hex");
const cached = remoteVerifyCache.get(hash);
if (cached && Date.now() < cached.exp && cached.record) {
return resolveAuthContext(req);
}
const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key";
const syncSecret =
process.env.AURA_MCP_SYNC_SECRET ||
process.env.AURA_API_KEY ||
process.env.COURIER_AUTH_TOKEN ||
"aura_live_mcp_master_key_2026";
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 3500);
try {
const resp = await fetch(verifyUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-aura-sync-secret": syncSecret,
},
body: JSON.stringify({ token }),
signal: ctrl.signal,
});
if (!resp.ok) return local;
const data: any = await resp.json().catch(() => ({}));
if (!data?.valid || !data?.tenantId) return local;
const status = data.allowed ? String(data.status || "ACTIVE") : String(data.status || "PAYMENT_DUE");
await upsertDynamicKeyHash({
tokenHash: hash,
rawToken: token,
tenantId: String(data.tenantId),
storeName: data.storeName,
scopes: Array.isArray(data.scopes) && data.scopes.length ? data.scopes : ["read", "write"],
isAdmin: Boolean(data.isAdmin),
status,
});
return resolveAuthContext(req);
} catch {
return local;
} finally {
clearTimeout(timer);
}
}
export async function optionalAuthMiddleware(req: Request, _res: Response, next: NextFunction): Promise<void> {
req.auraAuth = await resolveAuthContextAsync(req);
next(); next();
} }
/** /**
* Strict /mcp Authentication & Per-Key Rate Limit Guard * Strict /mcp Authentication & Per-Key Rate Limit Guard
* Allows unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping, list_couriers) * Allows unauthenticated discovery handshakes (initialize, notifications/initialized, tools/list, ping, list_couriers)
@@ -221,6 +446,20 @@ export function requireMcpAuth(req: Request, res: Response, next: NextFunction):
const ctx = req.auraAuth || resolveAuthContext(req); const ctx = req.auraAuth || resolveAuthContext(req);
req.auraAuth = ctx; req.auraAuth = ctx;
if (ctx.deniedReason) {
res.status(ctx.httpStatus || 402).json(
wrapError(
new McpToolError({
code: "UNAUTHORIZED",
message: ctx.deniedReason,
retryable: false,
source: "validator",
})
)
);
return;
}
// If a caller explicitly passed an invalid / forged token, always reject with 401 // If a caller explicitly passed an invalid / forged token, always reject with 401
if (ctx.tenantId === "invalid") { if (ctx.tenantId === "invalid") {
res.status(401).json( res.status(401).json(