@ranimontagna/agent-toolkit 0.1.6 → 0.1.9

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 (108) hide show
  1. package/README.md +83 -10
  2. package/package.json +1 -1
  3. package/skills/backend/database/postgres-patterns/LICENSE.ANTIGRAVITY +21 -0
  4. package/skills/backend/database/postgres-patterns/LICENSE.ECC +21 -0
  5. package/skills/backend/database/postgres-patterns/NOTICE.md +11 -0
  6. package/skills/backend/database/postgres-patterns/SKILL.md +180 -0
  7. package/skills/backend/go/golang-patterns/LICENSE +21 -0
  8. package/skills/backend/go/golang-patterns/NOTICE.md +10 -0
  9. package/skills/backend/go/golang-patterns/SKILL.md +674 -0
  10. package/skills/backend/go/golang-testing/LICENSE +21 -0
  11. package/skills/backend/go/golang-testing/NOTICE.md +10 -0
  12. package/skills/backend/go/golang-testing/SKILL.md +329 -0
  13. package/skills/backend/java/java-coding-standards/LICENSE +21 -0
  14. package/skills/backend/java/java-coding-standards/NOTICE.md +10 -0
  15. package/skills/backend/java/java-coding-standards/SKILL.md +383 -0
  16. package/skills/backend/java/java-junit/LICENSE +21 -0
  17. package/skills/backend/java/java-junit/NOTICE.md +10 -0
  18. package/skills/backend/java/java-junit/SKILL.md +64 -0
  19. package/skills/backend/kotlin/kotlin-patterns/LICENSE +21 -0
  20. package/skills/backend/kotlin/kotlin-patterns/NOTICE.md +7 -0
  21. package/skills/backend/kotlin/kotlin-patterns/SKILL.md +711 -0
  22. package/skills/backend/kotlin/kotlin-testing/LICENSE +21 -0
  23. package/skills/backend/kotlin/kotlin-testing/NOTICE.md +7 -0
  24. package/skills/backend/kotlin/kotlin-testing/SKILL.md +824 -0
  25. package/skills/backend/python/python-patterns/LICENSE +21 -0
  26. package/skills/backend/python/python-patterns/NOTICE.md +7 -0
  27. package/skills/backend/python/python-patterns/SKILL.md +424 -0
  28. package/skills/backend/python/python-testing/LICENSE +21 -0
  29. package/skills/backend/python/python-testing/NOTICE.md +7 -0
  30. package/skills/backend/python/python-testing/SKILL.md +494 -0
  31. package/skills/devops/docker-patterns/LICENSE.ANTIGRAVITY +21 -0
  32. package/skills/devops/docker-patterns/LICENSE.ECC +21 -0
  33. package/skills/devops/docker-patterns/NOTICE.md +11 -0
  34. package/skills/devops/docker-patterns/SKILL.md +397 -0
  35. package/skills/frontend/accessibility/LICENSE +21 -0
  36. package/skills/frontend/accessibility/NOTICE.md +10 -0
  37. package/skills/frontend/accessibility/SKILL.md +145 -0
  38. package/skills/frontend/design/ui-ux-pro-max/LICENSE +21 -0
  39. package/skills/frontend/design/ui-ux-pro-max/NOTICE.md +12 -0
  40. package/skills/frontend/design/ui-ux-pro-max/SKILL.md +672 -0
  41. package/skills/frontend/design/ui-ux-pro-max/data/_sync_all.py +414 -0
  42. package/skills/frontend/design/ui-ux-pro-max/data/app-interface.csv +31 -0
  43. package/skills/frontend/design/ui-ux-pro-max/data/charts.csv +26 -0
  44. package/skills/frontend/design/ui-ux-pro-max/data/colors.csv +162 -0
  45. package/skills/frontend/design/ui-ux-pro-max/data/design.csv +1776 -0
  46. package/skills/frontend/design/ui-ux-pro-max/data/draft.csv +1779 -0
  47. package/skills/frontend/design/ui-ux-pro-max/data/google-fonts.csv +1924 -0
  48. package/skills/frontend/design/ui-ux-pro-max/data/icons.csv +106 -0
  49. package/skills/frontend/design/ui-ux-pro-max/data/landing.csv +35 -0
  50. package/skills/frontend/design/ui-ux-pro-max/data/products.csv +162 -0
  51. package/skills/frontend/design/ui-ux-pro-max/data/react-performance.csv +45 -0
  52. package/skills/frontend/design/ui-ux-pro-max/data/stacks/angular.csv +51 -0
  53. package/skills/frontend/design/ui-ux-pro-max/data/stacks/astro.csv +54 -0
  54. package/skills/frontend/design/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  55. package/skills/frontend/design/ui-ux-pro-max/data/stacks/html-tailwind.csv +56 -0
  56. package/skills/frontend/design/ui-ux-pro-max/data/stacks/jetpack-compose.csv +53 -0
  57. package/skills/frontend/design/ui-ux-pro-max/data/stacks/laravel.csv +51 -0
  58. package/skills/frontend/design/ui-ux-pro-max/data/stacks/nextjs.csv +53 -0
  59. package/skills/frontend/design/ui-ux-pro-max/data/stacks/nuxt-ui.csv +51 -0
  60. package/skills/frontend/design/ui-ux-pro-max/data/stacks/nuxtjs.csv +59 -0
  61. package/skills/frontend/design/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  62. package/skills/frontend/design/ui-ux-pro-max/data/stacks/react.csv +54 -0
  63. package/skills/frontend/design/ui-ux-pro-max/data/stacks/shadcn.csv +61 -0
  64. package/skills/frontend/design/ui-ux-pro-max/data/stacks/svelte.csv +54 -0
  65. package/skills/frontend/design/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  66. package/skills/frontend/design/ui-ux-pro-max/data/stacks/threejs.csv +54 -0
  67. package/skills/frontend/design/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  68. package/skills/frontend/design/ui-ux-pro-max/data/styles.csv +85 -0
  69. package/skills/frontend/design/ui-ux-pro-max/data/typography.csv +74 -0
  70. package/skills/frontend/design/ui-ux-pro-max/data/ui-reasoning.csv +162 -0
  71. package/skills/frontend/design/ui-ux-pro-max/data/ux-guidelines.csv +100 -0
  72. package/skills/frontend/design/ui-ux-pro-max/scripts/core.py +262 -0
  73. package/skills/frontend/design/ui-ux-pro-max/scripts/design_system.py +1148 -0
  74. package/skills/frontend/design/ui-ux-pro-max/scripts/search.py +114 -0
  75. package/skills/frontend/react/react-patterns/SKILL.md +4 -4
  76. package/skills/frontend/react/react-patterns/rules/react/LICENSE +21 -0
  77. package/skills/frontend/react/react-patterns/rules/react/NOTICE.md +11 -0
  78. package/skills/frontend/react/react-patterns/rules/react/coding-style.md +109 -0
  79. package/skills/frontend/react/react-patterns/rules/react/hooks.md +187 -0
  80. package/skills/frontend/react/react-patterns/rules/react/patterns.md +194 -0
  81. package/skills/frontend/react/react-patterns/rules/react/security.md +180 -0
  82. package/skills/frontend/react/react-patterns/rules/react/testing.md +208 -0
  83. package/skills/frontend/react/react-performance/SKILL.md +2 -2
  84. package/skills/frontend/react/react-performance/rules/react/LICENSE +21 -0
  85. package/skills/frontend/react/react-performance/rules/react/NOTICE.md +11 -0
  86. package/skills/frontend/react/react-performance/rules/react/coding-style.md +109 -0
  87. package/skills/frontend/react/react-performance/rules/react/hooks.md +187 -0
  88. package/skills/frontend/react/react-performance/rules/react/patterns.md +194 -0
  89. package/skills/frontend/react/react-performance/rules/react/security.md +180 -0
  90. package/skills/frontend/react/react-performance/rules/react/testing.md +208 -0
  91. package/skills/frontend/react/react-testing/SKILL.md +4 -4
  92. package/skills/frontend/react/react-testing/rules/react/LICENSE +21 -0
  93. package/skills/frontend/react/react-testing/rules/react/NOTICE.md +11 -0
  94. package/skills/frontend/react/react-testing/rules/react/coding-style.md +109 -0
  95. package/skills/frontend/react/react-testing/rules/react/hooks.md +187 -0
  96. package/skills/frontend/react/react-testing/rules/react/patterns.md +194 -0
  97. package/skills/frontend/react/react-testing/rules/react/security.md +180 -0
  98. package/skills/frontend/react/react-testing/rules/react/testing.md +208 -0
  99. package/skills/general/code-reviewer/AGENTS.md +292 -0
  100. package/skills/general/code-reviewer/LICENSE +201 -0
  101. package/skills/general/code-reviewer/NOTICE.md +10 -0
  102. package/skills/general/code-reviewer/SKILL.md +132 -0
  103. package/skills/general/code-reviewer/rules/correctness-error-handling.md +279 -0
  104. package/skills/general/code-reviewer/rules/maintainability-naming.md +149 -0
  105. package/skills/general/code-reviewer/rules/maintainability-type-hints.md +93 -0
  106. package/skills/general/code-reviewer/rules/performance-n-plus-one.md +250 -0
  107. package/skills/general/code-reviewer/rules/security-sql-injection.md +142 -0
  108. package/skills/general/code-reviewer/rules/security-xss-prevention.md +225 -0
