agents-templated 1.0.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.
@@ -0,0 +1,269 @@
1
+ ---
2
+ title: "Security Rules & Best Practices"
3
+ description: "Framework and language-agnostic security patterns for enterprise applications"
4
+ version: "3.0.0"
5
+ tags: ["security", "owasp", "authentication", "validation"]
6
+ ---
7
+
8
+ # Security Rules & Best Practices
9
+
10
+ You are an expert security-focused developer implementing security-first development regardless of technology stack.
11
+
12
+ ## Core Security Principles
13
+
14
+ - **Defense in Depth**: Implement multiple layers of security controls
15
+ - **Least Privilege**: Grant minimum necessary permissions for each role/service
16
+ - **Input Validation**: Validate all inputs at boundaries with appropriate schema validation
17
+ - **Output Encoding**: Encode all outputs to prevent injection attacks
18
+ - **Secure by Default**: Choose secure configurations over convenience
19
+ - **Fail Securely**: Default to denial, require explicit allow
20
+
21
+ ## Authentication & Authorization Patterns
22
+
23
+ ### Session Management Best Practices
24
+
25
+ Implement secure session handling regardless of framework:
26
+ - **Session storage**: Use secure cookies (HttpOnly, Secure, SameSite) or JWT tokens
27
+ - **Token expiration**: Implement appropriate timeout for token validity
28
+ - **Refresh tokens**: Separate long-lived and short-lived tokens
29
+ - **Session invalidation**: Properly terminate sessions on logout
30
+ - **CSRF protection**: Verify request origin for state-changing operations
31
+
32
+ ### Authentication Patterns (Language-Agnostic)
33
+
34
+ Authentication Flow:
35
+ 1. User provides credentials (username/password)
36
+ 2. Validate credentials against hashed password in database
37
+ 3. Create session or JWT token with user identity
38
+ 4. Return session/token to client with secure flags
39
+ 5. Client includes token/session in subsequent requests
40
+ 6. Server validates token/session on each request
41
+ 7. Extract user identity from verified token/session
42
+
43
+ **Key Requirements:**
44
+ - Hash passwords with strong algorithms (bcrypt, scrypt, argon2)
45
+ - Salt rounds: 12+ for bcrypt
46
+ - Never store plaintext passwords
47
+ - Implement rate limiting on authentication endpoints
48
+ - Log authentication attempts (failures especially)
49
+ - Provide clear error messages that don't leak user information
50
+
51
+ ### Authorization Patterns (Language-Agnostic)
52
+
53
+ Authorization Flow:
54
+ 1. Extract user identity from authenticated session/token
55
+ 2. For each protected operation:
56
+ a. Check if user is authenticated
57
+ b. Retrieve user''s roles/permissions from database
58
+ c. Verify required permissions for operation
59
+ d. Allow or deny based on permission check
60
+ 3. Log authorization checks (especially failures)
61
+ 4. Return appropriate error for denied access
62
+
63
+ **Role-Based Access Control (RBAC):**
64
+ - Define roles with clear permissions (admin, moderator, user, guest)
65
+ - Assign roles to users (can be multiple)
66
+ - Check user''s roles before allowing sensitive operations
67
+ - Implement at API boundaries and critical business logic
68
+ - Audit role changes and permission checks
69
+
70
+ ## Input Validation & Sanitization
71
+
72
+ ### Validation Strategy (Technology-Agnostic)
73
+
74
+ Validate all user inputs at API boundaries:
75
+
76
+ Validation Process:
77
+ 1. Define schema/rules for each input
78
+ - Data type (string, number, boolean, date, etc.)
79
+ - Length constraints (min/max)
80
+ - Format requirements (regex patterns)
81
+ - Allowed values (whitelist)
82
+ - Required fields
83
+
84
+ 2. Validate incoming data against schema
85
+ - Reject invalid data with clear error messages
86
+ - Never modify user input, reject or accept
87
+
88
+ 3. Transform/normalize data if needed
89
+ - Trim whitespace
90
+ - Convert to lowercase/uppercase as appropriate
91
+ - Parse dates to consistent format
92
+
93
+ 4. Return validation result
94
+ - Success with validated data
95
+ - Failure with specific field errors
96
+
97
+ **Common Validation Rules:**
98
+ - Email: Valid format using standardized validation, convert to lowercase
99
+ - Password: Minimum 8 characters, complexity requirements (uppercase, lowercase, number, special)
100
+ - Names: 2-100 characters, alphanumeric with spaces allowed
101
+ - URLs: Valid URL format for whitelist only
102
+ - Phone: Valid format for your region
103
+ - User IDs: UUID v4 format or similar non-sequential identifiers
104
+
105
+ ### Special Input Handling
106
+
107
+ **File Uploads:**
108
+ - Validate file content type (MIME type check from file content, not extension)
109
+ - Enforce size limits (max upload size)
110
+ - Scan for malware when possible
111
+ - Store outside web root
112
+ - No execute permission on upload directory
113
+ - Serve with inline=false to force download
114
+
115
+ **API Parameters:**
116
+ - Validate query parameters with same rules as request body
117
+ - Whitelist allowed parameters per endpoint
118
+ - Validate pagination limits (max 100-1000 items)
119
+ - Validate sort fields against whitelist
120
+
121
+ **Database Queries:**
122
+ - Use ORM/parameterized queries only (never string concatenation)
123
+ - Filter results to authenticated user''s data
124
+ - Limit results with pagination
125
+ - Monitor for suspicious query patterns
126
+
127
+ ## Rate Limiting & DoS Protection
128
+
129
+ ### Rate Limiting Strategy
130
+
131
+ Implement rate limiting on sensitive endpoints:
132
+
133
+ Rate Limiting Levels:
134
+ - Authentication endpoints: 5 attempts per 15 minutes per IP
135
+ - API endpoints: 100-1000 requests per hour per user/IP
136
+ - Public endpoints: 1000+ requests per hour per IP
137
+ - Critical operations: 1 attempt per minute per user
138
+
139
+ **Implementation approach:**
140
+ - Use Redis or similar for distributed rate limiting
141
+ - Track by IP address, user ID, or API key depending on endpoint
142
+ - Return 429 (Too Many Requests) when limit exceeded
143
+ - Include retry-after header in response
144
+ - Log rate limit violations
145
+
146
+ ## OWASP Top 10 Protection
147
+
148
+ ### A01: Broken Access Control
149
+ - Implement authentication on all protected endpoints
150
+ - Check authorization for current user before returning data
151
+ - Use role-based access control with clear permission model
152
+ - Validate user can only access their own data
153
+ - Log authorization failures for security monitoring
154
+
155
+ ### A02: Cryptographic Failures
156
+ - Hash passwords with strong algorithms (bcrypt, scrypt, argon2)
157
+ - Use HTTPS in production for all communications
158
+ - Store secrets in environment variables, never in code
159
+ - Use secure cookie flags (HttpOnly, Secure, SameSite)
160
+ - Encrypt sensitive data at rest when appropriate
161
+
162
+ ### A03: Injection
163
+ - Use ORM/parameterized queries only (no string concatenation)
164
+ - Validate all inputs with schema/whitelist approach
165
+ - Encode output data in appropriate context (HTML, URL, etc.)
166
+ - Implement Content Security Policy headers
167
+ - Use prepared statements for database queries
168
+
169
+ ### A04: Insecure Design
170
+ - Implement authentication and authorization from start
171
+ - Rate limit authentication endpoints
172
+ - Validate input at every API boundary
173
+ - Design with fail-secure defaults
174
+ - Implement comprehensive error handling
175
+
176
+ ### A05: Security Misconfiguration
177
+ - Run only necessary services/features
178
+ - Implement all security headers (CSP, X-Frame-Options, HSTS, etc.)
179
+ - Update frameworks and dependencies regularly
180
+ - Remove default accounts and credentials
181
+ - Validate environment variables at startup
182
+
183
+ ### A06: Vulnerable Components
184
+ - Keep dependencies updated with security patches
185
+ - Use lock files (package-lock.json, requirements.txt, etc.)
186
+ - Regularly scan dependencies for vulnerabilities
187
+ - Remove unused dependencies
188
+ - Only use supported versions of frameworks
189
+
190
+ ### A07: Authentication Failure
191
+ - Implement strong password requirements
192
+ - Use rate limiting on authentication endpoints
193
+ - Hash passwords securely (bcrypt, scrypt, argon2)
194
+ - Implement session timeouts
195
+ - Log authentication attempts
196
+
197
+ ### A08: Data Integrity Failures
198
+ - Validate all input data with schema validation
199
+ - Implement proper error handling
200
+ - Log integrity violation attempts
201
+ - Use strong checksums/hashes for critical data
202
+ - Implement database constraints
203
+
204
+ ### A09: Logging and Monitoring Failure
205
+ - Log authentication and authorization events
206
+ - Log sensitive operations and data access
207
+ - Monitor for suspicious patterns
208
+ - Keep logs secure and don''t expose sensitive info
209
+ - Alert on security-relevant events
210
+
211
+ ### A10: SSRF (Server-Side Request Forgery)
212
+ - Validate and whitelist URLs that application accesses
213
+ - Implement network-level restrictions
214
+ - Disable unused URL schemes
215
+ - Implement timeouts on external requests
216
+ - Log and monitor external API calls
217
+
218
+ ## Environment & Secrets Management
219
+
220
+ ### Environment Variables
221
+
222
+ Environment Variable Validation Pattern:
223
+ 1. Define all required variables with types
224
+ 2. Load from .env file or environment not from code
225
+ 3. Validate all variables exist at startup
226
+ 4. Validate all variables are correct type/format
227
+ 5. Provide clear error if validation fails
228
+ 6. Never log or expose environment variables
229
+
230
+ **Sensitive Variables:**
231
+ - Database credentials (URL, passwords)
232
+ - API keys and secrets
233
+ - Encryption keys
234
+ - Authentication secrets (session secret, JWT secret)
235
+ - Third-party service credentials
236
+
237
+ No sensitive variables should ever be:
238
+ - Committed to version control
239
+ - Logged (even in debug logs)
240
+ - Exposed in error messages
241
+ - Included in client-side code
242
+ - Transmitted in URLs
243
+
244
+ ## Security Checklist
245
+
246
+ Before deploying to production:
247
+
248
+ - [ ] All inputs validated with schema validation
249
+ - [ ] Password hashing implemented with strong algorithm
250
+ - [ ] Rate limiting on authentication endpoints
251
+ - [ ] HTTPS enforced in production
252
+ - [ ] Security headers configured
253
+ - [ ] Environment variables validated at startup
254
+ - [ ] No sensitive data in logs
255
+ - [ ] Database queries use ORM (no raw SQL)
256
+ - [ ] Authorization checks on protected endpoints
257
+ - [ ] Error messages don''t leak sensitive information
258
+ - [ ] External API calls use HTTPS
259
+ - [ ] Dependencies scanned for vulnerabilities
260
+ - [ ] Unused dependencies removed
261
+ - [ ] Dead code removed
262
+ - [ ] Secrets never committed to version control
263
+ - [ ] Session/token timeouts configured
264
+ - [ ] CSRF protection implemented (if applicable)
265
+
266
+ ---
267
+
268
+ Remember: **Security must be built in from the beginning, not added as an afterthought.**
269
+ Every feature should consider security implications, and every developer should understand these principles.
@@ -0,0 +1,344 @@
1
+ ---
2
+ title: "Code Style and Standards"
3
+ description: "Language-agnostic naming conventions, formatting rules, and code quality standards"
4
+ alwaysApply: true
5
+ version: "3.0.0"
6
+ tags: ["style", "formatting", "naming", "quality"]
7
+ globs:
8
+ - "**/*"
9
+ ---
10
+
11
+ # Code Style and Standards
12
+
13
+ Language and framework-agnostic standards for clean, maintainable code.
14
+
15
+ ## General Code Quality
16
+
17
+ ### Core Principles
18
+
19
+ - **Readability**: Code should be easy to understand without extensive comments
20
+ - **Consistency**: Follow the same patterns throughout the codebase
21
+ - **Simplicity**: Prefer simple solutions to complex ones
22
+ - **SOLID principles**: Single responsibility, Open/closed, Liskov, Interface segregation, Dependency inversion
23
+ - **DRY**: Don''t Repeat Yourself - extract common patterns
24
+
25
+ ### Code Review Standards
26
+
27
+ Code should:
28
+ - Do one thing well
29
+ - Be testable
30
+ - Have no dead code
31
+ - Follow established patterns
32
+ - Include appropriate comments
33
+ - Have meaningful names
34
+ - Handle errors appropriately
35
+ - Consider security implications
36
+ - Consider performance implications
37
+
38
+ ## Naming Conventions
39
+
40
+ ### File Naming
41
+
42
+ Choose from established conventions:
43
+
44
+ **Option 1: kebab-case (Recommended)**
45
+ - File names: `user-profile.ts`, `navigation-bar.tsx`, `date-utils.js`
46
+ - Matches URLs and file systems
47
+ - Language-agnostic
48
+ - Easy to type and read
49
+
50
+ **Option 2: snake_case**
51
+ - File names: `user_profile.py`, `date_utils.go`
52
+ - Common in Python, Go, and Ruby
53
+ - Matches language conventions
54
+
55
+ **Option 3: PascalCase**
56
+ - File names: `UserProfile.tsx`, `DateUtils.ts`
57
+ - Common in C# and some JavaScript frameworks
58
+ - Use consistently if chosen
59
+
60
+ **Consistency rule**: Pick ONE and use it throughout the entire project.
61
+
62
+ ### Code Naming
63
+
64
+ Consistent naming patterns:
65
+
66
+ **Variables and Functions**
67
+ - Use camelCase: `getUserData`, `isLoading`, `handleSubmit`
68
+ - Use English words (even in non-English projects)
69
+ - Be descriptive: `user` is worse than `currentUser`
70
+ - Avoid abbreviations: `getDesc` vs `getDescription`
71
+ - Prefix booleans with is/has: `isActive`, `hasPermission`
72
+
73
+ **Constants**
74
+ - Use UPPER_SNAKE_CASE: `MAX_RETRIES`, `API_BASE_URL`
75
+ - Immutable values that don''t change
76
+ - Global configuration values
77
+ - Magic numbers should become constants
78
+
79
+ **Classes/Types/Interfaces**
80
+ - Use PascalCase: `UserProfile`, `ApiResponse`, `DatabaseConfig`
81
+ - Descriptive and specific names
82
+ - Avoid generic names like `Data`, `Info`, `Object`
83
+
84
+ **Enums**
85
+ - Type name PascalCase: `UserStatus`
86
+ - Values UPPER_SNAKE_CASE: `ACTIVE`, `INACTIVE`
87
+ - Example: `UserStatus.ACTIVE`, `Theme.DARK_MODE`
88
+
89
+ ### Examples
90
+
91
+ Good naming:
92
+ ```
93
+ getUserById()
94
+ isValidEmail()
95
+ parseJsonResponse()
96
+ calculateProposedDiscount()
97
+ MAXIMUM_RETRY_ATTEMPTS
98
+ ValidationError
99
+ ```
100
+
101
+ Bad naming:
102
+ ```
103
+ get()
104
+ foo(), bar(), x
105
+ process()
106
+ u1, u2, s
107
+ var1, var2
108
+ handleIt()
109
+ ```
110
+
111
+ ## Formatting
112
+
113
+ ### Consistent Formatting
114
+
115
+ Use automated tools:
116
+ - **Prettier**: JavaScript/TypeScript/CSS/YAML
117
+ - **Black**: Python
118
+ - **gofmt**: Go
119
+ - **rustfmt**: Rust
120
+ - **clang-format**: C/C++
121
+ - Your language''s standard formatter
122
+
123
+ Benefits:
124
+ - No debates about formatting
125
+ - Quick review of actual changes
126
+ - Consistent codebase
127
+
128
+ ### Line Length
129
+
130
+ - Target: 80-120 characters
131
+ - Maximum: 120-140 characters
132
+ - Avoid scrolling horizontally
133
+
134
+ ### Indentation
135
+
136
+ Choose ONE and use consistently:
137
+ - **2 spaces**: JavaScript, YAML, some Python
138
+ - **4 spaces**: Python, Java, most languages
139
+ - **Tabs**: If configured, consistently
140
+
141
+ ### Comments & Documentation
142
+
143
+ Good comments explain:
144
+ - **Why**: The reason for this code
145
+ - **Complex logic**: How it works if not obvious
146
+ - **Edge cases**: Special handling and why
147
+ - **Warnings**: Performance implications or gotchas
148
+
149
+ Bad comments:
150
+ ```
151
+ // Increment x
152
+ x = x + 1
153
+
154
+ // Loop through users
155
+ for (user in users) { ... }
156
+
157
+ // This is a variable
158
+ let name = getUserName()
159
+ ```
160
+
161
+ Good comments:
162
+ ```
163
+ // Increment retry counter before exponential backoff
164
+ retryCount = retryCount + 1
165
+
166
+ // Process users in batches to prevent memory overload
167
+ for (batch in users.batches()) { ... }
168
+
169
+ // Fetch fresh name from API to avoid stale cache
170
+ let name = getUserName()
171
+ ```
172
+
173
+ ### Comments vs Code
174
+
175
+ Let code speak for itself:
176
+
177
+ Instead of:
178
+ ```
179
+ // Get user age
180
+ int age = currentYear - birthYear
181
+ ```
182
+
183
+ Write:
184
+ ```
185
+ int age = calculateAge(currentYear, birthYear)
186
+ ```
187
+
188
+ ## Code Organization
189
+
190
+ ### Module Organization
191
+
192
+ Order within files:
193
+ 1. **Imports/Dependencies** - at top
194
+ 2. **Constants** - module-level constants
195
+ 3. **Types/Interfaces** - type definitions
196
+ 4. **Functions/Classes** - main code (public first, private after)
197
+ 5. **Exports** - explicit exports at end
198
+
199
+ ### Function Organization
200
+
201
+ Function structure:
202
+ 1. **Parameters** - at top
203
+ 2. **Early returns** - validate inputs early
204
+ 3. **Logic** - main implementation
205
+ 4. **Return** - return result
206
+
207
+ ### Class/Object Organization
208
+
209
+ Class structure:
210
+ 1. **Constructor/initializer**
211
+ 2. **Public methods**
212
+ 3. **Private methods**
213
+ 4. **Getters/setters**
214
+ 5. **Static methods** (if applicable)
215
+
216
+ ## Type Definitions
217
+
218
+ ### Clear Type Contracts
219
+
220
+ Document what your types expect:
221
+
222
+ ```
223
+ Define data structures clearly:
224
+ - What fields are required
225
+ - What data types
226
+ - What values are valid
227
+ - Any constraints or rules
228
+ ```
229
+
230
+ ### Avoid Magic Values
231
+
232
+ Instead of magic numbers/strings:
233
+ ```
234
+ if (status === 1) { ... }
235
+ if (timeout === 60000) { ... }
236
+
237
+ const ACTIVE_STATUS = 1
238
+ const DEFAULT_TIMEOUT_MS = 60000
239
+ if (status === ACTIVE_STATUS) { ... }
240
+ ```
241
+
242
+ ## Error Handling
243
+
244
+ ### Clear Error Messages
245
+
246
+ Error messages should:
247
+ - Describe what went wrong
248
+ - Explain why (if not obvious)
249
+ - Suggest how to fix
250
+ - Use user-friendly language
251
+
252
+ Good error messages:
253
+ - "Email format is invalid. Please enter a valid email address."
254
+ - "Password must be at least 8 characters."
255
+ - "User with this email already exists."
256
+
257
+ Bad error messages:
258
+ - "Error"
259
+ - "Invalid input"
260
+ - "Stack trace here..."
261
+
262
+ ### Error Handling Pattern
263
+
264
+ Proper error handling:
265
+ 1. Catch/handle errors explicitly
266
+ 2. Log error with context
267
+ 3. Return appropriate error response
268
+ 4. Never expose sensitive data
269
+ 5. Include error code for client handling
270
+
271
+ ## Security in Code
272
+
273
+ ### Dangerous Patterns to Avoid
274
+
275
+ Never:
276
+ - Store secrets in code
277
+ - Log sensitive data
278
+ - Dynamic SQL/query construction
279
+ - Eval user input
280
+ - Hardcoded API keys
281
+ - Return sensitive data in errors
282
+ - Skip input validation
283
+
284
+ Always:
285
+ - Validate all inputs
286
+ - Use parameterized queries
287
+ - Hash sensitive data
288
+ - Use environment variables for secrets
289
+ - Log security events
290
+ - Encode output appropriately
291
+
292
+ ## Performance Considerations
293
+
294
+ ### Avoid N+1 Queries
295
+
296
+ Good:
297
+ ```
298
+ Get all users once with their posts
299
+ Result: 1 query
300
+ ```
301
+
302
+ Bad:
303
+ ```
304
+ For each user (loop):
305
+ Get posts for that user
306
+ Result: 1 + N queries
307
+ ```
308
+
309
+ ### Avoid Premature Optimization
310
+
311
+ Focus on:
312
+ 1. **Correct code first** - Works before optimizing
313
+ 2. **Readable code** - Easy to understand
314
+ 3. **Profile critical paths** - Where time is spent
315
+ 4. **Optimize bottlenecks** - Only where it matters
316
+
317
+ ## Testing
318
+
319
+ ### Code for Testability
320
+
321
+ Testable code:
322
+ - Has clear inputs and outputs
323
+ - Is easy to mock dependencies
324
+ - Has single responsibility
325
+ - Doesn''t depend on side effects
326
+ - Has deterministic behavior
327
+
328
+ ### Test Naming
329
+
330
+ Test names describe what is being tested:
331
+ ```
332
+ testEmailValidationAcceptsValidEmail()
333
+ testUserCreationReturnsUserWithId()
334
+ testPasswordResetTokenExpiresAfter24Hours()
335
+
336
+ test1()
337
+ testFunction()
338
+ testWorks()
339
+ ```
340
+
341
+ ---
342
+
343
+ Remember: **Write code for humans first, computers second.**
344
+ Clean code is maintainable code, and maintainable code is more secure, performant, and bug-free.