chore(build): sync compiled dist artifacts with d1e0948 and add .dockerignore
This commit is contained in:
Vendored
+232
-10
@@ -14,6 +14,7 @@ const WRITE_TOOLS = new Set([
|
||||
"create_parcel",
|
||||
"resolve_ndr_issue",
|
||||
"cancel_parcel",
|
||||
"update_parcel",
|
||||
"bulk_create_parcels",
|
||||
]);
|
||||
// Per-key sliding-window rate limiter store
|
||||
@@ -60,10 +61,108 @@ function safeCompare(a, b) {
|
||||
return false;
|
||||
return timingSafeEqual(bufA, bufB);
|
||||
}
|
||||
/**
|
||||
* In-memory / env-configured tenant API keys registry.
|
||||
* Maps sha256(token) -> { tenantId, scopes, isAdmin }
|
||||
*/
|
||||
const dynamicKeyHashes = new Map();
|
||||
const remoteVerifyCache = new Map();
|
||||
let authDbPool = null;
|
||||
export async function initDynamicAuthStore(pool) {
|
||||
authDbPool = pool;
|
||||
if (!pool)
|
||||
return;
|
||||
try {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS aura_mcp_dynamic_keys (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
tenant_id TEXT NOT NULL,
|
||||
store_name TEXT,
|
||||
scopes JSONB NOT NULL DEFAULT '["read","write"]',
|
||||
is_admin BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
status TEXT NOT NULL DEFAULT 'ACTIVE',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)
|
||||
`);
|
||||
const res = await pool.query("SELECT token_hash, tenant_id, store_name, scopes, is_admin, status, updated_at FROM aura_mcp_dynamic_keys");
|
||||
for (const row of res.rows || []) {
|
||||
dynamicKeyHashes.set(row.token_hash, {
|
||||
tokenHash: row.token_hash,
|
||||
tenantId: row.tenant_id,
|
||||
storeName: row.store_name || undefined,
|
||||
scopes: Array.isArray(row.scopes) ? row.scopes : ["read", "write"],
|
||||
isAdmin: Boolean(row.is_admin),
|
||||
status: String(row.status || "ACTIVE").toUpperCase(),
|
||||
updatedAt: new Date(row.updated_at || Date.now()).toISOString(),
|
||||
});
|
||||
}
|
||||
console.log(`[Auth] Loaded ${dynamicKeyHashes.size} dynamic MCP key(s) from PostgreSQL.`);
|
||||
}
|
||||
catch (err) {
|
||||
console.warn("[Auth] Dynamic key table init skipped:", err?.message);
|
||||
}
|
||||
}
|
||||
export async function upsertDynamicKeyHash(opts) {
|
||||
const hash = (opts.tokenHash || (opts.rawToken ? createHash("sha256").update(opts.rawToken).digest("hex") : "")).trim();
|
||||
if (!hash)
|
||||
throw new Error("tokenHash or rawToken required");
|
||||
const status = String(opts.status || "ACTIVE").toUpperCase();
|
||||
const scopes = Array.isArray(opts.scopes) && opts.scopes.length ? opts.scopes : ["read", "write"];
|
||||
const rec = {
|
||||
tokenHash: hash,
|
||||
tenantId: opts.tenantId,
|
||||
storeName: opts.storeName,
|
||||
scopes,
|
||||
isAdmin: Boolean(opts.isAdmin),
|
||||
status,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
dynamicKeyHashes.set(hash, rec);
|
||||
if (opts.rawToken) {
|
||||
remoteVerifyCache.set(hash, { exp: Date.now() + 20_000, record: rec });
|
||||
}
|
||||
if (authDbPool) {
|
||||
try {
|
||||
await authDbPool.query(`INSERT INTO aura_mcp_dynamic_keys (token_hash, tenant_id, store_name, scopes, is_admin, status, updated_at)
|
||||
VALUES ($1, $2, $3, $4::jsonb, $5, $6, NOW())
|
||||
ON CONFLICT (token_hash) DO UPDATE SET
|
||||
tenant_id = EXCLUDED.tenant_id,
|
||||
store_name = COALESCE(EXCLUDED.store_name, aura_mcp_dynamic_keys.store_name),
|
||||
scopes = EXCLUDED.scopes,
|
||||
is_admin = EXCLUDED.is_admin,
|
||||
status = EXCLUDED.status,
|
||||
updated_at = NOW()`, [hash, rec.tenantId, rec.storeName || null, JSON.stringify(scopes), rec.isAdmin, status]);
|
||||
}
|
||||
catch (err) {
|
||||
console.warn("[Auth] Failed persisting dynamic key:", err?.message);
|
||||
}
|
||||
}
|
||||
return rec;
|
||||
}
|
||||
export async function setTenantDynamicKeyStatus(tenantId, status) {
|
||||
const norm = String(status || "SUSPENDED").toUpperCase();
|
||||
let updated = 0;
|
||||
for (const [h, rec] of dynamicKeyHashes.entries()) {
|
||||
if (rec.tenantId === tenantId) {
|
||||
dynamicKeyHashes.set(h, { ...rec, status: norm, updatedAt: new Date().toISOString() });
|
||||
remoteVerifyCache.delete(h);
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
if (authDbPool) {
|
||||
try {
|
||||
await authDbPool.query("UPDATE aura_mcp_dynamic_keys SET status = $1, updated_at = NOW() WHERE tenant_id = $2", [norm, tenantId]);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
export function listDynamicKeySummaries() {
|
||||
return Array.from(dynamicKeyHashes.values()).map((r) => ({
|
||||
hashPrefix: r.tokenHash.slice(0, 10) + "...",
|
||||
tenantId: r.tenantId,
|
||||
storeName: r.storeName || "",
|
||||
status: r.status,
|
||||
scopes: r.scopes,
|
||||
updatedAt: r.updatedAt,
|
||||
}));
|
||||
}
|
||||
const registeredKeyHashes = new Map();
|
||||
export function registerApiKey(token, tenantId, scopes = ["read", "write"], isAdmin = false) {
|
||||
const hash = createHash("sha256").update(token).digest("hex");
|
||||
@@ -125,6 +224,42 @@ export function resolveAuthContext(req) {
|
||||
callerToken: token,
|
||||
};
|
||||
}
|
||||
// 3b. Dynamic Database / Synced Tenant Key lookup
|
||||
if (dynamicKeyHashes.has(tokenHash)) {
|
||||
const dyn = dynamicKeyHashes.get(tokenHash);
|
||||
if (dyn.status === "PAYMENT_DUE") {
|
||||
return {
|
||||
authenticated: false,
|
||||
tenantId: dyn.tenantId,
|
||||
scopes: [],
|
||||
isByok,
|
||||
isAdmin: false,
|
||||
callerToken: token,
|
||||
deniedReason: "পেমেন্ট বাকি থাকায় MCP Connector অ্যাক্সেস হোল্ড করা হয়েছে (Payment Due)।",
|
||||
httpStatus: 402,
|
||||
};
|
||||
}
|
||||
if (dyn.status === "SUSPENDED" || dyn.status === "DISABLED") {
|
||||
return {
|
||||
authenticated: false,
|
||||
tenantId: dyn.tenantId,
|
||||
scopes: [],
|
||||
isByok,
|
||||
isAdmin: false,
|
||||
callerToken: token,
|
||||
deniedReason: "অ্যাডমিন দ্বারা MCP Connector অ্যাক্সেস স্থগিত করা হয়েছে।",
|
||||
httpStatus: 403,
|
||||
};
|
||||
}
|
||||
return {
|
||||
authenticated: true,
|
||||
tenantId: dyn.tenantId,
|
||||
scopes: dyn.scopes,
|
||||
isByok,
|
||||
isAdmin: dyn.isAdmin,
|
||||
callerToken: token,
|
||||
};
|
||||
}
|
||||
// Check env-configured tenant keys: AURA_TENANT_KEYS="tenantA:keyA,tenantB:keyB"
|
||||
const envTenants = process.env.AURA_TENANT_KEYS;
|
||||
if (envTenants) {
|
||||
@@ -155,8 +290,64 @@ export function resolveAuthContext(req) {
|
||||
/**
|
||||
* Middleware: Evaluates auth context for all requests
|
||||
*/
|
||||
export function optionalAuthMiddleware(req, _res, next) {
|
||||
req.auraAuth = resolveAuthContext(req);
|
||||
export async function resolveAuthContextAsync(req) {
|
||||
const token = extractBearerToken(req);
|
||||
const local = resolveAuthContext(req);
|
||||
if (process.env.NODE_ENV === "test" ||
|
||||
!token ||
|
||||
!token.startsWith("snl_mcp_") ||
|
||||
local.authenticated ||
|
||||
local.deniedReason) {
|
||||
return local;
|
||||
}
|
||||
const hash = createHash("sha256").update(token).digest("hex");
|
||||
const cached = remoteVerifyCache.get(hash);
|
||||
if (cached && Date.now() < cached.exp && cached.record) {
|
||||
return resolveAuthContext(req);
|
||||
}
|
||||
const verifyUrl = process.env.SNEHALATA_VERIFY_KEY_URL || "https://www.snehalata.com/api/mcp/verify-key";
|
||||
const syncSecret = process.env.AURA_MCP_SYNC_SECRET ||
|
||||
process.env.AURA_API_KEY ||
|
||||
process.env.COURIER_AUTH_TOKEN ||
|
||||
"aura_live_mcp_master_key_2026";
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 3500);
|
||||
try {
|
||||
const resp = await fetch(verifyUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-aura-sync-secret": syncSecret,
|
||||
},
|
||||
body: JSON.stringify({ token }),
|
||||
signal: ctrl.signal,
|
||||
});
|
||||
if (!resp.ok)
|
||||
return local;
|
||||
const data = await resp.json().catch(() => ({}));
|
||||
if (!data?.valid || !data?.tenantId)
|
||||
return local;
|
||||
const status = data.allowed ? String(data.status || "ACTIVE") : String(data.status || "PAYMENT_DUE");
|
||||
await upsertDynamicKeyHash({
|
||||
tokenHash: hash,
|
||||
rawToken: token,
|
||||
tenantId: String(data.tenantId),
|
||||
storeName: data.storeName,
|
||||
scopes: Array.isArray(data.scopes) && data.scopes.length ? data.scopes : ["read", "write"],
|
||||
isAdmin: Boolean(data.isAdmin),
|
||||
status,
|
||||
});
|
||||
return resolveAuthContext(req);
|
||||
}
|
||||
catch {
|
||||
return local;
|
||||
}
|
||||
finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
export async function optionalAuthMiddleware(req, _res, next) {
|
||||
req.auraAuth = await resolveAuthContextAsync(req);
|
||||
next();
|
||||
}
|
||||
/**
|
||||
@@ -169,6 +360,15 @@ export function requireMcpAuth(req, res, next) {
|
||||
const method = body && typeof body === "object" ? body.method : undefined;
|
||||
const ctx = req.auraAuth || resolveAuthContext(req);
|
||||
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 (ctx.tenantId === "invalid") {
|
||||
res.status(401).json(wrapError(new McpToolError({
|
||||
@@ -326,14 +526,36 @@ export function verifyWebhookSignature(req, provider) {
|
||||
if (pfSecret && safeCompare(pfSig, pfSecret))
|
||||
return true;
|
||||
}
|
||||
// 4. Universal master secret or bearer token fallback
|
||||
// 4. Universal master secret, registered tenant key, or merchant_token URL parameter fallback
|
||||
const masterSecret = process.env.AURA_WEBHOOK_SECRET || process.env.AURA_API_KEY || "aura_webhook_secret_2026";
|
||||
const candidate = extractBearerToken(req) ||
|
||||
const paramToken = (req.params && req.params.merchant_token) ? String(req.params.merchant_token).trim() : undefined;
|
||||
const candidate = paramToken ||
|
||||
extractBearerToken(req) ||
|
||||
req.headers["x-webhook-secret"] ||
|
||||
req.query["token"] ||
|
||||
req.query["secret"];
|
||||
if (candidate && typeof candidate === "string" && safeCompare(candidate.trim(), masterSecret)) {
|
||||
return true;
|
||||
if (candidate && typeof candidate === "string") {
|
||||
const trimmed = candidate.trim();
|
||||
if (safeCompare(trimmed, masterSecret)) {
|
||||
return true;
|
||||
}
|
||||
const tokenHash = createHash("sha256").update(trimmed).digest("hex");
|
||||
if (registeredKeyHashes.has(tokenHash)) {
|
||||
return true;
|
||||
}
|
||||
const envTenants = process.env.AURA_TENANT_KEYS;
|
||||
if (envTenants) {
|
||||
for (const pair of envTenants.split(",")) {
|
||||
const [tId, tKey] = pair.split(":");
|
||||
if ((tKey && safeCompare(trimmed, tKey.trim())) || (tId && safeCompare(trimmed, tId.trim()))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Accept non-empty merchant_token path identifier (>= 8 chars) for dedicated merchant webhook endpoints
|
||||
if (paramToken && paramToken.length >= 8 && /^[a-zA-Z0-9_\-]+$/.test(paramToken)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user