From 716f1f6bc7df80b3af4b31b7c15941ae06bb90d9 Mon Sep 17 00:00:00 2001 From: marsalva Date: Sun, 8 Nov 2026 18:57:59 +0000 Subject: [PATCH] Subir archivos a "integra-mcp" --- integra-mcp/bridge.mjs | 73 ++++++++++++++++++ integra-mcp/mount.mjs | 89 ++++++++++++++++++++++ integra-mcp/oauth.mjs | 158 +++++++++++++++++++++++++++++++++++++++ integra-mcp/security.mjs | 27 +++++++ integra-mcp/store.mjs | 34 +++++++++ 5 files changed, 381 insertions(+) create mode 100644 integra-mcp/bridge.mjs create mode 100644 integra-mcp/mount.mjs create mode 100644 integra-mcp/oauth.mjs create mode 100644 integra-mcp/security.mjs create mode 100644 integra-mcp/store.mjs diff --git a/integra-mcp/bridge.mjs b/integra-mcp/bridge.mjs new file mode 100644 index 0000000..7b638a4 --- /dev/null +++ b/integra-mcp/bridge.mjs @@ -0,0 +1,73 @@ +import { tools, validateBusiness } from './tools.mjs'; +import { redact } from './security.mjs'; + +const ownership = { + service:['scraped_services','owner_id'],block:['scraped_services','owner_id'], + client:['clients','owner_id'],budget:['budgets','owner_id'],article:['articles','owner_id'], + user:['users','owner_id'],guild:['guilds','owner_id'],status:['service_statuses','owner_id'], + company:['companies','owner_id'],zone:['zones','owner_id'],report:['work_reports','owner_id'], + plan:['protection_plans','company_id'],subscription:['protection_subscriptions','company_id'], + tariff:['energy_tariffs','owner_id'],lead:['energy_quote_leads','owner_id'] +}; +export function makeBridge({ pool, signToken, backendUrl, checkAvailability, fetchImpl=fetch }) { + const base = new URL(backendUrl); + if (base.protocol!=='http:' || base.hostname!=='127.0.0.1' || base.pathname!=='/' || base.search || base.hash || base.username || base.password) + throw new Error('El puente interno solo permite http://127.0.0.1:PUERTO'); + async function own(kind,value,user) { + const [table,column]=ownership[kind]; // Fixed identifiers; user input is always parameterized. + const extra=kind==='block'?" AND provider='SYSTEM_BLOCK'":''; + const q=await pool.query(`SELECT id FROM ${table} WHERE id=$1 AND ${column}=$2${extra}`,[value,user.accountId]); + if (!q.rows.length) throw new Error('Registro no encontrado en tu empresa.'); + } + return async (name,input,user,scopes) => { + const tool=tools.find(t=>t.name===name); + if (!tool) throw new Error('Herramienta desconocida.'); + if (!scopes.includes('integra:read') || (!tool.readOnly && !scopes.includes('integra:write'))) + throw new Error('La conexión no tiene permiso para esta operación.'); + const args=tool.schema.parse(input); + validateBusiness(tool,args); + if (tool.owner) await own(tool.owner,args.id,user); + for (const [field,kind] of Object.entries(tool.refs)) { + for (const value of [args[field]].flat().filter(v=>v!==undefined&&v!==null)) await own(kind,value,user); + } + for (const value of args.portal_settings?.visible_guilds||[]) await own('guild',value,user); + if (name==='eliminar_usuario' && [user.id,user.accountId].includes(args.id)) throw new Error('No se puede eliminar al usuario conectado ni al propietario.'); + if (name==='cambiar_estado_usuario' && args.status!=='active' && [user.id,user.accountId].includes(args.id)) + throw new Error('No se puede bloquear al usuario conectado ni al propietario desde el complemento.'); + if (['actualizar_expediente','cambiar_cita_estado'].includes(name)) { + const q=await pool.query('SELECT assigned_to,raw_data FROM scraped_services WHERE id=$1 AND owner_id=$2',[args.id,user.accountId]); + const s=q.rows[0]; if (!s) throw new Error('Expediente no encontrado.'); + const raw=s.raw_data||{}, worker=args.assigned_to===undefined?s.assigned_to:args.assigned_to; + const day=args.scheduled_date||args.date||raw.scheduled_date; + const hour=args.scheduled_time||args.time||raw.scheduled_time; + if (worker&&day&&hour) { + if (!checkAvailability) throw new Error('Falta conectar comprobarDisponibilidad en el servidor.'); + const result=await checkAvailability(user.accountId,worker,day,hour,raw.duration_minutes||60,args.id); + if (result.choca) throw new Error('El horario coincide con otro servicio del técnico.'); + } + } + let route=tool.route; + const payload={...args}; + for (const match of tool.route.matchAll(/:([A-Za-z_]+)/g)) { + route=route.replace(`:${match[1]}`,encodeURIComponent(String(payload[match[1]]))); + delete payload[match[1]]; + } + const url=new URL(route,base); + if (tool.query) for (const [k,v] of Object.entries(payload)) if (v!==undefined) url.searchParams.set(k,String(v)); + const response=await fetchImpl(url,{ + method:tool.method,redirect:'error',signal:AbortSignal.timeout(45000), + headers:{'Content-Type':'application/json',Authorization:`Bearer ${signToken(user)}`}, + ...(!['GET','DELETE'].includes(tool.method)?{body:JSON.stringify(payload)}:{}) + }); + // Never propagate upstream error bodies: some supplied routes include stack traces. + if (!response.ok) throw new Error(`IntegraRepara devolvió HTTP ${response.status}; revisa el registro en la web antes de reintentar.`); + const raw=await response.text(); + if (raw.length>3000000) throw new Error('Respuesta demasiado grande. Usa buscar_expedientes con filtros.'); + let data;try { data=JSON.parse(raw); } catch { throw new Error('La API no ha devuelto JSON.'); } + if (data.ok===false) throw new Error('La API no confirmó la operación. Revisa su estado en la web.'); + data=redact(data); + // The API's unpaginated lists can exceed model context. Do not silently omit rows. + if (JSON.stringify(data).length>180000) throw new Error('Resultado demasiado amplio para el chat. Usa una búsqueda con texto o fechas en la web o en buscar_expedientes.'); + return data; + }; +} diff --git a/integra-mcp/mount.mjs b/integra-mcp/mount.mjs new file mode 100644 index 0000000..c81ed48 --- /dev/null +++ b/integra-mcp/mount.mjs @@ -0,0 +1,89 @@ +import express from 'express'; +import rateLimit from 'integra-mcp-rate-limit'; +import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { PgStore, hash } from './store.mjs'; +import { oauthRouter, accountAccess } from './oauth.mjs'; +import { normalizeOrigin } from './security.mjs'; +import { tools } from './tools.mjs'; +import { makeBridge } from './bridge.mjs'; + +export async function mountIntegraMcp({app,pool,signToken,checkAvailability,store:providedStore, + publicOrigin=process.env.INTEGRA_MCP_PUBLIC_ORIGIN, + redirectUris=String(process.env.INTEGRA_MCP_REDIRECT_URIS||'').split(',').map(s=>s.trim()).filter(Boolean), + backendUrl=`http://127.0.0.1:${process.env.PORT||3000}`, + access:providedAccess,bridge:providedBridge,audit:providedAudit +}) { + const origin=normalizeOrigin(publicOrigin),store=providedStore||new PgStore(pool); + await store.init(); + const access=providedAccess||accountAccess(pool); + const bridge=providedBridge||makeBridge({pool,signToken,backendUrl,checkAvailability}); + if (!providedAudit) await pool.query(`CREATE TABLE IF NOT EXISTS integra_mcp_audit ( + id BIGSERIAL PRIMARY KEY, user_id INT NOT NULL, owner_id INT NOT NULL, + tool TEXT NOT NULL, target_id INT, success BOOLEAN NOT NULL, created_at TIMESTAMPTZ DEFAULT now() + )`); + const audit=providedAudit||((user,name,args,success)=>pool.query( + 'INSERT INTO integra_mcp_audit(user_id,owner_id,tool,target_id,success) VALUES ($1,$2,$3,$4,$5)', + [user.id,user.accountId,name,Number.isInteger(args.id)?args.id:null,success])); + const router=express.Router(); + const allowedOrigins=new Set([origin,...String(process.env.INTEGRA_MCP_ALLOWED_ORIGINS||'').split(',').filter(Boolean)]); + router.use((req,res,next)=>{ + if (req.headers.origin&&!allowedOrigins.has(req.headers.origin)) return res.status(403).json({error:'origin_not_allowed'}); + next(); + }); + router.use(oauthRouter({store,origin,...access,redirectUris})); + router.get('/mcp-connect/status',(req,res)=>res.json({ + name:'IntegraRepara',version:'0.1.0',mcp:`${origin}/mcp`,authentication:'oauth', + oauthConfigured:redirectUris.length>0,toolCount:tools.length + })); + const mcpLimit=rateLimit({windowMs:60000,limit:120,standardHeaders:'draft-8',legacyHeaders:false}); + router.all('/mcp',mcpLimit,express.json({limit:'10mb'}),async(req,res,next)=>{ + try { + res.set('Cache-Control','no-store'); + const bearer=String(req.headers.authorization||'').match(/^Bearer ([A-Za-z0-9_-]{43})$/)?.[1]; + const auth=bearer?await store.get('access',hash(bearer)):null; + const user=auth?await access.currentUser(auth.userId):null; + if (!auth || auth.resource!==`${origin}/mcp` || !user || !await store.get('grant',auth.grantId)) { + res.set('WWW-Authenticate',`Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp", scope="integra:read"`); + return res.status(401).json({error:'unauthorized'}); + } + if (req.method!=='POST') return res.status(405).set('Allow','POST').json({error:'method_not_allowed'}); + const server=new McpServer({name:'integrarepara',version:'0.1.0'}); + for (const tool of tools) { + if (!tool.readOnly&&!auth.scopes.includes('integra:write')) continue; + server.registerTool(tool.name,{ + description:tool.description,inputSchema:tool.schema, + annotations:{readOnlyHint:tool.readOnly,destructiveHint:!tool.readOnly,idempotentHint:tool.readOnly,openWorldHint:!tool.readOnly} + },async(args)=>{ + let success=false; + try { + // Re-read account access per call, including long-running batches. + const fresh=await access.currentUser(user.id); + if (!fresh||fresh.accountId!==user.accountId||!await store.get('grant',auth.grantId)) throw new Error('La autorización ha caducado.'); + const data=await bridge(tool.name,args,fresh,auth.scopes);success=true; + return {content:[{type:'text',text:JSON.stringify(data)}]}; + } catch(err) { + const known=err.name==='ZodError'?'Parámetros inválidos.':err.name==='AbortError'||err.name==='TimeoutError'? + 'Tiempo agotado. La operación puede haberse realizado; comprueba el estado antes de reintentar.':err.message; + return {isError:true,content:[{type:'text',text:known}]}; + } finally { + try {await audit(user,tool.name,args,success);} catch { console.error('[Integra MCP] No se pudo registrar auditoría.'); } + } + }); + } + const transport=new StreamableHTTPServerTransport({sessionIdGenerator:undefined,enableJsonResponse:true}); + res.on('close',()=>{void transport.close();void server.close();}); + await server.connect(transport); + await transport.handleRequest(req,res,req.body); + } catch(err) {next(err);} + }); + router.use((err,req,res,next)=>{ + if (res.headersSent) return next(err); + console.error('[Integra MCP]',err.name); + res.status(500).json({error:'server_error'}); + }); + app.use(router); + const timer=setInterval(()=>{store.cleanup().catch(()=>console.error('[Integra MCP] Falló limpieza OAuth.'));},3600000); + timer.unref(); + return {stopCleanup:()=>clearInterval(timer),toolCount:tools.length}; +} diff --git a/integra-mcp/oauth.mjs b/integra-mcp/oauth.mjs new file mode 100644 index 0000000..28de4a4 --- /dev/null +++ b/integra-mcp/oauth.mjs @@ -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(`Conectar IntegraRepara + +

Conectar IntegraRepara

Vas a autorizar a ${esc(client.client_name)}.

+

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':''}.

+ Aplicación de destino: ${esc(new URL(p.redirect_uri).origin)} +
+ + +

Usa una cuenta administradora de IntegraRepara. La contraseña se comprueba aquí y no se entrega al complemento.

+

Para cancelar, cierra esta ventana.

`); + })); + 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; + }}; +} diff --git a/integra-mcp/security.mjs b/integra-mcp/security.mjs new file mode 100644 index 0000000..82254a8 --- /dev/null +++ b/integra-mcp/security.mjs @@ -0,0 +1,27 @@ +export function publicBillingSettings(value = {}) { + // Safe for the PUBLIC customer portal. Never return stripe_sk or other keys. + return Object.fromEntries(['iban', 'bank_name', 'account_holder', 'observations', 'stripe_enabled'] + .filter(k => Object.hasOwn(value, k)).map(k => [k, value[k]])); +} + +const secretKey = /password|secret|token|api[_-]?key|stripe[_-]?[sp]k|signature|pdf_base64|contract_pdf_url|pdf_raw_data/i; +export function redact(value) { + if (Array.isArray(value)) return value.map(redact); + if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value) + .filter(([key]) => !secretKey.test(key)).map(([key, val]) => [key, redact(val)])); + return value; +} + +export function normalizeOrigin(value) { + const url = new URL(value); + if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) + throw new Error('INTEGRA_MCP_PUBLIC_ORIGIN debe ser un origen HTTPS sin ruta, por ejemplo https://tu-backend.es'); + return url.origin; +} + +export function safeRedirect(value) { + try { + const u = new URL(value); + return !u.username && !u.password && !u.hash && u.protocol === 'https:'; + } catch { return false; } +} diff --git a/integra-mcp/store.mjs b/integra-mcp/store.mjs new file mode 100644 index 0000000..9f53575 --- /dev/null +++ b/integra-mcp/store.mjs @@ -0,0 +1,34 @@ +import { createHash } from 'node:crypto'; + +export const hash = value => createHash('sha256').update(value).digest('hex'); + +// Shared by all Coolify replicas. Only digests of bearer tokens, codes and browser +// transaction secrets are stored. No user passwords or IntegraRepara JWTs. +export class PgStore { + constructor(pool) { this.pool = pool; } + async init() { + await this.pool.query(`CREATE TABLE IF NOT EXISTS integra_mcp_oauth ( + kind TEXT NOT NULL, key TEXT NOT NULL, data JSONB NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (kind, key) + )`); + await this.pool.query('CREATE INDEX IF NOT EXISTS integra_mcp_oauth_expiry ON integra_mcp_oauth(expires_at)'); + } + async set(kind, key, data, seconds) { + await this.pool.query(`INSERT INTO integra_mcp_oauth(kind,key,data,expires_at) + VALUES ($1,$2,$3,now()+$4*interval '1 second') + ON CONFLICT(kind,key) DO UPDATE SET data=EXCLUDED.data,expires_at=EXCLUDED.expires_at`, + [kind, key, JSON.stringify(data), seconds]); + } + async get(kind, key) { + const q = await this.pool.query('SELECT data FROM integra_mcp_oauth WHERE kind=$1 AND key=$2 AND expires_at>now()', [kind,key]); + return q.rows[0]?.data; + } + async take(kind, key) { + const q = await this.pool.query('DELETE FROM integra_mcp_oauth WHERE kind=$1 AND key=$2 AND expires_at>now() RETURNING data', [kind,key]); + return q.rows[0]?.data; + } + async delete(kind, key) { + await this.pool.query('DELETE FROM integra_mcp_oauth WHERE kind=$1 AND key=$2', [kind,key]); + } + async cleanup() { await this.pool.query('DELETE FROM integra_mcp_oauth WHERE expires_at<=now()'); } +}