opencode-apex 0.1.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/core/crypto.ts ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Apex Redact — criptografía del marcador de secretos.
3
+ *
4
+ * Cada secreto se cifra con AES-256-GCM y se sustituye por:
5
+ * `${prefix}${base64url(iv || tag || ciphertext)}${suffix}`
6
+ *
7
+ * No hay mapping interno: la restauración descifra el propio marcador.
8
+ * La clave se resuelve desde la configuración del plugin (material directo,
9
+ * `env:VAR`, `file:/ruta`, `hex:...` o `base64:...`).
10
+ */
11
+
12
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto"
13
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
14
+ import { homedir } from "node:os"
15
+ import { dirname, join } from "node:path"
16
+
17
+ const ALGORITHM = "aes-256-gcm"
18
+ const IV_LENGTH = 12
19
+ const TAG_LENGTH = 16
20
+
21
+ /** Fuente de la que se obtuvo el material de clave. */
22
+ export type KeySource = "config" | "env" | "file" | "generated"
23
+
24
+ export interface ResolvedKey {
25
+ readonly key: Buffer
26
+ readonly source: KeySource
27
+ readonly fingerprint: string
28
+ }
29
+
30
+ /**
31
+ * Deriva 32 bytes de clave a partir del material (determinista).
32
+ * El mismo material produce siempre la misma clave → descifrable entre sesiones.
33
+ */
34
+ export function deriveKey(material: string): Buffer {
35
+ return createHash("sha256").update(material, "utf8").digest()
36
+ }
37
+
38
+ /** Fingerprint corto (no reversible) para logs y diagnóstico. */
39
+ export function keyFingerprint(key: Buffer): string {
40
+ return createHash("sha256").update(key).digest("hex").slice(0, 8)
41
+ }
42
+
43
+ const DEFAULT_KEY_FILE = join(homedir(), ".config", "opencode", "apex.key")
44
+
45
+ /**
46
+ * Resuelve el material de clave desde la especificación de configuración.
47
+ *
48
+ * Formatos aceptados:
49
+ * - `env:NOMBRE` → variable de entorno
50
+ * - `file:/ruta` → contenido del fichero (trim)
51
+ * - `hex:0102...` → bytes hexadecimales (usados como material)
52
+ * - `base64:...` → bytes base64 (usados como material)
53
+ * - cualquier otro → el propio literal como material
54
+ *
55
+ * Si no hay material disponible se genera una clave aleatoria y se persiste
56
+ * en `~/.config/opencode/apex.key` (0600), avisando por consola: la clave debe
57
+ * fijarse en la configuración para que sea estable entre equipos/sesiones.
58
+ */
59
+ export function resolveKey(spec: string | undefined): ResolvedKey {
60
+ const material = resolveKeyMaterial(spec)
61
+ if (material) {
62
+ const key = deriveKey(material.value)
63
+ return { key, source: material.source, fingerprint: keyFingerprint(key) }
64
+ }
65
+
66
+ // Sin material en config/env: reutilizar la clave persistida de una
67
+ // ejecución anterior antes de generar una nueva (si no, los marcadores
68
+ // emitidos previamente quedarían huérfanos e irrestaurables).
69
+ const persisted = readPersistedKey()
70
+ if (persisted) {
71
+ return { key: persisted, source: "generated", fingerprint: keyFingerprint(persisted) }
72
+ }
73
+
74
+ // Fallback: clave aleatoria persistida
75
+ const key = generatePersistedKey()
76
+ return { key, source: "generated", fingerprint: keyFingerprint(key) }
77
+ }
78
+
79
+ /**
80
+ * Lee la clave persistida por una ejecución anterior (`apex.key` = 32 bytes
81
+ * en base64). Devuelve null si no existe, está vacía o no es válida — en ese
82
+ * caso el llamador genera (y persiste) una nueva.
83
+ */
84
+ function readPersistedKey(): Buffer | null {
85
+ try {
86
+ if (!existsSync(DEFAULT_KEY_FILE)) return null
87
+ const raw = readFileSync(DEFAULT_KEY_FILE, "utf8").trim()
88
+ if (!raw) return null
89
+ const key = Buffer.from(raw, "base64")
90
+ return key.length === 32 ? key : null
91
+ } catch {
92
+ return null
93
+ }
94
+ }
95
+
96
+ function resolveKeyMaterial(
97
+ spec: string | undefined,
98
+ ): { value: string; source: KeySource } | null {
99
+ const raw = (spec ?? "").trim()
100
+
101
+ if (raw.startsWith("env:")) {
102
+ const name = raw.slice(4).trim()
103
+ const value = process.env[name]
104
+ if (value) return { value, source: "env" }
105
+ return null
106
+ }
107
+
108
+ if (raw.startsWith("file:")) {
109
+ const path = raw.slice(5).trim()
110
+ try {
111
+ if (existsSync(path)) {
112
+ const value = readFileSync(path, "utf8").trim()
113
+ if (value) return { value, source: "file" }
114
+ }
115
+ } catch {
116
+ // fichero ilegible → siguiente fuente
117
+ }
118
+ return null
119
+ }
120
+
121
+ if (raw.startsWith("hex:")) {
122
+ const hex = raw.slice(4).trim()
123
+ if (/^[0-9a-fA-F]+$/.test(hex) && hex.length > 0) return { value: hex, source: "config" }
124
+ return null
125
+ }
126
+
127
+ if (raw.startsWith("base64:")) {
128
+ const b64 = raw.slice(7).trim()
129
+ if (b64.length > 0) return { value: b64, source: "config" }
130
+ return null
131
+ }
132
+
133
+ if (raw.length > 0) return { value: raw, source: "config" }
134
+
135
+ // Sin config: env por defecto
136
+ const envValue = process.env.APEX_REDACT_KEY
137
+ if (envValue) return { value: envValue, source: "env" }
138
+
139
+ return null
140
+ }
141
+
142
+ function generatePersistedKey(): Buffer {
143
+ const key = randomBytes(32)
144
+ try {
145
+ mkdirSync(dirname(DEFAULT_KEY_FILE), { recursive: true })
146
+ writeFileSync(DEFAULT_KEY_FILE, key.toString("base64"), { mode: 0o600 })
147
+ chmodSync(DEFAULT_KEY_FILE, 0o600)
148
+ console.warn(
149
+ `[apex.redact] No hay clave configurada. Generada clave aleatoria en ${DEFAULT_KEY_FILE}. ` +
150
+ `Fija "redact.key" en la config (o la env APEX_REDACT_KEY) para una clave estable.`,
151
+ )
152
+ } catch (error) {
153
+ console.warn(`[apex.redact] No se pudo persistir la clave generada: ${String(error)}`)
154
+ }
155
+ return key
156
+ }
157
+
158
+ /** Cifra un secreto y devuelve el payload base64url (iv || tag || ciphertext). */
159
+ export function encryptSecret(secret: string, key: Buffer): string {
160
+ const iv = randomBytes(IV_LENGTH)
161
+ const cipher = createCipheriv(ALGORITHM, key, iv)
162
+ const ciphertext = Buffer.concat([cipher.update(secret, "utf8"), cipher.final()])
163
+ const tag = cipher.getAuthTag()
164
+ return Buffer.concat([iv, tag, ciphertext]).toString("base64url")
165
+ }
166
+
167
+ /**
168
+ * Descifra un payload de marcador. Devuelve `null` si el payload no es válido
169
+ * o la autenticación GCM falla (p. ej. un texto con forma de marcador que no
170
+ * fue generado por nosotros) — en ese caso el llamador deja el texto intacto.
171
+ */
172
+ export function decryptSecret(payload: string, key: Buffer): string | null {
173
+ try {
174
+ const buffer = Buffer.from(payload, "base64url")
175
+ if (buffer.length < IV_LENGTH + TAG_LENGTH + 1) return null
176
+
177
+ const iv = buffer.subarray(0, IV_LENGTH)
178
+ const tag = buffer.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH)
179
+ const ciphertext = buffer.subarray(IV_LENGTH + TAG_LENGTH)
180
+
181
+ const decipher = createDecipheriv(ALGORITHM, key, iv)
182
+ decipher.setAuthTag(tag)
183
+ const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()])
184
+ return plaintext.toString("utf8")
185
+ } catch {
186
+ return null
187
+ }
188
+ }
189
+
190
+ /** Escapa una cadena para usarla como literal dentro de una RegExp. */
191
+ export function escapeRegExp(value: string): string {
192
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
193
+ }
package/core/guard.ts ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Apex Guard — meta-permisos por agente, decididos en el plugin.
3
+ *
4
+ * POR QUÉ EXISTE. La capa gratuita de OpenCode Zen rechaza la petición
5
+ * («free tier can only be used from within OpenCode») cuando el agente tiene
6
+ * alguna herramienta QUITADA, sea por `permission: <tool>: deny` o por
7
+ * `tools: <tool>: false`. Medido: una sola regla `shell: deny` basta. Y hay un
8
+ * segundo motivo para no usar `deny` en la config: opencode corta el camino
9
+ * antes de llamar a los plugins —
10
+ *
11
+ * // packages/core/src/permission.ts
12
+ * if (denied(input, rules)) return { effect: "deny", rules } // sin hooks
13
+ * const event = yield* hooks.trigger("permission", "evaluate", …)
14
+ *
15
+ * — así que un `deny` de config no es interceptable ni auditable.
16
+ *
17
+ * De ahí el reparto: la config declara `allow`/`ask` y **nunca** `deny`, con lo
18
+ * que el toolset se mantiene completo (el modelo las ve todas y el gate no
19
+ * salta), y la prohibición efectiva se decide aquí, sobre el `effect: "ask"`
20
+ * que sí llega al hook. Cada decisión queda registrada, que es lo que permite
21
+ * reportar qué intentó cada agente.
22
+ *
23
+ * Este fichero es el motor puro: sin Effect, sin IO, sin dependencias del host,
24
+ * para poder probarlo con una tabla de casos.
25
+ */
26
+
27
+ export type GuardEffect = "allow" | "deny" | "ask"
28
+
29
+ /**
30
+ * Qué hacer cuando NINGUNA regla coincide. `"keep"` deja el permiso como venía y
31
+ * es el único valor seguro por defecto: cualquier otro reescribe en masa lo que
32
+ * decidió la config del host — un `fallback: "allow"` convierte en `allow` todos
33
+ * los `ask`, y con ello anula de golpe las reglas de `shell` y deja al advisor
34
+ * sin nada que juzgar. (Pasó: un `rm -r` se ejecutó sin preguntar.)
35
+ */
36
+ export type GuardFallback = GuardEffect | "keep"
37
+
38
+ /**
39
+ * Una regla. `action` y `resource` son patrones con `*` (cualquier cosa), igual
40
+ * que los de `permission` en la config de opencode: `"shell"`, `"hindsight_*"`,
41
+ * `"rm -rf *"`, `".opencode/scout/**"`.
42
+ *
43
+ * `resource` ausente equivale a `"*"`.
44
+ */
45
+ export interface GuardRule {
46
+ readonly action: string
47
+ readonly resource?: string
48
+ readonly effect: GuardEffect
49
+ readonly reason?: string
50
+ }
51
+
52
+ /** Política de un agente: lista ordenada, **la última coincidencia gana**. */
53
+ export type GuardPolicy = readonly GuardRule[]
54
+
55
+ export interface GuardConfigShape {
56
+ /** "enforce" aplica el efecto; "report" solo registra y no toca el permiso. */
57
+ readonly mode: "enforce" | "report"
58
+ /** Efecto cuando ninguna regla coincide; "keep" respeta el del host. */
59
+ readonly fallback: GuardFallback
60
+ /**
61
+ * Reglas por agente. La clave `"*"` es la base común: sus reglas se evalúan
62
+ * ANTES que las del agente, así que las del agente pueden afinarlas.
63
+ */
64
+ readonly agents: Readonly<Record<string, GuardPolicy>>
65
+ /** Entradas que conserva el informe en memoria. */
66
+ readonly keep: number
67
+ }
68
+
69
+ export interface GuardDecision {
70
+ readonly effect: GuardEffect
71
+ /** Efecto que traía el permiso antes de pasar por aquí. */
72
+ readonly incoming: GuardEffect
73
+ readonly reason?: string
74
+ /** Regla que decidió, o undefined si decidió el fallback. */
75
+ readonly rule?: GuardRule
76
+ /** Recurso concreto que provocó la decisión (el primero que la dispara). */
77
+ readonly resource?: string
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Coincidencia de patrones
82
+ // ---------------------------------------------------------------------------
83
+
84
+ const cache = new Map<string, RegExp>()
85
+
86
+ /**
87
+ * Glob a regex, con la misma semántica laxa que usa opencode en sus reglas de
88
+ * permiso: `*` cubre cualquier cosa, incluidas las barras. Es deliberado — un
89
+ * patrón de recurso lo mismo describe una ruta (`.opencode/x/**`) que una línea
90
+ * de comando (`rm -rf *`), y distinguir `*` de `**` por tramos solo sorprendería
91
+ * a quien escribe la regla.
92
+ */
93
+ function toRegExp(pattern: string): RegExp {
94
+ const hit = cache.get(pattern)
95
+ if (hit) return hit
96
+ const body = pattern
97
+ .split("*")
98
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
99
+ .join(".*")
100
+ const re = new RegExp(`^${body}$`, "s")
101
+ cache.set(pattern, re)
102
+ return re
103
+ }
104
+
105
+ export function matches(pattern: string, value: string): boolean {
106
+ return pattern === "*" || pattern === value || toRegExp(pattern).test(value)
107
+ }
108
+
109
+ /**
110
+ * Normaliza un patrón de recurso a ruta absoluta cuando es relativo.
111
+ *
112
+ * Los recursos que entrega el host para `read`/`edit`/`write` son rutas
113
+ * absolutas, así que una regla escrita como `.opencode/scout/**` no coincidiría
114
+ * nunca. Se expande contra el directorio del proyecto. Lo que ya es absoluto, un
115
+ * `~` o un patrón que no parece ruta (un comando de shell) se deja intacto.
116
+ */
117
+ export function expandResource(pattern: string, projectDir: string, home: string): string {
118
+ if (pattern === "*" || pattern === "") return "*"
119
+ if (pattern.startsWith("/")) return pattern
120
+ if (pattern === "~" || pattern.startsWith("~/")) return home + pattern.slice(1)
121
+ // Un comando de shell no es una ruta: si lleva espacios, no se toca.
122
+ if (/\s/.test(pattern)) return pattern
123
+ return `${projectDir.replace(/\/+$/, "")}/${pattern}`
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Decisión
128
+ // ---------------------------------------------------------------------------
129
+
130
+ export interface GuardQuery {
131
+ readonly agent?: string
132
+ readonly action: string
133
+ readonly resources: readonly string[]
134
+ readonly incoming: GuardEffect
135
+ }
136
+
137
+ /**
138
+ * Reglas aplicables a un agente: la base `"*"` primero y las suyas después, de
139
+ * modo que las del agente ganan por ser posteriores.
140
+ */
141
+ export function policyFor(config: GuardConfigShape, agent: string | undefined): GuardPolicy {
142
+ const base = config.agents["*"] ?? []
143
+ const own = agent ? config.agents[agent] ?? [] : []
144
+ return [...base, ...own]
145
+ }
146
+
147
+ /**
148
+ * Decide el efecto. Recorre las reglas y se queda con la ÚLTIMA que coincide —
149
+ * el mismo criterio que opencode aplica a su propio ruleset, donde las reglas
150
+ * del agente se añaden al final y por eso mandan.
151
+ *
152
+ * Un `deny` gana sobre un `allow` de la misma pasada solo si va después. Eso es
153
+ * lo que permite «nada, salvo esta ruta»: primero el `deny` amplio, luego el
154
+ * `allow` estrecho.
155
+ */
156
+ export function decide(
157
+ config: GuardConfigShape,
158
+ query: GuardQuery,
159
+ paths: { projectDir: string; home: string },
160
+ ): GuardDecision {
161
+ const rules = policyFor(config, query.agent)
162
+ // Sin recursos el permiso sigue siendo evaluable: se trata como "*".
163
+ const resources = query.resources.length > 0 ? query.resources : ["*"]
164
+
165
+ let winner: { rule: GuardRule; resource: string } | undefined
166
+ for (const rule of rules) {
167
+ if (!matches(rule.action, query.action)) continue
168
+ // El patrón se prueba TAL CUAL y expandido a absoluto, porque el host entrega
169
+ // el recurso de las dos formas según la tool: medido, `read` llega como
170
+ // `package.json` (relativo al cwd) mientras las reglas del propio opencode
171
+ // hablan de `/home/…/.opencode/plan/*`. Expandir sin más dejaría sin efecto
172
+ // toda regla de ruta escrita en relativo, que son justo las útiles.
173
+ const patterns = new Set([rule.resource ?? "*", expandResource(rule.resource ?? "*", paths.projectDir, paths.home)])
174
+ const hit = resources.find((resource) => [...patterns].some((pattern) => matches(pattern, resource)))
175
+ if (hit === undefined) continue
176
+ winner = { rule, resource: hit }
177
+ }
178
+
179
+ if (!winner) {
180
+ const effect = config.fallback === "keep" ? query.incoming : config.fallback
181
+ return { effect, incoming: query.incoming, reason: "ninguna regla coincide" }
182
+ }
183
+ return {
184
+ effect: winner.rule.effect,
185
+ incoming: query.incoming,
186
+ reason: winner.rule.reason,
187
+ rule: winner.rule,
188
+ resource: winner.resource,
189
+ }
190
+ }
191
+
192
+ // ---------------------------------------------------------------------------
193
+ // Informe
194
+ // ---------------------------------------------------------------------------
195
+
196
+ export interface GuardEntry {
197
+ readonly at: number
198
+ readonly agent: string
199
+ readonly action: string
200
+ readonly resources: readonly string[]
201
+ readonly incoming: GuardEffect
202
+ readonly effect: GuardEffect
203
+ /** Efecto realmente aplicado: en modo "report" es el de entrada. */
204
+ readonly applied: GuardEffect
205
+ readonly reason?: string
206
+ readonly rule?: string
207
+ }
208
+
209
+ /** Anillo de decisiones. Solo memoria: un informe no vale una escritura a disco por tool call. */
210
+ export class GuardReport {
211
+ private entries: GuardEntry[] = []
212
+ constructor(private readonly keep: number) {}
213
+
214
+ add(entry: GuardEntry): void {
215
+ this.entries.push(entry)
216
+ if (this.entries.length > this.keep) this.entries.splice(0, this.entries.length - this.keep)
217
+ }
218
+
219
+ all(): readonly GuardEntry[] {
220
+ return this.entries
221
+ }
222
+
223
+ /** Últimas `n`, de la más reciente a la más antigua. */
224
+ recent(n: number): readonly GuardEntry[] {
225
+ return this.entries.slice(-n).reverse()
226
+ }
227
+
228
+ /** Recuento por agente → efecto aplicado, para el resumen del informe. */
229
+ summary(): Record<string, Record<GuardEffect, number>> {
230
+ const out: Record<string, Record<GuardEffect, number>> = {}
231
+ for (const e of this.entries) {
232
+ const row = (out[e.agent] ??= { allow: 0, deny: 0, ask: 0 })
233
+ row[e.applied]++
234
+ }
235
+ return out
236
+ }
237
+
238
+ clear(): void {
239
+ this.entries = []
240
+ }
241
+ }
242
+
243
+ /** Formatea una regla para el informe, sin volcar el objeto entero. */
244
+ export function ruleLabel(rule: GuardRule | undefined): string | undefined {
245
+ if (!rule) return undefined
246
+ const resource = rule.resource && rule.resource !== "*" ? ` ${rule.resource}` : ""
247
+ return `${rule.effect} ${rule.action}${resource}`
248
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Apex Events — listener HTTP plano para disparar la ingesta de eventos.
3
+ *
4
+ * Expone EL MISMO `events.ingest` (mismo handler, mismo contrato de payload),
5
+ * pensado para scripts que no pueden custodiar credenciales del servidor:
6
+ * un `curl` desde otra máquina, un hook de arranque, un túnel, etc.
7
+ *
8
+ * Seguridad:
9
+ * - `host` configurable (por defecto loopback). Bind a una interfaz LAN solo
10
+ * si confías en la red; bind a 0.0.0.0 sin token es peligroso (cualquiera
11
+ * podría inyectar prompts al agente).
12
+ * - `token` opcional: si está definido se exige (header `x-apex-token` o
13
+ * segmento de path `/ingest/<token>`).
14
+ * - Límite de cuerpo (64 KB por defecto) y JSON estricto.
15
+ */
16
+
17
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
18
+ import { timingSafeEqual } from "node:crypto"
19
+ import { networkInterfaces } from "node:os"
20
+
21
+ export interface IngestListenerOptions {
22
+ /** Interfaz de escucha (p. ej. "127.0.0.1" o "0.0.0.0" o una IP LAN). */
23
+ readonly host: string
24
+ /** Puerto de escucha. */
25
+ readonly port: number
26
+ /** Token opcional (si se define, es obligatorio en cada petición). */
27
+ readonly token?: string
28
+ /** Handler de ingesta: el mismo que usa `apex.events.ingest`. */
29
+ readonly ingest: (input: unknown) => Promise<unknown>
30
+ /** Límite de cuerpo en bytes (default 64 KB). */
31
+ readonly maxBodyBytes?: number
32
+ }
33
+
34
+ export interface IngestListener {
35
+ readonly host: string
36
+ readonly port: number
37
+ readonly close: () => Promise<void>
38
+ }
39
+
40
+ /**
41
+ * URLs por las que se puede alcanzar el listener.
42
+ * - host concreto (loopback o IP LAN) → solo esa
43
+ * - `0.0.0.0`/`::` → loopback + todas las IPv4 no internas de la máquina
44
+ */
45
+ export function listenerUrls(host: string, port: number, token?: string): string[] {
46
+ const suffix = token && token.length > 0 ? `/${token}` : ""
47
+ const path = `/ingest${suffix}`
48
+ const wildcard = host === "0.0.0.0" || host === "::" || host === "[::]"
49
+
50
+ if (!wildcard) return [`http://${host}:${port}${path}`]
51
+
52
+ const urls = [`http://127.0.0.1:${port}${path}`]
53
+ for (const entries of Object.values(networkInterfaces())) {
54
+ for (const entry of entries ?? []) {
55
+ if (entry.family === "IPv4" && !entry.internal) urls.push(`http://${entry.address}:${port}${path}`)
56
+ }
57
+ }
58
+ return urls
59
+ }
60
+
61
+ const DEFAULT_MAX_BODY = 64 * 1024
62
+
63
+ /** Comparación de tokens en tiempo constante. */
64
+ function tokenMatches(expected: string, received: string): boolean {
65
+ const a = Buffer.from(expected)
66
+ const b = Buffer.from(received)
67
+ if (a.length !== b.length) return false
68
+ return timingSafeEqual(a, b)
69
+ }
70
+
71
+ function json(res: ServerResponse, status: number, payload: unknown): void {
72
+ const body = JSON.stringify(payload)
73
+ res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(body) })
74
+ res.end(body)
75
+ }
76
+
77
+ function readBody(req: IncomingMessage, limit: number): Promise<string> {
78
+ return new Promise((resolve, reject) => {
79
+ let size = 0
80
+ const chunks: Buffer[] = []
81
+ req.on("data", (chunk: Buffer) => {
82
+ size += chunk.length
83
+ if (size > limit) {
84
+ // No destruimos el socket: drenamos para poder responder 413 y cerrar limpio.
85
+ reject(new Error("payload too large"))
86
+ req.resume()
87
+ return
88
+ }
89
+ chunks.push(chunk)
90
+ })
91
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")))
92
+ req.on("error", reject)
93
+ })
94
+ }
95
+
96
+ /**
97
+ * Arranca el listener. Lanza si el puerto no se puede abrir (el llamador decide
98
+ * si eso desactiva el listener sin romper el módulo).
99
+ */
100
+ export async function startIngestListener(options: IngestListenerOptions): Promise<IngestListener> {
101
+ const maxBody = options.maxBodyBytes ?? DEFAULT_MAX_BODY
102
+ const token = options.token && options.token.length > 0 ? options.token : undefined
103
+ const loopback = options.host === "127.0.0.1" || options.host === "localhost" || options.host === "::1"
104
+
105
+ if (!loopback && !token) {
106
+ console.warn(
107
+ `[Apex Events] listener de ingesta en ${options.host} SIN token: cualquiera con acceso a esa ` +
108
+ `interfaz puede inyectar prompts al agente. Define events.listener.token o usa 127.0.0.1.`,
109
+ )
110
+ }
111
+
112
+ const server = createServer((req, res) => {
113
+ void handle(req, res)
114
+ })
115
+
116
+ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
117
+ try {
118
+ const url = new URL(req.url ?? "/", `http://${options.host}`)
119
+ const segments = url.pathname.split("/").filter((s) => s.length > 0)
120
+
121
+ // GET /health → comprobación para túneles/monitorización
122
+ if (req.method === "GET" && (url.pathname === "/health" || url.pathname === "/")) {
123
+ json(res, 200, { ok: true, listener: "apex.events.ingest", host: options.host, port: options.port })
124
+ return
125
+ }
126
+
127
+ // POST /ingest · POST /ingest/<token>
128
+ if (segments[0] !== "ingest") {
129
+ json(res, 404, { error: "not_found", hint: "usa POST /ingest" })
130
+ return
131
+ }
132
+ if (req.method !== "POST") {
133
+ json(res, 405, { error: "method_not_allowed", hint: "usa POST" })
134
+ return
135
+ }
136
+
137
+ if (token) {
138
+ const fromPath = segments[1]
139
+ const fromHeader = req.headers["x-apex-token"]
140
+ const provided = fromPath ?? (typeof fromHeader === "string" ? fromHeader : undefined)
141
+ if (!provided || !tokenMatches(token, provided)) {
142
+ json(res, 401, { error: "unauthorized" })
143
+ return
144
+ }
145
+ }
146
+
147
+ const raw = await readBody(req, maxBody)
148
+ let parsed: unknown
149
+ try {
150
+ parsed = raw.length > 0 ? JSON.parse(raw) : {}
151
+ } catch {
152
+ json(res, 400, { error: "invalid_json" })
153
+ return
154
+ }
155
+
156
+ // Acepta el payload directo o el envoltorio del RPC ({ input: … })
157
+ const input =
158
+ parsed && typeof parsed === "object" && "input" in (parsed as Record<string, unknown>)
159
+ ? (parsed as Record<string, unknown>).input
160
+ : parsed
161
+
162
+ const output = await options.ingest(input)
163
+ json(res, 200, output ?? { accepted: false })
164
+ } catch (error) {
165
+ const message = error instanceof Error ? error.message : String(error)
166
+ if (message === "payload too large") {
167
+ json(res, 413, { error: "payload_too_large", maxBytes: maxBody })
168
+ return
169
+ }
170
+ json(res, 500, { error: "ingest_failed", message })
171
+ }
172
+ }
173
+
174
+ await new Promise<void>((resolve, reject) => {
175
+ server.once("error", reject)
176
+ server.listen(options.port, options.host, () => {
177
+ server.removeListener("error", reject)
178
+ resolve()
179
+ })
180
+ })
181
+
182
+ const address = server.address()
183
+ const boundPort = typeof address === "object" && address !== null ? address.port : options.port
184
+
185
+ return {
186
+ host: options.host,
187
+ port: boundPort,
188
+ close: () =>
189
+ new Promise<void>((resolve) => {
190
+ server.close(() => resolve())
191
+ }),
192
+ }
193
+ }