Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions .github/workflows/build-windows-installer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Build Windows Installer

on:
push:
branches: [ feat/ecac-bot-installer ]
workflow_dispatch:

jobs:
build-installer:
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Install Inno Setup via Chocolatey
run: |
choco install innosetup -y

- name: Show Inno path
run: |
dir "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" || dir "C:\Program Files\Inno Setup 6\ISCC.exe"

- name: Compile Inno Setup script
working-directory: ${{ github.workspace }}
run: |
$iscc = 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe'
if (-not (Test-Path $iscc)) { $iscc = 'C:\Program Files\Inno Setup 6\ISCC.exe' }
if (-not (Test-Path $iscc)) { Write-Error 'ISCC not found' ; exit 2 }
& $iscc "$env:GITHUB_WORKSPACE\ecac-bot\installers\installer.iss"

- name: Package output
run: |
$out = Get-ChildItem -Path "$env:GITHUB_WORKSPACE" -Recurse -Filter "ecac-bot-installer-setup.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $out) { Write-Error 'Installer exe not found' ; exit 2 }
Write-Host "Found installer: $($out.FullName)"
Copy-Item $out.FullName -Destination "$env:GITHUB_WORKSPACE\ecac-bot\ecac-windows-installer.exe" -Force

- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: ecac-windows-installer
path: ecac-bot/ecac-windows-installer.exe
43 changes: 43 additions & 0 deletions ecac-bot/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# ============================================
# Configuração do Bot RPA PER/DCOMP
# ============================================
# Copie este arquivo para .env e preencha os valores

# ===== AUTENTICAÇÃO DO BOT =====
# Token gerado em: Sistema > Administração > Tokens RPA
BOT_TOKEN=462c87ad1bfe914e6d935d2ae4d3e786eb2dd9ff8fb2d8baaeccbfca7f59cad0

# ===== CONEXÃO COM O SISTEMA =====
# URL da API do sistema (não altere)
API_BASE_URL=https://ekddbjpakojzzfzapssv.supabase.co/functions/v1/rpa-api

# ===== CONFIGURAÇÕES DO BOT =====
# Modo sem interface (true = invisível, false = mostra navegador)
HEADLESS_MODE=false

# Intervalo entre verificações de novas consultas (segundos)
POLLING_INTERVAL=60

# Timeout para operações no e-CAC (segundos)
ECAC_TIMEOUT=120

# Número máximo de consultas simultâneas
MAX_WORKERS=2

# ===== LOGS E DEBUG =====
LOG_LEVEL=INFO
LOG_FILE=./logs/bot.log
SCREENSHOTS_DIR=./screenshots

# Mantém o navegador aberto ao final (depuração)
DETACH_BROWSER=false

# Delay artificial entre ações (ms). Ex: 250 deixa mais 'humano'
SLOWMO_MS=0

# Concurrency de navegadores do e-CAC (recomendado 1)
ECAC_CONCURRENCY=1

# ===== OPCIONAL: PERFIL DO NAVEGADOR =====
# Se quiser rodar com um perfil persistente, descomente e ajuste o caminho:
# BROWSER_USER_DATA_DIR=C:\Users\SeuUsuário\AppData\Local\Google\Chrome\User Data\PlaywrightProfile
4 changes: 4 additions & 0 deletions ecac-bot/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
*.env
/.cache
/.output
92 changes: 92 additions & 0 deletions ecac-bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# ecac-bot

Pequeno scaffold para automação do e-CAC — apenas um ponto de partida. **Atenção:** use apenas em contas que você tem autorização para acessar.

## 🚀 Instalador Windows (Recomendado para Usuários)

Para usuários finais no **Windows 10/11**, recomenda-se usar o instalador executável que inclui tudo pré-configurado:

