create-command-center 0.0.0-stage → 0.3.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 (67) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE.agent-skills +21 -0
  3. package/README.md +62 -2
  4. package/RELEASING.md +29 -0
  5. package/UPSTREAM.md +13 -0
  6. package/bin/create-command-center.mjs +34 -0
  7. package/installer/build-parsers.mjs +21 -0
  8. package/installer/install.mjs +103 -0
  9. package/installer/template/AGENTS.md +9 -0
  10. package/installer/template/README.md +13 -0
  11. package/installer/template/gitignore +5 -0
  12. package/installer/template/repos/index.md +5 -0
  13. package/package.json +41 -4
  14. package/references/accessibility-checklist.md +160 -0
  15. package/references/definition-of-done.md +67 -0
  16. package/references/observability-checklist.md +92 -0
  17. package/references/orchestration-patterns.md +370 -0
  18. package/references/performance-checklist.md +239 -0
  19. package/references/security-checklist.md +250 -0
  20. package/references/testing-patterns.md +236 -0
  21. package/skills/accessibility-engineering/SKILL.md +133 -0
  22. package/skills/accessibility-engineering/scripts/audit-a11y.sh +233 -0
  23. package/skills/api-and-interface-design/SKILL.md +369 -0
  24. package/skills/browser-testing-with-devtools/SKILL.md +319 -0
  25. package/skills/cc/SKILL.md +26 -0
  26. package/skills/cc/assets/config.md +28 -0
  27. package/skills/cc/assets/progress.md +23 -0
  28. package/skills/cc/references/jobs.md +30 -0
  29. package/skills/cc/references/registration.md +63 -0
  30. package/skills/cc/scripts/checks.mjs +109 -0
  31. package/skills/cc/scripts/errors.mjs +3 -0
  32. package/skills/cc/scripts/home.mjs +60 -0
  33. package/skills/cc/scripts/init.mjs +499 -0
  34. package/skills/cc/scripts/inspection.mjs +315 -0
  35. package/skills/cc/scripts/vendor/LICENSE.parsers.txt +70 -0
  36. package/skills/cc/scripts/vendor/parsers.mjs +9951 -0
  37. package/skills/ci-cd-and-automation/SKILL.md +395 -0
  38. package/skills/code-review-and-quality/SKILL.md +402 -0
  39. package/skills/code-simplification/SKILL.md +331 -0
  40. package/skills/constraint-driven-development/SKILL.md +319 -0
  41. package/skills/constraint-driven-development/references/floor-guard.md +182 -0
  42. package/skills/constraint-driven-development/scripts/quality-gate.mjs +45 -0
  43. package/skills/context-engineering/SKILL.md +353 -0
  44. package/skills/debugging-and-error-recovery/SKILL.md +300 -0
  45. package/skills/deprecation-and-migration/SKILL.md +252 -0
  46. package/skills/documentation-and-adrs/SKILL.md +320 -0
  47. package/skills/doubt-driven-development/SKILL.md +245 -0
  48. package/skills/frontend-ui-engineering/SKILL.md +346 -0
  49. package/skills/git-workflow-and-versioning/SKILL.md +355 -0
  50. package/skills/idea-refine/SKILL.md +195 -0
  51. package/skills/idea-refine/examples.md +238 -0
  52. package/skills/idea-refine/frameworks.md +99 -0
  53. package/skills/idea-refine/refinement-criteria.md +113 -0
  54. package/skills/idea-refine/scripts/idea-refine.sh +15 -0
  55. package/skills/incremental-implementation/SKILL.md +249 -0
  56. package/skills/interview-me/SKILL.md +235 -0
  57. package/skills/observability-and-instrumentation/SKILL.md +238 -0
  58. package/skills/performance-optimization/SKILL.md +267 -0
  59. package/skills/performance-optimization/references/optimization-patterns.md +250 -0
  60. package/skills/planning-and-task-breakdown/SKILL.md +259 -0
  61. package/skills/security-and-hardening/SKILL.md +216 -0
  62. package/skills/security-and-hardening/references/hardening-patterns.md +333 -0
  63. package/skills/shipping-and-launch/SKILL.md +336 -0
  64. package/skills/source-driven-development/SKILL.md +217 -0
  65. package/skills/spec-driven-development/SKILL.md +307 -0
  66. package/skills/test-driven-development/SKILL.md +400 -0
  67. package/skills/using-agent-skills/SKILL.md +194 -0
