@rune-kit/rune 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +357 -0
  3. package/agents/.gitkeep +0 -0
  4. package/agents/architect.md +29 -0
  5. package/agents/asset-creator.md +11 -0
  6. package/agents/audit.md +11 -0
  7. package/agents/autopsy.md +11 -0
  8. package/agents/brainstorm.md +11 -0
  9. package/agents/browser-pilot.md +11 -0
  10. package/agents/coder.md +29 -0
  11. package/agents/completion-gate.md +11 -0
  12. package/agents/constraint-check.md +11 -0
  13. package/agents/context-engine.md +11 -0
  14. package/agents/cook.md +11 -0
  15. package/agents/db.md +11 -0
  16. package/agents/debug.md +11 -0
  17. package/agents/dependency-doctor.md +11 -0
  18. package/agents/deploy.md +11 -0
  19. package/agents/design.md +11 -0
  20. package/agents/docs-seeker.md +11 -0
  21. package/agents/fix.md +11 -0
  22. package/agents/hallucination-guard.md +11 -0
  23. package/agents/incident.md +11 -0
  24. package/agents/integrity-check.md +11 -0
  25. package/agents/journal.md +11 -0
  26. package/agents/launch.md +11 -0
  27. package/agents/logic-guardian.md +11 -0
  28. package/agents/marketing.md +11 -0
  29. package/agents/onboard.md +11 -0
  30. package/agents/perf.md +11 -0
  31. package/agents/plan.md +11 -0
  32. package/agents/preflight.md +11 -0
  33. package/agents/problem-solver.md +11 -0
  34. package/agents/rescue.md +11 -0
  35. package/agents/research.md +11 -0
  36. package/agents/researcher.md +29 -0
  37. package/agents/review-intake.md +11 -0
  38. package/agents/review.md +11 -0
  39. package/agents/reviewer.md +28 -0
  40. package/agents/safeguard.md +11 -0
  41. package/agents/sast.md +11 -0
  42. package/agents/scanner.md +28 -0
  43. package/agents/scope-guard.md +11 -0
  44. package/agents/scout.md +11 -0
  45. package/agents/sentinel.md +11 -0
  46. package/agents/sequential-thinking.md +11 -0
  47. package/agents/session-bridge.md +11 -0
  48. package/agents/skill-forge.md +11 -0
  49. package/agents/skill-router.md +11 -0
  50. package/agents/surgeon.md +11 -0
  51. package/agents/team.md +11 -0
  52. package/agents/test.md +11 -0
  53. package/agents/trend-scout.md +11 -0
  54. package/agents/verification.md +11 -0
  55. package/agents/video-creator.md +11 -0
  56. package/agents/watchdog.md +11 -0
  57. package/agents/worktree.md +11 -0
  58. package/commands/.gitkeep +0 -0
  59. package/commands/rune.md +168 -0
  60. package/compiler/__tests__/openclaw-adapter.test.js +140 -0
  61. package/compiler/__tests__/parser.test.js +55 -0
  62. package/compiler/adapters/antigravity.js +59 -0
  63. package/compiler/adapters/claude.js +37 -0
  64. package/compiler/adapters/cursor.js +67 -0
  65. package/compiler/adapters/generic.js +60 -0
  66. package/compiler/adapters/index.js +45 -0
  67. package/compiler/adapters/openclaw.js +150 -0
  68. package/compiler/adapters/windsurf.js +60 -0
  69. package/compiler/bin/rune.js +288 -0
  70. package/compiler/doctor.js +153 -0
  71. package/compiler/emitter.js +240 -0
  72. package/compiler/parser.js +208 -0
  73. package/compiler/transformer.js +69 -0
  74. package/compiler/transforms/branding.js +27 -0
  75. package/compiler/transforms/cross-references.js +29 -0
  76. package/compiler/transforms/frontmatter.js +38 -0
  77. package/compiler/transforms/hooks.js +68 -0
  78. package/compiler/transforms/subagents.js +36 -0
  79. package/compiler/transforms/tool-names.js +60 -0
  80. package/contexts/dev.md +34 -0
  81. package/contexts/research.md +43 -0
  82. package/contexts/review.md +55 -0
  83. package/extensions/ai-ml/PACK.md +517 -0
  84. package/extensions/analytics/PACK.md +557 -0
  85. package/extensions/backend/PACK.md +678 -0
  86. package/extensions/chrome-ext/PACK.md +995 -0
  87. package/extensions/content/PACK.md +381 -0
  88. package/extensions/devops/PACK.md +520 -0
  89. package/extensions/ecommerce/PACK.md +280 -0
  90. package/extensions/gamedev/PACK.md +393 -0
  91. package/extensions/mobile/PACK.md +273 -0
  92. package/extensions/saas/PACK.md +805 -0
  93. package/extensions/security/PACK.md +536 -0
  94. package/extensions/trading/PACK.md +597 -0
  95. package/extensions/ui/PACK.md +947 -0
  96. package/package.json +47 -0
  97. package/skills/.gitkeep +0 -0
  98. package/skills/adversary/SKILL.md +271 -0
  99. package/skills/asset-creator/SKILL.md +157 -0
  100. package/skills/audit/SKILL.md +466 -0
  101. package/skills/autopsy/SKILL.md +200 -0
  102. package/skills/ba/SKILL.md +279 -0
  103. package/skills/brainstorm/SKILL.md +266 -0
  104. package/skills/browser-pilot/SKILL.md +168 -0
  105. package/skills/completion-gate/SKILL.md +151 -0
  106. package/skills/constraint-check/SKILL.md +165 -0
  107. package/skills/context-engine/SKILL.md +176 -0
  108. package/skills/cook/SKILL.md +636 -0
  109. package/skills/db/SKILL.md +256 -0
  110. package/skills/debug/SKILL.md +240 -0
  111. package/skills/dependency-doctor/SKILL.md +235 -0
  112. package/skills/deploy/SKILL.md +174 -0
  113. package/skills/design/DESIGN-REFERENCE.md +365 -0
  114. package/skills/design/SKILL.md +462 -0
  115. package/skills/doc-processor/SKILL.md +254 -0
  116. package/skills/docs/SKILL.md +336 -0
  117. package/skills/docs-seeker/SKILL.md +166 -0
  118. package/skills/fix/SKILL.md +192 -0
  119. package/skills/git/SKILL.md +285 -0
  120. package/skills/hallucination-guard/SKILL.md +204 -0
  121. package/skills/incident/SKILL.md +241 -0
  122. package/skills/integrity-check/SKILL.md +169 -0
  123. package/skills/journal/SKILL.md +190 -0
  124. package/skills/launch/SKILL.md +330 -0
  125. package/skills/logic-guardian/SKILL.md +240 -0
  126. package/skills/marketing/SKILL.md +229 -0
  127. package/skills/mcp-builder/SKILL.md +311 -0
  128. package/skills/onboard/SKILL.md +298 -0
  129. package/skills/perf/SKILL.md +297 -0
  130. package/skills/plan/SKILL.md +520 -0
  131. package/skills/preflight/SKILL.md +231 -0
  132. package/skills/problem-solver/SKILL.md +284 -0
  133. package/skills/rescue/SKILL.md +434 -0
  134. package/skills/research/SKILL.md +122 -0
  135. package/skills/review/SKILL.md +354 -0
  136. package/skills/review-intake/SKILL.md +222 -0
  137. package/skills/safeguard/SKILL.md +188 -0
  138. package/skills/sast/SKILL.md +190 -0
  139. package/skills/scaffold/SKILL.md +276 -0
  140. package/skills/scope-guard/SKILL.md +150 -0
  141. package/skills/scout/SKILL.md +232 -0
  142. package/skills/sentinel/SKILL.md +320 -0
  143. package/skills/sentinel-env/SKILL.md +226 -0
  144. package/skills/sequential-thinking/SKILL.md +234 -0
  145. package/skills/session-bridge/SKILL.md +287 -0
  146. package/skills/skill-forge/SKILL.md +317 -0
  147. package/skills/skill-router/SKILL.md +267 -0
  148. package/skills/surgeon/SKILL.md +203 -0
  149. package/skills/team/SKILL.md +397 -0
  150. package/skills/test/SKILL.md +271 -0
  151. package/skills/trend-scout/SKILL.md +145 -0
  152. package/skills/verification/SKILL.md +201 -0
  153. package/skills/video-creator/SKILL.md +201 -0
  154. package/skills/watchdog/SKILL.md +166 -0
  155. package/skills/worktree/SKILL.md +140 -0
