@workingpayload/agent-skills 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/APIForge/skill.md +165 -0
  2. package/AccessPlus/skill.md +136 -0
  3. package/AlgoMaster/skill.md +125 -0
  4. package/Architekt AI/skill.md +140 -0
  5. package/AuthCraft/skill.md +144 -0
  6. package/AutoScriptor/skill.md +137 -0
  7. package/BoilerCore/skill.md +136 -0
  8. package/BugHunter Pro/skill.md +133 -0
  9. package/ChangeScribe/skill.md +113 -0
  10. package/CodeSage/skill.md +163 -0
  11. package/CommitCraft/skill.md +113 -0
  12. package/CoverageMax/skill.md +161 -0
  13. package/CronGenius/skill.md +157 -0
  14. package/DataPolish/skill.md +142 -0
  15. package/DataWeaver/skill.md +151 -0
  16. package/DockMaster/skill.md +158 -0
  17. package/DocuGenie/skill.md +138 -0
  18. package/EdgeGuard/skill.md +160 -0
  19. package/EnvWizard/skill.md +156 -0
  20. package/ErrorMedic/skill.md +152 -0
  21. package/FeatureSmith/skill.md +139 -0
  22. package/FlexiLayout/skill.md +144 -0
  23. package/FlowTester/skill.md +154 -0
  24. package/FunctionForge/skill.md +136 -0
  25. package/InputShield/skill.md +144 -0
  26. package/IssueForge/skill.md +148 -0
  27. package/KubeCrafter/skill.md +149 -0
  28. package/LogicLens/skill.md +132 -0
  29. package/MockSmith/skill.md +146 -0
  30. package/ModelSensei/skill.md +138 -0
  31. package/PRMentor/skill.md +103 -0
  32. package/PerfDetective/skill.md +90 -0
  33. package/PipelinePro/skill.md +146 -0
  34. package/PolyglotShift/skill.md +94 -0
  35. package/PromptForge/skill.md +118 -0
  36. package/QueryPulse/skill.md +123 -0
  37. package/README.md +416 -329
  38. package/ReadMeCraft/skill.md +127 -0
  39. package/RefactorX/skill.md +84 -0
  40. package/RenderBoost/skill.md +148 -0
  41. package/SEOMancer/skill.md +156 -0
  42. package/ScrapeMaster/skill.md +157 -0
  43. package/SecretSniffer/skill.md +123 -0
  44. package/SecureScan/skill.md +130 -0
  45. package/ServiceSplitter/skill.md +153 -0
  46. package/SpeedSmith/skill.md +155 -0
  47. package/StackWise/skill.md +155 -0
  48. package/TaskOrchestrator/skill.md +135 -0
  49. package/TestCrafter/skill.md +158 -0
  50. package/TraceMind/skill.md +143 -0
  51. package/UISmith/skill.md +131 -0
  52. package/bin/cli.js +377 -0
  53. package/extension-extender/SKILL.md +122 -0
  54. package/fastapi-furious/SKILL.md +148 -0
  55. package/package.json +41 -32
  56. package/python-master/SKILL.md +108 -0
  57. package/react-ranger/SKILL.md +93 -0
  58. package/scripts/build_index.py +282 -0
  59. package/scripts/doctor.py +541 -0
  60. package/scripts/install.py +397 -0
  61. package/scripts/route.py +348 -0
  62. package/scripts/score.py +355 -0
  63. package/scripts/test_skill.py +473 -0
  64. package/scripts/validate.py +254 -0
  65. package/skills-routing.json +1131 -0
  66. package/skills.json +3261 -0
  67. package/cli.js +0 -181
  68. package/skills/APIForge/skill.md +0 -32
  69. package/skills/AccessPlus/skill.md +0 -32
  70. package/skills/AlgoMaster/skill.md +0 -32
  71. package/skills/Architekt AI/skill.md +0 -32
  72. package/skills/AuthCraft/skill.md +0 -32
  73. package/skills/AutoScriptor/skill.md +0 -32
  74. package/skills/BoilerCore/skill.md +0 -32
  75. package/skills/BugHunter Pro/skill.md +0 -32
  76. package/skills/ChangeScribe/skill.md +0 -32
  77. package/skills/CodeSage/skill.md +0 -32
  78. package/skills/CommitCraft/skill.md +0 -32
  79. package/skills/CoverageMax/skill.md +0 -32
  80. package/skills/CronGenius/skill.md +0 -32
  81. package/skills/DataPolish/skill.md +0 -32
  82. package/skills/DataWeaver/skill.md +0 -32
  83. package/skills/DockMaster/skill.md +0 -32
  84. package/skills/DocuGenie/skill.md +0 -32
  85. package/skills/EdgeGuard/skill.md +0 -32
  86. package/skills/EnvWizard/skill.md +0 -32
  87. package/skills/ErrorMedic/skill.md +0 -32
  88. package/skills/Extension-Extender/SKILL.md +0 -41
  89. package/skills/Extension-Extender/references/ui-guidelines.md +0 -26
  90. package/skills/Fastapi-Furious/README.md +0 -16
  91. package/skills/Fastapi-Furious/SKILL.md +0 -37
  92. package/skills/FeatureSmith/skill.md +0 -32
  93. package/skills/FlexiLayout/skill.md +0 -32
  94. package/skills/FlowTester/skill.md +0 -32
  95. package/skills/FunctionForge/skill.md +0 -32
  96. package/skills/InputShield/skill.md +0 -32
  97. package/skills/IssueForge/skill.md +0 -32
  98. package/skills/KubeCrafter/skill.md +0 -32
  99. package/skills/LogicLens/skill.md +0 -32
  100. package/skills/MockSmith/skill.md +0 -32
  101. package/skills/ModelSensei/skill.md +0 -32
  102. package/skills/PRMentor/skill.md +0 -32
  103. package/skills/PerfDetective/skill.md +0 -32
  104. package/skills/PipelinePro/skill.md +0 -32
  105. package/skills/PolyglotShift/skill.md +0 -32
  106. package/skills/PromptForge/skill.md +0 -32
  107. package/skills/Python-Master/README.md +0 -11
  108. package/skills/Python-Master/SKILL.md +0 -37
  109. package/skills/QueryPulse/skill.md +0 -32
  110. package/skills/React-Ranger/README.md +0 -17
  111. package/skills/React-Ranger/SKILL.md +0 -37
  112. package/skills/ReadMeCraft/skill.md +0 -32
  113. package/skills/RefactorX/skill.md +0 -32
  114. package/skills/RenderBoost/skill.md +0 -32
  115. package/skills/SEOMancer/skill.md +0 -32
  116. package/skills/ScrapeMaster/skill.md +0 -32
  117. package/skills/SecretSniffer/skill.md +0 -32
  118. package/skills/SecureScan/skill.md +0 -32
  119. package/skills/ServiceSplitter/skill.md +0 -32
  120. package/skills/SpeedSmith/skill.md +0 -32
  121. package/skills/StackWise/skill.md +0 -32
  122. package/skills/TaskOrchestrator/skill.md +0 -32
  123. package/skills/TestCrafter/skill.md +0 -32
  124. package/skills/TraceMind/skill.md +0 -32
  125. package/skills/UISmith/skill.md +0 -32
  126. /package/{skills/Extension-Extender → extension-extender}/assets/manifest.json +0 -0
  127. /package/{skills/Extension-Extender → extension-extender}/assets/popup.css +0 -0
  128. /package/{skills/Extension-Extender → extension-extender}/assets/popup.html +0 -0
  129. /package/{skills/Extension-Extender → extension-extender}/assets/popup.js +0 -0