@@ -0,0 +1,239 @@
1
+ # Performance Checklist
2
+
3
+ Quick reference checklist for web application performance. Use alongside the `performance-optimization` skill.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Core Web Vitals Targets](#core-web-vitals-targets)
8
+ - [TTFB Diagnosis](#ttfb-diagnosis)
9
+ - [Frontend Checklist](#frontend-checklist)
10
+ - [Backend Checklist](#backend-checklist)
11
+ - [Caching Strategies](#caching-strategies)
12
+ - [Measurement Commands](#measurement-commands)
13
+ - [Common Anti-Patterns](#common-anti-patterns)
14
+
15
+ ## Core Web Vitals Targets
16
+
17
+ | Metric | Good | Needs Work | Poor |
18
+ |--------|------|------------|------|
19
+ | LCP (Largest Contentful Paint) | ≤ 2.5s | ≤ 4.0s | > 4.0s |
20
+ | INP (Interaction to Next Paint) | ≤ 200ms | ≤ 500ms | > 500ms |
21
+ | CLS (Cumulative Layout Shift) | ≤ 0.1 | ≤ 0.25 | > 0.25 |
22
+
23
+ ## TTFB Diagnosis
24
+
25
+ When TTFB is slow (> 800ms), check each component in DevTools Network waterfall:
26
+
27
+ - [ ] **DNS resolution** slow → add `<link rel="dns-prefetch">` or `<link rel="preconnect">` for known origins
28
+ - [ ] **TCP/TLS handshake** slow → enable HTTP/2, consider edge deployment, verify keep-alive
29
+ - [ ] **Server processing** slow → profile backend, check slow queries, add caching
30
+
31
+ ## Frontend Checklist
32
+
33
+ ### Images
34
+ - [ ] Images use modern formats (WebP, AVIF)
35
+ - [ ] Images are responsively sized (`srcset` and `sizes`)
36
+ - [ ] Images and `<source>` elements have explicit `width` and `height` (prevents CLS in art direction)
37
+ - [ ] Below-the-fold images use `loading="lazy"` and `decoding="async"`
38
+ - [ ] Hero/LCP images use `fetchpriority="high"` and no lazy loading
39
+
40
+ ### JavaScript
41
+ - [ ] Bundle size under 200KB gzipped (initial load)
42
+ - [ ] Code splitting with dynamic `import()` for routes and heavy features
43
+ - [ ] Tree shaking enabled (verify dependency ships ESM and marks `sideEffects: false`)
44
+ - [ ] No blocking JavaScript in `<head>` (use `defer` or `async`)
45
+ - [ ] Heavy computation offloaded to Web Workers (if applicable)
46
+ - [ ] `React.memo()` on expensive components that re-render with same props
47
+ - [ ] `useMemo()` / `useCallback()` only where profiling shows benefit
48
+ - [ ] Long tasks (> 50ms) broken up to keep the main thread available — main lever for INP
49
+ - [ ] `yieldToMain` pattern used inside long-running loops so input events can run between chunks
50
+ - [ ] Modern scheduling APIs used where available: `scheduler.yield()` (preferred), `scheduler.postTask()` with priorities, `isInputPending()` to yield only when needed
51
+ - [ ] `requestIdleCallback` for deferrable, non-urgent work (analytics flush, prefetch, warmup)
52
+ - [ ] Non-critical work deferred out of event handlers (e.g. analytics, logging) so the response to the interaction is not delayed
53
+ - [ ] Third-party scripts loaded with `async` / `defer`, audited for size, and fronted by a facade when heavy (chat widgets, embeds)
54
+
55
+ ### CSS
56
+ - [ ] Critical CSS inlined or preloaded
57
+ - [ ] No render-blocking CSS for non-critical styles
58
+ - [ ] No CSS-in-JS runtime cost in production (use extraction)
59
+
60
+ ### Fonts
61
+ - [ ] Limited to 2–3 font families, 2–3 weights each (every additional weight is another request)
62
+ - [ ] WOFF2 format only (smallest, universal support — skip WOFF/TTF/EOT)
63
+ - [ ] Self-hosted when possible (third-party font CDNs add DNS + TCP + TLS round-trips)
64
+ - [ ] LCP-critical fonts preloaded: `<link rel="preload" as="font" type="font/woff2" crossorigin>`
65
+ - [ ] `font-display: swap` (or `optional` for non-critical) to avoid FOIT blocking render
66
+ - [ ] Subsetted via `unicode-range` to ship only the glyphs each page needs
67
+ - [ ] Variable fonts considered when multiple weights/styles are required (one file replaces many)
68
+ - [ ] Fallback font metrics adjusted with `size-adjust`, `ascent-override`, `descent-override` to reduce CLS on font swap
69
+ - [ ] System font stack considered before any custom font
70
+
71
+ ### Network
72
+ - [ ] Static assets cached with long `max-age` + content hashing
73
+ - [ ] API responses cached where appropriate (`Cache-Control`)
74
+ - [ ] HTTP/2 or HTTP/3 enabled
75
+ - [ ] Resources preconnected (`<link rel="preconnect">`) for known origins
76
+ - [ ] `fetchpriority` used on critical non-image resources (e.g., key `<link rel="preload">`, above-the-fold `<script>`) — not only on `<img>`
77
+ - [ ] No unnecessary redirects
78
+
79
+ ### Rendering
80
+ - [ ] No layout thrashing (forced synchronous layouts)
81
+ - [ ] Animations use `transform` and `opacity` (GPU-accelerated)
82
+ - [ ] Long lists use virtualization (e.g., `react-window`)
83
+ - [ ] No unnecessary full-page re-renders
84
+ - [ ] Off-screen sections use `content-visibility: auto` with `contain-intrinsic-size` to skip layout/paint of non-visible areas
85
+ - [ ] No `unload` event handlers and no `Cache-Control: no-store` on HTML responses — preserves back/forward cache (bfcache) eligibility
86
+
87
+ ## Backend Checklist
88
+
89
+ ### Database
90
+ - [ ] No N+1 query patterns (use eager loading / joins)
91
+ - [ ] Queries have appropriate indexes
92
+ - [ ] List endpoints paginated (never `SELECT * FROM table`)
93
+ - [ ] Connection pooling configured
94
+ - [ ] Slow query logging enabled
95
+
96
+ #### Query plans
97
+ - [ ] `EXPLAIN ANALYZE` captured **before** the fix, not just after — it is the baseline
98
+ - [ ] `Seq Scan` on a large table understood: index missing, unusable, or genuinely not worth it
99
+ - [ ] Estimated vs actual `rows=` within an order of magnitude (if not, refresh statistics before touching indexes)
100
+ - [ ] No `Sort` node that a composite index could absorb
101
+ - [ ] Plan re-checked after the change — an index that did not change the plan gets reverted
102
+
103
+ #### Index strategy
104
+ - [ ] Composite index column order is equality first, then range/sort
105
+ - [ ] Index covers the query shape (filter + sort), not just one column in isolation
106
+ - [ ] Covering index considered for hot read paths (index-only scan avoids the heap fetch)
107
+ - [ ] Not indexing low-selectivity columns *for the dominant value*; a partial index still serves the rare-value query (`WHERE status = 'failed'`)
108
+ - [ ] Expression index used where the query applies a function (`lower(email)`)
109
+ - [ ] Full-text or trigram index used for leading-wildcard search, not a B-tree
110
+ - [ ] Write cost measured on write-heavy tables (every index taxes every `INSERT`/`UPDATE`)
111
+ - [ ] Unused and duplicate indexes dropped (they cost writes and buy nothing)
112
+
113
+ #### Connection pooling
114
+ - [ ] One pool per process, not per request or per module
115
+ - [ ] `instances × pool max` stays under the database's `max_connections`
116
+ - [ ] `connectionTimeoutMillis` set so exhaustion fails fast instead of queueing forever
117
+ - [ ] Exhaustion diagnosed before resizing: find what holds connections (long transactions, missing `await`, leaked clients)
118
+ - [ ] Serverless / autoscaling fronted by a multiplexing proxy (pgbouncer, RDS Proxy) rather than a larger pool
119
+
120
+ ### API
121
+ - [ ] Response times < 200ms (p95)
122
+ - [ ] No synchronous heavy computation in request handlers
123
+ - [ ] Bulk operations instead of loops of individual calls
124
+ - [ ] Response compression (gzip/brotli)
125
+ - [ ] Appropriate caching (in-memory, Redis, CDN)
126
+
127
+ ### Infrastructure
128
+ - [ ] CDN for static assets
129
+ - [ ] Server located close to users (or edge deployment)
130
+ - [ ] Horizontal scaling configured (if needed)
131
+ - [ ] Health check endpoint for load balancer
132
+
133
+ ## Caching Strategies
134
+
135
+ The decision material (which layer, which invalidation strategy, what never to cache) lives in the `performance-optimization` skill. This section covers the read/write patterns and the checklist.
136
+
137
+ ### Read and write patterns
138
+
139
+ | Pattern | How it works | Use when | Watch out for |
140
+ |---|---|---|---|
141
+ | **Cache-aside** (lazy) | App checks cache, on miss reads origin and populates | Default choice; read-heavy, tolerant of a cold first hit | Every miss hits the origin, so it needs stampede protection |
142
+ | **Read-through** | Cache layer itself loads on miss | You want the load path in one place, not at every call site | Hides origin latency; a slow origin looks like a slow cache |
143
+ | **Write-through** | Write goes to cache and origin together, synchronously | Reads must never see a stale value after a write | Adds cache latency to every write |
144
+ | **Write-behind** (write-back) | Write hits cache, origin updated asynchronously | Write-heavy, and the origin is the bottleneck | Data loss window if the cache dies before the flush. Needs durability you can defend |
145
+
146
+ ### Negative caching
147
+
148
+ Cache the *absence* of a result too. A key that misses on every lookup (a nonexistent user ID probed in a loop, a 404 asset) sends every request to the origin, which is a cache that only protects the happy path.
149
+
150
+ - Store an explicit "not found" sentinel with a **shorter** TTL than positive entries
151
+ - Keep the negative TTL short enough that a newly created record appears promptly
152
+ - Never let an origin *error* become a negative cache entry, or one failing minute becomes many
153
+
154
+ ### Request coalescing (stampede protection)
155
+
156
+ One recompute, N waiters. Prevents a hot key's expiry from delivering the full concurrent load to the origin:
157
+
158
+ ```typescript
159
+ const inFlight = new Map<string, Promise<unknown>>();
160
+
161
+ function loadOnce<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
162
+ const existing = inFlight.get(key) as Promise<T> | undefined;
163
+ if (existing) return existing;
164
+ const p = fetcher().finally(() => inFlight.delete(key));
165
+ inFlight.set(key, p);
166
+ return p;
167
+ }
168
+ ```
169
+
170
+ For a shared cache, the same idea needs a distributed lock, or `stale-while-revalidate` so waiters serve the stale value instead of blocking.
171
+
172
+ ### Cache checklist
173
+ - [ ] The cached call was measured as expensive first (caching a fast call adds a hop and buys nothing)
174
+ - [ ] Read/write ratio justifies the cache (re-read far more often than written)
175
+ - [ ] Cache key includes every input the response varies on: tenant, viewer, locale, permissions, feature flags
176
+ - [ ] No per-user data cached under a key that does not identify the user
177
+ - [ ] One invalidation strategy chosen (TTL, event/tag, or versioned keys), not an accidental mix
178
+ - [ ] Acceptable staleness window written down, not implied by whatever TTL was typed
179
+ - [ ] Stampede protection on hot keys (coalescing, lock, or `stale-while-revalidate`)
180
+ - [ ] Negative results cached with a shorter TTL; origin errors never cached
181
+ - [ ] Eviction policy and memory ceiling set (an unbounded cache is a memory leak)
182
+ - [ ] Hit rate monitored — a cache nobody measures is an assumption, and a low hit rate is pure overhead
183
+ - [ ] Nothing cached whose staleness is a correctness bug (balances, permissions, inventory at checkout)
184
+
185
+ ## Measurement Commands
186
+
187
+ ### INP field data and DevTools workflow
188
+
189
+ 1. **Field data first** — check [CrUX Vis](https://developer.chrome.com/docs/crux/vis) or your RUM tool for real-user INP before optimising
190
+ 2. **Identify slow interactions** — open DevTools → Performance panel → record while interacting; look for long tasks triggered by clicks/keystrokes
191
+ 3. **Test on mid-range Android** — INP issues often only surface on slower hardware; use a real device or DevTools CPU throttling (4×–6× slowdown)
192
+
193
+ ```bash
194
+ # Lighthouse CLI
195
+ npx lighthouse http://localhost:3000 --output json --output-path ./report.json
196
+
197
+ # Bundle analysis
198
+ npx webpack-bundle-analyzer stats.json
199
+ # or for Vite:
200
+ npx vite-bundle-visualizer
201
+
202
+ # Check bundle size
203
+ npx bundlesize
204
+ ```
205
+
206
+ ```javascript
207
+ // Web Vitals in code
208
+ import { onLCP, onINP, onCLS } from 'web-vitals';
209
+ onLCP(console.log);
210
+ onINP(console.log);
211
+ onCLS(console.log);
212
+
213
+ // INP with interaction-level detail (attribution build). The attribution build
214
+ // exports the same names, so alias it when both builds share a module.
215
+ import { onINP as onINPWithAttribution } from 'web-vitals/attribution';
216
+ onINPWithAttribution(({ value, attribution }) => {
217
+ const { interactionTarget, inputDelay, processingDuration, presentationDelay } = attribution;
218
+ console.log({ value, interactionTarget, inputDelay, processingDuration, presentationDelay });
219
+ });
220
+ ```
221
+
222
+ ## Common Anti-Patterns
223
+
224
+ | Anti-Pattern | Impact | Fix |
225
+ |---|---|---|
226
+ | N+1 queries | Linear DB load growth | Use joins, includes, or batch loading |
227
+ | Unbounded queries | Memory exhaustion, timeouts | Always paginate, add LIMIT |
228
+ | Missing indexes | Slow reads as data grows | Add indexes for filtered/sorted columns |
229
+ | Indexing without reading the plan | Write cost paid, read gain unproven | `EXPLAIN ANALYZE` before and after; revert if the plan is unchanged |
230
+ | Redundant / unused indexes | Every write pays for them | Audit usage stats, drop what nothing reads |
231
+ | Connection pool per request | Exhausts `max_connections` under load | One pool per process; proxy for serverless |
232
+ | Cache key missing the viewer | One user's data served to another | Key on tenant, viewer, locale, permissions |
233
+ | Unbounded cache | Memory leak wearing an optimization's clothing | Set eviction policy and a memory ceiling |
234
+ | Cache stampede on a hot key | Origin takes full concurrent load at expiry | Coalesce misses, or `stale-while-revalidate` |
235
+ | Layout thrashing | Jank, dropped frames | Batch DOM reads, then batch writes |
236
+ | Unoptimized images | Slow LCP, wasted bandwidth | Use WebP, responsive sizes, lazy load |
237
+ | Large bundles | Slow Time to Interactive | Code split, tree shake, audit deps |
238
+ | Blocking main thread | Poor INP, unresponsive UI | Chunk long tasks with `scheduler.yield()` / `yieldToMain`, offload to Web Workers |
239
+ | Memory leaks | Growing memory, eventual crash | Clean up listeners, intervals, refs |
@@ -0,0 +1,250 @@
1
+ # Security Checklist
2
+
3
+ Quick reference for web application security. Use alongside the `security-and-hardening` skill.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Threat Modeling (Start Here)](#threat-modeling-start-here)
8
+ - [Pre-Commit Checks](#pre-commit-checks)
9
+ - [Authentication](#authentication)
10
+ - [Authorization](#authorization)
11
+ - [Input Validation](#input-validation)
12
+ - [Security Headers](#security-headers)
13
+ - [CORS Configuration](#cors-configuration)
14
+ - [Data Protection](#data-protection)
15
+ - [Dependency Security](#dependency-security)
16
+ - [AI / LLM Security](#ai--llm-security)
17
+ - [Error Handling](#error-handling)
18
+ - [OWASP Top 10 Quick Reference](#owasp-top-10-quick-reference)
19
+ - [OWASP Top 10 for LLMs Quick Reference](#owasp-top-10-for-llms-quick-reference)
20
+
21
+ ## Threat Modeling (Start Here)
22
+
23
+ Before reaching for controls, spend five minutes thinking like an attacker:
24
+
25
+ - [ ] Trust boundaries mapped (requests, uploads, webhooks, third-party APIs, LLM output, and local values written by processes you don't control)
26
+ - [ ] Assets named (credentials, PII, payment data, admin actions, money movement)
27
+ - [ ] STRIDE run per boundary (Spoofing, Tampering, Repudiation, Info disclosure, DoS, Elevation)
28
+ - [ ] Abuse cases written next to use cases ("how would I misuse this?")
29
+
30
+ ## Pre-Commit Checks
31
+
32
+ - [ ] No secrets in code (`git diff --cached -i -G'password|secret|api_key|token' --name-only` — lists only the names of files whose staged diff matches, never the value itself; any output means review those files before committing)
33
+ - [ ] `.gitignore` covers: `.env`, `.env.local`, `*.pem`, `*.key`
34
+ - [ ] `.env.example` uses placeholder values (not real secrets)
35
+
36
+ ## Authentication
37
+
38
+ - [ ] Passwords hashed with bcrypt (≥12 rounds), scrypt, or argon2
39
+ - [ ] Session cookies: `httpOnly`, `secure`, `sameSite: 'lax'`
40
+ - [ ] Session expiration configured (reasonable max-age)
41
+ - [ ] Rate limiting on login endpoint (≤10 attempts per 15 minutes)
42
+ - [ ] Password reset tokens: time-limited (≤1 hour), single-use
43
+ - [ ] Account lockout after repeated failures (optional, with notification)
44
+ - [ ] MFA supported for sensitive operations (optional but recommended)
45
+
46
+ ## Authorization
47
+
48
+ - [ ] Every protected endpoint checks authentication
49
+ - [ ] Every resource access checks ownership/role (prevents IDOR)
50
+ - [ ] Admin endpoints require admin role verification
51
+ - [ ] API keys scoped to minimum necessary permissions
52
+ - [ ] JWT tokens validated (signature, expiration, issuer)
53
+
54
+ ## Input Validation
55
+
56
+ - [ ] All user input validated at system boundaries (API routes, form handlers)
57
+ - [ ] Validation uses allowlists (not denylists)
58
+ - [ ] String lengths constrained (min/max)
59
+ - [ ] Numeric ranges validated
60
+ - [ ] Email, URL, and date formats validated with proper libraries
61
+ - [ ] File uploads: type restricted, size limited, content verified
62
+ - [ ] SQL queries parameterized (no string concatenation)
63
+ - [ ] HTML output encoded (use framework auto-escaping)
64
+ - [ ] URLs validated before redirect (prevent open redirect)
65
+ - [ ] Server-side URL fetches allowlisted; private/reserved IPs blocked (prevent SSRF)
66
+ - [ ] Destructive path operations (delete/move/overwrite): symlinks resolved, allowlisted root, minimum depth, ownership evidence read before the call
67
+
68
+ ### Destructive Path Operations
69
+
70
+ Containment for a target named by data. Resolve first, then decide — and treat the
71
+ result as a candidate, not as authorization:
72
+
73
+ ```typescript
74
+ import { realpath, readFile } from 'node:fs/promises';
75
+ import { resolve, relative, isAbsolute, join, sep } from 'node:path';
76
+
77
+ const ALLOWED_ROOTS = ['/var/lib/myapp/sessions']; // an allowlist, not a pattern
78
+ const MIN_DEPTH = 1; // so a root is never the target
79
+
80
+ async function resolveDeletable(candidate: string, expectedOwner: string) {
81
+ const target = await realpath(resolve(candidate)); // symlinks resolved BEFORE the check
82
+ const inRoot = ALLOWED_ROOTS.some((root) => {
83
+ const rel = relative(root, target);
84
+ // `rel === '..'` / `'../'` only — a plain `startsWith('..')` would also
85
+ // reject a legitimate child named `..cache`.
86
+ if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return false;
87
+ return rel.split(sep).length >= MIN_DEPTH;
88
+ });
89
+ if (!inRoot) throw new Error(`refusing: outside allowed roots (${target})`);
90
+
91
+ const owner = await readFile(join(target, '.owner'), 'utf8').catch(() => null);
92
+ if (owner?.trim() !== expectedOwner) throw new Error(`refusing: unproven owner (${target})`);
93
+ return target;
94
+ }
95
+ ```
96
+
97
+ What this does not do, and must be said where the snippet is copied from:
98
+
99
+ - **The marker is self-attestation.** Anything that can write inside the root can write
100
+ `.owner`. `expectedOwner` has to come from authenticated state, and the marker needs
101
+ integrity protection (restrictive ownership, or a MAC) before it is authorization
102
+ rather than a consistency check against a misderived target.
103
+ - **Returning a path leaves a check/use race.** Where an untrusted process can swap an
104
+ ancestor between the check and the call, operate on a descriptor with no-follow,
105
+ beneath-the-root semantics, or guarantee the hierarchy is immutable for the duration.
106
+
107
+ ## Security Headers
108
+
109
+ ```
110
+ Content-Security-Policy: default-src 'self'; script-src 'self'
111
+ Strict-Transport-Security: max-age=31536000; includeSubDomains
112
+ X-Content-Type-Options: nosniff
113
+ X-Frame-Options: DENY
114
+ X-XSS-Protection: 0 (disabled, rely on CSP)
115
+ Referrer-Policy: strict-origin-when-cross-origin
116
+ Permissions-Policy: camera=(), microphone=(), geolocation=()
117
+ ```
118
+
119
+ ## CORS Configuration
120
+
121
+ ```typescript
122
+ // Restrictive (recommended)
123
+ cors({
124
+ origin: ['https://yourdomain.com', 'https://app.yourdomain.com'],
125
+ credentials: true,
126
+ methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
127
+ allowedHeaders: ['Content-Type', 'Authorization'],
128
+ })
129
+
130
+ // NEVER use in production:
131
+ cors({ origin: '*' }) // Allows any origin
132
+ ```
133
+
134
+ ## Data Protection
135
+
136
+ - [ ] Sensitive fields excluded from API responses (`passwordHash`, `resetToken`, etc.)
137
+ - [ ] Sensitive data not logged (passwords, tokens, full CC numbers)
138
+ - [ ] PII encrypted at rest (if required by regulation)
139
+ - [ ] HTTPS for all external communication
140
+ - [ ] Database backups encrypted
141
+ - [ ] Personal data is classified, collected against a stated purpose, and minimized
142
+ - [ ] Personal data has a retention limit and a working deletion path (incl. backups, caches, indexes)
143
+ - [ ] Export/delete (data-subject) requests are supported where required; third-party sharing has consent and a data-processing agreement
144
+
145
+ ## Dependency Security
146
+
147
+ First locate the **installation boundary**. If the package is matched by a parent `workspaces` declaration, use that workspace root; otherwise use the nearest project root that owns both its manifest and dependency graph. At that boundary, corroborate `packageManager` (when present), the lockfile, and CI commands. Stop if they disagree or competing manager lockfiles exist there. A nested project is independent only when it is outside the parent workspace; independent subprojects may legitimately use different managers.
148
+
149
+ | Manager/version signal | Frozen/immutable CI install | Known-advisory audit |
150
+ |---|---|---|
151
+ | npm (`package-lock.json` or `npm-shrinkwrap.json`) | `npm ci` | `npm audit` |
152
+ | pnpm | `pnpm install --frozen-lockfile` | `pnpm audit` |
153
+ | Yarn 2+ | `yarn install --immutable` | `yarn npm audit -A -R` |
154
+ | Yarn 1 | `yarn install --frozen-lockfile` | `yarn audit` |
155
+
156
+ For an unlisted manager or version, consult its official documentation; do not substitute another manager's commands or newer defaults.
157
+
158
+ ### Install-Script Gate
159
+
160
+ Never discover dependency lifecycle scripts by first executing an ordinary install on a client whose defaults have not been verified.
161
+
162
+ 1. Bootstrap with dependency scripts disabled, or with a documented default-deny policy plus fail-closed enforcement.
163
+ 2. Inspect the exact script source and package version before approval.
164
+ 3. Record the narrowest native allow/deny policy at the installation boundary and commit it.
165
+ 4. Run a clean frozen/immutable install with that policy and verify the required packages still build.
166
+
167
+ **Point-in-time snapshot:** Package-manager defaults and command names change quickly. Verify this matrix against the pinned client's current official documentation before relying on it.
168
+
169
+ | Manager version | Native policy |
170
+ |---|---|
171
+ | npm without verified granular approvals | Bootstrap with `npm ci --ignore-scripts`, or persist `ignore-scripts=true` when project-wide blocking is intended. Keep scripts disabled or deliberately upgrade before allowing any reviewed dependency script. |
172
+ | npm 11.18.x (verified on 11.18.0) | Unreviewed dependency scripts run with a warning by default. Enforce `strict-allow-scripts=true` before a normal install, then use the workspace-unaware `npm install-scripts ls` from the installation boundary; keep approvals version-pinned and denials name-wide. |
173
+ | npm 12.x (verified on 12.0.1) | Unreviewed dependency scripts are skipped by default; `strict-allow-scripts=true` makes their presence fail the install before execution. Use the same `npm install-scripts` review and approval flow. |
174
+ | pnpm 11+ | Use `pnpm approve-builds` and commit `allowBuilds` decisions; `strictDepBuilds` defaults to `true`, so unreviewed builds fail. |
175
+ | pnpm 10.26–10.x | Configure `allowBuilds` explicitly, or use `pnpm approve-builds` with the legacy `onlyBuiltDependencies` / `ignoredBuiltDependencies` lists. Set `strictDepBuilds: true`; its v10 default is `false`. |
176
+ | pnpm 10.1–10.25 | `pnpm approve-builds` records the legacy lists; enable `strictDepBuilds` where supported (10.3+). |
177
+ | Older or unknown pnpm | Bootstrap with `pnpm install --frozen-lockfile --ignore-scripts`. Keep scripts disabled unless the pinned version documents an enforceable policy. |
178
+ | Yarn 4.14+ | Dependency postinstalls are disabled by default. Grant only required exceptions with top-level `dependenciesMeta.<package>.built: true`. |
179
+ | Yarn 2–4.13 | Set `enableScripts: false` in `.yarnrc.yml`, then grant only required exceptions with top-level `dependenciesMeta.<package>.built: true`; do not enable scripts globally. |
180
+ | Yarn 1 | Bootstrap with `yarn install --ignore-scripts`; keep scripts disabled unless each required exception is reviewed under the pinned client's documented workflow. |
181
+
182
+ Authoritative checks: [npm install-scripts](https://docs.npmjs.com/cli/v11/commands/npm-install-scripts/), [install policy](https://docs.npmjs.com/cli/v11/commands/npm-install/), and [CLI releases](https://github.com/npm/cli/releases); [pnpm approve-builds](https://pnpm.io/cli/approve-builds) and [build settings](https://pnpm.io/settings#allowbuilds); [Yarn security](https://yarnpkg.com/features/security) and [manifest](https://yarnpkg.com/configuration/manifest#dependenciesMeta).
183
+
184
+ **Supply-chain hygiene** (advisory audits do not catch newly malicious packages):
185
+ - [ ] Exactly one authoritative lockfile per project/workspace root is committed and CI never rewrites it
186
+ - [ ] Critical/high findings are triaged for reachability; deferrals have a reason and review date
187
+ - [ ] Forced audit remediation (`npm audit fix --force` or equivalent) is never automatic; remediation diffs and changelogs are reviewed
188
+ - [ ] Registry signatures/provenance are verified where the manager supports it
189
+ - [ ] Dependency lifecycle scripts are blocked before first execution and approved only through the pinned manager's native policy
190
+ - [ ] New dependencies are reviewed for ownership, maintenance, release age, provenance, transitive graph, and typosquatting
191
+
192
+ ## AI / LLM Security
193
+
194
+ For any feature that calls an LLM (chatbots, summarizers, agents, RAG):
195
+
196
+ - [ ] Model output treated as untrusted — never into `eval`/SQL/shell/`innerHTML`/file paths
197
+ - [ ] Prompt injection assumed; permissions enforced in code, not in the system prompt
198
+ - [ ] Secrets, cross-tenant data, and full system prompts kept out of the context window
199
+ - [ ] Tool/agent permissions scoped; destructive or irreversible actions require confirmation
200
+ - [ ] Token, rate, and recursion/loop limits set (bound consumption)
201
+
202
+ ## Error Handling
203
+
204
+ ```typescript
205
+ // Production: generic error, no internals
206
+ res.status(500).json({
207
+ error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' }
208
+ });
209
+
210
+ // NEVER in production:
211
+ res.status(500).json({
212
+ error: err.message,
213
+ stack: err.stack, // Exposes internals
214
+ query: err.sql, // Exposes database details
215
+ });
216
+ ```
217
+
218
+ ## OWASP Top 10 Quick Reference
219
+
220
+ Numbering follows the [OWASP Top 10:2025](https://owasp.org/Top10/2025/). Cite a category with its year (`A06:2025`), since the 2021 edition used different numbers for several of the same categories.
221
+
222
+ | # | Vulnerability | Prevention |
223
+ |---|---|---|
224
+ | A01 | Broken Access Control (now includes SSRF) | Auth checks on every endpoint, ownership verification; validate/allowlist server-side fetch URLs, restrict outbound requests |
225
+ | A02 | Security Misconfiguration | Security headers, minimal permissions, secure defaults |
226
+ | A03 | Software Supply Chain Failures | The ecosystem's dependency audit (`npm audit`, `pip-audit`, ...), keep deps updated, minimal deps, review new packages and install scripts |
227
+ | A04 | Cryptographic Failures | HTTPS, strong hashing, no secrets in code |
228
+ | A05 | Injection | Parameterized queries, input validation |
229
+ | A06 | Insecure Design | Threat modeling, spec-driven development |
230
+ | A07 | Authentication Failures | Strong passwords, rate limiting, session management |
231
+ | A08 | Software or Data Integrity Failures | Verify updates, signed artifacts, no deserialization of untrusted data |
232
+ | A09 | Security Logging and Alerting Failures | Log security events, alert on them, don't log secrets |
233
+ | A10 | Mishandling of Exceptional Conditions | Fail closed, handle every error path, generic error bodies |
234
+
235
+ ## OWASP Top 10 for LLMs Quick Reference
236
+
237
+ For apps with LLM features. See the [OWASP GenAI Security Project](https://genai.owasp.org/llm-top-10/).
238
+
239
+ | ID | Risk | Prevention |
240
+ |---|---|---|
241
+ | LLM01 | Prompt Injection | Don't trust the system prompt as a boundary; enforce permissions in code |
242
+ | LLM02 | Sensitive Information Disclosure | Keep secrets/PII out of prompts; filter outputs |
243
+ | LLM03 | Supply Chain | Vet models, datasets, and plugins like any dependency |
244
+ | LLM04 | Data and Model Poisoning | Use trusted model sources, verify integrity; vet fine-tuning and RAG data |
245
+ | LLM05 | Improper Output Handling | Treat model output as untrusted; validate, parameterize, encode |
246
+ | LLM06 | Excessive Agency | Scope tool permissions; confirm destructive actions |
247
+ | LLM07 | System Prompt Leakage | Assume the system prompt can leak; put no secrets in it |
248
+ | LLM08 | Vector and Embedding Weaknesses | Partition RAG embeddings per tenant; validate documents before indexing |
249
+ | LLM09 | Misinformation | Ground answers with citations; validate critical claims; keep a human in the loop |
250
+ | LLM10 | Unbounded Consumption | Cap tokens, request rate, and loop/recursion depth |