Open source · MIT · Node 22+

Pegue vulnerabilidades no frontend antes do deploy.

O FrontGuard analisa React, Vue, Svelte, Angular e JS/TS puro atrás de XSS, segredos vazados, autenticação insegura e dependências vulneráveis. Um comando, sem cadastro, e seu código não sai da sua máquina.

npx @juliocarneiro/frontguard
Começar Ver todas as regras
src/Comment.tsx
export function Comment({ comment, user }: Props) {
  useEffect(() => {
    localStorage.setItem('authToken', user.token);
  }, [user]);
 
  const preview = document.getElementById('preview')!;
  preview.innerHTML = comment.draft;
 
  return (
    <article>
      <div dangerouslySetInnerHTML={{ __html: comment.body }} />
      <a href={`/u/${user.id}?token=${user.token}`}>Profile</a>
    </article>
  );
}

npx @juliocarneiro/frontguard

  1. altaAuth token stored in Web Storage: key "authToken"src/Comment.tsx:3:5 · FG-AUTH-001
  2. altaDynamic innerHTML/outerHTML assignment: innerHTMLsrc/Comment.tsx:7:3 · FG-XSS-001
  3. altaReact dangerouslySetInnerHTMLsrc/Comment.tsx:11:12 · FG-XSS-004
  4. altaCredential passed in a URLsrc/Comment.tsx:12:16 · FG-AUTH-002

✖ 4 problemas (4 alta) · 1 arquivo analisado

Saída real do FrontGuard nestes exemplos.

31regras embutidas
130+formatos de segredo
5formatos de lockfile
5frameworks
Cobertura

O que ele detecta

Cinco categorias, ajustadas para código que roda no navegador.

Pontos de XSS

innerHTML, eval, document.write, dangerouslySetInnerHTML, v-html, {@html}, bypass do sanitizer do Angular e URLs javascript:.

Segredos vazados

Mais de 130 formatos de token, chaves privadas, JWTs e URLs de banco. Mascarados em todo relatório, e chaves públicas por natureza são ignoradas.

Autenticação insegura

Tokens no localStorage, credenciais na query string e senhas fixas no código.

Configuração

Source maps públicos, recursos http:// e ws://, scripts de terceiros sem SRI e postMessage para "*".

Dependências vulneráveis

Versões exatas dos lockfiles de npm, pnpm, yarn e bun, checadas no OSV.dev com CVE e versão corrigida.

Começar

Três jeitos de entrar

Teste em dez segundos e depois deixe no seu fluxo.

  1. Analise agora

    Nada para instalar: o npx baixa o pacote e analisa a pasta atual, saindo com código 1 quando encontra algo grave. Use o nome completo com escopo, mostrado abaixo.

  2. Configure o projeto

    Instala o FrontGuard, cria a config, adiciona um script "security" e um workflow do GitHub Actions. Pergunta antes de cada passo.

  3. Rode em todo lugar

    Local, em hooks de pre-commit ou no CI. Resultados no terminal, em JSON, num painel HTML ou em SARIF.

O pacote no npm é @juliocarneiro/frontguard. Não existe um pacote "frontguard" sem escopo, então "npx frontguard" só funciona depois que o FrontGuard está instalado no projeto; "frontguard" é o nome do comando que ele instala (usado pelo npm run security).

Feito para frontend

Menos alarme falso, mais bug de verdade

Entende frameworks

Os blocos <script> de .vue, .svelte, .astro e .html são analisados no lugar, então cada achado aponta a linha e a coluna certas.

Sabe o que é público

Chaves publicáveis do Stripe, DSNs do Sentry e anon keys do Supabase foram feitas para o navegador. O FrontGuard não alarma à toa.

Não vaza o que encontra

Segredos são mascarados no terminal, no JSON, no HTML e no SARIF, inclusive nas linhas de contexto de outros achados.

Lê seu lockfile

Inclui dependências transitivas, separa as de desenvolvimento percorrendo o grafo e mostra a versão que corrige cada falha.

Um parse por arquivo

Todas as regras compartilham um único parse e uma única travessia do Babel, no estilo do ESLint, então projetos grandes levam segundos.

Silencioso quando precisa

Nível por regra, modo "warn" que nunca quebra o build e comentários // frontguard-ignore-next-line.

