193 lines
14 KiB
JavaScript
193 lines
14 KiB
JavaScript
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
|
|
import express from 'express';
|
|
import bcrypt from 'bcryptjs';
|
|
import rateLimit from 'integra-mcp-rate-limit';
|
|
import { hash } from './store.mjs';
|
|
import { safeRedirect, redirectAllowed } from './security.mjs';
|
|
|
|
const random = () => randomBytes(32).toString('base64url');
|
|
const equal = (a,b) => typeof a === 'string' && typeof b === 'string' && a.length === b.length &&
|
|
timingSafeEqual(Buffer.from(a),Buffer.from(b));
|
|
const esc = s => String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
const scopesAllowed = ['integra:read','integra:write'];
|
|
const fail = (res,error='invalid_request',status=400) => res.status(status).json({error});
|
|
const wrap = fn => (req,res,next) => Promise.resolve(fn(req,res)).catch(next);
|
|
const denialMessages = Object.freeze({
|
|
invalid_origin:'El formulario no se ha enviado desde el origen de IntegraRepara.',
|
|
invalid_form:'Falta el identificador del formulario. Abre una conexión nueva.',
|
|
flow_missing_or_expired:'La conexión ha caducado o ya se ha utilizado. Abre una conexión nueva.',
|
|
cookie_missing:'El navegador no ha enviado la cookie de esta conexión.',
|
|
cookie_mismatch:'La cookie corresponde a otro formulario. Cierra los anteriores y abre una conexión nueva.',
|
|
callback_not_allowed:'El callback de esta conexión ya no está permitido en el servidor.',
|
|
invalid_credentials:'No se ha podido validar el email o teléfono y la contraseña.',
|
|
user_not_found:'La cuenta validada ya no existe.',
|
|
user_inactive:'La cuenta está inactiva o bloqueada.',
|
|
user_not_verified:'La cuenta no tiene la verificación requerida por el conector.',
|
|
role_not_admin:'La cuenta validada no tiene rol admin ni superadmin.',
|
|
owner_not_found:'No existe el propietario de la empresa asociado a esta cuenta.',
|
|
owner_inactive:'El propietario de la empresa está inactivo o bloqueado.',
|
|
owner_not_verified:'El propietario de la empresa no tiene la verificación requerida por el conector.',
|
|
flow_already_used:'Otra solicitud ya ha utilizado este formulario. Abre una conexión nueva.',
|
|
account_rejected:'La cuenta ha sido rechazada por el proveedor de acceso.'
|
|
});
|
|
function deny(res, reason) {
|
|
const safeReason=Object.hasOwn(denialMessages,reason)?reason:'account_rejected';
|
|
// Fixed reason codes only. Never log identity, form bodies, credentials or cookies.
|
|
console.warn('[Integra MCP OAuth] access_denied:',safeReason);
|
|
return res.status(403).json({error:'access_denied',reason:safeReason,error_description:denialMessages[safeReason]});
|
|
}
|
|
|
|
export function oauthRouter({ store, origin, authenticate, currentUser, redirectUris }) {
|
|
if (!redirectUris.every(safeRedirect)) throw new Error('Los callbacks deben usar HTTPS o HTTP local en 127.0.0.1.');
|
|
const resource = `${origin}/mcp`;
|
|
const router = express.Router();
|
|
router.use(express.json({limit:'16kb'}),express.urlencoded({extended:false,limit:'16kb'}));
|
|
router.use((req,res,next)=>{res.set('Cache-Control','no-store');next();});
|
|
const strictLimit = rateLimit({windowMs:15*60000,limit:20,standardHeaders:'draft-8',legacyHeaders:false});
|
|
router.get('/.well-known/oauth-authorization-server', (req,res)=>res.json({
|
|
issuer:origin,authorization_endpoint:`${origin}/mcp-connect/authorize`,token_endpoint:`${origin}/mcp-connect/token`,
|
|
registration_endpoint:`${origin}/mcp-connect/register`,revocation_endpoint:`${origin}/mcp-connect/revoke`,
|
|
response_types_supported:['code'],grant_types_supported:['authorization_code','refresh_token'],
|
|
code_challenge_methods_supported:['S256'],token_endpoint_auth_methods_supported:['none'],
|
|
authorization_response_iss_parameter_supported:true,
|
|
scopes_supported:scopesAllowed
|
|
}));
|
|
for (const route of ['/.well-known/oauth-protected-resource','/.well-known/oauth-protected-resource/mcp']) {
|
|
router.get(route,(req,res)=>res.json({resource,authorization_servers:[origin],scopes_supported:scopesAllowed,resource_name:'IntegraRepara'}));
|
|
}
|
|
router.post('/mcp-connect/register',strictLimit,wrap(async(req,res)=>{
|
|
const b=req.body;
|
|
if (!Array.isArray(b.redirect_uris) || !b.redirect_uris.length || b.redirect_uris.length>10 ||
|
|
!b.redirect_uris.every(u=>redirectAllowed(u,redirectUris)) ||
|
|
(b.token_endpoint_auth_method && b.token_endpoint_auth_method!=='none') ||
|
|
(b.grant_types && (!Array.isArray(b.grant_types) || !b.grant_types.every(g=>['authorization_code','refresh_token'].includes(g)))) ||
|
|
(b.response_types && (!Array.isArray(b.response_types) || b.response_types.some(t=>t!=='code'))))
|
|
return fail(res,'invalid_client_metadata');
|
|
const client={client_id:random(),client_name:String(b.client_name||'Cliente MCP').slice(0,100),
|
|
redirect_uris:b.redirect_uris,token_endpoint_auth_method:'none',grant_types:['authorization_code','refresh_token'],response_types:['code']};
|
|
await store.set('client',client.client_id,client,365*86400);
|
|
res.status(201).json(client);
|
|
}));
|
|
router.get('/mcp-connect/authorize',strictLimit,wrap(async(req,res)=>{
|
|
const p=req.query;
|
|
if (Object.values(p).some(v=>typeof v!=='string')) return fail(res);
|
|
const client=await store.get('client',p.client_id);
|
|
const scopes=[...new Set(String(p.scope||'integra:read').split(' ').filter(Boolean))];
|
|
if (!client || !redirectAllowed(p.redirect_uri,client.redirect_uris) || !redirectAllowed(p.redirect_uri,redirectUris) ||
|
|
p.response_type!=='code' || p.code_challenge_method!=='S256' || !/^[A-Za-z0-9_-]{43}$/.test(p.code_challenge||'') ||
|
|
p.resource!==resource || !scopes.includes('integra:read') || scopes.some(s=>!scopesAllowed.includes(s)) || (p.state||'').length>2048)
|
|
return fail(res);
|
|
const requestId=random(),browserSecret=random();
|
|
await store.set('flow',hash(requestId),{...p,scopes,browserHash:hash(browserSecret)},600);
|
|
res.set({
|
|
'Content-Security-Policy':"default-src 'none'; style-src 'unsafe-inline'; form-action 'self' http://127.0.0.1:*; frame-ancestors 'none'; base-uri 'none'", 'X-Frame-Options':'DENY','Referrer-Policy':'strict-origin','X-Content-Type-Options':'nosniff'
|
|
});
|
|
res.cookie('integra_mcp_flow',browserSecret,{httpOnly:true,secure:true,sameSite:'lax',path:'/mcp-connect',maxAge:600000});
|
|
res.type('html').send(`<!doctype html><html lang="es"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Conectar IntegraRepara</title>
|
|
<style>body{font:16px system-ui;background:#f1f5f9;color:#0f172a;padding:24px}main{max-width:480px;margin:6vh auto;background:white;padding:32px;border-radius:16px}label{display:block;margin:16px 0}input,button{box-sizing:border-box;width:100%;padding:12px;font:inherit}button{background:#1e3a8a;color:white;border:0;border-radius:6px}small{overflow-wrap:anywhere}</style>
|
|
<main><h1>Conectar IntegraRepara</h1><p>Vas a autorizar a <strong>${esc(client.client_name)}</strong>.</p>
|
|
<p>Permisos: consultar datos de tu empresa${scopes.includes('integra:write')?', crear y modificar registros, eliminar registros y activar acciones con WhatsApp según lo que solicites':''}.</p>
|
|
<small>Aplicación de destino: ${esc(new URL(p.redirect_uri).origin)}</small>
|
|
<form method="post" action="/mcp-connect/consent"><input type="hidden" name="request_id" value="${requestId}">
|
|
<label>Email o teléfono<input name="email" autocomplete="username" required maxlength="254"></label>
|
|
<label>Contraseña<input type="password" name="password" autocomplete="current-password" required maxlength="1024"></label>
|
|
<p>Usa una cuenta administradora de IntegraRepara. La contraseña se comprueba aquí y no se entrega al complemento.</p>
|
|
<button>Iniciar sesión y autorizar</button></form><p>Para cancelar, cierra esta ventana.</p></main></html>`);
|
|
}));
|
|
router.post('/mcp-connect/consent',strictLimit,wrap(async(req,res)=>{
|
|
if (req.headers.origin!==origin) return deny(res,'invalid_origin');
|
|
if (typeof req.body.request_id!=='string') return deny(res,'invalid_form');
|
|
const flow=await store.get('flow',hash(req.body.request_id));
|
|
const cookie=String(req.headers.cookie||'').split(';').map(s=>s.trim()).find(s=>s.startsWith('integra_mcp_flow='))?.slice('integra_mcp_flow='.length);
|
|
if (!flow) return deny(res,'flow_missing_or_expired');
|
|
if (!cookie) return deny(res,'cookie_missing');
|
|
if (!equal(flow.browserHash,hash(cookie))) return deny(res,'cookie_mismatch');
|
|
if (!redirectAllowed(flow.redirect_uri,redirectUris)) return deny(res,'callback_not_allowed');
|
|
let reason='account_rejected';
|
|
const user=await authenticate(req.body.email,req.body.password,code=>{if(Object.hasOwn(denialMessages,code))reason=code;});
|
|
if (!user) return deny(res,reason);
|
|
if (!await store.take('flow',hash(req.body.request_id))) return deny(res,'flow_already_used');
|
|
const code=random();
|
|
await store.set('code',hash(code),{...flow,userId:user.id},120);
|
|
res.clearCookie('integra_mcp_flow',{httpOnly:true,secure:true,sameSite:'lax',path:'/mcp-connect'});
|
|
const callback=new URL(flow.redirect_uri);callback.searchParams.set('code',code);
|
|
callback.searchParams.set('iss',origin);
|
|
if (flow.state) callback.searchParams.set('state',flow.state);
|
|
res.redirect(303,callback.href);
|
|
}));
|
|
async function issue(record,grantId) {
|
|
const access=random(),refresh=random();
|
|
const data={userId:record.userId,clientId:record.client_id,scopes:record.scopes,resource,grantId};
|
|
await store.set('access',hash(access),data,3600);
|
|
await store.set('refresh',hash(refresh),data,30*86400);
|
|
return {access_token:access,refresh_token:refresh,token_type:'Bearer',expires_in:3600,scope:data.scopes.join(' ')};
|
|
}
|
|
router.post('/mcp-connect/token',strictLimit,wrap(async(req,res)=>{
|
|
const b=req.body;
|
|
if (b.resource!==resource || typeof b.client_id!=='string' || !await store.get('client',b.client_id)) return fail(res,'invalid_client');
|
|
if (b.grant_type==='authorization_code') {
|
|
if (typeof b.code!=='string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(b.code_verifier||'')) return fail(res,'invalid_grant');
|
|
const record=await store.get('code',hash(b.code));
|
|
const challenge=createHash('sha256').update(b.code_verifier).digest('base64url');
|
|
if (!record || record.client_id!==b.client_id || record.redirect_uri!==b.redirect_uri || record.resource!==resource ||
|
|
!equal(record.code_challenge,challenge) || !redirectAllowed(record.redirect_uri,redirectUris) || !await currentUser(record.userId))
|
|
return fail(res,'invalid_grant');
|
|
if (!await store.take('code',hash(b.code))) return fail(res,'invalid_grant');
|
|
const grantId=random();await store.set('grant',grantId,{userId:record.userId,clientId:b.client_id},30*86400);
|
|
return res.json(await issue(record,grantId));
|
|
}
|
|
if (b.grant_type==='refresh_token') {
|
|
if (typeof b.refresh_token!=='string') return fail(res,'invalid_grant');
|
|
const record=await store.get('refresh',hash(b.refresh_token));
|
|
if (!record || record.clientId!==b.client_id || record.resource!==resource || !await store.get('grant',record.grantId) || !await currentUser(record.userId))
|
|
return fail(res,'invalid_grant');
|
|
const scopes=b.scope===undefined?record.scopes:String(b.scope).split(' ').filter(Boolean);
|
|
if (!scopes.includes('integra:read') || scopes.some(s=>!record.scopes.includes(s))) return fail(res,'invalid_scope');
|
|
if (!await store.take('refresh',hash(b.refresh_token))) return fail(res,'invalid_grant');
|
|
return res.json(await issue({userId:record.userId,client_id:b.client_id,scopes},record.grantId));
|
|
}
|
|
return fail(res,'unsupported_grant_type');
|
|
}));
|
|
router.post('/mcp-connect/revoke',strictLimit,wrap(async(req,res)=>{
|
|
const b=req.body;
|
|
if (typeof b.token!=='string' || typeof b.client_id!=='string') return fail(res);
|
|
for (const kind of ['access','refresh']) {
|
|
const record=await store.get(kind,hash(b.token));
|
|
if (record?.clientId===b.client_id) await store.delete('grant',record.grantId);
|
|
}
|
|
res.status(200).end();
|
|
}));
|
|
router.use((err,req,res,next)=>{
|
|
if (res.headersSent) return next(err);
|
|
console.error('[Integra MCP OAuth]',err.name);
|
|
res.status(500).json({error:'server_error'});
|
|
});
|
|
return router;
|
|
}
|
|
|
|
export function accountAccess(pool) {
|
|
const rejected = (report,reason) => { if(typeof report==='function')report(reason);return null; };
|
|
async function currentUser(userId,report) {
|
|
const q=await pool.query('SELECT id,owner_id,role,status,is_verified FROM users WHERE id=$1',[userId]);
|
|
const u=q.rows[0];
|
|
if (!u) return rejected(report,'user_not_found');
|
|
if (u.status!=='active') return rejected(report,'user_inactive');
|
|
if (u.is_verified!==true) return rejected(report,'user_not_verified');
|
|
if (!['admin','superadmin'].includes(String(u.role).trim().toLowerCase())) return rejected(report,'role_not_admin');
|
|
const accountId=u.owner_id||u.id;
|
|
const owner=await pool.query('SELECT status,is_verified FROM users WHERE id=$1',[accountId]);
|
|
if (!owner.rows[0]) return rejected(report,'owner_not_found');
|
|
if (owner.rows[0].status!=='active') return rejected(report,'owner_inactive');
|
|
if (owner.rows[0].is_verified!==true) return rejected(report,'owner_not_verified');
|
|
return {...u,accountId,role:String(u.role).trim().toLowerCase()};
|
|
}
|
|
return {currentUser,async authenticate(email,password,report) {
|
|
if (typeof email!=='string' || typeof password!=='string' || email.length>254 || password.length>1024) return rejected(report,'invalid_credentials');
|
|
const q=await pool.query('SELECT id,password_hash FROM users WHERE email=$1 OR phone=$1 ORDER BY id LIMIT 1',[email]);
|
|
const u=q.rows[0];
|
|
// A valid dummy bcrypt hash keeps unknown-account failures expensive as well.
|
|
const valid=await bcrypt.compare(password,u?.password_hash||'$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy');
|
|
return valid&&u?currentUser(u.id,report):rejected(report,'invalid_credentials');
|
|
}};
|
|
}
|