From b5fad083bda0e0ba4406ef4d9d3b57eb2a53eff1 Mon Sep 17 00:00:00 2001 From: Paulo Victor T Silva Date: Sat, 14 Nov 2026 16:20:34 -0300 Subject: [PATCH 1/3] =?UTF-8?q?fix(detect):=20detec=C3=A7=C3=A3o=20no=20Wi?= =?UTF-8?q?ndows=20l=C3=AA=20as=20chaves=20Uninstall=20(HKLM,=20WOW6432Nod?= =?UTF-8?q?e,=20HKCU)=20e=20App=20Paths=20sem=20derrubar=20tudo=20quando?= =?UTF-8?q?=20uma=20raiz=20n=C3=A3o=20existe;=20origem=20na=20detec=C3=A7?= =?UTF-8?q?=C3=A3o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CLAUDE.md | 1 + catalog/catalog.yaml | 15 +- docs/catalogo.md | 12 +- internal/catalog/catalog.go | 6 +- internal/catalog/detect.go | 13 +- internal/catalog/detect_test.go | 34 ++++ internal/detect/detect_test.go | 80 ---------- internal/detect/embed_test.go | 16 ++ internal/detect/windows.go | 70 +++++++-- internal/detect/windows_test.go | 264 ++++++++++++++++++++++++++++++++ 10 files changed, 409 insertions(+), 102 deletions(-) create mode 100644 internal/detect/embed_test.go create mode 100644 internal/detect/windows_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 970dd00..9d2c5a2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,6 +47,7 @@ Ferramenta em Go para preparar máquinas Windows, Linux e macOS com um comando ( - `internal/providers/dnf`: `rpm -q --qf %{EVR}\n pkg` e `dnf list --showduplicates pkg` (ReadOnly; `ParseList` cobre dnf4 (nome longo quebrado em duas linhas) e dnf5, só o nome exato), `dnf install -y pkg[-versão]` com `Elevate`, sem Prepare (o dnf atualiza metadados sozinho). `Validate` recusa `/`, `@` e `.rpm` (o dnf lê `dir/x.rpm` como arquivo local e `@grupo` como grupo). Erros pelo stderr (`No match for argument`/`Unable to find a match` → `ErrNotFound`, ou `ErrVersionUnsupported` se havia versão fixada). Fixtures sintéticas. - `internal/providers/pacman`: `pacman -Q pkg` e `pacman -Si pkg` (ReadOnly; `-Q` sem o `repo/`), `pacman -S --needed --noconfirm pkg` com `Elevate`, NUNCA `-Sy` (atualização parcial). `SupportsVersion` sempre recusa (`ErrVersionUnsupported`). `apt.Validate` agora recusa nome terminado em `.deb` (o apt-get o lê como arquivo local). - `internal/providers/flatpak`: `flatpak list --app --columns=application,version` e `flatpak remote-info ` (ReadOnly, `LC_ALL=C`), `flatpak install --system -y --noninteractive ` com `Elevate` (instalação de SISTEMA; remote padrão `flathub`, via `source`). `Validate` recusa `/`, `@` e sufixos `.flatpak`, `.flatpakref`, `.flatpakrepo` em id e source (o flatpak os lê como arquivo). Só a versão atual: `SupportsVersion` recusa. "already installed" vira `AlreadyInstalled`; remote ausente = `ErrNotFound` com o comando `flatpak remote-add` na mensagem (o toolkit não adiciona remote sozinho). +- Detecção fora do winget (Windows): `internal/detect/windows.go` lê só por leitura, sem elevar, os `Uninstall` de HKLM, HKLM\WOW6432Node e HKCU (nome base exato, `publisher` opcional; ignora SystemComponent e atualizações) e o `App Paths` (`app_path`, complementar), tudo num PowerShell fixo que termina em `exit 0` (antes o exit 1 de uma raiz ausente descartava a saída toda); o estado mostra a origem (`[HKCU]`, `App Paths`). Python sem detect.windows de propósito; AppX não é lido. Detalhes em `docs/catalogo.md`. - `toolkit install app[@versão]...` (`internal/cli/install.go`): carrega o catálogo (mesmas flags do `list`), valida TODOS os argumentos antes de executar qualquer coisa (`parseTarget`, `resolveVersion`: app com lista → `VersionVars` + `InstallApp` confere `VersionApplied`; `versions: true` → versão crua ao provider, validada por `ValidVersion`; sem versions → recusa `@`), monta o `Registry` com os seis providers sobre o Runner (`Deps.NewRunner`/`Providers`/`CheckElevation` injetáveis; padrão `exec.OSRunner`) e roda `Candidates` + `InstallApp` app a app (uma falha não impede os demais; erro final `falhou: a, b`). O plano é SEMPRE calculado primeiro, num passe com `DryRunRunner` (leituras REAIS, mutações só registradas) e impresso COMO SERÁ EXECUTADO com o MESMO GOOS/euid do runner real (`Deps.Euid`, nil = `os.Geteuid`; `OSRunner.Euid`: como root o Elevate não usa sudo, então o plano não mostra `sudo` nem avisa dele; no install real o passe do plano não repete cabeçalhos dos apps, mas se o plano sai vazio ou algum app falha nele o que ele escreveu é mantido; o aviso de `sudo -n` vem de `OSRunner.UsesSudo`, a mesma decisão do argv, e acende também para passo elevado com `Secret`) (`exec.OSRunner.Display`: `sudo -n -- env VAR=... cmd` no Unix com Elevate, `VAR=... cmd` com Env sem Elevate, `[exige administrador]` no Windows sem token), com aviso de `sudo -n` quando há passo elevado no Unix. `--dry-run` para aí. Sem `--dry-run`, depois do plano: `--yes`/`-y` executa direto; senão, com terminal (`Deps.Interactive`/`Stdin`), pergunta `[s/N]` (só s/sim/y/yes confirmam); sem terminal exige `--yes` (erro antes de qualquer mutação). Plano vazio (tudo instalado) não pergunta nem exige `--yes`; se algum app não for planejável, nada é instalado (valida tudo antes). `ErrNeedsAdmin` imprime a dica `sudo -v` (o toolkit nunca pede senha). Flatpak imprime o aviso de runtimes (GB) e de instalação só de sistema. Toda saída de pacote/catálogo passa por `printable`. O pacman 404 de espelho velho pede `sudo pacman -Syu` (nunca `-Sy`); `dnf install -y` aceita importar a chave GPG de repositório novo (o toolkit não adiciona repositórios). - `internal/recipes` (fase 3, PR1): `Parse(file, data)` valida receitas sobre `yaml.Node` com o mesmo rigor do catálogo (erros `arquivo:linha:col` via `catalog.Errors`, todos de uma vez; chave desconhecida/repetida, âncora/alias, id de receita = nome do arquivo, id/etapa duplicados, exatamente um entre `run` e `install`, exatamente uma ação (`powershell`/`sh`/`bash`/`wsl`) válida para o SO da receita, `success_codes` 1..65535, `timeout` até 24h, `install` só `id` ou `id@versão`, diagnóstico sem `install` nem reboot; controle/Cf/Zl/Zp é erro em tudo, e `\n`/`\t` só dentro de scripts). `Recipe.Hash` = sha256 do YAML. `LoadFS(fsys, "recipes")` lê `recipes//.yaml` (pasta tem de bater com `os`); `toolkit.Recipes` (embed) traz `wsl-dev` (sem a etapa `setup-inside`, que depende do `unix.sh` da fase 6), `linux-dev` e os `diag-*`; `assets_test.go` confere que validam e que todo `install` existe no catálogo. - `internal/state` (fase 3, PR2): `state.json` das receitas. `File`/`RecipeState`/`StepState` (status de etapa pending/running/done/skipped/failed/awaiting-reboot; de receita running/awaiting-reboot/done/failed; `Options{Yes,Verbose}` guardadas para a retomada; `User` de quem iniciou; `BootID` e `ResumeAttempts` por etapa). `FileStore{Dir, ToolkitVersion}` (Dir = `platform.Paths.StateDir`): `Load` (inexistente = vazio; link simbólico/não regular = `ErrUnsafePath`; JSON quebrado, campo desconhecido, lixo no fim, status inválido ou invariante violada = `ErrCorrupt`, nunca descartado em silêncio; `schema_version` maior que o do binário = `ErrNewerSchema`; teto 4 MiB), `Save`/`Update` (lock `state.json.lock` com O_EXCL, espera 10 s e `ErrLocked`; lock com mais de 10 min é de processo morto e é removido; escrita atômica tmp 0600 no mesmo diretório + fsync + rename + fsync do diretório; `Update` faz ler-modificar-gravar sob o mesmo lock, sem corrida). Estado inválido nunca é gravado. Lock velho só é removido se o pid gravado não existe mais (`pidAlive`, Unix) e o arquivo ainda é o mesmo (`SameFile` + data) antes do `Remove`. O lock grava `pid início` (Linux: campo 22 de `/proc//stat`): pid reaproveitado por outro processo não segura o lock, e passada 1 hora (o lock vale milissegundos) ele sai mesmo com o pid vivo. diff --git a/catalog/catalog.yaml b/catalog/catalog.yaml index d9312a3..2ff7ca5 100644 --- a/catalog/catalog.yaml +++ b/catalog/catalog.yaml @@ -2,8 +2,11 @@ # # O bloco opcional `detect` diz como achar o app já instalado FORA do gerenciador (só leitura): o .app do .dmg no # macOS, o programa do instalador no Windows, o .desktop ou o snap no Linux. Só entram valores conhecidos; sem -# certeza, o app fica sem o bloco (python não tem, e git só tem o do Windows: no macOS e no Linux ele é linha de -# comando, sem app). +# certeza, o app fica sem o bloco (python não tem: cada versão menor convive com as outras e o DisplayName +# "Python 3.12.x (64-bit)" não separa a que o usuário pediu; e git só tem o do Windows: no macOS e no Linux ele é linha de +# comando, sem app). No Windows, display_name casa com o DisplayName do registro Uninstall (nome exato, ou com +# versão e "(x64 ...)" no fim: nunca por substring), e app_path é só evidência complementar (a chave existe em +# App Paths), usada quando o Uninstall não tem o app; só entra para exe conhecido. apps: git: name: Git @@ -57,7 +60,7 @@ apps: linux: [{ provider: flatpak, id: org.mozilla.firefox }] detect: macos: { app_bundle: Firefox.app, bundle_id: org.mozilla.firefox } - windows: { display_name: Mozilla Firefox } + windows: { display_name: Mozilla Firefox, app_path: firefox.exe } linux: { desktop_id: firefox.desktop, snap: firefox } vlc: @@ -99,14 +102,14 @@ apps: linux: [{ provider: flatpak, id: com.brave.Browser }] detect: macos: { app_bundle: "Brave Browser.app", bundle_id: com.brave.Browser } - windows: { display_name: Brave } + windows: { display_name: Brave, app_path: brave.exe } chrome: name: Google Chrome category: navegadores windows: [{ provider: winget, id: Google.Chrome }] detect: - windows: { display_name: Google Chrome } + windows: { display_name: Google Chrome, app_path: chrome.exe } libreoffice: name: LibreOffice @@ -123,6 +126,8 @@ apps: category: utilitarios windows: [{ provider: winget, id: Giorgiotani.Peazip }] linux: [{ provider: flatpak, id: io.github.peazip.PeaZip }] + detect: + windows: { display_name: PeaZip } # Acesso remoto (PR13, decisão 3 do plano): RustDesk (AGPL-3.0) entra SÓ com o aviso na tela. Ids verificados em # 2026-11-14: cask rustdesk (API do Homebrew, com sha256) e flatpak com.rustdesk.RustDesk (Flathub, verificado pelo diff --git a/docs/catalogo.md b/docs/catalogo.md index 06d1eb6..167cd3a 100644 --- a/docs/catalogo.md +++ b/docs/catalogo.md @@ -82,7 +82,9 @@ Sem isto, um app instalado à mão (o Discord que veio do `.dmg`, o programa do |---|---|---|---| | `macos` | `app_bundle` | nome do bundle (`Discord.app`) | existe como pasta em `/Applications` ou `~/Applications`; a versão vem de `Contents/Info.plist` (`CFBundleShortVersionString`, senão `CFBundleVersion`) | | `macos` | `bundle_id` | `CFBundleIdentifier` (`com.hnc.Discord`) | se o nome não existir, olha o `Info.plist` dos `.app` dessas duas pastas (até 500 por pasta), para achar um app renomeado | -| `windows` | `display_name` | `DisplayName` do registro Uninstall (`Discord`) | um PowerShell de texto fixo (caminho absoluto, só leitura) lista `HKLM` e `HKCU`, visões 64 e 32 bits; a versão é o `DisplayVersion` | +| `windows` | `display_name` | `DisplayName` do registro Uninstall (`Discord`) | um PowerShell de texto fixo (caminho absoluto, só leitura, sem elevar) lê as chaves `Uninstall` de `HKLM`, `HKLM\WOW6432Node` e `HKCU`; a versão é o `DisplayVersion`; ignora `SystemComponent=1`, atualizações (`ParentKeyName`/`ReleaseType`) e nome vazio | +| `windows` | `publisher` | `Publisher` do registro (`Google LLC`) | opcional; quando informado, tem de ser igual ao do registro (sem diferenciar maiúsculas); publisher ausente no registro não casa | +| `windows` | `app_path` | nome do exe em `App Paths` (`chrome.exe`) | evidência complementar: a chave `HKLM`/`HKCU` `\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\` existe (sem versão). Só vale quando o Uninstall não tem o app. Só declare para exe conhecido; termina em `.exe`, sem barras | | `linux` | `desktop_id` | arquivo `.desktop` (`discord.desktop`) | existe em `/usr/share/applications` ou `~/.local/share/applications` | | `linux` | `flatpak_id` | id do flatpak | `flatpak list --app` (também vale quando o instalador do catálogo é o próprio flatpak: a segunda leitura é redundante, mas inofensiva) | | `linux` | `snap` | nome do snap | `snap list ` | @@ -99,6 +101,14 @@ Regras: - O `display_name` casa sem diferenciar maiúsculas com o `DisplayName` do registro **depois de tirar do fim** os grupos entre parênteses e os tokens que são só versão: `7-Zip 24.08 (x64)` casa com `7-Zip`, `Mozilla Firefox (x64 pt-BR)` com `Mozilla Firefox`; `Git Extensions` **não** casa com `Git`. Escreva o nome base. +- No Windows o estado diz de onde veio: `instalado (fora do winget)` e, no detalhe da aba, no `toolkit list` e no + `install`, o lugar: `Programas e recursos do Windows [HKCU] ("Discord")` ou `App Paths do Windows [HKLM] (chrome.exe)`. + Uma raiz do registro que falha (acesso negado, chave ausente) só some da leitura: as outras continuam valendo, e + falha de leitura NUNCA vira "instalado". O script termina sempre com `exit 0` (uma raiz ausente não pode + derrubar a saída das outras). Apps da Microsoft Store (AppX) não são lidos: o catálogo não tem nome de pacote + AppX para nenhum app. Python não tem `detect.windows` de propósito: as versões menores convivem e o `DisplayName` + (`Python 3.13.x (64-bit)`) não diz se é a que o usuário pediu. O `install` NÃO instala por cima sem o + `--force` (o aviso `já instalado fora do winget em ...` e o plano vazio); com `--force` ele segue e repete o aviso. - A detecção é de melhor esforço: `plutil`, PowerShell, `flatpak` ou `snap` ausentes ou falhando viram "não detectado", nunca um erro que trave o install. Todo texto lido (plist, registro, saída de comando, nome de arquivo) passa por `textsafe` e é limitado em tamanho. diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index f79c899..0c6dcd9 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -72,7 +72,9 @@ type Installer struct { type Detect struct { AppBundle string // macos: nome do bundle em /Applications ou ~/Applications ("Discord.app") BundleID string // macos: CFBundleIdentifier ("com.hnc.Discord") - DisplayName string // windows: DisplayName do registro Uninstall + DisplayName string // windows: DisplayName do registro Uninstall (nome exato, ou com versão e (x64) no fim) + Publisher string // windows: Publisher do registro Uninstall; quando informado, tem de ser igual (sem diferenciar maiúsculas) + AppPath string // windows: nome do exe em App Paths ("chrome.exe"); evidência complementar, só presença DesktopID string // linux: arquivo .desktop ("discord.desktop") FlatpakID string // linux: id do flatpak Snap string // linux: nome do snap @@ -82,7 +84,7 @@ type Detect struct { // Empty diz se nenhum campo está preenchido. func (d Detect) Empty() bool { - return d.AppBundle == "" && d.BundleID == "" && d.DisplayName == "" && d.DesktopID == "" && d.FlatpakID == "" && d.Snap == "" + return d.AppBundle == "" && d.BundleID == "" && d.DisplayName == "" && d.Publisher == "" && d.AppPath == "" && d.DesktopID == "" && d.FlatpakID == "" && d.Snap == "" } // App é um item do catálogo. diff --git a/internal/catalog/detect.go b/internal/catalog/detect.go index 6c62177..e54ca68 100644 --- a/internal/catalog/detect.go +++ b/internal/catalog/detect.go @@ -14,7 +14,7 @@ import ( // são erros diferentes (como nos instaladores). var detectFields = map[string][]string{ KeyMacOS: {"app_bundle", "bundle_id"}, - KeyWindows: {"display_name"}, + KeyWindows: {"display_name", "publisher", "app_path"}, KeyLinux: {"desktop_id", "flatpak_id", "snap"}, } @@ -27,6 +27,7 @@ var ( bundleIDRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]*$`) desktopIDRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*\.desktop$`) flatpakIDRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`) + appPathRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._ +-]*\.exe$`) snapRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`) ) @@ -94,7 +95,7 @@ func (p *parser) parseDetectOS(appID, osKey string, n *yaml.Node) (Detect, bool) p.errAt(v, "app %q: detect.%s: %q não pode ser vazio nem ter espaço nas pontas", appID, osKey, k.Value) continue } - if utf8.RuneCountInString(val) > maxDetectLen || (strings.Contains(val, "..") && k.Value != "display_name") { + if utf8.RuneCountInString(val) > maxDetectLen || (strings.Contains(val, "..") && k.Value != "display_name" && k.Value != "publisher") { p.errAt(v, "app %q: detect.%s: %q com tamanho ou formato inválido", appID, osKey, k.Value) continue } @@ -109,6 +110,12 @@ func (p *parser) parseDetectOS(appID, osKey string, n *yaml.Node) (Detect, bool) case "display_name": ok = true // texto livre (já sem controle e formatação pela carga); casa com o DisplayName do registro d.DisplayName = val + case "publisher": + ok = true // texto livre, como display_name + d.Publisher = val + case "app_path": + ok = appPathRe.MatchString(val) + d.AppPath = val case "desktop_id": ok = desktopIDRe.MatchString(val) d.DesktopID = val @@ -141,6 +148,8 @@ func detectHint(field string) string { return "nome do bundle terminado em .app, sem barras, como Discord.app" case "bundle_id": return "letras, números, ponto e hífen, como com.hnc.Discord" + case "app_path": + return "nome do executável terminado em .exe, sem barras, como chrome.exe" case "desktop_id": return "arquivo terminado em .desktop, sem barras" case "flatpak_id": diff --git a/internal/catalog/detect_test.go b/internal/catalog/detect_test.go index c53656b..f720977 100644 --- a/internal/catalog/detect_test.go +++ b/internal/catalog/detect_test.go @@ -93,6 +93,14 @@ func TestDetectErros(t *testing.T) { {"display com borda em branco", " detect:\n windows: { display_name: \" Discord\" }\n", `display_name`}, {"valor não é texto", " detect:\n linux: { snap: [a] }\n", `snap`}, {"ESC no valor", " detect:\n windows: { display_name: \"Dis\\ecord\" }\n", `U+001B`}, + {"publisher em outro SO", " detect:\n macos: { publisher: X }\n", `não vale para detect.macos`}, + {"app_path em outro SO", " detect:\n linux: { app_path: chrome.exe }\n", `não vale para detect.linux`}, + {"app_path sem .exe", " detect:\n windows: { app_path: chrome }\n", `app_path`}, + {"app_path com barra", " detect:\n windows: { app_path: \"a\\\\b.exe\" }\n", `app_path`}, + {"app_path com ..", " detect:\n windows: { app_path: \"a..b.exe\" }\n", `app_path`}, + {"publisher vazio", " detect:\n windows: { publisher: \" \" }\n", `publisher`}, + {"publisher com ESC", " detect:\n windows: { publisher: \"Go\\eogle\" }\n", `U+001B`}, + {"publisher gigante", " detect:\n windows: { publisher: \"" + strings.Repeat("a", 201) + "\" }\n", `publisher`}, {"bidi", " detect:\n windows: { display_name: \"Dis\\u202Ecord\" }\n", `U+202E`}, } for _, tc := range cases { @@ -118,3 +126,29 @@ func TestDetectErroTemLinhaEColuna(t *testing.T) { t.Fatalf("posição: %v", err) } } + +func TestDetectWindowsPublisherEAppPath(t *testing.T) { + src := detectBase + ` detect: + windows: { display_name: Google Chrome, publisher: "Google LLC", app_path: chrome.exe } +` + c, err := Parse("catalog.yaml", []byte(src)) + if err != nil { + t.Fatal(err) + } + a, _ := c.Get("discord") + w, ok := a.DetectFor("windows") + if !ok || w.Publisher != "Google LLC" || w.AppPath != "chrome.exe" { + t.Fatalf("%+v", w) + } + // So app_path (sem display_name) também é um bloco válido, e o Merge copia os campos novos. + only := detectBase + " detect:\n windows: { app_path: chrome.exe }\n" + c2, err := Parse("catalog.yaml", []byte(only)) + if err != nil { + t.Fatal(err) + } + m, _ := Merge(c2, nil, false) + a2, _ := m.Get("discord") + if d, ok := a2.DetectFor("windows"); !ok || d.AppPath != "chrome.exe" { + t.Fatalf("merge: %+v %v", d, ok) + } +} diff --git a/internal/detect/detect_test.go b/internal/detect/detect_test.go index 2decc44..0c805fb 100644 --- a/internal/detect/detect_test.go +++ b/internal/detect/detect_test.go @@ -237,86 +237,6 @@ func TestSemBlocoDeDeteccaoParaOSONaoFazNada(t *testing.T) { } } -const registro = "Git\t2.45.1\r\nDiscord\t1.0.9170\r\n7-Zip 24.08 (x64)\t24.08\r\nGit Extensions\t5.0\r\nMozilla Firefox (x64 pt-BR)\t129.0\r\nDis\x1b[31mcord Falso\t1\r\nProgramação Estúdio\t2.0\r\n" - -func winStub(out string) *stub { - return &stub{handle: func(exec.Cmd) (exec.Result, error) { return ok(out) }} -} - -func TestWindowsRegistroUninstall(t *testing.T) { - s := winStub(registro) - d := New(s, Options{GOOS: "windows"}) - f, found := find(t, d, app(t, " windows: { display_name: Discord }\n")) - if !found || f.Version != "1.0.9170" || !strings.Contains(f.Where, `"Discord"`) { - t.Fatalf("%v %+v", found, f) - } - // O único comando é o PowerShell fixo, só leitura, sem nada do catálogo no script. - if len(s.calls) != 1 || s.calls[0].Name != `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe` { - t.Fatalf("chamadas: %v", s.calls) - } - if strings.Contains(strings.Join(s.calls[0].Args, " "), "Discord") { - t.Fatal("o nome do catálogo não pode entrar no script") - } - s.assertReadOnly(t) - for _, k := range []string{"HKLM:", "HKCU:", "WOW6432Node"} { - if !strings.Contains(s.calls[0].Args[3], k) { - t.Fatalf("o script não cobre %s", k) - } - } -} - -func TestWindowsCasamentoPorNome(t *testing.T) { - cases := []struct { - display, version string - want bool - }{ - {"Git", "2.45.1", true}, - {"7-Zip", "24.08", true}, - {"Mozilla Firefox", "129.0", true}, - {"Programação Estúdio", "2.0", true}, - {"git", "2.45.1", true}, - {"Extensions", "", false}, - {"Dis", "", false}, - } - for _, tc := range cases { - f, found := find(t, New(winStub(registro), Options{GOOS: "windows"}), app(t, " windows: { display_name: \""+tc.display+"\" }\n")) - if found != tc.want { - t.Errorf("%q: achou=%v (%+v)", tc.display, found, f) - } - if found && tc.version != "" && f.Version != tc.version { - t.Errorf("%q: versão %q", tc.display, f.Version) - } - } - // "Git" não casa com "Git Extensions" (a entrada só com ela). - if _, found := find(t, New(winStub("Git Extensions\t5.0\r\n"), Options{GOOS: "windows"}), app(t, " windows: { display_name: Git }\n")); found { - t.Fatal("Git Extensions não é Git") - } -} - -func TestWindowsNomeComESCNaSaidaEhSanitizado(t *testing.T) { - // O display_name do catálogo com ESC é recusado pelo parser; aqui o que importa é a saída do sistema. - f, found := find(t, New(winStub("Discord (x64)\t1.0\x1b[0m\r\n"), Options{GOOS: "windows"}), app(t, " windows: { display_name: Discord }\n")) - if !found || strings.ContainsAny(f.Version+f.Where, "\x1b\x07") { - t.Fatalf("saída crua: %q %q", f.Where, f.Version) - } -} - -func TestWindowsFalhaDoPowerShellNaoEhDeteccao(t *testing.T) { - spec := app(t, " windows: { display_name: Discord }\n") - for name, h := range map[string]func(exec.Cmd) (exec.Result, error){ - "erro": func(exec.Cmd) (exec.Result, error) { return exec.Result{}, errors.New("boom") }, - "exit": func(exec.Cmd) (exec.Result, error) { - return exec.Result{ExitCode: 1, Stdout: []byte("Discord\t1")}, nil - }, - "vazio": func(exec.Cmd) (exec.Result, error) { return ok("") }, - "sem nome": func(exec.Cmd) (exec.Result, error) { return ok("\t1.0\r\n") }, - } { - if _, found := find(t, New(&stub{handle: h}, Options{GOOS: "windows"}), spec); found { - t.Errorf("%s: não deveria achar", name) - } - } -} - func TestMatchDisplayName(t *testing.T) { cases := []struct { reg, want string diff --git a/internal/detect/embed_test.go b/internal/detect/embed_test.go new file mode 100644 index 0000000..54da421 --- /dev/null +++ b/internal/detect/embed_test.go @@ -0,0 +1,16 @@ +package detect + +import ( + "os" + "testing" +) + +// embeddedCatalog lê o catálogo embutido do repositório (somente leitura). +func embeddedCatalog(t *testing.T) []byte { + t.Helper() + b, err := os.ReadFile("../../catalog/catalog.yaml") + if err != nil { + t.Fatal(err) + } + return b +} diff --git a/internal/detect/windows.go b/internal/detect/windows.go index e0608ed..3ac13d2 100644 --- a/internal/detect/windows.go +++ b/internal/detect/windows.go @@ -13,18 +13,46 @@ import ( // windowsPowerShell é fixo: um powershell.exe achado no PATH poderia ser plantado. const windowsPowerShell = `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe` -// uninstallScript lista "DisplayNameDisplayVersion" do registro Uninstall nas quatro visões: HKLM e HKCU, -// 64 e 32 bits (WOW6432Node). É texto FIXO: nada do catálogo entra no script (o casamento é feito em Go), então -// não há injeção. A saída em UTF-8 mantém os acentos dos nomes. +// uninstallScript lê o registro, SÓ LEITURA, e imprime uma linha por item, separada por TAB: +// +// U origem nome versão publisher SystemComponent atualização (chave de desinstalação) +// A origem exe (App Paths) +// +// origem: HKLM, HKLM-WOW64 (WOW6432Node) ou HKCU. "atualização" é 1 quando há ParentKeyName ou ReleaseType +// (patch, hotfix). O script é texto FIXO e ASCII: nada do catálogo entra nele (o casamento é feito em Go), então +// não há injeção. Cada raiz tem o seu try: uma que falha (acesso negado, chave ausente) só some da saída e as +// outras continuam. Termina SEMPRE com exit 0: com SilentlyContinue, uma raiz ausente (ex.: o WOW6432Node do +// HKCU) deixa $? falso e o powershell -Command sairia com 1, e antes isso descartava a saída inteira, mesmo +// com os outros apps lidos. Falha de verdade (PowerShell que não abre, timeout) continua vindo como erro ou +// exit != 0 do próprio processo e nunca vira "instalado". A saída em UTF-8 mantém os acentos dos nomes. const uninstallScript = `$ErrorActionPreference='SilentlyContinue';` + `[Console]::OutputEncoding=[Text.Encoding]::UTF8;` + - `foreach($h in 'HKLM:','HKCU:'){foreach($s in 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall','SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'){` + - `Get-ItemProperty -Path ($h+'\'+$s+'\*') | Where-Object { $_.DisplayName } | ForEach-Object { ($_.DisplayName -replace '[\t\r\n]',' ') + [char]9 + ($_.DisplayVersion -replace '[\t\r\n]',' ') } } }` + `function C($v){if($null -eq $v){''}else{([string]$v) -replace '[\t\r\n]',' '}};` + + `$t=[char]9;$cv='\SOFTWARE\Microsoft\Windows\CurrentVersion\';` + + `$u=@(@('HKLM','HKLM:'+$cv+'Uninstall'),@('HKLM-WOW64','HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'),@('HKCU','HKCU:'+$cv+'Uninstall'));` + + `foreach($r in $u){try{Get-ItemProperty -Path ($r[1]+'\*') | Where-Object { $_.DisplayName } | ForEach-Object { ` + + `$sc=if($_.SystemComponent -eq 1){'1'}else{'0'};$up=if($_.ParentKeyName -or $_.ReleaseType){'1'}else{'0'};` + + `'U'+$t+$r[0]+$t+(C $_.DisplayName)+$t+(C $_.DisplayVersion)+$t+(C $_.Publisher)+$t+$sc+$t+$up } }catch{}};` + + `foreach($r in @(@('HKLM','HKLM:'+$cv+'App Paths'),@('HKCU','HKCU:'+$cv+'App Paths'))){try{Get-ChildItem -Path $r[1] | ForEach-Object { 'A'+$t+$r[0]+$t+(C $_.PSChildName) } }catch{}};` + + `exit 0` const maxUninstallOutput = 4 << 20 +// originLabel é o nome da raiz do registro para o usuário; "" = origem desconhecida (linha descartada). +func originLabel(o string) string { + switch o { + case "HKLM": + return "HKLM" + case "HKLM-WOW64": + return "HKLM-WOW64" + case "HKCU": + return "HKCU" + } + return "" +} + func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, bool) { - if spec.DisplayName == "" || d.rn == nil { + if (spec.DisplayName == "" && spec.AppPath == "") || d.rn == nil { return Found{}, false } res, err := d.rn.Run(ctx, d.readOnly(exec.Cmd{Name: windowsPowerShell, @@ -33,14 +61,32 @@ func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, return Found{}, false } want := strings.TrimSpace(spec.DisplayName) + pub := strings.TrimSpace(spec.Publisher) + exe := strings.TrimSpace(spec.AppPath) + var viaPath *Found for _, line := range strings.Split(string(res.Stdout), "\n") { - line = strings.TrimRight(line, "\r") - name, ver, _ := strings.Cut(line, "\t") - name = strings.TrimSpace(name) - if name == "" || !MatchDisplayName(name, want) { - continue + f := strings.Split(strings.TrimRight(line, "\r"), "\t") + switch { + case len(f) == 7 && f[0] == "U" && want != "": + label := originLabel(f[1]) + name := strings.TrimSpace(f[2]) + if label == "" || name == "" || f[5] == "1" || f[6] == "1" || !MatchDisplayName(name, want) { + continue + } + if pub != "" && !strings.EqualFold(strings.TrimSpace(f[4]), pub) { + continue + } + // O Uninstall traz a versão e tem prioridade sobre o App Paths. + return Found{Where: `Programas e recursos do Windows [` + label + `] ("` + clean(name, 100) + `")`, Version: clean(f[3], 64)}, true + case len(f) == 3 && f[0] == "A" && exe != "" && viaPath == nil: + label := originLabel(f[1]) + if label != "" && strings.EqualFold(strings.TrimSpace(f[2]), exe) { + viaPath = &Found{Where: "App Paths do Windows [" + label + "] (" + clean(f[2], 100) + ")"} + } } - return Found{Where: `Programas e recursos do Windows ("` + clean(name, 100) + `")`, Version: clean(ver, 64)}, true + } + if viaPath != nil { + return *viaPath, true } return Found{}, false } diff --git a/internal/detect/windows_test.go b/internal/detect/windows_test.go new file mode 100644 index 0000000..7289624 --- /dev/null +++ b/internal/detect/windows_test.go @@ -0,0 +1,264 @@ +package detect + +import ( + "errors" + "strings" + "testing" + + "github.com/PiluTech/toolkit/internal/catalog" + "github.com/PiluTech/toolkit/internal/exec" +) + +// Formato da saída do script (ver windows.go): uma linha por item, separada por TAB. +// U origem nome versão publisher SystemComponent ParentKeyName (chave de desinstalação) +// A origem exe (App Paths) +// As fixtures são SINTÉTICAS: nomes no formato conhecido de cada instalador, não capturas de uma máquina real. + +func winStub(lines ...string) *stub { + out := strings.Join(lines, "\r\n") + "\r\n" + return &stub{handle: func(exec.Cmd) (exec.Result, error) { return ok(out) }} +} + +// u monta uma linha de chave de desinstalação. +func u(origin, name, version, publisher string) string { + return strings.Join([]string{"U", origin, name, version, publisher, "0", "0"}, "\t") +} + +func winApp(t *testing.T, fields string) catalog.App { + t.Helper() + return app(t, " windows: { "+fields+" }\n") +} + +// Cada app do catálogo embutido, com o DisplayName típico e a origem esperada. +func TestWindowsCadaAppDoCatalogoEhDetectadoComAOrigem(t *testing.T) { + cases := []struct { + id, display, version, origin string + }{ + {"git", "Git", "2.45.1", "HKLM"}, + {"vscode", "Microsoft Visual Studio Code", "1.95.0", "HKLM"}, + {"vscode", "Microsoft Visual Studio Code (User)", "1.95.0", "HKCU"}, + {"discord", "Discord", "1.0.9170", "HKCU"}, + {"firefox", "Mozilla Firefox (x64 pt-BR)", "132.0", "HKLM"}, + {"vlc", "VLC media player", "3.0.21", "HKLM"}, + {"7zip", "7-Zip 24.08 (x64 edition)", "24.08", "HKLM"}, + {"7zip", "7-Zip", "24.08", "HKLM"}, + {"brave", "Brave", "130.1.71.118", "HKLM"}, + {"chrome", "Google Chrome", "130.0.6723.92", "HKLM-WOW64"}, + {"libreoffice", "LibreOffice 25.8.2.2", "25.8.2.2", "HKLM"}, + {"peazip", "PeaZip", "9.9.0", "HKLM"}, + } + c, err := catalog.Parse("catalog.yaml", embeddedCatalog(t)) + if err != nil { + t.Fatal(err) + } + for _, tc := range cases { + a, ok := c.Get(tc.id) + if !ok { + t.Fatalf("app %s sem entrada no catálogo", tc.id) + } + s := winStub(u(tc.origin, tc.display, tc.version, "Editora")) + f, found := find(t, New(s, Options{GOOS: "windows"}), a) + if !found { + t.Errorf("%s (%q): não detectado", tc.id, tc.display) + continue + } + if f.Version != tc.version { + t.Errorf("%s: versão %q", tc.id, f.Version) + } + if !strings.Contains(f.Where, tc.origin) || !strings.Contains(f.Where, tc.display) { + t.Errorf("%s: origem não aparece em %q", tc.id, f.Where) + } + } +} + +// Controles de falso positivo: entradas parecidas que NÃO são o app. +func TestWindowsFalsosPositivosNaoCasam(t *testing.T) { + c, err := catalog.Parse("catalog.yaml", embeddedCatalog(t)) + if err != nil { + t.Fatal(err) + } + cases := []struct{ id, display string }{ + {"libreoffice", "LibreOffice 25.8 Help Pack (Portuguese)"}, + {"libreoffice", "LibreOffice 25.8.2.2 Help Pack (Portuguese)"}, + {"libreoffice", "LibreOffice Help Pack"}, + {"git", "Git Extensions"}, + {"git", "Git LFS"}, + {"vscode", "Microsoft Visual Studio Code Insiders"}, + {"brave", "Brave Update Helper"}, + {"brave", "BraveSoftware Update"}, + {"chrome", "Google Chrome Remote Desktop Host"}, + {"vlc", "VLC Skin"}, + {"7zip", "7-Zip Shell Extension"}, + {"firefox", "Mozilla Firefox ESR Helper"}, + } + for _, tc := range cases { + a, _ := c.Get(tc.id) + if _, found := find(t, New(winStub(u("HKLM", tc.display, "1.0", "X")), Options{GOOS: "windows"}), a); found { + t.Errorf("%s: %q não deveria casar", tc.id, tc.display) + } + } +} + +func TestWindowsSystemComponentEParentKeyNameSaoIgnorados(t *testing.T) { + a := winApp(t, "display_name: Git") + sys := strings.Join([]string{"U", "HKLM", "Git", "2.0", "X", "1", "0"}, "\t") + upd := strings.Join([]string{"U", "HKLM", "Git", "2.0", "X", "0", "1"}, "\t") + if _, found := find(t, New(winStub(sys, upd), Options{GOOS: "windows"}), a); found { + t.Fatal("SystemComponent=1 e atualização (ParentKeyName) não contam") + } + // Uma entrada boa depois das ignoradas ainda conta. + if _, found := find(t, New(winStub(sys, upd, u("HKLM", "Git", "2.1", "X")), Options{GOOS: "windows"}), a); !found { + t.Fatal("a entrada válida deveria casar") + } +} + +func TestWindowsDisplayNameVazioEhIgnorado(t *testing.T) { + a := winApp(t, "display_name: Git") + if _, found := find(t, New(winStub(u("HKLM", "", "1", "X"), u("HKLM", " ", "1", "X")), Options{GOOS: "windows"}), a); found { + t.Fatal("nome vazio não casa") + } +} + +func TestWindowsPublisherDeclaradoExigeIgualdade(t *testing.T) { + a := winApp(t, `display_name: Chrome, publisher: "Google LLC"`) + if _, found := find(t, New(winStub(u("HKLM", "Chrome", "1", "Outra Empresa")), Options{GOOS: "windows"}), a); found { + t.Fatal("publisher diferente não casa") + } + if _, found := find(t, New(winStub(u("HKLM", "Chrome", "1", "")), Options{GOOS: "windows"}), a); found { + t.Fatal("publisher ausente não casa quando o catálogo exige") + } + if _, found := find(t, New(winStub(u("HKLM", "Chrome", "1", "google llc")), Options{GOOS: "windows"}), a); !found { + t.Fatal("publisher igual (sem maiúsculas) deveria casar") + } +} + +func TestWindowsAppPathsComoEvidenciaComplementar(t *testing.T) { + a := winApp(t, "display_name: Google Chrome, app_path: chrome.exe") + ap := strings.Join([]string{"A", "HKLM", "chrome.exe"}, "\t") + f, found := find(t, New(winStub(ap), Options{GOOS: "windows"}), a) + if !found || !strings.Contains(f.Where, "App Paths") || !strings.Contains(f.Where, "chrome.exe") || f.Version != "" { + t.Fatalf("%v %+v", found, f) + } + // O Uninstall tem prioridade (traz a versão). + f, found = find(t, New(winStub(ap, u("HKLM", "Google Chrome", "130", "G")), Options{GOOS: "windows"}), a) + if !found || f.Version != "130" || strings.Contains(f.Where, "App Paths") { + t.Fatalf("%v %+v", found, f) + } + // Outro exe não casa; sem app_path no catálogo o App Paths é ignorado. + other := strings.Join([]string{"A", "HKCU", "firefox.exe"}, "\t") + if _, found = find(t, New(winStub(other), Options{GOOS: "windows"}), a); found { + t.Fatal("outro exe") + } + if _, found = find(t, New(winStub(ap), Options{GOOS: "windows"}), winApp(t, "display_name: Google Chrome")); found { + t.Fatal("sem app_path no catálogo") + } + // App com só app_path (sem display_name) também funciona. + if _, found = find(t, New(winStub(ap), Options{GOOS: "windows"}), winApp(t, "app_path: chrome.exe")); !found { + t.Fatal("só app_path") + } +} + +func TestWindowsTextoDeForaEhSanitizado(t *testing.T) { + a := winApp(t, "display_name: Discord") + f, found := find(t, New(winStub(u("HKCU", "Discord\x1b[31m", "1.0\x1b[0m\u202e", "P")), Options{GOOS: "windows"}), a) + // ESC no nome faz o nome diferir: não casa, e nada cru vaza. + if found { + t.Fatalf("nome com ESC não deveria casar: %+v", f) + } + f, found = find(t, New(winStub(u("HKCU", "Discord", "1.0\x1b[0m\u202e\x07", "P")), Options{GOOS: "windows"}), a) + if !found || strings.ContainsAny(f.Version+f.Where, "\x1b\x07\u202e") { + t.Fatalf("saída crua: %q %q", f.Where, f.Version) + } +} + +func TestWindowsFalhaNaoEhDeteccao(t *testing.T) { + a := winApp(t, "display_name: Discord") + for name, h := range map[string]func(exec.Cmd) (exec.Result, error){ + "erro": func(exec.Cmd) (exec.Result, error) { return exec.Result{}, errors.New("boom") }, + "exit": func(exec.Cmd) (exec.Result, error) { + return exec.Result{ExitCode: 1, Stderr: []byte("negado"), Stdout: []byte(u("HKCU", "Discord", "1", "P"))}, nil + }, + "vazio": func(exec.Cmd) (exec.Result, error) { return ok("") }, + "sem nome": func(exec.Cmd) (exec.Result, error) { return ok(u("HKCU", "", "1", "P") + "\r\n") }, + "lixo": func(exec.Cmd) (exec.Result, error) { return ok("Discord\t1.0\r\nU\r\nU\tHKCU\r\n") }, + "origem ruim": func(exec.Cmd) (exec.Result, error) { return ok(u("HKXX", "Discord", "1", "P") + "\r\n") }, + } { + if _, found := find(t, New(&stub{handle: h}, Options{GOOS: "windows"}), a); found { + t.Errorf("%s: não deveria achar", name) + } + } +} + +// Uma raiz que falha (acesso negado) só some da saída: as outras continuam valendo. +func TestWindowsRaizFaltandoNaoDerrubaAsOutras(t *testing.T) { + a := winApp(t, "display_name: Discord") + f, found := find(t, New(winStub(u("HKCU", "Discord", "1.0", "P")), Options{GOOS: "windows"}), a) + if !found || !strings.Contains(f.Where, "HKCU") { + t.Fatalf("%v %+v", found, f) + } +} + +// Contrato do comando: PowerShell fixo por caminho absoluto, só leitura, sem elevar, script ASCII, nada do +// catálogo no script, raízes cobertas e saída com exit 0 (uma raiz ausente, como o WOW6432Node do HKCU, não +// pode virar exit code diferente de zero e derrubar a detecção inteira). +func TestWindowsContratoDoComando(t *testing.T) { + s := winStub(u("HKCU", "Discord", "1", "P")) + d := New(s, Options{GOOS: "windows"}) + find(t, d, winApp(t, "display_name: Discord, publisher: Zzz, app_path: zzz.exe")) + if len(s.calls) != 1 { + t.Fatalf("chamadas: %v", s.calls) + } + c := s.calls[0] + if c.Name != `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe` || !c.ReadOnly || c.Elevate { + t.Fatalf("comando: %+v", c) + } + script := c.Args[len(c.Args)-1] + for _, r := range script { + if r > 0x7e || (r < 0x20 && r != '\n') { + t.Fatalf("script não ASCII imprimível: %q", r) + } + } + for _, k := range []string{"HKLM:", "HKCU:", `WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall`, `App Paths`, "DisplayName", "Publisher", "DisplayVersion", "SystemComponent", "ParentKeyName", "exit 0"} { + if !strings.Contains(script, k) { + t.Errorf("o script não cobre %q", k) + } + } + for _, k := range []string{"Discord", "Zzz", "zzz"} { + if strings.Contains(script, k) { + t.Errorf("%q do catálogo entrou no script", k) + } + } + for _, bad := range []string{"Set-ItemProperty", "Remove-", "New-Item", "Start-Process", "Invoke-", "reg add", "reg delete"} { + if strings.Contains(script, bad) { + t.Errorf("script com comando de escrita %q", bad) + } + } +} + +// Python não tem detect no Windows de propósito: as versões menores convivem e o DisplayName não diz qual o +// usuário pediu (detectar "Python 3.13" como "Python" faria o install de 3.12 dizer "já instalado"). +func TestWindowsPythonSemDeteccaoDeProposito(t *testing.T) { + c, err := catalog.Parse("catalog.yaml", embeddedCatalog(t)) + if err != nil { + t.Fatal(err) + } + a, _ := c.Get("python") + if _, ok := a.DetectFor("windows"); ok { + t.Fatal("python não deve ter detect.windows") + } +} + +// Os apps com app_path no catálogo embutido são detectados só por ele (instalação sem entrada no Uninstall). +func TestWindowsAppPathsDoCatalogoEmbutido(t *testing.T) { + c, err := catalog.Parse("catalog.yaml", embeddedCatalog(t)) + if err != nil { + t.Fatal(err) + } + for id, exe := range map[string]string{"chrome": "chrome.exe", "firefox": "firefox.exe", "brave": "brave.exe"} { + a, _ := c.Get(id) + f, found := find(t, New(winStub(strings.Join([]string{"A", "HKCU", exe}, "\t")), Options{GOOS: "windows"}), a) + if !found || !strings.Contains(f.Where, exe) { + t.Errorf("%s: %v %+v", id, found, f) + } + } +} From 9b2555031db302c2ef1117993ba8f0e9e423feeb Mon Sep 17 00:00:00 2001 From: Paulo Victor T Silva Date: Sat, 14 Nov 2026 16:38:15 -0300 Subject: [PATCH 2/3] =?UTF-8?q?fix(detect):=20caminhos=20do=20script=20com?= =?UTF-8?q?o=20literais=20completos=20(sem=20v=C3=ADrgula/+),=20App=20Path?= =?UTF-8?q?s=20l=C3=AA=20o=20valor=20padr=C3=A3o=20e=20exige=20execut?= =?UTF-8?q?=C3=A1vel=20local,=20status=20por=20raiz=20e=20'leitura=20incom?= =?UTF-8?q?pleta';=20teste=20que=20executa=20o=20script=20real?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/catalogo.md | 14 +- internal/cli/external_test.go | 51 +++++ internal/cli/install.go | 2 +- internal/cli/list.go | 8 + internal/cli/status.go | 19 ++ internal/cli/tui.go | 2 +- internal/detect/detect.go | 4 + internal/detect/windows.go | 114 +++++++++-- internal/detect/windows_script_test.go | 270 +++++++++++++++++++++++++ internal/detect/windows_test.go | 38 +++- internal/msg/msg.go | 2 + internal/providers/registry.go | 2 + internal/tui/apps.go | 27 ++- internal/tui/apps_external_test.go | 14 ++ 14 files changed, 531 insertions(+), 36 deletions(-) create mode 100644 internal/detect/windows_script_test.go diff --git a/docs/catalogo.md b/docs/catalogo.md index 167cd3a..11a91e9 100644 --- a/docs/catalogo.md +++ b/docs/catalogo.md @@ -84,7 +84,7 @@ Sem isto, um app instalado à mão (o Discord que veio do `.dmg`, o programa do | `macos` | `bundle_id` | `CFBundleIdentifier` (`com.hnc.Discord`) | se o nome não existir, olha o `Info.plist` dos `.app` dessas duas pastas (até 500 por pasta), para achar um app renomeado | | `windows` | `display_name` | `DisplayName` do registro Uninstall (`Discord`) | um PowerShell de texto fixo (caminho absoluto, só leitura, sem elevar) lê as chaves `Uninstall` de `HKLM`, `HKLM\WOW6432Node` e `HKCU`; a versão é o `DisplayVersion`; ignora `SystemComponent=1`, atualizações (`ParentKeyName`/`ReleaseType`) e nome vazio | | `windows` | `publisher` | `Publisher` do registro (`Google LLC`) | opcional; quando informado, tem de ser igual ao do registro (sem diferenciar maiúsculas); publisher ausente no registro não casa | -| `windows` | `app_path` | nome do exe em `App Paths` (`chrome.exe`) | evidência complementar: a chave `HKLM`/`HKCU` `\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\` existe (sem versão). Só vale quando o Uninstall não tem o app. Só declare para exe conhecido; termina em `.exe`, sem barras | +| `windows` | `app_path` | nome da subchave em `App Paths` (`chrome.exe`) | evidência complementar, sem versão, só quando o Uninstall não tem o app. Lê o **valor padrão** da subchave `HKLM`/`HKCU` `\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\`, tira as aspas externas, expande as variáveis de ambiente e exige um **executável local existente**: caminho absoluto `X:\...` terminado em `.exe`, **arquivo** (não pasta), nunca de rede (`\\servidor\...`) nem relativo; nada é executado. Valor vazio, ilegível ou inexistente = não detectado. Se o app declara `publisher`, o App Paths **não o contorna**: só vale com um Uninstall do mesmo publisher. Só declare para exe conhecido; termina em `.exe`, sem barras | | `linux` | `desktop_id` | arquivo `.desktop` (`discord.desktop`) | existe em `/usr/share/applications` ou `~/.local/share/applications` | | `linux` | `flatpak_id` | id do flatpak | `flatpak list --app` (também vale quando o instalador do catálogo é o próprio flatpak: a segunda leitura é redundante, mas inofensiva) | | `linux` | `snap` | nome do snap | `snap list ` | @@ -103,8 +103,16 @@ Regras: com `Mozilla Firefox`; `Git Extensions` **não** casa com `Git`. Escreva o nome base. - No Windows o estado diz de onde veio: `instalado (fora do winget)` e, no detalhe da aba, no `toolkit list` e no `install`, o lugar: `Programas e recursos do Windows [HKCU] ("Discord")` ou `App Paths do Windows [HKLM] (chrome.exe)`. - Uma raiz do registro que falha (acesso negado, chave ausente) só some da leitura: as outras continuam valendo, e - falha de leitura NUNCA vira "instalado". O script termina sempre com `exit 0` (uma raiz ausente não pode + O script reporta o estado de CADA raiz (Uninstall `HKLM`, `HKLM-WOW64`, `HKCU` e App Paths `HKLM`, `HKCU`): + `ok`, `ausente` (a raiz não existe: normal para `HKCU\WOW6432Node` e App Paths) ou `falhou` (erro real, como acesso + negado). As leituras válidas das outras raízes continuam valendo, e falha de leitura NUNCA vira "instalado". Se + alguma raiz relevante falhou (ou o PowerShell falhou por inteiro) e o app não foi achado, o estado é + **"não detectado (leitura incompleta)"** em vez de "não instalado" (`list --installed`: `detect_gap: "incomplete"` no + JSON; na aba Apps, "não detectado (parcial)" quando a coluna é estreita). No Windows, app **sem bloco `detect`** + (Python, Microsoft Store/AppX) aparece como "não detectado" (`detect_gap: "not_applicable"`), porque a ausência no + winget não prova que ele não está na máquina. Os caminhos do registro no script são literais completos (sem `+`: + no PowerShell a vírgula tem precedência maior); um teste estático e um teste que executa o script num PowerShell com + cmdlets falsos (só no runner Windows do CI) conferem os 3 caminhos do Uninstall e os 2 de App Paths. O script termina sempre com `exit 0` (uma raiz ausente não pode derrubar a saída das outras). Apps da Microsoft Store (AppX) não são lidos: o catálogo não tem nome de pacote AppX para nenhum app. Python não tem `detect.windows` de propósito: as versões menores convivem e o `DisplayName` (`Python 3.13.x (64-bit)`) não diz se é a que o usuário pediu. O `install` NÃO instala por cima sem o diff --git a/internal/cli/external_test.go b/internal/cli/external_test.go index 60d0d7f..016389b 100644 --- a/internal/cli/external_test.go +++ b/internal/cli/external_test.go @@ -299,3 +299,54 @@ func (invalidatingDetector) Find(context.Context, catalog.App) (detect.Found, bo return detect.Found{}, false, nil } func (d invalidatingDetector) Invalidate() { *d.n++ } + +// fakeDetector devolve sempre o mesmo resultado (para testar só o encanamento do estado). +type fakeDetector struct{ f detect.Found } + +func (d fakeDetector) Find(context.Context, catalog.App) (detect.Found, bool, error) { + return d.f, false, nil +} + +func TestEstadoLeituraIncompletaNaoViraNaoInstalado(t *testing.T) { + f := macFake(t) + deps := macDeps(f, nil) + deps.Detector = func(exec.Runner) ExternalDetector { return fakeDetector{detect.Found{Incomplete: true}} } + out, _, err := runCmd(t, deps, "list", "--installed") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "não detectado (leitura incompleta)") || strings.Contains(out, "não instalado") { + t.Fatalf("esperava 'não detectado (leitura incompleta)':\n%s", out) + } + jout, _, _ := runCmd(t, deps, "list", "--installed", "--json") + if !strings.Contains(jout, `"detect_gap": "incomplete"`) { + t.Fatalf("json sem detect_gap:\n%s", jout) + } + b := &appsBackend{deps: deps} + if st := b.Status(context.Background(), "vlc"); st.Installed || st.DetectGap != tui.DetectIncomplete { + t.Fatalf("tui: %+v", st) + } + noMutation(t, f) +} + +// No Windows, app sem bloco detect (Python, Microsoft Store): "não detectado", não "não instalado". +func TestEstadoAppSemDeteccaoNoWindowsDizNaoDetectado(t *testing.T) { + cat := `apps: + py: + name: Python + category: dev + windows: [{ provider: winget, id: Python.Python.3.12 }] +` + f := exectest.New(t).WithPath("winget", `C:\winget.exe`). + On("winget list --id Python.Python.3.12 -e --disable-interactivity", exectest.Exit(int(uint32(0x8A150014)), "")) + deps := Deps{GOOS: "windows", EmbeddedYML: []byte(cat), NewRunner: func() exec.Runner { return f }, + CheckElevation: func(exec.Cmd) error { return nil }, Interactive: func() bool { return false }, + Detector: func(r exec.Runner) ExternalDetector { return detect.New(r, detect.Options{GOOS: "windows"}) }} + out, _, err := runCmd(t, deps, "list", "--installed", "--os", "windows") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "não detectado") || strings.Contains(out, "não instalado") { + t.Fatalf("esperava 'não detectado':\n%s", out) + } +} diff --git a/internal/cli/install.go b/internal/cli/install.go index d38778f..db4bcb2 100644 --- a/internal/cli/install.go +++ b/internal/cli/install.go @@ -236,7 +236,7 @@ func (d Deps) externalFinder(rn exec.Runner, app catalog.App) providers.External } return func(ctx context.Context) (providers.External, bool, error) { f, ok, err := det.Find(ctx, app) - return providers.External{Where: f.Where, Version: f.Version}, ok, err + return providers.External{Where: f.Where, Version: f.Version, Incomplete: f.Incomplete}, ok, err } } diff --git a/internal/cli/list.go b/internal/cli/list.go index df44f40..4729eff 100644 --- a/internal/cli/list.go +++ b/internal/cli/list.go @@ -132,6 +132,9 @@ type listItem struct { ExternalPath string `json:"external_path,omitempty"` // StatusError: não deu para verificar (sem instalador aplicável, leitura falhou). StatusError string `json:"status_error,omitempty"` + // DetectGap (só com installed=false): "incomplete" (leitura do registro incompleta) ou "not_applicable" + // (app sem detecção neste SO). Nos dois casos o texto é "não detectado", nunca "não instalado". + DetectGap string `json:"detect_gap,omitempty"` } func newListCmd(deps Deps) *cobra.Command { @@ -279,6 +282,7 @@ func fillState(ctx context.Context, it *listItem, deps Deps, rn exec.Runner, reg inst := st.Installed it.Installed = &inst it.InstalledVersion = printable(st.Version) + it.DetectGap = st.DetectGap switch { case st.External != nil: it.Source = "external" @@ -295,6 +299,10 @@ func stateCell(it listItem) string { switch { case it.StatusError != "": return msg.ListStateUnknown + case (it.Installed == nil || !*it.Installed) && it.DetectGap == DetectIncomplete: + return msg.ListStateIncomplete + case (it.Installed == nil || !*it.Installed) && it.DetectGap == DetectNotApplicable: + return msg.ListStateUndetected case it.Installed == nil || !*it.Installed: return msg.ListStateNo } diff --git a/internal/cli/status.go b/internal/cli/status.go index a032837..1dad947 100644 --- a/internal/cli/status.go +++ b/internal/cli/status.go @@ -6,6 +6,7 @@ import ( "github.com/PiluTech/toolkit/internal/catalog" "github.com/PiluTech/toolkit/internal/exec" "github.com/PiluTech/toolkit/internal/providers" + "github.com/PiluTech/toolkit/internal/tui" ) // appState é o estado de um app na máquina, só por leitura: instalado pelo gerenciador do catálogo, instalado FORA @@ -14,8 +15,18 @@ type appState struct { Installed bool Version string External *providers.External + // DetectGap, com Installed false, diz por que "não instalado" seria enganoso: DetectIncomplete (a leitura do + // registro falhou em parte) ou DetectNotApplicable (o app não tem detecção no Windows, ex.: Python e apps da + // Microsoft Store). Vazio = a leitura foi completa e o app não está. + DetectGap string } +// Valores de appState.DetectGap. +const ( + DetectIncomplete = tui.DetectIncomplete + DetectNotApplicable = tui.DetectNotApplicable +) + // readState lê o estado do app pelo primeiro instalador aplicável (a mesma regra do install): primeiro o // gerenciador (IsInstalled) e, só se ele disser "não instalado", a detecção fora do gerenciador. Nada é executado // que mude o sistema. @@ -45,6 +56,14 @@ func readState(ctx context.Context, deps Deps, rn exec.Runner, reg *providers.Re ext.Manager = providers.DisplayName(c.Provider.Name()) return appState{Installed: true, Version: ext.Version, External: &ext}, nil } + if ext.Incomplete { + return appState{DetectGap: DetectIncomplete}, nil + } + if deps.GOOS == "windows" { + if _, has := app.DetectFor(deps.GOOS); !has { + return appState{DetectGap: DetectNotApplicable}, nil + } + } } return appState{}, nil } diff --git a/internal/cli/tui.go b/internal/cli/tui.go index 4542053..45b90bf 100644 --- a/internal/cli/tui.go +++ b/internal/cli/tui.go @@ -276,7 +276,7 @@ func (b *appsBackend) Status(ctx context.Context, id string) tui.AppStatus { if err != nil { return tui.AppStatus{Err: err} } - out := tui.AppStatus{Installed: st.Installed, Version: st.Version} + out := tui.AppStatus{Installed: st.Installed, Version: st.Version, DetectGap: st.DetectGap} if st.External != nil { out.External, out.ExternalManager, out.ExternalWhere = true, st.External.Manager, st.External.Where out.Version = st.External.Version diff --git a/internal/detect/detect.go b/internal/detect/detect.go index b4f6503..af3344f 100644 --- a/internal/detect/detect.go +++ b/internal/detect/detect.go @@ -28,6 +28,10 @@ type Found struct { Where string // Version é a versão lida do Info.plist, do registro, do flatpak ou do snap; vazia se não deu para ler. Já sanitizada. Version string + // Incomplete só vem com ok == false: a leitura falhou em parte (ex.: uma raiz do registro com acesso negado) + // ou por inteiro, então "não achei" NÃO quer dizer "não está instalado". A UI diz "não detectado (leitura + // incompleta)" em vez de "não instalado". + Incomplete bool } // Options configura o detector. Tudo é injetável: os testes nunca tocam o disco nem o sistema reais. diff --git a/internal/detect/windows.go b/internal/detect/windows.go index 3ac13d2..3f80665 100644 --- a/internal/detect/windows.go +++ b/internal/detect/windows.go @@ -16,24 +16,43 @@ const windowsPowerShell = `C:\Windows\System32\WindowsPowerShell\v1.0\powershell // uninstallScript lê o registro, SÓ LEITURA, e imprime uma linha por item, separada por TAB: // // U origem nome versão publisher SystemComponent atualização (chave de desinstalação) -// A origem exe (App Paths) +// A origem subchave caminho folha (App Paths: valor PADRÃO da subchave) +// S tipo origem estado (estado da raiz: ok, ausente ou falhou) // // origem: HKLM, HKLM-WOW64 (WOW6432Node) ou HKCU. "atualização" é 1 quando há ParentKeyName ou ReleaseType -// (patch, hotfix). O script é texto FIXO e ASCII: nada do catálogo entra nele (o casamento é feito em Go), então -// não há injeção. Cada raiz tem o seu try: uma que falha (acesso negado, chave ausente) só some da saída e as -// outras continuam. Termina SEMPRE com exit 0: com SilentlyContinue, uma raiz ausente (ex.: o WOW6432Node do -// HKCU) deixa $? falso e o powershell -Command sairia com 1, e antes isso descartava a saída inteira, mesmo -// com os outros apps lidos. Falha de verdade (PowerShell que não abre, timeout) continua vindo como erro ou +// (patch, hotfix). "caminho" é o valor padrão da subchave de App Paths, sem aspas externas e com as variáveis de +// ambiente expandidas ([Environment]::ExpandEnvironmentVariables, só isso); "folha" é 1 quando esse caminho é +// local absoluto (X:\...), termina em .exe e é um ARQUIVO que existe (Test-Path -PathType Leaf; nada é executado). +// O script é texto FIXO e ASCII: nada do catálogo entra nele (o casamento é feito em Go), então não há injeção. +// +// Os caminhos do registro são literais COMPLETOS, sem concatenação: no PowerShell a vírgula tem precedência +// maior que o +, então @('HKLM','HKLM:'+$cv+'X') viraria uma lista de 4 elementos. Cada raiz tem o seu +// try/catch com -ErrorAction Stop: ItemNotFoundException = "ausente" (normal para HKCU\WOW6432Node e App Paths); +// qualquer outro erro (acesso negado) = "falhou", e as leituras das outras raízes continuam valendo. O script +// termina SEMPRE com exit 0; falha de verdade (PowerShell que não abre, timeout) continua vindo como erro ou // exit != 0 do próprio processo e nunca vira "instalado". A saída em UTF-8 mantém os acentos dos nomes. -const uninstallScript = `$ErrorActionPreference='SilentlyContinue';` + +const uninstallScript = `$ErrorActionPreference='Stop';` + `[Console]::OutputEncoding=[Text.Encoding]::UTF8;` + `function C($v){if($null -eq $v){''}else{([string]$v) -replace '[\t\r\n]',' '}};` + - `$t=[char]9;$cv='\SOFTWARE\Microsoft\Windows\CurrentVersion\';` + - `$u=@(@('HKLM','HKLM:'+$cv+'Uninstall'),@('HKLM-WOW64','HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'),@('HKCU','HKCU:'+$cv+'Uninstall'));` + - `foreach($r in $u){try{Get-ItemProperty -Path ($r[1]+'\*') | Where-Object { $_.DisplayName } | ForEach-Object { ` + - `$sc=if($_.SystemComponent -eq 1){'1'}else{'0'};$up=if($_.ParentKeyName -or $_.ReleaseType){'1'}else{'0'};` + - `'U'+$t+$r[0]+$t+(C $_.DisplayName)+$t+(C $_.DisplayVersion)+$t+(C $_.Publisher)+$t+$sc+$t+$up } }catch{}};` + - `foreach($r in @(@('HKLM','HKLM:'+$cv+'App Paths'),@('HKCU','HKCU:'+$cv+'App Paths'))){try{Get-ChildItem -Path $r[1] | ForEach-Object { 'A'+$t+$r[0]+$t+(C $_.PSChildName) } }catch{}};` + + `$t=[char]9;` + + `$u=@(@{N='HKLM';P='HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'},` + + `@{N='HKLM-WOW64';P='HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'},` + + `@{N='HKCU';P='HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'});` + + `$a=@(@{N='HKLM';P='HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths'},` + + `@{N='HKCU';P='HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths'});` + + `foreach($r in $u){$s='ok';try{foreach($k in @(Get-ChildItem -Path $r.P)){try{$n=$k.GetValue('DisplayName');if($n){` + + `$sc=if($k.GetValue('SystemComponent') -eq 1){'1'}else{'0'};` + + `$up=if($k.GetValue('ParentKeyName') -or $k.GetValue('ReleaseType')){'1'}else{'0'};` + + `'U'+$t+$r.N+$t+(C $n)+$t+(C $k.GetValue('DisplayVersion'))+$t+(C $k.GetValue('Publisher'))+$t+$sc+$t+$up}}catch{$s='falhou'}}` + + `}catch [System.Management.Automation.ItemNotFoundException]{$s='ausente'}catch{$s='falhou'};` + + `'S'+$t+'U'+$t+$r.N+$t+$s};` + + `foreach($r in $a){$s='ok';try{foreach($k in @(Get-ChildItem -Path $r.P)){try{$p='';$l='0';` + + `$v=$k.GetValue('',$null,'DoNotExpandEnvironmentNames');` + + `if($v -is [string]){$p=[Environment]::ExpandEnvironmentVariables($v.Trim().Trim('"').Trim());` + + `if(($p -match '^[A-Za-z]:\\[^\\]') -and ($p -match '\.exe$')){if(Test-Path -LiteralPath $p -PathType Leaf){$l='1'}}};` + + `'A'+$t+$r.N+$t+(C $k.PSChildName)+$t+(C $p)+$t+$l}catch{$s='falhou'}}` + + `}catch [System.Management.Automation.ItemNotFoundException]{$s='ausente'}catch{$s='falhou'};` + + `'S'+$t+'A'+$t+$r.N+$t+$s};` + `exit 0` const maxUninstallOutput = 4 << 20 @@ -51,6 +70,37 @@ func originLabel(o string) string { return "" } +// rootKey identifica uma raiz do registro lida pelo script: tipo "U" (Uninstall) ou "A" (App Paths) e origem. +type rootKey struct{ kind, origin string } + +// windowsRoots são as raízes que o script lê. Uma que não reportou estado conta como falha (saída truncada). +var ( + uninstallRoots = []rootKey{{"U", "HKLM"}, {"U", "HKLM-WOW64"}, {"U", "HKCU"}} + appPathsRoots = []rootKey{{"A", "HKLM"}, {"A", "HKCU"}} +) + +// localExe diz se p é um caminho local absoluto de arquivo .exe ("X:\...\app.exe"): nada de UNC ("\\servidor\..."), +// caminho relativo, pasta de unidade nem outra extensão. +func localExe(p string) bool { + if len(p) < 4 || p[1] != ':' || p[2] != '\\' || p[3] == '\\' { + return false + } + c := p[0] | 0x20 + return c >= 'a' && c <= 'z' && strings.HasSuffix(strings.ToLower(p), ".exe") +} + +// incomplete diz se alguma das raízes relevantes não foi lida com sucesso ("ok" ou "ausente"). +func incomplete(status map[rootKey]string, roots ...[]rootKey) bool { + for _, rs := range roots { + for _, k := range rs { + if st := status[k]; st != "ok" && st != "ausente" { + return true + } + } + } + return false +} + func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, bool) { if (spec.DisplayName == "" && spec.AppPath == "") || d.rn == nil { return Found{}, false @@ -58,19 +108,32 @@ func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, res, err := d.rn.Run(ctx, d.readOnly(exec.Cmd{Name: windowsPowerShell, Args: []string{"-NoProfile", "-NonInteractive", "-Command", uninstallScript}, Timeout: 30 * time.Second})) if err != nil || res.ExitCode != 0 || len(res.Stdout) > maxUninstallOutput { - return Found{}, false + // Nada foi lido: não é "não instalado", é detecção incompleta. + return Found{Incomplete: true}, false } want := strings.TrimSpace(spec.DisplayName) pub := strings.TrimSpace(spec.Publisher) exe := strings.TrimSpace(spec.AppPath) - var viaPath *Found + var ( + viaPath *Found + pubSeen bool // há entrada de Uninstall (de app, não atualização) com o publisher exigido + ) + status := map[rootKey]string{} for _, line := range strings.Split(string(res.Stdout), "\n") { f := strings.Split(strings.TrimRight(line, "\r"), "\t") switch { + case len(f) == 4 && f[0] == "S": + status[rootKey{f[1], f[2]}] = strings.TrimSpace(f[3]) case len(f) == 7 && f[0] == "U" && want != "": label := originLabel(f[1]) name := strings.TrimSpace(f[2]) - if label == "" || name == "" || f[5] == "1" || f[6] == "1" || !MatchDisplayName(name, want) { + if label == "" || name == "" || f[5] == "1" || f[6] == "1" { + continue + } + if pub != "" && strings.EqualFold(strings.TrimSpace(f[4]), pub) { + pubSeen = true + } + if !MatchDisplayName(name, want) { continue } if pub != "" && !strings.EqualFold(strings.TrimSpace(f[4]), pub) { @@ -78,17 +141,28 @@ func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, } // O Uninstall traz a versão e tem prioridade sobre o App Paths. return Found{Where: `Programas e recursos do Windows [` + label + `] ("` + clean(name, 100) + `")`, Version: clean(f[3], 64)}, true - case len(f) == 3 && f[0] == "A" && exe != "" && viaPath == nil: + case len(f) == 5 && f[0] == "A" && exe != "" && viaPath == nil: label := originLabel(f[1]) - if label != "" && strings.EqualFold(strings.TrimSpace(f[2]), exe) { + // Só vale a subchave do exe pedido com valor padrão apontando para um .exe local que EXISTE (a + // folha vem do Test-Path do script; o formato é conferido de novo aqui). + if label != "" && strings.EqualFold(strings.TrimSpace(f[2]), exe) && f[4] == "1" && localExe(strings.TrimSpace(f[3])) { viaPath = &Found{Where: "App Paths do Windows [" + label + "] (" + clean(f[2], 100) + ")"} } } } - if viaPath != nil { + // O publisher exigido pelo catálogo não é contornado pelo App Paths: ele só complementa um Uninstall do + // mesmo publisher. + if viaPath != nil && (pub == "" || pubSeen) { return *viaPath, true } - return Found{}, false + var rs [][]rootKey + if want != "" { + rs = append(rs, uninstallRoots) + } + if exe != "" { + rs = append(rs, appPathsRoots) + } + return Found{Incomplete: incomplete(status, rs...)}, false } var versionTokenRe = regexp.MustCompile(`^[vV]?[0-9]+([._][0-9A-Za-z]+)*$`) diff --git a/internal/detect/windows_script_test.go b/internal/detect/windows_script_test.go new file mode 100644 index 0000000..f0911d1 --- /dev/null +++ b/internal/detect/windows_script_test.go @@ -0,0 +1,270 @@ +package detect + +import ( + "bytes" + "context" + "os" + "os/exec" + "regexp" + "sort" + "strings" + "testing" + + "github.com/PiluTech/toolkit/internal/catalog" + tkexec "github.com/PiluTech/toolkit/internal/exec" +) + +// legacyScript é o script ANTIGO (só o trecho dos caminhos), com o defeito que a Lupa achou: no PowerShell a +// vírgula tem precedência maior que o +, então @('HKLM','HKLM:'+$cv+'Uninstall') vira 4 elementos e $r[1] é +// só 'HKLM:'. Fica aqui para provar que a verificação estática reprova esse padrão. +const legacyScript = `$cv='\SOFTWARE\Microsoft\Windows\CurrentVersion\';` + + `$u=@(@('HKLM','HKLM:'+$cv+'Uninstall'),@('HKLM-WOW64','HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'),@('HKCU','HKCU:'+$cv+'Uninstall'));` + + `foreach($r in @(@('HKLM','HKLM:'+$cv+'App Paths'),@('HKCU','HKCU:'+$cv+'App Paths'))){}` + +var wantUninstallPaths = []string{ + `HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`, + `HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall`, + `HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall`, +} + +var wantAppPaths = []string{ + `HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths`, + `HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths`, +} + +var ( + pathConcatRe = regexp.MustCompile(`'HK(LM|CU):[^']*'\s*\+|\+\s*'?HK(LM|CU):|\$cv\b`) + pathLitRe = regexp.MustCompile(`'(HK(?:LM|CU):[^']*)'`) +) + +// scriptPathProblems devolve o que há de errado nos caminhos de registro do script: concatenação com + (a +// vírgula do PowerShell pega antes) e a diferença para os 5 caminhos literais completos esperados. +func scriptPathProblems(script string) []string { + var out []string + if pathConcatRe.MatchString(script) { + out = append(out, "caminho de registro montado com + (ou variável $cv): use literais completos") + } + got := map[string]int{} + for _, m := range pathLitRe.FindAllStringSubmatch(script, -1) { + got[m[1]]++ + } + for _, w := range append(append([]string{}, wantUninstallPaths...), wantAppPaths...) { + if got[w] != 1 { + out = append(out, "caminho literal esperado exatamente 1 vez: "+w) + } + delete(got, w) + } + for extra := range got { + out = append(out, "caminho inesperado: "+extra) + } + sort.Strings(out) + return out +} + +// Roda em qualquer SO (inclusive o Mac de desenvolvimento, sem PowerShell): os caminhos têm de ser literais. +func TestWindowsScriptCaminhosSaoLiteraisCompletos(t *testing.T) { + if p := scriptPathProblems(uninstallScript); len(p) != 0 { + t.Fatalf("script com caminhos de registro errados: %v", p) + } +} + +func TestWindowsScriptAntigoEhReprovadoPelaVerificacaoEstatica(t *testing.T) { + p := scriptPathProblems(legacyScript) + if len(p) == 0 || !strings.Contains(strings.Join(p, "\n"), "montado com +") { + t.Fatalf("o script antigo deveria ser reprovado: %v", p) + } +} + +// --- parse e regras do App Paths (valor padrão, executável local existente) --- + +func chromeApp(t *testing.T) catalog.App { + t.Helper() + return winApp(t, "display_name: Google Chrome, app_path: chrome.exe") +} + +func TestWindowsAppPathsExigeExecutavelLocalExistente(t *testing.T) { + cases := []struct { + name string + line string + found bool + }{ + {"app válido", ap("HKLM", "chrome.exe", chromePath, "1"), true}, + {"chave vazia (sem valor padrão)", ap("HKLM", "chrome.exe", "", "0"), false}, + {"só o nome da subchave, sem o valor padrão", ap("HKLM", "chrome.exe", "chrome.exe", "0"), false}, + {"caminho ausente (arquivo não existe)", ap("HKLM", "chrome.exe", chromePath, "0"), false}, + {"pasta, não arquivo", ap("HKLM", "chrome.exe", `C:\Program Files\Google\Chrome\Application\chrome.exe`, "0"), false}, + {"caminho de rede UNC", ap("HKLM", "chrome.exe", `\\servidor\share\chrome.exe`, "1"), false}, + {"caminho relativo", ap("HKLM", "chrome.exe", `Application\chrome.exe`, "1"), false}, + {"relativo à unidade", ap("HKLM", "chrome.exe", `C:chrome.exe`, "1"), false}, + {"extensão diferente de .exe", ap("HKLM", "chrome.exe", `C:\Apps\chrome.bat`, "1"), false}, + {"unidade sem arquivo", ap("HKLM", "chrome.exe", `C:\`, "1"), false}, + {"valor com aspas externas já tratadas pelo script", ap("HKCU", "chrome.exe", chromePath, "1"), true}, + } + for _, tc := range cases { + f, found := find(t, New(winStub(tc.line), Options{GOOS: "windows"}), chromeApp(t)) + if found != tc.found { + t.Errorf("%s: found=%v (%+v)", tc.name, found, f) + } + } +} + +func TestWindowsAppPathsNaoContornaPublisherDoCatalogo(t *testing.T) { + a := winApp(t, `display_name: Google Chrome, publisher: "Google LLC", app_path: chrome.exe`) + good := ap("HKLM", "chrome.exe", chromePath, "1") + // App Paths sozinho não detecta app que exige publisher. + if _, found := find(t, New(winStub(good), Options{GOOS: "windows"}), a); found { + t.Fatal("App Paths sozinho contornou o publisher exigido") + } + // Publisher divergente no Uninstall + App Paths válido: também não. + if _, found := find(t, New(winStub(u("HKLM", "Outra coisa", "1", "Outra Empresa"), good), Options{GOOS: "windows"}), a); found { + t.Fatal("publisher divergente + App Paths não pode detectar") + } + // Com Uninstall do publisher certo, o App Paths vale (mesmo se o DisplayName diferir). + if _, found := find(t, New(winStub(u("HKLM", "Google Chrome Beta Renomeado", "1", "Google LLC"), good), Options{GOOS: "windows"}), a); !found { + t.Fatal("App Paths com Uninstall do mesmo publisher deveria valer") + } +} + +// --- estado por raiz --- + +func TestWindowsStatusPorRaiz(t *testing.T) { + a := winApp(t, "display_name: Discord") + all := func(over map[rootKey]string) []string { + var out []string + for _, r := range append(append([]rootKey{}, uninstallRoots...), appPathsRoots...) { + state := "ok" + if o, ok := over[r]; ok { + state = o + } + out = append(out, st(r.kind, r.origin, state)) + } + return out + } + hkcuFail := map[rootKey]string{{"U", "HKCU"}: "falhou"} + // Raiz ausente (normal) e tudo lido: não achou = não instalado (sem Incomplete). + f, found := find(t, New(winRaw(all(map[rootKey]string{{"U", "HKCU"}: "ausente"})...), Options{GOOS: "windows"}), a) + if found || f.Incomplete { + t.Fatalf("ausente é normal: %+v %v", f, found) + } + // Uma raiz falhou e o app não foi achado: leitura incompleta. + f, found = find(t, New(winRaw(all(hkcuFail)...), Options{GOOS: "windows"}), a) + if found || !f.Incomplete { + t.Fatalf("raiz falhou: esperava Incomplete: %+v %v", f, found) + } + // Uma raiz falhou, mas o app foi achado em outra: as leituras válidas valem. + f, found = find(t, New(winRaw(append(all(hkcuFail), u("HKLM", "Discord", "1.0", "P"))...), Options{GOOS: "windows"}), a) + if !found || f.Incomplete || f.Version != "1.0" { + t.Fatalf("achado deveria valer: %+v %v", f, found) + } + // Raiz que não reportou estado (saída truncada) também é incompleta. + if f, found = find(t, New(winRaw(u("HKCU", "Outro", "1", "P")), Options{GOOS: "windows"}), a); found || !f.Incomplete { + t.Fatalf("sem estado: %+v %v", f, found) + } + // App Paths que falhou só pesa para app com app_path; Uninstall que falhou não pesa para app_path-only. + ap1 := winApp(t, "app_path: chrome.exe") + if f, found = find(t, New(winRaw(all(hkcuFail)...), Options{GOOS: "windows"}), ap1); found || f.Incomplete { + t.Fatalf("Uninstall falho não importa para app só com app_path: %+v %v", f, found) + } + if f, found = find(t, New(winRaw(all(map[rootKey]string{{"A", "HKLM"}: "falhou"})...), Options{GOOS: "windows"}), ap1); found || !f.Incomplete { + t.Fatalf("App Paths falho: %+v %v", f, found) + } + // PowerShell que falha por inteiro: incompleto, nunca "instalado". + bad := &stub{handle: func(tkexec.Cmd) (tkexec.Result, error) { return tkexec.Result{ExitCode: 1}, nil }} + if f, found = find(t, New(bad, Options{GOOS: "windows"}), a); found || !f.Incomplete { + t.Fatalf("exit 1: %+v %v", f, found) + } +} + +// --- execução do script REAL num PowerShell de verdade, com cmdlets FALSOS --- + +// fakeCmdlets sombreia Get-ChildItem e Test-Path (funções ganham dos cmdlets) e registra no stderr cada -Path +// recebido ("CAP|cmdlet|caminho"). Nada toca o registro real: as chaves são objetos sintéticos. +const fakeCmdlets = `$ErrorActionPreference='Stop'; +function Key($name,$vals){$o=New-Object PSObject;$o|Add-Member NoteProperty PSChildName $name; + $o|Add-Member ScriptMethod GetValue {param($n,$d,$opt) $this.V[$n]};$o|Add-Member NoteProperty V $vals;$o}; +function Get-ChildItem{param([string]$Path) + [Console]::Error.WriteLine('CAP|GCI|'+$Path); + switch($Path){ + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'{ + Key 'g1' @{DisplayName='Git';DisplayVersion='2.45.1';Publisher='The Git Development Community';SystemComponent=0} + Key 'g2' @{DisplayName='Git';SystemComponent=1} + Key 'g3' @{DisplayName='Git Patch';ParentKeyName='x'} + Key 'g4' @{DisplayVersion='9'}} + 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall'{throw (New-Object System.Management.Automation.ItemNotFoundException 'ausente')} + 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'{throw 'acesso negado'} + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths'{ + Key 'chrome.exe' @{''='"%TKFAKE%\chrome.exe"'} + Key 'vazio.exe' @{} + Key 'rede.exe' @{''='\\servidor\s\rede.exe'} + Key 'rel.exe' @{''='rel.exe'} + Key 'pasta.exe' @{''='C:\Pasta\pasta.exe'}} + 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths'{throw (New-Object System.Management.Automation.ItemNotFoundException 'ausente')} + default{throw ('caminho inesperado: '+$Path)}}}; +function Test-Path{param([string]$LiteralPath,[string]$PathType) + [Console]::Error.WriteLine('CAP|TP|'+$LiteralPath+'|'+$PathType); + $LiteralPath -eq 'C:\Fake\chrome.exe'}; +` + +func shell(t *testing.T) string { + t.Helper() + for _, n := range []string{"pwsh", "powershell"} { + if p, err := exec.LookPath(n); err == nil { + return p + } + } + t.Skip("sem pwsh/powershell nesta máquina: roda no runner Windows do CI") + return "" +} + +func TestWindowsScriptRealExecutadoComCmdletsFalsos(t *testing.T) { + sh := shell(t) + var stderr bytes.Buffer + s := &stub{handle: func(c tkexec.Cmd) (tkexec.Result, error) { + script := c.Args[len(c.Args)-1] + cmd := exec.CommandContext(context.Background(), sh, "-NoProfile", "-NonInteractive", "-Command", fakeCmdlets+script) //nolint:gosec // só o PowerShell de TESTE, com cmdlets falsos + cmd.Env = append(os.Environ(), `TKFAKE=C:\Fake`) + var out bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &stderr + err := cmd.Run() + return tkexec.Result{Stdout: out.Bytes()}, err + }} + a := winApp(t, "display_name: Git, app_path: chrome.exe") + f, found := find(t, New(s, Options{GOOS: "windows"}), a) + if !found || f.Version != "2.45.1" { + t.Fatalf("Git deveria ser achado pelo Uninstall HKLM: %+v %v\nstderr: %s", f, found, stderr.String()) + } + var gci, tp []string + for _, l := range strings.Split(stderr.String(), "\n") { + l = strings.TrimSpace(l) + switch { + case strings.HasPrefix(l, "CAP|GCI|"): + gci = append(gci, strings.TrimPrefix(l, "CAP|GCI|")) + case strings.HasPrefix(l, "CAP|TP|"): + tp = append(tp, strings.TrimPrefix(l, "CAP|TP|")) + case l != "": + t.Errorf("stderr inesperado do script: %q", l) + } + } + want := append(append([]string{}, wantUninstallPaths...), wantAppPaths...) + sort.Strings(want) + sort.Strings(gci) + if strings.Join(gci, "\n") != strings.Join(want, "\n") { + t.Fatalf("Get-ChildItem -Path recebeu\n%s\nesperado\n%s", strings.Join(gci, "\n"), strings.Join(want, "\n")) + } + // Só o chrome.exe (local absoluto .exe, com a variável expandida) vai ao Test-Path, como arquivo (Leaf). + if strings.Join(tp, "\n") != `C:\Fake\chrome.exe|Leaf`+"\n"+`C:\Pasta\pasta.exe|Leaf` { + t.Fatalf("Test-Path recebeu: %q", tp) + } + // O resultado completo: chrome.exe existe; o das pastas/UNC/relativo/sem valor não conta. + for exe, want := range map[string]bool{"chrome.exe": true, "vazio.exe": false, "rede.exe": false, "rel.exe": false, "pasta.exe": false} { + _, got := find(t, New(s, Options{GOOS: "windows"}), winApp(t, "app_path: "+exe)) + if got != want { + t.Errorf("%s: found=%v, esperado %v", exe, got, want) + } + } + // HKCU\Uninstall falhou (acesso negado): app não achado vira leitura incompleta. + f, found = find(t, New(s, Options{GOOS: "windows"}), winApp(t, "display_name: Nao Existe")) + if found || !f.Incomplete { + t.Fatalf("esperava leitura incompleta: %+v %v", f, found) + } +} diff --git a/internal/detect/windows_test.go b/internal/detect/windows_test.go index 7289624..629c748 100644 --- a/internal/detect/windows_test.go +++ b/internal/detect/windows_test.go @@ -11,14 +11,36 @@ import ( // Formato da saída do script (ver windows.go): uma linha por item, separada por TAB. // U origem nome versão publisher SystemComponent ParentKeyName (chave de desinstalação) -// A origem exe (App Paths) +// A origem subchave caminho folha (App Paths: valor padrão; folha 1 = .exe local existente) +// S tipo origem estado (estado da raiz: ok, ausente, falhou) // As fixtures são SINTÉTICAS: nomes no formato conhecido de cada instalador, não capturas de uma máquina real. func winStub(lines ...string) *stub { + all := append([]string{}, lines...) + for _, r := range append(append([]rootKey{}, uninstallRoots...), appPathsRoots...) { + all = append(all, st(r.kind, r.origin, "ok")) + } + return winRaw(all...) +} + +// winRaw devolve EXATAMENTE as linhas dadas (sem os estados "ok" que winStub acrescenta). +func winRaw(lines ...string) *stub { out := strings.Join(lines, "\r\n") + "\r\n" return &stub{handle: func(exec.Cmd) (exec.Result, error) { return ok(out) }} } +// st monta a linha de estado de uma raiz. +func st(kind, origin, state string) string { + return strings.Join([]string{"S", kind, origin, state}, "\t") +} + +// ap monta uma linha de App Paths. +func ap(origin, sub, path, leaf string) string { + return strings.Join([]string{"A", origin, sub, path, leaf}, "\t") +} + +const chromePath = `C:\Program Files\Google\Chrome\Application\chrome.exe` + // u monta uma linha de chave de desinstalação. func u(origin, name, version, publisher string) string { return strings.Join([]string{"U", origin, name, version, publisher, "0", "0"}, "\t") @@ -134,26 +156,26 @@ func TestWindowsPublisherDeclaradoExigeIgualdade(t *testing.T) { func TestWindowsAppPathsComoEvidenciaComplementar(t *testing.T) { a := winApp(t, "display_name: Google Chrome, app_path: chrome.exe") - ap := strings.Join([]string{"A", "HKLM", "chrome.exe"}, "\t") - f, found := find(t, New(winStub(ap), Options{GOOS: "windows"}), a) + lin := ap("HKLM", "chrome.exe", chromePath, "1") + f, found := find(t, New(winStub(lin), Options{GOOS: "windows"}), a) if !found || !strings.Contains(f.Where, "App Paths") || !strings.Contains(f.Where, "chrome.exe") || f.Version != "" { t.Fatalf("%v %+v", found, f) } // O Uninstall tem prioridade (traz a versão). - f, found = find(t, New(winStub(ap, u("HKLM", "Google Chrome", "130", "G")), Options{GOOS: "windows"}), a) + f, found = find(t, New(winStub(lin, u("HKLM", "Google Chrome", "130", "G")), Options{GOOS: "windows"}), a) if !found || f.Version != "130" || strings.Contains(f.Where, "App Paths") { t.Fatalf("%v %+v", found, f) } // Outro exe não casa; sem app_path no catálogo o App Paths é ignorado. - other := strings.Join([]string{"A", "HKCU", "firefox.exe"}, "\t") + other := ap("HKCU", "firefox.exe", `C:\Firefox\firefox.exe`, "1") if _, found = find(t, New(winStub(other), Options{GOOS: "windows"}), a); found { t.Fatal("outro exe") } - if _, found = find(t, New(winStub(ap), Options{GOOS: "windows"}), winApp(t, "display_name: Google Chrome")); found { + if _, found = find(t, New(winStub(lin), Options{GOOS: "windows"}), winApp(t, "display_name: Google Chrome")); found { t.Fatal("sem app_path no catálogo") } // App com só app_path (sem display_name) também funciona. - if _, found = find(t, New(winStub(ap), Options{GOOS: "windows"}), winApp(t, "app_path: chrome.exe")); !found { + if _, found = find(t, New(winStub(lin), Options{GOOS: "windows"}), winApp(t, "app_path: chrome.exe")); !found { t.Fatal("só app_path") } } @@ -256,7 +278,7 @@ func TestWindowsAppPathsDoCatalogoEmbutido(t *testing.T) { } for id, exe := range map[string]string{"chrome": "chrome.exe", "firefox": "firefox.exe", "brave": "brave.exe"} { a, _ := c.Get(id) - f, found := find(t, New(winStub(strings.Join([]string{"A", "HKCU", exe}, "\t")), Options{GOOS: "windows"}), a) + f, found := find(t, New(winStub(ap("HKCU", exe, `C:\Apps\`+exe, "1")), Options{GOOS: "windows"}), a) if !found || !strings.Contains(f.Where, exe) { t.Errorf("%s: %v %+v", id, found, f) } diff --git a/internal/msg/msg.go b/internal/msg/msg.go index 0793061..f551b7d 100644 --- a/internal/msg/msg.go +++ b/internal/msg/msg.go @@ -44,6 +44,8 @@ const ( ListStateExternalAt = " em %s" ListStateNo = "não instalado" ListStateUnknown = "não deu para verificar" + ListStateUndetected = "não detectado" + ListStateIncomplete = "não detectado (leitura incompleta)" ListVersionsAny = "sim" ListVersionsNone = "-" ) diff --git a/internal/providers/registry.go b/internal/providers/registry.go index 71fa347..054592b 100644 --- a/internal/providers/registry.go +++ b/internal/providers/registry.go @@ -119,6 +119,8 @@ type External struct { Manager string // nome para o usuário do gerenciador esperado ("Homebrew") Where string // onde está ("/Applications/Discord.app") Version string // versão lida, se houver + // Incomplete só vem com found == false: a leitura falhou em parte, então "não achei" não é "não instalado". + Incomplete bool } // ExternalFinder procura o app fora do gerenciador (leitura). O segundo valor é false quando não há. Um erro diff --git a/internal/tui/apps.go b/internal/tui/apps.go index 3648e8e..5d358a5 100644 --- a/internal/tui/apps.go +++ b/internal/tui/apps.go @@ -33,9 +33,18 @@ type AppStatus struct { External bool ExternalManager string ExternalWhere string - Err error // não deu para verificar + // DetectGap (só com Installed false): "incomplete" (leitura do registro incompleta) ou "not_applicable" (app + // sem detecção neste SO). O estado vira "não detectado", nunca "não instalado". + DetectGap string + Err error // não deu para verificar } +// Valores de AppStatus.DetectGap. +const ( + DetectIncomplete = "incomplete" + DetectNotApplicable = "not_applicable" +) + // AppsBackend é o que a aba Apps precisa do resto do toolkit. A implementação real (catálogo + providers // sobre o Runner) fica em internal/cli; os testes usam um falso. type AppsBackend interface { @@ -855,8 +864,11 @@ func (t *AppsTab) rowLine(i int, c cols) string { // Texto do estado "instalado fora do gerenciador": completo quando a coluna comporta, curto senão. const ( - stateExternalFull = "instalado (fora do %s)" - stateExternalShort = "instalado (fora)" + stateExternalFull = "instalado (fora do %s)" + stateExternalShort = "instalado (fora)" + stateUndetected = "não detectado" + stateUndetectedShort = "não detectado (parcial)" + stateUndetectedIncomplete = "não detectado (leitura incompleta)" ) // externalText escolhe o texto de "instalado fora do gerenciador" que cabe em width colunas (com o símbolo). @@ -888,6 +900,15 @@ func (t *AppsTab) stateText(a AppInfo, width int) (state, ver string) { case st.Installed: return SymOK + " instalado", st.Version } + switch st.DetectGap { + case DetectIncomplete: + if full := SymPending + " " + stateUndetectedIncomplete; lipgloss.Width(full) <= width { + return full, "" + } + return SymPending + " " + stateUndetectedShort, "" + case DetectNotApplicable: + return SymPending + " " + stateUndetected, "" + } return SymPending + " não instalado", "" } diff --git a/internal/tui/apps_external_test.go b/internal/tui/apps_external_test.go index 476883b..2cf58c6 100644 --- a/internal/tui/apps_external_test.go +++ b/internal/tui/apps_external_test.go @@ -60,3 +60,17 @@ func TestAppsInstaladoNormalContinuaIgual(t *testing.T) { t.Fatalf("git instalado pelo gerenciador:\n%s", v) } } + +func TestAppsSemDeteccaoCompletaDizNaoDetectado(t *testing.T) { + st := defaultStatus() + st["python"] = AppStatus{DetectGap: DetectIncomplete} + v := plain(loaded(t, &fakeBackend{apps: sampleApps(), status: st}).View(120, 19)) + if !strings.Contains(v, "○ não detectado (parcial)") && !strings.Contains(v, "○ não detectado (leitura incompleta)") { + t.Fatalf("estado incompleto ausente:\n%s", v) + } + st["python"] = AppStatus{DetectGap: DetectNotApplicable} + v = plain(loaded(t, &fakeBackend{apps: sampleApps(), status: st}).View(120, 19)) + if !strings.Contains(v, "○ não detectado") || strings.Contains(v, "leitura incompleta") { + t.Fatalf("estado sem detecção ausente:\n%s", v) + } +} From 3eefdb4e93265bfc74b88e29fdc16b0ec1235043 Mon Sep 17 00:00:00 2001 From: Paulo Victor T Silva Date: Sat, 14 Nov 2026 16:51:32 -0300 Subject: [PATCH 3/3] =?UTF-8?q?fix(detect):=20App=20Paths=20recusado=20qua?= =?UTF-8?q?ndo=20o=20cat=C3=A1logo=20exige=20publisher;=20unidade=20local?= =?UTF-8?q?=20(Fixed)=20antes=20do=20Test-Path;=20teste=20execut=C3=A1vel?= =?UTF-8?q?=20falha=20no=20Windows=20sem=20PowerShell?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/catalogo.md | 2 +- internal/detect/windows.go | 19 ++++++------ internal/detect/windows_script_test.go | 43 +++++++++++++++++++++----- 3 files changed, 46 insertions(+), 18 deletions(-) diff --git a/docs/catalogo.md b/docs/catalogo.md index 11a91e9..e60bf82 100644 --- a/docs/catalogo.md +++ b/docs/catalogo.md @@ -84,7 +84,7 @@ Sem isto, um app instalado à mão (o Discord que veio do `.dmg`, o programa do | `macos` | `bundle_id` | `CFBundleIdentifier` (`com.hnc.Discord`) | se o nome não existir, olha o `Info.plist` dos `.app` dessas duas pastas (até 500 por pasta), para achar um app renomeado | | `windows` | `display_name` | `DisplayName` do registro Uninstall (`Discord`) | um PowerShell de texto fixo (caminho absoluto, só leitura, sem elevar) lê as chaves `Uninstall` de `HKLM`, `HKLM\WOW6432Node` e `HKCU`; a versão é o `DisplayVersion`; ignora `SystemComponent=1`, atualizações (`ParentKeyName`/`ReleaseType`) e nome vazio | | `windows` | `publisher` | `Publisher` do registro (`Google LLC`) | opcional; quando informado, tem de ser igual ao do registro (sem diferenciar maiúsculas); publisher ausente no registro não casa | -| `windows` | `app_path` | nome da subchave em `App Paths` (`chrome.exe`) | evidência complementar, sem versão, só quando o Uninstall não tem o app. Lê o **valor padrão** da subchave `HKLM`/`HKCU` `\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\`, tira as aspas externas, expande as variáveis de ambiente e exige um **executável local existente**: caminho absoluto `X:\...` terminado em `.exe`, **arquivo** (não pasta), nunca de rede (`\\servidor\...`) nem relativo; nada é executado. Valor vazio, ilegível ou inexistente = não detectado. Se o app declara `publisher`, o App Paths **não o contorna**: só vale com um Uninstall do mesmo publisher. Só declare para exe conhecido; termina em `.exe`, sem barras | +| `windows` | `app_path` | nome da subchave em `App Paths` (`chrome.exe`) | evidência complementar, sem versão, só quando o Uninstall não tem o app. Lê o **valor padrão** da subchave `HKLM`/`HKCU` `\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\`, tira as aspas externas, expande as variáveis de ambiente e exige um **executável local existente**: caminho absoluto `X:\...` terminado em `.exe`, **arquivo** (não pasta), nunca de rede (`\\servidor\...`) nem relativo, e em **unidade local** (`DriveType` Fixed, conferido antes de qualquer acesso: letra mapeada para a rede é recusada sem tocar o arquivo); nada é executado. Valor vazio, ilegível ou inexistente = não detectado. Se o app declara `publisher`, o App Paths **não é usado** (ele não traz publisher, e outro programa do mesmo publisher não prova o executável): só o Uninstall com nome e publisher certos detecta. Só declare para exe conhecido; termina em `.exe`, sem barras | | `linux` | `desktop_id` | arquivo `.desktop` (`discord.desktop`) | existe em `/usr/share/applications` ou `~/.local/share/applications` | | `linux` | `flatpak_id` | id do flatpak | `flatpak list --app` (também vale quando o instalador do catálogo é o próprio flatpak: a segunda leitura é redundante, mas inofensiva) | | `linux` | `snap` | nome do snap | `snap list ` | diff --git a/internal/detect/windows.go b/internal/detect/windows.go index 3f80665..3925437 100644 --- a/internal/detect/windows.go +++ b/internal/detect/windows.go @@ -22,7 +22,9 @@ const windowsPowerShell = `C:\Windows\System32\WindowsPowerShell\v1.0\powershell // origem: HKLM, HKLM-WOW64 (WOW6432Node) ou HKCU. "atualização" é 1 quando há ParentKeyName ou ReleaseType // (patch, hotfix). "caminho" é o valor padrão da subchave de App Paths, sem aspas externas e com as variáveis de // ambiente expandidas ([Environment]::ExpandEnvironmentVariables, só isso); "folha" é 1 quando esse caminho é -// local absoluto (X:\...), termina em .exe e é um ARQUIVO que existe (Test-Path -PathType Leaf; nada é executado). +// local absoluto (X:\...), termina em .exe, está em unidade LOCAL (DriveType Fixed, conferido ANTES de qualquer +// acesso: letra mapeada para a rede não passa e o Test-Path nem roda) e é um ARQUIVO que existe (Test-Path +// -PathType Leaf; nada é executado). // O script é texto FIXO e ASCII: nada do catálogo entra nele (o casamento é feito em Go), então não há injeção. // // Os caminhos do registro são literais COMPLETOS, sem concatenação: no PowerShell a vírgula tem precedência @@ -49,7 +51,8 @@ const uninstallScript = `$ErrorActionPreference='Stop';` + `foreach($r in $a){$s='ok';try{foreach($k in @(Get-ChildItem -Path $r.P)){try{$p='';$l='0';` + `$v=$k.GetValue('',$null,'DoNotExpandEnvironmentNames');` + `if($v -is [string]){$p=[Environment]::ExpandEnvironmentVariables($v.Trim().Trim('"').Trim());` + - `if(($p -match '^[A-Za-z]:\\[^\\]') -and ($p -match '\.exe$')){if(Test-Path -LiteralPath $p -PathType Leaf){$l='1'}}};` + + `if(($p -match '^[A-Za-z]:\\[^\\]') -and ($p -match '\.exe$')){$dt='';try{$dt=[string][IO.DriveInfo]::new($p.Substring(0,1)).DriveType}catch{};` + + `if($dt -eq 'Fixed'){if(Test-Path -LiteralPath $p -PathType Leaf){$l='1'}}}};` + `'A'+$t+$r.N+$t+(C $k.PSChildName)+$t+(C $p)+$t+$l}catch{$s='falhou'}}` + `}catch [System.Management.Automation.ItemNotFoundException]{$s='ausente'}catch{$s='falhou'};` + `'S'+$t+'A'+$t+$r.N+$t+$s};` + @@ -116,7 +119,6 @@ func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, exe := strings.TrimSpace(spec.AppPath) var ( viaPath *Found - pubSeen bool // há entrada de Uninstall (de app, não atualização) com o publisher exigido ) status := map[rootKey]string{} for _, line := range strings.Split(string(res.Stdout), "\n") { @@ -130,9 +132,6 @@ func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, if label == "" || name == "" || f[5] == "1" || f[6] == "1" { continue } - if pub != "" && strings.EqualFold(strings.TrimSpace(f[4]), pub) { - pubSeen = true - } if !MatchDisplayName(name, want) { continue } @@ -141,7 +140,7 @@ func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, } // O Uninstall traz a versão e tem prioridade sobre o App Paths. return Found{Where: `Programas e recursos do Windows [` + label + `] ("` + clean(name, 100) + `")`, Version: clean(f[3], 64)}, true - case len(f) == 5 && f[0] == "A" && exe != "" && viaPath == nil: + case len(f) == 5 && f[0] == "A" && exe != "" && pub == "" && viaPath == nil: label := originLabel(f[1]) // Só vale a subchave do exe pedido com valor padrão apontando para um .exe local que EXISTE (a // folha vem do Test-Path do script; o formato é conferido de novo aqui). @@ -150,9 +149,9 @@ func (d *Detector) findWindows(ctx context.Context, spec catalog.Detect) (Found, } } } - // O publisher exigido pelo catálogo não é contornado pelo App Paths: ele só complementa um Uninstall do - // mesmo publisher. - if viaPath != nil && (pub == "" || pubSeen) { + // App Paths não traz publisher: com publisher exigido pelo catálogo o fallback é recusado (outro programa do + // mesmo publisher não prova que o executável é o app); só o Uninstall com nome e publisher certos vale. + if viaPath != nil { return *viaPath, true } var rs [][]rootKey diff --git a/internal/detect/windows_script_test.go b/internal/detect/windows_script_test.go index f0911d1..d2cefca 100644 --- a/internal/detect/windows_script_test.go +++ b/internal/detect/windows_script_test.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "regexp" + "runtime" "sort" "strings" "testing" @@ -119,9 +120,29 @@ func TestWindowsAppPathsNaoContornaPublisherDoCatalogo(t *testing.T) { if _, found := find(t, New(winStub(u("HKLM", "Outra coisa", "1", "Outra Empresa"), good), Options{GOOS: "windows"}), a); found { t.Fatal("publisher divergente + App Paths não pode detectar") } - // Com Uninstall do publisher certo, o App Paths vale (mesmo se o DisplayName diferir). - if _, found := find(t, New(winStub(u("HKLM", "Google Chrome Beta Renomeado", "1", "Google LLC"), good), Options{GOOS: "windows"}), a); !found { - t.Fatal("App Paths com Uninstall do mesmo publisher deveria valer") + // Outro programa do MESMO publisher (Google Drive, Google LLC) não prova que o chrome.exe é o app: sem + // vínculo entre o publisher e o executável, o fallback do App Paths é recusado. + for _, other := range []string{"Google Drive", "Google Chrome Beta Renomeado"} { + if _, found := find(t, New(winStub(u("HKLM", other, "1", "Google LLC"), good), Options{GOOS: "windows"}), a); found { + t.Fatalf("%q do mesmo publisher autorizou o App Paths do chrome.exe", other) + } + } + // O Uninstall do próprio app, com nome e publisher certos, continua detectando. + if _, found := find(t, New(winStub(u("HKLM", "Google Chrome", "1", "Google LLC")), Options{GOOS: "windows"}), a); !found { + t.Fatal("Uninstall com nome e publisher certos deveria detectar") + } +} + +// A unidade tem de ser LOCAL (DriveType Fixed) antes de qualquer acesso ao arquivo: Test-Path num destino de rede +// mapeado (Z:) já toca a rede. A verificação estática vale em qualquer SO; o teste executável fica abaixo. +func TestWindowsScriptValidaUnidadeLocalAntesDoTestPath(t *testing.T) { + d := strings.Index(uninstallScript, "[IO.DriveInfo]") + tp := strings.Index(uninstallScript, "Test-Path") + if d < 0 || tp < 0 || d > tp { + t.Fatalf("DriveInfo (%d) deve vir antes do Test-Path (%d)", d, tp) + } + if !strings.Contains(uninstallScript, "'Fixed'") { + t.Fatal("só unidade Fixed é local") } } @@ -197,7 +218,8 @@ function Get-ChildItem{param([string]$Path) Key 'vazio.exe' @{} Key 'rede.exe' @{''='\\servidor\s\rede.exe'} Key 'rel.exe' @{''='rel.exe'} - Key 'pasta.exe' @{''='C:\Pasta\pasta.exe'}} + Key 'pasta.exe' @{''='C:\Pasta\pasta.exe'} + Key 'mapeado.exe' @{''='Z:\Rede\mapeado.exe'}} 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths'{throw (New-Object System.Management.Automation.ItemNotFoundException 'ausente')} default{throw ('caminho inesperado: '+$Path)}}}; function Test-Path{param([string]$LiteralPath,[string]$PathType) @@ -207,12 +229,18 @@ function Test-Path{param([string]$LiteralPath,[string]$PathType) func shell(t *testing.T) string { t.Helper() + if runtime.GOOS != "windows" { + t.Skip("o script usa [IO.DriveInfo] do Windows: o teste executável roda só no runner Windows do CI") + } for _, n := range []string{"pwsh", "powershell"} { if p, err := exec.LookPath(n); err == nil { return p } } - t.Skip("sem pwsh/powershell nesta máquina: roda no runner Windows do CI") + if runtime.GOOS == "windows" { + t.Fatal("PowerShell ausente no Windows: o teste executável do script não pode ser pulado aqui") + } + t.Skip("o script usa [IO.DriveInfo] do Windows: o teste executável roda só no runner Windows do CI") return "" } @@ -251,12 +279,13 @@ func TestWindowsScriptRealExecutadoComCmdletsFalsos(t *testing.T) { if strings.Join(gci, "\n") != strings.Join(want, "\n") { t.Fatalf("Get-ChildItem -Path recebeu\n%s\nesperado\n%s", strings.Join(gci, "\n"), strings.Join(want, "\n")) } - // Só o chrome.exe (local absoluto .exe, com a variável expandida) vai ao Test-Path, como arquivo (Leaf). + // Só o chrome.exe (local absoluto .exe, com a variável expandida) vai ao Test-Path, como arquivo (Leaf); o + // destino em Z: (unidade que não é Fixed) é recusado ANTES, sem chegar ao acesso ao arquivo. if strings.Join(tp, "\n") != `C:\Fake\chrome.exe|Leaf`+"\n"+`C:\Pasta\pasta.exe|Leaf` { t.Fatalf("Test-Path recebeu: %q", tp) } // O resultado completo: chrome.exe existe; o das pastas/UNC/relativo/sem valor não conta. - for exe, want := range map[string]bool{"chrome.exe": true, "vazio.exe": false, "rede.exe": false, "rel.exe": false, "pasta.exe": false} { + for exe, want := range map[string]bool{"chrome.exe": true, "vazio.exe": false, "rede.exe": false, "rel.exe": false, "pasta.exe": false, "mapeado.exe": false} { _, got := find(t, New(s, Options{GOOS: "windows"}), winApp(t, "app_path: "+exe)) if got != want { t.Errorf("%s: found=%v, esperado %v", exe, got, want)