Improve/python preflight safety hook ci #1

Merged
fraujulian merged 2 commits from improve/python-preflight-safety-hook-ci into main 2026-11-05 09:57:15 +00:00
62 changed files with 453 additions and 300 deletions
Showing only changes of commit 6159c6373c - Show all commits

No files matched your search

+10 -10
View File
@@ -4,24 +4,24 @@
"permanent_context_hard_limit_tokens": 15000, "permanent_context_hard_limit_tokens": 15000,
"metrics": { "metrics": {
"permanent_context_tokens": { "permanent_context_tokens": {
"claude": 5451, "claude": 5959,
"codex": 3767 "codex": 4100
}, },
"instruction_tokens": { "instruction_tokens": {
"claude": 1485, "claude": 1670,
"codex": 1485 "codex": 1670
}, },
"skill_metadata_tokens": { "skill_metadata_tokens": {
"claude": 3163, "claude": 3354,
"codex": 1554 "codex": 1575
}, },
"auto_loaded_rule_tokens": { "auto_loaded_rule_tokens": {
"claude": 678, "claude": 732,
"codex": 678 "codex": 731
}, },
"rule_catalog_tokens": { "rule_catalog_tokens": {
"claude": 28818, "claude": 36519,
"codex": 8510 "codex": 8944
}, },
"agent_metadata_tokens": { "agent_metadata_tokens": {
"claude": 204, "claude": 204,
+10 -10
View File
@@ -1,13 +1,13 @@
metric client baseline_tokens metric client baseline_tokens
permanent_context_tokens claude 5451 permanent_context_tokens claude 5959
permanent_context_tokens codex 3767 permanent_context_tokens codex 4100
instruction_tokens claude 1485 instruction_tokens claude 1670
instruction_tokens codex 1485 instruction_tokens codex 1670
skill_metadata_tokens claude 3163 skill_metadata_tokens claude 3354
skill_metadata_tokens codex 1554 skill_metadata_tokens codex 1575
auto_loaded_rule_tokens claude 678 auto_loaded_rule_tokens claude 732
auto_loaded_rule_tokens codex 678 auto_loaded_rule_tokens codex 731
rule_catalog_tokens claude 28818 rule_catalog_tokens claude 36519
rule_catalog_tokens codex 8510 rule_catalog_tokens codex 8944
agent_metadata_tokens claude 204 agent_metadata_tokens claude 204
agent_metadata_tokens codex 124 agent_metadata_tokens codex 124
1 metric client baseline_tokens
2 permanent_context_tokens claude 5451 5959
3 permanent_context_tokens codex 3767 4100
4 instruction_tokens claude 1485 1670
5 instruction_tokens codex 1485 1670
6 skill_metadata_tokens claude 3163 3354
7 skill_metadata_tokens codex 1554 1575
8 auto_loaded_rule_tokens claude 678 732
9 auto_loaded_rule_tokens codex 678 731
10 rule_catalog_tokens claude 28818 36519
11 rule_catalog_tokens codex 8510 8944
12 agent_metadata_tokens claude 204
13 agent_metadata_tokens codex 124
+2
View File
@@ -6,6 +6,8 @@ Shared definitions are the source of truth. Rebuild after every semantic change.
Create cross-cutting rules such as Git or Microsoft guidance as focused Markdown files directly in `shared/rules/`. Put each language, framework, or library in its own directory with an `index.md` and focused files under `references/`; put security rules in `shared/rules/security/`. Add the matching loading condition and generated Claude skill name to `shared/global-instructions.md` and the directory index. The build copies rule trees to Codex and generates Claude skills from each rule file. Put always-applicable guidance in `general.md`, which the build embeds for both clients; a new rule file is not automatically embedded. Create cross-cutting rules such as Git or Microsoft guidance as focused Markdown files directly in `shared/rules/`. Put each language, framework, or library in its own directory with an `index.md` and focused files under `references/`; put security rules in `shared/rules/security/`. Add the matching loading condition and generated Claude skill name to `shared/global-instructions.md` and the directory index. The build copies rule trees to Codex and generates Claude skills from each rule file. Put always-applicable guidance in `general.md`, which the build embeds for both clients; a new rule file is not automatically embedded.
Start every rule file with a unique level-1 heading followed by an "Apply these rules when ..." line: the heading becomes the generated Claude skill description, and the scope line tells an agent loading the file cold whether it applies. Language and framework rules contain only language-specific mechanics and point to the shared security, UI/UX, or parent-language rules instead of restating them. The build rejects rule files without a level-1 heading, duplicate titles, reference files missing from their index, index links to missing files, and routes in the global instructions to rules or skills that do not exist.
## Add a skill ## Add a skill
Create `shared/skills/<skill>/SKILL.md` for a standalone skill, or `shared/skills/<category>/<skill>/SKILL.md` for a grouped workflow. Each leaf skill directory must contain a readable `SKILL.md` with valid YAML frontmatter. Keep the initial workflow focused; place longer supporting material under `references/`. Reference shared rules instead of repeating persistent standards. Create `shared/skills/<skill>/SKILL.md` for a standalone skill, or `shared/skills/<category>/<skill>/SKILL.md` for a grouped workflow. Each leaf skill directory must contain a readable `SKILL.md` with valid YAML frontmatter. Keep the initial workflow focused; place longer supporting material under `references/`. Reference shared rules instead of repeating persistent standards.
+2 -1
View File
@@ -59,9 +59,10 @@ On Windows, an unavailable profile-folder lookup falls back to PowerShell's home
| Script | Purpose | | Script | Purpose |
| --- | --- | | --- | --- |
| `checks/validate-config.py` | Validate generated Codex TOML and Claude JSON. | | `checks/validate-config.py` | Validate generated Codex TOML and Claude JSON, generated rule skills, agent tool names, and the rule catalog structure and routing. |
| `tests/test-build-validation.ps1`, `tests/test-build-validation.sh` | Validate build failures and generated output. | | `tests/test-build-validation.ps1`, `tests/test-build-validation.sh` | Validate build failures and generated output. |
| `tests/test-capabilities.ps1`, `tests/test-capabilities.sh` | Check that Python resolution skips a broken interpreter on PATH (such as the Windows Store alias) and that the capability check reports the resolved interpreter. | | `tests/test-capabilities.ps1`, `tests/test-capabilities.sh` | Check that Python resolution skips a broken interpreter on PATH (such as the Windows Store alias) and that the capability check reports the resolved interpreter. |
| `tests/test-rule-structure.py` | Validate the rule-structure checks in `checks/validate-config.py`: level-1 headings, unique titles, complete indexes, and existing routing targets. |
| `tests/test-command-safety.py` | Validate the command-safety hook: destructive Bash, PowerShell, and cmd variants are blocked, ordinary commands pass, unusable input fails open, and both shell wrappers pass stdin and exit codes through. | | `tests/test-command-safety.py` | Validate the command-safety hook: destructive Bash, PowerShell, and cmd variants are blocked, ordinary commands pass, unusable input fails open, and both shell wrappers pass stdin and exit codes through. |
| `tests/test-install-guards.ps1`, `tests/test-install-guards.sh` | Validate install and update guard conditions. | | `tests/test-install-guards.ps1`, `tests/test-install-guards.sh` | Validate install and update guard conditions. |
| `tests/test-config-effects.py` | Check that generated limits and permissions take effect: Codex keeps the V1 multi-agent implementation that honors `agents.max_depth`; with `AI_CONFIG_LIVE_TESTS=1`, short Haiku sessions confirm that Claude withholds the Agent tool from subagents, refuses subagents above the concurrency limit, and blocks `git reset --hard` in every shell tool. | | `tests/test-config-effects.py` | Check that generated limits and permissions take effect: Codex keeps the V1 multi-agent implementation that honors `agents.max_depth`; with `AI_CONFIG_LIVE_TESTS=1`, short Haiku sessions confirm that Claude withholds the Agent tool from subagents, refuses subagents above the concurrency limit, and blocks `git reset --hard` in every shell tool. |
+4
View File
@@ -2,3 +2,7 @@
# defective sample projects, so they are excluded. # defective sample projects, so they are excluded.
target-version = "py311" target-version = "py311"
extend-exclude = ["scripts/benchmarks/tasks", "generated", "generated.*"] extend-exclude = ["scripts/benchmarks/tasks", "generated", "generated.*"]
[lint]
# Pin the rule set: newer ruff releases widen the default selection.
select = ["E4", "E7", "E9", "F"]
+40
View File
@@ -4,6 +4,7 @@
from __future__ import annotations from __future__ import annotations
import json import json
import re
import sys import sys
import tomllib import tomllib
from pathlib import Path from pathlib import Path
@@ -89,6 +90,43 @@ def validate_agent_tools(package: Path) -> None:
fail(f"{path}: unknown Claude tool name(s): {', '.join(unknown)}") fail(f"{path}: unknown Claude tool name(s): {', '.join(unknown)}")
RULE_PATH = re.compile(r"`(rules/[A-Za-z0-9_./-]+\.md)`")
RULE_SKILL = re.compile(r"`(rules-[a-z0-9-]+)`")
REFERENCE_LINK = re.compile(r"`(references/[A-Za-z0-9_./-]+\.md)`")
def validate_rule_tree(codex_package: Path) -> None:
"""Keep the rule catalog routable: unique H1 titles, complete indexes, and no dangling links."""
rules = codex_package / "rules"
titles: dict[str, Path] = {}
for path in sorted(rules.rglob("*.md")):
first = next((line for line in path.read_text(encoding="utf-8-sig").splitlines() if line.strip()), "")
if not first.startswith("# "):
fail(f"{path}: a rule must start with a level-1 heading; it becomes the Claude skill description")
title = first[2:].strip().lower()
if title in titles:
fail(f"{path}: title duplicates {titles[title]}; rule titles must be unique")
titles[title] = path
for index in sorted(rules.rglob("index.md")):
linked = set(REFERENCE_LINK.findall(index.read_text(encoding="utf-8-sig")))
for link in linked:
if not (index.parent / link).is_file():
fail(f"{index}: links missing rule {link}")
for reference in sorted((index.parent / "references").glob("*.md")):
if f"references/{reference.name}" not in linked:
fail(f"{reference}: not linked from {index}")
for link in RULE_PATH.findall((codex_package / "AGENTS.md").read_text(encoding="utf-8-sig")):
if not (codex_package / link).is_file():
fail(f"{codex_package / 'AGENTS.md'}: routes to missing rule {link}")
def validate_rule_routing(claude_package: Path) -> None:
instructions = claude_package / "CLAUDE.md"
for skill in set(RULE_SKILL.findall(instructions.read_text(encoding="utf-8-sig"))):
if not (claude_package / "skills" / skill / "SKILL.md").is_file():
fail(f"{instructions}: routes to missing skill {skill}")
def main() -> int: def main() -> int:
if len(sys.argv) != 3: if len(sys.argv) != 3:
print("usage: validate-config.py <codex-toml> <claude-json>", file=sys.stderr) print("usage: validate-config.py <codex-toml> <claude-json>", file=sys.stderr)
@@ -97,6 +135,8 @@ def main() -> int:
validate_claude(Path(sys.argv[2])) validate_claude(Path(sys.argv[2]))
validate_rule_skills(Path(sys.argv[2]).parent) validate_rule_skills(Path(sys.argv[2]).parent)
validate_agent_tools(Path(sys.argv[2]).parent) validate_agent_tools(Path(sys.argv[2]).parent)
validate_rule_tree(Path(sys.argv[1]).parent)
validate_rule_routing(Path(sys.argv[2]).parent)
return 0 return 0
+1 -1
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# shellcheck disable=SC2154
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh # shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh" . "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || true resolve_python || true
# shellcheck disable=SC2154
read_install_boolean() { read_install_boolean() {
local prompt=$1 default=$2 hint=y/N answer local prompt=$1 default=$2 hint=y/N answer
+1 -1
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# shellcheck disable=SC2154
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh # shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh" . "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || true resolve_python || true
# shellcheck disable=SC2154
read_update_selection() { read_update_selection() {
local saved key value local saved key value
+1 -1
View File
@@ -116,7 +116,7 @@ class InstallOptionsTests(unittest.TestCase):
def test_qmd_warm_match_is_anchored(self): def test_qmd_warm_match_is_anchored(self):
self.assertTrue(OPTIONS.is_qmd_warm({'command': 'bash "/c/hooks/scripts/qmd-warm.sh"'})) self.assertTrue(OPTIONS.is_qmd_warm({'command': 'bash "/c/hooks/scripts/qmd-warm.sh"'}))
self.assertTrue(OPTIONS.is_qmd_warm({'command_windows': 'pwsh "C:\hooks\Start-QmdWarm.ps1"'})) self.assertTrue(OPTIONS.is_qmd_warm({'command_windows': r'pwsh "C:\hooks\Start-QmdWarm.ps1"'}))
self.assertFalse(OPTIONS.is_qmd_warm({'command': 'bash "/c/hooks/scripts/my-qmd-warm.sh"'})) self.assertFalse(OPTIONS.is_qmd_warm({'command': 'bash "/c/hooks/scripts/my-qmd-warm.sh"'}))
def test_merge_json_keeps_user_session_hook_and_drops_qmd_when_disabled(self): def test_merge_json_keeps_user_session_hook_and_drops_qmd_when_disabled(self):
+1 -1
View File
@@ -67,7 +67,7 @@ try {
if (@($selection.Deselected | Where-Object { $_.name -eq 'Context7' }).Count -ne 1) { throw 'A different MCPorter server must not select Context7.' } if (@($selection.Deselected | Where-Object { $_.name -eq 'Context7' }).Count -ne 1) { throw 'A different MCPorter server must not select Context7.' }
} finally { Remove-Item -LiteralPath $mcporterHome -Recurse -Force -ErrorAction SilentlyContinue } } finally { Remove-Item -LiteralPath $mcporterHome -Recurse -Force -ErrorAction SilentlyContinue }
$script:managedArguments = @() $script:managedArguments = @()
function python { $script:managedArguments = @($args); $global:LASTEXITCODE = 0 } function Invoke-Python { $script:managedArguments = @($args); $global:LASTEXITCODE = 0 }
$entry = [pscustomobject]@{ name = 'Test'; codex_method = 'plugin'; codex_marketplace = '-'; codex_plugin = 'test@market' } $entry = [pscustomobject]@{ name = 'Test'; codex_method = 'plugin'; codex_marketplace = '-'; codex_plugin = 'test@market' }
Sync-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -HomePath $testHome -Update -Summary -Entries @($entry) Sync-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -HomePath $testHome -Update -Summary -Entries @($entry)
if ($managedArguments -notcontains 'sync' -or $managedArguments -notcontains '--update' -or $managedArguments -notcontains 'Test' -or $managedArguments -notcontains $testHome) { throw 'Managed reconciliation must receive selection, home, and update mode.' } if ($managedArguments -notcontains 'sync' -or $managedArguments -notcontains '--update' -or $managedArguments -notcontains 'Test' -or $managedArguments -notcontains $testHome) { throw 'Managed reconciliation must receive selection, home, and update mode.' }
+62
View File
@@ -0,0 +1,62 @@
import importlib.util
from pathlib import Path
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SPEC = importlib.util.spec_from_file_location('validate_config', ROOT / 'scripts/checks/validate-config.py')
VALIDATE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(VALIDATE)
class RuleStructureTests(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.package = Path(directory.name)
self.write('rules/lang/index.md', '# Lang Rules\n\n| Topic | `references/a.md` | `rules-lang-a` |\n')
self.write('rules/lang/references/a.md', '# Lang A\n\n* Rule.\n')
self.write('rules/git.md', '# Git Guidelines\n')
self.write('AGENTS.md', 'Load `rules/lang/index.md` and `rules/git.md`.\n')
def write(self, relative, text):
path = self.package / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding='utf-8')
def assertRejected(self, fragment):
with self.assertRaisesRegex(ValueError, fragment):
VALIDATE.validate_rule_tree(self.package)
def test_accepts_consistent_tree(self):
VALIDATE.validate_rule_tree(self.package)
def test_rejects_missing_level_one_heading(self):
self.write('rules/lang/references/a.md', '## Forms\n')
self.assertRejected('level-1 heading')
def test_rejects_duplicate_titles(self):
self.write('rules/other.md', '# Lang A\n')
self.assertRejected('must be unique')
def test_rejects_unlinked_reference(self):
self.write('rules/lang/references/b.md', '# Lang B\n')
self.assertRejected('not linked')
def test_rejects_dangling_index_link(self):
self.write('rules/lang/index.md', '# Lang Rules\n\n`references/a.md` `references/missing.md`\n')
self.assertRejected('links missing rule')
def test_rejects_route_to_missing_rule(self):
self.write('AGENTS.md', 'Load `rules/lang/gone.md`.\n')
self.assertRejected('routes to missing rule')
def test_rejects_claude_route_to_missing_skill(self):
self.write('CLAUDE.md', 'Invoke `rules-lang-a` and `rules-missing`.\n')
self.write('skills/rules-lang-a/SKILL.md', '---\nname: rules-lang-a\n---\n')
with self.assertRaisesRegex(ValueError, 'missing skill rules-missing'):
VALIDATE.validate_rule_routing(self.package)
if __name__ == '__main__':
unittest.main()
+4 -3
View File
@@ -51,10 +51,11 @@ for shell in powershell bash; do
test "$(find "$package/agents" -type f | wc -l)" -eq "$source_agent_count" test "$(find "$package/agents" -type f | wc -l)" -eq "$source_agent_count"
expected_reviewer_shell_tool=Bash expected_reviewer_shell_tool=Bash
[ "$shell" != powershell ] || expected_reviewer_shell_tool=PowerShell [ "$shell" != powershell ] || expected_reviewer_shell_tool=PowerShell
if [ "$client" = claude ]; then grep -q "^tools: Read,Grep,Glob,$expected_reviewer_shell_tool\$" "$package/agents/reviewer.md"; fi # Generated files may have CRLF endings when the PowerShell build produced them, so allow trailing whitespace.
if [ "$client" = claude ]; then grep -q "^tools: Read,Grep,Glob,${expected_reviewer_shell_tool}[[:space:]]*\$" "$package/agents/reviewer.md"; fi
if [ "$client" = claude ]; then if [ "$client" = claude ]; then
for role in architect researcher; do for role in architect researcher; do
grep -q "^tools: Read,Grep,Glob,WebFetch,WebSearch,$expected_reviewer_shell_tool\$" "$package/agents/$role.md" || { printf '%s research shell capability is missing in %s\n' "$role" "$package"; exit 1; } grep -q "^tools: Read,Grep,Glob,WebFetch,WebSearch,${expected_reviewer_shell_tool}[[:space:]]*\$" "$package/agents/$role.md" || { printf '%s research shell capability is missing in %s\n' "$role" "$package"; exit 1; }
done done
fi fi
expected_skill_count=$source_skill_count expected_skill_count=$source_skill_count
@@ -79,7 +80,7 @@ for shell in powershell bash; do
grep -q 'bash .*flashbang.sh' "$package/$file" grep -q 'bash .*flashbang.sh' "$package/$file"
fi fi
if [ "$client" = codex ]; then if [ "$client" = codex ]; then
[ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\]$/\1/p' "$package/$file" | sort)" = $'SessionStart\nStop\nStop\nUserPromptSubmit' ] [ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\][[:space:]]*$/\1/p' "$package/$file" | sort)" = $'PreToolUse\nSessionStart\nStop\nStop\nUserPromptSubmit' ]
! grep -q 'flashbang-if-input' "$package/$file" ! grep -q 'flashbang-if-input' "$package/$file"
! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file" ! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file"
grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file" grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file"
@@ -1,3 +1,4 @@
import os
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
@@ -53,6 +54,8 @@ class UserCustomizationTests(unittest.TestCase):
(home / '.my-ai-configuration/instructions/codex.md').read_text()) (home / '.my-ai-configuration/instructions/codex.md').read_text())
def test_add_credentials_installs_a_client_scoped_helper(self): def test_add_credentials_installs_a_client_scoped_helper(self):
if os.name != 'nt':
self.skipTest('The OS credential store is supported on Windows only.')
powershell = shutil.which('powershell') or shutil.which('pwsh') powershell = shutil.which('powershell') or shutil.which('pwsh')
if powershell is None: if powershell is None:
self.skipTest('PowerShell is unavailable.') self.skipTest('PowerShell is unavailable.')
+1 -1
View File
@@ -10,7 +10,7 @@ For Codex, read the listed rule path directly. For Claude, invoke the matching `
Changes to or reviews of code, scripts, hooks, tests, infrastructure, integrations, or executable configuration: `rules/security/index.md` / `rules-security`. Skip it for prose-only changes. Changes to or reviews of code, scripts, hooks, tests, infrastructure, integrations, or executable configuration: `rules/security/index.md` / `rules-security`. Skip it for prose-only changes.
Focused security: authentication, authorization, sessions, tokens, permissions, tenants => `rules/security/references/auth.md` / `rules-security-auth`; HTTP, requests, serialization, endpoints => `api.md` / `rules-security-api`; browser, cookies, redirects, XSS, CSRF => `web.md` / `rules-security-web`; databases, queries, persistence, sensitive data => `data.md` / `rules-security-data`; files, uploads, archives, paths, processes, IPC, deserialization => `files.md` / `rules-security-files`; network, URLs, proxies, TLS, SSRF => `network.md` / `rules-security-network`; cryptography, secrets, keys, credentials => `crypto.md` / `rules-security-crypto`; dependencies, packages, plugins, builds, deployment, CI => `supply-chain.md` / `rules-security-supply-chain`; active security testing => `testing.md` / `rules-security-testing`. Focused security (Codex paths under `rules/security/references/`): authentication, authorization, sessions, tokens, permissions, tenants => `auth.md` / `rules-security-auth`; inbound HTTP endpoints, request handling, API (de)serialization => `api.md` / `rules-security-api`; browser, cookies, redirects, XSS, CSRF => `web.md` / `rules-security-web`; databases, queries, persistence, sensitive data => `data.md` / `rules-security-data`; files, uploads, archives, paths, processes, IPC, XML parsing, deserialization => `files.md` / `rules-security-files`; outbound HTTP calls, webhooks, URL fetching, proxies, TLS, SSRF => `network.md` / `rules-security-network`; cryptography, secrets, keys, credentials => `crypto.md` / `rules-security-crypto`; dependencies, packages, plugins, builds, deployment, CI => `supply-chain.md` / `rules-security-supply-chain`; LLM calls, prompts, agents, tools, retrieval/RAG => `ai.md` / `rules-security-ai`; active security testing => `testing.md` / `rules-security-testing`.
Technology indexes: Angular => `rules/angular/index.md` / `rules-angular`; C#/.NET => `rules/csharp/index.md` / `rules-csharp`; Java/JVM => `rules/java/index.md` / `rules-java`; TypeScript/ECMAScript => `rules/typescript/index.md` / `rules-typescript`; UI/UX => `rules/ui-ux/index.md` / `rules-ui-ux`; WPF/XAML/MVVM => `rules/wpf/index.md` / `rules-wpf`. Technology indexes: Angular => `rules/angular/index.md` / `rules-angular`; C#/.NET => `rules/csharp/index.md` / `rules-csharp`; Java/JVM => `rules/java/index.md` / `rules-java`; TypeScript/ECMAScript => `rules/typescript/index.md` / `rules-typescript`; UI/UX => `rules/ui-ux/index.md` / `rules-ui-ux`; WPF/XAML/MVVM => `rules/wpf/index.md` / `rules-wpf`.
+4 -4
View File
@@ -1,14 +1,14 @@
# Angular Rules # Angular Rules
For Angular work, open the focused topic rule that matches the change. Apply the security and accessibility rule whenever browser-facing behavior is affected. For Angular work, open the focused topic rule that matches the change. Angular code is TypeScript: load the matching TypeScript topic rules (`rules/typescript/index.md` / `rules-typescript`) as well. Load the security and accessibility rule when the change renders untrusted content, binds HTML or URLs, configures HTTP security or tokens, or builds interactive controls.
| Topic | Codex rule | Claude skill | | Topic | Codex rule | Claude skill |
| --- | --- | --- | | --- | --- | --- |
| Components and state | `references/components-and-state.md` | `rules-angular-components-and-state` | | Components, change detection, signals, and DOM access | `references/components-and-state.md` | `rules-angular-components-and-state` |
| Templates and styling | `references/templates-and-styling.md` | `rules-angular-templates-and-styling` | | Templates and styling | `references/templates-and-styling.md` | `rules-angular-templates-and-styling` |
| RxJS | `references/rxjs.md` | `rules-angular-rxjs` | | RxJS | `references/rxjs.md` | `rules-angular-rxjs` |
| Services and HTTP | `references/services-and-http.md` | `rules-angular-services-and-http` | | Dependency injection, services, and HTTP | `references/services-and-http.md` | `rules-angular-services-and-http` |
| Forms and routing | `references/forms-and-routing.md` | `rules-angular-forms-and-routing` | | Forms and routing | `references/forms-and-routing.md` | `rules-angular-forms-and-routing` |
| Security and accessibility | `references/security-and-accessibility.md` | `rules-angular-security-and-accessibility` | | Security and accessibility | `references/security-and-accessibility.md` | `rules-angular-security-and-accessibility` |
| Performance | `references/performance.md` | `rules-angular-performance` | | Performance | `references/performance.md` | `rules-angular-performance` |
| Testing and architecture | `references/testing-and-architecture.md` | `rules-angular-testing-and-architecture` | | Testing, architecture, and package versions | `references/testing-and-architecture.md` | `rules-angular-testing-and-architecture` |
@@ -1,13 +1,18 @@
# Angular Components, Change Detection, and Signals
Apply these rules when creating or changing Angular components, directives, signal state, change detection, or DOM access.
## Components ## Components
* Prefer standalone components, directives, and pipes for new work. Avoid introducing `NgModule` unless the existing architecture requires it. * Prefer standalone components, directives, and pipes for new work. Avoid introducing `NgModule` unless the existing architecture requires it.
* Keep components small; move substantial business logic to a focused service or domain layer. * Keep components small; move substantial business logic to a focused service or domain layer.
* Keep dependencies explicit and follow the feature architecture. Avoid god components, god services, unnecessary wrappers, and abstractions without a concrete need. * Keep dependencies explicit and follow the feature architecture. Avoid god components, god services, unnecessary wrappers, and abstractions without a concrete need.
* Use `ChangeDetectionStrategy.OnPush` unless there is a concrete reason not to. * Use `ChangeDetectionStrategy.OnPush` unless there is a concrete reason not to, in both zone.js and zoneless applications.
* Keep component state minimal and prefer immutable state updates. * Keep component state minimal and prefer immutable state updates.
* Avoid direct mutation of shared state. * Avoid direct mutation of shared state.
* Keep inputs and outputs strongly typed. * Keep inputs and outputs strongly typed.
* Prefer signal-based inputs and outputs when consistent with the project. * In new code on Angular 19+, use `input()` and `input.required()`, `output()` (an `OutputEmitterRef`, not a signal), `model()` for intended two-way bindings, and signal queries (`viewChild`, `viewChildren`, `contentChild`, `contentChildren`). Keep `@Input`, `@Output`, and decorator queries only where the surrounding code uses them.
* Use the `host` object in component metadata instead of `@HostBinding` and `@HostListener` in new code.
* Avoid unnecessary two-way binding. * Avoid unnecessary two-way binding.
* Avoid unnecessary component-to-component coupling. * Avoid unnecessary component-to-component coupling.
* Prefer explicit data flow from parent to child and explicit events upward. * Prefer explicit data flow from parent to child and explicit events upward.
@@ -15,6 +20,12 @@
* Use lifecycle hooks only when required. * Use lifecycle hooks only when required.
* Avoid complex initialization logic inside constructors. * Avoid complex initialization logic inside constructors.
## Change Detection
* Check whether the application uses zone.js or is zoneless: new applications are zoneless by default since Angular 21 (`provideZonelessChangeDetection`, stable since 20.2). Do not migrate between the two as a side effect of another task.
* In zoneless applications, change template-bound state only through signals, `markForCheck`, the `async` pipe, or template event handlers. Mutating plain fields in `setTimeout` or promise callbacks does not update the view.
* Do not add `NgZone` APIs (`onStable`, `onMicrotaskEmpty`, `runOutsideAngular`) for rendering logic; use `afterNextRender` or `afterRenderEffect` for DOM work after rendering.
## Signals and State ## Signals and State
* Prefer signals for local and synchronous reactive state. * Prefer signals for local and synchronous reactive state.
@@ -22,5 +33,16 @@
* Keep signals private when external mutation is not intended, and expose readonly state where practical. * Keep signals private when external mutation is not intended, and expose readonly state where practical.
* Avoid circular signal dependencies. * Avoid circular signal dependencies.
* Use `effect` only for actual side effects, not as a replacement for normal data flow. Keep effects small and deterministic, and clean up resources they create. * Use `effect` only for actual side effects, not as a replacement for normal data flow. Keep effects small and deterministic, and clean up resources they create.
* Use `linkedSignal` (Angular 20+) for writable state that resets when a source changes, instead of an `effect` that writes signals.
* For parameter-driven reads, use `httpResource`, `resource`, or `rxResource` (stable since Angular 22; experimental in 19 to 21, so use them there only if the project already does). Use RxJS for event streams, cancellation semantics, and multi-step flows; convert with `toSignal` at the component edge, in an injection context. Never perform writes or mutations through resources.
* Do not use global state unless multiple unrelated parts of the application genuinely need it. * Do not use global state unless multiple unrelated parts of the application genuinely need it.
* Do not introduce a state-management library without a clear requirement. * Do not introduce a state-management library without a clear requirement.
## DOM and Browser APIs
* Prefer Angular APIs and declarative templates over direct DOM manipulation.
* Use `Renderer2` only when direct rendering abstraction is actually needed.
* Avoid accessing globals directly when it harms testability or SSR compatibility.
* When the application uses SSR, guard `window`, `document`, `localStorage`, and similar browser-only APIs with `isPlatformBrowser`, or run DOM access in `afterNextRender` or `afterRenderEffect`, which run only in the browser.
* Clean up event listeners, observers and timers.
* Avoid layout thrashing in performance-sensitive code.
@@ -1,11 +1,13 @@
# Angular Forms and Routing
Apply these rules when building Angular forms, validation, routes, guards, or resolvers.
## Forms ## Forms
* Prefer reactive forms for non-trivial forms. * Follow the form approach the project uses. For non-trivial forms, use typed reactive forms (`FormGroup`, `FormControl`, `NonNullableFormBuilder`; `nonNullable` controls where reset should restore the initial value) and never `Untyped*` classes in new code.
* Keep forms strongly typed. * Signal forms (`@angular/forms/signals`) are stable since Angular 22. Use them for new forms only when the project is on 22+ and has adopted them; do not migrate existing forms unasked.
* Avoid untyped forms.
* Keep validation rules centralized and reusable where practical. * Keep validation rules centralized and reusable where practical.
* Validate on both client and server where required. * Client-side validation is user experience; the server must validate every submission. Never treat client-side validation as a security boundary.
* Never treat client-side validation as a security boundary.
* Keep form state separate from domain state when useful. * Keep form state separate from domain state when useful.
* Avoid large components that combine layout, validation, persistence and business logic. * Avoid large components that combine layout, validation, persistence and business logic.
* Display validation errors consistently. * Display validation errors consistently.
@@ -14,11 +16,13 @@
## Routing ## Routing
* Keep route definitions explicit and predictable. * Keep route definitions explicit and predictable.
* Prefer lazy loading for larger feature areas. * Prefer lazy loading for larger feature areas with `loadComponent` or `loadChildren` pointing to standalone route arrays.
* Write new guards and resolvers as functions (`CanActivateFn`, `ResolveFn`); keep class-based guards where the project uses them, since they remain supported.
* Use `withComponentInputBinding()` to bind route parameters to component inputs where the project enables it.
* Avoid loading large feature bundles eagerly without need. * Avoid loading large feature bundles eagerly without need.
* Use route guards only for navigation behavior, not as a security boundary. * Use route guards only for navigation behavior, not as a security boundary.
* Authorization must still be enforced on the backend. * Authorization must still be enforced on the backend.
* Keep resolvers focused. * Keep resolvers focused.
* Avoid expensive work during navigation unless required. * Avoid expensive work during navigation unless required.
* Keep route parameters strongly typed at application boundaries where practical. * Route and query parameters arrive as `string | null`. Parse and validate them before use and treat them as untrusted input.
* Do not rely on client-side routing state for sensitive authorization decisions. * Do not rely on client-side routing state for sensitive authorization decisions.
+12 -30
View File
@@ -1,33 +1,15 @@
# Angular Performance
Apply these rules when optimizing Angular rendering, loading, bundle size, or hydration.
## Performance ## Performance
* Use `OnPush`. Apply the TypeScript performance rule for general measurement, allocation, and bundle guidance, and these Angular-specific levers on top. Measure before optimizing.
* Use stable tracking in loops.
* Avoid unnecessary change detection triggers.
* Avoid repeated expensive template calculations.
* Avoid unnecessary subscriptions.
* Avoid unnecessary DOM rendering.
* Lazy-load large features and heavy dependencies where appropriate.
* Avoid large initial bundles.
* Avoid importing full libraries when only a small part is required.
* Avoid unnecessary deep cloning.
* Avoid unnecessary object and array recreation in hot paths.
* Keep state updates targeted.
* Avoid unnecessary global state updates.
* Measure bundle size and runtime performance before micro-optimizing.
* Prefer architectural improvements over template-level micro-optimizations.
## Performance Priority * Use `OnPush` and signals so change detection touches only what changed (see the components rule for zoneless applications).
* Defer heavy, below-the-fold, or rarely used template parts with `@defer` and an explicit trigger such as `on viewport` or `on interaction`, with a placeholder that reserves layout space.
Prioritize Angular performance work in this order: * Use `NgOptimizedImage` (`ngSrc`) for images, with explicit dimensions and `priority` for the largest contentful image.
* Lazy-load routes and heavy dependencies, and keep the bundle budgets in `angular.json` enforced; do not raise a budget to make a build pass without approval.
* Application architecture * For server-side rendering, use `provideClientHydration()`, which includes incremental hydration since Angular 22; do not add the deprecated `withIncrementalHydration()` there. Use event replay instead of re-rendering on hydration.
* Network and API behavior * Use `runOutsideAngular` only in zone.js applications, for high-frequency events that must not trigger change detection.
* Bundle size and lazy loading * Keep RxJS and signal updates targeted; avoid global state updates for local changes.
* State architecture
* Change detection
* Rendering and DOM complexity
* RxJS and subscription behavior
* Memory allocations
* CPU micro-optimizations
Never optimize based purely on assumptions.
+4
View File
@@ -1,3 +1,7 @@
# Angular RxJS
Apply these rules when writing or changing RxJS streams, subscriptions, or signal and observable interop in Angular.
## RxJS ## RxJS
* Use RxJS for asynchronous streams, events and complex reactive flows. * Use RxJS for asynchronous streams, events and complex reactive flows.
@@ -1,37 +1,20 @@
# Angular Security and Accessibility
Apply these rules when Angular code renders untrusted content, binds HTML or URLs, configures HTTP security, handles tokens, or builds interactive UI. Load `rules-security-web` for the general browser rules and `rules-ui-ux-visual-and-accessibility` for general accessibility; this file adds only Angular specifics.
## Security ## Security
* Treat all external data as untrusted. * Use `bypassSecurityTrust*` only as the shared web security rule allows: compile-time constants, developer-controlled values, or output of a maintained sanitizer, with the reason in a comment.
* Never bypass Angular sanitization without a verified reason. * `[innerHTML]` is sanitized, but `ElementRef.nativeElement.innerHTML` and `Renderer2.setProperty(el, 'innerHTML', ...)` bypass sanitization; never use them with untrusted content.
* Avoid direct DOM manipulation. * Never build templates from user data or compile templates at runtime.
* Avoid `innerHTML` with untrusted content. * Angular's `HttpClient` sends the XSRF token (configured with `withXsrfConfiguration`) only on mutating requests to relative or same-origin URLs. APIs on another origin that use cookie authentication need their own CSRF protection.
* Avoid `bypassSecurityTrust*` unless explicitly required and the input is fully controlled. * Prefer `autoCsp` (build option, inline scripts only, not with SSR) or a nonce through `ngCspNonce` or `CSP_NONCE` over relaxing the Content Security Policy.
* Never expose secrets in frontend code. * Never place server secrets in the Angular application. Handle session tokens as the shared web security rule defines: prefer `HttpOnly` cookies or a backend-for-frontend; tokens the app must hold stay in memory, and refresh tokens never go into `localStorage` or `sessionStorage`.
* Never store sensitive credentials in the Angular application. * Route guards and hidden UI are navigation aids, not authorization; enforce authorization on the backend.
* Do not rely on frontend checks for authorization.
* Enforce authentication and authorization on the backend.
* Avoid leaking sensitive information through logs or error messages.
* Use secure cookie or token handling according to the application's authentication architecture.
* Avoid storing sensitive tokens in insecure browser storage without a deliberate security decision.
* Do not disable security controls for convenience.
## DOM and Browser APIs
* Prefer Angular APIs and declarative templates over direct DOM manipulation.
* Use `Renderer2` only when direct rendering abstraction is actually needed.
* Avoid accessing globals directly when it harms testability or SSR compatibility.
* Consider SSR and hydration compatibility for browser-specific code.
* Guard access to `window`, `document`, `localStorage` and similar browser-only APIs when SSR is supported.
* Clean up event listeners, observers and timers.
* Avoid layout thrashing in performance-sensitive code.
## Accessibility ## Accessibility
* Use semantic HTML. * Bind ARIA attributes with `[attr.aria-*]`, and keep accessible names and states synchronized with signal or component state.
* Preserve keyboard navigation. * Use Angular CDK accessibility utilities (`FocusTrap`, `LiveAnnouncer`, `FocusMonitor`) instead of hand-written focus management, or `@angular/aria` where the project uses it.
* Ensure interactive elements are actually interactive elements. * After router navigation, move focus to the main content or heading and update the page title (`Title` service or route `title`).
* Do not replace buttons with clickable `div` elements. * Do not replace buttons or links with clickable `div` elements.
* Provide labels for form controls.
* Maintain visible focus behavior.
* Use ARIA only when native HTML semantics are insufficient.
* Avoid unnecessary custom widgets.
* Keep accessible names and states synchronized with UI state.
@@ -1,9 +1,13 @@
# Angular Dependency Injection, Services, and HTTP
Apply these rules when creating Angular services, configuring dependency injection, or calling HTTP APIs.
## Dependency Injection ## Dependency Injection
* Prefer Angular dependency injection for application services. * Prefer Angular dependency injection for application services.
* Keep injected dependencies minimal. * Keep injected dependencies minimal.
* Avoid service locator patterns. * Avoid service locator patterns.
* Prefer `inject()` where it improves readability and is consistent with the project. * Prefer the `inject()` function over constructor parameter injection, as the Angular style guide recommends since v20; keep constructor injection where the surrounding code consistently uses it.
* Do not inject services that are not used. * Do not inject services that are not used.
* Scope services intentionally. * Scope services intentionally.
* Prefer application-wide singletons only for truly shared stateless or coordinated state. * Prefer application-wide singletons only for truly shared stateless or coordinated state.
@@ -27,13 +31,13 @@
* Keep API access centralized and strongly typed. * Keep API access centralized and strongly typed.
* Prefer dedicated API clients or data-access services. * Prefer dedicated API clients or data-access services.
* Do not use `any` for API responses. * Do not use `any` for API responses. The type parameter of `HttpClient.get<T>()` or `httpResource<T>()` is a compile-time assertion, not validation.
* Treat all server responses as untrusted at runtime. * Treat all server responses as `unknown` until validated, as in the TypeScript runtime-safety rule. Validate them with a schema or parser at the data-access boundary before they drive authorization, persistence, navigation, or rendering.
* Validate external data when the contract is security- or correctness-critical.
* Keep DTOs separate from domain models when their responsibilities differ. * Keep DTOs separate from domain models when their responsibilities differ.
* Avoid duplicate API calls. * Avoid duplicate API calls.
* Cache only when the invalidation strategy is clear. * Cache only when the invalidation strategy is clear.
* Avoid manual URL string construction when typed helpers or centralized endpoints are available. * Avoid manual URL string construction when typed helpers or centralized endpoints are available.
* Configure HTTP with `provideHttpClient(withInterceptors([...]), withFetch())` and functional interceptors in new code, not `HttpClientModule` or `HTTP_INTERCEPTORS` classes.
* Use interceptors only for cross-cutting concerns. * Use interceptors only for cross-cutting concerns.
* Do not put unrelated business logic into HTTP interceptors. * Do not put unrelated business logic into HTTP interceptors.
* Handle cancellation where appropriate. * Handle cancellation where appropriate.
@@ -1,18 +1,19 @@
# Angular Templates and Styling
Apply these rules when writing Angular templates, control flow, or component styles.
## Templates ## Templates
* Keep expressions short and readable. * Keep expressions short and readable.
* Do not execute expensive methods from templates. * Reading signals and `computed` values in templates is correct. Do not call other methods that compute or allocate from templates; use `computed` or a pure pipe instead.
* Avoid function calls in templates when their result can be derived or cached.
* Avoid complex conditions directly in markup. * Avoid complex conditions directly in markup.
* Prefer derived state in TypeScript over repeated template expressions. * Prefer derived state in TypeScript over repeated template expressions.
* Use Angular control flow syntax such as `@if`, `@for` and `@switch` for new code. * Use Angular control flow syntax such as `@if`, `@for` and `@switch` for new code.
* Always provide stable tracking for repeated collections. * In `@for`, track a stable unique key such as `track item.id`; use `$index` only for static lists that never reorder. For legacy `*ngFor`, supply `trackBy`.
* Avoid deeply nested template structures. * Avoid deeply nested template structures.
* Split large templates into focused components when it improves maintainability. * Split large templates into focused components when it improves maintainability.
* Avoid unnecessary DOM elements. * Avoid unnecessary DOM elements.
* Use semantic HTML. * Use semantic HTML and native elements before custom implementations; see the accessibility section of the Angular security and accessibility rule.
* Prefer native HTML behavior before custom implementations.
* Keep accessibility in mind when choosing elements and interactions.
## Styling ## Styling
@@ -1,5 +1,14 @@
# Angular Testing and Architecture
Apply these rules when writing Angular tests, organizing features, or changing Angular package versions.
## Testing ## Testing
Apply the TypeScript testing rule for general test design, and these Angular specifics.
* Use the project's test runner. New CLI projects use Vitest since Angular 21; Karma remains supported, so do not migrate runners as part of another task.
* In zoneless tests, configure `TestBed` with `provideZonelessChangeDetection()` and use `await fixture.whenStable()` instead of `fakeAsync` and `tick`, which require zone.js.
* Set signal inputs with `fixture.componentRef.setInput()`. Test HTTP with `provideHttpClient()` plus `provideHttpClientTesting()` and `HttpTestingController`. Prefer Angular CDK component harnesses for interacting with material or CDK components.
* Test behavior, not implementation details. * Test behavior, not implementation details.
* Prefer focused component tests. * Prefer focused component tests.
* Test critical user interactions. * Test critical user interactions.
@@ -26,29 +35,10 @@
* Avoid exposing internal implementation details across feature boundaries. * Avoid exposing internal implementation details across feature boundaries.
* Prefer local ownership of state and logic. * Prefer local ownership of state and logic.
## Code Quality ## Code Quality and Dependencies
* Use strict TypeScript settings. Apply the TypeScript rules for types, style, and dependency review, plus these Angular specifics.
* Avoid `any`.
* Avoid unnecessary type assertions.
* Avoid non-null assertions unless safety is guaranteed.
* Prefer modern, readable syntax.
* Use descriptive names.
* Avoid vague names such as `data`, `item`, `value` or `temp` when better names exist.
* Remove dead code.
* Remove unused imports and dependencies.
* Add comments only for non-obvious decisions or public contracts.
* Treat Angular, TypeScript and lint warnings seriously.
* Do not suppress diagnostics without a concrete reason.
* Prefer correctness, security and maintainability over cleverness.
## Dependency Rules
* Treat Angular compiler, template type-checking, and lint warnings seriously; do not suppress them without a concrete reason.
* Keep all `@angular/*` packages on the same major and minor version, and upgrade them with `ng update` so migrations run.
* Prefer Angular and browser platform capabilities before adding third-party libraries. * Prefer Angular and browser platform capabilities before adding third-party libraries.
* Do not add dependencies without a clear benefit.
* Avoid libraries that duplicate existing framework functionality.
* Avoid abandoned or poorly maintained packages.
* Keep Angular package versions aligned.
* Do not mix incompatible Angular package versions.
* Respect the existing lockfile and package manager.
* Avoid unrelated dependency upgrades.
@@ -2,10 +2,11 @@
Apply these rules when designing public APIs, service boundaries, or application architecture. Apply these rules when designing public APIs, service boundaries, or application architecture.
* Give APIs explicit, strongly typed contracts. Keep trusted internal paths free of checks already done at the boundary. * Give APIs explicit, strongly typed contracts. On trusted internal paths, do not repeat format or argument validation the boundary already performed. Authorization, resource ownership, and tenant scoping are never "already done": enforce them at the operation that accesses the data.
* Separate request models from persistence and domain models. Bind only fields the caller may set, and project only fields the caller may read. * Separate request models from persistence and domain models. Bind only fields the caller may set, and project only fields the caller may read.
* Authenticate and authorize before accessing protected resources. Keep the decision close to the protected operation, enforce resource ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable. * Authenticate and authorize before accessing protected resources. Keep the decision close to the protected operation, enforce resource ownership and tenant scope in the data access path, not only in the UI or route layer, and fail closed when identity, ownership, or policy evaluation is unavailable.
* Use explicit, bounded pagination for potentially large collections. * Use explicit, bounded pagination for potentially large collections.
* Treat EF Core `DbContext` as a short-lived, non-thread-safe unit of work: scoped per request in web apps, created through `IDbContextFactory<T>` per operation in desktop apps and background services, never shared across threads or held as a singleton. Use `AsNoTracking` for read-only queries, and use `FromSql` or `FromSqlInterpolated` instead of concatenating into `FromSqlRaw`.
* Keep application, domain, and infrastructure concerns separate. Avoid cross-layer coupling and service-locator patterns. * Keep application, domain, and infrastructure concerns separate. Avoid cross-layer coupling and service-locator patterns.
* Use dependency injection when substitution or lifecycle management is needed. Keep dependencies explicit and avoid excessive constructor dependencies. * Use dependency injection when substitution or lifecycle management is needed. Keep dependencies explicit and avoid excessive constructor dependencies.
* Preserve established project and public API conventions unless a concrete compatibility or correctness issue requires a change. * Preserve established project and public API conventions unless a concrete compatibility or correctness issue requires a change.
@@ -5,9 +5,11 @@ Apply these rules when adding or changing asynchronous APIs, background work, or
* Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks. * Use asynchronous APIs for genuinely asynchronous I/O; do not wrap synchronous work in unnecessary tasks.
* Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock. * Keep asynchronous operations async through the call chain. Avoid `.Result`, `.Wait()`, and other synchronous waits that can block threads or deadlock.
* Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller. * Accept and propagate `CancellationToken` through work that can take meaningful time or be cancelled by its caller.
* Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use an appropriate queue or concurrency limiter when work must be throttled. * In library and service code, use `ConfigureAwait(false)` or follow the project's CA2007 setting. In UI code (WPF view models and event handlers) use plain `await` so the continuation resumes on the UI thread.
* Use `ValueTask` only when profiling supports it and its usage contract is clear; otherwise prefer `Task`. * Bound concurrency for large or unbounded workloads. Avoid creating a task per item or using uncontrolled `Task.WhenAll`; use `Parallel.ForEachAsync` with `MaxDegreeOfParallelism` (.NET 6+) or `SemaphoreSlim.WaitAsync` with the release in `finally`.
* Use `ValueTask` only when profiling supports it. Await a `ValueTask` exactly once, never concurrently, and never read `.Result` before it completes; otherwise prefer `Task`.
* Keep shared state safe under concurrent access and preserve cancellation and exception behavior when coordinating tasks. Prefer immutable messages or synchronization primitives with clear ownership over unsynchronized shared mutation. * Keep shared state safe under concurrent access and preserve cancellation and exception behavior when coordinating tasks. Prefer immutable messages or synchronization primitives with clear ownership over unsynchronized shared mutation.
* Avoid holding locks across `await`, blocking thread-pool threads, and starting background work whose lifetime is detached from its owner. * For synchronous locks on .NET 9+, prefer `System.Threading.Lock` over locking on `object`. Use `SemaphoreSlim` when a critical section contains `await`. Avoid blocking thread-pool threads and starting background work whose lifetime is detached from its owner.
* For producer/consumer work, apply backpressure and bound buffered items so a fast producer cannot exhaust memory. * For producer/consumer work, use `Channel.CreateBounded` so a fast producer gets backpressure and cannot exhaust memory.
* Retry only transient failures, with bounded attempts and delay. Preserve idempotency and cancellation, and avoid multiplying retries across nested layers. * Retry only transient failures, with bounded attempts and delay, in one layer only. Prefer the project's resilience library (`Microsoft.Extensions.Http.Resilience` or Polly v8) over hand-written loops. Preserve idempotency and cancellation.
* Create `HttpClient` through `IHttpClientFactory` or reuse a long-lived instance with `SocketsHttpHandler.PooledConnectionLifetime`; never create one per request.
@@ -2,8 +2,8 @@
Apply these rules when editing C# syntax, class structure, and everyday code organization. Apply these rules when editing C# syntax, class structure, and everyday code organization.
* Follow current C# and .NET conventions and the style already used in the project. * Follow the style already used in the project. Before using newer syntax, check `TargetFramework` and `LangVersion`, including `Directory.Build.props`: `net10.0` defaults to C# 14, while .NET Framework 4.x defaults to C# 7.3, where records, file-scoped namespaces, collection expressions, primary constructors, and the `field` keyword are unavailable. Do not raise `LangVersion` without approval.
* Prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity. * Within the available language version, prefer direct, readable code over clever control flow, hidden magic, or outdated verbosity.
* Keep classes, methods, and responsibilities focused. Use descriptive names and established domain terms; avoid unexplained abbreviations. * Keep classes, methods, and responsibilities focused. Use descriptive names and established domain terms; avoid unexplained abbreviations.
* Prefer composition over inheritance. Use inheritance only for a real substitutable contract, and seal types when extension is not intended. * Prefer composition over inheritance. Use inheritance only for a real substitutable contract, and seal types when extension is not intended.
* Avoid unnecessary wrappers, abstractions, reflection, runtime type checks, and global mutable state. * Avoid unnecessary wrappers, abstractions, reflection, runtime type checks, and global mutable state.
@@ -6,8 +6,8 @@ Apply these rules when handling external input, failures, logs, or sensitive inf
* Validate size, range, format, and allowed values before expensive parsing or allocation. Keep validation consistent with downstream business and security constraints. * Validate size, range, format, and allowed values before expensive parsing or allocation. Keep validation consistent with downstream business and security constraints.
* Fail fast for invalid arguments or impossible state. Do not use exceptions for routine control flow or swallow unexpected exceptions. * Fail fast for invalid arguments or impossible state. Do not use exceptions for routine control flow or swallow unexpected exceptions.
* Preserve useful exception context without exposing secrets, personal data, or internal details in logs, APIs, or user-facing errors. * Preserve useful exception context without exposing secrets, personal data, or internal details in logs, APIs, or user-facing errors.
* Use structured logging and avoid excessive logging, especially in hot paths. Never log credentials, tokens, or sensitive payloads. * Use structured logging with message templates and named placeholders, not string interpolation (CA2254); use `[LoggerMessage]` source-generated methods in hot paths. Never log credentials, tokens, or sensitive payloads.
* Dispose owned resources correctly, including on failure paths. * Dispose owned resources with `using` or `await using` (for `IAsyncDisposable`), including on failure paths. Do not dispose dependencies injected by the container.
* Use narrow exception handling around the operation that can fail. Do not catch broadly merely to retry, continue with partial state, or convert failures into success. * Use narrow exception handling around the operation that can fail. Do not catch broadly merely to retry, continue with partial state, or convert failures into success.
* Avoid returning different error detail to unauthenticated callers when it would disclose whether protected accounts, records, or resources exist. * Avoid returning different error detail to unauthenticated callers when it would disclose whether protected accounts, records, or resources exist.
* Treat resource limits as part of safe error handling: cap request bodies, page sizes, query complexity, decompressed data, collection sizes, parser depth, and other attacker-controlled work. * Treat resource limits as part of safe error handling: cap request bodies, page sizes, query complexity, decompressed data, collection sizes, parser depth, and other attacker-controlled work.
+9 -10
View File
@@ -1,13 +1,12 @@
# C# Security # C# Security
Apply these rules when implementing or reviewing security-sensitive .NET code. Load the matching shared security rule for the affected API, identity, data, file, network, cryptographic, or dependency boundary as well. Apply these rules when implementing or reviewing security-sensitive .NET code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only .NET specifics.
* Use parameterized database APIs. If a query identifier or sort expression cannot be parameterized, select it from a fixed allowlist; never concatenate untrusted input into SQL. * Use parameters with ADO.NET (`SqlParameter`) and EF Core (`FromSql` or `FromSqlInterpolated`, never concatenation into `FromSqlRaw` or `ExecuteSqlRaw`). Select dynamic identifiers and sort expressions from a fixed allowlist.
* For file access, canonicalize the resolved path and verify it remains inside the authorized root. Account for reparse points and symlinks when the attacker can affect directory contents. * Resolve file paths with `Path.GetFullPath(Path.Combine(root, input))` and require the result to start with the root plus a trailing directory separator, using `StringComparison.OrdinalIgnoreCase` on Windows. Account for reparse points and symlinks when the attacker can affect directory contents.
* For process execution, avoid a shell. Pass executable and arguments separately using APIs supported by the target framework, validate each argument, and restrict executable paths. * For process execution, set `ProcessStartInfo.UseShellExecute = false` explicitly (its default is `true` on .NET Framework), start the executable by absolute path, and pass arguments through `ArgumentList` (.NET Core 2.1+). On .NET Framework, build `Arguments` with correct Windows argument escaping instead of ad-hoc quoting. Never pass untrusted arguments to `.bat` or `.cmd` targets, because `cmd.exe` re-parses them; validate each argument against an allowlist.
* Deserialize into explicit DTOs or allowlisted types. Avoid unsafe polymorphic type activation and unbounded object graphs for untrusted data. * Deserialize into explicit DTOs or allowlisted types. Prefer `System.Text.Json` and allow polymorphism only through registered `[JsonDerivedType]` types. For untrusted data never use `BinaryFormatter` (it throws since .NET 9; do not restore it through the unsupported compatibility package), `NetDataContractSerializer`, `SoapFormatter`, `LosFormatter`, or Newtonsoft.Json `TypeNameHandling` other than `None`. Bound object-graph depth and size.
* Apply timeouts to regular expressions that evaluate untrusted input and prefer patterns with predictable complexity. * For regular expressions on untrusted input on .NET 7+, use `RegexOptions.NonBacktracking` when the pattern needs no backreferences or lookarounds; otherwise pass an explicit match timeout, because there is none by default. Declare regexes with `[GeneratedRegex]` on .NET 7+.
* Keep secrets in an approved secret store or protected configuration source. Never embed them in assemblies, client bundles, or source. * Use `RandomNumberGenerator` for security values and `CryptographicOperations.FixedTimeEquals` for comparing secrets. Never return `true` unconditionally from `ServerCertificateCustomValidationCallback` or `RemoteCertificateValidationCallback`.
* Use platform TLS and established cryptographic APIs. Do not create custom cryptography or disable certificate validation; use cryptographically secure randomness for security tokens. * Keep secrets in user secrets during development and in a secret store such as Azure Key Vault in deployed environments; use ASP.NET Core Data Protection for application-level protection of payloads. Never embed secrets in assemblies or client bundles.
* Use framework output encoding and safe APIs for HTML, XML, and other interpreters. Do not build executable markup or queries from untrusted strings. * Use Razor's automatic encoding and `System.Text.Encodings.Web` encoders; avoid `Html.Raw` and `MarkupString` with untrusted content.
* Review security-sensitive changes with tests for rejected, malformed, oversized, unauthenticated, and cross-tenant inputs, as applicable.
@@ -2,8 +2,9 @@
Apply these rules when changing tests, package references, analyzers, or build diagnostics. Apply these rules when changing tests, package references, analyzers, or build diagnostics.
* Write deterministic behavior-based tests. Avoid coupling assertions to private call order, implementation details, current time, or uncontrolled external services. * Write deterministic behavior-based tests. Avoid coupling assertions to private call order, implementation details, or uncontrolled external services. Inject `TimeProvider` (.NET 8+) instead of reading `DateTime.Now`, and use `FakeTimeProvider` from `Microsoft.Extensions.TimeProvider.Testing` in tests.
* Make code testable through clear contracts and dependencies; do not add production hooks or abstractions solely for tests without a concrete need. * Make code testable through clear contracts and dependencies; do not add production hooks or abstractions solely for tests without a concrete need.
* Prefer the .NET BCL and existing supported packages over new libraries when they solve the problem adequately. * Prefer the .NET BCL and existing supported packages over new libraries when they solve the problem adequately.
* Treat compiler, analyzer, and nullable warnings seriously. Suppress a diagnostic only for a specific, documented reason and narrow the suppression to the affected code. * Treat compiler, analyzer, and nullable warnings seriously. Suppress a diagnostic only for a specific, documented reason and narrow the suppression to the affected code.
* Include analyzers in the verification of the changed path. * Build the changed projects with analyzers enabled and warnings visible. Where the project sets `TreatWarningsAsErrors`, `AnalysisLevel`, or `EnforceCodeStyleInBuild`, never lower them to get a green build, and respect `.editorconfig`.
* Add or update packages through Central Package Management (`Directory.Packages.props`) when the repository uses it. Keep NuGetAudit enabled; it audits transitive packages by default only for `net10.0`+ projects, so prefer `NuGetAuditMode` `all` for older targets when the project allows it.
@@ -5,7 +5,7 @@ Apply these rules when designing type contracts, choosing collection shapes, or
* Prefer strongly typed models over `object`, `dynamic`, loosely typed dictionaries, or string-based contracts. * Prefer strongly typed models over `object`, `dynamic`, loosely typed dictionaries, or string-based contracts.
* Write null-safe code: enable nullable reference types where supported, model nullability accurately, and check nullable values before dereferencing them. Avoid null-forgiving operators unless a nearby invariant proves the value cannot be null. * Write null-safe code: enable nullable reference types where supported, model nullability accurately, and check nullable values before dereferencing them. Avoid null-forgiving operators unless a nearby invariant proves the value cannot be null.
* Prefer concrete collection types for internal parameters, properties, and local APIs when the contract does not need abstraction. * Prefer concrete collection types for internal parameters, properties, and local APIs when the contract does not need abstraction.
* Expose collection interfaces such as `IReadOnlyList<T>`, `IEnumerable<T>`, `IDictionary<TKey, TValue>`, or `ICollection<T>` only when their capability is part of an intentional boundary or public contract. * At public boundaries, return read-only shapes (`IReadOnlyList<T>`, `IReadOnlyDictionary<TKey, TValue>`, or `ReadOnlyCollection<T>`) and accept the least capable interface the method needs (`IEnumerable<T>` or `IReadOnlyCollection<T>`). Expose mutable interfaces such as `IList<T>` or `IDictionary<TKey, TValue>` only when callers must mutate. Consider `FrozenDictionary` or `FrozenSet` (.NET 8+) for read-mostly lookups.
* Choose collection types based on lookup, ordering, mutation, and iteration needs. Pre-size collections only when expected capacity is known and material. * Choose collection types based on lookup, ordering, mutation, and iteration needs. Pre-size collections only when expected capacity is known and material.
* Avoid large mutable structs and direct exposure of mutable internal collections. * Avoid large mutable structs and direct exposure of mutable internal collections.
* Prefer immutable data and readonly state where practical, while preserving established API and serialization contracts. * Prefer immutable data and readonly state where practical, while preserving established API and serialization contracts.
+1 -1
View File
@@ -1,4 +1,4 @@
## Decision Rule # Decision Rule
* Gather evidence from the repository, available tooling, and current technical sources before making technical decisions. * Gather evidence from the repository, available tooling, and current technical sources before making technical decisions.
* Make technical implementation and code-style decisions independently when existing code, reliable documentation, or established standards provide sufficient evidence and the decision is reversible. * Make technical implementation and code-style decisions independently when existing code, reliable documentation, or established standards provide sufficient evidence and the decision is reversible.
+1
View File
@@ -10,5 +10,6 @@ For Java or JVM work, open only the topic rules relevant to the task. Follow the
| Async work and concurrency | `references/async-and-concurrency.md` | `rules-java-async-and-concurrency` | | Async work and concurrency | `references/async-and-concurrency.md` | `rules-java-async-and-concurrency` |
| Performance | `references/performance.md` | `rules-java-performance` | | Performance | `references/performance.md` | `rules-java-performance` |
| Security | `references/security.md` | `rules-java-security` | | Security | `references/security.md` | `rules-java-security` |
| Spring Boot and Spring Security | `references/spring.md` | `rules-java-spring` |
| Validation, errors, and logging | `references/safety-and-errors.md` | `rules-java-safety-and-errors` | | Validation, errors, and logging | `references/safety-and-errors.md` | `rules-java-safety-and-errors` |
| Tests, dependencies, and build diagnostics | `references/testing-and-dependencies.md` | `rules-java-testing-and-dependencies` | | Tests, dependencies, and build diagnostics | `references/testing-and-dependencies.md` | `rules-java-testing-and-dependencies` |
@@ -2,7 +2,7 @@
Apply these rules when designing public APIs, service boundaries, or application structure. Apply these rules when designing public APIs, service boundaries, or application structure.
* Give APIs explicit request, response, and error contracts. Validate external input at the boundary without scattering redundant checks through trusted internal code. * Give APIs explicit request, response, and error contracts. Validate external input at the boundary without scattering redundant format checks through trusted internal code; authorization, ownership, and tenant scoping are never such redundant checks.
* Separate transport models, domain models, and persistence entities. Accept only fields callers may set and return only fields they may read. * Separate transport models, domain models, and persistence entities. Accept only fields callers may set and return only fields they may read.
* Authorize the specific resource and operation where data is accessed or changed. Preserve ownership and tenant scope across alternate paths and background work. * Authorize the specific resource and operation where data is accessed or changed. Preserve ownership and tenant scope across alternate paths and background work.
* Bound payloads, page sizes, query complexity, and operation cost. Use pagination or streaming for potentially large results. * Bound payloads, page sizes, query complexity, and operation cost. Use pagination or streaming for potentially large results.
@@ -3,10 +3,13 @@
Apply these rules when changing executors, threads, futures, background work, or shared state. Apply these rules when changing executors, threads, futures, background work, or shared state.
* Choose synchronous, asynchronous, platform-thread, or virtual-thread execution for the actual workload and target Java release. Virtual threads suit many blocking I/O tasks; they do not accelerate CPU work. * Choose synchronous, asynchronous, platform-thread, or virtual-thread execution for the actual workload and target Java release. Virtual threads suit many blocking I/O tasks; they do not accelerate CPU work.
* Create one virtual thread per task (`Executors.newVirtualThreadPerTaskExecutor()`); never pool virtual threads. Limit downstream concurrency with a `Semaphore`, not with a fixed pool size.
* On JDK 21 to 23, blocking inside `synchronized` pins the carrier thread; prefer `ReentrantLock` on hot blocking paths there. JDK 24+ (JEP 491) removes that pinning, but native frames and class initialization still pin.
* Do not cache expensive objects in `ThreadLocal` when running on virtual threads. On JDK 25+, prefer `ScopedValue` (final, JEP 506) for request-scoped context.
* Keep task lifetime owned by a request, service, or scoped executor. Close or shut down owned executors and handle completion, failure, timeout, and cancellation. * Keep task lifetime owned by a request, service, or scoped executor. Close or shut down owned executors and handle completion, failure, timeout, and cancellation.
* Propagate interruption and cancellation. When catching `InterruptedException` without rethrowing it, restore the interrupt flag and stop work safely; do not turn cancellation into success. * Propagate interruption and cancellation. When catching `InterruptedException` without rethrowing it, restore the interrupt flag and stop work safely; do not turn cancellation into success.
* Bound queues, fan-out, and downstream calls. Virtual threads reduce thread cost but do not remove database, network, memory, or rate limits. * Bound queues, fan-out, and downstream calls. Virtual threads reduce thread cost but do not remove database, network, memory, or rate limits.
* Protect shared mutable state with clear ownership or suitable concurrency primitives. Do not assume `volatile` makes compound actions atomic. * Protect shared mutable state with clear ownership or suitable concurrency primitives. Do not assume `volatile` makes compound actions atomic.
* Avoid blocking joins inside unrelated executor tasks when they can exhaust a bounded pool. Use `CompletableFuture` or parallel streams only when their execution context and failure behavior are understood. * Avoid blocking joins inside unrelated executor tasks when they can exhaust a bounded pool. Use `CompletableFuture` or parallel streams only when their execution context and failure behavior are understood.
* Keep retries limited to transient failures, with bounded attempts and delay. Preserve idempotency and avoid retry multiplication across layers. * Keep retries limited to transient failures, with bounded attempts and delay. Preserve idempotency and avoid retry multiplication across layers.
* Use preview concurrency APIs only when the project explicitly enables them for its target release. * Use preview concurrency APIs only when the project explicitly enables them for its target release; `StructuredTaskScope` is still a preview API in JDK 25.
@@ -7,5 +7,5 @@ Apply these rules when handling external input, failures, resources, or logs.
* Use try-with-resources for owned `AutoCloseable` resources. Keep ownership explicit and do not close resources supplied by a caller unless the contract says so. * Use try-with-resources for owned `AutoCloseable` resources. Keep ownership explicit and do not close resources supplied by a caller unless the contract says so.
* Catch only failures the current layer can handle. Preserve exception causes and useful context; do not swallow failures, catch broadly to continue with partial state, or use exceptions for routine control flow. * Catch only failures the current layer can handle. Preserve exception causes and useful context; do not swallow failures, catch broadly to continue with partial state, or use exceptions for routine control flow.
* Preserve interruption and cancellation during error handling. Timeouts and retries need bounds and must not silently turn failure into success. * Preserve interruption and cancellation during error handling. Timeouts and retries need bounds and must not silently turn failure into success.
* Use structured logs where the project supports them. Never log credentials, tokens, personal data, or unbounded payloads; avoid excessive logging in hot paths. * Use structured logs where the project supports them. Never log credentials, tokens, personal data, or unbounded payloads; avoid excessive logging in hot paths. Pass untrusted values as parameters, never as the log format string, and strip or encode CR/LF in them unless the log format is structured.
* Return safe, consistent error information. Do not disclose protected resource existence or internal details to unauthorized callers. * Return safe, consistent error information. Do not disclose protected resource existence or internal details to unauthorized callers.
+9 -8
View File
@@ -1,12 +1,13 @@
# Java Security # Java Security
Apply these rules to security-sensitive Java code. Load the focused shared security rule for each affected boundary as well. Apply these rules to security-sensitive Java code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only Java specifics, and the Spring rule covers Spring Boot and Spring Security.
* Validate untrusted input before expensive work and authorize the specific resource and operation. Java types and client-side validation do not establish trust.
* Use parameterized database APIs such as `PreparedStatement`. Select dynamic identifiers or sort expressions from a fixed allowlist; never concatenate untrusted data into SQL. * Use parameterized database APIs such as `PreparedStatement`. Select dynamic identifiers or sort expressions from a fixed allowlist; never concatenate untrusted data into SQL.
* Resolve file paths against an authorized root and account for symlinks and replacement races when an attacker can change the filesystem. Limit file size and processing work. * Resolve file paths with `root.resolve(input).normalize()` and check containment with `Path.startsWith(root)`, never `String.startsWith`, which accepts `/data/app2` for `/data/app`. `normalize()` does not resolve symlinks; use `toRealPath()` when links matter and the file exists, and account for replacement races. Check every `ZipEntry` name the same way. Limit file size and processing work.
* Use `ProcessBuilder` with an executable and separate arguments; avoid shell interpretation. Restrict executable paths and validate attacker-controlled arguments. * Use `ProcessBuilder` with an absolute executable path and separate arguments; avoid shell interpretation. On Windows, the argument list is flattened into one command line that the target re-parses, and `.bat` or `.cmd` targets run through `cmd.exe`; never pass untrusted arguments to them, and validate attacker-controlled arguments against an allowlist.
* Deserialize into explicit allowed types. Avoid native Java serialization and unrestricted polymorphic type activation for untrusted data; bound input size and nesting. * Parse untrusted XML with DTDs disabled (`http://apache.org/xml/features/disallow-doctype-decl` set to `true`), or, where DTDs are required, with external entities and external DTD and schema access disabled (`XMLConstants.ACCESS_EXTERNAL_DTD` and `ACCESS_EXTERNAL_SCHEMA` set to `""`, `XMLConstants.FEATURE_SECURE_PROCESSING` enabled). Apply this to every factory that reads untrusted XML: `DocumentBuilderFactory`, `SAXParserFactory`, `XMLInputFactory`, `TransformerFactory`, `SchemaFactory`, and JAXB unmarshallers.
* Use the platform's maintained TLS, cryptographic, and secure-random APIs. Do not disable certificate validation or build custom cryptography. * Deserialize into explicit allowed types and bound input size and nesting. Avoid native Java serialization for untrusted data; where it is unavoidable, install an `ObjectInputFilter` allowlist. With Jackson, never enable default typing (`activateDefaultTyping`) or `@JsonTypeInfo(use = Id.CLASS)` for untrusted input; use `Id.NAME` with registered subtypes or a strict `PolymorphicTypeValidator`. Spring Boot 4 uses Jackson 3 (`tools.jackson.*` packages; annotations stay in `com.fasterxml.jackson.annotation`). Load YAML with SnakeYAML 2.x or a `SafeConstructor`. Never evaluate untrusted SpEL, OGNL, or JNDI names.
* Keep secrets out of source, logs, exception messages, and serialized responses. Use approved secret storage and clear ownership for sensitive data. * Use the platform's maintained TLS, cryptographic, and secure-random APIs with the parameters in the shared cryptography rule. Always specify the full `Cipher` transformation, for example `AES/GCM/NoPadding`, because `Cipher.getInstance("AES")` means ECB. Use `SecureRandom`, never `java.util.Random`, for security values, and `MessageDigest.isEqual` for constant-time comparison. Never install trust-all `X509TrustManager` or `HostnameVerifier` implementations. Do not rely on the Security Manager; JDK 24+ disables it permanently.
* Use context-appropriate encoding for HTML, XML, and other interpreters. Test rejected, malformed, oversized, unauthorized, and cross-tenant inputs where relevant. * For outbound URLs, parse with `java.net.URI` (the `URL` constructors are deprecated since JDK 20) and check every resolved `InetAddress` (`isLoopbackAddress`, `isLinkLocalAddress`, `isSiteLocalAddress`, `isAnyLocalAddress`, `isMulticastAddress`); these miss IPv6 unique-local `fc00::/7`, carrier-grade NAT `100.64.0.0/10`, and IPv4-mapped IPv6, so check those explicitly. Keep `java.net.http.HttpClient` on its default `Redirect.NEVER` or revalidate every hop.
* For regular expressions on untrusted input, bound the input length first and avoid nested or overlapping quantifiers, because `java.util.regex` has no timeout; use RE2/J for untrusted patterns.
* Encode output with the template engine's automatic escaping or the OWASP Java Encoder for the exact context; never build HTML, XML, LDAP, or JPQL from untrusted strings.
+12
View File
@@ -0,0 +1,12 @@
# Java Spring Boot and Spring Security
Apply these rules when changing Spring Boot configuration, Spring Security, Spring MVC or WebFlux endpoints, Spring Data repositories, or Actuator exposure. Follow the project's Spring Boot and Spring Security versions; Spring Boot 4 and Spring Framework 7 are current.
* Deny by default: end the `authorizeHttpRequests` chain with `.anyRequest().authenticated()` (or `denyAll()`) and list public routes explicitly with `permitAll`.
* Keep CSRF protection enabled for browser clients that authenticate with cookies or sessions. Disable it only for stateless token-authenticated APIs, and say why in the configuration.
* Expose only `health` and `info` Actuator endpoints publicly. Never expose `env`, `heapdump`, `threaddump`, `configprops`, `loggers`, `mappings`, or `beans` without authentication; `heapdump` and `env` leak secrets. Prefer a separate management port.
* Enforce method security (`@PreAuthorize` with `@EnableMethodSecurity`) on service methods reachable from non-HTTP entry points such as messaging, schedulers, or batch jobs.
* Bind requests to dedicated DTOs, never directly to JPA entities with `@RequestBody` or `@ModelAttribute`, to prevent mass assignment. Validate DTOs with Bean Validation (`@Valid`).
* Use parameter binding in JPQL, HQL, and `@Query` native SQL; never concatenate untrusted input into query strings. Select dynamic sort properties from an allowlist before building `Sort` objects.
* Store passwords through a `DelegatingPasswordEncoder` with an encoder that meets the shared cryptography rule, for example `Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8()`, and upgrade legacy hashes on login.
* Keep secrets out of `application.yml` and profiles in the repository; bind them from environment variables or a secret store.
+4 -3
View File
@@ -17,11 +17,12 @@ Load only the topic rules that match the affected boundary.
| Topic | Codex rule | Claude skill | | Topic | Codex rule | Claude skill |
| --- | --- | --- | | --- | --- | --- |
| Authentication, authorization, sessions, tokens, permissions, and tenants | `references/auth.md` | `rules-security-auth` | | Authentication, authorization, sessions, tokens, permissions, and tenants | `references/auth.md` | `rules-security-auth` |
| HTTP, requests, serialization, and endpoints | `references/api.md` | `rules-security-api` | | Inbound HTTP endpoints, request handling, and API (de)serialization | `references/api.md` | `rules-security-api` |
| Browsers, cookies, redirects, XSS, and CSRF | `references/web.md` | `rules-security-web` | | Browsers, cookies, redirects, XSS, and CSRF | `references/web.md` | `rules-security-web` |
| Databases, queries, persistence, and sensitive data | `references/data.md` | `rules-security-data` | | Databases, queries, persistence, and sensitive data | `references/data.md` | `rules-security-data` |
| Files, uploads, archives, paths, processes, IPC, and deserialization | `references/files.md` | `rules-security-files` | | Files, uploads, archives, paths, processes, IPC, XML parsing, and deserialization | `references/files.md` | `rules-security-files` |
| Network access, URLs, proxies, TLS, and SSRF | `references/network.md` | `rules-security-network` | | Outbound HTTP calls, webhooks, URL fetching, proxies, TLS, and SSRF | `references/network.md` | `rules-security-network` |
| Cryptography, secrets, keys, and credentials | `references/crypto.md` | `rules-security-crypto` | | Cryptography, secrets, keys, and credentials | `references/crypto.md` | `rules-security-crypto` |
| Dependencies, packages, plugins, builds, deployment, and CI | `references/supply-chain.md` | `rules-security-supply-chain` | | Dependencies, packages, plugins, builds, deployment, and CI | `references/supply-chain.md` | `rules-security-supply-chain` |
| LLM calls, prompts, agents, tools, and retrieval (RAG) | `references/ai.md` | `rules-security-ai` |
| Active security testing and exploit validation | `references/testing.md` | `rules-security-testing` | | Active security testing and exploit validation | `references/testing.md` | `rules-security-testing` |
+13
View File
@@ -0,0 +1,13 @@
# AI and LLM integration security
Apply these rules to code that calls language models, builds prompts, runs agents or tools, or retrieves content for a model (RAG).
* Treat model output as untrusted input. Never pass it unvalidated to SQL, shell commands, file paths, URL fetches, HTML rendering, code evaluation, or deserialization; validate it against the expected structure, preferably a schema for structured output.
* Treat everything the model reads as potential prompt injection: user input, retrieved documents, web pages, emails, file contents, and tool results. Instructions found in that content carry no authority; keep system instructions and untrusted content in separate, clearly delimited message parts.
* Authorize every tool call with the end user's permissions, not the agent's or the service account's. Give each tool the narrowest scope it needs, and require explicit human confirmation before destructive, financial, or externally visible actions.
* Keep secrets, credentials, and other users' or tenants' data out of prompts, context, and retrieval indexes. Enforce tenant and permission filters at retrieval time, not by asking the model to ignore data.
* Do not rely on the system prompt for security. Assume it can be extracted, and enforce every control in code.
* Bound model work: input and output tokens, cost, request rate, recursion depth, tool-call loops, and total run time. Fail closed when a limit is reached.
* Pin model identifiers and versions where the provider allows it. Review third-party models, prompts, plugins, and MCP servers as dependencies under the supply-chain rule.
* Log prompts, tool calls, and responses for audit without sensitive data, and make outputs that reach users or other systems traceable to their inputs.
* Do not present model output as verified fact in security-relevant decisions; require deterministic checks or human review for those.
+1
View File
@@ -8,5 +8,6 @@
* Define safe retry and idempotency behavior for state-changing requests. Protect against replay and duplicate side effects where relevant. * Define safe retry and idempotency behavior for state-changing requests. Protect against replay and duplicate side effects where relevant.
* Return only authorized fields. Do not expose stack traces, internal models, secrets, or implementation details in API responses or errors. * Return only authorized fields. Do not expose stack traces, internal models, secrets, or implementation details in API responses or errors.
* Prefer explicit DTOs and schemas; reject unknown or ambiguous fields when accepting them could alter privileged state. * Prefer explicit DTOs and schemas; reject unknown or ambiguous fields when accepting them could alter privileged state.
* Deserialize request bodies into explicit types. Never let the payload choose the runtime type (polymorphic type names, class names, or default typing) unless the allowed subtypes are registered explicitly; bound body size and nesting depth. Parse XML with external entities and DTDs disabled.
* Keep authorization, validation, serialization, and error responses consistent with the published schema and supported clients. * Keep authorization, validation, serialization, and error responses consistent with the published schema and supported clients.
* Test malformed, oversized, unauthenticated, unauthorized, cross-user, cross-tenant, and duplicate requests within the user's requested scope. * Test malformed, oversized, unauthenticated, unauthorized, cross-user, cross-tenant, and duplicate requests within the user's requested scope.
+6 -2
View File
@@ -1,11 +1,15 @@
# Authentication and authorization security # Authentication and authorization security
* Use established authentication standards and password hashing; never store plaintext or reversibly encrypted passwords. * Use established authentication standards and password hashing; never store plaintext or reversibly encrypted passwords.
* Use a maintained password-hashing scheme configured for the deployment environment. Never create password schemes or reduce work factors merely to improve latency. * Hash passwords with Argon2id (at least m=19 MiB, t=2, p=1); if unavailable, scrypt (N=2^17, r=8, p=1), bcrypt (cost 10 or higher; inputs beyond 72 bytes are truncated, so reject or pre-handle longer passwords), or PBKDF2-HMAC-SHA256 with at least 600,000 iterations where FIPS compliance requires it (OWASP Password Storage Cheat Sheet). Never create password schemes or reduce work factors merely to improve latency; rehash on login when parameters are raised.
* Enforce authorization server-side for every sensitive operation and verify resource ownership and tenant boundaries. * Enforce authorization server-side for every sensitive operation and verify resource ownership and tenant boundaries.
* Deny by default and check authorization on every request, including background jobs and alternate API paths. Do not trust role or identity values supplied by clients. * Deny by default and check authorization on every request, including background jobs and alternate API paths. Do not trust role or identity values supplied by clients.
* Use least-privilege roles, short-lived sessions or tokens, secure renewal and revocation, and invalidate credentials after password, recovery, or privilege changes. * Use least-privilege roles, short-lived sessions or tokens, secure renewal and revocation, and invalidate credentials after password, recovery, or privilege changes.
* Validate token algorithm, issuer, audience, signature, expiry, and any required not-before or key identifier claims before trusting it. Reject unexpected algorithms and malformed claims. * Validate JWTs as RFC 8725 recommends:
* Fix the accepted algorithms on the server, bind each key to exactly one algorithm, and never take the algorithm from the token header; reject `none`.
* Validate signature, issuer, audience, expiry, and not-before, with bounded clock skew. Use explicit typing (`typ`, for example `at+jwt`) or distinct audiences to prevent substituting one token kind for another, such as an ID token for an access token.
* Resolve the `kid` header only against a trusted key set, and treat it as untrusted input. Never fetch keys from token-supplied `jku`, `x5u`, or `jwk` headers.
* Signed JWT payloads are readable by anyone; keep sensitive data out of them.
* Protect login, recovery, reset, MFA, and privileged actions against brute force, enumeration, replay, CSRF, and privilege escalation. * Protect login, recovery, reset, MFA, and privileged actions against brute force, enumeration, replay, CSRF, and privilege escalation.
* Store session identifiers securely; rotate them after authentication or privilege changes and invalidate them on logout or account recovery. * Store session identifiers securely; rotate them after authentication or privilege changes and invalidate them on logout or account recovery.
* Test unauthenticated, unauthorized, cross-user, cross-tenant, expired-token, revoked-session, and recovery-flow paths. * Test unauthenticated, unauthorized, cross-user, cross-tenant, expired-token, revoked-session, and recovery-flow paths.
+7 -3
View File
@@ -1,9 +1,13 @@
# Cryptography and secrets security # Cryptography and secrets security
* Never implement custom cryptographic primitives or use obsolete algorithms. * Never implement custom cryptographic primitives. Never use MD5 or SHA-1 for security purposes, DES, 3DES, RC4, ECB mode, or unauthenticated CBC.
* Use maintained platform cryptography with authenticated encryption, secure randomness, and verified signatures and certificates. Use safe, documented parameter choices rather than inventing formats or defaults. * Use maintained platform cryptography with authenticated encryption, secure randomness, and verified signatures and certificates. Minimum choices (as of OWASP and NIST guidance in 2025; check current guidance when starting a project):
* Symmetric encryption: AES-256-GCM with a unique 96-bit nonce per key and message, never reused, or ChaCha20-Poly1305.
* Hashing and MACs: SHA-256 or stronger; HMAC-SHA-256 or stronger.
* Signatures and key exchange: Ed25519, ECDSA or ECDH with P-256 or stronger, or RSA with at least 2048 bits (3072 for keys that must stay secure beyond 2030), with RSA-OAEP or RSA-PSS padding.
* Transport: TLS 1.2 or newer, TLS 1.3 preferred; never disable certificate or hostname validation.
* Keep key generation, storage, access, rotation, revocation, and backup separate from application data where practical. Restrict each key to its intended purpose. * Keep key generation, storage, access, rotation, revocation, and backup separate from application data where practical. Restrict each key to its intended purpose.
* Treat tokens, private keys, connection strings, and credentials as secrets; keep them out of source, URLs, command lines, logs, fixtures, error messages, and frontend code. * Treat tokens, private keys, connection strings, and credentials as secrets; keep them out of source, URLs, command lines, logs, fixtures, and error messages. Keep server-side credentials out of frontend code; browser handling of user session tokens follows the web security rule.
* Use environment-appropriate secret storage, separate environments, and rotate compromised or overexposed credentials. Do not silently fall back to a weaker key or algorithm when configuration is missing. * Use environment-appropriate secret storage, separate environments, and rotate compromised or overexposed credentials. Do not silently fall back to a weaker key or algorithm when configuration is missing.
* Compare secret-derived values with established constant-time APIs when the comparison is security-sensitive. * Compare secret-derived values with established constant-time APIs when the comparison is security-sensitive.
* Do not log plaintext or retain decrypted sensitive data longer than required. Apply secure disposal only where the runtime and data type provide meaningful guarantees. * Do not log plaintext or retain decrypted sensitive data longer than required. Apply secure disposal only where the runtime and data type provide meaningful guarantees.
+2 -1
View File
@@ -5,6 +5,7 @@
* Restrict filesystem permissions to the intended identity and directory. Use safe temporary-file creation and avoid predictable names or permissive shared locations. * Restrict filesystem permissions to the intended identity and directory. Use safe temporary-file creation and avoid predictable names or permissive shared locations.
* Validate upload content using limits and format-aware parsing; do not trust names or client-supplied MIME types. Store untrusted uploads outside executable or public paths. * Validate upload content using limits and format-aware parsing; do not trust names or client-supplied MIME types. Store untrusted uploads outside executable or public paths.
* Limit archive entry count, nesting, total expanded size, and path destinations to prevent traversal and resource exhaustion. * Limit archive entry count, nesting, total expanded size, and path destinations to prevent traversal and resource exhaustion.
* Do not execute uploaded or untrusted files. Avoid shell execution; when a process is required, fix the executable and pass validated arguments through structured process APIs. * Do not execute uploaded or untrusted files. Avoid shell execution; when a process is required, fix the executable by absolute path and pass validated arguments through structured process APIs. On Windows, never pass untrusted arguments to `.bat` or `.cmd` targets, because `cmd.exe` re-parses them.
* Treat local files, IPC, and deserialized input as untrusted at relevant boundaries. Use explicit deserialization types and bound depth, size, and processing time. * Treat local files, IPC, and deserialized input as untrusted at relevant boundaries. Use explicit deserialization types and bound depth, size, and processing time.
* Parse untrusted XML with DTD processing and external entity resolution disabled (XXE); the language rules name the parser settings. Never let serialized input choose arbitrary runtime types.
* Avoid insecure temporary-file handoff and check permissions and ownership before consuming files from shared or attacker-writable locations. * Avoid insecure temporary-file handoff and check permissions and ownership before consuming files from shared or attacker-writable locations.
+7 -5
View File
@@ -1,11 +1,13 @@
# Web and frontend security # Web and frontend security
* Escape or sanitize untrusted content; never inject untrusted HTML or bypass framework sanitization. * Escape or sanitize untrusted content; never inject untrusted HTML. Bypass framework sanitization (for example Angular `bypassSecurityTrust*` or React `dangerouslySetInnerHTML`) only for compile-time constants, developer-controlled values, or the output of a maintained sanitizer, and state the reason in a comment at the call site.
* Encode output for its exact context (HTML, attributes, JavaScript, CSS, or URL). Prefer text APIs and framework-safe templates; use a maintained sanitizer only when rich HTML is required. * Encode output for its exact context (HTML, attributes, JavaScript, CSS, or URL). Prefer text APIs and framework-safe templates; use a maintained sanitizer only when rich HTML is required.
* Protect state-changing browser requests from CSRF where applicable; validate origin or anti-CSRF tokens and do not treat CORS as authorization. * Protect state-changing browser requests from CSRF where applicable; validate origin or anti-CSRF tokens and do not treat CORS as authorization.
* Use `HttpOnly`, `Secure`, and appropriate `SameSite` cookie settings for sensitive sessions. Rotate session IDs after authentication and privilege changes. * Use `HttpOnly`, `Secure`, and appropriate `SameSite` cookie settings for sensitive sessions; session rotation follows the authentication rule.
* Validate redirect targets against an allowlist. Avoid sensitive data in URLs, referrers, browser history, analytics, and error reports. * Validate redirect targets against an allowlist. Avoid sensitive data in URLs, referrers, browser history, analytics, and error reports.
* Apply restrictive Content Security Policy and clickjacking protections where applicable. Do not weaken security headers to accommodate unsafe inline content without a reviewed design. * Apply a restrictive Content Security Policy and clickjacking protection (`frame-ancestors`) where applicable. Do not weaken security headers to accommodate unsafe inline content without a reviewed design.
* Treat frontend code, source maps, and browser storage as visible. Never place secrets there or rely on client-side checks for authorization. * Treat frontend code, source maps, and browser storage as visible, and never rely on client-side checks for authorization.
* Protect state-changing operations against clickjacking and unintended form submissions when relevant; require explicit confirmation for high-impact actions. * Never place server secrets (API keys, client secrets, signing or encryption keys, connection strings) in frontend code, bundles, public runtime configuration, or browser storage.
* For user sessions in browser apps, prefer `HttpOnly` cookies or a backend-for-frontend (BFF) that keeps OAuth tokens on the server. If the browser app must hold tokens, keep access tokens in memory and short-lived, use refresh-token rotation, and never store refresh tokens in `localStorage` or `sessionStorage` (RFC 10017, OAuth 2.0 for Browser-Based Applications). This is the single rule for browser token handling; language and framework rules defer to it.
* Protect state-changing operations against unintended form submissions; require explicit confirmation for high-impact actions.
* Keep dependencies and third-party scripts minimal. Apply integrity and origin controls to externally hosted resources where supported. * Keep dependencies and third-party scripts minimal. Apply integrity and origin controls to externally hosted resources where supported.
@@ -2,11 +2,11 @@
Apply these rules when implementing promises, I/O, streams, subscriptions, timers, or other long-lived work. Apply these rules when implementing promises, I/O, streams, subscriptions, timers, or other long-lived work.
* Handle every rejected promise. Do not leave floating promises; for intentional fire-and-forget work, attach error handling and make its owner and lifetime explicit. * Handle every rejected promise. Do not leave floating promises; for intentional fire-and-forget work, attach error handling and make its owner and lifetime explicit. Where the project uses typescript-eslint, keep `no-floating-promises` and `no-misused-promises` enabled.
* Use `await` when sequencing or error handling depends on completion. Use `Promise.all` only for independent, bounded work that can safely run together. * Use `await` when sequencing or error handling depends on completion. Use `Promise.all` only for independent, bounded work that can safely run together.
* Limit concurrency for large workloads with a queue or limiter. Apply backpressure to streams and producer/consumer flows instead of buffering without a bound. * Limit concurrency for large workloads with a queue or limiter. Apply backpressure to streams and producer/consumer flows instead of buffering without a bound.
* Support cancellation with `AbortSignal` when callers need to stop I/O or long-running work. Propagate it through nested calls and release resources when cancellation occurs. * Support cancellation with `AbortSignal` when callers need to stop I/O or long-running work. Propagate it through nested calls and release resources when cancellation occurs.
* Avoid synchronous blocking and long CPU-bound work on the Node.js event loop or browser main thread. Move substantial CPU work to a worker or split it into bounded tasks when measurements justify it. * Avoid synchronous blocking and long CPU-bound work on the Node.js event loop or browser main thread. Move substantial CPU work to a worker or split it into bounded tasks when measurements justify it.
* Remove event listeners, timers, subscriptions, streams, and abort handlers when their owner is done. Avoid retaining closures or resources beyond their intended lifetime. * Remove event listeners, timers, subscriptions, streams, and abort handlers when their owner is done. Prefer `using` and `await using` with `Symbol.dispose`/`Symbol.asyncDispose` for scoped resources when the target supports them (TypeScript 5.2+; native in Node 24+ and current browsers). Avoid retaining closures or resources beyond their intended lifetime.
* Keep shared mutable state safe and deterministic when asynchronous operations can overlap. Prevent stale responses from overwriting newer state when request ordering matters. * Keep shared mutable state safe and deterministic when asynchronous operations can overlap. Prevent stale responses from overwriting newer state when request ordering matters.
* Retry only failures known to be transient, with bounded attempts and delay. Preserve idempotency and cancellation; avoid multiplying retries across layers. * Retry only failures known to be transient, with bounded attempts and delay. Preserve idempotency and cancellation; avoid multiplying retries across layers.
@@ -2,7 +2,10 @@
Apply these rules when changing package dependencies, module structure, imports, or public exports. Apply these rules when changing package dependencies, module structure, imports, or public exports.
* Follow the project's existing module system consistently; avoid mixing ESM and CommonJS without a compatibility need. * Follow the project's existing module system and `tsconfig` consistently. For new configuration, use `module`/`moduleResolution` `nodenext` for code that Node runs directly (with explicit file extensions in relative imports) and `bundler` for bundled applications; `node`/`node10` resolution is deprecated since TypeScript 6.0.
* Enable `verbatimModuleSyntax` in new configuration and use `import type` for type-only imports.
* When code runs through Node's built-in type stripping (on by default since Node 22.18 and 23.6, stable since 24.12), enable `erasableSyntaxOnly` (TypeScript 5.8+): enums, namespaces with runtime code, parameter properties, and `import =` aliases fail there.
* Avoid mixing ESM and CommonJS without a compatibility need. `require()` of ES modules works by default from Node 20.19 and 22.12; on older runtimes, CommonJS cannot `require` an ES module.
* Keep modules focused and boundaries intentional. Avoid circular dependencies and unnecessary public exports. * Keep modules focused and boundaries intentional. Avoid circular dependencies and unnecessary public exports.
* Separate transport models from domain logic where that boundary exists. Do not leak implementation details through public APIs. * Separate transport models from domain logic where that boundary exists. Do not leak implementation details through public APIs.
* Prefer built-in platform APIs or installed packages before adding a dependency. Keep dependencies minimal, supported, and compatible with the lockfile. * Prefer built-in platform APIs or installed packages before adding a dependency. Keep dependencies minimal, supported, and compatible with the lockfile.
@@ -6,8 +6,8 @@ Apply these rules when handling API payloads, user input, browser data, or other
* Validate untrusted data at system boundaries before storing it, using it for authorization, or passing it to sensitive operations. Use schema validation when external contracts are complex. * Validate untrusted data at system boundaries before storing it, using it for authorization, or passing it to sensitive operations. Use schema validation when external contracts are complex.
* Handle `null` and `undefined` intentionally, and narrow values before use. Avoid implicit coercion and unsafe dynamic property access. * Handle `null` and `undefined` intentionally, and narrow values before use. Avoid implicit coercion and unsafe dynamic property access.
* Prefer allowlists for security-sensitive input. Prevent prototype pollution when merging untrusted objects; avoid unsafe recursive merges and dynamic writes to ordinary object prototypes. * Prefer allowlists for security-sensitive input. Prevent prototype pollution when merging untrusted objects; avoid unsafe recursive merges and dynamic writes to ordinary object prototypes.
* Treat URL, path, header, query, and redirect destinations as untrusted. Server-side fetches must restrict schemes and destinations, validate every redirect, and enforce response size and timeout limits. * Treat URL, path, header, query, and redirect destinations as untrusted; server-side fetches follow the shared network security rule.
* Use framework-safe text binding and automatic output encoding. Avoid `innerHTML`, `dangerouslySetInnerHTML`, and equivalent escape hatches unless sanitized content is required and a maintained sanitizer is applied. * Use framework-safe text binding and automatic output encoding. Avoid `innerHTML`, `dangerouslySetInnerHTML`, and equivalent escape hatches unless sanitized content is required and a maintained sanitizer is applied.
* For cookie-based authentication, preserve secure cookie attributes and the application's CSRF protections. Do not store authentication secrets in browser-accessible storage without an explicit threat model and security design. * For cookie-based authentication, preserve secure cookie attributes and the application's CSRF protections. Handle session tokens as the shared web security rule defines: prefer `HttpOnly` cookies or a backend-for-frontend, keep tokens the app must hold in memory, and never store refresh tokens in `localStorage` or `sessionStorage`.
* Never expose secrets or sensitive data in output, logs, or errors. Client-side validation and route guards do not replace server-side authentication, authorization, or validation. * Never expose secrets or sensitive data in output, logs, or errors. Client-side validation and route guards do not replace server-side authentication, authorization, or validation.
* Bound input size, nesting, parsing work, and response size before processing untrusted JSON or other structured data. * Bound input size, nesting, parsing work, and response size before processing untrusted JSON or other structured data.
+9 -10
View File
@@ -1,13 +1,12 @@
# TypeScript Security # TypeScript Security
Apply these rules when implementing or reviewing security-sensitive TypeScript code. Load the matching shared security rule for the affected API, identity, data, browser, file, network, cryptographic, or dependency boundary as well. Apply these rules when implementing or reviewing security-sensitive TypeScript or JavaScript code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only TypeScript and JavaScript specifics. Runtime validation lives in the runtime-safety rule.
* Validate external data at runtime before using it in authorization decisions, database operations, filesystem access, or privileged actions. A type assertion is not validation. * A type, generic parameter, or assertion is not validation; construct trusted values only after a runtime check.
* Enforce authentication, authorization, tenant scoping, and input validation on the server. Browser checks, hidden controls, route guards, and TypeScript types do not create a security boundary. * Use `crypto.randomUUID()` or `crypto.getRandomValues()` (Node: `node:crypto`) for tokens and security-sensitive identifiers, never `Math.random()`. Compare secrets with `crypto.timingSafeEqual` in Node.
* Keep credentials and private keys on trusted servers. Never embed secrets in frontend bundles, source maps, browser storage, or public runtime configuration. * Run processes with `execFile` or `spawn` and an argument array; never use `exec` or `shell: true` with interpolated input.
* Use cryptographically secure platform randomness for tokens and security-sensitive identifiers. Do not use `Math.random()` for secrets, session values, or authorization codes. * Never pass untrusted strings to `eval`, `new Function`, or the string forms of `setTimeout` and `setInterval`.
* Use parameterized database APIs and allowlists for dynamic identifiers. Avoid constructing SQL, shell commands, HTML, or other interpreted input by string concatenation. * Use `Map` or `Object.create(null)` for untrusted keys, and reject `__proto__`, `constructor`, and `prototype` when merging untrusted objects.
* For server-side URL fetching, restrict protocols and destinations, validate redirects, and bound time, response size, and concurrency to reduce SSRF and resource-exhaustion risk. * Use Trusted Types where the Content Security Policy enforces them, instead of disabling the policy.
* Use the framework's safe output encoding and preserve CSP, TLS, cookie, and CSRF protections. Do not disable these controls to make a request or test pass. * In Node, resolve file paths with `path.resolve(root, input)` and require the result to start with `root + path.sep`; use `fs.realpath` when symlinks matter.
* Review untrusted object merges for prototype pollution, unsafe deserialization, and mass assignment. Copy only fields the caller is allowed to control. * Use the database driver's parameter binding or a query builder's parameterized API; never build SQL with template literals.
* Review dependency additions and upgrades for source, package identity, install scripts, transitive risk, and lockfile changes.
@@ -2,7 +2,8 @@
Apply these rules when defining TypeScript types, public function contracts, or domain data models. Apply these rules when defining TypeScript types, public function contracts, or domain data models.
* Prefer `strict: true`, precise types, and `unknown` for values whose shape has not been validated. Avoid `any`, broad assertions, and non-null assertions that hide uncertainty. * Keep `strict` enabled (the default since TypeScript 6.0; set it explicitly on older versions) and never weaken it to make code compile. Enable `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` for new projects where the codebase allows it.
* Use precise types and `unknown` for values whose shape has not been validated. Avoid `any`, broad assertions, and non-null assertions that hide uncertainty. Use `satisfies` to check a literal against a type without widening it.
* Model variants with discriminated unions and use literal unions for constrained values. Make invalid states difficult to represent. * Model variants with discriminated unions and use literal unions for constrained values. Make invalid states difficult to represent.
* Prefer `readonly` and immutable data when mutation is unnecessary. Use interfaces for implementation contracts or declaration merging; use type aliases for unions and compositions. * Prefer `readonly` and immutable data when mutation is unnecessary. Use interfaces for implementation contracts or declaration merging; use type aliases for unions and compositions.
* Give exported APIs, callbacks, and non-trivial functions explicit contracts; rely on inference for simple local values where it keeps code clearer. * Give exported APIs, callbacks, and non-trivial functions explicit contracts; rely on inference for simple local values where it keeps code clearer.
@@ -1,3 +1,7 @@
# UI Content, Feedback, and Responsiveness
Apply these rules when writing interface text or designing loading, progress, success, and error feedback.
## Content and Language ## Content and Language
* Use plain, concise language. * Use plain, concise language.
@@ -1,3 +1,7 @@
# UI Destructive Actions and Error Prevention
Apply these rules when designing destructive or irreversible actions, defaults, undo, and safeguards against user error.
## Destructive Actions ## Destructive Actions
* Clearly label destructive actions. * Clearly label destructive actions.
+4
View File
@@ -1,3 +1,7 @@
# UI Form Design
Apply these rules when designing form layout, labels, input behavior, and validation messages.
## Forms ## Forms
* Keep forms as short as practical. * Keep forms as short as practical.
@@ -1,3 +1,7 @@
# UI Navigation and Actions
Apply these rules when designing navigation structure, buttons, menus, and primary or secondary actions.
## Navigation ## Navigation
* Navigation must be predictable and consistent. * Navigation must be predictable and consistent.
@@ -1,3 +1,7 @@
# UI Tables, Search, and Dialogs
Apply these rules when designing data tables, search and filtering, or dialogs and modals.
## Tables and Data-Dense Views ## Tables and Data-Dense Views
* Use tables only for genuinely tabular data. * Use tables only for genuinely tabular data.
@@ -1,3 +1,7 @@
# UI Visual Design, Accessibility, and Responsive Layout
Apply these rules when choosing layout, typography, color, focus behavior, accessibility, or responsive behavior.
## Visual Design ## Visual Design
* Prefer modern, clean and restrained visual design. * Prefer modern, clean and restrained visual design.
+3 -3
View File
@@ -1,6 +1,6 @@
# WPF Rules # WPF Rules
For WPF, XAML, or MVVM work, open only the focused topic rules relevant to the change. For WPF, XAML, or MVVM work, open only the focused topic rules relevant to the change. WPF code is C#: load the matching C# topic rules (`rules/csharp/index.md` / `rules-csharp`) for language, async, and API guidance, and the shared security rules (`rules/security/index.md` / `rules-security`) for security-relevant changes.
| Topic | Codex rule | Claude skill | | Topic | Codex rule | Claude skill |
| --- | --- | --- | | --- | --- | --- |
@@ -8,5 +8,5 @@ For WPF, XAML, or MVVM work, open only the focused topic rules relevant to the c
| Commands, async, and threading | `references/commands-and-async.md` | `rules-wpf-commands-and-async` | | Commands, async, and threading | `references/commands-and-async.md` | `rules-wpf-commands-and-async` |
| Collections and XAML | `references/collections-and-xaml.md` | `rules-wpf-collections-and-xaml` | | Collections and XAML | `references/collections-and-xaml.md` | `rules-wpf-collections-and-xaml` |
| Resources and lifecycle | `references/resources-and-lifecycle.md` | `rules-wpf-resources-and-lifecycle` | | Resources and lifecycle | `references/resources-and-lifecycle.md` | `rules-wpf-resources-and-lifecycle` |
| Security and errors | `references/security-and-errors.md` | `rules-wpf-security-and-errors` | | Security, errors, logging, and validation | `references/security-and-errors.md` | `rules-wpf-security-and-errors` |
| Architecture, testing, and performance | `references/architecture-and-quality.md` | `rules-wpf-architecture-and-quality` | | Architecture, dependency injection, testing, and performance | `references/architecture-and-quality.md` | `rules-wpf-architecture-and-quality` |
@@ -1,9 +1,12 @@
# WPF Architecture, Dependency Injection, Testing, and Performance
Apply these rules when structuring a WPF application, wiring dependency injection, testing view models, or optimizing performance. Load the C# rules for language-level guidance.
## Architecture ## Architecture
* Use modern C# and current WPF conventions. Prefer MVVM for non-trivial views and keep code-behind limited to view-specific behavior. * Use the C# version the project targets (see the C# coding-style rule; .NET Framework 4.x WPF apps default to C# 7.3). Prefer MVVM for non-trivial views and keep code-behind limited to view-specific behavior.
* Keep UI, application, and domain logic separate. Avoid business logic in views and direct service access from controls. * Keep UI, application, and domain logic separate. Avoid business logic in views and direct service access from controls.
* Keep dependencies explicit and testable; prefer composition over inheritance and avoid unnecessary abstractions or framework wrappers. * Keep dependencies explicit and testable; prefer composition over inheritance and avoid unnecessary abstractions or framework wrappers.
* Keep presentation, application, domain and infrastructure concerns separated.
* Avoid direct database access from views or ViewModels. * Avoid direct database access from views or ViewModels.
* Avoid direct HTTP access from controls. * Avoid direct HTTP access from controls.
* Keep external integrations behind focused services. * Keep external integrations behind focused services.
@@ -16,13 +19,11 @@
## Dependency Injection ## Dependency Injection
* Use dependency injection where lifecycle management, substitution or testability benefits from it. Follow the C# architecture rule for general dependency injection, plus:
* Avoid service locator patterns.
* Keep constructor dependencies minimal. * Register views and view models as transient unless they hold intentionally shared state; register shared services as singletons only when they are thread-safe and stateless or own deliberately shared state.
* Do not inject dependencies that are not used. * Do not resolve services from `App.Current` or a static container inside view models; inject them.
* Choose service lifetimes intentionally. * Create EF Core contexts per operation through `IDbContextFactory<T>` (see the C# architecture rule).
* Do not make stateful services global without a concrete reason.
* Avoid introducing interfaces solely for dependency injection when no abstraction is needed.
## Testing ## Testing
@@ -37,30 +38,22 @@
## Code Quality ## Code Quality
* Use nullable reference types. Follow the C# coding-style and testing rules, plus:
* Prefer modern, readable C# syntax.
* Avoid unnecessary interfaces and abstractions. * Treat binding errors as defects: check the debugger output or XAML binding failures diagnostics for failed bindings after UI changes.
* Prefer concrete types where no abstraction is required.
* Use descriptive names.
* Remove dead code.
* Add comments only for non-obvious decisions or public contracts.
* Treat compiler, analyzer and binding warnings seriously.
* Do not suppress warnings without a concrete reason.
* Prefer correctness, responsiveness, security and maintainability over cleverness.
## Performance ## Performance
* Keep the UI thread responsive. * Keep the UI thread responsive.
* Minimize visual tree depth. * Minimize visual tree depth.
* Keep virtualization enabled. * Keep virtualization enabled (see the virtualization section of the collections rule).
* Avoid unnecessary bindings. * Avoid unnecessary bindings.
* Avoid unnecessary converters. * Avoid unnecessary converters.
* Avoid unnecessary resource lookups. * Avoid unnecessary resource lookups.
* Avoid unnecessary property change notifications. * Avoid unnecessary property change notifications.
* Avoid frequent full collection refreshes. * Avoid frequent full collection refreshes.
* Avoid loading large datasets eagerly. * Avoid loading large datasets eagerly.
* Avoid loading large images at full resolution when unnecessary. * Load images as the images section of the resources rule defines, and freeze `Freezable` objects where practical.
* Freeze `Freezable` objects where practical.
* Reuse immutable resources where appropriate. * Reuse immutable resources where appropriate.
* Avoid unnecessary animations. * Avoid unnecessary animations.
* Avoid high-frequency timers on the UI thread. * Avoid high-frequency timers on the UI thread.
@@ -1,11 +1,15 @@
# WPF Collections, XAML, Layout, and Virtualization
Apply these rules when binding collections, writing XAML, building layouts, or rendering large lists.
## Collections ## Collections
* Use `ObservableCollection<T>` only when collection change notifications are required. * Use `ObservableCollection<T>` only when collection change notifications are required.
* Do not use `ObservableCollection<T>` as a general-purpose collection. * Do not use `ObservableCollection<T>` as a general-purpose collection.
* Use `List<T>` or other suitable collections for non-observable internal data. * Use `List<T>` or other suitable collections for non-observable internal data.
* Avoid replacing entire observable collections when incremental updates are sufficient. * Use incremental `Add` and `Remove` for small changes. For bulk changes, assign a new collection instance or raise a single `Reset`; never raise multi-item `Add`, `Remove`, or `Replace` notifications to WPF bindings, because `ListCollectionView` throws `NotSupportedException` for range actions.
* Avoid thousands of individual collection notifications when a bulk update is more appropriate. * Wrap sort and filter changes in `ICollectionView.DeferRefresh()`.
* Keep collection mutations on the correct thread. * Mutate bound collections on the UI thread. Use `BindingOperations.EnableCollectionSynchronization` only when off-thread mutation is unavoidable.
* Avoid exposing mutable internal collections unnecessarily. * Avoid exposing mutable internal collections unnecessarily.
* Prefer read-only views where consumers should not modify data. * Prefer read-only views where consumers should not modify data.
@@ -35,15 +39,10 @@
* Avoid fixed sizes unless the design requires them. * Avoid fixed sizes unless the design requires them.
* Prefer responsive sizing with `Auto` and `*`. * Prefer responsive sizing with `Auto` and `*`.
* Avoid layout configurations that cause excessive measure/arrange passes. * Avoid layout configurations that cause excessive measure/arrange passes.
* Be careful with large visual trees inside scrolling containers. * Be careful with large visual trees inside scrolling containers; see the virtualization section.
* Avoid disabling virtualization accidentally.
## Virtualization ## Virtualization
* Keep UI virtualization enabled for large collections. * Keep UI virtualization enabled for large collections and use `VirtualizingPanel.VirtualizationMode="Recycling"`.
* Do not use container layouts that disable virtualization without a reason. * These settings silently disable virtualization: `ScrollViewer.CanContentScroll="False"`, grouping without `VirtualizingPanel.IsVirtualizingWhenGrouping="True"`, a non-virtualizing `ItemsPanel` such as `StackPanel` or `WrapPanel`, and placing the list inside a `ScrollViewer` or `StackPanel` that gives it unlimited height.
* Avoid wrapping large virtualized item lists in additional scrolling containers. * Verify virtualization with large data sets, and use paging or incremental loading for very large ones.
* Use virtualizing panels where appropriate.
* Verify virtualization when displaying large data sets.
* Avoid rendering thousands of controls simultaneously.
* Prefer paging, incremental loading or virtualization for very large data sets.
@@ -1,3 +1,7 @@
# WPF Commands, Async, and Threading
Apply these rules when implementing commands, async operations, UI-thread work, or event subscriptions in WPF.
## Commands ## Commands
* Prefer commands over click handlers for ViewModel-driven actions. * Prefer commands over click handlers for ViewModel-driven actions.
@@ -6,8 +10,7 @@
* Keep `CanExecute` logic cheap. * Keep `CanExecute` logic cheap.
* Refresh command availability only when relevant state changes. * Refresh command availability only when relevant state changes.
* Avoid command implementations with hidden side effects. * Avoid command implementations with hidden side effects.
* Handle async commands safely. * Implement async commands with the project's MVVM library (for example CommunityToolkit.Mvvm `AsyncRelayCommand` or `[RelayCommand]`): disable re-entry unless concurrent runs are intended, expose cancellation for long operations, and surface failures to the user.
* Prevent accidental duplicate execution when an async action must not run concurrently.
* Never use `async void` except for true event handlers. * Never use `async void` except for true event handlers.
## Async and Threading ## Async and Threading
@@ -17,8 +20,7 @@
* Do not block the UI thread. * Do not block the UI thread.
* Run I/O asynchronously. * Run I/O asynchronously.
* Move expensive CPU work off the UI thread only when necessary. * Move expensive CPU work off the UI thread only when necessary.
* Marshal UI updates back to the UI thread when required. * Let `await` resume on the UI thread in view models instead of calling the Dispatcher. When marshaling is unavoidable, inject a dispatcher abstraction; never use `Application.Current.Dispatcher` in view models, which breaks testing without a UI thread.
* Keep Dispatcher usage minimal and explicit.
* Do not use the Dispatcher to hide incorrect threading design. * Do not use the Dispatcher to hide incorrect threading design.
* Support `CancellationToken` for cancellable long-running operations. * Support `CancellationToken` for cancellable long-running operations.
* Cancel obsolete work when views or selections change. * Cancel obsolete work when views or selections change.
@@ -27,13 +29,8 @@
## UI Thread ## UI Thread
* Treat the UI thread as a scarce resource. * Treat the UI thread as a scarce resource: no I/O, parsing, serialization, database, or network work on it.
* Keep the interface responsive and do not block the UI thread with I/O or expensive CPU work. Move CPU work off-thread only when needed and marshal UI changes back explicitly. * Batch UI updates and avoid updating bound collections in tight loops; see the collections rule for bulk changes.
* Avoid expensive loops, parsing, serialization, database access or network calls on the UI thread.
* Avoid excessive Dispatcher invocations.
* Batch UI updates where practical.
* Do not update UI-bound collections excessively in tight loops.
* Avoid synchronous waits on background work.
* Keep rendering-related callbacks lightweight. * Keep rendering-related callbacks lightweight.
## Events ## Events
@@ -41,7 +38,7 @@
* Avoid unnecessary event subscriptions. * Avoid unnecessary event subscriptions.
* Unsubscribe from long-lived publishers when required. * Unsubscribe from long-lived publishers when required.
* Prevent memory leaks from event handlers. * Prevent memory leaks from event handlers.
* Prefer weak events where publisher lifetime significantly exceeds subscriber lifetime. * Use `WeakEventManager<TSource, TEventArgs>` where the publisher lives significantly longer than the subscriber.
* Keep event handlers small. * Keep event handlers small.
* Do not use events as hidden global communication channels. * Do not use events as hidden global communication channels.
* Avoid excessive event chaining. * Avoid excessive event chaining.
@@ -1,3 +1,7 @@
# WPF MVVM, Binding, and Properties
Apply these rules when writing view models, data bindings, property notifications, dependency properties, or behaviors.
## MVVM ## MVVM
* Keep ViewModels focused on presentation state and commands. * Keep ViewModels focused on presentation state and commands.
@@ -38,7 +42,7 @@
* Keep dependent property notifications explicit. * Keep dependent property notifications explicit.
* Avoid hidden notification chains that are difficult to reason about. * Avoid hidden notification chains that are difficult to reason about.
* Prefer reusable base implementations only when they reduce duplication without obscuring behavior. * Prefer reusable base implementations only when they reduce duplication without obscuring behavior.
* Do not use reflection-based notification mechanisms unless there is a concrete benefit. * Use the project's MVVM library for notifications. Without one, prefer CommunityToolkit.Mvvm source generators (`[ObservableProperty]`, `[RelayCommand]`; on partial properties from 8.4.1 with C# 14) or a base class using `[CallerMemberName]`. Avoid reflection- or proxy-based notification frameworks unless the project already uses one.
## Dependency Properties ## Dependency Properties
@@ -1,3 +1,7 @@
# WPF Resources, Windows, and Lifecycle
Apply these rules when managing resources and styles, windows and dialogs, navigation, memory, or images in WPF.
## Resources and Styles ## Resources and Styles
* Use shared resources for repeated styles, brushes, templates and dimensions. * Use shared resources for repeated styles, brushes, templates and dimensions.
@@ -16,7 +20,7 @@
* Avoid creating duplicate windows unintentionally. * Avoid creating duplicate windows unintentionally.
* Do not keep hidden windows alive without a reason. * Do not keep hidden windows alive without a reason.
* Separate dialog logic from business logic. * Separate dialog logic from business logic.
* Prefer dialog services when ViewModels need to request user interaction. * Show dialogs through the dialog service described in the MVVM rule.
* Keep ownership relationships explicit. * Keep ownership relationships explicit.
* Avoid application shutdown behavior that depends on accidental window lifetime. * Avoid application shutdown behavior that depends on accidental window lifetime.
@@ -40,7 +44,7 @@
* Cached views * Cached views
* Closures * Closures
* Collection views * Collection views
* Binding-related references * Binding-related references: binding to a CLR property of a source that does not implement `INotifyPropertyChanged` keeps the source alive; bind only to `INotifyPropertyChanged` or dependency-property sources.
* Dispose resources correctly. * Dispose resources correctly.
* Stop timers and background work when no longer needed. * Stop timers and background work when no longer needed.
* Avoid retaining closed windows or unloaded views. * Avoid retaining closed windows or unloaded views.
@@ -49,10 +53,6 @@
## Images and Media ## Images and Media
* Load images at an appropriate resolution. * Decode images at display size with `BitmapImage.DecodePixelWidth` or `DecodePixelHeight`.
* Avoid decoding images significantly larger than their displayed size. * Load file-based images with `BitmapCacheOption.OnLoad` and close the stream, so the file is not locked.
* Release streams and file handles correctly. * Call `Freeze()` on immutable bitmaps and brushes, and cache images only with a clear memory limit.
* Avoid locking image files unintentionally.
* Cache images only when there is a clear memory strategy.
* Avoid keeping large bitmaps alive unnecessarily.
* Prefer frozen image resources when they are immutable.
@@ -1,53 +1,37 @@
# WPF Security, Errors, and Validation
Apply these rules when a WPF application handles secrets, files, processes, untrusted data, exceptions, logging, or input validation. Load the C# security rule and the shared security rules as well.
## Security ## Security
* Treat all external input as untrusted. * A desktop client cannot keep a secret from its user. Never ship service credentials or API keys in the application; use per-user authentication (for example MSAL with the Windows broker) and server-side authorization.
* Never expose secrets, credentials or tokens in UI code. * Store user tokens and other per-user secrets with DPAPI (`ProtectedData` with `DataProtectionScope.CurrentUser`) or Windows Credential Manager, never in plain settings, `app.config`, or files.
* Do not store secrets in configuration files committed to source control. * Follow the C# deserialization rule. Never pass untrusted XAML to `XamlReader.Load` or `XamlReader.Parse`, which can instantiate arbitrary types, and treat clipboard and drag-and-drop payloads from other processes as untrusted input.
* Avoid leaking sensitive information through logs, dialogs or exception messages. * Run with standard user rights; request elevation only for the specific operation that needs it, never for the whole application.
* Validate file paths and external resources.
* Do not execute external processes or files without explicit validation.
* Avoid insecure deserialization.
* Do not weaken TLS, authentication or certificate validation.
* Prefer secure defaults.
* Never disable security controls for convenience.
## File and Process Access ## File and Process Access
* Validate file paths before use. * Resolve and validate file paths as the C# security rule defines before use.
* Avoid assuming files or directories exist. * Do not assume files or directories exist; handle missing files, permissions, and locked files with clear user feedback.
* Handle permissions and locked files gracefully. * Start processes as the C# security rule defines: `UseShellExecute = false` set explicitly (it defaults to `true` on .NET Framework), an absolute executable path, `ArgumentList` on .NET Core 2.1+, and no untrusted arguments to `.bat` or `.cmd` targets.
* Avoid arbitrary shell execution. * Create temporary files with `Path.GetTempFileName` or a private directory and delete them when done.
* Quote and validate process arguments safely.
* Do not concatenate untrusted input into shell commands.
* Avoid elevated privileges unless explicitly required.
* Clean up temporary files when appropriate.
## Error Handling ## Error Handling
* Handle expected errors explicitly. Follow the C# safety and error-handling rule, plus:
* Do not swallow exceptions.
* Preserve useful exception context. * Show users clear, actionable messages instead of raw exception text.
* Avoid showing raw technical exceptions directly to end users. * Wire `Application.DispatcherUnhandledException`, `TaskScheduler.UnobservedTaskException`, and `AppDomain.CurrentDomain.UnhandledException` once at startup to log the failure and decide whether the app can continue.
* Log enough information for diagnosis without exposing sensitive data. * Wrap the body of every `async void` event handler in `try`/`catch`, and do not start fire-and-forget tasks whose exceptions nobody observes.
* Keep user-facing error messages clear and actionable.
* Avoid using exceptions for normal control flow.
* Ensure background exceptions are observed.
## Logging ## Logging
* Use structured logging. Follow the C# logging rule (message templates, no secrets), plus:
* Avoid excessive logging on the UI thread.
* Do not log every property change or binding update. * Do not log every property change or binding update, and keep logging off the UI thread's hot paths.
* Never log secrets, tokens, credentials or sensitive user data.
* Include relevant context for operational failures.
* Avoid logging the same exception repeatedly at multiple layers.
## Validation ## Validation
* Validate user input at the appropriate boundary. * Implement input validation in view models with `INotifyDataErrorInfo` (or the project's MVVM library, such as CommunityToolkit.Mvvm `ObservableValidator`); keep complex validation out of XAML `ValidationRule`s.
* Keep validation logic out of XAML when it becomes complex. * Display validation errors consistently and preserve user input on recoverable errors.
* Prefer reusable validation rules or ViewModel validation for non-trivial cases. * UI validation is not a security boundary; validate again in the domain or backend.
* Display validation errors consistently.
* Do not rely on UI validation as a security boundary.
* Validate again at backend or domain boundaries when required.
* Preserve user input on recoverable errors.