@ia-ccun/code-agent-cli 0.0.2 → 0.0.4-8.beta.1

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 (189) hide show
  1. package/README.md +92 -11
  2. package/bin/cli.js +212 -59
  3. package/config/agent/APPEND_SYSTEM.md +46 -5
  4. package/config/agent/bin/fd +0 -0
  5. package/config/agent/bin/rg +0 -0
  6. package/config/agent/dangerous-patterns.json +106 -0
  7. package/config/agent/extensions/aicode-tips.ts +191 -0
  8. package/config/agent/extensions/bash-check.ts +227 -0
  9. package/config/agent/extensions/context-monitor.ts +275 -0
  10. package/config/agent/extensions/context.ts +1 -0
  11. package/config/agent/extensions/custom-footer.ts +33 -2
  12. package/config/agent/extensions/custom.ts +24 -91
  13. package/config/agent/extensions/error-monitor.ts +142 -0
  14. package/config/agent/extensions/msg-debug.ts +185 -0
  15. package/config/agent/extensions/review.ts +4 -0
  16. package/config/agent/extensions/working-msg.ts +39 -20
  17. package/config/agent/mcp.json +4 -0
  18. package/config/agent/models.json +16 -43
  19. package/config/agent/prompts/code-simplifier.md +51 -0
  20. package/config/agent/prompts/feat.md +2 -2
  21. package/config/agent/prompts/git-commit.md +9 -15
  22. package/config/agent/prompts/init-project.md +2 -1
  23. package/config/agent/prompts/workflow.md +3 -2
  24. package/config/agent/settings.json +17 -5
  25. package/config/agent/skills/brainstorming/SKILL.md +167 -0
  26. package/config/agent/skills/brainstorming/scripts/frame-template.html +214 -0
  27. package/config/agent/skills/brainstorming/scripts/helper.js +88 -0
  28. package/config/agent/skills/brainstorming/scripts/server.cjs +338 -0
  29. package/config/agent/skills/brainstorming/scripts/start-server.sh +153 -0
  30. package/config/agent/skills/brainstorming/scripts/stop-server.sh +55 -0
  31. package/config/agent/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  32. package/config/agent/skills/brainstorming/visual-companion.md +286 -0
  33. package/config/agent/skills/code-review/SKILL.md +4 -2
  34. package/config/agent/skills/commit/SKILL.md +10 -5
  35. package/config/agent/skills/csv-data-summarizer/SKILL.md +2 -1
  36. package/config/agent/skills/design-md/README.md +34 -0
  37. package/config/agent/skills/design-md/SKILL.md +172 -0
  38. package/config/agent/skills/design-md/examples/DESIGN.md +154 -0
  39. package/config/agent/skills/dispatching-parallel-agents/SKILL.md +185 -0
  40. package/config/agent/skills/executing-plans/SKILL.md +73 -0
  41. package/config/agent/skills/find-skills/SKILL.md +5 -1
  42. package/config/agent/skills/finishing-a-development-branch/SKILL.md +204 -0
  43. package/config/agent/skills/fireworks-tech-graph/LICENSE +21 -0
  44. package/config/agent/skills/fireworks-tech-graph/README.md +528 -0
  45. package/config/agent/skills/fireworks-tech-graph/README.zh.md +499 -0
  46. package/config/agent/skills/fireworks-tech-graph/SKILL.md +537 -0
  47. package/config/agent/skills/fireworks-tech-graph/agentloop-core.svg +101 -0
  48. package/config/agent/skills/fireworks-tech-graph/agents/openai.yaml +4 -0
  49. package/config/agent/skills/fireworks-tech-graph/assets/samples/sample-style1-flat.png +0 -0
  50. package/config/agent/skills/fireworks-tech-graph/assets/samples/sample-style2-dark.png +0 -0
  51. package/config/agent/skills/fireworks-tech-graph/assets/samples/sample-style3-blueprint.png +0 -0
  52. package/config/agent/skills/fireworks-tech-graph/assets/samples/sample-style4-notion.png +0 -0
  53. package/config/agent/skills/fireworks-tech-graph/assets/samples/sample-style5-glass.png +0 -0
  54. package/config/agent/skills/fireworks-tech-graph/assets/samples/sample-style6-claude.png +0 -0
  55. package/config/agent/skills/fireworks-tech-graph/assets/samples/sample-style7-openai.png +0 -0
  56. package/config/agent/skills/fireworks-tech-graph/fixtures/agent-memory-types-style4.json +181 -0
  57. package/config/agent/skills/fireworks-tech-graph/fixtures/api-flow-style7.json +40 -0
  58. package/config/agent/skills/fireworks-tech-graph/fixtures/mem0-style1.json +297 -0
  59. package/config/agent/skills/fireworks-tech-graph/fixtures/microservices-style3.json +64 -0
  60. package/config/agent/skills/fireworks-tech-graph/fixtures/multi-agent-style5.json +45 -0
  61. package/config/agent/skills/fireworks-tech-graph/fixtures/system-architecture-style6.json +48 -0
  62. package/config/agent/skills/fireworks-tech-graph/fixtures/tool-call-style2.json +182 -0
  63. package/config/agent/skills/fireworks-tech-graph/package.json +42 -0
  64. package/config/agent/skills/fireworks-tech-graph/references/icons.md +406 -0
  65. package/config/agent/skills/fireworks-tech-graph/references/style-1-flat-icon.md +108 -0
  66. package/config/agent/skills/fireworks-tech-graph/references/style-2-dark-terminal.md +107 -0
  67. package/config/agent/skills/fireworks-tech-graph/references/style-3-blueprint.md +113 -0
  68. package/config/agent/skills/fireworks-tech-graph/references/style-4-notion-clean.md +94 -0
  69. package/config/agent/skills/fireworks-tech-graph/references/style-5-glassmorphism.md +125 -0
  70. package/config/agent/skills/fireworks-tech-graph/references/style-6-claude-official.md +209 -0
  71. package/config/agent/skills/fireworks-tech-graph/references/style-7-openai.md +215 -0
  72. package/config/agent/skills/fireworks-tech-graph/references/style-diagram-matrix.md +135 -0
  73. package/config/agent/skills/fireworks-tech-graph/references/svg-layout-best-practices.md +100 -0
  74. package/config/agent/skills/fireworks-tech-graph/scripts/README.md +244 -0
  75. package/config/agent/skills/fireworks-tech-graph/scripts/generate-diagram.sh +157 -0
  76. package/config/agent/skills/fireworks-tech-graph/scripts/generate-from-template.py +1556 -0
  77. package/config/agent/skills/fireworks-tech-graph/scripts/test-all-styles.sh +135 -0
  78. package/config/agent/skills/fireworks-tech-graph/scripts/validate-svg.sh +292 -0
  79. package/config/agent/skills/fireworks-tech-graph/templates/agent-architecture.svg +28 -0
  80. package/config/agent/skills/fireworks-tech-graph/templates/architecture.svg +23 -0
  81. package/config/agent/skills/fireworks-tech-graph/templates/comparison-matrix.svg +14 -0
  82. package/config/agent/skills/fireworks-tech-graph/templates/data-flow.svg +28 -0
  83. package/config/agent/skills/fireworks-tech-graph/templates/er-diagram.svg +21 -0
  84. package/config/agent/skills/fireworks-tech-graph/templates/flowchart.svg +21 -0
  85. package/config/agent/skills/fireworks-tech-graph/templates/sequence.svg +20 -0
  86. package/config/agent/skills/fireworks-tech-graph/templates/state-machine.svg +20 -0
  87. package/config/agent/skills/fireworks-tech-graph/templates/timeline.svg +19 -0
  88. package/config/agent/skills/fireworks-tech-graph/templates/use-case.svg +21 -0
  89. package/config/agent/skills/frontend-design/SKILL.md +4 -1
  90. package/config/agent/skills/hello/SKILL.md +5 -2
  91. package/config/agent/skills/impeccable/adapt/SKILL.md +204 -0
  92. package/config/agent/skills/impeccable/animate/SKILL.md +177 -0
  93. package/config/agent/skills/impeccable/arrange/SKILL.md +127 -0
  94. package/config/agent/skills/impeccable/audit/SKILL.md +128 -0
  95. package/config/agent/skills/impeccable/bolder/SKILL.md +119 -0
  96. package/config/agent/skills/impeccable/clarify/SKILL.md +185 -0
  97. package/config/agent/skills/impeccable/colorize/SKILL.md +145 -0
  98. package/config/agent/skills/impeccable/critique/SKILL.md +122 -0
  99. package/config/agent/skills/impeccable/delight/SKILL.md +306 -0
  100. package/config/agent/skills/impeccable/distill/SKILL.md +124 -0
  101. package/config/agent/skills/impeccable/extract/SKILL.md +94 -0
  102. package/config/agent/skills/impeccable/frontend-design/reference/color-and-contrast.md +132 -0
  103. package/config/agent/skills/impeccable/frontend-design/reference/interaction-design.md +123 -0
  104. package/config/agent/skills/impeccable/frontend-design/reference/motion-design.md +99 -0
  105. package/config/agent/skills/impeccable/frontend-design/reference/responsive-design.md +114 -0
  106. package/config/agent/skills/impeccable/frontend-design/reference/spatial-design.md +100 -0
  107. package/config/agent/skills/impeccable/frontend-design/reference/typography.md +133 -0
  108. package/config/agent/skills/impeccable/frontend-design/reference/ux-writing.md +107 -0
  109. package/config/agent/skills/impeccable/harden/SKILL.md +357 -0
  110. package/config/agent/skills/impeccable/normalize/SKILL.md +73 -0
  111. package/config/agent/skills/impeccable/onboard/SKILL.md +248 -0
  112. package/config/agent/skills/impeccable/optimize/SKILL.md +268 -0
  113. package/config/agent/skills/impeccable/overdrive/SKILL.md +144 -0
  114. package/config/agent/skills/impeccable/polish/SKILL.md +205 -0
  115. package/config/agent/skills/impeccable/quieter/SKILL.md +105 -0
  116. package/config/agent/skills/impeccable/teach-impeccable/SKILL.md +71 -0
  117. package/config/agent/skills/impeccable/typeset/SKILL.md +118 -0
  118. package/config/agent/skills/librarian/SKILL.md +5 -1
  119. package/config/agent/skills/markdown-to-html/SKILL.md +5 -2
  120. package/config/agent/skills/owasp-security/SKILL.md +539 -0
  121. package/config/agent/skills/pr/SKILL.md +5 -2
  122. package/config/agent/skills/receiving-code-review/SKILL.md +216 -0
  123. package/config/agent/skills/refactor/SKILL.md +5 -2
  124. package/config/agent/skills/requesting-code-review/SKILL.md +108 -0
  125. package/config/agent/skills/requesting-code-review/code-reviewer.md +146 -0
  126. package/config/agent/skills/session-learning/SKILL.md +185 -0
  127. package/config/agent/skills/skill-creator/SKILL.md +339 -213
  128. package/config/agent/skills/skill-creator/agents/analyzer.md +274 -0
  129. package/config/agent/skills/skill-creator/agents/comparator.md +202 -0
  130. package/config/agent/skills/skill-creator/agents/grader.md +223 -0
  131. package/config/agent/skills/skill-creator/assets/eval_review.html +146 -0
  132. package/config/agent/skills/skill-creator/eval-viewer/generate_review.py +471 -0
  133. package/config/agent/skills/skill-creator/eval-viewer/viewer.html +1325 -0
  134. package/config/agent/skills/skill-creator/references/schemas.md +430 -0
  135. package/config/agent/skills/skill-creator/scripts/__init__.py +0 -0
  136. package/config/agent/skills/skill-creator/scripts/aggregate_benchmark.py +401 -0
  137. package/config/agent/skills/skill-creator/scripts/generate_report.py +326 -0
  138. package/config/agent/skills/skill-creator/scripts/improve_description.py +248 -0
  139. package/config/agent/skills/skill-creator/scripts/package_skill.py +33 -7
  140. package/config/agent/skills/skill-creator/scripts/quick_validate.py +11 -3
  141. package/config/agent/skills/skill-creator/scripts/run_eval.py +310 -0
  142. package/config/agent/skills/skill-creator/scripts/run_loop.py +332 -0
  143. package/config/agent/skills/skill-creator/scripts/utils.py +47 -0
  144. package/config/agent/skills/subagent-driven-development/SKILL.md +280 -0
  145. package/config/agent/skills/subagent-driven-development/code-quality-reviewer-prompt.md +26 -0
  146. package/config/agent/skills/subagent-driven-development/implementer-prompt.md +113 -0
  147. package/config/agent/skills/subagent-driven-development/spec-reviewer-prompt.md +61 -0
  148. package/config/agent/skills/systematic-debugging/CREATION-LOG.md +119 -0
  149. package/config/agent/skills/systematic-debugging/SKILL.md +300 -0
  150. package/config/agent/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  151. package/config/agent/skills/systematic-debugging/condition-based-waiting.md +115 -0
  152. package/config/agent/skills/systematic-debugging/defense-in-depth.md +122 -0
  153. package/config/agent/skills/systematic-debugging/find-polluter.sh +63 -0
  154. package/config/agent/skills/systematic-debugging/root-cause-tracing.md +169 -0
  155. package/config/agent/skills/systematic-debugging/test-academic.md +14 -0
  156. package/config/agent/skills/systematic-debugging/test-pressure-1.md +58 -0
  157. package/config/agent/skills/systematic-debugging/test-pressure-2.md +68 -0
  158. package/config/agent/skills/systematic-debugging/test-pressure-3.md +69 -0
  159. package/config/agent/skills/test-driven-development/SKILL.md +375 -0
  160. package/config/agent/skills/test-driven-development/testing-anti-patterns.md +299 -0
  161. package/config/agent/skills/ui-ux-pro-max/SKILL.md +4 -1
  162. package/config/agent/skills/unit-test/SKILL.md +4 -2
  163. package/config/agent/skills/using-git-worktrees/SKILL.md +222 -0
  164. package/config/agent/skills/using-superpowers/SKILL.md +118 -0
  165. package/config/agent/skills/using-superpowers/references/codex-tools.md +25 -0
  166. package/config/agent/skills/using-superpowers/references/gemini-tools.md +33 -0
  167. package/config/agent/skills/verification-before-completion/SKILL.md +142 -0
  168. package/config/agent/skills/writing-plans/SKILL.md +148 -0
  169. package/config/agent/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  170. package/config/agent/skills/writing-skills/SKILL.md +669 -0
  171. package/config/agent/skills/writing-skills/anthropic-best-practices.md +1150 -0
  172. package/config/agent/skills/writing-skills/examples/CLAUDE_MD_TESTING.md +189 -0
  173. package/config/agent/skills/writing-skills/graphviz-conventions.dot +172 -0
  174. package/config/agent/skills/writing-skills/persuasion-principles.md +187 -0
  175. package/config/agent/skills/writing-skills/render-graphs.js +168 -0
  176. package/config/agent/skills/writing-skills/testing-skills-with-subagents.md +384 -0
  177. package/config.json +23 -2
  178. package/dist/banner.js +3 -3
  179. package/dist/banner.js.map +1 -1
  180. package/package.json +20 -15
  181. package/scripts/banner.txt +6 -0
  182. package/scripts/postinstall.js +203 -11
  183. package/config/agent/prompts/git-rollback.md +0 -91
  184. package/config/agent/prompts/git-worktree.md +0 -277
  185. package/config/agent/prompts/help.md +0 -10
  186. package/config/agent/skills/github/SKILL.md +0 -47
  187. package/config/agent/skills/skill-creator/references/output-patterns.md +0 -82
  188. package/config/agent/skills/skill-creator/references/workflows.md +0 -28
  189. package/config/agent/skills/skill-creator/scripts/init_skill.py +0 -303