@@ -0,0 +1,144 @@
1
+ ---
2
+ name: flexilayout
3
+ description: Designs and debugs responsive CSS layouts using Flexbox, CSS Grid, container queries, and design tokens. Use when a user needs help with alignment bugs, breakpoint strategies, fluid typography, WCAG contrast, or building responsive UI components.
4
+ ---
5
+
6
+ # FlexiLayout
7
+
8
+ ## Overview
9
+
10
+ Diagnoses and fixes CSS layout problems, builds responsive component systems using Flexbox/Grid, implements container queries, enforces WCAG 2.2 contrast ratios, and structures design tokens for consistent responsive behavior.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Diagnose the Layout Problem
15
+
16
+ Before writing CSS, identify the layout model in use:
17
+ - Is this a **one-dimensional** flow? → Flexbox
18
+ - Is this a **two-dimensional** grid? → CSS Grid
19
+ - Does the component need to respond to its **container**, not the viewport? → Container Queries
20
+
21
+ Ask for (or inspect) the existing markup structure. Never apply layout CSS without understanding the HTML hierarchy.
22
+
23
+ ### 2. Apply the Correct Layout Primitive
24
+
25
+ **Flexbox — use for:**
26
+ ```css
27
+ .container {
28
+ display: flex;
29
+ flex-wrap: wrap; /* prevent overflow on small screens */
30
+ gap: var(--space-4); /* prefer gap over margin for spacing */
31
+ align-items: stretch; /* default; override explicitly */
32
+ }
33
+ /* Never use margin: auto on flex children for centering — use justify-content on parent */
34
+ ```
35
+
36
+ **CSS Grid — use for:**
37
+ ```css
38
+ .grid {
39
+ display: grid;
40
+ grid-template-columns: repeat(auto-fit, minmax(min(280px, 100%), 1fr));
41
+ gap: var(--space-6);
42
+ }
43
+ /* Use named grid lines or grid-template-areas for complex layouts */
44
+ .layout {
45
+ grid-template-areas:
46
+ "header header"
47
+ "sidebar main"
48
+ "footer footer";
49
+ }
50
+ ```
51
+
52
+ **Container Queries — use when the component is reused at varying widths:**
53
+ ```css
54
+ .card-wrapper {
55
+ container-type: inline-size;
56
+ container-name: card;
57
+ }
58
+ @container card (min-width: 480px) {
59
+ .card { flex-direction: row; }
60
+ }
61
+ ```
62
+
63
+ ### 3. Define Breakpoint Strategy
64
+
65
+ Use a **mobile-first** `min-width` approach. Anchor breakpoints to content, not device names:
66
+
67
+ ```css
68
+ /* Design tokens — define once, use everywhere */
69
+ :root {
70
+ --bp-sm: 480px;
71
+ --bp-md: 768px;
72
+ --bp-lg: 1024px;
73
+ --bp-xl: 1280px;
74
+ }
75
+
76
+ /* Usage */
77
+ @media (min-width: 768px) { ... }
78
+ ```
79
+
80
+ Prefer container queries over media queries for component-level responsiveness. Reserve media queries for page-level layout shifts (e.g., collapsing a sidebar).
81
+
82
+ ### 4. Fluid Typography & Spacing Tokens
83
+
84
+ ```css
85
+ :root {
86
+ /* Fluid type scale using clamp() */
87
+ --text-base: clamp(1rem, 0.9rem + 0.5vw, 1.25rem);
88
+ --text-lg: clamp(1.125rem, 1rem + 0.75vw, 1.5rem);
89
+
90
+ /* Spacing scale */
91
+ --space-1: 0.25rem;
92
+ --space-2: 0.5rem;
93
+ --space-4: 1rem;
94
+ --space-6: 1.5rem;
95
+ --space-8: 2rem;
96
+ }
97
+ ```
98
+
99
+ ### 5. WCAG 2.2 Contrast Compliance
100
+
101
+ - **AA minimum:** 4.5:1 for normal text, 3:1 for large text (18px+ or 14px+ bold) and UI components.
102
+ - **AAA target:** 7:1 for body text.
103
+
104
+ Verification steps:
105
+ 1. Use the WebAIM Contrast Checker or browser DevTools accessibility panel.
106
+ 2. Check both light and dark mode token pairs.
107
+ 3. Verify focus indicators meet 3:1 against adjacent colors (WCAG 2.2 SC 2.4.11).
108
+
109
+ ```css
110
+ /* Example accessible focus ring */
111
+ :focus-visible {
112
+ outline: 3px solid var(--color-focus);
113
+ outline-offset: 2px;
114
+ }
115
+ ```
116
+
117
+ ### 6. Validate & Output
118
+
119
+ Deliver:
120
+ 1. Corrected/new CSS with inline comments explaining each decision.
121
+ 2. A responsive behavior summary (what changes at each breakpoint).
122
+ 3. Any WCAG issues found and the fix applied.
123
+ 4. Browser support notes for any properties used (container queries require Chrome 105+, Firefox 110+, Safari 16+).
124
+
125
+ ## Edge Cases
126
+
127
+ **RTL support:** Set `dir="rtl"` on the root element or component container. Replace physical margin/padding properties with CSS logical properties: `margin-inline-start` instead of `margin-left`, `padding-inline-end` instead of `padding-right`. Use `[dir="rtl"]` selectors for directional overrides that logical properties cannot cover (e.g., icon flip transforms).
128
+
129
+ **Subgrid progressive enhancement:** Use `@supports` to layer subgrid in where available:
130
+ ```css
131
+ @supports (grid-template-rows: subgrid) {
132
+ .card-grid > .card {
133
+ display: grid;
134
+ grid-row: span 3;
135
+ grid-template-rows: subgrid; /* align header/body/footer across cards */
136
+ }
137
+ }
138
+ ```
139
+
140
+ **Subgrid alignment across nested components:** When a card grid inside a section needs column alignment with sibling grids, use `display: subgrid` on the nested container. Fall back to matching `grid-template-columns` values if subgrid support is insufficient.
141
+
142
+ **Overflow and `min-width: 0` on flex/grid children:** Flex and grid children default to `min-width: auto`, which prevents shrinking below content size and causes overflow. Fix: add `min-width: 0` (or `overflow: hidden`) to the child that needs to shrink.
143
+
144
+ **Dark mode token conflicts:** When system `prefers-color-scheme: dark` overrides explicit theme tokens, wrap dark tokens in both `@media (prefers-color-scheme: dark)` and a `[data-theme="dark"]` selector so JavaScript-controlled theme toggling and OS-level preference both work correctly.
@@ -0,0 +1,154 @@
1
+ ---
2
+ name: flowtester
3
+ description: Writes end-to-end and integration tests using Playwright or Cypress with the Page Object Model, AAA pattern, and CI-friendly configuration. Use when a user needs help with E2E test structure, test isolation, flaky test debugging, API contract testing, or CI pipeline integration.
4
+ ---
5
+
6
+ # FlowTester
7
+
8
+ ## Overview
9
+
10
+ Produces production-quality integration and E2E tests using Playwright (preferred) or Cypress, structured with the Page Object Model (POM), Arrange-Act-Assert (AAA) pattern, proper test isolation, and CI pipeline hooks. Addresses flaky tests with deterministic waiting strategies.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Clarify Scope
15
+
16
+ Determine the test type needed:
17
+ - **E2E (browser):** Full user journey through the UI — use Playwright or Cypress.
18
+ - **Integration (API):** Cross-service contract verification — use Playwright's `request` fixture, Supertest, or Pact for consumer-driven contracts.
19
+ - **Component integration:** Isolated component with real child components — use Playwright Component Testing or Cypress Component Testing.
20
+
21
+ Identify: the user journey to test, the entry URL, required auth state, and any third-party services to stub.
22
+
23
+ ### 2. Set Up Page Object Model
24
+
25
+ Create one PO class per page/feature area. POs encapsulate selectors and actions — tests contain only assertions and flow.
26
+
27
+ ```typescript
28
+ // pages/LoginPage.ts
29
+ export class LoginPage {
30
+ readonly emailInput = this.page.getByLabel('Email');
31
+ readonly passwordInput = this.page.getByLabel('Password');
32
+ readonly submitButton = this.page.getByRole('button', { name: 'Sign in' });
33
+ readonly errorMessage = this.page.getByRole('alert');
34
+ constructor(private page: Page) {}
35
+ async login(email: string, password: string) {
36
+ await this.emailInput.fill(email);
37
+ await this.passwordInput.fill(password);
38
+ await this.submitButton.click();
39
+ }
40
+ async goto() { await this.page.goto('/login'); }
41
+ }
42
+ ```
43
+
44
+ Selector priority: `getByRole` > `getByLabel` > `getByTestId` > CSS. Never use positional selectors like `nth-child`.
45
+
46
+ ### 3. Write Tests with AAA Pattern
47
+
48
+ ```typescript
49
+ test('authenticates valid user → redirects to dashboard', async ({ page }) => {
50
+ const loginPage = new LoginPage(page);
51
+ await loginPage.goto();
52
+ // Act
53
+ await loginPage.login('user@example.com', 'correct-password');
54
+ // Assert
55
+ await expect(page).toHaveURL('/dashboard');
56
+ });
57
+
58
+ test('shows error for invalid credentials', async ({ page }) => {
59
+ const loginPage = new LoginPage(page);
60
+ await loginPage.goto();
61
+ await loginPage.login('user@example.com', 'wrong-password');
62
+ await expect(loginPage.errorMessage).toContainText('Invalid email or password');
63
+ });
64
+ ```
65
+
66
+ ### 4. Test Isolation
67
+
68
+ - Use `test.beforeEach` to reset state, never `test.afterEach` (failures skip teardown).
69
+ - Seed DB state via API calls in `beforeEach`, not via UI interactions.
70
+ - Use Playwright's `storageState` to persist authenticated sessions across tests without re-logging in every test.
71
+
72
+ ```typescript
73
+ // playwright.config.ts
74
+ export default defineConfig({
75
+ globalSetup: './global-setup.ts', // creates storageState file
76
+ use: {
77
+ storageState: 'playwright/.auth/user.json',
78
+ baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
79
+ },
80
+ });
81
+ ```
82
+
83
+ ### 5. Stub External Services
84
+
85
+ Use **MSW (Mock Service Worker)** for browser-level API stubbing in component/integration tests:
86
+ ```typescript
87
+ // Playwright: intercept at network level
88
+ await page.route('**/api/payments/**', route =>
89
+ route.fulfill({ status: 200, body: JSON.stringify({ status: 'success' }) })
90
+ );
91
+ ```
92
+
93
+ For Cypress: use `cy.intercept()` with `cy.fixture()` for response bodies.
94
+
95
+ ### 6. Eliminate Flaky Tests
96
+
97
+ | Anti-pattern | Fix |
98
+ |---|---|
99
+ | `page.waitForTimeout(2000)` | `await expect(locator).toBeVisible()` |
100
+ | Hardcoded test IDs that change | `data-testid` attributes on stable elements |
101
+ | Shared global state between tests | `storageState` reset per test group |
102
+ | Race conditions on navigation | `await page.waitForURL('/target')` after click |
103
+ | Animation interference | `page.emulateMedia({ reducedMotion: 'reduce' })` |
104
+
105
+ ### 7. CI Integration
106
+
107
+ ```yaml
108
+ - run: npx playwright install --with-deps chromium
109
+ - run: npx playwright test --workers=4 --reporter=html --shard=1/4
110
+ env: { BASE_URL: "${{ secrets.STAGING_URL }}" }
111
+ - uses: actions/upload-artifact@v4
112
+ if: always()
113
+ with: { name: playwright-report, path: playwright-report/ }
114
+ ```
115
+
116
+ Use `--shard=N/M` across matrix jobs to parallelize large suites.
117
+
118
+ ## Output Format
119
+
120
+ Deliver:
121
+ 1. Page Object files in `tests/pages/`.
122
+ 2. Test spec files in `tests/<feature>/`.
123
+ 3. `playwright.config.ts` or `cypress.config.ts` snippet.
124
+ 4. CI workflow YAML fragment.
125
+ 5. Any MSW handler files if API stubbing is needed.
126
+
127
+ ## Edge Cases
128
+
129
+ **Auth-protected routes:** Create a `global-setup.ts` that programmatically logs in once via the API, saves `storageState` to disk, and reuses it for all tests — avoids per-test login overhead and prevents rate-limiting.
130
+
131
+ **Dynamic data in assertions:** Never assert on data that changes between runs (e.g., `createdAt` timestamps). Assert on structure and type using regex or partial matchers: `expect(text).toMatch(/Order #\d+/)`.
132
+
133
+ **Cypress vs. Playwright for multi-tab/multi-origin:** Cypress cannot handle multiple browser tabs or cross-origin iframes in the same test. If the flow opens a new tab (e.g., OAuth popup), use Playwright's `context.waitForEvent('page')` pattern instead.
134
+
135
+ **File download assertions:**
136
+ ```typescript
137
+ const [download] = await Promise.all([
138
+ page.waitForEvent('download'),
139
+ page.getByRole('button', { name: 'Export CSV' }).click(),
140
+ ]);
141
+ expect(download.suggestedFilename()).toMatch(/^report-\d{4}\.csv$/);
142
+ const path = await download.path();
143
+ const stats = fs.statSync(path!);
144
+ expect(stats.size).toBeGreaterThan(100); // non-empty file
145
+ ```
146
+
147
+ **Shared staging DB isolation:** When parallel workers share a staging DB, namespace data per worker using unique prefixes or schemas. Wrap each test in a transaction and roll back on teardown:
148
+ ```typescript
149
+ // Per-worker prefix
150
+ const prefix = `test_w${process.env.TEST_WORKER_INDEX ?? 0}_${Date.now()}`;
151
+ // Seed: createUser({ email: `${prefix}@example.com` })
152
+ // After each test: DELETE FROM ... WHERE email LIKE '${prefix}%'
153
+ // Or: wrap in a DB transaction and ROLLBACK in afterEach
154
+ ```
@@ -0,0 +1,136 @@
1
+ ---
2
+ name: functionforge
3
+ description: Writes pure, testable utility functions using functional programming principles — immutability, referential transparency, Result/Either types, currying, and pipe/compose. Use when a user needs to generate or refactor functions with explicit type signatures, safe error handling, or composable data transforms.
4
+ ---
5
+
6
+ # FunctionForge
7
+
8
+ ## Overview
9
+
10
+ Produces pure functions with explicit type signatures, safe error-handling via Result/Either types, and composable pipelines using pipe/compose. Every function is side-effect-free, deterministic, and independently testable.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Write the Type Signature First
15
+
16
+ Before implementation, define the full type signature. This constrains the solution space and serves as documentation.
17
+
18
+ ```typescript
19
+ // TypeScript
20
+ declare function parsePositiveInt(input: unknown): Result<number, ValidationError>
21
+ declare function formatCurrency(amount: number, locale: string): string
22
+ declare function groupBy<T, K extends string>(
23
+ key: (item: T) => K,
24
+ items: T[]
25
+ ): Record<K, T[]>
26
+ ```
27
+
28
+ ### 2. Enforce Purity Constraints
29
+
30
+ A function is pure if:
31
+ - **Same inputs always produce same outputs** (no `Date.now()`, `Math.random()`, or global reads inside)
32
+ - **No observable side effects** (no mutations, no I/O, no exceptions thrown for control flow)
33
+
34
+ ```typescript
35
+ // IMPURE — mutates input
36
+ function sortItems(items: Item[]): Item[] {
37
+ return items.sort((a, b) => a.name.localeCompare(b.name)); // sort mutates in place
38
+ }
39
+
40
+ // PURE — returns new array
41
+ function sortItems(items: readonly Item[]): Item[] {
42
+ return [...items].sort((a, b) => a.name.localeCompare(b.name));
43
+ }
44
+ ```
45
+
46
+ Use `readonly` / `Readonly<T>` / `as const` in TypeScript. Use `Object.freeze()` for runtime immutability when needed.
47
+
48
+ ### 3. Return Result/Either Instead of Throwing
49
+
50
+ ```typescript
51
+ // Using neverthrow (TypeScript)
52
+ import { ok, err, Result } from 'neverthrow';
53
+
54
+ type ValidationError = { code: string; message: string };
55
+
56
+ function parseEmail(input: unknown): Result<string, ValidationError> {
57
+ if (typeof input !== 'string') {
58
+ return err({ code: 'TYPE_ERROR', message: 'Expected string' });
59
+ }
60
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input)) {
61
+ return err({ code: 'INVALID_FORMAT', message: 'Not a valid email address' });
62
+ }
63
+ return ok(input.toLowerCase().trim());
64
+ }
65
+
66
+ // Caller handles both paths explicitly — no try/catch surprises
67
+ const result = parseEmail(userInput);
68
+ if (result.isOk()) {
69
+ sendEmail(result.value);
70
+ } else {
71
+ showError(result.error.message);
72
+ }
73
+ ```
74
+
75
+ In Python: use `returns.result` `Success`/`Failure` or a simple dataclass wrapper.
76
+
77
+ ### 4. Apply Currying for Partial Application
78
+
79
+ ```typescript
80
+ const multiply = (factor: number) => (value: number): number => value * factor;
81
+ const double = multiply(2);
82
+ const prices = [10, 20, 30].map(double); // [20, 40, 60]
83
+ ```
84
+
85
+ Curry data-last to enable point-free style with `pipe`.
86
+
87
+ ### 5. Compose with pipe / compose
88
+
89
+ ```typescript
90
+ import { pipe } from 'fp-ts/function';
91
+ // or: import { pipe } from 'remeda';
92
+
93
+ const processOrder = (raw: unknown) =>
94
+ pipe(
95
+ raw,
96
+ validateOrder, // unknown -> Result<RawOrder, Error>
97
+ map(normalizeOrder), // Result<RawOrder, Error> -> Result<Order, Error>
98
+ map(applyDiscount(0.1)),
99
+ map(formatForShipment)
100
+ );
101
+ ```
102
+
103
+ `pipe(value, f, g, h)` = left-to-right, readable as a data pipeline.
104
+ `compose(h, g, f)(value)` = right-to-left, mathematical composition order.
105
+
106
+ Prefer `pipe` for readability. Use `compose` only when building reusable composed functions.
107
+
108
+ ### 6. Verify Referential Transparency
109
+
110
+ A function has referential transparency if replacing any call with its return value does not change program behavior. Verify by: running twice with identical inputs (results must be deeply equal), checking for hidden mutable closure state, and confirming no dependence on call order.
111
+
112
+ ## Output Format
113
+
114
+ Deliver for each function: type signature, pure implementation, unit tests (happy path + error + boundary), and a `pipe`/`compose` usage example if composable.
115
+
116
+ ## Edge Cases
117
+
118
+ **Async purity:** Async functions that fetch data are not pure, but can be kept referentially transparent by injecting the fetch dependency: `fetchUser(httpClient)(id)`. This keeps business logic pure and testable with a mocked client.
119
+
120
+ **null / undefined inputs:** Always guard at the boundary with a `Result`-returning parser. Never let `null` propagate into pure computation — use `Option<T>` (from `fp-ts` or `effect`) for values that may be absent.
121
+
122
+ **Recursive functions and stack overflow:** For deeply recursive operations, use trampolining or convert to iterative with an explicit stack.
123
+
124
+ **Monetary value precision:** Never use floating-point for money. Store values as integer cents (`amount: number` in whole cents), or use `big.js`/`decimal.js` (JS) or Python's `Decimal` for arbitrary precision. Example: `new Decimal('19.99').times('1.08').toFixed(2)`.
125
+
126
+ **Mixed sync/async pipe composition:** When a pipeline mixes sync and async steps, use `TaskEither` from `fp-ts` to lift sync `Either` values into the async chain, or explicitly `await` intermediate `Result` values before passing to the next pure step:
127
+ ```typescript
128
+ import { pipe } from 'fp-ts/function';
129
+ import * as TE from 'fp-ts/TaskEither';
130
+ const processAsync = (raw: unknown) =>
131
+ pipe(
132
+ TE.fromEither(validateOrder(raw)), // sync Either → TaskEither
133
+ TE.chainW(order => TE.tryCatch(() => fetchPrice(order), toError)),
134
+ TE.map(applyDiscount(0.1)),
135
+ );
136
+ ```
@@ -0,0 +1,144 @@
1
+ ---
2
+ name: inputshield
3
+ description: Implements rigorous input validation, sanitization, and encoding to prevent OWASP Top 10 vulnerabilities including XSS, SQL injection, and command injection. Use when a user needs schema validation with Zod/Joi/Pydantic, parameterized queries, CSP headers, allowlist strategies, or context-specific output encoding.
4
+ ---
5
+
6
+ # InputShield
7
+
8
+ ## Overview
9
+
10
+ Designs and implements a defense-in-depth input validation strategy: schema validation at the boundary (Zod/Joi/Pydantic), parameterized queries for database access, context-specific output encoding for XSS prevention, and HTTP security headers (CSP, CORS). Follows OWASP Top 10 2021 guidelines.
11
+
12
+ ## Workflow
13
+
14
+ ### 1. Identify All Input Surfaces
15
+
16
+ Enumerate every point where untrusted data enters the system:
17
+ - HTTP request body, query params, path params, headers, cookies
18
+ - File uploads (name, MIME type, content)
19
+ - WebSocket messages
20
+ - Environment variables read at runtime
21
+ - Data imported from external APIs or files
22
+
23
+ Mark each surface with its trust level: **untrusted** (external user), **semi-trusted** (internal service), or **trusted** (own DB read).
24
+
25
+ ### 2. Validate at the Boundary — Schema First
26
+
27
+ **TypeScript (Zod):**
28
+ ```typescript
29
+ import { z } from 'zod';
30
+
31
+ const CreateUserSchema = z.object({
32
+ email: z.string().email().max(255).toLowerCase(),
33
+ username: z.string()
34
+ .min(3).max(30)
35
+ .regex(/^[a-zA-Z0-9_-]+$/, 'Only alphanumeric, underscore, hyphen allowed'),
36
+ age: z.number().int().min(13).max(120).optional(),
37
+ role: z.enum(['viewer', 'editor', 'admin']), // allowlist, never freeform
38
+ });
39
+
40
+ type CreateUserInput = z.infer<typeof CreateUserSchema>;
41
+
42
+ // In Express route handler:
43
+ const result = CreateUserSchema.safeParse(req.body);
44
+ if (!result.success) {
45
+ return res.status(400).json({ errors: result.error.flatten() });
46
+ }
47
+ const data: CreateUserInput = result.data; // type-safe from here
48
+ ```
49
+
50
+ **Python (Pydantic v2):**
51
+ ```python
52
+ class CreateUserRequest(BaseModel):
53
+ email: EmailStr
54
+ username: str
55
+ role: Literal['viewer', 'editor', 'admin']
56
+ @field_validator('username')
57
+ @classmethod
58
+ def username_alphanumeric(cls, v: str) -> str:
59
+ if not re.match(r'^[a-zA-Z0-9_-]{3,30}$', v): raise ValueError('Invalid format')
60
+ return v
61
+ ```
62
+
63
+ **Rules:**
64
+ - Always use **allowlists** (define what is permitted) over denylists (block known bad values).
65
+ - Validate **type → format → range → business rule** in that order.
66
+ - Reject on first failure; do not attempt to sanitize malformed input.
67
+
68
+ ### 3. Prevent SQL Injection — Parameterized Queries Only
69
+
70
+ ```typescript
71
+ // VULNERABLE — never do this
72
+ const query = `SELECT * FROM users WHERE email = '${email}'`;
73
+
74
+ // SAFE — parameterized (node-postgres)
75
+ const { rows } = await pool.query(
76
+ 'SELECT id, name FROM users WHERE email = $1 AND active = $2',
77
+ [email, true]
78
+ );
79
+
80
+ // SAFE — ORM (Prisma)
81
+ const user = await prisma.user.findUnique({ where: { email } });
82
+
83
+ // SAFE — raw query with ORM escape (TypeORM)
84
+ await dataSource.query('SELECT * FROM users WHERE email = ?', [email]);
85
+ ```
86
+
87
+ Never interpolate user data into SQL strings, even after regex validation.
88
+
89
+ ### 4. Prevent XSS — Context-Specific Output Encoding
90
+
91
+ Different contexts require different encoding:
92
+
93
+ | Context | Encoding method |
94
+ |---|---|
95
+ | HTML body | `DOMPurify.sanitize(html)` or `escapeHtml(text)` |
96
+ | HTML attribute | `encodeURIComponent()` or template engine auto-escape |
97
+ | JavaScript string | `JSON.stringify()` — never template literal interpolation |
98
+ | CSS value | Allowlist permitted values; reject anything else |
99
+ | URL parameter | `encodeURIComponent()` |
100
+
101
+ Use `DOMPurify.sanitize(html, { ALLOWED_TAGS: ['b','i','em','strong','a'], ALLOWED_ATTR: ['href'] })` only for rich-text rendering. For plain text: use framework auto-escaping (React JSX, Jinja2). Never use `dangerouslySetInnerHTML` / `v-html` with untrusted data.
102
+
103
+ ### 5. Set HTTP Security Headers
104
+
105
+ Use `helmet` (Express) with CSP directives: `defaultSrc: ["'self'"]`, `scriptSrc` with a per-request nonce, `objectSrc: ["'none'"]`, `frameAncestors: ["'none'"]`. Set `referrerPolicy: strict-origin-when-cross-origin`. Always set cookies with `httpOnly; Secure; SameSite=Strict`.
106
+
107
+ ### 6. File Upload Validation
108
+
109
+ Check file signature (magic bytes) via `file-type` library — not just extension or `Content-Type`. Enforce size limits. Store outside web root; serve via signed URLs (S3, GCS):
110
+ ```typescript
111
+ const detected = await fromBuffer(buffer);
112
+ const allowed = ['image/jpeg', 'image/png', 'image/webp'];
113
+ if (!detected || !allowed.includes(detected.mime)) throw new ValidationError('Not permitted');
114
+ if (buffer.length > 5 * 1024 * 1024) throw new ValidationError('Exceeds 5MB');
115
+ ```
116
+
117
+ ## Output Format
118
+
119
+ For each input surface, deliver:
120
+ 1. Schema definition (Zod/Joi/Pydantic) with all constraints documented.
121
+ 2. Integration point (where validation runs in the request lifecycle).
122
+ 3. Error response format (RFC 7807 Problem Details recommended).
123
+ 4. Any headers or encoding additions required.
124
+
125
+ ## Edge Cases
126
+
127
+ **Open redirect via URL inputs:** Validate that redirect URLs are either relative paths or match an explicit allowlist of trusted domains. `new URL(input).hostname` must match `ALLOWED_REDIRECT_HOSTS`.
128
+
129
+ **Unicode normalization attacks:** Input like `SELECT` (fullwidth characters) may bypass keyword denylists. Normalize to NFKC before validation: `input.normalize('NFKC')`.
130
+
131
+ **Mass assignment / over-posting:** Use `z.pick()` or Pydantic's `model_validate(..., strict=True)`. Never spread the entire validated object into an ORM call.
132
+
133
+ **GraphQL-specific validation:** Enforce query depth limiting (reject depth > 7), complexity analysis (assign cost per field, reject above budget), and disable introspection in production. Guard against batch attacks by rate-limiting per operation name and rejecting arrays of operations exceeding a threshold.
134
+ ```typescript
135
+ import depthLimit from 'graphql-depth-limit';
136
+ const schema = makeExecutableSchema({ ... });
137
+ app.use('/graphql', graphqlHTTP({
138
+ validationRules: [depthLimit(7)],
139
+ // disable introspection:
140
+ // fieldResolver: (src, args, ctx, info) => { if (info.fieldName === '__schema') throw new Error('Forbidden'); }
141
+ }));
142
+ ```
143
+
144
+ **SVG upload risk:** SVGs are XML that can contain embedded `<script>` tags and event handlers. Never serve user-uploaded SVGs as `image/svg+xml` without sanitization. Pipe through DOMPurify (server-side via `jsdom`) or `svg-sanitizer`, or convert to PNG/WebP via `sharp` before serving.