@xmarts/genius-setup 1.15.0 → 1.16.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.
- package/hooks/genius_inject.py +90 -21
- package/package.json +1 -1
- package/plugin/skills/content-humanizer/SKILL.md +60 -0
- package/plugin/skills/content-style-bible/SKILL.md +77 -0
- package/plugin/skills/content-war-tank/SKILL.md +22 -0
- package/plugin/skills/contentforge/SKILL.md +40 -0
- package/plugin/skills/debugging-and-error-recovery/SKILL.md +300 -0
- package/plugin/skills/documentation-and-adrs/SKILL.md +278 -0
- package/plugin/skills/interview-me/SKILL.md +225 -0
- package/plugin/skills/security-and-hardening/SKILL.md +461 -0
- package/plugin/skills/source-driven-development/SKILL.md +194 -0
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: security-and-hardening
|
|
3
|
+
description: Hardens code against vulnerabilities. Use when handling user input, authentication, data storage, or external integrations. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Security and Hardening
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Security-first development practices for web applications. Treat every external input as hostile, every secret as sacred, and every authorization check as mandatory. Security isn't a phase — it's a constraint on every line of code that touches user data, authentication, or external systems.
|
|
11
|
+
|
|
12
|
+
## When to Use
|
|
13
|
+
|
|
14
|
+
- Building anything that accepts user input
|
|
15
|
+
- Implementing authentication or authorization
|
|
16
|
+
- Storing or transmitting sensitive data
|
|
17
|
+
- Integrating with external APIs or services
|
|
18
|
+
- Adding file uploads, webhooks, or callbacks
|
|
19
|
+
- Handling payment or PII data
|
|
20
|
+
|
|
21
|
+
## Process: Threat Model First
|
|
22
|
+
|
|
23
|
+
Controls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker:
|
|
24
|
+
|
|
25
|
+
1. **Map the trust boundaries.** Where does untrusted data cross into your system? HTTP requests, form fields, file uploads, webhooks, third-party APIs, message queues, and **LLM output**. Every boundary is attack surface.
|
|
26
|
+
2. **Name the assets.** What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement.
|
|
27
|
+
3. **Run STRIDE over each boundary** — a quick lens, not a ceremony:
|
|
28
|
+
|
|
29
|
+
| Threat | Ask | Typical mitigation |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| **S**poofing | Can someone impersonate a user/service? | Authentication, signature verification |
|
|
32
|
+
| **T**ampering | Can data be altered in transit or at rest? | Integrity checks, parameterized queries, HTTPS |
|
|
33
|
+
| **R**epudiation | Can an action be denied later? | Audit logging of security events |
|
|
34
|
+
| **I**nformation disclosure | Can data leak? | Encryption, field allowlists, generic errors |
|
|
35
|
+
| **D**enial of service | Can it be overwhelmed? | Rate limiting, input size caps, timeouts |
|
|
36
|
+
| **E**levation of privilege | Can a user gain rights they shouldn't? | Authorization checks, least privilege |
|
|
37
|
+
|
|
38
|
+
4. **Write abuse cases next to use cases.** For each feature, ask "how would I misuse this?" — then make that your first test.
|
|
39
|
+
|
|
40
|
+
If you can't name the trust boundaries for a feature, you're not ready to secure it. This is OWASP **A04: Insecure Design** — most breaches begin in design, not code.
|
|
41
|
+
|
|
42
|
+
## The Three-Tier Boundary System
|
|
43
|
+
|
|
44
|
+
### Always Do (No Exceptions)
|
|
45
|
+
|
|
46
|
+
- **Validate all external input** at the system boundary (API routes, form handlers)
|
|
47
|
+
- **Parameterize all database queries** — never concatenate user input into SQL
|
|
48
|
+
- **Encode output** to prevent XSS (use framework auto-escaping, don't bypass it)
|
|
49
|
+
- **Use HTTPS** for all external communication
|
|
50
|
+
- **Hash passwords** with bcrypt/scrypt/argon2 (never store plaintext)
|
|
51
|
+
- **Set security headers** (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)
|
|
52
|
+
- **Use httpOnly, secure, sameSite cookies** for sessions
|
|
53
|
+
- **Run `npm audit`** (or equivalent) before every release
|
|
54
|
+
|
|
55
|
+
### Ask First (Requires Human Approval)
|
|
56
|
+
|
|
57
|
+
- Adding new authentication flows or changing auth logic
|
|
58
|
+
- Storing new categories of sensitive data (PII, payment info)
|
|
59
|
+
- Adding new external service integrations
|
|
60
|
+
- Changing CORS configuration
|
|
61
|
+
- Adding file upload handlers
|
|
62
|
+
- Modifying rate limiting or throttling
|
|
63
|
+
- Granting elevated permissions or roles
|
|
64
|
+
|
|
65
|
+
### Never Do
|
|
66
|
+
|
|
67
|
+
- **Never commit secrets** to version control (API keys, passwords, tokens)
|
|
68
|
+
- **Never log sensitive data** (passwords, tokens, full credit card numbers)
|
|
69
|
+
- **Never trust client-side validation** as a security boundary
|
|
70
|
+
- **Never disable security headers** for convenience
|
|
71
|
+
- **Never use `eval()` or `innerHTML`** with user-provided data
|
|
72
|
+
- **Never store sessions in client-accessible storage** (localStorage for auth tokens)
|
|
73
|
+
- **Never expose stack traces** or internal error details to users
|
|
74
|
+
|
|
75
|
+
## OWASP Top 10 Prevention Patterns
|
|
76
|
+
|
|
77
|
+
These are prevention patterns, not a ranking. For the 2021 ordering, see the quick-reference table in `references/security-checklist.md`.
|
|
78
|
+
|
|
79
|
+
### Injection (SQL, NoSQL, OS Command)
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
// BAD: SQL injection via string concatenation
|
|
83
|
+
const query = `SELECT * FROM users WHERE id = '${userId}'`;
|
|
84
|
+
|
|
85
|
+
// GOOD: Parameterized query
|
|
86
|
+
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
|
|
87
|
+
|
|
88
|
+
// GOOD: ORM with parameterized input
|
|
89
|
+
const user = await prisma.user.findUnique({ where: { id: userId } });
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Broken Authentication
|
|
93
|
+
|
|
94
|
+
```typescript
|
|
95
|
+
// Password hashing
|
|
96
|
+
import { hash, compare } from 'bcrypt';
|
|
97
|
+
|
|
98
|
+
const SALT_ROUNDS = 12;
|
|
99
|
+
const hashedPassword = await hash(plaintext, SALT_ROUNDS);
|
|
100
|
+
const isValid = await compare(plaintext, hashedPassword);
|
|
101
|
+
|
|
102
|
+
// Session management
|
|
103
|
+
app.use(session({
|
|
104
|
+
secret: process.env.SESSION_SECRET, // From environment, not code
|
|
105
|
+
resave: false,
|
|
106
|
+
saveUninitialized: false,
|
|
107
|
+
cookie: {
|
|
108
|
+
httpOnly: true, // Not accessible via JavaScript
|
|
109
|
+
secure: true, // HTTPS only
|
|
110
|
+
sameSite: 'lax', // CSRF protection
|
|
111
|
+
maxAge: 24 * 60 * 60 * 1000, // 24 hours
|
|
112
|
+
},
|
|
113
|
+
}));
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Cross-Site Scripting (XSS)
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
// BAD: Rendering user input as HTML
|
|
120
|
+
element.innerHTML = userInput;
|
|
121
|
+
|
|
122
|
+
// GOOD: Use framework auto-escaping (React does this by default)
|
|
123
|
+
return <div>{userInput}</div>;
|
|
124
|
+
|
|
125
|
+
// If you MUST render HTML, sanitize first
|
|
126
|
+
import DOMPurify from 'dompurify';
|
|
127
|
+
const clean = DOMPurify.sanitize(userInput);
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Broken Access Control
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
// Always check authorization, not just authentication
|
|
134
|
+
app.patch('/api/tasks/:id', authenticate, async (req, res) => {
|
|
135
|
+
const task = await taskService.findById(req.params.id);
|
|
136
|
+
|
|
137
|
+
// Check that the authenticated user owns this resource
|
|
138
|
+
if (task.ownerId !== req.user.id) {
|
|
139
|
+
return res.status(403).json({
|
|
140
|
+
error: { code: 'FORBIDDEN', message: 'Not authorized to modify this task' }
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Proceed with update
|
|
145
|
+
const updated = await taskService.update(req.params.id, req.body);
|
|
146
|
+
return res.json(updated);
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Security Misconfiguration
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
// Security headers (use helmet for Express)
|
|
154
|
+
import helmet from 'helmet';
|
|
155
|
+
app.use(helmet());
|
|
156
|
+
|
|
157
|
+
// Content Security Policy
|
|
158
|
+
app.use(helmet.contentSecurityPolicy({
|
|
159
|
+
directives: {
|
|
160
|
+
defaultSrc: ["'self'"],
|
|
161
|
+
scriptSrc: ["'self'"],
|
|
162
|
+
styleSrc: ["'self'", "'unsafe-inline'"], // Tighten if possible
|
|
163
|
+
imgSrc: ["'self'", 'data:', 'https:'],
|
|
164
|
+
connectSrc: ["'self'"],
|
|
165
|
+
},
|
|
166
|
+
}));
|
|
167
|
+
|
|
168
|
+
// CORS — restrict to known origins
|
|
169
|
+
app.use(cors({
|
|
170
|
+
origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000',
|
|
171
|
+
credentials: true,
|
|
172
|
+
}));
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Sensitive Data Exposure
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
// Never return sensitive fields in API responses
|
|
179
|
+
function sanitizeUser(user: UserRecord): PublicUser {
|
|
180
|
+
const { passwordHash, resetToken, ...publicFields } = user;
|
|
181
|
+
return publicFields;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Use environment variables for secrets
|
|
185
|
+
const API_KEY = process.env.STRIPE_API_KEY;
|
|
186
|
+
if (!API_KEY) throw new Error('STRIPE_API_KEY not configured');
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### Server-Side Request Forgery (SSRF)
|
|
190
|
+
|
|
191
|
+
Any time the server fetches a URL the user influenced — webhooks, "import from URL", image proxies, link previews — an attacker can aim it at internal services (cloud metadata, `localhost`, private IPs).
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
// BAD: fetch whatever the user gives you
|
|
195
|
+
await fetch(req.body.webhookUrl);
|
|
196
|
+
|
|
197
|
+
// GOOD: allowlist scheme + host, reject if ANY resolved IP is private, forbid redirects
|
|
198
|
+
import { lookup } from 'node:dns/promises';
|
|
199
|
+
import ipaddr from 'ipaddr.js';
|
|
200
|
+
|
|
201
|
+
const ALLOWED_HOSTS = new Set(['hooks.example.com']);
|
|
202
|
+
|
|
203
|
+
async function assertSafeUrl(raw: string): Promise<URL> {
|
|
204
|
+
const url = new URL(raw);
|
|
205
|
+
if (url.protocol !== 'https:') throw new Error('https only');
|
|
206
|
+
if (!ALLOWED_HOSTS.has(url.hostname)) throw new Error('host not allowed');
|
|
207
|
+
// Resolve ALL records; a single private/reserved address fails the check.
|
|
208
|
+
const addrs = await lookup(url.hostname, { all: true });
|
|
209
|
+
if (addrs.some((a) => ipaddr.parse(a.address).range() !== 'unicast')) {
|
|
210
|
+
throw new Error('private/reserved IP');
|
|
211
|
+
}
|
|
212
|
+
return url;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
await fetch(await assertSafeUrl(req.body.webhookUrl), { redirect: 'error' });
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
The `range() !== 'unicast'` check covers loopback, link-local `169.254.169.254` (cloud metadata, the #1 SSRF target), private, and unique-local ranges across IPv4 and IPv6.
|
|
219
|
+
|
|
220
|
+
**Caveat — this still has a TOCTOU gap.** `fetch` resolves DNS again after the check, so an attacker using a short-TTL record can rebind to an internal IP between validation and connection. For high-risk surfaces, resolve once and connect to the pinned IP, or put a filtering agent in front (`request-filtering-agent` / `ssrf-req-filter`).
|
|
221
|
+
|
|
222
|
+
## Input Validation Patterns
|
|
223
|
+
|
|
224
|
+
### Schema Validation at Boundaries
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
import { z } from 'zod';
|
|
228
|
+
|
|
229
|
+
const CreateTaskSchema = z.object({
|
|
230
|
+
title: z.string().min(1).max(200).trim(),
|
|
231
|
+
description: z.string().max(2000).optional(),
|
|
232
|
+
priority: z.enum(['low', 'medium', 'high']).default('medium'),
|
|
233
|
+
dueDate: z.string().datetime().optional(),
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// Validate at the route handler
|
|
237
|
+
app.post('/api/tasks', async (req, res) => {
|
|
238
|
+
const result = CreateTaskSchema.safeParse(req.body);
|
|
239
|
+
if (!result.success) {
|
|
240
|
+
return res.status(422).json({
|
|
241
|
+
error: {
|
|
242
|
+
code: 'VALIDATION_ERROR',
|
|
243
|
+
message: 'Invalid input',
|
|
244
|
+
details: result.error.flatten(),
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
// result.data is now typed and validated
|
|
249
|
+
const task = await taskService.create(result.data);
|
|
250
|
+
return res.status(201).json(task);
|
|
251
|
+
});
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### File Upload Safety
|
|
255
|
+
|
|
256
|
+
```typescript
|
|
257
|
+
// Restrict file types and sizes
|
|
258
|
+
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
|
|
259
|
+
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
|
|
260
|
+
|
|
261
|
+
function validateUpload(file: UploadedFile) {
|
|
262
|
+
if (!ALLOWED_TYPES.includes(file.mimetype)) {
|
|
263
|
+
throw new ValidationError('File type not allowed');
|
|
264
|
+
}
|
|
265
|
+
if (file.size > MAX_SIZE) {
|
|
266
|
+
throw new ValidationError('File too large (max 5MB)');
|
|
267
|
+
}
|
|
268
|
+
// Don't trust the file extension — check magic bytes if critical
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
## Triaging npm audit Results
|
|
273
|
+
|
|
274
|
+
Not all audit findings require immediate action. Use this decision tree:
|
|
275
|
+
|
|
276
|
+
```
|
|
277
|
+
npm audit reports a vulnerability
|
|
278
|
+
├── Severity: critical or high
|
|
279
|
+
│ ├── Is the vulnerable code reachable in your app?
|
|
280
|
+
│ │ ├── YES --> Fix immediately (update, patch, or replace the dependency)
|
|
281
|
+
│ │ └── NO (dev-only dep, unused code path) --> Fix soon, but not a blocker
|
|
282
|
+
│ └── Is a fix available?
|
|
283
|
+
│ ├── YES --> Update to the patched version
|
|
284
|
+
│ └── NO --> Check for workarounds, consider replacing the dependency, or add to allowlist with a review date
|
|
285
|
+
├── Severity: moderate
|
|
286
|
+
│ ├── Reachable in production? --> Fix in the next release cycle
|
|
287
|
+
│ └── Dev-only? --> Fix when convenient, track in backlog
|
|
288
|
+
└── Severity: low
|
|
289
|
+
└── Track and fix during regular dependency updates
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
**Key questions:**
|
|
293
|
+
- Is the vulnerable function actually called in your code path?
|
|
294
|
+
- Is the dependency a runtime dependency or dev-only?
|
|
295
|
+
- Is the vulnerability exploitable given your deployment context (e.g., a server-side vulnerability in a client-only app)?
|
|
296
|
+
|
|
297
|
+
When you defer a fix, document the reason and set a review date.
|
|
298
|
+
|
|
299
|
+
### Supply-Chain Hygiene
|
|
300
|
+
|
|
301
|
+
`npm audit` catches known CVEs; it won't catch a malicious or typosquatted package. Also:
|
|
302
|
+
|
|
303
|
+
- **Commit the lockfile** and install with `npm ci` (not `npm install`) in CI — reproducible builds, no silent version drift.
|
|
304
|
+
- **Review new dependencies before adding them** — maintenance, download counts, and whether they truly earn their place. Every dependency is attack surface (OWASP **A06: Vulnerable Components**, **LLM03: Supply Chain**).
|
|
305
|
+
- **Be wary of `postinstall` scripts** in unfamiliar packages — they run arbitrary code at install time.
|
|
306
|
+
- **Watch for typosquats** — `cross-env` vs `crossenv`, `react-dom` vs `reactdom`.
|
|
307
|
+
|
|
308
|
+
## Rate Limiting
|
|
309
|
+
|
|
310
|
+
```typescript
|
|
311
|
+
import rateLimit from 'express-rate-limit';
|
|
312
|
+
|
|
313
|
+
// General API rate limit
|
|
314
|
+
app.use('/api/', rateLimit({
|
|
315
|
+
windowMs: 15 * 60 * 1000, // 15 minutes
|
|
316
|
+
max: 100, // 100 requests per window
|
|
317
|
+
standardHeaders: true,
|
|
318
|
+
legacyHeaders: false,
|
|
319
|
+
}));
|
|
320
|
+
|
|
321
|
+
// Stricter limit for auth endpoints
|
|
322
|
+
app.use('/api/auth/', rateLimit({
|
|
323
|
+
windowMs: 15 * 60 * 1000,
|
|
324
|
+
max: 10, // 10 attempts per 15 minutes
|
|
325
|
+
}));
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
## Secrets Management
|
|
329
|
+
|
|
330
|
+
```
|
|
331
|
+
.env files:
|
|
332
|
+
├── .env.example → Committed (template with placeholder values)
|
|
333
|
+
├── .env → NOT committed (contains real secrets)
|
|
334
|
+
└── .env.local → NOT committed (local overrides)
|
|
335
|
+
|
|
336
|
+
.gitignore must include:
|
|
337
|
+
.env
|
|
338
|
+
.env.local
|
|
339
|
+
.env.*.local
|
|
340
|
+
*.pem
|
|
341
|
+
*.key
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
**Always check before committing:**
|
|
345
|
+
```bash
|
|
346
|
+
# Check for accidentally staged secrets
|
|
347
|
+
git diff --cached | grep -i "password\|secret\|api_key\|token"
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
**If a secret is ever committed, rotate it.** Deleting the line or rewriting history is not enough — assume it's compromised the moment it reaches a remote. Revoke and reissue the key first, then purge it from history.
|
|
351
|
+
|
|
352
|
+
## Securing AI / LLM Features
|
|
353
|
+
|
|
354
|
+
If your app calls an LLM — chatbots, summarizers, agents, RAG — it inherits a new attack surface. Map it to the [OWASP Top 10 for LLM Applications (2025)](https://genai.owasp.org/llm-top-10/):
|
|
355
|
+
|
|
356
|
+
- **Treat all model output as untrusted input (LLM05: Improper Output Handling).** Never pass LLM output straight into `eval`, SQL, a shell, `innerHTML`, or a file path. Validate and encode it exactly as you would raw user input.
|
|
357
|
+
- **Assume prompts can be hijacked (LLM01: Prompt Injection).** Untrusted text in the context window — a user message, a fetched web page, a PDF — can carry instructions. The system prompt is not a security boundary; enforce permissions in code, not in the prompt.
|
|
358
|
+
- **Keep secrets and other users' data out of prompts (LLM02 / LLM07).** Anything in the context can be echoed back. Don't put API keys, cross-tenant data, or the full system prompt where the model can repeat it.
|
|
359
|
+
- **Constrain tool and agent permissions (LLM06: Excessive Agency).** Scope tools to the minimum, require confirmation for destructive or irreversible actions, and validate every tool argument.
|
|
360
|
+
- **Bound consumption (LLM10: Unbounded Consumption).** Cap tokens, request rate, and loop/recursion depth so a crafted input can't run up cost or hang the system.
|
|
361
|
+
- **Isolate retrieval data (LLM08: Vector and Embedding Weaknesses).** In RAG, treat the vector store as a trust boundary: partition embeddings per tenant so one user can't retrieve another's data, and validate documents before indexing so poisoned content can't steer answers.
|
|
362
|
+
|
|
363
|
+
```typescript
|
|
364
|
+
// BAD: trusting model output as a command or as markup
|
|
365
|
+
const sql = await llm.generate(`Write SQL for: ${userQuestion}`);
|
|
366
|
+
await db.query(sql); // arbitrary query execution
|
|
367
|
+
container.innerHTML = await llm.reply(userMessage); // stored XSS, via the model
|
|
368
|
+
|
|
369
|
+
// GOOD: model output is data — parse defensively, then validate, then encode
|
|
370
|
+
let intent;
|
|
371
|
+
try {
|
|
372
|
+
intent = CommandSchema.parse(JSON.parse(await llm.replyJson(userMessage)));
|
|
373
|
+
} catch {
|
|
374
|
+
throw new ValidationError('unexpected model output'); // JSON.parse or schema failed
|
|
375
|
+
}
|
|
376
|
+
await runAllowlistedAction(intent.action, intent.params);
|
|
377
|
+
container.textContent = await llm.reply(userMessage);
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
## Security Review Checklist
|
|
381
|
+
|
|
382
|
+
```markdown
|
|
383
|
+
### Authentication
|
|
384
|
+
- [ ] Passwords hashed with bcrypt/scrypt/argon2 (salt rounds ≥ 12)
|
|
385
|
+
- [ ] Session tokens are httpOnly, secure, sameSite
|
|
386
|
+
- [ ] Login has rate limiting
|
|
387
|
+
- [ ] Password reset tokens expire
|
|
388
|
+
|
|
389
|
+
### Authorization
|
|
390
|
+
- [ ] Every endpoint checks user permissions
|
|
391
|
+
- [ ] Users can only access their own resources
|
|
392
|
+
- [ ] Admin actions require admin role verification
|
|
393
|
+
|
|
394
|
+
### Input
|
|
395
|
+
- [ ] All user input validated at the boundary
|
|
396
|
+
- [ ] SQL queries are parameterized
|
|
397
|
+
- [ ] HTML output is encoded/escaped
|
|
398
|
+
- [ ] Server-side URL fetches are allowlisted (no SSRF to internal services)
|
|
399
|
+
|
|
400
|
+
### Data
|
|
401
|
+
- [ ] No secrets in code or version control
|
|
402
|
+
- [ ] Sensitive fields excluded from API responses
|
|
403
|
+
- [ ] PII encrypted at rest (if applicable)
|
|
404
|
+
|
|
405
|
+
### Infrastructure
|
|
406
|
+
- [ ] Security headers configured (CSP, HSTS, etc.)
|
|
407
|
+
- [ ] CORS restricted to known origins
|
|
408
|
+
- [ ] Dependencies audited for vulnerabilities
|
|
409
|
+
- [ ] Error messages don't expose internals
|
|
410
|
+
|
|
411
|
+
### Supply Chain
|
|
412
|
+
- [ ] Lockfile committed; CI installs with `npm ci`
|
|
413
|
+
- [ ] New dependencies reviewed (maintenance, downloads, postinstall scripts)
|
|
414
|
+
|
|
415
|
+
### AI / LLM (if used)
|
|
416
|
+
- [ ] Model output treated as untrusted (no eval/SQL/innerHTML/shell)
|
|
417
|
+
- [ ] Secrets and other users' data kept out of prompts
|
|
418
|
+
- [ ] Tool/agent permissions scoped; destructive actions require confirmation
|
|
419
|
+
```
|
|
420
|
+
## See Also
|
|
421
|
+
|
|
422
|
+
For detailed security checklists and pre-commit verification steps, see `references/security-checklist.md`.
|
|
423
|
+
|
|
424
|
+
## Common Rationalizations
|
|
425
|
+
|
|
426
|
+
| Rationalization | Reality |
|
|
427
|
+
|---|---|
|
|
428
|
+
| "This is an internal tool, security doesn't matter" | Internal tools get compromised. Attackers target the weakest link. |
|
|
429
|
+
| "We'll add security later" | Security retrofitting is 10x harder than building it in. Add it now. |
|
|
430
|
+
| "No one would try to exploit this" | Automated scanners will find it. Security by obscurity is not security. |
|
|
431
|
+
| "The framework handles security" | Frameworks provide tools, not guarantees. You still need to use them correctly. |
|
|
432
|
+
| "It's just a prototype" | Prototypes become production. Security habits from day one. |
|
|
433
|
+
| "Threat modeling is overkill here" | Five minutes of "how would I attack this?" prevents the design flaws no control can patch later. |
|
|
434
|
+
| "It's just LLM output, it's only text" | That "text" can be a SQL statement, a script tag, or a shell command. Treat it like any untrusted input. |
|
|
435
|
+
|
|
436
|
+
## Red Flags
|
|
437
|
+
|
|
438
|
+
- User input passed directly to database queries, shell commands, or HTML rendering
|
|
439
|
+
- Secrets in source code or commit history
|
|
440
|
+
- API endpoints without authentication or authorization checks
|
|
441
|
+
- Missing CORS configuration or wildcard (`*`) origins
|
|
442
|
+
- No rate limiting on authentication endpoints
|
|
443
|
+
- Stack traces or internal errors exposed to users
|
|
444
|
+
- Dependencies with known critical vulnerabilities
|
|
445
|
+
- Server fetches user-supplied URLs without an allowlist (SSRF)
|
|
446
|
+
- LLM/model output passed into a query, the DOM, a shell, or `eval`
|
|
447
|
+
- Secrets, PII, or the full system prompt placed inside an LLM context window
|
|
448
|
+
|
|
449
|
+
## Verification
|
|
450
|
+
|
|
451
|
+
After implementing security-relevant code:
|
|
452
|
+
|
|
453
|
+
- [ ] `npm audit` shows no critical or high vulnerabilities
|
|
454
|
+
- [ ] No secrets in source code or git history
|
|
455
|
+
- [ ] All user input validated at system boundaries
|
|
456
|
+
- [ ] Authentication and authorization checked on every protected endpoint
|
|
457
|
+
- [ ] Security headers present in response (check with browser DevTools)
|
|
458
|
+
- [ ] Error responses don't expose internal details
|
|
459
|
+
- [ ] Rate limiting active on auth endpoints
|
|
460
|
+
- [ ] Server-side URL fetches validated against an allowlist (no SSRF)
|
|
461
|
+
- [ ] LLM/model output validated and encoded before use (if AI features present)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: source-driven-development
|
|
3
|
+
description: Grounds every implementation decision in official documentation. Use when you want authoritative, source-cited code free from outdated patterns. Use when building with any framework or library where correctness matters.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Source-Driven Development
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Every framework-specific code decision must be backed by official documentation. Don't implement from memory — verify, cite, and let the user see your sources. Training data goes stale, APIs get deprecated, best practices evolve. This skill ensures the user gets code they can trust because every pattern traces back to an authoritative source they can check.
|
|
11
|
+
|
|
12
|
+
## When to Use
|
|
13
|
+
|
|
14
|
+
- The user wants code that follows current best practices for a given framework
|
|
15
|
+
- Building boilerplate, starter code, or patterns that will be copied across a project
|
|
16
|
+
- The user explicitly asks for documented, verified, or "correct" implementation
|
|
17
|
+
- Implementing features where the framework's recommended approach matters (forms, routing, data fetching, state management, auth)
|
|
18
|
+
- Reviewing or improving code that uses framework-specific patterns
|
|
19
|
+
- Any time you are about to write framework-specific code from memory
|
|
20
|
+
|
|
21
|
+
**When NOT to use:**
|
|
22
|
+
|
|
23
|
+
- Correctness does not depend on a specific version (renaming variables, fixing typos, moving files)
|
|
24
|
+
- Pure logic that works the same across all versions (loops, conditionals, data structures)
|
|
25
|
+
- The user explicitly wants speed over verification ("just do it quickly")
|
|
26
|
+
|
|
27
|
+
## The Process
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
DETECT ──→ FETCH ──→ IMPLEMENT ──→ CITE
|
|
31
|
+
│ │ │ │
|
|
32
|
+
▼ ▼ ▼ ▼
|
|
33
|
+
What Get the Follow the Show your
|
|
34
|
+
stack? relevant documented sources
|
|
35
|
+
docs patterns
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Step 1: Detect Stack and Versions
|
|
39
|
+
|
|
40
|
+
Read the project's dependency file to identify exact versions:
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
package.json → Node/React/Vue/Angular/Svelte
|
|
44
|
+
composer.json → PHP/Symfony/Laravel
|
|
45
|
+
requirements.txt / pyproject.toml → Python/Django/Flask
|
|
46
|
+
go.mod → Go
|
|
47
|
+
Cargo.toml → Rust
|
|
48
|
+
Gemfile → Ruby/Rails
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
State what you found explicitly:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
STACK DETECTED:
|
|
55
|
+
- React 19.1.0 (from package.json)
|
|
56
|
+
- Vite 6.2.0
|
|
57
|
+
- Tailwind CSS 4.0.3
|
|
58
|
+
→ Fetching official docs for the relevant patterns.
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
If versions are missing or ambiguous, **ask the user**. Don't guess — the version determines which patterns are correct.
|
|
62
|
+
|
|
63
|
+
### Step 2: Fetch Official Documentation
|
|
64
|
+
|
|
65
|
+
Fetch the specific documentation page for the feature you're implementing. Not the homepage, not the full docs — the relevant page.
|
|
66
|
+
|
|
67
|
+
**Source hierarchy (in order of authority):**
|
|
68
|
+
|
|
69
|
+
| Priority | Source | Example |
|
|
70
|
+
|----------|--------|---------|
|
|
71
|
+
| 1 | Official documentation | react.dev, docs.djangoproject.com, symfony.com/doc |
|
|
72
|
+
| 2 | Official blog / changelog | react.dev/blog, nextjs.org/blog |
|
|
73
|
+
| 3 | Web standards references | MDN, web.dev, html.spec.whatwg.org |
|
|
74
|
+
| 4 | Browser/runtime compatibility | caniuse.com, node.green |
|
|
75
|
+
|
|
76
|
+
**Not authoritative — never cite as primary sources:**
|
|
77
|
+
|
|
78
|
+
- Stack Overflow answers
|
|
79
|
+
- Blog posts or tutorials (even popular ones)
|
|
80
|
+
- AI-generated documentation or summaries
|
|
81
|
+
- Your own training data (that is the whole point — verify it)
|
|
82
|
+
|
|
83
|
+
**Be precise with what you fetch:**
|
|
84
|
+
|
|
85
|
+
```
|
|
86
|
+
BAD: Fetch the React homepage
|
|
87
|
+
GOOD: Fetch react.dev/reference/react/useActionState
|
|
88
|
+
|
|
89
|
+
BAD: Search "django authentication best practices"
|
|
90
|
+
GOOD: Fetch docs.djangoproject.com/en/6.0/topics/auth/
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
After fetching, extract the key patterns and note any deprecation warnings or migration guidance.
|
|
94
|
+
|
|
95
|
+
When official sources conflict with each other (e.g. a migration guide contradicts the API reference), surface the discrepancy to the user and verify which pattern actually works against the detected version.
|
|
96
|
+
|
|
97
|
+
### Step 3: Implement Following Documented Patterns
|
|
98
|
+
|
|
99
|
+
Write code that matches what the documentation shows:
|
|
100
|
+
|
|
101
|
+
- Use the API signatures from the docs, not from memory
|
|
102
|
+
- If the docs show a new way to do something, use the new way
|
|
103
|
+
- If the docs deprecate a pattern, don't use the deprecated version
|
|
104
|
+
- If the docs don't cover something, flag it as unverified
|
|
105
|
+
|
|
106
|
+
**When docs conflict with existing project code:**
|
|
107
|
+
|
|
108
|
+
```
|
|
109
|
+
CONFLICT DETECTED:
|
|
110
|
+
The existing codebase uses useState for form loading state,
|
|
111
|
+
but React 19 docs recommend useActionState for this pattern.
|
|
112
|
+
(Source: react.dev/reference/react/useActionState)
|
|
113
|
+
|
|
114
|
+
Options:
|
|
115
|
+
A) Use the modern pattern (useActionState) — consistent with current docs
|
|
116
|
+
B) Match existing code (useState) — consistent with codebase
|
|
117
|
+
→ Which approach do you prefer?
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Surface the conflict. Don't silently pick one.
|
|
121
|
+
|
|
122
|
+
### Step 4: Cite Your Sources
|
|
123
|
+
|
|
124
|
+
Every framework-specific pattern gets a citation. The user must be able to verify every decision.
|
|
125
|
+
|
|
126
|
+
**In code comments:**
|
|
127
|
+
|
|
128
|
+
```typescript
|
|
129
|
+
// React 19 form handling with useActionState
|
|
130
|
+
// Source: https://react.dev/reference/react/useActionState#usage
|
|
131
|
+
const [state, formAction, isPending] = useActionState(submitOrder, initialState);
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
**In conversation:**
|
|
135
|
+
|
|
136
|
+
```
|
|
137
|
+
I'm using useActionState instead of manual useState for the
|
|
138
|
+
form submission state. React 19 replaced the manual
|
|
139
|
+
isPending/setIsPending pattern with this hook.
|
|
140
|
+
|
|
141
|
+
Source: https://react.dev/blog/2024/12/05/react-19#actions
|
|
142
|
+
"useTransition now supports async functions [...] to handle
|
|
143
|
+
pending states automatically"
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
**Citation rules:**
|
|
147
|
+
|
|
148
|
+
- Full URLs, not shortened
|
|
149
|
+
- Prefer deep links with anchors where possible (e.g. `/useActionState#usage` over `/useActionState`) — anchors survive doc restructuring better than top-level pages
|
|
150
|
+
- Quote the relevant passage when it supports a non-obvious decision
|
|
151
|
+
- Include browser/runtime support data when recommending platform features
|
|
152
|
+
- If you cannot find documentation for a pattern, say so explicitly:
|
|
153
|
+
|
|
154
|
+
```
|
|
155
|
+
UNVERIFIED: I could not find official documentation for this
|
|
156
|
+
pattern. This is based on training data and may be outdated.
|
|
157
|
+
Verify before using in production.
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Honesty about what you couldn't verify is more valuable than false confidence.
|
|
161
|
+
|
|
162
|
+
## Common Rationalizations
|
|
163
|
+
|
|
164
|
+
| Rationalization | Reality |
|
|
165
|
+
|---|---|
|
|
166
|
+
| "I'm confident about this API" | Confidence is not evidence. Training data contains outdated patterns that look correct but break against current versions. Verify. |
|
|
167
|
+
| "Fetching docs wastes tokens" | Hallucinating an API wastes more. The user debugs for an hour, then discovers the function signature changed. One fetch prevents hours of rework. |
|
|
168
|
+
| "The docs won't have what I need" | If the docs don't cover it, that's valuable information — the pattern may not be officially recommended. |
|
|
169
|
+
| "I'll just mention it might be outdated" | A disclaimer doesn't help. Either verify and cite, or clearly flag it as unverified. Hedging is the worst option. |
|
|
170
|
+
| "This is a simple task, no need to check" | Simple tasks with wrong patterns become templates. The user copies your deprecated form handler into ten components before discovering the modern approach exists. |
|
|
171
|
+
|
|
172
|
+
## Red Flags
|
|
173
|
+
|
|
174
|
+
- Writing framework-specific code without checking the docs for that version
|
|
175
|
+
- Using "I believe" or "I think" about an API instead of citing the source
|
|
176
|
+
- Implementing a pattern without knowing which version it applies to
|
|
177
|
+
- Citing Stack Overflow or blog posts instead of official documentation
|
|
178
|
+
- Using deprecated APIs because they appear in training data
|
|
179
|
+
- Not reading `package.json` / dependency files before implementing
|
|
180
|
+
- Delivering code without source citations for framework-specific decisions
|
|
181
|
+
- Fetching an entire docs site when only one page is relevant
|
|
182
|
+
|
|
183
|
+
## Verification
|
|
184
|
+
|
|
185
|
+
After implementing with source-driven development:
|
|
186
|
+
|
|
187
|
+
- [ ] Framework and library versions were identified from the dependency file
|
|
188
|
+
- [ ] Official documentation was fetched for framework-specific patterns
|
|
189
|
+
- [ ] All sources are official documentation, not blog posts or training data
|
|
190
|
+
- [ ] Code follows the patterns shown in the current version's documentation
|
|
191
|
+
- [ ] Non-trivial decisions include source citations with full URLs
|
|
192
|
+
- [ ] No deprecated APIs are used (checked against migration guides)
|
|
193
|
+
- [ ] Conflicts between docs and existing code were surfaced to the user
|
|
194
|
+
- [ ] Anything that could not be verified is explicitly flagged as unverified
|