opencode-apex 0.6.0 → 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/core/kdbx.ts ADDED
@@ -0,0 +1,374 @@
1
+ /**
2
+ * Apex Cred — integración KDBX (KeePass 2.x).
3
+ *
4
+ * Permite usar un fichero .kdbx como almacén de credenciales:
5
+ * - interoperable con KeePassXC / KeePass / otras apps;
6
+ * - todos los valores secretos se extraen para la redacción del contexto;
7
+ * - el agente puede referenciar credenciales por nombre sin ver el secreto.
8
+ *
9
+ * KDBX4 usa Argon2; configuramos kdbxweb con hash-wasm (WASM puro, sin addon nativo).
10
+ */
11
+
12
+ import { argon2d, argon2id } from "hash-wasm"
13
+ import * as kdbxweb from "kdbxweb"
14
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
15
+ import { dirname } from "node:path"
16
+
17
+ export interface KdbxEntryRecord {
18
+ /** Nombre estable en apex (título de la entrada). */
19
+ name: string
20
+ username: string
21
+ password: string
22
+ url: string
23
+ notes: string
24
+ /** Campos personalizados (valor en claro). */
25
+ fields: Record<string, string>
26
+ /** Nombres de campos personalizados protegidos/secreto. */
27
+ protectedFields: string[]
28
+ /** Tipo lógico opcional: ssh, http-bearer, http-basic, api-key, generic... */
29
+ kind: string
30
+ /** UUID de la entrada KDBX (hex), si viene del fichero. */
31
+ uuid?: string
32
+ /** Grupo dentro del KDBX. */
33
+ group?: string
34
+ }
35
+
36
+ export interface KdbxStore {
37
+ readonly path: string
38
+ readonly entries: () => KdbxEntryRecord[]
39
+ readonly get: (name: string) => KdbxEntryRecord | undefined
40
+ readonly set: (entry: KdbxEntryRecord) => void
41
+ readonly remove: (name: string) => boolean
42
+ readonly save: () => Promise<void>
43
+ readonly reload: () => Promise<void>
44
+ /** Todos los valores secretos (para redacción). */
45
+ readonly secretValues: () => string[]
46
+ readonly close: () => void
47
+ }
48
+
49
+ let argon2Ready = false
50
+
51
+ function ensureArgon2(): void {
52
+ if (argon2Ready) return
53
+ kdbxweb.CryptoEngine.setArgon2Impl(
54
+ async (password, salt, memory, iterations, length, parallelism, type, version) => {
55
+ const hash = await (type === kdbxweb.CryptoEngine.Argon2TypeArgon2d ? argon2d : argon2id)({
56
+ password: new Uint8Array(password),
57
+ salt: new Uint8Array(salt),
58
+ parallelism,
59
+ iterations,
60
+ memorySize: memory,
61
+ hashLength: length,
62
+ outputType: "binary",
63
+ version,
64
+ })
65
+ return hash.buffer.slice(hash.byteOffset, hash.byteOffset + hash.byteLength) as ArrayBuffer
66
+ },
67
+ )
68
+ argon2Ready = true
69
+ }
70
+
71
+ function toArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffer {
72
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer
73
+ }
74
+
75
+ function readField(entry: kdbxweb.KdbxEntry, key: string): string {
76
+ const v = entry.fields.get(key)
77
+ if (v == null) return ""
78
+ if (v instanceof kdbxweb.ProtectedValue) return v.getText()
79
+ return String(v)
80
+ }
81
+
82
+ function isProtected(entry: kdbxweb.KdbxEntry, key: string): boolean {
83
+ const v = entry.fields.get(key)
84
+ return v instanceof kdbxweb.ProtectedValue
85
+ }
86
+
87
+ const STANDARD_FIELDS = new Set(["Title", "UserName", "Password", "URL", "Notes", "otp", "TOTP Seed", "TOTP Settings"])
88
+
89
+ function entryToRecord(entry: kdbxweb.KdbxEntry, group?: string): KdbxEntryRecord {
90
+ const fields: Record<string, string> = {}
91
+ const protectedFields: string[] = []
92
+ for (const [k, v] of entry.fields.entries()) {
93
+ if (STANDARD_FIELDS.has(k)) continue
94
+ if (v instanceof kdbxweb.ProtectedValue) {
95
+ fields[k] = v.getText()
96
+ protectedFields.push(k)
97
+ } else {
98
+ fields[k] = String(v)
99
+ }
100
+ }
101
+ const kind = fields["apex:kind"] ?? ""
102
+ // No exponer apex:kind como campo custom normal si lo tratamos como metadata interna
103
+ const cleanFields: Record<string, string> = {}
104
+ const cleanProtected: string[] = []
105
+ for (const [k, v] of Object.entries(fields)) {
106
+ if (k === "apex:kind") continue
107
+ cleanFields[k] = v
108
+ if (protectedFields.includes(k)) cleanProtected.push(k)
109
+ }
110
+
111
+ return {
112
+ name: readField(entry, "Title"),
113
+ username: readField(entry, "UserName"),
114
+ password: readField(entry, "Password"),
115
+ url: readField(entry, "URL"),
116
+ notes: readField(entry, "Notes"),
117
+ fields: cleanFields,
118
+ protectedFields: cleanProtected,
119
+ kind,
120
+ uuid: entry.uuid?.toString(),
121
+ group,
122
+ }
123
+ }
124
+
125
+ function applyRecordToEntry(entry: kdbxweb.KdbxEntry, record: KdbxEntryRecord): void {
126
+ entry.fields.set("Title", record.name)
127
+ entry.fields.set("UserName", record.username ?? "")
128
+ entry.fields.set("Password", kdbxweb.ProtectedValue.fromString(record.password ?? ""))
129
+ entry.fields.set("URL", record.url ?? "")
130
+ entry.fields.set("Notes", record.notes ?? "")
131
+
132
+ // Eliminar campos custom antiguos no estándar que ya no están
133
+ for (const k of [...entry.fields.keys()]) {
134
+ if (STANDARD_FIELDS.has(k)) continue
135
+ if (k === "apex:kind") continue
136
+ if (!(k in (record.fields ?? {}))) entry.fields.delete(k)
137
+ }
138
+
139
+ for (const [k, v] of Object.entries(record.fields ?? {})) {
140
+ if (STANDARD_FIELDS.has(k) || k === "apex:kind") continue
141
+ const protect = (record.protectedFields ?? []).includes(k)
142
+ entry.fields.set(k, protect ? kdbxweb.ProtectedValue.fromString(v) : v)
143
+ }
144
+
145
+ if (record.kind) {
146
+ entry.fields.set("apex:kind", record.kind)
147
+ } else {
148
+ entry.fields.delete("apex:kind")
149
+ }
150
+
151
+ entry.times.update()
152
+ }
153
+
154
+ function collectEntries(group: kdbxweb.KdbxGroup, path: string[] = []): KdbxEntryRecord[] {
155
+ const currentPath = group.name ? [...path, group.name] : path
156
+ const out: KdbxEntryRecord[] = []
157
+ for (const entry of group.entries) {
158
+ out.push(entryToRecord(entry, currentPath.join("/")))
159
+ }
160
+ for (const sub of group.groups) {
161
+ out.push(...collectEntries(sub, currentPath))
162
+ }
163
+ return out
164
+ }
165
+
166
+ function findEntry(db: kdbxweb.Kdbx, name: string): { entry: kdbxweb.KdbxEntry; group: kdbxweb.KdbxGroup } | null {
167
+ const walk = (group: kdbxweb.KdbxGroup): { entry: kdbxweb.KdbxEntry; group: kdbxweb.KdbxGroup } | null => {
168
+ for (const entry of group.entries) {
169
+ if (readField(entry, "Title") === name) return { entry, group }
170
+ }
171
+ for (const sub of group.groups) {
172
+ const found = walk(sub)
173
+ if (found) return found
174
+ }
175
+ return null
176
+ }
177
+ for (const g of db.groups) {
178
+ const found = walk(g)
179
+ if (found) return found
180
+ }
181
+ return null
182
+ }
183
+
184
+ export interface OpenKdbxOptions {
185
+ path: string
186
+ password?: string
187
+ keyFile?: string | Uint8Array | ArrayBuffer
188
+ createIfMissing?: boolean
189
+ /** Nombre de DB al crear. */
190
+ dbName?: string
191
+ /** Grupo donde se crean entradas nuevas. */
192
+ group?: string
193
+ }
194
+
195
+ function makeCredentials(password?: string, keyFile?: string | Uint8Array | ArrayBuffer): kdbxweb.Credentials {
196
+ let keyFileBuf: ArrayBuffer | null = null
197
+ if (keyFile) {
198
+ if (typeof keyFile === "string") {
199
+ const raw = readFileSync(keyFile)
200
+ keyFileBuf = toArrayBuffer(raw)
201
+ } else if (keyFile instanceof ArrayBuffer) {
202
+ keyFileBuf = keyFile
203
+ } else {
204
+ keyFileBuf = toArrayBuffer(keyFile)
205
+ }
206
+ }
207
+ const pw = password ? kdbxweb.ProtectedValue.fromString(password) : null
208
+ return new kdbxweb.Credentials(pw, keyFileBuf)
209
+ }
210
+
211
+ export async function openKdbxStore(options: OpenKdbxOptions): Promise<KdbxStore> {
212
+ ensureArgon2()
213
+ const { path } = options
214
+ const credentials = makeCredentials(options.password, options.keyFile)
215
+
216
+ let db: kdbxweb.Kdbx
217
+ if (existsSync(path)) {
218
+ const raw = readFileSync(path)
219
+ db = await kdbxweb.Kdbx.load(toArrayBuffer(raw), credentials)
220
+ } else {
221
+ if (!options.createIfMissing) throw new Error(`KDBX no existe: ${path}`)
222
+ mkdirSync(dirname(path), { recursive: true })
223
+ db = kdbxweb.Kdbx.create(credentials, options.dbName ?? "apex-creds")
224
+ db.meta.recycleBinEnabled = false
225
+ const data = await db.save()
226
+ writeAtomic(path, Buffer.from(data))
227
+ }
228
+ // Almacén gestionado por apex: sin papelera, los borrados son reales.
229
+ db.meta.recycleBinEnabled = false
230
+
231
+ const save = async (): Promise<void> => {
232
+ const data = await db.save()
233
+ writeAtomic(path, Buffer.from(data))
234
+ }
235
+
236
+ const reload = async (): Promise<void> => {
237
+ const raw = readFileSync(path)
238
+ db = await kdbxweb.Kdbx.load(toArrayBuffer(raw), credentials)
239
+ db.meta.recycleBinEnabled = false
240
+ }
241
+
242
+ const entries = (): KdbxEntryRecord[] => {
243
+ const recycle = db.meta.recycleBinUuid
244
+ return db.groups
245
+ .filter((g) => !(recycle && g.uuid.equals(recycle)))
246
+ .flatMap((g) => collectEntries(g))
247
+ }
248
+
249
+ const get = (name: string): KdbxEntryRecord | undefined => entries().find((e) => e.name === name)
250
+
251
+ const resolveGroup = (): kdbxweb.KdbxGroup => {
252
+ const wanted = options.group?.trim()
253
+ if (!wanted) return db.getDefaultGroup()
254
+ const walk = (g: kdbxweb.KdbxGroup): kdbxweb.KdbxGroup | null => {
255
+ if (g.name === wanted) return g
256
+ for (const sub of g.groups) { const f = walk(sub); if (f) return f }
257
+ return null
258
+ }
259
+ for (const g of db.groups) { const f = walk(g); if (f) return f }
260
+ return db.createGroup(db.getDefaultGroup(), wanted)
261
+ }
262
+
263
+ const set = (record: KdbxEntryRecord): void => {
264
+ const found = findEntry(db, record.name)
265
+ if (found) {
266
+ applyRecordToEntry(found.entry, record)
267
+ return
268
+ }
269
+ const group = resolveGroup()
270
+ const entry = db.createEntry(group)
271
+ applyRecordToEntry(entry, record)
272
+ }
273
+
274
+ const remove = (name: string): boolean => {
275
+ const found = findEntry(db, name)
276
+ if (!found) return false
277
+ db.remove(found.entry)
278
+ return true
279
+ }
280
+
281
+ const secretValues = (): string[] => {
282
+ const vals: string[] = []
283
+ const walk = (group: kdbxweb.KdbxGroup): void => {
284
+ for (const entry of group.entries) {
285
+ for (const [k, v] of entry.fields.entries()) {
286
+ if (!(v instanceof kdbxweb.ProtectedValue)) continue
287
+ // Username/URL/Notes no son secretos aunque estén protegidos en algún caso raro
288
+ if (k === "Title") continue
289
+ const text = v.getText()
290
+ if (text) vals.push(text)
291
+ }
292
+ }
293
+ for (const sub of group.groups) walk(sub)
294
+ }
295
+ for (const g of db.groups) walk(g)
296
+ return vals
297
+ }
298
+
299
+ const close = (): void => {
300
+ // kdbxweb no tiene close explícito; soltar referencia
301
+ // @ts-expect-error - permitir GC
302
+ db = undefined
303
+ }
304
+
305
+ return { path, entries, get, set, remove, save, reload, secretValues, close }
306
+ }
307
+
308
+ function writeAtomic(path: string, data: Buffer): void {
309
+ mkdirSync(dirname(path), { recursive: true })
310
+ const tmp = `${path}.tmp.${process.pid}.${Date.now()}`
311
+ // 0600: el fichero está cifrado, pero no hay motivo para que otros usuarios lo lean.
312
+ writeFileSync(tmp, data, { mode: 0o600 })
313
+ renameSync(tmp, path)
314
+ }
315
+
316
+ /** Heurística simple para detectar tipo de credencial. */
317
+ export function inferKind(record: Partial<KdbxEntryRecord>): string {
318
+ if (record.kind) return record.kind
319
+ const url = (record.url ?? "").toLowerCase()
320
+ if (url.startsWith("ssh://")) return "ssh"
321
+ if (url.startsWith("postgres://") || url.startsWith("postgresql://") || url.startsWith("mysql://") || url.startsWith("mongodb://") || url.startsWith("redis://")) return "database"
322
+ if (url.startsWith("http://") || url.startsWith("https://")) {
323
+ if (record.fields?.["Authorization"] || record.protectedFields?.includes("token") || record.fields?.["token"]) return "http-bearer"
324
+ return "http"
325
+ }
326
+ if (record.fields?.["apiKey"] || record.fields?.["apikey"] || record.protectedFields?.includes("apiKey")) return "api-key"
327
+ return "generic"
328
+ }
329
+
330
+ /** Extrae info no secreta para mostrar al agente. */
331
+ export function publicMeta(record: KdbxEntryRecord): Record<string, unknown> {
332
+ const kind = inferKind(record)
333
+ const meta: Record<string, unknown> = {
334
+ name: record.name,
335
+ kind,
336
+ hasPassword: !!record.password,
337
+ hasUsername: !!record.username,
338
+ }
339
+ if (record.url) {
340
+ try {
341
+ const u = new URL(record.url)
342
+ meta.url = `${u.protocol}//${u.host}${u.pathname}`
343
+ if (u.username) meta.urlUsername = u.username
344
+ if (u.port) meta.port = u.port
345
+ meta.host = u.hostname
346
+ meta.protocol = u.protocol.replace(/:$/, "")
347
+ } catch {
348
+ // URL no parseable (puede ser ssh://user@host:port sin formato estándar)
349
+ meta.url = record.url.replace(/:\/\/([^:@/]+):([^@/]+)@/, "://$1:***@")
350
+ }
351
+ }
352
+ if (record.username) meta.username = record.username
353
+ const publicFields = Object.keys(record.fields ?? {}).filter((k) => !(record.protectedFields ?? []).includes(k))
354
+ if (publicFields.length > 0) meta.publicFields = publicFields
355
+ const secretFields = (record.protectedFields ?? []).filter((k) => record.fields?.[k])
356
+ if (secretFields.length > 0) meta.secretFields = secretFields
357
+ if (record.group) meta.group = record.group
358
+ return meta
359
+ }
360
+
361
+ /** Parsea una URI tipo ssh://user:pass@host:port/path en record parcial. */
362
+ export function parseCredentialUri(uri: string): Partial<KdbxEntryRecord> {
363
+ // ssh://user:pass@host:22
364
+ const m = uri.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/(?:([^:@/]*)(?::([^@/]*))?@)?([^/:?#]+)(?::(\d+))?(.*)$/)
365
+ if (!m) return { url: uri }
366
+ const [, scheme, user, pass, host, port, rest] = m
367
+ const rec: Partial<KdbxEntryRecord> = {
368
+ kind: scheme === "ssh" ? "ssh" : scheme === "https" || scheme === "http" ? "http" : scheme,
369
+ username: user ? decodeURIComponent(user) : "",
370
+ password: pass ? decodeURIComponent(pass) : "",
371
+ url: port ? `${scheme}://${host}:${port}${rest ?? ""}` : `${scheme}://${host}${rest ?? ""}`,
372
+ }
373
+ return rec
374
+ }
package/core/tools-run.ts CHANGED
@@ -20,6 +20,7 @@
20
20
 
21
21
  import { Effect } from "effect"
22
22
  import type { Scope } from "effect"
23
+ import { Tool } from "@opencode/plugin/effect"
23
24
  import type { Plugin } from "@opencode/plugin/effect"
24
25
  import type { EventsToolsConfig } from "./config.js"
25
26
 
@@ -140,14 +141,28 @@ export function makeToolsRunner(ctx: Plugin.Context, config: ToolsRunConfig) {
140
141
  if (!found) return fail(`tool not registered in this project: ${tool}`, agent)
141
142
 
142
143
  const sessionID = await session()
144
+ // Contexto sintético. `tool.call` (requerido desde plugin 2.4) delega en
145
+ // otra tool registrada con el MISMO allow/deny de events.tools: una tool
146
+ // no puede alcanzar vía nested call lo que tools.run le negaría directo.
147
+ const context: Parameters<(typeof found)["execute"]>[1] = {
148
+ sessionID: sessionID as never,
149
+ agent: agent as never,
150
+ messageID: `msg_apexrun${Date.now().toString(36)}` as never,
151
+ id: `apex_run_${Date.now().toString(36)}_${++seq}` as never,
152
+ progress: () => Effect.void,
153
+ tool: {
154
+ call: (name, callInput) => {
155
+ const toolError = (message: string) => Effect.fail(new Tool.Error({ message }))
156
+ const nestedBlocked = checkTool(name, config)
157
+ if (nestedBlocked) return toolError(nestedBlocked)
158
+ const nested = tools.find((candidate) => candidate.id === name)
159
+ if (!nested) return toolError(`tool not registered in this project: ${name}`)
160
+ return nested.execute(callInput ?? {}, context)
161
+ },
162
+ },
163
+ }
143
164
  const result = await Effect.runPromise(
144
- found.execute(input.input ?? {}, {
145
- sessionID: sessionID as never,
146
- agent: agent as never,
147
- messageID: `msg_apexrun${Date.now().toString(36)}` as never,
148
- id: `apex_run_${Date.now().toString(36)}_${++seq}` as never,
149
- progress: () => Effect.void,
150
- }),
165
+ found.execute(input.input ?? {}, context),
151
166
  { signal: AbortSignal.timeout(input.timeoutMs ?? config.timeoutMs) },
152
167
  )
153
168
  return {