Subir archivos a "integra-mcp"
This commit is contained in:
158
integra-mcp/oauth.mjs
Normal file
158
integra-mcp/oauth.mjs
Normal file
@@ -0,0 +1,158 @@
|
||||
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 } 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);
|
||||
|
||||
export function oauthRouter({ store, origin, authenticate, currentUser, redirectUris }) {
|
||||
if (!redirectUris.every(safeRedirect)) throw new Error('Los callbacks OAuth deben ser URL HTTPS exactas.');
|
||||
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'],
|
||||
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=>redirectUris.includes(u)) ||
|
||||
(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 || !client.redirect_uris.includes(p.redirect_uri) || !redirectUris.includes(p.redirect_uri) ||
|
||||
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'; frame-ancestors 'none'; base-uri 'none'",
|
||||
'X-Frame-Options':'DENY','Referrer-Policy':'no-referrer','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 || typeof req.body.request_id!=='string') return fail(res,'access_denied',403);
|
||||
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)) || !redirectUris.includes(flow.redirect_uri)) 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);
|
||||
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);
|
||||
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) || !redirectUris.includes(record.redirect_uri) || !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 allowed = u => u && u.status==='active' && u.is_verified===true &&
|
||||
['admin','superadmin'].includes(String(u.role).trim().toLowerCase());
|
||||
async function currentUser(userId) {
|
||||
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;
|
||||
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;
|
||||
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;
|
||||
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;
|
||||
}};
|
||||
}
|
||||
Reference in New Issue
Block a user