feat: add SDK support for PDF document signing and visual seal customization tools

This commit is contained in:
Claudecio Martins
2026-10-11 18:34:47 -03:00
parent d8d2e6ee46
commit b46d8b665f
12 changed files with 3497 additions and 121 deletions
+421 -112
View File
@@ -7,6 +7,12 @@
<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;
@@ -615,10 +621,13 @@
<!-- Abas de Navegação -->
<div class="tabs-nav">
<button class="tab-btn active" data-tab="tab-pdf">
<span>📄</span> Assinar 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 (NF-e)
<span>📋</span> Assinar XML (XAdES / NF-e)
</button>
<button class="tab-btn" data-tab="tab-file">
<span>📁</span> Arquivos em Geral
@@ -628,19 +637,19 @@
</button>
</div>
<!-- ABA 1: ASSINAR PDF -->
<!-- ABA 1: ASSINAR PDF (INTERATIVO COM RETORNO EM BASE64) -->
<div id="tab-pdf" class="tab-pane active">
<div class="card-grid">
<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 PDF</span>
<span class="badge-tag">PAdES / Digest</span>
<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);">Suporta qualquer documento .pdf</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>
@@ -649,80 +658,157 @@
<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</span>
<span class="badge-tag">PDF Carregado</span>
</div>
<div class="form-group">
<label class="form-label">Digest SHA-256 Calculado no Navegador (Base64):</label>
<div id="pdfDigestBox" class="code-box">Selecione um arquivo PDF para calcular o digest...</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: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px;">
<div class="form-group">
<label class="form-label">Tema do Selo do Agente:</label>
<select id="pdfSealThemeSelect" class="cert-bar-select">
<option value="icp-brasil">ICP-Brasil Institucional (Padrão)</option>
<option value="gov-br">Governamental (Gov.br / ITI)</option>
<option value="cybercore-modern">CyberCore Moderno</option>
<option value="minimal-clean">Minimalista Clássico</option>
<option value="custom">🎨 Selo Customizado do Designer</option>
</select>
</div>
<div class="form-group">
<label class="form-label">Razão / Motivo da Assinatura:</label>
<input type="text" id="pdfReasonInput" value="Documento aprovado e assinado digitalmente" placeholder="Ex: De acordo com os termos">
</div>
<div class="form-group">
<label class="form-label">Localização:</label>
<input type="text" id="pdfLocationInput" value="Curitiba, PR - Brasil" placeholder="Ex: Brasília, DF">
</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>
<button id="btnSignPdf" class="btn btn-primary" style="padding: 12px;" disabled>
<span>✍️</span> Assinar PDF com CyberCore
</button>
<div id="pdfAlert" class="alert alert-info" style="display: none;"></div>
<div id="pdfAlert" class="alert alert-info" style="display: none; margin-top: 14px;"></div>
</div>
<div class="card">
<!-- Card de Resultado do PDF Assinado -->
<div id="pdfResultCard" class="card" style="display: none;">
<div class="card-header">
<span class="card-title"><span>🛡️</span> Resultado da Assinatura Digital</span>
<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">Assinatura Digital Retornada (Base64):</label>
<div id="pdfSigOutput" class="code-box" style="min-height: 120px;">Aguardando assinatura do PDF...</div>
</div>
<div class="form-group">
<label class="form-label">Cadeia do Certificado Digital X.509:</label>
<div id="pdfCertOutput" class="code-box">Nenhum certificado emitido ainda.</div>
<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: ASSINAR XML -->
<!-- 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 / XMLDSig)</span>
<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">Estrutura XML para Assinatura:</label>
<textarea id="xmlContentInput" rows="7" placeholder="Cole o XML ou selecione um arquivo..."></textarea>
<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">Digest SHA-256 Calculado no Navegador (Base64):</label>
<div id="xmlDigestBox" class="code-box">Aguardando XML...</div>
<label class="form-label">Estrutura XML para Assinatura:</label>
<textarea id="xmlContentInput" rows="8" placeholder="Cole o XML ou selecione um arquivo..."></textarea>
</div>
<button id="btnSignXml" class="btn btn-primary" style="padding: 12px;" disabled>
<span>✍️</span> Assinar XML com CyberCore
</button>
<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;"></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 (XMLDSig)</span>
<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">Bloco SignatureValue (Base64):</label>
<div id="xmlSigOutput" class="code-box" style="min-height: 120px;">Aguardando assinatura do XML...</div>
</div>
<div class="form-group">
<label class="form-label">Tag XMLDSig Incorporável:</label>
<div id="xmlTagOutput" class="code-box">&lt;Signature xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;...&lt;/Signature&gt;</div>
<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>
@@ -851,7 +937,7 @@
<!-- Lógica Javascript com o SDK -->
<script type="module">
import { CyberCoreSigner } from '../src/signer-sdk.js';
import { CyberCoreSigner, PdfStampPicker, PdfSealDesigner } from '../src/signer-sdk.js';
const signer = new CyberCoreSigner({
baseUrl: 'http://127.0.0.1:21325',
@@ -870,6 +956,16 @@
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');
@@ -879,7 +975,13 @@
tabButtons.forEach(b => b.classList.remove('active'));
tabPanes.forEach(p => p.classList.remove('active'));
btn.classList.add('active');
document.getElementById(btn.dataset.tab).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();
}
});
});
@@ -900,6 +1002,29 @@
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 {
@@ -913,7 +1038,7 @@
return;
}
certs.forEach((c, index) => {
certs.forEach((c) => {
const opt = document.createElement('option');
opt.value = c.id;
opt.textContent = `${c.common_name || c.alias} [${c.type}] (${c.device_name || c.provider_id})`;
@@ -949,10 +1074,24 @@
function updateButtonStates() {
const hasCert = Boolean(selectedCertificateId);
document.getElementById('btnSignPdf').disabled = !hasCert || !currentPdfDigest;
document.getElementById('btnSignXml').disabled = !hasCert || !currentXmlDigest;
document.getElementById('btnSignGen').disabled = !hasCert || !currentGenDigest;
document.getElementById('btnAuthLogin').disabled = !hasCert;
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
@@ -964,6 +1103,7 @@
statusDot.classList.add('online');
statusText.textContent = 'Conectado & Autorizado';
await loadCertificates();
await loadSealThemes();
} catch (err) {
alert('Erro ao conectar: ' + err.message);
} finally {
@@ -976,25 +1116,31 @@
const online = await checkAgentStatus();
if (online) {
await loadCertificates();
await loadSealThemes();
}
});
// =========================================================================
// ABA 1: LÓGICA DE PDF
// 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 pdfDigestBox = document.getElementById('pdfDigestBox');
const btnSignPdf = document.getElementById('btnSignPdf');
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 pdfSigOutput = document.getElementById('pdfSigOutput');
const pdfCertOutput = document.getElementById('pdfCertOutput');
let currentPdfFile = null;
let currentPdfDigest = null;
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 => {
@@ -1019,17 +1165,84 @@
pdfFileMeta.style.display = 'flex';
const buffer = await file.arrayBuffer();
currentPdfBytes = buffer;
currentPdfDigest = await signer._calculateSha256(buffer);
pdfDigestBox.textContent = `SHA-256 (Base64): ${currentPdfDigest}\nArquivo: ${file.name} (${file.size} bytes)`;
stampPickerMount.style.display = 'block';
pdfOptionsSection.style.display = 'block';
if (!pdfStampPicker) {
pdfStampPicker = new PdfStampPicker({
container: stampPickerMount,
pdfSource: buffer,
initialScale: 1.0,
onPositionChange: (pos) => {
console.log('Posição do selo atualizada:', pos);
}
});
} else {
pdfStampPicker.loadPdf(buffer);
}
updateButtonStates();
}
btnSignPdf.addEventListener('click', async () => {
btnSignPdf.disabled = true;
btnSignPdf.innerHTML = '<span class="spinner"></span> Solicitando no Agente...';
// 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 aberta no seu computador...';
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;
const signParams = {
certificateId: selectedCertificateId,
pdf: currentPdfBytes,
page: stampConfig.page,
x: stampConfig.x,
y: stampConfig.y,
scale: stampConfig.scale,
reason: document.getElementById('pdfReasonInput').value || 'Assinado Digitalmente',
location: document.getElementById('pdfLocationInput').value || 'Brasil'
};
if (selectedTheme === 'custom' && currentCustomSealConfig) {
signParams.seal_custom = currentCustomSealConfig;
} else {
signParams.seal_theme_id = selectedTheme === 'custom' ? 'icp-brasil' : selectedTheme;
}
const result = await signer.signPdfDocument(signParams);
pdfAlert.className = 'alert alert-success';
pdfAlert.textContent = '✓ Documento PDF assinado com sucesso via PAdES (ISO 32000)!';
currentSignedPdfBase64 = result.signed_pdf;
pdfResultCard.style.display = 'block';
pdfResultSize.textContent = (result.signed_pdf.length * 0.75 / 1024).toFixed(1) + ' KB';
pdfResultSha256.textContent = result.sha256 || 'Calculado com sucesso';
pdfResultBase64.textContent = result.signed_pdf;
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, {
@@ -1038,30 +1251,97 @@
});
pdfAlert.className = 'alert alert-success';
pdfAlert.textContent = `✓ Documento PDF assinado com sucesso via ${result.algorithm}!`;
pdfSigOutput.textContent = result.signature;
pdfCertOutput.textContent = result.certificate;
pdfAlert.textContent = `✓ Digest assinado com sucesso! Algoritmo: ${result.algorithm}`;
} catch (err) {
pdfAlert.className = 'alert alert-error';
pdfAlert.textContent = 'Erro ao assinar PDF: ' + err.message;
pdfAlert.textContent = 'Erro ao assinar digest: ' + err.message;
} finally {
btnSignPdf.disabled = false;
btnSignPdf.innerHTML = '<span>✍️</span> Assinar PDF com CyberCore';
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: LÓGICA DE XML
// ABA 2: DESIGNER DE SELOS VISUAIS
// =========================================================================
function initSealDesigner() {
const mount = document.getElementById('sealDesignerMount');
pdfSealDesigner = new PdfSealDesigner({
container: mount,
initialConfig: {
name: 'Selo Customizado',
title: 'ASSINADO DIGITALMENTE',
primary_color: '#0284c7',
secondary_color: '#10b981',
background_color: '#ffffff',
text_color: '#0f172a',
border_color: '#38bdf8',
icon_style: 'shield',
default_cpf_mode: 'MASKED',
default_include_date_time: true
},
onConfigChange: (cfg) => {
currentCustomSealConfig = cfg;
}
});
// 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';
// Alterna para aba PDF
document.querySelector('[data-tab="tab-pdf"]').click();
alert('Selo customizado selecionado para a assinatura do PDF!');
});
}
// =========================================================================
// ABA 3: LÓGICA DE XML (XAdES-BES & XMLDSig)
// =========================================================================
const xmlContentInput = document.getElementById('xmlContentInput');
const xmlDigestBox = document.getElementById('xmlDigestBox');
const btnSignXml = document.getElementById('btnSignXml');
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 xmlTagOutput = document.getElementById('xmlTagOutput');
let currentXmlDigest = null;
const btnDownloadXml = document.getElementById('btnDownloadXml');
const btnCopyXml = document.getElementById('btnCopyXml');
const sampleXml = `<nfeProc versao="4.00" xmlns="http://www.portalfiscal.inf.br/nfe">
<NFe>
@@ -1083,30 +1363,52 @@
</NFe>
</nfeProc>`;
async function updateXmlDigest() {
const xml = xmlContentInput.value.trim();
if (!xml) {
currentXmlDigest = null;
xmlDigestBox.textContent = 'Digite ou cole o XML para calcular o digest...';
} else {
currentXmlDigest = await signer._calculateSha256(xml);
xmlDigestBox.textContent = `SHA-256 Digest (Base64): ${currentXmlDigest}\nTamanho: ${xml.length} caracteres`;
}
updateButtonStates();
}
xmlContentInput.addEventListener('input', updateXmlDigest);
xmlContentInput.addEventListener('input', () => updateButtonStates());
btnLoadXmlSample.addEventListener('click', () => {
xmlContentInput.value = sampleXml;
updateXmlDigest();
updateButtonStates();
});
btnSignXml.addEventListener('click', async () => {
btnSignXml.disabled = true;
btnSignXml.innerHTML = '<span class="spinner"></span> Solicitando no Agente...';
// 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 = 'Confirme a assinatura na janela do CyberCore Signer...';
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, {
@@ -1115,33 +1417,40 @@
});
xmlAlert.className = 'alert alert-success';
xmlAlert.textContent = `✓ XML assinado com sucesso via ${result.algorithm}!`;
xmlAlert.textContent = `✓ Digest XML assinado com sucesso via ${result.algorithm}!`;
xmlSigOutput.textContent = result.signature;
const xmlSigSnippet = `<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
<Reference URI="#NFe35261012345678000199550010000001001234567890">
<DigestValue>${result.digest}</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>${result.signature.slice(0, 48)}...</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>${result.certificate.slice(0, 48)}...</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>`;
xmlTagOutput.textContent = xmlSigSnippet;
} catch (err) {
xmlAlert.className = 'alert alert-error';
xmlAlert.textContent = 'Erro ao assinar XML: ' + err.message;
xmlAlert.textContent = 'Erro ao assinar digest do XML: ' + err.message;
} finally {
btnSignXml.disabled = false;
btnSignXml.innerHTML = '<span>✍️</span> Assinar XML com CyberCore';
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
// =========================================================================