@rune-kit/rune 2.1.1 → 2.2.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 (157) hide show
  1. package/README.md +40 -34
  2. package/compiler/__tests__/pack-split.test.js +145 -0
  3. package/compiler/adapters/antigravity.js +1 -1
  4. package/compiler/adapters/codex.js +77 -0
  5. package/compiler/adapters/cursor.js +1 -1
  6. package/compiler/adapters/generic.js +1 -1
  7. package/compiler/adapters/index.js +4 -0
  8. package/compiler/adapters/opencode.js +86 -0
  9. package/compiler/adapters/windsurf.js +1 -1
  10. package/compiler/bin/rune.js +10 -7
  11. package/compiler/doctor.js +42 -0
  12. package/compiler/emitter.js +64 -10
  13. package/compiler/parser.js +42 -3
  14. package/compiler/transformer.js +10 -6
  15. package/compiler/transforms/branding.js +1 -1
  16. package/compiler/transforms/compliance.js +40 -0
  17. package/extensions/ai-ml/PACK.md +38 -474
  18. package/extensions/ai-ml/skills/ai-agents.md +172 -0
  19. package/extensions/ai-ml/skills/code-sandbox.md +187 -0
  20. package/extensions/ai-ml/skills/deep-research.md +146 -0
  21. package/extensions/ai-ml/skills/embedding-search.md +66 -0
  22. package/extensions/ai-ml/skills/fine-tuning-guide.md +74 -0
  23. package/extensions/ai-ml/skills/llm-architect.md +125 -0
  24. package/extensions/ai-ml/skills/llm-integration.md +64 -0
  25. package/extensions/ai-ml/skills/prompt-patterns.md +72 -0
  26. package/extensions/ai-ml/skills/rag-patterns.md +66 -0
  27. package/extensions/ai-ml/skills/web-extraction.md +114 -0
  28. package/extensions/analytics/PACK.md +19 -484
  29. package/extensions/analytics/skills/ab-testing.md +72 -0
  30. package/extensions/analytics/skills/dashboard-patterns.md +83 -0
  31. package/extensions/analytics/skills/data-validation.md +68 -0
  32. package/extensions/analytics/skills/funnel-analysis.md +81 -0
  33. package/extensions/analytics/skills/sql-patterns.md +57 -0
  34. package/extensions/analytics/skills/statistical-analysis.md +79 -0
  35. package/extensions/analytics/skills/tracking-setup.md +71 -0
  36. package/extensions/backend/PACK.md +44 -618
  37. package/extensions/backend/skills/api-patterns.md +84 -0
  38. package/extensions/backend/skills/async-pipeline.md +193 -0
  39. package/extensions/backend/skills/auth-patterns.md +97 -0
  40. package/extensions/backend/skills/background-jobs.md +133 -0
  41. package/extensions/backend/skills/caching-patterns.md +108 -0
  42. package/extensions/backend/skills/cli-generation.md +133 -0
  43. package/extensions/backend/skills/database-patterns.md +87 -0
  44. package/extensions/backend/skills/middleware-patterns.md +104 -0
  45. package/extensions/chrome-ext/PACK.md +19 -921
  46. package/extensions/chrome-ext/skills/cws-preflight.md +143 -0
  47. package/extensions/chrome-ext/skills/cws-publish.md +104 -0
  48. package/extensions/chrome-ext/skills/ext-ai-integration.md +251 -0
  49. package/extensions/chrome-ext/skills/ext-messaging.md +139 -0
  50. package/extensions/chrome-ext/skills/ext-storage.md +133 -0
  51. package/extensions/chrome-ext/skills/mv3-scaffold.md +164 -0
  52. package/extensions/content/PACK.md +43 -335
  53. package/extensions/content/skills/blog-patterns.md +88 -0
  54. package/extensions/content/skills/cms-integration.md +131 -0
  55. package/extensions/content/skills/content-scoring.md +107 -0
  56. package/extensions/content/skills/i18n.md +83 -0
  57. package/extensions/content/skills/mdx-authoring.md +137 -0
  58. package/extensions/content/skills/reference.md +1014 -0
  59. package/extensions/content/skills/seo-patterns.md +67 -0
  60. package/extensions/content/skills/video-repurpose.md +153 -0
  61. package/extensions/devops/PACK.md +38 -457
  62. package/extensions/devops/skills/chaos-testing.md +67 -0
  63. package/extensions/devops/skills/ci-cd.md +75 -0
  64. package/extensions/devops/skills/docker.md +58 -0
  65. package/extensions/devops/skills/edge-serverless.md +163 -0
  66. package/extensions/devops/skills/infra-as-code.md +158 -0
  67. package/extensions/devops/skills/kubernetes.md +110 -0
  68. package/extensions/devops/skills/monitoring.md +57 -0
  69. package/extensions/devops/skills/server-setup.md +64 -0
  70. package/extensions/devops/skills/ssl-domain.md +42 -0
  71. package/extensions/ecommerce/PACK.md +62 -226
  72. package/extensions/ecommerce/skills/cart-system.md +79 -0
  73. package/extensions/ecommerce/skills/inventory-mgmt.md +102 -0
  74. package/extensions/ecommerce/skills/order-management.md +126 -0
  75. package/extensions/ecommerce/skills/payment-integration.md +472 -0
  76. package/extensions/ecommerce/skills/shopify-dev.md +69 -0
  77. package/extensions/ecommerce/skills/subscription-billing.md +93 -0
  78. package/extensions/ecommerce/skills/tax-compliance.md +117 -0
  79. package/extensions/gamedev/PACK.md +66 -317
  80. package/extensions/gamedev/skills/asset-pipeline.md +74 -0
  81. package/extensions/gamedev/skills/audio-system.md +129 -0
  82. package/extensions/gamedev/skills/camera-system.md +87 -0
  83. package/extensions/gamedev/skills/ecs.md +98 -0
  84. package/extensions/gamedev/skills/game-loops.md +72 -0
  85. package/extensions/gamedev/skills/input-system.md +199 -0
  86. package/extensions/gamedev/skills/multiplayer.md +180 -0
  87. package/extensions/gamedev/skills/particles.md +105 -0
  88. package/extensions/gamedev/skills/physics-engine.md +89 -0
  89. package/extensions/gamedev/skills/scene-management.md +146 -0
  90. package/extensions/gamedev/skills/threejs-patterns.md +90 -0
  91. package/extensions/gamedev/skills/webgl.md +71 -0
  92. package/extensions/mobile/PACK.md +56 -223
  93. package/extensions/mobile/skills/app-store-connect.md +152 -0
  94. package/extensions/mobile/skills/app-store-prep.md +66 -0
  95. package/extensions/mobile/skills/deep-linking.md +109 -0
  96. package/extensions/mobile/skills/flutter.md +60 -0
  97. package/extensions/mobile/skills/ios-build-pipeline.md +142 -0
  98. package/extensions/mobile/skills/native-bridge.md +66 -0
  99. package/extensions/mobile/skills/ota-updates.md +97 -0
  100. package/extensions/mobile/skills/push-notifications.md +111 -0
  101. package/extensions/mobile/skills/react-native.md +82 -0
  102. package/extensions/saas/PACK.md +26 -720
  103. package/extensions/saas/skills/billing-integration.md +121 -0
  104. package/extensions/saas/skills/feature-flags.md +130 -0
  105. package/extensions/saas/skills/multi-tenant.md +103 -0
  106. package/extensions/saas/skills/onboarding-flow.md +139 -0
  107. package/extensions/saas/skills/subscription-flow.md +95 -0
  108. package/extensions/saas/skills/team-management.md +144 -0
  109. package/extensions/security/PACK.md +10 -448
  110. package/extensions/security/skills/api-security.md +140 -0
  111. package/extensions/security/skills/compliance.md +68 -0
  112. package/extensions/security/skills/owasp-audit.md +64 -0
  113. package/extensions/security/skills/pentest-patterns.md +77 -0
  114. package/extensions/security/skills/secret-mgmt.md +65 -0
  115. package/extensions/security/skills/supply-chain.md +65 -0
  116. package/extensions/trading/PACK.md +18 -535
  117. package/extensions/trading/skills/chart-components.md +55 -0
  118. package/extensions/trading/skills/experiment-loop.md +125 -0
  119. package/extensions/trading/skills/fintech-patterns.md +47 -0
  120. package/extensions/trading/skills/indicator-library.md +58 -0
  121. package/extensions/trading/skills/quant-analysis.md +111 -0
  122. package/extensions/trading/skills/realtime-data.md +58 -0
  123. package/extensions/trading/skills/trade-logic.md +104 -0
  124. package/extensions/ui/PACK.md +34 -853
  125. package/extensions/ui/skills/a11y-audit.md +91 -0
  126. package/extensions/ui/skills/animation-patterns.md +106 -0
  127. package/extensions/ui/skills/component-patterns.md +75 -0
  128. package/extensions/ui/skills/design-decision.md +98 -0
  129. package/extensions/ui/skills/design-system.md +68 -0
  130. package/extensions/ui/skills/landing-patterns.md +155 -0
  131. package/extensions/ui/skills/palette-picker.md +162 -0
  132. package/extensions/ui/skills/react-health.md +90 -0
  133. package/extensions/ui/skills/type-system.md +125 -0
  134. package/extensions/ui/skills/web-vitals.md +153 -0
  135. package/extensions/zalo/PACK.md +117 -0
  136. package/extensions/zalo/skills/zalo-oa-mcp.md +317 -0
  137. package/extensions/zalo/skills/zalo-oa-messaging.md +429 -0
  138. package/extensions/zalo/skills/zalo-oa-setup.md +236 -0
  139. package/extensions/zalo/skills/zalo-oa-webhook.md +189 -0
  140. package/extensions/zalo/skills/zalo-personal-messaging.md +194 -0
  141. package/extensions/zalo/skills/zalo-personal-setup.md +153 -0
  142. package/extensions/zalo/skills/zalo-rate-guard.md +219 -0
  143. package/package.json +5 -2
  144. package/skills/brainstorm/SKILL.md +63 -1
  145. package/skills/cook/SKILL.md +89 -6
  146. package/skills/debug/SKILL.md +5 -0
  147. package/skills/fix/SKILL.md +5 -0
  148. package/skills/mcp-builder/SKILL.md +48 -1
  149. package/skills/neural-memory/SKILL.md +362 -0
  150. package/skills/plan/SKILL.md +3 -0
  151. package/skills/rescue/SKILL.md +5 -0
  152. package/skills/review/SKILL.md +44 -5
  153. package/skills/review-intake/SKILL.md +17 -1
  154. package/skills/skill-router/SKILL.md +106 -8
  155. package/skills/team/SKILL.md +24 -1
  156. package/skills/test/SKILL.md +18 -0
  157. package/skills/verification/SKILL.md +40 -1