Regras

Cada regra, documentada

Cada regra tem id estável, severidade, mapeamento CWE e uma correção concreta.

RegraSeveridadeO que detecta
FG-XSS-001no-inner-htmlaltaDynamic innerHTML/outerHTML assignmentAssigning a dynamic value to innerHTML or outerHTML parses it as HTML, which executes injected markup and scripts.
FG-XSS-002no-evalcríticaDynamic code executioneval(), new Function() and string arguments to setTimeout/setInterval compile strings as code, turning any injected value into code execution.
FG-XSS-003no-document-writealtadocument.write() calldocument.write() and document.writeln() inject raw HTML into the page and are a classic XSS sink.
FG-XSS-004no-dangerously-set-inner-htmlaltaReact dangerouslySetInnerHTMLdangerouslySetInnerHTML bypasses React escaping. Any untrusted data that reaches __html is executed as markup.
FG-XSS-005no-v-htmlaltaVue v-html directivev-html renders raw HTML and executes any markup injected into the bound value.
FG-XSS-006no-bypass-security-trustcríticaAngular sanitizer bypassDomSanitizer.bypassSecurityTrust* disables the built-in Angular XSS protection for that value.
FG-XSS-007no-html-sink-callaltaDynamic HTML passed to a parsing APIinsertAdjacentHTML, Range.createContextualFragment and setHTMLUnsafe parse their argument as HTML, executing injected markup.
FG-XSS-008no-javascript-urlmédiajavascript: URLjavascript: URLs run code when followed. They are a common XSS vector in href, src and form actions.
FG-XSS-009no-svelte-htmlaltaSvelte {@html} tag{@html ...} inserts raw HTML without escaping and executes injected markup.
FG-XSS-010no-open-redirectaltaNavigation to a URL taken from the page addressA value read from location.search/hash, URLSearchParams, document.referrer or window.name is used as a navigation target. Attackers craft links that redirect victims to phishing pages, or run code with a javascript: URL (DOM-based XSS).
FG-XSS-011no-dangerous-attributealtaCode-executing attribute set from a dynamic valueEvent-handler attributes (onclick, onerror...) are compiled as JavaScript and iframe srcdoc is parsed as a full HTML document, so a dynamic value there executes injected code. URL attributes fed from the page address accept javascript: URLs.
FG-XSS-012no-prototype-pollutionaltaPrototype pollution in object mergeA merge/extend/set helper copies attacker-controllable keys onto an object without rejecting "__proto__", "constructor" and "prototype". A payload such as {"__proto__": {...}} then adds properties to every object on the page, which turns into DOM XSS through sanitizers and templating (DOMPurify CVE-2026-41238) or code execution on the server (React2Shell, CVE-2025-55182).
FG-SEC-001no-aws-credentialscríticaAWS credentials exposedAWS access keys or secret keys were found in source code. They grant direct access to AWS services and can lead to full account compromise.
FG-SEC-002no-api-tokensaltaAPI key or token exposedA provider API key or token was found hardcoded in source code. Anything bundled into frontend code is readable by every visitor.
FG-SEC-003no-private-keyscríticaPrivate key exposedA private cryptographic key (RSA, EC, DSA, PGP or OpenSSH) was found.
FG-SEC-004no-hardcoded-jwtaltaHardcoded JWTA JSON Web Token was found in source code. JWTs carry identity claims and are often still valid when leaked.
FG-SEC-005no-connection-stringscríticaDatabase connection string exposedA database URL containing credentials was found in source code.
FG-SEC-006no-high-entropy-stringsmédiaHigh-entropy stringA long random-looking string was found. It may be a credential; review it and suppress the finding if it is not.
FG-SEC-007no-secret-in-public-envaltaServer secret exposed through a public env variableVariables prefixed with NEXT_PUBLIC_, VITE_, REACT_APP_, NUXT_PUBLIC_, PUBLIC_, EXPO_PUBLIC_... are inlined into the JavaScript sent to the browser. A name like VITE_SUPABASE_SERVICE_ROLE_KEY or NEXT_PUBLIC_STRIPE_SECRET means a server secret is readable by every visitor.
FG-AUTH-001no-token-in-web-storagealtaAuth token stored in Web StoragelocalStorage and sessionStorage are readable by any script on the page, so a single XSS bug leaks every token stored there.
FG-AUTH-002no-token-in-urlaltaCredential passed in a URLTokens in query strings end up in browser history, server and proxy logs, and Referer headers.
FG-AUTH-003no-hardcoded-credentialscríticaHardcoded credentialA password or secret is assigned as a string literal. Everything in frontend code ships to the browser and can be read by anyone.
FG-AUTH-004no-insecure-randommédiaMath.random() used for a security valueMath.random() is not cryptographically secure: its output can be predicted from a few samples. Tokens, nonces, OAuth state, PKCE verifiers, salts or passwords generated with it can be guessed.
FG-AUTH-005no-insecure-cookiemédiaAuth cookie written from JavaScriptA session or token cookie is set through document.cookie. Cookies written by JavaScript can never be httpOnly, so any XSS can read them, and without Secure and SameSite they also travel over plain HTTP and cross-site requests.
FG-CFG-001no-public-sourcemapsmédiaPublic source maps in build configPublishing source maps exposes your original source code, comments and internal paths to anyone.
FG-CFG-002no-mixed-contentmédiaInsecure http:// or ws:// resourceLoading scripts, data or sockets over plain HTTP/WS lets anyone on the network read or tamper with them, and browsers block it on HTTPS pages.
FG-CFG-003require-sribaixaThird-party resource without Subresource IntegrityA script or stylesheet is loaded from another origin without an integrity hash. If that host is compromised, its code runs on your page.
FG-CFG-004no-wildcard-postmessagemédiapostMessage with "*" target originpostMessage(data, "*") delivers the message to whatever origin the target window currently has, leaking data to attacker-controlled frames.
FG-CFG-005require-message-origin-checkmédiamessage event handler without an origin checkA window "message" listener reads the event without checking event.origin. Any site that can open or frame your page can post messages to it, so the data must be treated as attacker-controlled (DOM XSS, token theft, CSRF-style actions).
FG-CFG-006no-exposed-dev-servermédiaDev server protections disabledThe dev server accepts any Host header, any CORS origin or serves files outside the project. Any website you visit can then read your source and files such as .env through your local dev server (DNS rebinding and cross-origin reads, as in the Vite file-read CVEs CVE-2025-30208, CVE-2025-31125 and CVE-2025-24010).
FG-DEP-001no-vulnerable-dependenciesaltaVulnerable dependencyAn installed package version has a published security advisory (source: OSV.dev).

