opencode-apex 0.6.0 → 0.8.1

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.
@@ -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 CHANGED
@@ -3,13 +3,12 @@
3
3
  *
4
4
  * Diferencia con `core/redact.ts`: ese motor detecta POR FORMA (regex con
5
5
  * prefijo conocido: `ghp_…`, `AKIA…`); este almacén conoce el LITERAL exacto
6
- * porque el usuario lo declaró (`/cred set nombre=valor`). Recall 100%, cero
7
- * falsos positivos — no hay heurística ni modelo en el camino caliente.
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
8
  *
9
- * Cada entrada se expone a `core/redact.ts` como un `PatternDefinition` más
10
- * (nombre `cred:<name>`), vía `patterns()` — un GETTER que `createRedactEngine`
11
- * llama en cada `redactText`, así que una alta nueva se aplica sin recompilar
12
- * el motor ni reiniciar el plugin.
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.
13
12
  *
14
13
  * Variantes cubiertas además del literal: URL-encoded, base64 y JSON-escaped
15
14
  * (comillas fuera), porque el mismo secreto reaparece así en comandos,
@@ -18,17 +17,38 @@
18
17
  * Persistencia: `ctx.storage["apex:cred"]`, cada valor cifrado con la misma
19
18
  * clave de apex (`core/crypto.ts`). En memoria se guarda el texto plano —
20
19
  * hace falta para construir los patrones en cada redacción.
20
+ *
21
+ * Soporta entradas ricas (username/password/url/kind/fields) y backing KDBX.
21
22
  */
22
23
 
23
24
  import { decryptSecret, encryptSecret, escapeRegExp } from "./crypto.js"
24
25
  import type { PatternDefinition } from "./patterns.js"
25
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
+
26
42
  export interface CredStore {
27
- /** Guarda o sobreescribe. Lanza si `value` no cumple `minLength`. */
43
+ /** Guarda o sobreescribe. Lanza si ningún valor secreto cumple `minLength`. */
28
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
29
48
  readonly remove: (name: string) => boolean
30
49
  readonly has: (name: string) => boolean
31
50
  readonly list: () => string[]
51
+ readonly entries: () => CredEntry[]
32
52
  /** Patrones vivos para `RedactEngineOptions.patterns` (llamar perezosamente). */
33
53
  readonly patterns: () => PatternDefinition[]
34
54
  /** Payload cifrado por nombre, listo para `ctx.storage.set("apex:cred", …)`. */
@@ -37,6 +57,49 @@ export interface CredStore {
37
57
  readonly load: (serialized: Record<string, string>) => void
38
58
  }
39
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
+
40
103
  /** Variantes del literal que también deben redactarse. */
41
104
  function variantsOf(value: string): string[] {
42
105
  const variants = new Set<string>([value])
@@ -50,6 +113,11 @@ function variantsOf(value: string): string[] {
50
113
  } catch {
51
114
  // no debería fallar nunca con utf8, pero por si acaso
52
115
  }
116
+ try {
117
+ variants.add(Buffer.from(value, "utf8").toString("base64url"))
118
+ } catch {
119
+ // idem
120
+ }
53
121
  // JSON.stringify añade comillas envolventes; solo interesa el cuerpo escapado.
54
122
  const jsonEscaped = JSON.stringify(value).slice(1, -1)
55
123
  variants.add(jsonEscaped)
@@ -79,21 +147,43 @@ export function getActiveCredStore(): CredStore | null {
79
147
 
80
148
  export function createCredStore(options: CredStoreOptions): CredStore {
81
149
  const { key, minLength = 6 } = options
82
- const entries = new Map<string, string>()
150
+ const entries = new Map<string, CredEntry>()
83
151
 
84
- const buildPatterns = (): PatternDefinition[] =>
85
- [...entries.entries()].map(([name, value]) => {
86
- const alternatives = variantsOf(value)
87
- .map(escapeRegExp)
88
- .sort((a, b) => b.length - a.length) // la variante más larga primero (evita cortes parciales)
89
- .join("|")
90
- return {
91
- name: `cred:${name}`,
92
- regex: new RegExp(alternatives, "g"),
93
- confidence: "high" as const,
94
- source: "apex" as const,
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
+ })
95
168
  }
96
- })
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
+ }
97
187
 
98
188
  return {
99
189
  set: (name, value) => {
@@ -104,17 +194,48 @@ export function createCredStore(options: CredStoreOptions): CredStore {
104
194
  `un secreto débil redactaría coincidencias normales del texto`,
105
195
  )
106
196
  }
107
- entries.set(name, value)
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)
108
211
  },
212
+ get: (name) => entries.get(name),
109
213
  remove: (name) => entries.delete(name),
110
214
  has: (name) => entries.has(name),
111
215
  list: () => [...entries.keys()].sort(),
216
+ entries: () => [...entries.values()].map((e) => normalizeEntry(e)),
112
217
  patterns: buildPatterns,
113
- serialize: () => Object.fromEntries([...entries.entries()].map(([name, value]) => [name, encryptSecret(value, key)])),
218
+ serialize: () =>
219
+ Object.fromEntries(
220
+ [...entries.entries()].map(([name, entry]) => [name, encryptSecret(JSON.stringify(entry), key)]),
221
+ ),
114
222
  load: (serialized) => {
115
223
  for (const [name, payload] of Object.entries(serialized)) {
116
- const value = decryptSecret(payload, key)
117
- if (value !== null) entries.set(name, value)
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" }))
118
239
  }
119
240
  },
120
241
  }