Files
cybercore-signer/sdk/demo/index.html

1685 lines
60 KiB
HTML

<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CyberCore Signer — Assinatura Digital de PDF, XML, Arquivos e Login Digital (CCSP/1)</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script>
if (window.pdfjsLib) {
window.pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
}
</script>
<style>
:root {
--bg-base: #090d16;
--bg-surface: #0f172a;
--bg-card: #131c31;
--bg-card-subtle: #18223c;
--bg-hover: #1e293b;
--border-subtle: #24304f;
--border-focus: #38bdf8;
--border-glow: rgba(56, 189, 248, 0.35);
--primary: #38bdf8;
--primary-hover: #0ea5e9;
--primary-glow: rgba(56, 189, 248, 0.25);
--accent-purple: #818cf8;
--accent-cyan: #22d3ee;
--success: #34d399;
--warning: #fbbf24;
--danger: #f87171;
--text-main: #f8fafc;
--text-muted: #94a3b8;
--text-dim: #64748b;
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
--font-mono: 'JetBrains Mono', monospace;
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 14px;
--shadow-card: 0 10px 25px -5px rgba(0, 0, 0, 0.4), 0 8px 10px -6px rgba(0, 0, 0, 0.3);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: var(--bg-base);
color: var(--text-main);
font-family: var(--font-sans);
line-height: 1.5;
min-height: 100vh;
display: flex;
flex-direction: column;
background-image:
radial-gradient(at 0% 0%, rgba(56, 189, 248, 0.08) 0px, transparent 50%),
radial-gradient(at 100% 100%, rgba(129, 140, 248, 0.07) 0px, transparent 50%);
}
/* Header */
header {
background: rgba(15, 23, 42, 0.85);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border-subtle);
position: sticky;
top: 0;
z-index: 100;
padding: 14px 28px;
}
.header-content {
max-width: 1280px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.brand-wrap {
display: flex;
align-items: center;
gap: 12px;
}
.brand-logo {
width: 38px;
height: 38px;
background: linear-gradient(135deg, var(--primary), var(--accent-purple));
border-radius: var(--radius-sm);
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: 19px;
color: #0f172a;
box-shadow: 0 0 16px var(--primary-glow);
}
.brand-text h1 {
font-size: 16px;
font-weight: 700;
letter-spacing: 0.5px;
background: linear-gradient(to right, #ffffff, #cbd5e1);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
.brand-text p {
font-size: 11px;
color: var(--text-muted);
letter-spacing: 0.2px;
}
.header-actions {
display: flex;
align-items: center;
gap: 12px;
}
.agent-status-badge {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 14px;
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: 20px;
font-size: 12px;
font-weight: 500;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--danger);
box-shadow: 0 0 8px var(--danger);
transition: all 0.3s ease;
}
.status-dot.online {
background: var(--success);
box-shadow: 0 0 8px var(--success);
}
/* Container Principal */
main {
flex: 1;
max-width: 1280px;
width: 100%;
margin: 24px auto;
padding: 0 20px;
display: flex;
flex-direction: column;
gap: 24px;
}
.banner {
background: linear-gradient(135deg, rgba(30, 41, 59, 0.6), rgba(15, 23, 42, 0.95));
border: 1px solid var(--border-subtle);
border-radius: var(--radius-lg);
padding: 20px 24px;
display: flex;
justify-content: space-between;
align-items: center;
gap: 20px;
box-shadow: var(--shadow-card);
}
.banner-text h2 {
font-size: 17px;
font-weight: 700;
color: #fff;
margin-bottom: 4px;
}
.banner-text p {
font-size: 13px;
color: var(--text-muted);
max-width: 820px;
}
/* Seletor de Certificado Global */
.cert-bar {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-md);
padding: 14px 20px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.cert-bar-left {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
min-width: 280px;
}
.cert-bar-select {
flex: 1;
background: var(--bg-surface);
border: 1px solid var(--border-subtle);
color: #fff;
padding: 8px 12px;
border-radius: var(--radius-sm);
font-size: 13px;
outline: none;
cursor: pointer;
}
.cert-bar-select:focus {
border-color: var(--primary);
}
/* Abas de Navegação de Funcionalidades */
.tabs-nav {
display: flex;
gap: 8px;
border-bottom: 1px solid var(--border-subtle);
padding-bottom: 4px;
flex-wrap: wrap;
}
.tab-btn {
background: transparent;
border: none;
color: var(--text-muted);
padding: 10px 18px;
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
font-size: 13px;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
transition: all 0.2s ease;
position: relative;
}
.tab-btn:hover {
color: var(--text-main);
background: rgba(30, 41, 59, 0.4);
}
.tab-btn.active {
color: var(--primary);
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-bottom: 1px solid var(--bg-card);
}
.tab-btn.active::after {
content: '';
position: absolute;
bottom: -1px;
left: 0;
right: 0;
height: 2px;
background: var(--primary);
}
.tab-pane {
display: none;
flex-direction: column;
gap: 20px;
}
.tab-pane.active {
display: flex;
}
/* Cards e Grids */
.card-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
@media (max-width: 900px) {
.card-grid {
grid-template-columns: 1fr;
}
}
.card {
background: var(--bg-card);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-md);
padding: 20px;
display: flex;
flex-direction: column;
gap: 16px;
box-shadow: var(--shadow-card);
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid var(--border-subtle);
padding-bottom: 12px;
}
.card-title {
font-size: 15px;
font-weight: 600;
color: #fff;
display: flex;
align-items: center;
gap: 8px;
}
/* Drop Zone para Arquivos */
.drop-zone {
border: 2px dashed var(--border-subtle);
border-radius: var(--radius-md);
padding: 28px 20px;
text-align: center;
cursor: pointer;
background: rgba(15, 23, 42, 0.4);
transition: all 0.2s ease;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.drop-zone:hover, .drop-zone.dragover {
border-color: var(--primary);
background: rgba(56, 189, 248, 0.05);
}
.drop-icon {
font-size: 32px;
}
.file-meta-box {
background: var(--bg-surface);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-sm);
padding: 12px 14px;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
}
/* Botões */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px 18px;
font-size: 13px;
font-weight: 600;
font-family: var(--font-sans);
border-radius: var(--radius-sm);
cursor: pointer;
transition: all 0.2s ease;
border: none;
outline: none;
}
.btn-primary {
background: linear-gradient(135deg, var(--primary), var(--primary-hover));
color: #090d16;
box-shadow: 0 4px 14px var(--primary-glow);
}
.btn-primary:hover {
filter: brightness(1.1);
transform: translateY(-1px);
}
.btn-secondary {
background: var(--bg-hover);
color: var(--text-main);
border: 1px solid var(--border-subtle);
}
.btn-secondary:hover {
background: #334155;
border-color: #475569;
}
.btn-auth {
background: linear-gradient(135deg, #10b981, #059669);
color: #ffffff;
box-shadow: 0 4px 14px rgba(16, 185, 129, 0.3);
}
.btn-auth:hover {
filter: brightness(1.15);
transform: translateY(-1px);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none !important;
filter: grayscale(0.5);
}
/* Formulários e Inputs */
.form-group {
display: flex;
flex-direction: column;
gap: 6px;
}
.form-label {
font-size: 12px;
font-weight: 500;
color: var(--text-muted);
}
textarea, input[type="text"] {
width: 100%;
background: var(--bg-surface);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-sm);
padding: 10px 12px;
color: #fff;
font-family: var(--font-mono);
font-size: 12px;
resize: vertical;
outline: none;
transition: border-color 0.2s;
}
textarea:focus, input[type="text"]:focus {
border-color: var(--primary);
}
.code-box {
background: #060911;
border: 1px solid var(--border-subtle);
border-radius: var(--radius-sm);
padding: 12px;
font-family: var(--font-mono);
font-size: 11px;
color: #38bdf8;
max-height: 180px;
overflow-y: auto;
word-break: break-all;
white-space: pre-wrap;
}
.alert {
padding: 10px 14px;
border-radius: var(--radius-sm);
font-size: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.alert-info {
background: rgba(56, 189, 248, 0.1);
border: 1px solid rgba(56, 189, 248, 0.25);
color: #38bdf8;
}
.alert-success {
background: rgba(52, 211, 153, 0.1);
border: 1px solid rgba(52, 211, 153, 0.25);
color: #34d399;
}
.alert-error {
background: rgba(248, 113, 113, 0.1);
border: 1px solid rgba(248, 113, 113, 0.25);
color: #f87171;
}
/* Crachá de Usuário Logado */
.user-badge-card {
background: linear-gradient(135deg, rgba(16, 185, 129, 0.1), rgba(15, 23, 42, 0.8));
border: 1px solid rgba(52, 211, 153, 0.35);
border-radius: var(--radius-md);
padding: 20px;
display: flex;
gap: 18px;
align-items: center;
}
.user-avatar {
width: 56px;
height: 56px;
border-radius: 50%;
background: linear-gradient(135deg, var(--success), #059669);
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: #090d16;
font-weight: 800;
box-shadow: 0 0 16px rgba(52, 211, 153, 0.3);
}
.user-info h3 {
font-size: 16px;
font-weight: 700;
color: #fff;
}
.user-info p {
font-size: 12px;
color: var(--text-muted);
}
.badge-tag {
display: inline-block;
padding: 2px 8px;
border-radius: 4px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
background: rgba(56, 189, 248, 0.15);
color: var(--primary);
border: 1px solid rgba(56, 189, 248, 0.3);
}
.badge-a1 {
background: rgba(52, 211, 153, 0.15);
color: var(--success);
border-color: rgba(52, 211, 153, 0.3);
}
.badge-a3 {
background: rgba(56, 189, 248, 0.15);
color: var(--primary);
border-color: rgba(56, 189, 248, 0.3);
}
.spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: #fff;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
footer {
border-top: 1px solid var(--border-subtle);
padding: 18px 24px;
text-align: center;
font-size: 12px;
color: var(--text-dim);
margin-top: auto;
}
</style>
</head>
<body>
<header>
<div class="header-content">
<div class="brand-wrap">
<div class="brand-logo">CC</div>
<div class="brand-text">
<h1>CYBERCORE SIGNER</h1>
<p>Assinatura de Documentos (PDF / XML / Arquivos) e Autenticação Digital ICP-Brasil (CCSP/1)</p>
</div>
</div>
<div class="header-actions">
<div class="agent-status-badge">
<div id="statusDot" class="status-dot"></div>
<span id="statusText">Verificando agente...</span>
</div>
<button id="btnConnect" class="btn btn-primary" style="padding: 7px 14px; font-size: 12px;">
<span>⚡</span> Conectar & Autorizar
</button>
</div>
</div>
</header>
<main>
<div class="banner">
<div class="banner-text">
<h2>Plataforma Unificada de Assinatura & Identidade Digital</h2>
<p>
O CyberCore Signer permite que aplicações web assinem <strong>documentos PDF, arquivos XML (NF-e/XMLDSig) e arquivos gerais</strong>, além de realizar <strong>Login Seguro com Certificado Digital (A1/A3)</strong> via protocolo CCSP/1 diretamente na máquina do usuário.
</p>
</div>
<button id="btnCheckStatus" class="btn btn-secondary">
<span>🔄</span> Recarregar Agente
</button>
</div>
<!-- Barra de Certificados Ativos -->
<div class="cert-bar">
<div class="cert-bar-left">
<span style="font-size: 13px; font-weight: 600; color: #fff;">Certificado Ativo:</span>
<select id="certSelect" class="cert-bar-select">
<option value="">Conecte o agente para carregar os certificados...</option>
</select>
</div>
<div id="certBadgeInfo" style="display: flex; gap: 8px; align-items: center;">
<span id="certTypeBadge" class="badge-tag" style="display: none;">A1</span>
<span id="certValidityText" style="font-size: 11px; color: var(--text-muted);"></span>
</div>
</div>
<!-- Abas de Navegação -->
<div class="tabs-nav">
<button class="tab-btn active" data-tab="tab-pdf">
<span>📄</span> Assinar PDF (Com Stamp Picker)
</button>
<button class="tab-btn" data-tab="tab-seals">
<span>🎨</span> Designer de Selos
</button>
<button class="tab-btn" data-tab="tab-xml">
<span>📋</span> Assinar XML (XAdES / NF-e)
</button>
<button class="tab-btn" data-tab="tab-file">
<span>📁</span> Arquivos em Geral
</button>
<button class="tab-btn" data-tab="tab-auth">
<span>🔑</span> Login com Certificado Digital
</button>
</div>
<!-- ABA 1: ASSINAR PDF (INTERATIVO COM RETORNO EM BASE64) -->
<div id="tab-pdf" class="tab-pane active">
<div class="card-grid" style="grid-template-columns: 1fr;">
<div class="card">
<div class="card-header">
<span class="card-title"><span>📄</span> Seleção do Documento & Posicionador de Selo (Stamp Picker)</span>
<span class="badge-tag">PAdES ISO 32000 / Base64</span>
</div>
<div id="pdfDropZone" class="drop-zone">
<div class="drop-icon">📑</div>
<p style="font-size: 13px; font-weight: 600; color: #fff;">Arraste um PDF ou clique para selecionar</p>
<p style="font-size: 11px; color: var(--text-muted);">O documento será renderizado abaixo para você escolher onde posicionar o selo</p>
<input type="file" id="pdfFileInput" accept="application/pdf" style="display: none;">
</div>
<div id="pdfFileMeta" class="file-meta-box" style="display: none;">
<div>
<strong id="pdfFileName" style="color: #fff;">contrato_prestacao.pdf</strong>
<div id="pdfFileSize" style="color: var(--text-muted); font-size: 11px;">0 KB</div>
</div>
<span class="badge-tag">PDF Carregado</span>
</div>
<!-- Contêiner do PdfStampPicker -->
<div id="stampPickerMount" style="margin-top: 14px; display: none;"></div>
<!-- Configurações do Selo e da Assinatura -->
<div id="pdfOptionsSection" style="margin-top: 16px; display: none; background: var(--bg-surface); padding: 16px; border-radius: var(--radius-sm); border: 1px solid var(--border-subtle);">
<h4 style="font-size: 13px; font-weight: 700; color: #fff; margin-bottom: 12px;">🎨 Configurações do Selo Visual</h4>
<div style="display: grid; grid-template-columns: minmax(240px, 360px); gap: 14px;">
<div class="form-group">
<label class="form-label">Tema do Selo Visual:</label>
<select id="pdfSealThemeSelect" class="cert-bar-select">
<option value="icp-brasil">Selo Padrão ICP-Brasil (Oficial)</option>
<option value="custom">🎨 Selo Personalizado do Designer</option>
</select>
</div>
</div>
<div style="margin-top: 16px; display: flex; gap: 10px; flex-wrap: wrap;">
<button id="btnSignPdfFull" class="btn btn-primary" style="flex: 2; padding: 12px; font-size: 13px;" disabled>
<span>✍️</span> Assinar PDF Completo no Agente (Devolve Base64)
</button>
<button id="btnSignPdfDigest" class="btn btn-secondary" style="flex: 1; padding: 12px; font-size: 12px;" disabled>
<span>🛡️</span> Assinar Apenas Digest (PAdES Remoto)
</button>
</div>
</div>
<div id="pdfAlert" class="alert alert-info" style="display: none; margin-top: 14px;"></div>
</div>
<!-- Card de Resultado do PDF Assinado -->
<div id="pdfResultCard" class="card" style="display: none;">
<div class="card-header">
<span class="card-title"><span>🎉</span> PDF Assinado Retornado com Sucesso</span>
<div style="display: flex; gap: 8px;">
<button id="btnDownloadPdf" class="btn btn-primary" style="padding: 6px 14px; font-size: 12px;">
<span>💾</span> Baixar PDF Assinado (.pdf)
</button>
<button id="btnCopyPdfBase64" class="btn btn-secondary" style="padding: 6px 12px; font-size: 12px;">
<span>📋</span> Copiar Base64
</button>
</div>
</div>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 14px; margin-bottom: 14px;">
<div class="form-group">
<label class="form-label">Status da Operação:</label>
<div id="pdfResultStatus" style="font-weight: 700; color: var(--success); font-size: 13px;">Assinado com Sucesso</div>
</div>
<div class="form-group">
<label class="form-label">Tamanho do PDF Assinado:</label>
<div id="pdfResultSize" style="font-family: var(--font-mono); font-size: 12px; color: #fff;">0 KB</div>
</div>
<div class="form-group">
<label class="form-label">SHA-256 do Documento Final:</label>
<div id="pdfResultSha256" style="font-family: var(--font-mono); font-size: 11px; color: var(--primary); word-break: break-all;">-</div>
</div>
</div>
<div class="form-group">
<label class="form-label">Conteúdo do PDF Assinado em Base64 (pronto para envio ao Backend):</label>
<div id="pdfResultBase64" class="code-box" style="max-height: 140px;"></div>
</div>
</div>
</div>
</div>
<!-- ABA 2: DESIGNER DE SELOS VISUAIS -->
<div id="tab-seals" class="tab-pane">
<div class="card-grid" style="grid-template-columns: 1fr;">
<div class="card">
<div class="card-header">
<span class="card-title"><span>🎨</span> Designer Interativo de Selos Visuais</span>
<span class="badge-tag">Customização em Tempo Real</span>
</div>
<p style="font-size: 13px; color: var(--text-muted); margin-bottom: 14px;">
Crie, personalize cores, tipografia, logotipos e metadados de selos visuais. As configurações geradas aqui podem ser enviadas diretamente na requisição de assinatura de PDF (<code style="color: var(--primary);">seal_custom</code>) ou salvas no sistema.
</p>
<div id="sealDesignerMount"></div>
</div>
</div>
</div>
<!-- ABA 3: ASSINAR XML -->
<div id="tab-xml" class="tab-pane">
<div class="card-grid">
<div class="card">
<div class="card-header">
<span class="card-title"><span>📋</span> Conteúdo do XML (NF-e / CT-e / NFS-e)</span>
<button id="btnLoadXmlSample" class="btn btn-secondary" style="padding: 4px 10px; font-size: 11px;">
Carregar Exemplo NF-e
</button>
</div>
<div class="form-group">
<label class="form-label">Perfil de Assinatura XML:</label>
<select id="xmlProfileSelect" class="cert-bar-select">
<option value="XADES_BES">XAdES-BES (Padrão Oficial ICP-Brasil / NF-e)</option>
<option value="XMLDSIG">XMLDSig W3C Padrão (Enveloped)</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Estrutura XML para Assinatura:</label>
<textarea id="xmlContentInput" rows="8" placeholder="Cole o XML ou selecione um arquivo..."></textarea>
</div>
<div style="display: flex; gap: 10px; margin-top: 4px;">
<button id="btnSignXmlFull" class="btn btn-primary" style="flex: 2; padding: 12px;" disabled>
<span>✍️</span> Assinar XML Completo no Agente
</button>
<button id="btnSignXmlDigest" class="btn btn-secondary" style="flex: 1; padding: 12px; font-size: 12px;" disabled>
<span>🛡️</span> Apenas Digest
</button>
</div>
<div id="xmlAlert" class="alert alert-info" style="display: none; margin-top: 14px;"></div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title"><span>🛡️</span> Pacote XML Assinado</span>
<div style="display: flex; gap: 6px;">
<button id="btnDownloadXml" class="btn btn-primary" style="padding: 4px 10px; font-size: 11px; display: none;">
<span>💾</span> Baixar XML
</button>
<button id="btnCopyXml" class="btn btn-secondary" style="padding: 4px 10px; font-size: 11px; display: none;">
<span>📋</span> Copiar
</button>
</div>
</div>
<div class="form-group">
<label class="form-label">XML Assinado Completo (com envelope de assinatura):</label>
<div id="xmlSigOutput" class="code-box" style="min-height: 220px; max-height: 380px;">Aguardando submissão do XML para assinatura...</div>
</div>
</div>
</div>
</div>
<!-- ABA 3: ARQUIVOS EM GERAL -->
<div id="tab-file" class="tab-pane">
<div class="card-grid">
<div class="card">
<div class="card-header">
<span class="card-title"><span>📁</span> Qualquer Arquivo (CAdES / Detached)</span>
<span class="badge-tag">Universal</span>
</div>
<div id="genDropZone" class="drop-zone">
<div class="drop-icon">📦</div>
<p style="font-size: 13px; font-weight: 600; color: #fff;">Arraste qualquer arquivo ou clique para selecionar</p>
<p style="font-size: 11px; color: var(--text-muted);">ZIP, DOCX, XLSX, TXT, imagens, áudios, etc.</p>
<input type="file" id="genFileInput" style="display: none;">
</div>
<div id="genFileMeta" class="file-meta-box" style="display: none;">
<div>
<strong id="genFileName" style="color: #fff;">arquivo.ext</strong>
<div id="genFileSize" style="color: var(--text-muted); font-size: 11px;">0 KB</div>
</div>
<span id="genFileBadge" class="badge-tag">ARQUIVO</span>
</div>
<div class="form-group">
<label class="form-label">Hash Criptográfico SHA-256 (Base64):</label>
<div id="genDigestBox" class="code-box">Selecione um arquivo para calcular o hash...</div>
</div>
<button id="btnSignGen" class="btn btn-primary" style="padding: 12px;" disabled>
<span>✍️</span> Assinar Arquivo com CyberCore
</button>
<div id="genAlert" class="alert alert-info" style="display: none;"></div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title"><span>🛡️</span> Assinatura CAdES / Detached</span>
</div>
<div class="form-group">
<label class="form-label">Assinatura Digital (Base64):</label>
<div id="genSigOutput" class="code-box" style="min-height: 120px;">Aguardando assinatura...</div>
</div>
<div class="form-group">
<label class="form-label">Metadados da Assinatura:</label>
<div id="genMetaOutput" class="code-box">Nenhum metadado disponível.</div>
</div>
</div>
</div>
</div>
<!-- ABA 4: LOGIN COM CERTIFICADO DIGITAL -->
<div id="tab-auth" class="tab-pane">
<div class="card-grid">
<div class="card">
<div class="card-header">
<span class="card-title"><span>🔑</span> Autenticação em Sistema Web</span>
<span class="badge-tag" style="background: rgba(16, 185, 129, 0.2); color: var(--success); border-color: rgba(52, 211, 153, 0.3);">
Challenge-Response
</span>
</div>
<p style="font-size: 13px; color: var(--text-muted);">
O sistema web emite um <strong>desafio criptográfico único</strong> que é assinado localmente com a chave privada do certificado (A1 ou Token/Smart Card A3), validando a identidade do usuário sem necessidade de senhas.
</p>
<div class="form-group">
<label class="form-label">Desafio do Servidor (Challenge / Server Nonce):</label>
<input type="text" id="authChallengeInput" readonly>
</div>
<div style="display: flex; gap: 10px;">
<button id="btnNewChallenge" class="btn btn-secondary" style="padding: 8px 14px; font-size: 12px;">
<span>🎲</span> Gerar Novo Desafio
</button>
<button id="btnAuthLogin" class="btn btn-auth" style="flex: 1; padding: 12px;" disabled>
<span>🔐</span> Entrar com Certificado Digital
</button>
</div>
<div id="authAlert" class="alert alert-info" style="display: none;"></div>
</div>
<div class="card">
<div class="card-header">
<span class="card-title"><span>👤</span> Sessão do Usuário Autenticado</span>
</div>
<div id="authUserCard" class="user-badge-card" style="display: none;">
<div id="authUserAvatar" class="user-avatar">CS</div>
<div class="user-info">
<h3 id="authUserName">Nome do Titular</h3>
<p id="authUserCpf">CPF / CNPJ: 000.000.000-00</p>
<div style="margin-top: 6px; display: flex; gap: 8px;">
<span class="badge-tag badge-a1">Autenticado com Sucesso</span>
<span id="authUserCertType" class="badge-tag badge-a3">ICP-Brasil</span>
</div>
</div>
</div>
<div id="authWaitBox" style="text-align: center; color: var(--text-dim); padding: 40px 20px; font-size: 13px;">
Clique em "Entrar com Certificado Digital" para iniciar a sessão segura.
</div>
<div class="form-group" style="margin-top: 10px;">
<label class="form-label">Token de Sessão / Assinatura do Desafio:</label>
<div id="authSigOutput" class="code-box">Nenhuma autenticação realizada ainda.</div>
</div>
</div>
</div>
</div>
</main>
<footer>
CyberCore Signer v0.1.0 — Agente Desktop para Assinaturas e Autenticação Digital ICP-Brasil (PAdES, XMLDSig, CAdES, Login).
</footer>
<!-- Lógica Javascript com o SDK -->
<script type="module">
import { CyberCoreSigner, PdfStampPicker, PdfSealDesigner } from '../src/signer-sdk.js';
const signer = new CyberCoreSigner({
baseUrl: 'http://127.0.0.1:21325',
applicationName: 'Portal Corporativo CyberCore'
});
// Elementos Compartilhados
const statusDot = document.getElementById('statusDot');
const statusText = document.getElementById('statusText');
const btnConnect = document.getElementById('btnConnect');
const btnCheckStatus = document.getElementById('btnCheckStatus');
const certSelect = document.getElementById('certSelect');
const certTypeBadge = document.getElementById('certTypeBadge');
const certValidityText = document.getElementById('certValidityText');
let currentCertificates = [];
let selectedCertificateId = null;
// Componentes e Estado
let pdfStampPicker = null;
let pdfSealDesigner = null;
let currentPdfFile = null;
let currentPdfBytes = null;
let currentPdfDigest = null;
let currentCustomSealConfig = null;
let currentSignedPdfBase64 = null;
let currentSignedXml = null;
// Gerenciador de Abas
const tabButtons = document.querySelectorAll('.tab-btn');
const tabPanes = document.querySelectorAll('.tab-pane');
tabButtons.forEach(btn => {
btn.addEventListener('click', () => {
tabButtons.forEach(b => b.classList.remove('active'));
tabPanes.forEach(p => p.classList.remove('active'));
btn.classList.add('active');
const targetTab = btn.dataset.tab;
document.getElementById(targetTab).classList.add('active');
// Lazy-mount do Designer de Selos
if (targetTab === 'tab-seals' && !pdfSealDesigner) {
initSealDesigner();
}
});
});
// Verificação de Status
async function checkAgentStatus() {
statusText.textContent = 'Verificando...';
try {
const isOnline = await signer.isInstalled(1500);
if (isOnline) {
const status = await signer.getStatus();
statusDot.classList.add('online');
statusText.textContent = `Online (${status.os || 'Windows'})`;
return true;
}
} catch (e) {}
statusDot.classList.remove('online');
statusText.textContent = 'Agente Offline';
return false;
}
// Carregamento de Temas de Selos
async function loadSealThemes() {
try {
const themeSelect = document.getElementById('pdfSealThemeSelect');
const themes = await signer.getSealThemes();
if (themes && themes.length > 0) {
themeSelect.innerHTML = '';
themes.forEach(t => {
const opt = document.createElement('option');
opt.value = t.id;
opt.textContent = `${t.name} (${t.id})`;
themeSelect.appendChild(opt);
});
const customOpt = document.createElement('option');
customOpt.value = 'custom';
customOpt.textContent = '🎨 Selo Customizado do Designer';
themeSelect.appendChild(customOpt);
}
} catch (err) {
console.warn('Não foi possível carregar temas dinâmicos de selos:', err);
}
}
// Carregamento de Certificados
async function loadCertificates() {
try {
const certs = await signer.getCertificates();
currentCertificates = certs;
certSelect.innerHTML = '';
if (!certs || certs.length === 0) {
certSelect.innerHTML = '<option value="">Nenhum certificado detectado no agente</option>';
updateButtonStates();
return;
}
certs.forEach((c) => {
const opt = document.createElement('option');
opt.value = c.id;
let rawName = c.common_name || c.alias || 'Certificado';
let displayName = rawName;
let docNum = c.cpf || c.cnpj || c.cpf_cnpj || '';
if (rawName.includes(':')) {
const parts = rawName.split(':');
displayName = parts[0].trim();
if (!docNum && parts[1]) {
docNum = parts[1].trim();
}
}
const digits = docNum ? String(docNum).replace(/\D/g, '') : '';
let docFormatted = '';
if (digits.length === 14) {
docFormatted = 'CNPJ ' + digits.substring(0, 2) + '.' + digits.substring(2, 5) + '.' + digits.substring(5, 8) + '/' + digits.substring(8, 12) + '-' + digits.substring(12, 14);
} else if (digits.length === 11) {
docFormatted = 'CPF ' + digits.substring(0, 3) + '.' + digits.substring(3, 6) + '.' + digits.substring(6, 9) + '-' + digits.substring(9, 11);
} else if (docNum) {
docFormatted = docNum;
}
const typeStr = '[' + (c.type || 'A1') + ']';
const text = docFormatted ? `${displayName}, ${docFormatted} ${typeStr}` : `${displayName} ${typeStr}`;
opt.textContent = text;
certSelect.appendChild(opt);
});
certSelect.selectedIndex = 0;
onCertificateChanged();
} catch (err) {
console.error('Erro ao carregar certificados:', err);
}
}
function onCertificateChanged() {
const selectedId = certSelect.value;
selectedCertificateId = selectedId;
const cert = currentCertificates.find(c => c.id === selectedId);
if (cert) {
certTypeBadge.style.display = 'inline-block';
certTypeBadge.textContent = cert.type || 'A1';
certTypeBadge.className = `badge-tag ${cert.type === 'A3' ? 'badge-a3' : 'badge-a1'}`;
certValidityText.textContent = `Validade: ${cert.valid_to ? new Date(cert.valid_to).toLocaleDateString() : 'N/D'}`;
if (pdfStampPicker) {
const rawDoc = cert.cpf || cert.cnpj || cert.cpf_cnpj || '';
const digits = String(rawDoc).replace(/\D/g, '');
let docStr = '';
if (digits.length === 14) {
docStr = 'CNPJ: ' + digits.substring(0, 2) + '.' + digits.substring(2, 5) + '.' + digits.substring(5, 8) + '/' + digits.substring(8, 12) + '-' + digits.substring(12, 14);
} else if (digits.length === 11) {
docStr = 'CPF: ' + digits.substring(0, 3) + '.' + digits.substring(3, 6) + '.' + digits.substring(6, 9) + '-' + digits.substring(9, 11);
} else {
docStr = cert.type === 'A3' ? 'Token Físico A3' : 'ICP-Brasil';
}
let cleanSignerName = cert.common_name || cert.alias || 'Titular';
if (cleanSignerName && cleanSignerName.includes(':')) {
cleanSignerName = cleanSignerName.split(':')[0].trim();
}
pdfStampPicker.updateSealTheme(null, {
signerName: cleanSignerName,
signerDoc: docStr
});
}
} else {
certTypeBadge.style.display = 'none';
certValidityText.textContent = '';
}
updateButtonStates();
}
certSelect.addEventListener('change', onCertificateChanged);
function updateButtonStates() {
const hasCert = Boolean(selectedCertificateId);
const hasPdf = Boolean(currentPdfBytes);
const hasXml = Boolean(document.getElementById('xmlContentInput').value.trim());
const btnFull = document.getElementById('btnSignPdfFull');
const btnDigest = document.getElementById('btnSignPdfDigest');
if (btnFull) btnFull.disabled = !hasCert || !hasPdf;
if (btnDigest) btnDigest.disabled = !hasCert || !hasPdf;
const btnXmlFull = document.getElementById('btnSignXmlFull');
const btnXmlDigest = document.getElementById('btnSignXmlDigest');
if (btnXmlFull) btnXmlFull.disabled = !hasCert || !hasXml;
if (btnXmlDigest) btnXmlDigest.disabled = !hasCert || !hasXml;
const btnGen = document.getElementById('btnSignGen');
if (btnGen) btnGen.disabled = !hasCert || !currentGenDigest;
const btnAuth = document.getElementById('btnAuthLogin');
if (btnAuth) btnAuth.disabled = !hasCert;
}
// Conexão e Handshake
btnConnect.addEventListener('click', async () => {
btnConnect.disabled = true;
btnConnect.innerHTML = '<span class="spinner"></span> Solicitando...';
try {
await signer.connect();
statusDot.classList.add('online');
statusText.textContent = 'Conectado & Autorizado';
await loadCertificates();
await loadSealThemes();
} catch (err) {
alert('Erro ao conectar: ' + err.message);
} finally {
btnConnect.disabled = false;
btnConnect.innerHTML = '<span>⚡</span> Conectar & Autorizar';
}
});
btnCheckStatus.addEventListener('click', async () => {
const online = await checkAgentStatus();
if (online) {
await loadCertificates();
await loadSealThemes();
}
});
// =========================================================================
// ABA 1: LÓGICA DE PDF (STAMP PICKER & ASSINATURA BASE64)
// =========================================================================
const pdfDropZone = document.getElementById('pdfDropZone');
const pdfFileInput = document.getElementById('pdfFileInput');
const pdfFileMeta = document.getElementById('pdfFileMeta');
const pdfFileName = document.getElementById('pdfFileName');
const pdfFileSize = document.getElementById('pdfFileSize');
const stampPickerMount = document.getElementById('stampPickerMount');
const pdfOptionsSection = document.getElementById('pdfOptionsSection');
const pdfSealThemeSelect = document.getElementById('pdfSealThemeSelect');
const btnSignPdfFull = document.getElementById('btnSignPdfFull');
const btnSignPdfDigest = document.getElementById('btnSignPdfDigest');
const pdfAlert = document.getElementById('pdfAlert');
const pdfResultCard = document.getElementById('pdfResultCard');
const pdfResultSize = document.getElementById('pdfResultSize');
const pdfResultSha256 = document.getElementById('pdfResultSha256');
const pdfResultBase64 = document.getElementById('pdfResultBase64');
const btnDownloadPdf = document.getElementById('btnDownloadPdf');
const btnCopyPdfBase64 = document.getElementById('btnCopyPdfBase64');
pdfDropZone.addEventListener('click', () => pdfFileInput.click());
pdfFileInput.addEventListener('change', e => {
if (e.target.files.length) handlePdfSelected(e.target.files[0]);
});
pdfDropZone.addEventListener('dragover', e => {
e.preventDefault();
pdfDropZone.classList.add('dragover');
});
pdfDropZone.addEventListener('dragleave', () => pdfDropZone.classList.remove('dragover'));
pdfDropZone.addEventListener('drop', e => {
e.preventDefault();
pdfDropZone.classList.remove('dragover');
if (e.dataTransfer.files.length) handlePdfSelected(e.dataTransfer.files[0]);
});
async function handlePdfSelected(file) {
currentPdfFile = file;
pdfFileName.textContent = file.name;
pdfFileSize.textContent = (file.size / 1024).toFixed(1) + ' KB';
pdfFileMeta.style.display = 'flex';
const buffer = await file.arrayBuffer();
currentPdfBytes = buffer;
currentPdfDigest = await signer._calculateSha256(buffer);
stampPickerMount.style.display = 'block';
pdfOptionsSection.style.display = 'block';
const activeCert = currentCertificates.find(c => c.id === selectedCertificateId);
const currentThemeVal = pdfSealThemeSelect ? pdfSealThemeSelect.value : 'icp-brasil';
const initialTheme = (currentThemeVal === 'custom' && currentCustomSealConfig)
? currentCustomSealConfig
: currentThemeVal;
const rawCertName = activeCert ? (activeCert.common_name || activeCert.alias) : '';
const cleanCertName = rawCertName.includes(':') ? rawCertName.split(':')[0].trim() : rawCertName;
const initialSignerInfo = activeCert ? {
signerName: cleanCertName,
signerDoc: activeCert.cpf_cnpj ? `CPF: ${activeCert.cpf_cnpj}` : (activeCert.type === 'A3' ? 'Token Físico A3' : 'ICP-Brasil')
} : {
signerName: 'Nome do Titular do Certificado',
signerDoc: 'CPF: ***.456.789-**'
};
if (!pdfStampPicker) {
pdfStampPicker = new PdfStampPicker({
container: stampPickerMount,
pdf: buffer,
sealTheme: initialTheme,
signerInfo: initialSignerInfo,
initialScale: 1.0,
onPositionChange: (pos) => {
console.log('Posição do selo atualizada:', pos);
},
onSignRequest: () => {
btnSignPdfFull.click();
}
});
} else {
pdfStampPicker.updateSealTheme(initialTheme, initialSignerInfo);
pdfStampPicker.loadPdf(buffer);
}
updateButtonStates();
}
// Sincroniza alteração de tema com o selo sobre o PDF
pdfSealThemeSelect.addEventListener('change', () => {
const themeVal = pdfSealThemeSelect.value;
if (themeVal === 'custom') {
if (!currentCustomSealConfig && typeof pdfSealDesigner !== 'undefined' && pdfSealDesigner) {
currentCustomSealConfig = pdfSealDesigner.getConfig();
}
if (pdfStampPicker && currentCustomSealConfig) {
pdfStampPicker.updateSealTheme(currentCustomSealConfig);
}
} else {
if (pdfStampPicker) {
pdfStampPicker.updateSealTheme(themeVal);
}
}
});
// Assinatura Completa de PDF (Devolve PDF Assinado Base64)
btnSignPdfFull.addEventListener('click', async () => {
btnSignPdfFull.disabled = true;
btnSignPdfFull.innerHTML = '<span class="spinner"></span> Assinando no Agente...';
pdfAlert.style.display = 'block';
pdfAlert.className = 'alert alert-info';
pdfAlert.textContent = 'Confirme a assinatura na janela do CyberCore Signer...';
try {
const stampConfig = pdfStampPicker ? pdfStampPicker.getStampConfig() : { page: 1, x: 50, y: 50, scale: 1.0 };
const selectedTheme = pdfSealThemeSelect.value;
let effectiveCustomSeal = null;
if (selectedTheme === 'custom') {
if (currentCustomSealConfig) {
effectiveCustomSeal = currentCustomSealConfig;
} else if (typeof pdfSealDesigner !== 'undefined' && pdfSealDesigner) {
effectiveCustomSeal = pdfSealDesigner.getConfig();
currentCustomSealConfig = effectiveCustomSeal;
}
}
const signParams = {
certificateId: selectedCertificateId,
pdf: currentPdfFile || currentPdfBytes,
page: stampConfig.page,
x: stampConfig.x,
y: stampConfig.y,
scale: stampConfig.scale,
sealCustom: effectiveCustomSeal,
seal_custom: effectiveCustomSeal,
sealThemeId: (selectedTheme === 'custom' ? null : selectedTheme),
seal_theme_id: (selectedTheme === 'custom' ? null : selectedTheme)
};
const result = await signer.signPdfDocument(signParams);
pdfAlert.className = 'alert alert-success';
pdfAlert.textContent = '✓ Documento PDF assinado com sucesso via PAdES (ISO 32000)!';
const signedPdfBase64 = result.signedPdf || result.signed_pdf || '';
currentSignedPdfBase64 = signedPdfBase64;
pdfResultCard.style.display = 'block';
pdfResultSize.textContent = (signedPdfBase64.length * 0.75 / 1024).toFixed(1) + ' KB';
pdfResultSha256.textContent = result.sha256 || 'Calculado com sucesso';
pdfResultBase64.textContent = signedPdfBase64;
pdfResultCard.scrollIntoView({ behavior: 'smooth' });
} catch (err) {
pdfAlert.className = 'alert alert-error';
pdfAlert.textContent = 'Erro ao assinar PDF: ' + err.message;
} finally {
btnSignPdfFull.disabled = false;
btnSignPdfFull.innerHTML = '<span>✍️</span> Assinar PDF Completo no Agente (Devolve Base64)';
}
});
// Assinatura via Digest (Fluxo Tradicional)
btnSignPdfDigest.addEventListener('click', async () => {
btnSignPdfDigest.disabled = true;
btnSignPdfDigest.innerHTML = '<span class="spinner"></span> Solicitando...';
pdfAlert.style.display = 'block';
pdfAlert.className = 'alert alert-info';
pdfAlert.textContent = 'Assinando digest do PDF no CyberCore Signer...';
try {
const result = await signer.signPdf(currentPdfFile, {
certificateId: selectedCertificateId,
documentName: currentPdfFile.name
});
pdfAlert.className = 'alert alert-success';
pdfAlert.textContent = `✓ Digest assinado com sucesso! Algoritmo: ${result.algorithm}`;
} catch (err) {
pdfAlert.className = 'alert alert-error';
pdfAlert.textContent = 'Erro ao assinar digest: ' + err.message;
} finally {
btnSignPdfDigest.disabled = false;
btnSignPdfDigest.innerHTML = '<span>🛡️</span> Assinar Apenas Digest (PAdES Remoto)';
}
});
// Download do PDF Assinado
btnDownloadPdf.addEventListener('click', () => {
if (!currentSignedPdfBase64) return;
const blob = signer._base64ToBlob(currentSignedPdfBase64, 'application/pdf');
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
const origName = currentPdfFile ? currentPdfFile.name.replace(/\.pdf$/i, '') : 'documento';
a.href = url;
a.download = `${origName}_assinado.pdf`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
// Cópia do Base64 do PDF
btnCopyPdfBase64.addEventListener('click', async () => {
if (!currentSignedPdfBase64) return;
await navigator.clipboard.writeText(currentSignedPdfBase64);
const origText = btnCopyPdfBase64.innerHTML;
btnCopyPdfBase64.innerHTML = '<span>✓</span> Copiado!';
setTimeout(() => { btnCopyPdfBase64.innerHTML = origText; }, 2000);
});
// =========================================================================
// ABA 2: DESIGNER DE SELOS VISUAIS
// =========================================================================
function initSealDesigner() {
const mount = document.getElementById('sealDesignerMount');
pdfSealDesigner = new PdfSealDesigner({
container: mount,
initialTheme: {
name: 'Selo Customizado',
customHeader: 'DOCUMENTO ASSINADO DIGITALMENTE',
primaryColor: '#0284c7',
secondaryColor: '#10b981',
backgroundColor: '#ffffff',
textColor: '#0f172a',
borderColor: '#38bdf8',
iconStyle: 'shield',
defaultCpfMode: 'MASKED',
defaultIncludeDateTime: true
},
onChange: (cfg) => {
currentCustomSealConfig = cfg;
}
});
// Inicializa currentCustomSealConfig com o estado atual do designer
currentCustomSealConfig = pdfSealDesigner.getConfig();
// Botão para aplicar o selo na aba de PDF
const applyBtnWrap = document.createElement('div');
applyBtnWrap.style.marginTop = '16px';
applyBtnWrap.style.display = 'flex';
applyBtnWrap.style.gap = '10px';
applyBtnWrap.innerHTML = `
<button id="btnApplySealToPdf" class="btn btn-primary" style="padding: 10px 18px; font-size: 13px;">
<span>🚀</span> Usar este Selo no Posicionador de PDF
</button>
`;
mount.appendChild(applyBtnWrap);
document.getElementById('btnApplySealToPdf').addEventListener('click', () => {
currentCustomSealConfig = pdfSealDesigner.getConfig();
pdfSealThemeSelect.value = 'custom';
if (pdfStampPicker) {
pdfStampPicker.updateSealTheme(currentCustomSealConfig);
}
// Alterna para aba PDF
document.querySelector('[data-tab="tab-pdf"]').click();
alert('Selo customizado selecionado e aplicado ao posicionador de PDF!');
});
}
// =========================================================================
// ABA 3: LÓGICA DE XML (XAdES-BES & XMLDSig)
// =========================================================================
const xmlContentInput = document.getElementById('xmlContentInput');
const xmlProfileSelect = document.getElementById('xmlProfileSelect');
const btnSignXmlFull = document.getElementById('btnSignXmlFull');
const btnSignXmlDigest = document.getElementById('btnSignXmlDigest');
const btnLoadXmlSample = document.getElementById('btnLoadXmlSample');
const xmlAlert = document.getElementById('xmlAlert');
const xmlSigOutput = document.getElementById('xmlSigOutput');
const btnDownloadXml = document.getElementById('btnDownloadXml');
const btnCopyXml = document.getElementById('btnCopyXml');
const sampleXml = `<nfeProc versao="4.00" xmlns="http://www.portalfiscal.inf.br/nfe">
<NFe>
<infNFe Id="NFe35261012345678000199550010000001001234567890" versao="4.00">
<ide>
<cUF>35</cUF>
<natOp>VENDA DE MERCADORIAS</natOp>
<mod>55</mod>
<serie>1</serie>
<nNF>100</nNF>
<dhEmi>2026-10-09T10:00:00-03:00</dhEmi>
<tpNF>1</tpNF>
</ide>
<emit>
<CNPJ>12345678000199</CNPJ>
<xNome>CYBERCORE TECNOLOGIA LTDA</xNome>
</emit>
</infNFe>
</NFe>
</nfeProc>`;
xmlContentInput.addEventListener('input', () => updateButtonStates());
btnLoadXmlSample.addEventListener('click', () => {
xmlContentInput.value = sampleXml;
updateButtonStates();
});
// Assinatura Completa de XML
btnSignXmlFull.addEventListener('click', async () => {
btnSignXmlFull.disabled = true;
btnSignXmlFull.innerHTML = '<span class="spinner"></span> Assinando no Agente...';
xmlAlert.style.display = 'block';
xmlAlert.className = 'alert alert-info';
xmlAlert.textContent = 'Assinando XML no CyberCore Signer...';
try {
const xml = xmlContentInput.value.trim();
const profile = xmlProfileSelect.value;
const result = await signer.signXmlDocument({
certificateId: selectedCertificateId,
xml: xml,
profile: profile
});
xmlAlert.className = 'alert alert-success';
xmlAlert.textContent = `✓ XML assinado com sucesso via perfil ${result.profile || profile}!`;
currentSignedXml = result.signed_xml;
xmlSigOutput.textContent = result.signed_xml;
btnDownloadXml.style.display = 'inline-flex';
btnCopyXml.style.display = 'inline-flex';
} catch (err) {
xmlAlert.className = 'alert alert-error';
xmlAlert.textContent = 'Erro ao assinar XML: ' + err.message;
} finally {
btnSignXmlFull.disabled = false;
btnSignXmlFull.innerHTML = '<span>✍️</span> Assinar XML Completo no Agente';
}
});
// Assinatura via Digest de XML
btnSignXmlDigest.addEventListener('click', async () => {
btnSignXmlDigest.disabled = true;
btnSignXmlDigest.innerHTML = '<span class="spinner"></span> Solicitando...';
xmlAlert.style.display = 'block';
xmlAlert.className = 'alert alert-info';
xmlAlert.textContent = 'Assinando digest do XML no CyberCore Signer...';
try {
const result = await signer.signXml(xmlContentInput.value, {
certificateId: selectedCertificateId,
documentName: 'nfe-3526.xml'
});
xmlAlert.className = 'alert alert-success';
xmlAlert.textContent = `✓ Digest XML assinado com sucesso via ${result.algorithm}!`;
xmlSigOutput.textContent = result.signature;
} catch (err) {
xmlAlert.className = 'alert alert-error';
xmlAlert.textContent = 'Erro ao assinar digest do XML: ' + err.message;
} finally {
btnSignXmlDigest.disabled = false;
btnSignXmlDigest.innerHTML = '<span>🛡️</span> Apenas Digest';
}
});
// Download do XML Assinado
btnDownloadXml.addEventListener('click', () => {
if (!currentSignedXml) return;
const blob = new Blob([currentSignedXml], { type: 'application/xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'documento_assinado.xml';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
// Copiar XML
btnCopyXml.addEventListener('click', async () => {
if (!currentSignedXml) return;
await navigator.clipboard.writeText(currentSignedXml);
const origText = btnCopyXml.innerHTML;
btnCopyXml.innerHTML = '<span>✓</span> Copiado!';
setTimeout(() => { btnCopyXml.innerHTML = origText; }, 2000);
});
// =========================================================================
// ABA 3: LÓGICA DE ARQUIVOS GERAIS
// =========================================================================
const genDropZone = document.getElementById('genDropZone');
const genFileInput = document.getElementById('genFileInput');
const genFileMeta = document.getElementById('genFileMeta');
const genFileName = document.getElementById('genFileName');
const genFileSize = document.getElementById('genFileSize');
const genFileBadge = document.getElementById('genFileBadge');
const genDigestBox = document.getElementById('genDigestBox');
const btnSignGen = document.getElementById('btnSignGen');
const genAlert = document.getElementById('genAlert');
const genSigOutput = document.getElementById('genSigOutput');
const genMetaOutput = document.getElementById('genMetaOutput');
let currentGenFile = null;
let currentGenDigest = null;
genDropZone.addEventListener('click', () => genFileInput.click());
genFileInput.addEventListener('change', e => {
if (e.target.files.length) handleGenFileSelected(e.target.files[0]);
});
genDropZone.addEventListener('dragover', e => {
e.preventDefault();
genDropZone.classList.add('dragover');
});
genDropZone.addEventListener('dragleave', () => genDropZone.classList.remove('dragover'));
genDropZone.addEventListener('drop', e => {
e.preventDefault();
genDropZone.classList.remove('dragover');
if (e.dataTransfer.files.length) handleGenFileSelected(e.dataTransfer.files[0]);
});
async function handleGenFileSelected(file) {
currentGenFile = file;
genFileName.textContent = file.name;
genFileSize.textContent = (file.size / 1024).toFixed(1) + ' KB';
const ext = file.name.includes('.') ? file.name.split('.').pop().toUpperCase() : 'FILE';
genFileBadge.textContent = ext;
genFileMeta.style.display = 'flex';
const buffer = await file.arrayBuffer();
currentGenDigest = await signer._calculateSha256(buffer);
genDigestBox.textContent = `SHA-256: ${currentGenDigest}\nArquivo: ${file.name} (${file.type || 'binário'})`;
updateButtonStates();
}
btnSignGen.addEventListener('click', async () => {
btnSignGen.disabled = true;
btnSignGen.innerHTML = '<span class="spinner"></span> Solicitando no Agente...';
genAlert.style.display = 'block';
genAlert.className = 'alert alert-info';
genAlert.textContent = 'Confirme a assinatura na janela do CyberCore Signer...';
try {
const result = await signer.signFile(currentGenFile, {
certificateId: selectedCertificateId,
documentName: currentGenFile.name
});
genAlert.className = 'alert alert-success';
genAlert.textContent = `✓ Arquivo assinado com sucesso via ${result.algorithm}!`;
genSigOutput.textContent = result.signature;
genMetaOutput.textContent = JSON.stringify({
documentName: result.documentName,
documentType: result.documentType,
digest: result.digest,
algorithm: result.algorithm,
requestId: result.requestId
}, null, 2);
} catch (err) {
genAlert.className = 'alert alert-error';
genAlert.textContent = 'Erro ao assinar arquivo: ' + err.message;
} finally {
btnSignGen.disabled = false;
btnSignGen.innerHTML = '<span>✍️</span> Assinar Arquivo com CyberCore';
}
});
// =========================================================================
// ABA 4: LOGIN COM CERTIFICADO DIGITAL
// =========================================================================
const authChallengeInput = document.getElementById('authChallengeInput');
const btnNewChallenge = document.getElementById('btnNewChallenge');
const btnAuthLogin = document.getElementById('btnAuthLogin');
const authAlert = document.getElementById('authAlert');
const authUserCard = document.getElementById('authUserCard');
const authWaitBox = document.getElementById('authWaitBox');
const authUserAvatar = document.getElementById('authUserAvatar');
const authUserName = document.getElementById('authUserName');
const authUserCpf = document.getElementById('authUserCpf');
const authUserCertType = document.getElementById('authUserCertType');
const authSigOutput = document.getElementById('authSigOutput');
function generateNewAuthChallenge() {
const serverNonce = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
authChallengeInput.value = `cybercore-auth-v1:${Date.now()}:${serverNonce}`;
}
generateNewAuthChallenge();
btnNewChallenge.addEventListener('click', generateNewAuthChallenge);
btnAuthLogin.addEventListener('click', async () => {
btnAuthLogin.disabled = true;
btnAuthLogin.innerHTML = '<span class="spinner"></span> Autenticando...';
authAlert.style.display = 'block';
authAlert.className = 'alert alert-info';
authAlert.textContent = 'Confirme o Login na tela do CyberCore Signer (e digite seu PIN se token A3)...';
try {
const authResult = await signer.authenticate({
certificateId: selectedCertificateId,
challenge: authChallengeInput.value
});
authAlert.className = 'alert alert-success';
authAlert.textContent = '✓ Identidade validada! Sessão de usuário autenticada com sucesso.';
authWaitBox.style.display = 'none';
authUserCard.style.display = 'flex';
const name = authResult.subjectName || 'Titular do Certificado';
authUserName.textContent = name;
authUserCpf.textContent = authResult.subjectCpfCnpj ? `CPF/CNPJ: ${authResult.subjectCpfCnpj}` : 'ICP-Brasil Autenticado';
const initials = name.split(' ').map(p => p[0]).filter(Boolean).slice(0, 2).join('').toUpperCase();
authUserAvatar.textContent = initials || 'CC';
authSigOutput.textContent = `STATUS: AUTHENTICATED\nCHALLENGE: ${authResult.challenge}\nSIGNATURE: ${authResult.signature}\nCERT_HOLDER: ${name}`;
} catch (err) {
authAlert.className = 'alert alert-error';
authAlert.textContent = 'Falha no login com certificado: ' + err.message;
} finally {
btnAuthLogin.disabled = false;
btnAuthLogin.innerHTML = '<span>🔐</span> Entrar com Certificado Digital';
}
});
// Inicialização
checkAgentStatus();
</script>
</body>
</html>