feat: initial commit - CertConverter PFX & AppWPP (React)
This commit is contained in:
+24
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||||
|
"plugins": ["react", "oxc"],
|
||||||
|
"rules": {
|
||||||
|
"react/rules-of-hooks": "error",
|
||||||
|
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||||
|
}
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
# Estágio 1: Build da aplicação React
|
||||||
|
FROM node:20-alpine AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Copia manifestos de dependência
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
# Instalação limpa
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
|
# Copia código fonte
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Compila para produção
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Estágio 2: Servidor Web Nginx ultra-leve
|
||||||
|
FROM nginx:alpine
|
||||||
|
|
||||||
|
# Remove configuração padrão
|
||||||
|
RUN rm -rf /usr/share/nginx/html/*
|
||||||
|
|
||||||
|
# Copia arquivos compilados do builder
|
||||||
|
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||||
|
|
||||||
|
# Copia arquivo de configuração do Nginx
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
|
||||||
|
EXPOSE 80
|
||||||
|
|
||||||
|
CMD ["nginx", "-g", "daemon off;"]
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# Suíte Web: Conversor de Certificados PFX & AppWPP (WhatsApp Manager)
|
||||||
|
|
||||||
|
Aplicação web completa desenvolvida em **React.js + Vite**, integrando duas soluções essenciais em uma única interface moderna, autônoma e de alta performance:
|
||||||
|
|
||||||
|
1. 🔒 **Conversor de Certificados Digitais (.PFX):**
|
||||||
|
Converte certificados do formato PKCS#12 (`*.pfx` ou `*.p12`) para **`*.crt`**, **`*.pem`** e **`*.key`**, reproduzindo 100% da lógica dos comandos nativos do OpenSSL no navegador (100% Client-Side).
|
||||||
|
2. 💬 **AppWPP (Gerenciador de Sessões WPPConnect):**
|
||||||
|
Migrado da versão Electron (`D:\Flavio\Projetos\AppWPP`) para **React.js puro**, permitindo gerenciar servidores WPPConnect, iniciar sessões, escanear QR Codes em tempo real, consultar status, gerar tokens e sincronizar dados com backup JSON ou Supabase.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Como Executar Localmente
|
||||||
|
|
||||||
|
### 1. Iniciar o Servidor de Desenvolvimento
|
||||||
|
```bash
|
||||||
|
cd C:\Openssl\bin\cert-converter-app
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
Acesse no navegador:
|
||||||
|
* 💻 **No computador local:** [http://localhost:5173](http://localhost:5173)
|
||||||
|
* 📱 **Na rede local:** `http://192.168.0.3:5173`
|
||||||
|
|
||||||
|
### 2. Gerar Versão de Produção (Build)
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
A pasta estática e otimizada **`dist/`** será gerada pronta para hospedar.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🛠️ Recursos das Aplicações
|
||||||
|
|
||||||
|
### 1. Conversor de Certificados Digitais (.PFX)
|
||||||
|
- **Equivalência OpenSSL:**
|
||||||
|
- **`*.crt`**: `openssl pkcs12 -in cert.pfx -clcerts -nokeys -out cert.crt` *(Apenas o certificado folha do cliente)*.
|
||||||
|
- **`*.pem`**: `openssl pkcs12 -in cert.pfx -nokeys -out cert.pem` *(Cadeia completa pública)*.
|
||||||
|
- **`*.key`**: `openssl pkcs12 -in cert.pfx -nocerts -nodes -out cert.key` *(Chave privada pronta para uso imediato em Nginx, Apache, IIS e NF-e)*.
|
||||||
|
- **Inspeção de Metadados:** Titular, CNPJ/CPF detectado automaticamente, AC Emissora, Validade e Dias Restantes, Serial e Thumbprints SHA-1/SHA-256.
|
||||||
|
- **Exportação:** Copiar código com 1 clique, download individual ou **Baixar Pacote (.ZIP)** completo.
|
||||||
|
|
||||||
|
### 2. AppWPP (Gerenciador WPPConnect)
|
||||||
|
- **Gerenciamento de Servidores:** Cadastro de múltiplos servidores WPPConnect (URL Base e Secret Key) com teste de conexão.
|
||||||
|
- **Sessões do WhatsApp:**
|
||||||
|
- Iniciar / Fechar / Desconectar sessões.
|
||||||
|
- Consulta de status em tempo real (`connected`, `qr`, `connecting`, `disconnected`).
|
||||||
|
- Modal interativo de **QR Code com atualização automática** e fechamento instantâneo após a leitura do celular.
|
||||||
|
- Geração e cópia de Token JWT de autenticação.
|
||||||
|
- Limpeza de dados de sessão no servidor.
|
||||||
|
- Inicialização em lote de todas as sessões pendentes.
|
||||||
|
- Listagem de todas as sessões registradas diretamente no servidor.
|
||||||
|
- **Persistência & Backup:**
|
||||||
|
- Armazenamento local no navegador (`localStorage`) com carga automática dos dados pré-existentes (`appwpp-data.json`).
|
||||||
|
- Exportação e importação de backups em formato JSON.
|
||||||
|
- Configuração opcional de integração com Supabase.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🌐 Guia de Hospedagem em Produção
|
||||||
|
|
||||||
|
| Plataforma | Procedimento |
|
||||||
|
| :--- | :--- |
|
||||||
|
| **Vercel** *(Recomendado)* | Execute `npx vercel` na pasta do projeto ou conecte ao repositório GitHub. |
|
||||||
|
| **Netlify** | Execute `npm run build` e arraste a pasta `dist` em [app.netlify.com/drop](https://app.netlify.com/drop). |
|
||||||
|
| **GitHub Pages** | Execute `npm run deploy` utilizando o pacote `gh-pages`. |
|
||||||
|
| **Docker / Linux** | Execute `docker compose up -d --build` (inicia na porta 8080 com Nginx otimizado). |
|
||||||
|
| **Windows Server (IIS)** | Execute `npm run build` e copie a pasta `dist` para o diretório do site no IIS (arquivo `web.config` já incluso). |
|
||||||
|
| **Apache / cPanel** | Suba os arquivos da pasta `dist` para `public_html` (arquivo `.htaccess` já incluso). |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📄 Licença
|
||||||
|
Distribuído sob a licença MIT. Livre para uso pessoal e comercial.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
services:
|
||||||
|
cert-converter:
|
||||||
|
build: .
|
||||||
|
container_name: cert-converter-app
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "8080:80"
|
||||||
|
environment:
|
||||||
|
- NODE_ENV=production
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%230ea5e9' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10'/><path d='m9 12 2 2 4-4'/></svg>" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>CertConverter PFX - Conversor de Certificados Digitais (.pfx para .crt, .pem, .key)</title>
|
||||||
|
<meta name="description" content="Converta certificados digitais do formato PKCS#12 (.pfx/.p12) para .crt, .pem e .key de forma 100% segura e offline no navegador." />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name localhost;
|
||||||
|
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html index.htm;
|
||||||
|
|
||||||
|
# Compressão Gzip
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 10240;
|
||||||
|
gzip_proxied expired no-cache no-store private auth;
|
||||||
|
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml application/javascript;
|
||||||
|
gzip_disable "MSIE [1-6]\.";
|
||||||
|
|
||||||
|
# Headers de Segurança
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN";
|
||||||
|
add_header X-XSS-Protection "1; mode=block";
|
||||||
|
add_header X-Content-Type-Options "nosniff";
|
||||||
|
add_header Referrer-Policy "strict-origin-when-cross-origin";
|
||||||
|
|
||||||
|
# SPA Routing (Single Page Application)
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Cache de assets estáticos
|
||||||
|
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, no-transform";
|
||||||
|
}
|
||||||
|
|
||||||
|
error_page 500 502 503 504 /50x.html;
|
||||||
|
location = /50x.html {
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+1442
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "cert-converter-app",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"lint": "oxlint",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"jszip": "^3.10.2",
|
||||||
|
"lucide-react": "^1.57.0",
|
||||||
|
"node-forge": "^1.4.0",
|
||||||
|
"react": "^19.2.8",
|
||||||
|
"react-dom": "^19.2.8"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "^19.2.18",
|
||||||
|
"@types/react-dom": "^19.2.7",
|
||||||
|
"@vitejs/plugin-react": "^6.1.1",
|
||||||
|
"oxlint": "^1.81.0",
|
||||||
|
"vite": "^8.3.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<IfModule mod_rewrite.c>
|
||||||
|
RewriteEngine On
|
||||||
|
RewriteBase /
|
||||||
|
RewriteRule ^index\.html$ - [L]
|
||||||
|
RewriteCond %{REQUEST_FILENAME} !-f
|
||||||
|
RewriteCond %{REQUEST_FILENAME} !-d
|
||||||
|
RewriteRule . /index.html [L]
|
||||||
|
</IfModule>
|
||||||
|
|
||||||
|
# Compressão Gzip
|
||||||
|
<IfModule mod_deflate.c>
|
||||||
|
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
|
||||||
|
</IfModule>
|
||||||
|
|
||||||
|
# Headers de Segurança
|
||||||
|
<IfModule mod_headers.c>
|
||||||
|
Header set X-Content-Type-Options "nosniff"
|
||||||
|
Header set X-Frame-Options "SAMEORIGIN"
|
||||||
|
Header set X-XSS-Protection "1; mode=block"
|
||||||
|
</IfModule>
|
||||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||||
|
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||||
|
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||||
|
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||||
|
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||||
|
</symbol>
|
||||||
|
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||||
|
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||||
|
</symbol>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,32 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<configuration>
|
||||||
|
<system.webServer>
|
||||||
|
<staticContent>
|
||||||
|
<remove fileExtension=".json" />
|
||||||
|
<mimeMap fileExtension=".json" mimeType="application/json" />
|
||||||
|
<remove fileExtension=".woff" />
|
||||||
|
<mimeMap fileExtension=".woff" mimeType="font/woff" />
|
||||||
|
<remove fileExtension=".woff2" />
|
||||||
|
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
|
||||||
|
</staticContent>
|
||||||
|
<rewrite>
|
||||||
|
<rules>
|
||||||
|
<rule name="React SPA Routes" stopProcessing="true">
|
||||||
|
<match url=".*" />
|
||||||
|
<conditions logicalGrouping="MatchAll">
|
||||||
|
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
|
||||||
|
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
|
||||||
|
</conditions>
|
||||||
|
<action type="Rewrite" url="/" />
|
||||||
|
</rule>
|
||||||
|
</rules>
|
||||||
|
</rewrite>
|
||||||
|
<httpProtocol>
|
||||||
|
<customHeaders>
|
||||||
|
<add name="X-Frame-Options" value="SAMEORIGIN" />
|
||||||
|
<add name="X-Content-Type-Options" value="nosniff" />
|
||||||
|
<add name="X-XSS-Protection" value="1; mode=block" />
|
||||||
|
</customHeaders>
|
||||||
|
</httpProtocol>
|
||||||
|
</system.webServer>
|
||||||
|
</configuration>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
/* Estilos globais gerenciados em src/index.css */
|
||||||
+243
@@ -0,0 +1,243 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import {
|
||||||
|
ShieldCheck,
|
||||||
|
ArrowRight,
|
||||||
|
RotateCcw,
|
||||||
|
AlertCircle,
|
||||||
|
Sparkles,
|
||||||
|
Lock,
|
||||||
|
Loader2,
|
||||||
|
MessageSquare
|
||||||
|
} from 'lucide-react';
|
||||||
|
import Header from './components/Header';
|
||||||
|
import SecurityBadge from './components/SecurityBadge';
|
||||||
|
import UploadZone from './components/UploadZone';
|
||||||
|
import PasswordInput from './components/PasswordInput';
|
||||||
|
import CertificateInfo from './components/CertificateInfo';
|
||||||
|
import OutputFiles from './components/OutputFiles';
|
||||||
|
import OpenSslReference from './components/OpenSslReference';
|
||||||
|
import HostGuideModal from './components/HostGuideModal';
|
||||||
|
import AppWPP from './components/wpp/AppWPP';
|
||||||
|
import { convertPfx } from './utils/certConverter';
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const [activeTab, setActiveTab] = useState('cert'); // 'cert' | 'wpp'
|
||||||
|
const [file, setFile] = useState(null);
|
||||||
|
const [arrayBuffer, setArrayBuffer] = useState(null);
|
||||||
|
const [baseName, setBaseName] = useState('certificado');
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [isConverting, setIsConverting] = useState(false);
|
||||||
|
const [conversionResult, setConversionResult] = useState(null);
|
||||||
|
const [errorMessage, setErrorMessage] = useState('');
|
||||||
|
const [isHostingGuideOpen, setIsHostingGuideOpen] = useState(false);
|
||||||
|
|
||||||
|
// Manipula seleção de arquivo .pfx
|
||||||
|
const handleFileSelected = (selectedFile) => {
|
||||||
|
setFile(selectedFile);
|
||||||
|
setConversionResult(null);
|
||||||
|
setErrorMessage('');
|
||||||
|
|
||||||
|
// Extrai nome base sem a extensão
|
||||||
|
const nameWithoutExt = selectedFile.name.replace(/\.[^/.]+$/, '');
|
||||||
|
setBaseName(nameWithoutExt || 'certificado');
|
||||||
|
|
||||||
|
// Lê os bytes brutos do arquivo
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (e) => {
|
||||||
|
setArrayBuffer(e.target.result);
|
||||||
|
};
|
||||||
|
reader.onerror = () => {
|
||||||
|
setErrorMessage('Falha ao ler o arquivo selecionado no seu computador.');
|
||||||
|
};
|
||||||
|
reader.readAsArrayBuffer(selectedFile);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Limpa tudo para recomeçar
|
||||||
|
const handleFileCleared = () => {
|
||||||
|
setFile(null);
|
||||||
|
setArrayBuffer(null);
|
||||||
|
setPassword('');
|
||||||
|
setConversionResult(null);
|
||||||
|
setErrorMessage('');
|
||||||
|
setBaseName('certificado');
|
||||||
|
};
|
||||||
|
|
||||||
|
// Executa a conversão criptográfica
|
||||||
|
const handleConvert = () => {
|
||||||
|
if (!arrayBuffer) {
|
||||||
|
setErrorMessage('Por favor, selecione um arquivo de certificado .pfx primeiro.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsConverting(true);
|
||||||
|
setErrorMessage('');
|
||||||
|
|
||||||
|
// Executa em pequeno timeout para permitir renderizar o estado de carregamento
|
||||||
|
setTimeout(() => {
|
||||||
|
try {
|
||||||
|
const result = convertPfx(arrayBuffer, password);
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
setConversionResult(result);
|
||||||
|
setErrorMessage('');
|
||||||
|
} else {
|
||||||
|
setConversionResult(null);
|
||||||
|
setErrorMessage(result.error);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setConversionResult(null);
|
||||||
|
setErrorMessage('Ocorreu um erro inesperado ao converter: ' + (err.message || ''));
|
||||||
|
} finally {
|
||||||
|
setIsConverting(false);
|
||||||
|
}
|
||||||
|
}, 80);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="app-layout">
|
||||||
|
{/* Barra de Navegação Superior com Alternador de Apps */}
|
||||||
|
<Header
|
||||||
|
activeTab={activeTab}
|
||||||
|
onSelectTab={setActiveTab}
|
||||||
|
onOpenHostingGuide={() => setIsHostingGuideOpen(true)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Conteúdo Principal */}
|
||||||
|
<main className="main-content">
|
||||||
|
{activeTab === 'cert' ? (
|
||||||
|
<div className="container">
|
||||||
|
{/* Banner de Segurança & Privacidade */}
|
||||||
|
<SecurityBadge />
|
||||||
|
|
||||||
|
{/* Card Principal de Conversão */}
|
||||||
|
<section className="card-converter">
|
||||||
|
<div className="card-header-bar">
|
||||||
|
<div className="card-header-title">
|
||||||
|
<Sparkles size={20} className="text-cyan" />
|
||||||
|
<h2>Conversão de Certificado Digital (.pfx)</h2>
|
||||||
|
</div>
|
||||||
|
<span className="step-badge">Etapa 1 de 2</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Zona de Upload / Drag & Drop */}
|
||||||
|
<UploadZone
|
||||||
|
file={file}
|
||||||
|
onFileSelected={handleFileSelected}
|
||||||
|
onFileCleared={handleFileCleared}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Campo de Senha (habilitado quando há arquivo) */}
|
||||||
|
{file && (
|
||||||
|
<div className="form-controls-wrapper">
|
||||||
|
<PasswordInput
|
||||||
|
password={password}
|
||||||
|
onChange={setPassword}
|
||||||
|
onSubmit={handleConvert}
|
||||||
|
disabled={isConverting}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Botões de Ação */}
|
||||||
|
<div className="actions-bar">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-convert"
|
||||||
|
onClick={handleConvert}
|
||||||
|
disabled={isConverting}
|
||||||
|
>
|
||||||
|
{isConverting ? (
|
||||||
|
<>
|
||||||
|
<Loader2 size={18} className="animate-spin" />
|
||||||
|
<span>Processando Criptografia...</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Lock size={18} />
|
||||||
|
<span>Converter para .CRT, .PEM e .KEY</span>
|
||||||
|
<ArrowRight size={18} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-reset"
|
||||||
|
onClick={handleFileCleared}
|
||||||
|
disabled={isConverting}
|
||||||
|
title="Limpar e selecionar outro arquivo"
|
||||||
|
>
|
||||||
|
<RotateCcw size={16} />
|
||||||
|
<span>Limpar</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Mensagem de Erro amigável */}
|
||||||
|
{errorMessage && (
|
||||||
|
<div className="alert-error-box">
|
||||||
|
<AlertCircle size={20} />
|
||||||
|
<div className="alert-error-text">
|
||||||
|
<strong>Atenção:</strong> {errorMessage}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Exibição dos Resultados após conversão */}
|
||||||
|
{conversionResult && (
|
||||||
|
<section className="results-container">
|
||||||
|
{/* Metadados e Validade do Certificado */}
|
||||||
|
<CertificateInfo metadata={conversionResult.metadata} />
|
||||||
|
|
||||||
|
{/* Arquivos Gerados com Abas, Cópia e Download */}
|
||||||
|
<OutputFiles
|
||||||
|
results={conversionResult}
|
||||||
|
baseName={baseName}
|
||||||
|
metadata={conversionResult.metadata}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Referência Técnica dos Comandos OpenSSL equivalentes */}
|
||||||
|
<OpenSslReference baseName={baseName} />
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
/* Aplicativo WPPConnect Integrado */
|
||||||
|
<div className="wpp-view-wrapper">
|
||||||
|
<AppWPP />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{/* Rodapé Informativo */}
|
||||||
|
<footer className="footer">
|
||||||
|
<div className="footer-content">
|
||||||
|
<p>
|
||||||
|
{activeTab === 'cert'
|
||||||
|
? 'CertConverter Web — Conversão PKCS#12 / X.509 em conformidade com padrões ICP-Brasil e OpenSSL.'
|
||||||
|
: 'AppWPP Web — Gerenciador de Sessões WPPConnect integrado ao portal de utilitários.'}
|
||||||
|
</p>
|
||||||
|
<div className="footer-links">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="link-plain"
|
||||||
|
onClick={() => setIsHostingGuideOpen(true)}
|
||||||
|
>
|
||||||
|
Como Hospedar esta Aplicação
|
||||||
|
</button>
|
||||||
|
<span>•</span>
|
||||||
|
<span className="footer-shield">
|
||||||
|
<ShieldCheck size={14} /> 100% no cliente (Executa em qualquer navegador)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
|
||||||
|
{/* Modal com Guia Passo a Passo de Hospedagem */}
|
||||||
|
<HostGuideModal
|
||||||
|
isOpen={isHostingGuideOpen}
|
||||||
|
onClose={() => setIsHostingGuideOpen(false)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 4.0 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,147 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
CheckCircle2,
|
||||||
|
AlertTriangle,
|
||||||
|
XCircle,
|
||||||
|
Calendar,
|
||||||
|
Building,
|
||||||
|
User,
|
||||||
|
Key,
|
||||||
|
Hash,
|
||||||
|
ShieldCheck,
|
||||||
|
Clock
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
export default function CertificateInfo({ metadata }) {
|
||||||
|
if (!metadata) return null;
|
||||||
|
|
||||||
|
const { subject, issuer, validity, taxId, keyDetails, serialNumber, fingerprints, totalCerts } = metadata;
|
||||||
|
|
||||||
|
// Status de validade
|
||||||
|
const getStatusBadge = () => {
|
||||||
|
if (validity.isExpired) {
|
||||||
|
return (
|
||||||
|
<span className="badge-status badge-expired">
|
||||||
|
<XCircle size={14} />
|
||||||
|
Expirado ({Math.abs(validity.daysRemaining)} dias atrás)
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (validity.daysRemaining <= 30) {
|
||||||
|
return (
|
||||||
|
<span className="badge-status badge-warning">
|
||||||
|
<AlertTriangle size={14} />
|
||||||
|
Expira em breve ({validity.daysRemaining} dias)
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className="badge-status badge-active">
|
||||||
|
<CheckCircle2 size={14} />
|
||||||
|
Válido / Ativo ({validity.daysRemaining} dias restantes)
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="card-cert-info">
|
||||||
|
<div className="cert-info-header">
|
||||||
|
<div className="cert-info-title-group">
|
||||||
|
<ShieldCheck className="text-emerald" size={22} />
|
||||||
|
<h3 className="cert-info-title">Metadados e Inspeção do Certificado</h3>
|
||||||
|
</div>
|
||||||
|
{getStatusBadge()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="cert-grid">
|
||||||
|
{/* Titular */}
|
||||||
|
<div className="cert-grid-item full-width">
|
||||||
|
<div className="cert-label">
|
||||||
|
<User size={15} />
|
||||||
|
<span>Titular / Nome Comum (CN)</span>
|
||||||
|
</div>
|
||||||
|
<div className="cert-value font-highlight">
|
||||||
|
{subject.commonName || 'Não especificado'}
|
||||||
|
</div>
|
||||||
|
{taxId && (
|
||||||
|
<div className="tax-id-tag">
|
||||||
|
<strong>{taxId.type}:</strong> {taxId.value}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Emissor */}
|
||||||
|
<div className="cert-grid-item">
|
||||||
|
<div className="cert-label">
|
||||||
|
<Building size={15} />
|
||||||
|
<span>Autoridade Emissora (Issuer)</span>
|
||||||
|
</div>
|
||||||
|
<div className="cert-value">
|
||||||
|
{issuer.commonName || issuer.organization || 'Não especificado'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chave e Tamanho */}
|
||||||
|
<div className="cert-grid-item">
|
||||||
|
<div className="cert-label">
|
||||||
|
<Key size={15} />
|
||||||
|
<span>Chave Criptográfica</span>
|
||||||
|
</div>
|
||||||
|
<div className="cert-value">
|
||||||
|
{keyDetails ? `${keyDetails.type} (${keyDetails.bits} bits)` : 'Chave não encontrada'}
|
||||||
|
{metadata.hasPrivateKey && <span className="tag-pill tag-pill-success">Chave Privada Incluída</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Validade Inicial */}
|
||||||
|
<div className="cert-grid-item">
|
||||||
|
<div className="cert-label">
|
||||||
|
<Calendar size={15} />
|
||||||
|
<span>Válido a partir de</span>
|
||||||
|
</div>
|
||||||
|
<div className="cert-value">{validity.notBeforeFormatted}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Validade Final */}
|
||||||
|
<div className="cert-grid-item">
|
||||||
|
<div className="cert-label">
|
||||||
|
<Clock size={15} />
|
||||||
|
<span>Válido até</span>
|
||||||
|
</div>
|
||||||
|
<div className="cert-value">{validity.notAfterFormatted}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Serial Number */}
|
||||||
|
<div className="cert-grid-item">
|
||||||
|
<div className="cert-label">
|
||||||
|
<Hash size={15} />
|
||||||
|
<span>Número de Série</span>
|
||||||
|
</div>
|
||||||
|
<div className="cert-value cert-mono">{serialNumber || 'N/A'}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Cadeia de Certificados */}
|
||||||
|
<div className="cert-grid-item">
|
||||||
|
<div className="cert-label">
|
||||||
|
<ShieldCheck size={15} />
|
||||||
|
<span>Total de Certificados na Cadeia</span>
|
||||||
|
</div>
|
||||||
|
<div className="cert-value">
|
||||||
|
{totalCerts} certificado(s) detectado(s)
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Fingerprint SHA-1 */}
|
||||||
|
<div className="cert-grid-item full-width">
|
||||||
|
<div className="cert-label">
|
||||||
|
<Hash size={15} />
|
||||||
|
<span>Impressão Digital (Thumbprint SHA-1)</span>
|
||||||
|
</div>
|
||||||
|
<div className="cert-value cert-mono text-sm">
|
||||||
|
{fingerprints?.sha1 || 'N/A'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { ShieldCheck, MessageSquare, Server, Layers } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function Header({ activeTab, onSelectTab, onOpenHostingGuide }) {
|
||||||
|
return (
|
||||||
|
<header className="header">
|
||||||
|
<div className="header-container">
|
||||||
|
<div className="header-brand">
|
||||||
|
<div className="brand-icon-wrapper">
|
||||||
|
{activeTab === 'cert' ? (
|
||||||
|
<ShieldCheck className="brand-icon" size={26} />
|
||||||
|
) : (
|
||||||
|
<MessageSquare className="brand-icon" size={26} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h1 className="brand-title">
|
||||||
|
{activeTab === 'cert' ? 'CertConverter PFX' : 'AppWPP Manager'}
|
||||||
|
</h1>
|
||||||
|
<p className="brand-subtitle">
|
||||||
|
{activeTab === 'cert'
|
||||||
|
? 'Conversor de Certificado Digital (.pfx para .crt, .pem, .key)'
|
||||||
|
: 'Gerenciador de Sessões WPPConnect / WhatsApp'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Seletor Central de Aplicação */}
|
||||||
|
<div className="app-nav-tabs">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`app-nav-btn ${activeTab === 'cert' ? 'app-nav-btn-active' : ''}`}
|
||||||
|
onClick={() => onSelectTab('cert')}
|
||||||
|
>
|
||||||
|
<ShieldCheck size={18} />
|
||||||
|
<span>Conversor PFX</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`app-nav-btn ${activeTab === 'wpp' ? 'app-nav-btn-active app-nav-btn-wpp' : ''}`}
|
||||||
|
onClick={() => onSelectTab('wpp')}
|
||||||
|
>
|
||||||
|
<MessageSquare size={18} />
|
||||||
|
<span>AppWPP (WhatsApp)</span>
|
||||||
|
<span className="nav-badge-pill">8</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="header-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="guide-button"
|
||||||
|
onClick={onOpenHostingGuide}
|
||||||
|
title="Ver instruções de hospedagem da aplicação"
|
||||||
|
>
|
||||||
|
<Server size={18} />
|
||||||
|
<span>Hospedagem</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import {
|
||||||
|
X,
|
||||||
|
Server,
|
||||||
|
Globe,
|
||||||
|
Layers,
|
||||||
|
Terminal,
|
||||||
|
Check,
|
||||||
|
Copy,
|
||||||
|
FileCode,
|
||||||
|
HardDrive
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
export default function HostGuideModal({ isOpen, onClose }) {
|
||||||
|
const [activePlatform, setActivePlatform] = useState('vercel');
|
||||||
|
const [copiedKey, setCopiedKey] = useState(null);
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const handleCopy = (code, key) => {
|
||||||
|
navigator.clipboard.writeText(code);
|
||||||
|
setCopiedKey(key);
|
||||||
|
setTimeout(() => setCopiedKey(null), 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const platforms = [
|
||||||
|
{ id: 'vercel', name: 'Vercel', icon: Globe },
|
||||||
|
{ id: 'netlify', name: 'Netlify', icon: Layers },
|
||||||
|
{ id: 'github', name: 'GitHub Pages', icon: Terminal },
|
||||||
|
{ id: 'docker', name: 'Docker / Linux', icon: Server },
|
||||||
|
{ id: 'iis', name: 'Windows IIS', icon: HardDrive },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal-dialog" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div className="modal-title-box">
|
||||||
|
<Server size={22} className="text-cyan" />
|
||||||
|
<div>
|
||||||
|
<h3 className="modal-title">Guia de Hospedagem & Deploy</h3>
|
||||||
|
<p className="modal-subtitle">Como publicar esta aplicação React em produção</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="modal-close-btn" onClick={onClose}>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Abas de Plataforma */}
|
||||||
|
<div className="modal-tabs">
|
||||||
|
{platforms.map((p) => {
|
||||||
|
const Icon = p.icon;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={p.id}
|
||||||
|
type="button"
|
||||||
|
className={`modal-tab-btn ${activePlatform === p.id ? 'modal-tab-btn-active' : ''}`}
|
||||||
|
onClick={() => setActivePlatform(p.id)}
|
||||||
|
>
|
||||||
|
<Icon size={16} />
|
||||||
|
<span>{p.name}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Conteúdo da Plataforma */}
|
||||||
|
<div className="modal-body">
|
||||||
|
{/* VERCEL */}
|
||||||
|
{activePlatform === 'vercel' && (
|
||||||
|
<div className="guide-content">
|
||||||
|
<h4>Hospedar na Vercel (Recomendado - Gratuito e Instantâneo)</h4>
|
||||||
|
<p>
|
||||||
|
A Vercel é a plataforma mais simples para hospedar aplicações Vite/React. Possui SSL automático e CDN global.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h5>Opção 1: Via Linha de Comando (CLI da Vercel)</h5>
|
||||||
|
<div className="guide-code-box">
|
||||||
|
<pre>
|
||||||
|
<code>{`# 1. Instale a CLI da Vercel globalmente
|
||||||
|
npm i -g vercel
|
||||||
|
|
||||||
|
# 2. Na pasta do projeto, execute o comando de deploy
|
||||||
|
vercel`}</code>
|
||||||
|
</pre>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-copy-guide"
|
||||||
|
onClick={() => handleCopy(`npm i -g vercel\nvercel`, 'vercel-cli')}
|
||||||
|
>
|
||||||
|
{copiedKey === 'vercel-cli' ? <Check size={16} /> : <Copy size={16} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h5>Opção 2: Conectar com o Repositório GitHub</h5>
|
||||||
|
<ol className="guide-steps">
|
||||||
|
<li>Suba este projeto para o seu repositório no GitHub.</li>
|
||||||
|
<li>Acesse <strong>vercel.com</strong> e faça login com seu GitHub.</li>
|
||||||
|
<li>Clique em <strong>Add New Project</strong> e importe o repositório.</li>
|
||||||
|
<li>O Framework Preset será detectado automaticamente como <strong>Vite</strong>.</li>
|
||||||
|
<li>Clique em <strong>Deploy</strong>. Seu link HTTPS estará no ar em segundos!</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* NETLIFY */}
|
||||||
|
{activePlatform === 'netlify' && (
|
||||||
|
<div className="guide-content">
|
||||||
|
<h4>Hospedar na Netlify (Deploy com Arrastar e Soltar ou Git)</h4>
|
||||||
|
<p>Você pode fazer o deploy sem nem precisar de conta Git, apenas gerando a pasta estática:</p>
|
||||||
|
|
||||||
|
<h5>Método Drop (Arrastar Pasta):</h5>
|
||||||
|
<div className="guide-code-box">
|
||||||
|
<pre>
|
||||||
|
<code>{`# 1. Gere a compilação de produção
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# 2. A pasta 'dist' será gerada com os arquivos estáticos prontos.`}</code>
|
||||||
|
</pre>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-copy-guide"
|
||||||
|
onClick={() => handleCopy(`npm run build`, 'netlify-build')}
|
||||||
|
>
|
||||||
|
{copiedKey === 'netlify-build' ? <Check size={16} /> : <Copy size={16} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ol className="guide-steps">
|
||||||
|
<li>Acesse <strong>app.netlify.com/drop</strong>.</li>
|
||||||
|
<li>Arraste a pasta <strong>dist</strong> gerada direto para a tela do navegador.</li>
|
||||||
|
<li>Pronto! O site recebe uma URL pública com HTTPS imediato.</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* GITHUB PAGES */}
|
||||||
|
{activePlatform === 'github' && (
|
||||||
|
<div className="guide-content">
|
||||||
|
<h4>Hospedar no GitHub Pages</h4>
|
||||||
|
<p>Hospedagem gratuita direto no seu repositório do GitHub.</p>
|
||||||
|
|
||||||
|
<div className="guide-code-box">
|
||||||
|
<pre>
|
||||||
|
<code>{`# 1. Instale o gh-pages como dependência de desenvolvimento
|
||||||
|
npm install -D gh-pages
|
||||||
|
|
||||||
|
# 2. Adicione no package.json:
|
||||||
|
# "homepage": "https://seu-usuario.github.io/cert-converter-app",
|
||||||
|
# "scripts": {
|
||||||
|
# "predeploy": "npm run build",
|
||||||
|
# "deploy": "gh-pages -d dist"
|
||||||
|
# }
|
||||||
|
|
||||||
|
# 3. Dispare o deploy:
|
||||||
|
npm run deploy`}</code>
|
||||||
|
</pre>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-copy-guide"
|
||||||
|
onClick={() => handleCopy(`npm install -D gh-pages\nnpm run deploy`, 'gh-pages')}
|
||||||
|
>
|
||||||
|
{copiedKey === 'gh-pages' ? <Check size={16} /> : <Copy size={16} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* DOCKER / LINUX */}
|
||||||
|
{activePlatform === 'docker' && (
|
||||||
|
<div className="guide-content">
|
||||||
|
<h4>Hospedar em Servidor Próprio / Linux com Docker & Nginx</h4>
|
||||||
|
<p>Para empresas ou redes internas que desejam rodar o conversor em servidor on-premise isolado:</p>
|
||||||
|
|
||||||
|
<div className="guide-code-box">
|
||||||
|
<pre>
|
||||||
|
<code>{`# 1. Construir a imagem Docker
|
||||||
|
docker build -t cert-converter-app .
|
||||||
|
|
||||||
|
# 2. Rodar o container na porta 80
|
||||||
|
docker run -d -p 80:80 --name cert-converter cert-converter-app`}</code>
|
||||||
|
</pre>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-copy-guide"
|
||||||
|
onClick={() => handleCopy(`docker build -t cert-converter-app .\ndocker run -d -p 80:80 --name cert-converter cert-converter-app`, 'docker')}
|
||||||
|
>
|
||||||
|
{copiedKey === 'docker' ? <Check size={16} /> : <Copy size={16} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="guide-note">
|
||||||
|
Um arquivo <strong>Dockerfile</strong> e <strong>nginx.conf</strong> otimizados já foram criados na raiz do projeto.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* IIS */}
|
||||||
|
{activePlatform === 'iis' && (
|
||||||
|
<div className="guide-content">
|
||||||
|
<h4>Hospedar no Windows Server (IIS)</h4>
|
||||||
|
<p>Ideal para empresas com infraestrutura interna Windows:</p>
|
||||||
|
|
||||||
|
<ol className="guide-steps">
|
||||||
|
<li>Execute <code>npm run build</code> para gerar a pasta <code>dist</code>.</li>
|
||||||
|
<li>Copie os arquivos da pasta <code>dist</code> para o diretório do IIS (ex: <code>C:\inetpub\wwwroot\cert-converter</code>).</li>
|
||||||
|
<li>Crie um site ou aplicativo no Gerenciador do IIS apontando para essa pasta.</li>
|
||||||
|
<li>
|
||||||
|
Certifique-se de que o arquivo <code>web.config</code> incluído no projeto esteja na raiz para gerenciar as rotas.
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer">
|
||||||
|
<button type="button" className="btn-modal-close" onClick={onClose}>
|
||||||
|
Entendido / Fechar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Terminal, Copy, Check, ChevronDown, ChevronUp } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function OpenSslReference({ baseName = 'certificado' }) {
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
const [copiedIndex, setCopiedIndex] = useState(null);
|
||||||
|
|
||||||
|
const commands = [
|
||||||
|
{
|
||||||
|
title: '1. Conversão para CRT (Apenas Certificado do Cliente)',
|
||||||
|
flags: '-clcerts -nokeys',
|
||||||
|
cmd: `openssl pkcs12 -in ${baseName}.pfx -clcerts -nokeys -out ${baseName}.crt`,
|
||||||
|
desc: 'Extrai exclusivamente o certificado cliente (-clcerts) omitindo a chave privada (-nokeys).'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '2. Conversão para PEM (Cadeia Completa de Certificados)',
|
||||||
|
flags: '-nokeys',
|
||||||
|
cmd: `openssl pkcs12 -in ${baseName}.pfx -nokeys -out ${baseName}.pem`,
|
||||||
|
desc: 'Extrai todos os certificados da cadeia pública (cliente, intermediários e raiz), sem chaves privadas.'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '3. Conversão para KEY (Chave Privada Descriptografada)',
|
||||||
|
flags: '-nocerts -nodes',
|
||||||
|
cmd: `openssl pkcs12 -in ${baseName}.pfx -nocerts -nodes -out ${baseName}.key`,
|
||||||
|
desc: 'Extrai apenas a chave privada (-nocerts) sem senha/descriptografada (-nodes) para uso direto em servidores.'
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const handleCopy = (text, index) => {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
setCopiedIndex(index);
|
||||||
|
setTimeout(() => setCopiedIndex(null), 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="openssl-ref-card">
|
||||||
|
<div
|
||||||
|
className="openssl-ref-header"
|
||||||
|
onClick={() => setIsOpen(!isOpen)}
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
>
|
||||||
|
<div className="openssl-ref-title">
|
||||||
|
<Terminal size={20} className="text-cyan" />
|
||||||
|
<span>Equivalência com Comandos CLI do OpenSSL</span>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="btn-toggle-ref">
|
||||||
|
{isOpen ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isOpen && (
|
||||||
|
<div className="openssl-ref-body">
|
||||||
|
<p className="openssl-ref-intro">
|
||||||
|
Este aplicativo web executa rigorosamente as mesmas operações criptográficas que os comandos nativos do OpenSSL abaixo:
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="cmd-list">
|
||||||
|
{commands.map((c, idx) => (
|
||||||
|
<div key={idx} className="cmd-item">
|
||||||
|
<div className="cmd-item-header">
|
||||||
|
<strong>{c.title}</strong>
|
||||||
|
<span className="cmd-flag-tag">{c.flags}</span>
|
||||||
|
</div>
|
||||||
|
<div className="cmd-code-line">
|
||||||
|
<code>{c.cmd}</code>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-copy-cmd"
|
||||||
|
onClick={() => handleCopy(c.cmd, idx)}
|
||||||
|
title="Copiar comando"
|
||||||
|
>
|
||||||
|
{copiedIndex === idx ? <Check size={16} className="text-emerald" /> : <Copy size={16} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="cmd-desc">{c.desc}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import {
|
||||||
|
FileCode2,
|
||||||
|
Key,
|
||||||
|
FileText,
|
||||||
|
Download,
|
||||||
|
Copy,
|
||||||
|
Check,
|
||||||
|
Archive,
|
||||||
|
ExternalLink,
|
||||||
|
ShieldAlert
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { downloadFile, downloadAllAsZip } from '../utils/downloadHelper';
|
||||||
|
|
||||||
|
export default function OutputFiles({ results, baseName, metadata }) {
|
||||||
|
const [activeTab, setActiveTab] = useState('crt');
|
||||||
|
const [copiedKey, setCopiedKey] = useState(null);
|
||||||
|
|
||||||
|
if (!results) return null;
|
||||||
|
|
||||||
|
const handleCopy = (content, keyName) => {
|
||||||
|
navigator.clipboard.writeText(content);
|
||||||
|
setCopiedKey(keyName);
|
||||||
|
setTimeout(() => {
|
||||||
|
setCopiedKey(null);
|
||||||
|
}, 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDownloadSingle = (type) => {
|
||||||
|
const filename = `${baseName}.${type}`;
|
||||||
|
downloadFile(results[type], filename);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDownloadZip = () => {
|
||||||
|
downloadAllAsZip(results, baseName, metadata);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tabs = [
|
||||||
|
{
|
||||||
|
id: 'crt',
|
||||||
|
label: `${baseName}.crt`,
|
||||||
|
ext: '.CRT',
|
||||||
|
title: 'Certificado do Cliente',
|
||||||
|
desc: 'Apenas o certificado folha/cliente do titular (sem certificados intermediários da CA e sem chave privada).',
|
||||||
|
command: `openssl pkcs12 -in ${baseName}.pfx -clcerts -nokeys -out ${baseName}.crt`,
|
||||||
|
content: results.crt,
|
||||||
|
icon: FileCode2,
|
||||||
|
badge: 'Público',
|
||||||
|
badgeClass: 'badge-blue'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'pem',
|
||||||
|
label: `${baseName}.pem`,
|
||||||
|
ext: '.PEM',
|
||||||
|
title: 'Cadeia Completa de Certificados',
|
||||||
|
desc: 'Contém todos os certificados da cadeia (certificado cliente + certificados intermediários e raiz), sem chaves.',
|
||||||
|
command: `openssl pkcs12 -in ${baseName}.pfx -nokeys -out ${baseName}.pem`,
|
||||||
|
content: results.pem,
|
||||||
|
icon: FileText,
|
||||||
|
badge: 'Cadeia Completa',
|
||||||
|
badgeClass: 'badge-purple'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'key',
|
||||||
|
label: `${baseName}.key`,
|
||||||
|
ext: '.KEY',
|
||||||
|
title: 'Chave Privada (Descriptografada)',
|
||||||
|
desc: 'Chave privada pronta para uso em servidores web (Nginx, Apache), microsserviços ou sistemas de emissão de NF-e (-nodes).',
|
||||||
|
command: `openssl pkcs12 -in ${baseName}.pfx -nocerts -nodes -out ${baseName}.key`,
|
||||||
|
content: results.key,
|
||||||
|
icon: Key,
|
||||||
|
badge: 'Privado / Confidencial',
|
||||||
|
badgeClass: 'badge-amber',
|
||||||
|
isSecret: true
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const currentTab = tabs.find(t => t.id === activeTab) || tabs[0];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="output-section">
|
||||||
|
<div className="output-header-bar">
|
||||||
|
<div>
|
||||||
|
<h3 className="output-heading">Arquivos Convertidos</h3>
|
||||||
|
<p className="output-subheading">
|
||||||
|
Geração concluída com sucesso. Escolha um arquivo para pré-visualizar ou baixe o pacote completo.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-download-zip"
|
||||||
|
onClick={handleDownloadZip}
|
||||||
|
>
|
||||||
|
<Archive size={18} />
|
||||||
|
<span>Baixar Pacote (.ZIP)</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Cards de Atalho Rápido */}
|
||||||
|
<div className="quick-download-cards">
|
||||||
|
{tabs.map((tab) => (
|
||||||
|
<div
|
||||||
|
key={tab.id}
|
||||||
|
className={`quick-card ${activeTab === tab.id ? 'quick-card-selected' : ''}`}
|
||||||
|
onClick={() => setActiveTab(tab.id)}
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
>
|
||||||
|
<div className="quick-card-top">
|
||||||
|
<span className={`tag-pill ${tab.badgeClass}`}>{tab.ext}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-icon-download"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
handleDownloadSingle(tab.id);
|
||||||
|
}}
|
||||||
|
title={`Baixar ${baseName}.${tab.id}`}
|
||||||
|
>
|
||||||
|
<Download size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="quick-card-name">{baseName}.{tab.id}</div>
|
||||||
|
<div className="quick-card-title">{tab.title}</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Visualizador de Arquivo com Abas */}
|
||||||
|
<div className="file-viewer-container">
|
||||||
|
<div className="viewer-tab-bar">
|
||||||
|
<div className="viewer-tabs">
|
||||||
|
{tabs.map((tab) => {
|
||||||
|
const Icon = tab.icon;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
type="button"
|
||||||
|
className={`viewer-tab-btn ${activeTab === tab.id ? 'viewer-tab-btn-active' : ''}`}
|
||||||
|
onClick={() => setActiveTab(tab.id)}
|
||||||
|
>
|
||||||
|
<Icon size={16} />
|
||||||
|
<span>{baseName}.{tab.id}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="viewer-tab-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-copy-code"
|
||||||
|
onClick={() => handleCopy(currentTab.content, currentTab.id)}
|
||||||
|
>
|
||||||
|
{copiedKey === currentTab.id ? (
|
||||||
|
<>
|
||||||
|
<Check size={16} className="text-emerald" />
|
||||||
|
<span>Copiado!</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Copy size={16} />
|
||||||
|
<span>Copiar Conteúdo</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-download-file-direct"
|
||||||
|
onClick={() => handleDownloadSingle(currentTab.id)}
|
||||||
|
>
|
||||||
|
<Download size={16} />
|
||||||
|
<span>Baixar .{currentTab.id}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Informações da Aba Ativa */}
|
||||||
|
<div className="viewer-meta-bar">
|
||||||
|
<div className="viewer-desc">
|
||||||
|
<strong>{currentTab.title}:</strong> {currentTab.desc}
|
||||||
|
</div>
|
||||||
|
{currentTab.isSecret && (
|
||||||
|
<div className="alert-key-security">
|
||||||
|
<ShieldAlert size={16} />
|
||||||
|
<span>Atenção: A chave privada não deve ser compartilhada publicamente.</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bloco de Código com o Conteúdo */}
|
||||||
|
<div className="code-block-wrapper">
|
||||||
|
<pre className="code-pre">
|
||||||
|
<code>{currentTab.content || '// Conteúdo vazio ou não gerado'}</code>
|
||||||
|
</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Lock, Eye, EyeOff, KeyRound } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function PasswordInput({ password, onChange, onSubmit, disabled }) {
|
||||||
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
|
|
||||||
|
const handleKeyDown = (e) => {
|
||||||
|
if (e.key === 'Enter' && onSubmit) {
|
||||||
|
e.preventDefault();
|
||||||
|
onSubmit();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="password-section">
|
||||||
|
<label className="password-label" htmlFor="cert-password">
|
||||||
|
<KeyRound size={16} />
|
||||||
|
<span>Senha do Certificado (.pfx)</span>
|
||||||
|
</label>
|
||||||
|
<div className="password-input-wrapper">
|
||||||
|
<input
|
||||||
|
id="cert-password"
|
||||||
|
type={showPassword ? 'text' : 'password'}
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder="Digite a senha do certificado PFX..."
|
||||||
|
className="password-input"
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="password-toggle-btn"
|
||||||
|
onClick={() => setShowPassword(!showPassword)}
|
||||||
|
title={showPassword ? 'Ocultar senha' : 'Ver senha'}
|
||||||
|
tabIndex={-1}
|
||||||
|
>
|
||||||
|
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="password-hint">
|
||||||
|
Caso o certificado não possua senha, deixe este campo em branco.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Lock, Cpu, Globe } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function SecurityBadge() {
|
||||||
|
return (
|
||||||
|
<div className="security-banner">
|
||||||
|
<div className="security-badge">
|
||||||
|
<Lock size={16} />
|
||||||
|
<span>100% Client-Side & Seguro</span>
|
||||||
|
</div>
|
||||||
|
<p className="security-text">
|
||||||
|
Todo o processamento criptográfico ocorre localmente no seu próprio navegador através do motor Web Crypto.
|
||||||
|
Seu arquivo <strong>.pfx</strong> e sua senha <strong>nunca saem do seu computador</strong> nem são enviados para servidores externos.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import React, { useRef, useState } from 'react';
|
||||||
|
import { UploadCloud, FileCheck, X, AlertCircle } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function UploadZone({ file, onFileSelected, onFileCleared }) {
|
||||||
|
const [isDragging, setIsDragging] = useState(false);
|
||||||
|
const fileInputRef = useRef(null);
|
||||||
|
|
||||||
|
const handleDragOver = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragging(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDragLeave = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragging(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDrop = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setIsDragging(false);
|
||||||
|
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||||||
|
validateAndSetFile(e.dataTransfer.files[0]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleInputChange = (e) => {
|
||||||
|
if (e.target.files && e.target.files.length > 0) {
|
||||||
|
validateAndSetFile(e.target.files[0]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateAndSetFile = (selectedFile) => {
|
||||||
|
const ext = selectedFile.name.split('.').pop().toLowerCase();
|
||||||
|
if (ext === 'pfx' || ext === 'p12') {
|
||||||
|
onFileSelected(selectedFile);
|
||||||
|
} else {
|
||||||
|
alert('Por favor, selecione um arquivo de certificado com extensão .pfx ou .p12');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatFileSize = (bytes) => {
|
||||||
|
if (bytes < 1024) return bytes + ' bytes';
|
||||||
|
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
|
||||||
|
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="upload-section">
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
ref={fileInputRef}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
accept=".pfx,.p12,application/x-pkcs12"
|
||||||
|
style={{ display: 'none' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{!file ? (
|
||||||
|
<div
|
||||||
|
className={`dropzone ${isDragging ? 'dropzone-active' : ''}`}
|
||||||
|
onDragOver={handleDragOver}
|
||||||
|
onDragLeave={handleDragLeave}
|
||||||
|
onDrop={handleDrop}
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
>
|
||||||
|
<div className="dropzone-icon">
|
||||||
|
<UploadCloud size={48} />
|
||||||
|
</div>
|
||||||
|
<h3 className="dropzone-title">Arraste seu arquivo .pfx aqui ou clique para selecionar</h3>
|
||||||
|
<p className="dropzone-subtitle">Suporta arquivos PKCS#12 (.pfx, .p12)</p>
|
||||||
|
<button type="button" className="btn-select-file">
|
||||||
|
Selecionar Arquivo .PFX
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="file-card">
|
||||||
|
<div className="file-info-left">
|
||||||
|
<div className="file-icon-box">
|
||||||
|
<FileCheck size={28} className="file-icon-check" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="file-name">{file.name}</div>
|
||||||
|
<div className="file-meta">
|
||||||
|
<span className="file-badge">PFX / PKCS#12</span>
|
||||||
|
<span className="file-size">{formatFileSize(file.size)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-remove-file"
|
||||||
|
onClick={onFileCleared}
|
||||||
|
title="Remover arquivo selecionado"
|
||||||
|
>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,566 @@
|
|||||||
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
|
import {
|
||||||
|
Server,
|
||||||
|
Plus,
|
||||||
|
Settings,
|
||||||
|
Play,
|
||||||
|
List,
|
||||||
|
Trash2,
|
||||||
|
Search,
|
||||||
|
Smartphone,
|
||||||
|
Globe,
|
||||||
|
Activity,
|
||||||
|
MessageSquare,
|
||||||
|
AlertCircle,
|
||||||
|
CheckCircle2,
|
||||||
|
Info,
|
||||||
|
Edit2
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { getStoredServers, saveServers } from '../../utils/appWppStorage';
|
||||||
|
import {
|
||||||
|
startSession,
|
||||||
|
closeSession,
|
||||||
|
logoutSession,
|
||||||
|
checkSessionStatus,
|
||||||
|
clearSessionData,
|
||||||
|
generateToken,
|
||||||
|
ensureQRPrefix
|
||||||
|
} from '../../utils/wppConnectApi';
|
||||||
|
import WppSessionCard from './WppSessionCard';
|
||||||
|
import ModalServer from './ModalServer';
|
||||||
|
import ModalSession from './ModalSession';
|
||||||
|
import ModalQRCode from './ModalQRCode';
|
||||||
|
import ModalListSessions from './ModalListSessions';
|
||||||
|
import ModalSettings from './ModalSettings';
|
||||||
|
import ModalConfirm from './ModalConfirm';
|
||||||
|
|
||||||
|
export default function AppWPP() {
|
||||||
|
const [servers, setServers] = useState([]);
|
||||||
|
const [activeServerId, setActiveServerId] = useState(null);
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [toasts, setToasts] = useState([]);
|
||||||
|
|
||||||
|
// Modals state
|
||||||
|
const [isServerModalOpen, setIsServerModalOpen] = useState(false);
|
||||||
|
const [serverToEdit, setServerToEdit] = useState(null);
|
||||||
|
|
||||||
|
const [isSessionModalOpen, setIsSessionModalOpen] = useState(false);
|
||||||
|
const [sessionToEdit, setSessionToEdit] = useState(null);
|
||||||
|
|
||||||
|
const [isQRModalOpen, setIsQRModalOpen] = useState(false);
|
||||||
|
const [activeQRSession, setActiveQRSession] = useState(null);
|
||||||
|
|
||||||
|
const [isListSessionsOpen, setIsListSessionsOpen] = useState(false);
|
||||||
|
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
||||||
|
|
||||||
|
// Styled Confirm Modal state
|
||||||
|
const [confirmModal, setConfirmModal] = useState({
|
||||||
|
isOpen: false,
|
||||||
|
title: '',
|
||||||
|
message: '',
|
||||||
|
description: '',
|
||||||
|
confirmText: 'Confirmar',
|
||||||
|
type: 'warning',
|
||||||
|
onConfirm: () => {}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Carrega servidores armazenados na montagem
|
||||||
|
useEffect(() => {
|
||||||
|
const list = getStoredServers();
|
||||||
|
setServers(list);
|
||||||
|
if (list.length > 0) {
|
||||||
|
setActiveServerId(list[0].id);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Salva no localStorage sempre que `servers` mudar
|
||||||
|
const updateServersState = (updatedList) => {
|
||||||
|
setServers(updatedList);
|
||||||
|
saveServers(updatedList);
|
||||||
|
};
|
||||||
|
|
||||||
|
const showToast = (message, type = 'info') => {
|
||||||
|
const id = Date.now().toString() + Math.random().toString();
|
||||||
|
setToasts((prev) => [...prev, { id, message, type }]);
|
||||||
|
setTimeout(() => {
|
||||||
|
setToasts((prev) => prev.filter((t) => t.id !== id));
|
||||||
|
}, 3500);
|
||||||
|
};
|
||||||
|
|
||||||
|
const activeServer = servers.find((s) => s.id === activeServerId) || null;
|
||||||
|
|
||||||
|
// Servidor CRUD
|
||||||
|
const handleSaveServer = (serverData) => {
|
||||||
|
let updated;
|
||||||
|
const exists = servers.some((s) => s.id === serverData.id);
|
||||||
|
if (exists) {
|
||||||
|
updated = servers.map((s) => (s.id === serverData.id ? { ...s, ...serverData } : s));
|
||||||
|
showToast(`Servidor "${serverData.name}" atualizado!`, 'success');
|
||||||
|
} else {
|
||||||
|
updated = [...servers, serverData];
|
||||||
|
setActiveServerId(serverData.id);
|
||||||
|
showToast(`Servidor "${serverData.name}" adicionado com sucesso!`, 'success');
|
||||||
|
}
|
||||||
|
updateServersState(updated);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveServer = () => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
setConfirmModal({
|
||||||
|
isOpen: true,
|
||||||
|
title: 'Remover Servidor',
|
||||||
|
message: `Tem certeza que deseja remover o servidor "${activeServer.name}"?`,
|
||||||
|
description: 'Todas as sessões cadastradas para este servidor deixarão de ser exibidas na listagem.',
|
||||||
|
confirmText: 'Remover Servidor',
|
||||||
|
type: 'danger',
|
||||||
|
onConfirm: () => {
|
||||||
|
const updated = servers.filter((s) => s.id !== activeServer.id);
|
||||||
|
updateServersState(updated);
|
||||||
|
setActiveServerId(updated.length > 0 ? updated[0].id : null);
|
||||||
|
showToast(`Servidor "${activeServer.name}" removido.`, 'info');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Sessão CRUD
|
||||||
|
const handleSaveSession = async (sessionData, originalName) => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
|
||||||
|
let updatedSessions = [...(activeServer.sessions || [])];
|
||||||
|
if (originalName) {
|
||||||
|
updatedSessions = updatedSessions.map((s) => (s.name === originalName ? sessionData : s));
|
||||||
|
showToast(`Sessão "${sessionData.name}" atualizada!`, 'success');
|
||||||
|
} else {
|
||||||
|
if (updatedSessions.some((s) => s.name === sessionData.name)) {
|
||||||
|
showToast('Já existe uma sessão com este nome.', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updatedSessions.push(sessionData);
|
||||||
|
showToast(`Sessão "${sessionData.name}" criada!`, 'success');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedServer = { ...activeServer, sessions: updatedSessions };
|
||||||
|
const updatedServers = servers.map((s) => (s.id === activeServer.id ? updatedServer : s));
|
||||||
|
updateServersState(updatedServers);
|
||||||
|
|
||||||
|
// Se for nova sessão, tenta gerar token e iniciar
|
||||||
|
if (!originalName) {
|
||||||
|
try {
|
||||||
|
const token = await generateToken(activeServer, sessionData.name);
|
||||||
|
if (token) {
|
||||||
|
sessionData.token = token;
|
||||||
|
updateServersState(
|
||||||
|
servers.map((s) =>
|
||||||
|
s.id === activeServer.id
|
||||||
|
? { ...s, sessions: updatedSessions.map((x) => (x.name === sessionData.name ? { ...x, token } : x)) }
|
||||||
|
: s
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
handleStartSession(sessionData.name, true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveSession = (sessionName) => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
setConfirmModal({
|
||||||
|
isOpen: true,
|
||||||
|
title: 'Excluir Sessão',
|
||||||
|
message: `Deseja realmente excluir a sessão "${sessionName}"?`,
|
||||||
|
description: 'Esta sessão será removida do gerenciador para este servidor.',
|
||||||
|
confirmText: 'Excluir Sessão',
|
||||||
|
type: 'danger',
|
||||||
|
onConfirm: () => {
|
||||||
|
const updatedSessions = activeServer.sessions.filter((s) => s.name !== sessionName);
|
||||||
|
const updatedServers = servers.map((s) =>
|
||||||
|
s.id === activeServer.id ? { ...s, sessions: updatedSessions } : s
|
||||||
|
);
|
||||||
|
updateServersState(updatedServers);
|
||||||
|
showToast(`Sessão "${sessionName}" removida.`, 'info');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Ações de Sessão
|
||||||
|
const handleStartSession = async (sessionName, openQR = true) => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
|
||||||
|
// Atualiza estado local para connecting
|
||||||
|
updateSessionProperty(sessionName, { status: 'connecting' });
|
||||||
|
|
||||||
|
if (openQR) {
|
||||||
|
setActiveQRSession(sessionName);
|
||||||
|
setIsQRModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await startSession(activeServer, sessionName);
|
||||||
|
if ((data.status || '').toLowerCase() === 'qrcode' && (data.qrcode || data.urlcode)) {
|
||||||
|
const qr = ensureQRPrefix(data.qrcode || data.urlcode);
|
||||||
|
updateSessionProperty(sessionName, { qrCode: qr, status: 'qr' });
|
||||||
|
showToast(`Escaneie o QR Code para "${sessionName}".`, 'warning');
|
||||||
|
} else if (data.status === 'connected') {
|
||||||
|
updateSessionProperty(sessionName, { status: 'connected', connectedAt: new Date().toLocaleString('pt-BR') });
|
||||||
|
showToast(`Sessão "${sessionName}" conectada com sucesso!`, 'success');
|
||||||
|
} else {
|
||||||
|
updateSessionProperty(sessionName, { status: 'qr' });
|
||||||
|
showToast(`Aguardando QR Code para "${sessionName}".`, 'warning');
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Start session error:', err);
|
||||||
|
updateSessionProperty(sessionName, { status: 'qr' });
|
||||||
|
showToast(`Aguardando leitura do QR Code para "${sessionName}".`, 'warning');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCloseSession = async (sessionName) => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
try {
|
||||||
|
await closeSession(activeServer, sessionName);
|
||||||
|
updateSessionProperty(sessionName, { status: 'disconnected' });
|
||||||
|
showToast(`Sessão "${sessionName}" fechada.`, 'success');
|
||||||
|
} catch (err) {
|
||||||
|
showToast(`Erro ao fechar sessão: ${err.message}`, 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLogoutSession = async (sessionName) => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
try {
|
||||||
|
await logoutSession(activeServer, sessionName);
|
||||||
|
updateSessionProperty(sessionName, { status: 'disconnected' });
|
||||||
|
showToast(`Sessão "${sessionName}" desconectada.`, 'success');
|
||||||
|
} catch (err) {
|
||||||
|
showToast(`Erro ao desconectar: ${err.message}`, 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCheckStatus = async (sessionName) => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
try {
|
||||||
|
const status = await checkSessionStatus(activeServer, sessionName);
|
||||||
|
const isConnected = status === true || status === 'connected';
|
||||||
|
const newStatus = isConnected ? 'connected' : 'disconnected';
|
||||||
|
updateSessionProperty(sessionName, {
|
||||||
|
status: newStatus,
|
||||||
|
connectedAt: isConnected ? new Date().toLocaleString('pt-BR') : undefined
|
||||||
|
});
|
||||||
|
showToast(`Status de "${sessionName}": ${newStatus}`, isConnected ? 'success' : 'warning');
|
||||||
|
} catch (err) {
|
||||||
|
showToast(`Erro ao verificar status: ${err.message}`, 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClearSession = (sessionName) => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
setConfirmModal({
|
||||||
|
isOpen: true,
|
||||||
|
title: 'Limpar Dados da Sessão',
|
||||||
|
message: `Limpar arquivos e dados de "${sessionName}" no servidor?`,
|
||||||
|
description: 'Esta operação removerá os tokens e os arquivos em cache da sessão diretamente no servidor WPPConnect.',
|
||||||
|
confirmText: 'Limpar Arquivos e Dados',
|
||||||
|
type: 'warning',
|
||||||
|
onConfirm: async () => {
|
||||||
|
try {
|
||||||
|
await clearSessionData(activeServer, sessionName);
|
||||||
|
showToast(`Dados da sessão "${sessionName}" limpos com sucesso no servidor.`, 'success');
|
||||||
|
} catch (err) {
|
||||||
|
showToast(`Erro ao limpar dados: ${err.message}`, 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleStartAll = async () => {
|
||||||
|
if (!activeServer || !activeServer.sessions) return;
|
||||||
|
showToast('Iniciando todas as sessões...', 'info');
|
||||||
|
for (const session of activeServer.sessions) {
|
||||||
|
if (session.status !== 'connected') {
|
||||||
|
await handleStartSession(session.name, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
showToast('Processamento de inicialização concluído.', 'success');
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateSessionProperty = (sessionName, props) => {
|
||||||
|
if (!activeServer) return;
|
||||||
|
const updatedSessions = activeServer.sessions.map((s) =>
|
||||||
|
s.name === sessionName ? { ...s, ...props } : s
|
||||||
|
);
|
||||||
|
const updatedServers = servers.map((srv) =>
|
||||||
|
srv.id === activeServer.id ? { ...srv, sessions: updatedSessions } : srv
|
||||||
|
);
|
||||||
|
updateServersState(updatedServers);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Filtro de sessões
|
||||||
|
const filteredSessions = (activeServer?.sessions || []).filter((s) =>
|
||||||
|
s.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="wpp-app-container">
|
||||||
|
{/* Sidebar de Servidores */}
|
||||||
|
<aside className="wpp-sidebar">
|
||||||
|
<div className="wpp-sidebar-header">
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.625rem' }}>
|
||||||
|
<div className="wpp-logo-badge">
|
||||||
|
<MessageSquare size={20} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2 className="wpp-app-title">AppWPP</h2>
|
||||||
|
<p className="wpp-app-sub">Gerenciador WPPConnect</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-icon-wpp"
|
||||||
|
onClick={() => setIsSettingsOpen(true)}
|
||||||
|
title="Configurações e Backup"
|
||||||
|
>
|
||||||
|
<Settings size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="wpp-servers-section">
|
||||||
|
<div className="wpp-servers-header">
|
||||||
|
<span>SERVIDORES</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-icon-add-server"
|
||||||
|
onClick={() => {
|
||||||
|
setServerToEdit(null);
|
||||||
|
setIsServerModalOpen(true);
|
||||||
|
}}
|
||||||
|
title="Adicionar Servidor"
|
||||||
|
>
|
||||||
|
<Plus size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="wpp-servers-list">
|
||||||
|
{servers.map((s) => (
|
||||||
|
<div
|
||||||
|
key={s.id}
|
||||||
|
className={`wpp-server-item ${s.id === activeServerId ? 'wpp-server-active' : ''}`}
|
||||||
|
onClick={() => setActiveServerId(s.id)}
|
||||||
|
>
|
||||||
|
<span className={`wpp-server-dot ${s.online ? 'dot-online' : 'dot-offline'}`} />
|
||||||
|
<div className="wpp-server-info-col">
|
||||||
|
<span className="wpp-server-name-text">{s.name}</span>
|
||||||
|
<span className="wpp-server-url-text">{s.baseUrl}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-edit-server-mini"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setServerToEdit(s);
|
||||||
|
setIsServerModalOpen(true);
|
||||||
|
}}
|
||||||
|
title="Editar servidor"
|
||||||
|
>
|
||||||
|
<Edit2 size={13} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{servers.length === 0 && (
|
||||||
|
<div style={{ padding: '1.5rem 1rem', textAlign: 'center', color: '#64748b', fontSize: '0.8rem' }}>
|
||||||
|
Nenhum servidor cadastrado. Clique no "+" para adicionar.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="wpp-sidebar-footer">
|
||||||
|
<span>WPPConnect React v1.0.2</span>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* Conteúdo Principal do Servidor Selecionado */}
|
||||||
|
<main className="wpp-main-area">
|
||||||
|
{activeServer ? (
|
||||||
|
<div className="wpp-server-view">
|
||||||
|
{/* Topbar do Servidor */}
|
||||||
|
<div className="wpp-server-topbar">
|
||||||
|
<div className="wpp-server-title-box">
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
|
||||||
|
<h2 className="wpp-view-server-name">{activeServer.name}</h2>
|
||||||
|
<span className={`wpp-badge-status ${activeServer.online ? 'badge-online' : 'badge-offline'}`}>
|
||||||
|
{activeServer.online ? 'Online' : 'Offline'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className="wpp-view-server-url">{activeServer.baseUrl}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="wpp-server-actions-group">
|
||||||
|
<button type="button" className="btn-wpp-secondary-top" onClick={handleStartAll}>
|
||||||
|
<Play size={15} />
|
||||||
|
<span>Iniciar Todas</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button type="button" className="btn-wpp-secondary-top" onClick={() => setIsListSessionsOpen(true)}>
|
||||||
|
<List size={15} />
|
||||||
|
<span>Listar no Servidor</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button type="button" className="btn-wpp-danger-top" onClick={handleRemoveServer}>
|
||||||
|
<Trash2 size={15} />
|
||||||
|
<span>Remover Servidor</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Toolbar de Sessões (Busca e Nova Sessão) */}
|
||||||
|
<div className="wpp-sessions-toolbar">
|
||||||
|
<div className="wpp-search-box">
|
||||||
|
<Search size={16} className="text-muted" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Buscar sessão..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="wpp-search-input"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-new-session"
|
||||||
|
onClick={() => {
|
||||||
|
setSessionToEdit(null);
|
||||||
|
setIsSessionModalOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Plus size={16} />
|
||||||
|
<span>Nova Sessão</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Grid de Cards de Sessões */}
|
||||||
|
<div className="wpp-sessions-grid">
|
||||||
|
{filteredSessions.map((session) => (
|
||||||
|
<WppSessionCard
|
||||||
|
key={session.name}
|
||||||
|
session={session}
|
||||||
|
onStart={handleStartSession}
|
||||||
|
onCloseSession={handleCloseSession}
|
||||||
|
onLogout={handleLogoutSession}
|
||||||
|
onCheckStatus={handleCheckStatus}
|
||||||
|
onEdit={(s) => {
|
||||||
|
setSessionToEdit(s);
|
||||||
|
setIsSessionModalOpen(true);
|
||||||
|
}}
|
||||||
|
onClear={handleClearSession}
|
||||||
|
onRemove={handleRemoveSession}
|
||||||
|
onShowQR={(name) => {
|
||||||
|
setActiveQRSession(name);
|
||||||
|
setIsQRModalOpen(true);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{filteredSessions.length === 0 && (
|
||||||
|
<div className="wpp-empty-sessions">
|
||||||
|
<Smartphone size={48} className="text-muted" />
|
||||||
|
<h3>Nenhuma sessão encontrada</h3>
|
||||||
|
<p>
|
||||||
|
{searchQuery
|
||||||
|
? 'Nenhuma sessão corresponde à busca informada.'
|
||||||
|
: 'Clique em "+ Nova Sessão" acima para cadastrar sua primeira sessão do WhatsApp.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="wpp-empty-app">
|
||||||
|
<Smartphone size={64} className="text-emerald" />
|
||||||
|
<h2>Bem-vindo ao AppWPP</h2>
|
||||||
|
<p>Selecione ou adicione um servidor WPPConnect para gerenciar suas sessões do WhatsApp.</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-convert"
|
||||||
|
onClick={() => {
|
||||||
|
setServerToEdit(null);
|
||||||
|
setIsServerModalOpen(true);
|
||||||
|
}}
|
||||||
|
style={{ marginTop: '1rem', padding: '0.75rem 1.5rem' }}
|
||||||
|
>
|
||||||
|
Adicionar Servidor WPPConnect
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{/* Modals */}
|
||||||
|
<ModalServer
|
||||||
|
isOpen={isServerModalOpen}
|
||||||
|
onClose={() => setIsServerModalOpen(false)}
|
||||||
|
onSave={handleSaveServer}
|
||||||
|
serverToEdit={serverToEdit}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ModalSession
|
||||||
|
isOpen={isSessionModalOpen}
|
||||||
|
onClose={() => setIsSessionModalOpen(false)}
|
||||||
|
onSave={handleSaveSession}
|
||||||
|
sessionToEdit={sessionToEdit}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ModalQRCode
|
||||||
|
isOpen={isQRModalOpen}
|
||||||
|
onClose={() => setIsQRModalOpen(false)}
|
||||||
|
server={activeServer}
|
||||||
|
sessionName={activeQRSession}
|
||||||
|
onConnected={(name) => {
|
||||||
|
updateSessionProperty(name, { status: 'connected', connectedAt: new Date().toLocaleString('pt-BR') });
|
||||||
|
showToast(`Sessão "${name}" conectada com sucesso!`, 'success');
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ModalListSessions
|
||||||
|
isOpen={isListSessionsOpen}
|
||||||
|
onClose={() => setIsListSessionsOpen(false)}
|
||||||
|
server={activeServer}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<ModalSettings
|
||||||
|
isOpen={isSettingsOpen}
|
||||||
|
onClose={() => setIsSettingsOpen(false)}
|
||||||
|
servers={servers}
|
||||||
|
onImportServers={(newServers) => {
|
||||||
|
updateServersState(newServers);
|
||||||
|
if (newServers.length > 0) setActiveServerId(newServers[0].id);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Modal de Confirmação Estilizado */}
|
||||||
|
<ModalConfirm
|
||||||
|
isOpen={confirmModal.isOpen}
|
||||||
|
onClose={() => setConfirmModal((prev) => ({ ...prev, isOpen: false }))}
|
||||||
|
onConfirm={confirmModal.onConfirm}
|
||||||
|
title={confirmModal.title}
|
||||||
|
message={confirmModal.message}
|
||||||
|
description={confirmModal.description}
|
||||||
|
confirmText={confirmModal.confirmText}
|
||||||
|
type={confirmModal.type}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Toasts */}
|
||||||
|
<div className="wpp-toasts-container">
|
||||||
|
{toasts.map((t) => (
|
||||||
|
<div key={t.id} className={`wpp-toast toast-${t.type}`}>
|
||||||
|
{t.type === 'success' && <CheckCircle2 size={16} />}
|
||||||
|
{t.type === 'error' && <AlertCircle size={16} />}
|
||||||
|
{t.type === 'warning' && <AlertCircle size={16} />}
|
||||||
|
{t.type === 'info' && <Info size={16} />}
|
||||||
|
<span>{t.message}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { X, AlertTriangle, Trash2, ShieldAlert } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function ModalConfirm({
|
||||||
|
isOpen,
|
||||||
|
onClose,
|
||||||
|
onConfirm,
|
||||||
|
title = 'Confirmar Ação',
|
||||||
|
message,
|
||||||
|
description,
|
||||||
|
confirmText = 'Confirmar',
|
||||||
|
cancelText = 'Cancelar',
|
||||||
|
type = 'warning', // 'warning' | 'danger'
|
||||||
|
icon: CustomIcon
|
||||||
|
}) {
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const isDanger = type === 'danger';
|
||||||
|
const IconComponent = CustomIcon || (isDanger ? Trash2 : AlertTriangle);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div
|
||||||
|
className="modal-dialog modal-confirm-dialog"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
style={{ maxWidth: '460px' }}
|
||||||
|
>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div className="modal-title-box">
|
||||||
|
<div className={`modal-confirm-icon-box ${isDanger ? 'icon-box-danger' : 'icon-box-warning'}`}>
|
||||||
|
<IconComponent size={20} />
|
||||||
|
</div>
|
||||||
|
<h3 className="modal-title">{title}</h3>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="modal-close-btn" onClick={onClose} title="Fechar">
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-body" style={{ padding: '1.5rem' }}>
|
||||||
|
<p className="modal-confirm-message">{message}</p>
|
||||||
|
{description && (
|
||||||
|
<p className="modal-confirm-desc">{description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer" style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.75rem' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-modal-cancel"
|
||||||
|
onClick={onClose}
|
||||||
|
>
|
||||||
|
{cancelText}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`btn-modal-action-confirm ${isDanger ? 'btn-confirm-danger' : 'btn-confirm-warning'}`}
|
||||||
|
onClick={() => {
|
||||||
|
onConfirm();
|
||||||
|
onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<IconComponent size={16} />
|
||||||
|
<span>{confirmText}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { X, Server, Loader2, RefreshCw } from 'lucide-react';
|
||||||
|
import { listAllServerSessions } from '../../utils/wppConnectApi';
|
||||||
|
|
||||||
|
export default function ModalListSessions({ isOpen, onClose, server }) {
|
||||||
|
const [sessions, setSessions] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen && server) {
|
||||||
|
loadSessions();
|
||||||
|
}
|
||||||
|
}, [isOpen, server]);
|
||||||
|
|
||||||
|
const loadSessions = async () => {
|
||||||
|
if (!server) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
try {
|
||||||
|
const list = await listAllServerSessions(server);
|
||||||
|
setSessions(list);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err.message || 'Erro ao consultar sessões no servidor.');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal-dialog" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '580px' }}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div className="modal-title-box">
|
||||||
|
<Server size={20} className="text-emerald" />
|
||||||
|
<h3 className="modal-title">Sessões no Servidor ({server?.name})</h3>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="modal-close-btn" onClick={onClose}>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-body" style={{ minHeight: '200px', maxHeight: '60vh', overflowY: 'auto' }}>
|
||||||
|
{loading ? (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '3rem 0', gap: '0.75rem' }}>
|
||||||
|
<Loader2 size={32} className="animate-spin text-emerald" />
|
||||||
|
<p style={{ color: '#94a3b8', fontSize: '0.85rem' }}>Consultando servidor WPPConnect...</p>
|
||||||
|
</div>
|
||||||
|
) : error ? (
|
||||||
|
<div className="alert-error-box">
|
||||||
|
<span>{error}</span>
|
||||||
|
</div>
|
||||||
|
) : sessions.length === 0 ? (
|
||||||
|
<p style={{ textAlign: 'center', color: '#94a3b8', padding: '2rem 0' }}>
|
||||||
|
Nenhuma sessão ativa encontrada diretamente neste servidor.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
|
||||||
|
{sessions.map((sessName, idx) => {
|
||||||
|
const localSession = server.sessions?.find(s => s.name === sessName);
|
||||||
|
const isConnected = localSession?.status === 'connected';
|
||||||
|
return (
|
||||||
|
<div key={idx} className="wpp-server-session-row">
|
||||||
|
<span style={{ fontWeight: 600, color: '#f8fafc', fontFamily: 'var(--font-mono)' }}>{sessName}</span>
|
||||||
|
<span className={`wpp-status-pill ${isConnected ? 'status-connected' : 'status-disconnected'}`}>
|
||||||
|
{isConnected ? 'Conectado' : 'Registrado'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer" style={{ justifyContent: 'space-between' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-reset"
|
||||||
|
onClick={loadSessions}
|
||||||
|
disabled={loading}
|
||||||
|
style={{ display: 'inline-flex', alignItems: 'center', gap: '0.375rem' }}
|
||||||
|
>
|
||||||
|
<RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
|
||||||
|
<span>Recarregar</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn-modal-close" onClick={onClose}>
|
||||||
|
Fechar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import React, { useEffect, useState } from 'react';
|
||||||
|
import { X, QrCode, RefreshCw, CheckCircle2, Loader2, Smartphone } from 'lucide-react';
|
||||||
|
import { fetchQRCode, checkSessionStatus, ensureQRPrefix } from '../../utils/wppConnectApi';
|
||||||
|
|
||||||
|
export default function ModalQRCode({ isOpen, onClose, server, sessionName, onConnected }) {
|
||||||
|
const [qrSrc, setQrSrc] = useState('');
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isConnected, setIsConnected] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen || !server || !sessionName) return;
|
||||||
|
|
||||||
|
setIsConnected(false);
|
||||||
|
const session = server.sessions?.find(s => s.name === sessionName);
|
||||||
|
if (session?.qrCode) {
|
||||||
|
setQrSrc(ensureQRPrefix(session.qrCode));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Carrega o QR Code inicial
|
||||||
|
loadQR();
|
||||||
|
|
||||||
|
// 1. Polling para atualizar o QR Code a cada 25s
|
||||||
|
const qrInterval = setInterval(() => {
|
||||||
|
loadQR();
|
||||||
|
}, 25000);
|
||||||
|
|
||||||
|
// 2. Polling rápido a cada 2.5s para checar se o usuário escaneou e conectou
|
||||||
|
const statusInterval = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const status = await checkSessionStatus(server, sessionName);
|
||||||
|
if (status === true || status === 'connected') {
|
||||||
|
setIsConnected(true);
|
||||||
|
clearInterval(statusInterval);
|
||||||
|
clearInterval(qrInterval);
|
||||||
|
if (onConnected) onConnected(sessionName);
|
||||||
|
setTimeout(() => {
|
||||||
|
onClose();
|
||||||
|
}, 1800);
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
}, 2500);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearInterval(qrInterval);
|
||||||
|
clearInterval(statusInterval);
|
||||||
|
};
|
||||||
|
}, [isOpen, server, sessionName]);
|
||||||
|
|
||||||
|
const loadQR = async () => {
|
||||||
|
if (!server || !sessionName) return;
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const qr = await fetchQRCode(server, sessionName);
|
||||||
|
if (qr) setQrSrc(qr);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('Erro ao carregar QR Code:', e);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal-dialog" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '420px', textAlign: 'center' }}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div className="modal-title-box">
|
||||||
|
<QrCode size={20} className="text-emerald" />
|
||||||
|
<h3 className="modal-title">QR Code: {sessionName}</h3>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="modal-close-btn" onClick={onClose}>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-body" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '2rem 1.5rem' }}>
|
||||||
|
{isConnected ? (
|
||||||
|
<div style={{ padding: '2rem 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '0.75rem' }}>
|
||||||
|
<CheckCircle2 size={56} className="text-emerald" />
|
||||||
|
<h4 style={{ color: '#34d399', fontSize: '1.2rem', fontWeight: 600 }}>WhatsApp Conectado!</h4>
|
||||||
|
<p style={{ color: '#94a3b8', fontSize: '0.85rem' }}>A sessão foi autenticada com sucesso.</p>
|
||||||
|
</div>
|
||||||
|
) : qrSrc ? (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
|
||||||
|
<div className="wpp-qr-box">
|
||||||
|
<img src={qrSrc} alt="QR Code WhatsApp" style={{ width: '240px', height: '240px', borderRadius: '8px', display: 'block' }} />
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'inline-flex', alignItems: 'center', gap: '0.5rem', marginTop: '1rem', color: '#94a3b8', fontSize: '0.85rem' }}>
|
||||||
|
<Smartphone size={16} />
|
||||||
|
<span>Abra o WhatsApp > Dispositivos Conectados > Conectar</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ padding: '2.5rem 1rem', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
|
||||||
|
<Loader2 size={36} className="animate-spin text-emerald" />
|
||||||
|
<p style={{ color: '#94a3b8', fontSize: '0.9rem' }}>Aguardando o servidor gerar o QR Code...</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer" style={{ justifyContent: 'space-between' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-reset"
|
||||||
|
onClick={loadQR}
|
||||||
|
disabled={isLoading || isConnected}
|
||||||
|
style={{ display: 'inline-flex', alignItems: 'center', gap: '0.375rem', fontSize: '0.8rem' }}
|
||||||
|
>
|
||||||
|
<RefreshCw size={14} className={isLoading ? 'animate-spin' : ''} />
|
||||||
|
<span>Atualizar QR Code</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn-modal-close" onClick={onClose}>
|
||||||
|
Fechar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { X, Server, Eye, EyeOff, Check, AlertCircle, Loader2 } from 'lucide-react';
|
||||||
|
import { testServerConnection, normalizeUrl } from '../../utils/wppConnectApi';
|
||||||
|
|
||||||
|
export default function ModalServer({ isOpen, onClose, onSave, serverToEdit }) {
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [baseUrl, setBaseUrl] = useState('');
|
||||||
|
const [secretKey, setSecretKey] = useState('');
|
||||||
|
const [showSecret, setShowSecret] = useState(false);
|
||||||
|
const [testStatus, setTestStatus] = useState(null); // { loading, success, message, error }
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (serverToEdit) {
|
||||||
|
setName(serverToEdit.name || '');
|
||||||
|
setBaseUrl(serverToEdit.baseUrl || '');
|
||||||
|
setSecretKey(serverToEdit.secretKey || '');
|
||||||
|
} else {
|
||||||
|
setName('');
|
||||||
|
setBaseUrl('');
|
||||||
|
setSecretKey('');
|
||||||
|
}
|
||||||
|
setTestStatus(null);
|
||||||
|
}, [serverToEdit, isOpen]);
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const handleTest = async () => {
|
||||||
|
if (!baseUrl || !secretKey) {
|
||||||
|
setTestStatus({ error: 'Preencha a URL e a Secret Key antes de testar.' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setTestStatus({ loading: true });
|
||||||
|
try {
|
||||||
|
const res = await testServerConnection(baseUrl, secretKey);
|
||||||
|
if (res.ok) {
|
||||||
|
setTestStatus({ success: true, message: res.message });
|
||||||
|
} else {
|
||||||
|
setTestStatus({ error: res.error });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setTestStatus({ error: err.message || 'Falha na conexão com o servidor' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!name.trim() || !baseUrl.trim() || !secretKey.trim()) {
|
||||||
|
alert('Por favor, preencha todos os campos obrigatórios.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSave({
|
||||||
|
id: serverToEdit ? serverToEdit.id : Date.now().toString(),
|
||||||
|
name: name.trim(),
|
||||||
|
baseUrl: normalizeUrl(baseUrl),
|
||||||
|
secretKey: secretKey.trim(),
|
||||||
|
online: serverToEdit ? serverToEdit.online : false,
|
||||||
|
sessions: serverToEdit ? serverToEdit.sessions : []
|
||||||
|
});
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal-dialog" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '520px' }}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div className="modal-title-box">
|
||||||
|
<Server size={20} className="text-emerald" />
|
||||||
|
<h3 className="modal-title">{serverToEdit ? 'Editar Servidor' : 'Adicionar Servidor WPPConnect'}</h3>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="modal-close-btn" onClick={onClose}>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSave}>
|
||||||
|
<div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">Nome do Servidor</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="password-input"
|
||||||
|
placeholder="Ex: C2 Sistemas"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">URL Base</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="password-input"
|
||||||
|
placeholder="http://localhost:21465 ou http://meuservidor.com:22700"
|
||||||
|
value={baseUrl}
|
||||||
|
onChange={(e) => setBaseUrl(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">Secret Key / Token</label>
|
||||||
|
<div className="password-input-wrapper">
|
||||||
|
<input
|
||||||
|
type={showSecret ? 'text' : 'password'}
|
||||||
|
className="password-input"
|
||||||
|
placeholder="Secret Key configurada no WPPConnect"
|
||||||
|
value={secretKey}
|
||||||
|
onChange={(e) => setSecretKey(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="password-toggle-btn"
|
||||||
|
onClick={() => setShowSecret(!showSecret)}
|
||||||
|
>
|
||||||
|
{showSecret ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{testStatus && (
|
||||||
|
<div className={`wpp-test-result ${testStatus.error ? 'wpp-test-error' : testStatus.success ? 'wpp-test-success' : 'wpp-test-loading'}`}>
|
||||||
|
{testStatus.loading && <Loader2 size={16} className="animate-spin" />}
|
||||||
|
{testStatus.success && <Check size={16} />}
|
||||||
|
{testStatus.error && <AlertCircle size={16} />}
|
||||||
|
<span>{testStatus.loading ? 'Testando conexão...' : testStatus.message || testStatus.error}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer" style={{ justifyContent: 'space-between' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-reset"
|
||||||
|
onClick={handleTest}
|
||||||
|
disabled={testStatus?.loading}
|
||||||
|
>
|
||||||
|
Testar Conexão
|
||||||
|
</button>
|
||||||
|
<div style={{ display: 'flex', gap: '0.5rem' }}>
|
||||||
|
<button type="button" className="btn-modal-close" onClick={onClose}>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="btn-convert" style={{ padding: '0.55rem 1.25rem' }}>
|
||||||
|
{serverToEdit ? 'Atualizar' : 'Salvar Servidor'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { X, MessageSquare, Key, Globe, Shield } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function ModalSession({ isOpen, onClose, onSave, sessionToEdit }) {
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [token, setToken] = useState('');
|
||||||
|
const [webhook, setWebhook] = useState('');
|
||||||
|
const [waitQrCode, setWaitQrCode] = useState(false);
|
||||||
|
const [proxyUrl, setProxyUrl] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (sessionToEdit) {
|
||||||
|
setName(sessionToEdit.name || '');
|
||||||
|
setToken(sessionToEdit.token || '');
|
||||||
|
setWebhook(sessionToEdit.webhook || '');
|
||||||
|
setWaitQrCode(sessionToEdit.waitQrCode || false);
|
||||||
|
setProxyUrl(sessionToEdit.proxy?.url || '');
|
||||||
|
} else {
|
||||||
|
setName('');
|
||||||
|
setToken('');
|
||||||
|
setWebhook('');
|
||||||
|
setWaitQrCode(false);
|
||||||
|
setProxyUrl('');
|
||||||
|
}
|
||||||
|
}, [sessionToEdit, isOpen]);
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const handleSubmit = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!name.trim()) {
|
||||||
|
alert('Informe o nome da sessão.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
onSave({
|
||||||
|
name: name.trim(),
|
||||||
|
token: token.trim(),
|
||||||
|
webhook: webhook.trim(),
|
||||||
|
waitQrCode,
|
||||||
|
proxy: proxyUrl.trim() ? { url: proxyUrl.trim() } : null,
|
||||||
|
status: sessionToEdit ? sessionToEdit.status : 'disconnected',
|
||||||
|
connectedAt: sessionToEdit ? sessionToEdit.connectedAt : '',
|
||||||
|
qrCode: sessionToEdit ? sessionToEdit.qrCode : ''
|
||||||
|
}, sessionToEdit?.name);
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal-dialog" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '520px' }}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div className="modal-title-box">
|
||||||
|
<MessageSquare size={20} className="text-emerald" />
|
||||||
|
<h3 className="modal-title">{sessionToEdit ? 'Editar Sessão' : 'Nova Sessão WhatsApp'}</h3>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="modal-close-btn" onClick={onClose}>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">Nome da Sessão (Identificador)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="password-input"
|
||||||
|
placeholder="Ex: atendimento_01, admin, clinica"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">Token de Autenticação (Opcional)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="password-input"
|
||||||
|
placeholder="Token JWT gerado pelo servidor"
|
||||||
|
value={token}
|
||||||
|
onChange={(e) => setToken(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">Webhook URL (Opcional)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="password-input"
|
||||||
|
placeholder="https://meusite.com/api/wpp-webhook"
|
||||||
|
value={webhook}
|
||||||
|
onChange={(e) => setWebhook(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group" style={{ display: 'flex', alignItems: 'center', gap: '0.625rem' }}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id="chk-wait-qr"
|
||||||
|
checked={waitQrCode}
|
||||||
|
onChange={(e) => setWaitQrCode(e.target.checked)}
|
||||||
|
style={{ width: '18px', height: '18px', accentColor: '#00e676' }}
|
||||||
|
/>
|
||||||
|
<label htmlFor="chk-wait-qr" style={{ fontSize: '0.875rem', color: '#cbd5e1', cursor: 'pointer' }}>
|
||||||
|
Aguardar leitura do QR Code na inicialização
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">Proxy URL (Opcional)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="password-input"
|
||||||
|
placeholder="http://proxy.exemplo.com:8080"
|
||||||
|
value={proxyUrl}
|
||||||
|
onChange={(e) => setProxyUrl(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer">
|
||||||
|
<button type="button" className="btn-modal-close" onClick={onClose}>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="btn-convert" style={{ padding: '0.55rem 1.25rem' }}>
|
||||||
|
{sessionToEdit ? 'Atualizar Sessão' : 'Criar Sessão'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
|
import { X, Settings, Download, Upload, Database, Check, AlertCircle } from 'lucide-react';
|
||||||
|
import { getSupabaseConfig, saveSupabaseConfig, exportAppWppBackup } from '../../utils/appWppStorage';
|
||||||
|
|
||||||
|
export default function ModalSettings({ isOpen, onClose, servers, onImportServers }) {
|
||||||
|
const [supabaseUrl, setSupabaseUrl] = useState('');
|
||||||
|
const [supabaseKey, setSupabaseKey] = useState('');
|
||||||
|
const [msg, setMsg] = useState(null);
|
||||||
|
const fileInputRef = useRef(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isOpen) {
|
||||||
|
const cfg = getSupabaseConfig();
|
||||||
|
setSupabaseUrl(cfg.supabaseUrl || '');
|
||||||
|
setSupabaseKey(cfg.supabaseAnonKey || '');
|
||||||
|
setMsg(null);
|
||||||
|
}
|
||||||
|
}, [isOpen]);
|
||||||
|
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
const handleSaveSupabase = (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
saveSupabaseConfig({ supabaseUrl: supabaseUrl.trim(), supabaseAnonKey: supabaseKey.trim() });
|
||||||
|
setMsg({ type: 'success', text: 'Configurações salvas localmente com sucesso!' });
|
||||||
|
setTimeout(() => setMsg(null), 3000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExportBackup = () => {
|
||||||
|
exportAppWppBackup(servers);
|
||||||
|
setMsg({ type: 'success', text: 'Backup exportado com sucesso!' });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImportFile = (e) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (event) => {
|
||||||
|
try {
|
||||||
|
const json = JSON.parse(event.target.result);
|
||||||
|
if (json && Array.isArray(json.servers)) {
|
||||||
|
onImportServers(json.servers);
|
||||||
|
setMsg({ type: 'success', text: `${json.servers.length} servidor(es) importado(s) com sucesso!` });
|
||||||
|
} else {
|
||||||
|
setMsg({ type: 'error', text: 'Formato inválido. O arquivo JSON deve conter um array "servers".' });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setMsg({ type: 'error', text: 'Erro ao processar arquivo JSON: ' + err.message });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsText(file);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal-dialog" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '540px' }}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<div className="modal-title-box">
|
||||||
|
<Settings size={20} className="text-emerald" />
|
||||||
|
<h3 className="modal-title">Configurações & Backup (AppWPP)</h3>
|
||||||
|
</div>
|
||||||
|
<button type="button" className="modal-close-btn" onClick={onClose}>
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
|
||||||
|
{msg && (
|
||||||
|
<div className={`wpp-test-result ${msg.type === 'success' ? 'wpp-test-success' : 'wpp-test-error'}`}>
|
||||||
|
{msg.type === 'success' ? <Check size={16} /> : <AlertCircle size={16} />}
|
||||||
|
<span>{msg.text}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Backup e Sincronização Local */}
|
||||||
|
<div className="wpp-settings-card">
|
||||||
|
<h4 style={{ color: '#f8fafc', fontSize: '0.95rem', marginBottom: '0.5rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||||
|
<Download size={16} className="text-cyan" />
|
||||||
|
<span>Backup e Importação (appwpp-data.json)</span>
|
||||||
|
</h4>
|
||||||
|
<p style={{ color: '#94a3b8', fontSize: '0.8rem', marginBottom: '1rem' }}>
|
||||||
|
Exporte seus servidores e sessões para transferir entre máquinas ou importe um arquivo existente.
|
||||||
|
</p>
|
||||||
|
<div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
|
||||||
|
<button type="button" className="btn-reset" onClick={handleExportBackup} style={{ display: 'inline-flex', alignItems: 'center', gap: '0.375rem' }}>
|
||||||
|
<Download size={15} />
|
||||||
|
<span>Exportar Backup (.json)</span>
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn-reset" onClick={() => fileInputRef.current?.click()} style={{ display: 'inline-flex', alignItems: 'center', gap: '0.375rem' }}>
|
||||||
|
<Upload size={15} />
|
||||||
|
<span>Importar Backup (.json)</span>
|
||||||
|
</button>
|
||||||
|
<input type="file" ref={fileInputRef} onChange={handleImportFile} accept=".json" style={{ display: 'none' }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Supabase Config */}
|
||||||
|
<form onSubmit={handleSaveSupabase} className="wpp-settings-card">
|
||||||
|
<h4 style={{ color: '#f8fafc', fontSize: '0.95rem', marginBottom: '0.5rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
|
||||||
|
<Database size={16} className="text-emerald" />
|
||||||
|
<span>Conexão Supabase (Opcional)</span>
|
||||||
|
</h4>
|
||||||
|
<p style={{ color: '#94a3b8', fontSize: '0.8rem', marginBottom: '1rem' }}>
|
||||||
|
Configure a sincronização com banco de dados Supabase na nuvem.
|
||||||
|
</p>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">Supabase URL</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="password-input"
|
||||||
|
placeholder="https://seuprojeto.supabase.co"
|
||||||
|
value={supabaseUrl}
|
||||||
|
onChange={(e) => setSupabaseUrl(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="form-group">
|
||||||
|
<label className="wpp-form-label">Anon Key / API Key</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
className="password-input"
|
||||||
|
placeholder="eyJhbGciOi..."
|
||||||
|
value={supabaseKey}
|
||||||
|
onChange={(e) => setSupabaseKey(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button type="submit" className="btn-convert" style={{ alignSelf: 'flex-start', padding: '0.5rem 1rem', fontSize: '0.85rem' }}>
|
||||||
|
Salvar Configurações
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="modal-footer">
|
||||||
|
<button type="button" className="btn-modal-close" onClick={onClose}>
|
||||||
|
Fechar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import {
|
||||||
|
Play,
|
||||||
|
X,
|
||||||
|
LogOut,
|
||||||
|
Activity,
|
||||||
|
Edit3,
|
||||||
|
Trash2,
|
||||||
|
QrCode,
|
||||||
|
Clock,
|
||||||
|
Key,
|
||||||
|
Copy,
|
||||||
|
Check
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
export default function WppSessionCard({
|
||||||
|
session,
|
||||||
|
onStart,
|
||||||
|
onCloseSession,
|
||||||
|
onLogout,
|
||||||
|
onCheckStatus,
|
||||||
|
onEdit,
|
||||||
|
onClear,
|
||||||
|
onRemove,
|
||||||
|
onShowQR
|
||||||
|
}) {
|
||||||
|
const [copiedToken, setCopiedToken] = React.useState(false);
|
||||||
|
|
||||||
|
const getStatusBadge = () => {
|
||||||
|
switch (session.status) {
|
||||||
|
case 'connected':
|
||||||
|
return <span className="wpp-status-pill status-connected">Conectado</span>;
|
||||||
|
case 'qr':
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="wpp-status-pill status-qr clickable"
|
||||||
|
onClick={() => onShowQR(session.name)}
|
||||||
|
title="Clique para ver o QR Code"
|
||||||
|
>
|
||||||
|
<QrCode size={12} />
|
||||||
|
<span>Aguardando QR</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
case 'connecting':
|
||||||
|
return <span className="wpp-status-pill status-connecting">Conectando...</span>;
|
||||||
|
default:
|
||||||
|
return <span className="wpp-status-pill status-disconnected">Desconectado</span>;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCopyToken = () => {
|
||||||
|
if (!session.token) return;
|
||||||
|
navigator.clipboard.writeText(session.token);
|
||||||
|
setCopiedToken(true);
|
||||||
|
setTimeout(() => setCopiedToken(false), 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="wpp-session-card">
|
||||||
|
<div className="wpp-session-card-header">
|
||||||
|
<span className="wpp-session-name" title={session.name}>{session.name}</span>
|
||||||
|
{getStatusBadge()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="wpp-session-card-body">
|
||||||
|
{session.connectedAt && (
|
||||||
|
<div className="wpp-session-meta-item">
|
||||||
|
<Clock size={13} />
|
||||||
|
<span>{session.connectedAt}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{session.token && (
|
||||||
|
<div className="wpp-session-token-box" onClick={handleCopyToken} title="Clique para copiar o token">
|
||||||
|
<Key size={12} />
|
||||||
|
<span className="wpp-session-token-text">{session.token.slice(0, 18)}...</span>
|
||||||
|
{copiedToken ? <Check size={12} className="text-emerald" /> : <Copy size={12} />}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="wpp-session-card-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-wpp-action btn-wpp-primary"
|
||||||
|
onClick={() => onStart(session.name)}
|
||||||
|
title="Iniciar sessão e abrir QR Code"
|
||||||
|
>
|
||||||
|
<Play size={13} />
|
||||||
|
<span>Iniciar</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-wpp-action btn-wpp-secondary"
|
||||||
|
onClick={() => onCloseSession(session.name)}
|
||||||
|
title="Fechar sessão"
|
||||||
|
>
|
||||||
|
<X size={13} />
|
||||||
|
<span>Fechar</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-wpp-action btn-wpp-secondary"
|
||||||
|
onClick={() => onLogout(session.name)}
|
||||||
|
title="Desconectar sessão do WhatsApp"
|
||||||
|
>
|
||||||
|
<LogOut size={13} />
|
||||||
|
<span>Sair</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-wpp-action btn-wpp-secondary"
|
||||||
|
onClick={() => onCheckStatus(session.name)}
|
||||||
|
title="Consultar status no servidor"
|
||||||
|
>
|
||||||
|
<Activity size={13} />
|
||||||
|
<span>Status</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-wpp-action btn-wpp-secondary"
|
||||||
|
onClick={() => onEdit(session)}
|
||||||
|
title="Editar dados da sessão"
|
||||||
|
>
|
||||||
|
<Edit3 size={13} />
|
||||||
|
<span>Editar</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-wpp-action btn-wpp-warning"
|
||||||
|
onClick={() => onClear(session.name)}
|
||||||
|
title="Limpar arquivos da sessão no servidor"
|
||||||
|
>
|
||||||
|
<Trash2 size={13} />
|
||||||
|
<span>Limpar</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-wpp-action btn-wpp-danger"
|
||||||
|
onClick={() => onRemove(session.name)}
|
||||||
|
title="Excluir sessão do gerenciador"
|
||||||
|
>
|
||||||
|
<Trash2 size={13} />
|
||||||
|
<span>Excluir</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+2150
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import './index.css'
|
||||||
|
import App from './App.jsx'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import initialData from './initialWppData.json';
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'appwpp_servers_data_v1';
|
||||||
|
const SUPABASE_KEY = 'appwpp_supabase_config_v1';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Carrega a lista de servidores do localStorage ou usa o arquivo inicial
|
||||||
|
*/
|
||||||
|
export function getStoredServers() {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(STORAGE_KEY);
|
||||||
|
if (raw) {
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
if (parsed && Array.isArray(parsed.servers)) {
|
||||||
|
return parsed.servers;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('Erro ao carregar do localStorage:', e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback para dados iniciais existentes em D:\Flavio\Projetos\AppWPP
|
||||||
|
if (initialData && Array.isArray(initialData.servers)) {
|
||||||
|
saveServers(initialData.servers);
|
||||||
|
return initialData.servers;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Salva a lista de servidores no localStorage
|
||||||
|
*/
|
||||||
|
export function saveServers(servers) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(STORAGE_KEY, JSON.stringify({ servers }, null, 2));
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Erro ao salvar servidores no localStorage:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuração Supabase
|
||||||
|
*/
|
||||||
|
export function getSupabaseConfig() {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(SUPABASE_KEY);
|
||||||
|
return raw ? JSON.parse(raw) : { supabaseUrl: '', supabaseAnonKey: '' };
|
||||||
|
} catch {
|
||||||
|
return { supabaseUrl: '', supabaseAnonKey: '' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveSupabaseConfig(config) {
|
||||||
|
localStorage.setItem(SUPABASE_KEY, JSON.stringify(config));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exporta backup em formato JSON compatível com o appwpp-data.json original
|
||||||
|
*/
|
||||||
|
export function exportAppWppBackup(servers) {
|
||||||
|
const data = JSON.stringify({ servers }, null, 2);
|
||||||
|
const blob = new Blob([data], { type: 'application/json' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = `appwpp-data-backup-${new Date().toISOString().slice(0, 10)}.json`;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import forge from 'node-forge';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extrai CPF ou CNPJ de uma string de texto (ex: Common Name ou OUs de certificados ICP-Brasil)
|
||||||
|
*/
|
||||||
|
function extractTaxId(text) {
|
||||||
|
if (!text) return null;
|
||||||
|
// Procura padrão CNPJ (14 dígitos) ou CPF (11 dígitos)
|
||||||
|
const cnpjMatch = text.match(/\b\d{2}\.?\d{3}\.?\d{3}\/?\d{4}-?\d{2}\b/) || text.match(/:(\d{14})\b/);
|
||||||
|
if (cnpjMatch) {
|
||||||
|
const raw = (cnpjMatch[1] || cnpjMatch[0]).replace(/\D/g, '');
|
||||||
|
if (raw.length === 14) {
|
||||||
|
return { type: 'CNPJ', value: raw.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/, '$1.$2.$3/$4-$5') };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const cpfMatch = text.match(/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/) || text.match(/:(\d{11})\b/);
|
||||||
|
if (cpfMatch) {
|
||||||
|
const raw = (cpfMatch[1] || cpfMatch[0]).replace(/\D/g, '');
|
||||||
|
if (raw.length === 11) {
|
||||||
|
return { type: 'CPF', value: raw.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/, '$1.$2.$3-$4') };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converte um arquivo PFX/P12 (ArrayBuffer) para os formatos CRT, PEM e KEY.
|
||||||
|
*
|
||||||
|
* Equivalência OpenSSL:
|
||||||
|
* - PEM: openssl pkcs12 -in [cert].pfx -nokeys -out [cert].pem
|
||||||
|
* - CRT: openssl pkcs12 -in [cert].pfx -clcerts -nokeys -out [cert].crt
|
||||||
|
* - KEY: openssl pkcs12 -in [cert].pfx -nocerts -nodes -out [cert].key
|
||||||
|
*
|
||||||
|
* @param {ArrayBuffer} arrayBuffer - Conteúdo bruto do arquivo .pfx
|
||||||
|
* @param {string} password - Senha de importação do arquivo
|
||||||
|
* @returns {object} Objeto com os conteúdos em formato string e metadados
|
||||||
|
*/
|
||||||
|
export function convertPfx(arrayBuffer, password = '') {
|
||||||
|
try {
|
||||||
|
const bytes = forge.util.createBuffer(arrayBuffer).getBytes();
|
||||||
|
const p12Asn1 = forge.asn1.fromDer(bytes);
|
||||||
|
const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, password);
|
||||||
|
|
||||||
|
// 1. Extração de Bolsas de Certificados (Cert Bags)
|
||||||
|
const certBagsObj = p12.getBags({ bagType: forge.pki.oids.certBag });
|
||||||
|
const certBags = certBagsObj[forge.pki.oids.certBag] || [];
|
||||||
|
|
||||||
|
// 2. Extração de Bolsas de Chave Privada (Shrouded & Plain)
|
||||||
|
const shroudedBags = p12.getBags({ bagType: forge.pki.oids.pkcs8ShroudedKeyBag })[forge.pki.oids.pkcs8ShroudedKeyBag] || [];
|
||||||
|
const plainKeyBags = p12.getBags({ bagType: forge.pki.oids.keyBag })[forge.pki.oids.keyBag] || [];
|
||||||
|
const keyBags = [...shroudedBags, ...plainKeyBags];
|
||||||
|
|
||||||
|
if (certBags.length === 0 && keyBags.length === 0) {
|
||||||
|
throw new Error('Nenhum certificado ou chave privada encontrado no arquivo PFX fornecido.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const allCerts = certBags.filter(b => b.cert).map(b => b.cert);
|
||||||
|
|
||||||
|
// 3. Obter Chave Privada
|
||||||
|
let privateKey = null;
|
||||||
|
let privateKeyBag = null;
|
||||||
|
if (keyBags.length > 0 && keyBags[0].key) {
|
||||||
|
privateKeyBag = keyBags[0];
|
||||||
|
privateKey = keyBags[0].key;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Identificar o Certificado Cliente (Leaf Certificate)
|
||||||
|
// No OpenSSL -clcerts filtra somente o certificado associado à chave privada
|
||||||
|
let clientCert = null;
|
||||||
|
if (privateKey) {
|
||||||
|
// Tentativa 1: Correspondência por localKeyId
|
||||||
|
const keyLocalId = privateKeyBag?.attributes?.localKeyId?.[0];
|
||||||
|
if (keyLocalId) {
|
||||||
|
const foundBag = certBags.find(b => b.attributes?.localKeyId?.[0] === keyLocalId);
|
||||||
|
if (foundBag?.cert) clientCert = foundBag.cert;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tentativa 2: Correspondência pelo Módulo da Chave Pública (RSA Modulus)
|
||||||
|
if (!clientCert && privateKey.n) {
|
||||||
|
const keyModulus = privateKey.n.toString();
|
||||||
|
const found = allCerts.find(c => c.publicKey?.n?.toString() === keyModulus);
|
||||||
|
if (found) clientCert = found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se houver apenas 1 certificado ou não foi possível associar, seleciona o primeiro
|
||||||
|
if (!clientCert && allCerts.length > 0) {
|
||||||
|
clientCert = allCerts[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ordenar certificados da cadeia: Certificado do cliente primeiro, seguido pelos intermediários/raiz
|
||||||
|
const chainCerts = allCerts.filter(c => c !== clientCert);
|
||||||
|
const orderedAllCerts = clientCert ? [clientCert, ...chainCerts] : allCerts;
|
||||||
|
|
||||||
|
// 5. Geração dos formatos de saída:
|
||||||
|
|
||||||
|
// .CRT: Apenas o certificado cliente (equivalente a -clcerts -nokeys)
|
||||||
|
const crt = clientCert ? forge.pki.certificateToPem(clientCert) : '';
|
||||||
|
|
||||||
|
// .PEM: Todos os certificados da cadeia (equivalente a -nokeys)
|
||||||
|
const pem = orderedAllCerts.map(c => forge.pki.certificateToPem(c)).join('\n');
|
||||||
|
|
||||||
|
// .KEY: Chave privada desprotegida (equivalente a -nocerts -nodes)
|
||||||
|
const key = privateKey ? forge.pki.privateKeyToPem(privateKey) : '';
|
||||||
|
|
||||||
|
// 6. Extração de Metadados Detalhados para exibição
|
||||||
|
let metadata = null;
|
||||||
|
if (clientCert) {
|
||||||
|
const getAttr = (attrs, name, shortName) => {
|
||||||
|
const item = attrs.find(a => a.name === name || (shortName && a.shortName === shortName));
|
||||||
|
return item ? item.value : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const certDer = forge.asn1.toDer(forge.pki.certificateToAsn1(clientCert)).getBytes();
|
||||||
|
const sha1 = forge.md.sha1.create().update(certDer).digest().toHex().match(/.{2}/g).join(':').toUpperCase();
|
||||||
|
const sha256 = forge.md.sha256.create().update(certDer).digest().toHex().match(/.{2}/g).join(':').toUpperCase();
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const notBefore = clientCert.validity.notBefore;
|
||||||
|
const notAfter = clientCert.validity.notAfter;
|
||||||
|
const isValid = now >= notBefore && now <= notAfter;
|
||||||
|
const isExpired = now > notAfter;
|
||||||
|
const daysRemaining = Math.ceil((notAfter.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
|
||||||
|
|
||||||
|
const commonName = getAttr(clientCert.subject.attributes, 'commonName', 'CN') || 'Não identificado';
|
||||||
|
const taxId = extractTaxId(commonName) || extractTaxId(JSON.stringify(clientCert.subject.attributes));
|
||||||
|
|
||||||
|
metadata = {
|
||||||
|
subject: {
|
||||||
|
commonName,
|
||||||
|
organization: getAttr(clientCert.subject.attributes, 'organizationName', 'O') || '',
|
||||||
|
orgUnits: clientCert.subject.attributes.filter(a => a.name === 'organizationalUnitName' || a.shortName === 'OU').map(a => a.value),
|
||||||
|
country: getAttr(clientCert.subject.attributes, 'countryName', 'C') || '',
|
||||||
|
state: getAttr(clientCert.subject.attributes, 'stateOrProvinceName', 'ST') || '',
|
||||||
|
locality: getAttr(clientCert.subject.attributes, 'localityName', 'L') || '',
|
||||||
|
},
|
||||||
|
issuer: {
|
||||||
|
commonName: getAttr(clientCert.issuer.attributes, 'commonName', 'CN') || 'Não identificado',
|
||||||
|
organization: getAttr(clientCert.issuer.attributes, 'organizationName', 'O') || '',
|
||||||
|
country: getAttr(clientCert.issuer.attributes, 'countryName', 'C') || '',
|
||||||
|
},
|
||||||
|
validity: {
|
||||||
|
notBefore: notBefore.toISOString(),
|
||||||
|
notAfter: notAfter.toISOString(),
|
||||||
|
notBeforeFormatted: notBefore.toLocaleString('pt-BR'),
|
||||||
|
notAfterFormatted: notAfter.toLocaleString('pt-BR'),
|
||||||
|
isValid,
|
||||||
|
isExpired,
|
||||||
|
daysRemaining
|
||||||
|
},
|
||||||
|
taxId,
|
||||||
|
serialNumber: clientCert.serialNumber,
|
||||||
|
fingerprints: {
|
||||||
|
sha1,
|
||||||
|
sha256
|
||||||
|
},
|
||||||
|
keyDetails: privateKey ? {
|
||||||
|
type: 'RSA',
|
||||||
|
bits: privateKey.n ? privateKey.n.bitLength() : 2048
|
||||||
|
} : null,
|
||||||
|
totalCerts: allCerts.length,
|
||||||
|
hasPrivateKey: !!privateKey
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
crt,
|
||||||
|
pem,
|
||||||
|
key,
|
||||||
|
metadata
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
let msg = err.message || 'Erro ao processar o certificado.';
|
||||||
|
|
||||||
|
if (
|
||||||
|
msg.includes('Invalid password') ||
|
||||||
|
msg.includes('PKCS#12 MAC could not be verified') ||
|
||||||
|
msg.includes('MAC verify') ||
|
||||||
|
msg.includes('mac is invalid')
|
||||||
|
) {
|
||||||
|
msg = 'Senha incorreta para o arquivo PFX. Por favor, confira a senha e tente novamente.';
|
||||||
|
} else if (
|
||||||
|
msg.includes('Too few bytes') ||
|
||||||
|
msg.includes('Cannot read') ||
|
||||||
|
msg.includes('ASN.1') ||
|
||||||
|
msg.includes('Unexpected')
|
||||||
|
) {
|
||||||
|
msg = 'O arquivo selecionado não é um arquivo PKCS#12 / PFX válido ou está corrompido.';
|
||||||
|
} else if (msg.includes('PBES2') || msg.includes('algorithm')) {
|
||||||
|
msg = 'O certificado utiliza uma cifra moderna (PBES2/AES). Tente converter ou recriar no padrão PKCS#12 compatível.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: msg
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import JSZip from 'jszip';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Faz o download de um arquivo de texto no navegador
|
||||||
|
* @param {string} content - Conteúdo textual do arquivo
|
||||||
|
* @param {string} filename - Nome do arquivo para download (ex: 'meu_cert.crt')
|
||||||
|
* @param {string} mimeType - Tipo MIME (default: 'text/plain;charset=utf-8')
|
||||||
|
*/
|
||||||
|
export function downloadFile(content, filename, mimeType = 'text/plain;charset=utf-8') {
|
||||||
|
if (!content) return;
|
||||||
|
const blob = new Blob([content], { type: mimeType });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = filename;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cria e baixa um arquivo ZIP contendo os arquivos .crt, .pem, .key e um sumário .txt
|
||||||
|
* @param {object} files - Objeto contendo { crt, pem, key }
|
||||||
|
* @param {string} baseName - Nome base sem extensão (ex: 'cert_olho')
|
||||||
|
* @param {object} metadata - Metadados do certificado para inclusão no resumo
|
||||||
|
*/
|
||||||
|
export async function downloadAllAsZip(files, baseName = 'certificado', metadata = null) {
|
||||||
|
const zip = new JSZip();
|
||||||
|
|
||||||
|
// Adiciona arquivos convertidos
|
||||||
|
if (files.crt) {
|
||||||
|
zip.file(`${baseName}.crt`, files.crt);
|
||||||
|
}
|
||||||
|
if (files.pem) {
|
||||||
|
zip.file(`${baseName}.pem`, files.pem);
|
||||||
|
}
|
||||||
|
if (files.key) {
|
||||||
|
zip.file(`${baseName}.key`, files.key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gera arquivo informativo com detalhes
|
||||||
|
if (metadata) {
|
||||||
|
const infoText = [
|
||||||
|
'=========================================================================',
|
||||||
|
' DETALHES DO CERTIFICADO DIGITAL CONVERTIDO ',
|
||||||
|
'=========================================================================',
|
||||||
|
`Arquivo Original: ${baseName}.pfx`,
|
||||||
|
`Data da Conversão: ${new Date().toLocaleString('pt-BR')}`,
|
||||||
|
'',
|
||||||
|
'--- TITULAR (SUBJECT) ---',
|
||||||
|
`Nome Comum (CN): ${metadata.subject?.commonName || '-'}`,
|
||||||
|
metadata.taxId ? `Documento (${metadata.taxId.type}): ${metadata.taxId.value}` : null,
|
||||||
|
`Organização (O): ${metadata.subject?.organization || '-'}`,
|
||||||
|
`Localidade: ${metadata.subject?.locality || '-'}, ${metadata.subject?.state || '-'} - ${metadata.subject?.country || '-'}`,
|
||||||
|
'',
|
||||||
|
'--- EMISSOR (ISSUER) ---',
|
||||||
|
`Autoridade Certificadora: ${metadata.issuer?.commonName || '-'}`,
|
||||||
|
`Organização Emissora: ${metadata.issuer?.organization || '-'}`,
|
||||||
|
'',
|
||||||
|
'--- VALIDADE ---',
|
||||||
|
`Válido a partir de: ${metadata.validity?.notBeforeFormatted || '-'}`,
|
||||||
|
`Válido até: ${metadata.validity?.notAfterFormatted || '-'}`,
|
||||||
|
`Status: ${metadata.validity?.isValid ? 'ATIVO / VÁLIDO' : 'EXPIRADO'} (${metadata.validity?.daysRemaining} dias restantes)`,
|
||||||
|
'',
|
||||||
|
'--- CHAVE E CRIPTOGRAFIA ---',
|
||||||
|
`Chave Privada: ${metadata.keyDetails ? `${metadata.keyDetails.type} ${metadata.keyDetails.bits} bits` : 'Não incluída'}`,
|
||||||
|
`Número de Série: ${metadata.serialNumber || '-'}`,
|
||||||
|
`Impressão Digital SHA-1: ${metadata.fingerprints?.sha1 || '-'}`,
|
||||||
|
`Impressão Digital SHA-256: ${metadata.fingerprints?.sha256 || '-'}`,
|
||||||
|
'',
|
||||||
|
'--- ARQUIVOS GERADOS ---',
|
||||||
|
`1. ${baseName}.crt -> Apenas o certificado cliente (equivalente ao openssl -clcerts -nokeys)`,
|
||||||
|
`2. ${baseName}.pem -> Cadeia completa de certificados (equivalente ao openssl -nokeys)`,
|
||||||
|
`3. ${baseName}.key -> Chave privada desprotegida (equivalente ao openssl -nocerts -nodes)`,
|
||||||
|
'',
|
||||||
|
'========================================================================='
|
||||||
|
].filter(Boolean).join('\n');
|
||||||
|
|
||||||
|
zip.file('LEIA-ME-INFO.txt', infoText);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Gera o blob do ZIP e dispara o download
|
||||||
|
const blob = await zip.generateAsync({ type: 'blob' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url;
|
||||||
|
a.download = `${baseName}_convertido.zip`;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,217 @@
|
|||||||
|
/**
|
||||||
|
* Cliente de API WPPConnect para o AppWPP (React)
|
||||||
|
*/
|
||||||
|
|
||||||
|
export function normalizeUrl(url) {
|
||||||
|
if (!url) return '';
|
||||||
|
let u = url.trim().replace(/\/+$/, '');
|
||||||
|
if (!/^https?:\/\//i.test(u)) u = 'http://' + u;
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ensureQRPrefix(qrCode) {
|
||||||
|
if (!qrCode) return '';
|
||||||
|
return qrCode.startsWith('data:') ? qrCode : `data:image/png;base64,${qrCode}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSessionAuth(server, session) {
|
||||||
|
if (!server) return null;
|
||||||
|
return session?.token || server.secretKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Testa conectividade com o servidor WPPConnect
|
||||||
|
*/
|
||||||
|
export async function testServerConnection(baseUrl, secretKey) {
|
||||||
|
const normUrl = normalizeUrl(baseUrl);
|
||||||
|
const res = await fetch(`${normUrl}/api/${secretKey}/show-all-sessions`, {
|
||||||
|
headers: { 'Authorization': `Bearer ${secretKey}` },
|
||||||
|
signal: AbortSignal.timeout(8000),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
return { ok: true, message: 'Conexão OK! Servidor respondeu com sucesso.' };
|
||||||
|
} else if (res.status === 401) {
|
||||||
|
return { ok: false, error: 'Token incorreto. Verifique a Secret Key.' };
|
||||||
|
} else {
|
||||||
|
const text = await res.text().catch(() => '');
|
||||||
|
return { ok: false, error: `Erro ${res.status}: ${text || 'Resposta inesperada'}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inicia uma sessão WPPConnect
|
||||||
|
*/
|
||||||
|
export async function startSession(server, sessionName, options = {}) {
|
||||||
|
const baseUrl = normalizeUrl(server.baseUrl);
|
||||||
|
const session = server.sessions?.find(s => s.name === sessionName);
|
||||||
|
const authToken = getSessionAuth(server, session);
|
||||||
|
|
||||||
|
const url = `${baseUrl}/api/${sessionName}/start-session`;
|
||||||
|
const body = { waitQrCode: true };
|
||||||
|
if (session?.webhook) body.webhook = session.webhook;
|
||||||
|
if (session?.proxy) body.proxy = session.proxy;
|
||||||
|
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${authToken}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errText = await res.text();
|
||||||
|
throw new Error(errText || `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gera token JWT para a sessão
|
||||||
|
*/
|
||||||
|
export async function generateToken(server, sessionName) {
|
||||||
|
const baseUrl = normalizeUrl(server.baseUrl);
|
||||||
|
const res = await fetch(`${baseUrl}/api/${sessionName}/${server.secretKey}/generate-token`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${server.secretKey}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ session: sessionName }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
return data.token || null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Consulta status de conexão da sessão
|
||||||
|
*/
|
||||||
|
export async function checkSessionStatus(server, sessionName) {
|
||||||
|
const baseUrl = normalizeUrl(server.baseUrl);
|
||||||
|
const session = server.sessions?.find(s => s.name === sessionName);
|
||||||
|
const authToken = getSessionAuth(server, session);
|
||||||
|
|
||||||
|
const res = await fetch(`${baseUrl}/api/${sessionName}/check-connection-session`, {
|
||||||
|
headers: { 'Authorization': `Bearer ${authToken}` },
|
||||||
|
signal: AbortSignal.timeout(6000),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
return data.status || 'unknown';
|
||||||
|
}
|
||||||
|
return 'error';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Busca o QR Code da sessão
|
||||||
|
*/
|
||||||
|
export async function fetchQRCode(server, sessionName) {
|
||||||
|
const baseUrl = normalizeUrl(server.baseUrl);
|
||||||
|
const session = server.sessions?.find(s => s.name === sessionName);
|
||||||
|
const authToken = getSessionAuth(server, session);
|
||||||
|
|
||||||
|
const qrRes = await fetch(`${baseUrl}/api/${sessionName}/qrcode-session`, {
|
||||||
|
headers: { 'Authorization': `Bearer ${authToken}` },
|
||||||
|
signal: AbortSignal.timeout(10000),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!qrRes.ok) return null;
|
||||||
|
|
||||||
|
const ct = qrRes.headers.get('content-type') || '';
|
||||||
|
if (ct.includes('json')) {
|
||||||
|
const data = await qrRes.json();
|
||||||
|
return data.qrcode ? ensureQRPrefix(data.qrcode) : null;
|
||||||
|
} else if (ct.includes('image')) {
|
||||||
|
const buf = await qrRes.arrayBuffer();
|
||||||
|
const bytes = new Uint8Array(buf);
|
||||||
|
let binary = '';
|
||||||
|
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
||||||
|
return `data:${ct};base64,${btoa(binary)}`;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fecha a sessão
|
||||||
|
*/
|
||||||
|
export async function closeSession(server, sessionName) {
|
||||||
|
const baseUrl = normalizeUrl(server.baseUrl);
|
||||||
|
const session = server.sessions?.find(s => s.name === sessionName);
|
||||||
|
let authToken = getSessionAuth(server, session);
|
||||||
|
|
||||||
|
const res = await fetch(`${baseUrl}/api/${sessionName}/close-session`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
|
||||||
|
body: JSON.stringify({ secretkey: server.secretKey }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errBody = await res.text().catch(() => '');
|
||||||
|
throw new Error(errBody || `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Desconecta a sessão (Logout)
|
||||||
|
*/
|
||||||
|
export async function logoutSession(server, sessionName) {
|
||||||
|
const baseUrl = normalizeUrl(server.baseUrl);
|
||||||
|
const session = server.sessions?.find(s => s.name === sessionName);
|
||||||
|
let authToken = getSessionAuth(server, session);
|
||||||
|
|
||||||
|
const res = await fetch(`${baseUrl}/api/${sessionName}/logout-session`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
|
||||||
|
body: JSON.stringify({ secretkey: server.secretKey }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errBody = await res.text().catch(() => '');
|
||||||
|
throw new Error(errBody || `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Limpa arquivos e dados da sessão no servidor
|
||||||
|
*/
|
||||||
|
export async function clearSessionData(server, sessionName) {
|
||||||
|
const baseUrl = normalizeUrl(server.baseUrl);
|
||||||
|
const res = await fetch(`${baseUrl}/api/${sessionName}/${server.secretKey}/clear-session-data`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${server.secretKey}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const errBody = await res.text().catch(() => '');
|
||||||
|
throw new Error(errBody || `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lista todas as sessões registradas no servidor
|
||||||
|
*/
|
||||||
|
export async function listAllServerSessions(server) {
|
||||||
|
const baseUrl = normalizeUrl(server.baseUrl);
|
||||||
|
const res = await fetch(`${baseUrl}/api/${server.secretKey}/show-all-sessions`, {
|
||||||
|
headers: { 'Authorization': `Bearer ${server.secretKey}` },
|
||||||
|
signal: AbortSignal.timeout(10000),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||||
|
const data = await res.json();
|
||||||
|
return data.response || [];
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
import { defineConfig } from 'vite'
|
||||||
|
|
||||||
|
// https://vite.dev/config/
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user