mcp remoto token
This commit is contained in:
95
mcp-server/auth/mcpTokens.js
Normal file
95
mcp-server/auth/mcpTokens.js
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
/**
|
||||||
|
* MCP Token Validation
|
||||||
|
*
|
||||||
|
* Valida tokens X-MCP-Secret contra Redis.
|
||||||
|
* El backend Python escribe la clave `mcp_tokens:<sha256_hex>` con metadata JSON:
|
||||||
|
* {
|
||||||
|
* "id": "...",
|
||||||
|
* "user": "superadmin",
|
||||||
|
* "project": "vegaasesores.com",
|
||||||
|
* "label": "MacBook Pro",
|
||||||
|
* "createdAt": 1234567890,
|
||||||
|
* "lastUsedAt": null | 1234567900
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* El plaintext es "acai_<43 chars>" y se hashea con sha256 hex en minusculas.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import Redis from "ioredis";
|
||||||
|
import crypto from "node:crypto";
|
||||||
|
|
||||||
|
const REDIS_URL = process.env.REDIS_URL || "redis://redis:6379";
|
||||||
|
|
||||||
|
// Cliente Redis compartido (lazy init para no conectar si el MCP corre en modo stdio
|
||||||
|
// u otros escenarios donde el middleware HTTP nunca se invoque).
|
||||||
|
let redisClient = null;
|
||||||
|
|
||||||
|
function getRedis() {
|
||||||
|
if (redisClient) return redisClient;
|
||||||
|
try {
|
||||||
|
redisClient = new Redis(REDIS_URL, {
|
||||||
|
lazyConnect: false,
|
||||||
|
maxRetriesPerRequest: 3,
|
||||||
|
enableReadyCheck: false,
|
||||||
|
});
|
||||||
|
redisClient.on("error", (err) => {
|
||||||
|
console.error("[mcp-tokens] redis error:", err.message);
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[mcp-tokens] no se pudo inicializar redis:", e.message);
|
||||||
|
redisClient = null;
|
||||||
|
}
|
||||||
|
return redisClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hashea un string con SHA256 y devuelve hex en minusculas.
|
||||||
|
*/
|
||||||
|
export function sha256Hex(str) {
|
||||||
|
return crypto.createHash("sha256").update(str, "utf8").digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valida un X-MCP-Secret plaintext contra Redis.
|
||||||
|
* @param {string} secret - plaintext tipo "acai_xxx"
|
||||||
|
* @returns {Promise<{user: string, project: string, id: string} | null>}
|
||||||
|
*/
|
||||||
|
export async function validateMcpToken(secret) {
|
||||||
|
if (!secret || typeof secret !== "string") return null;
|
||||||
|
const r = getRedis();
|
||||||
|
if (!r) return null;
|
||||||
|
|
||||||
|
const sha = sha256Hex(secret);
|
||||||
|
const key = `mcp_tokens:${sha}`;
|
||||||
|
|
||||||
|
let raw;
|
||||||
|
try {
|
||||||
|
raw = await r.get(key);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[mcp-tokens] redis GET error:", err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!raw) return null;
|
||||||
|
|
||||||
|
let meta;
|
||||||
|
try {
|
||||||
|
meta = JSON.parse(raw);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!meta || !meta.user || !meta.project) return null;
|
||||||
|
|
||||||
|
// Actualizacion asincrona de lastUsedAt — no bloqueamos la request.
|
||||||
|
updateLastUsedAt(key, meta).catch((e) => {
|
||||||
|
console.error("[mcp-tokens] lastUsedAt update failed:", e.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { user: meta.user, project: meta.project, id: meta.id || "" };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function updateLastUsedAt(key, meta) {
|
||||||
|
const r = getRedis();
|
||||||
|
if (!r) return;
|
||||||
|
const next = { ...meta, lastUsedAt: Math.floor(Date.now() / 1000) };
|
||||||
|
await r.set(key, JSON.stringify(next));
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
getMcpSessionCredentials
|
getMcpSessionCredentials
|
||||||
} from "./auth/index.js";
|
} from "./auth/index.js";
|
||||||
import { fetchProjectInfo } from "./auth/localClient.js";
|
import { fetchProjectInfo } from "./auth/localClient.js";
|
||||||
|
import { validateMcpToken } from "./auth/mcpTokens.js";
|
||||||
import { createSessionServer } from "./server.js";
|
import { createSessionServer } from "./server.js";
|
||||||
import { runWithSession } from "./utils/sessionContext.js";
|
import { runWithSession } from "./utils/sessionContext.js";
|
||||||
|
|
||||||
@@ -180,11 +181,45 @@ export function startHttpServer() {
|
|||||||
app.use(cors({
|
app.use(cors({
|
||||||
origin: '*',
|
origin: '*',
|
||||||
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
|
methods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
|
||||||
allowedHeaders: ['Content-Type', 'X-Acai-Token', 'X-Acai-Website', 'X-Acai-Token-Hash', 'X-User-Token', 'X-Project-Name', 'X-Acai-User', 'Authorization', 'Mcp-Session-Id'],
|
allowedHeaders: ['Content-Type', 'X-Acai-Token', 'X-Acai-Website', 'X-Acai-Token-Hash', 'X-User-Token', 'X-Project-Name', 'X-Acai-User', 'X-MCP-Secret', 'Authorization', 'Mcp-Session-Id'],
|
||||||
exposedHeaders: ['Mcp-Session-Id'],
|
exposedHeaders: ['Mcp-Session-Id'],
|
||||||
credentials: true
|
credentials: true
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
//=============================================================================
|
||||||
|
// MCP SECRET MIDDLEWARE
|
||||||
|
// Si llega X-MCP-Secret, lo validamos contra Redis (mcp_tokens:<sha256>) y
|
||||||
|
// reemplazamos los headers de identidad con los del token. El cliente NO
|
||||||
|
// puede forzar X-Acai-User / X-Project-Name si esta usando X-MCP-Secret.
|
||||||
|
// Si NO llega X-MCP-Secret, pasa de largo (modo legacy/dev: el cliente se
|
||||||
|
// identifica manualmente con X-Acai-User + X-Project-Name).
|
||||||
|
//=============================================================================
|
||||||
|
app.use(async (req, res, next) => {
|
||||||
|
const secret = req.headers["x-mcp-secret"];
|
||||||
|
if (!secret) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const auth = await validateMcpToken(secret);
|
||||||
|
if (!auth) {
|
||||||
|
res.status(401)
|
||||||
|
.setHeader("Content-Type", "application/json")
|
||||||
|
.end(JSON.stringify({ error: "Invalid MCP token" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Sobrescribe los headers de identidad con los del token validado.
|
||||||
|
req.headers["x-acai-user"] = auth.user;
|
||||||
|
req.headers["x-project-name"] = auth.project;
|
||||||
|
return next();
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[MCP] mcpSecretMiddleware error:", err.message);
|
||||||
|
res.status(401)
|
||||||
|
.setHeader("Content-Type", "application/json")
|
||||||
|
.end(JSON.stringify({ error: "Invalid MCP token" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
//=============================================================================
|
//=============================================================================
|
||||||
// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-03-26)
|
// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-03-26)
|
||||||
// This is the new recommended transport for MCP
|
// This is the new recommended transport for MCP
|
||||||
|
|||||||
79
mcp-server/package-lock.json
generated
79
mcp-server/package-lock.json
generated
@@ -15,6 +15,7 @@
|
|||||||
"cors": "^2.8.6",
|
"cors": "^2.8.6",
|
||||||
"dotenv": "^16.3.1",
|
"dotenv": "^16.3.1",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
|
"ioredis": "^5.10.1",
|
||||||
"jsdom": "^27.2.0",
|
"jsdom": "^27.2.0",
|
||||||
"redis": "^4.7.0",
|
"redis": "^4.7.0",
|
||||||
"sharp": "^0.33.5",
|
"sharp": "^0.33.5",
|
||||||
@@ -596,6 +597,12 @@
|
|||||||
"url": "https://opencollective.com/libvips"
|
"url": "https://opencollective.com/libvips"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@ioredis/commands": {
|
||||||
|
"version": "1.5.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.1.tgz",
|
||||||
|
"integrity": "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@modelcontextprotocol/sdk": {
|
"node_modules/@modelcontextprotocol/sdk": {
|
||||||
"version": "1.27.1",
|
"version": "1.27.1",
|
||||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.27.1.tgz",
|
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.27.1.tgz",
|
||||||
@@ -1249,6 +1256,15 @@
|
|||||||
"node": ">=0.4.0"
|
"node": ">=0.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/denque": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/depd": {
|
"node_modules/depd": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||||
@@ -1928,6 +1944,30 @@
|
|||||||
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/ioredis": {
|
||||||
|
"version": "5.10.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.10.1.tgz",
|
||||||
|
"integrity": "sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@ioredis/commands": "1.5.1",
|
||||||
|
"cluster-key-slot": "^1.1.0",
|
||||||
|
"debug": "^4.3.4",
|
||||||
|
"denque": "^2.1.0",
|
||||||
|
"lodash.defaults": "^4.2.0",
|
||||||
|
"lodash.isarguments": "^3.1.0",
|
||||||
|
"redis-errors": "^1.2.0",
|
||||||
|
"redis-parser": "^3.0.0",
|
||||||
|
"standard-as-callback": "^2.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12.22.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/ioredis"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ip-address": {
|
"node_modules/ip-address": {
|
||||||
"version": "10.1.0",
|
"version": "10.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",
|
||||||
@@ -2100,6 +2140,18 @@
|
|||||||
"integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
|
"integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
|
||||||
"license": "BSD-2-Clause"
|
"license": "BSD-2-Clause"
|
||||||
},
|
},
|
||||||
|
"node_modules/lodash.defaults": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/lodash.isarguments": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/lru-cache": {
|
"node_modules/lru-cache": {
|
||||||
"version": "11.2.7",
|
"version": "11.2.7",
|
||||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz",
|
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.7.tgz",
|
||||||
@@ -2557,6 +2609,27 @@
|
|||||||
"@redis/time-series": "1.1.0"
|
"@redis/time-series": "1.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/redis-errors": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/redis-parser": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"redis-errors": "^1.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/require-from-string": {
|
"node_modules/require-from-string": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
|
||||||
@@ -2826,6 +2899,12 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/standard-as-callback": {
|
||||||
|
"version": "2.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz",
|
||||||
|
"integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/statuses": {
|
"node_modules/statuses": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
"cors": "^2.8.6",
|
"cors": "^2.8.6",
|
||||||
"dotenv": "^16.3.1",
|
"dotenv": "^16.3.1",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
|
"ioredis": "^5.10.1",
|
||||||
"jsdom": "^27.2.0",
|
"jsdom": "^27.2.0",
|
||||||
"redis": "^4.7.0",
|
"redis": "^4.7.0",
|
||||||
"sharp": "^0.33.5",
|
"sharp": "^0.33.5",
|
||||||
|
|||||||
Reference in New Issue
Block a user