1. Baixe [**ecac-windows-installer.exe**](https://github.com/confisped-hub/openclaw-cloud/releases/download/v0.2.0/ecac-windows-installer.exe) da seção [Releases](https://github.com/confisped-hub/openclaw-cloud/releases)
2. Execute o arquivo `.exe` e siga as instruções
- Ele instalará automaticamente Node.js, Python, e todas as dependências
- Configurará o diretório de instalação em `C:\Program Files\ECAC-Bot`
3. Após a instalação:
- Navegue até `C:\Program Files\ECAC-Bot\ecac-bot`
- Copie `.env.example` para `.env`
- Preencha `ECAC_USERNAME`, `ECAC_PASSWORD` e `API_BASE_URL` (se usar modo worker)
- Execute `npm start` ou use o worker conforme descrito abaixo

## Manual de Instalação (Desenvolvedores / Linux/macOS)

Passos rápidos:

1. Copie `.env.example` para `.env` e preencha `ECAC_USERNAME` e `ECAC_PASSWORD`.
2. Instale dependências:

```bash
cd ecac-bot
npm install
npm run install-playwright
```

3. Rodar (recomendado com headful para tratar MFA manualmente):

```bash
# headful (padrão no .env.example)
npm start

# ou em headless
HEADLESS=true npm start
```

Notas importantes:
- Os seletores de login e de alteração de perfil em `src/bot.js` são exemplos. O e-CAC frequentemente muda a interface — ajuste os seletores conforme necessário.
- Não armazene credenciais em repositórios. Use variáveis de ambiente seguras.
- Se houver autenticação multifator (MFA), rode em modo não-headless, autentique manualmente no navegador quando solicitado e pressione Enter no terminal para continuar.

- O bot gera artefatos de depuração na raiz do projeto quando executado: `ecac-login-after-submit.png`, `ecac-login-after-submit.html`, `ecac-after-auth.png`, `ecac-after-profile-click.png`, `ecac-after-confirm.png`. Use estes arquivos para inspecionar elementos e ajustar seletores.
- Para inspecionar a UI e gerar seletores, considere usar o Playwright Codegen:

```bash
npx playwright codegen https://cav.receita.fazenda.gov.br/autenticacao/login
```

Isto abre um navegador interativo e escreve os comandos Playwright conforme você navega — muito útil para extrair seletores reais do e-CAC.

**Helper Windows para certificado**

Há um helper opcional para Windows que tenta importar um PFX e selecionar o certificado no diálogo de autenticação do Windows usando `pywinauto`.

- Arquivo: `win_cert_helper.py`
- Requer Python no Windows e dependência `pywinauto`.
- Uso recomendado: o `worker` (em Windows) inicia automaticamente o helper quando baixa um PFX; o helper aguarda o popup e tenta selecionar o certificado correspondente.

Instalação mínima no Windows:

```powershell
python -m pip install pywinauto
```

Observações:
- Este helper só funciona no Windows e deve ser executado no mesmo host onde o navegador será aberto.
- Se falhar, o `worker` tenta importar o PFX via `certutil` como fallback; em outros sistemas você precisará importar o PFX manualmente.

Import automático (Windows)

1. O `worker` agora tenta executar `win_import_pfx.ps1` para importar o PFX via `certutil` no usuário atual. Em seguida inicia `win_cert_helper.py` para aguardar e selecionar o certificado no diálogo.
2. Requisitos no Windows:

```powershell
# Powershell script usa certutil (builtin) e o helper usa pywinauto
python -m pip install pywinauto
```

3. Se preferir usar um perfil de navegador persistente (útil para evitar diálogos com certificados ou reutilizar sessão), defina `BROWSER_USER_DATA_DIR` no `.env` apontando para uma pasta (ex.: `C:\Users\SeuUsuario\AppData\Local\Google\Chrome\User Data\PlaywrightProfile`). O `bot` abrirá o contexto persistente usando esse diretório.

Exemplo `.env` parcial:

```
API_BASE_URL=https://sua.api
BOT_TOKEN=token
BROWSER_USER_DATA_DIR=C:\Users\SeuUsuario\AppData\Local\Google\Chrome\User Data\PlaywrightProfile
```
43 changes: 43 additions & 0 deletions ecac-bot/installer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env node
const { spawnSync } = require('child_process');
const os = require('os');
const path = require('path');
const fs = require('fs');

function run(cmd, args, opts = {}) {
console.log('>', cmd, args.join(' '));
const r = spawnSync(cmd, args, Object.assign({ stdio: 'inherit' }, opts));
if (r.error) throw r.error;
if (r.status !== 0) throw new Error(`${cmd} exited ${r.status}`);
}

async function main() {
const platform = os.platform();
const installerDir = path.join(__dirname, 'installers');

if (!fs.existsSync(installerDir)) {
console.error('installers dir not found');
process.exit(2);
}

try {
if (platform === 'win32') {
const script = path.join(installerDir, 'install_windows.ps1');
if (!fs.existsSync(script)) throw new Error('install_windows.ps1 not found');
console.log('Running Windows installer (PowerShell)');
run('powershell', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script]);
} else {
const script = path.join(installerDir, 'install_unix.sh');
if (!fs.existsSync(script)) throw new Error('install_unix.sh not found');
console.log('Running Unix installer (sh)');
run('sh', [script]);
}

console.log('\nInstallation finished. Run `npm install` and `npx playwright install --with-deps` in ecac-bot if not already run.');
} catch (e) {
console.error('Installer failed:', e.message || e);
process.exit(1);
}
}

