const $ = (selector) => document.querySelector(selector); const $$ = (selector) => [...document.querySelectorAll(selector)]; const PLANS = { single: { name: 'Relatório completo', amount: '29.90', display: 'R$ 29,90', projects: 1, scans: 1 }, pro: { name: 'Plano Pro · 30 dias', amount: '79.00', display: 'R$ 79,00', projects: 10, scans: 100, days: 30 }, team: { name: 'Plano Team · 30 dias', amount: '299.00', display: 'R$ 299,00', projects: 50, scans: 1500, days: 30 }, }; const API_URL = String(window.huggingface?.variables?.KONAET_API_URL || '').replace(/\/$/, ''); const SEVERITY_LABELS = { critical: 'CRÍTICO', high: 'ALTO', medium: 'MÉDIO', low: 'BAIXO' }; const HEALTH_LABELS = { testing: 'Testes', documentation: 'Documentação', maintenance: 'Manutenção', security: 'Segurança', automation: 'Automação' }; let lastRepository = ''; let lastAnalysis = null; let currentCheckout = null; let accountOverview = null; let serverHistory = []; let serverAccessVerified = false; let reportIntegrity = ''; let lastScanId = ''; let externalBridge = null; let paymentPoll = null; function oauthSession() { try { return JSON.parse(localStorage.getItem('konaet-xray-oauth')); } catch { return null; } } async function apiRequest(path, options = {}) { if (!API_URL) throw new Error('O servidor da conta não está configurado.'); const oauth = oauthSession(); if (!oauth?.accessToken) throw new Error('Entre novamente para acessar sua conta.'); const response = await fetch(`${API_URL}${path}`, { ...options, headers: { authorization: `Bearer ${oauth.accessToken}`, ...(options.body ? { 'content-type': 'application/json' } : {}), ...options.headers }, cache: 'no-store', }); let data = {}; try { data = await response.json(); } catch {} if (!response.ok) { const messages = { scan_limit_reached: 'O limite de leituras deste plano foi atingido.', repository_limit_reached: 'O limite de repositórios deste plano foi atingido.', repository_not_covered: `Este relatório pertence a ${data.repository || 'outro repositório'}.`, member_limit_reached: 'A equipe já atingiu o limite de cinco contas.', invite_unavailable: 'Este convite não existe, venceu ou já foi usado.', team_plan_inactive: 'O plano Team deste convite não está ativo.', plan_expired: 'Este plano terminou. Renove para abrir o relatório completo.', repository_not_public: 'Esse repositório não está público no GitHub. Repositórios privados ainda não são aceitos no Lab.', repository_too_large: 'O GitHub devolveu uma lista incompleta. Use o Core local para esse repositório grande.', github_unavailable: 'O GitHub não respondeu. Tente novamente mais tarde, sem perder uma leitura.', github_rate_limited: 'O GitHub limitou temporariamente as consultas. Tente mais tarde; sua leitura não foi consumida.', invalid_checkout: 'Confira o e-mail e os dados do plano.', automatic_payment_unavailable: 'O pagamento automático ainda não está configurado.', payment_provider_unavailable: 'O Mercado Pago não respondeu. Tente novamente em alguns instantes.', invalid_provider_response: 'O provedor não devolveu um Pix válido. Nenhuma cobrança foi criada.', guest_scan_used: 'Esta análise gratuita já foi usada. Entre para continuar com sua conta.', origin_not_allowed: 'Abra o Konaet X-Ray pelo endereço oficial para fazer a análise.', public_scan_unavailable: 'A análise segura está temporariamente indisponível.', }; const error = new Error(messages[data.error] || 'Não foi possível concluir esta operação agora.'); error.code = data.error; error.data = data; throw error; } return data; } function clamp(value, minimum = 0, maximum = 100) { return Math.max(minimum, Math.min(maximum, Math.round(value))); } function repositoryName(value) { const match = String(value).trim().replace(/\.git$/, '').match(/^(?:https?:\/\/github\.com\/)?([\w.-]+)\/([\w.-]+)\/?$/); if (!match) throw new Error('Cole um link válido do GitHub.'); return `${match[1]}/${match[2]}`; } async function analyze(value) { if (!API_URL) throw new Error('A análise segura está temporariamente indisponível.'); const requestId = crypto.randomUUID ? crypto.randomUUID() : `guest_${Date.now()}_${Math.random().toString(36).slice(2)}`; const body = JSON.stringify({ repository: repositoryName(value), clientRequestId: requestId }); for (let attempt = 0; attempt < 3; attempt += 1) { let response; try { response = await fetch(`${API_URL}/api/public/scans`, { method: 'POST', headers: { 'content-type': 'application/json' }, body, cache: 'no-store', }); } catch { if (attempt < 2) { await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1))); continue; } throw new Error('Não foi possível conectar à análise segura. Confira a conexão e tente novamente.'); } let data = {}; try { data = await response.json(); } catch {} if (response.ok) { if (!data.scan?.report) throw new Error('O servidor devolveu uma resposta incompleta. Tente novamente.'); return { ...data.scan.report, verifiedByServer: true }; } if ([502, 503, 504].includes(response.status) && data.error !== 'github_rate_limited' && attempt < 2) { await new Promise((resolve) => setTimeout(resolve, 500 * (attempt + 1))); continue; } const messages = { guest_scan_used: 'Esta análise gratuita já foi usada. Entre para continuar com sua conta.', repository_not_public: 'Repositório não encontrado ou privado.', repository_too_large: 'Esse repositório é grande demais para a demonstração. Use o Core para uma leitura completa.', github_unavailable: 'O GitHub não respondeu à análise agora. Tente novamente em alguns instantes.', github_rate_limited: 'O GitHub limitou temporariamente as consultas. Tente mais tarde; sua análise grátis não foi consumida.', public_scan_unavailable: 'A análise segura está temporariamente indisponível.', origin_not_allowed: 'Abra o Konaet X-Ray pelo endereço oficial para fazer a análise.', invalid_scan: 'Confira o link do repositório e tente novamente.', }; throw new Error(messages[data.error] || `Não foi possível concluir a análise (HTTP ${response.status}${data.error ? `, ${data.error}` : ''}). Tente novamente.`); } } function signedAccount() { try { const oauth = JSON.parse(localStorage.getItem('konaet-xray-oauth')); const info = oauth?.userInfo; if (!info) return null; return { id: String(info.sub || info.preferred_username || info.name), name: info.preferred_username || info.name || 'Conta Hugging Face', avatar: info.picture || '', email: info.email || '' }; } catch { return null; } } function purchaseStorageKey() { const account = signedAccount(); return account ? `konaet-xray-purchase:${account.id}` : 'konaet-xray-last-purchase'; } function savedPurchase() { try { const account = signedAccount(); let purchase = JSON.parse(localStorage.getItem(purchaseStorageKey())); if (account && !purchase) { const legacy = JSON.parse(localStorage.getItem('konaet-xray-last-purchase')); if (legacy && !legacy.accountId) { purchase = { ...legacy, accountId: account.id, accountName: account.name }; localStorage.setItem(purchaseStorageKey(), JSON.stringify(purchase)); localStorage.removeItem('konaet-xray-last-purchase'); } } return purchase && PLANS[purchase.planId] && /^KX[A-Z0-9]+$/.test(purchase.reference) ? purchase : null; } catch { return null; } } function storePurchase(purchase) { const account = signedAccount(); const owned = account ? { ...purchase, accountId: account.id, accountName: account.name } : purchase; localStorage.setItem(purchaseStorageKey(), JSON.stringify(owned)); return owned; } function purchaseIsActive(purchase) { if (purchase?.status !== 'approved') return false; if (!purchase.expiresAt) return true; return new Date(purchase.expiresAt) > new Date(); } function renderPurchase(purchase) { if (!purchase) { $('#purchase-summary').hidden = true; return; } const active = purchaseIsActive(purchase); const approved = purchase.status === 'approved'; $('#purchase-description').textContent = `${PLANS[purchase.planId].name} · ${PLANS[purchase.planId].display}`; $('#purchase-reference').textContent = `Referência ${purchase.reference}`; $('#purchase-title').textContent = active ? 'Pagamento aprovado' : approved ? 'Acesso encerrado' : 'Compra registrada'; $('#purchase-status').textContent = active ? purchase.planId === 'single' ? `Uma leitura completa de ${purchase.approvedRepository || purchase.repository || 'um repositório'}, sem prazo para consultar o relatório salvo.` : `Acesso até ${new Date(purchase.expiresAt).toLocaleString('pt-BR')}.` : approved ? 'O período deste plano terminou.' : purchase.provider === 'mercadopago' ? 'Aguardando o Mercado Pago confirmar o Pix automaticamente.' : 'Aguardando confirmação da entrada na conta Konaet.'; $('#resume-purchase').textContent = active ? (lastAnalysis ? 'Abrir relatório' : 'Usar compra') : approved ? 'Renovar plano' : 'Ver pagamento'; $('#purchase-summary').classList.toggle('pending', !active); $('#purchase-summary').hidden = false; renderFullReport(); } function syncPurchaseFromAccess(access) { serverAccessVerified = Boolean(access?.purchase?.active); if (!serverAccessVerified || !PLANS[access.plan?.id]) { renderFullReport(); return savedPurchase(); } const current = savedPurchase(); const updated = storePurchase({ ...(current?.reference === access.purchase.reference ? current : {}), reference: access.purchase.reference, planId: access.plan.id, amount: access.purchase.amount, repository: access.purchase.repository || current?.repository || 'não informado', status: 'approved', approvedAt: access.purchase.approved_at, expiresAt: access.purchase.expires_at, approvedRepository: access.purchase.repository || null, role: access.role, teamId: access.teamId, }); renderPurchase(updated); return updated; } function renderServerHistory() { const targets = [$('#server-history'), $('#history-list')].filter(Boolean); targets.forEach((target) => target.replaceChildren()); if (!serverHistory.length) { targets.forEach((target) => { const empty = document.createElement('p'); empty.className = 'muted'; empty.textContent = 'Nenhuma leitura salva nesta conta ainda.'; target.append(empty); }); return; } serverHistory.forEach((item) => { targets.forEach((target) => { const row = document.createElement('button'); row.type = 'button'; row.className = 'history-button'; row.dataset.scanId = item.id; const name = document.createElement('strong'); name.textContent = item.repository; const score = document.createElement('span'); score.textContent = `${item.score}/100 · ${new Date(item.createdAt).toLocaleString('pt-BR')}`; const delta = document.createElement('span'); delta.textContent = item.delta == null ? 'primeira leitura' : `${item.delta > 0 ? '+' : ''}${item.delta} pontos`; if (item.delta > 0) delta.className = 'trend-up'; if (item.delta < 0) delta.className = 'trend-down'; row.append(name, score, delta); row.addEventListener('click', () => openSavedScan(item.id)); target.append(row); }); }); } function renderAccountTrend() { const chart = $('#account-trend'); chart.replaceChildren(); const recent = serverHistory.slice(0, 12).reverse(); if (!recent.length) { const empty = document.createElement('span'); empty.className = 'muted small'; empty.textContent = 'As notas das próximas leituras aparecerão neste gráfico.'; chart.append(empty); return; } recent.forEach((item) => { const column = document.createElement('div'); column.className = 'trend-column'; column.title = `${item.repository}: ${item.score}/100`; const bar = document.createElement('i'); bar.style.height = `${Math.max(3, Number(item.score))}%`; const label = document.createElement('span'); label.textContent = item.repository.split('/').pop(); column.append(bar, label); chart.append(column); }); } function renderAccountAccess(access) { const plan = access.plan; const expiresAt = access.purchase?.expires_at ? new Date(access.purchase.expires_at) : null; const milliseconds = expiresAt ? Math.max(0, expiresAt.getTime() - Date.now()) : 0; const daysLeft = expiresAt ? Math.ceil(milliseconds / 86400000) : null; $('#account-access-title').textContent = `${plan.name} ativo`; $('#account-days-left').textContent = daysLeft == null ? 'Sem prazo' : `${daysLeft} dia${daysLeft === 1 ? '' : 's'} restante${daysLeft === 1 ? '' : 's'}`; const duration = plan.days || 0; $('#account-access-progress').style.width = duration ? `${Math.max(0, Math.min(100, (daysLeft / duration) * 100))}%` : '100%'; const benefits = plan.id === 'free' ? ['3 leituras básicas por mês', 'Até 3 alertas', 'Sem relatório detalhado'] : plan.id === 'single' ? ['1 repositório', '1 leitura completa', 'Relatório salvo sem vencimento', 'VCR-1 e prova JSON verificável', 'PDF e plano de correção'] : plan.id === 'pro' ? ['10 repositórios', '100 leituras completas', 'Histórico de 90 dias', 'Comparação entre commits', 'VCR-1 em cada leitura', 'Evidências, hotspots, prova JSON e PDF'] : ['50 repositórios', '1.500 leituras completas', '5 contas por convite', 'Histórico compartilhado de 365 dias', 'VCR-1 em cada leitura', 'Workspace, limites e resultados compartilhados']; const list = $('#account-benefits'); list.replaceChildren(); benefits.forEach((benefit) => { const item = document.createElement('li'); item.textContent = benefit; list.append(item); }); } function renderTeam(team, access) { const ownerTools = $('#team-owner-tools'); $('#team-status').textContent = ''; if (!team) { $('#team-title').textContent = 'Entrar em uma equipe'; $('#team-description').textContent = 'Cole um código de convite do titular do Team para compartilhar limites e histórico.'; ownerTools.hidden = true; $('#accept-invite-form').hidden = false; return; } $('#team-title').textContent = team.name; $('#team-description').textContent = `${team.members.length}/${access.plan.limits.members} contas conectadas · histórico e limites compartilhados.`; $('#accept-invite-form').hidden = true; ownerTools.hidden = access.role !== 'owner'; if (access.role !== 'owner') return; const box = $('#team-members'); box.replaceChildren(); team.members.forEach((member) => { const row = document.createElement('div'); row.className = 'team-member'; const label = document.createElement('div'); const name = document.createElement('strong'); name.textContent = member.account_name; const role = document.createElement('span'); role.textContent = member.role === 'owner' ? 'Titular' : 'Membro'; label.append(name, role); row.append(label); if (member.role !== 'owner') { const remove = document.createElement('button'); remove.className = 'text-button'; remove.type = 'button'; remove.textContent = 'Remover'; remove.addEventListener('click', () => removeTeamMember(member.id)); row.append(remove); } box.append(row); }); (team.invites || []).forEach((invite) => { const row = document.createElement('div'); row.className = 'team-member'; const label = document.createElement('div'); const name = document.createElement('strong'); name.textContent = invite.label || 'Convite pendente'; const state = document.createElement('span'); state.textContent = `Convite até ${new Date(invite.expires_at).toLocaleDateString('pt-BR')}`; label.append(name, state); const revoke = document.createElement('button'); revoke.className = 'text-button'; revoke.type = 'button'; revoke.textContent = 'Cancelar'; revoke.addEventListener('click', () => revokeTeamInvite(invite.id)); row.append(label, revoke); box.append(row); }); } function renderAccountDashboard(data) { accountOverview = data; const access = data.access; const plan = access.plan; $('#account-dashboard').hidden = false; $('#dashboard-plan').textContent = plan.name; $('#dashboard-role').textContent = access.role === 'owner' ? 'Titular' : 'Membro da equipe'; $('#dashboard-scans').textContent = `${access.usage.scans}/${plan.limits.scans}`; $('#dashboard-repositories').textContent = `${access.usage.repositories}/${plan.limits.repositories}`; $('#dashboard-history-count').textContent = String(serverHistory.length); $('#dashboard-renewal').textContent = access.purchase?.expires_at ? new Date(access.purchase.expires_at).toLocaleDateString('pt-BR') : 'Não vence'; $('#dashboard-validity').textContent = access.purchase ? access.purchase.expires_at ? `Acesso liberado até ${new Date(access.purchase.expires_at).toLocaleString('pt-BR')}.` : `Compra única para ${access.purchase.repository || 'um repositório'}: a leitura comprada fica disponível sem vencimento.` : `${access.remaining.scans} leituras básicas restantes neste mês.`; renderAccountAccess(access); syncPurchaseFromAccess(access); renderTeam(data.team, access); renderAccountTrend(); renderServerHistory(); } async function loadAccountDashboard() { if (!signedAccount() || !API_URL) { $('#account-dashboard').hidden = true; return; } try { const [overview, history] = await Promise.all([apiRequest('/api/account'), apiRequest('/api/scans')]); serverHistory = history.scans || []; renderAccountDashboard(overview); } catch (error) { $('#team-status').textContent = error.message; } } async function openSavedScan(scanId) { try { resetExternalBridge(); $('#status').textContent = 'Abrindo relatório salvo…'; const data = await apiRequest(`/api/scans/${encodeURIComponent(scanId)}`); reportIntegrity = data.scan.reportHash || ''; lastScanId = data.scan.id || scanId; lastAnalysis = { ...data.scan.report, verifiedByServer: true }; lastRepository = data.scan.repository; $('#repository').value = lastRepository; renderPreview(lastAnalysis); renderFullReport(); $('#status').textContent = 'Relatório salvo aberto.'; (purchaseIsActive(savedPurchase()) ? $('#full-report') : $('#result')).scrollIntoView({ behavior: 'smooth' }); } catch (error) { $('#status').textContent = error.message; } } async function removeTeamMember(memberId) { try { await apiRequest(`/api/team/members/${encodeURIComponent(memberId)}`, { method: 'DELETE' }); $('#team-status').textContent = 'Conta removida da equipe.'; await loadAccountDashboard(); } catch (error) { $('#team-status').textContent = error.message; } } async function revokeTeamInvite(inviteId) { try { await apiRequest(`/api/team/invites/${encodeURIComponent(inviteId)}`, { method: 'DELETE' }); $('#team-status').textContent = 'Convite cancelado.'; await loadAccountDashboard(); } catch (error) { $('#team-status').textContent = error.message; } } async function loadApprovals() { try { let purchase = savedPurchase(); const oauth = JSON.parse(localStorage.getItem('konaet-xray-oauth')); if (API_URL) { if (!oauth?.accessToken) return; const accountResponse = await fetch(`${API_URL}/api/entitlements/current`, { headers: { authorization: `Bearer ${oauth.accessToken}` }, cache: 'no-store', }); if (accountResponse.ok) { const accountData = await accountResponse.json(); const planPriority = { team: 3, pro: 2, single: 1 }; const serverPurchases = (accountData.purchases || []).filter((item) => PLANS[item.plan_id]); const selected = serverPurchases.find((item) => item.reference === purchase?.reference && item.active) || serverPurchases.filter((item) => item.active).sort((left, right) => planPriority[right.plan_id] - planPriority[left.plan_id])[0] || serverPurchases.find((item) => item.reference === purchase?.reference) || serverPurchases[0]; if (selected) { serverAccessVerified = Boolean(selected.active); purchase = storePurchase({ ...(purchase?.reference === selected.reference ? purchase : {}), reference: selected.reference, planId: selected.plan_id, amount: selected.amount, repository: selected.repository || purchase?.repository || 'não informado', status: selected.status, reportedAt: selected.created_at, approvedAt: selected.approved_at, expiresAt: selected.expires_at, approvedRepository: selected.repository || null, provider: selected.provider || 'direct_pix', }); renderPurchase(purchase); } else { serverAccessVerified = false; renderFullReport(); } } if (!purchase) return; const response = await fetch(`${API_URL}/api/entitlements?reference=${encodeURIComponent(purchase.reference)}`, { headers: { authorization: `Bearer ${oauth.accessToken}` }, cache: 'no-store', }); if (!response.ok) { serverAccessVerified = false; renderFullReport(); return; } const approved = await response.json(); serverAccessVerified = Boolean(approved.active); if (approved.active) { const updated = storePurchase({ ...purchase, status: 'approved', approvedAt: approved.approved_at, expiresAt: approved.expires_at, approvedRepository: approved.repository || null }); renderPurchase(updated); } renderFullReport(); return; } serverAccessVerified = false; renderFullReport(); } catch { // A página continua navegável, mas nunca libera acesso pago sem resposta do servidor. } } function entitlementFor(repository) { const purchase = savedPurchase(); if (API_URL && !serverAccessVerified) return { allowed: false, purchase }; if (API_URL && !lastAnalysis?.verifiedByServer) return { allowed: false, purchase }; if (!purchaseIsActive(purchase)) return { allowed: false, purchase }; const plan = PLANS[purchase.planId]; const repositories = purchase.repositories || []; if (API_URL) { if (purchase.planId === 'single' && purchase.approvedRepository && purchase.approvedRepository.toLowerCase() !== repository.toLowerCase()) { return { allowed: false, purchase, reason: `Este relatório foi comprado para ${purchase.approvedRepository}.` }; } return { allowed: true, purchase, plan }; } if (purchase.planId === 'single') { const bound = purchase.approvedRepository || purchase.boundRepository; if (bound && bound.toLowerCase() !== repository.toLowerCase()) return { allowed: false, purchase, reason: `Este relatório foi comprado para ${bound}.` }; if (!bound) storePurchase({ ...purchase, boundRepository: repository, repositories: [repository] }); return { allowed: true, purchase: savedPurchase(), plan }; } if (!repositories.some((item) => item.toLowerCase() === repository.toLowerCase())) { if (repositories.length >= plan.projects) return { allowed: false, purchase, reason: `O limite de ${plan.projects} repositórios deste plano foi atingido.` }; storePurchase({ ...purchase, repositories: [...repositories, repository] }); } return { allowed: true, purchase: savedPurchase(), plan }; } function createBar(label, value, suffix = '/100') { const row = document.createElement('div'); row.className = 'bar-row'; const name = document.createElement('span'); name.textContent = label; const track = document.createElement('div'); track.className = 'bar-track'; const fill = document.createElement('div'); fill.className = `bar-fill ${value >= 75 ? 'good' : value >= 50 ? 'warn' : 'bad'}`; fill.style.width = `${clamp(value)}%`; track.append(fill); const number = document.createElement('strong'); number.textContent = `${Math.round(value)}${suffix}`; row.append(name, track, number); return row; } function renderHealth(target, health) { const box = $(target); box.replaceChildren(); Object.entries(health).forEach(([key, value]) => box.append(createBar(HEALTH_LABELS[key], value))); } function renderPreview(analysis) { $('#result-name').textContent = analysis.name; $('#result-summary').textContent = analysis.summary; $('#score').textContent = analysis.score; $('#score-ring').style.setProperty('--score', analysis.score); $('#files').textContent = analysis.files; $('#source').textContent = analysis.source; $('#tests').textContent = analysis.tests; $('#risk-count').textContent = analysis.findings.length; renderHealth('#preview-health', analysis.health); const box = $('#preview-findings'); box.replaceChildren(); const visible = analysis.findings.slice(0, 3); if (!visible.length) { const item = document.createElement('p'); item.className = 'preview-finding'; item.textContent = 'Nenhum alerta relevante foi encontrado nesta leitura.'; box.append(item); } else { visible.forEach((item) => { const paragraph = document.createElement('p'); paragraph.className = `preview-finding ${item.severity}`; paragraph.textContent = `${SEVERITY_LABELS[item.severity]} · ${item.title}`; box.append(paragraph); }); } $('#result').hidden = false; } function renderTechnologyChart(technologies) { const box = $('#technology-chart'); box.replaceChildren(); const maximum = Math.max(...technologies.map((item) => item.bytes), 1); technologies.forEach((item) => box.append(createBar(item.name, item.bytes / maximum * 100, ` · ${item.files}`))); if (!technologies.length) box.textContent = 'Nenhum arquivo de código reconhecido.'; } function renderSeverityChart(counts) { const box = $('#severity-chart'); box.replaceChildren(); const maximum = Math.max(...Object.values(counts), 1); Object.entries(counts).forEach(([key, value]) => box.append(createBar(SEVERITY_LABELS[key], value / maximum * 100, ` · ${value}`))); } function renderDetailedFindings(findings) { const box = $('#detailed-findings'); box.replaceChildren(); $('#finding-total').textContent = `${findings.length} achado(s)`; if (!findings.length) { const empty = document.createElement('p'); empty.textContent = 'Nenhum risco relevante foi encontrado pelos critérios desta leitura.'; box.append(empty); return; } findings.forEach((item) => { const card = document.createElement('article'); card.className = 'finding-card'; const badge = document.createElement('span'); badge.className = `severity ${item.severity}`; badge.textContent = SEVERITY_LABELS[item.severity]; const content = document.createElement('div'); const title = document.createElement('h4'); title.textContent = item.title; const why = document.createElement('p'); why.textContent = item.why; content.append(title, why); if (item.files.length) { const files = document.createElement('div'); files.className = 'finding-files'; files.textContent = `Evidência: ${item.files.join(' · ')}`; content.append(files); } const fix = document.createElement('div'); fix.className = 'fix-box'; fix.textContent = `Como corrigir: ${item.fix}`; content.append(fix); card.append(badge, content); box.append(card); }); } function renderActionPlan(actions) { const list = $('#action-plan'); list.replaceChildren(); actions.forEach((item) => { const row = document.createElement('li'); const title = document.createElement('strong'); title.textContent = `${SEVERITY_LABELS[item.severity]} · ${item.title}`; const text = document.createElement('div'); text.textContent = item.action; row.append(title, text); list.append(row); }); } function renderDecisionMatrix(decision) { const block = $('#decision-matrix-block'); if (!decision?.candidates?.length) { block.hidden = true; return; } block.hidden = false; $('#decision-matrix-summary').textContent = `${decision.candidates.length} opção(ões) comparadas · ${decision.coverage}% dos arquivos de código entraram na leitura interna.`; $('#decision-matrix-limits').textContent = decision.limitations; const box = $('#decision-matrix'); box.replaceChildren(); decision.candidates.slice(0, 8).forEach((candidate) => { const row = document.createElement('div'); row.className = 'decision-row'; const title = document.createElement('strong'); title.textContent = candidate.title; row.append(title); for (const [label, value] of [['Prioridade', candidate.priority], ['Impacto', candidate.impact], ['Confiança', candidate.confidence], ['Esforço', candidate.effort]]) { const metric = document.createElement('div'); metric.className = 'decision-score'; const name = document.createElement('span'); name.textContent = label; const score = document.createElement('b'); score.textContent = `${value}/100`; metric.append(name, score); row.append(metric); } box.append(row); }); } function renderRepairProof(proof) { const block = $('#repair-proof-block'); if (!proof?.candidates) { block.hidden = true; return; } block.hidden = false; const verification = $('#proof-verification'); verification.className = 'proof-verification'; verification.textContent = lastScanId ? 'Verificação da conta ainda não executada.' : 'Este plano ainda não está vinculado a uma leitura salva na conta.'; $('#verify-repair-proof').disabled = !lastScanId; $('#repair-proof-summary').textContent = `${proof.summary.total} correção(ões) avaliadas · ${proof.summary.blocked} bloqueada(s) para automação · ${proof.summary.humanReview} exigem revisão humana.`; $('#repair-proof-hash').textContent = proof.proofHash; $('#repair-state-root').textContent = proof.sourceStateRoot; $('#repair-proof-limits').textContent = proof.limitations; const list = $('#repair-list'); list.replaceChildren(); proof.candidates.slice(0, 8).forEach((candidate) => { const card = document.createElement('article'); card.className = `repair-card ${candidate.verdict === 'bloquear_automacao' ? 'blocked' : candidate.verdict === 'revisao_humana_obrigatoria' ? 'review' : ''}`; const title = document.createElement('h4'); title.textContent = candidate.title; const recommendation = document.createElement('p'); recommendation.textContent = candidate.recommendation; const meta = document.createElement('div'); meta.className = 'repair-meta'; for (const value of [`Decisão: ${candidate.verdict.replaceAll('_', ' ')}`, `Impacto ${candidate.impact}/100`, `Confiança ${candidate.confidence}/100`]) { const tag = document.createElement('span'); tag.textContent = value; meta.append(tag); } const affected = document.createElement('p'); affected.className = 'muted small'; affected.textContent = `Arquivos diretos: ${candidate.directlyAffected.join(', ') || 'não identificados'}${candidate.potentiallyAffected.length ? ` · Possíveis dependentes: ${candidate.potentiallyAffected.join(', ')}` : ''}`; const checks = document.createElement('ul'); candidate.requiredChecks.forEach((check) => { const item = document.createElement('li'); item.textContent = check; checks.append(item); }); card.append(title, recommendation, meta, affected, checks); list.append(card); }); } function resetExternalBridge() { externalBridge = null; $('#external-artifacts').value = ''; $('#external-bridge-results').replaceChildren(); $('#external-bridge-status').className = 'proof-verification'; $('#external-bridge-status').textContent = 'Nenhum relatório externo importado nesta sessão.'; $('#download-external-bridge').hidden = true; } function renderExternalBridge() { const box = $('#external-bridge-results'); box.replaceChildren(); if (!externalBridge) return; const counts = { critical: 0, high: 0, medium: 0, low: 0 }; for (const finding of externalBridge.findings) counts[finding.severity] += 1; const summary = document.createElement('article'); const title = document.createElement('strong'); title.textContent = `${externalBridge.findings.length} sinal(is) · ${externalBridge.artifacts.length} arquivo(s)`; const description = document.createElement('span'); description.textContent = `Críticos ${counts.critical} · Altos ${counts.high} · Médios ${counts.medium} · Baixos ${counts.low}. Origem declarada, sem verificação do commit.`; summary.append(title, description); box.append(summary); for (const finding of externalBridge.findings.slice(0, 40)) { const row = document.createElement('article'); const heading = document.createElement('strong'); heading.textContent = `${SEVERITY_LABELS[finding.severity]} · ${finding.engine} · ${finding.ruleId}`; const detail = document.createElement('span'); detail.textContent = `${finding.title}${finding.file ? ` · ${finding.file}${finding.line ? `:${finding.line}` : ''}` : ''}`; row.append(heading, detail); box.append(row); } if (externalBridge.findings.length > 40) { const more = document.createElement('p'); more.className = 'muted small'; more.textContent = `Exibindo 40 sinais. Baixe o resumo para ver os ${externalBridge.findings.length} registros higienizados.`; box.append(more); } } function renderHotspots(hotspots) { const body = $('#hotspot-body'); body.replaceChildren(); hotspots.forEach((item) => { const row = document.createElement('tr'); const path = document.createElement('td'); path.textContent = item.path; const size = document.createElement('td'); size.textContent = `${Math.max(1, Math.round(item.size / 1024))} KB${item.lines ? ` · ${item.lines} linhas` : ''}`; const signals = document.createElement('td'); signals.textContent = item.signals.length ? item.signals.join(', ') : 'tamanho/estrutura'; const priority = document.createElement('td'); priority.textContent = item.priority >= 70 ? 'Alta' : item.priority >= 40 ? 'Média' : 'Baixa'; row.append(path, size, signals, priority); body.append(row); }); } function renderEvolution(analysis) { const box = $('#evolution-block'); const evolution = analysis.evolution; if (!evolution) { box.hidden = true; return; } box.hidden = false; $('#evolution-summary').textContent = `Nota ${evolution.previousScore}/100 → ${analysis.score}/100 (${evolution.scoreDelta > 0 ? '+' : ''}${evolution.scoreDelta} pontos). Commit anterior: ${(evolution.previousCommit || 'não informado').slice(0, 12)}. Não indica causa da mudança da nota.`; const groups = $('#evolution-files'); groups.replaceChildren(); for (const [label, key] of [['Adicionados', 'added'], ['Alterados', 'modified'], ['Removidos', 'removed']]) { const container = document.createElement('div'); const count = document.createElement('strong'); count.textContent = evolution[key].count; const title = document.createElement('span'); title.textContent = label; container.append(count, title); for (const file of evolution[key].sample) { const path = document.createElement('code'); path.textContent = file; container.append(path); } groups.append(container); } const affected = evolution.potentiallyAffected || []; $('#evolution-limits').textContent = affected.length ? `${affected.length} possível(is) dependente(s) pelos imports observados: ${affected.join(', ')}. ${evolution.partial ? 'Amostra incompleta, outros impactos são desconhecidos.' : 'É um indício, não prova de impacto em execução.'}` : 'Nenhum dependente apareceu nos imports lidos. A análise é parcial e não exclui impacto em outros arquivos.'; } function historyStorageKey() { const account = signedAccount(); return account ? `konaet-xray-history:${account.id}` : null; } function recordHistory(analysis, planId) { if (API_URL || !['pro', 'team'].includes(planId)) return; const key = historyStorageKey(); if (!key) return; try { const history = JSON.parse(localStorage.getItem(key)) || []; const entry = { name: analysis.name, score: analysis.score, scannedAt: analysis.scannedAt }; const next = [entry, ...history.filter((item) => item.name !== entry.name || item.scannedAt !== entry.scannedAt)].slice(0, 20); localStorage.setItem(key, JSON.stringify(next)); } catch { // Histórico é opcional e local. } } function renderHistory(planId) { const block = $('#history-block'); if (!['single', 'pro', 'team'].includes(planId)) { block.hidden = true; return; } block.hidden = false; if (API_URL && signedAccount()) { renderServerHistory(); return; } const list = $('#history-list'); list.replaceChildren(); let history = []; try { history = JSON.parse(localStorage.getItem(historyStorageKey())) || []; } catch { history = []; } history.forEach((item) => { const row = document.createElement('div'); row.className = 'history-item'; const name = document.createElement('strong'); name.textContent = item.name; const details = document.createElement('span'); details.textContent = `${item.score}/100 · ${new Date(item.scannedAt).toLocaleString('pt-BR')}`; row.append(name, details); list.append(row); }); } function renderFullReport() { if (!lastAnalysis || lastAnalysis.preview) { $('#full-report').hidden = true; return; } const entitlement = entitlementFor(lastAnalysis.name); if (!entitlement.allowed) { $('#full-report').hidden = true; if (entitlement.reason) $('#status').textContent = entitlement.reason; return; } const purchase = entitlement.purchase; $('#full-report-title').textContent = `Análise completa · ${lastAnalysis.name}`; $('#full-report-summary').textContent = lastAnalysis.summary; $('#full-health').textContent = `${lastAnalysis.score}/100`; $('#full-high').textContent = lastAnalysis.severityCounts.critical + lastAnalysis.severityCounts.high; $('#full-inspected').textContent = `${lastAnalysis.inspected}/${lastAnalysis.source}`; $('#full-plan').textContent = PLANS[purchase.planId].name.replace(' · 30 dias', ''); $('#report-provenance').textContent = lastAnalysis.commit ? `GitHub ${lastAnalysis.commit.slice(0, 12)} · ${lastAnalysis.inspected} dos ${lastAnalysis.source} arquivos de código lidos internamente · confiança ${lastAnalysis.scoreConfidence ?? 'não calculada'}/100. Quando a leitura é parcial, a nota máxima é reduzida para não transformar ausência de alerta em certeza. Hash do relatório: ${reportIntegrity || 'não disponível'}. Não é prova de segurança ou comportamento.` : 'Estimativa baseada nos arquivos públicos do GitHub. Não garante ausência de falhas.'; renderHealth('#health-chart', lastAnalysis.health); renderSeverityChart(lastAnalysis.severityCounts); renderTechnologyChart(lastAnalysis.technologies); const decision = $('#decision-summary'); decision.replaceChildren(); const decisionBox = document.createElement('div'); decisionBox.className = 'decision'; const decisionTitle = document.createElement('strong'); decisionTitle.textContent = lastAnalysis.score >= 70 ? 'Pode avançar com correções planejadas' : 'Estabilize antes de ampliar'; const decisionText = document.createElement('span'); decisionText.textContent = lastAnalysis.summary; decisionBox.append(decisionTitle, decisionText); decision.append(decisionBox); renderDetailedFindings(lastAnalysis.findings); renderActionPlan(lastAnalysis.actions); renderHotspots(lastAnalysis.hotspots); renderEvolution(lastAnalysis); renderDecisionMatrix(lastAnalysis.decision); renderRepairProof(lastAnalysis.repairProof); recordHistory(lastAnalysis, purchase.planId); renderHistory(purchase.planId); $('#full-report').hidden = false; } function freeUsageKey() { const account = signedAccount(); const month = new Date().toISOString().slice(0, 7); return account ? `konaet-xray-free:${account.id}:${month}` : null; } function freeUsage() { const key = freeUsageKey(); return key ? Number(localStorage.getItem(key) || 0) : 0; } function markFreeUsage() { const account = signedAccount(); if (account) localStorage.setItem(freeUsageKey(), String(freeUsage() + 1)); else localStorage.setItem('konaet-xray-free-used', new Date().toISOString()); renderTrialState(); } function guestTrialUsed() { return Boolean(localStorage.getItem('konaet-xray-free-used')); } function renderTrialState() { const account = signedAccount(); const label = $('#trial-label'); if (!label) return; const serverRemaining = accountOverview?.access?.plan?.id === 'free' ? accountOverview.access.remaining.scans : null; label.textContent = account ? `${serverRemaining == null ? Math.max(0, 3 - freeUsage()) : serverRemaining} leituras Free` : guestTrialUsed() ? 'Análise grátis usada' : '1 análise grátis'; $('#login-gate').hidden = Boolean(account) || !guestTrialUsed(); } function requestLogin(message = 'Entre para continuar.') { $('#status').textContent = message; window.dispatchEvent(new CustomEvent('konaet-login-required')); } async function recordScanWithServer(repository) { const requestId = crypto.randomUUID ? crypto.randomUUID() : `scan_${Date.now()}_${Math.random().toString(36).slice(2)}`; const data = await apiRequest('/api/scans', { method: 'POST', body: JSON.stringify({ repository, clientRequestId: requestId }), }); reportIntegrity = data.scan.reportHash || ''; lastScanId = data.scan.id || ''; if (data.access) syncPurchaseFromAccess(data.access); return { ...data.scan.report, verifiedByServer: true }; } $('#scan-form').addEventListener('submit', async (event) => { event.preventDefault(); const account = signedAccount(); const purchase = savedPurchase(); if (!account && guestTrialUsed()) { requestLogin('Sua primeira análise gratuita já foi usada. Entre para continuar.'); return; } const freeLimitReached = API_URL && accountOverview?.access?.plan?.id === 'free' ? accountOverview.access.remaining.scans <= 0 : freeUsage() >= 3; if (account && !purchaseIsActive(purchase) && freeLimitReached) { $('#status').textContent = 'Seu limite Free deste mês terminou. Escolha um relatório ou plano para continuar.'; $('#planos').scrollIntoView({ behavior: 'smooth' }); return; } const button = event.currentTarget.querySelector('button'); button.disabled = true; $('#status').textContent = 'Lendo estrutura e sinais do repositório…'; try { let analysis; if (account && API_URL) { $('#status').textContent = 'Lendo o GitHub no servidor e conferindo seu plano…'; analysis = await recordScanWithServer(repositoryName($('#repository').value)); } else { lastScanId = ''; reportIntegrity = ''; analysis = await analyze($('#repository').value); if (!purchaseIsActive(purchase)) markFreeUsage(); } resetExternalBridge(); lastRepository = analysis.name; lastAnalysis = analysis; renderPreview(analysis); renderFullReport(); $('#status').textContent = analysis.preview ? 'Diagnóstico gratuito concluído.' : 'Análise completa concluída.'; (purchaseIsActive(savedPurchase()) && !$('#full-report').hidden ? $('#full-report') : $('#result')).scrollIntoView({ behavior: 'smooth' }); if (account && API_URL) await loadAccountDashboard(); } catch (error) { $('#status').textContent = error.message; } finally { button.disabled = false; } }); function renderPixCode(payload, base64 = '') { $('#pix-code').value = payload; if (base64) { $('#qr').src = `data:image/png;base64,${base64.replace(/^data:image\/[^;]+;base64,/, '')}`; } else { const qr = qrcode(0, 'M'); qr.addData(payload); qr.make(); $('#qr').src = qr.createDataURL(6, 10); } $('#qr').hidden = false; $('#qr-placeholder').hidden = true; } function renderOfficialPaymentLink(ticketUrl = '') { const link = $('#open-pix'); if (!ticketUrl) { link.hidden = true; link.removeAttribute('href'); return; } link.href = ticketUrl; link.hidden = false; } function paymentSupportUrl(checkout) { const message = encodeURIComponent(`Olá, preciso de ajuda com um pagamento do Konaet X-Ray.\nPlano: ${PLANS[checkout.planId].name}\nReferência: ${checkout.reference || 'ainda não criada'}\nConta: ${checkout.account.name}`); const configured = String(window.huggingface?.variables?.KONAET_WHATSAPP_URL || '').trim(); if (!configured) return `https://wa.me/?text=${message}`; return `${configured}${configured.includes('?') ? '&' : '?'}text=${message}`; } function showLegacyPayment(checkout) { $('#checkout-notice').classList.remove('automatic'); $('#checkout-notice').textContent = 'Esta referência pertence ao fluxo antigo. Nenhum dado Pix permanente é publicado no navegador.'; $('#payment-state').textContent = `Compra ${checkout.reference} aguardando conferência. Use o suporte se precisar de ajuda.`; $('#payment-state').hidden = false; $('#copy-pix').disabled = true; $('#copy-pix').textContent = 'Pix legado'; } async function pollPayment(reference) { if (!reference || !API_URL) return; try { const data = await apiRequest(`/api/checkout/pix?reference=${encodeURIComponent(reference)}`); if (data.payment?.qrCode && !$('#pix-code').value) renderPixCode(data.payment.qrCode, data.payment.qrCodeBase64); renderOfficialPaymentLink(data.payment?.ticketUrl); if (!data.purchase?.active) return; const purchase = storePurchase({ ...savedPurchase(), status: 'approved', approvedAt: data.purchase.approved_at, expiresAt: data.purchase.expires_at, provider: data.purchase.provider, }); serverAccessVerified = true; renderPurchase(purchase); $('#checkout-notice').classList.add('automatic'); $('#checkout-notice').textContent = 'Pagamento confirmado pelo Mercado Pago.'; $('#payment-state').textContent = `${PLANS[purchase.planId].name} liberado nesta conta.`; $('#payment-state').hidden = false; if (paymentPoll) clearInterval(paymentPoll); paymentPoll = null; await loadAccountDashboard(); } catch { // A próxima consulta tenta novamente sem apagar o QR Code. } } function startPaymentPolling(reference) { if (paymentPoll) clearInterval(paymentPoll); pollPayment(reference); paymentPoll = setInterval(() => pollPayment(reference), 3000); } async function createCheckoutPayment() { if (!currentCheckout || currentCheckout.reference) return; const email = $('#checkout-email').value.trim(); if (!/^\S+@\S+\.\S+$/.test(email)) { $('#payment-state').textContent = 'Informe um e-mail válido para gerar o Pix.'; $('#payment-state').hidden = false; $('#checkout-email').focus(); return; } $('#copy-pix').disabled = true; $('#copy-pix').textContent = 'Gerando Pix…'; $('#reference').textContent = 'Criando…'; $('#checkout-notice').classList.remove('automatic'); $('#checkout-notice').textContent = 'Solicitando um Pix exclusivo ao Mercado Pago. Nenhuma cobrança duplicada será criada.'; try { const data = await apiRequest('/api/checkout/pix', { method: 'POST', body: JSON.stringify({ planId: currentCheckout.planId, repository: currentCheckout.repository === 'não informado' ? '' : currentCheckout.repository, email, }), }); const purchase = storePurchase({ planId: currentCheckout.planId, reference: data.reference, repository: currentCheckout.repository, amount: data.amount, provider: data.provider, status: 'pending', reportedAt: new Date().toISOString(), }); currentCheckout = { ...currentCheckout, ...purchase }; renderPurchase(purchase); renderPixCode(data.qrCode, data.qrCodeBase64); renderOfficialPaymentLink(data.ticketUrl); $('#reference').textContent = data.reference; $('#checkout-notice').classList.add('automatic'); $('#checkout-notice').textContent = 'A confirmação é automática. Depois do Pix, esta tela muda para Pagamento aprovado sem comprovante.'; $('#payment-state').textContent = 'Aguardando o pagamento no banco…'; $('#payment-state').hidden = false; $('#confirm-payment').href = paymentSupportUrl(currentCheckout); startPaymentPolling(data.reference); } catch (error) { $('#reference').textContent = 'Não criada'; $('#checkout-notice').classList.remove('automatic'); $('#checkout-notice').textContent = 'Nenhum Pix foi criado. Confira os dados e tente novamente.'; $('#payment-state').textContent = error.message; $('#payment-state').hidden = false; } finally { $('#copy-pix').disabled = false; $('#copy-pix').textContent = $('#pix-code').value ? 'Copiar Pix' : 'Gerar Pix'; } } async function openCheckout(planId, purchase = null) { const account = signedAccount(); if (!account) { sessionStorage.setItem('konaet-xray-pending-plan', planId); requestLogin('Entre para vincular a compra à sua conta.'); return; } const plan = PLANS[planId]; const repository = purchase?.repository || lastRepository || 'não informado'; currentCheckout = { planId, reference: purchase?.reference || null, repository, account }; $('#checkout-title').textContent = plan.name; $('#checkout-price').textContent = plan.display; $('#reference').textContent = purchase?.reference || 'Ainda não criada'; $('#checkout-email').value = account.email || ''; $('#pix-code').value = ''; $('#qr').removeAttribute('src'); $('#qr').hidden = true; $('#qr-placeholder').hidden = false; renderOfficialPaymentLink(''); $('#payment-state').hidden = true; $('#checkout-notice').classList.remove('automatic'); $('#checkout-notice').textContent = 'Digite o e-mail do pagador para criar um Pix exclusivo.'; $('#confirm-payment').href = paymentSupportUrl(currentCheckout); $('#copy-pix').textContent = 'Gerar Pix'; $('#checkout').showModal(); if (purchase?.reference) { currentCheckout.provider = purchase.provider || 'direct_pix'; if (currentCheckout.provider === 'direct_pix') { showLegacyPayment(currentCheckout); startPaymentPolling(purchase.reference); } else { await pollPayment(purchase.reference); startPaymentPolling(purchase.reference); } } else if (account.email) { await createCheckoutPayment(); } else { $('#payment-state').textContent = 'Digite seu e-mail e clique em Gerar Pix.'; $('#payment-state').hidden = false; } } $$('[data-buy]').forEach((button) => button.addEventListener('click', () => openCheckout(button.dataset.buy))); $$('[data-focus-scan]').forEach((button) => button.addEventListener('click', () => { $('#repository').focus(); $('#top').scrollIntoView({ behavior: 'smooth' }); })); $('.dialog-close').addEventListener('click', () => { if (paymentPoll) clearInterval(paymentPoll); paymentPoll = null; $('#checkout').close(); }); $('#copy-pix').addEventListener('click', async () => { if (!$('#pix-code').value) { await createCheckoutPayment(); return; } const code = $('#pix-code'); try { await navigator.clipboard.writeText(code.value); } catch { code.select(); document.execCommand('copy'); } $('#copy-pix').textContent = 'Pix copiado!'; }); $('#resume-purchase').addEventListener('click', () => { const purchase = savedPurchase(); if (!purchase) return; if (purchaseIsActive(purchase)) { const saved = serverHistory.find((item) => purchase.planId === 'single' ? item.repository.toLowerCase() === (purchase.approvedRepository || purchase.repository || '').toLowerCase() : true); if (!$('#full-report').hidden) $('#full-report').scrollIntoView({ behavior: 'smooth' }); else if (saved) openSavedScan(saved.id); else { if (purchase.planId === 'single' && purchase.approvedRepository) $('#repository').value = purchase.approvedRepository; $('#repository').focus(); $('#top').scrollIntoView({ behavior: 'smooth' }); } } else openCheckout(purchase.planId, purchase.status === 'approved' ? null : purchase); }); $('#print-report').addEventListener('click', () => window.print()); $('#verify-repair-proof').addEventListener('click', async () => { if (!lastScanId) return; const button = $('#verify-repair-proof'); const status = $('#proof-verification'); button.disabled = true; status.className = 'proof-verification'; status.textContent = 'Conferindo o relatório salvo, o manifesto e o VCR-1 no servidor…'; try { const result = await apiRequest(`/api/scans/${encodeURIComponent(lastScanId)}/verify`); if (!result.valid || result.scan.reportHash !== reportIntegrity) throw new Error('O relatório exibido não confere com o registro salvo.'); status.className = 'proof-verification valid'; status.textContent = `Integridade confirmada para ${result.scan.repository}@${result.scan.commit.slice(0, 12)}. Relatório, evidências e plano conferem com a leitura salva. Correções e testes não foram executados pelo X-Ray.`; } catch (error) { status.className = 'proof-verification invalid'; status.textContent = `Não foi possível confirmar esta leitura: ${error.message}`; } finally { button.disabled = false; } }); $('#download-repair-proof').addEventListener('click', () => { if (!lastAnalysis?.repairProof || !lastAnalysis?.evidenceManifest) return; const bundle = { scan: lastScanId ? { id: lastScanId, repository: lastAnalysis.name, commit: lastAnalysis.commit, reportHash: reportIntegrity } : null, evidenceManifest: lastAnalysis.evidenceManifest, repairProof: lastAnalysis.repairProof }; const blob = new Blob([`${JSON.stringify(bundle, null, 2)}\n`], { type: 'application/json' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = `konaet-vcr-${lastAnalysis.name.replace('/', '-')}.json`; link.click(); URL.revokeObjectURL(link.href); }); $('#external-artifacts').addEventListener('change', async (event) => { const files = [...event.currentTarget.files]; if (!files.length) return; const status = $('#external-bridge-status'); status.className = 'proof-verification'; status.textContent = 'Lendo e higienizando os arquivos localmente…'; try { if (files.length > 5) throw new Error('Envie no máximo cinco arquivos por vez.'); const { parseExternalArtifact } = await import('./external-bridge.js'); const artifacts = []; const findings = []; for (const file of files) { if (file.size > 2_000_000) throw new Error(`${file.name}: arquivo acima de 2 MB.`); const parsed = await parseExternalArtifact(file.name, await file.text()); artifacts.push(parsed.artifact); findings.push(...parsed.findings); } externalBridge = { schemaVersion: '1.0.0', repository: lastAnalysis.name, commit: lastAnalysis.commit, snapshotBinding: 'not-verified', artifacts, findings: findings.slice(0, 1000) }; status.className = 'proof-verification valid'; status.textContent = 'Importação local concluída. Os arquivos não foram enviados ao servidor. Sinais externos não verificam o commit e não alteram a nota ou o VCR-1.'; $('#download-external-bridge').hidden = false; renderExternalBridge(); } catch (error) { externalBridge = null; $('#download-external-bridge').hidden = true; $('#external-bridge-results').replaceChildren(); status.className = 'proof-verification invalid'; status.textContent = error.message; } }); $('#download-external-bridge').addEventListener('click', () => { if (!externalBridge) return; const blob = new Blob([`${JSON.stringify(externalBridge, null, 2)}\n`], { type: 'application/json' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = `konaet-external-evidence-${lastAnalysis.name.replace('/', '-')}.json`; link.click(); URL.revokeObjectURL(link.href); }); $('#gate-login').addEventListener('click', () => requestLogin()); $('#refresh-account').addEventListener('click', () => loadAccountDashboard()); $('#create-invite-form').addEventListener('submit', async (event) => { event.preventDefault(); try { const data = await apiRequest('/api/team/invites', { method: 'POST', body: JSON.stringify({ label: $('#invite-label').value.trim() }), }); $('#new-invite-code').textContent = data.invite.code; $('#invite-result').hidden = false; $('#invite-label').value = ''; $('#team-status').textContent = 'Envie esse código somente para a pessoa que entrará na equipe. Ele vence em sete dias.'; await loadAccountDashboard(); } catch (error) { $('#team-status').textContent = error.message; } }); $('#accept-invite-form').addEventListener('submit', async (event) => { event.preventDefault(); try { await apiRequest('/api/team/invites/accept', { method: 'POST', body: JSON.stringify({ code: $('#invite-code').value.trim() }), }); $('#invite-code').value = ''; $('#team-status').textContent = 'Conta adicionada à equipe.'; await loadAccountDashboard(); await loadApprovals(); } catch (error) { $('#team-status').textContent = error.message; } }); $('#copy-invite').addEventListener('click', async () => { const code = $('#new-invite-code').textContent; if (!code) return; try { await navigator.clipboard.writeText(code); } catch {} $('#copy-invite').textContent = 'Copiado!'; }); window.addEventListener('konaet-account-change', () => { renderTrialState(); const purchase = savedPurchase(); renderPurchase(purchase); loadApprovals(); loadAccountDashboard(); const pendingPlan = sessionStorage.getItem('konaet-xray-pending-plan'); if (pendingPlan && PLANS[pendingPlan]) { sessionStorage.removeItem('konaet-xray-pending-plan'); openCheckout(pendingPlan); } }); renderTrialState(); renderPurchase(savedPurchase()); loadApprovals(); loadAccountDashboard(); setInterval(loadApprovals, 30000); window.KonaetXRay = { repositoryName, savedPurchase };