@@ -0,0 +1,536 @@
1
+ ---
2
+ name: "@rune/security"
3
+ description: Deep security analysis — OWASP audit, penetration testing patterns, secret management, compliance checking, supply chain security, and API hardening.
4
+ metadata:
5
+ author: runedev
6
+ version: "0.2.0"
7
+ layer: L4
8
+ price: "$15"
9
+ target: Security engineers
10
+ tools:
11
+ - Read
12
+ - Grep
13
+ - Bash
14
+ - Edit
15
+ - Write
16
+ ---
17
+
18
+ # @rune/security
19
+
20
+ ## Purpose
21
+
22
+ @rune/security delivers manual-grade security analysis for teams that need more than an automated gate. Where `sentinel` (L2) runs fast checks on every commit, this pack runs thorough, on-demand audits: threat modeling entire auth flows, mapping real attack surfaces, designing vault strategies, auditing supply chain integrity, hardening API surfaces, and producing compliance audit trails. All six skills share the same threat mindset — assume breach, prove safety, document evidence.
23
+
24
+ ## Triggers
25
+
26
+ - `/rune security` — manual invocation, full pack audit
27
+ - `/rune owasp-audit` | `/rune pentest-patterns` | `/rune secret-mgmt` | `/rune compliance` | `/rune supply-chain` | `/rune api-security` — single skill invocation
28
+ - Called by `cook` (L1) when auth, crypto, payment, or PII-handling code is detected
29
+ - Called by `review` (L2) when security-critical patterns are flagged during code review
30
+ - Called by `deploy` (L2) before production releases when security scope is active
31
+
32
+ ## Skills Included
33
+
34
+ ### owasp-audit
35
+
36
+ Deep OWASP Top 10 (2021) + API Security Top 10 (2023) audit — goes beyond sentinel's automated checks with manual code review of authentication flows, session management, access control logic, cryptographic patterns, and CI/CD pipeline security. Produces exploitability-rated findings.
37
+
38
+ #### Workflow
39
+
40
+ **Step 1 — Threat Model**
41
+ Use Read to load entry points (routes, controllers, middleware). Map which OWASP categories apply to this codebase (A01 Broken Access Control, A02 Cryptographic Failures, A03 Injection, A07 Auth Failures, A08 Software and Data Integrity Failures). Build a risk matrix before touching any code. Tag each route with applicable threat categories.
42
+
43
+ **Step 2 — Manual Code Review (OWASP Web Top 10)**
44
+ Use Grep to locate auth middleware, session setup, role checks, and crypto calls. Read each file. Manually verify: Are authorization checks applied consistently? Are sessions invalidated on logout? Are crypto primitives current (no MD5/SHA1 for passwords)? Check deserialization endpoints for A08 — untrusted data deserialized without type constraints is a critical integrity failure.
45
+
46
+ **Step 3 — CI/CD Pipeline Security Check**
47
+ Audit GitHub Actions / GitLab CI / Bitbucket Pipelines yaml files. Check for: expression injection in `run:` steps using untrusted `${{ github.event.* }}` context, env variables printed in logs, third-party actions pinned to mutable tags (use SHA pins), overly broad `permissions:` blocks, secrets exposed via `env:` at workflow level instead of step level.
48
+
49
+ **Step 4 — OWASP API Security Top 10 (2023)**
50
+ Specifically check:
51
+ - **API1:2023 BOLA** — does every object-level endpoint verify the requesting user owns/has permission for that specific resource ID?
52
+ - **API2:2023 Broken Authentication** — are API keys rotatable? Are JWTs validated (signature, expiry, audience claim)?
53
+ - **API5:2023 Broken Function Level Authorization** — are admin/internal API functions gated by role, not just authentication? Can a regular user reach `/admin/*` or `/internal/*` endpoints by guessing paths?
54
+ - **A08:2021 Integrity Failures** — are deserialized payloads schema-validated before use? Are CI/CD pipelines pulling unverified artifacts?
55
+
56
+ **Step 5 — Verify Exploitability and Report**
57
+ For each finding, confirm it is reachable from an unauthenticated or low-privilege context. Rate severity (CRITICAL/HIGH/MEDIUM/LOW). Emit a structured report with file:line references and concrete remediation steps.
58
+
59
+ #### Example
60
+
61
+ ```typescript
62
+ // FINDING: API1:2023 BOLA — missing object-level ownership check
63
+ // File: src/routes/documents.ts, Line: 28
64
+
65
+ // VULNERABLE: fetches document by ID without verifying ownership
66
+ router.get('/documents/:id', requireAuth, async (req, res) => {
67
+ const doc = await db.documents.findById(req.params.id) // any user can fetch any doc
68
+ res.json(doc)
69
+ })
70
+
71
+ // REMEDIATION: filter by both id AND authenticated user
72
+ router.get('/documents/:id', requireAuth, async (req, res) => {
73
+ const doc = await db.documents.findOne({
74
+ id: req.params.id,
75
+ ownerId: req.user.id, // enforces ownership at query level
76
+ })
77
+ if (!doc) return res.status(404).json({ error: 'Not found' })
78
+ res.json(doc)
79
+ })
80
+
81
+ // FINDING: CI/CD injection — GitHub Actions workflow
82
+ // File: .github/workflows/pr-check.yml, Line: 14
83
+ // VULNERABLE: untrusted PR title interpolated directly into run: step
84
+ // run: echo "PR: ${{ github.event.pull_request.title }}"
85
+ // REMEDIATION: assign to env var first — GitHub sanitizes env var expansion
86
+ // env:
87
+ // PR_TITLE: ${{ github.event.pull_request.title }}
88
+ // run: echo "PR: $PR_TITLE"
89
+ ```
90
+
91
+ ---
92
+
93
+ ### pentest-patterns
94
+
95
+ Penetration testing methodology — attack surface mapping, vulnerability identification, proof-of-concept construction, automated fuzzing setup, JWT attack pattern detection, GraphQL hardening, and remediation verification. Outputs actionable PoC code, not just advisories.
96
+
97
+ #### Workflow
98
+
99
+ **Step 1 — Map Attack Surface**
100
+ Use Grep to enumerate all HTTP endpoints, WebSocket handlers, file upload paths, and external-facing inputs. List trust boundaries: what data crosses from client to server without validation? Identify highest-value targets (auth endpoints, admin APIs, payment flows). Note GraphQL endpoints — they require separate analysis.
101
+
102
+ **Step 2 — Identify and Construct PoC**
103
+ For each attack vector, use Read to inspect input handling. Write minimal PoC code (curl command, script, or payload) that demonstrates the vulnerability — SSRF via URL parameter, SQL injection via unsanitized filter, IDOR via predictable ID enumeration. Keep PoCs minimal and clearly scoped to the finding.
104
+
105
+ **Step 3 — JWT Attack Pattern Review**
106
+ Inspect all JWT creation and validation code. Check for:
107
+ - **Algorithm confusion (alg:none)** — does the validator accept `"alg":"none"` tokens?
108
+ - **Key confusion (RS256 → HS256)** — if the public key is accessible, can an attacker sign HS256 tokens with it?
109
+ - **Token replay** — is `jti` (JWT ID) tracked and blacklisted on logout? Is token expiry enforced server-side, not just client-side?
110
+ - **Audience/issuer validation** — are `aud` and `iss` claims verified to prevent cross-service token reuse?
111
+
112
+ **Step 4 — Automated Fuzzing Setup**
113
+ Use property-based testing to fuzz input boundaries. Set up `fast-check` (TypeScript) or `hypothesis` (Python) to generate adversarial inputs for parsers, validators, and business logic. Focus on: integer overflows in numeric fields, Unicode normalization in string comparisons, path traversal in file name parameters, prototype pollution in object merge operations.
114
+
115
+ **Step 5 — GraphQL Security Review**
116
+ If a GraphQL endpoint exists: Is introspection disabled in production? Are deeply nested queries limited (max depth/complexity)? Are batch queries rate-limited independently? Check for field-level authorization — a resolver that returns user data must enforce the same ownership checks as a REST equivalent.
117
+
118
+ **Step 6 — Suggest Remediation and Verify Fix**
119
+ Pair each PoC with a concrete fix. After fix is applied, use Bash to re-run the PoC and confirm it no longer succeeds. Document the before/after in the security report.
120
+
121
+ #### Example
122
+
123
+ ```typescript
124
+ // FINDING: SSRF — user-supplied URL fetched server-side without allowlist
125
+ // File: src/api/webhook.ts, Line: 34
126
+
127
+ // VULNERABLE: attacker can probe internal services
128
+ const response = await fetch(req.body.callbackUrl)
129
+ // POC: curl -X POST /api/webhook -d '{"callbackUrl":"http://169.254.169.254/latest/meta-data/"}'
130
+
131
+ // REMEDIATION: validate against allowlist before fetching
132
+ const ALLOWED_HOSTS = new Set(['api.partner.com', 'hooks.stripe.com'])
133
+ const parsed = new URL(req.body.callbackUrl)
134
+ if (!ALLOWED_HOSTS.has(parsed.hostname)) {
135
+ throw new ForbiddenError('callbackUrl host not in allowlist')
136
+ }
137
+
138
+ // FINDING: JWT algorithm confusion
139
+ // File: src/middleware/auth.ts, Line: 19
140
+ // VULNERABLE: accepts any algorithm the token declares
141
+ import jwt from 'jsonwebtoken'
142
+ const payload = jwt.verify(token, secret) // no algorithm pin
143
+
144
+ // REMEDIATION: pin algorithm explicitly
145
+ const payload = jwt.verify(token, secret, { algorithms: ['HS256'] })
146
+
147
+ // FUZZING SETUP: fast-check for path traversal in file name param
148
+ import * as fc from 'fast-check'
149
+ fc.assert(
150
+ fc.property(fc.string(), (filename) => {
151
+ const result = sanitizeFilename(filename)
152
+ return !result.includes('..') && !result.includes('/')
153
+ })
154
+ )
155
+
156
+ // GRAPHQL: max depth guard (graphql-depth-limit)
157
+ import depthLimit from 'graphql-depth-limit'
158
+ const server = new ApolloServer({
159
+ validationRules: [depthLimit(5)],
160
+ })
161
+ ```
162
+
163
+ ---
164
+
165
+ ### secret-mgmt
166
+
167
+ Secret management patterns — audit current secret handling, design vault or environment strategy, implement rotation policies, detect secrets in pre-commit hooks, and verify zero leaks in logs, errors, and source history.
168
+
169
+ #### Workflow
170
+
171
+ **Step 1 — Scan Current Secret Handling**
172
+ Use Grep to search for hardcoded credentials, API keys, connection strings, and JWT secrets across all source files and config files. Check git history with Bash (`git log -S 'password' --source --all`) to surface secrets ever committed. Catalog every secret by type and location. Check for base64-encoded secrets (`grep -r 'base64' | grep -i 'key\|secret\|pass'`).
173
+
174
+ **Step 2 — Design Vault or Env Strategy**
175
+ Based on project type (serverless, container, bare metal), prescribe a secret backend: AWS Secrets Manager, HashiCorp Vault, Doppler, or `.env` + CI/CD injection. Define which secrets are per-environment vs per-service. Write the access pattern (IAM role, token scope, least privilege).
176
+
177
+ **Step 3 — .env File Safety Audit**
178
+ Verify `.env` and `.env.*` files are in `.gitignore`. Check that a `.env.example` exists with placeholder values (not real secrets). Audit CI/CD environment variable lists — flag any variable that contains `SECRET`, `KEY`, `TOKEN`, or `PASSWORD` that is not masked. Verify `.env.example` is kept in sync with application startup validation schema.
179
+
180
+ **Step 4 — Secret Rotation Automation**
181
+ Document rotation schedule per secret type. For AWS: use Secrets Manager rotation Lambda triggered on schedule. For GitHub Actions: document secret rotation runbook (rotate in provider → update in repo Settings → verify deployment). Add startup validation that fails fast if any required env var is absent or malformed. Set up gitleaks or trufflehog as pre-commit hook to catch accidental commits before they hit remote.
182
+
183
+ **Step 5 — Verify No Leaks in Runtime**
184
+ Use Grep to confirm secrets never appear in log statements, error responses, or exception stack traces. Check error serialization — does the global error handler accidentally serialize `process.env` or full request headers into the response body?
185
+
186
+ #### Example
187
+
188
+ ```typescript
189
+ // PATTERN: startup validation — fail fast on missing secrets
190
+ import { z } from 'zod'
191
+
192
+ const SecretsSchema = z.object({
193
+ DATABASE_URL: z.string().url(),
194
+ JWT_SECRET: z.string().min(32),
195
+ STRIPE_SECRET: z.string().startsWith('sk_'),
196
+ OPENAI_API_KEY: z.string().startsWith('sk-'),
197
+ })
198
+
199
+ export const secrets = SecretsSchema.parse(process.env) // throws at boot if absent/malformed
200
+
201
+ // NEVER log secrets — use masked representation
202
+ logger.info(`DB connected to ${new URL(secrets.DATABASE_URL).hostname}`)
203
+
204
+ // PRE-COMMIT: .gitleaks.toml — scan for secrets before commit
205
+ // [[rules]]
206
+ // id = "generic-api-key"
207
+ // description = "Generic API Key"
208
+ // regex = '''(?i)(api_key|apikey|secret)[^\w]*[=:]\s*['"]?[0-9a-zA-Z\-_]{16,}'''
209
+ // entropy = 3.5
210
+
211
+ // ROTATION LAMBDA: AWS Secrets Manager rotation handler skeleton
212
+ export async function handler(event: SecretsManagerRotationEvent) {
213
+ const { SecretId, ClientRequestToken, Step } = event
214
+ switch (Step) {
215
+ case 'createSecret': await createNewVersion(SecretId, ClientRequestToken); break
216
+ case 'setSecret': await updateDownstreamService(SecretId, ClientRequestToken); break
217
+ case 'testSecret': await validateNewSecret(SecretId, ClientRequestToken); break
218
+ case 'finishSecret': await finalizeRotation(SecretId, ClientRequestToken); break
219
+ }
220
+ }
221
+ ```
222
+
223
+ ---
224
+
225
+ ### compliance
226
+
227
+ Compliance checking — identify applicable standards (SOC 2, GDPR, HIPAA, PCI-DSS v4.0), map requirements to code patterns, perform gap analysis, automate evidence collection, and generate audit-ready evidence packages.
228
+
229
+ #### Workflow
230
+
231
+ **Step 1 — Identify Applicable Standards**
232
+ Read project README, data model, and infrastructure config to determine which standards apply: does the app handle health data (HIPAA), payment card data (PCI-DSS v4.0), EU personal data (GDPR 2016/679), or serve enterprise customers (SOC 2 Type II)? Output a compliance scope document before analysis. Reference standard versions explicitly to prevent stale guidance.
233
+
234
+ **Step 2 — Map Requirements to Code**
235
+ Use Grep to locate data retention logic, consent flows, access logging, encryption at rest/transit, and data deletion endpoints. Cross-reference each requirement against actual implementation. For each gap, record: requirement (with section number), current state, risk level, and remediation effort estimate.
236
+
237
+ **Step 3 — Generate Audit Trail**
238
+ Use Read to verify logging coverage on sensitive operations (login, data export, admin actions, PII access). Confirm logs are tamper-evident, include actor identity and timestamp, and are retained for required duration. Emit a structured compliance report suitable for auditor review.
239
+
240
+ **Step 4 — Automated Evidence Collection**
241
+ For SOC 2 / PCI-DSS audits: automate evidence gathering rather than manual screenshots. Export access logs covering the audit period. Generate a cryptographically signed summary of security controls in place (encryption algorithms, TLS versions, auth mechanisms). For PCI-DSS v4.0 specifically: document Targeted Risk Analysis (TRA) for each customized approach control, verify MFA is enforced on ALL access to the cardholder data environment (not just admin accounts — PCI v4.0 requires it universally), and document compensating controls where requirements cannot be met natively.
242
+
243
+ **Step 5 — Gap Report and Remediation Roadmap**
244
+ For each compliance gap: assign severity (blocker for certification vs. advisory), estimated remediation effort (hours), and owner. Output a prioritized remediation roadmap with estimated time-to-compliance.
245
+
246
+ #### Example
247
+
248
+ ```typescript
249
+ // PATTERN: GDPR-compliant audit trail for PII access
250
+ interface AuditEvent {
251
+ eventId: string // UUID, immutable
252
+ actor: string // userId or serviceAccount
253
+ action: string // 'READ_PII' | 'EXPORT_DATA' | 'DELETE_USER'
254
+ resource: string // 'users/{id}'
255
+ timestamp: string // ISO 8601 UTC
256
+ ip: string // requestor IP for breach tracing
257
+ outcome: 'SUCCESS' | 'DENIED'
258
+ }
259
+
260
+ // Log to append-only store — never DELETE or UPDATE audit rows
261
+ async function logAuditEvent(event: AuditEvent): Promise<void> {
262
+ await db.auditLog.create({ data: event })
263
+ // Also emit to SIEM (Splunk, Datadog) for real-time alerting
264
+ }
265
+
266
+ // PATTERN: PCI-DSS v4.0 — MFA enforcement check at login
267
+ // Verify ALL users (not just admin) are challenged with MFA
268
+ // Gap example: MFA only on /admin routes → FAIL for PCI v4.0 Req 8.4.2
269
+ async function authenticateUser(credentials: LoginDto): Promise<AuthResult> {
270
+ const user = await verifyPassword(credentials)
271
+ // PCI v4.0 Req 8.4.2: MFA required for ALL interactive logins to CDE
272
+ const mfaRequired = isInCDE(user) // must be true for any CDE-touching user
273
+ if (mfaRequired && !credentials.mfaToken) {
274
+ throw new UnauthorizedError('MFA required')
275
+ }
276
+ return issueSession(user)
277
+ }
278
+
279
+ // EVIDENCE COLLECTION: export access log summary for SOC 2 auditor
280
+ // bash: aws cloudtrail lookup-events \
281
+ // --start-time $(date -d '90 days ago' +%s) \
282
+ // --query 'Events[*].{Time:EventTime,User:Username,Action:EventName}' \
283
+ // --output json > soc2-evidence-access-log.json
284
+ ```
285
+
286
+ ---
287
+
288
+ ### supply-chain
289
+
290
+ Supply chain security analysis — detect dependency confusion attacks, typosquatting, lockfile injection, manifest confusion, and verify SLSA provenance attestations. Generates a complete supply chain risk report.
291
+
292
+ #### Workflow
293
+
294
+ **Step 1 — Inventory Dependencies**
295
+ Use Read on `package.json` / `requirements.txt` / `go.mod` / `Cargo.toml`. Build a complete dependency graph including devDependencies and indirect (transitive) dependencies via `npm ls --all --json` or `pip-audit --format json`. Flag phantom dependencies — packages used in source code (via import) but not declared in the manifest.
296
+
297
+ **Step 2 — Check Naming Collisions (Dependency Confusion)**
298
+ For any private/internal package names (scoped like `@company/internal-lib` OR unscoped names that look internal), verify they also exist on the public registry (npm, PyPI, RubyGems). If a package name is registered internally but NOT on the public registry, an attacker can register it there — package managers may prefer the public version depending on configuration. Flag all such packages for private registry enforcement.
299
+
300
+ **Step 3 — Typosquatting Detection**
301
+ Compare each dependency name against a known-popular packages list. Flag names with edit distance ≤ 2 from a popular package: `lodas` (lodash), `requets` (requests), `coloers` (colors), `expres` (express). Also flag: packages with unusual character substitution (zero vs letter o, l vs 1), recently published packages with very high download counts but no GitHub stars, and packages with install scripts that execute shell commands.
302
+
303
+ **Step 4 — Verify Lockfile Integrity**
304
+ Check that `package-lock.json` / `yarn.lock` / `pnpm-lock.yaml` exists and is committed. Verify resolved hashes match between manifest and lockfile. Detect lockfile injection: compare resolved URLs — any `file:`, `git+`, or non-registry URL in the lockfile for a package expected to come from the registry is a red flag. Run `npm audit signatures` (npm ≥ 9.5) to verify package signatures against the registry's public key.
305
+
306
+ **Step 5 — Audit Transitive Dependencies and Known Malicious Packages**
307
+ Run `npm audit --all` / `pip-audit` / `cargo audit`. Cross-reference against OSV (Open Source Vulnerabilities) database. Check install scripts: `cat node_modules/<pkg>/package.json | jq '.scripts.install,.scripts.postinstall'` — any install script running `curl | sh` or spawning child processes is HIGH severity.
308
+
309
+ **Step 6 — SLSA Provenance and Report**
310
+ For critical dependencies, check if SLSA provenance attestations are available (`npm install @sigstore/bundle` / cosign verify-attestation). Emit `.rune/security/supply-chain-report.md` with: dependency inventory, collision risks, typosquatting flags, lockfile anomalies, install script warnings, and remediation steps.
311
+
312
+ #### Example
313
+
314
+ ```bash
315
+ # STEP 1: Full dependency inventory with phantom dep check
316
+ npm ls --all --json 2>/dev/null | jq '[.. | objects | select(.version) | {name: .name, version: .version}]' > deps-inventory.json
317
+
318
+ # STEP 2: Check if internal package exists on public registry
319
+ # VULNERABLE: @company/utils exists internally but NOT on npm → dependency confusion risk
320
+ curl -s https://registry.npmjs.org/@company/utils | jq '.error'
321
+ # If returns null (package exists publicly) → verify it's YOUR package, not an attacker's
322
+
323
+ # STEP 3: Detect install scripts in dependencies
324
+ for pkg in node_modules/*/package.json; do
325
+ scripts=$(jq -r '(.scripts.install // "") + " " + (.scripts.postinstall // "")' "$pkg")
326
+ if echo "$scripts" | grep -qE 'curl|wget|exec|spawn|child_process'; then
327
+ echo "WARN: install script in $pkg: $scripts"
328
+ fi
329
+ done
330
+
331
+ # STEP 4: Verify lockfile integrity (npm ≥ 9.5)
332
+ npm audit signatures
333
+ # Expected: "audited X packages, 0 packages have invalid signatures"
334
+ ```
335
+
336
+ ```typescript
337
+ // PATTERN: enforce private registry for scoped packages (.npmrc)
338
+ // @company:registry=https://npm.company.internal
339
+ // //npm.company.internal/:_authToken=${NPM_INTERNAL_TOKEN}
340
+
341
+ // PATTERN: detect phantom dependencies in TypeScript
342
+ // Any import from a package not in dependencies/devDependencies = phantom dep
343
+ // Tool: depcheck → npx depcheck --json | jq '.missing'
344
+ ```
345
+
346
+ ---
347
+
348
+ ### api-security
349
+
350
+ API hardening patterns — rate limiting strategies, input sanitization beyond schema validation, CORS configuration, Content Security Policy generation, and security headers middleware. Outputs ready-to-use middleware code for Express, Fastify, and Next.js.
351
+
352
+ #### Workflow
353
+
354
+ **Step 1 — Enumerate API Endpoints**
355
+ Use Grep to list all route definitions across the codebase. Categorize by: public (unauthenticated), authenticated, admin, and internal (service-to-service). For each endpoint, note: whether it accepts user-controlled input, whether it has rate limiting applied, and whether it can trigger expensive operations (DB writes, external API calls, file I/O).
356
+
357
+ **Step 2 — Audit Rate Limiting**
358
+ Check if rate limiting is applied per-endpoint or only globally. Global rate limits are bypassable — an attacker can flood a single expensive endpoint within the global budget. Verify rate limits are enforced at the infrastructure level (not just in-process) so they survive server restarts and work across horizontally scaled instances. Recommend: Redis-backed sliding window for authenticated endpoints, token bucket for public endpoints. Set tighter limits on auth endpoints (login, password reset, OTP verify) to prevent brute force.
359
+
360
+ **Step 3 — Audit Input Validation**
361
+ Schema validation (Zod, Joi) is necessary but not sufficient. Additionally check:
362
+ - **HTML inputs** — is DOMPurify or equivalent used before any user content is rendered as HTML?
363
+ - **File uploads** — is MIME type validated from magic bytes (not just the `Content-Type` header)? Is file size capped before reading into memory?
364
+ - **Path parameters** — could `req.params.filename` be `../../etc/passwd`? Normalize with `path.resolve` and verify it stays within the allowed base directory.
365
+ - **Numeric IDs** — are they validated as integers to prevent NoSQL/ORM injection via object payloads?
366
+
367
+ **Step 4 — Verify CORS Configuration**
368
+ Check that `Access-Control-Allow-Origin` is not `*` for authenticated endpoints. Verify origins are defined per-environment (development allows localhost, production allows only the production domain). Check credentials handling — `credentials: true` must never be paired with `origin: '*'`. Verify preflight caching (`Access-Control-Max-Age`) is set to reduce OPTIONS request overhead without being too long.
369
+
370
+ **Step 5 — Generate CSP Policy**
371
+ Build a Content Security Policy tailored to the application's actual resource origins. Use `script-src 'nonce-{random}'` for inline scripts rather than `'unsafe-inline'`. Generate nonces server-side per request. Define `connect-src` to only allow the actual API and WebSocket origins. Add `upgrade-insecure-requests` for HTTPS-only deployments.
372
+
373
+ **Step 6 — Emit Security Headers Middleware**
374
+ Produce a complete security headers middleware file. Include: HSTS with preload, X-Content-Type-Options, X-Frame-Options, Referrer-Policy (strict-origin-when-cross-origin), and Permissions-Policy to restrict camera/mic/geolocation access. Output the middleware as a ready-to-paste file for the detected framework.
375
+
376
+ #### Example
377
+
378
+ ```typescript
379
+ // EXPRESS: complete security headers middleware
380
+ // File to create: src/middleware/security-headers.ts
381
+
382
+ import { Request, Response, NextFunction } from 'express'
383
+ import crypto from 'crypto'
384
+
385
+ export function securityHeaders(req: Request, res: Response, next: NextFunction) {
386
+ const nonce = crypto.randomBytes(16).toString('base64')
387
+ res.locals.cspNonce = nonce
388
+
389
+ res.setHeader('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload')
390
+ res.setHeader('X-Content-Type-Options', 'nosniff')
391
+ res.setHeader('X-Frame-Options', 'DENY')
392
+ res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin')
393
+ res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()')
394
+ res.setHeader(
395
+ 'Content-Security-Policy',
396
+ [
397
+ `script-src 'nonce-${nonce}' 'strict-dynamic'`,
398
+ "style-src 'self' https://fonts.googleapis.com",
399
+ "font-src 'self' https://fonts.gstatic.com",
400
+ "connect-src 'self' wss://api.yourdomain.com",
401
+ "img-src 'self' data: https:",
402
+ "frame-ancestors 'none'",
403
+ 'upgrade-insecure-requests',
404
+ ].join('; ')
405
+ )
406
+ next()
407
+ }
408
+
409
+ // RATE LIMITING: Redis-backed sliding window (express-rate-limit + ioredis)
410
+ import rateLimit from 'express-rate-limit'
411
+ import RedisStore from 'rate-limit-redis'
412
+ import Redis from 'ioredis'
413
+
414
+ const redis = new Redis(process.env.REDIS_URL)
415
+
416
+ // Tight limit on auth endpoints — brute force prevention
417
+ export const authRateLimit = rateLimit({
418
+ windowMs: 15 * 60 * 1000, // 15 minutes
419
+ max: 10, // 10 attempts per window
420
+ standardHeaders: 'draft-7',
421
+ legacyHeaders: false,
422
+ store: new RedisStore({ sendCommand: (...args) => redis.call(...args) }),
423
+ message: { error: 'Too many attempts, please try again later' },
424
+ })
425
+
426
+ // General API limit — per-user sliding window
427
+ export const apiRateLimit = rateLimit({
428
+ windowMs: 60 * 1000, // 1 minute
429
+ max: 100, // 100 req/min per IP
430
+ keyGenerator: (req) => req.user?.id ?? req.ip, // per-user when authenticated
431
+ store: new RedisStore({ sendCommand: (...args) => redis.call(...args) }),
432
+ })
433
+
434
+ // INPUT: path traversal prevention for file name parameters
435
+ import path from 'path'
436
+
437
+ function safeFilePath(baseDir: string, userFilename: string): string {
438
+ const normalized = path.resolve(baseDir, userFilename)
439
+ if (!normalized.startsWith(path.resolve(baseDir))) {
440
+ throw new ForbiddenError('Path traversal attempt detected')
441
+ }
442
+ return normalized
443
+ }
444
+
445
+ // CORS: environment-aware origin allowlist
446
+ const CORS_ORIGINS: Record<string, string[]> = {
447
+ production: ['https://app.yourdomain.com'],
448
+ staging: ['https://staging.yourdomain.com'],
449
+ development: ['http://localhost:3000', 'http://localhost:5173'],
450
+ }
451
+
452
+ export const corsOptions = {
453
+ origin: (origin: string | undefined, cb: Function) => {
454
+ const allowed = CORS_ORIGINS[process.env.NODE_ENV ?? 'development']
455
+ if (!origin || allowed.includes(origin)) return cb(null, true)
456
+ cb(new Error('Not allowed by CORS'))
457
+ },
458
+ credentials: true,
459
+ maxAge: 600, // cache preflight for 10 minutes
460
+ }
461
+ ```
462
+
463
+ ```typescript
464
+ // NEXT.JS: security headers in next.config.ts
465
+ const securityHeaders = [
466
+ { key: 'X-DNS-Prefetch-Control', value: 'on' },
467
+ { key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
468
+ { key: 'X-Frame-Options', value: 'DENY' },
469
+ { key: 'X-Content-Type-Options', value: 'nosniff' },
470
+ { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
471
+ { key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=()' },
472
+ ]
473
+
474
+ export default {
475
+ async headers() {
476
+ return [{ source: '/(.*)', headers: securityHeaders }]
477
+ },
478
+ }
479
+ ```
480
+
481
+ ---
482
+
483
+ ## Connections
484
+
485
+ ```
486
+ Calls → scout (L2): scan codebase for security patterns before audit
487
+ Calls → verification (L3): run security tooling (Semgrep, Trivy, npm audit, gitleaks)
488
+ Called By ← review (L2): when security-critical code detected during review
489
+ Called By ← cook (L1): when auth/input/payment/PII code is in scope
490
+ Called By ← deploy (L2): pre-release security gate when security scope active
491
+ ```
492
+
493
+ ## Constraints
494
+
495
+ 1. MUST use opus model for auth, crypto, and payment code review — these domains require maximum reasoning depth.
496
+ 2. MUST NOT rely solely on automated tool output — every finding requires manual confirmation of exploitability before reporting.
497
+ 3. MUST produce actionable findings: each issue includes file:line reference, severity rating, and concrete remediation steps.
498
+ 4. MUST differentiate scope from sentinel — @rune/security does deep on-demand analysis; sentinel does fast automated gates on every commit. Never duplicate sentinel's job.
499
+ 5. MUST generate defensive examples only — no offensive exploit code beyond minimal PoC sufficient to confirm exploitability.
500
+
501
+ ## Sharp Edges
502
+
503
+ | Failure Mode | Severity | Mitigation |
504
+ |---|---|---|
505
+ | Reporting false positives as confirmed vulnerabilities | HIGH | Always verify exploitability manually before including in final report |
506
+ | Auditing only code, missing infra/config attack surface | HIGH | Include Dockerfile, CI/CD yaml, nginx/CDN config, and .npmrc in scope |
507
+ | Secret scan misses base64-encoded or env-injected secrets | HIGH | Scan both raw and decoded forms; check CI/CD variable lists |
508
+ | Compliance gap analysis based on outdated standard version | MEDIUM | Reference standard version explicitly (e.g., GDPR 2016/679, PCI-DSS v4.0) |
509
+ | OWASP audit skips indirect dependencies (transitive vulns) | MEDIUM | Run `npm audit --all` or `pip-audit` to surface transitive CVEs |
510
+ | Pentest PoC accidentally run against production | CRITICAL | Confirm target environment before executing any PoC — add env guard to scripts |
511
+ | Supply chain: only checking direct deps, missing transitive | HIGH | Use `npm ls --all` or `pip-audit` — transitive deps are equally exploitable |
512
+ | Rate limits enforced in-process only (bypassed at scale) | HIGH | Use Redis-backed store; in-process limits don't survive horizontal scaling |
513
+ | CSP nonce reuse across requests | CRITICAL | Generate a new `crypto.randomBytes(16)` nonce per request, never cache |
514
+ | BOLA check missed on bulk/list endpoints | HIGH | List endpoints that return multiple objects must also filter by authenticated user's scope |
515
+
516
+ ## Difference from sentinel
517
+
518
+ `sentinel` = lightweight automated gate (every commit, fast, cheap, blocks bad merges)
519
+ `@rune/security` = deep manual-grade audit (on-demand, thorough, expensive, produces audit-ready reports)
520
+
521
+ sentinel catches: known CVEs in deps, hardcoded secrets, obvious injection patterns.
522
+ @rune/security catches: logic flaws in auth flows, missing authorization on specific routes, supply chain confusion attacks, API rate limiting gaps, compliance gaps, attack chains spanning multiple services.
523
+
524
+ ## Done When
525
+
526
+ - All OWASP Top 10 (2021) + API Security Top 10 (2023) categories explicitly assessed (confirmed safe or finding raised)
527
+ - Every HIGH/CRITICAL finding has a PoC or reproduction steps confirming exploitability
528
+ - Secret audit covers source history, not just current HEAD; pre-commit hook configured
529
+ - Supply chain report emitted to `.rune/security/supply-chain-report.md` with all collision/typosquatting risks
530
+ - Security headers middleware generated and wired into the application
531
+ - Compliance report maps each applicable standard requirement to a code location or gap, with remediation roadmap
532
+ - Structured security report emitted with severity ratings and remediation steps
533
+
534
+ ## Cost Profile
535
+
536
+ ~10,000–28,000 tokens per full pack audit depending on codebase size and number of skills invoked. opus default for auth/crypto/payment/compliance review — these require maximum reasoning depth. haiku for initial pattern scanning (scout phase) and dependency inventory. sonnet for supply-chain analysis and API hardening code generation. Expect 5–10 minutes elapsed for a mid-size application running the full pack.