opencode-apex 0.3.0 → 0.4.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/CHANGELOG.md +37 -0
- package/README.md +6 -1
- package/core/autostart.ts +67 -0
- package/core/config.ts +2 -0
- package/core/daemon-client.ts +180 -0
- package/daemon/main.ts +1039 -0
- package/daemon/shared.ts +155 -0
- package/daemon/webhooks.ts +165 -0
- package/docs/CONFIG.md +2 -1
- package/docs/ENDPOINTS.md +87 -0
- package/endpoints.ts +286 -0
- package/index.ts +9 -1
- package/opencode-apex.jsonc +3 -1
- package/package.json +10 -4
- package/skills/apex-callbacks/SKILL.md +7 -2
- package/skills/apex-callbacks/references/reachability.md +3 -1
- package/skills/apex-endpoints/SKILL.md +130 -0
package/daemon/main.ts
ADDED
|
@@ -0,0 +1,1039 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* apex-daemon — un proceso por usuario que mantiene lo que el plugin no puede mantener
|
|
3
|
+
* (OpenCode descarga los plugins tras 60 min sin actividad):
|
|
4
|
+
*
|
|
5
|
+
* - rutas propias en el túnel OpenTunnel del perfil `default`, el mismo que usa el acceso
|
|
6
|
+
* remoto de OpenCode (cada uno reclama sus rutas), con caducidad;
|
|
7
|
+
* - el receptor de webhooks: verifica la firma o el token de cada uno y solo entonces
|
|
8
|
+
* llama en local a `events.ingest` (el password del servidor no sale de la máquina);
|
|
9
|
+
* - los microservicios del agente: arranque, reinicio con espera creciente, logs y TTL.
|
|
10
|
+
*
|
|
11
|
+
* Multiplataforma a propósito: sin systemd ni launchd. Lo lanza el plugin desacoplado con
|
|
12
|
+
* el propio binario de OpenCode en modo bun (`BUN_BE_BUN=1`); un lockfile evita dos.
|
|
13
|
+
*
|
|
14
|
+
* Dos listeners en 127.0.0.1: control (token del daemon; nunca se publica) y webhooks
|
|
15
|
+
* (lo único que apunta el túnel). Separarlos es lo que pide OpenTunnel: lo que solo debe
|
|
16
|
+
* ser local, en un listener que nunca se enruta.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { spawn, type ChildProcess } from "node:child_process"
|
|
20
|
+
import {
|
|
21
|
+
chmodSync,
|
|
22
|
+
closeSync,
|
|
23
|
+
existsSync,
|
|
24
|
+
mkdirSync,
|
|
25
|
+
openSync,
|
|
26
|
+
readFileSync,
|
|
27
|
+
renameSync,
|
|
28
|
+
statSync,
|
|
29
|
+
unlinkSync,
|
|
30
|
+
writeFileSync,
|
|
31
|
+
writeSync,
|
|
32
|
+
} from "node:fs"
|
|
33
|
+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"
|
|
34
|
+
import { uptime } from "node:os"
|
|
35
|
+
import { join } from "node:path"
|
|
36
|
+
import { rpcUrl, tunnelDirectory } from "../core/server-endpoint.js"
|
|
37
|
+
import {
|
|
38
|
+
bootStamp,
|
|
39
|
+
daemonPaths,
|
|
40
|
+
emptyRegistry,
|
|
41
|
+
randomRoute,
|
|
42
|
+
randomToken,
|
|
43
|
+
validRouteName,
|
|
44
|
+
type DaemonInfo,
|
|
45
|
+
type ProxyProtocol,
|
|
46
|
+
type Registry,
|
|
47
|
+
type RestartPolicy,
|
|
48
|
+
type ServerTarget,
|
|
49
|
+
type ServiceEntry,
|
|
50
|
+
type TunnelEntry,
|
|
51
|
+
type WebhookEntry,
|
|
52
|
+
type WebhookProvider,
|
|
53
|
+
} from "./shared.js"
|
|
54
|
+
import { parseBody, slackChallenge, toIngest, verify, type Headers } from "./webhooks.js"
|
|
55
|
+
|
|
56
|
+
const VERSION = process.env.APEX_DAEMON_VERSION ?? "dev"
|
|
57
|
+
const paths = daemonPaths()
|
|
58
|
+
const IDLE_EXIT_MS = Number(process.env.APEX_DAEMON_IDLE_MINUTES ?? 10) * 60_000
|
|
59
|
+
const MAX_BODY = 1024 * 1024
|
|
60
|
+
const SWEEP_MS = Number(process.env.APEX_DAEMON_SWEEP_MS ?? 15_000)
|
|
61
|
+
const PROVIDERS: readonly WebhookProvider[] = ["github", "stripe", "slack", "hmac", "token"]
|
|
62
|
+
|
|
63
|
+
const log = (...parts: unknown[]) => console.log(new Date().toISOString(), ...parts)
|
|
64
|
+
|
|
65
|
+
// ============================================================================
|
|
66
|
+
// Proceso único
|
|
67
|
+
// ============================================================================
|
|
68
|
+
|
|
69
|
+
function alive(pid: number): boolean {
|
|
70
|
+
try {
|
|
71
|
+
process.kill(pid, 0)
|
|
72
|
+
return true
|
|
73
|
+
} catch (error) {
|
|
74
|
+
return (error as NodeJS.ErrnoException).code === "EPERM"
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function acquireLock(): boolean {
|
|
79
|
+
mkdirSync(paths.home, { recursive: true, mode: 0o700 })
|
|
80
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
81
|
+
try {
|
|
82
|
+
const fd = openSync(paths.lock, "wx", 0o600)
|
|
83
|
+
writeSync(fd, String(process.pid))
|
|
84
|
+
closeSync(fd)
|
|
85
|
+
return true
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
|
|
88
|
+
const owner = Number(readFileSync(paths.lock, "utf8").trim())
|
|
89
|
+
if (Number.isInteger(owner) && owner > 0 && owner !== process.pid && alive(owner)) return false
|
|
90
|
+
try {
|
|
91
|
+
unlinkSync(paths.lock)
|
|
92
|
+
} catch {
|
|
93
|
+
// otro proceso ya lo limpió
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return false
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ============================================================================
|
|
101
|
+
// Registro (0600, escritura atómica)
|
|
102
|
+
// ============================================================================
|
|
103
|
+
|
|
104
|
+
function writePrivate(file: string, data: string): void {
|
|
105
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
106
|
+
writeFileSync(tmp, data, { mode: 0o600 })
|
|
107
|
+
renameSync(tmp, file)
|
|
108
|
+
try {
|
|
109
|
+
chmodSync(file, 0o600)
|
|
110
|
+
} catch {
|
|
111
|
+
// Windows: los permisos POSIX no aplican
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function loadRegistry(): Registry & { ports?: { control?: number; hooks?: number } } {
|
|
116
|
+
try {
|
|
117
|
+
const parsed = JSON.parse(readFileSync(paths.registry, "utf8"))
|
|
118
|
+
return { ...emptyRegistry(), ...parsed }
|
|
119
|
+
} catch {
|
|
120
|
+
return emptyRegistry()
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const registry = loadRegistry()
|
|
125
|
+
const save = () => writePrivate(paths.registry, JSON.stringify(registry, null, 2))
|
|
126
|
+
|
|
127
|
+
// ============================================================================
|
|
128
|
+
// Servidor de OpenCode por proyecto: el daemon llama a events.ingest en local
|
|
129
|
+
// ============================================================================
|
|
130
|
+
|
|
131
|
+
function readPassword(target: ServerTarget): string | null {
|
|
132
|
+
const source = target.password
|
|
133
|
+
if (!source) return null
|
|
134
|
+
if (source.kind === "value") return source.value
|
|
135
|
+
try {
|
|
136
|
+
const record = JSON.parse(readFileSync(source.file, "utf8")) as Record<string, unknown>
|
|
137
|
+
const value = record[source.field]
|
|
138
|
+
return typeof value === "string" ? value : null
|
|
139
|
+
} catch {
|
|
140
|
+
return null
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function ingest(directory: string, input: unknown): Promise<{ ok: boolean; status?: number; error?: string }> {
|
|
145
|
+
const target = registry.servers[directory]
|
|
146
|
+
if (!target) return { ok: false, error: "no OpenCode server known for this project yet (open it in OpenCode once)" }
|
|
147
|
+
const password = readPassword(target)
|
|
148
|
+
const headers: Record<string, string> = { "content-type": "application/json" }
|
|
149
|
+
if (password) headers.authorization = `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
|
|
150
|
+
try {
|
|
151
|
+
const response = await fetch(rpcUrl(target.baseUrl, "events.ingest", directory), {
|
|
152
|
+
method: "POST",
|
|
153
|
+
headers,
|
|
154
|
+
body: JSON.stringify({ input }),
|
|
155
|
+
signal: AbortSignal.timeout(15_000),
|
|
156
|
+
})
|
|
157
|
+
if (response.ok) return { ok: true, status: response.status }
|
|
158
|
+
return { ok: false, status: response.status, error: (await response.text()).slice(0, 300) }
|
|
159
|
+
} catch (error) {
|
|
160
|
+
return { ok: false, error: String((error as Error).message ?? error) }
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ============================================================================
|
|
165
|
+
// Túnel (OpenTunnel SDK, perfil default compartido con OpenCode)
|
|
166
|
+
// ============================================================================
|
|
167
|
+
|
|
168
|
+
type Connection = Awaited<ReturnType<Awaited<ReturnType<typeof loadClient>>["tunnel"]["connect"]>>
|
|
169
|
+
|
|
170
|
+
async function loadClient() {
|
|
171
|
+
const { create } = await import("@opentunnel/client")
|
|
172
|
+
return create()
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const tunnel = {
|
|
176
|
+
client: null as Awaited<ReturnType<typeof loadClient>> | null,
|
|
177
|
+
connection: null as Connection | null,
|
|
178
|
+
hostname: null as string | null,
|
|
179
|
+
state: "idle" as "idle" | "provisioning" | "connecting" | "connected" | "reconnecting" | "error",
|
|
180
|
+
lastError: null as string | null,
|
|
181
|
+
connectedAt: null as number | null,
|
|
182
|
+
queue: Promise.resolve() as Promise<void>,
|
|
183
|
+
retry: null as ReturnType<typeof setTimeout> | null,
|
|
184
|
+
failures: 0,
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
let hooksPort = 0
|
|
188
|
+
let controlPort = 0
|
|
189
|
+
|
|
190
|
+
function routeTable(): Record<string, string | { target: string; proxyProtocol: ProxyProtocol }> {
|
|
191
|
+
const routes: Record<string, string | { target: string; proxyProtocol: ProxyProtocol }> = {}
|
|
192
|
+
for (const entry of registry.tunnels) {
|
|
193
|
+
// Las rutas de webhooks apuntan al listener de webhooks, cuyo puerto puede cambiar.
|
|
194
|
+
const target = registry.webhooks.some((hook) => hook.id === entry.ownerID) ? `127.0.0.1:${hooksPort}` : entry.target
|
|
195
|
+
routes[entry.route] = entry.proxyProtocol ? { target, proxyProtocol: entry.proxyProtocol } : target
|
|
196
|
+
}
|
|
197
|
+
return routes
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Hostname del túnel del dispositivo, leído del disco (`tunnel.json`, lo escribe el SDK cuando
|
|
202
|
+
* el certificado está listo). No pasa por el SDK: mientras `connect` aprovisiona, sus
|
|
203
|
+
* llamadas esperan y una petición de control se quedaría colgada.
|
|
204
|
+
*/
|
|
205
|
+
async function knownHostname(): Promise<string | null> {
|
|
206
|
+
if (tunnel.hostname) return tunnel.hostname
|
|
207
|
+
try {
|
|
208
|
+
const stored = JSON.parse(readFileSync(join(tunnelDirectory(), "default", "tunnel.json"), "utf8")) as { hostname?: unknown }
|
|
209
|
+
if (typeof stored.hostname === "string" && stored.hostname.length > 0) tunnel.hostname = stored.hostname
|
|
210
|
+
} catch {
|
|
211
|
+
// sin túnel todavía
|
|
212
|
+
}
|
|
213
|
+
return tunnel.hostname
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function urlOf(route: string): string | null {
|
|
217
|
+
return tunnel.hostname ? `https://${route}.${tunnel.hostname}` : null
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Aplica el registro al túnel. Serializado: un connect/setRoutes cada vez. */
|
|
221
|
+
function syncRoutes(): Promise<void> {
|
|
222
|
+
tunnel.queue = tunnel.queue.then(applyRoutes, applyRoutes)
|
|
223
|
+
return tunnel.queue
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function applyRoutes(): Promise<void> {
|
|
227
|
+
const routes = routeTable()
|
|
228
|
+
const empty = Object.keys(routes).length === 0
|
|
229
|
+
try {
|
|
230
|
+
if (empty) {
|
|
231
|
+
if (tunnel.connection) {
|
|
232
|
+
const connection = tunnel.connection
|
|
233
|
+
tunnel.connection = null
|
|
234
|
+
await connection.close()
|
|
235
|
+
}
|
|
236
|
+
tunnel.state = "idle"
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
if (tunnel.connection) {
|
|
240
|
+
await tunnel.connection.setRoutes(routes)
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
tunnel.client ??= await loadClient()
|
|
244
|
+
// Sin identidad, connect crea el túnel del dispositivo (certificado: ~1 min).
|
|
245
|
+
tunnel.state = (await knownHostname()) ? "connecting" : "provisioning"
|
|
246
|
+
const connection = await tunnel.client.tunnel.connect({
|
|
247
|
+
routes,
|
|
248
|
+
onEvent: (event) => {
|
|
249
|
+
if (event.type === "connected") {
|
|
250
|
+
tunnel.state = "connected"
|
|
251
|
+
tunnel.connectedAt = Date.now()
|
|
252
|
+
tunnel.failures = 0
|
|
253
|
+
} else if (event.type === "reconnecting" || event.type === "disconnected") {
|
|
254
|
+
tunnel.state = "reconnecting"
|
|
255
|
+
if (event.type === "disconnected") tunnel.lastError = event.reason
|
|
256
|
+
} else if (event.type === "route-conflict") {
|
|
257
|
+
tunnel.lastError = `route conflict: ${event.routes.join(", ")}`
|
|
258
|
+
} else if (event.type === "stopped" && event.error) {
|
|
259
|
+
tunnel.lastError = event.error
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
})
|
|
263
|
+
tunnel.connection = connection
|
|
264
|
+
tunnel.hostname = connection.tunnel.hostname
|
|
265
|
+
tunnel.state = "connected"
|
|
266
|
+
tunnel.connectedAt = Date.now()
|
|
267
|
+
tunnel.lastError = null
|
|
268
|
+
void connection.closed.then(
|
|
269
|
+
() => onTunnelStopped(connection, null),
|
|
270
|
+
(error) => onTunnelStopped(connection, error),
|
|
271
|
+
)
|
|
272
|
+
// Rutas cambiadas mientras conectaba.
|
|
273
|
+
const now = routeTable()
|
|
274
|
+
if (JSON.stringify(now) !== JSON.stringify(routes)) await connection.setRoutes(now)
|
|
275
|
+
} catch (error) {
|
|
276
|
+
tunnel.state = "error"
|
|
277
|
+
tunnel.lastError = String((error as Error).message ?? error)
|
|
278
|
+
log("tunnel error:", tunnel.lastError)
|
|
279
|
+
scheduleRetry()
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function onTunnelStopped(connection: Connection, error: unknown): void {
|
|
284
|
+
if (tunnel.connection !== connection) return
|
|
285
|
+
tunnel.connection = null
|
|
286
|
+
tunnel.state = "error"
|
|
287
|
+
tunnel.lastError = error ? String((error as Error).message ?? error) : "tunnel closed"
|
|
288
|
+
log("tunnel stopped:", tunnel.lastError)
|
|
289
|
+
scheduleRetry()
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function scheduleRetry(): void {
|
|
293
|
+
if (tunnel.retry || registry.tunnels.length === 0) return
|
|
294
|
+
const delay = Math.min(1000 * 2 ** tunnel.failures, 60_000)
|
|
295
|
+
tunnel.failures++
|
|
296
|
+
tunnel.retry = setTimeout(() => {
|
|
297
|
+
tunnel.retry = null
|
|
298
|
+
void syncRoutes()
|
|
299
|
+
}, delay)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ============================================================================
|
|
303
|
+
// Microservicios
|
|
304
|
+
// ============================================================================
|
|
305
|
+
|
|
306
|
+
const children = new Map<string, ChildProcess>()
|
|
307
|
+
const stopping = new Set<string>()
|
|
308
|
+
const startedAt = new Map<string, number>()
|
|
309
|
+
const restartTimers = new Map<string, ReturnType<typeof setTimeout>>()
|
|
310
|
+
const currentBoot = () => bootStamp(Date.now(), uptime())
|
|
311
|
+
|
|
312
|
+
/** Entorno de un servicio: el del daemon menos credenciales de OpenCode, más lo suyo. */
|
|
313
|
+
function serviceEnv(service: ServiceEntry): NodeJS.ProcessEnv {
|
|
314
|
+
const env: NodeJS.ProcessEnv = { ...process.env }
|
|
315
|
+
for (const key of ["OPENCODE_SERVER_PASSWORD", "OPENCODE_PASSWORD", "BUN_BE_BUN", "APEX_DAEMON_VERSION"]) delete env[key]
|
|
316
|
+
const route = registry.tunnels.find((entry) => entry.ownerID === service.id)
|
|
317
|
+
return {
|
|
318
|
+
...env,
|
|
319
|
+
...service.env,
|
|
320
|
+
...(service.port ? { PORT: String(service.port) } : {}),
|
|
321
|
+
...(route && urlOf(route.route) ? { APEX_PUBLIC_URL: urlOf(route.route)! } : {}),
|
|
322
|
+
APEX_SERVICE_NAME: service.name,
|
|
323
|
+
APEX_INGEST_URL: `http://127.0.0.1:${controlPort}/v1/ingest`,
|
|
324
|
+
APEX_INGEST_TOKEN: service.ingestToken,
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function rotate(file: string, max: number): void {
|
|
329
|
+
try {
|
|
330
|
+
if (statSync(file).size > max) renameSync(file, `${file}.1`)
|
|
331
|
+
} catch {
|
|
332
|
+
// no existe todavía
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function startService(service: ServiceEntry): void {
|
|
337
|
+
if (children.has(service.id)) return
|
|
338
|
+
mkdirSync(paths.logs, { recursive: true, mode: 0o700 })
|
|
339
|
+
rotate(service.logFile, 10 * 1024 * 1024)
|
|
340
|
+
const fd = openSync(service.logFile, "a", 0o600)
|
|
341
|
+
writeSync(fd, `\n--- ${new Date().toISOString()} start: ${service.command}\n`)
|
|
342
|
+
let child: ChildProcess
|
|
343
|
+
try {
|
|
344
|
+
// detached: grupo propio (se para entero) y sobrevive a un reinicio del daemon,
|
|
345
|
+
// que lo adopta por pid. La salida va directa al fichero, sin pasar por el daemon.
|
|
346
|
+
child = spawn(service.command, {
|
|
347
|
+
cwd: service.cwd,
|
|
348
|
+
env: serviceEnv(service),
|
|
349
|
+
shell: true,
|
|
350
|
+
detached: true,
|
|
351
|
+
stdio: ["ignore", fd, fd],
|
|
352
|
+
windowsHide: true,
|
|
353
|
+
})
|
|
354
|
+
} catch (error) {
|
|
355
|
+
closeSync(fd)
|
|
356
|
+
service.status = "failed"
|
|
357
|
+
service.lastExit = { code: null, signal: String((error as Error).message), at: Date.now() }
|
|
358
|
+
save()
|
|
359
|
+
return
|
|
360
|
+
}
|
|
361
|
+
closeSync(fd)
|
|
362
|
+
children.set(service.id, child)
|
|
363
|
+
startedAt.set(service.id, Date.now())
|
|
364
|
+
service.pid = child.pid ?? null
|
|
365
|
+
service.bootAt = currentBoot()
|
|
366
|
+
service.status = "running"
|
|
367
|
+
save()
|
|
368
|
+
child.on("exit", (code, signal) => {
|
|
369
|
+
children.delete(service.id)
|
|
370
|
+
onServiceExit(service.id, code, signal)
|
|
371
|
+
})
|
|
372
|
+
child.on("error", (error) => {
|
|
373
|
+
log(`service ${service.name}:`, error.message)
|
|
374
|
+
// Sin proceso (no hubo spawn): no llegará exit.
|
|
375
|
+
if (child.pid === undefined) {
|
|
376
|
+
children.delete(service.id)
|
|
377
|
+
service.pid = null
|
|
378
|
+
service.status = "failed"
|
|
379
|
+
service.lastExit = { code: null, signal: error.message, at: Date.now() }
|
|
380
|
+
save()
|
|
381
|
+
}
|
|
382
|
+
})
|
|
383
|
+
child.unref()
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function onServiceExit(id: string, code: number | null, signal: string | null): void {
|
|
387
|
+
const service = registry.services.find((entry) => entry.id === id)
|
|
388
|
+
if (!service) return
|
|
389
|
+
service.pid = null
|
|
390
|
+
service.lastExit = { code, signal, at: Date.now() }
|
|
391
|
+
if (stopping.has(id)) {
|
|
392
|
+
stopping.delete(id)
|
|
393
|
+
service.status = "stopped"
|
|
394
|
+
save()
|
|
395
|
+
return
|
|
396
|
+
}
|
|
397
|
+
// Estable más de un minuto: el contador de reinicios vuelve a cero.
|
|
398
|
+
if (Date.now() - (startedAt.get(id) ?? 0) > 60_000) service.restarts = 0
|
|
399
|
+
const again = service.restart === "always" || (service.restart === "on-failure" && code !== 0)
|
|
400
|
+
if (!again) {
|
|
401
|
+
service.status = code === 0 ? "stopped" : "failed"
|
|
402
|
+
save()
|
|
403
|
+
return
|
|
404
|
+
}
|
|
405
|
+
const delay = Math.min(1000 * 2 ** service.restarts, 60_000)
|
|
406
|
+
service.restarts++
|
|
407
|
+
service.status = "backoff"
|
|
408
|
+
save()
|
|
409
|
+
restartTimers.set(
|
|
410
|
+
id,
|
|
411
|
+
setTimeout(() => {
|
|
412
|
+
restartTimers.delete(id)
|
|
413
|
+
const current = registry.services.find((entry) => entry.id === id)
|
|
414
|
+
if (current && current.status === "backoff") startService(current)
|
|
415
|
+
}, delay),
|
|
416
|
+
)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Mata el grupo del servicio: SIGTERM y, a los 5 s, SIGKILL (Windows: taskkill /T /F). */
|
|
420
|
+
function killTree(pid: number): void {
|
|
421
|
+
if (process.platform === "win32") {
|
|
422
|
+
spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on("error", () => {})
|
|
423
|
+
return
|
|
424
|
+
}
|
|
425
|
+
const signal = (sig: NodeJS.Signals) => {
|
|
426
|
+
try {
|
|
427
|
+
process.kill(-pid, sig)
|
|
428
|
+
} catch {
|
|
429
|
+
try {
|
|
430
|
+
process.kill(pid, sig)
|
|
431
|
+
} catch {
|
|
432
|
+
// ya no existe
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
signal("SIGTERM")
|
|
437
|
+
setTimeout(() => {
|
|
438
|
+
if (alive(pid)) signal("SIGKILL")
|
|
439
|
+
}, 5000).unref()
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function stopService(service: ServiceEntry): void {
|
|
443
|
+
const timer = restartTimers.get(service.id)
|
|
444
|
+
if (timer) {
|
|
445
|
+
clearTimeout(timer)
|
|
446
|
+
restartTimers.delete(service.id)
|
|
447
|
+
}
|
|
448
|
+
if (service.pid && alive(service.pid)) {
|
|
449
|
+
stopping.add(service.id)
|
|
450
|
+
killTree(service.pid)
|
|
451
|
+
// Adoptado (sin ChildProcess): no habrá evento exit.
|
|
452
|
+
if (!children.has(service.id)) {
|
|
453
|
+
stopping.delete(service.id)
|
|
454
|
+
service.pid = null
|
|
455
|
+
service.status = "stopped"
|
|
456
|
+
}
|
|
457
|
+
} else {
|
|
458
|
+
service.pid = null
|
|
459
|
+
service.status = "stopped"
|
|
460
|
+
}
|
|
461
|
+
save()
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Al arrancar: adopta los servicios vivos del daemon anterior; arranca el resto. */
|
|
465
|
+
function resumeServices(restartAll: boolean): void {
|
|
466
|
+
const boot = currentBoot()
|
|
467
|
+
for (const service of registry.services) {
|
|
468
|
+
if (service.status === "stopped" || service.status === "failed") continue
|
|
469
|
+
const sameBoot = service.bootAt !== null && Math.abs(boot - service.bootAt) <= 20_000
|
|
470
|
+
if (service.pid && sameBoot && alive(service.pid)) {
|
|
471
|
+
if (restartAll) {
|
|
472
|
+
// El puerto de control cambió: APEX_INGEST_URL del servicio ya no vale.
|
|
473
|
+
killTree(service.pid)
|
|
474
|
+
service.pid = null
|
|
475
|
+
setTimeout(() => startService(service), 1500)
|
|
476
|
+
continue
|
|
477
|
+
}
|
|
478
|
+
service.status = "running"
|
|
479
|
+
log(`adopted service ${service.name} (pid ${service.pid})`)
|
|
480
|
+
continue
|
|
481
|
+
}
|
|
482
|
+
service.pid = null
|
|
483
|
+
startService(service)
|
|
484
|
+
}
|
|
485
|
+
save()
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Vigila los adoptados (sin evento exit): cuando mueren, se tratan como una salida. */
|
|
489
|
+
function watchAdopted(): void {
|
|
490
|
+
for (const service of registry.services) {
|
|
491
|
+
if (service.status === "running" && service.pid && !children.has(service.id) && !alive(service.pid)) {
|
|
492
|
+
onServiceExit(service.id, null, null)
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ============================================================================
|
|
498
|
+
// Altas, bajas y caducidad
|
|
499
|
+
// ============================================================================
|
|
500
|
+
|
|
501
|
+
function expiry(ttlMinutes: unknown): number | null {
|
|
502
|
+
const ttl = Number(ttlMinutes)
|
|
503
|
+
return Number.isFinite(ttl) && ttl > 0 ? Date.now() + ttl * 60_000 : null
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function pickRoute(name: unknown): string {
|
|
507
|
+
if (typeof name === "string" && name.length > 0) {
|
|
508
|
+
const route = name.toLowerCase()
|
|
509
|
+
if (!validRouteName(route)) throw new HttpError(400, `invalid route name "${name}" (lowercase letters, digits, dashes)`)
|
|
510
|
+
if (registry.tunnels.some((entry) => entry.route === route)) throw new HttpError(409, `route "${route}" already in use`)
|
|
511
|
+
return route
|
|
512
|
+
}
|
|
513
|
+
return randomRoute()
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** Nunca publicar el servidor de OpenCode: para eso está su acceso remoto (con password). */
|
|
517
|
+
function assertNotServerPort(host: string, port: number): void {
|
|
518
|
+
for (const target of Object.values(registry.servers)) {
|
|
519
|
+
try {
|
|
520
|
+
const url = new URL(target.baseUrl)
|
|
521
|
+
const local = ["127.0.0.1", "localhost", "[::1]", "0.0.0.0"].includes(url.hostname)
|
|
522
|
+
if (local && ["127.0.0.1", "localhost", "::1"].includes(host) && Number(url.port) === port)
|
|
523
|
+
throw new HttpError(400, "that is the OpenCode server port: use OpenCode remote access (opencode service set remote true)")
|
|
524
|
+
} catch (error) {
|
|
525
|
+
if (error instanceof HttpError) throw error
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function removeTunnel(id: string): boolean {
|
|
531
|
+
const before = registry.tunnels.length
|
|
532
|
+
registry.tunnels = registry.tunnels.filter((entry) => entry.id !== id && entry.ownerID !== id)
|
|
533
|
+
return registry.tunnels.length !== before
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function removeWebhook(hook: WebhookEntry): void {
|
|
537
|
+
registry.webhooks = registry.webhooks.filter((entry) => entry.id !== hook.id)
|
|
538
|
+
removeTunnel(hook.id)
|
|
539
|
+
try {
|
|
540
|
+
unlinkSync(hook.secretFile)
|
|
541
|
+
} catch {
|
|
542
|
+
// ya no estaba
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function removeService(service: ServiceEntry): void {
|
|
547
|
+
stopService(service)
|
|
548
|
+
registry.services = registry.services.filter((entry) => entry.id !== service.id)
|
|
549
|
+
removeTunnel(service.id)
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
let idleSince: number | null = null
|
|
553
|
+
|
|
554
|
+
function sweep(): void {
|
|
555
|
+
const now = Date.now()
|
|
556
|
+
let changed = false
|
|
557
|
+
for (const entry of [...registry.tunnels]) {
|
|
558
|
+
if (!entry.ownerID && entry.expiresAt !== null && entry.expiresAt <= now) {
|
|
559
|
+
log(`expired tunnel ${entry.route}`)
|
|
560
|
+
changed = removeTunnel(entry.id) || changed
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
for (const hook of [...registry.webhooks]) {
|
|
564
|
+
if (hook.expiresAt !== null && hook.expiresAt <= now) {
|
|
565
|
+
log(`expired webhook ${hook.name}`)
|
|
566
|
+
removeWebhook(hook)
|
|
567
|
+
changed = true
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
for (const service of [...registry.services]) {
|
|
571
|
+
if (service.expiresAt !== null && service.expiresAt <= now) {
|
|
572
|
+
log(`expired service ${service.name}`)
|
|
573
|
+
removeService(service)
|
|
574
|
+
changed = true
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
watchAdopted()
|
|
578
|
+
if (changed) {
|
|
579
|
+
save()
|
|
580
|
+
void syncRoutes()
|
|
581
|
+
}
|
|
582
|
+
const empty = registry.tunnels.length === 0 && registry.webhooks.length === 0 && registry.services.length === 0
|
|
583
|
+
idleSince = empty ? (idleSince ?? now) : null
|
|
584
|
+
if (idleSince !== null && now - idleSince >= IDLE_EXIT_MS) {
|
|
585
|
+
log("idle: nothing to keep, exiting")
|
|
586
|
+
void shutdown(0)
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// ============================================================================
|
|
591
|
+
// HTTP
|
|
592
|
+
// ============================================================================
|
|
593
|
+
|
|
594
|
+
class HttpError extends Error {
|
|
595
|
+
constructor(
|
|
596
|
+
readonly status: number,
|
|
597
|
+
message: string,
|
|
598
|
+
) {
|
|
599
|
+
super(message)
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function readBody(request: IncomingMessage): Promise<Buffer> {
|
|
604
|
+
return new Promise((resolve, reject) => {
|
|
605
|
+
const chunks: Buffer[] = []
|
|
606
|
+
let size = 0
|
|
607
|
+
request.on("data", (chunk: Buffer) => {
|
|
608
|
+
size += chunk.length
|
|
609
|
+
if (size > MAX_BODY) {
|
|
610
|
+
reject(new HttpError(413, "body too large"))
|
|
611
|
+
request.destroy()
|
|
612
|
+
return
|
|
613
|
+
}
|
|
614
|
+
chunks.push(chunk)
|
|
615
|
+
})
|
|
616
|
+
request.on("end", () => resolve(Buffer.concat(chunks)))
|
|
617
|
+
request.on("error", reject)
|
|
618
|
+
})
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function send(response: ServerResponse, status: number, body: unknown, type = "application/json"): void {
|
|
622
|
+
if (response.headersSent) return
|
|
623
|
+
const text = typeof body === "string" ? body : JSON.stringify(body)
|
|
624
|
+
response.writeHead(status, { "content-type": type, "cache-control": "no-store" })
|
|
625
|
+
response.end(text)
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function lowerHeaders(request: IncomingMessage): Headers {
|
|
629
|
+
const out: Record<string, string> = {}
|
|
630
|
+
for (const [key, value] of Object.entries(request.headers)) {
|
|
631
|
+
if (typeof value === "string") out[key.toLowerCase()] = value
|
|
632
|
+
else if (Array.isArray(value)) out[key.toLowerCase()] = value.join(", ")
|
|
633
|
+
}
|
|
634
|
+
return out
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Lo que ve el plugin de un webhook: nunca el secreto, solo su fichero. */
|
|
638
|
+
function publicHook(hook: WebhookEntry) {
|
|
639
|
+
const { secret: _secret, ...rest } = hook
|
|
640
|
+
const route = registry.tunnels.find((entry) => entry.ownerID === hook.id)
|
|
641
|
+
return { ...rest, url: route ? urlOf(route.route) : null }
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function publicService(service: ServiceEntry) {
|
|
645
|
+
const { ingestToken: _token, env, ...rest } = service
|
|
646
|
+
const route = registry.tunnels.find((entry) => entry.ownerID === service.id)
|
|
647
|
+
return { ...rest, envKeys: Object.keys(env), url: route ? urlOf(route.route) : null }
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function publicTunnel(entry: TunnelEntry) {
|
|
651
|
+
return { ...entry, url: urlOf(entry.route) }
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function tunnelStatus() {
|
|
655
|
+
return {
|
|
656
|
+
state: tunnel.state,
|
|
657
|
+
hostname: tunnel.hostname,
|
|
658
|
+
lastError: tunnel.lastError,
|
|
659
|
+
connectedAt: tunnel.connectedAt,
|
|
660
|
+
routes: Object.keys(routeTable()).length,
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
function owned(body: Record<string, unknown>) {
|
|
665
|
+
const directory = typeof body.directory === "string" ? body.directory : ""
|
|
666
|
+
if (!directory) throw new HttpError(400, "directory is required")
|
|
667
|
+
return {
|
|
668
|
+
directory,
|
|
669
|
+
sessionID: typeof body.sessionID === "string" ? body.sessionID : null,
|
|
670
|
+
createdAt: Date.now(),
|
|
671
|
+
expiresAt: expiry(body.ttlMinutes),
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function newId(prefix: string): string {
|
|
676
|
+
return `${prefix}_${randomToken(6)}`
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
async function control(request: IncomingMessage, response: ServerResponse, token: string): Promise<void> {
|
|
680
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1")
|
|
681
|
+
const method = request.method ?? "GET"
|
|
682
|
+
const auth = request.headers.authorization ?? ""
|
|
683
|
+
|
|
684
|
+
// Ingest de los servicios: su propio token, no el del daemon.
|
|
685
|
+
if (url.pathname === "/v1/ingest" && method === "POST") {
|
|
686
|
+
const service = registry.services.find((entry) => auth === `Bearer ${entry.ingestToken}`)
|
|
687
|
+
if (!service) return send(response, 401, { error: "unauthorized" })
|
|
688
|
+
const body = parseBody(await readBody(request), "application/json")
|
|
689
|
+
const payload = (body.payload && typeof body.payload === "object" ? body.payload : body) as Record<string, unknown>
|
|
690
|
+
const result = await ingest(service.directory, {
|
|
691
|
+
source: typeof body.source === "string" ? body.source : `service:${service.name}`,
|
|
692
|
+
...(typeof body.type === "string" ? { type: body.type } : {}),
|
|
693
|
+
...(typeof body.eventID === "string" ? { eventID: body.eventID } : {}),
|
|
694
|
+
payload,
|
|
695
|
+
})
|
|
696
|
+
return send(response, result.ok ? 202 : 502, result)
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
if (auth !== `Bearer ${token}`) return send(response, 401, { error: "unauthorized" })
|
|
700
|
+
const body = method === "POST" ? (parseBody(await readBody(request), "application/json") as Record<string, unknown>) : {}
|
|
701
|
+
const [, , kind, id, action] = url.pathname.split("/")
|
|
702
|
+
|
|
703
|
+
if (url.pathname === "/v1/health") return send(response, 200, { ok: true, version: VERSION, pid: process.pid, startedAt: info.startedAt })
|
|
704
|
+
|
|
705
|
+
if (url.pathname === "/v1/state") {
|
|
706
|
+
await knownHostname()
|
|
707
|
+
return send(response, 200, {
|
|
708
|
+
version: VERSION,
|
|
709
|
+
pid: process.pid,
|
|
710
|
+
startedAt: info.startedAt,
|
|
711
|
+
ports: { control: controlPort, hooks: hooksPort },
|
|
712
|
+
tunnel: tunnelStatus(),
|
|
713
|
+
tunnels: registry.tunnels.filter((entry) => !entry.ownerID).map(publicTunnel),
|
|
714
|
+
webhooks: registry.webhooks.map(publicHook),
|
|
715
|
+
services: registry.services.map(publicService),
|
|
716
|
+
servers: Object.keys(registry.servers),
|
|
717
|
+
})
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
if (url.pathname === "/v1/server" && method === "POST") {
|
|
721
|
+
const directory = String(body.directory ?? "")
|
|
722
|
+
const target = body.target as ServerTarget | undefined
|
|
723
|
+
if (!directory || !target?.baseUrl) throw new HttpError(400, "directory and target.baseUrl are required")
|
|
724
|
+
registry.servers[directory] = { baseUrl: target.baseUrl, password: target.password ?? null, updatedAt: Date.now() }
|
|
725
|
+
save()
|
|
726
|
+
return send(response, 200, { ok: true })
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
if (url.pathname === "/v1/shutdown" && method === "POST") {
|
|
730
|
+
send(response, 200, { ok: true })
|
|
731
|
+
setTimeout(() => void shutdown(0), 50)
|
|
732
|
+
return
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
if (kind === "tunnels") {
|
|
736
|
+
if (method === "POST" && !id) {
|
|
737
|
+
const port = Number(body.port)
|
|
738
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) throw new HttpError(400, "port must be 1-65535")
|
|
739
|
+
if (port === controlPort) throw new HttpError(400, "that port is the apex daemon's control port")
|
|
740
|
+
const host = typeof body.host === "string" && body.host.length > 0 ? body.host : "127.0.0.1"
|
|
741
|
+
assertNotServerPort(host, port)
|
|
742
|
+
const proxyProtocol = body.proxyProtocol === "v1" || body.proxyProtocol === "v2" ? body.proxyProtocol : undefined
|
|
743
|
+
const entry: TunnelEntry = {
|
|
744
|
+
kind: "tunnel",
|
|
745
|
+
id: newId("tun"),
|
|
746
|
+
...owned(body),
|
|
747
|
+
route: pickRoute(body.name),
|
|
748
|
+
target: `${host}:${port}`,
|
|
749
|
+
...(proxyProtocol ? { proxyProtocol } : {}),
|
|
750
|
+
}
|
|
751
|
+
registry.tunnels.push(entry)
|
|
752
|
+
save()
|
|
753
|
+
void syncRoutes()
|
|
754
|
+
await knownHostname()
|
|
755
|
+
return send(response, 201, { ...publicTunnel(entry), tunnel: tunnelStatus() })
|
|
756
|
+
}
|
|
757
|
+
if (method === "DELETE" && id) {
|
|
758
|
+
const removed = removeTunnel(id) || removeTunnel(registry.tunnels.find((entry) => entry.route === id)?.id ?? "")
|
|
759
|
+
save()
|
|
760
|
+
void syncRoutes()
|
|
761
|
+
return send(response, removed ? 200 : 404, { removed })
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
if (kind === "webhooks") {
|
|
766
|
+
if (method === "POST" && !id) {
|
|
767
|
+
const provider = String(body.provider ?? "") as WebhookProvider
|
|
768
|
+
if (!PROVIDERS.includes(provider)) throw new HttpError(400, `provider must be one of ${PROVIDERS.join(", ")}`)
|
|
769
|
+
const name = String(body.name ?? "")
|
|
770
|
+
if (!/^[\w.-]{1,64}$/.test(name)) throw new HttpError(400, "name: 1-64 letters, digits, dot, dash, underscore")
|
|
771
|
+
if (registry.webhooks.some((hook) => hook.name === name)) throw new HttpError(409, `webhook "${name}" already exists`)
|
|
772
|
+
const given = typeof body.secret === "string" && body.secret.length > 0 ? body.secret : null
|
|
773
|
+
if (!given && (provider === "stripe" || provider === "slack"))
|
|
774
|
+
throw new HttpError(400, `${provider} signs with a secret it gives you: pass it as secret`)
|
|
775
|
+
const secret = given ?? randomToken(32)
|
|
776
|
+
const hookId = newId("hook")
|
|
777
|
+
mkdirSync(join(paths.home, "secrets"), { recursive: true, mode: 0o700 })
|
|
778
|
+
const secretFile = join(paths.home, "secrets", `${hookId}.secret`)
|
|
779
|
+
writePrivate(secretFile, secret)
|
|
780
|
+
const route = pickRoute(undefined)
|
|
781
|
+
const hook: WebhookEntry = {
|
|
782
|
+
kind: "webhook",
|
|
783
|
+
id: hookId,
|
|
784
|
+
...owned(body),
|
|
785
|
+
name,
|
|
786
|
+
provider,
|
|
787
|
+
secret,
|
|
788
|
+
secretFile,
|
|
789
|
+
...(typeof body.header === "string" ? { header: body.header.toLowerCase() } : {}),
|
|
790
|
+
...(body.encoding === "base64" ? { encoding: "base64" as const } : {}),
|
|
791
|
+
source: typeof body.source === "string" && body.source.length > 0 ? body.source : provider,
|
|
792
|
+
route,
|
|
793
|
+
stats: { ok: 0, rejected: 0, failed: 0, lastAt: null, lastError: null },
|
|
794
|
+
}
|
|
795
|
+
registry.webhooks.push(hook)
|
|
796
|
+
registry.tunnels.push({
|
|
797
|
+
kind: "tunnel",
|
|
798
|
+
id: newId("tun"),
|
|
799
|
+
directory: hook.directory,
|
|
800
|
+
sessionID: hook.sessionID,
|
|
801
|
+
createdAt: hook.createdAt,
|
|
802
|
+
expiresAt: hook.expiresAt,
|
|
803
|
+
route,
|
|
804
|
+
target: `127.0.0.1:${hooksPort}`,
|
|
805
|
+
ownerID: hook.id,
|
|
806
|
+
})
|
|
807
|
+
save()
|
|
808
|
+
void syncRoutes()
|
|
809
|
+
await knownHostname()
|
|
810
|
+
return send(response, 201, { ...publicHook(hook), tunnel: tunnelStatus() })
|
|
811
|
+
}
|
|
812
|
+
if (method === "DELETE" && id) {
|
|
813
|
+
const hook = registry.webhooks.find((entry) => entry.id === id || entry.name === id)
|
|
814
|
+
if (!hook) return send(response, 404, { removed: false })
|
|
815
|
+
removeWebhook(hook)
|
|
816
|
+
save()
|
|
817
|
+
void syncRoutes()
|
|
818
|
+
return send(response, 200, { removed: true })
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
if (kind === "services") {
|
|
823
|
+
const service = id ? registry.services.find((entry) => entry.id === id || entry.name === id) : undefined
|
|
824
|
+
if (method === "POST" && !id) {
|
|
825
|
+
const name = String(body.name ?? "")
|
|
826
|
+
if (!/^[\w.-]{1,64}$/.test(name)) throw new HttpError(400, "name: 1-64 letters, digits, dot, dash, underscore")
|
|
827
|
+
if (registry.services.some((entry) => entry.name === name)) throw new HttpError(409, `service "${name}" already exists (down it first)`)
|
|
828
|
+
const command = String(body.command ?? "")
|
|
829
|
+
if (!command.trim()) throw new HttpError(400, "command is required")
|
|
830
|
+
const port = body.port === undefined || body.port === null ? null : Number(body.port)
|
|
831
|
+
if (port !== null && (!Number.isInteger(port) || port <= 0 || port > 65535)) throw new HttpError(400, "port must be 1-65535")
|
|
832
|
+
if (body.public === true && port === null) throw new HttpError(400, "a public service needs its port")
|
|
833
|
+
if (body.public === true && port !== null) assertNotServerPort("127.0.0.1", port)
|
|
834
|
+
const restart: RestartPolicy = body.restart === "never" || body.restart === "on-failure" ? body.restart : "always"
|
|
835
|
+
const env: Record<string, string> = {}
|
|
836
|
+
for (const [key, value] of Object.entries((body.env ?? {}) as Record<string, unknown>)) env[key] = String(value)
|
|
837
|
+
const base = owned(body)
|
|
838
|
+
const cwd = typeof body.cwd === "string" && body.cwd.length > 0 ? body.cwd : base.directory
|
|
839
|
+
if (!existsSync(cwd)) throw new HttpError(400, `cwd does not exist: ${cwd}`)
|
|
840
|
+
const serviceId = newId("svc")
|
|
841
|
+
const entry: ServiceEntry = {
|
|
842
|
+
kind: "service",
|
|
843
|
+
id: serviceId,
|
|
844
|
+
...base,
|
|
845
|
+
name,
|
|
846
|
+
command,
|
|
847
|
+
cwd,
|
|
848
|
+
env,
|
|
849
|
+
port,
|
|
850
|
+
restart,
|
|
851
|
+
ingestToken: randomToken(24),
|
|
852
|
+
logFile: join(paths.logs, `${name}.log`),
|
|
853
|
+
pid: null,
|
|
854
|
+
bootAt: null,
|
|
855
|
+
status: "starting",
|
|
856
|
+
restarts: 0,
|
|
857
|
+
lastExit: null,
|
|
858
|
+
}
|
|
859
|
+
registry.services.push(entry)
|
|
860
|
+
if (body.public === true && port !== null) {
|
|
861
|
+
registry.tunnels.push({
|
|
862
|
+
kind: "tunnel",
|
|
863
|
+
id: newId("tun"),
|
|
864
|
+
directory: base.directory,
|
|
865
|
+
sessionID: base.sessionID,
|
|
866
|
+
createdAt: base.createdAt,
|
|
867
|
+
expiresAt: base.expiresAt,
|
|
868
|
+
route: pickRoute(body.route),
|
|
869
|
+
target: `127.0.0.1:${port}`,
|
|
870
|
+
...(body.proxyProtocol === "v1" || body.proxyProtocol === "v2" ? { proxyProtocol: body.proxyProtocol } : {}),
|
|
871
|
+
ownerID: serviceId,
|
|
872
|
+
})
|
|
873
|
+
await knownHostname()
|
|
874
|
+
void syncRoutes()
|
|
875
|
+
}
|
|
876
|
+
save()
|
|
877
|
+
startService(entry)
|
|
878
|
+
return send(response, 201, { ...publicService(entry), tunnel: tunnelStatus() })
|
|
879
|
+
}
|
|
880
|
+
if (!service) return send(response, 404, { error: "no such service" })
|
|
881
|
+
if (method === "DELETE") {
|
|
882
|
+
removeService(service)
|
|
883
|
+
save()
|
|
884
|
+
void syncRoutes()
|
|
885
|
+
return send(response, 200, { removed: true })
|
|
886
|
+
}
|
|
887
|
+
if (method === "POST" && action === "restart") {
|
|
888
|
+
stopService(service)
|
|
889
|
+
service.restarts = 0
|
|
890
|
+
service.status = "starting"
|
|
891
|
+
setTimeout(() => startService(service), 1000)
|
|
892
|
+
return send(response, 200, { restarting: true })
|
|
893
|
+
}
|
|
894
|
+
if (method === "GET" && action === "logs") {
|
|
895
|
+
const lines = Math.min(Math.max(Number(url.searchParams.get("lines") ?? 100) || 100, 1), 2000)
|
|
896
|
+
let text = ""
|
|
897
|
+
try {
|
|
898
|
+
const data = readFileSync(service.logFile, "utf8")
|
|
899
|
+
text = data.split("\n").slice(-lines - 1).join("\n")
|
|
900
|
+
} catch {
|
|
901
|
+
text = ""
|
|
902
|
+
}
|
|
903
|
+
return send(response, 200, { file: service.logFile, status: service.status, text })
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
return send(response, 404, { error: `no route ${method} ${url.pathname}` })
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/** Webhooks: el Host (lo elige el visitante) solo SELECCIONA el webhook; la firma decide. */
|
|
911
|
+
async function hooks(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
912
|
+
const route = (request.headers.host ?? "").split(":")[0]!.split(".")[0]!.toLowerCase()
|
|
913
|
+
const hook = registry.webhooks.find((entry) => entry.route === route)
|
|
914
|
+
if (!hook) return send(response, 404, { error: "unknown webhook" })
|
|
915
|
+
if (request.method !== "POST") return send(response, 405, { error: "POST only" })
|
|
916
|
+
const body = await readBody(request)
|
|
917
|
+
const headers = lowerHeaders(request)
|
|
918
|
+
const url = new URL(request.url ?? "/", "https://webhook.invalid")
|
|
919
|
+
const verdict = verify(hook, headers, body, url)
|
|
920
|
+
hook.stats.lastAt = Date.now()
|
|
921
|
+
if (!verdict.ok) {
|
|
922
|
+
hook.stats.rejected++
|
|
923
|
+
hook.stats.lastError = verdict.reason ?? "rejected"
|
|
924
|
+
save()
|
|
925
|
+
return send(response, 401, { error: "invalid signature" })
|
|
926
|
+
}
|
|
927
|
+
const payload = parseBody(body, headers["content-type"])
|
|
928
|
+
const challenge = slackChallenge(hook, payload)
|
|
929
|
+
if (challenge !== null) return send(response, 200, challenge, "text/plain")
|
|
930
|
+
const result = await ingest(hook.directory, toIngest(hook, headers, payload))
|
|
931
|
+
if (result.ok) {
|
|
932
|
+
hook.stats.ok++
|
|
933
|
+
hook.stats.lastError = null
|
|
934
|
+
} else {
|
|
935
|
+
hook.stats.failed++
|
|
936
|
+
hook.stats.lastError = result.error ?? `ingest ${result.status}`
|
|
937
|
+
}
|
|
938
|
+
save()
|
|
939
|
+
// 503: el emisor reintenta (Stripe, Slack); el agente no se entera si OpenCode no está.
|
|
940
|
+
return send(response, result.ok ? 202 : 503, result.ok ? { ok: true } : { ok: false })
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
function wrap(handler: (request: IncomingMessage, response: ServerResponse) => Promise<void>) {
|
|
944
|
+
return (request: IncomingMessage, response: ServerResponse) => {
|
|
945
|
+
handler(request, response).catch((error) => {
|
|
946
|
+
const status = error instanceof HttpError ? error.status : 500
|
|
947
|
+
if (status === 500) log("request error:", error)
|
|
948
|
+
send(response, status, { error: String((error as Error).message ?? error) })
|
|
949
|
+
})
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
function listen(server: Server, preferred: number | undefined): Promise<number> {
|
|
954
|
+
return new Promise((resolve, reject) => {
|
|
955
|
+
const attempt = (port: number) => {
|
|
956
|
+
server.once("error", (error: NodeJS.ErrnoException) => {
|
|
957
|
+
if (port !== 0 && error.code === "EADDRINUSE") attempt(0)
|
|
958
|
+
else reject(error)
|
|
959
|
+
})
|
|
960
|
+
server.listen(port, "127.0.0.1", () => {
|
|
961
|
+
const address = server.address()
|
|
962
|
+
resolve(typeof address === "object" && address ? address.port : port)
|
|
963
|
+
})
|
|
964
|
+
}
|
|
965
|
+
attempt(preferred ?? 0)
|
|
966
|
+
})
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
// ============================================================================
|
|
970
|
+
// Arranque y parada
|
|
971
|
+
// ============================================================================
|
|
972
|
+
|
|
973
|
+
let info: DaemonInfo
|
|
974
|
+
let controlServer: Server
|
|
975
|
+
let hooksServer: Server
|
|
976
|
+
let sweeper: ReturnType<typeof setInterval>
|
|
977
|
+
let closing = false
|
|
978
|
+
|
|
979
|
+
async function shutdown(code: number): Promise<never> {
|
|
980
|
+
if (!closing) {
|
|
981
|
+
closing = true
|
|
982
|
+
log("shutting down")
|
|
983
|
+
clearInterval(sweeper)
|
|
984
|
+
// Los servicios siguen vivos (desacoplados): el próximo daemon los adopta.
|
|
985
|
+
try {
|
|
986
|
+
await tunnel.connection?.close()
|
|
987
|
+
await tunnel.client?.dispose()
|
|
988
|
+
} catch {
|
|
989
|
+
// nada que hacer
|
|
990
|
+
}
|
|
991
|
+
controlServer?.close()
|
|
992
|
+
hooksServer?.close()
|
|
993
|
+
save()
|
|
994
|
+
for (const file of [paths.info, paths.lock]) {
|
|
995
|
+
try {
|
|
996
|
+
if (file === paths.info && existsSync(file) && JSON.parse(readFileSync(file, "utf8")).pid !== process.pid) continue
|
|
997
|
+
unlinkSync(file)
|
|
998
|
+
} catch {
|
|
999
|
+
// ya no estaba
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
process.exit(code)
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
async function main(): Promise<void> {
|
|
1007
|
+
if (!acquireLock()) {
|
|
1008
|
+
log("another apex daemon is running")
|
|
1009
|
+
process.exit(0)
|
|
1010
|
+
}
|
|
1011
|
+
const token = randomToken(24)
|
|
1012
|
+
const previous = registry.ports ?? {}
|
|
1013
|
+
controlServer = createServer(wrap((request, response) => control(request, response, token)))
|
|
1014
|
+
hooksServer = createServer(wrap(hooks))
|
|
1015
|
+
controlPort = await listen(controlServer, previous.control)
|
|
1016
|
+
hooksPort = await listen(hooksServer, previous.hooks)
|
|
1017
|
+
const portsChanged = previous.control !== undefined && previous.control !== controlPort
|
|
1018
|
+
registry.ports = { control: controlPort, hooks: hooksPort }
|
|
1019
|
+
info = { pid: process.pid, port: controlPort, token, version: VERSION, startedAt: Date.now() }
|
|
1020
|
+
writePrivate(paths.info, JSON.stringify(info))
|
|
1021
|
+
save()
|
|
1022
|
+
log(`apex daemon ${VERSION} pid ${process.pid} · control 127.0.0.1:${controlPort} · hooks 127.0.0.1:${hooksPort}`)
|
|
1023
|
+
|
|
1024
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => void shutdown(0))
|
|
1025
|
+
process.on("uncaughtException", (error) => log("uncaught:", error))
|
|
1026
|
+
process.on("unhandledRejection", (error) => log("unhandled:", error))
|
|
1027
|
+
|
|
1028
|
+
resumeServices(portsChanged)
|
|
1029
|
+
// Carga el SDK ya: si apex se actualiza, su directorio viejo puede desaparecer.
|
|
1030
|
+
tunnel.client = await loadClient().catch((error) => {
|
|
1031
|
+
tunnel.lastError = `OpenTunnel SDK unavailable: ${String((error as Error).message ?? error)}`
|
|
1032
|
+
log(tunnel.lastError)
|
|
1033
|
+
return null
|
|
1034
|
+
})
|
|
1035
|
+
if (registry.tunnels.length > 0) void syncRoutes()
|
|
1036
|
+
sweeper = setInterval(sweep, SWEEP_MS)
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
void main()
|