orquestra-mcp 1.80.0 → 1.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/package.json +1 -1
- package/src/api.mjs +4 -1
- package/src/configFile.mjs +25 -3
- package/src/http.mjs +11 -2
- package/src/security.mjs +50 -0
- package/src/server.mjs +4 -0
- package/src/setup.mjs +107 -50
package/README.md
CHANGED
|
@@ -64,6 +64,12 @@ Variable opcional `ORQUESTRA_WEB_URL` para apuntar el login a otro lugar
|
|
|
64
64
|
(ej. `http://localhost:5173` mientras desarrollas `orquestra-web` local en
|
|
65
65
|
vez de contra producción).
|
|
66
66
|
|
|
67
|
+
Seguridad del login: el callback local solo escucha en `127.0.0.1` y acepta únicamente
|
|
68
|
+
el origen de la web de Orquestra. `ORQUESTRA_API_BASE`, `ORQUESTRA_WEB_URL` y el `apiBase`
|
|
69
|
+
del archivo deben ser `https://` (se permite `http://` solo en `localhost`/`127.0.0.1`/`[::1]`)
|
|
70
|
+
y sin `usuario:clave@`. Para usar a propósito un `http://` remoto: `ORQUESTRA_ALLOW_INSECURE_API=1`
|
|
71
|
+
(el token viaja sin cifrar; se avisa por stderr).
|
|
72
|
+
|
|
67
73
|
## Setup manual (alternativa, sin el flujo de navegador)
|
|
68
74
|
|
|
69
75
|
Si prefieres generar el token tú mismo en vez de usar `setup`:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "orquestra-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.82.0",
|
|
4
4
|
"description": "Servidor MCP de Orquestra -- 161 tools para leer y escribir tareas, ideas, changelog, infraestructura, contenido, QA y más desde un agente de IA",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/api.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { readConfigFile, resolveProjectForCwd, entryForAgent, agentKey, CONFIG_PATH } from './configFile.mjs'
|
|
2
2
|
import { request } from './http.mjs'
|
|
3
|
+
import { validateBaseUrl } from './security.mjs'
|
|
3
4
|
|
|
4
5
|
const DEFAULT_API_BASE = 'https://api.orquestra.me'
|
|
5
6
|
|
|
@@ -22,7 +23,9 @@ export function loadConfig() {
|
|
|
22
23
|
)
|
|
23
24
|
}
|
|
24
25
|
|
|
25
|
-
|
|
26
|
+
// https obligatorio (salvo localhost) y sin user:pass@ -- el token viaja a esta URL en cada llamada.
|
|
27
|
+
const apiBaseSource = process.env.ORQUESTRA_API_BASE ? 'ORQUESTRA_API_BASE' : `apiBase de ${CONFIG_PATH}`
|
|
28
|
+
const apiBase = validateBaseUrl(process.env.ORQUESTRA_API_BASE || folderConfig?.apiBase || DEFAULT_API_BASE, apiBaseSource)
|
|
26
29
|
const apiToken = process.env.ORQUESTRA_API_TOKEN || folderConfig?.apiToken
|
|
27
30
|
const workspaceId = process.env.ORQUESTRA_WORKSPACE_ID || folderConfig?.workspaceId
|
|
28
31
|
|
package/src/configFile.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync, chmodSync } from 'fs'
|
|
2
2
|
import { homedir, hostname } from 'os'
|
|
3
3
|
import { randomBytes } from 'crypto'
|
|
4
4
|
import { join, dirname, win32, posix } from 'path'
|
|
5
|
+
import { warnOnce } from './security.mjs'
|
|
5
6
|
|
|
6
7
|
export const CONFIG_PATH = join(homedir(), '.orquestra', 'mcp-config.json')
|
|
7
8
|
|
|
@@ -28,8 +29,27 @@ function migrateLegacyConfig(raw) {
|
|
|
28
29
|
return { projects }
|
|
29
30
|
}
|
|
30
31
|
|
|
32
|
+
// Permisos (tokens en claro en disco): carpeta 0700 y archivos 0600. Si ya existen más abiertos
|
|
33
|
+
// (p. ej. 0644) se corrigen y se avisa por stderr UNA vez. No aplica en Windows (sin modos POSIX).
|
|
34
|
+
function tightenMode(path, mode) {
|
|
35
|
+
if (process.platform === 'win32') return
|
|
36
|
+
try {
|
|
37
|
+
const current = statSync(path).mode & 0o777
|
|
38
|
+
if ((current & ~mode) === 0) return
|
|
39
|
+
chmodSync(path, mode)
|
|
40
|
+
warnOnce(`perm:${path}`, `${path} tenía permisos ${current.toString(8)} (otros usuarios podían leerlo); los corregí a ${mode.toString(8)}.`)
|
|
41
|
+
} catch {}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function ensureConfigDir() {
|
|
45
|
+
const dir = dirname(CONFIG_PATH)
|
|
46
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
47
|
+
tightenMode(dir, 0o700)
|
|
48
|
+
}
|
|
49
|
+
|
|
31
50
|
export function readConfigFile() {
|
|
32
51
|
if (!existsSync(CONFIG_PATH)) return null
|
|
52
|
+
tightenMode(CONFIG_PATH, 0o600)
|
|
33
53
|
let raw
|
|
34
54
|
try {
|
|
35
55
|
raw = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'))
|
|
@@ -42,7 +62,8 @@ export function readConfigFile() {
|
|
|
42
62
|
}
|
|
43
63
|
|
|
44
64
|
export function writeConfigFile(data) {
|
|
45
|
-
|
|
65
|
+
ensureConfigDir()
|
|
66
|
+
if (existsSync(CONFIG_PATH)) tightenMode(CONFIG_PATH, 0o600) // writeFileSync solo aplica `mode` al crear
|
|
46
67
|
writeFileSync(CONFIG_PATH, JSON.stringify(data, null, 2), { mode: 0o600 })
|
|
47
68
|
}
|
|
48
69
|
|
|
@@ -135,11 +156,12 @@ export const MACHINE_PATH = join(homedir(), '.orquestra', 'machine.json')
|
|
|
135
156
|
|
|
136
157
|
export function readOrCreateMachine() {
|
|
137
158
|
try {
|
|
159
|
+
tightenMode(MACHINE_PATH, 0o600)
|
|
138
160
|
const saved = JSON.parse(readFileSync(MACHINE_PATH, 'utf8'))
|
|
139
161
|
if (/^[a-f0-9]{16,64}$/.test(saved.id)) return { id: saved.id, name: saved.name || hostname().replace(/\.local$/, '') }
|
|
140
162
|
} catch {}
|
|
141
163
|
const machine = { id: randomBytes(8).toString('hex'), name: hostname().replace(/\.local$/, '') }
|
|
142
|
-
|
|
164
|
+
ensureConfigDir()
|
|
143
165
|
writeFileSync(MACHINE_PATH, JSON.stringify(machine, null, 2), { mode: 0o600 })
|
|
144
166
|
return machine
|
|
145
167
|
}
|
package/src/http.mjs
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// - El 429 de la propia API (créditos agotados, tope de regeneraciones...) trae `error` en el
|
|
11
11
|
// body y es definitivo: no se reintenta.
|
|
12
12
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
13
|
+
import { maskTokens } from './security.mjs'
|
|
13
14
|
|
|
14
15
|
export const TIMEOUT_MS = 30_000
|
|
15
16
|
export const RETRIES = 2
|
|
@@ -23,7 +24,7 @@ export const cancelContext = new AsyncLocalStorage()
|
|
|
23
24
|
|
|
24
25
|
export class ApiError extends Error {
|
|
25
26
|
constructor(status, message, { code, details } = {}) {
|
|
26
|
-
super(message)
|
|
27
|
+
super(maskTokens(message)) // nunca un orq_… en un mensaje de error
|
|
27
28
|
this.status = status
|
|
28
29
|
if (code) this.code = code
|
|
29
30
|
if (details !== undefined) this.details = details
|
|
@@ -57,6 +58,9 @@ async function readBody(res) {
|
|
|
57
58
|
try { return text ? JSON.parse(text) : null } catch { return text }
|
|
58
59
|
}
|
|
59
60
|
|
|
61
|
+
const hasAuthorization = headers => Object.keys(headers || {}).some(k => k.toLowerCase() === 'authorization')
|
|
62
|
+
export const isRedirectError = err => /redirect/i.test(`${err?.message} ${err?.cause?.message}`)
|
|
63
|
+
|
|
60
64
|
const isGatewayThrottle = (status, body) => status === 429 && !(body && typeof body === 'object' && body.error)
|
|
61
65
|
|
|
62
66
|
/**
|
|
@@ -72,9 +76,14 @@ export async function request(url, init = {}, { timeoutMs = TIMEOUT_MS, retries
|
|
|
72
76
|
const last = attempt >= retries
|
|
73
77
|
let res
|
|
74
78
|
try {
|
|
75
|
-
|
|
79
|
+
// Con Authorization puesto NO se siguen redirecciones: un 3xx a otro host se llevaría el Bearer.
|
|
80
|
+
const redirect = hasAuthorization(init.headers) ? 'error' : init.redirect
|
|
81
|
+
res = await fetch(url, { ...init, ...(redirect ? { redirect } : {}), signal: anySignal([cancel, AbortSignal.timeout(timeoutMs)]) })
|
|
76
82
|
} catch (err) {
|
|
77
83
|
if (cancel.aborted) throw new ApiError(0, 'Cancelado', { code: 'cancelled' })
|
|
84
|
+
if (isRedirectError(err)) {
|
|
85
|
+
throw new ApiError(0, 'La API respondió con una redirección y no se sigue (el token no se reenvía a otro destino). Revisa ORQUESTRA_API_BASE.', { code: 'redirect_blocked' })
|
|
86
|
+
}
|
|
78
87
|
const timedOut = err?.name === 'TimeoutError' || err?.name === 'AbortError'
|
|
79
88
|
if (isRead && !last) { await sleep(backoff(attempt), cancel); continue }
|
|
80
89
|
if (timedOut) {
|
package/src/security.mjs
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Defensas del cliente (endurecimiento de auth): validación de URLs a las que viaja el token,
|
|
2
|
+
// enmascarado de tokens en mensajes y avisos por stderr. TODO aviso va a stderr: stdout es del
|
|
3
|
+
// protocolo MCP y cualquier línea extra lo rompe.
|
|
4
|
+
|
|
5
|
+
const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
6
|
+
const warned = new Set()
|
|
7
|
+
|
|
8
|
+
// Avisa una sola vez por clave (por proceso), siempre por stderr.
|
|
9
|
+
export function warnOnce(key, message) {
|
|
10
|
+
if (warned.has(key)) return
|
|
11
|
+
warned.add(key)
|
|
12
|
+
console.error(`[orquestra-mcp] ${message}`)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Solo para tests: permite volver a ver los avisos.
|
|
16
|
+
export function resetWarnings() { warned.clear() }
|
|
17
|
+
|
|
18
|
+
// Valida una URL base a la que se va a mandar el token (apiBase) o que se abre en el navegador
|
|
19
|
+
// (webUrl). Devuelve la URL sin barras finales. `label` es el nombre de la variable para el mensaje.
|
|
20
|
+
// - solo http(s), sin credenciales embebidas (user:pass@)
|
|
21
|
+
// - https obligatorio salvo localhost/127.0.0.1/[::1] (desarrollo)
|
|
22
|
+
// - http remoto solo con ORQUESTRA_ALLOW_INSECURE_API=1 (anulación explícita, con aviso por stderr)
|
|
23
|
+
export function validateBaseUrl(raw, label = 'ORQUESTRA_API_BASE') {
|
|
24
|
+
let url
|
|
25
|
+
try { url = new URL(String(raw)) } catch { throw new Error(`${label} no es una URL válida.`) }
|
|
26
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
|
27
|
+
throw new Error(`${label} debe ser http(s); recibí "${url.protocol}".`)
|
|
28
|
+
}
|
|
29
|
+
if (url.username || url.password) {
|
|
30
|
+
throw new Error(`${label} no puede llevar usuario/contraseña embebidos (user:pass@host): se filtrarían en logs y errores.`)
|
|
31
|
+
}
|
|
32
|
+
if (url.protocol === 'http:' && !LOCAL_HOSTS.has(url.hostname)) {
|
|
33
|
+
if (process.env.ORQUESTRA_ALLOW_INSECURE_API !== '1') {
|
|
34
|
+
throw new Error(
|
|
35
|
+
`${label} usa http:// hacia ${url.host}: el token viajaría en texto plano. Usa https://. ` +
|
|
36
|
+
`Si de verdad necesitas http en un host no local (red de confianza, pruebas), anúlalo de forma explícita con ` +
|
|
37
|
+
`ORQUESTRA_ALLOW_INSECURE_API=1 (no se recomienda).`
|
|
38
|
+
)
|
|
39
|
+
}
|
|
40
|
+
warnOnce(`insecure:${url.host}`, `ADVERTENCIA: ${label} usa http:// hacia ${url.host} y ORQUESTRA_ALLOW_INSECURE_API=1 está activo; el token viaja SIN cifrar.`)
|
|
41
|
+
}
|
|
42
|
+
return url.href.replace(/\/+$/, '')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Enmascara tokens de Orquestra (orq_…) y cabeceras Bearer en cualquier texto antes de mostrarlo.
|
|
46
|
+
export function maskTokens(text) {
|
|
47
|
+
return String(text ?? '')
|
|
48
|
+
.replace(/orq_[A-Za-z0-9_\-]+/g, 'orq_***')
|
|
49
|
+
.replace(/(Bearer\s+)[A-Za-z0-9._~+\/=\-]+/gi, '$1***')
|
|
50
|
+
}
|
package/src/server.mjs
CHANGED
|
@@ -421,6 +421,7 @@ export function createServer() {
|
|
|
421
421
|
assignedTo: z.string().optional().describe('uid del responsable para filtrar (opcional)'),
|
|
422
422
|
tag: z.string().optional().describe('Un tag exacto para filtrar -- solo uno, no una lista (opcional)'),
|
|
423
423
|
workCategory: z.enum(WORK_CATEGORIES).optional().describe('Categoría de trabajo para filtrar (opcional): plan | build | delivery | review'),
|
|
424
|
+
hasSpec: z.boolean().optional().describe('true = solo tareas con spec enlazada (specDocId); false = solo las que no tienen (ORQ-633). Mide que el campo exista, no que el doc siga existiendo. Se combina con los demás filtros.'),
|
|
424
425
|
code: z.string().optional().describe('Folio exacto (ej. "ORQ-209") o código de módulo/grupo (ej. "AUTH-3", "V2-3"): devuelve { tasks: [esa tarea completa con checklist y verificaciones] } (o [] si no existe). No se combina con otros filtros ni con paginación; para una sola tarea get_task es equivalente.'),
|
|
425
426
|
q: z.string().optional().describe('Texto a buscar en título y descripción (insensible a mayúsculas); el servidor filtra ANTES de paginar. Se combina con los demás filtros.'),
|
|
426
427
|
groupKey: z.string().max(10).optional().describe('Clave de agrupación exacta (ej. "V2") para traer solo las tareas de ese grupo (groupCode V2-1, V2-2...) -- úsalo antes de crear una tarea nueva de una iniciativa para reutilizar la clave y ver cuáles existen (opcional)'),
|
|
@@ -442,6 +443,7 @@ export function createServer() {
|
|
|
442
443
|
assignedTo: args.assignedTo,
|
|
443
444
|
tag: args.tag,
|
|
444
445
|
workCategory: args.workCategory,
|
|
446
|
+
hasSpec: args.hasSpec,
|
|
445
447
|
groupKey: args.groupKey,
|
|
446
448
|
q: args.q,
|
|
447
449
|
includeClosed: args.includeClosed,
|
|
@@ -961,6 +963,7 @@ export function createServer() {
|
|
|
961
963
|
blockedByIds: z.array(z.string()).optional().describe('"Bloqueada por" -- ids de otras tareas'),
|
|
962
964
|
location: z.string().optional().describe('Solo meeting/call/followup/business'),
|
|
963
965
|
estimatedDays: z.number().optional().describe('Estimación en días'),
|
|
966
|
+
specDocId: z.string().optional().describe('ORQ-633: id del doc que es la spec de esta tarea (flujo /orquestra-spec). Debe existir en este proyecto; también vincula tarea y doc en "Relacionado"'),
|
|
964
967
|
stack: z.array(z.string()).optional().describe('Tecnologías (ej. "node", "react")'),
|
|
965
968
|
branch: z.string().optional().describe('Branch asociado'),
|
|
966
969
|
prNumber: z.string().optional().describe('Número del PR (sin "#")'),
|
|
@@ -1022,6 +1025,7 @@ export function createServer() {
|
|
|
1022
1025
|
location: z.string().optional(),
|
|
1023
1026
|
comment: D(z.string().optional(), 'Qué hiciste o por qué; obligatorio en la práctica con statusId'),
|
|
1024
1027
|
estimatedDays: z.number().optional(),
|
|
1028
|
+
specDocId: D(z.string().optional(), 'Id del doc spec de la tarea (debe existir en el proyecto); "" lo quita'),
|
|
1025
1029
|
stack: z.array(z.string()).optional(),
|
|
1026
1030
|
branch: D(z.string().optional(), 'Branch asociado; setéalo al empezar a trabajar'),
|
|
1027
1031
|
prNumber: D(z.string().optional(), 'Número del PR (sin "#")'),
|
package/src/setup.mjs
CHANGED
|
@@ -1,20 +1,113 @@
|
|
|
1
1
|
import { createServer } from 'http'
|
|
2
|
-
import { randomBytes } from 'crypto'
|
|
3
|
-
import {
|
|
2
|
+
import { randomBytes, timingSafeEqual } from 'crypto'
|
|
3
|
+
import { execFile } from 'child_process'
|
|
4
4
|
import { createInterface } from 'readline'
|
|
5
5
|
import { homedir } from 'os'
|
|
6
6
|
import { resolve } from 'path'
|
|
7
7
|
import { findLegacyNpxConfigs, MIGRATE_COMMAND } from './updateCheck.mjs'
|
|
8
8
|
import { migrateClientConfigs } from './clientConfig.mjs'
|
|
9
|
+
import { validateBaseUrl, maskTokens } from './security.mjs'
|
|
9
10
|
import { upsertProjectMapping, replaceAgentToken, connectedAgents, readOrCreateMachine, agentKey, CONFIG_PATH } from './configFile.mjs'
|
|
10
11
|
|
|
11
12
|
const DEFAULT_API_BASE = 'https://api.orquestra.me'
|
|
12
13
|
const DEFAULT_WEB_URL = 'https://app.orquestra.me'
|
|
13
14
|
const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000
|
|
14
15
|
|
|
16
|
+
// Comando para abrir la URL SIN shell (argumentos separados: nada se interpreta). Solo http(s).
|
|
17
|
+
export function browserCommand(url, platform = process.platform) {
|
|
18
|
+
const parsed = new URL(url)
|
|
19
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') throw new Error('Solo se abren URLs http(s).')
|
|
20
|
+
const href = parsed.href
|
|
21
|
+
if (platform === 'darwin') return { cmd: 'open', args: [href] }
|
|
22
|
+
if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler', href] }
|
|
23
|
+
return { cmd: 'xdg-open', args: [href] }
|
|
24
|
+
}
|
|
25
|
+
|
|
15
26
|
function openBrowser(url) {
|
|
16
|
-
|
|
17
|
-
|
|
27
|
+
try {
|
|
28
|
+
const { cmd, args } = browserCommand(url)
|
|
29
|
+
execFile(cmd, args, () => {}).on('error', () => {})
|
|
30
|
+
} catch {} // la URL ya se imprimió: el usuario puede abrirla a mano
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const MAX_BODY_BYTES = 16 * 1024
|
|
34
|
+
|
|
35
|
+
const sameSecret = (a, b) => {
|
|
36
|
+
const x = Buffer.from(String(a ?? '')), y = Buffer.from(String(b ?? ''))
|
|
37
|
+
return x.length === y.length && timingSafeEqual(x, y)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Callback local del login: UN solo servidor en 127.0.0.1 (puerto 0; el puerto sale de ESE servidor,
|
|
41
|
+
// sin reservar-cerrar-reabrir). Solo acepta el origen de la web de Orquestra, valida `state` en
|
|
42
|
+
// tiempo constante, limita el cuerpo y cierra tras el primer intento válido.
|
|
43
|
+
export async function startCallbackServer({ state, webUrl, timeoutMs = CALLBACK_TIMEOUT_MS }) {
|
|
44
|
+
const allowedOrigin = new URL(webUrl).origin
|
|
45
|
+
let done = false
|
|
46
|
+
let settle
|
|
47
|
+
const result = new Promise((resolve, reject) => { settle = { resolve, reject } })
|
|
48
|
+
result.catch(() => {}) // evita "unhandled" si nadie espera todavía
|
|
49
|
+
|
|
50
|
+
const json = (res, status, obj) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)) }
|
|
51
|
+
|
|
52
|
+
const httpServer = createServer((req, res) => {
|
|
53
|
+
const origin = req.headers.origin
|
|
54
|
+
// Anti DNS-rebinding: solo Host de loopback con nuestro puerto.
|
|
55
|
+
const port = httpServer.address().port
|
|
56
|
+
if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(req.headers.host)) return json(res, 403, { ok: false, error: 'host no permitido' })
|
|
57
|
+
if (origin && origin !== allowedOrigin) return json(res, 403, { ok: false, error: 'origen no permitido' })
|
|
58
|
+
if (origin) {
|
|
59
|
+
res.setHeader('Access-Control-Allow-Origin', allowedOrigin)
|
|
60
|
+
res.setHeader('Vary', 'Origin')
|
|
61
|
+
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS')
|
|
62
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
|
|
63
|
+
if (req.headers['access-control-request-private-network']) res.setHeader('Access-Control-Allow-Private-Network', 'true')
|
|
64
|
+
}
|
|
65
|
+
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
66
|
+
if (req.method !== 'POST' || req.url !== '/callback') return json(res, 404, { ok: false })
|
|
67
|
+
if (done) return json(res, 410, { ok: false, error: 'el login ya se completó' })
|
|
68
|
+
if (Number(req.headers['content-length']) > MAX_BODY_BYTES) { res.setHeader('Connection', 'close'); return json(res, 413, { ok: false, error: 'cuerpo demasiado grande' }) }
|
|
69
|
+
|
|
70
|
+
const chunks = []
|
|
71
|
+
let size = 0
|
|
72
|
+
let tooBig = false
|
|
73
|
+
req.on('data', chunk => {
|
|
74
|
+
if (tooBig) return
|
|
75
|
+
size += chunk.length
|
|
76
|
+
if (size > MAX_BODY_BYTES) { tooBig = true; res.setHeader('Connection', 'close'); json(res, 413, { ok: false, error: 'cuerpo demasiado grande' }); return }
|
|
77
|
+
chunks.push(chunk)
|
|
78
|
+
})
|
|
79
|
+
req.on('end', () => {
|
|
80
|
+
if (tooBig || res.writableEnded) return
|
|
81
|
+
let parsed
|
|
82
|
+
try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { return json(res, 400, { ok: false, error: 'JSON inválido' }) }
|
|
83
|
+
const { state: gotState, idToken } = parsed || {}
|
|
84
|
+
if (!sameSecret(gotState, state) || typeof idToken !== 'string' || !idToken) return json(res, 400, { ok: false, error: 'state/idToken inválido' })
|
|
85
|
+
if (done) return json(res, 410, { ok: false, error: 'el login ya se completó' })
|
|
86
|
+
done = true // un solo intento válido
|
|
87
|
+
json(res, 200, { ok: true })
|
|
88
|
+
res.on('finish', () => { httpServer.close(); httpServer.closeAllConnections?.() })
|
|
89
|
+
clearTimeout(timer)
|
|
90
|
+
settle.resolve(idToken)
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
const timer = setTimeout(() => {
|
|
95
|
+
done = true
|
|
96
|
+
httpServer.close(); httpServer.closeAllConnections?.()
|
|
97
|
+
settle.reject(new Error('Se agotó el tiempo esperando el login (5 min). Corre "npx orquestra-mcp setup" de nuevo.'))
|
|
98
|
+
}, timeoutMs)
|
|
99
|
+
|
|
100
|
+
await new Promise((resolve, reject) => {
|
|
101
|
+
httpServer.once('error', reject)
|
|
102
|
+
httpServer.listen(0, '127.0.0.1', resolve)
|
|
103
|
+
}).catch(err => { clearTimeout(timer); throw err })
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
server: httpServer,
|
|
107
|
+
port: httpServer.address().port,
|
|
108
|
+
idToken: result,
|
|
109
|
+
close() { done = true; clearTimeout(timer); httpServer.close(); httpServer.closeAllConnections?.() },
|
|
110
|
+
}
|
|
18
111
|
}
|
|
19
112
|
|
|
20
113
|
// Herramientas conocidas (ORQ-415): cada una queda como su propio agente en
|
|
@@ -27,58 +120,20 @@ function prompt(question) {
|
|
|
27
120
|
}
|
|
28
121
|
|
|
29
122
|
export async function runSetup({ agent: presetAgent } = {}) {
|
|
30
|
-
|
|
31
|
-
const
|
|
123
|
+
// https obligatorio (salvo localhost) y sin user:pass@, igual que loadConfig().
|
|
124
|
+
const apiBase = validateBaseUrl(process.env.ORQUESTRA_API_BASE || DEFAULT_API_BASE, 'ORQUESTRA_API_BASE')
|
|
125
|
+
const webUrl = validateBaseUrl(process.env.ORQUESTRA_WEB_URL || DEFAULT_WEB_URL, 'ORQUESTRA_WEB_URL')
|
|
32
126
|
const state = randomBytes(16).toString('hex')
|
|
33
127
|
|
|
34
|
-
|
|
35
|
-
const
|
|
36
|
-
await new Promise(resolve => server.listen(0, resolve))
|
|
37
|
-
const port = server.address().port
|
|
38
|
-
server.close()
|
|
39
|
-
|
|
40
|
-
const idTokenPromise = new Promise((resolve, reject) => {
|
|
41
|
-
const httpServer = createServer((req, res) => {
|
|
42
|
-
res.setHeader('Access-Control-Allow-Origin', '*')
|
|
43
|
-
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS')
|
|
44
|
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
|
|
45
|
-
|
|
46
|
-
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
47
|
-
if (req.method !== 'POST' || req.url !== '/callback') { res.writeHead(404); res.end(); return }
|
|
48
|
-
|
|
49
|
-
let body = ''
|
|
50
|
-
req.on('data', chunk => { body += chunk })
|
|
51
|
-
req.on('end', () => {
|
|
52
|
-
try {
|
|
53
|
-
const { state: gotState, idToken } = JSON.parse(body)
|
|
54
|
-
if (gotState !== state || !idToken) throw new Error('state/idToken inválido')
|
|
55
|
-
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
56
|
-
res.end(JSON.stringify({ ok: true }))
|
|
57
|
-
clearTimeout(timeout)
|
|
58
|
-
httpServer.close()
|
|
59
|
-
resolve(idToken)
|
|
60
|
-
} catch (e) {
|
|
61
|
-
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
62
|
-
res.end(JSON.stringify({ ok: false, error: e.message }))
|
|
63
|
-
}
|
|
64
|
-
})
|
|
65
|
-
})
|
|
66
|
-
|
|
67
|
-
const timeout = setTimeout(() => {
|
|
68
|
-
httpServer.close()
|
|
69
|
-
reject(new Error('Se agotó el tiempo esperando el login (5 min). Corre "npx orquestra-mcp setup" de nuevo.'))
|
|
70
|
-
}, CALLBACK_TIMEOUT_MS)
|
|
71
|
-
|
|
72
|
-
httpServer.listen(port)
|
|
73
|
-
httpServer.on('error', reject)
|
|
74
|
-
})
|
|
128
|
+
const callback = await startCallbackServer({ state, webUrl })
|
|
129
|
+
const { port } = callback
|
|
75
130
|
|
|
76
131
|
const authUrl = `${webUrl}/cli-auth?state=${state}&port=${port}`
|
|
77
132
|
console.log('Abriendo el navegador para conectar tu cuenta de Orquestra...')
|
|
78
133
|
console.log(`Si no se abre solo, entra a: ${authUrl}`)
|
|
79
134
|
openBrowser(authUrl)
|
|
80
135
|
|
|
81
|
-
const idToken = await
|
|
136
|
+
const idToken = await callback.idToken
|
|
82
137
|
console.log('Login recibido, configurando...')
|
|
83
138
|
|
|
84
139
|
const machine = readOrCreateMachine()
|
|
@@ -90,11 +145,12 @@ export async function runSetup({ agent: presetAgent } = {}) {
|
|
|
90
145
|
const callBootstrap = async (extra = {}) => {
|
|
91
146
|
const res = await fetch(`${apiBase}/v1/bootstrap`, {
|
|
92
147
|
method: 'POST',
|
|
148
|
+
redirect: 'error', // con el Bearer puesto no se sigue ninguna redirección
|
|
93
149
|
headers: { Authorization: `Bearer ${idToken}`, 'Content-Type': 'application/json' },
|
|
94
150
|
body: JSON.stringify({ agentLabel, machineId: machine.id, machineName: machine.name, askIfMissing: true, ...extra }),
|
|
95
151
|
})
|
|
96
152
|
const body = await res.json()
|
|
97
|
-
if (!res.ok) throw new Error(body?.error || `HTTP ${res.status}`)
|
|
153
|
+
if (!res.ok) throw new Error(maskTokens(body?.error) || `HTTP ${res.status}`)
|
|
98
154
|
return body
|
|
99
155
|
}
|
|
100
156
|
const askName = async (question) => {
|
|
@@ -145,11 +201,12 @@ export async function runSetup({ agent: presetAgent } = {}) {
|
|
|
145
201
|
const createProject = async (name) => {
|
|
146
202
|
const res2 = await fetch(`${apiBase}/v1/projects?workspaceId=${workspaceId}`, {
|
|
147
203
|
method: 'POST',
|
|
204
|
+
redirect: 'error',
|
|
148
205
|
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
149
206
|
body: JSON.stringify({ name }),
|
|
150
207
|
})
|
|
151
208
|
const newProject = await res2.json()
|
|
152
|
-
if (!res2.ok) throw new Error(newProject?.error || `HTTP ${res2.status}`)
|
|
209
|
+
if (!res2.ok) throw new Error(maskTokens(newProject?.error) || `HTTP ${res2.status}`)
|
|
153
210
|
console.log(`Proyecto "${newProject.name}"${wsLabel} creado y configurado como default.`)
|
|
154
211
|
return newProject.id
|
|
155
212
|
}
|