main();
31 changes: 31 additions & 0 deletions ecac-bot/installers/install_unix.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/env sh
set -e
echo "=== ECAC-BOT INSTALLER (Unix) ==="

command -v node >/dev/null 2>&1 || { echo "Node.js is required. Install: https://nodejs.org/"; exit 2; }
command -v python3 >/dev/null 2>&1 || { echo "Python3 not found. Install python3 to use helper scripts."; }

echo "Installing npm dependencies..."
npm install

echo "Installing Playwright browsers (this may take a while)..."
npx playwright install --with-deps

if [ -f requirements.txt ]; then
echo "Installing Python requirements (helper)..."
python3 -m pip install -r requirements.txt || echo "pip install may have failed"
fi

if [ -n "$BROWSER_USER_DATA_DIR" ]; then
echo "Ensuring browser user data dir exists: $BROWSER_USER_DATA_DIR"
mkdir -p "$BROWSER_USER_DATA_DIR"
fi

if [ ! -f .env ] && [ -f .env.example ]; then
cp .env.example .env
echo "Created .env from .env.example — edit it now before running the bot."
else
echo ".env already exists or .env.example missing."
fi

echo "Installer finished. Please edit .env and then run: npm run start:worker"
43 changes: 43 additions & 0 deletions ecac-bot/installers/install_windows.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
Write-Host "=== ECAC-BOT INSTALLER (Windows) ==="

# Helper: check executables
function Check-Cmd($name) {
$p = Get-Command $name -ErrorAction SilentlyContinue
if (-not $p) { Write-Host "WARNING: $name not found in PATH" }
return $p -ne $null
}

Write-Host "Checking Node/npm..."
if (-not (Check-Cmd node)) { Write-Error "Node.js is required. Install from https://nodejs.org/"; exit 2 }
if (-not (Check-Cmd python)) { Write-Host "Python not found. Please install Python 3." }

Write-Host "Installing npm dependencies..."
npm install

Write-Host "Installing Playwright browsers (this may take a while)..."
npx playwright install --with-deps

if (Test-Path requirements.txt) {
Write-Host "Installing Python requirements (helper)..."
try {
python -m pip install -r requirements.txt
} catch {
Write-Warning "pip install may have failed. Ensure pip is available."
}
}

# Create persistent browser profile dir if requested
if ($env:BROWSER_USER_DATA_DIR) {
Write-Host "Ensuring browser user data dir exists: $env:BROWSER_USER_DATA_DIR"
New-Item -ItemType Directory -Force -Path $env:BROWSER_USER_DATA_DIR | Out-Null
}

# Copy .env.example to .env if not present
if (-not (Test-Path .env) -and (Test-Path .env.example)) {
Copy-Item .env.example .env
Write-Host "Created .env from .env.example — edit it now before running the bot."
} else {
Write-Host ".env already exists or .env.example missing."
}

Write-Host "Installer finished. Please edit .env and then run: npm run start:worker"
20 changes: 20 additions & 0 deletions ecac-bot/installers/installer.iss
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[Setup]
AppName=ECAC Bot Installer
AppVersion=0.1.0
; Install per-user to avoid requiring Administrator privileges
PrivilegesRequired=lowest
DefaultDirName={userappdata}\ECAC-Bot
DisableProgramGroupPage=yes
OutputBaseFilename=ecac-bot-installer-setup
Compression=lzma
SolidCompression=yes
SourceDir=..\..

[Files]
; Copia todo o diretório ecac-bot para o diretório de instalação
Source: "ecac-bot\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs

[Run]
; Executa o script PowerShell de pós-instalação para instalar dependências
; Run the helper as the original (non-elevated) user so %APPDATA% and env vars point to the launcher
Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\win_installer_helper.ps1"""; WorkingDir: "{app}"; Flags: runasoriginaluser
Loading