@@ -0,0 +1,144 @@
1
+ ---
2
+ name: "team-management"
3
+ pack: "@rune/saas"
4
+ description: "Organization, team, and member permissions — RBAC hierarchy, invite flow with expiry, permission checking at API and UI layers, and audit trail for permission changes."
5
+ model: sonnet
6
+ tools: [Read, Edit, Write, Grep, Glob, Bash]
7
+ ---
8
+
9
+ # team-management
10
+
11
+ Organization, team, and member permissions — RBAC hierarchy, invite flow with expiry, permission checking at API and UI layers, and audit trail for permission changes.
12
+
13
+ #### Role Hierarchy
14
+
15
+ ```
16
+ Owner (1 per org)
17
+ └── Admin (multiple)
18
+ └── Member (default role)
19
+ └── Viewer (read-only)
20
+ ```
21
+
22
+ Org-level roles apply across all teams. Team-level roles can be more restrictive (e.g., org Member can be team Admin for a specific team).
23
+
24
+ #### Permission Matrix
25
+
26
+ | Action | Owner | Admin | Member | Viewer |
27
+ |---|---|---|---|---|
28
+ | Delete organization | ✅ | ❌ | ❌ | ❌ |
29
+ | Manage billing | ✅ | ✅ | ❌ | ❌ |
30
+ | Invite members | ✅ | ✅ | ❌ | ❌ |
31
+ | Create teams | ✅ | ✅ | ❌ | ❌ |
32
+ | Create projects | ✅ | ✅ | ✅ | ❌ |
33
+ | View projects | ✅ | ✅ | ✅ | ✅ |
34
+ | Manage team members | ✅ | ✅ (own teams) | ❌ | ❌ |
35
+
36
+ #### Workflow
37
+
38
+ **Step 1 — Design org/team schema**
39
+ Model: `Organization → Team → Membership (userId, orgId, teamId?, role)`. Org-level membership has `teamId = null`. Team-level membership scopes the role to a specific team. Use a single `Membership` table with nullable `teamId` rather than separate `OrgMember` and `TeamMember` tables.
40
+
41
+ **Step 2 — Implement RBAC middleware**
42
+ Create a `requirePermission(action)` middleware that reads `req.user.id` + `req.tenantId`, loads the user's role for that org, and checks against a permission map. Fail fast: return 403 immediately if permission not found. Never trust client-provided role claims.
43
+
44
+ **Step 3 — Build invite flow**
45
+ Invite: generate a signed token (`crypto.randomBytes(32).hex`), store with `{ email, orgId, role, invitedBy, expiresAt: +7d }`, send email with link. Accept: verify token not expired, not already accepted, create Membership record, mark invite as accepted. Resend: invalidate old token, create new one with fresh expiry. Pending invites visible to admins in settings.
46
+
47
+ **Step 4 — Add permission UI gates**
48
+ In React: `<CanAccess action="invite_members"><InviteButton /></CanAccess>` — hides UI elements the user can't use. Also disable + tooltip pattern: show the button but disable it with "Upgrade to invite members" tooltip (better UX than hiding, helps users understand what's possible). Enforce the same check in the API — UI gates are cosmetic only.
49
+
50
+ **Step 5 — Emit audit trail**
51
+ Every permission change, role assignment, invite, and removal MUST log to an `AuditLog` table: `{ orgId, actorId, targetId, action, before, after, ip, userAgent, timestamp }`. Surface the last 100 entries in the org settings Security tab. Retain for 90 days minimum (compliance requirement for SOC2).
52
+
53
+ #### Example
54
+
55
+ ```typescript
56
+ // Prisma schema — org, team, membership
57
+ model Organization {
58
+ id String @id @default(cuid())
59
+ name String
60
+ slug String @unique
61
+ members Membership[]
62
+ teams Team[]
63
+ }
64
+
65
+ model Team {
66
+ id String @id @default(cuid())
67
+ orgId String
68
+ name String
69
+ org Organization @relation(fields: [orgId], references: [id])
70
+ members Membership[]
71
+ }
72
+
73
+ model Membership {
74
+ id String @id @default(cuid())
75
+ userId String
76
+ orgId String
77
+ teamId String? // null = org-level role
78
+ role Role
79
+ user User @relation(fields: [userId], references: [id])
80
+ org Organization @relation(fields: [orgId], references: [id])
81
+ team Team? @relation(fields: [teamId], references: [id])
82
+
83
+ @@unique([userId, orgId, teamId]) // one role per user per scope
84
+ }
85
+
86
+ enum Role { OWNER ADMIN MEMBER VIEWER }
87
+
88
+ // Permission map
89
+ const PERMISSIONS = {
90
+ delete_org: ['OWNER'],
91
+ manage_billing: ['OWNER', 'ADMIN'],
92
+ invite_members: ['OWNER', 'ADMIN'],
93
+ create_projects: ['OWNER', 'ADMIN', 'MEMBER'],
94
+ view_projects: ['OWNER', 'ADMIN', 'MEMBER', 'VIEWER'],
95
+ } as const;
96
+ type Action = keyof typeof PERMISSIONS;
97
+
98
+ // RBAC middleware — never trust client-provided role
99
+ const requirePermission = (action: Action) => async (req: Request, res: Response, next: NextFunction) => {
100
+ const membership = await prisma.membership.findFirst({
101
+ where: { userId: req.user!.id, orgId: req.tenantId!, teamId: null },
102
+ });
103
+ if (!membership || !(PERMISSIONS[action] as readonly string[]).includes(membership.role)) {
104
+ return res.status(403).json({ error: { code: 'FORBIDDEN', action } });
105
+ }
106
+ req.userRole = membership.role;
107
+ next();
108
+ };
109
+
110
+ // React permission hook
111
+ function usePermission(action: Action): boolean {
112
+ const { membership } = useOrg();
113
+ if (!membership) return false;
114
+ return (PERMISSIONS[action] as readonly string[]).includes(membership.role);
115
+ }
116
+
117
+ // Invite flow
118
+ const createInvite = async (orgId: string, email: string, role: Role, invitedBy: string) => {
119
+ const token = crypto.randomBytes(32).toString('hex');
120
+ await prisma.invite.create({
121
+ data: { orgId, email, role, invitedBy, token, expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) },
122
+ });
123
+ await emailQueue.add('invite', { email, token, orgId });
124
+ return token;
125
+ };
126
+
127
+ const acceptInvite = async (token: string, userId: string) => {
128
+ const invite = await prisma.invite.findUnique({ where: { token } });
129
+ if (!invite || invite.acceptedAt || invite.expiresAt < new Date()) {
130
+ throw new Error('Invalid or expired invite');
131
+ }
132
+ await prisma.$transaction([
133
+ prisma.membership.create({ data: { userId, orgId: invite.orgId, role: invite.role } }),
134
+ prisma.invite.update({ where: { token }, data: { acceptedAt: new Date() } }),
135
+ prisma.auditLog.create({ data: { orgId: invite.orgId, actorId: userId, action: 'MEMBER_JOINED', targetId: userId } }),
136
+ ]);
137
+ };
138
+ ```
139
+
140
+ **Sharp edges for team-management:**
141
+ - **Permission escalation**: an Admin inviting another Admin is fine, but an Admin promoting themselves to Owner must be blocked. Rule: you can only assign roles lower than your own.
142
+ - **Cross-org data leak**: when loading team resources, always filter by `orgId`. A user who belongs to two orgs must never see org B's data when acting in org A's context.
143
+ - **Invite token reuse**: after an invite is accepted, mark it accepted immediately in the same transaction as membership creation. Race condition: two tabs accepting the same invite → use `@@unique` on membership + catch unique constraint error.
144
+ - **Owner removal**: prevent the last Owner from being removed or downgraded. Always require at least one Owner per org. Check before processing the role change.
@@ -7,6 +7,7 @@ metadata:
7
7
  layer: L4
