diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 51aa292..d7877b6 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -15,6 +15,7 @@ env: RUSTFLAGS: -D warnings CARGO_HOME: /opt/hostedtoolcache/cargo RUSTUP_HOME: /opt/hostedtoolcache/rustup + NPM_CONFIG_CACHE: /opt/hostedtoolcache/npm-cache jobs: lint: @@ -27,6 +28,11 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy + - uses: actions/setup-node@v7 + with: + node-version: 22 + - name: UI translation coverage + run: node scripts/check-ui-i18n.mjs - name: Workflows and templates (valid YAML) run: | python3 -c 'import yaml' 2>/dev/null \ diff --git a/.githooks/pre-push b/.githooks/pre-push index fe370d7..c7faa7c 100755 --- a/.githooks/pre-push +++ b/.githooks/pre-push @@ -1,3 +1,3 @@ #!/usr/bin/env bash set -euo pipefail -exec "$(git rev-parse --show-toplevel)/scripts/verificar.sh" +exec "$(git rev-parse --show-toplevel)/scripts/check.sh" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 02cae4f..45c68ba 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,11 +12,11 @@ Thanks for helping. Xexéu is a continuous attack surface and vulnerability audi ## Workflow ```bash -scripts/instalar-hooks.sh -scripts/verificar.sh +scripts/install-hooks.sh +scripts/check.sh ``` -`verificar.sh` validates code formatting, clippy with warnings as errors, UI translation coverage, shell script syntax, workflow YAML files, SemVer consistency, and prohibited terms. +`check.sh` validates code formatting, clippy with warnings as errors, UI translation coverage, shell script syntax, workflow YAML files, SemVer consistency and `docker compose config` in about a minute; `scripts/check.sh --full` also runs the workspace tests and `cargo audit`. ## Interface and translation diff --git a/CONTRIBUTING.pt-BR.md b/CONTRIBUTING.pt-BR.md index f4accc2..7bc0f6f 100644 --- a/CONTRIBUTING.pt-BR.md +++ b/CONTRIBUTING.pt-BR.md @@ -12,11 +12,11 @@ Obrigado por ajudar. O Xexéu é um motor de auditoria contínua de superfície ## Fluxo de trabalho ```bash -scripts/instalar-hooks.sh -scripts/verificar.sh +scripts/install-hooks.sh +scripts/check.sh ``` -`verificar.sh` executa formatação, clippy com avisos como erro, cobertura de tradução da UI, sintaxe de shell, YAML de workflows, consistência de SemVer e inspeção de termos proibidos. +`check.sh` executa formatação, clippy com avisos como erro, cobertura de tradução da UI, sintaxe de shell, YAML de workflows, consistência de SemVer e `docker compose config` em cerca de um minuto; `scripts/check.sh --full` também roda os testes do workspace e o `cargo audit`. ## Interface e tradução diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..2117c9c --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Xexéu contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apps/gui/ui/i18n-en.js b/apps/gui/ui/i18n-en.js index f936d49..24e27be 100644 --- a/apps/gui/ui/i18n-en.js +++ b/apps/gui/ui/i18n-en.js @@ -90,7 +90,6 @@ export const EN = { 'Baixo (0.1-3.9)': 'Low (0.1-3.9)', 'No KEV': 'In KEV', 'Ordenar': 'Sort by', - 'Maior CVSS': 'Highest CVSS', 'Menor CVSS': 'Lowest CVSS', 'KEV primeiro': 'KEV first', 'ID (CVE / Check)': 'ID (CVE / Check)', @@ -175,4 +174,44 @@ export const EN = { 'Tem certeza que deseja remover o grupo': 'Are you sure you want to remove the group', 'Pelo menos um alvo autorizado é obrigatório.': 'At least one authorized target is required.', 'Nome do grupo é obrigatório.': 'Group name is required.', + 'Hosts e Superfície': 'Hosts and Surface', + 'Ativos identificados no escopo autorizado e portas abertas observadas': 'Assets found within the authorized scope and the open ports observed', + 'Inventário de Vulnerabilidades': 'Vulnerability Inventory', + 'Correlação de versões com feeds NVD, checagens de configuração e CISA KEV': 'Version correlation with NVD feeds, configuration checks and CISA KEV', + 'Alvos configurados, perfis de portas e cadência contínua': 'Configured targets, port profiles and continuous cadence', + 'Mudanças na Superfície': 'Surface Changes', + 'Linha do tempo de novas portas, hosts sumidos e alterações observadas': 'Timeline of new ports, vanished hosts and observed changes', + '{n}s atrás': '{n}s ago', + '{n}min atrás': '{n}min ago', + '{n}h atrás': '{n}h ago', + '{n}d atrás': '{n}d ago', + 'Falha ao comunicar com a API do Xexéu': 'Could not reach the Xexéu API', + 'Contém vulnerabilidade no CISA KEV!': 'Has a vulnerability in CISA KEV!', + 'Clique para abrir na tabela de hosts': 'Click to open it in the hosts table', + 'Serviço desconhecido': 'Unknown service', + 'Serviço': 'Service', + 'Versão': 'Version', + 'Confiança': 'Confidence', + 'Catálogo KEV': 'KEV catalog', + 'Sim (Ativamente explorado)': 'Yes (actively exploited)', + 'Não': 'No', + 'Erro ao salvar grupo': 'Could not save the group', + 'Erro de rede ao salvar grupo': 'Network error while saving the group', + 'Erro ao remover grupo': 'Could not remove the group', + 'Erro de rede ao remover grupo': 'Network error while removing the group', + 'Xexéu — Auditoria Contínua de Superfície de Ataque': 'Xexéu — Continuous Attack Surface Auditing', + 'superfície de risco': 'risk surface', + 'Informações de sincronização incremental NVD e catálogo CISA KEV.': 'Incremental NVD sync and CISA KEV catalog status.', + 'Média': 'Medium', + 'Crítica': 'Critical', + 'Navegação principal': 'Main navigation', + 'Top hosts por maior CVSS': 'Top hosts by highest CVSS', + 'IP, grupo ou serviço...': 'IP, group or service...', + 'Filtrar por status': 'Filter by status', + 'Filtrar por severidade': 'Filter by severity', + 'Filtrar por período': 'Filter by period', + 'Filtrar por IP ou tipo de evento...': 'Filter by IP or event type...', + 'Token de administração (exibido no log do xexeu serve ou definido em XEXEU_ADMIN_TOKEN):': 'Admin token (shown in the xexeu serve log or set in XEXEU_ADMIN_TOKEN):', + 'token de administração ausente ou inválido': 'admin token missing or invalid', + 'origem da requisição não confere': 'request origin does not match', }; diff --git a/scripts/apt-install.sh b/scripts/apt-install.sh new file mode 100755 index 0000000..1f677b8 --- /dev/null +++ b/scripts/apt-install.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# Installs apt packages in CI without depending on fast mirrors: reuses cached .deb +# archives when present and retries with per-attempt timeouts if apt stalls or fails. +# +# Usage: scripts/apt-install.sh ... +set -euo pipefail +[ $# -ge 2 ] || { echo "usage: $0 ..." >&2; exit 2; } +cache="$1"; shift +pkgs=("$@") +mkdir -p "$cache/partial" +# apt runs as root and leaves files (lock, .deb) unreadable by non-root runner users; +# restore ownership on exit so cache directories remain accessible. +trap 'sudo chown -R "$(id -u):$(id -g)" "$cache" 2>/dev/null || true; rm -f "$cache/lock"' EXIT +opts=(-o "Dir::Cache::archives=$cache" -y) + +# 1) With cached .deb files and package index present: install directly without updating apt lists +if [ -z "$(dpkg --print-foreign-architectures)" ] && ls "$cache"/*.deb >/dev/null 2>&1 && ls /var/lib/apt/lists/*Packages* >/dev/null 2>&1 && timeout 300 sudo apt-get "${opts[@]}" install "${pkgs[@]}"; then + echo "installed from cache" + exit 0 +fi + +# 2) Cache miss (or multiarch / incomplete): update and install, up to 3 attempts with timeout +for attempt in 1 2 3; do + if timeout 240 sudo apt-get update && { [ -z "$(dpkg --print-foreign-architectures)" ] || timeout 600 sudo apt-get "${opts[@]}" upgrade; } && timeout 600 sudo apt-get "${opts[@]}" install "${pkgs[@]}"; then + echo "installed (attempt $attempt)" + exit 0 + fi + echo "apt failed or timed out (attempt $attempt of 3)" >&2 + sleep $((attempt * 10)) +done +echo "failed to install: ${pkgs[*]}" >&2 +exit 1 diff --git a/scripts/check-ui-i18n.mjs b/scripts/check-ui-i18n.mjs new file mode 100644 index 0000000..257eea5 --- /dev/null +++ b/scripts/check-ui-i18n.mjs @@ -0,0 +1,299 @@ +#!/usr/bin/env node +// Verifies that the English dictionary covers all user-facing interface strings. +// +// Static zero-dependency scanner: reads the UI files (JS and HTML) and the +// pt-BR messages emitted by the Rust core (errors, diagnostics, engine status), +// failing whenever a string looks like Portuguese and lacks a translation. Also +// rejects duplicate keys in the dictionary (in a JS object literal the last key wins silently). +// +// Usage: node scripts/check-ui-i18n.mjs + +import { readFileSync, readdirSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(fileURLToPath(new URL('.', import.meta.url)), '..'); +const rel = (p) => relative(root, p).replaceAll('\\', '/'); + +// ---------------------------------------------------------------- dictionary + +const dictPath = join(root, 'apps/gui/ui/i18n-en.js'); +const dictSource = readFileSync(dictPath, 'utf8'); + +const keyRe = /^\s*(['"])((?:(?!\1).)*)\1\s*:/gm; +const seen = new Map(); +const duplicates = []; +let m; +while ((m = keyRe.exec(dictSource))) { + const key = m[2]; + const line = dictSource.slice(0, m.index).split('\n').length; + if (seen.has(key)) duplicates.push({ key, first: seen.get(key), again: line }); + else seen.set(key, line); +} + +if (duplicates.length) { + console.error('Duplicate keys in apps/gui/ui/i18n-en.js:'); + for (const d of duplicates) console.error(` ${JSON.stringify(d.key)} (lines ${d.first} and ${d.again})`); + process.exitCode = 1; +} + +const { EN } = await import(new URL('../apps/gui/ui/i18n-en.js', import.meta.url).href); + +const exact = new Set(Object.keys(EN).filter((k) => !k.includes('{n}'))); +const patterns = Object.keys(EN) + .filter((k) => k.includes('{n}')) + .map((k) => { + const parts = k.split('{n}').map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')); + return new RegExp('^' + parts.join('(.+?)') + '$', 's'); + }); + +function translated(text) { + if (exact.has(text)) return true; + return patterns.some((re) => re.test(text)); +} + +// ---------------------------------------------------------------- heuristic + +const ACCENT = /[áàâãäéèêëíìîïóòôõöúùûüçÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ]/; +const WORDS = [ + 'pilar', 'pilares', 'ameaças', 'escopo', 'autorizado', 'tema', 'idioma', 'esqueleto', 'analisar', + 'atualizar', 'status', 'alerta', 'alertas', 'registros', 'detector', 'protocolo', 'anomalias', + 'fusão', 'evidências', 'conexões', 'sessões', 'persistentes', 'desenvolvimento', 'prova', 'opaca', + 'pesquisa', 'determinística', 'armazenamento', 'implementados', 'matemáticos', 'quatro', 'pacote', + 'enviado', 'fora', 'próprias', 'autorização', 'explícita', 'serviço', 'indisponível', 'selecionado', + 'analisando', 'concluída', 'falha', 'verificando', 'versão', 'recente', 'disponível', 'possível', + 'carregados', 'navegação', 'principal', 'recentes', 'futuro', 'carregará', 'sustenta', 'motor', + 'detecção', 'próximas', 'specs', 'fechar', 'claro', 'escuro', 'rede', 'redes', 'interface', 'interfaces', 'captura', 'capturar', 'modo', 'ativar', 'ativa', + 'desativar', 'iniciar', 'parar', 'nenhum', 'nenhuma', 'selecione', 'selecionada', 'canal', + 'sinal', 'segurança', 'clientes', 'cliente', 'oculta', 'oculto', 'privilégio', 'administrador', + 'necessário', 'pra', 'própria', 'próprias', 'autorização', 'responsável', 'sessão', 'trilha', + 'auditoria', 'registrada', 'registrado', 'local', 'adaptador', 'compatível', 'recarregue', + 'escutando', 'levar', 'segundos', 'enquanto', 'canais', 'varridos', 'erro', 'desconhecido', + 'desconhecida', 'não', 'sim', 'mais', 'menos', 'uma', 'uns', 'umas', 'aqui', 'onde', 'quando', + 'como', 'qual', 'para', 'com', 'sem', 'dos', 'das', 'por', 'que', 'checando', 'checar', + 'atualização', 'atualizado', 'trocar', 'possível', 'quebrável', 'quebrado', 'rompida', + 'corrompida', 'inválido', 'inválida', 'entrada', 'dicionário', 'quadros', 'quantidade', + 'injetar', 'encontrado', 'encontrada', 'suportada', 'permissão', 'insuficiente', 'instale', + 'root', 'indisponível', 'plataforma', 'criada', 'ainda', 'ferramenta', 'ferramentas', + 'exportar', 'importar', 'imprimir', 'baixar', 'recomendado', 'recomendada', 'aberta', + 'aberto', 'inconclusivo', 'inconclusiva', 'capturado', 'capturada', 'conhecido', + 'conhecida', 'opcional', 'opcionais', 'fechar', 'motivo', 'linha', 'tempo', 'quadro', + 'tentativas', 'ambas', +]; + +const BRAND = /Xexéu|Xexeu|Português|English/gi; +const isPortuguese = (raw) => { + const s = raw.replace(BRAND, ' '); + return ACCENT.test(s) || WORDS.some((w) => new RegExp(`(^|[^a-zà-ú])${w}([^a-zà-ú]|$)`, 'i').test(s)); +}; + +const ALLOW = new Set([ + 'Xexéu', 'Português', 'English', 'Auto', 'Wi-Fi', 'Zeek', 'DuckDB', 'API', 'JSON', 'CLI', + 'MIT', 'Apache-2.0', 'OK', 'status-indicator {n}', +]); +const ALLOW_PREFIX = ['http://', 'https://', 'data:', 'file:', '#', '.', '/']; +const ALLOW_EXACT = new Set(['—', '-', '·']); + +function suspicious(text) { + const s = text.replace(/\s+/g, ' ').trim(); + if (!s || s.length < 2) return false; + if (ALLOW.has(s) || ALLOW_EXACT.has(s)) return false; + if (ALLOW_PREFIX.some((p) => s.startsWith(p))) return false; + if (!isPortuguese(s)) return false; + // Technical tokens: CSS selectors, classes, extensions, expressions + if (/^[.#\w-]+(\s*[,>+~]\s*[.#\w-]+)+$/.test(s)) return false; + if (/^[a-z0-9_.:/@%{}$-]+$/i.test(s) && !ACCENT.test(s)) return false; + return true; +} + +// ---------------------------------------------------------------- extractors + +function jsStrings(source, file, baseLine = 1) { + const out = []; + let i = 0; + let line = baseLine; + let prev = ''; + const skipRegex = () => { + i++; + let inClass = false; + while (i < source.length) { + const ch = source[i]; + if (ch === '\\') { i += 2; continue; } + if (ch === '[') inClass = true; + else if (ch === ']') inClass = false; + else if (ch === '/' && !inClass) { i++; break; } + else if (ch === '\n') line++; + i++; + } + while (i < source.length && /[a-z]/i.test(source[i])) i++; + }; + while (i < source.length) { + const c = source[i]; + if (c === '\n') { line++; i++; prev = '\n'; continue; } + if (c === ' ' || c === '\t' || c === '\r') { i++; continue; } + if (c === '/' && source[i + 1] === '/') { + while (i < source.length && source[i] !== '\n') i++; + continue; + } + if (c === '/' && source[i + 1] === '*') { + i += 2; + while (i < source.length && !(source[i] === '*' && source[i + 1] === '/')) { if (source[i] === '\n') line++; i++; } + i += 2; + continue; + } + if (c === '/' && (/[=(:,[!&|?{};+\-*%^~<>]/.test(prev) || prev === 'return')) { + skipRegex(); + prev = ')'; + continue; + } + if (c === "'" || c === '"') { + const quote = c; + const startLine = line; + let value = ''; + i++; + while (i < source.length) { + const ch = source[i]; + if (ch === '\\') { + const n = source[i + 1]; + if (n === 'n') value += '\n'; + else if (n === 't') value += '\t'; + else if (n === 'r') value += '\r'; + else if (n === '\n') line++; + else value += n ?? ''; + i += 2; + continue; + } + if (ch === quote) { i++; break; } + if (ch === '\n') line++; + value += ch; + i++; + } + out.push({ text: value, file, line: startLine }); + prev = ')'; + continue; + } + if (c === '`') { + const startLine = line; + let value = ''; + i++; + while (i < source.length) { + const ch = source[i]; + if (ch === '\\') { + const n = source[i + 1]; + if (n === 'n') value += '\n'; + else if (n === 't') value += '\t'; + else if (n === '\n') line++; + else value += n ?? ''; + i += 2; + continue; + } + if (ch === '`') { i++; break; } + if (ch === '$' && source[i + 1] === '{') { + value += '{n}'; + i += 2; + const exprStart = i; + const exprLine = line; + let depth = 1; + while (i < source.length && depth > 0) { + if (source[i] === '{') depth++; + else if (source[i] === '}') depth--; + else if (source[i] === '\n') line++; + i++; + } + out.push(...jsStrings(source.slice(exprStart, i - 1), file, exprLine)); + continue; + } + if (ch === '\n') line++; + value += ch; + i++; + } + out.push({ text: value, file, line: startLine }); + prev = ')'; + continue; + } + prev = c; + i++; + } + return out; +} + +function htmlStrings(source, file, baseLine = 1) { + const out = []; + const lineAt = (idx) => baseLine + source.slice(0, idx).split('\n').length - 1; + // Text between tags (including leading and trailing text nodes) + let last = 0; + for (const m of source.matchAll(/<[^>]*>/g)) { + out.push({ text: source.slice(last, m.index), file, line: lineAt(last) }); + last = m.index + m[0].length; + } + out.push({ text: source.slice(last), file, line: lineAt(last) }); + // Translatable attributes (single or double quotes) + for (const m of source.matchAll(/\b(placeholder|title|aria-label|alt|data-empty)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) { + out.push({ text: m[2] ?? m[3], file, line: lineAt(m.index) }); + } + return out; +} + +// Extracts pt-BR messages from the Rust core: #[error("...")], .push("...".into()), +// "...".into(), and format!("...", ...). Placeholders ({name}, {0}, {} etc.) are +// normalized to {n}, matching the dictionary format. +function rustLabels(source, file) { + const out = []; + const lineAt = (idx) => source.slice(0, idx).split('\n').length; + const norm = (s) => s.replace(/\{[^}]*\}/g, '{n}'); + const grab = (re) => { + for (const m of source.matchAll(re)) { + out.push({ text: norm(m[1]), file, line: lineAt(m.index) }); + } + }; + grab(/#\[error\(\s*"((?:[^"\\]|\\.)*)"\s*\)\]/g); + grab(/"((?:[^"\\]|\\.)*)"\s*\.into\(\)/g); + grab(/format!\(\s*"((?:[^"\\]|\\.)*)"/g); + return out; +} + +// ---------------------------------------------------------------- collection + +const uiFiles = readdirSync(join(root, 'apps/gui/ui')) + .filter((f) => f.endsWith('.js') && f !== 'i18n-en.js' && f !== 'vendor' && !f.endsWith('.min.js')) + .map((f) => join(root, 'apps/gui/ui', f)); +uiFiles.push(join(root, 'apps/gui/ui/index.html')); + +// The Rust core's messages reach only the CLI, never the dashboard. +const rustFiles = [].map((f) => join(root, f)); + +const found = []; +for (const file of uiFiles) { + const source = readFileSync(file, 'utf8'); + if (file.endsWith('.html')) found.push(...htmlStrings(source, file)); + else { + for (const str of jsStrings(source, file)) { + if (/<[a-z!/][^>]*>/i.test(str.text)) found.push(...htmlStrings(str.text, file, str.line)); + else found.push(str); + } + } +} +for (const file of rustFiles) found.push(...rustLabels(readFileSync(file, 'utf8'), file)); + +const missing = []; +const seenMissing = new Set(); +for (const { text, file, line } of found) { + if (!suspicious(text)) continue; + const key = text.replace(/\s+/g, ' ').trim(); + if (translated(key)) continue; + const id = `${key}\u0000${rel(file)}\u0000${line}`; + if (seenMissing.has(id)) continue; + seenMissing.add(id); + missing.push({ text: key, file: rel(file), line }); +} + +if (missing.length) { + console.error('Untranslated Portuguese strings in apps/gui/ui/i18n-en.js:\n'); + for (const x of missing) console.error(` ${x.file}:${x.line} ${JSON.stringify(x.text)}`); + console.error(`\n${missing.length} untranslated string(s).`); + process.exitCode = 1; +} + +if (!process.exitCode) { + console.log(`i18n ok: ${found.length} strings checked, ${Object.keys(EN).length} dictionary keys.`); +} diff --git a/scripts/verificar.sh b/scripts/check.sh similarity index 70% rename from scripts/verificar.sh rename to scripts/check.sh index 5e4dcb1..39370fe 100755 --- a/scripts/verificar.sh +++ b/scripts/check.sh @@ -1,13 +1,15 @@ #!/usr/bin/env bash -# Verificação local: executa as mesmas checagens do CI antes do push. +# Local verification: runs the same fast checks as CI before pushing. # -# scripts/verificar.sh completo: fmt, clippy, scripts, workflows, semver, compose, testes -# scripts/verificar.sh --rapido pula a suíte de testes do workspace +# scripts/check.sh fast (~1 min): fmt, clippy, i18n, scripts, workflows, semver +# scripts/check.sh --full also runs workspace tests and cargo audit # +# CI takes 5 to 30 minutes per run; almost everything that breaks CI is caught +# here in seconds. set -uo pipefail cd "$(dirname "$0")/.." -rapido=0 -[ "${1:-}" = "--rapido" ] || [ "${1:-}" = "--fast" ] && rapido=1 +full=0 +[ "${1:-}" = "--full" ] || [ "${1:-}" = "--completo" ] && full=1 failures=() step() { # step "name" command... local name="$1"; shift @@ -16,18 +18,22 @@ step() { # step "name" command... } step "formatting (cargo fmt)" cargo fmt --all -- --check +# Same flags as CI: warnings are treated as errors across all targets, including tests step "clippy (workspace, all targets)" env RUSTFLAGS="-D warnings" cargo clippy --workspace --all-targets -step "bash script syntax" bash -c 'for f in scripts/*.sh .githooks/*; do [ -f "$f" ] || continue; bash -n "$f" || exit 1; done' - +step "UI translation coverage" node scripts/check-ui-i18n.mjs +step "bash script syntax" bash -c 'for f in scripts/*.sh .githooks/*; do bash -n "$f" || exit 1; done' step "workflows and templates (valid YAML)" python3 -c " +import sys +try: + import yaml +except ImportError: + sys.exit('PyYAML missing: pip install pyyaml') import glob, yaml for f in glob.glob('.gitea/**/*.yml', recursive=True): yaml.safe_load(open(f)) " - step "brand assets" test -s logo.png - step "consistent Semantic Versioning 2.0.0" python3 -c " import re, sys from pathlib import Path @@ -56,8 +62,9 @@ else printf '\n(docker compose config: skipped, docker compose not available)\n' fi -if [ "$rapido" = 0 ]; then +if [ "$full" = 1 ]; then step "tests (cargo test --workspace)" cargo test --workspace + step "dependency audit (cargo audit)" cargo audit fi printf '\n' diff --git a/scripts/instalar-hooks.sh b/scripts/instalar-hooks.sh deleted file mode 100755 index 8978549..0000000 --- a/scripts/instalar-hooks.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -# Ativa os Git hooks do repositório (.githooks/pre-push e .githooks/commit-msg). -set -euo pipefail -cd "$(dirname "$0")/.." -git config core.hooksPath .githooks -echo "hooks ativados: git commit valida Conventional Commits e git push executa scripts/verificar.sh (desative com: git config --unset core.hooksPath)" diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh new file mode 100755 index 0000000..49319fc --- /dev/null +++ b/scripts/install-hooks.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Enables the repository Git hooks (.githooks/pre-push and .githooks/commit-msg). +set -euo pipefail +cd "$(dirname "$0")/.." +git config core.hooksPath .githooks +echo "hooks enabled: git commit validates Conventional Commits in English and git push runs scripts/check.sh (disable with: git config --unset core.hooksPath)"