@fontdata/ai-harness 4.5.2 → 4.7.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/.claude-plugin/plugin.json +2 -2
- package/README.md +8 -0
- package/dist/banco-dados/command.js +58 -14
- package/dist/banco-dados/conexao.js +10 -4
- package/dist/banco-dados/drivers/mariadb.js +4 -0
- package/dist/banco-dados/drivers/postgres.js +4 -0
- package/dist/banco-dados/drivers/sqlite.js +3 -0
- package/dist/banco-dados/ferramentas.js +42 -9
- package/dist/banco-dados/modelo-banco.js +31 -0
- package/dist/cli.js +7 -0
- package/dist/config/config.js +47 -5
- package/dist/doctor/checks.js +2 -0
- package/dist/doctor/seguranca.js +101 -0
- package/dist/init.js +1 -1
- package/dist/install/plan.js +16 -3
- package/dist/install/settings.js +86 -15
- package/dist/seguranca/checar-comando.js +90 -0
- package/dist/update/update.js +17 -13
- package/package.json +1 -1
- package/templates/hooks/arquivo-sensivel.mjs +83 -0
- package/templates/hooks/comando-destrutivo.mjs +74 -0
- package/templates/hooks/hooks.json +9 -2
- package/templates/hooks/lib/comando-texto.mjs +386 -0
- package/templates/hooks/lib/config.mjs +43 -0
- package/templates/hooks/lib/hook.mjs +22 -12
- package/templates/hooks/lib/regras/apagar.mjs +100 -0
- package/templates/hooks/lib/regras/git.mjs +131 -0
- package/templates/hooks/lib/regras/remoto.mjs +228 -0
- package/templates/hooks/lib/regras/sql.mjs +63 -0
- package/templates/hooks/lib/segredos.mjs +1 -1
- package/templates/rules/seguranca.md +83 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { invocacao, palavras, segmentos, semTextoLivre } from './lib/comando-texto.mjs';
|
|
3
|
+
import { segurancaConfig } from './lib/config.mjs';
|
|
4
|
+
import { runHook } from './lib/hook.mjs';
|
|
5
|
+
import { findActiveWorks } from './lib/rastro.mjs';
|
|
6
|
+
import { REGRAS as APAGAR } from './lib/regras/apagar.mjs';
|
|
7
|
+
import { REGRAS as GIT } from './lib/regras/git.mjs';
|
|
8
|
+
import { REGRAS as REMOTO } from './lib/regras/remoto.mjs';
|
|
9
|
+
import { REGRAS as SQL } from './lib/regras/sql.mjs';
|
|
10
|
+
|
|
11
|
+
const TODAS = [...APAGAR, ...GIT, ...SQL, ...REMOTO];
|
|
12
|
+
const REGRAS = [...TODAS.filter((r) => r.decisao === 'negar'), ...TODAS.filter((r) => r.decisao === 'perguntar')];
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Os segmentos e, depois de cada um, os do script passado a `sh -c`, `pwsh -Command` ou `cmd /c`.
|
|
16
|
+
* @param {string[]} lista @param {number} [profundidade] @returns {string[]} */
|
|
17
|
+
function comScriptsInternos(lista, profundidade = 0) {
|
|
18
|
+
return lista.flatMap((segmento) => {
|
|
19
|
+
const { nome, args } = invocacao(palavras(segmento));
|
|
20
|
+
let script = null;
|
|
21
|
+
if (['sh', 'bash', 'zsh', 'dash', 'ksh'].includes(nome)) {
|
|
22
|
+
const k = args.findIndex((a) => /^-[a-z]*c[a-z]*$/i.test(a));
|
|
23
|
+
if (k !== -1) script = args[k + 1] ?? null;
|
|
24
|
+
} else if (['pwsh', 'powershell'].includes(nome)) {
|
|
25
|
+
const k = args.findIndex((a) => /^-c(ommand)?$/i.test(a));
|
|
26
|
+
if (k !== -1) script = args.slice(k + 1).join(' ');
|
|
27
|
+
} else if (nome === 'cmd') {
|
|
28
|
+
const k = args.findIndex((a) => /^\/[ck]$/i.test(a));
|
|
29
|
+
if (k !== -1) script = args.slice(k + 1).join(' ');
|
|
30
|
+
}
|
|
31
|
+
if (!script || profundidade >= 3) return [segmento];
|
|
32
|
+
return [segmento, ...comScriptsInternos(segmentos(semTextoLivre(script)), profundidade + 1)];
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param {string} comando */
|
|
37
|
+
function rodarComExclamacao(comando) {
|
|
38
|
+
const linha = comando.trim();
|
|
39
|
+
return !linha.includes('\n') && linha.length <= 200 ? `! ${linha}` : '! <comando>';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
await runHook('comando-destrutivo', (input, { root }) => {
|
|
43
|
+
const comando = input.tool_input?.command;
|
|
44
|
+
if (comando === undefined || comando === null) return null;
|
|
45
|
+
try {
|
|
46
|
+
if (typeof comando !== 'string') throw new Error(`tool_input.command não é texto (${typeof comando})`);
|
|
47
|
+
/** @type {string[] | undefined} */
|
|
48
|
+
let ativos;
|
|
49
|
+
/** @type {import('./lib/comando-texto.mjs').ContextoComando} */
|
|
50
|
+
const ctx = {
|
|
51
|
+
comando,
|
|
52
|
+
segmentos: comScriptsInternos(segmentos(semTextoLivre(comando))),
|
|
53
|
+
raiz: root,
|
|
54
|
+
seguranca: segurancaConfig(root),
|
|
55
|
+
get trabalhosAtivos() {
|
|
56
|
+
return (ativos ??= findActiveWorks(root));
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
const regra = REGRAS.find((r) => r.testar(ctx));
|
|
60
|
+
if (!regra) return null;
|
|
61
|
+
if (regra.decisao === 'perguntar') return { motivo: `${regra.id}: ${regra.motivo}`, decisao: 'perguntar' };
|
|
62
|
+
return {
|
|
63
|
+
motivo:
|
|
64
|
+
`${regra.id}: ${regra.motivo}. O agente não roda este comando; se for isso mesmo, o dev pode rodá-lo ele ` +
|
|
65
|
+
`mesmo na sessão com ${rodarComExclamacao(comando)}`,
|
|
66
|
+
decisao: 'negar',
|
|
67
|
+
};
|
|
68
|
+
} catch (erro) {
|
|
69
|
+
const motivo = erro instanceof Error ? erro.message : String(erro);
|
|
70
|
+
throw new Error(
|
|
71
|
+
`${motivo}; se o hook travar comandos válidos, ponha hooks.comando-destrutivo em "aviso" no .ai-harness/config.json até a correção`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
@@ -9,9 +9,16 @@
|
|
|
9
9
|
],
|
|
10
10
|
"PreToolUse": [
|
|
11
11
|
{
|
|
12
|
-
"matcher": "Bash",
|
|
12
|
+
"matcher": "Bash|PowerShell",
|
|
13
13
|
"hooks": [
|
|
14
|
-
{ "type": "command", "
|
|
14
|
+
{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/templates/hooks/segredo-no-commit.mjs\"" },
|
|
15
|
+
{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/templates/hooks/comando-destrutivo.mjs\"" }
|
|
16
|
+
]
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"matcher": "Edit|Write|MultiEdit|NotebookEdit",
|
|
20
|
+
"hooks": [
|
|
21
|
+
{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/templates/hooks/arquivo-sensivel.mjs\"" }
|
|
15
22
|
]
|
|
16
23
|
},
|
|
17
24
|
{
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/** @typedef {{ valor: string, inicio: number, fim: number, heredoc: boolean, subs: string[] }} Palavra */
|
|
4
|
+
/** @typedef {{ palavras: Palavra[], corpos: Array<[number, number]>, inicio: number, fim: number, separador: string }} Segmento */
|
|
5
|
+
/** @typedef {{ pastas_descartaveis: string[], negar_leitura_segredos: boolean, desligar_bypass: boolean }} Seguranca */
|
|
6
|
+
/** @typedef {{ comando: string, segmentos: string[], raiz: string, seguranca: Seguranca, readonly trabalhosAtivos: string[] }} ContextoComando */
|
|
7
|
+
/** @typedef {{ id: string, decisao: 'negar' | 'perguntar', motivo: string, testar: (ctx: ContextoComando) => boolean }} Regra */
|
|
8
|
+
|
|
9
|
+
export const INTERPRETADORES_SHELL = new Set([
|
|
10
|
+
'sh', 'bash', 'zsh', 'dash', 'ksh', 'fish', 'csh', 'tcsh', 'pwsh', 'powershell', 'cmd', 'iex', 'invoke-expression', 'source',
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
const ESCAPAVEIS = '\'"\\$`()';
|
|
14
|
+
const FIM_DE_DELIMITADOR = /[\s;|&<>()]/;
|
|
15
|
+
|
|
16
|
+
/** @type {Record<string, string[]>} */
|
|
17
|
+
const PREFIXOS = {
|
|
18
|
+
sudo: ['-u', '-g', '-h', '-p', '-C', '-D', '-r', '-t', '-U', '-T'],
|
|
19
|
+
doas: ['-u', '-C'],
|
|
20
|
+
env: ['-u', '-C'],
|
|
21
|
+
command: [],
|
|
22
|
+
builtin: [],
|
|
23
|
+
exec: ['-a'],
|
|
24
|
+
nohup: [],
|
|
25
|
+
time: ['-f', '-o'],
|
|
26
|
+
nice: ['-n'],
|
|
27
|
+
npx: ['-p', '--package'],
|
|
28
|
+
bunx: ['-p', '--package'],
|
|
29
|
+
pnpx: [],
|
|
30
|
+
'&': [],
|
|
31
|
+
'{': [],
|
|
32
|
+
'}': [],
|
|
33
|
+
'!': [],
|
|
34
|
+
if: [],
|
|
35
|
+
then: [],
|
|
36
|
+
else: [],
|
|
37
|
+
elif: [],
|
|
38
|
+
do: [],
|
|
39
|
+
while: [],
|
|
40
|
+
until: [],
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export function nomeBase(/** @type {string} */ palavra) {
|
|
44
|
+
return (palavra.split(/[\\/]/).pop() ?? '').toLowerCase().replace(/\.(exe|cmd|bat|com)$/, '');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param {string} texto @param {number} j posição do `<<` */
|
|
48
|
+
function lerHeredoc(texto, j) {
|
|
49
|
+
let k = j + 2;
|
|
50
|
+
if (texto[k] === '-') k++;
|
|
51
|
+
while (texto[k] === ' ' || texto[k] === '\t') k++;
|
|
52
|
+
const inicio = k;
|
|
53
|
+
let quote = '';
|
|
54
|
+
while (k < texto.length) {
|
|
55
|
+
const c = texto[k] ?? '';
|
|
56
|
+
if (quote) {
|
|
57
|
+
if (c === quote) quote = '';
|
|
58
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
59
|
+
else if (FIM_DE_DELIMITADOR.test(c)) break;
|
|
60
|
+
k++;
|
|
61
|
+
}
|
|
62
|
+
return { delimitador: texto.slice(inicio, k).replace(/["'\\]/g, ''), fim: k };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Delimitador ausente vai até o fim. @param {string} texto @param {number} inicio @param {string[]} delimitadores */
|
|
66
|
+
function lerCorpos(texto, inicio, delimitadores) {
|
|
67
|
+
/** @type {Array<[number, number]>} */
|
|
68
|
+
const trechos = [];
|
|
69
|
+
let pos = inicio;
|
|
70
|
+
for (const delimitador of delimitadores) {
|
|
71
|
+
const comeco = pos;
|
|
72
|
+
for (;;) {
|
|
73
|
+
const eol = texto.indexOf('\n', pos);
|
|
74
|
+
const linha = texto.slice(pos, eol === -1 ? texto.length : eol);
|
|
75
|
+
if (linha.trim() === delimitador || eol === -1) {
|
|
76
|
+
trechos.push([comeco, pos + linha.length]);
|
|
77
|
+
pos = eol === -1 ? texto.length : eol + 1;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
pos = eol + 1;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { trechos, fim: pos };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Fim do `$(...)` aberto antes de `j`. @param {string} texto @param {number} j */
|
|
87
|
+
function fimSubshell(texto, j) {
|
|
88
|
+
let profundidade = 1;
|
|
89
|
+
/** @type {string[]} */
|
|
90
|
+
let pendentes = [];
|
|
91
|
+
while (j < texto.length) {
|
|
92
|
+
const c = texto[j];
|
|
93
|
+
if (c === '\\') j += 2;
|
|
94
|
+
else if (c === "'") {
|
|
95
|
+
const f = texto.indexOf("'", j + 1);
|
|
96
|
+
j = f === -1 ? texto.length : f + 1;
|
|
97
|
+
} else if (c === '"') j = lerAspasDuplas(texto, j).fim;
|
|
98
|
+
else if (c === '`') {
|
|
99
|
+
const f = texto.indexOf('`', j + 1);
|
|
100
|
+
j = f === -1 ? j + 1 : f + 1;
|
|
101
|
+
} else if (texto.startsWith('<<<', j)) j += 3;
|
|
102
|
+
else if (texto.startsWith('<<', j)) {
|
|
103
|
+
const heredoc = lerHeredoc(texto, j);
|
|
104
|
+
if (heredoc.delimitador) pendentes.push(heredoc.delimitador);
|
|
105
|
+
j = heredoc.fim;
|
|
106
|
+
} else if (c === '\n' && pendentes.length) {
|
|
107
|
+
j = lerCorpos(texto, j + 1, pendentes).fim;
|
|
108
|
+
pendentes = [];
|
|
109
|
+
} else {
|
|
110
|
+
if (c === '(') profundidade++;
|
|
111
|
+
if (c === ')' && --profundidade === 0) return j + 1;
|
|
112
|
+
j++;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return texto.length;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Sem a aspa de fechamento pelo bash, relê sem escape de barra como o PowerShell em `"C:\"`: o bash o recusaria.
|
|
120
|
+
* @param {string} texto @param {number} i @returns {{ valor: string, fim: number, subs: string[] }} */
|
|
121
|
+
function lerAspasDuplas(texto, i) {
|
|
122
|
+
let valor = '';
|
|
123
|
+
/** @type {string[]} */
|
|
124
|
+
const subs = [];
|
|
125
|
+
let j = i + 1;
|
|
126
|
+
while (j < texto.length) {
|
|
127
|
+
const c = texto[j];
|
|
128
|
+
if (c === '"') return { valor, fim: j + 1, subs };
|
|
129
|
+
if (c === '\\' && '"\\$`\n'.includes(texto[j + 1] ?? '')) {
|
|
130
|
+
if (texto[j + 1] !== '\n') valor += texto[j + 1];
|
|
131
|
+
j += 2;
|
|
132
|
+
} else if (c === '$' && texto[j + 1] === '(') {
|
|
133
|
+
const fim = fimSubshell(texto, j + 2);
|
|
134
|
+
subs.push(texto.slice(j + 2, fim - 1));
|
|
135
|
+
valor += texto.slice(j, fim);
|
|
136
|
+
j = fim;
|
|
137
|
+
} else if (c === '`' && texto.indexOf('`', j + 1) !== -1) {
|
|
138
|
+
const fim = texto.indexOf('`', j + 1);
|
|
139
|
+
subs.push(texto.slice(j + 1, fim));
|
|
140
|
+
valor += texto.slice(j, fim + 1);
|
|
141
|
+
j = fim + 1;
|
|
142
|
+
} else {
|
|
143
|
+
valor += c;
|
|
144
|
+
j++;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const fecha = texto.indexOf('"', i + 1);
|
|
148
|
+
return fecha === -1 ? { valor: texto.slice(i + 1), fim: texto.length, subs } : { valor: texto.slice(i + 1, fecha), fim: fecha + 1, subs };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** @param {string} texto @returns {Segmento[]} */
|
|
152
|
+
function analisar(texto) {
|
|
153
|
+
/** @type {Segmento[]} */
|
|
154
|
+
const segmentos = [];
|
|
155
|
+
/** @type {(inicio: number) => Segmento} */
|
|
156
|
+
const novo = (inicio) => ({ palavras: [], corpos: [], inicio, fim: inicio, separador: '' });
|
|
157
|
+
let seg = novo(0);
|
|
158
|
+
/** @type {{ valor: string, inicio: number, subs: string[], heredoc?: boolean } | null} */
|
|
159
|
+
let atual = null;
|
|
160
|
+
/** @type {Array<{ delimitador: string, seg: Segmento }>} */
|
|
161
|
+
let pendentes = [];
|
|
162
|
+
let i = 0;
|
|
163
|
+
|
|
164
|
+
const palavra = () => (atual ??= { valor: '', inicio: i, subs: [] });
|
|
165
|
+
const fechar = (/** @type {number} */ fim) => {
|
|
166
|
+
if (atual) seg.palavras.push({ valor: atual.valor, inicio: atual.inicio, fim, heredoc: Boolean(atual.heredoc), subs: atual.subs });
|
|
167
|
+
atual = null;
|
|
168
|
+
};
|
|
169
|
+
const separar = (/** @type {string} */ separador, /** @type {number} */ tamanho) => {
|
|
170
|
+
fechar(i);
|
|
171
|
+
seg.fim = i;
|
|
172
|
+
seg.separador = separador;
|
|
173
|
+
segmentos.push(seg);
|
|
174
|
+
i += tamanho;
|
|
175
|
+
if (separador === '\n' && pendentes.length) {
|
|
176
|
+
const { trechos, fim } = lerCorpos(texto, i, pendentes.map((p) => p.delimitador));
|
|
177
|
+
trechos.forEach((trecho, k) => pendentes[k]?.seg.corpos.push(trecho));
|
|
178
|
+
pendentes = [];
|
|
179
|
+
i = fim;
|
|
180
|
+
}
|
|
181
|
+
seg = novo(i);
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
while (i < texto.length) {
|
|
185
|
+
const c = texto[i];
|
|
186
|
+
const prox = texto[i + 1];
|
|
187
|
+
if (c === "'") {
|
|
188
|
+
const p = palavra();
|
|
189
|
+
const fim = texto.indexOf("'", i + 1);
|
|
190
|
+
p.valor += texto.slice(i + 1, fim === -1 ? texto.length : fim);
|
|
191
|
+
i = fim === -1 ? texto.length : fim + 1;
|
|
192
|
+
} else if (c === '"') {
|
|
193
|
+
const p = palavra();
|
|
194
|
+
const lido = lerAspasDuplas(texto, i);
|
|
195
|
+
p.valor += lido.valor;
|
|
196
|
+
p.subs.push(...lido.subs);
|
|
197
|
+
i = lido.fim;
|
|
198
|
+
} else if (c === '$' && prox === '(') {
|
|
199
|
+
const p = palavra();
|
|
200
|
+
const fim = fimSubshell(texto, i + 2);
|
|
201
|
+
p.subs.push(texto.slice(i + 2, fim - 1));
|
|
202
|
+
p.valor += texto.slice(i, fim);
|
|
203
|
+
i = fim;
|
|
204
|
+
} else if (c === '`' && texto.indexOf('`', i + 1) !== -1) {
|
|
205
|
+
const p = palavra();
|
|
206
|
+
const fim = texto.indexOf('`', i + 1);
|
|
207
|
+
p.subs.push(texto.slice(i + 1, fim));
|
|
208
|
+
p.valor += texto.slice(i, fim + 1);
|
|
209
|
+
i = fim + 1;
|
|
210
|
+
} else if (c === '\\' && prox === '\n') {
|
|
211
|
+
i += 2;
|
|
212
|
+
} else if (c === '\\' && prox !== undefined && ESCAPAVEIS.includes(prox)) {
|
|
213
|
+
palavra().valor += prox;
|
|
214
|
+
i += 2;
|
|
215
|
+
} else if (c === ' ' || c === '\t' || c === '\r') {
|
|
216
|
+
fechar(i);
|
|
217
|
+
i++;
|
|
218
|
+
} else if (c === '#' && !atual) {
|
|
219
|
+
const eol = texto.indexOf('\n', i);
|
|
220
|
+
i = eol === -1 ? texto.length : eol;
|
|
221
|
+
} else if (c === '\n') separar('\n', 1);
|
|
222
|
+
else if (c === ';') separar(';', 1);
|
|
223
|
+
else if (c === '(' || c === ')') separar(c, 1);
|
|
224
|
+
else if (c === '&' && prox === '&') separar('&&', 2);
|
|
225
|
+
else if (c === '|' && prox === '|') separar('||', 2);
|
|
226
|
+
else if (c === '|' && prox === '&') separar('|&', 2);
|
|
227
|
+
else if (c === '|') separar('|', 1);
|
|
228
|
+
else if (c === '&' && prox !== '>' && !/[<>]$/.test(atual?.valor ?? '')) separar('&', 1);
|
|
229
|
+
else if (texto.startsWith('<<<', i)) {
|
|
230
|
+
palavra().valor += '<<<';
|
|
231
|
+
i += 3;
|
|
232
|
+
} else if (c === '<' && prox === '<') {
|
|
233
|
+
fechar(i);
|
|
234
|
+
const heredoc = lerHeredoc(texto, i);
|
|
235
|
+
if (heredoc.delimitador) pendentes.push({ delimitador: heredoc.delimitador, seg });
|
|
236
|
+
atual = { valor: `<<${heredoc.delimitador}`, inicio: i, subs: [], heredoc: true };
|
|
237
|
+
i = heredoc.fim;
|
|
238
|
+
fechar(i);
|
|
239
|
+
} else {
|
|
240
|
+
palavra().valor += c;
|
|
241
|
+
i++;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
fechar(i);
|
|
245
|
+
seg.fim = i;
|
|
246
|
+
segmentos.push(seg);
|
|
247
|
+
return segmentos;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** @param {string} texto @param {Segmento} seg */
|
|
251
|
+
function textoDoSegmento(texto, seg) {
|
|
252
|
+
return [texto.slice(seg.inicio, seg.fim).trim(), ...seg.corpos.map(([a, b]) => texto.slice(a, b))].join('\n').trim();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Trechos fora de aspas; o corpo do heredoc fica no trecho que o abre. @param {string} comando */
|
|
256
|
+
export function segmentos(comando) {
|
|
257
|
+
return analisar(comando)
|
|
258
|
+
.map((seg) => textoDoSegmento(comando, seg))
|
|
259
|
+
.filter(Boolean);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Palavras sem aspas e sem os operadores de heredoc. @param {string} segmento */
|
|
263
|
+
export function palavras(segmento) {
|
|
264
|
+
return analisar(segmento).flatMap((seg) => seg.palavras.filter((p) => !p.heredoc).map((p) => p.valor));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** @param {string[]} lista */
|
|
268
|
+
function inicioDoComando(lista) {
|
|
269
|
+
let k = 0;
|
|
270
|
+
while (k < lista.length) {
|
|
271
|
+
const atual = lista[k] ?? '';
|
|
272
|
+
const nome = nomeBase(atual);
|
|
273
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(atual)) {
|
|
274
|
+
k++;
|
|
275
|
+
} else if (Object.hasOwn(PREFIXOS, nome)) {
|
|
276
|
+
const comValor = PREFIXOS[nome] ?? [];
|
|
277
|
+
k++;
|
|
278
|
+
while ((lista[k] ?? '').startsWith('-')) k += comValor.includes(lista[k] ?? '') ? 2 : 1;
|
|
279
|
+
} else if (['npm', 'pnpm', 'yarn'].includes(nome) && ['exec', 'dlx', 'x'].includes(lista[k + 1] ?? '')) {
|
|
280
|
+
k += 2;
|
|
281
|
+
while ((lista[k] ?? '').startsWith('-')) k++;
|
|
282
|
+
} else break;
|
|
283
|
+
}
|
|
284
|
+
return k;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** @param {string[]} lista */
|
|
288
|
+
function semRedirecoes(lista) {
|
|
289
|
+
/** @type {string[]} */
|
|
290
|
+
const saida = [];
|
|
291
|
+
for (let k = 0; k < lista.length; k++) {
|
|
292
|
+
const atual = lista[k] ?? '';
|
|
293
|
+
if (/^(\d+|&)?(>>?|<|>\||<<<)$/.test(atual)) k++;
|
|
294
|
+
else if (!/^(\d+|&)?(>>?|<)/.test(atual)) saida.push(atual);
|
|
295
|
+
}
|
|
296
|
+
return saida;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Programa depois de atribuições, `sudo`, `env`, `npx` e afins; args sem redirecionamentos. @param {string[]} lista */
|
|
300
|
+
export function invocacao(lista) {
|
|
301
|
+
const limpa = semRedirecoes(lista);
|
|
302
|
+
const k = inicioDoComando(limpa);
|
|
303
|
+
return { nome: nomeBase(limpa[k] ?? ''), args: limpa.slice(k + 1) };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** @param {Segmento[]} segs @param {number} k */
|
|
307
|
+
function saidaVaiParaShell(segs, k) {
|
|
308
|
+
for (let m = k; segs[m]?.separador === '|' || segs[m]?.separador === '|&'; m++) {
|
|
309
|
+
const seguinte = segs[m + 1];
|
|
310
|
+
if (seguinte && INTERPRETADORES_SHELL.has(invocacao(seguinte.palavras.filter((p) => !p.heredoc).map((p) => p.valor)).nome)) return true;
|
|
311
|
+
}
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** @param {Segmento} seg @returns {{ palavras: Palavra[], corpos: boolean }} */
|
|
316
|
+
function textoLivreDo(seg) {
|
|
317
|
+
const normais = seg.palavras.filter((p) => !p.heredoc);
|
|
318
|
+
const valores = normais.map((p) => p.valor);
|
|
319
|
+
const k = inicioDoComando(valores);
|
|
320
|
+
const nome = nomeBase(valores[k] ?? '');
|
|
321
|
+
const heredocs = seg.palavras.filter((p) => p.heredoc);
|
|
322
|
+
if (['grep', 'egrep', 'fgrep', 'rg', 'echo'].includes(nome)) return { palavras: [...normais.slice(k + 1), ...heredocs], corpos: true };
|
|
323
|
+
if (nome !== 'git') return { palavras: [], corpos: false };
|
|
324
|
+
|
|
325
|
+
let j = k + 1;
|
|
326
|
+
while ((valores[j] ?? '').startsWith('-')) j += ['-C', '-c', '--git-dir', '--work-tree', '--namespace'].includes(valores[j] ?? '') ? 2 : 1;
|
|
327
|
+
const sub = valores[j];
|
|
328
|
+
if (sub === 'grep') return { palavras: [...normais.slice(j + 1), ...heredocs], corpos: true };
|
|
329
|
+
/** @type {Palavra[]} */
|
|
330
|
+
const livres = [];
|
|
331
|
+
for (let m = j + 1; m < normais.length; m++) {
|
|
332
|
+
const atual = valores[m] ?? '';
|
|
333
|
+
const p = normais[m];
|
|
334
|
+
const seguinte = normais[m + 1];
|
|
335
|
+
if (!p) continue;
|
|
336
|
+
if (sub === 'log' && (/^-[SG]$/.test(atual) || atual === '--grep')) {
|
|
337
|
+
livres.push(p);
|
|
338
|
+
if (seguinte) livres.push(seguinte);
|
|
339
|
+
m++;
|
|
340
|
+
} else if (sub === 'log' && (/^-[SG]./.test(atual) || atual.startsWith('--grep='))) livres.push(p);
|
|
341
|
+
else if (sub === 'commit' && (/^-[A-Za-z]*m$/.test(atual) || atual === '--message')) {
|
|
342
|
+
if (seguinte) livres.push(seguinte);
|
|
343
|
+
m++;
|
|
344
|
+
} else if (sub === 'commit' && (/^-[A-Za-z]*m./.test(atual) || atual.startsWith('--message='))) {
|
|
345
|
+
const corte = atual.startsWith('--') ? 0 : atual.indexOf('m') + 1;
|
|
346
|
+
livres.push({ ...p, inicio: p.inicio + corte });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return sub === 'commit' ? { palavras: [...livres, ...heredocs], corpos: true } : { palavras: livres, corpos: false };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** `$(cat <<'EOF' … EOF)`: só texto, o idioma da mensagem de commit e do corpo de PR. */
|
|
353
|
+
function soHeredocDoCat(/** @type {string} */ sub) {
|
|
354
|
+
const segs = analisar(sub).filter((seg) => seg.palavras.length);
|
|
355
|
+
const unico = segs[0];
|
|
356
|
+
if (segs.length !== 1 || !unico || !unico.corpos.length) return false;
|
|
357
|
+
const { nome, args } = invocacao(unico.palavras.filter((p) => !p.heredoc).map((p) => p.valor));
|
|
358
|
+
return nome === 'cat' && args.length === 0;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Tira o texto livre (mensagem de commit, args de grep, rg, echo e git log -S/-G), salvo se a saída vai para shell.
|
|
363
|
+
* As substituições `$(...)` e crases voltam no fim, uma por linha, porque rodam. @param {string} comando @returns {string} */
|
|
364
|
+
export function semTextoLivre(comando) {
|
|
365
|
+
const segs = analisar(comando);
|
|
366
|
+
/** @type {Array<[number, number]>} */
|
|
367
|
+
const cortes = [];
|
|
368
|
+
/** @type {string[]} */
|
|
369
|
+
const extras = [];
|
|
370
|
+
segs.forEach((seg, k) => {
|
|
371
|
+
for (const p of seg.palavras) for (const sub of p.subs) if (!soHeredocDoCat(sub)) extras.push(semTextoLivre(sub));
|
|
372
|
+
if (saidaVaiParaShell(segs, k)) return;
|
|
373
|
+
const livre = textoLivreDo(seg);
|
|
374
|
+
for (const p of livre.palavras) cortes.push([p.inicio, p.fim]);
|
|
375
|
+
if (livre.corpos) cortes.push(...seg.corpos);
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
let saida = '';
|
|
379
|
+
let pos = 0;
|
|
380
|
+
for (const [a, b] of cortes.sort((x, y) => x[0] - y[0])) {
|
|
381
|
+
if (a > pos) saida += comando.slice(pos, a);
|
|
382
|
+
pos = Math.max(pos, b);
|
|
383
|
+
}
|
|
384
|
+
saida += comando.slice(pos);
|
|
385
|
+
return [saida, ...extras].join('\n');
|
|
386
|
+
}
|
|
@@ -13,6 +13,8 @@ import { join } from 'node:path';
|
|
|
13
13
|
export const DEFAULT_HOOK_MODES = {
|
|
14
14
|
lembrete: 'aviso',
|
|
15
15
|
'segredo-no-commit': 'bloqueio',
|
|
16
|
+
'comando-destrutivo': 'bloqueio',
|
|
17
|
+
'arquivo-sensivel': 'bloqueio',
|
|
16
18
|
'task-so-fecha-verde': 'aviso',
|
|
17
19
|
'proteger-contratos': 'aviso',
|
|
18
20
|
'sem-jargao': 'aviso',
|
|
@@ -39,3 +41,44 @@ export function hookMode(root, hook) {
|
|
|
39
41
|
return fallback;
|
|
40
42
|
}
|
|
41
43
|
}
|
|
44
|
+
|
|
45
|
+
/** Mesmos padrões de `seguranca` em src/config/config.ts. */
|
|
46
|
+
export const PASTAS_DESCARTAVEIS_PADRAO = [
|
|
47
|
+
'node_modules',
|
|
48
|
+
'dist',
|
|
49
|
+
'build',
|
|
50
|
+
'out',
|
|
51
|
+
'coverage',
|
|
52
|
+
'.next',
|
|
53
|
+
'.turbo',
|
|
54
|
+
'.cache',
|
|
55
|
+
'.vite',
|
|
56
|
+
'tmp',
|
|
57
|
+
'temp',
|
|
58
|
+
'__history',
|
|
59
|
+
'__recovery',
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Seção `seguranca` da config; config ausente, ilegível ou valor inválido cai no padrão daquela chave.
|
|
64
|
+
* @param {string} root
|
|
65
|
+
* @returns {{ pastas_descartaveis: string[], negar_leitura_segredos: boolean, desligar_bypass: boolean }}
|
|
66
|
+
*/
|
|
67
|
+
export function segurancaConfig(root) {
|
|
68
|
+
const seguranca = { pastas_descartaveis: [...PASTAS_DESCARTAVEIS_PADRAO], negar_leitura_segredos: true, desligar_bypass: false };
|
|
69
|
+
const file = join(root, '.ai-harness', 'config.json');
|
|
70
|
+
if (!existsSync(file)) return seguranca;
|
|
71
|
+
/** @type {any} */
|
|
72
|
+
let raw;
|
|
73
|
+
try {
|
|
74
|
+
raw = JSON.parse(readFileSync(file, 'utf8'))?.seguranca;
|
|
75
|
+
} catch {
|
|
76
|
+
return seguranca;
|
|
77
|
+
}
|
|
78
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return seguranca;
|
|
79
|
+
const pastas = raw.pastas_descartaveis;
|
|
80
|
+
if (Array.isArray(pastas) && pastas.every((pasta) => typeof pasta === 'string' && pasta !== '')) seguranca.pastas_descartaveis = pastas;
|
|
81
|
+
if (typeof raw.negar_leitura_segredos === 'boolean') seguranca.negar_leitura_segredos = raw.negar_leitura_segredos;
|
|
82
|
+
if (typeof raw.desligar_bypass === 'boolean') seguranca.desligar_bypass = raw.desligar_bypass;
|
|
83
|
+
return seguranca;
|
|
84
|
+
}
|
|
@@ -5,7 +5,7 @@ import { DEFAULT_HOOK_MODES, hookMode } from './config.mjs';
|
|
|
5
5
|
import { recordEvent } from './rastro.mjs';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
|
-
* @typedef {{ motivo: string }} Violation
|
|
8
|
+
* @typedef {{ motivo: string, decisao?: 'negar' | 'perguntar' }} Violation
|
|
9
9
|
* @typedef {{ root: string, mode: 'aviso' | 'bloqueio' }} HookContext
|
|
10
10
|
* @callback Handler
|
|
11
11
|
* @param {Record<string, any>} input
|
|
@@ -19,17 +19,20 @@ async function readStdin() {
|
|
|
19
19
|
return data;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/** @type {readonly string[]} */
|
|
23
|
+
const MODOS_FORCADOS = ['aviso', 'bloqueio'];
|
|
24
|
+
|
|
22
25
|
/**
|
|
23
|
-
*
|
|
24
|
-
* acrescenta contexto; nos demais eventos o bloqueio usa `decision: "block"`.
|
|
26
|
+
* Fora de `PreToolUse`, o bloqueio responde `decision: "block"`, mesmo quando a decisão é perguntar.
|
|
25
27
|
* @param {string} event
|
|
26
28
|
* @param {'aviso' | 'bloqueio'} mode
|
|
29
|
+
* @param {boolean} pergunta
|
|
27
30
|
* @param {string} message
|
|
28
31
|
*/
|
|
29
|
-
function response(event, mode, message) {
|
|
32
|
+
function response(event, mode, pergunta, message) {
|
|
30
33
|
if (event === 'PreToolUse') {
|
|
31
34
|
return mode === 'bloqueio'
|
|
32
|
-
? { hookSpecificOutput: { hookEventName: event, permissionDecision: 'deny', permissionDecisionReason: message } }
|
|
35
|
+
? { hookSpecificOutput: { hookEventName: event, permissionDecision: pergunta ? 'ask' : 'deny', permissionDecisionReason: message } }
|
|
33
36
|
: { hookSpecificOutput: { hookEventName: event, additionalContext: message } };
|
|
34
37
|
}
|
|
35
38
|
if (mode === 'bloqueio') return { decision: 'block', reason: message };
|
|
@@ -37,8 +40,9 @@ function response(event, mode, message) {
|
|
|
37
40
|
}
|
|
38
41
|
|
|
39
42
|
/**
|
|
40
|
-
* Executa um hook
|
|
41
|
-
*
|
|
43
|
+
* Executa um hook; o handler devolve `{ motivo, decisao? }` ou null. `perguntar` pede aprovação só em
|
|
44
|
+
* `PreToolUse` no modo bloqueio. Erros falham abertos, exceto em hook de segurança no modo bloqueio.
|
|
45
|
+
* `AI_HARNESS_MODO_FORCADO` troca o modo da config; `AI_HARNESS_SEM_RASTRO=1` não grava evento.
|
|
42
46
|
* @param {string} name
|
|
43
47
|
* @param {Handler} handler
|
|
44
48
|
*/
|
|
@@ -53,7 +57,8 @@ export async function runHook(name, handler) {
|
|
|
53
57
|
if (typeof input !== 'object' || input === null) return;
|
|
54
58
|
|
|
55
59
|
const root = process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd();
|
|
56
|
-
const
|
|
60
|
+
const forcado = process.env.AI_HARNESS_MODO_FORCADO;
|
|
61
|
+
const mode = forcado && MODOS_FORCADOS.includes(forcado) ? /** @type {'aviso' | 'bloqueio'} */ (forcado) : hookMode(root, name);
|
|
57
62
|
if (mode === 'desligado') return;
|
|
58
63
|
|
|
59
64
|
/** @type {Violation | null} */
|
|
@@ -67,17 +72,22 @@ export async function runHook(name, handler) {
|
|
|
67
72
|
}
|
|
68
73
|
if (!violation) return;
|
|
69
74
|
|
|
75
|
+
const event = String(input.hook_event_name ?? '');
|
|
76
|
+
const pergunta = mode === 'bloqueio' && event === 'PreToolUse' && violation.decisao === 'perguntar';
|
|
70
77
|
const message = `[ai-harness · ${name}] ${violation.motivo}`;
|
|
71
|
-
process.stdout.write(JSON.stringify(response(
|
|
78
|
+
process.stdout.write(JSON.stringify(response(event, mode, pergunta, message)));
|
|
79
|
+
if (process.env.AI_HARNESS_SEM_RASTRO === '1') return;
|
|
72
80
|
|
|
81
|
+
const bloqueou = mode === 'bloqueio' && !pergunta;
|
|
82
|
+
const motivo = violation.motivo.slice(0, 1000);
|
|
73
83
|
try {
|
|
74
84
|
recordEvent(root, {
|
|
75
|
-
evento:
|
|
85
|
+
evento: bloqueou ? 'hook_bloqueio' : 'hook_aviso',
|
|
76
86
|
origem: 'hook',
|
|
77
87
|
nome: name,
|
|
78
88
|
modo: mode,
|
|
79
|
-
resultado:
|
|
80
|
-
dados: { motivo:
|
|
89
|
+
resultado: bloqueou ? 'bloqueio' : 'aviso',
|
|
90
|
+
dados: pergunta ? { motivo, decisao: 'perguntar' } : { motivo },
|
|
81
91
|
});
|
|
82
92
|
} catch {
|
|
83
93
|
// o rastro nunca impede a resposta do hook.
|