opencode-apex 0.5.1 → 0.8.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 +117 -0
- package/README.md +1 -0
- package/advisor.ts +35 -2
- package/browser.ts +26 -0
- package/core/advisor-agent.ts +6 -0
- package/core/advisor-session.ts +184 -3
- package/core/config.ts +91 -0
- package/core/cred-channel.ts +300 -0
- package/core/cred.ts +242 -0
- package/core/kdbx.ts +374 -0
- package/core/redact.ts +4 -2
- package/core/tools-run.ts +22 -7
- package/cred.ts +979 -0
- package/daemon/main.ts +89 -7
- package/daemon/mcp.ts +261 -0
- package/daemon/shared.ts +9 -0
- package/docs/ADVISOR.md +37 -1
- package/docs/CONFIG.md +3 -1
- package/docs/CRED.md +150 -0
- package/docs/ENDPOINTS.md +11 -3
- package/docs/EVENTS.md +42 -0
- package/docs/REDACT.md +5 -0
- package/endpoints.ts +106 -2
- package/index.ts +24 -2
- package/opencode-apex.jsonc +3 -1
- package/package.json +11 -6
- package/redact.ts +7 -3
- package/skills/apex-callbacks/SKILL.md +7 -0
package/core/config.ts
CHANGED
|
@@ -94,6 +94,44 @@ export interface EventsToolsConfig {
|
|
|
94
94
|
timeoutMs: number
|
|
95
95
|
}
|
|
96
96
|
|
|
97
|
+
export interface CredLlmConfig {
|
|
98
|
+
/** Off por defecto: `/cred set` explícito no necesita modelo. Solo habilita `/cred learn`. */
|
|
99
|
+
enabled: boolean
|
|
100
|
+
/** Endpoint OpenAI-compatible de un servidor LOCAL (Ollama, llama.cpp, LM Studio). */
|
|
101
|
+
endpoint: string
|
|
102
|
+
model: string
|
|
103
|
+
timeoutMs: number
|
|
104
|
+
/**
|
|
105
|
+
* Si no está en true, un modelo remoto se rechaza con aviso: el propósito de
|
|
106
|
+
* `/cred learn` es no sacar el secreto de la máquina para identificarlo.
|
|
107
|
+
*/
|
|
108
|
+
allowRemote: boolean
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface CredKdbxConfig {
|
|
112
|
+
/** Usar un fichero .kdbx como almacén principal (interoperable con KeePassXC). */
|
|
113
|
+
enabled: boolean
|
|
114
|
+
/** Ruta al .kdbx. Soporta ~. */
|
|
115
|
+
path: string
|
|
116
|
+
/** Contraseña del .kdbx: literal | env:VAR | file:/ruta. */
|
|
117
|
+
password: string
|
|
118
|
+
/** Fichero de clave opcional. */
|
|
119
|
+
keyFile: string
|
|
120
|
+
/** Crear el .kdbx si no existe. */
|
|
121
|
+
createIfMissing: boolean
|
|
122
|
+
/** Recargar cuando el fichero cambie en disco (interop con apps externas). */
|
|
123
|
+
watch: boolean
|
|
124
|
+
/** Nombre del grupo KDBX donde se guardan entradas creadas por apex. */
|
|
125
|
+
group: string
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface CredConfig {
|
|
129
|
+
/** Secretos más cortos se rechazan (ver core/cred.ts). */
|
|
130
|
+
minLength: number
|
|
131
|
+
llm: CredLlmConfig
|
|
132
|
+
kdbx: CredKdbxConfig
|
|
133
|
+
}
|
|
134
|
+
|
|
97
135
|
export interface AdvisorConfig {
|
|
98
136
|
model?: string
|
|
99
137
|
actions: string[]
|
|
@@ -102,6 +140,7 @@ export interface AdvisorConfig {
|
|
|
102
140
|
|
|
103
141
|
export interface ApexConfig {
|
|
104
142
|
redact: RedactConfig
|
|
143
|
+
cred: CredConfig
|
|
105
144
|
events: EventsConfig
|
|
106
145
|
advisor: AdvisorConfig
|
|
107
146
|
guard: GuardConfigShape
|
|
@@ -129,6 +168,48 @@ const redactConfigSchema = z.object({
|
|
|
129
168
|
.default(() => ({ toolInput: true })),
|
|
130
169
|
})
|
|
131
170
|
|
|
171
|
+
const DEFAULT_CRED_LLM = {
|
|
172
|
+
enabled: false,
|
|
173
|
+
endpoint: "http://127.0.0.1:11434/v1",
|
|
174
|
+
model: "qwen2.5:3b",
|
|
175
|
+
timeoutMs: 4000,
|
|
176
|
+
allowRemote: false,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const DEFAULT_CRED_KDBX = {
|
|
180
|
+
enabled: false,
|
|
181
|
+
path: "~/.config/opencode/apex-creds.kdbx",
|
|
182
|
+
password: "env:APEX_CRED_KDBX_PASSWORD",
|
|
183
|
+
keyFile: "",
|
|
184
|
+
createIfMissing: true,
|
|
185
|
+
watch: true,
|
|
186
|
+
group: "apex",
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const credLlmConfigSchema = z.object({
|
|
190
|
+
enabled: z.boolean().default(DEFAULT_CRED_LLM.enabled),
|
|
191
|
+
endpoint: z.string().default(DEFAULT_CRED_LLM.endpoint),
|
|
192
|
+
model: z.string().default(DEFAULT_CRED_LLM.model),
|
|
193
|
+
timeoutMs: z.number().int().positive().default(DEFAULT_CRED_LLM.timeoutMs),
|
|
194
|
+
allowRemote: z.boolean().default(DEFAULT_CRED_LLM.allowRemote),
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
const credKdbxConfigSchema = z.object({
|
|
198
|
+
enabled: z.boolean().default(DEFAULT_CRED_KDBX.enabled),
|
|
199
|
+
path: z.string().default(DEFAULT_CRED_KDBX.path),
|
|
200
|
+
password: z.string().default(DEFAULT_CRED_KDBX.password),
|
|
201
|
+
keyFile: z.string().default(DEFAULT_CRED_KDBX.keyFile),
|
|
202
|
+
createIfMissing: z.boolean().default(DEFAULT_CRED_KDBX.createIfMissing),
|
|
203
|
+
watch: z.boolean().default(DEFAULT_CRED_KDBX.watch),
|
|
204
|
+
group: z.string().default(DEFAULT_CRED_KDBX.group),
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
const credConfigSchema = z.object({
|
|
208
|
+
minLength: z.number().int().positive().default(6),
|
|
209
|
+
llm: credLlmConfigSchema.default(() => ({ ...DEFAULT_CRED_LLM })),
|
|
210
|
+
kdbx: credKdbxConfigSchema.default(() => ({ ...DEFAULT_CRED_KDBX })),
|
|
211
|
+
})
|
|
212
|
+
|
|
132
213
|
const ruleConditionSchema = z.object({
|
|
133
214
|
field: z.string(),
|
|
134
215
|
operator: z.enum(["equals", "contains", "matches", "gt", "lt", "in", "notIn", "exists", "notExists"]),
|
|
@@ -199,6 +280,11 @@ const advisorConfigSchema = z.object({
|
|
|
199
280
|
location: z.string().optional(),
|
|
200
281
|
// Lee /proc antes de juzgar un kill: de quién es cada PID. Ver core/process-context.ts.
|
|
201
282
|
processContext: z.boolean().default(true),
|
|
283
|
+
// Últimos mensajes de USUARIO (nunca del modelo/tools) de la sesión que pide el
|
|
284
|
+
// permiso, para que el advisor reconozca un permiso ya dado en chat normal —
|
|
285
|
+
// igual que un agente con el contexto completo (p. ej. Claude Code en modo auto).
|
|
286
|
+
conversationContext: z.boolean().default(true),
|
|
287
|
+
conversationMessages: z.number().int().positive().default(10),
|
|
202
288
|
})
|
|
203
289
|
|
|
204
290
|
const guardRuleSchema = z.object({
|
|
@@ -238,6 +324,7 @@ const browserConfigSchema = z.object({
|
|
|
238
324
|
|
|
239
325
|
export const apexConfigSchema = z.object({
|
|
240
326
|
redact: redactConfigSchema.default(() => ({ mode: "strict" as const, patterns: [], bundles: [...DEFAULT_BUNDLES], minConfidence: "medium" as const, allowlist: [], prefix: "[SECRET:", suffix: "]", key: "", restore: { toolInput: true } })),
|
|
327
|
+
cred: credConfigSchema.default(() => ({ minLength: 6, llm: { ...DEFAULT_CRED_LLM }, kdbx: { ...DEFAULT_CRED_KDBX } })),
|
|
241
328
|
events: eventsConfigSchema.default(() => ({ routing: "all" as const, subscriptions: [], server: {}, tools: defaultEventsTools() })),
|
|
242
329
|
advisor: advisorConfigSchema.default(() => ({ actions: [], decisive: false, evaluate: "ask-only" as const, timeoutMs: 10000, processContext: true })),
|
|
243
330
|
guard: guardConfigSchema.default(() => ({
|
|
@@ -259,6 +346,7 @@ export const apexConfigSchema = z.object({
|
|
|
259
346
|
modules: z
|
|
260
347
|
.object({
|
|
261
348
|
redact: z.boolean().optional(),
|
|
349
|
+
cred: z.boolean().optional(),
|
|
262
350
|
events: z.boolean().optional(),
|
|
263
351
|
advisor: z.boolean().optional(),
|
|
264
352
|
guard: z.boolean().optional(),
|
|
@@ -268,6 +356,9 @@ export const apexConfigSchema = z.object({
|
|
|
268
356
|
tempAccess: z.boolean().optional(),
|
|
269
357
|
// Activado por defecto: apex_tunnel/webhook/daemon (el daemon solo se lanza al usarlas).
|
|
270
358
|
endpoints: z.boolean().optional(),
|
|
359
|
+
// Activado por defecto (con events y endpoints): servidor MCP `apex` con MCP Events para
|
|
360
|
+
// los triggers de automations de OpenCode. Lanza el daemon al cargar el plugin.
|
|
361
|
+
automations: z.boolean().optional(),
|
|
271
362
|
})
|
|
272
363
|
.default(() => ({})),
|
|
273
364
|
})
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apex Cred — canales: usar una credencial contra su recurso SIN que el agente
|
|
3
|
+
* vea el secreto.
|
|
4
|
+
*
|
|
5
|
+
* Regla que sostiene todo el módulo: el DESTINO lo fija la credencial, nunca el
|
|
6
|
+
* agente. Si el agente pudiera elegir host/URL, bastaría con apuntar el canal a
|
|
7
|
+
* un servidor suyo para recibir el `Authorization` o la contraseña. Por eso:
|
|
8
|
+
* - http: solo se llama al mismo origen (esquema+host+puerto) que la URL
|
|
9
|
+
* guardada; las redirecciones no se siguen.
|
|
10
|
+
* - ssh: host, puerto y usuario salen de la credencial.
|
|
11
|
+
*
|
|
12
|
+
* La contraseña de ssh viaja por SSH_ASKPASS (OpenSSH ≥ 8.4), no por argv ni
|
|
13
|
+
* por `sshpass`: el script auxiliar no contiene el secreto, solo imprime una
|
|
14
|
+
* variable de entorno del proceso hijo.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { spawn } from "node:child_process"
|
|
18
|
+
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
|
|
19
|
+
import { tmpdir } from "node:os"
|
|
20
|
+
import { join } from "node:path"
|
|
21
|
+
import type { CredEntry } from "./cred.js"
|
|
22
|
+
|
|
23
|
+
export interface ChannelResult {
|
|
24
|
+
ok: boolean
|
|
25
|
+
output: unknown
|
|
26
|
+
/** Cadenas derivadas del secreto que se inyectaron (p. ej. base64 de Basic): a redactar en la salida. */
|
|
27
|
+
injected: string[]
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const MAX_OUTPUT = 20000
|
|
31
|
+
const HTTP_KINDS = new Set(["http", "https", "http-bearer", "http-basic", "api-key"])
|
|
32
|
+
|
|
33
|
+
const limit = (text: string): string =>
|
|
34
|
+
text.length > MAX_OUTPUT ? `${text.slice(0, MAX_OUTPUT)}\n...[truncated]` : text
|
|
35
|
+
|
|
36
|
+
const fail = (output: string): ChannelResult => ({ ok: false, output, injected: [] })
|
|
37
|
+
|
|
38
|
+
export function channelKind(entry: CredEntry, mode?: string): string {
|
|
39
|
+
if (mode && mode !== "auto") return mode
|
|
40
|
+
if (entry.kind && entry.kind !== "generic") return entry.kind
|
|
41
|
+
const url = (entry.url ?? "").toLowerCase()
|
|
42
|
+
if (url.startsWith("ssh://")) return "ssh"
|
|
43
|
+
if (url.startsWith("http://") || url.startsWith("https://")) {
|
|
44
|
+
if (entry.fields?.["token"]) return "http-bearer"
|
|
45
|
+
if (entry.fields?.["apiKey"] || entry.fields?.["apikey"]) return "api-key"
|
|
46
|
+
return entry.username ? "http-basic" : "http-bearer"
|
|
47
|
+
}
|
|
48
|
+
return entry.kind ?? "generic"
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function isSupportedChannel(kind: string): boolean {
|
|
52
|
+
return kind === "ssh" || HTTP_KINDS.has(kind)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Ejemplo de uso (sin secretos) para devolver al agente al abrir el canal. */
|
|
56
|
+
export function channelUsage(kind: string): Record<string, unknown> {
|
|
57
|
+
if (kind === "ssh") return { action: "exec", params: { command: "uname -a", timeoutMs: 30000 } }
|
|
58
|
+
return {
|
|
59
|
+
action: "request",
|
|
60
|
+
params: { method: "GET", path: "/", headers: {}, body: null },
|
|
61
|
+
note: "path/url must stay on the credential's own origin",
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
// HTTP
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
|
|
69
|
+
export interface HttpTarget {
|
|
70
|
+
url: URL
|
|
71
|
+
error?: undefined
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Resuelve el destino de una petición contra el origen de la credencial.
|
|
76
|
+
* Acepta `path` relativo o `url` absoluta; cualquier otro origen se rechaza.
|
|
77
|
+
*/
|
|
78
|
+
export function resolveHttpTarget(
|
|
79
|
+
entry: CredEntry,
|
|
80
|
+
params: Record<string, unknown>,
|
|
81
|
+
): { url: URL } | { error: string } {
|
|
82
|
+
if (!entry.url) return { error: "credential has no URL: set one (/cred set <name> --url https://host) to bind the channel to a host" }
|
|
83
|
+
let base: URL
|
|
84
|
+
try {
|
|
85
|
+
base = new URL(entry.url)
|
|
86
|
+
} catch {
|
|
87
|
+
return { error: "credential URL is not a valid URL" }
|
|
88
|
+
}
|
|
89
|
+
if (base.protocol !== "http:" && base.protocol !== "https:") {
|
|
90
|
+
return { error: `credential URL scheme ${base.protocol} is not http(s)` }
|
|
91
|
+
}
|
|
92
|
+
base.username = ""
|
|
93
|
+
base.password = ""
|
|
94
|
+
const wanted = params.url ?? params.path
|
|
95
|
+
let target: URL
|
|
96
|
+
try {
|
|
97
|
+
target = wanted === undefined || wanted === null || wanted === "" ? base : new URL(String(wanted), base)
|
|
98
|
+
} catch {
|
|
99
|
+
return { error: "invalid url/path" }
|
|
100
|
+
}
|
|
101
|
+
if (target.origin !== base.origin) {
|
|
102
|
+
return { error: `refused: ${target.origin} is not the credential's origin (${base.origin}); the secret is only sent to its own host` }
|
|
103
|
+
}
|
|
104
|
+
if (target.username || target.password) return { error: "refused: userinfo in URL" }
|
|
105
|
+
return { url: target }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Cabeceras de autenticación según el tipo. Devuelve también las cadenas inyectadas. */
|
|
109
|
+
export function authHeaders(
|
|
110
|
+
kind: string,
|
|
111
|
+
entry: CredEntry,
|
|
112
|
+
): { headers: Record<string, string>; injected: string[] } {
|
|
113
|
+
const password = entry.password ?? entry.value ?? ""
|
|
114
|
+
const username = entry.username ?? ""
|
|
115
|
+
const token = entry.fields?.["token"] || password
|
|
116
|
+
const apiKey = entry.fields?.["apiKey"] || entry.fields?.["apikey"] || password
|
|
117
|
+
|
|
118
|
+
if (kind === "api-key") {
|
|
119
|
+
const name = entry.fields?.["header"] || "x-api-key"
|
|
120
|
+
return apiKey ? { headers: { [name]: apiKey }, injected: [apiKey] } : { headers: {}, injected: [] }
|
|
121
|
+
}
|
|
122
|
+
if (kind === "http-basic" || ((kind === "http" || kind === "https") && username && password && !entry.fields?.["token"])) {
|
|
123
|
+
const b64 = Buffer.from(`${username}:${password}`).toString("base64")
|
|
124
|
+
return { headers: { authorization: `Basic ${b64}` }, injected: [b64] }
|
|
125
|
+
}
|
|
126
|
+
if (token) return { headers: { authorization: `Bearer ${token}` }, injected: [token] }
|
|
127
|
+
return { headers: {}, injected: [] }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function httpRequest(kind: string, entry: CredEntry, params: Record<string, unknown>): Promise<ChannelResult> {
|
|
131
|
+
const target = resolveHttpTarget(entry, params)
|
|
132
|
+
if ("error" in target) return fail(target.error)
|
|
133
|
+
|
|
134
|
+
const auth = authHeaders(kind, entry)
|
|
135
|
+
if (auth.injected.length === 0) return fail("credential has no secret to authenticate with")
|
|
136
|
+
|
|
137
|
+
const headers = new Headers()
|
|
138
|
+
const requested = params.headers && typeof params.headers === "object" ? (params.headers as Record<string, unknown>) : {}
|
|
139
|
+
for (const [k, v] of Object.entries(requested)) {
|
|
140
|
+
try {
|
|
141
|
+
headers.set(k, String(v))
|
|
142
|
+
} catch {
|
|
143
|
+
return fail(`invalid header: ${k}`)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
// La credencial manda: el agente no puede sustituir la cabecera de autenticación.
|
|
147
|
+
for (const [k, v] of Object.entries(auth.headers)) headers.set(k, v)
|
|
148
|
+
|
|
149
|
+
const method = String(params.method ?? "GET").toUpperCase()
|
|
150
|
+
let body: string | undefined
|
|
151
|
+
if (params.body !== undefined && params.body !== null && method !== "GET" && method !== "HEAD") {
|
|
152
|
+
if (typeof params.body === "string") body = params.body
|
|
153
|
+
else {
|
|
154
|
+
body = JSON.stringify(params.body)
|
|
155
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json")
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const timeoutMs = Math.min(Math.max(Number(params.timeoutMs) || 30000, 1000), 120000)
|
|
160
|
+
const controller = new AbortController()
|
|
161
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
162
|
+
try {
|
|
163
|
+
// redirect manual: un 30x hacia otro host no debe llevarse la credencial.
|
|
164
|
+
const resp = await fetch(target.url, { method, headers, body, redirect: "manual", signal: controller.signal })
|
|
165
|
+
const text = await resp.text()
|
|
166
|
+
const out: Record<string, unknown> = {
|
|
167
|
+
status: resp.status,
|
|
168
|
+
headers: Object.fromEntries(resp.headers.entries()),
|
|
169
|
+
body: limit(text),
|
|
170
|
+
}
|
|
171
|
+
if (resp.status >= 300 && resp.status < 400) out.note = "redirect not followed (the credential stays on its own origin)"
|
|
172
|
+
return { ok: resp.ok, output: out, injected: auth.injected }
|
|
173
|
+
} catch (error) {
|
|
174
|
+
return { ok: false, output: `http request failed: ${String((error as Error)?.message ?? error)}`, injected: auth.injected }
|
|
175
|
+
} finally {
|
|
176
|
+
clearTimeout(timer)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------------------------------------------------------------------------
|
|
181
|
+
// SSH
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
export interface SshTarget {
|
|
185
|
+
host: string
|
|
186
|
+
port: string
|
|
187
|
+
user: string
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function resolveSshTarget(entry: CredEntry): SshTarget | { error: string } {
|
|
191
|
+
if (!entry.url) return { error: "credential has no URL: expected ssh://host[:port]" }
|
|
192
|
+
const m = /^ssh:\/\/(?:([^:@/]*)(?::[^@/]*)?@)?(\[[0-9a-fA-F:]+\]|[^/:?#\s]+)(?::(\d{1,5}))?(?:[/?#].*)?$/.exec(entry.url.trim())
|
|
193
|
+
if (!m) return { error: "credential URL is not a valid ssh:// URL" }
|
|
194
|
+
const host = m[2]!.replace(/^\[|\]$/g, "")
|
|
195
|
+
let user = entry.username || ""
|
|
196
|
+
if (!user && m[1]) {
|
|
197
|
+
try { user = decodeURIComponent(m[1]) } catch { user = m[1] }
|
|
198
|
+
}
|
|
199
|
+
const port = m[3] ?? "22"
|
|
200
|
+
if (!user) return { error: "credential has no username" }
|
|
201
|
+
// Nada que ssh pueda leer como opción, ni espacios.
|
|
202
|
+
if (/^-/.test(host) || /^-/.test(user) || /[\s@]/.test(user) || /\s/.test(host)) return { error: "invalid ssh host/user" }
|
|
203
|
+
if (Number(port) < 1 || Number(port) > 65535) return { error: "invalid ssh port" }
|
|
204
|
+
return { host, port, user }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function run(
|
|
208
|
+
cmd: string,
|
|
209
|
+
args: string[],
|
|
210
|
+
opts: { env: Record<string, string | undefined>; timeoutMs: number; stdin?: string },
|
|
211
|
+
): Promise<{ code: number; stdout: string; stderr: string; timedOut: boolean }> {
|
|
212
|
+
return new Promise((resolve, reject) => {
|
|
213
|
+
const child = spawn(cmd, args, { env: opts.env as NodeJS.ProcessEnv, stdio: ["pipe", "pipe", "pipe"], detached: true })
|
|
214
|
+
let stdout = ""
|
|
215
|
+
let stderr = ""
|
|
216
|
+
let timedOut = false
|
|
217
|
+
const cap = MAX_OUTPUT * 4
|
|
218
|
+
child.stdout.on("data", (d) => { if (stdout.length < cap) stdout += String(d) })
|
|
219
|
+
child.stderr.on("data", (d) => { if (stderr.length < cap) stderr += String(d) })
|
|
220
|
+
const timer = setTimeout(() => {
|
|
221
|
+
timedOut = true
|
|
222
|
+
try { process.kill(-child.pid!, "SIGKILL") } catch { child.kill("SIGKILL") }
|
|
223
|
+
}, opts.timeoutMs)
|
|
224
|
+
child.on("error", (error) => { clearTimeout(timer); reject(error) })
|
|
225
|
+
child.on("close", (code) => { clearTimeout(timer); resolve({ code: code ?? -1, stdout, stderr, timedOut }) })
|
|
226
|
+
child.stdin.on("error", () => {})
|
|
227
|
+
if (opts.stdin !== undefined) child.stdin.write(opts.stdin)
|
|
228
|
+
child.stdin.end()
|
|
229
|
+
})
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function sshExec(entry: CredEntry, params: Record<string, unknown>): Promise<ChannelResult> {
|
|
233
|
+
const target = resolveSshTarget(entry)
|
|
234
|
+
if ("error" in target) return fail(target.error)
|
|
235
|
+
const command = typeof params.command === "string" ? params.command : ""
|
|
236
|
+
if (!command.trim()) return fail("missing params.command")
|
|
237
|
+
const password = entry.password ?? entry.value ?? ""
|
|
238
|
+
if (!password) return fail("credential has no password")
|
|
239
|
+
const timeoutMs = Math.min(Math.max(Number(params.timeoutMs) || 30000, 1000), 600000)
|
|
240
|
+
|
|
241
|
+
const dir = mkdtempSync(join(tmpdir(), "apex-askpass-"))
|
|
242
|
+
const askpass = join(dir, "askpass.sh")
|
|
243
|
+
try {
|
|
244
|
+
writeFileSync(askpass, '#!/bin/sh\nprintf \'%s\\n\' "$APEX_CRED_ASKPASS_VALUE"\n', { mode: 0o700 })
|
|
245
|
+
chmodSync(askpass, 0o700)
|
|
246
|
+
const r = await run(
|
|
247
|
+
"ssh",
|
|
248
|
+
[
|
|
249
|
+
"-o", "StrictHostKeyChecking=accept-new",
|
|
250
|
+
"-o", "PreferredAuthentications=password,keyboard-interactive",
|
|
251
|
+
"-o", "PubkeyAuthentication=no",
|
|
252
|
+
"-o", "NumberOfPasswordPrompts=1",
|
|
253
|
+
"-o", `ConnectTimeout=${Math.min(30, Math.ceil(timeoutMs / 1000))}`,
|
|
254
|
+
"-p", target.port,
|
|
255
|
+
"-l", target.user,
|
|
256
|
+
"--",
|
|
257
|
+
target.host,
|
|
258
|
+
command,
|
|
259
|
+
],
|
|
260
|
+
{
|
|
261
|
+
env: {
|
|
262
|
+
...process.env,
|
|
263
|
+
SSH_ASKPASS: askpass,
|
|
264
|
+
SSH_ASKPASS_REQUIRE: "force",
|
|
265
|
+
DISPLAY: process.env.DISPLAY ?? "apex:0",
|
|
266
|
+
APEX_CRED_ASKPASS_VALUE: password,
|
|
267
|
+
},
|
|
268
|
+
timeoutMs,
|
|
269
|
+
stdin: typeof params.stdin === "string" ? params.stdin : undefined,
|
|
270
|
+
},
|
|
271
|
+
)
|
|
272
|
+
const out: Record<string, unknown> = { code: r.code, stdout: limit(r.stdout), stderr: limit(r.stderr) }
|
|
273
|
+
if (r.timedOut) out.note = `timed out after ${timeoutMs}ms`
|
|
274
|
+
return { ok: r.code === 0 && !r.timedOut, output: out, injected: [] }
|
|
275
|
+
} catch (error) {
|
|
276
|
+
const code = (error as NodeJS.ErrnoException)?.code
|
|
277
|
+
return fail(code === "ENOENT" ? "ssh client not found on this machine" : `ssh failed: ${String((error as Error)?.message ?? error)}`)
|
|
278
|
+
} finally {
|
|
279
|
+
try { rmSync(dir, { recursive: true, force: true }) } catch {}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ---------------------------------------------------------------------------
|
|
284
|
+
|
|
285
|
+
export async function runChannelAction(
|
|
286
|
+
kind: string,
|
|
287
|
+
entry: CredEntry,
|
|
288
|
+
action: string,
|
|
289
|
+
params: Record<string, unknown>,
|
|
290
|
+
): Promise<ChannelResult> {
|
|
291
|
+
if (kind === "ssh") {
|
|
292
|
+
if (action !== "exec") return fail(`ssh channel supports action "exec" (got "${action}")`)
|
|
293
|
+
return sshExec(entry, params)
|
|
294
|
+
}
|
|
295
|
+
if (HTTP_KINDS.has(kind)) {
|
|
296
|
+
if (action !== "request") return fail(`http channel supports action "request" (got "${action}")`)
|
|
297
|
+
return httpRequest(kind, entry, params)
|
|
298
|
+
}
|
|
299
|
+
return fail(`no channel for kind "${kind}": supported kinds are ssh, http, http-bearer, http-basic, api-key`)
|
|
300
|
+
}
|
package/core/cred.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apex Cred — almacén de secretos declarados explícitamente por el usuario.
|
|
3
|
+
*
|
|
4
|
+
* Diferencia con `core/redact.ts`: ese motor detecta POR FORMA (regex con
|
|
5
|
+
* prefijo conocido: `ghp_…`, `AKIA…`); este almacén conoce el LITERAL exacto
|
|
6
|
+
* porque el usuario lo declaró (`/cred set ...`). Recall 100%, cero falsos
|
|
7
|
+
* positivos — no hay heurística ni modelo en el camino caliente.
|
|
8
|
+
*
|
|
9
|
+
* Cada entrada se expone a `core/redact.ts` como `PatternDefinition`(s) vía
|
|
10
|
+
* `patterns()` — un GETTER que `createRedactEngine` llama en cada `redactText`,
|
|
11
|
+
* así que una alta nueva se aplica sin recompilar el motor ni reiniciar el plugin.
|
|
12
|
+
*
|
|
13
|
+
* Variantes cubiertas además del literal: URL-encoded, base64 y JSON-escaped
|
|
14
|
+
* (comillas fuera), porque el mismo secreto reaparece así en comandos,
|
|
15
|
+
* payloads y logs.
|
|
16
|
+
*
|
|
17
|
+
* Persistencia: `ctx.storage["apex:cred"]`, cada valor cifrado con la misma
|
|
18
|
+
* clave de apex (`core/crypto.ts`). En memoria se guarda el texto plano —
|
|
19
|
+
* hace falta para construir los patrones en cada redacción.
|
|
20
|
+
*
|
|
21
|
+
* Soporta entradas ricas (username/password/url/kind/fields) y backing KDBX.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { decryptSecret, encryptSecret, escapeRegExp } from "./crypto.js"
|
|
25
|
+
import type { PatternDefinition } from "./patterns.js"
|
|
26
|
+
|
|
27
|
+
export interface CredEntry {
|
|
28
|
+
name: string
|
|
29
|
+
/** Secreto genérico/legacy (equivale a password si no hay password). */
|
|
30
|
+
value?: string
|
|
31
|
+
username?: string
|
|
32
|
+
password?: string
|
|
33
|
+
url?: string
|
|
34
|
+
notes?: string
|
|
35
|
+
kind?: string
|
|
36
|
+
/** Campos personalizados. */
|
|
37
|
+
fields?: Record<string, string>
|
|
38
|
+
/** Nombres de campos personalizados que son secretos. */
|
|
39
|
+
protectedFields?: string[]
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CredStore {
|
|
43
|
+
/** Guarda o sobreescribe. Lanza si ningún valor secreto cumple `minLength`. */
|
|
44
|
+
readonly set: (name: string, value: string) => void
|
|
45
|
+
/** Guarda entrada rica. */
|
|
46
|
+
readonly setEntry: (entry: CredEntry) => void
|
|
47
|
+
readonly get: (name: string) => CredEntry | undefined
|
|
48
|
+
readonly remove: (name: string) => boolean
|
|
49
|
+
readonly has: (name: string) => boolean
|
|
50
|
+
readonly list: () => string[]
|
|
51
|
+
readonly entries: () => CredEntry[]
|
|
52
|
+
/** Patrones vivos para `RedactEngineOptions.patterns` (llamar perezosamente). */
|
|
53
|
+
readonly patterns: () => PatternDefinition[]
|
|
54
|
+
/** Payload cifrado por nombre, listo para `ctx.storage.set("apex:cred", …)`. */
|
|
55
|
+
readonly serialize: () => Record<string, string>
|
|
56
|
+
/** Carga un payload cifrado previamente persistido (ignora entradas no descifrables). */
|
|
57
|
+
readonly load: (serialized: Record<string, string>) => void
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Valores secretos de una entrada que deben redactarse. */
|
|
61
|
+
export function secretValuesOf(entry: CredEntry): string[] {
|
|
62
|
+
const vals: string[] = []
|
|
63
|
+
const push = (v?: string) => {
|
|
64
|
+
if (v && typeof v === "string") vals.push(v)
|
|
65
|
+
}
|
|
66
|
+
push(entry.password)
|
|
67
|
+
push(entry.value)
|
|
68
|
+
for (const [k, v] of Object.entries(entry.fields ?? {})) {
|
|
69
|
+
if ((entry.protectedFields ?? []).includes(k)) push(v)
|
|
70
|
+
}
|
|
71
|
+
// Si no hay protectedFields explícito pero hay fields, no asumir — solo los marcados.
|
|
72
|
+
return [...new Set(vals)]
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Metadatos públicos (seguros para el agente/modelo). */
|
|
76
|
+
export function publicEntry(entry: CredEntry): Record<string, unknown> {
|
|
77
|
+
const out: Record<string, unknown> = { name: entry.name }
|
|
78
|
+
if (entry.kind) out.kind = entry.kind
|
|
79
|
+
if (entry.username) out.username = entry.username
|
|
80
|
+
out.hasPassword = !!(entry.password || entry.value)
|
|
81
|
+
if (entry.url) {
|
|
82
|
+
try {
|
|
83
|
+
const u = new URL(entry.url)
|
|
84
|
+
// Sin query: ahí suelen viajar tokens (?api_key=…).
|
|
85
|
+
out.url = `${u.protocol}//${u.host}${u.pathname}`
|
|
86
|
+
out.host = u.hostname
|
|
87
|
+
out.protocol = u.protocol.replace(/:$/, "")
|
|
88
|
+
if (u.port) out.port = Number(u.port)
|
|
89
|
+
if (u.username) out.urlUsername = decodeURIComponent(u.username)
|
|
90
|
+
} catch {
|
|
91
|
+
out.url = entry.url.replace(/:\/\/[^@/\s]*@/, "://***@").replace(/[?#].*$/, "")
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const publicFields = Object.keys(entry.fields ?? {}).filter(
|
|
95
|
+
(k) => !(entry.protectedFields ?? []).includes(k),
|
|
96
|
+
)
|
|
97
|
+
if (publicFields.length > 0) out.publicFields = publicFields
|
|
98
|
+
const secretFields = (entry.protectedFields ?? []).filter((k) => entry.fields?.[k])
|
|
99
|
+
if (secretFields.length > 0) out.secretFields = secretFields
|
|
100
|
+
return out
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Variantes del literal que también deben redactarse. */
|
|
104
|
+
function variantsOf(value: string): string[] {
|
|
105
|
+
const variants = new Set<string>([value])
|
|
106
|
+
try {
|
|
107
|
+
variants.add(encodeURIComponent(value))
|
|
108
|
+
} catch {
|
|
109
|
+
// valor no codificable como URI (raro) → se ignora la variante
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
variants.add(Buffer.from(value, "utf8").toString("base64"))
|
|
113
|
+
} catch {
|
|
114
|
+
// no debería fallar nunca con utf8, pero por si acaso
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
variants.add(Buffer.from(value, "utf8").toString("base64url"))
|
|
118
|
+
} catch {
|
|
119
|
+
// idem
|
|
120
|
+
}
|
|
121
|
+
// JSON.stringify añade comillas envolventes; solo interesa el cuerpo escapado.
|
|
122
|
+
const jsonEscaped = JSON.stringify(value).slice(1, -1)
|
|
123
|
+
variants.add(jsonEscaped)
|
|
124
|
+
return [...variants].filter((v) => v.length > 0)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface CredStoreOptions {
|
|
128
|
+
readonly key: Buffer
|
|
129
|
+
/** Secretos más cortos que esto se rechazan: "123" o "admin" redactarían medio contexto. */
|
|
130
|
+
readonly minLength?: number
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Singleton activo, para que `redact.ts` (independiente de `cred.ts`) pueda
|
|
135
|
+
* sumar los literales declarados por el usuario a sus patrones, sin que un
|
|
136
|
+
* módulo dependa del orden de registro del otro.
|
|
137
|
+
*/
|
|
138
|
+
let activeStore: CredStore | null = null
|
|
139
|
+
|
|
140
|
+
export function setActiveCredStore(store: CredStore | null): void {
|
|
141
|
+
activeStore = store
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function getActiveCredStore(): CredStore | null {
|
|
145
|
+
return activeStore
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function createCredStore(options: CredStoreOptions): CredStore {
|
|
149
|
+
const { key, minLength = 6 } = options
|
|
150
|
+
const entries = new Map<string, CredEntry>()
|
|
151
|
+
|
|
152
|
+
const buildPatterns = (): PatternDefinition[] => {
|
|
153
|
+
const patterns: PatternDefinition[] = []
|
|
154
|
+
for (const [name, entry] of entries.entries()) {
|
|
155
|
+
const secrets = secretValuesOf(entry).filter((v) => v.length >= minLength)
|
|
156
|
+
for (let i = 0; i < secrets.length; i++) {
|
|
157
|
+
const value = secrets[i]!
|
|
158
|
+
const alternatives = variantsOf(value)
|
|
159
|
+
.map(escapeRegExp)
|
|
160
|
+
.sort((a, b) => b.length - a.length)
|
|
161
|
+
.join("|")
|
|
162
|
+
patterns.push({
|
|
163
|
+
name: secrets.length === 1 ? `cred:${name}` : `cred:${name}:${i + 1}`,
|
|
164
|
+
regex: new RegExp(alternatives, "g"),
|
|
165
|
+
confidence: "high" as const,
|
|
166
|
+
source: "apex" as const,
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return patterns
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const normalizeEntry = (entry: CredEntry): CredEntry => {
|
|
174
|
+
const clean: CredEntry = { name: entry.name.trim() }
|
|
175
|
+
if (entry.value !== undefined) clean.value = entry.value
|
|
176
|
+
if (entry.username !== undefined) clean.username = entry.username
|
|
177
|
+
if (entry.password !== undefined) clean.password = entry.password
|
|
178
|
+
if (entry.url !== undefined) clean.url = entry.url
|
|
179
|
+
if (entry.notes !== undefined) clean.notes = entry.notes
|
|
180
|
+
if (entry.kind !== undefined) clean.kind = entry.kind
|
|
181
|
+
if (entry.fields !== undefined) clean.fields = { ...entry.fields }
|
|
182
|
+
if (entry.protectedFields !== undefined) clean.protectedFields = [...entry.protectedFields]
|
|
183
|
+
// Compat: si solo viene value, tratarlo como password también para uso en canales
|
|
184
|
+
if (clean.value && !clean.password) clean.password = clean.value
|
|
185
|
+
return clean
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
set: (name, value) => {
|
|
190
|
+
if (!name.trim()) throw new Error("apex cred: el nombre no puede estar vacío")
|
|
191
|
+
if (value.length < minLength) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
`apex cred: el valor es demasiado corto (${value.length} < ${minLength}); ` +
|
|
194
|
+
`un secreto débil redactaría coincidencias normales del texto`,
|
|
195
|
+
)
|
|
196
|
+
}
|
|
197
|
+
entries.set(name, normalizeEntry({ name, value, password: value, kind: "generic" }))
|
|
198
|
+
},
|
|
199
|
+
setEntry: (entry) => {
|
|
200
|
+
if (!entry.name?.trim()) throw new Error("apex cred: el nombre no puede estar vacío")
|
|
201
|
+
const normalized = normalizeEntry(entry)
|
|
202
|
+
const secrets = secretValuesOf(normalized)
|
|
203
|
+
if (secrets.length === 0) throw new Error("apex cred: la entrada no tiene ningún valor secreto")
|
|
204
|
+
if (secrets.every((v) => v.length < minLength)) {
|
|
205
|
+
throw new Error(
|
|
206
|
+
`apex cred: todos los secretos son demasiado cortos (< ${minLength}); ` +
|
|
207
|
+
`un secreto débil redactaría coincidencias normales del texto`,
|
|
208
|
+
)
|
|
209
|
+
}
|
|
210
|
+
entries.set(normalized.name, normalized)
|
|
211
|
+
},
|
|
212
|
+
get: (name) => entries.get(name),
|
|
213
|
+
remove: (name) => entries.delete(name),
|
|
214
|
+
has: (name) => entries.has(name),
|
|
215
|
+
list: () => [...entries.keys()].sort(),
|
|
216
|
+
entries: () => [...entries.values()].map((e) => normalizeEntry(e)),
|
|
217
|
+
patterns: buildPatterns,
|
|
218
|
+
serialize: () =>
|
|
219
|
+
Object.fromEntries(
|
|
220
|
+
[...entries.entries()].map(([name, entry]) => [name, encryptSecret(JSON.stringify(entry), key)]),
|
|
221
|
+
),
|
|
222
|
+
load: (serialized) => {
|
|
223
|
+
for (const [name, payload] of Object.entries(serialized)) {
|
|
224
|
+
const decrypted = decryptSecret(payload, key)
|
|
225
|
+
if (decrypted === null) continue
|
|
226
|
+
try {
|
|
227
|
+
const parsed = JSON.parse(decrypted) as unknown
|
|
228
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && "name" in (parsed as any)) {
|
|
229
|
+
const entry = parsed as CredEntry
|
|
230
|
+
if (!entry.name) entry.name = name
|
|
231
|
+
entries.set(name, normalizeEntry(entry))
|
|
232
|
+
continue
|
|
233
|
+
}
|
|
234
|
+
} catch {
|
|
235
|
+
// legacy: valor plano cifrado
|
|
236
|
+
}
|
|
237
|
+
// Legacy format: decrypted is the raw secret string
|
|
238
|
+
entries.set(name, normalizeEntry({ name, value: decrypted, password: decrypted, kind: "generic" }))
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
}
|
|
242
|
+
}
|