@@ -0,0 +1,187 @@
1
+ ---
2
+ paths:
3
+ - "**/*.tsx"
4
+ - "**/*.jsx"
5
+ - "**/hooks/**/*.ts"
6
+ - "**/hooks/**/*.js"
7
+ - "**/use-*.ts"
8
+ - "**/use-*.tsx"
9
+ ---
10
+ # React Hooks
11
+
12
+ > This file covers **React hooks** (`useState`, `useEffect`, `useMemo`, `useCallback`, custom hooks) — NOT the Claude Code `hooks/` runtime system. Naming matches the per-language convention `rules/<lang>/hooks.md` used across this repo.
13
+ >
14
+ > Extends the upstream `typescript/patterns.md` and `common/patterns.md` rules.
15
+
16
+ ## Rules of Hooks
17
+
18
+ Enforce `eslint-plugin-react-hooks` with `react-hooks/rules-of-hooks` set to error.
19
+
20
+ 1. Hooks only at the top level of a function component or another hook
21
+ 2. Never in loops, conditionals, nested functions, or after early returns
22
+ 3. Always called in the same order on every render
23
+ 4. Only inside React function components or custom hooks (functions starting with `use`)
24
+
25
+ ```tsx
26
+ // WRONG: conditional hook
27
+ function Foo({ enabled }: { enabled: boolean }) {
28
+ if (enabled) {
29
+ const [x, setX] = useState(0); // rule violation
30
+ }
31
+ }
32
+
33
+ // CORRECT: hook unconditional, condition inside
34
+ function Foo({ enabled }: { enabled: boolean }) {
35
+ const [x, setX] = useState(0);
36
+ if (!enabled) return null;
37
+ return <span>{x}</span>;
38
+ }
39
+ ```
40
+
41
+ ## `useEffect` — When NOT to Use
42
+
43
+ `useEffect` is for synchronizing with external systems (subscriptions, browser APIs, third-party libraries). It is **not** the right tool for:
44
+
45
+ - Derived state — compute it during render
46
+ - Transforming data for rendering — compute it during render
47
+ - Resetting state when a prop changes — use a `key` on the parent or derive from props
48
+ - Notifying parents of state changes — call the callback in the event handler
49
+ - Initializing app-level singletons — call the function module-side or in `main.tsx`
50
+
51
+ ```tsx
52
+ // WRONG: effect for derived state
53
+ const [fullName, setFullName] = useState("");
54
+ useEffect(() => {
55
+ setFullName(`${first} ${last}`);
56
+ }, [first, last]);
57
+
58
+ // CORRECT: derive during render
59
+ const fullName = `${first} ${last}`;
60
+ ```
61
+
62
+ ## Dependency Arrays
63
+
64
+ - Always include every reactive value referenced inside the effect/callback
65
+ - Enable `react-hooks/exhaustive-deps` lint rule — never silence it without a comment explaining why
66
+ - If the dep array grows unwieldy, the effect is doing too much — split it
67
+ - Stable identity for functions passed in deps: wrap in `useCallback` only when the function is itself a dependency of another hook or passed to a memoized child
68
+
69
+ ## Cleanup
70
+
71
+ Every subscription, interval, listener, or in-flight request must clean up.
72
+
73
+ ```tsx
74
+ useEffect(() => {
75
+ const controller = new AbortController();
76
+ fetch(url, { signal: controller.signal }).then(handleResponse);
77
+ return () => controller.abort();
78
+ }, [url]);
79
+ ```
80
+
81
+ ```tsx
82
+ useEffect(() => {
83
+ const id = setInterval(tick, 1000);
84
+ return () => clearInterval(id);
85
+ }, []);
86
+ ```
87
+
88
+ Missing cleanup = race conditions when deps change, memory leaks on unmount.
89
+
90
+ ## `useMemo` and `useCallback` — When Worth It
91
+
92
+ Default position: **do not memoize**. Add `useMemo` / `useCallback` only when:
93
+
94
+ 1. The value is passed to a `React.memo`-wrapped child as a prop, and identity matters
95
+ 2. The value is a dependency of another `useEffect` / `useMemo` / `useCallback`
96
+ 3. The computation is measurably expensive (profile before assuming)
97
+
98
+ Premature memoization adds noise, hides bugs, and can be slower than the recompute it replaces.
99
+
100
+ ## Custom Hooks
101
+
102
+ Extract a custom hook when:
103
+
104
+ - The same hook sequence (state + effect + computed) appears in 2+ components
105
+ - The logic has a clear, nameable purpose (`useDebounce`, `useOnClickOutside`, `useLocalStorage`)
106
+ - You want to test the logic independently of any component
107
+
108
+ Do NOT extract when:
109
+
110
+ - It would have a single caller — inline it
111
+ - The "hook" is just `useState` with a different name — adds indirection, no value
112
+
113
+ ```tsx
114
+ export function useDebounce<T>(value: T, delay: number): T {
115
+ const [debounced, setDebounced] = useState(value);
116
+ useEffect(() => {
117
+ const id = setTimeout(() => setDebounced(value), delay);
118
+ return () => clearTimeout(id);
119
+ }, [value, delay]);
120
+ return debounced;
121
+ }
122
+ ```
123
+
124
+ ## `useState` Patterns
125
+
126
+ - Initial state from prop only at mount: pass a function `useState(() => computeInitial(prop))` when computation is expensive
127
+ - Functional updater when the new state depends on the old: `setCount(c => c + 1)` — never `setCount(count + 1)` inside async or batched contexts
128
+ - Group related state into one object only when they always change together; otherwise split into multiple `useState` calls
129
+ - Use `useReducer` once state transitions are conditional on the previous state or there are 3+ related values
130
+
131
+ ## `useRef` Patterns
132
+
133
+ - DOM refs for imperative APIs (focus, scroll, third-party libs)
134
+ - Mutable container that does not trigger re-render (timer ids, previous values, "is mounted" flags)
135
+ - Never read or write `ref.current` during render — only inside effects or event handlers
136
+ - `useImperativeHandle` only when exposing a child API to a parent ref — last-resort escape hatch
137
+
138
+ ## `useSyncExternalStore`
139
+
140
+ Use this hook to subscribe to any external store (browser API, third-party state lib, custom event emitter). It is the supported way to make external state safe with concurrent rendering.
141
+
142
+ ```tsx
143
+ const isOnline = useSyncExternalStore(
144
+ (cb) => {
145
+ window.addEventListener("online", cb);
146
+ window.addEventListener("offline", cb);
147
+ return () => {
148
+ window.removeEventListener("online", cb);
149
+ window.removeEventListener("offline", cb);
150
+ };
151
+ },
152
+ () => navigator.onLine,
153
+ () => true,
154
+ );
155
+ ```
156
+
157
+ ## React 19 Additions
158
+
159
+ - `use()` — unwrap promises and contexts inline; usable conditionally (only hook with that property)
160
+ - `useFormStatus()` / `useFormState()` (or `useActionState`) — form submission state without prop drilling
161
+ - `useOptimistic()` — optimistic UI updates while a server action is pending
162
+ - `useTransition()` — mark non-urgent state updates so urgent ones stay responsive
163
+
164
+ When the project targets React 19+, prefer these over hand-rolled equivalents.
165
+
166
+ ## Stale Closure Trap
167
+
168
+ Async handlers and intervals capture the values from the render where they were created. Fix by:
169
+
170
+ 1. Using the functional updater form of `setState`
171
+ 2. Putting the changing value in the dep array of `useEffect` and rebuilding the handler
172
+ 3. Reading from a ref that is kept in sync
173
+
174
+ ## Lint Configuration
175
+
176
+ Required rules:
177
+
178
+ ```json
179
+ {
180
+ "rules": {
181
+ "react-hooks/rules-of-hooks": "error",
182
+ "react-hooks/exhaustive-deps": "warn"
183
+ }
184
+ }
185
+ ```
186
+
187
+ Treat `exhaustive-deps` warnings as errors in CI for new code.
@@ -0,0 +1,194 @@
1
+ ---
2
+ paths:
3
+ - "**/*.tsx"
4
+ - "**/*.jsx"
5
+ - "**/components/**/*.ts"
6
+ - "**/components/**/*.js"
7
+ - "**/app/**/*.tsx"
8
+ - "**/pages/**/*.tsx"
9
+ ---
10
+ # React Patterns
11
+
12
+ > This file extends the upstream `typescript/patterns.md` and `common/patterns.md` rules with React specific content. For hook-specific rules see [hooks.md](./hooks.md).
13
+
14
+ ## Container / Presentational Split
15
+
16
+ Container components own data fetching, state, and side effects. Presentational components receive props and render — no service calls, no hooks beyond local UI state.
17
+
18
+ ```tsx
19
+ // Container — owns data
20
+ export function UserPage({ userId }: { userId: string }) {
21
+ const { data: user, isLoading } = useUser(userId);
22
+ if (isLoading) return <Spinner />;
23
+ if (!user) return <NotFound />;
24
+ return <UserCard user={user} onSelect={handleSelect} />;
25
+ }
26
+
27
+ // Presentational — pure
28
+ export function UserCard({ user, onSelect }: { user: User; onSelect: (id: string) => void }) {
29
+ return <button onClick={() => onSelect(user.id)}>{user.name}</button>;
30
+ }
31
+ ```
32
+
33
+ ## State Location Decision Tree
34
+
35
+ 1. Used by one component → `useState` inside it
36
+ 2. Used by parent + a few children → lift to nearest common ancestor, pass via props
37
+ 3. Used across distant branches → React Context **for low-frequency reads only** (theme, auth, locale)
38
+ 4. High-frequency updates shared across the tree → external store (Zustand, Jotai, Redux Toolkit)
39
+ 5. Server-derived data → server-state library (TanStack Query, SWR, RSC fetch) — not application state
40
+
41
+ Context misused for frequently changing values causes every consumer to re-render on every update.
42
+
43
+ ## Server / Client Component Boundary (RSC, Next.js App Router)
44
+
45
+ - Server Components are the default — they run on the server, do not ship to the client, and can `await` directly
46
+ - Client Components opt in with `"use client"` at the top of the file
47
+ - Data flows down: a Server Component can render a Client Component and pass serializable props
48
+ - A Client Component cannot import a Server Component, but it can receive one via `children` or named slots
49
+
50
+ ```tsx
51
+ // Server (default)
52
+ export default async function Page() {
53
+ const user = await fetchUser();
54
+ return <UserClient user={user} />;
55
+ }
56
+
57
+ // Client
58
+ "use client";
59
+ export function UserClient({ user }: { user: User }) {
60
+ const [tab, setTab] = useState("profile");
61
+ return <Tabs value={tab} onChange={setTab}>{user.name}</Tabs>;
62
+ }
63
+ ```
64
+
65
+ - Never import `"server-only"` packages (DB clients, secrets) from a Client Component file — wrap them in a Server Component or Server Action
66
+ - Mark sensitive modules with `import "server-only"` so the bundler errors if a client file imports them
67
+
68
+ ## Suspense + Error Boundaries
69
+
70
+ Every Suspense boundary needs an Error Boundary above it. The pair handles both states.
71
+
72
+ ```tsx
73
+ <ErrorBoundary fallback={<ErrorView />}>
74
+ <Suspense fallback={<Skeleton />}>
75
+ <UserDetails id={id} />
76
+ </Suspense>
77
+ </ErrorBoundary>
78
+ ```
79
+
80
+ - Place Suspense boundaries close to where data is needed, not at the route root
81
+ - Multiple narrower boundaries reveal loaded content progressively
82
+ - Error Boundary must be a Class Component (React 19 has no functional equivalent yet) OR use a library wrapper such as `react-error-boundary`
83
+
84
+ ## Forms
85
+
86
+ ### Uncontrolled (React 19 + form actions)
87
+
88
+ Prefer uncontrolled inputs with form actions when the form has a clear submit step. The browser owns the value; React reads it via `FormData` on submit.
89
+
90
+ ```tsx
91
+ async function action(formData: FormData) {
92
+ "use server";
93
+ await saveUser({ name: String(formData.get("name")) });
94
+ }
95
+
96
+ export function UserForm() {
97
+ return (
98
+ <form action={action}>
99
+ <input name="name" required />
100
+ <button type="submit">Save</button>
101
+ </form>
102
+ );
103
+ }
104
+ ```
105
+
106
+ ### Controlled
107
+
108
+ Use controlled inputs when the value drives other UI, requires real-time validation, or formatting.
109
+
110
+ ```tsx
111
+ const [email, setEmail] = useState("");
112
+ return <input value={email} onChange={(e) => setEmail(e.target.value)} />;
113
+ ```
114
+
115
+ ### Form Libraries
116
+
117
+ For complex forms (multi-step, dynamic field arrays, cross-field validation), use a library:
118
+
119
+ - React Hook Form — minimal re-renders, uncontrolled-first
120
+ - TanStack Form — typed, framework-agnostic
121
+ - Final Form — when subscription-based re-renders matter
122
+
123
+ ## Data Fetching
124
+
125
+ | Strategy | When |
126
+ |---|---|
127
+ | RSC fetch (`await` in Server Component) | Per-request data in Next.js App Router, no client-side cache needed |
128
+ | TanStack Query | Client-side cache, mutations, optimistic updates, polling |
129
+ | SWR | Lightweight cache + revalidation, simpler than TanStack Query |
130
+ | `fetch` in `useEffect` | Avoid — race conditions, no cache, no retry. Only acceptable for one-off fire-and-forget |
131
+
132
+ Never fetch in a `useEffect` when a real cache library is available — they handle deduping, cache invalidation, error retry, and Suspense integration.
133
+
134
+ ## Lists and Keys
135
+
136
+ - `key` must be stable across renders — never `index` for any list that can reorder, insert, or delete
137
+ - `key` must be unique among siblings, not globally
138
+ - A reordered list with index keys causes state in child components to attach to the wrong row
139
+
140
+ ## Composition over Inheritance
141
+
142
+ - Pass `children` for slot-style composition
143
+ - Pass render-prop functions for parameterized rendering
144
+ - Pass component types for plug-in points: `renderItem={UserRow}`
145
+ - Never extend a component class to specialize behavior
146
+
147
+ ## Compound Components
148
+
149
+ For related controls (Tabs, Accordion, Menu), use compound components sharing state via Context:
150
+
151
+ ```tsx
152
+ <Tabs defaultValue="profile">
153
+ <Tabs.List>
154
+ <Tabs.Trigger value="profile">Profile</Tabs.Trigger>
155
+ <Tabs.Trigger value="settings">Settings</Tabs.Trigger>
156
+ </Tabs.List>
157
+ <Tabs.Panel value="profile"><ProfileForm /></Tabs.Panel>
158
+ <Tabs.Panel value="settings"><SettingsForm /></Tabs.Panel>
159
+ </Tabs>
160
+ ```
161
+
162
+ ## Portals
163
+
164
+ Use `createPortal` for modals, tooltips, toast containers — anything that must escape the parent's `overflow: hidden` or `z-index` stacking context. Render to a stable DOM node mounted in `index.html`.
165
+
166
+ ## Refs and Forwarding (React 19+)
167
+
168
+ React 19 lets function components accept `ref` as a regular prop — `forwardRef` is no longer required.
169
+
170
+ ```tsx
171
+ export function Input({ ref, ...rest }: { ref?: React.Ref<HTMLInputElement> } & InputProps) {
172
+ return <input ref={ref} {...rest} />;
173
+ }
174
+ ```
175
+
176
+ Older codebases on React 18 still need `forwardRef`.
177
+
178
+ ## Out of Scope (Pointer Sections)
179
+
180
+ ### Next.js (App Router)
181
+
182
+ - Server Actions, Route Handlers, Middleware, Parallel/Intercepted Routes, streaming Metadata
183
+ - Treated as a separate framework concern — when adding deep Next-specific patterns, propose a dedicated `rules/nextjs/` track
184
+ - For now follow Next.js official docs for App Router specifics
185
+
186
+ ### React Native
187
+
188
+ - Platform-specific imports (`Platform.OS`, `.ios.tsx` / `.android.tsx`), `StyleSheet`, navigation libraries (React Navigation, Expo Router)
189
+ - Treated as a separate track — `rules/react-native/` is not yet present
190
+ - React core hooks/patterns from this file still apply
191
+
192
+ ## Skill Reference
193
+
194
+ For React-specific deep dives see `skills/react-patterns/SKILL.md`. For cross-framework frontend concerns see `skills/frontend-patterns/SKILL.md`. For accessibility see `skills/accessibility/SKILL.md`.
@@ -0,0 +1,180 @@
1
+ ---
2
+ paths:
3
+ - "**/*.tsx"
4
+ - "**/*.jsx"
5
+ - "**/components/**/*.ts"
6
+ - "**/app/**/*.ts"
7
+ - "**/pages/**/*.ts"
8
+ ---
9
+ # React Security
10
+
11
+ > This file extends the upstream `typescript/security.md` and `common/security.md` rules with React specific content.
12
+
13
+ ## XSS via `dangerouslySetInnerHTML`
14
+
15
+ CRITICAL. The prop name is deliberately scary — treat every usage as a code review halt.
16
+
17
+ ```tsx
18
+ // CRITICAL: unsanitized user input
19
+ <div dangerouslySetInnerHTML={{ __html: userBio }} />
20
+
21
+ // CORRECT options:
22
+ // 1. Render as text
23
+ <div>{userBio}</div>
24
+
25
+ // 2. Render parsed markdown via a library that sanitizes
26
+ <ReactMarkdown>{userBio}</ReactMarkdown>
27
+
28
+ // 3. If raw HTML is required, sanitize first with DOMPurify
29
+ import DOMPurify from "isomorphic-dompurify";
30
+ <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userBio) }} />
31
+ ```
32
+
33
+ Audit checklist for every `dangerouslySetInnerHTML` call:
34
+
35
+ - Is the input always under our control? Document the source.
36
+ - If user-derived: is it sanitized at the **same call site**? (Sanitization at the API boundary is acceptable only if every consumer is verified.)
37
+ - Is the sanitizer config allowlisting tags, not denylisting?
38
+
39
+ ## Unsafe URL Schemes
40
+
41
+ `javascript:` and `data:` URLs in `href`, `src`, and `xlink:href` execute arbitrary code.
42
+
43
+ ```tsx
44
+ // CRITICAL: javascript: URL injection
45
+ <a href={user.website}>Visit</a> // if user.website = "javascript:alert(1)"
46
+
47
+ // CORRECT: validate scheme
48
+ function safeUrl(url: string): string | undefined {
49
+ try {
50
+ const parsed = new URL(url);
51
+ if (["http:", "https:", "mailto:"].includes(parsed.protocol)) return url;
52
+ } catch {
53
+ return undefined;
54
+ }
55
+ return undefined;
56
+ }
57
+ <a href={safeUrl(user.website)}>Visit</a>
58
+ ```
59
+
60
+ React warns about `javascript:` URLs in `href` in development mode, but does not block them at runtime. `data:` URLs and other schemes also slip through. Always validate.
61
+
62
+ ## `target="_blank"` Without `rel`
63
+
64
+ `<a target="_blank">` without `rel="noopener noreferrer"` lets the target page access `window.opener` and run navigation hijacks.
65
+
66
+ ```tsx
67
+ // WRONG
68
+ <a href={externalUrl} target="_blank">External</a>
69
+
70
+ // CORRECT
71
+ <a href={externalUrl} target="_blank" rel="noopener noreferrer">External</a>
72
+ ```
73
+
74
+ Modern browsers default to `noopener` when `target="_blank"`, but do not rely on browser defaults — be explicit.
75
+
76
+ ## Server Action Input Validation
77
+
78
+ Server Actions (`"use server"`) run with the same trust level as a public API endpoint. Validate every input.
79
+
80
+ ```tsx
81
+ "use server";
82
+ import { z } from "zod";
83
+
84
+ const Input = z.object({
85
+ email: z.string().email(),
86
+ age: z.number().int().min(0).max(120),
87
+ });
88
+
89
+ export async function updateUser(_state: unknown, formData: FormData) {
90
+ const parsed = Input.safeParse({
91
+ email: formData.get("email"),
92
+ age: Number(formData.get("age")),
93
+ });
94
+ if (!parsed.success) return { error: parsed.error.flatten() };
95
+ // ...
96
+ }
97
+ ```
98
+
99
+ - Authenticate inside the action — do not trust the client-side route gate
100
+ - Authorize: confirm the current user has permission for the specific record they are mutating
101
+ - Rate limit sensitive actions
102
+
103
+ ## Secret Exposure via Env Vars
104
+
105
+ Prefixed env vars are bundled into the client. Treat them as public.
106
+
107
+ | Framework | Public prefix | Private |
108
+ |---|---|---|
109
+ | Next.js | `NEXT_PUBLIC_*` | All others |
110
+ | Vite | `VITE_*` | `.env` server-side only |
111
+ | Create React App | `REACT_APP_*`, plus `NODE_ENV` and `PUBLIC_URL` | All others (anything without the `REACT_APP_` prefix is server-side only) |
112
+ | Remix | `process.env` access in `loader`/`action` only | Same |
113
+
114
+ ```ts
115
+ // CRITICAL: secret leaked to client bundle
116
+ const apiKey = process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY;
117
+ ```
118
+
119
+ Audit on every PR that touches env vars: would this string in the public bundle be a problem?
120
+
121
+ ## Authentication / Authorization
122
+
123
+ - Never store sessions in `localStorage` — accessible to any XSS. Use httpOnly secure cookies.
124
+ - Never trust client-set state to gate sensitive UI. Render-gating in JSX prevents display, not access — the API must enforce.
125
+ - CSRF: cookie-based auth requires CSRF tokens or `SameSite=Strict`/`Lax` cookies
126
+ - Use double-submit cookies or origin verification for form actions when not using framework defaults
127
+
128
+ ## Content Security Policy (CSP)
129
+
130
+ Configure server-side. The minimum acceptable CSP for a React app:
131
+
132
+ ```
133
+ default-src 'self';
134
+ script-src 'self' 'nonce-{REQUEST_NONCE}';
135
+ style-src 'self' 'unsafe-inline';
136
+ img-src 'self' data: https:;
137
+ connect-src 'self' https://api.example.com;
138
+ frame-ancestors 'none';
139
+ ```
140
+
141
+ - Avoid `unsafe-inline` and `unsafe-eval` in `script-src`
142
+ - For SSR with inline scripts (Next.js streaming, hydration data), use per-request nonces — both Next.js and Remix support nonce injection
143
+ - `style-src 'unsafe-inline'` is often unavoidable for CSS-in-JS libraries — document the tradeoff
144
+
145
+ ## Prototype Pollution via Object Spread
146
+
147
+ ```tsx
148
+ // WRONG: untrusted JSON spread directly into state
149
+ const update = await req.json();
150
+ setState({ ...state, ...update }); // attacker controls __proto__
151
+
152
+ // CORRECT: parse with a schema, or guard keys
153
+ const Allowed = z.object({ name: z.string(), email: z.string().email() });
154
+ const parsed = Allowed.parse(await req.json());
155
+ setState({ ...state, ...parsed });
156
+ ```
157
+
158
+ ## SSR Template Injection
159
+
160
+ When using `renderToString` or `renderToPipeableStream`:
161
+
162
+ - All values rendered inside JSX are escaped by React — safe
163
+ - Values passed to `dangerouslySetInnerHTML` are NOT escaped — same rules as client
164
+ - Manually constructed HTML wrappers around the React output must be escaped or sanitized — never concatenate user input into the surrounding HTML template
165
+
166
+ ## Third-Party Components
167
+
168
+ - Audit `npm audit` before adding any UI library
169
+ - Check that the library does not internally use `dangerouslySetInnerHTML` on its input (e.g., rich text editors)
170
+ - Pin versions, review changelogs before major upgrades
171
+ - Be wary of components that accept HTML strings as props
172
+
173
+ ## Source Map Exposure in Production
174
+
175
+ Production builds should ship without source maps, or with sourcemaps uploaded to an error tracker (Sentry) and stripped from the public bundle. Public source maps leak internal logic and file structure.
176
+
177
+ ## Agent Support
178
+
179
+ - Use `security-reviewer` agent for comprehensive security audits across the codebase
180
+ - Use `react-reviewer` agent for React-specific patterns and the above rules in active code review