cortexhawk 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/.cortexhawk-team.yml +65 -0
  2. package/CHANGELOG.md +268 -0
  3. package/CLAUDE.md +96 -0
  4. package/LICENSE +21 -0
  5. package/PACKS.md +14 -0
  6. package/README.md +418 -0
  7. package/REGISTRY.md +23 -0
  8. package/agents/architect.md +46 -0
  9. package/agents/brainstormer.md +57 -0
  10. package/agents/code-simplifier.md +56 -0
  11. package/agents/codebase-mapper.md +63 -0
  12. package/agents/copywriter.md +48 -0
  13. package/agents/debugger.md +44 -0
  14. package/agents/designer.md +53 -0
  15. package/agents/devops.md +49 -0
  16. package/agents/docs-manager.md +50 -0
  17. package/agents/fullstack-developer.md +55 -0
  18. package/agents/git-manager.md +63 -0
  19. package/agents/implementer.md +30 -0
  20. package/agents/journal-writer.md +53 -0
  21. package/agents/planner.md +52 -0
  22. package/agents/project-manager.md +50 -0
  23. package/agents/researcher.md +46 -0
  24. package/agents/reviewer.md +63 -0
  25. package/agents/security-auditor.md +92 -0
  26. package/agents/teacher.md +71 -0
  27. package/agents/tester.md +41 -0
  28. package/commands/api-gen.md +17 -0
  29. package/commands/backlog.md +26 -0
  30. package/commands/bootstrap.md +32 -0
  31. package/commands/brainstorm.md +18 -0
  32. package/commands/build.md +16 -0
  33. package/commands/chain.md +46 -0
  34. package/commands/changelog.md +16 -0
  35. package/commands/check.md +40 -0
  36. package/commands/ci.md +32 -0
  37. package/commands/context.md +35 -0
  38. package/commands/debug.md +16 -0
  39. package/commands/deploy.md +16 -0
  40. package/commands/doc.md +15 -0
  41. package/commands/export.md +17 -0
  42. package/commands/journal.md +18 -0
  43. package/commands/learn.md +16 -0
  44. package/commands/map.md +16 -0
  45. package/commands/migrate.md +17 -0
  46. package/commands/monitor.md +16 -0
  47. package/commands/optimize.md +17 -0
  48. package/commands/plan.md +17 -0
  49. package/commands/pulse.md +46 -0
  50. package/commands/refactor.md +16 -0
  51. package/commands/research.md +18 -0
  52. package/commands/review.md +16 -0
  53. package/commands/scan.md +19 -0
  54. package/commands/ship.md +17 -0
  55. package/commands/simplify.md +16 -0
  56. package/commands/task.md +32 -0
  57. package/commands/tdd.md +17 -0
  58. package/commands/test.md +16 -0
  59. package/commands/upgrade.md +27 -0
  60. package/cortexhawk +450 -0
  61. package/hooks/agent-analytics.sh +67 -0
  62. package/hooks/branch-guard.sh +56 -0
  63. package/hooks/codex-dispatcher.sh +84 -0
  64. package/hooks/commit-guard.sh +71 -0
  65. package/hooks/compose.yml +47 -0
  66. package/hooks/dependency-check.sh +56 -0
  67. package/hooks/file-guard.sh +69 -0
  68. package/hooks/hooks.json +46 -0
  69. package/hooks/self-review.sh +71 -0
  70. package/hooks/session-start.sh +132 -0
  71. package/hooks/session-telemetry.sh +60 -0
  72. package/hooks/test-reminder.sh +75 -0
  73. package/install.sh +3805 -0
  74. package/mcp/README.md +37 -0
  75. package/mcp/context7.json +8 -0
  76. package/mcp/puppeteer.json +8 -0
  77. package/mcp/sequential-thinking.json +8 -0
  78. package/modes/default.md +5 -0
  79. package/modes/fast.md +5 -0
  80. package/modes/learn.md +9 -0
  81. package/modes/orchestration.md +5 -0
  82. package/modes/pair.md +10 -0
  83. package/modes/research.md +5 -0
  84. package/modes/review.md +5 -0
  85. package/package.json +32 -0
  86. package/profiles/api.json +27 -0
  87. package/profiles/data.json +23 -0
  88. package/profiles/fullstack.json +27 -0
  89. package/scripts/autodetect-profile.sh +68 -0
  90. package/scripts/benchmark.sh +106 -0
  91. package/scripts/chain-post-save.sh +23 -0
  92. package/scripts/generate-plans-index.sh +50 -0
  93. package/scripts/git-workflow-init.sh +115 -0
  94. package/scripts/install-codex.sh +128 -0
  95. package/scripts/interactive-init.sh +264 -0
  96. package/scripts/post-install-audit.sh +130 -0
  97. package/scripts/validate.sh +214 -0
  98. package/settings.json +90 -0
  99. package/setup.sh +67 -0
  100. package/skills/databases/schema-designer/SKILL.md +54 -0
  101. package/skills/databases/sql-optimizer/SKILL.md +37 -0
  102. package/skills/devops/ci-cd/SKILL.md +59 -0
  103. package/skills/devops/deployment/SKILL.md +49 -0
  104. package/skills/devops/docker/SKILL.md +57 -0
  105. package/skills/frameworks/api-design/SKILL.md +103 -0
  106. package/skills/frameworks/fastapi/SKILL.md +68 -0
  107. package/skills/frameworks/nextjs/SKILL.md +74 -0
  108. package/skills/frameworks/python/SKILL.md +89 -0
  109. package/skills/frameworks/react/SKILL.md +83 -0
  110. package/skills/frameworks/sveltekit/SKILL.md +69 -0
  111. package/skills/frameworks/tailwindcss/SKILL.md +75 -0
  112. package/skills/frameworks/typescript/SKILL.md +94 -0
  113. package/skills/meta/mcp-builder/SKILL.md +54 -0
  114. package/skills/meta/skill-creator/SKILL.md +43 -0
  115. package/skills/optimization/performance/SKILL.md +70 -0
  116. package/skills/quality/complexity-analyzer/SKILL.md +52 -0
  117. package/skills/quality/error-handling/SKILL.md +123 -0
  118. package/skills/quality/log-analyzer/SKILL.md +31 -0
  119. package/skills/quality/pattern-detector/SKILL.md +50 -0
  120. package/skills/security/auth-analyzer/SKILL.md +96 -0
  121. package/skills/security/compliance-checker/SKILL.md +92 -0
  122. package/skills/security/container-security/SKILL.md +128 -0
  123. package/skills/security/dependency-auditor/SKILL.md +100 -0
  124. package/skills/security/encryption/SKILL.md +94 -0
  125. package/skills/security/incident-response/SKILL.md +127 -0
  126. package/skills/security/secrets/SKILL.md +93 -0
  127. package/skills/security/security-headers/SKILL.md +83 -0
  128. package/skills/security/security-logging/SKILL.md +107 -0
  129. package/skills/security/vulnerability-scanner/SKILL.md +114 -0
  130. package/skills/testing/e2e-testing/SKILL.md +119 -0
  131. package/skills/testing/tdd/SKILL.md +40 -0
  132. package/skills/testing/test-generator/SKILL.md +39 -0
  133. package/skills/workflow/commit/SKILL.md +61 -0
  134. package/skills/workflow/confidence-check/SKILL.md +90 -0
  135. package/skills/workflow/pr-review-comments/SKILL.md +81 -0
  136. package/skills/workflow/pr-review-comments/scripts/fetch_comments.py +237 -0
