installer v1 (C+D): Windows EXE installer trio + build script + local Hub E2E

This commit is contained in:
gti
2026-09-23 17:44:48 -03:00
parent 91c4030b06
commit a9aded1e49
19 changed files with 792 additions and 16 deletions
+14
View File
@@ -0,0 +1,14 @@
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_PAYLOAD = ROOT / "dist" / "installer"
PAYLOAD = Path(os.environ.get("GTI_E2E_PAYLOAD", str(DEFAULT_PAYLOAD)))
sys._MEIPASS = str(PAYLOAD) # frozen-equivalent: extract_payload() reads this
sys.path.insert(0, str(ROOT / "agent" / "src"))
sys.path.insert(0, str(ROOT / "installer"))
import setup_main # noqa: E402
sys.exit(setup_main.cli())
+185
View File
@@ -0,0 +1,185 @@
"""Shared helpers for the Windows installer trio (Setup.exe / service host /
Uninstall.exe). Kept dependency-light (stdlib + httpx only) so each frozen
binary stays small and self-contained; the DPAPI credential write reuses the
agent's `gti_fiscal_agent.credential_store` module.
Policy enforced here (mirrors CLAUDE.md):
- `agent.env` NEVER holds AGENT_TOKEN or any secret — only non-secret config.
- `credentials.bin` is DPAPI LocalMachine-encrypted with a
SYSTEM/Administrators-only ACL (fail closed if DPAPI/icacls is unavailable).
- FIREBIRD_WRITES=0 and FISCAL_MODE=DRY_RUN are always written; no UI or flag
ever enables writes or AI write.
- The install code is sent once to the Hub and is never persisted locally.
"""
from __future__ import annotations
import os
import subprocess
import sys
import winreg
from pathlib import Path
import httpx
PROD_HUB_URL = "https://gtifiscal.gtigrupo.com.br"
SERVICE_NAME = "GTIFiscalAgent"
SERVICE_DISPLAY = "GTI Fiscal Agent"
SERVICE_FAILURE = "restart/60000/restart/60000/restart/60000"
UNINSTALL_KEY = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GTI Fiscal Agent"
def install_dir() -> Path:
override = os.environ.get("GTI_INSTALL_DIR")
if override:
return Path(override).resolve()
return Path(os.environ.get("PROGRAMFILES", r"C:\Program Files")) / "GTI" / "FiscalAgent"
def hub_url() -> str:
return (os.environ.get("GTI_HUB_URL") or PROD_HUB_URL).rstrip("/")
def machine_fingerprint(max_len: int = 128) -> str:
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography") as key:
value, _ = winreg.QueryValueEx(key, "MachineGuid")
return str(value)[:max_len]
except OSError:
return os.environ.get("COMPUTERNAME", "")[:max_len]
def enroll(install_code: str, *, hub: str | None = None) -> dict:
"""POST /v1/agents/enroll with the standalone install code. Returns the
parsed JSON on success; raises httpx.HTTPStatusError with the Hub's reason
in the response body otherwise."""
url = (hub or hub_url()).rstrip("/") + "/v1/agents/enroll"
payload = {
"install_code": install_code,
"hostname": os.environ.get("COMPUTERNAME", ""),
"agent_version": os.environ.get("AGENT_VERSION", ""),
"machine_fingerprint": machine_fingerprint(),
}
response = httpx.post(url, json=payload, timeout=30)
response.raise_for_status()
return response.json()
def write_agent_env(install_dir_path: Path, enroll_result: dict) -> None:
"""Write the non-secret agent.env. The permanent credential goes to
credentials.bin (DPAPI), never here. FIREBIRD_WRITES=0 / DRY_RUN always."""
from gti_fiscal_agent.runner import REFERENCE_SCHEMA_V1
install = Path(install_dir_path)
lines = [
(f"GTI_HUB_URL={enroll_result.get('hub_url') or hub_url()}"),
(f"AGENT_ID={enroll_result.get('agent_id') or ''}"),
("COMPANY_ID="),
("COMPANY_UF="),
("FIREBIRD_DATABASE_PATH="),
("FB_USER="),
("FB_PASSWORD="),
("FISCAL_MODE=DRY_RUN"),
("FIREBIRD_WRITES=0"),
(f"AGENT_VERSION={os.environ.get('AGENT_VERSION', '')}"),
("POLL_INTERVAL_SECONDS=15"),
(f"AGENT_LOG_PATH={install / 'logs' / 'agent.log'}"),
(f"AGENT_STATE_DB={install / 'agent_state.sqlite'}"),
(f"EXPECTED_SCHEMA_FINGERPRINT={REFERENCE_SCHEMA_V1}"),
(f"GTI_WRITE_EXECUTOR_PATH={install / 'scripts' / 'firebird_write_executor.py'}"),
(f"AGENT_HOSTNAME={os.environ.get('COMPUTERNAME', '')}"),
("AUTHORIZED_WRITE_DATABASE_PATH="),
]
install.mkdir(parents=True, exist_ok=True)
(install / "agent.env").write_text("\n".join(lines) + "\n", encoding="utf-8")
def write_credential(install_dir_path: Path, agent_token: str) -> None:
"""Write credentials.bin via DPAPI LocalMachine + ACL (fail closed)."""
from gti_fiscal_agent.credential_store import write_credential as _write
install = Path(install_dir_path)
install.mkdir(parents=True, exist_ok=True)
_write(install / "credentials.bin", agent_token)
def _sc(args: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(["sc.exe", *args], capture_output=True, text=True)
def install_service(install_dir_path: Path) -> None:
"""Register the service (Delayed Auto) and set its failure-recovery policy.
The frozen onedir host lives in <install>/GTIFiscalAgentService/ ; SCM's
binPath points at that executable (its `_internal/` dir travels with it)."""
exe = Path(install_dir_path) / "GTIFiscalAgentService" / "GTIFiscalAgentService.exe"
bin_path = f"\"{exe}\""
result = _sc(["create", SERVICE_NAME, "binPath=", bin_path, "start=", "auto", "DisplayName=", SERVICE_DISPLAY])
if result.returncode != 0 and "already exists" not in (result.stdout + result.stderr):
raise RuntimeError(f"sc create failed: {result.stdout} {result.stderr}".strip())
_sc(["config", SERVICE_NAME, "start=", "delayed-auto"])
_sc(["config", SERVICE_NAME, "obj=", "LocalSystem"])
failure = _sc(["failure", SERVICE_NAME, "reset=", "86400", "actions=", SERVICE_FAILURE])
if failure.returncode != 0:
raise RuntimeError(f"sc failure failed: {failure.stdout} {failure.stderr}".strip())
config = _sc(["qc", SERVICE_NAME])
if "DELAYED" not in (config.stdout + config.stderr).upper() and config.returncode == 0:
raise RuntimeError("sc config: delayed-auto did not stick")
def service_installed() -> bool:
result = _sc(["query", SERVICE_NAME])
return result.returncode == 0 and ("SERVICE_NAME" in result.stdout or "RUNNING" in result.stdout or "STOPPED" in result.stdout)
def service_running() -> bool:
result = _sc(["query", SERVICE_NAME])
return "RUNNING" in result.stdout
def start_service() -> None:
_sc(["start", SERVICE_NAME])
def stop_service() -> None:
_sc(["stop", SERVICE_NAME])
def remove_service() -> None:
"""Stop then delete the service; both best effort (idempotent)."""
stop_service()
_sc(["delete", SERVICE_NAME])
def write_arp_uninstall(install_dir_path: Path) -> None:
"""Write the Add/Remove Programs entry pointing to Uninstall.exe."""
install = Path(install_dir_path)
with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, UNINSTALL_KEY, 0, winreg.KEY_WRITE) as key:
winreg.SetValueEx(key, "DisplayName", 0, winreg.REG_SZ, SERVICE_DISPLAY)
winreg.SetValueEx(key, "DisplayVersion", 0, winreg.REG_SZ, os.environ.get("AGENT_VERSION", ""))
winreg.SetValueEx(key, "Publisher", 0, winreg.REG_SZ, "GTI Sistemas")
winreg.SetValueEx(key, "InstallLocation", 0, winreg.REG_SZ, str(install))
winreg.SetValueEx(key, "UninstallString", 0, winreg.REG_SZ, str(install / "Uninstall.exe"))
winreg.SetValueEx(key, "DisplayIcon", 0, winreg.REG_SZ, str(install / "GTIFiscalAgentService" / "GTIFiscalAgentService.exe"))
winreg.SetValueEx(key, "NoModify", 0, winreg.REG_DWORD, 1)
winreg.SetValueEx(key, "NoRepair", 0, winreg.REG_DWORD, 1)
def remove_arp_entry() -> None:
try:
winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, UNINSTALL_KEY)
except OSError:
pass
def audit_event(agent_token: str, hub: str, event_type: str, message: str) -> None:
"""Best-effort authenticated event POST (WINDOWS_INSTALL_COMPLETED etc.).
Never sends secrets; ignores failures so a hub hiccup cannot fail an install."""
try:
response = httpx.post(
(hub or hub_url()).rstrip("/") + "/v1/agents/events",
json={"event_type": event_type, "message": message, "context": {"source": "setup.exe", "agent_version": os.environ.get("AGENT_VERSION", "")}},
headers={"Authorization": f"Bearer {agent_token}"},
timeout=15,
)
response.raise_for_status()
except Exception: # noqa: BLE001 — best effort only
return
+24
View File
@@ -0,0 +1,24 @@
"""GTIFiscalAgentService.exe — frozen Windows Service host.
A thin entry that hands control to the already-bundled
`gti_agent_windows_service` wrapper (which reuses run_agent_service.run()).
It only guarantees the service locates `agent.env` and the DPAPI credential in
the install directory used by Setup.exe, regardless of how SCM launches it.
Built as a PyInstaller onedir; Setup.exe extracts this binary + its
`_internal/` dir into C:\Program Files\GTI\FiscalAgent\.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
INSTALL_DIR = Path(os.environ.get("PROGRAMFILES", r"C:\Program Files")) / "GTI" / "FiscalAgent"
os.environ.setdefault("GTI_AGENT_ENV_FILE", str(INSTALL_DIR / "agent.env"))
from gti_agent_windows_service import main # noqa: E402 (bundled by PyInstaller)
if __name__ == "__main__":
sys.exit(main())
+198
View File
@@ -0,0 +1,198 @@
"""Setup.exe — universal Windows installer for the GTI Fiscal Agent.
Two entry modes:
- GUI (default): tkinter wizard with a single install-code field.
- CLI (`--cli --code XXXX [--hub URL] [--install-dir PATH] [--no-service]`):
scripted install used by the automated E2E and the build smoke test.
Run elevated (PyInstaller --uac-admin). Enrollment is resolved by the Hub from
the install-code hash alone — no enrollment token, no bundle.
Flow on success:
1. POST /v1/agents/enroll {install_code, hostname, agent_version, machine_fingerprint}
2. write agent.env (non-secret only) + credentials.bin (DPAPI LocalMachine + ACL)
3. extract the bundled Service host (onedir) + Uninstall.exe + write executor
into the install directory
4. register service GTIFiscalAgent (Delayed Auto) + failure recovery
5. Firebird not configured -> report "serviço instalado; configure o arquivo
de banco para ativar" and do NOT start the service (no error loop)
6. write ARP uninstall key
7. best-effort WINDOWS_INSTALL_COMPLETED audit
The install code is never persisted; agent.env never holds the token; no UI or
flag enables Firebird/AI writes (always dry-run, writes disabled).
"""
from __future__ import annotations
import argparse
import os
import shutil
import sys
import threading
import tkinter as tk
from pathlib import Path
from tkinter import messagebox, ttk
import httpx
import install_common as common
MEIPASS = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent))
def install_flow(code: str, *, hub: str | None = None, install_dir_path: str | None = None, register_service: bool = True) -> dict:
"""Perform the full install. Returns the enroll result dict; raises RuntimeError
with a user-facing message on any failure."""
if install_dir_path:
os.environ["GTI_INSTALL_DIR"] = install_dir_path
install = common.install_dir()
try:
result = common.enroll(code, hub=hub)
except httpx.HTTPStatusError as error:
detail = ""
try:
detail = error.response.json().get("detail", "")
except Exception: # noqa: BLE001
detail = ""
reason = detail or error.response.reason_phrase or f"HTTP {error.response.status_code}"
raise RuntimeError(f"enrollment rejeitado: {reason}") from error
except Exception as error: # noqa: BLE001
raise RuntimeError(f"falha no enrollment: {error}") from error
agent_version = str(result.get("agent_version") or os.environ.get("AGENT_VERSION") or "")
os.environ["AGENT_VERSION"] = agent_version
common.write_agent_env(install, result)
common.write_credential(install, result["agent_token"])
extract_payload(install)
if register_service:
common.install_service(install)
common.write_arp_uninstall(install)
if common.service_running():
common.start_service()
try:
common.audit_event(result["agent_token"], result.get("hub_url") or hub, "WINDOWS_INSTALL_COMPLETED", f"agent {result.get('agent_id')} installed")
except Exception: # noqa: BLE001 — best effort
pass
result["install_dir"] = str(install)
result["agent_version"] = agent_version
return result
def extract_payload(install: Path) -> None:
"""Copy the bundled service host onedir, Uninstall.exe and the write
executor out of the onefile extraction dir into the install directory."""
install.mkdir(parents=True, exist_ok=True)
service_dir = MEIPASS / "GTIFiscalAgentService"
targets = [
(service_dir, install / "GTIFiscalAgentService"),
(MEIPASS / "Uninstall.exe", install / "Uninstall.exe"),
(MEIPASS / "scripts" / "firebird_write_executor.py", install / "scripts" / "firebird_write_executor.py"),
]
for source, dest in targets:
if not source.exists():
raise RuntimeError(f"bundled payload missing: {source}")
if source.is_dir():
shutil.copytree(source, dest, dirs_exist_ok=True)
else:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, dest)
class SetupWizard:
def __init__(self, root: tk.Tk):
self.root = root
root.title("GTI Fiscal Agent")
root.resizable(False, False)
root.geometry("720x250")
frame = ttk.Frame(root, padding=20)
frame.pack(fill="both", expand=True)
ttk.Label(frame, text="GTI Fiscal Agent — Instalação", font=("Segoe UI", 13, "bold")).pack(anchor="w")
ttk.Label(frame, text="Digite o código de instalação gerado no painel GTI Fiscal.").pack(anchor="w", pady=(4, 2))
ttk.Label(frame, text=f"Hub: {common.hub_url()}", foreground="#555").pack(anchor="w")
self.code_var = tk.StringVar()
ttk.Entry(frame, textvariable=self.code_var, width=26, font=("Consolas", 14), justify="center").pack(anchor="w", pady=(14, 4))
self.status = ttk.Label(frame, text="", foreground="#333")
self.status.pack(anchor="w", pady=(6, 0))
buttons = ttk.Frame(frame)
buttons.pack(anchor="e", pady=(10, 0))
self.install_btn = ttk.Button(buttons, text="Instalar", command=self.on_install)
self.install_btn.pack(side="left", padx=(0, 6))
ttk.Button(buttons, text="Fechar", command=root.destroy).pack(side="left")
root.bind("<Return>", lambda _event: self.on_install())
def _set_busy(self, busy: bool, text: str = ""):
self.status.config(text=text)
self.install_btn.config(state="disabled" if busy else "normal")
def on_install(self):
code = self.code_var.get().strip()
if not code:
self.status.config(text="Informe o código de instalação.", foreground="#b00")
return
self._set_busy(True, "Enviando código ao hub…")
threading.Thread(target=self._run, args=(code,), daemon=True).start()
def _run(self, code: str):
try:
result = install_flow(code)
except RuntimeError as error:
self._set_busy(False)
messagebox.showerror("GTI Fiscal Agent", str(error))
return
self._set_busy(False)
install = result["install_dir"]
messagebox.showinfo(
"GTI Fiscal Agent",
"Serviço GTI Fiscal Agent instalado com sucesso.\n\n"
"Firebird não está configurado — o serviço não foi iniciado.\n"
f"Local: {install}\n"
"Configure o arquivo de banco em agent.env para ativar.",
)
self.root.destroy()
def cli() -> int:
parser = argparse.ArgumentParser(description="GTI Fiscal Agent Setup (headless)")
parser.add_argument("--cli", action="store_true", help="run headless (no GUI)")
parser.add_argument("--code", required=True, help="XXXX-XXXX-XXXX-XXXX install code")
parser.add_argument("--hub", default=None, help="Hub base URL (dev override; default prod)")
parser.add_argument("--install-dir", default=None, help="install directory (dev override)")
parser.add_argument("--no-service", action="store_true", help="skip service registration + ARP (E2E scratch runs)")
args = parser.parse_args()
if args.hub:
os.environ["GTI_HUB_URL"] = args.hub
if args.install_dir:
os.environ["GTI_INSTALL_DIR"] = args.install_dir
result = install_flow(args.code, hub=args.hub, install_dir_path=args.install_dir, register_service=not args.no_service)
print(f"INSTALL_OK agent_id={result.get('agent_id')} install_dir={result.get('install_dir')} hub={result.get('hub_url')}")
return 0
def main():
if "--cli" in sys.argv:
try:
return cli()
except RuntimeError as error:
print(f"INSTALL_FAIL {error}", file=sys.stderr)
return 1
root = tk.Tk()
SetupWizard(root)
root.mainloop()
return 0
if __name__ == "__main__":
sys.exit(main())
+31
View File
@@ -0,0 +1,31 @@
"""Uninstall.exe — stops and removes the GTI Fiscal Agent service, then removes
the install directory (config, DPAPI credential, service host, state/logs) and
the ARP uninstall key. Invoked from Settings -> Apps -> GTI Fiscal Agent ->
Uninstall. Run elevated (PyInstaller --uac-admin); safe to run twice.
Never connects to the Hub and never reads the credential contents.
"""
from __future__ import annotations
import shutil
import sys
from pathlib import Path
import install_common as common
def main() -> int:
install = common.install_dir()
common.remove_service()
common.remove_arp_entry()
if install.exists():
try:
shutil.rmtree(install, ignore_errors=True)
except OSError:
pass # leftover locked handle; SCM may still hold the binary briefly
print(f"GTI Fiscal Agent removed from {install}")
return 0
if __name__ == "__main__":
sys.exit(main())