Skip to content

Commit b3e3f9f

Browse files
laywillclaude
andauthored
Security: Add safeguards to MEDIUM agents - Batch M5/M6 (Dev Experience, Specialized, Business, Meta-Orchestration) (#292)
* Security: Add safeguards to MEDIUM agents - Batch M5/M6 (Dev Experience, Specialized Domains, Business, Meta-Orchestration) Adds ## Security Safeguards sections (Input Validation + Rollback Procedures) to 29 remaining MEDIUM-risk agent files across 4 categories, then applies token-efficiency optimization (30-50% reduction) to each file. Categories covered: - 06-developer-experience (13 agents, issues #67-79) - 07-specialized-domains (7 agents, issues #80-86) - 08-business-product (1 agent, issue #95) - 09-meta-orchestration (8 agents, issues #87-94) Security approach: - Input Validation: domain-specific prose rules (no code blocks) - Rollback Procedures: operational CLI commands for each domain - No audit logging (handled by Claude Code Hooks at platform level) - No approval gates (MEDIUM risk level) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Security: Replace code blocks in Rollback Procedures with prose (M5/M6 agents) Revise the Rollback Procedures section across all 29 MEDIUM-risk agents (Categories 06-09) to follow the style established in fullstack-developer.md. Changes per file: - Remove all bash/powershell code blocks from Rollback Procedures - Replace with structured prose: Scope Constraints, Rollback Decision Framework, Validation Requirements, and 5-Minute Constraint - Tailor each section to the agent's specific domain Agents use guidelines rather than embedded implementation code — the agent knows how to code at runtime and needs guidance, not scripts. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Remove superfluous code snippets from agents --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 62270f9 commit b3e3f9f

33 files changed

Lines changed: 2246 additions & 6181 deletions

categories/01-core-development/electron-pro.md

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -96,22 +96,7 @@ Before executing any desktop application operations, validate all inputs to prev
9696

9797
**IPC Channel Validation**: Validate channel names `^[a-zA-Z0-9:_-]{1,64}$`, sanitize file paths `^[a-zA-Z0-9/_.-]{1,255}$` (no traversal), validate URLs `^(https?|file)://[a-zA-Z0-9.-]+` (no `file://` for remote), check protocol handlers `^[a-z][a-z0-9+.-]*://` (must be registered).
9898

99-
**Preload Script Input Sanitization**
100-
```javascript
101-
const { contextBridge, ipcRenderer } = require('electron');
102-
const ALLOWED_CHANNELS = {
103-
send: ['save-file', 'open-dialog', 'app-quit', 'update-check'],
104-
receive: ['file-saved', 'dialog-result', 'update-available']
105-
};
106-
contextBridge.exposeInMainWorld('electron', {
107-
send: (channel, data) => {
108-
if (!ALLOWED_CHANNELS.send.includes(channel)) throw new Error(`Invalid IPC channel: ${channel}`);
109-
if (typeof data !== 'object' || data === null) throw new Error('IPC data must be a plain object');
110-
if (data.filePath && !/^[a-zA-Z0-9/_.-]{1,255}$/.test(data.filePath)) throw new Error('Invalid file path format');
111-
ipcRenderer.send(channel, data);
112-
}
113-
});
114-
```
99+
**Preload Script Input Sanitization**: Validate all IPC channel names and data against strict allowlists. Maintain a whitelist of permitted send/receive channels (alphanumeric, colons, underscores, hyphens only). Reject unknown channels immediately. Validate all IPC data payloads: reject non-object data, validate filePaths against traversal patterns (no `../` or absolute paths to sensitive directories), validate URLs against protocol allowlist (no `file://` for remote operations). Only expose necessary APIs through `contextBridge` — never expose `ipcRenderer` directly or allow arbitrary function invocation.
115100

116101
**Configuration Validation**: Verify `contextIsolation: true` and `nodeIntegration: false` in all BrowserWindow configs, check CSP headers include `default-src 'self'`, validate code signing certs, verify update server URLs against allowlist.
117102

categories/01-core-development/graphql-architect.md

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -107,23 +107,7 @@ All GraphQL schema changes, resolver implementations, and federation configurati
107107
- Ensure query complexity limits are defined (default max depth: 10, max complexity: 1000)
108108
- Validate subscription event names match `/^[A-Z_]+$/` pattern
109109

110-
**Resolver Input Validation** (illustrates expected rigor):
111-
```typescript
112-
function validateResolverInput(args: any, schema: GraphQLFieldConfig) {
113-
const errors: string[] = [];
114-
// Check required args, input depth (<5 for DoS prevention),
115-
// sanitize strings, calculate query complexity (<1000 threshold)
116-
Object.keys(schema.args || {}).forEach(argName => {
117-
const arg = schema.args![argName];
118-
if (arg.type instanceof GraphQLNonNull && !(argName in args)) {
119-
errors.push(`Missing required argument: ${argName}`);
120-
}
121-
});
122-
if (args.input && getObjectDepth(args.input) > 5)
123-
errors.push(`Input depth exceeds 5`);
124-
if (errors.length > 0) throw new Error(`Validation failed: ${errors.join(', ')}`);
125-
}
126-
```
110+
**Resolver Input Validation**: Validate all resolver arguments against their declared GraphQL types. Verify required arguments are present (reject non-null violations). Limit input object nesting depth to prevent DoS attacks (enforce max depth of 5 for deeply nested inputs). Sanitize string inputs to prevent injection (escape special characters, validate format constraints). Calculate cumulative query complexity during execution and reject queries exceeding thresholds (max 1000 total complexity). Validate list sizes and pagination limits (reject page sizes >1000, offset >1000000). For custom scalars, validate format and range constraints before processing.
127111

128112
**Federation Composition Validation**: Validate subgraph schemas individually, run `rover subgraph check` for breaking changes, verify gateway composition succeeds, test reference resolvers return valid entity representations.
129113

categories/02-language-specialists/elixir-expert.md

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -101,30 +101,6 @@ Validate all inputs before executing Mix tasks, database ops, or process spawnin
101101

102102
Validation targets: **Mix task arguments** (validate env names match `^(dev|test|staging|prod)$`, reject shell metacharacters), **Database inputs** (Ecto changesets for all user data, parameterized queries only, validate foreign keys exist), **Process spawning** (validate module/function atoms exist before `GenServer.start_link/3`, sanitize dynamic supervisor child specs), **Phoenix routes** (validate path params, sanitize query strings, check content-type headers), **External commands** (if using `System.cmd/3`, validate against allowlist, escape all args), **Configuration** (validate runtime config values, check env vars exist before use), **File paths** (resolve with `Path.expand/1`, reject traversal sequences `../`, validate write permissions).
103103

104-
Example validation:
105-
```elixir
106-
defmodule MyApp.Validators do
107-
@valid_envs ~w(dev test staging prod)
108-
@safe_path_pattern ~r/^[a-zA-Z0-9_\-\/\.]+$/
109-
110-
def validate_environment!(env) when env in @valid_envs, do: :ok
111-
def validate_environment!(env), do: raise ArgumentError, "Invalid environment: #{env}"
112-
113-
def validate_file_path!(path) do
114-
expanded = Path.expand(path)
115-
if String.match?(expanded, @safe_path_pattern) and not String.contains?(path, "..") do
116-
:ok
117-
else
118-
raise ArgumentError, "Invalid file path: #{path}"
119-
end
120-
end
121-
122-
def sanitize_genserver_name(name) when is_atom(name) do
123-
if Code.ensure_loaded?(name), do: name, else: raise ArgumentError, "Module not loaded"
124-
end
125-
end
126-
```
127-
128104
Pre-execution checklist: All user inputs validated through Ecto changesets, Mix task args sanitized, GenServer/Supervisor specs validated before `start_link`, file paths resolved and checked, Phoenix params validated with strong params pattern, external command args escaped, runtime config validated at startup.
129105

130106
### Rollback Procedures

categories/02-language-specialists/javascript-pro.md

Lines changed: 6 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -102,51 +102,13 @@ Security practices: XSS prevention, CSRF protection, Content Security Policy, se
102102
All user inputs, file paths, and external data MUST be validated before processing to prevent code injection, path traversal, and malicious script execution.
103103

104104
**Required Validations**:
105-
- **File paths**: Must be within project directory, no `..` sequences
106-
```javascript
107-
function validateFilePath(userPath, projectRoot) {
108-
const resolved = path.resolve(projectRoot, userPath);
109-
if (!resolved.startsWith(projectRoot)) throw new Error(`Invalid path: ${userPath}`);
110-
return resolved;
111-
}
112-
```
113-
114-
- **Package names**: Match npm naming rules `^(@[a-z0-9-~][a-z0-9-._~]*/)?[a-z0-9-~][a-z0-9-._~]*$`
115-
```javascript
116-
function validatePackageName(name) {
117-
const npmPattern = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
118-
if (!npmPattern.test(name)) throw new Error(`Invalid package name: ${name}`);
119-
const blocklist = ['malicious-pkg', 'evil-lib'];
120-
if (blocklist.includes(name)) throw new Error(`Blocked package: ${name}`);
121-
return name;
122-
}
123-
```
124-
125-
- **Script content**: Scan for dangerous patterns
126-
```javascript
127-
function validateScriptContent(code) {
128-
const dangerousPatterns = [
129-
/require\s*\(\s*['"]child_process['"]\s*\)/,
130-
/eval\s*\(/,
131-
/Function\s*\(/,
132-
/process\.exit/,
133-
/fs\.unlinkSync/,
134-
/rm\s+-rf/
135-
];
136-
for (const pattern of dangerousPatterns) {
137-
if (pattern.test(code)) throw new Error(`Dangerous pattern: ${pattern}`);
138-
}
139-
return code;
140-
}
141-
```
105+
- **File paths**: Resolve against project root with `path.resolve()` and verify the result starts with the project root directory to prevent directory traversal attacks. Reject paths containing `..` sequences or absolute paths outside the project scope.
142106

143-
- **User-provided HTML/DOM**: Sanitize to prevent XSS
144-
```javascript
145-
function sanitizeHTML(dirty) {
146-
const map = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', "/": '&#x2F;'};
147-
return dirty.replace(/[&<>"'/]/g, (char) => map[char]);
148-
}
149-
```
107+
- **Package names**: Validate against npm naming rules (`^(@[a-z0-9-~][a-z0-9-._~]*/)?[a-z0-9-~][a-z0-9-._~]*$`). Maintain and check against a package blocklist for known malicious or problematic packages before installation or import.
108+
109+
- **Script content**: Scan uploaded or user-provided JavaScript code for dangerous patterns before execution or storage: `require()` calls to privileged modules (`child_process`, `fs`, `os`), `eval()`, `Function()` constructors, `process.exit` calls, filesystem operations (`fs.unlinkSync`, `fs.rmSync`), and shell command patterns. Reject code containing these patterns.
110+
111+
- **User-provided HTML/DOM**: Sanitize all user-generated content before inserting into the DOM to prevent XSS attacks. HTML-encode special characters (`&`, `<`, `>`, `"`, `'`, `/`) and use text nodes instead of `innerHTML` when possible. For rich content, use a dedicated HTML sanitization library (DOMPurify, sanitize-html) with safe allowlist configuration.
150112

151113
### Rollback Procedures
152114

0 commit comments

Comments
 (0)