@@ -0,0 +1,539 @@
1
+ ---
2
+ name: owasp-security
3
+ description: "Implement secure coding practices following OWASP Top 10. Use when dealing with OWASP, security, XSS, SQL injection, CSRF, secure coding, or vulnerabilities."
4
+ metadata:
5
+ version: "1.0.0"
6
+ author: "xujianjiang"
7
+ ---
8
+
9
+ # OWASP Top 10 Security
10
+
11
+ Prevent common security vulnerabilities in web applications.
12
+
13
+ ## OWASP Top 10 (2021)
14
+
15
+ | # | Vulnerability | Prevention |
16
+ |---|---------------|------------|
17
+ | A01 | Broken Access Control | Proper authorization checks |
18
+ | A02 | Cryptographic Failures | Strong encryption, secure storage |
19
+ | A03 | Injection | Input validation, parameterized queries |
20
+ | A04 | Insecure Design | Threat modeling, secure patterns |
21
+ | A05 | Security Misconfiguration | Hardened configs, no defaults |
22
+ | A06 | Vulnerable Components | Dependency scanning, updates |
23
+ | A07 | Auth Failures | MFA, secure session management |
24
+ | A08 | Data Integrity Failures | Input validation, signed updates |
25
+ | A09 | Logging Failures | Comprehensive audit logs |
26
+ | A10 | SSRF | URL validation, allowlists |
27
+
28
+ ## A01: Broken Access Control
29
+
30
+ ### Prevention Patterns
31
+ ```typescript
32
+ // ❌ BAD: No authorization check
33
+ app.get('/api/users/:id', async (req, res) => {
34
+ const user = await db.users.findById(req.params.id);
35
+ res.json(user);
36
+ });
37
+
38
+ // ✅ GOOD: Verify ownership
39
+ app.get('/api/users/:id', authenticate, async (req, res) => {
40
+ const userId = req.params.id;
41
+
42
+ // Users can only access their own data
43
+ if (req.user.id !== userId && req.user.role !== 'admin') {
44
+ return res.status(403).json({ error: 'Forbidden' });
45
+ }
46
+
47
+ const user = await db.users.findById(userId);
48
+ res.json(user);
49
+ });
50
+
51
+ // ✅ GOOD: Role-based access control (RBAC)
52
+ const requireRole = (...roles: string[]) => {
53
+ return (req: Request, res: Response, next: NextFunction) => {
54
+ if (!roles.includes(req.user?.role)) {
55
+ return res.status(403).json({ error: 'Insufficient permissions' });
56
+ }
57
+ next();
58
+ };
59
+ };
60
+
61
+ app.delete('/api/posts/:id', authenticate, requireRole('admin', 'moderator'), deletePost);
62
+ ```
63
+
64
+ ### Insecure Direct Object Reference (IDOR)
65
+ ```typescript
66
+ // ❌ BAD: Predictable IDs exposed
67
+ GET /api/invoices/1001
68
+ GET /api/invoices/1002 // Can enumerate others' invoices
69
+
70
+ // ✅ GOOD: Use UUIDs + ownership check
71
+ app.get('/api/invoices/:id', authenticate, async (req, res) => {
72
+ const invoice = await db.invoices.findOne({
73
+ id: req.params.id,
74
+ userId: req.user.id, // Enforce ownership
75
+ });
76
+
77
+ if (!invoice) {
78
+ return res.status(404).json({ error: 'Not found' });
79
+ }
80
+
81
+ res.json(invoice);
82
+ });
83
+ ```
84
+
85
+ ## A02: Cryptographic Failures
86
+
87
+ ### Password Hashing
88
+ ```typescript
89
+ import bcrypt from 'bcrypt';
90
+ import crypto from 'crypto';
91
+
92
+ // ✅ Hash passwords with bcrypt
93
+ const SALT_ROUNDS = 12;
94
+
95
+ async function hashPassword(password: string): Promise<string> {
96
+ return bcrypt.hash(password, SALT_ROUNDS);
97
+ }
98
+
99
+ async function verifyPassword(password: string, hash: string): Promise<boolean> {
100
+ return bcrypt.compare(password, hash);
101
+ }
102
+
103
+ // ✅ Secure token generation
104
+ function generateSecureToken(length = 32): string {
105
+ return crypto.randomBytes(length).toString('hex');
106
+ }
107
+
108
+ // ✅ Encrypt sensitive data
109
+ const ALGORITHM = 'aes-256-gcm';
110
+ const KEY = crypto.scryptSync(process.env.ENCRYPTION_KEY!, 'salt', 32);
111
+
112
+ function encrypt(text: string): { encrypted: string; iv: string; tag: string } {
113
+ const iv = crypto.randomBytes(16);
114
+ const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv);
115
+
116
+ let encrypted = cipher.update(text, 'utf8', 'hex');
117
+ encrypted += cipher.final('hex');
118
+
119
+ return {
120
+ encrypted,
121
+ iv: iv.toString('hex'),
122
+ tag: cipher.getAuthTag().toString('hex'),
123
+ };
124
+ }
125
+
126
+ function decrypt(encrypted: string, iv: string, tag: string): string {
127
+ const decipher = crypto.createDecipheriv(ALGORITHM, KEY, Buffer.from(iv, 'hex'));
128
+ decipher.setAuthTag(Buffer.from(tag, 'hex'));
129
+
130
+ let decrypted = decipher.update(encrypted, 'hex', 'utf8');
131
+ decrypted += decipher.final('utf8');
132
+
133
+ return decrypted;
134
+ }
135
+ ```
136
+
137
+ ### Secure Headers
138
+ ```typescript
139
+ import helmet from 'helmet';
140
+
141
+ app.use(helmet());
142
+ app.use(helmet.hsts({ maxAge: 31536000, includeSubDomains: true }));
143
+ app.use(helmet.contentSecurityPolicy({
144
+ directives: {
145
+ defaultSrc: ["'self'"],
146
+ scriptSrc: ["'self'", "'strict-dynamic'"],
147
+ styleSrc: ["'self'", "'unsafe-inline'"],
148
+ imgSrc: ["'self'", 'data:', 'https:'],
149
+ connectSrc: ["'self'"],
150
+ fontSrc: ["'self'"],
151
+ objectSrc: ["'none'"],
152
+ frameAncestors: ["'none'"],
153
+ },
154
+ }));
155
+ ```
156
+
157
+ ## A03: Injection
158
+
159
+ ### SQL Injection Prevention
160
+ ```typescript
161
+ // ❌ BAD: String concatenation
162
+ const query = `SELECT * FROM users WHERE email = '${email}'`;
163
+
164
+ // ✅ GOOD: Parameterized queries
165
+ // With Prisma
166
+ const user = await prisma.user.findUnique({ where: { email } });
167
+
168
+ // With raw SQL (parameterized)
169
+ const user = await db.query('SELECT * FROM users WHERE email = $1', [email]);
170
+
171
+ // With Knex
172
+ const user = await knex('users').where({ email }).first();
173
+ ```
174
+
175
+ ### NoSQL Injection Prevention
176
+ ```typescript
177
+ // ❌ BAD: Direct user input in query
178
+ const user = await User.findOne({ username: req.body.username });
179
+ // Attack: { "username": { "$gt": "" } } returns first user
180
+
181
+ // ✅ GOOD: Validate input type
182
+ import { z } from 'zod';
183
+
184
+ const loginSchema = z.object({
185
+ username: z.string().min(3).max(50),
186
+ password: z.string().min(8),
187
+ });
188
+
189
+ app.post('/login', async (req, res) => {
190
+ const { username, password } = loginSchema.parse(req.body);
191
+ const user = await User.findOne({ username: String(username) });
192
+ // ...
193
+ });
194
+ ```
195
+
196
+ ### Command Injection Prevention
197
+ ```typescript
198
+ import { execFile } from 'child_process';
199
+
200
+ // ❌ BAD: Shell injection
201
+ exec(`convert ${userInput} output.png`); // userInput: "; rm -rf /"
202
+
203
+ // ✅ GOOD: Use execFile with array args
204
+ execFile('convert', [userInput, 'output.png'], (error, stdout) => {
205
+ // Safe - arguments are not shell-interpreted
206
+ });
207
+
208
+ // ✅ GOOD: Validate and sanitize
209
+ const allowedFormats = ['png', 'jpg', 'gif'];
210
+ if (!allowedFormats.includes(format)) {
211
+ throw new Error('Invalid format');
212
+ }
213
+ ```
214
+
215
+ ## A04: Insecure Design
216
+
217
+ ### Rate Limiting
218
+ ```typescript
219
+ import rateLimit from 'express-rate-limit';
220
+
221
+ // General rate limit
222
+ const limiter = rateLimit({
223
+ windowMs: 15 * 60 * 1000, // 15 minutes
224
+ max: 100, // 100 requests per window
225
+ standardHeaders: true,
226
+ legacyHeaders: false,
227
+ });
228
+
229
+ // Strict limit for auth endpoints
230
+ const authLimiter = rateLimit({
231
+ windowMs: 60 * 60 * 1000, // 1 hour
232
+ max: 5, // 5 failed attempts
233
+ skipSuccessfulRequests: true,
234
+ });
235
+
236
+ app.use('/api/', limiter);
237
+ app.use('/api/auth/', authLimiter);
238
+ ```
239
+
240
+ ### Input Validation
241
+ ```typescript
242
+ import { z } from 'zod';
243
+
244
+ const userSchema = z.object({
245
+ email: z.string().email(),
246
+ password: z.string()
247
+ .min(8)
248
+ .regex(/[A-Z]/, 'Must contain uppercase')
249
+ .regex(/[a-z]/, 'Must contain lowercase')
250
+ .regex(/[0-9]/, 'Must contain number')
251
+ .regex(/[^A-Za-z0-9]/, 'Must contain special character'),
252
+ age: z.number().int().min(13).max(120),
253
+ role: z.enum(['user', 'admin']).default('user'),
254
+ });
255
+
256
+ app.post('/api/users', async (req, res) => {
257
+ try {
258
+ const data = userSchema.parse(req.body);
259
+ // Validated data is safe to use
260
+ } catch (error) {
261
+ if (error instanceof z.ZodError) {
262
+ return res.status(400).json({ errors: error.errors });
263
+ }
264
+ throw error;
265
+ }
266
+ });
267
+ ```
268
+
269
+ ## A05: Security Misconfiguration
270
+
271
+ ### Environment Configuration
272
+ ```typescript
273
+ // ✅ Never expose stack traces in production
274
+ app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
275
+ console.error(err.stack); // Log for debugging
276
+
277
+ res.status(500).json({
278
+ error: process.env.NODE_ENV === 'production'
279
+ ? 'Internal server error'
280
+ : err.message,
281
+ });
282
+ });
283
+
284
+ // ✅ Disable sensitive headers
285
+ app.disable('x-powered-by');
286
+
287
+ // ✅ Secure cookie configuration
288
+ app.use(session({
289
+ secret: process.env.SESSION_SECRET!,
290
+ cookie: {
291
+ secure: process.env.NODE_ENV === 'production',
292
+ httpOnly: true,
293
+ sameSite: 'strict',
294
+ maxAge: 24 * 60 * 60 * 1000, // 24 hours
295
+ },
296
+ resave: false,
297
+ saveUninitialized: false,
298
+ }));
299
+ ```
300
+
301
+ ## A06: Vulnerable Components
302
+
303
+ ### Dependency Scanning
304
+ ```bash
305
+ # Check for vulnerabilities
306
+ npm audit
307
+ npm audit fix
308
+
309
+ # Use Snyk for deeper scanning
310
+ npx snyk test
311
+ npx snyk monitor
312
+
313
+ # Keep dependencies updated
314
+ npx npm-check-updates -u
315
+ ```
316
+
317
+ ```json
318
+ // package.json - Use exact versions or ranges
319
+ {
320
+ "dependencies": {
321
+ "express": "^4.18.0", // Minor updates OK
322
+ "lodash": "4.17.21" // Exact version
323
+ },
324
+ "overrides": {
325
+ "vulnerable-package": "^2.0.0" // Force safe version
326
+ }
327
+ }
328
+ ```
329
+
330
+ ## A07: Authentication Failures
331
+
332
+ ### Secure Session Management
333
+ ```typescript
334
+ import jwt from 'jsonwebtoken';
335
+
336
+ // ✅ JWT with short expiry + refresh tokens
337
+ function generateTokens(userId: string) {
338
+ const accessToken = jwt.sign(
339
+ { userId },
340
+ process.env.JWT_SECRET!,
341
+ { expiresIn: '15m' } // Short-lived
342
+ );
343
+
344
+ const refreshToken = jwt.sign(
345
+ { userId, type: 'refresh' },
346
+ process.env.JWT_REFRESH_SECRET!,
347
+ { expiresIn: '7d' }
348
+ );
349
+
350
+ return { accessToken, refreshToken };
351
+ }
352
+
353
+ // ✅ Secure password reset
354
+ async function initiatePasswordReset(email: string) {
355
+ const user = await db.users.findByEmail(email);
356
+ if (!user) return; // Don't reveal if email exists
357
+
358
+ const token = crypto.randomBytes(32).toString('hex');
359
+ const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
360
+
361
+ await db.passwordResets.create({
362
+ userId: user.id,
363
+ token: hashedToken,
364
+ expiresAt: new Date(Date.now() + 60 * 60 * 1000), // 1 hour
365
+ });
366
+
367
+ await sendEmail(email, `Reset link: /reset?token=${token}`);
368
+ }
369
+ ```
370
+
371
+ ### Multi-Factor Authentication
372
+ ```typescript
373
+ import { authenticator } from 'otplib';
374
+ import QRCode from 'qrcode';
375
+
376
+ // Setup TOTP
377
+ async function setupMFA(userId: string) {
378
+ const secret = authenticator.generateSecret();
379
+ const otpauth = authenticator.keyuri(userId, 'MyApp', secret);
380
+ const qrCode = await QRCode.toDataURL(otpauth);
381
+
382
+ await db.users.update(userId, { mfaSecret: encrypt(secret) });
383
+
384
+ return { qrCode, secret };
385
+ }
386
+
387
+ // Verify TOTP
388
+ function verifyMFA(token: string, secret: string): boolean {
389
+ return authenticator.verify({ token, secret });
390
+ }
391
+ ```
392
+
393
+ ## A08: XSS Prevention
394
+
395
+ ```typescript
396
+ // ✅ React auto-escapes by default
397
+ const UserProfile = ({ user }) => (
398
+ <div>{user.name}</div> // Safe - auto-escaped
399
+ );
400
+
401
+ // ⚠️ Dangerous - avoid if possible
402
+ <div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} />
403
+
404
+ // ✅ Sanitize HTML if needed
405
+ import DOMPurify from 'dompurify';
406
+
407
+ const sanitizedHtml = DOMPurify.sanitize(userHtml, {
408
+ ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
409
+ ALLOWED_ATTR: ['href'],
410
+ });
411
+
412
+ // ✅ Content Security Policy
413
+ app.use(helmet.contentSecurityPolicy({
414
+ directives: {
415
+ scriptSrc: ["'self'"], // No inline scripts
416
+ styleSrc: ["'self'", "'unsafe-inline'"],
417
+ },
418
+ }));
419
+ ```
420
+
421
+ ## A09: Logging & Monitoring
422
+
423
+ ```typescript
424
+ import winston from 'winston';
425
+
426
+ const logger = winston.createLogger({
427
+ level: 'info',
428
+ format: winston.format.combine(
429
+ winston.format.timestamp(),
430
+ winston.format.json()
431
+ ),
432
+ transports: [
433
+ new winston.transports.File({ filename: 'error.log', level: 'error' }),
434
+ new winston.transports.File({ filename: 'combined.log' }),
435
+ ],
436
+ });
437
+
438
+ // ✅ Log security events
439
+ function logSecurityEvent(event: string, details: object) {
440
+ logger.warn({
441
+ type: 'security',
442
+ event,
443
+ ...details,
444
+ timestamp: new Date().toISOString(),
445
+ });
446
+ }
447
+
448
+ // Usage
449
+ logSecurityEvent('failed_login', { email, ip: req.ip, userAgent: req.headers['user-agent'] });
450
+ logSecurityEvent('access_denied', { userId, resource, action });
451
+ logSecurityEvent('suspicious_activity', { userId, pattern: 'rapid_requests' });
452
+ ```
453
+
454
+ ## A10: SSRF Prevention
455
+
456
+ ```typescript
457
+ import { URL } from 'url';
458
+
459
+ // ✅ Validate URLs against allowlist
460
+ const ALLOWED_HOSTS = ['api.example.com', 'cdn.example.com'];
461
+
462
+ function isAllowedUrl(urlString: string): boolean {
463
+ try {
464
+ const url = new URL(urlString);
465
+
466
+ // Block private IPs
467
+ const privatePatterns = [
468
+ /^localhost$/i,
469
+ /^127\./,
470
+ /^10\./,
471
+ /^172\.(1[6-9]|2[0-9]|3[01])\./,
472
+ /^192\.168\./,
473
+ /^0\./,
474
+ /^169\.254\./, // Link-local
475
+ ];
476
+
477
+ if (privatePatterns.some(p => p.test(url.hostname))) {
478
+ return false;
479
+ }
480
+
481
+ // Check allowlist
482
+ return ALLOWED_HOSTS.includes(url.hostname);
483
+ } catch {
484
+ return false;
485
+ }
486
+ }
487
+
488
+ app.post('/api/fetch-url', async (req, res) => {
489
+ const { url } = req.body;
490
+
491
+ if (!isAllowedUrl(url)) {
492
+ return res.status(400).json({ error: 'URL not allowed' });
493
+ }
494
+
495
+ const response = await fetch(url);
496
+ // ...
497
+ });
498
+ ```
499
+
500
+ ## Security Checklist
501
+
502
+ ```markdown
503
+ ## Pre-Deployment Checklist
504
+
505
+ ### Authentication
506
+ - [ ] Passwords hashed with bcrypt (cost ≥ 12)
507
+ - [ ] JWT tokens have short expiry
508
+ - [ ] Session cookies are httpOnly, secure, sameSite
509
+ - [ ] Rate limiting on auth endpoints
510
+
511
+ ### Authorization
512
+ - [ ] All endpoints have auth checks
513
+ - [ ] RBAC implemented correctly
514
+ - [ ] No IDOR vulnerabilities
515
+
516
+ ### Input/Output
517
+ - [ ] All input validated with Zod/Joi
518
+ - [ ] SQL queries parameterized
519
+ - [ ] XSS prevented (CSP, escaping)
520
+ - [ ] File uploads validated and sandboxed
521
+
522
+ ### Infrastructure
523
+ - [ ] HTTPS enforced
524
+ - [ ] Security headers configured
525
+ - [ ] Dependencies audited
526
+ - [ ] Secrets in environment variables
527
+
528
+ ### Monitoring
529
+ - [ ] Security events logged
530
+ - [ ] Error monitoring enabled
531
+ - [ ] Alerts configured
532
+ ```
533
+
534
+ ## Resources
535
+
536
+ - **OWASP Top 10**: https://owasp.org/Top10/
537
+ - **OWASP Cheat Sheets**: https://cheatsheetseries.owasp.org/
538
+ - **Node.js Security**: https://nodejs.org/en/docs/guides/security/
539
+ - **Snyk**: https://snyk.io/
@@ -1,7 +1,10 @@
1
1
  ---
2
2
  name: pr
3
- description: "分析代码变更并生成规范的 Pull Request 描述。"
4
- author: xujianjiang
3
+ description: "分析代码变更并生成规范的 Pull Request 描述。Use when generating PR descriptions, creating pull requests, or documenting changes."
4
+ disable-model-invocation: true
5
+ metadata:
6
+ version: "1.0.0"
7
+ author: "xujianjiang"
5
8
  ---
6
9
 
7
10
  # Git PR 描述 Skill