Referência completa das regras

CI

Achados na aba Security

A saída SARIF usa caminhos relativos, fingerprints estáveis e o security-severity do GitHub, então os alertas não se repetem entre execuções e ficam ordenados por gravidade. O npm create @juliocarneiro/frontguard escreve este workflow para você.

  • Quebra o job na severidade que você escolher
  • Anota os pull requests
  • Funciona em qualquer CI que leia SARIF ou JSON
.github/workflows/frontguard.yml
name: FrontGuard
on: [push, pull_request]
permissions:
  contents: read
  security-events: write
jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-node@v5
        with: { node-version: 22 }
      - run: npx --yes @juliocarneiro/frontguard@latest -r console,sarif
      - uses: github/codeql-action/upload-sarif@v4
        if: ${{ !cancelled() }}
        with:
          sarif_file: frontguard-report/frontguard-report.sarif
scan.ts
import { defineRule, scan, toSarif } from '@juliocarneiro/frontguard';

const noAlert = defineRule({
  meta: {
    id: 'ACME-001', name: 'no-alert', title: 'alert() call',
    severity: 'low', category: 'misconfig',
    description: 'alert() blocks the UI.',
    remediation: 'Use the design-system dialog.',
  },
  create: (context) => ({
    CallExpression({ node }) {
      if (node.callee.name === 'alert') {
        context.report({ line: node.loc.start.line, column: 1 });
      }
    },
  }),
});

const result = await scan({ config: { customRules: [noAlert] } });
await writeFile('report.sarif', toSarif(result));
API

Suas regras, o mesmo motor

Use o FrontGuard como biblioteca e crie regras para as convenções do seu time com a mesma API de visitors das regras embutidas.

Publique com mais segurança hoje.

Grátis e open source, sob a licença MIT.

npm create @juliocarneiro/frontguard
Estrela no GitHub