Subir archivos a "integra-mcp"
This commit is contained in:
@@ -12,6 +12,30 @@ const esc = s => String(s).replace(/[&<>"']/g,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.');
|
||||
@@ -72,13 +96,18 @@ export function oauthRouter({ store, origin, authenticate, currentUser, redirect
|
||||
<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 || typeof req.body.request_id!=='string') return fail(res,'access_denied',403);
|
||||
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 || !cookie || !equal(flow.browserHash,hash(cookie)) || !redirectAllowed(flow.redirect_uri,redirectUris)) return fail(res,'access_denied',403);
|
||||
const user=await authenticate(req.body.email,req.body.password);
|
||||
if (!user) return fail(res,'access_denied',403);
|
||||
if (!await store.take('flow',hash(req.body.request_id))) return fail(res,'access_denied',403);
|
||||
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'});
|
||||
@@ -138,23 +167,27 @@ export function oauthRouter({ store, origin, authenticate, currentUser, redirect
|
||||
}
|
||||
|
||||
export function accountAccess(pool) {
|
||||
const allowed = u => u && u.status==='active' && u.is_verified===true &&
|
||||
['admin','superadmin'].includes(String(u.role).trim().toLowerCase());
|
||||
async function currentUser(userId) {
|
||||
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 (!allowed(u)) return null;
|
||||
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]?.status!=='active' || owner.rows[0]?.is_verified!==true) return null;
|
||||
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) {
|
||||
if (typeof email!=='string' || typeof password!=='string' || email.length>254 || password.length>1024) return null;
|
||||
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):null;
|
||||
return valid&&u?currentUser(u.id,report):rejected(report,'invalid_credentials');
|
||||
}};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user