8
8
  price: "$15"
9
9
  target: Security engineers
10
+ format: split
10
11
  tools:
11
12
  - Read
12
13
  - Grep
@@ -31,460 +32,21 @@ tools:
31
32
 
32
33
  ## Skills Included
33
34
 
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
- ---
35
+ | Skill | Model | Description |
36
+ |-------|-------|-------------|
37
+ | [owasp-audit](skills/owasp-audit.md) | opus | Deep OWASP Top 10 (2021) + API Security Top 10 (2023) audit with manual code review, CI/CD pipeline security, and exploitability-rated findings. |
38
+ | [pentest-patterns](skills/pentest-patterns.md) | opus | Attack surface mapping, PoC construction, JWT attack pattern detection, automated fuzzing setup, and GraphQL hardening. |
39
+ | [secret-mgmt](skills/secret-mgmt.md) | sonnet | Audit secret handling, design vault/env strategy, implement rotation policies, and verify zero leaks in logs and source history. |
40
+ | [compliance](skills/compliance.md) | opus | SOC 2, GDPR, HIPAA, PCI-DSS v4.0 gap analysis, automated evidence collection, and audit-ready evidence packages. |
41
+ | [supply-chain](skills/supply-chain.md) | sonnet | Dependency confusion attacks, typosquatting, lockfile injection, manifest confusion, and SLSA provenance verification. |
42
+ | [api-security](skills/api-security.md) | sonnet | Rate limiting, input sanitization, CORS, CSP generation, and security headers middleware for Express, Fastify, and Next.js. |
482
43
 
483
44
  ## Connections
484
45
 
485
46
  ```
486
47
  Calls → scout (L2): scan codebase for security patterns before audit
487
48
  Calls → verification (L3): run security tooling (Semgrep, Trivy, npm audit, gitleaks)
49
+ Calls → @rune/backend (L4): auth pattern overlap — security audits reference backend auth flows
488
50
  Called By ← review (L2): when security-critical code detected during review
489
51
  Called By ← cook (L1): when auth/input/payment/PII code is in scope
490
52
  Called By ← deploy (L2): pre-release security gate when security scope active