@@ -0,0 +1,54 @@
1
+ ---
2
+ name: mcp-builder
3
+ description: Guide for building MCP (Model Context Protocol) servers — tools, resources, prompts, transport setup.
4
+ ---
5
+
6
+ # MCP Builder
7
+
8
+ ## MCP Server Structure
9
+ ```
10
+ my-mcp-server/
11
+ ├── package.json
12
+ ├── src/
13
+ │ └── index.ts # Server entry point
14
+ └── README.md
15
+ ```
16
+
17
+ ## Minimal TypeScript Server
18
+ ```typescript
19
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
20
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
21
+ import { z } from "zod";
22
+
23
+ const server = new McpServer({ name: "my-server", version: "1.0.0" });
24
+
25
+ server.tool("my_tool", "Description of what this tool does", {
26
+ param1: z.string().describe("Parameter description"),
27
+ }, async ({ param1 }) => ({
28
+ content: [{ type: "text", text: `Result: ${param1}` }]
29
+ }));
30
+
31
+ const transport = new StdioServerTransport();
32
+ await server.connect(transport);
33
+ ```
34
+
35
+ ## Python Server (FastMCP)
36
+ ```python
37
+ from mcp.server.fastmcp import FastMCP
38
+
39
+ mcp = FastMCP("my-server")
40
+
41
+ @mcp.tool()
42
+ def my_tool(param1: str) -> str:
43
+ """Description of what this tool does."""
44
+ return f"Result: {param1}"
45
+
46
+ mcp.run(transport="stdio")
47
+ ```
48
+
49
+ ## Rules
50
+ - Use stdio transport for local, HTTP/SSE for remote
51
+ - Every tool needs a clear description (Claude uses it for selection)
52
+ - Input validation with schemas (Zod for TS, Pydantic for Python)
53
+ - Return structured errors, not exceptions
54
+ - Keep tools focused — one action per tool
@@ -0,0 +1,43 @@
1
+ ---
2
+ name: skill-creator
3
+ description: Guide for creating new CortexHawk skills with proper structure and frontmatter.
4
+ ---
5
+
6
+ # Skill Creator
7
+
8
+ ## Structure
9
+ ```
10
+ skills/[category]/[skill-name]/
11
+ ├── SKILL.md # Required — instructions and metadata
12
+ ├── scripts/ # Optional — helper scripts
13
+ │ └── helper.py
14
+ └── resources/ # Optional — templates, configs
15
+ └── template.json
16
+ ```
17
+
18
+ ## SKILL.md Template
19
+ ```markdown
20
+ ---
21
+ name: [skill-name]
22
+ description: [When to use this skill — 1 sentence, be specific]
23
+ detect: [base | <file> | <file>:<pattern> | dir:<path> — omit if not auto-detectable]
24
+ ---
25
+
26
+ # [Skill Name]
27
+
28
+ ## [Core Content]
29
+ [Instructions Claude follows when this skill is active]
30
+
31
+ ## [Examples]
32
+ [Concrete examples with code]
33
+
34
+ ## [Checklist / Rules]
35
+ [Actionable items]
36
+ ```
37
+
38
+ ## Guidelines
39
+ - Description must be specific enough for auto-discovery to work
40
+ - Keep total content under 4K tokens — Claude loads it into context
41
+ - Use code examples over prose explanations
42
+ - Checklists are better than paragraphs
43
+ - Test the skill: ask Claude something matching the description and verify it loads
@@ -0,0 +1,70 @@
1
+ ---
2
+ name: performance
3
+ description: Profiling, N+1 detection, caching strategies, lazy loading, and bundle analysis.
4
+ ---
5
+
6
+ # Performance Optimization
7
+
8
+ ## Profiling Checklist
9
+ - [ ] Identify the bottleneck BEFORE optimizing — measure, don't guess
10
+ - [ ] Profile in production-like conditions (data size, concurrency)
11
+ - [ ] Set a target metric (response time, memory, bundle size)
12
+ - [ ] Measure after each change — verify improvement
13
+
14
+ ## N+1 Query Detection
15
+ ```sql
16
+ -- BAD: N+1 — 1 query for users + N queries for posts
17
+ SELECT * FROM users;
18
+ SELECT * FROM posts WHERE user_id = 1;
19
+ SELECT * FROM posts WHERE user_id = 2;
20
+ -- ... N more queries
21
+
22
+ -- GOOD: Eager load with JOIN or IN
23
+ SELECT u.*, p.* FROM users u LEFT JOIN posts p ON u.id = p.user_id;
24
+ -- Or
25
+ SELECT * FROM posts WHERE user_id IN (1, 2, 3, ...);
26
+ ```
27
+
28
+ ## Caching Strategies
29
+ | Strategy | Use When | TTL |
30
+ |---|---|---|
31
+ | In-memory (Map/LRU) | Hot data, single instance | Seconds-minutes |
32
+ | Redis/Memcached | Shared cache, multi-instance | Minutes-hours |
33
+ | HTTP Cache-Control | Static assets, API responses | Hours-days |
34
+ | CDN | Static files, images, fonts | Days-weeks |
35
+ | Memoization | Pure function results | Request lifetime |
36
+
37
+ ```typescript
38
+ // Simple LRU cache
39
+ const cache = new Map();
40
+ function cached<T>(key: string, ttl: number, fn: () => T): T {
41
+ const entry = cache.get(key);
42
+ if (entry && Date.now() - entry.time < ttl) return entry.value;
43
+ const value = fn();
44
+ cache.set(key, { value, time: Date.now() });
45
+ return value;
46
+ }
47
+ ```
48
+
49
+ ## Frontend
50
+ - Lazy load routes and heavy components: `React.lazy()`, dynamic `import()`
51
+ - Images: `loading="lazy"`, `srcset` for responsive, WebP/AVIF formats
52
+ - Bundle analysis: `webpack-bundle-analyzer`, `vite-plugin-inspect`
53
+ - Tree shaking: named imports, avoid barrel files re-exporting everything
54
+ - Debounce search inputs, throttle scroll/resize handlers
55
+
56
+ ## Backend
57
+ - Connection pooling for databases (don't create per-request connections)
58
+ - Pagination on all list endpoints — never return unbounded results
59
+ - Async I/O for network/disk operations
60
+ - Stream large responses instead of buffering in memory
61
+ - Index columns used in WHERE, ORDER BY, JOIN conditions
62
+
63
+ ## Checklist
64
+ - Measure before optimizing — no premature optimization
65
+ - One change at a time — isolate impact
66
+ - N+1 queries are the #1 backend performance killer — always check
67
+ - Cache invalidation strategy is as important as the cache itself
68
+ - Bundle size: aim for <200KB initial JS (gzipped)
69
+ - Time to Interactive: aim for <3s on 3G
70
+ - Database: EXPLAIN ANALYZE on slow queries
@@ -0,0 +1,52 @@
1
+ ---
2
+ name: complexity-analyzer
3
+ description: Analyze code complexity — cyclomatic complexity, cognitive complexity, dependency depth.
4
+ ---
5
+
6
+ # Complexity Analyzer
7
+
8
+ ## Metrics
9
+ - **Cyclomatic complexity** — Number of independent paths. Target: ≤10 per function
10
+ - **Cognitive complexity** — How hard to understand. Target: ≤15 per function
11
+ - **Dependency depth** — Import chain length. Target: ≤4 levels
12
+ - **Function length** — Lines of code. Target: ≤30 lines
13
+ - **Parameter count** — Function arguments. Target: ≤4 params
14
+
15
+ ## Complexity Reducers
16
+ - Extract method (split complex function)
17
+ - Replace conditional with polymorphism
18
+ - Early returns (reduce nesting)
19
+ - Lookup tables (replace switch/if chains)
20
+ - Decompose boolean expressions into named variables
21
+
22
+ ## Examples
23
+ ```python
24
+ # Cyclomatic complexity: 6 (too high)
25
+ def check(user, action, resource):
26
+ if user.is_admin:
27
+ return True
28
+ if action == "read" and resource.is_public:
29
+ return True
30
+ if action == "write" and user.id == resource.owner_id:
31
+ return True
32
+ if action == "delete" and user.role == "moderator":
33
+ return True
34
+ return False
35
+
36
+ # Reduced to 1 with lookup table
37
+ RULES = {
38
+ lambda u, r: u.is_admin: {"read", "write", "delete"},
39
+ lambda u, r: r.is_public: {"read"},
40
+ lambda u, r: u.id == r.owner_id: {"read", "write"},
41
+ lambda u, r: u.role == "moderator": {"read", "delete"},
42
+ }
43
+
44
+ def check(user, action, resource):
45
+ return any(action in actions for pred, actions in RULES.items() if pred(user, resource))
46
+ ```
47
+
48
+ ## Process
49
+ 1. Scan target files for functions exceeding thresholds
50
+ 2. Rank by severity (highest complexity first)
51
+ 3. Suggest specific refactoring for each
52
+ 4. Estimate effort (lines to change, risk level)
@@ -0,0 +1,123 @@
1
+ ---
2
+ name: error-handling
3
+ description: Error handling patterns — Result types, exceptions, retry with backoff, circuit breaker, and boundary validation.
4
+ detect: base
5
+ ---
6
+
7
+ # Error Handling
8
+
9
+ ## Result Type Pattern (TypeScript)
10
+ ```typescript
11
+ type Result<T, E = Error> =
12
+ | { ok: true; data: T }
13
+ | { ok: false; error: E };
14
+
15
+ function parseUser(input: unknown): Result<User, string> {
16
+ if (!isValidUser(input)) return { ok: false, error: "Invalid user data" };
17
+ return { ok: true, data: input as User };
18
+ }
19
+
20
+ // Usage — forces caller to handle both cases
21
+ const result = parseUser(data);
22
+ if (!result.ok) {
23
+ logger.error(result.error);
24
+ return res.status(400).json({ error: result.error });
25
+ }
26
+ const user = result.data; // TypeScript knows this is User
27
+ ```
28
+
29
+ ## Exception Patterns (Python)
30
+ ```python
31
+ # Custom exception hierarchy
32
+ class AppError(Exception):
33
+ def __init__(self, message: str, code: str, status: int = 500):
34
+ self.message = message
35
+ self.code = code
36
+ self.status = status
37
+
38
+ class NotFoundError(AppError):
39
+ def __init__(self, resource: str, id: str):
40
+ super().__init__(f"{resource} {id} not found", "NOT_FOUND", 404)
41
+
42
+ class ValidationError(AppError):
43
+ def __init__(self, details: list[dict]):
44
+ super().__init__("Validation failed", "VALIDATION_ERROR", 400)
45
+ self.details = details
46
+
47
+ # Global handler
48
+ @app.exception_handler(AppError)
49
+ async def handle_app_error(request, exc: AppError):
50
+ return JSONResponse(status_code=exc.status, content={
51
+ "error": {"code": exc.code, "message": exc.message}
52
+ })
53
+ ```
54
+
55
+ ## Retry with Exponential Backoff
56
+ ```python
57
+ import asyncio
58
+ import random
59
+
60
+ async def retry(fn, max_attempts=3, base_delay=1.0):
61
+ for attempt in range(max_attempts):
62
+ try:
63
+ return await fn()
64
+ except Exception as e:
65
+ if attempt == max_attempts - 1:
66
+ raise
67
+ delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
68
+ await asyncio.sleep(delay)
69
+ ```
70
+
71
+ ```typescript
72
+ async function retry<T>(fn: () => Promise<T>, maxAttempts = 3): Promise<T> {
73
+ for (let i = 0; i < maxAttempts; i++) {
74
+ try { return await fn(); }
75
+ catch (e) {
76
+ if (i === maxAttempts - 1) throw e;
77
+ await new Promise(r => setTimeout(r, 1000 * 2 ** i + Math.random() * 1000));
78
+ }
79
+ }
80
+ throw new Error("unreachable");
81
+ }
82
+ ```
83
+
84
+ ## Circuit Breaker
85
+ ```typescript
86
+ class CircuitBreaker {
87
+ private failures = 0;
88
+ private lastFailure = 0;
89
+ private state: "closed" | "open" | "half-open" = "closed";
90
+
91
+ constructor(private threshold = 5, private resetMs = 30000) {}
92
+
93
+ async call<T>(fn: () => Promise<T>): Promise<T> {
94
+ if (this.state === "open") {
95
+ if (Date.now() - this.lastFailure > this.resetMs) {
96
+ this.state = "half-open";
97
+ } else {
98
+ throw new Error("Circuit breaker is open");
99
+ }
100
+ }
101
+ try {
102
+ const result = await fn();
103
+ this.failures = 0;
104
+ this.state = "closed";
105
+ return result;
106
+ } catch (e) {
107
+ this.failures++;
108
+ this.lastFailure = Date.now();
109
+ if (this.failures >= this.threshold) this.state = "open";
110
+ throw e;
111
+ }
112
+ }
113
+ }
114
+ ```
115
+
116
+ ## Checklist
117
+ - Validate at system boundaries only (user input, external APIs) — trust internal code
118
+ - Never swallow errors silently — log or propagate
119
+ - Custom error types with machine-readable codes, not just messages
120
+ - Retry only idempotent operations (GET, PUT, DELETE) — never blind retry on POST
121
+ - Circuit breaker for external service calls — fail fast when downstream is down
122
+ - Always include correlation ID in error logs for tracing
123
+ - Never expose stack traces or internal details to users
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: log-analyzer
3
+ description: Analyze and improve logging — structured logging, levels, correlation IDs, sensitive data detection.
4
+ ---
5
+
6
+ # Log Analyzer
7
+
8
+ ## Structured Logging
9
+ ```python
10
+ # ❌ Unstructured
11
+ logger.info(f"User {user_id} created order {order_id}")
12
+
13
+ # ✅ Structured
14
+ logger.info("order_created", extra={"user_id": user_id, "order_id": order_id})
15
+ ```
16
+
17
+ ## Log Levels
18
+ | Level | Use for |
19
+ |---|---|
20
+ | ERROR | Something failed, needs attention |
21
+ | WARN | Unexpected but handled, potential issue |
22
+ | INFO | Key business events (user created, order placed) |
23
+ | DEBUG | Development details, not in production |
24
+
25
+ ## Checklist
26
+ - [ ] Structured format (JSON in production)
27
+ - [ ] Correlation/request ID on every log entry
28
+ - [ ] No PII in logs (emails, passwords, tokens, IPs)
29
+ - [ ] Error logs include stack trace and context
30
+ - [ ] Log rotation configured
31
+ - [ ] Centralized log aggregation (ELK, Grafana Loki, etc.)
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: pattern-detector
3
+ description: Detect code smells, anti-patterns, and design issues.
4
+ ---
5
+
6
+ # Pattern Detector
7
+
8
+ ## Code Smells
9
+ - **Long function** (>30 lines) → extract functions
10
+ - **Deep nesting** (>3 levels) → early returns, extract
11
+ - **God class** (>300 lines, >10 methods) → split by responsibility
12
+ - **Feature envy** (method uses another class more than its own) → move method
13
+ - **Primitive obsession** (raw strings/ints for structured data) → value objects
14
+ - **Shotgun surgery** (one change = edits in many places) → consolidate
15
+ - **Dead code** (unreachable, unused imports, commented out) → delete it
16
+
17
+ ## Anti-Patterns
18
+ - Callback hell → async/await
19
+ - Magic numbers/strings → named constants
20
+ - Copy-paste code → extract shared function
21
+ - Catch-all exception handling → specific exceptions
22
+ - Boolean parameters → separate functions or enums
23
+ - Mutable global state → dependency injection
24
+
25
+ ## Examples
26
+ ```python
27
+ # BAD: deep nesting
28
+ def process(data):
29
+ if data:
30
+ if data.valid:
31
+ if data.items:
32
+ for item in data.items:
33
+ handle(item)
34
+
35
+ # GOOD: early returns
36
+ def process(data):
37
+ if not data or not data.valid or not data.items:
38
+ return
39
+ for item in data.items:
40
+ handle(item)
41
+ ```
42
+
43
+ ```typescript
44
+ // BAD: magic numbers
45
+ if (password.length < 8) { ... }
46
+
47
+ // GOOD: named constant
48
+ const MIN_PASSWORD_LENGTH = 8;
49
+ if (password.length < MIN_PASSWORD_LENGTH) { ... }
50
+ ```
@@ -0,0 +1,96 @@
1
+ ---
2
+ name: auth-analyzer
3
+ description: Audit authentication and authorization — OAuth2, JWT, sessions, RBAC, password policy, and common auth vulnerabilities.
4
+ detect: package.json:passport package.json:next-auth package.json:bcrypt package.json:jose requirements.txt:authlib requirements.txt:bcrypt requirements.txt:passlib requirements.txt:pyjwt pyproject.toml:authlib pyproject.toml:bcrypt pyproject.toml:passlib pyproject.toml:pyjwt
5
+ ---
6
+
7
+ # Auth Analyzer
8
+
9
+ ## OAuth2 Flows
10
+ | Flow | Use Case | Security |
11
+ |---|---|---|
12
+ | Authorization Code + PKCE | SPAs, mobile | Recommended |
13
+ | Authorization Code | Server-side web | Recommended |
14
+ | Client Credentials | Machine-to-machine | Service only |
15
+ | Device Code | IoT, CLI | Limited UI |
16
+ | ~~Implicit~~ | ~~Legacy~~ | Never use |
17
+ | ~~Resource Owner Password~~ | ~~Legacy~~ | Never use |
18
+
19
+ ### PKCE Flow
20
+ ```
21
+ 1. Generate code_verifier (CSPRNG, 43-128 chars)
22
+ 2. code_challenge = base64url(sha256(code_verifier))
23
+ 3. Redirect to /authorize with code_challenge + state
24
+ 4. Validate state on callback
25
+ 5. Exchange code + code_verifier at /token
26
+ 6. Store access_token in memory, refresh_token in httpOnly cookie
27
+ ```
28
+
29
+ ## JWT Checklist
30
+ - [ ] Algorithm whitelist only — RS256/ES256 for distributed, never `none`
31
+ - [ ] Short expiration (access: 15min, refresh: 7-30 days)
32
+ - [ ] Refresh token rotation (invalidate old on use)
33
+ - [ ] Store in httpOnly cookie or memory (never localStorage)
34
+ - [ ] Validate `iss`, `aud`, `exp`, `iat` on every request
35
+ - [ ] No sensitive data in payload (base64, not encrypted)
36
+ - [ ] Key rotation via JWKS with `kid` — rotate every 90 days
37
+
38
+ ### Key Rotation
39
+ ```
40
+ 1. Generate new key pair, assign new kid
41
+ 2. Publish both old + new keys in JWKS
42
+ 3. Sign new tokens with new key only
43
+ 4. Remove old key after max token lifetime
44
+ ```
45
+
46
+ ## Session Security
47
+ - [ ] Session ID from CSPRNG (min 128 bits)
48
+ - [ ] Regenerate ID after login
49
+ - [ ] Timeout: idle (15-60min) + absolute (8-24h)
50
+ - [ ] Secure, HttpOnly, SameSite=Strict cookies
51
+ - [ ] Server-side invalidation on logout
52
+ - [ ] Invalidate all sessions on password change
53
+
54
+ ## Password Policy
55
+ - [ ] Argon2id or bcrypt (cost ≥12) — never SHA256/MD5
56
+ - [ ] Min 8 chars, check against breached lists
57
+ - [ ] Rate limit login (5/min per IP+account)
58
+ - [ ] Lockout after N failures with exponential backoff
59
+
60
+ ## Authorization (RBAC)
61
+ - [ ] Default deny — grant explicitly
62
+ - [ ] Check permissions server-side on every request
63
+ - [ ] No IDOR — verify `user.id == resource.owner_id`
64
+ - [ ] Role hierarchy enforced, reviewed quarterly
65
+ - [ ] Log all access control failures
66
+
67
+ ## Examples
68
+ ```python
69
+ # BAD: no algorithm validation
70
+ payload = jwt.decode(token, SECRET, algorithms=None)
71
+
72
+ # GOOD: explicit whitelist
73
+ payload = jwt.decode(token, SECRET, algorithms=["RS256"])
74
+ ```
75
+
76
+ ```typescript
77
+ // BAD: IDOR — no ownership check
78
+ const order = await db.orders.findById(req.params.id);
79
+
80
+ // GOOD: ownership verified
81
+ const order = await db.orders.findOne({
82
+ id: req.params.id,
83
+ userId: req.user.id,
84
+ });
85
+ if (!order) return res.status(404).json({ error: 'Not found' });
86
+ ```
87
+
88
+ ## Common Vulnerabilities
89
+ | Issue | Check | Fix |
90
+ |---|---|---|
91
+ | JWT none attack | Algorithm validated? | Whitelist algorithms |
92
+ | IDOR | Ownership checked? | Filter by user_id |
93
+ | Privilege escalation | Role checked on mutation? | Middleware on all routes |
94
+ | Session fixation | ID regenerated? | New ID post-login |
95
+ | Credential stuffing | Rate limiting? | Rate limit + CAPTCHA |
96
+ | Token theft via XSS | Stored in memory? | Never localStorage |
@@ -0,0 +1,92 @@
1
+ ---
2
+ name: compliance-checker
3
+ description: Check code against security standards — GDPR/RGPD, OWASP ASVS, SOC 2, PCI DSS, and data classification.
4
+ ---
5
+
6
+ # Compliance Checker
7
+
8
+ ## Data Classification
9
+ ```
10
+ Tier 1 — Critical: Passwords, payment info, SSN, health records
11
+ Encrypt at rest (AES-256-GCM), strict access control, audit logging
12
+
13
+ Tier 2 — Sensitive: PII (name, email, phone, address)
14
+ Encrypt at rest, access control, logging
15
+
16
+ Tier 3 — Internal: Preferences, settings, non-sensitive metadata
17
+ Standard access control
18
+
19
+ Tier 4 — Public: Display names, public posts
20
+ Standard storage
21
+ ```
22
+
23
+ ## GDPR / RGPD (EU Data Protection)
24
+ - [ ] Personal data inventory — what PII, where stored, how long
25
+ - [ ] Consent mechanism before collection
26
+ - [ ] Right to deletion (DELETE endpoint or process)
27
+ - [ ] Right to export (data portability, JSON/CSV)
28
+ - [ ] Data minimization — only collect what's necessary
29
+ - [ ] Privacy policy accessible and accurate
30
+ - [ ] Breach notification process documented (72h for GDPR)
31
+ - [ ] DPA with third-party processors
32
+ - [ ] No PII in logs, error messages, or analytics
33
+ - [ ] Data encrypted at rest and in transit
34
+
35
+ ```python
36
+ # GDPR: right to deletion
37
+ @app.delete("/api/users/me")
38
+ async def delete_account(user: User = Depends(get_current_user)):
39
+ await db.users.anonymize(user.id)
40
+ await db.sessions.revoke_all(user.id)
41
+ await audit_log.record("account_deleted", user.id)
42
+ return {"status": "account deleted"}
43
+
44
+ # GDPR: data export
45
+ @app.get("/api/users/me/export")
46
+ async def export_data(user: User = Depends(get_current_user)):
47
+ data = await db.users.get_all_data(user.id)
48
+ return JSONResponse(content=data, headers={
49
+ "Content-Disposition": f"attachment; filename=data_{user.id}.json"
50
+ })
51
+ ```
52
+
53
+ ## OWASP ASVS
54
+
55
+ ### Level 1 — Minimum
56
+ - [ ] All inputs validated server-side
57
+ - [ ] Output encoding prevents XSS
58
+ - [ ] Parameterized queries prevent injection
59
+ - [ ] Secure auth defaults
60
+ - [ ] Secure session management
61
+ - [ ] Error handling doesn't leak info
62
+
63
+ ### Level 2 — Standard (SaaS)
64
+ - [ ] All Level 1 + MFA available
65
+ - [ ] Security headers configured
66
+ - [ ] API rate limiting
67
+ - [ ] Dependency scanning automated
68
+ - [ ] Security logging and monitoring
69
+ - [ ] File upload validation (type, size, content)
70
+
71
+ ## SOC 2 Basics
72
+ - [ ] Access controls documented and enforced
73
+ - [ ] Audit trail for sensitive operations
74
+ - [ ] Incident response plan exists
75
+ - [ ] Data backup and recovery tested
76
+ - [ ] Change management process (PRs, reviews)
77
+ - [ ] Least privilege access for employees
78
+
79
+ ## PCI DSS (Payment)
80
+ - [ ] Card data encrypted in transit and at rest
81
+ - [ ] No card numbers stored post-authorization (tokenize)
82
+ - [ ] Access to cardholder data restricted by business need
83
+ - [ ] Unique IDs for all users with system access
84
+ - [ ] Regular vulnerability scans
85
+ - [ ] Network segmented (cardholder zone isolated)
86
+
87
+ ## Scan Process
88
+ 1. Scan codebase for PII patterns (email, phone, name, IP)
89
+ 2. Check if PII storage has encryption and retention policy
90
+ 3. Verify deletion and export endpoints exist
91
+ 4. Confirm security headers and auth are configured
92
+ 5. Flag compliance gaps with severity and remediation