@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.
@@ -0,0 +1,101 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { CONFIG_PATH } from '../config/config.js';
5
+ import { isHarnessPluginEnabled } from '../install/hooks.js';
6
+ import { EVENT_PERMISSION, HARNESS_DENY, SEGREDOS_DENY, SETTINGS_PATH } from '../install/settings.js';
7
+ const ALLOW_PERIGOSO = ['Bash', 'Bash(*)', 'Bash(rm:*)', 'Bash(git reset:*)', 'Bash(git clean:*)', 'Bash(curl:*)'];
8
+ const HOOKS_SEGURANCA = ['comando-destrutivo', 'arquivo-sensivel', 'segredo-no-commit'];
9
+ const HOOKS_DE_SHELL = ['comando-destrutivo', 'segredo-no-commit'];
10
+ const VARIAVEL_POWERSHELL = 'CLAUDE_CODE_USE_POWERSHELL_TOOL';
11
+ const UPDATE = '`npx @fontdata/ai-harness update --yes`';
12
+ const isObjeto = (valor) => typeof valor === 'object' && valor !== null && !Array.isArray(valor);
13
+ const listaDeTexto = (valor) => (Array.isArray(valor) ? valor.filter((item) => typeof item === 'string') : []);
14
+ function lerObjeto(arquivo) {
15
+ try {
16
+ const conteudo = JSON.parse(readFileSync(arquivo, 'utf8'));
17
+ return isObjeto(conteudo) ? conteudo : null;
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ function powershellHabilitado(root, home, settings) {
24
+ const arquivos = [settings, lerObjeto(join(root, '.claude', 'settings.local.json')), lerObjeto(join(home, '.claude', 'settings.json'))];
25
+ return arquivos.some((arquivo) => {
26
+ const valor = isObjeto(arquivo?.env) ? arquivo.env[VARIAVEL_POWERSHELL] : undefined;
27
+ return valor === '1' || valor === 'true' || valor === 1 || valor === true;
28
+ });
29
+ }
30
+ function matcherIncluiPowerShell(matcher) {
31
+ if (matcher === undefined || matcher === '' || matcher === '*')
32
+ return true;
33
+ return typeof matcher === 'string' && matcher.split('|').some((parte) => parte.trim() === 'PowerShell');
34
+ }
35
+ function hooksDeShellSemPowerShell(settings) {
36
+ const grupos = isObjeto(settings.hooks) && Array.isArray(settings.hooks.PreToolUse) ? settings.hooks.PreToolUse : [];
37
+ const nomes = grupos.filter(isObjeto).flatMap((grupo) => {
38
+ if (matcherIncluiPowerShell(grupo.matcher))
39
+ return [];
40
+ const comandos = (Array.isArray(grupo.hooks) ? grupo.hooks : []).map((hook) => (isObjeto(hook) && typeof hook.command === 'string' ? hook.command : ''));
41
+ return HOOKS_DE_SHELL.filter((nome) => comandos.some((comando) => comando.includes(`/${nome}.mjs`)));
42
+ });
43
+ return [...new Set(nomes)];
44
+ }
45
+ /** Avisa quando o settings do projeto ou o config deixam a proteção contra comandos destrutivos fraca ou desligada. */
46
+ export function checkSeguranca(root, config, home = homedir()) {
47
+ const settings = lerObjeto(join(root, SETTINGS_PATH));
48
+ if (!settings)
49
+ return [];
50
+ const permissoes = isObjeto(settings.permissions) ? settings.permissions : {};
51
+ const arquivo = join(root, SETTINGS_PATH);
52
+ const findings = [];
53
+ const allow = listaDeTexto(permissoes.allow);
54
+ const perigosas = allow.filter((regra) => ALLOW_PERIGOSO.includes(regra));
55
+ if (perigosas.length) {
56
+ findings.push({
57
+ id: 'seguranca-allow-perigoso',
58
+ severidade: 'aviso',
59
+ mensagem: `O permissions.allow de ${arquivo} libera sem aprovação comandos que apagam ou baixam código: ${perigosas.join(', ')}.`,
60
+ correcao: `Tire ${perigosas.join(', ')} do permissions.allow e libere só os comandos estreitos de que o projeto precisa.`,
61
+ });
62
+ }
63
+ if (permissoes.defaultMode === 'bypassPermissions') {
64
+ findings.push({
65
+ id: 'seguranca-bypass-padrao',
66
+ severidade: 'aviso',
67
+ mensagem: `O permissions.defaultMode de ${arquivo} é bypassPermissions: toda sessão começa sem pedir aprovação.`,
68
+ correcao: 'Remova o defaultMode ou use um modo que pergunte; o bypass, quando preciso, se liga por sessão.',
69
+ });
70
+ }
71
+ const deny = listaDeTexto(permissoes.deny);
72
+ const esperadas = config.seguranca.negar_leitura_segredos ? [...HARNESS_DENY, ...SEGREDOS_DENY] : HARNESS_DENY;
73
+ // O harness só grava o deny junto da permissão de evento; sem ela, o settings não é dele.
74
+ const ausentes = allow.includes(EVENT_PERMISSION) ? esperadas.filter((regra) => !deny.includes(regra)) : [];
75
+ if (ausentes.length) {
76
+ findings.push({
77
+ id: 'seguranca-deny-ausente',
78
+ severidade: 'aviso',
79
+ mensagem: `Faltam no permissions.deny de ${arquivo} regras do harness: ${ausentes.join(', ')}.`,
80
+ correcao: `Restaure com ${UPDATE}; para não negar a leitura de segredos, use seguranca.negar_leitura_segredos: false em ${CONFIG_PATH}.`,
81
+ });
82
+ }
83
+ for (const nome of HOOKS_SEGURANCA.filter((hook) => config.hooks[hook] === 'desligado')) {
84
+ findings.push({
85
+ id: 'seguranca-hook-desligado',
86
+ severidade: 'aviso',
87
+ mensagem: `O hook ${nome} está desligado em ${join(root, CONFIG_PATH)}.`,
88
+ correcao: `Volte hooks.${nome} para bloqueio (ou aviso, se precisar de uma saída temporária) em ${CONFIG_PATH}.`,
89
+ });
90
+ }
91
+ const semPowerShell = powershellHabilitado(root, home, settings) && !isHarnessPluginEnabled(root, home) ? hooksDeShellSemPowerShell(settings) : [];
92
+ if (semPowerShell.length) {
93
+ findings.push({
94
+ id: 'seguranca-powershell-sem-hook',
95
+ severidade: 'aviso',
96
+ mensagem: `A ferramenta PowerShell está habilitada (${VARIAVEL_POWERSHELL}), mas em ${arquivo} o registro de ${semPowerShell.join(', ')} não inclui PowerShell no matcher.`,
97
+ correcao: `Atualize os registros com ${UPDATE}, que passa o matcher para Bash|PowerShell.`,
98
+ });
99
+ }
100
+ return findings;
101
+ }
package/dist/init.js CHANGED
@@ -104,7 +104,7 @@ async function selectByGroups(catalog, initialIds = new Set()) {
104
104
  }
105
105
  /** Config com os padrões (sem sobrescrever a existente) e o bloco gerenciado do .gitignore. */
106
106
  function prepareProjectFiles(repoPath) {
107
- writeDefaultConfig(repoPath);
107
+ writeDefaultConfig(repoPath, { seguranca: true });
108
108
  syncGitignore(repoPath, readConfig(repoPath).config);
109
109
  }
110
110
  /**
@@ -4,15 +4,17 @@ import { allCommands, recommendedCommands, templatesDir } from '../catalog.js';
4
4
  import { runnableIds, suggestIds } from '../run.js';
5
5
  import { applyAtomically } from './atomic.js';
6
6
  import { buildLockItem, hashContent, LOCK_VERSION, readLock, writeLock } from './lock.js';
7
- import { HOOKS_ITEM_ID, PROJECT_HOOKS_DIR, projectHooksConfig } from './hooks.js';
7
+ import { HOOKS_ITEM_ID, isHarnessPluginEnabled, PROJECT_HOOKS_DIR, projectHooksConfig } from './hooks.js';
8
8
  import { neededSkillsFor, resolveSelection } from './selection.js';
9
9
  import { BANCO_MCP_NOME, bancoMcpServer, MCP_PATH, mergeMcpServers } from './mcp.js';
10
10
  import { gravarInstalarComentarios, gravarRegistrarMcp, readConfig } from '../config/config.js';
11
11
  import { COMMENTS_RULE_PATH, commentsHooksConfig, ensureCommentsBaseline, hookProprio, hookProprioRegistrado } from '../comentarios/instalar.js';
12
12
  import { perfilDelphiHooksConfig, perfisDoProjeto } from './perfis.js';
13
- import { combineHooks, HARNESS_DENY, harnessPermissions, mergeSettings } from './settings.js';
13
+ import { combineHooks, harnessDeny, harnessPermissions, mergeSettings } from './settings.js';
14
14
  /** Rule de convenção com o que é específico do projeto (D-38): é do projeto, então fica fora do lock. */
15
15
  export const PROJECT_RULE_PATH = '.claude/rules/harness-projeto.md';
16
+ export const SECURITY_RULE_ID = 'seguranca';
17
+ const SECURITY_RULE_PATH = '.claude/rules/seguranca.md';
16
18
  /** Esqueleto da rule de projeto; os comandos `-legado` renomeados pelo update entram na última seção. */
17
19
  export function projectRuleContent(legacy) {
18
20
  const template = readFileSync(join(templatesDir, 'rules', 'harness-projeto.md'), 'utf8');
@@ -77,6 +79,9 @@ export function itemSources(catalog, tipo, id) {
77
79
  if (tipo === 'rule' && id === 'comentarios') {
78
80
  return [{ path: COMMENTS_RULE_PATH, source: join(templatesDir, 'rules', 'comentarios.md') }];
79
81
  }
82
+ if (tipo === 'rule' && id === SECURITY_RULE_ID) {
83
+ return [{ path: SECURITY_RULE_PATH, source: join(templatesDir, 'rules', 'seguranca.md') }];
84
+ }
80
85
  if (tipo === 'perfil') {
81
86
  const perfil = catalog.perfis?.find((candidate) => candidate.id === id);
82
87
  if (!perfil)
@@ -178,6 +183,8 @@ export function planInstall(catalog, root, options) {
178
183
  add('skill', skill.id);
179
184
  if (options.hooks)
180
185
  add('hook', HOOKS_ITEM_ID);
186
+ if (options.hooks || isHarnessPluginEnabled(root))
187
+ add('rule', SECURITY_RULE_ID);
181
188
  if (options.agents)
182
189
  for (const agent of catalog.agents ?? [])
183
190
  add('agent', agent.id);
@@ -220,7 +227,13 @@ export function executePlan(root, plan, pkg, now = new Date()) {
220
227
  const permission = needsEventPermission(plan);
221
228
  const hooks = combineHooks(plan.registerHooks ? projectHooksConfig() : {}, plan.registerComments ? commentsHooksConfig() : {}, plan.registerPerfilDelphi ? perfilDelphiHooksConfig() : {});
222
229
  if (Object.keys(hooks).length || permission) {
223
- mergeSettings(root, { hooks, allow: permission ? harnessPermissions({ banco: bancoAtivo(plan) }) : [], deny: permission ? HARNESS_DENY : [] }, now);
230
+ const { seguranca } = readConfig(root).config;
231
+ mergeSettings(root, {
232
+ hooks,
233
+ allow: permission ? harnessPermissions({ banco: bancoAtivo(plan) }) : [],
234
+ deny: permission ? harnessDeny({ negarLeituraSegredos: seguranca.negar_leitura_segredos }) : [],
235
+ disableBypass: permission && seguranca.desligar_bypass,
236
+ }, now);
224
237
  }
225
238
  if (plan.registerComments)
226
239
  ensureCommentsBaseline(root);
@@ -1,5 +1,6 @@
1
1
  import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
+ import { projectHooksConfig } from './hooks.js';
3
4
  export const SETTINGS_PATH = join('.claude', 'settings.json');
4
5
  /** As skills de fluxo e os agents registram o rastro por este comando; sem a regra, cada evento pede aprovação. */
5
6
  export const EVENT_PERMISSION = 'Bash(npx @fontdata/ai-harness evento:*)';
@@ -34,14 +35,15 @@ export const READ_PERMISSIONS = [
34
35
  'Bash(gh pr diff:*)',
35
36
  'Bash(npm outdated:*)',
36
37
  ];
37
- const BANCO_TOOLS = ['listar_conexoes', 'listar_tabelas', 'descrever_tabela', 'consultar'];
38
+ const BANCO_TOOLS_LEGADAS = ['listar_conexoes', 'listar_tabelas', 'descrever_tabela', 'consultar'];
39
+ const BANCO_TOOLS = [...BANCO_TOOLS_LEGADAS, 'listar_bancos'];
38
40
  /**
39
41
  * Ferramentas do servidor MCP de banco, registrado pelo `.mcp.json` (`banco_dados`) ou pelo plugin
40
42
  * (`banco_dados`). A `consultar` também é liberada: os dados pessoais chegam mascarados.
41
43
  */
42
44
  export const BANCO_PERMISSIONS = ['mcp__banco_dados__', 'mcp__plugin_fontdata_banco_dados__'].flatMap((prefixo) => BANCO_TOOLS.map((ferramenta) => `${prefixo}${ferramenta}`));
43
45
  /** As mesmas regras com o nome antigo do servidor (`banco`, até a 2.7.0); o update as remove. */
44
- export const BANCO_PERMISSIONS_LEGADAS = ['mcp__banco__', 'mcp__plugin_fontdata_banco__'].flatMap((prefixo) => BANCO_TOOLS.map((ferramenta) => `${prefixo}${ferramenta}`));
46
+ export const BANCO_PERMISSIONS_LEGADAS = ['mcp__banco__', 'mcp__plugin_fontdata_banco__'].flatMap((prefixo) => BANCO_TOOLS_LEGADAS.map((ferramenta) => `${prefixo}${ferramenta}`));
45
47
  /** Regras de `permissions.allow` que o init e o update gravam para as skills e os agents do harness. */
46
48
  export const HARNESS_PERMISSIONS = [
47
49
  EVENT_PERMISSION,
@@ -65,6 +67,25 @@ export const HARNESS_DENY = [
65
67
  'Bash(git push * -f *)',
66
68
  'Bash(git push * +*)',
67
69
  ];
70
+ /** Sem curinga `.env.*`: como `deny` vence `allow`, ele deixaria o `.env.example` ilegível. */
71
+ export const SEGREDOS_DENY = [
72
+ 'Read(**/.env)',
73
+ 'Read(**/.env.local)',
74
+ 'Read(**/.env.*.local)',
75
+ 'Read(**/.env.development)',
76
+ 'Read(**/.env.dev)',
77
+ 'Read(**/.env.test)',
78
+ 'Read(**/.env.staging)',
79
+ 'Read(**/.env.production)',
80
+ 'Read(**/.env.prod)',
81
+ 'Read(**/*.pem)',
82
+ 'Read(**/*.key)',
83
+ 'Read(~/.ssh/**)',
84
+ 'Read(~/.aws/**)',
85
+ ];
86
+ export function harnessDeny({ negarLeituraSegredos }) {
87
+ return negarLeituraSegredos ? [...HARNESS_DENY, ...SEGREDOS_DENY] : HARNESS_DENY;
88
+ }
68
89
  function isPlainObject(value) {
69
90
  return typeof value === 'object' && value !== null && !Array.isArray(value);
70
91
  }
@@ -82,6 +103,18 @@ export function combineHooks(...configs) {
82
103
  }
83
104
  return combined;
84
105
  }
106
+ function lerPermissoes(root) {
107
+ try {
108
+ const settings = JSON.parse(readFileSync(join(root, SETTINGS_PATH), 'utf8'));
109
+ return isPlainObject(settings.permissions) ? settings.permissions : undefined;
110
+ }
111
+ catch {
112
+ return undefined;
113
+ }
114
+ }
115
+ export function bypassDesligado(root) {
116
+ return lerPermissoes(root)?.disableBypassPermissionsMode === 'disable';
117
+ }
85
118
  /** A regra já está em `permissions.allow` (ou na lista pedida) do `.claude/settings.json` do projeto? */
86
119
  export function hasAllowRule(root, rule, key = 'allow') {
87
120
  try {
@@ -101,6 +134,21 @@ export function hookCommands(hooks) {
101
134
  export function normalizarComandoHook(command) {
102
135
  return command.replace(/\$CLAUDE_PROJECT_DIR\b/g, '${CLAUDE_PROJECT_DIR}');
103
136
  }
137
+ function chaveHook(matcher, hook) {
138
+ const texto = (valor) => (typeof valor === 'string' ? valor : '');
139
+ return JSON.stringify([texto(matcher), normalizarComandoHook(texto(hook.command)), texto(hook.if)]);
140
+ }
141
+ function chavesDoEvento(grupos) {
142
+ return (Array.isArray(grupos) ? grupos : []).flatMap((grupo) => isPlainObject(grupo) && Array.isArray(grupo.hooks) ? grupo.hooks.filter(isPlainObject).map((hook) => chaveHook(grupo.matcher, hook)) : []);
143
+ }
144
+ export function hooksRegistrados(atual, desejado) {
145
+ if (!isPlainObject(atual))
146
+ return false;
147
+ return Object.entries(desejado).every(([evento, grupos]) => {
148
+ const existentes = new Set(chavesDoEvento(atual[evento]));
149
+ return grupos.every((grupo) => grupo.hooks.every((hook) => existentes.has(chaveHook(grupo.matcher, { ...hook }))));
150
+ });
151
+ }
104
152
  /**
105
153
  * Tira de `hooks` as entradas com esses comandos, nas duas grafias de `CLAUDE_PROJECT_DIR`, e apaga os grupos, os
106
154
  * eventos e a chave `hooks` que ficarem vazios. As outras chaves e os valores fora do formato esperado ficam como estão.
@@ -138,10 +186,9 @@ export function mergeHooksIntoSettings(root, hooks, now = new Date()) {
138
186
  }
139
187
  /**
140
188
  * Acrescenta hooks e regras de `permissions.allow` ao `.claude/settings.json` do projeto
141
- * sem perder o que já existe. Um hook é considerado presente quando algum grupo do mesmo
142
- * evento já tem o mesmo `command`, nas duas grafias de `CLAUDE_PROJECT_DIR`, e uma regra quando já está na lista, o que torna a
143
- * operação idempotente. As regras de `removeAllow` saem de `permissions.allow`. Tudo é gravado de uma vez, com um único backup datado do arquivo
144
- * original; JSON inválido é recusado sem tocar em nada. Os hooks de `removeHooks` saem antes dos acréscimos.
189
+ * sem perder o que já existe. Um hook está presente com o mesmo `command` (nas duas grafias de `CLAUDE_PROJECT_DIR`), `matcher`
190
+ * e `if`; o do `hooks.json` com outro `matcher` ou `if` sai do grupo antigo e vai para o do pedido. Uma regra está presente quando já está na lista,
191
+ * o que torna a operação idempotente. `remove*` tiram regras e hooks (`removeHooks` antes dos acréscimos). Tudo é gravado de uma vez, com um único backup datado; JSON inválido é recusado.
145
192
  */
146
193
  export function mergeSettings(root, additions, now = new Date()) {
147
194
  const file = join(root, SETTINGS_PATH);
@@ -179,15 +226,33 @@ export function mergeSettings(root, additions, now = new Date()) {
179
226
  if (hookEntries.length) {
180
227
  const merged = { ...(next.hooks ?? {}) };
181
228
  for (const [event, groups] of hookEntries) {
182
- const eventGroups = [...(merged[event] ?? [])];
183
- const known = new Set(hookCommands({ [event]: eventGroups }).map(normalizarComandoHook));
229
+ const desejadas = new Set(groups.flatMap((group) => group.hooks.map((hook) => chaveHook(group.matcher, { ...hook }))));
230
+ const doNucleo = new Set(hookCommands(projectHooksConfig()).map(normalizarComandoHook));
231
+ const doHarness = new Set(groups.flatMap((group) => group.hooks.map((hook) => normalizarComandoHook(hook.command))).filter((comando) => doNucleo.has(comando)));
232
+ const foraDoLugar = (matcher, hook) => isPlainObject(hook) && typeof hook.command === 'string' && doHarness.has(normalizarComandoHook(hook.command)) && !desejadas.has(chaveHook(matcher, hook));
233
+ const eventGroups = [...(merged[event] ?? [])].flatMap((group) => {
234
+ if (!isPlainObject(group) || !Array.isArray(group.hooks))
235
+ return [group];
236
+ const mantidos = group.hooks.filter((hook) => !foraDoLugar(group.matcher, hook));
237
+ if (mantidos.length === group.hooks.length)
238
+ return [group];
239
+ changed = true;
240
+ return mantidos.length ? [{ ...group, hooks: mantidos }] : [];
241
+ });
242
+ const known = new Set([...chavesDoEvento(eventGroups), ...hookCommands({ [event]: eventGroups }).map(normalizarComandoHook)]);
243
+ const chave = (matcher, hook) => doHarness.has(normalizarComandoHook(hook.command)) ? chaveHook(matcher, { ...hook }) : normalizarComandoHook(hook.command);
184
244
  for (const group of groups) {
185
- const missing = group.hooks.filter((hook) => !known.has(normalizarComandoHook(hook.command)));
245
+ const missing = group.hooks.filter((hook) => !known.has(chave(group.matcher, hook)));
186
246
  if (!missing.length)
187
247
  continue;
188
- eventGroups.push({ ...group, hooks: missing });
248
+ const irmaos = new Set(group.hooks.map((hook) => chaveHook(group.matcher, { ...hook })));
249
+ const destino = eventGroups.findIndex((existente) => chavesDoEvento([existente]).some((chave) => irmaos.has(chave)));
250
+ if (destino >= 0)
251
+ eventGroups[destino] = { ...eventGroups[destino], hooks: [...eventGroups[destino].hooks, ...missing] };
252
+ else
253
+ eventGroups.push({ ...group, hooks: missing });
189
254
  for (const hook of missing)
190
- known.add(normalizarComandoHook(hook.command));
255
+ known.add(chave(group.matcher, hook));
191
256
  changed = true;
192
257
  }
193
258
  merged[event] = eventGroups;
@@ -208,10 +273,16 @@ export function mergeSettings(root, additions, now = new Date()) {
208
273
  }
209
274
  next.permissions = { ...permissions, [key]: list };
210
275
  }
211
- const remove = additions.removeAllow ?? [];
212
- const currentAllow = next.permissions?.allow;
213
- if (remove.length && currentAllow?.some((rule) => remove.includes(rule))) {
214
- next.permissions = { ...next.permissions, allow: currentAllow.filter((rule) => !remove.includes(rule)) };
276
+ for (const [key, remove] of [['allow', additions.removeAllow ?? []], ['deny', additions.removeDeny ?? []]]) {
277
+ const current = next.permissions?.[key];
278
+ if (remove.length && current?.some((rule) => remove.includes(rule))) {
279
+ next.permissions = { ...next.permissions, [key]: current.filter((rule) => !remove.includes(rule)) };
280
+ changed = true;
281
+ }
282
+ }
283
+ const permissions = next.permissions ?? {};
284
+ if (additions.disableBypass && permissions.disableBypassPermissionsMode !== 'disable') {
285
+ next.permissions = { ...permissions, disableBypassPermissionsMode: 'disable' };
215
286
  changed = true;
216
287
  }
217
288
  if (!changed)
@@ -0,0 +1,90 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { join, relative } from 'node:path';
4
+ import { templatesDir } from '../catalog.js';
5
+ import { DEFAULT_HOOK_MODES, readConfig } from '../config/config.js';
6
+ import { PROJECT_HOOKS_DIR } from '../install/hooks.js';
7
+ import { acharRaiz } from '../raiz.js';
8
+ const HOOK = 'comando-destrutivo';
9
+ const PREFIXO = `[ai-harness · ${HOOK}] `;
10
+ const USO = 'Uso: npx @fontdata/ai-harness checar-comando "<comando>"';
11
+ export const CODIGO_SAIDA = { LIBERADO: 0, NEGADO: 2, PERGUNTA: 3 };
12
+ /** Erro de execução do hook: sai com 1, como o erro de uso. */
13
+ export class ErroChecagem extends Error {
14
+ }
15
+ function extrairRegra(mensagem) {
16
+ const texto = mensagem.startsWith(PREFIXO) ? mensagem.slice(PREFIXO.length) : mensagem;
17
+ const [, regra, motivo] = /^([a-z0-9]+(?:-[a-z0-9]+)*): ([\s\S]*)$/.exec(texto) ?? [];
18
+ return regra !== undefined && motivo !== undefined ? { regra, motivo } : { motivo: texto };
19
+ }
20
+ /**
21
+ * Roda o hook (a cópia instalada no projeto, senão a do pacote) no modo bloqueio e sem rastro, e devolve a decisão.
22
+ * `inicio` é de onde a raiz é procurada; `env` soma ao ambiente herdado. Lança `ErroChecagem` se o hook falhar.
23
+ */
24
+ export function checarComando(comando, opcoes = {}) {
25
+ const raiz = acharRaiz(opcoes.inicio);
26
+ const instalada = join(raiz, PROJECT_HOOKS_DIR, `${HOOK}.mjs`);
27
+ const hook = existsSync(instalada)
28
+ ? { origem: 'instalada', caminho: instalada }
29
+ : { origem: 'pacote', caminho: join(templatesDir, 'hooks', `${HOOK}.mjs`) };
30
+ const r = spawnSync(process.execPath, [hook.caminho], {
31
+ cwd: raiz,
32
+ input: JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: comando }, cwd: raiz }),
33
+ env: { ...process.env, ...opcoes.env, CLAUDE_PROJECT_DIR: raiz, AI_HARNESS_SEM_RASTRO: '1', AI_HARNESS_MODO_FORCADO: 'bloqueio' },
34
+ encoding: 'utf8',
35
+ });
36
+ const falha = (detalhe) => new ErroChecagem(`Erro ao executar o hook ${hook.caminho}: ${detalhe}`);
37
+ if (r.error)
38
+ throw falha(r.error.message);
39
+ if (r.status !== 0)
40
+ throw falha(`saiu com ${r.status ?? r.signal}.\n${r.stderr.trim()}`);
41
+ const modoConfigurado = readConfig(raiz).config.hooks[HOOK] ?? DEFAULT_HOOK_MODES[HOOK] ?? 'bloqueio';
42
+ const base = { raiz, hook, modoConfigurado };
43
+ if (!r.stdout.trim())
44
+ return { veredito: 'LIBERADO', ...base };
45
+ let saida;
46
+ try {
47
+ saida = JSON.parse(r.stdout);
48
+ }
49
+ catch {
50
+ throw falha(`resposta que não é JSON: ${r.stdout.trim().slice(0, 200)}`);
51
+ }
52
+ const decisao = saida.hookSpecificOutput?.permissionDecision;
53
+ const razao = saida.hookSpecificOutput?.permissionDecisionReason;
54
+ if ((decisao !== 'deny' && decisao !== 'ask') || typeof razao !== 'string') {
55
+ throw falha(`resposta inesperada (a cópia pode não aceitar AI_HARNESS_MODO_FORCADO): ${r.stdout.trim().slice(0, 200)}`);
56
+ }
57
+ return { veredito: decisao === 'deny' ? 'NEGADO' : 'PERGUNTA', ...extrairRegra(razao), ...base };
58
+ }
59
+ export function formatarChecagem(c) {
60
+ const linhas = [c.veredito];
61
+ if (c.veredito !== 'LIBERADO') {
62
+ linhas.push(`regra: ${c.regra ?? '(nenhuma)'}`, `motivo: ${c.motivo ?? ''}`);
63
+ }
64
+ const caminho = c.hook.origem === 'instalada' ? relative(c.raiz, c.hook.caminho) : c.hook.caminho;
65
+ linhas.push(`hook: ${c.hook.origem === 'instalada' ? 'cópia instalada' : 'cópia do pacote'} (${caminho})`);
66
+ if (c.modoConfigurado === 'aviso')
67
+ linhas.push('modo: no modo `aviso` configurado, só avisaria');
68
+ if (c.modoConfigurado === 'desligado')
69
+ linhas.push('modo: desligado: não roda nas sessões');
70
+ return linhas.join('\n');
71
+ }
72
+ /** `checar-comando "<comando>"`: 0 liberado, 2 negado, 3 pergunta, 1 erro de uso ou de execução. */
73
+ export function runCheckCommandCommand(argv) {
74
+ const comando = argv.join(' ');
75
+ if (!comando.trim()) {
76
+ console.error(USO);
77
+ return 1;
78
+ }
79
+ try {
80
+ const checagem = checarComando(comando);
81
+ console.log(formatarChecagem(checagem));
82
+ return CODIGO_SAIDA[checagem.veredito];
83
+ }
84
+ catch (erro) {
85
+ if (!(erro instanceof ErroChecagem))
86
+ throw erro;
87
+ console.error(erro.message);
88
+ return 1;
89
+ }
90
+ }
@@ -8,10 +8,10 @@ import { suggestFlag } from '../install/flags.js';
8
8
  import { HOOKS_ITEM_ID, isHarnessPluginEnabled, projectHooksConfig } from '../install/hooks.js';
9
9
  import { BANCO_MCP_NOME, BANCO_MCP_NOME_LEGADO, bancoMcpServer, ehEntradaGerenciada, MCP_PATH, mergeMcpServers } from '../install/mcp.js';
10
10
  import { hashContent, LOCK_PATH, LOCK_VERSION, readLock, writeLock } from '../install/lock.js';
11
- import { agentsForaDoLock, itemSources, packageInfo, PROJECT_RULE_PATH, projectRuleContent } from '../install/plan.js';
11
+ import { agentsForaDoLock, itemSources, packageInfo, PROJECT_RULE_PATH, projectRuleContent, SECURITY_RULE_ID } from '../install/plan.js';
12
12
  import { PERFIL_DELPHI_HOOK_COMMAND, perfilDelphiHooksConfig, perfilRecusadoNoConfig, PERFIS, perfisDoProjeto } from '../install/perfis.js';
13
13
  import { neededSkillsFor } from '../install/selection.js';
14
- import { BANCO_PERMISSIONS_LEGADAS, combineHooks, HARNESS_DENY, harnessPermissions, hasAllowRule, hookCommands, mergeSettings, normalizarComandoHook, SETTINGS_PATH, } from '../install/settings.js';
14
+ import { BANCO_PERMISSIONS_LEGADAS, bypassDesligado, combineHooks, harnessDeny, harnessPermissions, hasAllowRule, hookCommands, hooksRegistrados, mergeSettings, normalizarComandoHook, SEGREDOS_DENY, SETTINGS_PATH, } from '../install/settings.js';
15
15
  import { adoptLegacyInstall } from './legado.js';
16
16
  const PERFIL_DELPHI_ITEM = 'perfil:delphi';
17
17
  /** Pastas que os arquivos do item ocupam no projeto (`.claude/<tipo>/<nome>/`), as que ainda existem. */
@@ -41,7 +41,7 @@ function perfilDelphiRegistrado(root) {
41
41
  const comando = normalizarComandoHook(PERFIL_DELPHI_HOOK_COMMAND);
42
42
  return Object.keys(perfilDelphiHooksConfig()).every((evento) => hookCommands({ [evento]: hooks[evento] ?? [] }).map(normalizarComandoHook).includes(comando));
43
43
  }
44
- /** O settings do projeto já registra cada comando dos hooks do núcleo no evento dele, nas duas grafias. */
44
+ /** O settings do projeto já registra cada hook do núcleo no evento dele, com o mesmo `command`, `matcher` e `if`. */
45
45
  function hooksNucleoRegistrados(root) {
46
46
  let hooks;
47
47
  try {
@@ -50,13 +50,7 @@ function hooksNucleoRegistrados(root) {
50
50
  catch {
51
51
  return false;
52
52
  }
53
- if (!isPlainObject(hooks))
54
- return false;
55
- const registrados = hooks;
56
- return Object.entries(projectHooksConfig()).every(([evento, grupos]) => {
57
- const existentes = new Set(hookCommands({ [evento]: registrados[evento] ?? [] }).map(normalizarComandoHook));
58
- return hookCommands({ [evento]: grupos }).every((comando) => existentes.has(normalizarComandoHook(comando)));
59
- });
53
+ return hooksRegistrados(hooks, projectHooksConfig());
60
54
  }
61
55
  function isPlainObject(value) {
62
56
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -209,6 +203,8 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
209
203
  }
210
204
  for (const id of agentsForaDoLock(catalog, lock))
211
205
  addItem('agent', id, true);
206
+ if (trackedItems.has(`hook:${HOOKS_ITEM_ID}`) || isHarnessPluginEnabled(root, home))
207
+ addItem('rule', SECURITY_RULE_ID, true);
212
208
  const registrarHooksNucleo = !adotada && lock.itens.some((item) => item.tipo === 'hook' && item.id === HOOKS_ITEM_ID) && !isHarnessPluginEnabled(root, home) && !hooksNucleoRegistrados(root);
213
209
  // O padrão de comentários também chega ao lock anterior a ele, salvo com a recusa no config ou na flag. O hook é a
214
210
  // referência: o comando `comentarios` não registra a rule quando o projeto já tem uma própria.
@@ -226,9 +222,14 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
226
222
  const registrarPerfilDelphi = instalarPerfis.includes('delphi') || (!!itemDoPerfil('delphi') && !recusados.has(PERFIL_DELPHI_ITEM) && !perfilDelphiRegistrado(root));
227
223
  const registrarMcpConfig = config.banco_dados.registrar_mcp;
228
224
  const permissoesBanco = !semBanco && registrarMcpConfig;
225
+ const seguranca = { negarLeituraSegredos: config.seguranca.negar_leitura_segredos, desligarBypass: config.seguranca.desligar_bypass };
229
226
  const permissoesFaltando = [
230
227
  ...harnessPermissions({ banco: permissoesBanco }).filter((rule) => !hasAllowRule(root, rule)),
231
- ...HARNESS_DENY.filter((rule) => !hasAllowRule(root, rule, 'deny')).map((rule) => `deny ${rule}`),
228
+ ...harnessDeny({ negarLeituraSegredos: seguranca.negarLeituraSegredos })
229
+ .filter((rule) => !hasAllowRule(root, rule, 'deny'))
230
+ .map((rule) => `deny ${rule}`),
231
+ ...(seguranca.negarLeituraSegredos ? [] : SEGREDOS_DENY.filter((rule) => hasAllowRule(root, rule, 'deny')).map((rule) => `remover deny ${rule}`)),
232
+ ...(seguranca.desligarBypass && !bypassDesligado(root) ? ['disableBypassPermissionsMode "disable"'] : []),
232
233
  ];
233
234
  const permissoesLegadas = BANCO_PERMISSIONS_LEGADAS.filter((rule) => hasAllowRule(root, rule));
234
235
  const registrarMcp = !semBanco && registrarMcpConfig && !isHarnessPluginEnabled(root, home);
@@ -244,6 +245,7 @@ export function checkUpdate(root, catalog = loadCatalog(), legacy, home, { semBa
244
245
  recusarComentarios: semComentarios && config.comentarios.instalar,
245
246
  permissaoAusente: permissoesFaltando.length > 0,
246
247
  permissoesFaltando,
248
+ seguranca,
247
249
  permissoesLegadas,
248
250
  permissoesBanco,
249
251
  registrarMcp,
@@ -295,8 +297,10 @@ export function applyUpdate(root, report, options, pkg, now = new Date()) {
295
297
  const settings = mergeSettings(root, {
296
298
  hooks,
297
299
  allow: harnessPermissions({ banco: report.permissoesBanco }),
298
- deny: HARNESS_DENY,
300
+ deny: harnessDeny({ negarLeituraSegredos: report.seguranca.negarLeituraSegredos }),
299
301
  removeAllow: BANCO_PERMISSIONS_LEGADAS,
302
+ removeDeny: report.seguranca.negarLeituraSegredos ? [] : SEGREDOS_DENY,
303
+ disableBypass: report.seguranca.desligarBypass,
300
304
  removeHooks: itensRecusados(report.perfisRecusados).has(PERFIL_DELPHI_ITEM) ? [PERFIL_DELPHI_HOOK_COMMAND] : [],
301
305
  }, now);
302
306
  if (settings.changed)
@@ -422,7 +426,7 @@ export function describeUpdate(report) {
422
426
  const nucleo = report.registrarHooksNucleo ? [`Faltam hooks do harness em ${SETTINGS_PATH}; o --yes registra os que faltam.`] : [];
423
427
  const permission = report.permissaoAusente && !report.adotada
424
428
  ? [
425
- `Faltam permissões do harness em .claude/settings.json (${report.permissoesFaltando.join(', ')}); o --yes as acrescenta.`,
429
+ `Faltam permissões do harness em .claude/settings.json (${report.permissoesFaltando.join(', ')}); o --yes as aplica.`,
426
430
  ]
427
431
  : [];
428
432
  const comentarios = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fontdata/ai-harness",
3
- "version": "4.5.2",
3
+ "version": "4.7.0",
4
4
  "description": "Harness de engenharia com IA da Fontdata para Claude Code: roda os slash commands direto na pasta do projeto via npx, sem instalar nada — ou instala-os em .claude/commands.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,83 @@
1
+ // @ts-check
2
+ import { realpathSync } from 'node:fs';
3
+ import { homedir, tmpdir } from 'node:os';
4
+ import { basename, dirname, join, resolve, sep } from 'node:path';
5
+ import { runHook } from './lib/hook.mjs';
6
+
7
+ const SEM_CAIXA = process.platform === 'darwin' || process.platform === 'win32';
8
+
9
+ /** Resolve os links pelo maior ancestral que existe, porque o alvo pode não existir. @param {string} caminho */
10
+ function normalizar(caminho) {
11
+ let atual = resolve(caminho);
12
+ /** @type {string[]} */
13
+ const resto = [];
14
+ for (;;) {
15
+ try {
16
+ const real = realpathSync.native(atual);
17
+ return resto.length ? join(real, ...resto.reverse()) : real;
18
+ } catch {
19
+ const pai = dirname(atual);
20
+ if (pai === atual) return resolve(caminho);
21
+ resto.push(basename(atual));
22
+ atual = pai;
23
+ }
24
+ }
25
+ }
26
+
27
+ /** @param {string} caminho */
28
+ const chave = (caminho) => (SEM_CAIXA ? caminho.toLowerCase() : caminho);
29
+
30
+ /** @param {string} caminho @param {string} base ambos já normalizados */
31
+ function dentro(caminho, base) {
32
+ const c = chave(caminho);
33
+ const b = chave(base);
34
+ return c === b || c.startsWith(b.endsWith(sep) ? b : b + sep);
35
+ }
36
+
37
+ /** @param {string} raiz @param {string} alvo @returns {{ id: string, motivo: string, decisao: 'negar' | 'perguntar' } | null} */
38
+ function avaliar(raiz, alvo) {
39
+ const home = normalizar(homedir());
40
+ const emHome = (/** @type {string[]} */ ...partes) => normalizar(join(home, ...partes));
41
+ const emRaiz = (/** @type {string[]} */ ...partes) => normalizar(join(raiz, ...partes));
42
+ const igual = (/** @type {string} */ outro) => chave(alvo) === chave(outro);
43
+
44
+ if (alvo.split(sep).some((segmento) => chave(segmento) === '.git')) {
45
+ return { id: 'git-interno', motivo: `${alvo} fica dentro de .git/; gravar ali corrompe o repositório`, decisao: 'negar' };
46
+ }
47
+ const credenciais = [['.ssh'], ['.aws'], ['.config', 'gh'], ['.gnupg']].map((partes) => emHome(...partes));
48
+ if (credenciais.some((pasta) => dentro(alvo, pasta))) {
49
+ return { id: 'credenciais', motivo: `${alvo} fica numa pasta de credenciais do usuário`, decisao: 'negar' };
50
+ }
51
+ if (igual(emRaiz('.ai-harness', 'lock.json'))) {
52
+ return { id: 'lock-harness', motivo: 'o .ai-harness/lock.json só é gravado pelo init e pelo update do ai-harness', decisao: 'negar' };
53
+ }
54
+
55
+ const protecao = [
56
+ emRaiz('.ai-harness', 'config.json'),
57
+ emRaiz('.claude', 'settings.json'),
58
+ emRaiz('.claude', 'settings.local.json'),
59
+ emHome('.claude', 'settings.json'),
60
+ emHome('.claude', 'settings.local.json'),
61
+ ];
62
+ if (protecao.some(igual)) {
63
+ return { id: 'protecao-propria', motivo: `${alvo} configura os hooks e permissões; alterá-lo pode desligar a proteção`, decisao: 'perguntar' };
64
+ }
65
+
66
+ const liberadas = [raiz, normalizar(tmpdir()), normalizar('/tmp'), normalizar('/private/tmp'), emHome('.claude')];
67
+ if (liberadas.some((pasta) => dentro(alvo, pasta))) return null;
68
+ return { id: 'fora-da-raiz', motivo: `${alvo} fica fora da raiz do projeto (${raiz})`, decisao: 'perguntar' };
69
+ }
70
+
71
+ await runHook('arquivo-sensivel', (input, { root }) => {
72
+ const caminho = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
73
+ if (caminho === undefined || caminho === null || caminho === '') return null;
74
+ if (typeof caminho !== 'string') {
75
+ throw new Error(
76
+ `o caminho do arquivo não é texto (${typeof caminho}); se o hook travar gravações válidas, ponha ` +
77
+ 'hooks.arquivo-sensivel em "aviso" no .ai-harness/config.json até a correção'
78
+ );
79
+ }
80
+ const raiz = normalizar(root);
81
+ const regra = avaliar(raiz, normalizar(resolve(raiz, caminho)));
82
+ return regra && { motivo: `${regra.id}: ${regra.motivo}`, decisao: regra.decisao };
83
+ });