opencode-apex 0.3.0 → 0.5.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 +60 -0
- package/README.md +5 -1
- package/core/config.ts +2 -0
- package/core/daemon-client.ts +157 -0
- package/daemon/main.ts +688 -0
- package/daemon/shared.ts +119 -0
- package/daemon/webhooks.ts +165 -0
- package/docs/CONFIG.md +2 -1
- package/docs/ENDPOINTS.md +64 -0
- package/endpoints.ts +221 -0
- package/index.ts +9 -1
- package/opencode-apex.jsonc +3 -1
- package/package.json +9 -4
- package/skills/apex-callbacks/SKILL.md +3 -2
- package/skills/apex-callbacks/references/reachability.md +3 -1
- package/skills/apex-endpoints/SKILL.md +114 -0
package/daemon/main.ts
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
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
|
+
*
|
|
10
|
+
* Multiplataforma a propósito: sin systemd ni launchd. Lo lanza el plugin desacoplado con
|
|
11
|
+
* el propio binario de OpenCode en modo bun (`BUN_BE_BUN=1`); un lockfile evita dos.
|
|
12
|
+
*
|
|
13
|
+
* Dos listeners en 127.0.0.1: control (token del daemon; nunca se publica) y webhooks
|
|
14
|
+
* (lo único que apunta el túnel). Separarlos es lo que pide OpenTunnel: lo que solo debe
|
|
15
|
+
* ser local, en un listener que nunca se enruta.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
chmodSync,
|
|
20
|
+
closeSync,
|
|
21
|
+
existsSync,
|
|
22
|
+
mkdirSync,
|
|
23
|
+
openSync,
|
|
24
|
+
readFileSync,
|
|
25
|
+
renameSync,
|
|
26
|
+
unlinkSync,
|
|
27
|
+
writeFileSync,
|
|
28
|
+
writeSync,
|
|
29
|
+
} from "node:fs"
|
|
30
|
+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"
|
|
31
|
+
import { join } from "node:path"
|
|
32
|
+
import { rpcUrl, tunnelDirectory } from "../core/server-endpoint.js"
|
|
33
|
+
import {
|
|
34
|
+
daemonPaths,
|
|
35
|
+
emptyRegistry,
|
|
36
|
+
randomRoute,
|
|
37
|
+
randomToken,
|
|
38
|
+
validRouteName,
|
|
39
|
+
type DaemonInfo,
|
|
40
|
+
type ProxyProtocol,
|
|
41
|
+
type Registry,
|
|
42
|
+
type ServerTarget,
|
|
43
|
+
type TunnelEntry,
|
|
44
|
+
type WebhookEntry,
|
|
45
|
+
type WebhookProvider,
|
|
46
|
+
} from "./shared.js"
|
|
47
|
+
import { parseBody, slackChallenge, toIngest, verify, type Headers } from "./webhooks.js"
|
|
48
|
+
|
|
49
|
+
const VERSION = process.env.APEX_DAEMON_VERSION ?? "dev"
|
|
50
|
+
const paths = daemonPaths()
|
|
51
|
+
const IDLE_EXIT_MS = Number(process.env.APEX_DAEMON_IDLE_MINUTES ?? 10) * 60_000
|
|
52
|
+
const MAX_BODY = 1024 * 1024
|
|
53
|
+
const SWEEP_MS = Number(process.env.APEX_DAEMON_SWEEP_MS ?? 15_000)
|
|
54
|
+
const PROVIDERS: readonly WebhookProvider[] = ["github", "stripe", "slack", "hmac", "token"]
|
|
55
|
+
|
|
56
|
+
const log = (...parts: unknown[]) => console.log(new Date().toISOString(), ...parts)
|
|
57
|
+
|
|
58
|
+
// ============================================================================
|
|
59
|
+
// Proceso único
|
|
60
|
+
// ============================================================================
|
|
61
|
+
|
|
62
|
+
function alive(pid: number): boolean {
|
|
63
|
+
try {
|
|
64
|
+
process.kill(pid, 0)
|
|
65
|
+
return true
|
|
66
|
+
} catch (error) {
|
|
67
|
+
return (error as NodeJS.ErrnoException).code === "EPERM"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function acquireLock(): boolean {
|
|
72
|
+
mkdirSync(paths.home, { recursive: true, mode: 0o700 })
|
|
73
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
74
|
+
try {
|
|
75
|
+
const fd = openSync(paths.lock, "wx", 0o600)
|
|
76
|
+
writeSync(fd, String(process.pid))
|
|
77
|
+
closeSync(fd)
|
|
78
|
+
return true
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
|
|
81
|
+
const owner = Number(readFileSync(paths.lock, "utf8").trim())
|
|
82
|
+
if (Number.isInteger(owner) && owner > 0 && owner !== process.pid && alive(owner)) return false
|
|
83
|
+
try {
|
|
84
|
+
unlinkSync(paths.lock)
|
|
85
|
+
} catch {
|
|
86
|
+
// otro proceso ya lo limpió
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return false
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ============================================================================
|
|
94
|
+
// Registro (0600, escritura atómica)
|
|
95
|
+
// ============================================================================
|
|
96
|
+
|
|
97
|
+
function writePrivate(file: string, data: string): void {
|
|
98
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
99
|
+
writeFileSync(tmp, data, { mode: 0o600 })
|
|
100
|
+
renameSync(tmp, file)
|
|
101
|
+
try {
|
|
102
|
+
chmodSync(file, 0o600)
|
|
103
|
+
} catch {
|
|
104
|
+
// Windows: los permisos POSIX no aplican
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function loadRegistry(): Registry {
|
|
109
|
+
try {
|
|
110
|
+
const parsed = JSON.parse(readFileSync(paths.registry, "utf8"))
|
|
111
|
+
return { ...emptyRegistry(), ...parsed }
|
|
112
|
+
} catch {
|
|
113
|
+
return emptyRegistry()
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const registry = loadRegistry()
|
|
118
|
+
const save = () => writePrivate(paths.registry, JSON.stringify(registry, null, 2))
|
|
119
|
+
|
|
120
|
+
// ============================================================================
|
|
121
|
+
// Servidor de OpenCode por proyecto: el daemon llama a events.ingest en local
|
|
122
|
+
// ============================================================================
|
|
123
|
+
|
|
124
|
+
function readPassword(target: ServerTarget): string | null {
|
|
125
|
+
const source = target.password
|
|
126
|
+
if (!source) return null
|
|
127
|
+
if (source.kind === "value") return source.value
|
|
128
|
+
try {
|
|
129
|
+
const record = JSON.parse(readFileSync(source.file, "utf8")) as Record<string, unknown>
|
|
130
|
+
const value = record[source.field]
|
|
131
|
+
return typeof value === "string" ? value : null
|
|
132
|
+
} catch {
|
|
133
|
+
return null
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function ingest(directory: string, input: unknown): Promise<{ ok: boolean; status?: number; error?: string }> {
|
|
138
|
+
const target = registry.servers[directory]
|
|
139
|
+
if (!target) return { ok: false, error: "no OpenCode server known for this project yet (open it in OpenCode once)" }
|
|
140
|
+
const password = readPassword(target)
|
|
141
|
+
const headers: Record<string, string> = { "content-type": "application/json" }
|
|
142
|
+
if (password) headers.authorization = `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`
|
|
143
|
+
try {
|
|
144
|
+
const response = await fetch(rpcUrl(target.baseUrl, "events.ingest", directory), {
|
|
145
|
+
method: "POST",
|
|
146
|
+
headers,
|
|
147
|
+
body: JSON.stringify({ input }),
|
|
148
|
+
signal: AbortSignal.timeout(15_000),
|
|
149
|
+
})
|
|
150
|
+
if (response.ok) return { ok: true, status: response.status }
|
|
151
|
+
return { ok: false, status: response.status, error: (await response.text()).slice(0, 300) }
|
|
152
|
+
} catch (error) {
|
|
153
|
+
return { ok: false, error: String((error as Error).message ?? error) }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ============================================================================
|
|
158
|
+
// Túnel (OpenTunnel SDK, perfil default compartido con OpenCode)
|
|
159
|
+
// ============================================================================
|
|
160
|
+
|
|
161
|
+
type Connection = Awaited<ReturnType<Awaited<ReturnType<typeof loadClient>>["tunnel"]["connect"]>>
|
|
162
|
+
|
|
163
|
+
async function loadClient() {
|
|
164
|
+
const { create } = await import("@opentunnel/client")
|
|
165
|
+
return create()
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const tunnel = {
|
|
169
|
+
client: null as Awaited<ReturnType<typeof loadClient>> | null,
|
|
170
|
+
connection: null as Connection | null,
|
|
171
|
+
hostname: null as string | null,
|
|
172
|
+
state: "idle" as "idle" | "provisioning" | "connecting" | "connected" | "reconnecting" | "error",
|
|
173
|
+
lastError: null as string | null,
|
|
174
|
+
connectedAt: null as number | null,
|
|
175
|
+
queue: Promise.resolve() as Promise<void>,
|
|
176
|
+
retry: null as ReturnType<typeof setTimeout> | null,
|
|
177
|
+
failures: 0,
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
let hooksPort = 0
|
|
181
|
+
let controlPort = 0
|
|
182
|
+
|
|
183
|
+
function routeTable(): Record<string, string | { target: string; proxyProtocol: ProxyProtocol }> {
|
|
184
|
+
const routes: Record<string, string | { target: string; proxyProtocol: ProxyProtocol }> = {}
|
|
185
|
+
for (const entry of registry.tunnels)
|
|
186
|
+
routes[entry.route] = entry.proxyProtocol ? { target: entry.target, proxyProtocol: entry.proxyProtocol } : entry.target
|
|
187
|
+
// Todos los webhooks comparten el listener de webhooks; el Host elige cuál.
|
|
188
|
+
for (const hook of registry.webhooks) routes[hook.route] = `127.0.0.1:${hooksPort}`
|
|
189
|
+
return routes
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Hostname del túnel del dispositivo, leído del disco (`tunnel.json`, lo escribe el SDK cuando
|
|
194
|
+
* el certificado está listo). No pasa por el SDK: mientras `connect` aprovisiona, sus
|
|
195
|
+
* llamadas esperan y una petición de control se quedaría colgada.
|
|
196
|
+
*/
|
|
197
|
+
async function knownHostname(): Promise<string | null> {
|
|
198
|
+
if (tunnel.hostname) return tunnel.hostname
|
|
199
|
+
try {
|
|
200
|
+
const stored = JSON.parse(readFileSync(join(tunnelDirectory(), "default", "tunnel.json"), "utf8")) as { hostname?: unknown }
|
|
201
|
+
if (typeof stored.hostname === "string" && stored.hostname.length > 0) tunnel.hostname = stored.hostname
|
|
202
|
+
} catch {
|
|
203
|
+
// sin túnel todavía
|
|
204
|
+
}
|
|
205
|
+
return tunnel.hostname
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function urlOf(route: string): string | null {
|
|
209
|
+
return tunnel.hostname ? `https://${route}.${tunnel.hostname}` : null
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Aplica el registro al túnel. Serializado: un connect/setRoutes cada vez. */
|
|
213
|
+
function syncRoutes(): Promise<void> {
|
|
214
|
+
tunnel.queue = tunnel.queue.then(applyRoutes, applyRoutes)
|
|
215
|
+
return tunnel.queue
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function applyRoutes(): Promise<void> {
|
|
219
|
+
const routes = routeTable()
|
|
220
|
+
const empty = Object.keys(routes).length === 0
|
|
221
|
+
try {
|
|
222
|
+
if (empty) {
|
|
223
|
+
if (tunnel.connection) {
|
|
224
|
+
const connection = tunnel.connection
|
|
225
|
+
tunnel.connection = null
|
|
226
|
+
await connection.close()
|
|
227
|
+
}
|
|
228
|
+
tunnel.state = "idle"
|
|
229
|
+
return
|
|
230
|
+
}
|
|
231
|
+
if (tunnel.connection) {
|
|
232
|
+
await tunnel.connection.setRoutes(routes)
|
|
233
|
+
return
|
|
234
|
+
}
|
|
235
|
+
tunnel.client ??= await loadClient()
|
|
236
|
+
// Sin identidad, connect crea el túnel del dispositivo (certificado: ~1 min).
|
|
237
|
+
tunnel.state = (await knownHostname()) ? "connecting" : "provisioning"
|
|
238
|
+
const connection = await tunnel.client.tunnel.connect({
|
|
239
|
+
routes,
|
|
240
|
+
onEvent: (event) => {
|
|
241
|
+
if (event.type === "connected") {
|
|
242
|
+
tunnel.state = "connected"
|
|
243
|
+
tunnel.connectedAt = Date.now()
|
|
244
|
+
tunnel.failures = 0
|
|
245
|
+
} else if (event.type === "reconnecting" || event.type === "disconnected") {
|
|
246
|
+
tunnel.state = "reconnecting"
|
|
247
|
+
if (event.type === "disconnected") tunnel.lastError = event.reason
|
|
248
|
+
} else if (event.type === "route-conflict") {
|
|
249
|
+
tunnel.lastError = `route conflict: ${event.routes.join(", ")}`
|
|
250
|
+
} else if (event.type === "stopped" && event.error) {
|
|
251
|
+
tunnel.lastError = event.error
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
})
|
|
255
|
+
tunnel.connection = connection
|
|
256
|
+
tunnel.hostname = connection.tunnel.hostname
|
|
257
|
+
tunnel.state = "connected"
|
|
258
|
+
tunnel.connectedAt = Date.now()
|
|
259
|
+
tunnel.lastError = null
|
|
260
|
+
void connection.closed.then(
|
|
261
|
+
() => onTunnelStopped(connection, null),
|
|
262
|
+
(error) => onTunnelStopped(connection, error),
|
|
263
|
+
)
|
|
264
|
+
// Rutas cambiadas mientras conectaba.
|
|
265
|
+
const now = routeTable()
|
|
266
|
+
if (JSON.stringify(now) !== JSON.stringify(routes)) await connection.setRoutes(now)
|
|
267
|
+
} catch (error) {
|
|
268
|
+
tunnel.state = "error"
|
|
269
|
+
tunnel.lastError = String((error as Error).message ?? error)
|
|
270
|
+
log("tunnel error:", tunnel.lastError)
|
|
271
|
+
scheduleRetry()
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function onTunnelStopped(connection: Connection, error: unknown): void {
|
|
276
|
+
if (tunnel.connection !== connection) return
|
|
277
|
+
tunnel.connection = null
|
|
278
|
+
tunnel.state = "error"
|
|
279
|
+
tunnel.lastError = error ? String((error as Error).message ?? error) : "tunnel closed"
|
|
280
|
+
log("tunnel stopped:", tunnel.lastError)
|
|
281
|
+
scheduleRetry()
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function scheduleRetry(): void {
|
|
285
|
+
if (tunnel.retry || Object.keys(routeTable()).length === 0) return
|
|
286
|
+
const delay = Math.min(1000 * 2 ** tunnel.failures, 60_000)
|
|
287
|
+
tunnel.failures++
|
|
288
|
+
tunnel.retry = setTimeout(() => {
|
|
289
|
+
tunnel.retry = null
|
|
290
|
+
void syncRoutes()
|
|
291
|
+
}, delay)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ============================================================================
|
|
295
|
+
// Altas, bajas y caducidad
|
|
296
|
+
// ============================================================================
|
|
297
|
+
|
|
298
|
+
function expiry(ttlMinutes: unknown): number | null {
|
|
299
|
+
const ttl = Number(ttlMinutes)
|
|
300
|
+
return Number.isFinite(ttl) && ttl > 0 ? Date.now() + ttl * 60_000 : null
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function pickRoute(name: unknown): string {
|
|
304
|
+
if (typeof name === "string" && name.length > 0) {
|
|
305
|
+
const route = name.toLowerCase()
|
|
306
|
+
if (!validRouteName(route)) throw new HttpError(400, `invalid route name "${name}" (lowercase letters, digits, dashes)`)
|
|
307
|
+
if (route in routeTable()) throw new HttpError(409, `route "${route}" already in use`)
|
|
308
|
+
return route
|
|
309
|
+
}
|
|
310
|
+
return randomRoute()
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Nunca publicar el servidor de OpenCode: para eso está su acceso remoto (con password). */
|
|
314
|
+
function assertNotServerPort(host: string, port: number): void {
|
|
315
|
+
for (const target of Object.values(registry.servers)) {
|
|
316
|
+
try {
|
|
317
|
+
const url = new URL(target.baseUrl)
|
|
318
|
+
const local = ["127.0.0.1", "localhost", "[::1]", "0.0.0.0"].includes(url.hostname)
|
|
319
|
+
if (local && ["127.0.0.1", "localhost", "::1"].includes(host) && Number(url.port) === port)
|
|
320
|
+
throw new HttpError(400, "that is the OpenCode server port: use OpenCode remote access (opencode service set remote true)")
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if (error instanceof HttpError) throw error
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function removeTunnel(id: string): boolean {
|
|
328
|
+
const before = registry.tunnels.length
|
|
329
|
+
registry.tunnels = registry.tunnels.filter((entry) => entry.id !== id && entry.route !== id)
|
|
330
|
+
return registry.tunnels.length !== before
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function removeWebhook(hook: WebhookEntry): void {
|
|
334
|
+
registry.webhooks = registry.webhooks.filter((entry) => entry.id !== hook.id)
|
|
335
|
+
try {
|
|
336
|
+
unlinkSync(hook.secretFile)
|
|
337
|
+
} catch {
|
|
338
|
+
// ya no estaba
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
let idleSince: number | null = null
|
|
343
|
+
|
|
344
|
+
function sweep(): void {
|
|
345
|
+
const now = Date.now()
|
|
346
|
+
let changed = false
|
|
347
|
+
for (const entry of [...registry.tunnels]) {
|
|
348
|
+
if (entry.expiresAt !== null && entry.expiresAt <= now) {
|
|
349
|
+
log(`expired tunnel ${entry.route}`)
|
|
350
|
+
changed = removeTunnel(entry.id) || changed
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
for (const hook of [...registry.webhooks]) {
|
|
354
|
+
if (hook.expiresAt !== null && hook.expiresAt <= now) {
|
|
355
|
+
log(`expired webhook ${hook.name}`)
|
|
356
|
+
removeWebhook(hook)
|
|
357
|
+
changed = true
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (changed) {
|
|
361
|
+
save()
|
|
362
|
+
void syncRoutes()
|
|
363
|
+
}
|
|
364
|
+
const empty = registry.tunnels.length === 0 && registry.webhooks.length === 0
|
|
365
|
+
idleSince = empty ? (idleSince ?? now) : null
|
|
366
|
+
if (idleSince !== null && now - idleSince >= IDLE_EXIT_MS) {
|
|
367
|
+
log("idle: nothing to keep, exiting")
|
|
368
|
+
void shutdown(0)
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// ============================================================================
|
|
373
|
+
// HTTP
|
|
374
|
+
// ============================================================================
|
|
375
|
+
|
|
376
|
+
class HttpError extends Error {
|
|
377
|
+
constructor(
|
|
378
|
+
readonly status: number,
|
|
379
|
+
message: string,
|
|
380
|
+
) {
|
|
381
|
+
super(message)
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function readBody(request: IncomingMessage): Promise<Buffer> {
|
|
386
|
+
return new Promise((resolve, reject) => {
|
|
387
|
+
const chunks: Buffer[] = []
|
|
388
|
+
let size = 0
|
|
389
|
+
request.on("data", (chunk: Buffer) => {
|
|
390
|
+
size += chunk.length
|
|
391
|
+
if (size > MAX_BODY) {
|
|
392
|
+
reject(new HttpError(413, "body too large"))
|
|
393
|
+
request.destroy()
|
|
394
|
+
return
|
|
395
|
+
}
|
|
396
|
+
chunks.push(chunk)
|
|
397
|
+
})
|
|
398
|
+
request.on("end", () => resolve(Buffer.concat(chunks)))
|
|
399
|
+
request.on("error", reject)
|
|
400
|
+
})
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function send(response: ServerResponse, status: number, body: unknown, type = "application/json"): void {
|
|
404
|
+
if (response.headersSent) return
|
|
405
|
+
const text = typeof body === "string" ? body : JSON.stringify(body)
|
|
406
|
+
response.writeHead(status, { "content-type": type, "cache-control": "no-store" })
|
|
407
|
+
response.end(text)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function lowerHeaders(request: IncomingMessage): Headers {
|
|
411
|
+
const out: Record<string, string> = {}
|
|
412
|
+
for (const [key, value] of Object.entries(request.headers)) {
|
|
413
|
+
if (typeof value === "string") out[key.toLowerCase()] = value
|
|
414
|
+
else if (Array.isArray(value)) out[key.toLowerCase()] = value.join(", ")
|
|
415
|
+
}
|
|
416
|
+
return out
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Lo que ve el plugin de un webhook: nunca el secreto, solo su fichero. */
|
|
420
|
+
function publicHook(hook: WebhookEntry) {
|
|
421
|
+
const { secret: _secret, ...rest } = hook
|
|
422
|
+
return { ...rest, url: urlOf(hook.route) }
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function publicTunnel(entry: TunnelEntry) {
|
|
426
|
+
return { ...entry, url: urlOf(entry.route) }
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function tunnelStatus() {
|
|
430
|
+
return {
|
|
431
|
+
state: tunnel.state,
|
|
432
|
+
hostname: tunnel.hostname,
|
|
433
|
+
lastError: tunnel.lastError,
|
|
434
|
+
connectedAt: tunnel.connectedAt,
|
|
435
|
+
routes: Object.keys(routeTable()).length,
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function owned(body: Record<string, unknown>) {
|
|
440
|
+
const directory = typeof body.directory === "string" ? body.directory : ""
|
|
441
|
+
if (!directory) throw new HttpError(400, "directory is required")
|
|
442
|
+
return {
|
|
443
|
+
directory,
|
|
444
|
+
sessionID: typeof body.sessionID === "string" ? body.sessionID : null,
|
|
445
|
+
createdAt: Date.now(),
|
|
446
|
+
expiresAt: expiry(body.ttlMinutes),
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function newId(prefix: string): string {
|
|
451
|
+
return `${prefix}_${randomToken(6)}`
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async function control(request: IncomingMessage, response: ServerResponse, token: string): Promise<void> {
|
|
455
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1")
|
|
456
|
+
const method = request.method ?? "GET"
|
|
457
|
+
const auth = request.headers.authorization ?? ""
|
|
458
|
+
|
|
459
|
+
if (auth !== `Bearer ${token}`) return send(response, 401, { error: "unauthorized" })
|
|
460
|
+
const body = method === "POST" ? (parseBody(await readBody(request), "application/json") as Record<string, unknown>) : {}
|
|
461
|
+
const [, , kind, id] = url.pathname.split("/")
|
|
462
|
+
|
|
463
|
+
if (url.pathname === "/v1/health") return send(response, 200, { ok: true, version: VERSION, pid: process.pid, startedAt: info.startedAt })
|
|
464
|
+
|
|
465
|
+
if (url.pathname === "/v1/state") {
|
|
466
|
+
await knownHostname()
|
|
467
|
+
return send(response, 200, {
|
|
468
|
+
version: VERSION,
|
|
469
|
+
pid: process.pid,
|
|
470
|
+
startedAt: info.startedAt,
|
|
471
|
+
ports: { control: controlPort, hooks: hooksPort },
|
|
472
|
+
tunnel: tunnelStatus(),
|
|
473
|
+
tunnels: registry.tunnels.map(publicTunnel),
|
|
474
|
+
webhooks: registry.webhooks.map(publicHook),
|
|
475
|
+
servers: Object.keys(registry.servers),
|
|
476
|
+
})
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
if (url.pathname === "/v1/server" && method === "POST") {
|
|
480
|
+
const directory = String(body.directory ?? "")
|
|
481
|
+
const target = body.target as ServerTarget | undefined
|
|
482
|
+
if (!directory || !target?.baseUrl) throw new HttpError(400, "directory and target.baseUrl are required")
|
|
483
|
+
registry.servers[directory] = { baseUrl: target.baseUrl, password: target.password ?? null, updatedAt: Date.now() }
|
|
484
|
+
save()
|
|
485
|
+
return send(response, 200, { ok: true })
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
if (url.pathname === "/v1/shutdown" && method === "POST") {
|
|
489
|
+
send(response, 200, { ok: true })
|
|
490
|
+
setTimeout(() => void shutdown(0), 50)
|
|
491
|
+
return
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
if (kind === "tunnels") {
|
|
495
|
+
if (method === "POST" && !id) {
|
|
496
|
+
const port = Number(body.port)
|
|
497
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) throw new HttpError(400, "port must be 1-65535")
|
|
498
|
+
if (port === controlPort) throw new HttpError(400, "that port is the apex daemon's control port")
|
|
499
|
+
const host = typeof body.host === "string" && body.host.length > 0 ? body.host : "127.0.0.1"
|
|
500
|
+
assertNotServerPort(host, port)
|
|
501
|
+
const proxyProtocol = body.proxyProtocol === "v1" || body.proxyProtocol === "v2" ? body.proxyProtocol : undefined
|
|
502
|
+
const entry: TunnelEntry = {
|
|
503
|
+
kind: "tunnel",
|
|
504
|
+
id: newId("tun"),
|
|
505
|
+
...owned(body),
|
|
506
|
+
route: pickRoute(body.name),
|
|
507
|
+
target: `${host}:${port}`,
|
|
508
|
+
...(proxyProtocol ? { proxyProtocol } : {}),
|
|
509
|
+
}
|
|
510
|
+
registry.tunnels.push(entry)
|
|
511
|
+
save()
|
|
512
|
+
void syncRoutes()
|
|
513
|
+
await knownHostname()
|
|
514
|
+
return send(response, 201, { ...publicTunnel(entry), tunnel: tunnelStatus() })
|
|
515
|
+
}
|
|
516
|
+
if (method === "DELETE" && id) {
|
|
517
|
+
const removed = removeTunnel(id)
|
|
518
|
+
save()
|
|
519
|
+
void syncRoutes()
|
|
520
|
+
return send(response, removed ? 200 : 404, { removed })
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
if (kind === "webhooks") {
|
|
525
|
+
if (method === "POST" && !id) {
|
|
526
|
+
const provider = String(body.provider ?? "") as WebhookProvider
|
|
527
|
+
if (!PROVIDERS.includes(provider)) throw new HttpError(400, `provider must be one of ${PROVIDERS.join(", ")}`)
|
|
528
|
+
const name = String(body.name ?? "")
|
|
529
|
+
if (!/^[\w.-]{1,64}$/.test(name)) throw new HttpError(400, "name: 1-64 letters, digits, dot, dash, underscore")
|
|
530
|
+
if (registry.webhooks.some((hook) => hook.name === name)) throw new HttpError(409, `webhook "${name}" already exists`)
|
|
531
|
+
const given = typeof body.secret === "string" && body.secret.length > 0 ? body.secret : null
|
|
532
|
+
if (!given && (provider === "stripe" || provider === "slack"))
|
|
533
|
+
throw new HttpError(400, `${provider} signs with a secret it gives you: pass it as secret`)
|
|
534
|
+
const secret = given ?? randomToken(32)
|
|
535
|
+
const hookId = newId("hook")
|
|
536
|
+
mkdirSync(join(paths.home, "secrets"), { recursive: true, mode: 0o700 })
|
|
537
|
+
const secretFile = join(paths.home, "secrets", `${hookId}.secret`)
|
|
538
|
+
writePrivate(secretFile, secret)
|
|
539
|
+
const route = pickRoute(undefined)
|
|
540
|
+
const hook: WebhookEntry = {
|
|
541
|
+
kind: "webhook",
|
|
542
|
+
id: hookId,
|
|
543
|
+
...owned(body),
|
|
544
|
+
name,
|
|
545
|
+
provider,
|
|
546
|
+
secret,
|
|
547
|
+
secretFile,
|
|
548
|
+
...(typeof body.header === "string" ? { header: body.header.toLowerCase() } : {}),
|
|
549
|
+
...(body.encoding === "base64" ? { encoding: "base64" as const } : {}),
|
|
550
|
+
source: typeof body.source === "string" && body.source.length > 0 ? body.source : provider,
|
|
551
|
+
route,
|
|
552
|
+
stats: { ok: 0, rejected: 0, failed: 0, lastAt: null, lastError: null },
|
|
553
|
+
}
|
|
554
|
+
registry.webhooks.push(hook)
|
|
555
|
+
save()
|
|
556
|
+
void syncRoutes()
|
|
557
|
+
await knownHostname()
|
|
558
|
+
return send(response, 201, { ...publicHook(hook), tunnel: tunnelStatus() })
|
|
559
|
+
}
|
|
560
|
+
if (method === "DELETE" && id) {
|
|
561
|
+
const hook = registry.webhooks.find((entry) => entry.id === id || entry.name === id)
|
|
562
|
+
if (!hook) return send(response, 404, { removed: false })
|
|
563
|
+
removeWebhook(hook)
|
|
564
|
+
save()
|
|
565
|
+
void syncRoutes()
|
|
566
|
+
return send(response, 200, { removed: true })
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
return send(response, 404, { error: `no route ${method} ${url.pathname}` })
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** Webhooks: el Host (lo elige el visitante) solo SELECCIONA el webhook; la firma decide. */
|
|
574
|
+
async function hooks(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
575
|
+
const route = (request.headers.host ?? "").split(":")[0]!.split(".")[0]!.toLowerCase()
|
|
576
|
+
const hook = registry.webhooks.find((entry) => entry.route === route)
|
|
577
|
+
if (!hook) return send(response, 404, { error: "unknown webhook" })
|
|
578
|
+
if (request.method !== "POST") return send(response, 405, { error: "POST only" })
|
|
579
|
+
const body = await readBody(request)
|
|
580
|
+
const headers = lowerHeaders(request)
|
|
581
|
+
const url = new URL(request.url ?? "/", "https://webhook.invalid")
|
|
582
|
+
const verdict = verify(hook, headers, body, url)
|
|
583
|
+
hook.stats.lastAt = Date.now()
|
|
584
|
+
if (!verdict.ok) {
|
|
585
|
+
hook.stats.rejected++
|
|
586
|
+
hook.stats.lastError = verdict.reason ?? "rejected"
|
|
587
|
+
save()
|
|
588
|
+
return send(response, 401, { error: "invalid signature" })
|
|
589
|
+
}
|
|
590
|
+
const payload = parseBody(body, headers["content-type"])
|
|
591
|
+
const challenge = slackChallenge(hook, payload)
|
|
592
|
+
if (challenge !== null) return send(response, 200, challenge, "text/plain")
|
|
593
|
+
const result = await ingest(hook.directory, toIngest(hook, headers, payload))
|
|
594
|
+
if (result.ok) {
|
|
595
|
+
hook.stats.ok++
|
|
596
|
+
hook.stats.lastError = null
|
|
597
|
+
} else {
|
|
598
|
+
hook.stats.failed++
|
|
599
|
+
hook.stats.lastError = result.error ?? `ingest ${result.status}`
|
|
600
|
+
}
|
|
601
|
+
save()
|
|
602
|
+
// 503: el emisor reintenta (Stripe, Slack); el agente no se entera si OpenCode no está.
|
|
603
|
+
return send(response, result.ok ? 202 : 503, result.ok ? { ok: true } : { ok: false })
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function wrap(handler: (request: IncomingMessage, response: ServerResponse) => Promise<void>) {
|
|
607
|
+
return (request: IncomingMessage, response: ServerResponse) => {
|
|
608
|
+
handler(request, response).catch((error) => {
|
|
609
|
+
const status = error instanceof HttpError ? error.status : 500
|
|
610
|
+
if (status === 500) log("request error:", error)
|
|
611
|
+
send(response, status, { error: String((error as Error).message ?? error) })
|
|
612
|
+
})
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
function listen(server: Server): Promise<number> {
|
|
617
|
+
return new Promise((resolve, reject) => {
|
|
618
|
+
server.once("error", reject)
|
|
619
|
+
server.listen(0, "127.0.0.1", () => resolve((server.address() as { port: number }).port))
|
|
620
|
+
})
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// ============================================================================
|
|
624
|
+
// Arranque y parada
|
|
625
|
+
// ============================================================================
|
|
626
|
+
|
|
627
|
+
let info: DaemonInfo
|
|
628
|
+
let controlServer: Server
|
|
629
|
+
let hooksServer: Server
|
|
630
|
+
let sweeper: ReturnType<typeof setInterval>
|
|
631
|
+
let closing = false
|
|
632
|
+
|
|
633
|
+
async function shutdown(code: number): Promise<never> {
|
|
634
|
+
if (!closing) {
|
|
635
|
+
closing = true
|
|
636
|
+
log("shutting down")
|
|
637
|
+
clearInterval(sweeper)
|
|
638
|
+
try {
|
|
639
|
+
await tunnel.connection?.close()
|
|
640
|
+
await tunnel.client?.dispose()
|
|
641
|
+
} catch {
|
|
642
|
+
// nada que hacer
|
|
643
|
+
}
|
|
644
|
+
controlServer?.close()
|
|
645
|
+
hooksServer?.close()
|
|
646
|
+
save()
|
|
647
|
+
for (const file of [paths.info, paths.lock]) {
|
|
648
|
+
try {
|
|
649
|
+
if (file === paths.info && existsSync(file) && JSON.parse(readFileSync(file, "utf8")).pid !== process.pid) continue
|
|
650
|
+
unlinkSync(file)
|
|
651
|
+
} catch {
|
|
652
|
+
// ya no estaba
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
process.exit(code)
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
async function main(): Promise<void> {
|
|
660
|
+
if (!acquireLock()) {
|
|
661
|
+
log("another apex daemon is running")
|
|
662
|
+
process.exit(0)
|
|
663
|
+
}
|
|
664
|
+
const token = randomToken(24)
|
|
665
|
+
controlServer = createServer(wrap((request, response) => control(request, response, token)))
|
|
666
|
+
hooksServer = createServer(wrap(hooks))
|
|
667
|
+
controlPort = await listen(controlServer)
|
|
668
|
+
hooksPort = await listen(hooksServer)
|
|
669
|
+
info = { pid: process.pid, port: controlPort, token, version: VERSION, startedAt: Date.now() }
|
|
670
|
+
writePrivate(paths.info, JSON.stringify(info))
|
|
671
|
+
save()
|
|
672
|
+
log(`apex daemon ${VERSION} pid ${process.pid} · control 127.0.0.1:${controlPort} · hooks 127.0.0.1:${hooksPort}`)
|
|
673
|
+
|
|
674
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(signal, () => void shutdown(0))
|
|
675
|
+
process.on("uncaughtException", (error) => log("uncaught:", error))
|
|
676
|
+
process.on("unhandledRejection", (error) => log("unhandled:", error))
|
|
677
|
+
|
|
678
|
+
// Carga el SDK ya: si apex se actualiza, su directorio viejo puede desaparecer.
|
|
679
|
+
tunnel.client = await loadClient().catch((error) => {
|
|
680
|
+
tunnel.lastError = `OpenTunnel SDK unavailable: ${String((error as Error).message ?? error)}`
|
|
681
|
+
log(tunnel.lastError)
|
|
682
|
+
return null
|
|
683
|
+
})
|
|
684
|
+
if (Object.keys(routeTable()).length > 0) void syncRoutes()
|
|
685
|
+
sweeper = setInterval(sweep, SWEEP_MS)
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
void main()
|