From 2ef6f6be10af79780fbb55e63b816811248f325d Mon Sep 17 00:00:00 2001 From: Evandro Fonseca Junior Date: Tue, 20 Oct 2026 00:49:23 -0300 Subject: [PATCH] =?UTF-8?q?wip:=20snapshot=20das=20altera=C3=A7=C3=B5es=20?= =?UTF-8?q?n=C3=A3o=20commitadas=20(2026-10-20)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Origem: D:/Documents/Github/dev-workflows Arquivos omitidos (segredos, bancos de dados, logs, >50 MB): 0 --- .claude-plugin/marketplace.json | 15 + .claude-plugin/plugin.json | 14 + .github/workflows/ci.yml | 22 + .github/workflows/upstream.yml | 17 + CHANGELOG.md | 24 + adapters/opencode/dev-workflows.ts | 34 + agents/explorer.md | 19 + agents/implementer.md | 17 + agents/planner.md | 28 + agents/reviewer.md | 25 + agents/security-auditor.md | 20 + agents/ui-critic.md | 22 + agents/verifier.md | 17 + hooks/hooks.json | 27 + qa/check_upstream.py | 35 + qa/lint_skills.py | 126 ++ qa/test_gate.py | 97 ++ scripts/hooks/bash_guard.py | 48 + scripts/hooks/post_edit.py | 58 + scripts/hooks/stop_gate.py | 70 + scripts/install.py | 99 ++ scripts/quality-gate | 304 ++++ .../plays/api-security-review.md | 1506 +++++++++++++++++ .../plays/code-review-security.md | 204 +++ .../code-review-security/templates/finding.md | 48 + skills/cve-triage/schemas/finding.schema.json | 345 ++++ .../dependency-scanning/docs/fixer-policy.md | 111 ++ .../docs/normalized-json-output.md | 158 ++ .../dependency-scanning/docs/sarif-output.md | 229 +++ .../schemas/finding.schema.json | 345 ++++ skills/design-taste-frontend/LICENSE | 21 + skills/design-taste-frontend/SKILL.md | 1206 +++++++++++++ skills/dev-router/SKILL.md | 73 + skills/dev-router/references/quality-gate.md | 71 + skills/lean-code/SKILL.md | 53 + .../schemas/finding.schema.json | 345 ++++ skills/redesign-existing-projects/LICENSE | 21 + skills/redesign-existing-projects/SKILL.md | 178 ++ skills/sca-audit/plays/sca-audit.md | 140 ++ skills/sca-audit/templates/finding.md | 48 + skills/secrets-scan/plays/secrets-scan.md | 147 ++ skills/secrets-scan/templates/finding.md | 48 + .../plays/owasp-top10-web-review.md | 374 ++++ .../web-security-review/templates/finding.md | 48 + skills/wf-architecture/SKILL.md | 107 ++ skills/wf-architecture/references/adr.md | 31 + skills/wf-architecture/references/c4.md | 45 + skills/wf-architecture/references/ears.md | 35 + skills/wf-architecture/references/stride.md | 35 + skills/wf-backend/SKILL.md | 93 + skills/wf-backend/references/checks.md | 63 + skills/wf-bugfix/SKILL.md | 45 + skills/wf-frontend/SKILL.md | 98 ++ skills/wf-frontend/references/checks.md | 91 + skills/wf-frontend/references/pdf.md | 49 + skills/wf-readme/SKILL.md | 98 ++ skills/wf-readme/references/estrutura.md | 30 + skills/wf-readme/references/verificacao.md | 25 + skills/wf-refactor/SKILL.md | 38 + skills/wf-security-review/SKILL.md | 104 ++ .../references/owasp-2025.md | 48 + 61 files changed, 7892 insertions(+) create mode 100644 .claude-plugin/marketplace.json create mode 100644 .claude-plugin/plugin.json create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/upstream.yml create mode 100644 CHANGELOG.md create mode 100644 adapters/opencode/dev-workflows.ts create mode 100644 agents/explorer.md create mode 100644 agents/implementer.md create mode 100644 agents/planner.md create mode 100644 agents/reviewer.md create mode 100644 agents/security-auditor.md create mode 100644 agents/ui-critic.md create mode 100644 agents/verifier.md create mode 100644 hooks/hooks.json create mode 100644 qa/check_upstream.py create mode 100644 qa/lint_skills.py create mode 100644 qa/test_gate.py create mode 100644 scripts/hooks/bash_guard.py create mode 100644 scripts/hooks/post_edit.py create mode 100644 scripts/hooks/stop_gate.py create mode 100644 scripts/install.py create mode 100644 scripts/quality-gate create mode 100644 skills/api-security-review/plays/api-security-review.md create mode 100644 skills/code-review-security/plays/code-review-security.md create mode 100644 skills/code-review-security/templates/finding.md create mode 100644 skills/cve-triage/schemas/finding.schema.json create mode 100644 skills/dependency-scanning/docs/fixer-policy.md create mode 100644 skills/dependency-scanning/docs/normalized-json-output.md create mode 100644 skills/dependency-scanning/docs/sarif-output.md create mode 100644 skills/dependency-scanning/schemas/finding.schema.json create mode 100644 skills/design-taste-frontend/LICENSE create mode 100644 skills/design-taste-frontend/SKILL.md create mode 100644 skills/dev-router/SKILL.md create mode 100644 skills/dev-router/references/quality-gate.md create mode 100644 skills/lean-code/SKILL.md create mode 100644 skills/patch-prioritization/schemas/finding.schema.json create mode 100644 skills/redesign-existing-projects/LICENSE create mode 100644 skills/redesign-existing-projects/SKILL.md create mode 100644 skills/sca-audit/plays/sca-audit.md create mode 100644 skills/sca-audit/templates/finding.md create mode 100644 skills/secrets-scan/plays/secrets-scan.md create mode 100644 skills/secrets-scan/templates/finding.md create mode 100644 skills/web-security-review/plays/owasp-top10-web-review.md create mode 100644 skills/web-security-review/templates/finding.md create mode 100644 skills/wf-architecture/SKILL.md create mode 100644 skills/wf-architecture/references/adr.md create mode 100644 skills/wf-architecture/references/c4.md create mode 100644 skills/wf-architecture/references/ears.md create mode 100644 skills/wf-architecture/references/stride.md create mode 100644 skills/wf-backend/SKILL.md create mode 100644 skills/wf-backend/references/checks.md create mode 100644 skills/wf-bugfix/SKILL.md create mode 100644 skills/wf-frontend/SKILL.md create mode 100644 skills/wf-frontend/references/checks.md create mode 100644 skills/wf-frontend/references/pdf.md create mode 100644 skills/wf-readme/SKILL.md create mode 100644 skills/wf-readme/references/estrutura.md create mode 100644 skills/wf-readme/references/verificacao.md create mode 100644 skills/wf-refactor/SKILL.md create mode 100644 skills/wf-security-review/SKILL.md create mode 100644 skills/wf-security-review/references/owasp-2025.md diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..abfbb3a --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,15 @@ +{ + "name": "dev-workflows", + "description": "Dev workflows como plugin do Claude Code: roteador por nível, agentes, gate de qualidade e revisão de segurança.", + "owner": { + "name": "Evandro Fonseca Junior", + "url": "https://github.com/evandrodevbr" + }, + "plugins": [ + { + "name": "dev-workflows", + "source": "./", + "description": "Roteador por nível, agentes, gate de qualidade e workflows de front, back, arquitetura, segurança e README." + } + ] +} diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..69bdccb --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,14 @@ +{ + "name": "dev-workflows", + "displayName": "Dev Workflows", + "version": "2.0.0", + "description": "Workflows de desenvolvimento que escalam com o tamanho do pedido: roteador por nível, agentes com permissão mínima, gate de qualidade determinístico e revisão de segurança com fontes ao vivo.", + "author": { + "name": "Evandro Fonseca Junior", + "url": "https://github.com/evandrodevbr" + }, + "homepage": "https://github.com/evandrodevbr/dev-workflows", + "repository": "https://github.com/evandrodevbr/dev-workflows", + "license": "MIT", + "keywords": ["workflow", "code-review", "security", "frontend", "backend", "quality-gate"] +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c0efd44 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,22 @@ +name: ci + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Lint das skills, agentes e hooks + run: python3 qa/lint_skills.py + - name: Testes do gate e dos hooks + run: python3 qa/test_gate.py diff --git a/.github/workflows/upstream.yml b/.github/workflows/upstream.yml new file mode 100644 index 0000000..81194b3 --- /dev/null +++ b/.github/workflows/upstream.yml @@ -0,0 +1,17 @@ +name: upstream + +on: + schedule: + - cron: "0 9 1 * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + vendored-skills: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Skills vendorizadas atrás do upstream + run: python3 qa/check_upstream.py diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..2873b3c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,24 @@ +# Changelog + +## 2.0.0 (2026-09-24) + +### Added +- Claude Code plugin packaging (`.claude-plugin/plugin.json`, `marketplace.json`); workflows moved to `skills//SKILL.md`. +- `dev-router`: tiers 0 to 3 with security triggers that raise the tier, so small requests skip heavy phases. +- `lean-code`: reuse ladder, dependency justification, diff budget per tier. +- `wf-bugfix` and `wf-refactor`. +- Agents: `explorer`, `planner`, `implementer`, `reviewer`, `security-auditor`, `ui-critic`, `verifier`, each with only the tools its role needs. +- `scripts/quality-gate`: deterministic checks per tier, scoped to the diff; missing tools reported as unverified; new dependencies listed. +- Hooks: `Stop` gate, shell command guard, formatter after edits. +- opencode adapter and `scripts/install.py` for Claude Code, opencode and Hermes Agent. +- taste-skill (`design-taste-frontend`, `redesign-existing-projects`) vendored for `wf-frontend`. +- `qa/lint_skills.py`, `qa/test_gate.py`, `qa/check_upstream.py` and CI. + +### Changed +- The five workflows were cut to about 100 lines each; phases state their minimum tier; grep-count checks replaced by the gate and real tools. +- Security references moved to OWASP Top 10:2025, ASVS 5.0 and OWASP LLM Top 10 (2025). +- Machine-specific paths (`~/.hermes/...`, `vision_analyze`) and references to skills that do not exist publicly removed. + +### Removed +- The keyword-count quality harness (`qa/wf_quality_harness.py`, `test_quality.py`, `test_tests.py`, snapshots). It scored occurrences of words like `VERIFICAR` and `NUNCA`, so its "+98.6%" measured wording, not quality; it also failed on a fresh clone because it looked for skills in `~/.hermes`. +- apisec-inc's `api-security-review` from `wf-backend` (name collision with the vendored OWASP skill). diff --git a/adapters/opencode/dev-workflows.ts b/adapters/opencode/dev-workflows.ts new file mode 100644 index 0000000..8e8cf15 --- /dev/null +++ b/adapters/opencode/dev-workflows.ts @@ -0,0 +1,34 @@ +// dev-workflows for opencode: the same guard, formatter and gate scripts the Claude Code hooks run. +// Installed by `python3 scripts/install.py opencode`, which replaces __DW_ROOT__ with the checkout path. +// opencode cannot block the end of a turn, so a missing or failing gate is logged instead of blocking. +const ROOT = "__DW_ROOT__" + +const DevWorkflows = async (ctx: any) => { + const $ = ctx.$ ?? (globalThis as any).Bun?.$ + const directory = ctx.directory ?? ctx.location?.directory ?? process.cwd() + return { + "tool.execute.before": async (input: any, output: any) => { + if (!["bash", "shell"].includes(String(input?.tool ?? "").toLowerCase())) return + const command = output?.args?.command + if (typeof command !== "string" || !command) return + const r = await $`python3 ${ROOT}/scripts/hooks/bash_guard.py --check ${command}`.quiet().nothrow() + if (r.exitCode === 2) throw new Error(String(r.stdout).trim()) + }, + "tool.execute.after": async (input: any, output: any) => { + if (!["edit", "write", "patch", "multiedit"].includes(String(input?.tool ?? "").toLowerCase())) return + const file = input?.args?.filePath ?? output?.args?.filePath + if (typeof file === "string" && file) { + await $`python3 ${ROOT}/scripts/hooks/post_edit.py --file ${file}`.quiet().nothrow() + } + }, + event: async ({ event }: any) => { + if (event?.type !== "session.idle") return + const r = await $`python3 ${ROOT}/scripts/hooks/stop_gate.py --check ${directory}`.quiet().nothrow() + if (r.exitCode === 2) { + await ctx.client?.app?.log?.({ body: { service: "dev-workflows", level: "warn", message: String(r.stdout).trim() } }) + } + }, + } +} + +export default { id: "dev-workflows", setup: DevWorkflows } diff --git a/agents/explorer.md b/agents/explorer.md new file mode 100644 index 0000000..efa4ed8 --- /dev/null +++ b/agents/explorer.md @@ -0,0 +1,19 @@ +--- +name: explorer +description: Mapeia o código antes de uma mudança - onde fica o que importa, o que já existe para reaproveitar e como o projeto roda lint e testes. Só leitura. Use no nível 2 ou 3, ou no nível 1 quando não se sabe onde está o código. +tools: Read, Grep, Glob, Bash +model: haiku +--- + +Você mapeia o código para quem vai mudá-lo. Não edita nada. No Bash, só comandos de leitura +(`git log`, `git grep`, `ls`, `cat` de configs). + +Entregue, em até 300 palavras: + +1. **Onde mexer**: arquivos e funções relevantes, como `caminho:linha`, com uma linha sobre o papel de cada um. +2. **O que já existe**: helpers, componentes, tipos, validações ou padrões que resolvem parte do pedido e devem ser reaproveitados. Esta é a parte mais importante. +3. **Como verificar**: os comandos reais de teste, lint, typecheck e build (do `package.json`, `pyproject.toml`, `Makefile` ou CI). +4. **Convenções** que a mudança deve seguir (nomes, estrutura de pastas, tratamento de erro). +5. **Riscos**: chamadores que também dependem do que vai mudar. + +Se não achou algo, diga que não achou. Não invente caminhos. diff --git a/agents/implementer.md b/agents/implementer.md new file mode 100644 index 0000000..fba1f43 --- /dev/null +++ b/agents/implementer.md @@ -0,0 +1,17 @@ +--- +name: implementer +description: Implementa uma tarefa já planejada, com TDD e o menor diff que resolve, e roda o gate de qualidade no nível indicado. +tools: Read, Edit, Write, Bash, Grep, Glob +model: sonnet +skills: [lean-code] +--- + +Você implementa uma tarefa de cada vez, com o nível que o `dev-router` definiu. + +1. Leia os arquivos antes de editar. Siga as convenções do projeto. +2. **Comportamento novo ou corrigido começa por um teste que falha.** Rode e veja vermelho; depois implemente até ficar verde. +3. Aplique `lean-code`: reaproveite o que existe, sem abstração sem uso, sem dependência sem justificativa. +4. Rode o gate: `"${CLAUDE_PLUGIN_ROOT}/scripts/quality-gate" --tier N`. Corrija o que falhar. +5. Devolva: o que mudou (arquivos, linhas líquidas), o teste que prova, o veredito do gate e o que ficou "não verificado". + +Não declare pronto com teste vermelho ou gate falho. Se uma falha não é sua de corrigir, diga qual e por quê. diff --git a/agents/planner.md b/agents/planner.md new file mode 100644 index 0000000..87a8eaf --- /dev/null +++ b/agents/planner.md @@ -0,0 +1,28 @@ +--- +name: planner +description: Escreve o plano (nível 2) ou a spec com requisitos EARS, ADR e tarefas (nível 3) antes da implementação. Só leitura. +tools: Read, Grep, Glob +model: opus +--- + +Você planeja; não implementa. Use o mapa do `explorer` se houver, e prefira reaproveitar o que existe. + +## Nível 2: plano curto + +- Até 15 linhas. Tarefas de 2 a 5 minutos cada, com o arquivo exato e como verificar. +- O que **não** será feito (escopo cortado de propósito). +- Decisões que são do usuário, se houver. + +## Nível 3: spec + +1. **Requisitos EARS com ID**, um por linha: + - `REQ-001: WHEN THE SYSTEM SHALL ` + - `REQ-002: IF THEN THE SYSTEM SHALL ` + - `REQ-003: WHILE THE SYSTEM SHALL ` +2. **Não funcionais** com número: orçamento de performance (ex.: p95, LCP), nível ASVS (L2), limites. +3. **ADR** para cada decisão difícil de desfazer: contexto, opções, decisão, consequências. +4. **Tarefas** pequenas, cada uma com os `REQ-` que cobre e o teste que prova. +5. **Rollback**: como desfazer se der errado (migração reversível, feature flag). + +Salve a spec num arquivo (ex.: `docs/specs/.md`) e sugira `[spec]` no `.dev-workflows.toml` +para o gate conferir que todo `REQ-` tem teste. A spec passa pelo usuário antes da implementação. diff --git a/agents/reviewer.md b/agents/reviewer.md new file mode 100644 index 0000000..d9ad8ef --- /dev/null +++ b/agents/reviewer.md @@ -0,0 +1,25 @@ +--- +name: reviewer +description: Revisão independente de correção e simplicidade de um diff. Julga só o código e o plano, não o que a conversa afirma. Só leitura. Use no nível 2 ou 3 depois da implementação. +tools: Read, Grep, Glob, Bash +model: opus +--- + +Você revisa um diff sem ter participado da implementação. Não edite arquivos. No Bash, só leitura +(`git diff `, `git log`, rodar testes). + +Obtenha o diff com `git diff $(git merge-base HEAD origin/HEAD 2>/dev/null || echo HEAD)` mais os +arquivos não rastreados. Leia o código ao redor de cada trecho alterado. + +Procure: + +1. **Correção**: casos de borda, erro não tratado, concorrência, estado inconsistente, contrato quebrado com chamadores. +2. **Testes que provam**: o teste falharia se o bug voltasse? Testa o comportamento ou só a implementação? +3. **Simplicidade**: algo que poderia não existir, reaproveitar código do projeto ou ser apagado. +4. **Consistência** com as convenções do código ao redor. + +Para cada achado: severidade (`bloqueante`, `importante`, `sugestão`), `arquivo:linha`, o problema, +um cenário concreto de falha (entrada e resultado errado) e a correção sugerida. No máximo 10 achados, +os mais graves primeiro, sem questões de estilo que o lint já cobre. + +Sem achados: diga "sem achados" e liste o que você verificou. diff --git a/agents/security-auditor.md b/agents/security-auditor.md new file mode 100644 index 0000000..56dd103 --- /dev/null +++ b/agents/security-auditor.md @@ -0,0 +1,20 @@ +--- +name: security-auditor +description: Auditoria de segurança do diff e da superfície que ele toca - OWASP Top 10 2025, API Top 10, ASVS 5.0 e LLM Top 10, com CVEs consultados ao vivo. Só leitura. Use quando o dev-router disparar um gatilho de segurança ou no nível 3. +tools: Read, Grep, Glob, Bash, WebFetch +model: opus +skills: [wf-security-review] +--- + +Você audita; não corrige. Siga o `wf-security-review` com escopo no diff e no que ele alcança +(rotas, handlers, queries e componentes que usam o código alterado). + +- **Referências**: OWASP Top 10:2025, OWASP API Security Top 10 (2023), ASVS 5.0 no nível que o + router definiu (L1 no nível 2, L2 no nível 3), OWASP LLM Top 10 (2025) se a feature chama um LLM. +- **Dependências novas ou alteradas**: consulte OSV.dev ao vivo (`safedeps`) e registre data e fonte. + Nunca diga "sem CVE" sem ter consultado. +- **Scanners do gate** (semgrep, gitleaks, osv-scanner, trivy) são ponto de partida, não substituto da leitura. + +Para cada achado: severidade, CWE, `arquivo:linha`, como explorar (passo a passo curto), impacto e +correção. Diferencie vulnerabilidade confirmada de suspeita. Sem achados: liste o que verificou e as +fontes consultadas, com data. diff --git a/agents/ui-critic.md b/agents/ui-critic.md new file mode 100644 index 0000000..9979af7 --- /dev/null +++ b/agents/ui-critic.md @@ -0,0 +1,22 @@ +--- +name: ui-critic +description: Crítica visual e de UX de uma tela implementada - estados, acessibilidade, responsividade, contraste e padrões genéricos de "UI feita por IA". Só leitura. Use no nível 2 ou 3 quando houver UI. +tools: Read, Grep, Glob, Bash +model: sonnet +skills: [redesign-existing-projects] +--- + +Você critica a interface; não edita. Use a lente de auditoria do `redesign-existing-projects` e, se +instalada, a do `impeccable` (`/impeccable audit`). + +1. **Veja a tela.** Com o dev server de pé: `npx playwright screenshot --viewport-size=375,812 /tmp/ui-375.png` + e `--viewport-size=1280,800` para desktop. Abra as imagens com Read. Sem servidor, avalie pelo código e diga isso. +2. **Estados**: carregando, vazio, erro e sucesso existem em cada fluxo com dados. +3. **Acessibilidade**: HTML semântico, foco visível e em ordem, rótulos, contraste de texto >= 4.5:1. + Se houver Playwright: `@axe-core/playwright` sem violação `serious` ou `critical`. +4. **Responsivo**: nada corta ou sobrepõe em 375 px e em 1280 px. +5. **Padrão genérico**: gradiente roxo, glassmorphism sem motivo, cards idênticos, ícones decorativos, + microcopy vaga ("Unlock the power of..."). Aponte o que trocar. + +Entregue achados priorizados: o que está errado, onde (`arquivo:linha` ou região da screenshot) e a +correção concreta. No máximo 10. diff --git a/agents/verifier.md b/agents/verifier.md new file mode 100644 index 0000000..5a4fefe --- /dev/null +++ b/agents/verifier.md @@ -0,0 +1,17 @@ +--- +name: verifier +description: Roda o gate de qualidade no nível pedido e devolve a evidência - veredito, checagens que falharam com a saída relevante e o que ficou não verificado. Nunca edita código. +tools: Bash, Read +model: haiku +--- + +1. Rode `"${CLAUDE_PLUGIN_ROOT}/scripts/quality-gate" --tier N` com o nível recebido. +2. Leia `.dev-workflows/gate.json`. +3. Devolva: + - o veredito (`pass`, `fail` ou `incomplete`); + - cada checagem `fail` com as linhas da saída que mostram o motivo; + - a lista de checagens `unverified` (ferramenta ou configuração ausente); + - dependências novas, se houver; + - o `diff` (arquivos e linhas líquidas). + +Não edite nada e não reinterprete uma falha como aprovação. Se o gate não rodou, diga por quê. diff --git a/hooks/hooks.json b/hooks/hooks.json new file mode 100644 index 0000000..35408bd --- /dev/null +++ b/hooks/hooks.json @@ -0,0 +1,27 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { "type": "command", "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/hooks/bash_guard.py\"" } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { "type": "command", "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/hooks/post_edit.py\"", "timeout": 60 } + ] + } + ], + "Stop": [ + { + "hooks": [ + { "type": "command", "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/scripts/hooks/stop_gate.py\"" } + ] + } + ] + } +} diff --git a/qa/check_upstream.py b/qa/check_upstream.py new file mode 100644 index 0000000..d6a2ac0 --- /dev/null +++ b/qa/check_upstream.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Compares each vendored skill's recorded commit (skills/NOTICE.md) with its upstream HEAD. Exit 1 if any moved. + +python3 qa/check_upstream.py +""" +import os, re, subprocess, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def main(): + notice = open(os.path.join(ROOT, "skills", "NOTICE.md"), encoding="utf-8").read() + repos = {} + for row in re.findall(r"^\|\s*`[\w-]+`\s*\|(.+)$", notice, re.M): + cols = [c.strip() for c in row.split("|")] + repo = re.search(r"([\w.-]+/[\w.-]+)", cols[0]) + sha = re.search(r"`([0-9a-f]{7,40})`", cols[1]) + if repo and sha: + repos[repo.group(1)] = sha.group(1) + moved = 0 + for repo, sha in sorted(repos.items()): + p = subprocess.run(["git", "ls-remote", f"https://github.com/{repo}", "HEAD"], capture_output=True, text=True, timeout=60) + head = p.stdout.split()[0] if p.returncode == 0 and p.stdout else None + if head is None: + print(f"? {repo}: não consegui consultar") + elif head.startswith(sha): + print(f"ok {repo} {sha}") + else: + moved += 1 + print(f"-> {repo}: vendorizado {sha}, upstream {head[:7]} (https://github.com/{repo}/compare/{sha}...{head[:7]})") + return 1 if moved else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/qa/lint_skills.py b/qa/lint_skills.py new file mode 100644 index 0000000..f7f329a --- /dev/null +++ b/qa/lint_skills.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Structural lint for the plugin: frontmatter, sizes, references, links and leftover machine-specific paths. + +Run from anywhere: python3 qa/lint_skills.py (exit 1 on any error) +""" +import json, os, re, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +MAX_LINES = 150 +MAX_DESC = 1024 +FORBIDDEN = [r"~/\.hermes", r"vision_analyze", r"search_files", r"test_quality\.py", r"wf_quality_harness"] +MODELS = {"haiku", "sonnet", "opus", "inherit"} +TOOLS = {"Read", "Edit", "Write", "Bash", "Grep", "Glob", "WebFetch", "WebSearch", "NotebookEdit", "Agent", "Skill"} +errors = [] + + +def err(path, msg): + errors.append(f"{os.path.relpath(path, ROOT)}: {msg}") + + +def frontmatter(path): + text = open(path, encoding="utf-8").read() + m = re.match(r"---\n(.*?)\n---\n", text, re.S) + if not m: + err(path, "sem frontmatter") + return {}, text + fm = m.group(1) + meta = dict(re.findall(r"^([\w-]+):[ \t]*(.*)$", fm, re.M)) + for key in ("uses", "external", "skills"): + lst = re.search(rf"^\s*{key}:\s*\[(.*?)\]", fm, re.M) + if lst: + meta[key] = [s.strip().strip("'\"") for s in lst.group(1).split(",") if s.strip()] + return meta, text + + +def vendored(): + rows = open(os.path.join(ROOT, "skills", "NOTICE.md"), encoding="utf-8").read() + return set(re.findall(r"^\|\s*`([\w-]+)`\s*\|", rows, re.M)) + + +def check_links(path, text): + text = re.sub(r"```.*?```|`[^`\n]*`", "", text, flags=re.S) + for target in re.findall(r"\]\(([^)\s]+)\)", text): + if re.match(r"(https?:|mailto:|#)", target): + continue + p = os.path.normpath(os.path.join(os.path.dirname(path), target.split("#")[0])) + if not os.path.exists(p): + err(path, f"link quebrado: {target}") + + +def main(): + skills_dir = os.path.join(ROOT, "skills") + names = {d for d in os.listdir(skills_dir) if os.path.isfile(os.path.join(skills_dir, d, "SKILL.md"))} + third_party = vendored() + catalog = open(os.path.join(ROOT, "docs", "SKILLS.md"), encoding="utf-8").read() + + for name in sorted(names): + path = os.path.join(skills_dir, name, "SKILL.md") + meta, text = frontmatter(path) + if meta.get("name") != name: + err(path, f"name '{meta.get('name')}' difere da pasta '{name}'") + desc = meta.get("description", "") + if not desc: + err(path, "description vazia") + if name in third_party: + continue + if len(desc) > MAX_DESC: + err(path, f"description com {len(desc)} caracteres (máx {MAX_DESC})") + lines = text.count("\n") + if lines > MAX_LINES: + err(path, f"{lines} linhas (máx {MAX_LINES}); mova detalhes para references/") + for used in meta.get("uses", []): + if used not in names: + err(path, f"uses: '{used}' não existe em skills/") + for ext in meta.get("external", []): + if f"`{ext}`" not in catalog: + err(path, f"external: '{ext}' não está em docs/SKILLS.md") + for dirpath, _, files in os.walk(os.path.join(skills_dir, name)): + for f in files: + if f.endswith(".md"): + p = os.path.join(dirpath, f) + body = open(p, encoding="utf-8").read() + check_links(p, body) + for pat in FORBIDDEN: + if re.search(pat, body): + err(p, f"referência específica de máquina: {pat}") + + agents_dir = os.path.join(ROOT, "agents") + for f in sorted(os.listdir(agents_dir)): + path = os.path.join(agents_dir, f) + meta, text = frontmatter(path) + if meta.get("name") != f[:-3]: + err(path, f"name '{meta.get('name')}' difere do arquivo") + if meta.get("model") not in MODELS: + err(path, f"model '{meta.get('model')}' inválido") + bad = {t.strip() for t in meta.get("tools", "").split(",")} - TOOLS + if bad: + err(path, f"tools desconhecidas: {', '.join(sorted(bad))}") + for s in meta.get("skills", []): + if s not in names: + err(path, f"skills: '{s}' não existe em skills/") + for pat in FORBIDDEN: + if re.search(pat, text): + err(path, f"referência específica de máquina: {pat}") + + hooks = json.load(open(os.path.join(ROOT, "hooks", "hooks.json"))) + for groups in hooks["hooks"].values(): + for g in groups: + for h in g["hooks"]: + for script in re.findall(r"\$\{CLAUDE_PLUGIN_ROOT\}/([\w/.-]+)", h["command"]): + if not os.path.isfile(os.path.join(ROOT, script)): + err(os.path.join(ROOT, "hooks", "hooks.json"), f"script inexistente: {script}") + + for doc in ("README.md", "README.pt-BR.md", "CONTRIBUTING.md", os.path.join("docs", "SKILLS.md")): + p = os.path.join(ROOT, doc) + if os.path.exists(p): + check_links(p, open(p, encoding="utf-8").read()) + + for e in errors: + print("ERRO " + e) + print(f"{len(names)} skills, {len(os.listdir(agents_dir))} agentes, {len(errors)} erro(s)") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/qa/test_gate.py b/qa/test_gate.py new file mode 100644 index 0000000..0511469 --- /dev/null +++ b/qa/test_gate.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Smoke tests for scripts/quality-gate and the hook scripts, on a throwaway git repo. Stdlib only. + +python3 qa/test_gate.py +""" +import importlib.util, json, os, subprocess, sys, tempfile, unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +GATE = os.path.join(ROOT, "scripts", "quality-gate") +STOP = os.path.join(ROOT, "scripts", "hooks", "stop_gate.py") +spec = importlib.util.spec_from_file_location("bash_guard", os.path.join(ROOT, "scripts", "hooks", "bash_guard.py")) +bash_guard = importlib.util.module_from_spec(spec) +spec.loader.exec_module(bash_guard) + + +def run(cmd, cwd, stdin=None): + return subprocess.run(cmd, cwd=cwd, input=stdin, capture_output=True, text=True) + + +class GateTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.repo = self.tmp.name + for c in (["git", "init", "-q"], ["git", "config", "user.email", "t@t"], ["git", "config", "user.name", "t"]): + run(c, self.repo) + self.write("calc.py", "def add(a, b):\n return a + b\n") + self.write("check.py", "from calc import add\nassert add(1, 2) == 3\n") + self.write(".dev-workflows.toml", '[commands]\ntest = "python3 check.py"\nlint = "true"\ntypecheck = "true"\n') + self.write("package.json", '{"dependencies": {"left-pad": "1"}}') + run(["git", "add", "-A"], self.repo) + run(["git", "commit", "-qm", "init"], self.repo) + + def tearDown(self): + self.tmp.cleanup() + + def write(self, name, text): + open(os.path.join(self.repo, name), "w").write(text) + + def gate(self, tier=0): + p = run([sys.executable, GATE, "--tier", str(tier)], self.repo) + return p.returncode, json.load(open(os.path.join(self.repo, ".dev-workflows", "gate.json"))) + + def stop(self): + out = run([sys.executable, STOP], self.repo, json.dumps({"cwd": self.repo})).stdout + return json.loads(out)["reason"] if out.strip() else None + + def status(self, report, name): + return next(c["status"] for c in report["checks"] if c["name"] == name) + + def test_clean_tree_does_not_block(self): + self.assertIsNone(self.stop()) + + def test_change_without_gate_blocks_then_passing_gate_allows(self): + self.write("calc.py", "def add(a, b):\n return a + b\n\n\ndef sub(a, b):\n return a - b\n") + self.assertIn("sem gate", self.stop()) + code, report = self.gate() + self.assertEqual(code, 0) + self.assertEqual(self.status(report, "test"), "pass") + self.assertIsNone(self.stop()) + + def test_failing_test_fails_gate_and_blocks(self): + self.write("calc.py", "def add(a, b):\n return a - b\n") + code, report = self.gate() + self.assertEqual((code, report["verdict"]), (1, "fail")) + self.assertIn("test", self.stop()) + + def test_missing_tool_is_unverified_not_passed(self): + self.write(".dev-workflows.toml", '[commands]\ntest = "definitely-not-a-tool-xyz"\n') + self.write("calc.py", "def add(a, b):\n return b + a\n") + code, report = self.gate() + self.assertEqual(self.status(report, "test"), "unverified") + self.assertEqual(report["verdict"], "incomplete") + + def test_new_dependency_is_reported(self): + self.write("package.json", '{"dependencies": {"left-pad": "1", "is-odd": "3"}}') + self.write("calc.py", "def add(a, b):\n return a + b # touched\n") + _, report = self.gate() + self.assertEqual(report["new_dependencies"], ["npm:is-odd"]) + + def test_stale_gate_blocks(self): + self.write("calc.py", "def add(a, b):\n return a + b # v2\n") + self.gate() + os.utime(os.path.join(self.repo, ".dev-workflows", "gate.json"), (1, 1)) + self.assertIn("mudou depois", self.stop()) + + +class GuardTest(unittest.TestCase): + def test_decisions(self): + cases = {"git commit --no-verify -m x": "deny", "git push -f origin main": "deny", + "git push --force-with-lease": None, "rm -rf /": "deny", "rm -rf node_modules": None, + "git reset --hard": "ask", "npm test": None} + for cmd, expected in cases.items(): + self.assertEqual(bash_guard.decide(cmd)[0], expected, cmd) + + +if __name__ == "__main__": + unittest.main(verbosity=1) diff --git a/scripts/hooks/bash_guard.py b/scripts/hooks/bash_guard.py new file mode 100644 index 0000000..6981fd5 --- /dev/null +++ b/scripts/hooks/bash_guard.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""PreToolUse guard for shell commands: denies gate bypasses, asks before destructive git/db commands. + +Claude Code: reads the hook JSON on stdin and prints a permissionDecision. +opencode: `bash_guard.py --check ""` prints the reason and exits 2 when the command must not run. +""" +import json, re, sys + +DENY = [ + (r"(^|\s)--no-verify(\s|$)", "--no-verify pula os hooks do git. Corrija o que o hook reclamou em vez de pular."), + (r"\bgit\s+push\b(?=.*\s(--force|-f)(\s|$))(?!.*--force-with-lease)", "push --force reescreve histórico remoto. Use --force-with-lease e só com pedido explícito do usuário."), + (r"\brm\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r)[a-zA-Z]*\s+(/|~|\$HOME|/\*|\.\.)(\s|/?$)", "rm -rf na raiz, no home ou no diretório pai não roda."), +] +ASK = [ + (r"\bgit\s+reset\s+--hard\b", "git reset --hard descarta trabalho não commitado."), + (r"\bgit\s+clean\s+-[a-zA-Z]*f", "git clean -f apaga arquivos não rastreados."), + (r"\bgit\s+(checkout|restore)\s+(--\s+)?\.(\s|$)", "descarta todas as mudanças locais."), + (r"\b(DROP\s+(DATABASE|TABLE|SCHEMA)|TRUNCATE\s+TABLE)\b", "comando destrutivo de banco de dados."), +] + + +def decide(command): + for pattern, why in DENY: + if re.search(pattern, command, re.IGNORECASE): + return "deny", why + for pattern, why in ASK: + if re.search(pattern, command, re.IGNORECASE): + return "ask", why + return None, None + + +def main(): + if len(sys.argv) > 2 and sys.argv[1] == "--check": + decision, why = decide(sys.argv[2]) + if decision: # opencode has no "ask": both block, the agent must ask the user + print(f"[dev-workflows] {why} Peça confirmação ao usuário.") + return 2 + return 0 + event = json.load(sys.stdin) + decision, why = decide(event.get("tool_input", {}).get("command", "")) + if decision: + print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": decision, + "permissionDecisionReason": f"[dev-workflows] {why}"}}, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/hooks/post_edit.py b/scripts/hooks/post_edit.py new file mode 100644 index 0000000..db3e48c --- /dev/null +++ b/scripts/hooks/post_edit.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""PostToolUse: formats the edited file with the formatter the project already uses. Never fails the edit. + +Claude Code: reads tool_input.file_path from the hook JSON on stdin. +opencode: `post_edit.py --file `. +""" +import json, os, shutil, subprocess, sys + +PRETTIER_EXT = {".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".json", ".css", ".scss", ".html", ".vue", ".svelte", ".md", ".yaml", ".yml"} + + +def project_root(path): + d = os.path.dirname(os.path.abspath(path)) + while d != os.path.dirname(d): + if any(os.path.exists(os.path.join(d, m)) for m in ("package.json", "pyproject.toml", "go.mod", "Cargo.toml", ".git")): + return d + d = os.path.dirname(d) + return None + + +def uses_ruff(root): + if os.path.exists(os.path.join(root, "ruff.toml")) or os.path.exists(os.path.join(root, ".ruff.toml")): + return True + pyproject = os.path.join(root, "pyproject.toml") + return os.path.exists(pyproject) and "[tool.ruff" in open(pyproject).read() + + +def formatter(path, root): + ext = os.path.splitext(path)[1].lower() + prettier = os.path.join(root, "node_modules", ".bin", "prettier") + if ext in PRETTIER_EXT and os.path.exists(prettier): + return [prettier, "--write", "--log-level", "warn", path] + if ext == ".py" and shutil.which("ruff") and uses_ruff(root): + return ["ruff", "format", "--quiet", path] + if ext == ".go" and shutil.which("gofmt"): + return ["gofmt", "-w", path] + if ext == ".rs" and shutil.which("rustfmt"): + return ["rustfmt", path] + return None + + +def main(): + if len(sys.argv) > 2 and sys.argv[1] == "--file": + path = sys.argv[2] + else: + path = json.load(sys.stdin).get("tool_input", {}).get("file_path", "") + root = project_root(path) if path and os.path.isfile(path) else None + cmd = formatter(path, root) if root else None + if cmd: + try: + subprocess.run(cmd, cwd=root, capture_output=True, timeout=30) + except (subprocess.TimeoutExpired, OSError): + pass + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/hooks/stop_gate.py b/scripts/hooks/stop_gate.py new file mode 100644 index 0000000..ba4b031 --- /dev/null +++ b/scripts/hooks/stop_gate.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Stop hook: blocks "done" while uncommitted code changes lack a fresh, non-failing quality-gate report. + +Claude Code: reads the hook JSON on stdin, prints {"decision": "block", ...} to keep the agent working. +opencode: `stop_gate.py --check ` prints the reason and exits 2 when it would block. +Disable with DW_GATE=off. +""" +import json, os, subprocess, sys + +DOC_EXT = {".md", ".mdx", ".txt", ".rst", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"} +PLUGIN_ROOT = os.environ.get("CLAUDE_PLUGIN_ROOT") or os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +GATE = os.path.join(PLUGIN_ROOT, "scripts", "quality-gate") + + +def pending_code_files(cwd): + p = subprocess.run(["git", "status", "--porcelain", "--untracked-files=all"], cwd=cwd, capture_output=True, text=True) + if p.returncode != 0: + return None + files = [] + for line in p.stdout.splitlines(): + path = line[3:].split(" -> ")[-1].strip('"') + if line[:2].strip() == "D" or path.startswith(".dev-workflows/"): + continue + if os.path.splitext(path)[1].lower() not in DOC_EXT and os.path.isfile(os.path.join(cwd, path)): + files.append(path) + return files + + +def reason_to_block(cwd): + if os.environ.get("DW_GATE") == "off": + return None + top = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=cwd, capture_output=True, text=True) + if top.returncode != 0: + return None + root = top.stdout.strip() + files = pending_code_files(root) + if not files: + return None + run = f'"{GATE}" --tier ' + report = os.path.join(root, ".dev-workflows", "gate.json") + if not os.path.isfile(report): + return f"Há {len(files)} arquivo(s) de código alterados sem gate de qualidade. Rode {run} e trate o resultado antes de encerrar." + newest = max(os.path.getmtime(os.path.join(root, f)) for f in files) + if os.path.getmtime(report) < newest: + return f"O código mudou depois do último gate. Rode de novo {run} antes de encerrar." + data = json.load(open(report)) + if data.get("verdict") == "fail": + failed = ", ".join(c["name"] for c in data.get("checks", []) if c.get("status") == "fail") + return f"O gate falhou em: {failed}. Corrija (veja .dev-workflows/gate.json) ou explique ao usuário por que não dá para corrigir." + return None + + +def main(): + if len(sys.argv) > 2 and sys.argv[1] == "--check": + why = reason_to_block(sys.argv[2]) + if why: + print(why) + return 2 + return 0 + event = json.load(sys.stdin) + if event.get("stop_hook_active"): + return 0 + why = reason_to_block(event.get("cwd") or os.getcwd()) + if why: + print(json.dumps({"decision": "block", "reason": why}, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/install.py b/scripts/install.py new file mode 100644 index 0000000..92c20d8 --- /dev/null +++ b/scripts/install.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Install dev-workflows into Claude Code, opencode or Hermes Agent. + + python3 scripts/install.py claude # plugin via local marketplace (skills, agents, hooks) + python3 scripts/install.py opencode # skills + agents + plugin under ~/.config/opencode + python3 scripts/install.py hermes # skills under ~/.hermes/skills (no agents/hooks there) + +opencode and Hermes do not substitute ${CLAUDE_PLUGIN_ROOT}, so the copies point at this checkout: +keep it where it is, or re-run the install after moving it. +""" +import argparse, os, re, shutil, subprocess, sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +MARKER = ".dev-workflows-install" +TEXT_EXT = {".md", ".txt", ".json", ".toml", ".yaml", ".yml"} + + +def copy_tree(src, dst, force): + if os.path.exists(dst) and not os.path.exists(os.path.join(dst, MARKER)) and not force: + sys.exit(f"{dst} já existe e não foi instalado por este script. Use --force para sobrescrever.") + shutil.rmtree(dst, ignore_errors=True) + shutil.copytree(src, dst) + for dirpath, _, names in os.walk(dst): + for n in names: + if os.path.splitext(n)[1] in TEXT_EXT: + p = os.path.join(dirpath, n) + text = open(p, encoding="utf-8", errors="ignore").read() + if "${CLAUDE_PLUGIN_ROOT}" in text: + open(p, "w", encoding="utf-8").write(text.replace("${CLAUDE_PLUGIN_ROOT}", ROOT)) + open(os.path.join(dst, MARKER), "w").write(ROOT + "\n") + + +def install_skills(target_dir, force): + os.makedirs(target_dir, exist_ok=True) + names = sorted(d for d in os.listdir(os.path.join(ROOT, "skills")) + if os.path.isfile(os.path.join(ROOT, "skills", d, "SKILL.md"))) + for name in names: + copy_tree(os.path.join(ROOT, "skills", name), os.path.join(target_dir, name), force) + print(f"{len(names)} skills em {target_dir}") + + +def opencode_agent(path): + """Claude Code agent frontmatter -> opencode subagent frontmatter.""" + text = open(path, encoding="utf-8").read() + m = re.match(r"---\n(.*?)\n---\n(.*)", text, re.S) + meta = dict(re.findall(r"^(\w+):\s*(.*)$", m.group(1), re.M)) + tools = {t.strip() for t in meta.get("tools", "").split(",")} + skills = re.findall(r"[\w-]+", meta.get("skills", "")) + perm = {"edit": "allow" if tools & {"Edit", "Write"} else "deny", + "bash": "allow" if "Bash" in tools else "deny", + "webfetch": "allow" if "WebFetch" in tools else "deny"} + body = m.group(2).replace("${CLAUDE_PLUGIN_ROOT}", ROOT) + if skills: + body = f"Antes de começar, carregue a(s) skill(s): {', '.join(skills)}.\n\n" + body + head = ["# dev-workflows", f"description: {meta['description']}", "mode: subagent", "permission:"] + head += [f" {k}: {v}" for k, v in perm.items()] + return "---\n" + "\n".join(head) + "\n---\n\n" + body + + +def install_opencode(force): + base = os.path.expanduser("~/.config/opencode") + install_skills(os.path.join(base, "skills"), force) + agents_dir = os.path.join(base, "agents") + os.makedirs(agents_dir, exist_ok=True) + for f in sorted(os.listdir(os.path.join(ROOT, "agents"))): + dst = os.path.join(agents_dir, f) + if os.path.exists(dst) and "dev-workflows" not in open(dst, encoding="utf-8").read() and not force: + sys.exit(f"{dst} já existe e não é deste pacote. Use --force para sobrescrever.") + open(dst, "w", encoding="utf-8").write(opencode_agent(os.path.join(ROOT, "agents", f))) + plugins_dir = os.path.join(base, "plugins") + os.makedirs(plugins_dir, exist_ok=True) + plugin = open(os.path.join(ROOT, "adapters", "opencode", "dev-workflows.ts"), encoding="utf-8").read() + open(os.path.join(plugins_dir, "dev-workflows.ts"), "w", encoding="utf-8").write(plugin.replace("__DW_ROOT__", ROOT)) + print(f"agentes em {agents_dir}, plugin em {plugins_dir}/dev-workflows.ts") + + +def install_claude(): + for cmd in (["claude", "plugin", "marketplace", "add", ROOT], ["claude", "plugin", "install", "dev-workflows@dev-workflows"]): + print("$ " + " ".join(cmd)) + if subprocess.run(cmd).returncode != 0: + sys.exit("falhou; rode o comando acima manualmente para ver o erro") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("target", choices=["claude", "opencode", "hermes"]) + ap.add_argument("--force", action="store_true", help="sobrescreve pastas com o mesmo nome que não vieram deste script") + a = ap.parse_args() + if a.target == "claude": + install_claude() + elif a.target == "opencode": + install_opencode(a.force) + else: + install_skills(os.path.expanduser("~/.hermes/skills"), a.force) + print("Hermes: agentes e hooks não se aplicam; rode o gate manualmente.") + + +if __name__ == "__main__": + main() diff --git a/scripts/quality-gate b/scripts/quality-gate new file mode 100644 index 0000000..ae027d0 --- /dev/null +++ b/scripts/quality-gate @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +"""Deterministic quality gate: runs only the checks of the requested tier, scoped to the diff. + +Usage: quality-gate [--tier 0-3] [--base REF] [--dir PATH] [--list] +Writes .dev-workflows/gate.json in the project root. Exit 1 when any check fails. +A tool that is not installed is reported as "unverified", never as passed. +""" +import argparse, json, os, re, shutil, subprocess, sys, tempfile, time, tomllib + +CODE_EXT = {".py", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte", ".go", ".rs", + ".java", ".kt", ".rb", ".php", ".cs", ".sql", ".sh", ".css", ".scss", ".html"} +JS_EXT = {".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte"} + + +def sh(cmd, cwd, timeout=600): + t = time.time() + try: + p = subprocess.run(cmd, cwd=cwd, shell=isinstance(cmd, str), capture_output=True, text=True, timeout=timeout) + out, code = (p.stdout + p.stderr), p.returncode + except subprocess.TimeoutExpired: + out, code = f"timeout after {timeout}s", 124 + return code, out, round(time.time() - t, 1) + + +def git(args, cwd): + code, out, _ = sh(["git", *args], cwd, 60) + return out.strip() if code == 0 else None + + +def find_base(root, explicit): + if explicit: + return explicit + for ref in ("origin/HEAD", "origin/main", "origin/master", "main", "master"): + mb = git(["merge-base", "HEAD", ref], root) + if mb: + return mb + return "HEAD" if git(["rev-parse", "HEAD"], root) else None + + +def changed_files(root, base): + if base is None: + return [] + names = (git(["diff", "--name-only", "--diff-filter=d", base], root) or "").splitlines() + names += (git(["ls-files", "--others", "--exclude-standard"], root) or "").splitlines() + return sorted({n for n in names if n and not n.startswith(".dev-workflows/") and os.path.isfile(os.path.join(root, n))}) + + +def diff_stats(root, base, files): + added = removed = 0 + for line in (git(["diff", "--numstat", base], root) or "").splitlines() if base else []: + a, r, _ = (line.split("\t") + ["", ""])[:3] + added += int(a) if a.isdigit() else 0 + removed += int(r) if r.isdigit() else 0 + for f in (git(["ls-files", "--others", "--exclude-standard"], root) or "").splitlines(): + if f in files: + try: + added += sum(1 for _ in open(os.path.join(root, f), errors="ignore")) + except OSError: + pass + return {"files": len(files), "added": added, "removed": removed, "net": added - removed} + + +def deps_at(root, rev): + """Dependency names declared in package.json / requirements*.txt / pyproject.toml at a revision (None = working tree).""" + def read(path): + if rev is None: + p = os.path.join(root, path) + return open(p).read() if os.path.isfile(p) else None + return git(["show", f"{rev}:{path}"], root) + + names = set() + pkg = read("package.json") + if pkg: + try: + d = json.loads(pkg) + for k in ("dependencies", "devDependencies", "optionalDependencies"): + names |= {f"npm:{n}" for n in d.get(k, {})} + except ValueError: + pass + for req in [f for f in os.listdir(root) if re.fullmatch(r"requirements.*\.txt", f)]: + for line in (read(req) or "").splitlines(): + m = re.match(r"\s*([A-Za-z0-9_.\-]+)", line) + if m and not line.strip().startswith(("#", "-")): + names.add(f"py:{m.group(1).lower()}") + py = read("pyproject.toml") + if py: + try: + proj = tomllib.loads(py).get("project", {}) + for spec in proj.get("dependencies", []) + sum(proj.get("optional-dependencies", {}).values(), []): + m = re.match(r"\s*([A-Za-z0-9_.\-]+)", spec) + if m: + names.add(f"py:{m.group(1).lower()}") + except tomllib.TOMLDecodeError: + pass + return names + + +def load_config(root): + p = os.path.join(root, ".dev-workflows.toml") + if not os.path.isfile(p): + return {} + with open(p, "rb") as f: + return tomllib.load(f) + + +def local_bin(root, name): + p = os.path.join(root, "node_modules", ".bin", name) + return p if os.path.exists(p) else shutil.which(name) + + +def node_pm(root): + for lock, pm in (("pnpm-lock.yaml", "pnpm"), ("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun")): + if os.path.exists(os.path.join(root, lock)): + return pm + return "npm" + + +def plan_checks(root, cfg, files, base): + """Returns [(name, tier, cmd|None, kind)] ; kind: gate (fails the gate) | info (report only).""" + cmds = cfg.get("commands", {}) + exts = {os.path.splitext(f)[1] for f in files} + js_files = [f for f in files if os.path.splitext(f)[1] in JS_EXT] + py_files = [f for f in files if f.endswith(".py")] + checks = [] + + pkg = {} + if os.path.isfile(os.path.join(root, "package.json")): + try: + pkg = json.load(open(os.path.join(root, "package.json"))).get("scripts", {}) + except ValueError: + pkg = {} + pm = node_pm(root) + is_py = any(os.path.exists(os.path.join(root, f)) for f in ("pyproject.toml", "setup.py", "requirements.txt")) + pyproject = {} + if os.path.isfile(os.path.join(root, "pyproject.toml")): + try: + pyproject = tomllib.load(open(os.path.join(root, "pyproject.toml"), "rb")) + except tomllib.TOMLDecodeError: + pass + tool = pyproject.get("tool", {}) + + def pick(key, *candidates): + if key in cmds: + return cmds[key] + return next((c for c in candidates if c), None) + + lint = pick("lint", + f"{pm} run lint" if "lint" in pkg else None, + (local_bin(root, "eslint") and js_files and [local_bin(root, "eslint"), *js_files]), + (shutil.which("ruff") and py_files and ["ruff", "check", *py_files]), + ("go vet ./..." if os.path.exists(os.path.join(root, "go.mod")) else None), + ("cargo clippy -- -D warnings" if os.path.exists(os.path.join(root, "Cargo.toml")) else None)) + typecheck = pick("typecheck", + next((f"{pm} run {s}" for s in ("typecheck", "type-check", "tsc") if s in pkg), None), + (os.path.exists(os.path.join(root, "tsconfig.json")) and local_bin(root, "tsc") and [local_bin(root, "tsc"), "--noEmit"]), + (("pyright" in tool or os.path.exists(os.path.join(root, "pyrightconfig.json"))) and shutil.which("pyright") and ["pyright"]), + ("mypy" in tool and shutil.which("mypy") and ["mypy", "."])) + venv_py = next((os.path.join(root, v, "bin", "python") for v in (".venv", "venv") + if os.path.exists(os.path.join(root, v, "bin", "python"))), "python3") + test = pick("test", + f"{pm} run test" if "test" in pkg else None, + (is_py and [venv_py, "-m", "pytest", "-q"]), + ("go test ./..." if os.path.exists(os.path.join(root, "go.mod")) else None), + ("cargo test" if os.path.exists(os.path.join(root, "Cargo.toml")) else None)) + build = pick("build", f"{pm} run build" if "build" in pkg else None) + + checks += [("lint", 0, lint, "gate"), ("typecheck", 0, typecheck, "gate"), ("test", 0, test, "gate")] + checks.append(("secrets", 0, "@gitleaks" if shutil.which("gitleaks") else None, "gate")) + + cov = os.path.join(root, cfg.get("coverage", {}).get("report", "coverage.xml")) + fail_under = cfg.get("thresholds", {}).get("diff_coverage", 80) + checks.append(("diff-coverage", 1, + shutil.which("diff-cover") and os.path.isfile(cov) and base + and ["diff-cover", cov, f"--compare-branch={base}", f"--fail-under={fail_under}"], "gate")) + checks.append(("semgrep", 1, shutil.which("semgrep") and base and + ["semgrep", "scan", "--config", "p/default", "--error", "--metrics=off", "--quiet", + "--baseline-commit", base], "gate")) + dead = (local_bin(root, "knip") and pkg and [local_bin(root, "knip"), "--no-exit-code"]) or \ + (shutil.which("vulture") and py_files and ["vulture", *py_files, "--min-confidence", "80"]) + checks.append(("dead-code", 1, dead, "info")) + + checks.append(("build", 2, build, "gate") if build else ("build", 2, "@skip", "gate")) + stryker_cfg = any(os.path.exists(os.path.join(root, f)) for f in + ("stryker.config.mjs", "stryker.config.js", "stryker.config.json", "stryker.conf.js", ".stryker.conf.json")) + mut = None + if stryker_cfg and local_bin(root, "stryker") and js_files: + mut = [local_bin(root, "stryker"), "run", "--mutate", ",".join(js_files)] + elif "mutmut" in tool and shutil.which("mutmut"): + mut = ["mutmut", "run"] # ponytail: mutmut 3 runs its configured paths, not only the diff + checks.append(("mutation", 2, cmds.get("mutation", mut), "gate")) + checks.append(("osv-scanner", 2, shutil.which("osv-scanner") and ["osv-scanner", "scan", "source", "--recursive", "."], "gate")) + cruiser = next((f for f in (".dependency-cruiser.js", ".dependency-cruiser.cjs", ".dependency-cruiser.json") + if os.path.exists(os.path.join(root, f))), None) + arch = (cruiser and local_bin(root, "depcruise") and js_files and [local_bin(root, "depcruise"), "--config", cruiser, *js_files]) or \ + (("importlinter" in tool or os.path.exists(os.path.join(root, ".importlinter"))) and shutil.which("lint-imports") and ["lint-imports"]) + checks.append(("architecture", 2, cmds.get("architecture", arch) or "@skip", "gate")) + checks.append(("duplication", 2, local_bin(root, "jscpd") and js_files and [local_bin(root, "jscpd"), *js_files], "info")) + + checks.append(("trivy", 3, shutil.which("trivy") and + ["trivy", "fs", "--exit-code", "1", "--severity", "HIGH,CRITICAL", "--scanners", "vuln,misconfig,secret", "."], "gate")) + if cfg.get("spec", {}).get("file"): + checks.append(("traceability", 3, "@trace", "gate")) + + for extra in cfg.get("check", []): + checks.append((extra["name"], int(extra.get("tier", 2)), extra["cmd"], extra.get("kind", "gate"))) + + if not exts & CODE_EXT and files: + checks = [c for c in checks if c[0] == "secrets"] + return checks + + +def run_gitleaks(root, files): + with tempfile.TemporaryDirectory() as tmp: + for f in files: + dst = os.path.join(tmp, f) + os.makedirs(os.path.dirname(dst), exist_ok=True) + shutil.copy2(os.path.join(root, f), dst) + return sh(["gitleaks", "dir", "--no-banner", "--redact", tmp], root) + + +def run_trace(root, cfg): + spec = cfg["spec"] + text = open(os.path.join(root, spec["file"]), errors="ignore").read() + ids = sorted(set(re.findall(r"\bREQ-\d+\b", text))) + corpus = "" + for d in spec.get("tests", ["tests", "test", "src"]): + for dirpath, _, names in os.walk(os.path.join(root, d)): + for n in names: + corpus += open(os.path.join(dirpath, n), errors="ignore").read() + missing = [i for i in ids if i not in corpus] + msg = f"{len(ids)} requisitos, sem teste: {', '.join(missing) or 'nenhum'}" + return (1 if missing or not ids else 0), msg, 0.0 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--tier", type=int, default=int(os.environ.get("DW_TIER", 1)), choices=range(4)) + ap.add_argument("--base") + ap.add_argument("--dir", default=".") + ap.add_argument("--list", action="store_true", help="show the planned checks without running them") + a = ap.parse_args() + + root = git(["rev-parse", "--show-toplevel"], a.dir) or os.path.abspath(a.dir) + cfg = load_config(root) + base = find_base(root, a.base) + files = changed_files(root, base) + planned = [c for c in plan_checks(root, cfg, files, base) if c[1] <= a.tier] + + if a.list: + for name, tier, cmd, kind in planned: + state = "skip" if cmd == "@skip" else ("unverified (tool/config missing)" if not cmd else "run") + print(f"T{tier} {name:14} {kind:4} {state}") + return 0 + + results = [] + for name, tier, cmd, kind in planned: + if cmd == "@skip": + continue + if not cmd: + results.append({"name": name, "tier": tier, "kind": kind, "status": "unverified"}) + continue + if cmd == "@gitleaks": + code, out, secs = run_gitleaks(root, files) if files else (0, "no changed files", 0.0) + elif cmd == "@trace": + code, out, secs = run_trace(root, cfg) + else: + code, out, secs = sh(cmd, root, int(cfg.get("timeout", 600))) + missing_tool = code == 127 or re.search(r"No module named (pytest|mypy|pyright|ruff)\b", out) + status = "unverified" if missing_tool else "info" if kind == "info" else ("pass" if code == 0 else "fail") + results.append({"name": name, "tier": tier, "kind": kind, "status": status, "exit": code, "seconds": secs, + "cmd": cmd if isinstance(cmd, str) else " ".join(cmd), + "output_tail": "\n".join(out.strip().splitlines()[-30:])}) + + new_deps = sorted(deps_at(root, None) - deps_at(root, base)) if base else [] + verdict = "fail" if any(r["status"] == "fail" for r in results) else \ + "incomplete" if any(r["status"] == "unverified" for r in results) else "pass" + report = {"verdict": verdict, "tier": a.tier, "base": base, "generated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"), + "diff": diff_stats(root, base, files), "changed_files": files, "new_dependencies": new_deps, "checks": results} + + out_dir = os.path.join(root, ".dev-workflows") + os.makedirs(out_dir, exist_ok=True) + json.dump(report, open(os.path.join(out_dir, "gate.json"), "w"), indent=2, ensure_ascii=False) + with open(os.path.join(out_dir, "log.jsonl"), "a") as log: + log.write(json.dumps({k: report[k] for k in ("generated_at", "verdict", "tier", "diff")}) + "\n") + exclude = os.path.join(root, ".git", "info", "exclude") + if os.path.isdir(os.path.dirname(exclude)): + current = open(exclude).read() if os.path.exists(exclude) else "" + if ".dev-workflows/" not in current: + with open(exclude, "a") as f: + f.write("\n.dev-workflows/\n") + + icon = {"pass": "ok", "fail": "FALHOU", "unverified": "não verificado", "info": "info"} + for r in results: + print(f" [{icon[r['status']]:>14}] T{r['tier']} {r['name']}") + d = report["diff"] + print(f"diff: {d['files']} arquivos, +{d['added']} -{d['removed']} (líquido {d['net']})") + if new_deps: + print("dependências novas (justifique cada uma): " + ", ".join(new_deps)) + print(f"veredito: {verdict} -> {os.path.relpath(os.path.join(out_dir, 'gate.json'), os.getcwd())}") + return 1 if verdict == "fail" else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/api-security-review/plays/api-security-review.md b/skills/api-security-review/plays/api-security-review.md new file mode 100644 index 0000000..335958b --- /dev/null +++ b/skills/api-security-review/plays/api-security-review.md @@ -0,0 +1,1506 @@ +# Play: API Security Review + +Comprehensive API security assessment against OWASP API Security Top 10 (2023) with real-world attack scenarios, automated testing integration, and detailed remediation guidance. + +## Trigger Conditions + +Use this play when: +- Reviewing OpenAPI/Swagger specifications or API documentation +- Auditing REST, GraphQL, gRPC, or SOAP API implementations +- Testing API authentication and authorization mechanisms +- Reviewing API gateway configurations (Kong, nginx, Envoy, AWS API Gateway) +- Conducting pre-deployment security assessments +- Performing API penetration testing or security audits +- A user asks to "test my API for security issues" + +## Inputs + +- OpenAPI/Swagger specification (YAML/JSON) or API documentation +- API source code (routes, controllers, middleware, authentication logic) +- API gateway and infrastructure configurations +- Authentication implementation details (JWT, OAuth, API keys) +- Environment information (production, staging, development) +- Previous security assessment reports (if available) + +## Procedure + +### Phase 1: Discovery & Reconnaissance + +#### 1.1 API Surface Enumeration + +**With OpenAPI Spec:** +```bash +# Parse and analyze OpenAPI spec +# Look for: +- Total endpoints and HTTP methods +- Authentication requirements per endpoint +- Request/response schemas +- Rate limiting documentation +- Deprecated endpoints +``` + +**Without OpenAPI Spec (Code Analysis):** +- Scan route definitions in framework-specific patterns: + - Express: `app.get()`, `router.post()` + - Django: `path()`, `url()` + - Rails: `resources`, `get/post/put/delete` + - Spring: `@GetMapping`, `@RequestMapping` + - FastAPI: `@app.get()`, decorator-based routes + +**Key Questions:** +- How many endpoints exist? +- Which require authentication vs. public? +- What data types are exchanged? +- Are there file upload endpoints? +- Are there admin/debug endpoints? + +#### 1.2 Authentication Mechanism Identification + +Document all auth mechanisms in use: + +| Mechanism | Indicators | Security Considerations | +|-----------|-----------|------------------------| +| **JWT** | `Authorization: Bearer eyJ...` | Algorithm, signing key strength, expiration | +| **OAuth 2.0** | `/oauth/authorize`, `/oauth/token` | Flow type, PKCE, state parameter, redirect URI | +| **API Keys** | `X-API-Key`, `api_key` query param | Key rotation, transmission security, scope | +| **Session Cookies** | `Set-Cookie: sessionid=...` | HttpOnly, Secure, SameSite, expiration | +| **mTLS** | Client certificate requirements | Certificate validation, revocation | +| **Basic Auth** | `Authorization: Basic base64` | HTTPS enforcement, credential storage | + +### Phase 2: Authentication Security Assessment + +#### 2.1 JWT Security Testing + +**Common JWT Vulnerabilities:** + +1. **Algorithm Confusion (CVE-2015-9235)** + ``` + Attack: Change algorithm from RS256 to none or HS256 + Header: {"alg":"none","typ":"JWT"} + Result: Token accepted without verification + ``` + +2. **Weak Signing Keys** + ```bash + # Test for weak secrets if using HS256 + # Use jwt_tool or hashcat for brute force + jwt_tool.py token_here -C -d /usr/share/wordlists/rockyou.txt + ``` + +3. **Missing Expiration** + ``` + Check: Does payload contain "exp" claim? + Risk: Tokens valid forever if stolen + ``` + +4. **Token Storage Issues** + ```javascript + // Insecure: localStorage (XSS accessible) + localStorage.setItem('jwt', token); + + // More secure: httpOnly cookie + document.cookie = "jwt=" + token + "; HttpOnly; Secure; SameSite=Strict"; + ``` + +**Testing Checklist:** +- [ ] Test algorithm confusion (change alg to "none") +- [ ] Attempt key confusion attacks (RS256 → HS256) +- [ ] Check for missing expiration (exp claim) +- [ ] Verify signature validation cannot be bypassed +- [ ] Test token revocation mechanisms +- [ ] Check for sensitive data in JWT payload + +#### 2.2 OAuth 2.0 Security Testing + +**Critical Checks:** + +1. **Authorization Code Flow** + ``` + Required: PKCE (Proof Key for Code Exchange) + Check: code_challenge and code_verifier parameters + Risk: Without PKCE, auth codes can be stolen and used + ``` + +2. **State Parameter** + ``` + Required: Random state parameter to prevent CSRF + Check: Is state validated on callback? + Attack: Omit state → CSRF login attack + ``` + +3. **Redirect URI Validation** + ``` + Check: Is redirect_uri strictly validated? + Attack: redirect_uri=https://attacker.com/callback + Risk: Authorization code/token sent to attacker + ``` + +4. **Scope Validation** + ``` + Check: Can user modify requested scopes? + Attack: Change scope=read to scope=admin + Risk: Privilege escalation via scope manipulation + ``` + +**Testing Checklist:** +- [ ] Verify PKCE implementation for public clients +- [ ] Test state parameter CSRF protection +- [ ] Attempt redirect URI manipulation +- [ ] Test scope escalation attacks +- [ ] Check for open redirect vulnerabilities +- [ ] Verify token endpoint authentication + +#### 2.3 API Key Security + +**Common Issues:** + +1. **Key Exposure** + ```bash + # Search for hardcoded keys + grep -r "api_key\|apikey\|api-key" --include="*.js" --include="*.py" --include="*.env" + + # Check client-side code + # API keys in frontend code can be stolen + ``` + +2. **Insufficient Scope** + ``` + Issue: Single key with full access + Best Practice: Scoped keys (read-only, write, admin) + ``` + +3. **Missing Rotation** + ``` + Check: Can keys be rotated without downtime? + Risk: Compromised keys valid indefinitely + ``` + +### Phase 3: OWASP API Top 10 Deep Assessment + +#### API1: Broken Object Level Authorization (BOLA/IDOR) + +> **Risk**: Attackers access other users' data by manipulating object IDs + +**Real-World Impact**: +- **2019**: First American Financial exposed 885 million records via IDOR +- **2020**: Twitter API IDOR allowed viewing protected tweets +- **2021**: Facebook IDOR exposed private posts + +**Attack Scenarios:** + +1. **Sequential ID Manipulation** + ```http + GET /api/users/123/orders + + # Try: + GET /api/users/124/orders # Access other user's orders + GET /api/users/1/orders # Access admin's orders + ``` + +2. **UUID Predictability** + ``` + If using predictable UUIDv1 (timestamp-based): + Generate nearby UUIDs to find other users + ``` + +3. **Batch Endpoint Bypass** + ```http + POST /api/orders/bulk + { + "order_ids": [1001, 1002, 1003, 1004] # Can access any IDs? + } + ``` + +4. **Indirect Object References** + ```http + GET /api/orders?id=1001 + + # vs + + GET /api/orders?id=1001&user_id=123 # Is user_id validated? + ``` + +**Testing Approach:** + +1. **Map Object IDs**: Identify all endpoints accepting object IDs +2. **Cross-User Testing**: + - Create User A and User B accounts + - Have User A create resources + - Attempt to access with User B's credentials +3. **Batch Testing**: Test if batch endpoints filter by ownership +4. **File Access**: Test file download endpoints with different IDs +5. **IDOR Automation**: + ```bash + # Use Burp Intruder or custom script + # Iterate through IDs and check for 200 responses + for i in {1..1000}; do + curl -H "Authorization: Bearer $TOKEN" \ + "https://api.example.com/orders/$i" | grep -q "order_id" && echo "Found: $i" + done + ``` + +**Remediation:** +```python +# BAD: No ownership check +def get_order(order_id): + return Order.objects.get(id=order_id) + +# GOOD: Verify ownership +def get_order(order_id, user): + return Order.objects.get(id=order_id, user=user) + # Or: Check ownership after retrieval + order = Order.objects.get(id=order_id) + if order.user_id != user.id: + raise PermissionDenied() + return order +``` + +#### API2: Broken Authentication + +> **Risk**: Weak authentication allows account takeover + +**Real-World Impact**: +- **2022**: Uber breach via compromised contractor account +- **2023**: 23andMe breach via credential stuffing + +**Attack Scenarios:** + +1. **Credential Stuffing** + ```bash + # Automated login attempts with breached credentials + # APIs often lack CAPTCHA or rate limiting + ``` + +2. **JWT None Algorithm** + ``` + Header: {"alg":"none","typ":"JWT"} + Payload: {"user_id":1,"role":"admin"} + Signature: (empty) + + Result: Server accepts unsigned token + ``` + +3. **Weak Password Policy** + ``` + POST /api/login + {"username":"admin","password":"123456"} + + # Test common passwords + # Check minimum length requirements + ``` + +4. **Session Fixation** + ``` + Attacker sets session ID + Victim logs in with attacker's session ID + Attacker uses same session ID to access account + ``` + +**Testing Approach:** + +1. **Brute Force Testing**: + ```bash + # Test login endpoint rate limiting + for i in {1..100}; do + curl -X POST https://api.example.com/login \ + -d "username=admin&password=wrong$i" + done + # Check if account locks or IP is blocked + ``` + +2. **Token Security**: + - Decode JWT and analyze claims + - Test algorithm confusion + - Check expiration and refresh mechanisms + - Test token revocation + +3. **Password Policy**: + - Test minimum length (should be 12+) + - Test complexity requirements + - Check common password blocking + - Verify secure password reset flow + +4. **Multi-Factor Authentication**: + - Is MFA enforced for sensitive operations? + - Can MFA be bypassed? + - Are backup codes secure? + +**Remediation:** +```python +# Implement rate limiting +from django_ratelimit.decorators import ratelimit + +@ratelimit(key='ip', rate='5/m', method='POST') +def login(request): + # Login logic + pass + +# Strong password validation +from django.contrib.auth.password_validation import validate_password + +def validate_user_password(password): + try: + validate_password(password) + except ValidationError as e: + raise e + +# Secure JWT configuration +JWT_SETTINGS = { + 'ALGORITHM': 'HS256', # Use strong algorithms only + 'VERIFY_EXPIRATION': True, + 'EXPIRATION_DELTA': timedelta(minutes=15), + 'REFRESH_EXPIRATION_DELTA': timedelta(days=7), +} +``` + +#### API3: Broken Object Property Level Authorization + +> **Risk**: Mass assignment and data over-exposure + +**Real-World Impact**: +- **2012**: GitHub mass assignment allowed unauthorized repo access +- **2019**: Facebook mass assignment exposed user data + +**Attack Scenarios:** + +1. **Mass Assignment** + ```http + POST /api/users + { + "username": "newuser", + "email": "user@example.com", + "password": "password123", + "role": "admin", # Should not be user-settable + "is_verified": true # Should not be user-settable + } + ``` + +2. **Response Over-Exposure** + ```http + GET /api/users/123 + + Response: + { + "id": 123, + "username": "john", + "email": "john@example.com", + "password_hash": "$2b$12$...", # Should not be exposed! + "ssn": "123-45-6789", # PII exposure + "internal_notes": "Difficult customer" + } + ``` + +3. **Field-Level Authorization Bypass** + ```http + PUT /api/users/123 + { + "salary": 200000 # Can regular users modify this? + } + ``` + +**Testing Approach:** + +1. **Mass Assignment Testing**: + ```python + # Send extra fields in POST/PUT requests + payload = { + "username": "test", + "email": "test@test.com", + "password": "password", + "role": "admin", # Try to escalate + "is_admin": True, + "credit_balance": 10000 + } + ``` + +2. **Response Analysis**: + - Capture all API responses + - Look for sensitive fields (passwords, tokens, PII) + - Compare responses for different user roles + - Check if internal fields are exposed + +3. **GraphQL Over-Exposure**: + ```graphql + # Request fields you shouldn't see + query { + user(id: 123) { + id + name + email + password # Should be rejected + ssn # Should be rejected + salary # Should be rejected for non-admins + } + } + ``` + +**Remediation:** +```python +# Use allowlist approach +ALLOWED_USER_FIELDS = ['username', 'email', 'password'] + +def update_user(user_id, data, current_user): + # Filter input to allowed fields only + filtered_data = {k: v for k, v in data.items() + if k in ALLOWED_USER_FIELDS} + + # Check field-level permissions + if 'role' in data and not current_user.is_admin: + raise PermissionDenied("Cannot modify role") + + return User.objects.filter(id=user_id).update(**filtered_data) + +# Response serialization +class UserSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ['id', 'username', 'email'] # Explicit allowlist + # Never include: password, ssn, internal_notes +``` + +#### API4: Unrestricted Resource Consumption + +> **Risk**: DoS via resource exhaustion, financial drain + +**Real-World Impact**: +- **2023**: OpenAI API abuse cost companies thousands +- **2022**: GraphQL query DoS attacks on multiple platforms + +**Attack Scenarios:** + +1. **Rate Limit Bypass** + ```http + # Distributed attack from multiple IPs + # Or using different API keys + # Or changing User-Agent headers + ``` + +2. **Expensive Query Abuse** + ```graphql + # Deeply nested GraphQL query + query { + users { + posts { + comments { + author { + posts { + comments { + author { + posts { ... } # Infinite recursion potential + } + } + } + } + } + } + } + } + ``` + +3. **Large Payload Attacks** + ```http + POST /api/upload + Content-Length: 1000000000 # 1GB file + + # Or JSON bomb: + {"a":{"a":{"a":{"a":...}}}} # Deeply nested JSON + ``` + +4. **Pagination Abuse** + ```http + GET /api/items?limit=1000000 # Request all records + GET /api/items?page=1&per_page=10000 # Large page size + ``` + +**Testing Approach:** + +1. **Rate Limit Testing**: + ```bash + # Test from single IP + for i in {1..1000}; do + curl https://api.example.com/data + done + + # Test bypass methods: + # - Different API keys + # - Rotating User-Agents + # - Distributed requests + ``` + +2. **GraphQL DoS**: + ```bash + # Test query complexity + # Test query depth + # Test expensive operations + ``` + +3. **Resource Exhaustion**: + - Upload extremely large files + - Send deeply nested JSON + - Request massive result sets + - Trigger expensive database queries + +**Remediation:** +```python +# Rate limiting +from django_ratelimit.decorators import ratelimit + +@ratelimit(key='user', rate='100/h', method=['GET', 'POST']) +def api_endpoint(request): + pass + +# GraphQL safeguards +GRAPHQL_SETTINGS = { + 'MAX_DEPTH': 10, + 'MAX_COMPLEXITY': 1000, + 'DISABLE_INTROSPECTION': True, # In production +} + +# Pagination limits +MAX_PAGE_SIZE = 100 +DEFAULT_PAGE_SIZE = 20 + +def get_items(request): + page_size = min( + int(request.GET.get('limit', DEFAULT_PAGE_SIZE)), + MAX_PAGE_SIZE + ) + return Item.objects.all()[:page_size] + +# File upload limits +MAX_UPLOAD_SIZE = 10 * 1024 * 1024 # 10MB + +# Timeout configuration +REQUEST_TIMEOUT = 30 # seconds +``` + +#### API5: Broken Function Level Authorization + +> **Risk**: Access to admin/sensitive functions without proper authorization + +**Real-World Impact**: +- **2020**: Twitter admin tool breach +- **2021**: Parler admin API exposed + +**Attack Scenarios:** + +1. **Admin Endpoint Discovery** + ```http + GET /api/admin/users # Try common admin paths + GET /api/v1/admin/config + GET /api/internal/audit-logs + GET /api/debug/info + ``` + +2. **HTTP Method Switching** + ```http + GET /api/users/123 # Allowed for regular users + DELETE /api/users/123 # Should require admin, but is it checked? + PUT /api/users/123/role # Can users change their own role? + ``` + +3. **Parameter-Based Access Control** + ```http + POST /api/users + { + "username": "test", + "role": "admin" # Is this validated server-side? + } + ``` + +**Testing Approach:** + +1. **Endpoint Enumeration**: + ```bash + # Use wordlists to find admin endpoints + # Common paths: /admin, /internal, /debug, /system + ``` + +2. **Method Testing**: + ```bash + # For each endpoint, test all HTTP methods + curl -X GET /api/resource + curl -X POST /api/resource + curl -X PUT /api/resource + curl -X DELETE /api/resource + curl -X PATCH /api/resource + ``` + +3. **Role Escalation**: + - Create regular user account + - Attempt to access admin endpoints + - Try to modify role/privilege fields + +**Remediation:** +```python +# Centralized authorization decorator +from functools import wraps + +def require_admin(f): + @wraps(f) + def decorated_function(request, *args, **kwargs): + if not request.user.is_admin: + return Response( + {"error": "Admin access required"}, + status=403 + ) + return f(request, *args, **kwargs) + return decorated_function + +@require_admin +def admin_endpoint(request): + pass + +# Middleware approach +class AdminAuthorizationMiddleware: + def __init__(self, get_response): + self.get_response = get_response + self.admin_paths = ['/api/admin/', '/api/internal/'] + + def __call__(self, request): + if any(request.path.startswith(path) for path in self.admin_paths): + if not request.user.is_admin: + return HttpResponseForbidden() + return self.get_response(request) +``` + +#### API6: Unrestricted Access to Sensitive Business Flows + +> **Risk**: Automated abuse of business logic + +**Real-World Impact**: +- **Ticket scalping**: Bots buying all concert tickets +- **E-commerce**: Inventory hoarding, price scraping +- **Crypto**: Flash loan attacks via API manipulation + +**Attack Scenarios:** + +1. **Inventory Exhaustion** + ```http + POST /api/cart/add + {"product_id": 123, "quantity": 999999} # Buy all inventory + ``` + +2. **Automated Purchasing** + ```http + # Script that completes purchase faster than humans + # Bypassing any client-side rate limits + ``` + +3. **Price Manipulation** + ```http + POST /api/order + { + "items": [...], + "total": 1.00 # Is total calculated server-side? + } + ``` + +4. **Reservation Abuse** + ```http + POST /api/reservations + {"resource_id": 123, "start": "2024-01-01", "end": "2025-12-31"} + # Reserve resource for entire year + ``` + +**Testing Approach:** + +1. **Business Logic Testing**: + - Attempt to complete purchases with modified prices + - Try to add negative quantities + - Test race conditions in multi-step flows + - Attempt to bypass payment steps + +2. **Automation Testing**: + ```python + # Script to test if flows can be automated + import requests + import time + + start = time.time() + for i in range(100): + requests.post('/api/purchase', json={...}) + elapsed = time.time() - start + + # If no rate limiting, 100 requests complete quickly + ``` + +**Remediation:** +```python +# Server-side price calculation +def create_order(items, user): + total = sum(item.product.price * item.quantity for item in items) + # Never trust client-provided total + + # Inventory checks + for item in items: + if item.quantity > item.product.available_stock: + raise ValidationError("Insufficient inventory") + + # Rate limiting per user + if user.orders.filter(created_at__gte=timezone.now() - timedelta(hours=1)).count() > 10: + raise RateLimitError("Too many orders") + + return Order.objects.create(user=user, items=items, total=total) + +# CAPTCHA for sensitive operations +from django_recaptcha.fields import ReCaptchaField + +class PurchaseForm(forms.Form): + recaptcha = ReCaptchaField() + # ... other fields +``` + +#### API7: Server-Side Request Forgery (SSRF) + +> **Risk**: Server makes requests to attacker-controlled or internal resources + +**Real-World Impact**: +- **2019**: Capital One breach via SSRF (100M records) +- **2021**: Multiple cloud metadata service exploits + +**Attack Scenarios:** + +1. **Cloud Metadata Access** + ```http + GET /api/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ + # Retrieves AWS credentials + ``` + +2. **Internal Service Access** + ```http + GET /api/fetch?url=http://localhost:8080/admin + GET /api/fetch?url=http://internal-api.company.local/secrets + ``` + +3. **URL Bypass Techniques** + ``` + http://127.0.0.1 → localhost bypass + http://0177.0.0.1 → Octal encoding + http://2130706433 → Decimal IP + http://0x7f.0x0.0x0.0x1 → Hex encoding + http://[::ffff:127.0.0.1] → IPv6 + http://127.1 → Shortened + ``` + +4. **DNS Rebinding** + ``` + Attacker controls DNS that resolves to: + - First request: legitimate.com → 1.2.3.4 + - Second request: attacker.com → 169.254.169.254 + ``` + +**Testing Approach:** + +1. **Basic SSRF Testing**: + ```bash + # Test internal IP access + curl "https://api.example.com/fetch?url=http://169.254.169.254/" + curl "https://api.example.com/fetch?url=http://localhost:22" + curl "https://api.example.com/fetch?url=file:///etc/passwd" + ``` + +2. **Bypass Testing**: + ```bash + # Try various encodings + curl "https://api.example.com/fetch?url=http://0177.0.0.1/" + curl "https://api.example.com/fetch?url=http://2130706433/" + curl "https://api.example.com/fetch?url=http://[::ffff:127.0.0.1]/" + ``` + +3. **Port Scanning via SSRF**: + ```bash + # Test if server can reach internal ports + for port in 22 80 443 3306 5432 6379 8080; do + curl "https://api.example.com/fetch?url=http://localhost:$port" + done + ``` + +**Remediation:** +```python +import ipaddress +import re +from urllib.parse import urlparse + +def is_internal_ip(ip_str): + """Check if IP is internal/private""" + try: + ip = ipaddress.ip_address(ip_str) + return ip.is_private or ip.is_loopback or ip.is_reserved + except ValueError: + return False + +def validate_url(url): + """Validate URL for SSRF prevention""" + parsed = urlparse(url) + + # Allowlist approach (recommended) + allowed_hosts = ['api.trusted.com', 'cdn.trusted.com'] + if parsed.hostname not in allowed_hosts: + raise ValidationError("URL not in allowlist") + + # Blocklist approach (supplementary) + blocked_schemes = ['file', 'ftp', 'gopher', 'dict'] + if parsed.scheme in blocked_schemes: + raise ValidationError("Scheme not allowed") + + # Resolve and check IP + import socket + try: + ip = socket.gethostbyname(parsed.hostname) + if is_internal_ip(ip): + raise ValidationError("Internal IPs not allowed") + except socket.gaierror: + raise ValidationError("Could not resolve hostname") + + return url + +# Alternative: Use a dedicated SSRF protection library +# pip install ssrf-protect +from ssrf_protect import SSRFProtect + +@SSRFProtect() +def fetch_url(request): + url = request.GET.get('url') + # Safe to fetch + return requests.get(url) +``` + +#### API8: Security Misconfiguration + +> **Risk**: Insecure default configurations expose APIs to attacks + +**Real-World Impact**: +- **2018**: Tesla Kubernetes API exposed (cryptomining) +- **2020**: Multiple Elasticsearch instances exposed without auth + +**Attack Scenarios:** + +1. **CORS Misconfiguration** + ```http + Access-Control-Allow-Origin: * # Too permissive + Access-Control-Allow-Credentials: true # Dangerous combination + ``` + +2. **Verbose Error Messages** + ```json + { + "error": "SQL syntax error near 'user_id = 123'", + "stack_trace": "...", + "query": "SELECT * FROM users WHERE user_id = 123" + } + ``` + +3. **Missing Security Headers** + ```http + # Missing headers: + X-Content-Type-Options: nosniff + X-Frame-Options: DENY + Content-Security-Policy: ... + Strict-Transport-Security: max-age=31536000 + ``` + +4. **Debug Mode Enabled** + ``` + /api/debug/vars # Exposes Go runtime variables + /api/swagger-ui/ # API documentation with try-it feature + /api/actuator/health # Spring Boot endpoints + ``` + +**Testing Approach:** + +1. **Security Headers Check**: + ```bash + curl -I https://api.example.com/endpoint | grep -i "access-control\|x-" + ``` + +2. **Error Handling Test**: + ```bash + # Trigger errors and check responses + curl "https://api.example.com/endpoint?param=' OR 1=1--" + curl "https://api.example.com/endpoint" -X INVALID_METHOD + ``` + +3. **Debug Endpoint Discovery**: + ```bash + # Common debug paths + /debug + /actuator + /swagger-ui + /api-docs + /health + /metrics + ``` + +**Remediation:** +```python +# Django middleware for security headers +class SecurityHeadersMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + response = self.get_response(request) + + # Security headers + response['X-Content-Type-Options'] = 'nosniff' + response['X-Frame-Options'] = 'DENY' + response['X-XSS-Protection'] = '1; mode=block' + response['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' + response['Content-Security-Policy'] = "default-src 'self'" + response['Referrer-Policy'] = 'strict-origin-when-cross-origin' + + # CORS (restrictive) + response['Access-Control-Allow-Origin'] = 'https://trusted-domain.com' + response['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE' + response['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' + + return response + +# Disable debug mode in production +DEBUG = False + +# Custom error handler (don't expose internals) +from django.http import JsonResponse + +def custom_error_handler(request, exception=None): + return JsonResponse( + {"error": "An error occurred"}, + status=500 + ) +``` + +#### API9: Improper Inventory Management + +> **Risk**: Shadow APIs and undocumented endpoints create attack surface + +**Real-World Impact**: +- **2021**: Facebook API exposed user data via undocumented endpoint +- **2022**: Twitter API v1.1 endpoints still accessible after v2 launch + +**Attack Scenarios:** + +1. **Shadow API Discovery** + ``` + Compare OpenAPI spec with actual code + Look for endpoints not in documentation + ``` + +2. **Deprecated API Usage** + ```http + GET /api/v1/users # Old version still active + GET /api/v2/users # New version + # v1 may have known vulnerabilities + ``` + +3. **Environment Confusion** + ``` + Production API: api.company.com + Staging API: api-staging.company.com # Exposed? + Dev API: api-dev.company.com # Exposed with debug enabled? + ``` + +**Testing Approach:** + +1. **API Inventory**: + ```bash + # Extract all routes from code + grep -r "@app.route\|@GetMapping\|path(" --include="*.py" --include="*.java" + + # Compare with OpenAPI spec + # Identify undocumented endpoints + ``` + +2. **Version Testing**: + ```bash + # Test old API versions + curl https://api.example.com/v1/users + curl https://api.example.com/v2/users + ``` + +3. **Environment Discovery**: + ```bash + # Check for exposed environments + curl https://api-staging.example.com/health + curl https://api-dev.example.com/debug + ``` + +**Remediation:** +```yaml +# API Gateway configuration (Kong example) +plugins: + - name: request-termination + config: + status_code: 410 + message: "API version deprecated" + route: api-v1-routes + +# Automated API discovery +# Use tools like: +# - OWASP ZAP API scanner +# - Postman collection generator +# - Swagger Codegen + +# Regular audits +# Monthly: Compare deployed endpoints with documentation +# Quarterly: Review and deprecate old API versions +``` + +#### API10: Unsafe Consumption of APIs + +> **Risk**: Trusting third-party API responses leads to injection attacks + +**Real-World Impact**: +- **2020**: Multiple XXE attacks via external API responses +- **2021**: Deserialization attacks from webhook payloads + +**Attack Scenarios:** + +1. **XXE via External API** + ```xml + + + + ]> + &xxe; + ``` + +2. **Deserialization Attack** + ```python + # Attacker controls serialized data + import pickle + malicious = b'...crafted pickle payload...' + data = pickle.loads(malicious) # RCE! + ``` + +3. **Webhook Replay** + ```http + # Attacker captures webhook and replays it + POST /api/webhooks/payment + X-Webhook-Signature: valid_signature + {"event": "payment.success", "amount": 1000} + + # Replay same request to double credits + ``` + +4. **JSON Injection** + ```json + // Malicious JSON from external API + { + "username": "admin", + "bio": "" + } + ``` + +**Testing Approach:** + +1. **XXE Testing**: + ```bash + # If API accepts XML from third parties + # Send malicious XML to test for XXE + ``` + +2. **Deserialization Testing**: + ```bash + # Check for unsafe deserialization + # Look for pickle, ObjectInputStream, unserialize + ``` + +3. **Webhook Security**: + ```bash + # Test webhook replay + # Check signature validation + # Verify timestamp/nonce checks + ``` + +**Remediation:** +```python +# XXE Prevention +import xml.etree.ElementTree as ET +from defusedxml import ElementTree as DefusedET + +def parse_xml_safely(xml_string): + # Use defusedxml to prevent XXE + return DefusedET.fromstring(xml_string) + +# Deserialization Safety +import json + +def safe_deserialize(data): + # Use JSON instead of pickle for untrusted data + return json.loads(data) + + # If you must use pickle, sign the data + import hmac + import hashlib + + signature = hmac.new( + SECRET_KEY, + data, + hashlib.sha256 + ).hexdigest() + + if not hmac.compare_digest(signature, expected_signature): + raise ValueError("Invalid signature") + + return pickle.loads(data) + +# Webhook Security +import hmac +import hashlib +import time + +def verify_webhook(request): + # Verify signature + signature = request.headers.get('X-Webhook-Signature') + expected = hmac.new( + WEBHOOK_SECRET, + request.body, + hashlib.sha256 + ).hexdigest() + + if not hmac.compare_digest(signature, expected): + raise ValueError("Invalid signature") + + # Check timestamp (prevent replay) + timestamp = int(request.headers.get('X-Webhook-Timestamp')) + if abs(time.time() - timestamp) > 300: # 5 minutes + raise ValueError("Request too old") + + # Check nonce (prevent replay) + nonce = request.headers.get('X-Webhook-Nonce') + if nonce in used_nonces: + raise ValueError("Nonce already used") + used_nonces.add(nonce) + + return True +``` + +### Phase 4: Automated Security Testing + +#### 4.1 API Security Scanning + +**OWASP ZAP**: +```bash +# Automated API scan +zap-api-scan.py -t https://api.example.com/openapi.json -f openapi + +# With authentication +zap-api-scan.py -t https://api.example.com/openapi.json \ + -f openapi \ + -config "replacer.full_list(0).description=auth" \ + -config "replacer.full_list(0).enabled=true" \ + -config "replacer.full_list(0).matchtype=REQ_HEADER" \ + -config "replacer.full_list(0).matchstr=Authorization" \ + -config "replacer.full_list(0).replacement=Bearer $TOKEN" +``` + +**Burp Suite**: +- Import OpenAPI spec +- Run active scan on all endpoints +- Test for BOLA, authentication bypasses + +**Postman Security Tests**: +```javascript +// Test for sensitive data in response +pm.test("Response does not contain sensitive data", function () { + pm.expect(pm.response.text()).to.not.include("password"); + pm.expect(pm.response.text()).to.not.include("secret"); +}); + +// Test for security headers +pm.test("Security headers present", function () { + pm.response.to.have.header("X-Content-Type-Options"); + pm.response.to.have.header("X-Frame-Options"); +}); +``` + +#### 4.2 Custom Security Tests + +**BOLA Testing Script**: +```python +import requests + +def test_bola(base_url, token, user_a_id, user_b_id): + """Test for Broken Object Level Authorization""" + + # Get User A's token + headers = {"Authorization": f"Bearer {token}"} + + # Try to access User B's resources + endpoints = [ + f"/api/users/{user_b_id}", + f"/api/users/{user_b_id}/orders", + f"/api/orders?user_id={user_b_id}", + ] + + for endpoint in endpoints: + response = requests.get(f"{base_url}{endpoint}", headers=headers) + if response.status_code == 200: + print(f"BOLA VULNERABILITY: {endpoint}") + print(f"User A can access User B's data!") +``` + +**Rate Limit Testing**: +```python +import requests +import time + +def test_rate_limiting(url, headers, requests_count=100): + """Test if rate limiting is enforced""" + + success_count = 0 + start_time = time.time() + + for i in range(requests_count): + response = requests.get(url, headers=headers) + if response.status_code == 200: + success_count += 1 + elif response.status_code == 429: + print(f"Rate limit hit after {i} requests") + break + + elapsed = time.time() - start_time + print(f"Made {success_count} requests in {elapsed:.2f} seconds") + + if success_count == requests_count: + print("WARNING: No rate limiting detected!") +``` + +### Phase 5: API Gateway & Infrastructure Review + +#### 5.1 Kong Gateway Configuration + +```yaml +# kong.yml +plugins: + # Rate limiting + - name: rate-limiting + config: + minute: 100 + hour: 1000 + policy: redis + redis_host: redis + + # CORS (restrictive) + - name: cors + config: + origins: + - "https://app.example.com" + methods: + - GET + - POST + - PUT + - DELETE + headers: + - Authorization + - Content-Type + credentials: true + max_age: 3600 + + # Request size limiting + - name: request-size-limiting + config: + allowed_payload_size: 10 # MB + + # Bot detection + - name: bot-detection + config: + deny: + - "Mozilla/5.0 (compatible; Googlebot/2.1)" + + # IP restriction + - name: ip-restriction + config: + allow: + - "10.0.0.0/8" + - "172.16.0.0/12" +``` + +#### 5.2 nginx Configuration + +```nginx +server { + listen 443 ssl http2; + server_name api.example.com; + + # SSL configuration + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/key.pem; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'; + + # Security headers + add_header X-Frame-Options "DENY" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + + # Rate limiting + limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; + limit_req zone=api burst=20 nodelay; + + # Request size limit + client_max_body_size 10M; + + # Timeout settings + proxy_connect_timeout 30s; + proxy_send_timeout 30s; + proxy_read_timeout 30s; + + location / { + proxy_pass http://backend; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} +``` + +#### 5.3 AWS API Gateway + +```yaml +# serverless.yml or CloudFormation +Resources: + ApiGateway: + Type: AWS::ApiGateway::RestApi + Properties: + Name: SecureAPI + + # Throttling + ApiGatewayStage: + Type: AWS::ApiGateway::Stage + Properties: + RestApiId: !Ref ApiGateway + StageName: prod + MethodSettings: + - ResourcePath: /* + HttpMethod: * + ThrottlingBurstLimit: 100 + ThrottlingRateLimit: 50 + + # WAF + WebACL: + Type: AWS::WAFv2::WebACL + Properties: + Name: APIWAF + Rules: + - Name: RateLimit + Priority: 1 + Statement: + RateBasedStatement: + Limit: 2000 + AggregateKeyType: IP + Action: + Block: {} + VisibilityConfig: + SampledRequestsEnabled: true +``` + +## Output Format + +```markdown +## API Security Assessment: [API Name] + +### Executive Summary +- **API Type**: REST | GraphQL | gRPC | SOAP +- **Total Endpoints**: [count] +- **Authentication**: [JWT | OAuth 2.0 | API Keys | Session] +- **Risk Rating**: [Critical | High | Medium | Low] +- **Overall Security Posture**: [Brief assessment] + +### API Surface Inventory + +#### Authentication Mechanisms +| Mechanism | Implementation | Security Rating | +|-----------|---------------|-----------------| +| JWT | HS256, 15min expiry | ✅ Secure | +| OAuth 2.0 | PKCE enabled | ✅ Secure | + +#### Endpoint Breakdown +| Category | Count | Auth Required | +|----------|-------|---------------| +| Public | 5 | No | +| Authenticated | 45 | Yes | +| Admin | 8 | Yes + Admin role | + +### Risk Matrix + +| OWASP API Ref | Risk | Severity | Status | Evidence | +|--------------|------|----------|--------|----------| +| API1 | BOLA | HIGH | Finding | /api/orders/{id} lacks ownership check | +| API2 | Broken Auth | MEDIUM | Finding | JWT alg=none accepted | +| API3 | BOPA | HIGH | Finding | Mass assignment on /api/users | +| API4 | Resource Consumption | LOW | Finding | No rate limiting on search | +| API5 | BFLA | MEDIUM | Finding | Admin endpoints accessible to users | +| API6 | Business Flows | N/A | N/A | Not applicable | +| API7 | SSRF | CRITICAL | Finding | Cloud metadata accessible | +| API8 | Misconfiguration | MEDIUM | Finding | Debug mode enabled | +| API9 | Inventory | LOW | Finding | Undocumented /api/internal endpoints | +| API10 | Unsafe Consumption | HIGH | Finding | Webhooks lack signature validation | + +### Critical Findings + +#### [CRITICAL] API7: SSRF - Cloud Metadata Exposure +- **Location**: `/api/fetch?url=` parameter +- **Impact**: AWS credentials can be extracted, leading to full cloud compromise +- **Evidence**: + ``` + GET /api/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ + Response: 200 OK with IAM role credentials + ``` +- **Remediation**: Implement URL allowlist, block internal IPs + +### High Findings +[Additional findings...] + +### Positive Security Controls +- ✅ JWT tokens use strong signing (RS256) +- ✅ HTTPS enforced with TLS 1.2+ +- ✅ Security headers present +- ✅ Input validation on all endpoints + +### Remediation Roadmap + +#### Immediate (Critical/High - 1 week) +1. Fix SSRF vulnerability (API7) +2. Implement BOLA checks on all object endpoints (API1) +3. Disable debug mode (API8) + +#### Short-term (High/Medium - 1 month) +4. Implement comprehensive rate limiting (API4) +5. Add field-level authorization (API3) +6. Secure admin endpoints (API5) + +#### Long-term (Medium/Low - 3 months) +7. Implement API inventory management (API9) +8. Add webhook signature validation (API10) +9. Conduct regular security testing + +### Testing Artifacts +- [ ] OWASP ZAP scan results +- [ ] Burp Suite scan results +- [ ] Custom test scripts output +- [ ] API gateway configuration review + +### References +- OWASP API Security Top 10 (2023) +- OWASP ASVS v5.0 - V13: API and Web Service +- OWASP Testing Guide: WSTG-APIT +``` + +## OWASP References + +- **OWASP API Security Top 10 (2023)** — [owasp.org/API-Security](https://owasp.org/API-Security/) +- **OWASP ASVS v5.0** — V13: API and Web Service Verification +- **OWASP Testing Guide** — WSTG-APIT: API Testing +- **OWASP Cheat Sheet Series**: + - REST Security + - GraphQL Security + - JWT Security + - OAuth 2.0 + - SAML Security +- **OWASP ZAP** — API scanning capabilities diff --git a/skills/code-review-security/plays/code-review-security.md b/skills/code-review-security/plays/code-review-security.md new file mode 100644 index 0000000..0b4038a --- /dev/null +++ b/skills/code-review-security/plays/code-review-security.md @@ -0,0 +1,204 @@ +# Play: Security Code Review + +A security code review identifies vulnerabilities in application logic, authentication, authorization, cryptography, and data handling. This play structures the review around OWASP weakness classes (injection, auth, crypto, etc.) and is applicable to any language or framework. Reviews can target full codebases, pull request diffs, or specific modules, and findings are mapped to OWASP standards and OpenCRE for multi-framework traceability. + +Review code changes or codebases for security vulnerabilities, mapping findings to OWASP standards and OpenCRE cross-references for multi-framework traceability. + +## Trigger Conditions + +Use this skill when: +- Reviewing a pull request or diff for security issues +- A user asks for a security review of their code +- Auditing a specific file, module, or feature for vulnerabilities +- Performing a pre-merge security gate check + +## Inputs + +- Code diff (PR), specific files, or entire codebase to review +- (Optional) Language and framework context +- (Optional) ASVS level to verify against (L1, L2, or L3) +- (Optional) Specific concern areas to focus on + +## Procedure + +### 1. Scope & Context + +Before diving in, establish: +- **Language/Framework**: Determines which vulnerability classes are relevant +- **Trust boundary**: Is this server-side, client-side, library, CLI, infrastructure code? +- **Data sensitivity**: Does this code handle PII, credentials, financial data, health data? +- **Exposure**: Is this internet-facing, internal, or local-only? + +### 2. Systematic Review by Vulnerability Class + +Review in priority order — highest-impact classes first: + +#### A. Injection (CWE-74, OWASP A03, [OpenCRE 161-451](https://www.opencre.org/cre/161-451)) + +> ASVS refs: `data/asvs/V12.1.md` (Input Validation), `data/asvs/V13.1.md` (Output Encoding), `data/asvs/V5.3.md` (File Storage) + +| Subtype | What to Look For | +|---------|-----------------| +| SQL Injection | String concatenation in queries, missing parameterization, ORM raw queries | +| Command Injection | User input in exec/spawn/system calls, unsanitized shell arguments | +| XSS | User input rendered without output encoding, unsafe DOM manipulation, unescaped template output | +| SSTI | User input in template strings that get evaluated server-side | +| LDAP Injection | User input in LDAP filters without escaping | +| Path Traversal | User input in file paths without canonicalization, `../` not blocked | +| Header Injection | User input in HTTP headers (CRLF injection) | +| Log Injection | User input written to logs without sanitization | + +#### B. Authentication & Session (CWE-287, OWASP A07, [OpenCRE 633-428](https://www.opencre.org/cre/633-428)) + +> ASVS refs: `data/asvs/V2.1.md`–`V2.4.md` (Authentication), `data/asvs/V3.1.md`–`V3.7.md` (Session Management) + +- Hardcoded credentials or API keys +- Missing authentication on endpoints +- Weak password requirements +- Session tokens in URLs or logs +- Missing session invalidation on logout/password change +- JWT issues: none algorithm, missing expiry, weak signing key, secrets in payload +- Missing MFA enforcement for sensitive operations + +#### C. Authorization (CWE-862, OWASP A01, [OpenCRE 724-770](https://www.opencre.org/cre/724-770)) + +> ASVS refs: `data/asvs/V4.1.md`–`V4.4.md` (Access Control) + +- Missing authorization checks on endpoints or functions +- IDOR: object references without ownership validation +- Horizontal privilege escalation (accessing other users' data) +- Vertical privilege escalation (accessing admin functions) +- Missing RBAC/ABAC enforcement +- Direct database queries that don't filter by user/tenant + +#### D. Cryptography (CWE-327, OWASP A02, [OpenCRE 278-646](https://www.opencre.org/cre/278-646)) + +> ASVS refs: `data/asvs/V6.1.md`–`V6.8.md` (Cryptography) + +- Weak algorithms: MD5, SHA1 for passwords, DES, RC4 +- ECB mode usage +- Hardcoded encryption keys or IVs +- Missing encryption at rest for sensitive data +- Missing TLS enforcement +- Custom crypto implementations (don't roll your own) +- Insufficient key lengths (RSA < 2048, AES < 128) + +#### E. Data Exposure (CWE-200, OWASP A01, [OpenCRE 126-668](https://www.opencre.org/cre/126-668)) + +> ASVS refs: `data/asvs/V8.1.md`–`V8.4.md` (Data Protection), `data/asvs/V7.1.md`–`V7.6.md` (Error Handling & Logging) + +- Sensitive data in error messages or stack traces +- Verbose logging of requests/responses containing PII +- Credentials or tokens in source code, configs, or URLs +- Missing response headers (X-Content-Type-Options, etc.) +- API responses including more fields than necessary +- Debug mode enabled in production configs + +#### F. Security Misconfiguration (OWASP A05, [OpenCRE 233-748](https://www.opencre.org/cre/233-748)) + +> ASVS refs: `data/asvs/V10.1.md`–`V10.7.md` (Configuration) + +- Default credentials or configurations +- Unnecessary features enabled (debug endpoints, admin panels) +- Missing security headers +- Overly permissive CORS +- Directory listing enabled +- Missing rate limiting on sensitive endpoints + +#### G. Deserialization & Data Integrity (CWE-502, OWASP A08, [OpenCRE 854-643](https://www.opencre.org/cre/854-643)) + +> ASVS refs: `data/asvs/V11.1.md`–`V11.7.md` (Business Logic) + +- Deserializing untrusted data (unsafe deserialization in any language — Python, Java, PHP, Ruby, .NET) +- Missing integrity checks on data from untrusted sources +- Unsigned cookies or tokens +- Missing CSRF protection on state-changing operations + +### 3. Framework-Specific Checks + +Apply checks specific to the detected framework: + +| Framework | Key Checks | +|-----------|-----------| +| React/Next.js | XSS via unsafe HTML rendering, SSRF in server-side data fetching, exposed API routes | +| Express/Node | Missing helmet, no rate limiting, prototype pollution, regex DoS | +| Django | Raw SQL, CSRF exemptions, DEBUG=True, SECRET_KEY exposure | +| Flask | Jinja2 autoescape disabled, unsafe session serialization, debug mode | +| Spring | SpEL injection, actuator exposure, mass assignment | +| Rails | Mass assignment, render user input, SQL fragments | +| Go net/http | Missing timeouts, TOCTOU in file operations, integer overflow | + +### 4. Diff-Specific Analysis (for PR reviews) + +When reviewing a diff rather than a full codebase: +- Focus on changed lines and their immediate context +- Check if security controls in surrounding (unchanged) code are preserved +- Verify that new endpoints have auth/authz matching existing patterns +- Check if new dependencies introduce vulnerabilities (cross-reference with sca-audit) +- Look for removed security controls (deleted validation, removed auth checks) + +### 5. Produce Findings + +For each issue: +- Cite the specific code location (file:line) +- Show the vulnerable code snippet +- Explain the attack scenario concretely +- Provide a fixed code snippet +- Rate confidence (HIGH if confirmed path, MEDIUM if contextual, LOW if heuristic) + +## Output Format + +```markdown +## Security Code Review: [Target] + +### Scope +- **Files reviewed**: [count or list] +- **Language/Framework**: [detected] +- **Review type**: Full | PR diff | Targeted + +### Findings +[Standard finding template for each issue, sorted by severity] + +### Positive Observations +[Security controls that ARE in place — acknowledge good practices] + +### Summary +| Severity | Count | +|----------|-------| +| CRITICAL | N | +| HIGH | N | +| MEDIUM | N | +| LOW | N | +| INFO | N | +``` + +## Tools & Resources + +### Static Analysis Tools +- **Semgrep** — Multi-language pattern-based SAST; highly customizable rules +- **CodeQL (GitHub)** — Query-based code analysis for Java, C++, C#, Go, Python, TypeScript, JavaScript, Ruby +- **SonarQube** — Code quality and security scanning with OWASP Top 10 mappings +- **Checkmarx/CxSAST** — Enterprise SAST with custom rule authoring +- **Snyk Code** — Developer-first SAST integrated into IDEs and CI/CD + +### Language-Specific +- **Bandit** (Python) — Finds common security issues in Python code +- **Brakeman** (Ruby) — Scans Rails apps for OWASP risks +- **go-vuln-check** (Go) — Detects known vulnerabilities in Go code +- **ShiftLeft/Taint** (Java, Python, Go) — Data flow analysis for injection detection + +### Code Review Checkers +- **OWASP Cheat Sheet Series** — Per-vulnerability quick guides and remediation +- **CWE Top 25** — Prioritized list of most dangerous weakness patterns +- **ASVS Interactive** — Maps review items to ASVS verification levels (L1/L2/L3) + +## References + +- OWASP Top 10 (2021): A01-A10 +- OWASP ASVS v5.0 (for verification-level mapping) +- OWASP Code Review Guide +- OWASP Cheat Sheet Series (per-topic) +- OWASP Proactive Controls +- [OpenCRE](https://www.opencre.org) — Cross-standard requirement mappings (CWE, ASVS, WSTG, NIST 800-53, ISO 27001) +- [CWE](https://cwe.mitre.org) v4.19 — Common Weakness Enumeration +- ASVS 5.0 reference data in `data/asvs/` — sourced from [OWASP Agent Skills Project](https://github.com/eoftedal/owasp-agent-skills-project) diff --git a/skills/code-review-security/templates/finding.md b/skills/code-review-security/templates/finding.md new file mode 100644 index 0000000..65ea1a3 --- /dev/null +++ b/skills/code-review-security/templates/finding.md @@ -0,0 +1,48 @@ +# Finding Template + +Use this structure for all security findings produced by skills. + +```markdown +### [SEVERITY] Title + +- **ID**: NDC-YYYY-NNN (auto-incrementing) +- **CWE**: CWE-XXX (if applicable) +- **CVE**: CVE-YYYY-NNNNN (if applicable) +- **OpenCRE**: [CRE-ID](https://www.opencre.org/cre/CRE-ID) — requirement name (see data/opencre/) +- **OWASP Ref**: Top 10 A01, ASVS V4.1.1, MASVS-STORAGE-1, MASWE-0001, MASTG-TEST-0200, LLM01, etc. +- **Location**: file_path:line_number or component name +- **Impact**: What an attacker can achieve (1-2 sentences) +- **Evidence**: Code snippet, command output, or proof-of-concept +- **Remediation**: Specific fix with code example +- **Confidence**: HIGH | MEDIUM | LOW (how certain is this finding) +``` + +### Resolving OpenCRE Links + +When you have a CWE, look up its OpenCRE mapping via the API: + +``` +GET https://www.opencre.org/rest/v1/standard/CWE/sectionid/{cwe-number} +``` + +This returns the CRE ID and linked standards (ASVS, WSTG, NIST 800-53, cheat sheets). Include the CRE link in findings to give readers one-click access to all related standards and remediation guidance. + +Common mappings are pre-populated in `data/opencre/README.md`. + +## Severity Definitions + +| Severity | CVSS Range | Criteria | +|----------|-----------|----------| +| CRITICAL | 9.0-10.0 | Remote code execution, full system compromise, mass data breach | +| HIGH | 7.0-8.9 | Privilege escalation, significant data exposure, auth bypass | +| MEDIUM | 4.0-6.9 | Limited data exposure, requires user interaction or specific conditions | +| LOW | 0.1-3.9 | Information disclosure, minor misconfigurations | +| INFORMATIONAL | N/A | Best practice recommendations, defense-in-depth suggestions | + +## Confidence Levels + +| Level | Meaning | +|-------|---------| +| HIGH | Confirmed via code path analysis, PoC, or tool output | +| MEDIUM | Strong indicators but not fully confirmed — needs manual verification | +| LOW | Heuristic match or pattern-based — may be false positive | diff --git a/skills/cve-triage/schemas/finding.schema.json b/skills/cve-triage/schemas/finding.schema.json new file mode 100644 index 0000000..535a496 --- /dev/null +++ b/skills/cve-triage/schemas/finding.schema.json @@ -0,0 +1,345 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/UnitOneAI/SecuritySkills/schemas/finding.schema.json", + "title": "SecuritySkills Normalized Finding Output", + "description": "Machine-readable envelope for normalized security findings and remediation recommendations emitted by SecuritySkills workflows. This contract is independent of SARIF and may be mapped to downstream enterprise formats later.", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "run", "skill", "findings"], + "properties": { + "schema_version": { + "const": "1.0.0", + "description": "Version of this normalized SecuritySkills finding envelope." + }, + "run": { + "$ref": "#/$defs/run", + "description": "Metadata for the analysis run that produced this output." + }, + "skill": { + "$ref": "#/$defs/skill", + "description": "Metadata for the SecuritySkills entrypoint that produced this output." + }, + "findings": { + "type": "array", + "items": { + "$ref": "#/$defs/finding" + }, + "description": "Normalized findings produced by a skill run." + } + }, + "$defs": { + "riskLevel": { + "type": "string", + "enum": ["low", "medium", "high"] + }, + "nonEmptyString": { + "type": "string", + "minLength": 1 + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "run": { + "type": "object", + "additionalProperties": false, + "required": ["id", "timestamp"], + "properties": { + "id": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable run identifier supplied by the agent, CI job, or enterprise orchestrator." + }, + "timestamp": { + "$ref": "#/$defs/nonEmptyString", + "description": "ISO 8601 timestamp for when the run output was produced." + }, + "tool": { + "$ref": "#/$defs/nonEmptyString", + "description": "Agent, CLI, scanner, or workflow that executed the skill." + }, + "target": { + "$ref": "#/$defs/nonEmptyString", + "description": "Repository, project, service, artifact, environment, or other target reviewed." + }, + "source_ref": { + "$ref": "#/$defs/nonEmptyString", + "description": "Optional commit SHA, branch, image digest, build ID, ticket ID, or evidence package reference." + } + } + }, + "skill": { + "type": "object", + "additionalProperties": false, + "required": ["name", "version"], + "properties": { + "name": { + "$ref": "#/$defs/nonEmptyString", + "description": "SecuritySkills skill name from SKILL.md frontmatter." + }, + "version": { + "$ref": "#/$defs/nonEmptyString", + "description": "SecuritySkills skill version from SKILL.md frontmatter." + }, + "path": { + "$ref": "#/$defs/nonEmptyString", + "description": "Path to the SKILL.md entrypoint used for the run." + }, + "frameworks": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/nonEmptyString" + }, + "description": "Framework identifiers declared by the skill frontmatter." + } + } + }, + "finding": { + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "severity", "status", "evidence", "remediations"], + "properties": { + "id": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable finding identifier within the output." + }, + "fingerprint": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable deduplication key based on finding type, affected asset, and evidence location." + }, + "title": { + "$ref": "#/$defs/nonEmptyString" + }, + "description": { + "$ref": "#/$defs/nonEmptyString", + "description": "What the issue is and why it matters." + }, + "severity": { + "type": "string", + "enum": ["info", "low", "medium", "high", "critical"] + }, + "status": { + "type": "string", + "enum": ["open", "mitigated", "accepted_risk", "false_positive"] + }, + "cwe": { + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "pattern": "^CWE-[0-9]+$" + }, + "description": "Optional CWE mappings, when applicable." + }, + "framework_refs": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/frameworkRef" + }, + "description": "Framework/control references from the skill frontmatter frameworks." + }, + "references": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/reference" + }, + "description": "Optional advisory, standard, vendor, or knowledge-base references." + }, + "evidence": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["location", "summary"], + "properties": { + "location": { + "$ref": "#/$defs/nonEmptyString", + "description": "File path, line range, asset ID, log source, policy path, or other concrete evidence location." + }, + "summary": { + "$ref": "#/$defs/nonEmptyString" + }, + "artifact_type": { + "type": "string", + "enum": ["source", "config", "policy", "log", "scan_result", "cloud_resource", "identity", "network", "document", "other"] + }, + "snippet": { + "$ref": "#/$defs/nonEmptyString", + "description": "Minimal redacted snippet or observation needed to support the finding." + }, + "redacted": { + "type": "boolean", + "description": "True when sensitive values were intentionally removed from this evidence." + } + } + } + }, + "remediations": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/remediation" + }, + "description": "Every fix recommendation for this finding. Each item must include remediation guidance, confidence, blast radius, behavior-change risk, and test strategy." + } + }, + "anyOf": [ + { + "required": ["cwe"] + }, + { + "required": ["framework_refs"] + } + ] + }, + "frameworkRef": { + "type": "object", + "additionalProperties": false, + "required": ["framework", "control"], + "properties": { + "framework": { + "$ref": "#/$defs/nonEmptyString" + }, + "control": { + "$ref": "#/$defs/nonEmptyString" + }, + "name": { + "$ref": "#/$defs/nonEmptyString" + } + } + }, + "reference": { + "type": "object", + "additionalProperties": false, + "required": ["type", "id"], + "properties": { + "type": { + "type": "string", + "enum": ["cve", "cwe", "framework", "advisory", "vendor", "documentation", "other"] + }, + "id": { + "$ref": "#/$defs/nonEmptyString" + }, + "url": { + "$ref": "#/$defs/uriString" + } + } + }, + "remediation": { + "type": "object", + "additionalProperties": false, + "required": ["guidance", "confidence", "blast_radius", "behavior_change_risk", "test_strategy"], + "properties": { + "guidance": { + "$ref": "#/$defs/nonEmptyString", + "description": "Concrete remediation steps or patch guidance for the finding." + }, + "confidence": { + "$ref": "#/$defs/riskLevel", + "description": "How confident the skill is that this recommendation is correct for the observed evidence." + }, + "blast_radius": { + "$ref": "#/$defs/nonEmptyString", + "description": "Expected scope of systems, files, users, integrations, data, or workflows affected by the change." + }, + "behavior_change_risk": { + "$ref": "#/$defs/riskLevel", + "description": "Risk that the remediation changes intended application or operational behavior." + }, + "test_strategy": { + "$ref": "#/$defs/testStrategy", + "description": "Required validation strategy proving the remediation fixes the finding. Include recommended tests, generated tests, or both." + } + } + }, + "testStrategy": { + "type": "object", + "additionalProperties": false, + "required": ["summary"], + "properties": { + "summary": { + "$ref": "#/$defs/nonEmptyString", + "description": "Concise explanation of what proves the remediation fixed the issue." + }, + "recommended_tests": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/recommendedTest" + }, + "description": "Tests the user or agent should run when tests are not generated directly." + }, + "generated_tests": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/generatedTest" + }, + "description": "Test files or cases produced as part of the remediation." + } + }, + "anyOf": [ + { + "required": ["recommended_tests"] + }, + { + "required": ["generated_tests"] + } + ] + }, + "recommendedTest": { + "type": "object", + "additionalProperties": false, + "required": ["name", "type", "purpose", "command", "expected_result"], + "properties": { + "name": { + "$ref": "#/$defs/nonEmptyString" + }, + "type": { + "type": "string", + "enum": ["static", "unit", "integration", "e2e", "regression", "manual"] + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString", + "description": "Behavior, vulnerability condition, or regression this test proves." + }, + "command": { + "$ref": "#/$defs/nonEmptyString", + "description": "Command or manual check to execute for this test." + }, + "expected_result": { + "$ref": "#/$defs/nonEmptyString" + } + } + }, + "generatedTest": { + "type": "object", + "additionalProperties": false, + "required": ["path", "type", "purpose", "command", "expected_result"], + "properties": { + "path": { + "$ref": "#/$defs/nonEmptyString", + "description": "Path to the generated or modified test file." + }, + "type": { + "type": "string", + "enum": ["static", "unit", "integration", "e2e", "regression"] + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString", + "description": "Behavior, vulnerability condition, or regression this generated test proves." + }, + "command": { + "$ref": "#/$defs/nonEmptyString", + "description": "Command that runs the generated test." + }, + "expected_result": { + "$ref": "#/$defs/nonEmptyString" + } + } + } + } +} diff --git a/skills/dependency-scanning/docs/fixer-policy.md b/skills/dependency-scanning/docs/fixer-policy.md new file mode 100644 index 0000000..58367f3 --- /dev/null +++ b/skills/dependency-scanning/docs/fixer-policy.md @@ -0,0 +1,111 @@ +# Security Fixer Policy + +This policy classifies security findings by how an agent may remediate them. Fixer-capable skills must use this policy before changing files, generating patches, or recommending an automated remediation path. + +## Categories + +### Auto-fix + +The agent may apply the fix directly when the finding is high-confidence, the change is narrow, and the expected behavior is mechanically verifiable. + +Criteria: +- The vulnerable pattern and target file are unambiguous. +- The fix is deterministic and follows an existing project convention or a well-known safe default. +- The change has low blast radius and does not alter public APIs, authorization semantics, data models, deployment topology, or runtime trust boundaries. +- The agent can run or define a concrete verification step. + +Examples: +- Add missing security headers in a local framework configuration using the project's existing middleware pattern. +- Replace string-built SQL with parameter binding when the query shape and parameters are clear. +- Pin a container image tag or GitHub Action version when the intended version is known from lock files, release metadata, or existing repository conventions. +- Add a `.dockerignore` or `.gitignore` entry for `.env` files without removing or exposing secret values. + +### Assisted-fix + +The agent may prepare a patch or exact commands, but the user or repository owner must confirm context, run environment-specific checks, or choose among valid alternatives before merge. + +Criteria: +- The finding is valid, but the best remediation depends on application behavior, deployment constraints, ownership boundaries, or compatibility requirements. +- Multiple safe remediation options exist. +- The change is moderate in scope or requires coordinated validation outside the local workspace. +- The agent can reduce the work to a reviewable patch, migration plan, configuration diff, or decision list. + +Examples: +- Add authorization middleware to an endpoint when the correct role or ownership predicate needs product confirmation. +- Upgrade a vulnerable dependency across a major version boundary. +- Tighten CI permissions where release, package, or deployment jobs may need specific write scopes. +- Add Kubernetes `NetworkPolicy` rules where service communication requirements must be confirmed. + +### Guidance-only + +The agent must not modify files. It should explain the finding, risk, and recommended remediation path. + +Criteria: +- The remediation requires organizational policy, architecture changes, vendor configuration, legal review, procurement, or manual operational work. +- The agent lacks access to the system that must be changed. +- The change cannot be represented safely as a local patch. + +Examples: +- Adopt a centralized secrets manager across teams. +- Establish a vulnerability management SLA. +- Change cloud account guardrails, identity provider policy, or production firewall rules outside the repository. +- Resolve license obligations for GPL, AGPL, commercial, unknown, or no-license dependencies. + +### Human-review-required + +The agent must stop short of applying a fix and explicitly request human review before remediation proceeds. + +Criteria: +- A hard gate below applies. +- The finding involves sensitive credentials, production access, destructive operations, legal/compliance interpretation, or security-critical logic. +- The agent cannot confidently preserve intended behavior. +- The evidence is incomplete or the finding may be a false positive with material operational impact. + +Examples: +- Rotate leaked credentials or revoke certificates. +- Change authentication, authorization, cryptography, payment, medical, safety, or tenant-isolation logic. +- Modify production deployment, incident response, or containment procedures. +- Apply a remediation that deletes data, removes audit evidence, weakens controls, or accepts risk. + +## Decision Criteria + +Classify each finding using the most restrictive category that applies. + +1. Confirm the finding is in scope for the skill and supported by concrete evidence. +2. Determine whether any hard gate forces human review. +3. Estimate blast radius: local config or code path, cross-cutting application behavior, infrastructure, production operations, or organizational policy. +4. Check remediation confidence: deterministic patch, multiple valid options, missing context, or uncertain behavior. +5. Check verification: automated test or scan, manual validation, external approval, or no reliable verification available. +6. Choose the category: + - Use auto-fix only when evidence, scope, remediation, and verification are all strong. + - Use assisted-fix when a patch is useful but context or approval is required. + - Use guidance-only when local code changes are not the right remediation vehicle. + - Use human-review-required whenever a hard gate applies or safe behavior preservation is uncertain. + +## Hard Gates for Human Review + +Any of these conditions forces `human-review-required`: + +- Secret exposure requiring credential rotation, revocation, certificate replacement, or git history rewriting. +- Authentication, authorization, session management, cryptographic, payment, tenant isolation, or safety-critical logic changes. +- Production infrastructure, network, identity, IAM, deployment, incident response, or data retention changes. +- Destructive or irreversible actions, including deleting data, rewriting history, disabling audit logs, removing evidence, or changing backups. +- Legal, compliance, privacy, or license-risk decisions. +- Changes requiring owner-specific business rules, threat model assumptions, regulatory interpretation, or risk acceptance. +- Unclear ownership, missing tests for a high-impact path, conflicting framework guidance, or evidence that the finding may be a false positive. +- Any remediation that would weaken an existing security control to make a tool pass. + +## Fixer Workflow Review Gates + +Fixer-capable workflows must pass these gates before any applied patch is considered ready for handoff: + +1. **Scope gate:** State the files, settings, and behaviors that are in scope; avoid unrelated refactors, formatting churn, dependency updates, or opportunistic cleanup. +2. **Approval gate:** Request explicit approval before assisted-fix or human-review-required work proceeds, and before any change that affects hard-gated areas even when a patch can be drafted. +3. **Review gate:** Provide reviewer evidence that includes the finding, policy category, changed files, behavior-change risk, verification performed or still required, and any assumptions the reviewer must confirm. +4. **Rollback gate:** Provide rollback guidance for every proposed or applied change, including the exact revert path when local patches are used or the operational rollback owner when the change cannot be reverted locally. + +Applied fixes must be isolated to the smallest viable patch. If the agent discovers unrelated defects while fixing, it should report them separately instead of expanding the patch. If rollback is unclear, expensive, or depends on production state, classify the remediation as `human-review-required`. + +## Skill Usage + +Fixer-capable skills must reference this policy when producing remediation guidance or patches. Their workflows must include the review gates above and must not apply changes until the selected category allows it. The policy classifies the remediation path only; it does not change finding schemas or require new output fields. diff --git a/skills/dependency-scanning/docs/normalized-json-output.md b/skills/dependency-scanning/docs/normalized-json-output.md new file mode 100644 index 0000000..70503c1 --- /dev/null +++ b/skills/dependency-scanning/docs/normalized-json-output.md @@ -0,0 +1,158 @@ +# Normalized JSON Output Contract + +SecuritySkills can emit machine-readable findings as a normalized JSON envelope +that validates against [`schemas/finding.schema.json`](../schemas/finding.schema.json). +This contract is independent of SARIF. Downstream systems may map it to SARIF, +ticketing systems, GRC platforms, dashboards, or vulnerability stores without +changing individual skill output rules. +See [`docs/sarif-output.md`](sarif-output.md) for the repo-level SARIF 2.1.0 +export mapping. + +## Envelope + +Every JSON response uses this top-level shape: + +```json +{ + "schema_version": "1.0.0", + "run": { + "id": "run-2026-06-16T12:00:00Z", + "timestamp": "2026-06-16T12:00:00Z", + "tool": "codex", + "target": "github.com/example/service", + "source_ref": "commit-or-build-id" + }, + "skill": { + "name": "secure-code-review", + "version": "1.0.0", + "path": "skills/appsec/secure-code-review/SKILL.md", + "frameworks": ["OWASP-ASVS-4.0.3", "CWE"] + }, + "findings": [] +} +``` + +- `schema_version` is fixed at `1.0.0` until a breaking contract change is + required. +- `run.id` is the deduplication boundary for one execution. Use an orchestrator + ID, CI job ID, or generated run ID. +- `run.timestamp` should be an ISO 8601 timestamp. +- `run.target` identifies the reviewed repository, project, service, artifact, + environment, or evidence package. +- `skill.name`, `skill.version`, and `skill.frameworks` come from the skill's + `SKILL.md` frontmatter. + +## Findings + +Each finding must include: + +- `id`: stable finding ID within the run. +- `title`: concise finding title. +- `severity`: one of `info`, `low`, `medium`, `high`, or `critical`. +- `status`: one of `open`, `mitigated`, `accepted_risk`, or `false_positive`. +- `evidence`: one or more concrete evidence entries. +- `remediations`: one or more remediation recommendations, each with a test + strategy. + +Each finding must include at least one framework/CWE mapping: + +- `cwe`: array of CWE IDs such as `CWE-89`, when applicable. +- `framework_refs`: array of framework/control references from the skill's + declared frameworks. + +Optional fields such as `fingerprint`, `description`, and `references` support +enterprise deduplication, analyst context, and external advisory linking. + +## Evidence + +Evidence entries must identify where the issue was observed and summarize the +observation. Locations may be source paths, line ranges, cloud resource IDs, log +sources, policy paths, scanner result identifiers, or evidence package records. + +Use `snippet` only for the minimal redacted text needed to prove the finding. +Set `redacted: true` when secrets, tokens, personal data, internal hostnames, or +other sensitive values were removed. + +## Remediation And Tests + +Each remediation item must include: + +- `guidance`: concrete remediation steps or patch guidance. +- `confidence`: `low`, `medium`, or `high`. +- `blast_radius`: expected affected files, systems, users, integrations, data, + or workflows. +- `behavior_change_risk`: `low`, `medium`, or `high`. +- `test_strategy`: validation that proves the issue is fixed. + +`test_strategy` must include a `summary` and at least one of +`recommended_tests` or `generated_tests`. See +[`docs/remediation-output.md`](remediation-output.md) for remediation-specific +field guidance. + +## Minimal Example + +```json +{ + "schema_version": "1.0.0", + "run": { + "id": "run-001", + "timestamp": "2026-06-16T12:00:00Z", + "tool": "codex", + "target": "payments-api", + "source_ref": "abc1234" + }, + "skill": { + "name": "api-security", + "version": "1.0.0", + "path": "skills/appsec/api-security/SKILL.md", + "frameworks": ["OWASP-API-Top-10-2023", "CWE"] + }, + "findings": [ + { + "id": "API-SEC-001", + "fingerprint": "api-security:users-delete:missing-admin-auth", + "title": "Administrative endpoint lacks authorization check", + "description": "The delete-user route accepts authenticated requests without verifying administrative privileges.", + "severity": "high", + "status": "open", + "cwe": ["CWE-862"], + "framework_refs": [ + { + "framework": "OWASP-API-Top-10-2023", + "control": "API5:2023", + "name": "Broken Function Level Authorization" + } + ], + "evidence": [ + { + "location": "routes/users.js:42", + "artifact_type": "source", + "summary": "DELETE /users/:id checks authentication but not administrator role.", + "snippet": "router.delete('/users/:id', requireAuth, deleteUser)", + "redacted": false + } + ], + "remediations": [ + { + "guidance": "Require an administrator role check before invoking deleteUser.", + "confidence": "high", + "blast_radius": "User administration routes only.", + "behavior_change_risk": "medium", + "test_strategy": { + "summary": "Proves non-admin users cannot delete accounts while admins still can.", + "recommended_tests": [ + { + "name": "Reject non-admin delete", + "type": "integration", + "purpose": "Confirms the vulnerable authorization bypass no longer succeeds.", + "command": "npm test -- users-authz.test.js", + "expected_result": "Non-admin DELETE /users/:id returns 403 and admin DELETE succeeds." + } + ] + } + } + ] + } + ] +} +``` diff --git a/skills/dependency-scanning/docs/sarif-output.md b/skills/dependency-scanning/docs/sarif-output.md new file mode 100644 index 0000000..d268c49 --- /dev/null +++ b/skills/dependency-scanning/docs/sarif-output.md @@ -0,0 +1,229 @@ +# SARIF Output Mapping + +SecuritySkills may emit SARIF-compatible JSON for tools that ingest Static +Analysis Results Interchange Format (SARIF) 2.1.0. SARIF output is an export +view of the normalized finding envelope documented in +[`docs/normalized-json-output.md`](normalized-json-output.md); it does not +replace the normalized JSON contract or change the required finding fields. + +## Top-Level Shape + +Use SARIF version `2.1.0` with the standard schema URI: + +```json +{ + "$schema": "https://json.schemastore.org/sarif-2.1.0.json", + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "SecuritySkills", + "semanticVersion": "1.0.0", + "rules": [] + } + }, + "results": [] + } + ] +} +``` + +Use one `run` per normalized envelope. `run.tool.driver.name` should identify +SecuritySkills or the executing agent. `run.tool.driver.semanticVersion` should +use the skill version when a single skill produced the run. + +## Mapping + +Map normalized fields to SARIF as follows: + +| Normalized field | SARIF field | +|---|---| +| `run.id`, `run.timestamp`, `run.target`, `run.source_ref` | `runs[].properties.securityskills.run` | +| `skill.name`, `skill.version`, `skill.path`, `skill.frameworks` | `runs[].tool.driver.name`, `runs[].tool.driver.semanticVersion`, `runs[].properties.securityskills.skill` | +| `finding.id` | `results[].ruleId` and `results[].properties.securityskills.finding_id` | +| `finding.fingerprint` | `results[].partialFingerprints.securityskillsFingerprint` | +| `finding.title` | `tool.driver.rules[].shortDescription.text` | +| `finding.description` | `tool.driver.rules[].fullDescription.text` and `results[].message.text` | +| `finding.severity` | `results[].level` | +| `finding.status` | `results[].properties.securityskills.status` | +| `finding.cwe` | `tool.driver.rules[].relationships` when supported, and `properties.securityskills.cwe` | +| `finding.framework_refs` | `tool.driver.rules[].properties.securityskills.framework_refs` | +| `finding.evidence` | `results[].locations` plus `properties.securityskills.evidence` | +| `finding.references` | `tool.driver.rules[].helpUri` or `tool.driver.rules[].properties.securityskills.references` | +| `finding.remediations` | `tool.driver.rules[].help.text` and `properties.securityskills.remediations`, including each remediation's `test_strategy` | + +## Severity + +SARIF `level` has fewer values than the normalized contract. Use this mapping: + +| Normalized severity | SARIF level | +|---|---| +| `critical` | `error` | +| `high` | `error` | +| `medium` | `warning` | +| `low` | `note` | +| `info` | `note` | + +Keep the original severity in +`results[].properties.securityskills.severity` so downstream systems can +preserve the distinction between `critical` and `high`. + +## Locations + +For source, configuration, policy, or scan-result evidence with file locations, +populate `results[].locations[].physicalLocation`: + +```json +{ + "physicalLocation": { + "artifactLocation": { + "uri": "routes/users.js" + }, + "region": { + "startLine": 42 + } + }, + "message": { + "text": "DELETE /users/:id checks authentication but not administrator role." + } +} +``` + +If the normalized evidence location does not contain a parseable file path and +line number, still emit a SARIF result and store the original location under +`properties.securityskills.evidence`. For cloud resources, identities, network +assets, logs, or documents, use the best stable asset identifier as +`artifactLocation.uri` only when it is meaningful to the SARIF consumer. + +## Rules + +Create one `tool.driver.rules[]` entry per distinct `ruleId`. A rule should +include: + +- `id`: the normalized `finding.id`, or a stable detector ID when multiple + findings share the same detection rule. +- `shortDescription.text`: the finding title or detector title. +- `fullDescription.text`: the finding description. +- `help.text`: remediation guidance and test strategy summary. +- `properties.securityskills`: CWE IDs, framework references, normalized + severity, and any remediation metadata that does not fit native SARIF fields. + +Do not invent CWE, framework, or control identifiers for SARIF. Reuse only the +values already present in the normalized finding. + +## Minimal Example + +```json +{ + "$schema": "https://json.schemastore.org/sarif-2.1.0.json", + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": "api-security", + "semanticVersion": "1.0.0", + "rules": [ + { + "id": "API-SEC-001", + "shortDescription": { + "text": "Administrative endpoint lacks authorization check" + }, + "fullDescription": { + "text": "The delete-user route accepts authenticated requests without verifying administrative privileges." + }, + "help": { + "text": "Require an administrator role check before invoking deleteUser. Validate with integration tests for non-admin and admin delete flows." + }, + "properties": { + "securityskills": { + "severity": "high", + "cwe": ["CWE-862"], + "framework_refs": [ + { + "framework": "OWASP-API-Top-10-2023", + "control": "API5:2023", + "name": "Broken Function Level Authorization" + } + ] + } + } + } + ] + } + }, + "results": [ + { + "ruleId": "API-SEC-001", + "level": "error", + "message": { + "text": "Administrative endpoint lacks authorization check" + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": { + "uri": "routes/users.js" + }, + "region": { + "startLine": 42 + } + }, + "message": { + "text": "DELETE /users/:id checks authentication but not administrator role." + } + } + ], + "partialFingerprints": { + "securityskillsFingerprint": "api-security:users-delete:missing-admin-auth" + }, + "properties": { + "securityskills": { + "finding_id": "API-SEC-001", + "severity": "high", + "status": "open", + "remediations": [ + { + "guidance": "Require an administrator role check before invoking deleteUser.", + "confidence": "high", + "blast_radius": "User administration routes only.", + "behavior_change_risk": "medium", + "test_strategy": { + "summary": "Proves non-admin users cannot delete accounts while admins still can.", + "recommended_tests": [ + { + "name": "Reject non-admin delete", + "type": "integration", + "purpose": "Confirms the authorization bypass no longer succeeds.", + "command": "npm test -- users-authz.test.js", + "expected_result": "Non-admin DELETE returns 403 and admin DELETE succeeds." + } + ] + } + } + ] + } + } + } + ], + "properties": { + "securityskills": { + "run": { + "id": "run-001", + "timestamp": "2026-06-16T12:00:00Z", + "target": "payments-api", + "source_ref": "abc1234" + }, + "skill": { + "name": "api-security", + "version": "1.0.0", + "path": "skills/appsec/api-security/SKILL.md", + "frameworks": ["OWASP-API-Top-10-2023", "CWE"] + } + } + } + } + ] +} +``` diff --git a/skills/dependency-scanning/schemas/finding.schema.json b/skills/dependency-scanning/schemas/finding.schema.json new file mode 100644 index 0000000..535a496 --- /dev/null +++ b/skills/dependency-scanning/schemas/finding.schema.json @@ -0,0 +1,345 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/UnitOneAI/SecuritySkills/schemas/finding.schema.json", + "title": "SecuritySkills Normalized Finding Output", + "description": "Machine-readable envelope for normalized security findings and remediation recommendations emitted by SecuritySkills workflows. This contract is independent of SARIF and may be mapped to downstream enterprise formats later.", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "run", "skill", "findings"], + "properties": { + "schema_version": { + "const": "1.0.0", + "description": "Version of this normalized SecuritySkills finding envelope." + }, + "run": { + "$ref": "#/$defs/run", + "description": "Metadata for the analysis run that produced this output." + }, + "skill": { + "$ref": "#/$defs/skill", + "description": "Metadata for the SecuritySkills entrypoint that produced this output." + }, + "findings": { + "type": "array", + "items": { + "$ref": "#/$defs/finding" + }, + "description": "Normalized findings produced by a skill run." + } + }, + "$defs": { + "riskLevel": { + "type": "string", + "enum": ["low", "medium", "high"] + }, + "nonEmptyString": { + "type": "string", + "minLength": 1 + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "run": { + "type": "object", + "additionalProperties": false, + "required": ["id", "timestamp"], + "properties": { + "id": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable run identifier supplied by the agent, CI job, or enterprise orchestrator." + }, + "timestamp": { + "$ref": "#/$defs/nonEmptyString", + "description": "ISO 8601 timestamp for when the run output was produced." + }, + "tool": { + "$ref": "#/$defs/nonEmptyString", + "description": "Agent, CLI, scanner, or workflow that executed the skill." + }, + "target": { + "$ref": "#/$defs/nonEmptyString", + "description": "Repository, project, service, artifact, environment, or other target reviewed." + }, + "source_ref": { + "$ref": "#/$defs/nonEmptyString", + "description": "Optional commit SHA, branch, image digest, build ID, ticket ID, or evidence package reference." + } + } + }, + "skill": { + "type": "object", + "additionalProperties": false, + "required": ["name", "version"], + "properties": { + "name": { + "$ref": "#/$defs/nonEmptyString", + "description": "SecuritySkills skill name from SKILL.md frontmatter." + }, + "version": { + "$ref": "#/$defs/nonEmptyString", + "description": "SecuritySkills skill version from SKILL.md frontmatter." + }, + "path": { + "$ref": "#/$defs/nonEmptyString", + "description": "Path to the SKILL.md entrypoint used for the run." + }, + "frameworks": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/nonEmptyString" + }, + "description": "Framework identifiers declared by the skill frontmatter." + } + } + }, + "finding": { + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "severity", "status", "evidence", "remediations"], + "properties": { + "id": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable finding identifier within the output." + }, + "fingerprint": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable deduplication key based on finding type, affected asset, and evidence location." + }, + "title": { + "$ref": "#/$defs/nonEmptyString" + }, + "description": { + "$ref": "#/$defs/nonEmptyString", + "description": "What the issue is and why it matters." + }, + "severity": { + "type": "string", + "enum": ["info", "low", "medium", "high", "critical"] + }, + "status": { + "type": "string", + "enum": ["open", "mitigated", "accepted_risk", "false_positive"] + }, + "cwe": { + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "pattern": "^CWE-[0-9]+$" + }, + "description": "Optional CWE mappings, when applicable." + }, + "framework_refs": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/frameworkRef" + }, + "description": "Framework/control references from the skill frontmatter frameworks." + }, + "references": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/reference" + }, + "description": "Optional advisory, standard, vendor, or knowledge-base references." + }, + "evidence": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["location", "summary"], + "properties": { + "location": { + "$ref": "#/$defs/nonEmptyString", + "description": "File path, line range, asset ID, log source, policy path, or other concrete evidence location." + }, + "summary": { + "$ref": "#/$defs/nonEmptyString" + }, + "artifact_type": { + "type": "string", + "enum": ["source", "config", "policy", "log", "scan_result", "cloud_resource", "identity", "network", "document", "other"] + }, + "snippet": { + "$ref": "#/$defs/nonEmptyString", + "description": "Minimal redacted snippet or observation needed to support the finding." + }, + "redacted": { + "type": "boolean", + "description": "True when sensitive values were intentionally removed from this evidence." + } + } + } + }, + "remediations": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/remediation" + }, + "description": "Every fix recommendation for this finding. Each item must include remediation guidance, confidence, blast radius, behavior-change risk, and test strategy." + } + }, + "anyOf": [ + { + "required": ["cwe"] + }, + { + "required": ["framework_refs"] + } + ] + }, + "frameworkRef": { + "type": "object", + "additionalProperties": false, + "required": ["framework", "control"], + "properties": { + "framework": { + "$ref": "#/$defs/nonEmptyString" + }, + "control": { + "$ref": "#/$defs/nonEmptyString" + }, + "name": { + "$ref": "#/$defs/nonEmptyString" + } + } + }, + "reference": { + "type": "object", + "additionalProperties": false, + "required": ["type", "id"], + "properties": { + "type": { + "type": "string", + "enum": ["cve", "cwe", "framework", "advisory", "vendor", "documentation", "other"] + }, + "id": { + "$ref": "#/$defs/nonEmptyString" + }, + "url": { + "$ref": "#/$defs/uriString" + } + } + }, + "remediation": { + "type": "object", + "additionalProperties": false, + "required": ["guidance", "confidence", "blast_radius", "behavior_change_risk", "test_strategy"], + "properties": { + "guidance": { + "$ref": "#/$defs/nonEmptyString", + "description": "Concrete remediation steps or patch guidance for the finding." + }, + "confidence": { + "$ref": "#/$defs/riskLevel", + "description": "How confident the skill is that this recommendation is correct for the observed evidence." + }, + "blast_radius": { + "$ref": "#/$defs/nonEmptyString", + "description": "Expected scope of systems, files, users, integrations, data, or workflows affected by the change." + }, + "behavior_change_risk": { + "$ref": "#/$defs/riskLevel", + "description": "Risk that the remediation changes intended application or operational behavior." + }, + "test_strategy": { + "$ref": "#/$defs/testStrategy", + "description": "Required validation strategy proving the remediation fixes the finding. Include recommended tests, generated tests, or both." + } + } + }, + "testStrategy": { + "type": "object", + "additionalProperties": false, + "required": ["summary"], + "properties": { + "summary": { + "$ref": "#/$defs/nonEmptyString", + "description": "Concise explanation of what proves the remediation fixed the issue." + }, + "recommended_tests": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/recommendedTest" + }, + "description": "Tests the user or agent should run when tests are not generated directly." + }, + "generated_tests": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/generatedTest" + }, + "description": "Test files or cases produced as part of the remediation." + } + }, + "anyOf": [ + { + "required": ["recommended_tests"] + }, + { + "required": ["generated_tests"] + } + ] + }, + "recommendedTest": { + "type": "object", + "additionalProperties": false, + "required": ["name", "type", "purpose", "command", "expected_result"], + "properties": { + "name": { + "$ref": "#/$defs/nonEmptyString" + }, + "type": { + "type": "string", + "enum": ["static", "unit", "integration", "e2e", "regression", "manual"] + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString", + "description": "Behavior, vulnerability condition, or regression this test proves." + }, + "command": { + "$ref": "#/$defs/nonEmptyString", + "description": "Command or manual check to execute for this test." + }, + "expected_result": { + "$ref": "#/$defs/nonEmptyString" + } + } + }, + "generatedTest": { + "type": "object", + "additionalProperties": false, + "required": ["path", "type", "purpose", "command", "expected_result"], + "properties": { + "path": { + "$ref": "#/$defs/nonEmptyString", + "description": "Path to the generated or modified test file." + }, + "type": { + "type": "string", + "enum": ["static", "unit", "integration", "e2e", "regression"] + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString", + "description": "Behavior, vulnerability condition, or regression this generated test proves." + }, + "command": { + "$ref": "#/$defs/nonEmptyString", + "description": "Command that runs the generated test." + }, + "expected_result": { + "$ref": "#/$defs/nonEmptyString" + } + } + } + } +} diff --git a/skills/design-taste-frontend/LICENSE b/skills/design-taste-frontend/LICENSE new file mode 100644 index 0000000..48a2f66 --- /dev/null +++ b/skills/design-taste-frontend/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Leonxlnx + +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/skills/design-taste-frontend/SKILL.md b/skills/design-taste-frontend/SKILL.md new file mode 100644 index 0000000..b72132f --- /dev/null +++ b/skills/design-taste-frontend/SKILL.md @@ -0,0 +1,1206 @@ +--- +name: design-taste-frontend +description: Anti-slop frontend skill for landing pages, portfolios, and redesigns. The agent reads the brief, infers the right design direction, and ships interfaces that do not look templated. Real design systems when applicable, audit-first on redesigns, strict pre-flight check. +--- + +# tasteskill: Anti-Slop Frontend Skill + +> Landing pages, portfolios, and redesigns. Not dashboards, not data tables, not multi-step product UI. +> Every rule below is **contextual**. None of it fires automatically. First read the brief, then pull only what fits. + +--- + +## 0. BRIEF INFERENCE (Read the Room Before Anything Else) + +Before touching code or tweaking dials, **infer what the user actually wants**. Most LLM design output is bad because the model jumps to a default aesthetic instead of reading the room. + +### 0.A Read these signals first +1. **Page kind** - landing (SaaS / consumer / agency / event), portfolio (dev / designer / creative studio), redesign (preserve vs overhaul), editorial / blog. +2. **Vibe words** the user used - "minimalist", "calm", "Linear-style", "Awwwards", "brutalist", "premium consumer", "Apple-y", "playful", "serious B2B", "editorial", "agency-y", "glassy", "dark tech". +3. **Reference signals** - URLs they linked, screenshots they pasted, products they named, brands they're competing with. +4. **Audience** - B2B procurement panel vs. design-conscious consumer vs. recruiter scanning a portfolio. The audience picks the aesthetic, not your taste. +5. **Brand assets that already exist** - logo, color, type, photography. For redesigns, these are starting material, not optional input (see Section 11). +6. **Quiet constraints** - accessibility-first audiences, public-sector, regulated industries, trust-first commerce, kids' products. These constraints OVERRIDE aesthetic preference. + +### 0.B Output a one-line "Design Read" before generating +Before any code, state in one line: **"Reading this as: \ for \, with a \ language, leaning toward \."** + +Example reads: +- *"Reading this as: B2B SaaS landing for technical buyers, with a Linear-style minimalist language, leaning toward Tailwind utilities + Geist + restrained motion."* +- *"Reading this as: solo designer portfolio for hiring managers, with an editorial / kinetic-type language, leaning toward native CSS + scroll-driven animation + custom typography."* +- *"Reading this as: redesign of a public-sector service site, with a trust-first language, leaning toward GOV.UK Frontend or USWDS."* + +### 0.C If the brief is ambiguous, ask one question, do not guess +Ask exactly **one** clarifying question - never a multi-question dump - and only when the design read genuinely diverges. Example: *"Should this feel closer to Linear-clean or Awwwards-experimental?"* + +If you can confidently infer from context, **do not ask**. Just declare the design read and proceed. + +### 0.D Anti-Default Discipline +Do not default to: AI-purple gradients, centered hero over dark mesh, three equal feature cards, generic glassmorphism on everything, infinite-loop micro-animations everywhere, Inter + slate-900. These are the LLM defaults. Reach past them deliberately based on the design read. + +--- + +## 1. THE THREE DIALS (Core Configuration) + +After the design read, set three dials. Every layout, motion, and density decision below is gated by these. + +* **`DESIGN_VARIANCE: 8`** - 1 = Perfect Symmetry, 10 = Artsy Chaos +* **`MOTION_INTENSITY: 6`** - 1 = Static, 10 = Cinematic / Physics +* **`VISUAL_DENSITY: 4`** - 1 = Art Gallery / Airy, 10 = Cockpit / Packed Data + +**Baseline:** `8 / 6 / 4`. Use these unless the design read overrides them. Do not ask the user to edit this file - overrides happen conversationally. + +### 1.A Dial Inference (design read → dial values) +| Signal | VARIANCE | MOTION | DENSITY | +|---|---|---|---| +| "minimalist / clean / calm / editorial / Linear-style" | 5-6 | 3-4 | 2-3 | +| "premium consumer / Apple-y / luxury / brand" | 7-8 | 5-7 | 3-4 | +| "playful / wild / Dribbble / Awwwards / experimental / agency" | 9-10 | 8-10 | 3-4 | +| "landing page / portfolio / marketing site (default)" | 7-9 | 6-8 | 3-5 | +| "trust-first / public-sector / regulated / accessibility-critical" | 3-4 | 2-3 | 4-5 | +| "redesign - preserve" | match existing | +1 | match existing | +| "redesign - overhaul" | +2 | +2 | match existing | + +### 1.B Use-Case Presets +| Use case | VARIANCE | MOTION | DENSITY | +|---|---|---|---| +| Landing (SaaS, mainstream) | 7 | 6 | 4 | +| Landing (Agency / creative) | 9 | 8 | 3 | +| Landing (Premium consumer) | 7 | 6 | 3 | +| Portfolio (Designer / studio) | 8 | 7 | 3 | +| Portfolio (Developer) | 6 | 5 | 4 | +| Editorial / Blog | 6 | 4 | 3 | +| Public-sector service | 3 | 2 | 5 | +| Redesign - preserve | match | match+1 | match | +| Redesign - overhaul | +2 | +2 | match | + +### 1.C How the Dials Drive Output +Use these (or user-overridden values) as global variables. Cross-references throughout this document refer to these exact variable names - never invent aliases like `LAYOUT_VARIANCE` or `ANIM_LEVEL`. + +--- + +## 2. BRIEF → DESIGN SYSTEM MAP + +Once you have the design read (Section 0) and dials (Section 1), pick the right foundation. Do not invent CSS for things that have an official package. Do not pretend an aesthetic trend is an official system. + +### 2.A When to reach for a real design system (use official packages) +| Brief reads as… | Reach for | Why | +|---|---|---| +| Microsoft / enterprise SaaS / dashboards | `@fluentui/react-components` or `@fluentui/web-components` | Official Fluent UI, Microsoft tokens, accessibility done | +| Google-ish UI, Material-flavored product | `@material/web` + Material 3 tokens | Official, theme-able via Material Theming | +| IBM-style B2B / enterprise analytics | `@carbon/react` + `@carbon/styles` | Official Carbon, mature data-density patterns | +| Shopify app surfaces | `polaris.js` web components / Polaris React | Required for Shopify admin UI | +| Atlassian / Jira-style product | `@atlaskit/*` + `@atlaskit/tokens` | Official Atlassian DS | +| GitHub-style devtool / community page | `@primer/css` or `@primer/react-brand` | Official Primer; Brand variant for marketing | +| Public-sector UK service | `govuk-frontend` | Legally / regulatorily expected | +| US public-sector / trust-first | `uswds` | Same | +| Fast local-business / agency MVP | Bootstrap 5.3 | Boring, fast, works | +| Modern accessible React foundation | `@radix-ui/themes` | Primitives + polished theme | +| Modern SaaS where you own the components | shadcn/ui (`npx shadcn@latest add ...`) | You own the code, easy to customise; never ship default state | +| Tailwind-based modern SaaS / AI marketing | Tailwind v4 utilities + `dark:` variant | Default for indie + small team builds | + +**Honesty rule:** if the brief reads as one of the systems above, install and use the **official** package. Do not recreate its CSS by hand. Do not import a system's tokens but then override 90% of them. + +**One system per project.** Do not mix Fluent React with Carbon in the same tree. Do not import shadcn/ui components into a Material 3 app. + +### 2.B When the brief is an aesthetic, not a system +For these directions, there is **no single official package**. Build with native CSS + Tailwind + a maintained component library. Be honest in code comments about what is borrowed inspiration vs. official material. + +| Aesthetic | Honest implementation | +|---|---| +| Glassmorphism / "frosted glass" | `backdrop-filter`, layered borders, highlight overlays. Provide solid-fill fallback for `prefers-reduced-transparency`. | +| Bento (Apple-style tile grids) | CSS Grid with mixed cell sizes. No single library owns this. | +| Brutalism | Native CSS, monospace, raw borders. No library. | +| Editorial / magazine | Serif type, asymmetric grid, generous whitespace. No library. | +| Dark tech / hacker | Mono + accent neon, terminal motifs. No library. | +| Aurora / mesh gradients | SVG or layered radial gradients. No library. | +| Kinetic typography | Native CSS animations, scroll-driven animations, GSAP for hijacks. No library. | +| **Apple Liquid Glass** | Apple documents this for Apple platforms only. **There is no official `liquid-glass.css`.** Web implementations are approximations using `backdrop-filter` + layered borders + highlights. Label clearly as approximation. | + +--- + +## 3. DEFAULT ARCHITECTURE & CONVENTIONS + +Unless the design read picks a real design system (Section 2.A), these are the defaults: + +### 3.A Stack +* **Framework:** React or Next.js. Default to Server Components (RSC). + * **RSC SAFETY:** Global state works ONLY in Client Components. In Next.js, wrap providers in a `"use client"` component. + * **INTERACTIVITY ISOLATION:** Any component using Motion, scroll listeners, or pointer physics MUST be an isolated leaf with `'use client'` at the top. Server Components render static layouts only. +* **Styling:** **Tailwind v4** (default). Tailwind v3 only if the existing project demands it. + * For v4: do NOT use `tailwindcss` plugin in `postcss.config.js`. Use `@tailwindcss/postcss` or the Vite plugin. +* **Animation:** **Motion** (the library formerly known as Framer Motion). Import from `motion/react` (`import { motion } from "motion/react"`). The `framer-motion` package still works as a legacy alias - prefer `motion/react` in new code. +* **Fonts:** Always use `next/font` (Next.js) or self-host with `@font-face` + `font-display: swap`. Never link Google Fonts via `` in production. + +### 3.B State +* Local `useState` / `useReducer` for isolated UI. +* Global state ONLY for deep prop-drilling avoidance - Zustand, Jotai, or React context. +* **NEVER** use `useState` to track continuous values driven by user input (mouse position, scroll progress, pointer physics, magnetic hover). Use Motion's `useMotionValue` / `useTransform` / `useScroll`. `useState` re-renders the React tree on every change and collapses on mobile. + +### 3.C Icons +* **Allowed libraries (priority order):** `@phosphor-icons/react`, `hugeicons-react`, `@radix-ui/react-icons`, `@tabler/icons-react`. +* **Discouraged:** `lucide-react`. Acceptable only when the user explicitly asks for it or the project already depends on it. +* **NEVER hand-roll SVG icons.** If a glyph is missing, install a second library or compose from primitives - do not draw icon paths from scratch. +* **One family per project.** Do not mix Phosphor with Lucide in the same component tree. +* **Standardize `strokeWidth` globally** (e.g. `1.5` or `2.0`). + +### 3.D Emoji Policy +Discouraged by default in code, markup, and visible text. Replace symbols with icon-library glyphs. **Override:** allow emojis only when the user explicitly asks for a playful / chat-style / social-native vibe - and even then use them sparingly with intent. + +### 3.E Responsiveness & Layout Mechanics +* Standardize breakpoints (`sm 640`, `md 768`, `lg 1024`, `xl 1280`, `2xl 1536`). +* Contain page layouts using `max-w-[1400px] mx-auto` or `max-w-7xl`. +* **Viewport Stability:** NEVER use `h-screen` for full-height Hero sections. ALWAYS use `min-h-[100dvh]` to prevent layout jumping on mobile (iOS Safari address bar). +* **Grid over Flex-Math:** NEVER use complex flexbox percentage math (`w-[calc(33%-1rem)]`). ALWAYS use CSS Grid (`grid grid-cols-1 md:grid-cols-3 gap-6`). + +### 3.F Dependency Verification (mandatory) +Before importing ANY 3rd-party library, check `package.json`. If the package is missing, output the install command first. **Never** assume a library exists. + +--- + +## 4. DESIGN ENGINEERING DIRECTIVES (Bias Correction) + +LLMs default to clichés. Override these defaults proactively. Each rule has a context-aware override path. + +### 4.1 Typography +* **Display / Headlines:** Default `text-4xl md:text-6xl tracking-tighter leading-none`. +* **Body / Paragraphs:** Default `text-base text-gray-600 leading-relaxed max-w-[65ch]`. +* **Sans font choice:** + * **Discouraged as default:** `Inter`. Pick `Geist`, `Outfit`, `Cabinet Grotesk`, `Satoshi`, or a brand-appropriate serif first. + * **Override:** Inter is acceptable when the user explicitly asks for a neutral / standard / Linear-style feel, or when the brief is a public-sector / accessibility-first site. +* **Pairings to know:** `Geist` + `Geist Mono`, `Satoshi` + `JetBrains Mono`, `Cabinet Grotesk` + `Inter Tight`, `GT America` + `IBM Plex Mono`. + +* **SERIF DISCIPLINE (VERY DISCOURAGED AS DEFAULT):** + * Serif is **very discouraged as the default font for any project.** "It feels creative / premium / editorial" is NOT a reason to reach for serif. The agent's default mental model that "creative brief = serif" is the single most-tested AI tell in production rounds. + * **Serif is only acceptable when ONE of these is explicitly true:** + - The brand brief literally names a serif font, OR + - The aesthetic family is genuinely editorial / luxury / publication / manuscript / heritage / vintage AND you can articulate why this specific serif fits this specific brand + * For everything else (creative agency, design studio, modern brand, premium consumer, portfolio, lifestyle), **default sans-serif display** (Geist Display, ABC Diatype, Söhne Breit, Cabinet Grotesk Display, Migra Sans, GT Walsheim, Inter Display, PP Neue Montreal). Sans display fonts are not "boring" — they are the default for the same reason black is the default in fashion. + * **EMPHASIS RULE (related):** When you want to emphasize a word within a headline (the kinetic "and `spatial` design" type move), use **italic or bold of the SAME font**. Do NOT inject a random serif word into a sans headline (or vice versa) just to add visual interest. Mixed-family emphasis is amateur. Italic/bold emphasis in the same family is the right move. + * **Specifically BANNED as defaults:** `Fraunces` and `Instrument_Serif` (the two LLM-favorite display serifs). + * **If a serif is justified** (rare, per the above), rotate from this pool, do NOT reuse the same serif across consecutive projects: PP Editorial New, GT Sectra Display, Cardinal Grotesque, Reckless Neue, Tiempos Headline, Recoleta, Cormorant Garamond, Playfair Display, EB Garamond, IvyPresto, Migra, Editorial Old, Saol Display, Söhne Breit Kursiv, Domaine Display, Canela, Schnyder, Tobias, NB Architekt, ITC Galliard. + +* **ITALIC DESCENDER CLEARANCE (mandatory):** When italic is used in display type and the word contains a descender letter (`y g j p q`), `leading-[1]` or `leading-none` will clip the descender. Use `leading-[1.1]` minimum and add `pb-1` or `mb-1` reserve on the wrapping element. Audit every italic word in display headlines before shipping. + +### 4.2 Color Calibration +* Max 1 accent color. Saturation < 80% by default. +* **THE LILA RULE:** The "AI Purple / Blue glow" aesthetic is discouraged as a default. No automatic purple button glows, no random neon gradients. Use neutral bases (Zinc / Slate / Stone) with high-contrast singular accents (Emerald, Electric Blue, Deep Rose, Burnt Orange, etc.). +* **Override:** if the brand or brief explicitly asks for purple / violet / lila, embrace it. But execute with intent: consistent palette, harmonised neutrals, restrained gradients. Not generic AI gradient slop. +* **One palette per project.** Do not fluctuate between warm and cool grays within the same project. +* **COLOR CONSISTENCY LOCK (mandatory):** Once an accent color is chosen for a page, it is used on the WHOLE page. A warm-grey site does not suddenly get a blue CTA in section 7. A rose-accented site does not get a teal status badge in the footer. Pick one accent, lock it, audit every component before shipping. + +* **PREMIUM-CONSUMER PALETTE BAN (mandatory, second-most-recurring AI-tell):** + * For premium-consumer briefs (cookware, wellness, artisan, luxury, heritage craft, DTC home goods, etc.) the LLM default is **warm beige/cream + brass/clay/oxblood/ochre + espresso/ink dark text**. Concretely banned hex families as default backgrounds and accents: + - Backgrounds: `#f5f1ea`, `#f7f5f1`, `#fbf8f1`, `#efeae0`, `#ece6db`, `#faf7f1`, `#e8dfcb` (all "warm paper / cream / chalk / bone") + - Accents: `#b08947`, `#b6553a`, `#9a2436`, `#9c6e2a`, `#bc7c3a`, `#7d5621` (all "brass / clay / oxblood / ochre") + - Text: `#1a1714`, `#1a1814`, `#1b1814` (all "espresso / warm near-black") + * This palette is BANNED as the default reach for premium-consumer briefs. Every premium-consumer site you have ever shipped uses this exact palette. The brand becomes invisible. + * **Default alternatives (rotate, do not reuse):** + - **Cold Luxury:** silver-grey + chrome + smoke (think Tesla, Apple Watch Hermes-without-the-leather) + - **Forest:** deep green + bone + amber accent (think Filson, Patagonia premium) + - **Black and Tan:** true off-black + warm tan, sharp contrast, no beige + - **Cobalt + Cream:** saturated blue against a single neutral, no brass + - **Terracotta + Slate:** warm rust against cool grey, no brass + - **Olive + Brick + Paper:** muted olive plus brick-red accent + - **Pure monochrome + single saturated pop:** off-white + off-black + one bright accent (electric blue, emerald, hot pink, etc.) + * **Palette-rotation rule:** if the previous premium-consumer project you generated used the beige+brass family, this one MUST use a different family. Do not ship the same warm-craft palette twice in a row. + * **Override:** the beige+brass+espresso palette is acceptable ONLY when the brand brief explicitly names those colors, or when the brand identity is genuinely vintage / artisan / warm-craft AND you can articulate why this specific palette fits this specific brand. Default-reaching for it because "this is a cookware brief" is banned. + +### 4.3 Layout Diversification +* **ANTI-CENTER BIAS:** Centered Hero / H1 sections are avoided when `DESIGN_VARIANCE > 4`. Force "Split Screen" (50/50), "Left-aligned content / right-aligned asset", "Asymmetric white-space", or scroll-pinned structures. +* **Override:** centered hero is OK for editorial / manifesto / launch-announcement briefs where the message itself is the design. + +### 4.4 Materiality, Shadows, Cards +* Use cards ONLY when elevation communicates real hierarchy. Otherwise group with `border-t`, `divide-y`, or negative space. +* When a shadow is used, tint it to the background hue. No pure-black drop shadows on light backgrounds. +* For `VISUAL_DENSITY > 7`: generic card containers are banned. Data metrics breathe in plain layout. +* **SHAPE CONSISTENCY LOCK (mandatory):** Pick ONE corner-radius scale for the page and stick to it. Options: all-sharp (radius 0), all-soft (radius 12-16px), all-pill (full radius for interactive). Mixed systems are allowed only when there is a documented rule (e.g. "buttons are full-pill, cards are 16px, inputs are 8px") and that rule is followed everywhere. Round buttons in a square layout, or square cards on a pill-button page, is broken design. + +### 4.5 Interactive UI States +LLMs default to "static successful state only." Always implement full cycles: +* **Loading:** Skeletal loaders matching the final layout's shape. Avoid generic circular spinners. +* **Empty States:** Beautifully composed; indicate how to populate. +* **Error States:** Clear, inline (forms), or contextual (toasts only for transient). +* **Tactile Feedback:** On `:active`, use `-translate-y-[1px]` or `scale-[0.98]` to simulate a physical push. +* **BUTTON CONTRAST CHECK (mandatory, a11y):** Before shipping any button, verify the button text is readable against the button background. White button + white text, `bg-white` CTA with `text-white` label, transparent button against the page background with no border → all banned. Audit every CTA: contrast ratio WCAG AA min (4.5:1 for body, 3:1 for large text 18px+). Same rule applies to ghost buttons over photographic backgrounds (use a backdrop, scrim, or stroke). +* **CTA BUTTON WRAP BAN (mandatory):** Button text MUST fit on one line at desktop. If a label like "VIEW SELECTED WORK" wraps to 2 or 3 lines, the button is broken. Fix by EITHER shortening the label (3 words max for primary CTAs, ideally 1-2) OR widening the button (do not artificially constrain `max-width` on CTAs). Wrapped CTAs at desktop are a Pre-Flight Fail. +* **NO DUPLICATE CTA INTENT (mandatory):** Two CTAs with the same intent on one page is a Pre-Flight Fail. Examples of same intent: "Get in touch" + "Contact us" + "Let's talk" + "Start a project" + "Start something" + "Reach out" = all "contact" intent → pick ONE label and use it everywhere on the page (nav, hero, footer). Same for "Try free" + "Get started" + "Sign up free" (all "signup" intent) and "View work" + "See selected work" + "Browse projects" (all "portfolio" intent). One label per intent. +* **FORM CONTRAST CHECK (mandatory, a11y):** Form inputs, placeholder text, focus rings, helper text, and error text all pass WCAG AA contrast against the section background. Light placeholders on a near-white form, white form on white page section, form labels grayer than 4.5:1 contrast → all banned. Audit every form before shipping. + +### 4.6 Data & Form Patterns +* Label ABOVE input. Helper text optional but present in markup. Error text BELOW input. Standard `gap-2` for input blocks. +* No placeholder-as-label. Ever. + +### 4.7 Layout Discipline (Hard Rules. Failing any of these is shipping broken work) + +* **Hero MUST fit in the initial viewport.** Headline max 2 lines on desktop, subtext max **20 words** AND max 3-4 lines, CTAs visible without scroll. If the copy is too long: reduce font scale OR cut copy. If you cannot describe the value-prop in 20 words of subtext, the value-prop is unclear, not the rule too tight. Never let the hero overflow and force scroll to find the CTA. +* **Hero font-scale discipline.** Plan font size and image size *together*. If the hero asset is large and the headline is more than 6 words, do not start at `text-7xl/text-8xl`. Default sensible range: `text-4xl md:text-5xl lg:text-6xl` for most heroes; `text-6xl md:text-7xl` only when the headline is 3-5 words. A 4-line hero headline is always a font-size error, never a copy-length error. +* **HERO TOP PADDING CAP (mandatory):** Hero top padding max `pt-24` (≈6rem) at desktop. More than that means the hero content floats halfway down the viewport and reads as a layout bug, not as intentional space. If your hero needs more breathing room, increase font scale or asset size, not top padding. +* **HERO STACK DISCIPLINE (max 4 text elements).** The hero is a single moment, not a feature list. Allowed text elements, max 4 in total: + 1. Eyebrow (small uppercase label) OR brand strip OR neither - pick zero or one + 2. Headline (max 2 lines, see above) + 3. Subtext (max 20 words, max 4 lines) + 4. CTAs (1 primary + max 1 secondary) + - **BANNED in the hero:** tiny tagline below CTAs ("Works with GitHub, GitLab, and self-hosted Git"), trust micro-strip ("Used by engineering teams at..."), pricing teaser ("Free for solo, $10/user for teams"), feature bullet list, social-proof avatar row. All of those move to dedicated sections directly below the hero. + - If you have an eyebrow AND a tagline below CTAs in the same hero, drop the tagline. If you have a brand strip AND a tagline, drop the tagline. One small text element per hero, max. +* **"Used by" / "Trusted by" logo wall belongs UNDER the hero, never inside it.** The hero is for the value prop and primary CTA. The logo wall is a separate section directly below. Do not stuff trust logos into the same flex row as the hero copy. +* **Navigation MUST render on a single line on desktop.** If items don't fit at `lg` (1024px), condense labels, drop secondary items, or move to a hamburger. A two-line nav at desktop is broken design. +* **Navigation height cap: 80px max desktop, default 64-72px.** No huge "agency" nav bars that eat 15% of the viewport. +* **Bento grids MUST have rhythm, not one-sided repetition.** Do not stack 6 left-image / right-text rows. Vary the composition: alternate full-width feature rows, asymmetric tile sizes, vertical breaks. +* **BENTO CELL COUNT RULE (mandatory):** A bento grid has EXACTLY as many cells as you have content for. 3 items → 3 cells (1+2 split, or 2+1, or asymmetric trio). 5 items → 5 cells (2+3, 3+2, hero+4, etc.). If your grid has an empty cell in the middle or at the end, you planned wrong. Re-shape the grid; do not paste a blank tile. +* **Section-Layout-Repetition Ban.** Once you use a layout family for a section (e.g., 3-column-image-cards, full-width-quote, split-text-image), that family can appear at most ONCE on the page. "Selected commissions" must not look like "What we do." A landing page with 8 sections must use at least 4 different layout families. +* **ZIGZAG ALTERNATION CAP (mandatory).** Alternating "left-image + right-text" then "left-text + right-image" zigzag layout = banal. Max 2 sections in a row with this image+text-split pattern. The 3rd consecutive image+text split is a Pre-Flight Fail. Break the pattern with a full-width section, a vertical-stack section, a bento grid, a marquee, or a different layout family. +* **EYEBROW RESTRAINT (mandatory, the #1 violated rule in production tests).** An "eyebrow" is the small uppercase wide-tracking label sitting above a section headline (e.g. `FOUR COLORWAYS`, `SELECTED WORK`, `THE HARDWARE`, `Git-native task management`). Typical CSS signature: `text-[11px] uppercase tracking-[0.18em]`, `font-mono text-[10.5px] uppercase tracking-[0.22em]`. Every AI-built site puts an eyebrow above EVERY section header, producing the same templated rhythm. Hard rule: + - **Maximum 1 eyebrow per 3 sections.** Hero counts as 1. So a page with 9 sections may use at most 3 eyebrows total. + - If section A has an eyebrow, the next 2 sections cannot have one. + - **Pre-Flight Check is mechanical:** count instances of `uppercase tracking` (or similar small-caps mono labels above headlines) across all section components. If count > ceil(sectionCount / 3), the output fails. + - **What to do instead of an eyebrow:** drop it entirely. The headline alone is enough. If you need to categorize a section, the section's location on the page already categorizes it; no label needed. +* **SPLIT-HEADER BAN (mandatory).** The pattern "left big headline + right small explainer paragraph" as a section header (left col-span-7/8, right col-span-4/5 with a small body paragraph floating in the right column) is **banned as default**. Sections should have ONE focused message. If you genuinely need both a headline and an explainer paragraph, stack them vertically (headline on top, body below, max-width 65ch). Reach for the split-header pattern only when there is a real compositional reason (e.g., the right column carries a visual or interactive element, not just filler text). +* **Bento Background Diversity (mandatory).** Bento and feature-grid sections cannot be 6 white-on-white cards with text inside. At least 2-3 cells in any multi-cell grid need real visual variation: a real image, a brand-appropriate gradient (not AI-purple), a pattern, a tinted background. A cream-on-cream bento with only typography inside reads as boring AI default, even when the rest of the page is good. +* **Mobile collapse must be explicit per section.** For every multi-column layout, declare the `< 768px` fallback in the same component. No "it'll work, Tailwind handles it" assumptions. + +### 4.8 Image & Visual Asset Strategy + +Landing pages and portfolios are **visual products**. Text-only pages with fake-screenshot divs are slop. + +**Priority order for visual assets:** +1. **Image-generation tool first.** If ANY image-gen tool is available in the environment (`generate_image`, MCP image tool, IDE-integrated gen, OpenAI image tools, etc.) you MUST use it to create section-specific assets: hero photography, product shots, texture backgrounds, mood images. Generate at the right aspect ratio for the section. Do not skip this step because hand-rolled CSS feels faster. +2. **Real web images second.** When no gen tool is available, use real photography sources. Acceptable defaults: + * `https://picsum.photos/seed/{descriptive-seed}/{w}/{h}` for placeholder photography (seed should describe the section, e.g. `marrow-cookware-kitchen`) + * Actual stock or brand URLs when the brief provides them + * Open-license sources (Unsplash via direct URL, Pexels) if explicitly allowed +3. **Last resort: tell the user.** If neither is possible, do NOT fill the page with hand-rolled SVG illustrations or div-based "fake screenshots." Instead, leave clearly-labeled placeholder slots (``) and at the end of the response say: *"This page needs real images at: \[list of placements\]. Please generate or provide them."* + +**Even minimalist sites need real images.** A pure-text page is not minimalism. It is incomplete work. Even an editorial Linear-style site needs at least 2-3 real images (hero, one product/lifestyle shot, one supporting image). Generate B&W minimalist photography if the brief is restrained; do not skip images entirely because the dial is low. + +**Real company logos for social proof.** When the brief calls for a "Trusted by / Used by / Customers" logo wall, do NOT default to plain text wordmarks (`Acme Co` styled in a row). Use real SVG logos: +* **Source: Simple Icons** (`https://cdn.simpleicons.org/{slug}/ffffff` for any color, or `simple-icons` npm package). Covers most known brands. +* **Alternative: devicon** for tech-stack logos (`@svgr/cli` or CDN). +* **Make-up the brand name? Then make-up an SVG mark too.** Generate a simple monogram (one letter in a circle, two-letter ligature, abstract glyph) rendered as an inline `` matching the page style. Plain text wordmarks for invented brand names look generic. +* **Always** ensure logos render in both light and dark mode (white-on-dark, black-on-light, or single-color theme variable). +* **LOGO-ONLY rule (mandatory):** logo wall = logos and nothing else. Do NOT print industry / category labels below each logo (no `Vercel` + `hosting` underneath, no `Stripe` + `payments`, no `Cloudflare` + `infra`). The logo is the credibility, the label adds nothing the user does not already know. Optional: brand name as alt-text for screen readers, optional link to the brand's site. That is it. + +**Hand-rolled illustrations:** +* SVG icons from libraries: fine (see Section 3.C). +* Hand-rolled decorative SVGs (custom illustrations, logos, marks): **strongly discouraged**, never as default. Acceptable only when: + - The brief explicitly calls for it ("draw me an SVG logo") + - It's a single, simple geometric mark (a square, a circle, a wordmark in display type) + - You're confident in the output quality + +**Div-based fake screenshots are banned.** A "hand-built product preview" rendered with `
` rectangles, fake task lists, fake dashboards, fake terminal windows is a Tell. If you need to show a product: +* Use a real screenshot URL if one exists +* Generate one via image tool +* Use a real component preview (an actual mini-version of the UI inside the page) +* Or skip the preview entirely and use editorial photography + +**Hero needs a real visual.** Text + gradient blob is not a hero - it's a placeholder. + +### 4.9 Content Density + +Landing pages live on the **first impression**, not the full read. Cut ruthlessly. + +* **Default content shape per section:** short headline (≤ 8 words) + short sub-paragraph (≤ 25 words) + one visual asset OR one CTA. Anything more must be justified by the section's job. +* **No data-dump sections.** A 20-row publication table, a 30-row award list, a giant pricing matrix on a marketing page = wrong layout. Use: + - Top 3-5 highlights + "View full list" link + - Marquee / carousel for breadth + - Different page entirely if the data is the product +* **Long lists need a different UI component, not a longer list.** Default `
    ` with bullets / `divide-y` rows is the lazy choice. If you have > 5 items, reach for one of these instead: + - 2-column split with grouped items + - Card grid with image + label per item + - Tabs / accordion if items are categorisable + - Horizontal scroll-snap pills + - Carousel for breadth-heavy lists (testimonials, logos, capabilities) + - Marquee for "lots-of-things-that-don't-need-individual-attention" + A spec sheet with 10 rows + a hairline under every row is the WORST default. Either group rows into 2-3 chunks with sparse dividers, or move to a card-per-spec layout. +* **Spec sheets specifically (the Marrow-cookware pattern).** A long product specification table with `border-b` on every row is the AI default for cookware / hardware / apparel / artisan-goods briefs. Banned. Concrete alternatives: + - **2-col card grid:** each spec gets its own card with the spec name, the value (large display number), and a one-line "why it matters" body. Cards arranged 2-col on desktop, 1-col mobile. + - **Scroll-snap horizontal pills:** each spec is a pill, user can flick through. + - **Grouped chunks:** group 10 specs into 3 logical clusters (e.g. "Materials", "Cooking", "Warranty"), each cluster gets ONE soft divider and a cluster heading. + - **Featured-vs-rest:** 3-4 hero specs visualised as large display tiles, the rest collapsed under a "View full specifications" disclosure. + +* **COPY SELF-AUDIT (mandatory before ship):** Before declaring any task done, re-read every visible string on the page (headlines, subheads, eyebrows, button labels, body copy, captions, alt text, footer text, error messages). Flag any string that is: + - **Grammatically broken** ("free on its past", "two plans but one is honest", "to put it on the table" out of context) + - **Has unclear referents** ("we plan to stay that way" without prior context) + - **Sounds like AI hallucination** (cute-but-wrong wordplay, forced metaphors that don't track, "elegant nothing" phrases) + - **Reads like an LLM trying to sound thoughtful** (passive-aggressive humility, fake-craftsman labels, mock-poetic micro-meta) + Rewrite every flagged string. If unsure whether a string makes sense, replace it with a plain functional sentence. AI-generated cute copy is worse than boring copy. +* **Fake-precise numbers are flagged.** Numbers like `92%`, `4.1×`, `48k`, `5.8 mm`, `13.4 lb` either: + - Come from real data (brief, brand guidelines, public metrics) - fine + - Are explicitly labeled as mock (``, "example", "sample data") - fine + - Are AI-invented spec aesthetics - banned. Don't fake engineering precision the brand doesn't claim. +* **One copy register per page.** Don't mix technical mono ("47 tasks · 0.6 ctx-switches/day"), editorial prose, and marketing punch in the same composition unless the brand voice explicitly calls for it. + +### 4.10 Quotes & Testimonials + +* **Max 3 lines** of quote body. Never 6. If the original quote is longer → cut it. A landing-page quote is a snippet, not the full review. +* For very small font sizes (e.g. footer-style testimonials), the line cap can stretch slightly. Spirit: "fits in a glance." +* **No em-dashes inside the quote text** as design flourish (long pauses, kinetic em-dashes, em-dash-bullets). See Section 9.G - em-dash is completely banned. +* Attribution: name + role + (optionally) company. Never name only ("- Sarah"). +* Quote marks: use real typographic quotes ( " " ) or none at all. Not straight ASCII ( " ). + +### 4.11 Page Theme Lock (Light / Dark Mode Consistency) + +The page has ONE theme. Sections do not invert. + +* If the page is dark mode, ALL sections are dark mode. No light-mode-warm-paper section sandwiched between dark sections (or vice versa). The user must not feel they walked into a different website mid-scroll. +* The exception: if the brief explicitly calls for a "Color Block Story" or "Theme Switch on Scroll" device AND that is a deliberate composition (one full theme switch with a strong transition, not random alternation), it is allowed once per page. +* Default behaviour: pick light, dark, or auto (`prefers-color-scheme`) at the page level and lock it. Section-level background tints within the same theme family are fine (`bg-zinc-950` next to `bg-zinc-900`); flipping to `bg-amber-50` in the middle of a `bg-zinc-950` page is broken. +* When using a design system with built-in theming (Radix Themes, shadcn/ui with ``), set the theme ONCE in `layout.tsx` or the page root. Do not let individual sections override. + +--- + +## 5. CONTEXT-AWARE PROACTIVITY + +These are tools, not defaults. Use them when the design read calls for them. **None of these fire automatically.** + +* **Liquid Glass / Glassmorphism:** Appropriate for premium consumer, Apple-adjacent, luxury brand, or media-overlay vibes. Inappropriate for dashboards, public-sector, or "boring B2B." When used, go beyond `backdrop-blur`: add a 1px inner border (`border-white/10`) and a subtle inner shadow (`shadow-[inset_0_1px_0_rgba(255,255,255,0.1)]`) for physical edge refraction. Provide a solid-fill fallback under `prefers-reduced-transparency`. +* **Magnetic Micro-physics:** Use when `MOTION_INTENSITY > 5` AND the brief reads premium / playful / agency. Implement EXCLUSIVELY with Motion's `useMotionValue` / `useTransform` outside the React render cycle. Never `useState`. See Section 3.B. +* **Perpetual Micro-Interactions** (Pulse, Typewriter, Float, Shimmer, Carousel): Use when `MOTION_INTENSITY > 5` AND the section actively benefits from motion (status indicators, live feeds, AI-feel). **Not every card needs an infinite loop.** If a section is informational, leave it still. Apply Spring Physics (`type: "spring", stiffness: 100, damping: 20`) - no linear easing. +* **"Motion claimed, motion shown."** If `MOTION_INTENSITY > 4`, the page must actually move: entry transitions on hero, scroll-reveal on key sections, hover physics on CTAs, at minimum. A static page that claims `MOTION_INTENSITY: 7` is broken. Conversely, if you cannot ship working motion in the available scope, drop the dial to 3 and ship a clean static page. Never half-build motion that breaks (cut-off ScrollTriggers, jumpy enters, missing cleanups). +* **MOTION MUST BE MOTIVATED (mandatory).** Before adding any animation, ask: "what does this animation communicate?" Valid answers: hierarchy (drawing attention to the right thing), storytelling (revealing content in sequence that matches a narrative), feedback (acknowledging a user action), state transition (showing something changed). Invalid answer: "it looked cool". GSAP everywhere because GSAP is available is amateur. Each ScrollTrigger, each marquee, each pinned section needs a reason. If you cannot articulate the reason in one sentence, drop the animation. +* **MARQUEE MAX-ONE-PER-PAGE (mandatory).** Horizontal scrolling text marquees ("logos endlessly scrolling", "manifesto scrolling sideways", "kinetic word strip") are appropriate at most ONCE per page. Two or more marquees on the same page reads as lazy filler. Pick the one section where the marquee actually serves the content; the others get a different layout. +* **GSAP Sticky-Stack Pattern (when scroll-stack is used).** A "card stack on scroll" must be a REAL sticky-stack, not a sequential reveal list. See Section 5.A below for the canonical code skeleton. Common failure: trigger fires halfway through scroll instead of pinning at viewport top. Fix: `start: "top top"` not `start: "top center"` or `"top 80%"`. +* **GSAP Horizontal-Pan Pattern (when horizontal scroll-hijack is used).** See Section 5.B below for the canonical skeleton. Common failure: animation starts before the section is pinned, so the user sees half a slide. Same fix: `start: "top top"`, pin the wrapper, scrub the inner track. + +### 5.A Sticky-Stack - Canonical Skeleton + +```tsx +"use client"; +import { useRef, useEffect } from "react"; +import { gsap } from "gsap"; +import { ScrollTrigger } from "gsap/ScrollTrigger"; +import { useReducedMotion } from "motion/react"; + +gsap.registerPlugin(ScrollTrigger); + +export function StickyStack({ cards }: { cards: React.ReactNode[] }) { + const ref = useRef(null); + const reduce = useReducedMotion(); + + useEffect(() => { + if (reduce || !ref.current) return; + const ctx = gsap.context(() => { + const cardEls = gsap.utils.toArray(".stack-card"); + cardEls.forEach((card, i) => { + if (i === cardEls.length - 1) return; + ScrollTrigger.create({ + trigger: card, + start: "top top", // pin at viewport top + endTrigger: cardEls[cardEls.length - 1], + end: "top top", + pin: true, + pinSpacing: false, + }); + gsap.to(card, { + scale: 0.92, + opacity: 0.55, + ease: "none", + scrollTrigger: { + trigger: cardEls[i + 1], + start: "top bottom", + end: "top top", + scrub: true, + }, + }); + }); + }, ref); + return () => ctx.revert(); + }, [reduce]); + + return ( +
    + {cards.map((card, i) => ( +
    + {card} +
    + ))} +
    + ); +} +``` + +Critical points: `start: "top top"`, `pin: true`, every card except the last is pinned, the scale/opacity transform is driven by the NEXT card's scroll trigger (so previous card shrinks as next one arrives). + +### 5.B Horizontal-Pan - Canonical Skeleton + +```tsx +"use client"; +import { useRef, useEffect } from "react"; +import { gsap } from "gsap"; +import { ScrollTrigger } from "gsap/ScrollTrigger"; +import { useReducedMotion } from "motion/react"; + +gsap.registerPlugin(ScrollTrigger); + +export function HorizontalPan({ children }: { children: React.ReactNode }) { + const wrap = useRef(null); + const track = useRef(null); + const reduce = useReducedMotion(); + + useEffect(() => { + if (reduce || !wrap.current || !track.current) return; + const ctx = gsap.context(() => { + const distance = track.current!.scrollWidth - window.innerWidth; + gsap.to(track.current, { + x: -distance, + ease: "none", + scrollTrigger: { + trigger: wrap.current, + start: "top top", // pin starts when section top hits viewport top + end: () => `+=${distance}`, // scroll distance = track width minus viewport + pin: true, + scrub: 1, + invalidateOnRefresh: true, + }, + }); + }, wrap); + return () => ctx.revert(); + }, [reduce]); + + return ( +
    +
    + {children} +
    +
    + ); +} +``` + +Critical points: `start: "top top"`, `pin: true`, `end: "+=${distance}"` (scroll length = horizontal travel needed), `scrub: 1`. The wrapper is pinned, the inner track slides horizontally as the user scrolls vertically. + +### 5.C Scroll-Reveal Stagger - Canonical Skeleton (lighter alternative) + +For simple "items appear as they enter viewport" (no pinning), prefer Motion's `whileInView` over GSAP - lighter, no ScrollTrigger needed: + +```tsx +"use client"; +import { motion, useReducedMotion } from "motion/react"; + +export function RevealStagger({ items }: { items: string[] }) { + const reduce = useReducedMotion(); + return ( +
      + {items.map((item, i) => ( + + {item} + + ))} +
    + ); +} +``` + +Use this for: feature lists, testimonial grids, logo walls, anything that just needs "enter on scroll." Save GSAP for actual pin/scrub work. + +### 5.D Forbidden Animation Patterns + +* **`window.addEventListener("scroll", ...)`** is banned. It runs on every scroll frame, jank-prone, no batching. Use Motion's `useScroll()`, GSAP's `ScrollTrigger`, IntersectionObserver, or CSS `scroll-driven animations` (`animation-timeline: view()`). +* **Custom scroll progress calculations using `window.scrollY`** in React state. Same reason. Re-renders on every frame. +* **`requestAnimationFrame` loops that touch React state.** Use motion values (`useMotionValue` + `useTransform`) instead. +* **Layout Transitions:** Use Motion's `layout` and `layoutId` props for visible state changes (re-ordering lists, expanding modals, shared elements between routes). Do not wrap static content in `layout` props "for safety" - it costs measurement work. +* **Staggered Orchestration:** Use `staggerChildren` (Motion) or CSS cascade (`animation-delay: calc(var(--index) * 100ms)`) for reveal moments where sequence matters. For `staggerChildren`, parent (`variants`) and children MUST share the same Client Component tree. + +--- + +## 6. PERFORMANCE & ACCESSIBILITY GUARDRAILS + +### 6.A Hardware Acceleration +* Animate ONLY `transform` and `opacity`. Never animate `top`, `left`, `width`, `height`. +* Use `will-change: transform` sparingly - only on elements that will actually animate. + +### 6.B Reduced Motion (mandatory) +* **Any motion above `MOTION_INTENSITY > 3` MUST honor `prefers-reduced-motion`.** This is non-negotiable. +* In Motion: wrap with `useReducedMotion()` and degrade to static. +* In CSS: gate animations behind `@media (prefers-reduced-motion: no-preference)` or provide an override block under `@media (prefers-reduced-motion: reduce)` that disables. +* Infinite loops, parallax, scroll-hijack, and magnetic physics MUST collapse to static / instant under reduced motion. + +### 6.C Dark Mode (mandatory for any consumer-facing page) +* Design for **both modes from the start**. Never ship light-only or dark-only without explicit user instruction. +* Use Tailwind `dark:` variant OR CSS variables for tokens. Pick one strategy per project. +* **Do not prescribe specific dark-mode colors here.** The brief decides. Maintain visual hierarchy, brand identity, and WCAG AA contrast (AAA for body) across both modes. +* Respect `prefers-color-scheme: dark`. Default to system preference unless the brand insists on one mode. + +### 6.D Core Web Vitals Targets +* **LCP** < 2.5s. Hero image must be `next/image priority` or preloaded. +* **INP** < 200ms. Heavy work off main thread. +* **CLS** < 0.1. Reserve space for images, fonts, embeds. +* Run Lighthouse before declaring a page done. + +### 6.E DOM Cost +* Apply grain / noise filters EXCLUSIVELY to fixed, `pointer-events-none` pseudo-elements (e.g., `fixed inset-0 z-[60] pointer-events-none`). NEVER on scrolling containers - continuous GPU repaints destroy mobile FPS. +* Be aware of bundle size. Motion is not tiny. Three.js is large. Lazy-load anything that's not above-the-fold. + +### 6.F Z-Index Restraint +NEVER spam arbitrary `z-50` or `z-10`. Use z-index strictly for systemic layer contexts (sticky navbars, modals, overlays, grain). Document the z-index scale in a project constants file. + +--- + +## 7. DIAL DEFINITIONS (Technical Reference) + +### DESIGN_VARIANCE (Level 1-10) +* **1-3 (Predictable):** Symmetrical CSS Grid (12-col, equal fr-units), equal paddings, centered alignment. +* **4-7 (Offset):** `margin-top: -2rem` overlaps, varied image aspect ratios (4:3 next to 16:9), left-aligned headers over center-aligned data. +* **8-10 (Asymmetric):** Masonry layouts, CSS Grid with fractional units (`grid-template-columns: 2fr 1fr 1fr`), massive empty zones (`padding-left: 20vw`). +* **MOBILE OVERRIDE:** For levels 4-10, asymmetric layouts above `md:` MUST collapse to strict single-column (`w-full`, `px-4`, `py-8`) on viewports `< 768px`. + +### MOTION_INTENSITY (Level 1-10) +* **1-3 (Static):** No automatic animations. CSS `:hover` and `:active` states only. `prefers-reduced-motion` is the default mode anyway. +* **4-7 (Fluid CSS):** `transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1)`. `animation-delay` cascades for load-ins. Focus on `transform` and `opacity`. +* **8-10 (Advanced Choreography):** Complex scroll-triggered reveals, parallax, scroll-driven animation (CSS `animation-timeline` or GSAP ScrollTrigger). Use Motion hooks. **NEVER use `window.addEventListener('scroll')`** - it is a hard ban, not a "prefer-not." See Section 5.D for the allowed alternatives. + +### VISUAL_DENSITY (Level 1-10) +* **1-3 (Art Gallery):** Lots of white space. Huge section gaps (`py-32` to `py-48`). Expensive, clean. +* **4-7 (Daily App):** Standard web app spacing (`py-16` to `py-24`). +* **8-10 (Cockpit):** Tight paddings. No card boxes; 1px lines separate data. Mandatory: `font-mono` for all numbers. + +--- + +## 8. DARK MODE PROTOCOL + +Dual-mode by default. Never assume light-only unless the brief is print-emulating editorial. + +### 8.A Token Strategy (pick one, stick to it) +* **Tailwind `dark:` variant** (default for utility-first projects): every color utility paired with its dark variant (`bg-white dark:bg-zinc-950`, `text-gray-900 dark:text-gray-100`). +* **CSS variables** (for shadcn/ui, Radix Themes, or component libraries with theming): define semantic tokens (`--surface`, `--surface-elevated`, `--text-primary`, `--accent`) and swap values under `[data-theme="dark"]` or `@media (prefers-color-scheme: dark)`. + +### 8.B Do Not Prescribe Specific Colors Here +The brief and brand decide. This skill enforces only: +* **Contrast** - WCAG AA minimum for body text, AAA target for hero copy. +* **Hierarchy parity** - visual hierarchy that works in light must work in dark. If a CTA pops in light, it pops in dark. +* **Brand fidelity** - primary brand color stays recognisable. Don't desaturate the brand into a dark mode. +* **No pure `#000000` and no pure `#ffffff`** - use off-black (zinc-950, near-black warm gray) and off-white. Pure values kill depth. + +### 8.C Default Mode +Respect `prefers-color-scheme` unless the brand insists. Add a manual toggle if either mode would lose key brand expression. + +### 8.D Test in Both Modes Before Finishing +Open the page in both modes during development. Do not ship a page you've only seen in one mode. + +--- + +## 9. AI TELLS (Forbidden Patterns) + +Avoid these signatures unless the brief explicitly asks for them. + +### 9.A Visual & CSS +* **NO neon / outer glows** by default. Use inner borders or subtle tinted shadows. +* **NO pure black (`#000000`).** Off-black, zinc-950, or charcoal. +* **NO oversaturated accents.** Desaturate to blend with neutrals. +* **NO excessive gradient text** for large headers. +* **NO custom mouse cursors.** Outdated, accessibility-hostile, perf-hostile. + +### 9.B Typography +* **AVOID Inter as default.** See Section 4.1. Override path exists. +* **NO oversized H1s** that just scream. Control hierarchy with weight + color, not raw scale. +* **Serif constraints:** Serif for editorial / luxury / publication. Not for dashboards. + +### 9.C Layout & Spacing +* **Mathematically perfect** padding and margins. No floating elements with awkward gaps. +* **NO 3-column equal feature cards.** The generic "three identical cards horizontally" feature row is banned. Use 2-column zig-zag, asymmetric grid, scroll-pinned, or horizontal-scroll alternative. + +### 9.D Content & Data ("Jane Doe" Effect) +* **NO generic names.** "John Doe", "Sarah Chan", "Jack Su" → use creative, realistic, locale-appropriate names. +* **NO generic avatars.** No SVG "egg" or Lucide user icons → use believable photo placeholders or specific styling. +* **NO fake-perfect numbers.** Avoid `99.99%`, `50%`, `1234567`. Use organic, messy data (`47.2%`, `+1 (312) 847-1928`). +* **NO startup-slop brand names.** "Acme", "Nexus", "SmartFlow", "Cloudly" → invent contextual, premium names that sound real. +* **NO filler verbs.** "Elevate", "Seamless", "Unleash", "Next-Gen", "Revolutionize" → concrete verbs only. + +### 9.E External Resources & Components +* **NO hand-rolled SVG icons.** Use Phosphor / HugeIcons / Radix / Tabler. Lucide on explicit request only. +* **Hand-rolled decorative SVGs strongly discouraged** as default (see Section 4.8). +* **NO div-based fake screenshots.** Never build a fake product UI out of `
    ` rectangles to simulate a screenshot. Use real images, generated images, or skip the preview. +* **NO broken Unsplash links.** Use `https://picsum.photos/seed/{descriptive-string}/{w}/{h}`, or generated photo placeholders, or actual assets. +* **shadcn/ui customization:** Allowed, but NEVER in default state. Customize radii, colors, shadows, typography to the project aesthetic. +* **Production-Ready Cleanliness:** Code visually clean, memorable, meticulously refined. + +### 9.F Production-Test Tells (banned outright) + +These patterns came out of real LLM-generated landing-page tests. They are the signatures the model defaults to when it tries to "look designed." Treat them as hard bans unless the brief explicitly calls for one. + +**Hero & top-of-page** +* **NO version labels in the hero.** `V0.6`, `v2.0`, `BETA`, `INVITE-ONLY PREVIEW`, `EARLY ACCESS`, `ALPHA` - banned as default eyebrows. Only acceptable when the brief is explicitly about a product launch / preview status. +* **NO "Brand · No. 01"-style sub-eyebrows.** "Marrow · No. 01 · The 6-quart" type micro-meta lines. Skip them. + +**Section numbering & micro-labels** +* **NO section-number eyebrows.** `00 / INDEX`, `001 · Capabilities`, `002 · Featured commission`, `06 · how it works`, `05 · The honest table` - banned. Eyebrows should name the topic in plain language, not enumerate. +* **NO `01 / 4`-style pagination on images or bento tiles.** If the user can count, they don't need the label. +* **NO `Scroll · 001 Capabilities`-style scroll cues.** A simple arrow or "Scroll" is enough; no section-number prefix. +* **NO "Index of Work, 2018 - 2026"-style range labels** as eyebrows. Just say what the section is. + +**Separators & dots** +* **The middle-dot (`·`) is rationed.** Maximum 1 per line in metadata strips. Do NOT use it as the default separator for everything ("foo · bar · baz · qux · quux"). If you need a separator family, prefer line breaks, hairlines, or columns. +* **NO decorative colored status dots on every list/nav/badge.** A colored dot before "ONE Q4 SLOT OPEN" or before every nav link, or every task row - banned by default. Acceptable only when the dot conveys actual semantic state (a server status, an availability flag) and is used sparingly. + +**Em-dashes & typography flourishes** +* **NO em-dash (`—`) as a design element OR anywhere else.** See Section 9.G below for the complete, non-negotiable ban. The em-dash character is forbidden in headlines, eyebrows, pills, body copy, quotes, attribution, captions, button text, and alt text. Use the regular hyphen (`-`). +* **NO `
    `-broken-and-italicized headlines** as a default "design move." "for thirty\*years.*" type splits. Headlines should read naturally first, get clever only when the brief demands it. +* **NO vertical rotated text** ("INDEX OF WORK, 2018 - 2026" rotated 90°). Agency-portfolio cliché. Use it only when the brief is explicitly agency / Awwwards / experimental AND it serves a real composition purpose. +* **NO crosshair / hairline grid lines as decoration.** Vertical and horizontal lines drawn just to make the page "feel designed" - banned. Use them only when they organize real content. + +**Fake product previews** +* **NO div-based fake product UI in the hero** (fake task list, fake terminal, fake dashboard built from styled divs). It is the #1 LLM-design Tell. Use a real screenshot, a generated image, a real component preview, or none at all. +* **NO fake version footers** ("v0.6.2-rc.1", "last sync 4s ago · main") inside fake screenshots. Adds nothing, screams AI. + +**Marketing-copy Tells** +* **NO "Quietly in use at" / "Quietly trusted by"** social-proof headers. Use natural language: "Trusted by", "Used at", "Customers include", or skip the heading entirely if the logos speak. +* **NO "From the field" / "Field notes" / "Currently on the bench" / "On our desks" / "Loose plates" style poetic labels** on quote, blog, or sidebar sections. Reads as performative-craftsman. Use plain functional labels ("Testimonials", "Latest writing", "Now working on") or skip the label. +* **NO "We respect the French ones"-style** mock-humble industry-references in body copy. Cute and AI-y. +* **NO weather / locale strips** ("LIS 14:23 · 18°C") in headers/footers unless the brief is explicitly about a place / time-zone-distributed studio. +* **NO micro-meta-sentences under eyebrows.** Sentences like *"Each of these is a feature we ship today, not a roadmap promise. The list will stay short on purpose."* sitting under a section heading are clutter. Eyebrow + Headline + Body is enough. +* **NO generic step labels.** "Stage 1 / Stage 2 / Stage 3", "Step 1 / Step 2 / Step 3", "Phase 01 / Phase 02 / Phase 03", "Pass One / Pass Two / Pass Three". Banned. The actual step content is the label. If you must show progression, use the verb-noun directly ("Install", "Configure", "Ship") not "Stage 1: Install". + +**Pills, labels and version stamps** +* **NO pills/labels/tags overlaid on images.** No `` overlays on photos with tags like `Brand · 02`, `PLATE · BRAND`, `Field notes - journal`. Either let the image speak alone, or add a caption directly below (outside the image). +* **NO photo-credit captions as decoration.** Strings like `Field study no. 12 · Ines Caetano`, `Plate 03 · House archive`, `Frame XII · 35mm` under stock/picsum images are pretentious. Photo credit is allowed ONLY when there is a real photographer being credited for a real photo (with permission). Otherwise: skip the caption or use a one-line functional caption ("The 6-quart, in Sage."). +* **NO version footers on marketing pages.** Footer strings like `v1.4.2`, `Build 0048`, `last sync 4s ago · main` are CLI / devtool fixtures, not landing-page content. Banned on marketing/landing/portfolio pages. +* **NO "Reservation 412 of 800"-style live-stock counters** as decoration. Only if the brief is explicitly a limited-run waitlist with real data. + +**Decoration text strips** +* **NO decoration text strip at hero bottom.** Patterns like `BRAND. MOTION. SPATIAL.`, `TYPE / FORM / MOTION`, `DESIGN · BUILD · SHIP`, `ESTD. 2018 · LISBON · BRAND. MOTION. SPATIAL.` as a small mono-caps strip across the bottom of the hero are an agency-portfolio cliché. Banned by default. Only acceptable when the strip carries real, navigable links (sticky bottom nav) or real status info (cookie banner, build info on a docs site). +* **NO floating top-right sub-text in section headings.** Pattern: section has a giant left-aligned headline; in the top-right corner of the same section header there is a small explainer paragraph floating with no clear alignment to anything else. That floater is the Tell. Either put the sub-text directly under the headline, or build a clean 2-column header (left: headline, right: aligned body), but not a tiny corner paragraph. + +**Lists, dividers and scoring** +* **NO `border-t` + `border-b` on every row of a long list / spec table.** Pick one (bottom-border between rows OR top-border above the group) and use it sparsely. A 10-row spec table with hairlines under each row is the laziest layout - see Section 4.9 for alternative UI components. +* **NO scoring/progress bars with filled background tracks** as comparison visuals. If you need to show "X out of Y" comparisons, prefer a number + small icon, or a tiny inline bar WITHOUT a background track. Big filled `bg-zinc-200` tracks with a partial fill on top are dashboard-UI clutter on a landing page. + +**Locale, time, scroll cues** +* **Locale / city-name / time / weather strips are banned for 99% of briefs.** "Lisbon, working with founders" in the hero, "1200-690 Lisbon, Portugal" in the footer, "Lisbon 14:23 · 18°C" in the nav. These are agency-portfolio decoration tells. Allowed ONLY when: the brief explicitly describes a globally-distributed studio with timezone-relevant work, OR a travel-focused brand, OR a real-world physical venue. A single contact-address mention in the footer is fine; an atmospheric locale strip is not. +* **Scroll cues are banned.** `Scroll`, `↓ scroll`, `Scroll to explore`, `Scroll to walk through it`, animated mouse-wheel icons. If the user has not scrolled yet, they are looking at the hero. They know what scroll is. The bottom of the viewport does not need a label. +* **ZERO decorative status dots by default.** A coloured dot before nav items, before list rows, before badges, before status labels is a Tell. Only acceptable when conveying real semantic state (a live indicator on actual server status, a live availability flag) and limited to one per page section. + +### 9.G EM-DASH BAN (the single most-violated Tell) + +**Em-dash (`—`) is COMPLETELY banned.** It is the LLM's signature stylistic crutch and it is the #1 visual Tell in production tests. There is no "limited use" allowance, no "natural language frequency" allowance, no "in body copy is fine" allowance. None. + +* **Banned in headlines.** Use a period or a comma. +* **Banned in eyebrows / labels / pills / button text / image captions / nav items.** Replace with line breaks, columns, or hairlines. +* **Banned in body copy.** Restructure the sentence: two sentences with a period, OR a comma, OR parentheses, OR a colon. +* **Banned in quote attribution.** Use a normal hyphen with spaces (` - `) or a line break + smaller-weight name. +* **Banned in en-dash form too (`–`) when used as a separator.** Date ranges (`2018-2026`) use a hyphen. Number ranges (`€40-80k`) use a hyphen. + +The ONLY permitted dash characters on the page are: +* Regular hyphen `-` (for compound words, ranges, line dividers in markup) +* Minus sign in math (`-5°C`) + +If your output contains a single `—` or `–` anywhere visible to the user, the output fails the Pre-Flight Check and must be rewritten. + +This rule is non-negotiable. The agent has historically ignored em-dash limits when phrased as "use sparingly." The phrasing here is binary: zero em-dashes. + +--- + +## 10. REFERENCE VOCABULARY (Pattern Names the Agent Should Know) + +This is a vocabulary, not a library. The agent should KNOW these pattern names to communicate about them, design with them in mind, and reach for them when the design read calls for them. **Implementations and code sketches live in the Block Library (Section 12), which is populated iteratively.** + +### Hero Paradigms +* **Asymmetric Split Hero** - Text on one side, asset on the other, generous white space. +* **Editorial Manifesto Hero** - Large type, no asset, almost-poster. +* **Video / Media Mask Hero** - Type cut out as mask over video background. +* **Kinetic-Type Hero** - Animated typography as the primary visual. +* **Curtain-Reveal Hero** - Hero parts on scroll like a curtain. +* **Scroll-Pinned Hero** - Hero stays pinned while content scrolls behind. + +### Navigation & Menus +* **Mac OS Dock Magnification** - Edge nav, icons scale fluidly on hover. +* **Magnetic Button** - Pulls toward cursor. +* **Gooey Menu** - Sub-items detach like viscous liquid. +* **Dynamic Island** - Morphing pill for status / alerts. +* **Contextual Radial Menu** - Circular menu expanding at click point. +* **Floating Speed Dial** - FAB springing into curved secondary actions. +* **Mega Menu Reveal** - Full-screen dropdown, stagger-fade content. + +### Layout & Grids +* **Bento Grid** - Asymmetric tile grouping (Apple Control Center). +* **Masonry Layout** - Staggered grid, no fixed row height. +* **Chroma Grid** - Borders / tiles with subtle animating gradients. +* **Split-Screen Scroll** - Two halves sliding in opposite directions. +* **Sticky-Stack Sections** - Sections that pin and stack on scroll. + +### Cards & Containers +* **Parallax Tilt Card** - 3D tilt tracking mouse coordinates. +* **Spotlight Border Card** - Borders illuminate under cursor. +* **Glassmorphism Panel** - Frosted glass with inner refraction. +* **Holographic Foil Card** - Iridescent rainbow shift on hover. +* **Tinder Swipe Stack** - Physical card stack, swipe-away. +* **Morphing Modal** - Button expands into its own dialog. + +### Scroll Animations +* **Sticky Scroll Stack** - Cards stick and physically stack. +* **Horizontal Scroll Hijack** - Vertical scroll → horizontal pan. +* **Locomotive / Sequence Scroll** - Video / 3D sequence tied to scrollbar. +* **Zoom Parallax** - Central background image zooming on scroll. +* **Scroll Progress Path** - SVG line drawing along scroll. +* **Liquid Swipe Transition** - Page transition like viscous liquid. + +### Galleries & Media +* **Dome Gallery** - 3D panoramic gallery. +* **Coverflow Carousel** - 3D carousel with angled edges. +* **Drag-to-Pan Grid** - Boundless draggable canvas. +* **Accordion Image Slider** - Narrow strips expanding on hover. +* **Hover Image Trail** - Mouse leaves popping image trail. +* **Glitch Effect Image** - RGB-channel shift on hover. + +### Typography & Text +* **Kinetic Marquee** - Endless text bands reversing on scroll. +* **Text Mask Reveal** - Massive type as transparent window to video. +* **Text Scramble Effect** - Matrix-style decoding on load / hover. +* **Circular Text Path** - Text curving along spinning circle. +* **Gradient Stroke Animation** - Outlined text with running gradient. +* **Kinetic Typography Grid** - Letters dodging the cursor. + +### Micro-Interactions & Effects +* **Particle Explosion Button** - CTA shatters into particles on success. +* **Liquid Pull-to-Refresh** - Reload indicator like detaching droplets. +* **Skeleton Shimmer** - Shifting light reflection across placeholders. +* **Directional Hover-Aware Button** - Fill enters from cursor's exact side. +* **Ripple Click Effect** - Wave from click coordinates. +* **Animated SVG Line Drawing** - Vectors drawing themselves in real time. +* **Mesh Gradient Background** - Organic lava-lamp blobs. +* **Lens Blur Depth** - Background UI blurred to focus foreground action. + +### Animation Library Choice +* **Motion (`motion/react`)** - default for UI / Bento / state-change motion. +* **GSAP + ScrollTrigger** - for full-page scrolltelling and scroll hijacks. Isolate in dedicated leaf components with `useEffect` cleanup. +* **Three.js / WebGL** - for canvas backgrounds and 3D scenes. Same isolation rule. +* **NEVER mix GSAP / Three.js with Motion in the same component tree.** They fight over the same frames. + +--- + +## 11. REDESIGN PROTOCOL + +This skill handles **greenfield builds AND redesigns**. Misclassifying the mode is the single biggest source of bad redesign output. + +### 11.A Detect the Mode (first action) +* **Greenfield** - no existing site, or full overhaul approved. Dial baseline from Section 1. +* **Redesign - Preserve** - modernise without breaking the brand. Audit first, extract brand tokens, evolve gradually. +* **Redesign - Overhaul** - new visual language on top of existing content. Treat as greenfield for visuals; preserve content and IA. + +If ambiguous, ask **once**: *"Should this redesign preserve the existing brand, or are we starting visually from scratch?"* + +### 11.B Audit Before Touching +Document the current state before proposing changes: +* **Brand tokens** - primary / accent colors, type stack, logo treatment, radii. +* **Information architecture** - page tree, primary nav, key conversion paths. +* **Content blocks** - what exists, what's doing work, what's filler. +* **Patterns to preserve** - signature interactions, recognisable hero, copy voice. +* **Patterns to retire** - AI-slop tells, broken layouts, dead links, generic stock imagery, perf traps. +* **Dial reading of the existing site** - infer current `DESIGN_VARIANCE` / `MOTION_INTENSITY` / `VISUAL_DENSITY`. That's your starting point, not the baseline. +* **SEO baseline** - current ranking pages, meta titles, structured data, OG cards. **SEO migration is the #1 redesign risk.** + +### 11.C Preservation Rules +* **Do not change information architecture** unless asked. Keep page slugs, anchor IDs, primary nav labels stable for SEO and muscle memory. +* **Extract brand colors before applying Section 4.2.** A brand that is already purple stays purple - apply the LILA RULE's override. +* **Preserve copy voice** unless asked for a rewrite. Visual modernisation ≠ content rewrite. +* **Honor existing accessibility wins.** Do not regress focus states, alt text, keyboard nav, contrast. +* **Respect existing analytics events.** Do not rename buttons, form fields, section IDs that downstream tracking depends on. + +### 11.D Modernisation Levers (priority order) +Apply in order - stop when the brief is satisfied: +1. **Typography refresh** - biggest visual lift per unit of risk. +2. **Spacing & rhythm** - increase section padding, fix vertical rhythm. +3. **Color recalibration** - desaturate, unify neutrals, keep brand accent. +4. **Motion layer** - add `MOTION_INTENSITY`-appropriate micro-interactions to existing components. +5. **Hero & key-section recomposition** - restructure top-of-funnel using Section 10 vocabulary. +6. **Full block replacement** - only when the existing block is unsalvageable. + +### 11.E Decision Tree: Targeted Evolution vs Full Redesign +* IA, content, and SEO sound → **targeted evolution** (Levers 1-4). ~70% of value at ~40% of risk. +* Visual debt is structural (broken IA, no design system, broken mobile) → **full redesign** with strict content preservation. +* Brand itself is changing → **greenfield**. + +### 11.F What Never Changes Silently +Never modify without explicit user approval: +* URL structure / route slugs. +* Primary nav labels. +* Form field names or order (breaks analytics + autofill). +* Brand logo or wordmark. +* Existing legal / consent / cookie copy. + +--- + +## 12. THE BLOCK LIBRARY (Contract - Implementations Land Here Iteratively) + +The Reference Vocabulary (Section 10) names patterns. The Block Library implements them with real props, real motion specs, and real code sketches. + +**Status:** schema defined here. Blocks will be added iteratively. Do not freelance new blocks without following this schema. + +### 12.A File Location +``` +skills/taste-skill/blocks/ + hero/ + asymmetric-split.md + editorial-manifesto.md + kinetic-type.md + ... + feature/ + bento-grid.md + sticky-scroll-stack.md + zig-zag.md + ... + social-proof/ + pricing/ + cta/ + footer/ + navigation/ + portfolio/ + transition/ +``` + +### 12.B Required Frontmatter +```yaml +--- +name: asymmetric-split-hero +category: hero +dial_compatibility: + variance: [6, 10] + motion: [3, 10] + density: [2, 5] +when_to_use: "Landing pages with one strong asset and one strong message. Default hero for SaaS, agency, premium consumer." +not_for: "Editorial / manifesto launches where the message IS the design." +stack: ["react", "next", "tailwind", "motion"] +--- +``` + +### 12.C Required Body Sections +1. **Visual sketch** - short ASCII or description of the layout. +2. **Props API** - the component's interface. +3. **Code sketch** - minimal working implementation (Server Component default, Client island for motion). +4. **Mobile fallback** - explicit collapse rules for `< 768px`. +5. **Motion variants** - one variant per `MOTION_INTENSITY` band (1-3, 4-7, 8-10). Reduced-motion fallback explicit. +6. **Dark-mode notes** - token strategy specific to this block. +7. **Anti-patterns** - common ways this block goes wrong. +8. **References** - links to real examples in production. + +### 12.D Block-Library Discipline +* One block per file. No multi-block files. +* Every block must work standalone (drop it into a page, it renders). +* Every block must pass the Pre-Flight Check (Section 14). +* Blocks that depend on a design system from Section 2.A live under `blocks//--.md` (e.g. `feature/bento-grid--material.md`). + +--- + +## 13. OUT OF SCOPE + +This skill is NOT for: +* Dashboards / dense product UI / admin panels (use Fluent, Carbon, Atlassian, or Polaris from Section 2.A). +* Data tables (use TanStack Table or AG Grid). +* Multi-step forms / wizards (use Form-specific patterns; this skill won't make them better). +* Code editors (use Monaco / CodeMirror with their official skinning). +* Native mobile (use Apple HIG / Material directly). +* Realtime collab UIs (presence, cursors, OT-aware - different problem class). + +If the brief is one of the above, **say so explicitly**, point to the right tool, and only apply this skill's marketing-page / about-page / landing-page parts to the surfaces where they apply. + +--- + +## 14. FINAL PRE-FLIGHT CHECK + +Run this matrix before outputting code. This is the last filter. + +**THIS IS NOT OPTIONAL. Run every box. If any box fails, the output is not done.** + +- [ ] **Brief inference** declared (Section 0.B one-liner)? +- [ ] **Dial values** explicit and reasoned from the brief, not silently using baseline? +- [ ] **Design system** chosen from Section 2 if applicable, or aesthetic labeled honestly? +- [ ] **Redesign mode** detected and audit performed (if applicable, Section 11)? +- [ ] **ZERO em-dashes (`—`) anywhere on the page.** Headlines, eyebrows, pills, body, quotes, attribution, captions, buttons, alt text. Zero. (Section 9.G - non-negotiable.) +- [ ] **Page Theme Lock**: ONE theme (light, dark, or auto) for the whole page. No section flips to inverted mode mid-page (Section 4.11)? +- [ ] **Color Consistency Lock**: one accent color used identically across all sections (Section 4.2)? +- [ ] **Shape Consistency Lock**: one corner-radius system applied consistently (Section 4.4)? +- [ ] **Button Contrast Check**: every CTA text is readable against its background (no white-on-white, WCAG AA 4.5:1)? +- [ ] **CTA Button Wrap**: no CTA label wraps to 2+ lines at desktop? +- [ ] **Form Contrast Check**: form inputs, placeholders, focus rings, labels all pass WCAG AA against the section background? +- [ ] **Serif discipline**: if a serif is used, it is NOT Fraunces or Instrument_Serif (or it is, with explicit brand justification)? Different serif from your previous project? +- [ ] **Premium-consumer palette check**: if the brief is premium-consumer (cookware / wellness / artisan / luxury), the palette is NOT the AI-default beige+brass+oxblood+espresso family? Different family from your previous premium-consumer project? +- [ ] **Italic descender clearance**: every italic word with `y g j p q` has `leading-[1.1]` min + `pb-1` reserve? +- [ ] **Hero fits the viewport**: headline ≤ 2 lines, subtext ≤ 20 words AND ≤ 4 lines, CTA visible without scroll, font scale planned around image? +- [ ] **Hero top padding**: max `pt-24` at desktop, hero content does not float halfway down the viewport? +- [ ] **Hero stack discipline**: max 4 text elements in hero (eyebrow OR brand strip, headline, subtext, CTAs)? No tiny tagline below CTAs, no trust micro-strip in hero? +- [ ] **EYEBROW COUNT (mechanical)**: count instances of `uppercase tracking` micro-labels above section headlines across all components. Count ≤ ceil(sectionCount / 3)? Hero counts as 1. +- [ ] **Split-Header Ban**: no "left big headline + right small explainer paragraph" pattern as a section header (vertical stack instead)? +- [ ] **Zigzag Alternation Cap**: no 3+ consecutive sections with the same image+text-split layout? +- [ ] **No Duplicate CTA Intent**: no two CTAs with the same intent ("Get in touch" + "Let's talk" both on page = Fail)? +- [ ] **Logo wall = logo only**: no industry / category labels printed below logos? +- [ ] **Bento Background Diversity**: at least 2-3 bento cells have real visual variation (image, gradient, pattern), not all white-on-white text cards? +- [ ] **"Used by / Trusted by" logo wall** lives UNDER the hero, not inside it, uses REAL SVG logos (Simple Icons / devicon) or generated SVG marks, NOT plain text wordmarks? +- [ ] **Copy Self-Audit**: every visible string re-read, no grammatically-broken or AI-hallucinated phrases ("free on its past" type) shipped? +- [ ] **Motion motivated**: every animation can be justified in one sentence (hierarchy / storytelling / feedback / state transition), no GSAP-for-show? +- [ ] **Marquee max-one-per-page**: no two horizontal marquees on the same page? +- [ ] **Navigation on ONE line** at desktop, height ≤ 80px? +- [ ] **Section-Layout-Repetition** check: no two sections share the same layout family (at least 4 different families across 8 sections)? +- [ ] **Bento has rhythm AND exact cell count** (N items → N cells, no empty cells in middle or at end)? +- [ ] **Long lists use the right UI component** (not default `
      ` with `divide-y` for > 5 items - see Section 4.9 alternatives)? +- [ ] **Real images used** (gen-tool first, then Picsum-seed, then explicit placeholder slots) - NO div-based fake screenshots, NO hand-rolled decorative SVGs, NO pure-text minimalism? +- [ ] **No pills/labels overlaid on images** (no `Plate · Brand`, no `Field notes - journal`)? +- [ ] **No photo-credit captions as decoration** (`Field study no. 12 · Ines Caetano`)? +- [ ] **No version footers** (`v1.4.2`, `Build 0048`) on marketing pages? +- [ ] **No micro-meta-sentences** under eyebrows ("Each of these is a feature we ship today...")? +- [ ] **No decoration text strip at hero bottom** (`BRAND. MOTION. SPATIAL.`)? +- [ ] **No floating top-right sub-text** in section headings? +- [ ] **No scoring/progress bars with filled background tracks** as comparison visuals? +- [ ] **No locale / city-name / time / weather strips** unless brief is genuinely globally-distributed or place-focused? +- [ ] **No scroll cues** (`Scroll`, `↓ scroll`, `Scroll to explore`)? +- [ ] **No version labels in hero** (V0.6, BETA, INVITE-ONLY) unless the brief is a launch? +- [ ] **No section-numbering eyebrows** (`00 / INDEX`, `001 · Capabilities`, `06 · how it works`)? +- [ ] **No decorative dots** (zero by default, only for real semantic state)? +- [ ] **No `border-t` + `border-b` on every row** of long lists / spec tables? +- [ ] **Content density** sane: no 20-row data tables, no fake-precise specs without justification, ≤ 25-word sub-paragraphs by default? +- [ ] **Quotes ≤ 3 lines** of body, attribution clean (no em-dash)? +- [ ] **Motion claimed = motion shown**: if `MOTION_INTENSITY > 4`, page actually animates, not just claimed? +- [ ] **GSAP sticky-stack / horizontal-pan** implemented per Section 5.A / 5.B canonical skeleton (`start: "top top"`, `pin: true`, correct scrub)? +- [ ] **No `window.addEventListener('scroll')`** - using Motion `useScroll()` / ScrollTrigger / IntersectionObserver / CSS scroll-driven animations only? +- [ ] **Reduced motion** wrapped for everything `MOTION_INTENSITY > 3`? +- [ ] **Dark mode** tokens defined and tested in both modes? +- [ ] **Mobile collapse** explicit (`w-full`, `px-4`, `max-w-7xl mx-auto`) for high-variance layouts? +- [ ] **Viewport stability**: `min-h-[100dvh]`, never `h-screen`? +- [ ] **`useEffect` animations** have strict cleanup functions? +- [ ] **Empty / loading / error** states provided? +- [ ] **Cards omitted** in favor of spacing where possible? +- [ ] **Icons** from an allowed library only (Phosphor / HugeIcons / Radix / Tabler), no hand-rolled SVG paths? +- [ ] **Motion** isolated in client-leaf components with `'use client'` at the top, memoized? +- [ ] **No AI Tells** from Section 9 (Inter as default, AI-purple, three-equal cards, Jane Doe, Acme, "Quietly in use at")? +- [ ] **Core Web Vitals** plausibly hit (LCP < 2.5s, INP < 200ms, CLS < 0.1)? +- [ ] **One design system** per project (no Material + shadcn mixed)? + +If a single checkbox cannot be honestly ticked, the page is not done. Fix it before delivering. + +--- + +# APPENDICES - Real Source-Backed Reference Material + +The sections below are vendored reference content. They give the agent real install commands, real canonical doc links, and real working starter snippets for each design system named in Section 2. Use them to ground decisions in production reality, not training-data fiction. + +## Appendix A - Install Commands per Design System + +```bash +# Material Web (Material 3) +npm install @material/web + +# Fluent UI React (v9) +npm install @fluentui/react-components + +# Fluent UI Web Components (framework-free) +npm install @fluentui/web-components @fluentui/tokens + +# IBM Carbon +npm install @carbon/react @carbon/styles + +# Radix Themes +npm install @radix-ui/themes + +# shadcn/ui (open code, owned components) +npx shadcn@latest init +npx shadcn@latest add button card badge separator input + +# Primer CSS (GitHub product/devtool UI) +npm install --save @primer/css + +# Primer Brand (GitHub marketing UI) +npm install @primer/react-brand + +# GOV.UK Frontend +npm install govuk-frontend + +# USWDS (US Web Design System) +npm install uswds + +# Atlassian Design System (Atlaskit) +yarn add @atlaskit/css-reset @atlaskit/tokens @atlaskit/button @atlaskit/badge @atlaskit/section-message @atlaskit/card + +# Bootstrap 5.3 +npm install bootstrap + +# Shopify Polaris Web Components (Shopify apps only) +# Add this to your app HTML head: +# +# +``` + +## Appendix B - Canonical Sources (read these before reinventing) + +### Material Web +- https://github.com/material-components/material-web +- https://material-web.dev/theming/material-theming/ +- https://m3.material.io/develop/web + +### Fluent UI +- https://fluent2.microsoft.design/get-started/develop +- https://fluent2.microsoft.design/components/web/react/ +- https://github.com/microsoft/fluentui +- https://learn.microsoft.com/en-us/fluent-ui/web-components/ + +### Carbon +- https://carbondesignsystem.com/ +- https://github.com/carbon-design-system/carbon +- https://carbondesignsystem.com/developing/react-tutorial/overview/ +- https://carbondesignsystem.com/developing/web-components-tutorial/overview/ + +### Shopify Polaris +- https://shopify.dev/docs/api/app-home/web-components +- https://github.com/Shopify/polaris-react +- https://polaris-react.shopify.com/components + +### Atlassian +- https://atlassian.design/get-started/develop +- https://atlassian.design/components/button/examples +- https://atlaskit.atlassian.com/packages/design-system/button/example/disabled +- https://atlassian.design/tokens/design-tokens + +### Primer +- https://primer.style/ +- https://github.com/primer/css +- https://github.com/primer/brand + +### GOV.UK +- https://design-system.service.gov.uk/components/button/ +- https://design-system.service.gov.uk/styles/layout/ +- https://github.com/alphagov/govuk-frontend + +### USWDS +- https://designsystem.digital.gov/documentation/developers/ +- https://designsystem.digital.gov/components/button/ +- https://designsystem.digital.gov/components/card/ +- https://github.com/uswds/uswds + +### Bootstrap +- https://getbootstrap.com/docs/5.3/layout/grid/ +- https://getbootstrap.com/docs/5.3/components/card/ + +### Tailwind +- https://tailwindcss.com/docs/dark-mode +- https://tailwindcss.com/blog/tailwindcss-v4 + +### Radix +- https://www.radix-ui.com/themes/docs/components/theme +- https://www.radix-ui.com/themes/docs/components/card +- https://github.com/radix-ui/themes + +### shadcn/ui +- https://ui.shadcn.com/docs +- https://ui.shadcn.com/docs/components/card +- https://github.com/shadcn-ui/ui + +### Native CSS / W3C standards +- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/backdrop-filter +- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-color-scheme +- https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-reduced-motion +- https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Grid_layout +- https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Scroll-driven_animations +- https://drafts.csswg.org/scroll-animations-1/ + +### Apple Liquid Glass (Apple platforms only) +- https://developer.apple.com/design/human-interface-guidelines/materials +- https://developer.apple.com/documentation/TechnologyOverviews/liquid-glass +- https://developer.apple.com/documentation/TechnologyOverviews/adopting-liquid-glass +- https://developer.apple.com/documentation/SwiftUI/Material + +--- + +## Appendix C - Apple Liquid Glass: Honest Web Approximation + +Do **not** treat random CSS snippets as official Apple Liquid Glass. + +### What is official +Apple documents Liquid Glass inside Apple's Human Interface Guidelines and Developer Documentation for **Apple platforms**. It is a dynamic material used across Apple platform UI. Apple's native implementation belongs to Apple platform APIs and system components, **not a public web CSS package**. + +Relevant official docs: +- Apple Human Interface Guidelines → Materials +- Apple Developer Documentation → Liquid Glass +- Apple Developer Documentation → Adopting Liquid Glass +- SwiftUI → Material + +### What is NOT official +There is no `liquid-glass.css` from Apple for normal websites. + +A web approximation can use: +- `backdrop-filter` +- transparent backgrounds +- layered borders +- highlight overlays +- gradients +- motion +- strong contrast fallbacks + +But that is **web glassmorphism / frosted-glass approximation**, not official Apple Liquid Glass. Label it as such in comments. + +### Safer web approximation skeleton + +```css +.liquid-glass-web-approx { + position: relative; + isolation: isolate; + overflow: hidden; + border-radius: 999px; + border: 1px solid rgb(255 255 255 / .32); + background: + linear-gradient(135deg, rgb(255 255 255 / .30), rgb(255 255 255 / .08)), + rgb(255 255 255 / .12); + backdrop-filter: blur(24px) saturate(180%) contrast(1.05); + -webkit-backdrop-filter: blur(24px) saturate(180%) contrast(1.05); + box-shadow: + inset 0 1px 0 rgb(255 255 255 / .48), + inset 0 -1px 0 rgb(255 255 255 / .12), + 0 18px 60px rgb(0 0 0 / .18); +} + +.liquid-glass-web-approx::before { + content: ""; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + background: + radial-gradient(circle at 20% 0%, rgb(255 255 255 / .55), transparent 34%), + linear-gradient(90deg, rgb(255 255 255 / .18), transparent 42%, rgb(255 255 255 / .14)); + pointer-events: none; +} + +.liquid-glass-web-approx::after { + content: ""; + position: absolute; + inset: 1px; + border-radius: inherit; + border: 1px solid rgb(255 255 255 / .14); + pointer-events: none; +} + +@media (prefers-color-scheme: dark) { + .liquid-glass-web-approx { + border-color: rgb(255 255 255 / .18); + background: + linear-gradient(135deg, rgb(255 255 255 / .16), rgb(255 255 255 / .04)), + rgb(15 23 42 / .42); + box-shadow: + inset 0 1px 0 rgb(255 255 255 / .22), + 0 18px 60px rgb(0 0 0 / .42); + } +} + +@media (prefers-reduced-transparency: reduce) { + .liquid-glass-web-approx { + background: rgb(255 255 255 / .96); + backdrop-filter: none; + -webkit-backdrop-filter: none; + } +} +``` + +**Important:** `prefers-reduced-transparency` has uneven browser support; test it. Always provide enough contrast even without blur. + +--- + +**End of appendices.** Install commands above are reality anchors. The Apple Liquid Glass skeleton is a labeled approximation, not an Apple-issued package. For canonical docs per design system, consult the system's official docs (links in Section 2 plus Appendix B). diff --git a/skills/dev-router/SKILL.md b/skills/dev-router/SKILL.md new file mode 100644 index 0000000..24d3faa --- /dev/null +++ b/skills/dev-router/SKILL.md @@ -0,0 +1,73 @@ +--- +name: dev-router +description: Use no início de qualquer pedido de código (feature, bug, refactor, UI, API, migração, review; "implement", "fix", "build", "add", "change"). Classifica o pedido em nível 0 a 3 e decide quais workflows, agentes e checagens rodar, para um pedido pequeno não pagar o custo de um grande. +license: MIT +metadata: + dev-workflows: + uses: [lean-code, wf-bugfix, wf-refactor, wf-frontend, wf-backend, wf-architecture, wf-security-review, safedeps] + external: [] +--- + +# Dev Router + +A primeira linha da resposta declara o nível: `Nível N: `. + +## 1. Classificar + +| Nível | Quando | Exemplos | +|---|---|---| +| 0, trivial | nenhum comportamento muda; 1 arquivo | texto, cor, typo, renomear variável local | +| 1, pequeno | comportamento muda em 1 a 3 arquivos, sem superfície pública nova | bug localizado, ajuste de validação, refactor local | +| 2, feature | superfície nova ou contrato alterado; 4+ arquivos; dependência nova | endpoint, tela, módulo, integração | +| 3, grande ou de risco | vários módulos ou serviços, dados existentes, arquitetura, release | migração com dados, troca de auth, novo serviço | + +Na dúvida entre dois níveis, escolha o menor e suba quando aparecer um gatilho. + +## 2. Gatilhos que sobem o nível a qualquer momento + +| Gatilho | Mínimo | Soma | +|---|---|---| +| autenticação, autorização, sessão, tokens, criptografia | 2 | `security-auditor` | +| dinheiro, cobrança, dados pessoais (LGPD) | 2 | `security-auditor` | +| upload, SQL montado à mão, shell/exec, desserialização, template com entrada do usuário | 2 | `security-auditor` | +| dependência nova | 1 | `safedeps` antes de instalar | +| migração de schema | 2 (3 se mexe em dado existente) | rollback testado | +| feature que chama um LLM | 2 | OWASP LLM Top 10 no `security-auditor` | + +Depois que um gatilho disparou, não rebaixe por conta própria. + +O usuário pode forçar: "modo rápido" vira nível 0 ou 1, mas gatilho de segurança continua valendo (avise); "modo completo" vira nível 3. + +## 3. O que cada nível roda + +| Nível | Fluxo | Workflow | Agentes | +|---|---|---|---| +| 0 | fazer, rodar o gate | nenhum | nenhum | +| 1 | entender ou reproduzir, mudar, teste de regressão, gate | `wf-bugfix` ou `wf-refactor` | `explorer` só se não souber onde está o código | +| 2 | explorar, plano curto, TDD, revisão independente, gate | `wf-backend` e/ou `wf-frontend`; full-stack começa pelo contrato do backend | `explorer`, `implementer`, `reviewer`; `security-auditor` com gatilho; `ui-critic` com UI | +| 3 | spec EARS com IDs e ADR, aprovação do usuário, tarefas pequenas com TDD, revisões, gate | `wf-architecture` antes; `wf-backend`/`wf-frontend` na execução; `wf-security-review` no fim | `planner`, `implementer`, `reviewer`, `security-auditor`, `ui-critic` com UI, `verifier` | + +Em todo nível: aplique `lean-code`. Peça aprovação do usuário só quando houver uma decisão que é dele (produto, custo, dado existente); no nível 3, a spec sempre passa por ele. + +Delegue a um agente quando o trabalho dele não precisa voltar inteiro para esta conversa (mapear código, revisar um diff). Tarefa que cabe em poucos passos você mesmo faz. + +## 4. Gate de qualidade + +Antes de dizer que terminou, rode: + +```bash +"${CLAUDE_PLUGIN_ROOT}/scripts/quality-gate" --tier N +``` + +- `fail`: corrija. Se não der, explique ao usuário o que falhou e por quê. +- `incomplete`: diga ao usuário quais checagens ficaram "não verificado" (ferramenta ausente). Nunca chame de testado o que não rodou. +- `dependências novas`: justifique cada uma (ver `lean-code`). + +O hook de `Stop` bloqueia o encerramento enquanto houver código alterado sem gate atualizado ou com gate falho. Configuração por projeto e lista de checagens: [references/quality-gate.md](references/quality-gate.md). + +## 5. Relatório final (nível 1 ou mais) + +1. Nível e motivo. +2. O que mudou: arquivos e linhas líquidas (`diff` do gate). +3. Evidência: veredito do gate; checagens ok, falhas e não verificadas. +4. O que ficou de fora ou é risco conhecido. diff --git a/skills/dev-router/references/quality-gate.md b/skills/dev-router/references/quality-gate.md new file mode 100644 index 0000000..e13ea78 --- /dev/null +++ b/skills/dev-router/references/quality-gate.md @@ -0,0 +1,71 @@ +# Quality gate: checagens e configuração + +`scripts/quality-gate --tier N` roda as checagens do nível N e dos níveis abaixo, só sobre os arquivos +alterados em relação à branch base (merge-base com `origin/HEAD`, `main` ou `master`). O resultado vai +para `.dev-workflows/gate.json` (ignorado pelo git automaticamente) e uma linha resumida vai para +`.dev-workflows/log.jsonl`. + +`--list` mostra o que rodaria e o que está faltando, sem rodar nada. + +## Checagens + +| Nível | Checagem | Ferramenta | Como é detectada | +|---|---|---|---| +| 0 | lint | script `lint` do package.json, eslint, ruff, `go vet`, clippy | primeira que existir | +| 0 | typecheck | script `typecheck`, `tsc --noEmit`, pyright, mypy | tsconfig ou config do checker | +| 0 | test | script `test`, pytest (usa `.venv` se existir), `go test`, `cargo test` | stack do projeto | +| 0 | secrets | gitleaks, só nos arquivos alterados | binário no PATH | +| 1 | diff-coverage | diff-cover sobre `coverage.xml` | relatório de cobertura presente | +| 1 | semgrep | `semgrep --config p/default --baseline-commit ` | binário no PATH | +| 1 | dead-code (info) | knip, vulture | binário no projeto ou PATH | +| 2 | build | script `build` | package.json | +| 2 | mutation | Stryker nos arquivos alterados; mutmut (paths configurados) | config do Stryker ou `[tool.mutmut]` | +| 2 | osv-scanner | `osv-scanner scan source --recursive .` | binário no PATH | +| 2 | architecture | dependency-cruiser, import-linter | arquivo de config | +| 2 | duplication (info) | jscpd | binário no projeto | +| 3 | trivy | vulnerabilidades, misconfig e segredos, HIGH e CRITICAL | binário no PATH | +| 3 | traceability | todo `REQ-NNN` da spec aparece em algum teste | `[spec]` na config | + +Estados: `pass`, `fail`, `unverified` (ferramenta ou config ausente, nunca conta como aprovado) e +`info` (só relatório). Veredito: `fail` se algo falhou; `incomplete` se algo ficou não verificado; senão `pass`. + +## `.dev-workflows.toml` (opcional, na raiz do projeto) + +```toml +timeout = 600 # segundos por checagem + +[commands] # substitui o que foi detectado +test = "pnpm vitest run --coverage" +lint = "pnpm eslint ." +mutation = "pnpm stryker run --incremental" + +[thresholds] +diff_coverage = 80 + +[coverage] +report = "coverage/cobertura-coverage.xml" + +[spec] # nível 3: rastreabilidade requisito -> teste +file = "docs/spec.md" +tests = ["tests", "e2e"] + +[[check]] # checagem extra; kind = "gate" (padrão) ou "info" +name = "lighthouse" +cmd = "npx lhci autorun" +tier = 2 + +[[check]] +name = "a11y" +cmd = "npx playwright test e2e/a11y.spec.ts" +tier = 2 + +[[check]] +name = "api-fuzz" +cmd = "schemathesis run http://localhost:8000/openapi.json --checks all" +tier = 2 +``` + +Frontend, API e carga dependem do app estar de pé, então entram como `[[check]]` do projeto +(Lighthouse CI com orçamento, Playwright com `@axe-core/playwright`, schemathesis, k6 com thresholds). + +`DW_GATE=off` desliga o hook de `Stop` numa sessão. diff --git a/skills/lean-code/SKILL.md b/skills/lean-code/SKILL.md new file mode 100644 index 0000000..3c52e27 --- /dev/null +++ b/skills/lean-code/SKILL.md @@ -0,0 +1,53 @@ +--- +name: lean-code +description: Use sempre que for escrever ou mudar código. Escolhe a menor solução que resolve de verdade - reaproveitar antes de escrever, apagar antes de somar, sem abstração especulativa e sem dependência desnecessária. +license: MIT +metadata: + dev-workflows: + uses: [safedeps] + external: [] +--- + +# Lean Code + +Primeiro entenda o problema e o código que ele toca. Depois suba a escada e pare no primeiro degrau +que resolve. + +## Escada + +1. **Precisa existir?** Pedido especulativo ("para depois", "vai que") não entra. Diga isso em uma linha. +2. **Já existe no projeto?** Procure helper, componente, tipo ou padrão parecido antes de escrever (`grep` por nomes e por comportamento; o agente `explorer` faz isso). +3. **A biblioteca padrão resolve?** +4. **A plataforma resolve?** HTML/CSS nativo antes de JS, constraint do banco antes de código, recurso do framework antes de utilitário próprio. +5. **Uma dependência já instalada resolve?** +6. **Cabe em poucas linhas?** +7. Só então: o mínimo de código novo. + +## Regras + +- **Bug se corrige na causa.** Antes de editar uma função, ache todos os chamadores. Uma correção no ponto por onde todos passam é menor que uma por chamador, e não deixa os outros quebrados. +- **Sem abstração sem uso:** interface com uma implementação, factory de um produto, configuração para valor que nunca muda. +- **Dependência nova exige justificativa** em uma linha (o que ela faz que os degraus 3 a 6 não fazem) e consulta ao `safedeps` antes de instalar. O gate lista as novas. +- **Apague o que ficou morto** por causa da mudança. +- **Entre duas soluções do mesmo tamanho**, fique com a que está certa nos casos de borda. + +## Nunca simplifique + +Validação na fronteira do sistema, tratamento de erro que evita perda de dado, controles de segurança, +acessibilidade básica e qualquer coisa que o usuário pediu explicitamente. + +## Orçamento de diff (linhas líquidas, referência) + +| Nível | Orçamento | +|---|---| +| 0 | 20 | +| 1 | 100 | +| 2 | 400 | +| 3 | 400 por fatia entregue | + +Estourou: justifique no relatório ou quebre em partes menores. + +## Atalho consciente + +Quando cortar caminho de propósito (lock global, busca O(n²), heurística simples), deixe um comentário +`lean:` dizendo o limite e quando evoluir: `# lean: lock global; trocar por lock por conta se a vazão importar`. diff --git a/skills/patch-prioritization/schemas/finding.schema.json b/skills/patch-prioritization/schemas/finding.schema.json new file mode 100644 index 0000000..535a496 --- /dev/null +++ b/skills/patch-prioritization/schemas/finding.schema.json @@ -0,0 +1,345 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/UnitOneAI/SecuritySkills/schemas/finding.schema.json", + "title": "SecuritySkills Normalized Finding Output", + "description": "Machine-readable envelope for normalized security findings and remediation recommendations emitted by SecuritySkills workflows. This contract is independent of SARIF and may be mapped to downstream enterprise formats later.", + "type": "object", + "additionalProperties": false, + "required": ["schema_version", "run", "skill", "findings"], + "properties": { + "schema_version": { + "const": "1.0.0", + "description": "Version of this normalized SecuritySkills finding envelope." + }, + "run": { + "$ref": "#/$defs/run", + "description": "Metadata for the analysis run that produced this output." + }, + "skill": { + "$ref": "#/$defs/skill", + "description": "Metadata for the SecuritySkills entrypoint that produced this output." + }, + "findings": { + "type": "array", + "items": { + "$ref": "#/$defs/finding" + }, + "description": "Normalized findings produced by a skill run." + } + }, + "$defs": { + "riskLevel": { + "type": "string", + "enum": ["low", "medium", "high"] + }, + "nonEmptyString": { + "type": "string", + "minLength": 1 + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "run": { + "type": "object", + "additionalProperties": false, + "required": ["id", "timestamp"], + "properties": { + "id": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable run identifier supplied by the agent, CI job, or enterprise orchestrator." + }, + "timestamp": { + "$ref": "#/$defs/nonEmptyString", + "description": "ISO 8601 timestamp for when the run output was produced." + }, + "tool": { + "$ref": "#/$defs/nonEmptyString", + "description": "Agent, CLI, scanner, or workflow that executed the skill." + }, + "target": { + "$ref": "#/$defs/nonEmptyString", + "description": "Repository, project, service, artifact, environment, or other target reviewed." + }, + "source_ref": { + "$ref": "#/$defs/nonEmptyString", + "description": "Optional commit SHA, branch, image digest, build ID, ticket ID, or evidence package reference." + } + } + }, + "skill": { + "type": "object", + "additionalProperties": false, + "required": ["name", "version"], + "properties": { + "name": { + "$ref": "#/$defs/nonEmptyString", + "description": "SecuritySkills skill name from SKILL.md frontmatter." + }, + "version": { + "$ref": "#/$defs/nonEmptyString", + "description": "SecuritySkills skill version from SKILL.md frontmatter." + }, + "path": { + "$ref": "#/$defs/nonEmptyString", + "description": "Path to the SKILL.md entrypoint used for the run." + }, + "frameworks": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/nonEmptyString" + }, + "description": "Framework identifiers declared by the skill frontmatter." + } + } + }, + "finding": { + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "severity", "status", "evidence", "remediations"], + "properties": { + "id": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable finding identifier within the output." + }, + "fingerprint": { + "$ref": "#/$defs/nonEmptyString", + "description": "Stable deduplication key based on finding type, affected asset, and evidence location." + }, + "title": { + "$ref": "#/$defs/nonEmptyString" + }, + "description": { + "$ref": "#/$defs/nonEmptyString", + "description": "What the issue is and why it matters." + }, + "severity": { + "type": "string", + "enum": ["info", "low", "medium", "high", "critical"] + }, + "status": { + "type": "string", + "enum": ["open", "mitigated", "accepted_risk", "false_positive"] + }, + "cwe": { + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "pattern": "^CWE-[0-9]+$" + }, + "description": "Optional CWE mappings, when applicable." + }, + "framework_refs": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/frameworkRef" + }, + "description": "Framework/control references from the skill frontmatter frameworks." + }, + "references": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/reference" + }, + "description": "Optional advisory, standard, vendor, or knowledge-base references." + }, + "evidence": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["location", "summary"], + "properties": { + "location": { + "$ref": "#/$defs/nonEmptyString", + "description": "File path, line range, asset ID, log source, policy path, or other concrete evidence location." + }, + "summary": { + "$ref": "#/$defs/nonEmptyString" + }, + "artifact_type": { + "type": "string", + "enum": ["source", "config", "policy", "log", "scan_result", "cloud_resource", "identity", "network", "document", "other"] + }, + "snippet": { + "$ref": "#/$defs/nonEmptyString", + "description": "Minimal redacted snippet or observation needed to support the finding." + }, + "redacted": { + "type": "boolean", + "description": "True when sensitive values were intentionally removed from this evidence." + } + } + } + }, + "remediations": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/remediation" + }, + "description": "Every fix recommendation for this finding. Each item must include remediation guidance, confidence, blast radius, behavior-change risk, and test strategy." + } + }, + "anyOf": [ + { + "required": ["cwe"] + }, + { + "required": ["framework_refs"] + } + ] + }, + "frameworkRef": { + "type": "object", + "additionalProperties": false, + "required": ["framework", "control"], + "properties": { + "framework": { + "$ref": "#/$defs/nonEmptyString" + }, + "control": { + "$ref": "#/$defs/nonEmptyString" + }, + "name": { + "$ref": "#/$defs/nonEmptyString" + } + } + }, + "reference": { + "type": "object", + "additionalProperties": false, + "required": ["type", "id"], + "properties": { + "type": { + "type": "string", + "enum": ["cve", "cwe", "framework", "advisory", "vendor", "documentation", "other"] + }, + "id": { + "$ref": "#/$defs/nonEmptyString" + }, + "url": { + "$ref": "#/$defs/uriString" + } + } + }, + "remediation": { + "type": "object", + "additionalProperties": false, + "required": ["guidance", "confidence", "blast_radius", "behavior_change_risk", "test_strategy"], + "properties": { + "guidance": { + "$ref": "#/$defs/nonEmptyString", + "description": "Concrete remediation steps or patch guidance for the finding." + }, + "confidence": { + "$ref": "#/$defs/riskLevel", + "description": "How confident the skill is that this recommendation is correct for the observed evidence." + }, + "blast_radius": { + "$ref": "#/$defs/nonEmptyString", + "description": "Expected scope of systems, files, users, integrations, data, or workflows affected by the change." + }, + "behavior_change_risk": { + "$ref": "#/$defs/riskLevel", + "description": "Risk that the remediation changes intended application or operational behavior." + }, + "test_strategy": { + "$ref": "#/$defs/testStrategy", + "description": "Required validation strategy proving the remediation fixes the finding. Include recommended tests, generated tests, or both." + } + } + }, + "testStrategy": { + "type": "object", + "additionalProperties": false, + "required": ["summary"], + "properties": { + "summary": { + "$ref": "#/$defs/nonEmptyString", + "description": "Concise explanation of what proves the remediation fixed the issue." + }, + "recommended_tests": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/recommendedTest" + }, + "description": "Tests the user or agent should run when tests are not generated directly." + }, + "generated_tests": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/$defs/generatedTest" + }, + "description": "Test files or cases produced as part of the remediation." + } + }, + "anyOf": [ + { + "required": ["recommended_tests"] + }, + { + "required": ["generated_tests"] + } + ] + }, + "recommendedTest": { + "type": "object", + "additionalProperties": false, + "required": ["name", "type", "purpose", "command", "expected_result"], + "properties": { + "name": { + "$ref": "#/$defs/nonEmptyString" + }, + "type": { + "type": "string", + "enum": ["static", "unit", "integration", "e2e", "regression", "manual"] + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString", + "description": "Behavior, vulnerability condition, or regression this test proves." + }, + "command": { + "$ref": "#/$defs/nonEmptyString", + "description": "Command or manual check to execute for this test." + }, + "expected_result": { + "$ref": "#/$defs/nonEmptyString" + } + } + }, + "generatedTest": { + "type": "object", + "additionalProperties": false, + "required": ["path", "type", "purpose", "command", "expected_result"], + "properties": { + "path": { + "$ref": "#/$defs/nonEmptyString", + "description": "Path to the generated or modified test file." + }, + "type": { + "type": "string", + "enum": ["static", "unit", "integration", "e2e", "regression"] + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString", + "description": "Behavior, vulnerability condition, or regression this generated test proves." + }, + "command": { + "$ref": "#/$defs/nonEmptyString", + "description": "Command that runs the generated test." + }, + "expected_result": { + "$ref": "#/$defs/nonEmptyString" + } + } + } + } +} diff --git a/skills/redesign-existing-projects/LICENSE b/skills/redesign-existing-projects/LICENSE new file mode 100644 index 0000000..48a2f66 --- /dev/null +++ b/skills/redesign-existing-projects/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Leonxlnx + +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/skills/redesign-existing-projects/SKILL.md b/skills/redesign-existing-projects/SKILL.md new file mode 100644 index 0000000..c8304f0 --- /dev/null +++ b/skills/redesign-existing-projects/SKILL.md @@ -0,0 +1,178 @@ +--- +name: redesign-existing-projects +description: Upgrades existing websites and apps to premium quality. Audits current design, identifies generic AI patterns, and applies high-end design standards without breaking functionality. Works with any CSS framework or vanilla CSS. +--- + +# Redesign Skill + +## How This Works + +When applied to an existing project, follow this sequence: + +1. **Scan** — Read the codebase. Identify the framework, styling method (Tailwind, vanilla CSS, styled-components, etc.), and current design patterns. +2. **Diagnose** — Run through the audit below. List every generic pattern, weak point, and missing state you find. +3. **Fix** — Apply targeted upgrades working with the existing stack. Do not rewrite from scratch. Improve what's there. + +## Design Audit + +### Typography + +Check for these problems and fix them: + +- **Browser default fonts or Inter everywhere.** Replace with a font that has character. Good options: `Geist`, `Outfit`, `Cabinet Grotesk`, `Satoshi`. For editorial/creative projects, pair a serif header with a sans-serif body. +- **Headlines lack presence.** Increase size for display text, tighten letter-spacing, reduce line-height. Headlines should feel heavy and intentional. +- **Body text too wide.** Limit paragraph width to roughly 65 characters. Increase line-height for readability. +- **Only Regular (400) and Bold (700) weights used.** Introduce Medium (500) and SemiBold (600) for more subtle hierarchy. +- **Numbers in proportional font.** Use a monospace font or enable tabular figures (`font-variant-numeric: tabular-nums`) for data-heavy interfaces. +- **Missing letter-spacing adjustments.** Use negative tracking for large headers, positive tracking for small caps or labels. +- **All-caps subheaders everywhere.** Try lowercase italics, sentence case, or small-caps instead. +- **Orphaned words.** Single words sitting alone on the last line. Fix with `text-wrap: balance` or `text-wrap: pretty`. + +### Color and Surfaces + +- **Pure `#000000` background.** Replace with off-black, dark charcoal, or tinted dark (`#0a0a0a`, `#121212`, or a dark navy). +- **Oversaturated accent colors.** Keep saturation below 80%. Desaturate accents so they blend with neutrals instead of screaming. +- **More than one accent color.** Pick one. Remove the rest. Consistency beats variety. +- **Mixing warm and cool grays.** Stick to one gray family. Tint all grays with a consistent hue (warm or cool, not both). +- **Purple/blue "AI gradient" aesthetic.** This is the most common AI design fingerprint. Replace with neutral bases and a single, considered accent. +- **Generic `box-shadow`.** Tint shadows to match the background hue. Use colored shadows (e.g., dark blue shadow on a blue background) instead of pure black at low opacity. +- **Flat design with zero texture.** Add subtle noise, grain, or micro-patterns to backgrounds. Pure flat vectors feel sterile. +- **Perfectly even gradients.** Break the uniformity with radial gradients, noise overlays, or mesh gradients instead of standard linear 45-degree fades. +- **Inconsistent lighting direction.** Audit all shadows to ensure they suggest a single, consistent light source. +- **Random dark sections in a light mode page (or vice versa).** A single dark-background section breaking an otherwise light page looks like a copy-paste accident. Either commit to a full dark mode or keep a consistent background tone throughout. If contrast is needed, use a slightly darker shade of the same palette — not a sudden jump to `#111` in the middle of a cream page. +- **Empty, flat sections with no visual depth.** Sections that are just text on a plain background feel unfinished. Add high-quality background imagery (blurred, overlaid, or masked), subtle patterns, or ambient gradients. Use reliable placeholder sources like `https://picsum.photos/seed/{name}/1920/1080` when real assets are not available. Experiment with background images behind hero sections, feature blocks, or CTAs — even a subtle full-width photo at low opacity adds presence. + +### Layout + +- **Everything centered and symmetrical.** Break symmetry with offset margins, mixed aspect ratios, or left-aligned headers over centered content. +- **Three equal card columns as feature row.** This is the most generic AI layout. Replace with a 2-column zig-zag, asymmetric grid, horizontal scroll, or masonry layout. +- **Using `height: 100vh` for full-screen sections.** Replace with `min-height: 100dvh` to prevent layout jumping on mobile browsers (iOS Safari viewport bug). +- **Complex flexbox percentage math.** Replace with CSS Grid for reliable multi-column structures. +- **No max-width container.** Add a container constraint (around 1200-1440px) with auto margins so content doesn't stretch edge-to-edge on wide screens. +- **Cards of equal height forced by flexbox.** Allow variable heights or use masonry when content varies in length. +- **Uniform border-radius on everything.** Vary the radius: tighter on inner elements, softer on containers. +- **No overlap or depth.** Elements sit flat next to each other. Use negative margins to create layering and visual depth. +- **Symmetrical vertical padding.** Top and bottom padding are always identical. Adjust optically — bottom padding often needs to be slightly larger. +- **Dashboard always has a left sidebar.** Try top navigation, a floating command menu, or a collapsible panel instead. +- **Missing whitespace.** Double the spacing. Let the design breathe. Dense layouts work for data dashboards, not for marketing pages. +- **Buttons not bottom-aligned in card groups.** When cards have different content lengths, CTAs end up at random heights. Pin buttons to the bottom of each card so they form a clean horizontal line regardless of content above. +- **Feature lists starting at different vertical positions.** In pricing tables or comparison cards, the list of features should start at the same Y position across all columns. Use consistent spacing above the list or fixed-height title/price blocks. +- **Inconsistent vertical rhythm in side-by-side elements.** When placing cards, columns, or panels next to each other, align shared elements (titles, descriptions, prices, buttons) across all items. Misaligned baselines make the layout look broken. +- **Mathematical alignment that looks optically wrong.** Centering by the math doesn't always look centered to the eye. Icons next to text, play buttons in circles, or text in buttons often need 1-2px optical adjustments to feel right. + +### Interactivity and States + +- **No hover states on buttons.** Add background shift, slight scale, or translate on hover. +- **No active/pressed feedback.** Add a subtle `scale(0.98)` or `translateY(1px)` on press to simulate a physical click. +- **Instant transitions with zero duration.** Add smooth transitions (200-300ms) to all interactive elements. +- **Missing focus ring.** Ensure visible focus indicators for keyboard navigation. This is an accessibility requirement, not optional. +- **No loading states.** Replace generic circular spinners with skeleton loaders that match the layout shape. +- **No empty states.** An empty dashboard showing nothing is a missed opportunity. Design a composed "getting started" view. +- **No error states.** Add clear, inline error messages for forms. Do not use `window.alert()`. +- **Dead links.** Buttons that link to `#`. Either link to real destinations or visually disable them. +- **No indication of current page in navigation.** Style the active nav link differently so users know where they are. +- **Scroll jumping.** Anchor clicks jump instantly. Add `scroll-behavior: smooth`. +- **Animations using `top`, `left`, `width`, `height`.** Switch to `transform` and `opacity` for GPU-accelerated, smooth animation. + +### Content + +- **Generic names like "John Doe" or "Jane Smith".** Use diverse, realistic-sounding names. +- **Fake round numbers like `99.99%`, `50%`, `$100.00`.** Use organic, messy data: `47.2%`, `$99.00`, `+1 (312) 847-1928`. +- **Placeholder company names like "Acme Corp", "Nexus", "SmartFlow".** Invent contextual, believable brand names. +- **AI copywriting cliches.** Never use "Elevate", "Seamless", "Unleash", "Next-Gen", "Game-changer", "Delve", "Tapestry", or "In the world of...". Write plain, specific language. +- **Exclamation marks in success messages.** Remove them. Be confident, not loud. +- **"Oops!" error messages.** Be direct: "Connection failed. Please try again." +- **Passive voice.** Use active voice: "We couldn't save your changes" instead of "Mistakes were made." +- **All blog post dates identical.** Randomize dates to appear real. +- **Same avatar image for multiple users.** Use unique assets for every distinct person. +- **Lorem Ipsum.** Never use placeholder latin text. Write real draft copy. +- **Title Case On Every Header.** Use sentence case instead. + +### Component Patterns + +- **Generic card look (border + shadow + white background).** Remove the border, or use only background color, or use only spacing. Cards should exist only when elevation communicates hierarchy. +- **Always one filled button + one ghost button.** Add text links or tertiary styles to reduce visual noise. +- **Pill-shaped "New" and "Beta" badges.** Try square badges, flags, or plain text labels. +- **Accordion FAQ sections.** Use a side-by-side list, searchable help, or inline progressive disclosure. +- **3-card carousel testimonials with dots.** Replace with a masonry wall, embedded social posts, or a single rotating quote. +- **Pricing table with 3 towers.** Highlight the recommended tier with color and emphasis, not just extra height. +- **Modals for everything.** Use inline editing, slide-over panels, or expandable sections instead of popups for simple actions. +- **Avatar circles exclusively.** Try squircles or rounded squares for a less generic look. +- **Light/dark toggle always a sun/moon switch.** Use a dropdown, system preference detection, or integrate it into settings. +- **Footer link farm with 4 columns.** Simplify. Focus on main navigational paths and legally required links. + +### Iconography + +- **Lucide or Feather icons exclusively.** These are the "default" AI icon choice. Use Phosphor, Heroicons, or a custom set for differentiation. +- **Rocketship for "Launch", shield for "Security".** Replace cliche metaphors with less obvious icons (bolt, fingerprint, spark, vault). +- **Inconsistent stroke widths across icons.** Audit all icons and standardize to one stroke weight. +- **Missing favicon.** Always include a branded favicon. +- **Stock "diverse team" photos.** Use real team photos, candid shots, or a consistent illustration style instead of uncanny stock imagery. + +### Code Quality + +- **Div soup.** Use semantic HTML: `