opencode-apex 0.2.1 → 0.2.3
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 +102 -48
- package/LICENSE +21 -0
- package/README.md +308 -152
- package/browser/endpoint.ts +4 -1
- package/browser.ts +2 -1
- package/core/compat.ts +13 -12
- package/core/config.ts +14 -3
- package/core/crypto.ts +2 -1
- package/core/rpc.ts +1 -1
- package/core/server-endpoint.ts +1 -1
- package/core/tools-run.ts +7 -7
- package/docs/ADVISOR.md +129 -71
- package/docs/BROWSER.md +185 -158
- package/docs/CONFIG.md +145 -55
- package/docs/EVENTS.md +211 -90
- package/docs/GUARD.md +142 -104
- package/docs/REDACT.md +143 -89
- package/docs/TROUBLESHOOTING.md +237 -189
- package/events.ts +28 -22
- package/index.ts +9 -2
- package/opencode-apex.jsonc +150 -132
- package/package.json +32 -6
- package/redact.ts +5 -4
- package/skills/apex-callbacks/SKILL.md +139 -200
- package/skills/apex-callbacks/references/examples.md +261 -0
- package/skills/apex-callbacks/references/reachability.md +103 -0
- package/skills/apex-callbacks/references/relays.md +116 -0
- package/skills/apex-callbacks/references/run-anywhere.md +133 -0
package/docs/GUARD.md
CHANGED
|
@@ -1,65 +1,88 @@
|
|
|
1
|
-
# Apex Guard —
|
|
1
|
+
# Apex Guard — per-agent permission rules, decided by the plugin
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
> **OpenCode V2 only (>= 2.1).** The guard is a `permission.evaluate` hook of the V2 plugin
|
|
4
|
+
> API.
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
The guard lets you say, per agent, which tools and paths are allowed, denied or must be
|
|
7
|
+
asked about, and it keeps a report of every decision. It is **off by default**
|
|
8
|
+
(`modules.guard`). When you turn it on, it starts in `report` mode: it only records what it
|
|
9
|
+
*would* do.
|
|
7
10
|
|
|
8
|
-
|
|
11
|
+
## Background: OpenCode V2 permissions in 30 seconds
|
|
9
12
|
|
|
10
|
-
|
|
11
|
-
agente al que le falte una.** El mensaje es *«OpenCode's free tier can only be used from
|
|
12
|
-
within OpenCode»*, que suena a otra cosa. Basta una regla:
|
|
13
|
+
(Longer version in [ADVISOR.md § Background](ADVISOR.md#background-how-permissions-work-in-opencode-v2).)
|
|
13
14
|
|
|
14
|
-
|
|
15
|
+
- **Rules.** OpenCode checks each tool call against rules
|
|
16
|
+
`{ action, resource, effect: "allow" | "deny" | "ask" }`. Wildcards `*` are allowed, the
|
|
17
|
+
**last matching rule wins**, and no match means `ask`, which prompts you.
|
|
18
|
+
- **Where rules come from.** The agent's rules come first, then the session's.
|
|
19
|
+
- **Plugins.** They see each call in the `permission.evaluate` hook and may change the
|
|
20
|
+
effect, **except** for calls already denied by those rules. A `deny` in your config ends
|
|
21
|
+
the evaluation before any plugin runs.
|
|
22
|
+
|
|
23
|
+
## Why not just write `deny` rules in the config?
|
|
24
|
+
|
|
25
|
+
Two observed reasons. Each one is enough on its own.
|
|
26
|
+
|
|
27
|
+
**1. A config `deny` on a native tool can get the agent rejected by OpenCode Zen's free
|
|
28
|
+
tier.** A `deny` removes the tool from the agent's toolset. In our tests, a custom agent with
|
|
29
|
+
any native tool removed was refused by the Zen free models with *"OpenCode's free tier can
|
|
30
|
+
only be used from within OpenCode"*, an error that does not hint at the cause. One rule was
|
|
31
|
+
enough:
|
|
32
|
+
|
|
33
|
+
| Custom agent (`agents/*.md` frontmatter) | Result on Zen free models |
|
|
15
34
|
| --- | --- |
|
|
16
|
-
|
|
|
17
|
-
| `temperature`,
|
|
18
|
-
| **`permission: { shell: deny }`** | **
|
|
19
|
-
| **`tools: { shell: false }`** | **
|
|
35
|
+
| no `permission`, or only `allow` / `ask` | OK |
|
|
36
|
+
| `temperature`, own 3 600-character system prompt | OK |
|
|
37
|
+
| **`permission: { shell: deny }`** | **rejected** |
|
|
38
|
+
| **`tools: { shell: false }`** | **rejected** |
|
|
20
39
|
|
|
21
|
-
|
|
22
|
-
(`hindsight_*`, `apex_*`) no dispara nada — comprobado con `nemotron-3-ultra-free` y
|
|
23
|
-
`hindsight_banks_delete_bank`. Esas se siguen denegando en `permission`, que es más
|
|
24
|
-
simple; el guard solo gobierna lo nativo.
|
|
40
|
+
Notes on these observations:
|
|
25
41
|
|
|
26
|
-
|
|
42
|
+
- **Scope.** Only native tools trigger this. Denying MCP or plugin tools (`hindsight_*`,
|
|
43
|
+
`apex_*`) did not. Tested with `nemotron-3-ultra-free` and `hindsight_banks_delete_bank`.
|
|
44
|
+
For those tools, a plain config `deny` is fine.
|
|
45
|
+
- **Exception.** `space-bunny-free` was the only free model not affected.
|
|
46
|
+
- **Not fully explained.** OpenCode's own `explore` agent ships with
|
|
47
|
+
`{ action: "*", resource: "*", effect: "deny" }` (`packages/core/src/plugin/agent.ts`). Its
|
|
48
|
+
toolset is filtered the same way (`registry.snapshot(permissions)` in
|
|
49
|
+
`session/context.ts`), and yet it is *not* rejected. Something else tells built-in agents
|
|
50
|
+
from custom ones.
|
|
51
|
+
- **What is reproducible** is the table above: 3 out of 3 rejections for a `deny` in a custom
|
|
52
|
+
`.md` agent.
|
|
27
53
|
|
|
28
|
-
**
|
|
29
|
-
`{ action: "*", effect: "deny" }` de fábrica (`packages/core/src/plugin/agent.ts`), su
|
|
30
|
-
catálogo se filtra igual que el de cualquiera (`registry.snapshot(permissions)` en
|
|
31
|
-
`session/context.ts`) y aun así **no** lo rechazan. O sea que «toolset recortado» describe
|
|
32
|
-
el patrón pero no es el mecanismo: algo distingue un agente nativo de uno propio. Lo
|
|
33
|
-
medido y reproducible es lo de la tabla — un `deny` en un `.md` propio, 3 de 3 rechazos —,
|
|
34
|
-
y sobre eso se apoya este módulo. La regla práctica no cambia: en tus agentes, ningún
|
|
35
|
-
`deny` sobre herramientas nativas.
|
|
54
|
+
The practical rule: **in your own agents, do not `deny` native tools in the config.**
|
|
36
55
|
|
|
37
|
-
**2.
|
|
56
|
+
**2. A config `deny` never reaches plugins.** OpenCode stops before the hooks:
|
|
38
57
|
|
|
39
58
|
```ts
|
|
40
|
-
// packages/core/src/permission.ts
|
|
41
|
-
if (denied(input, rules)) return { effect: "deny", rules } //
|
|
42
|
-
|
|
59
|
+
// packages/core/src/permission.ts (OpenCode 2.1.1)
|
|
60
|
+
if (denied(input, rules)) return { effect: "deny", rules } // no hooks run
|
|
61
|
+
…
|
|
62
|
+
const event = yield* hooks.trigger("permission", "evaluate", { …, effect })
|
|
43
63
|
```
|
|
44
64
|
|
|
45
|
-
|
|
65
|
+
So a config `deny` cannot be refined per path, cannot be logged, and cannot be reported.
|
|
46
66
|
|
|
47
|
-
**
|
|
48
|
-
|
|
49
|
-
|
|
67
|
+
**The resulting split:**
|
|
68
|
+
- In the config and in `agents/*.md`, native tools only get `allow` or `ask`, so the toolset
|
|
69
|
+
stays complete.
|
|
70
|
+
- The actual prohibition is decided here, in the guard, on the `ask` / `allow` that does
|
|
71
|
+
reach the hook.
|
|
50
72
|
|
|
51
|
-
##
|
|
73
|
+
## Configuration
|
|
52
74
|
|
|
53
75
|
```jsonc
|
|
76
|
+
"modules": { "guard": true },
|
|
54
77
|
"guard": {
|
|
55
|
-
"mode": "enforce", // "report"
|
|
56
|
-
"fallback": "keep", //
|
|
57
|
-
"keep": 500, //
|
|
78
|
+
"mode": "enforce", // default "report": record only, never change the permission
|
|
79
|
+
"fallback": "keep", // default "keep": when no rule matches, leave the permission as it is
|
|
80
|
+
"keep": 500, // default 500: decisions kept in the in-memory report
|
|
58
81
|
"agents": {
|
|
59
82
|
"code-reviewer": [
|
|
60
|
-
{ "action": "write", "effect": "deny", "reason": "code-reviewer
|
|
61
|
-
{ "action": "edit", "effect": "deny", "reason": "code-reviewer
|
|
62
|
-
{ "action": "shell", "effect": "deny", "reason": "code-reviewer
|
|
83
|
+
{ "action": "write", "effect": "deny", "reason": "code-reviewer does not modify the project" },
|
|
84
|
+
{ "action": "edit", "effect": "deny", "reason": "code-reviewer does not modify the project" },
|
|
85
|
+
{ "action": "shell", "effect": "deny", "reason": "code-reviewer does not run commands" },
|
|
63
86
|
{ "action": "write", "resource": ".opencode/code-reviewer/**", "effect": "allow" },
|
|
64
87
|
{ "action": "edit", "resource": ".opencode/code-reviewer/**", "effect": "allow" }
|
|
65
88
|
]
|
|
@@ -67,63 +90,78 @@ la prohibición se decide aquí, sobre el `ask` que sí llega al hook.
|
|
|
67
90
|
}
|
|
68
91
|
```
|
|
69
92
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
93
|
+
How rules are matched:
|
|
94
|
+
|
|
95
|
+
- **The last matching rule wins**, as in OpenCode's own rules. That is what makes "nothing,
|
|
96
|
+
except this path" possible: first the broad `deny`, then the narrow `allow`.
|
|
97
|
+
- **The `"*"` key** holds rules for every agent. They are checked *before* the agent's own
|
|
98
|
+
rules, so an agent's rules can override them.
|
|
99
|
+
- **`action` and `resource` are patterns**, where `*` matches anything, `/` included.
|
|
100
|
+
`resource` defaults to `"*"`. If a call touches several resources, the rule matches when
|
|
101
|
+
any one of them matches.
|
|
102
|
+
- **Relative paths** in `resource` are tested both **as written** and **expanded** against
|
|
103
|
+
the project directory (`~/…` expands to your home), because OpenCode hands over resources
|
|
104
|
+
both ways: `read` arrives as `package.json`, while OpenCode's own rules use absolute paths
|
|
105
|
+
like `/home/…/.opencode/plan/*`. Patterns that contain spaces, such as shell commands,
|
|
106
|
+
are never expanded.
|
|
107
|
+
|
|
108
|
+
### `mode`
|
|
74
109
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
`/home/…/.opencode/plan/*`.
|
|
110
|
+
- `report` (default) records the decision but leaves the permission untouched.
|
|
111
|
+
- `enforce` applies it. Start with `report`, read the report, fix the rules, and only then
|
|
112
|
+
switch to `enforce`. A freshly written guard that starts denying can break a session
|
|
113
|
+
before you have seen a single rule in action.
|
|
80
114
|
|
|
81
115
|
### `fallback`
|
|
82
116
|
|
|
83
|
-
|
|
84
|
-
reescribe en masa lo que decidió el host: con `fallback: "allow"` todos los `ask` pasan a
|
|
85
|
-
`allow`, lo que anula las reglas de `shell` de la config y deja al advisor sin nada que
|
|
86
|
-
juzgar. Pasó durante el desarrollo — un `rm -r` se ejecutó sin preguntar.
|
|
117
|
+
What happens when no rule matches:
|
|
87
118
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
119
|
+
- **`keep`** (default) leaves the permission as OpenCode decided it, and it is the only safe
|
|
120
|
+
default.
|
|
121
|
+
- **Any other value** rewrites every unmatched decision, for every agent. With
|
|
122
|
+
`fallback: "allow"`, every `ask` becomes `allow`: your config's `shell` rules stop
|
|
123
|
+
prompting, and the advisor has nothing left to judge. During development this let an
|
|
124
|
+
`rm -r` run without asking.
|
|
91
125
|
|
|
92
|
-
|
|
126
|
+
A matching `allow` rule **does** upgrade an `ask` to `allow`, on purpose: that is how a
|
|
127
|
+
subagent can write into its own directory without bothering you. The upgrade always needs
|
|
128
|
+
an explicit rule; it never comes from the fallback.
|
|
93
129
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
`"ask"`. Con el guard delante, lo que él resuelve no llega al advisor, y lo que deja en
|
|
97
|
-
`ask` es exactamente lo que el advisor debe juzgar. Al revés, el advisor aprobaría cosas
|
|
98
|
-
que el guard iba a prohibir.
|
|
130
|
+
When the guard denies a call in `enforce` mode, the message reads
|
|
131
|
+
`⛔ apex.guard: <reason> [<rule>]`.
|
|
99
132
|
|
|
100
|
-
|
|
101
|
-
así que un hook que lance corta la cadena y **desactiva silenciosamente los que vengan
|
|
102
|
-
detrás**.
|
|
133
|
+
## Order: guard first, then advisor
|
|
103
134
|
|
|
104
|
-
|
|
135
|
+
The guard registers its hook **before** the [advisor](ADVISOR.md). OpenCode runs the
|
|
136
|
+
`permission.evaluate` hooks in registration order on the same event, and the advisor only
|
|
137
|
+
acts while the effect is still `ask`. So what the guard decides never reaches the advisor,
|
|
138
|
+
and whatever the guard leaves as `ask` is exactly what the advisor should judge. The other
|
|
139
|
+
way round, the advisor would approve calls the guard was about to forbid.
|
|
105
140
|
|
|
106
|
-
|
|
141
|
+
The guard's hook is wrapped in `try/catch`. OpenCode runs the hooks one after another, and a
|
|
142
|
+
hook that throws stops the chain, so every hook registered after it, the advisor included,
|
|
143
|
+
would silently stop running.
|
|
107
144
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
145
|
+
## The advisor itself
|
|
146
|
+
|
|
147
|
+
The `apex-advisor` agent is restricted by the permission rules apex gives it when it creates
|
|
148
|
+
the agent: deny everything except `execute` and `apex_advisor_decide`. Those are ordinary
|
|
149
|
+
OpenCode rules, so they apply whether the guard is on or not. If the advisor's model tries
|
|
150
|
+
`write`, OpenCode denies it before any hook runs. No model is consulted, so no recursion is
|
|
151
|
+
possible.
|
|
115
152
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
153
|
+
> When the guard is on, it applies the same three rules to `apex-advisor` as a second layer.
|
|
154
|
+
> They come from `createDefaultGuardConfig()` and are merged per agent with your
|
|
155
|
+
> `guard.agents`. Defining `guard.agents["apex-advisor"]` yourself replaces them. Before 0.2.2
|
|
156
|
+
> your (empty) `guard.agents` map dropped them by mistake. The advisor's main protection is
|
|
157
|
+
> still its agent ruleset.
|
|
121
158
|
|
|
122
|
-
##
|
|
159
|
+
## The report
|
|
123
160
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
161
|
+
The tool **`apex_guard_report`** returns the recorded decisions:
|
|
162
|
+
- **Inputs:** `limit` (default 40), `agent` and `effect`, which filters by the applied effect.
|
|
163
|
+
- **Output:** text, not JSON. An object with dynamic keys is rejected by OpenCode's tool
|
|
164
|
+
output validator, and a compact table costs far fewer tokens.
|
|
127
165
|
|
|
128
166
|
```
|
|
129
167
|
apex.guard · modo=enforce · fallback=keep · 17 decisiones registradas
|
|
@@ -137,29 +175,29 @@ resumen (allow/deny/ask por agente):
|
|
|
137
175
|
15:08:33 code-reviewer grep guard\.ts → allow
|
|
138
176
|
```
|
|
139
177
|
|
|
140
|
-
|
|
141
|
-
vez por location — el advisor corre en `/tmp/opencode-apex-advisor`, que es otra — y con
|
|
142
|
-
el estado en ámbito de módulo el hook de una instancia anota donde la tool de otra no
|
|
143
|
-
mira, con lo que el informe sale vacío teniendo el guard funcionando.
|
|
144
|
-
|
|
145
|
-
`APEX_GUARD_TRACE=1` escribe además cada decisión por consola.
|
|
146
|
-
|
|
147
|
-
## Rodaje
|
|
178
|
+
(The report text itself is currently in Spanish.)
|
|
148
179
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
180
|
+
- **Lifetime.** The report lives in memory only, and is shared by the whole OpenCode process
|
|
181
|
+
(`Symbol.for("apex.guard.report.v1")`). OpenCode loads the plugin once per directory: the
|
|
182
|
+
advisor runs in another one, `<tmp>/opencode-apex-advisor`. With per-module state, the hook
|
|
183
|
+
of one instance would record decisions where the tool of another never looks, and the
|
|
184
|
+
report would come out empty while the guard was working.
|
|
185
|
+
- **Trace.** Set `APEX_GUARD_TRACE=1` to also print every decision to the server console.
|
|
153
186
|
|
|
154
|
-
##
|
|
187
|
+
## Tell your agents about their toolset
|
|
155
188
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
189
|
+
The guard keeps every tool visible to the model, which is the whole point of not using
|
|
190
|
+
config `deny`. So the model does not know which tools it may use, and it will waste turns on
|
|
191
|
+
calls the guard is going to block. **Recommended:** end each agent's prompt with a short
|
|
192
|
+
"your toolset" section that mirrors its guard rules: what to use, what not to use, and the
|
|
193
|
+
path exceptions. apex does not generate this section for you.
|
|
160
194
|
|
|
161
195
|
## Tests
|
|
162
196
|
|
|
163
|
-
`bun test/guard.test.ts`
|
|
164
|
-
|
|
165
|
-
|
|
197
|
+
`bun test/guard.test.ts` runs 56 checks on the engine:
|
|
198
|
+
- pattern matching;
|
|
199
|
+
- resource expansion for relative and absolute paths;
|
|
200
|
+
- order precedence;
|
|
201
|
+
- the advisor policy;
|
|
202
|
+
- the report ring buffer;
|
|
203
|
+
- the `keep` fallback.
|
package/docs/REDACT.md
CHANGED
|
@@ -1,80 +1,100 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Redact: keep secrets away from the model
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
sustituye por un marcador autocontenido. No existe mapping en memoria: la restauración
|
|
5
|
-
descifra el propio marcador.
|
|
3
|
+
> **OpenCode V2 only (2.1 or newer).**
|
|
6
4
|
|
|
7
|
-
|
|
5
|
+
The redact module finds secrets in everything OpenCode is about to send to the model:
|
|
6
|
+
API keys, tokens, connection strings and so on. It **encrypts** each one and replaces it
|
|
7
|
+
with a readable marker. The model only ever sees the marker. When the model passes that
|
|
8
|
+
marker to a tool, apex decrypts it back, so the tool still receives the real value.
|
|
8
9
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
# p. ej. [SECRET:github-pat:AbC123...]
|
|
12
|
-
```
|
|
13
|
-
|
|
14
|
-
El **nombre del patrón** hace el marcador legible: el usuario sabe *qué* se
|
|
15
|
-
redactó aunque no pueda ver el secreto.
|
|
16
|
-
|
|
17
|
-
- Algoritmo: **AES-256-GCM** (autenticado: un payload manipulado no descifra).
|
|
18
|
-
- `iv`: 12 bytes aleatorios por cifrado · `tag`: 16 bytes · payload en `base64url`.
|
|
19
|
-
- `prefix`/`suffix` configurables (por defecto `[SECRET:` y `]`).
|
|
20
|
-
- Un texto con forma de marcador que **no** fue generado por nosotros no descifra y se
|
|
21
|
-
deja intacto (degradación segura).
|
|
22
|
-
|
|
23
|
-
## Clave
|
|
24
|
-
|
|
25
|
-
Se resuelve desde `redact.key` en `.opencode/opencode-apex.jsonc`:
|
|
26
|
-
|
|
27
|
-
| Formato | Ejemplo | Descripción |
|
|
28
|
-
| ----------------- | ----------------------------- | ------------------------------------ |
|
|
29
|
-
| literal | `"mi-frase-secreta"` | el propio texto es el material |
|
|
30
|
-
| `env:VAR` | `"env:APEX_REDACT_KEY"` | variable de entorno |
|
|
31
|
-
| `file:/ruta` | `"file:~/.config/opencode/apex.key"` | contenido del fichero (trim) |
|
|
32
|
-
| `hex:...` | `"hex:0011aaff..."` | material en hexadecimal |
|
|
33
|
-
| `base64:...` | `"base64:AAEC..."` | material en base64 |
|
|
34
|
-
|
|
35
|
-
El material se deriva a 32 bytes con SHA-256 (determinista ⇒ descifrable entre sesiones).
|
|
36
|
-
Sin clave disponible se genera una aleatoria y se persiste en `~/.config/opencode/apex.key`
|
|
37
|
-
(0600), con aviso: fíjala en la configuración para que sea estable.
|
|
38
|
-
|
|
39
|
-
## Flujo de hooks (crítico)
|
|
40
|
-
|
|
41
|
-
**Entrada al modelo → REDACTAR**
|
|
42
|
-
|
|
43
|
-
| Hook | Campo | Qué cubre |
|
|
44
|
-
| ---------------------- | ---------------------------- | --------------------------------------------- |
|
|
45
|
-
| `session.hook("context")` | `event.system/messages/tools` | system prompt + mensajes (prompt del usuario, resultados de tools) + definiciones de tools |
|
|
46
|
-
|
|
47
|
-
Un único punto, transport-agnostic: funciona con HTTP, WebSocket y providers ACP
|
|
48
|
-
porque corre en la construcción de la petición, antes del transporte.
|
|
49
|
-
|
|
50
|
-
**Salida hacia la herramienta → RESTAURAR**
|
|
10
|
+
There is no lookup table in memory: the marker *is* the encrypted secret, so nothing is
|
|
11
|
+
lost when OpenCode restarts. The encryption key is the only thing you need to keep.
|
|
51
12
|
|
|
52
|
-
|
|
53
|
-
| ------------------------- | ------------ | -------------------------------------------------- |
|
|
54
|
-
| `tool.hook("execute.before")` | `event.input` | argumentos de tool (el modelo emitió marcadores; la herramienta necesita el secreto real) |
|
|
13
|
+
## What a marker looks like
|
|
55
14
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
## Garantías de implementación
|
|
61
|
-
|
|
62
|
-
1. **Pasada única**: todas las coincidencias se recogen sobre el texto original y se
|
|
63
|
-
resuelven solapes (gana la más larga). Un patrón nunca puede re-cifrar un marcador
|
|
64
|
-
ya generado.
|
|
65
|
-
2. **Idempotencia**: los marcadores existentes son regiones protegidas. El mismo texto
|
|
66
|
-
puede atravesar `prompt → context → tool result` sin doble cifrado.
|
|
67
|
-
3. **Degradación segura**: marcador corrupto o ajeno ⇒ intacto. Payload inválido ⇒ `null`.
|
|
68
|
-
4. **Sin mapping**: nada que perder al reiniciar; la clave es la única pieza a custodiar.
|
|
15
|
+
```
|
|
16
|
+
{prefix}{patternName}:{base64url(iv || tag || ciphertext)}{suffix}
|
|
17
|
+
e.g. [SECRET:github-pat:AbC123...]
|
|
18
|
+
```
|
|
69
19
|
|
|
70
|
-
|
|
20
|
+
- **`patternName`** is the name of the detector that matched (for example `github-pat`,
|
|
21
|
+
`aws-access-key-id` or `custom-0`), so a human reading the conversation knows *what*
|
|
22
|
+
was hidden without seeing it.
|
|
23
|
+
- **Encryption** is AES-256-GCM, which is authenticated: a tampered payload does not
|
|
24
|
+
decrypt. The IV is 12 random bytes per secret, the tag is 16 bytes, and the payload is
|
|
25
|
+
base64url.
|
|
26
|
+
- **`prefix` and `suffix`** are configurable; the defaults are `[SECRET:` and `]`.
|
|
27
|
+
- **Unknown markers are left untouched**: text that looks like a marker but was not
|
|
28
|
+
produced with your key does not decrypt.
|
|
29
|
+
|
|
30
|
+
## When redaction and restoration happen
|
|
31
|
+
|
|
32
|
+
OpenCode plugins react to events through *hooks*. apex uses two:
|
|
33
|
+
|
|
34
|
+
| Direction | Hook | What it touches |
|
|
35
|
+
| --- | --- | --- |
|
|
36
|
+
| **To the model → redact** | `session.hook("context")` | The system prompt, every message (your prompts, previous answers, tool results) and the tool definitions, right before each request is sent. |
|
|
37
|
+
| **To a tool → restore** | `tool.hook("execute.before")` | The arguments of each tool call (only when `restore.toolInput` is `true`, the default). |
|
|
38
|
+
|
|
39
|
+
- The redaction hook runs while the request is being built, before any transport, so it
|
|
40
|
+
works the same over HTTP, WebSocket or ACP providers.
|
|
41
|
+
- **Nothing else is restored.** Model answers and reasoning keep the markers, so you see
|
|
42
|
+
`[SECRET:…]` in the chat.
|
|
43
|
+
- **The session history keeps the original text.** Redaction applies only to what is sent
|
|
44
|
+
to the model.
|
|
45
|
+
|
|
46
|
+
## The encryption key
|
|
47
|
+
|
|
48
|
+
The key comes from `redact.key`. apex resolves it in this order:
|
|
49
|
+
|
|
50
|
+
| `redact.key` value | Example | Key material |
|
|
51
|
+
| --- | --- | --- |
|
|
52
|
+
| `env:NAME` | `"env:APEX_REDACT_KEY"` | The value of that environment variable |
|
|
53
|
+
| `file:/path` | `"file:/home/me/.config/opencode/apex.key"` | The file's content, trimmed |
|
|
54
|
+
| `hex:…` | `"hex:0011aaff…"` | The hex string (must be hex digits) |
|
|
55
|
+
| `base64:…` | `"base64:AAEC…"` | The base64 string |
|
|
56
|
+
| any other text | `"my secret phrase"` | The text itself |
|
|
57
|
+
| empty (default) | `""` | The `APEX_REDACT_KEY` environment variable, if set |
|
|
58
|
+
|
|
59
|
+
1. The material is turned into a 32-byte key with SHA-256. The same material always gives
|
|
60
|
+
the same key, so markers stay decryptable across restarts and machines.
|
|
61
|
+
2. If none of the above yields any material (empty value, unset variable, missing or empty
|
|
62
|
+
file), apex reuses the key saved in `~/.config/opencode/apex.key`.
|
|
63
|
+
3. If that file does not exist either, apex generates a random key, saves it there (mode
|
|
64
|
+
`0600`) and logs a warning.
|
|
65
|
+
|
|
66
|
+
**Pitfalls:**
|
|
67
|
+
|
|
68
|
+
- `file:` paths may start with `~/` (your home directory). Any other relative path is
|
|
69
|
+
resolved against the server's working directory, so prefer `~/…` or an absolute path.
|
|
70
|
+
- If `env:NAME` points to a variable that is not set, apex goes straight to the saved key
|
|
71
|
+
file. It does **not** fall back to `APEX_REDACT_KEY`.
|
|
72
|
+
- **Changing the key orphans existing markers**: markers created with the old key no
|
|
73
|
+
longer decrypt and reach tools as plain marker text. Pick a key once (an environment
|
|
74
|
+
variable is the usual choice) and keep it.
|
|
75
|
+
- The server log shows which source was used and a short fingerprint, never the key:
|
|
76
|
+
`[apex.redact] Clave cargada (source=env, fp=1a2b3c4d), 96 patrones activos`.
|
|
77
|
+
|
|
78
|
+
## Guarantees
|
|
79
|
+
|
|
80
|
+
1. **Single pass.** All matches of all detectors are collected on the original text;
|
|
81
|
+
overlaps are resolved (the longest match wins). A detector can never match inside a
|
|
82
|
+
marker produced in the same pass.
|
|
83
|
+
2. **Idempotent.** Existing markers are protected regions, so the same text can flow
|
|
84
|
+
through prompt → context → tool result → context again without being encrypted twice.
|
|
85
|
+
3. **Safe degradation.** A corrupt or foreign marker is left as is; an invalid payload
|
|
86
|
+
decrypts to nothing and the text is kept.
|
|
87
|
+
4. **No state to lose.** There is no mapping table; only the key matters.
|
|
88
|
+
|
|
89
|
+
## Configuration
|
|
71
90
|
|
|
72
91
|
```jsonc
|
|
73
92
|
"redact": {
|
|
74
|
-
"mode": "strict",
|
|
75
|
-
"patterns": ["\\
|
|
76
|
-
"bundles": ["aws", "github", "jwt", "env", "openai",
|
|
77
|
-
"
|
|
93
|
+
"mode": "strict", // "strict" replaces · "warn" only logs
|
|
94
|
+
"patterns": ["\\bmy-token-[A-Za-z0-9]{16}\\b"], // your own regexes (note the \\)
|
|
95
|
+
"bundles": ["aws", "github", "jwt", "env", "openai"], // replaces the default list
|
|
96
|
+
"minConfidence": "medium", // low | medium | high
|
|
97
|
+
"allowlist": ["^sk-test-"], // regexes that are never redacted
|
|
78
98
|
"prefix": "[SECRET:",
|
|
79
99
|
"suffix": "]",
|
|
80
100
|
"key": "env:APEX_REDACT_KEY",
|
|
@@ -82,17 +102,34 @@ de cara al modelo.
|
|
|
82
102
|
}
|
|
83
103
|
```
|
|
84
104
|
|
|
85
|
-
|
|
86
|
-
|
|
105
|
+
| Key | Default | Meaning |
|
|
106
|
+
| --- | --- | --- |
|
|
107
|
+
| `mode` | `"strict"` | `strict` replaces secrets with markers. `warn` sends the text unchanged and only logs each finding (debug level) |
|
|
108
|
+
| `bundles` | the 38 default bundles | Named groups of detectors (see below). Setting it **replaces** the whole default list |
|
|
109
|
+
| `patterns` | `[]` | Your own regexes, added on top of the bundles. Each becomes `custom-<index>` in the marker, is always active (treated as high confidence) and is case-sensitive (JavaScript `g` flag only) |
|
|
110
|
+
| `minConfidence` | `"medium"` | Drops bundle detectors below this confidence |
|
|
111
|
+
| `allowlist` | `[]` | Regexes tested against each **matched secret**; a match that fits any of them is left in clear |
|
|
112
|
+
| `prefix` / `suffix` | `"[SECRET:"` / `"]"` | Marker delimiters |
|
|
113
|
+
| `key` | `""` | See [The encryption key](#the-encryption-key) |
|
|
114
|
+
| `restore.toolInput` | `true` | Decrypt markers in tool arguments |
|
|
115
|
+
|
|
116
|
+
- **Escaping in JSON:** `\b` in a JSON string is a backspace character. For a regex word
|
|
117
|
+
boundary write `\\b`. An invalid regex is skipped with a warning; it never stops the
|
|
118
|
+
plugin.
|
|
119
|
+
- **Unknown bundle names** are skipped with a warning that lists the valid names.
|
|
120
|
+
|
|
121
|
+
## Detectors and bundles
|
|
122
|
+
|
|
123
|
+
apex ships **104 detectors in 41 bundles**:
|
|
87
124
|
|
|
88
|
-
|
|
125
|
+
- 58 are copied from **opencode-warden**;
|
|
126
|
+
- 45 from **opencode-secret-redactor@0.5.1**;
|
|
127
|
+
- 1 is apex's own (`db-uri-credentials`).
|
|
89
128
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
`confidence` (low/medium/high) y opcionalmente un `validate()` (Luhn para tarjetas,
|
|
93
|
-
exclusión de IPs privadas).
|
|
129
|
+
Each detector has a confidence level (`low`, `medium`, `high`). Some also have an extra
|
|
130
|
+
check: the Luhn checksum for credit cards, and excluding private ranges for IPv4.
|
|
94
131
|
|
|
95
|
-
**
|
|
132
|
+
**Enabled by default (38 bundles):**
|
|
96
133
|
|
|
97
134
|
```
|
|
98
135
|
aws github gitlab slack jwt pem bearer env
|
|
@@ -102,20 +139,37 @@ observability pypi rubygems twilio sendgrid postman mailgun mailchimp
|
|
|
102
139
|
linear shopify square docker kubernetes cohere huggingface discord
|
|
103
140
|
```
|
|
104
141
|
|
|
105
|
-
**Opt-in** (
|
|
106
|
-
tarjeta), `network` (IPv4 públicas), `datadog`.
|
|
142
|
+
**Opt-in** (noisy or personal data; add them to `bundles` explicitly):
|
|
107
143
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
144
|
+
| Bundle | Detects |
|
|
145
|
+
| --- | --- |
|
|
146
|
+
| `pii` | email, US phone number, US SSN, credit card (Luhn-checked) |
|
|
147
|
+
| `network` | public IPv4 addresses |
|
|
148
|
+
| `datadog` | Datadog API keys |
|
|
112
149
|
|
|
113
|
-
|
|
114
|
-
> solo la salida de una tool. Por eso los patrones de baja confianza y PII están fuera
|
|
115
|
-
> por defecto: un email o una URI de redis en el código serían falsos positivos caros.
|
|
150
|
+
**`minConfidence`** decides how many detectors are active:
|
|
116
151
|
|
|
117
|
-
|
|
152
|
+
- `medium` (the default) skips the `low` ones: `cohere-key`, `redis-connection-string`,
|
|
153
|
+
and, when their bundles are enabled, `datadog-api-key`, `pii-us-phone` and `pii-ipv4`.
|
|
154
|
+
With the default bundles, 96 detectors are active.
|
|
155
|
+
- `low` enables all 98 detectors of the default bundles.
|
|
156
|
+
- `high` keeps only the unambiguous ones (78).
|
|
157
|
+
|
|
158
|
+
> **Why so conservative?** apex redacts the **whole** context (system prompt, history
|
|
159
|
+
> and tool definitions), not just one tool's output. An email address or a Redis URL in
|
|
160
|
+
> your source code would become a marker everywhere, which makes the code hard for the
|
|
161
|
+
> model to work with. Low-confidence and personal-data detectors are therefore off by
|
|
162
|
+
> default.
|
|
163
|
+
|
|
164
|
+
## Redacting from outside: RPC `apex/redact.process`
|
|
165
|
+
|
|
166
|
+
The same engine is available over the OpenCode server's RPC endpoint. That endpoint and
|
|
167
|
+
its authentication are explained in [EVENTS.md](EVENTS.md).
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
POST /api/rpc/apex/redact.process?location[directory]=<project>
|
|
171
|
+
{"input": {"text": "token ghp_…", "mode": "strict"}}
|
|
172
|
+
→ {"output": {"redacted": "token [SECRET:github-pat:…]", "findings": [{"pattern": "github-pat"}]}}
|
|
173
|
+
```
|
|
118
174
|
|
|
119
|
-
|
|
120
|
-
(incluido el nombre de patrón), round-trip, multi-patrón, valores anidados, allowlist,
|
|
121
|
-
modo warn, marcador ajeno e idempotencia.
|
|
175
|
+
It uses the configured detectors, `allowlist`, key and marker format.
|