@vibefoundry/vibe-shield 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +571 -3
  3. package/SECURITY.md +110 -0
  4. package/SKILL.md +124 -0
  5. package/dist/bin/vibe-shield.d.ts +59 -0
  6. package/dist/bin/vibe-shield.js +541 -0
  7. package/dist/src/index.d.ts +25 -0
  8. package/dist/src/index.js +108 -0
  9. package/dist/src/init/scaffold.d.ts +122 -0
  10. package/dist/src/init/scaffold.js +573 -0
  11. package/dist/src/mcp/server.d.ts +127 -0
  12. package/dist/src/mcp/server.js +479 -0
  13. package/dist/src/mcp-guard/skill-auditor.d.ts +105 -0
  14. package/dist/src/mcp-guard/skill-auditor.js +1129 -0
  15. package/dist/src/reporter/console-reporter.d.ts +58 -0
  16. package/dist/src/reporter/console-reporter.js +254 -0
  17. package/dist/src/reporter/formatters.d.ts +38 -0
  18. package/dist/src/reporter/formatters.js +262 -0
  19. package/dist/src/reporter/patch-prompt-writer.d.ts +35 -0
  20. package/dist/src/reporter/patch-prompt-writer.js +238 -0
  21. package/dist/src/scanner/context.d.ts +51 -0
  22. package/dist/src/scanner/context.js +568 -0
  23. package/dist/src/scanner/engine.d.ts +130 -0
  24. package/dist/src/scanner/engine.js +722 -0
  25. package/dist/src/scanner/gitignore.d.ts +49 -0
  26. package/dist/src/scanner/gitignore.js +195 -0
  27. package/dist/src/scanner/lexicon.d.ts +56 -0
  28. package/dist/src/scanner/lexicon.js +357 -0
  29. package/dist/src/scanner/rules/ai-vulnerabilities.d.ts +15 -0
  30. package/dist/src/scanner/rules/ai-vulnerabilities.js +859 -0
  31. package/dist/src/scanner/rules/client-exposure.d.ts +18 -0
  32. package/dist/src/scanner/rules/client-exposure.js +410 -0
  33. package/dist/src/scanner/rules/database-exposure.d.ts +15 -0
  34. package/dist/src/scanner/rules/database-exposure.js +626 -0
  35. package/dist/src/scanner/rules/helpers.d.ts +31 -0
  36. package/dist/src/scanner/rules/helpers.js +85 -0
  37. package/dist/src/scanner/rules/index.d.ts +30 -0
  38. package/dist/src/scanner/rules/index.js +95 -0
  39. package/dist/src/scanner/rules/secret-entropy.d.ts +17 -0
  40. package/dist/src/scanner/rules/secret-entropy.js +338 -0
  41. package/dist/src/scanner/rules/shared.d.ts +100 -0
  42. package/dist/src/scanner/rules/shared.js +161 -0
  43. package/dist/src/scanner/rules/unguarded-routes.d.ts +16 -0
  44. package/dist/src/scanner/rules/unguarded-routes.js +526 -0
  45. package/dist/src/scanner/text.d.ts +90 -0
  46. package/dist/src/scanner/text.js +472 -0
  47. package/dist/src/scanner/types.d.ts +340 -0
  48. package/dist/src/scanner/types.js +195 -0
  49. package/dist/src/secrets/patterns.d.ts +63 -0
  50. package/dist/src/secrets/patterns.js +392 -0
  51. package/package.json +94 -4
@@ -0,0 +1,573 @@
1
+ "use strict";
2
+ /**
3
+ * vibe-shield :: `npx github:avivgerz-hue/vibe-shield init`
4
+ * -------------------------------------
5
+ * One command turns any repository into a guarded one. It installs:
6
+ *
7
+ * - `.claude/skills/vibe-shield/SKILL.md` — the Agent Skill, so Claude Code
8
+ * (and any SKILL.md-aware agent) audits before it reports "done".
9
+ * - an `AGENTS.md` section — the same contract for Codex, Cursor, Windsurf and
10
+ * every other agent that reads a repo-level instruction file.
11
+ * - `.github/workflows/vibe-shield.yml` — fails the build on new findings.
12
+ * - `.vibe-shieldignore` — the documented escape hatch for generated code.
13
+ *
14
+ * Nothing is overwritten without `--force`, and every write is reported so the
15
+ * command is safe to re-run.
16
+ */
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
30
+ }) : function(o, v) {
31
+ o["default"] = v;
32
+ });
33
+ var __importStar = (this && this.__importStar) || (function () {
34
+ var ownKeys = function(o) {
35
+ ownKeys = Object.getOwnPropertyNames || function (o) {
36
+ var ar = [];
37
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
38
+ return ar;
39
+ };
40
+ return ownKeys(o);
41
+ };
42
+ return function (mod) {
43
+ if (mod && mod.__esModule) return mod;
44
+ var result = {};
45
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
46
+ __setModuleDefault(result, mod);
47
+ return result;
48
+ };
49
+ })();
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ exports.IGNORE_TEMPLATE = exports.WORKFLOW_TEMPLATE = exports.MCP_SERVER_ENTRY = exports.MCP_SERVER_SPEC = exports.MCP_SERVER_KEY = exports.AGENTS_SECTION = exports.SKILL_TEMPLATE = void 0;
52
+ exports.mcpServerEntry = mcpServerEntry;
53
+ exports.resolveInstallRev = resolveInstallRev;
54
+ exports.mergeMcpConfig = mergeMcpConfig;
55
+ exports.buildScaffold = buildScaffold;
56
+ exports.installScaffold = installScaffold;
57
+ exports.locateBundledSkill = locateBundledSkill;
58
+ const node_fs_1 = require("node:fs");
59
+ const path = __importStar(require("node:path"));
60
+ const shared_1 = require("../scanner/rules/shared");
61
+ const BANNER = '<!-- Managed by vibe-shield. Edit freely; `npx github:avivgerz-hue/vibe-shield init --force` regenerates this file. -->';
62
+ /* -------------------------------------------------------------------------- */
63
+ /* SKILL.md */
64
+ /* -------------------------------------------------------------------------- */
65
+ exports.SKILL_TEMPLATE = `---
66
+ name: vibe-shield
67
+ description: Audit any change for AI-introduced security bugs (leaked keys, unguarded API routes, disabled Row Level Security, SQL injection, prompt injection, poisoned MCP servers) and fix them before reporting a task as done. Use whenever you write or modify application code, API routes, server actions, database migrations, auth logic, environment variables, LLM calls, webhook handlers, agent skills or MCP configuration.
68
+ allowed-tools: Bash(npx github:avivgerz-hue/vibe-shield scan*), Bash(npx github:avivgerz-hue/vibe-shield audit-skills*), Bash(npx github:avivgerz-hue/vibe-shield explain*), Read(./**), Grep, Glob
69
+ license: MIT
70
+ metadata:
71
+ author: VibeFoundry
72
+ homepage: https://github.com/avivgerz-hue/vibe-shield
73
+ version: 1.0.0
74
+ ---
75
+
76
+ # vibe-shield
77
+
78
+ You are not allowed to say "done" until the code you just wrote passes a security audit.
79
+
80
+ AI coding agents ship a specific, repeatable class of vulnerability: a \`SUPABASE_SERVICE_ROLE_KEY\` behind a \`NEXT_PUBLIC_\` prefix, a \`DELETE\` route handler with no session check, a \`CREATE TABLE\` with no \`ENABLE ROW LEVEL SECURITY\`, a tool whose \`execute\` forwards model output into \`exec\`. These are not exotic — they are the default shape of code written quickly by something optimising for "it works". This skill is the second pair of eyes.
81
+
82
+ ## When to run
83
+
84
+ Run the audit **after every change that touches**:
85
+
86
+ - an API route, route handler, server action, RPC endpoint or GraphQL mutation
87
+ - authentication, session, role, permission or ownership logic
88
+ - a database migration, policy, grant, schema or Supabase table
89
+ - an environment variable, config file, \`.env*\` file or build config
90
+ - anything calling an LLM, a tool, a webhook, a shell command or the filesystem
91
+ - \`.claude/\`, \`.cursor/\`, \`AGENTS.md\`, \`mcp.json\` or any skill/config file
92
+
93
+ If you did not touch any of those, you do not need to run it.
94
+
95
+ ## The loop
96
+
97
+ \`\`\`bash
98
+ # 1. Scan (a whole-repo scan finishes in well under a second)
99
+ npx github:avivgerz-hue/vibe-shield scan --fail-on high
100
+
101
+ # 2. If it fails, generate the machine-readable fix list
102
+ npx github:avivgerz-hue/vibe-shield scan --fix-prompt
103
+
104
+ # 3. Read SECURITY_PATCH_PROMPT.md and fix every finding, critical first
105
+ # Each entry has the exact file:line, the vulnerable snippet, the CWE and
106
+ # the required change. Apply it literally.
107
+
108
+ # 4. Re-run until it exits 0
109
+ npx github:avivgerz-hue/vibe-shield scan --fail-on high
110
+ \`\`\`
111
+
112
+ \`--fail-on high\` exits non-zero while any high or critical finding exists. That is the gate.
113
+
114
+ ## Reading a finding
115
+
116
+ \`\`\`
117
+ CRITICAL 47:15 VSB-CLIENT-001 Server-only secret exposed through a public environment prefix
118
+ const key = process.env.NEXT_PUBLIC_OPENAI_API_KEY;
119
+ \`\`\`
120
+
121
+ | Part | Meaning |
122
+ | --- | --- |
123
+ | \`47:15\` | exact line and column to edit |
124
+ | \`VSB-CLIENT-001\` | rule id — use it with \`explain\` for full docs |
125
+ | message | why this specific line is exploitable |
126
+ | \`(CWE-200)\` | bug class, for a deeper search if the fix is unclear |
127
+
128
+ Need the full picture? \`npx github:avivgerz-hue/vibe-shield explain VSB-CLIENT-001\` prints the vulnerable shape, the fixed shape, remediation steps and references.
129
+
130
+ ## Hard rules
131
+
132
+ 1. **Fix the root cause.** Never delete an auth check, disable RLS, silence a log or add a catch-all \`catch {}\` to make the finding disappear.
133
+ 2. **Never suppress.** Do not add \`// vibe-shield-disable\`, do not edit \`.vibe-shieldignore\`, do not pass \`--ignore\`. Suppression is a decision for the human.
134
+ 3. **Rotate exposed credentials.** If the scan reported a live key, tell the user to rotate it at the provider in the same message. Removing the line does not un-leak it — the value may already be in a bundle, a cache or a git history.
135
+ 4. **Report honestly.** If you cannot fix a finding (you need a decision, a credential or a provider change), say so explicitly, name the rule id, and stop.
136
+ 5. **Re-verify.** A fix is not finished until the gate exits 0.
137
+
138
+ ## Agent surface audit
139
+
140
+ When you add or modify a skill, rule file, MCP server or instruction file, also run:
141
+
142
+ \`\`\`bash
143
+ npx github:avivgerz-hue/vibe-shield audit-skills
144
+ \`\`\`
145
+
146
+ Twelve \`VSB-AGENT-*\` rules check for hidden Unicode (zero-width and bidi characters used to smuggle instructions past review), \`curl\`/\`wget\` exfiltration of environment variables, credential-harvesting instructions (\`.env\`, \`~/.ssh\`, \`~/.aws\`), registry-tag or remote MCP servers, literal tokens in an \`env\` block, safety-override language, over-broad tool permissions, base64 \`eval\` payloads, remote-instruction fetching, wildcard \`allowed-tools\`, and shell injection in skill scripts.
147
+
148
+ Each finding carries a \`triage\` field: \`block\` means refuse and escalate, \`review\` means ask the user, \`report\` means mention it and continue. Do not blanket-refuse a repository because a rule fired — read the triage.
149
+
150
+ ## Flags worth knowing
151
+
152
+ | Flag | Effect |
153
+ | --- | --- |
154
+ | \`--format json\` | full machine-readable report (schemaVersion 1) |
155
+ | \`--format sarif\` | SARIF 2.1.0 for GitHub code scanning |
156
+ | \`--format compact\` | one line per finding |
157
+ | \`--format github\` | inline GitHub Actions annotations |
158
+ | \`--severity high\` | only report high and critical |
159
+ | \`--fail-on medium\` | stricter gate |
160
+ | \`--include-tests\` | include test and fixture files |
161
+ | \`--cache\` | reuse results between runs |
162
+ | \`--quiet\` | one-line verdict (ideal for piping) |
163
+ | \`rules\` | list every rule |
164
+ | \`explain <RULE_ID>\` | full documentation for one rule |
165
+
166
+ If the repository has a \`.mcp.json\`, the same three capabilities are also
167
+ available as MCP tools — \`vibe_shield_scan\`, \`vibe_shield_audit_skills\` and
168
+ \`vibe_shield_explain_rule\`. Prefer those when they are listed, because they
169
+ return structured findings instead of text you have to parse.
170
+
171
+ ## Definition of done
172
+
173
+ - [ ] \`npx github:avivgerz-hue/vibe-shield scan --fail-on high\` exits \`0\`
174
+ - [ ] \`npx github:avivgerz-hue/vibe-shield audit-skills\` exits \`0\` if you touched agent files
175
+ - [ ] every credential the scan surfaced has been flagged to the user for rotation
176
+ - [ ] no suppression directive was added
177
+ - [ ] the feature still works and the existing tests still pass
178
+
179
+ ## Install it into a repository
180
+
181
+ \`\`\`bash
182
+ npx github:avivgerz-hue/vibe-shield init
183
+ \`\`\`
184
+
185
+ That writes this file to \`.claude/skills/vibe-shield/SKILL.md\`, appends a security
186
+ gate section to \`AGENTS.md\`, adds a \`.cursor/rules/vibe-shield.mdc\`, and installs a
187
+ GitHub Actions workflow that fails the pull request on new high or critical
188
+ findings. Every future task in that repository starts guarded.
189
+ `;
190
+ /* -------------------------------------------------------------------------- */
191
+ /* AGENTS.md section */
192
+ /* -------------------------------------------------------------------------- */
193
+ exports.AGENTS_SECTION = `## Security gate (vibe-shield)
194
+
195
+ This repository is guarded by [vibe-shield](https://github.com/avivgerz-hue/vibe-shield).
196
+
197
+ Before you report any task as complete:
198
+
199
+ 1. Run \`npx github:avivgerz-hue/vibe-shield scan --fail-on high\` and fix every finding it reports.
200
+ 2. Never suppress a finding (\`vibe-shield-disable\`, \`.vibe-shieldignore\` edits,
201
+ \`--ignore\`) to make the gate pass — that is the human's call.
202
+ 3. If you touched \`.claude/\`, \`.cursor/\`, \`AGENTS.md\`, \`mcp.json\` or a skill,
203
+ also run \`npx github:avivgerz-hue/vibe-shield audit-skills\`.
204
+ 4. Surface any exposed credential to the user for rotation. Do not "fix" it by
205
+ deleting the line and moving on.
206
+
207
+ The gate exists because the most common way AI-written code reaches production
208
+ with a leaked \`SUPABASE_SERVICE_ROLE_KEY\` or an unauthenticated \`DELETE\`
209
+ endpoint is that nobody asked it a second question.
210
+ `;
211
+ /* -------------------------------------------------------------------------- */
212
+ /* .mcp.json */
213
+ /* -------------------------------------------------------------------------- */
214
+ /** Key this tool owns inside `mcpServers`; nothing else is ever touched. */
215
+ exports.MCP_SERVER_KEY = 'vibe-shield';
216
+ /**
217
+ * The server entry written into `.mcp.json`.
218
+ *
219
+ * `npx` is used rather than a local path so the config keeps working when the
220
+ * project is cloned elsewhere or the package is upgraded.
221
+ *
222
+ * The spec carries a `#<commit>` pin when `init` can determine one. A bare
223
+ * `github:owner/repo` re-resolves to the default branch head on every fresh
224
+ * install, so a mixed commit could change what runs the next time the server
225
+ * starts. Pin the commit that wrote this file and upgrades become explicit
226
+ * (`init --force` rewrites it).
227
+ */
228
+ exports.MCP_SERVER_SPEC = shared_1.SELF_GITHUB_SPEC;
229
+ /** Build the `.mcp.json` entry, pinned to `rev` when one is known. */
230
+ function mcpServerEntry(rev) {
231
+ const spec = rev ? `${exports.MCP_SERVER_SPEC}#${rev}` : exports.MCP_SERVER_SPEC;
232
+ return { command: 'npx', args: ['--yes', spec, 'mcp'] };
233
+ }
234
+ /** The unpinned entry, kept for callers that have no commit available. */
235
+ exports.MCP_SERVER_ENTRY = mcpServerEntry();
236
+ /**
237
+ * Merge the vibe-shield server into an existing `.mcp.json` without disturbing
238
+ * anything already there.
239
+ *
240
+ * Returns the serialised file and whether our key was newly added. Existing
241
+ * servers, other top-level keys and the user's formatting choices are preserved;
242
+ * a malformed file is reported rather than overwritten, because silently
243
+ * rewriting someone's MCP config could break every server they run.
244
+ */
245
+ /**
246
+ * Find the commit of the running install, so `.mcp.json` can pin it.
247
+ *
248
+ * Deliberately conservative: returns `null` rather than guessing, because a
249
+ * wrong pin is worse than no pin (it would silently freeze the server on an
250
+ * unrelated commit). The revision is only derivable when the CLI is running
251
+ * from inside an npm install of this package, which is the `npx github:` case.
252
+ *
253
+ * Order:
254
+ * 1. `VIBE_SHIELD_REV` — an explicit override, used by tests and CI.
255
+ * 2. The `resolved` field npm records in the *parent* project's lockfile.
256
+ * 3. `/app/.rev` — written into the container image at build time.
257
+ */
258
+ async function resolveInstallRev(rootDir, env = process.env) {
259
+ const explicit = env.VIBE_SHIELD_REV?.trim();
260
+ if (explicit)
261
+ return explicit;
262
+ const shaPattern = /(?:[?#]([0-9a-f]{40}))\b/i;
263
+ // A lockfile one or two directories above this file, in an npm install.
264
+ let dir = __dirname;
265
+ for (let depth = 0; depth < 4; depth += 1) {
266
+ for (const name of ['package-lock.json', 'npm-shrinkwrap.json']) {
267
+ try {
268
+ const raw = await node_fs_1.promises.readFile(path.join(dir, name), 'utf8');
269
+ const match = raw.match(shaPattern);
270
+ if (match?.[1])
271
+ return match[1];
272
+ }
273
+ catch {
274
+ // Keep walking.
275
+ }
276
+ }
277
+ const parent = path.dirname(dir);
278
+ if (parent === dir)
279
+ break;
280
+ dir = parent;
281
+ }
282
+ try {
283
+ const rev = (await node_fs_1.promises.readFile('/app/.rev', 'utf8')).trim();
284
+ if (/^[0-9a-f]{40}$/i.test(rev))
285
+ return rev;
286
+ }
287
+ catch {
288
+ // Not in the container image.
289
+ }
290
+ void rootDir;
291
+ return null;
292
+ }
293
+ function mergeMcpConfig(existing, options = {}) {
294
+ const entry = mcpServerEntry(options.rev);
295
+ if (existing === null || existing.trim() === '') {
296
+ return {
297
+ contents: `${JSON.stringify({ mcpServers: { [exports.MCP_SERVER_KEY]: entry } }, null, 2)}\n`,
298
+ changed: true,
299
+ };
300
+ }
301
+ let parsed;
302
+ try {
303
+ parsed = JSON.parse(existing);
304
+ }
305
+ catch (error) {
306
+ return {
307
+ contents: existing,
308
+ changed: false,
309
+ error: `.mcp.json is not valid JSON (${error instanceof Error ? error.message : String(error)}); left untouched.`,
310
+ };
311
+ }
312
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
313
+ return { contents: existing, changed: false, error: '.mcp.json is not a JSON object; left untouched.' };
314
+ }
315
+ const config = parsed;
316
+ const servers = config.mcpServers;
317
+ if (servers !== undefined && (typeof servers !== 'object' || servers === null || Array.isArray(servers))) {
318
+ return { contents: existing, changed: false, error: '.mcp.json has a non-object "mcpServers"; left untouched.' };
319
+ }
320
+ const table = (servers ?? {});
321
+ const present = Object.prototype.hasOwnProperty.call(table, exports.MCP_SERVER_KEY);
322
+ if (present && !options.force) {
323
+ return { contents: existing, changed: false };
324
+ }
325
+ const next = { ...config, mcpServers: { ...table, [exports.MCP_SERVER_KEY]: entry } };
326
+ return { contents: `${JSON.stringify(next, null, 2)}\n`, changed: true };
327
+ }
328
+ /* -------------------------------------------------------------------------- */
329
+ /* GitHub Actions workflow */
330
+ /* -------------------------------------------------------------------------- */
331
+ exports.WORKFLOW_TEMPLATE = `name: vibe-shield
332
+
333
+ on:
334
+ push:
335
+ branches: [main, master]
336
+ pull_request:
337
+ workflow_dispatch:
338
+
339
+ permissions:
340
+ contents: read
341
+ security-events: write
342
+ pull-requests: write
343
+
344
+ jobs:
345
+ scan:
346
+ name: Security audit
347
+ runs-on: ubuntu-latest
348
+ timeout-minutes: 10
349
+ steps:
350
+ - uses: actions/checkout@v4
351
+ with:
352
+ fetch-depth: 0
353
+
354
+ - uses: actions/setup-node@v4
355
+ with:
356
+ node-version: 20
357
+
358
+ - name: Scan for vulnerabilities
359
+ run: npx --yes github:avivgerz-hue/vibe-shield scan --format sarif --out vibe-shield.sarif --fail-on high
360
+ continue-on-error: true
361
+
362
+ - name: Upload SARIF to code scanning
363
+ if: always()
364
+ uses: github/codeql-action/upload-sarif@v3
365
+ with:
366
+ sarif_file: vibe-shield.sarif
367
+ category: vibe-shield
368
+
369
+ - name: Audit agent surface
370
+ run: npx --yes github:avivgerz-hue/vibe-shield audit-skills --fail-on high
371
+
372
+ - name: Enforce the gate
373
+ run: npx --yes github:avivgerz-hue/vibe-shield scan --fail-on high --quiet
374
+ `;
375
+ /* -------------------------------------------------------------------------- */
376
+ /* .vibe-shieldignore */
377
+ /* -------------------------------------------------------------------------- */
378
+ exports.IGNORE_TEMPLATE = `# .vibe-shieldignore — gitignore syntax.
379
+ #
380
+ # Keep this file as short as possible: every line hides real code from the
381
+ # security gate. Prefer an inline suppression with a reason where it applies:
382
+ #
383
+ # // vibe-shield-disable-next-line VSB-AI-001 -- path comes from a fixed enum
384
+ #
385
+ # Generated code, vendored third-party sources and build output are the only
386
+ # good reasons to ignore a path wholesale.
387
+
388
+ # Generated / vendored
389
+ # vendor/**
390
+ # **/*.generated.ts
391
+ # **/__generated__/**
392
+
393
+ # Local-only scratch work
394
+ # scratch/**
395
+ `;
396
+ /* -------------------------------------------------------------------------- */
397
+ /* Cursor rules */
398
+ /* -------------------------------------------------------------------------- */
399
+ const CURSOR_RULE = `---
400
+ description: Run vibe-shield before finishing any coding task
401
+ globs: ["**/*"]
402
+ alwaysApply: true
403
+ ---
404
+
405
+ ${BANNER}
406
+
407
+ # Security gate
408
+
409
+ Before reporting a task complete, run \`npx github:avivgerz-hue/vibe-shield scan --fail-on high\` and
410
+ fix every finding. Never suppress a finding to make the gate pass. If the scan
411
+ reports an exposed credential, tell the user to rotate it at the provider.
412
+ `;
413
+ /** Build the full set of files for a given target repository. */
414
+ function buildScaffold(options) {
415
+ const agents = options.agents ?? 'all';
416
+ const files = [];
417
+ if (agents === 'claude' || agents === 'all') {
418
+ files.push({
419
+ relativePath: '.claude/skills/vibe-shield/SKILL.md',
420
+ contents: exports.SKILL_TEMPLATE,
421
+ mode: 'write',
422
+ description: 'Agent Skill — forces Claude Code to audit before finishing',
423
+ });
424
+ }
425
+ if (agents === 'cursor' || agents === 'all') {
426
+ files.push({
427
+ relativePath: '.cursor/rules/vibe-shield.mdc',
428
+ contents: CURSOR_RULE,
429
+ mode: 'write',
430
+ description: 'Cursor rule — same gate for Cursor/Windsurf',
431
+ });
432
+ }
433
+ if (agents === 'generic' || agents === 'all') {
434
+ files.push({
435
+ relativePath: 'AGENTS.md',
436
+ contents: exports.AGENTS_SECTION,
437
+ mode: 'append',
438
+ marker: '## Security gate (vibe-shield)',
439
+ description: 'AGENTS.md section — Codex, Cursor, Windsurf, Amp',
440
+ });
441
+ }
442
+ if (options.workflow !== false) {
443
+ files.push({
444
+ relativePath: '.github/workflows/vibe-shield.yml',
445
+ contents: exports.WORKFLOW_TEMPLATE,
446
+ mode: 'write',
447
+ description: 'GitHub Actions — fails the PR on new high/critical findings',
448
+ });
449
+ }
450
+ files.push({
451
+ relativePath: '.mcp.json',
452
+ contents: '', // produced by mergeMcpConfig so existing servers survive
453
+ mode: 'merge',
454
+ description: 'MCP server config — lets Claude Code/Desktop, Cursor and Codex call the scanner',
455
+ });
456
+ files.push({
457
+ relativePath: '.vibe-shieldignore',
458
+ contents: exports.IGNORE_TEMPLATE,
459
+ mode: 'write',
460
+ description: 'Ignore file — documented escape hatch',
461
+ });
462
+ return files;
463
+ }
464
+ const exists = async (file) => {
465
+ try {
466
+ await node_fs_1.promises.access(file);
467
+ return true;
468
+ }
469
+ catch {
470
+ return false;
471
+ }
472
+ };
473
+ /** Write the scaffold into `options.rootDir`. Idempotent unless `force`. */
474
+ async function installScaffold(options) {
475
+ const rootDir = path.resolve(options.rootDir);
476
+ const result = { written: [], appended: [], skipped: [], blocked: [], warnings: [] };
477
+ const resolvedRev = options.rev === undefined ? await resolveInstallRev(rootDir, options.env) : options.rev;
478
+ const files = buildScaffold(options);
479
+ for (const file of files) {
480
+ const absolute = path.join(rootDir, file.relativePath);
481
+ const present = await exists(absolute);
482
+ if (file.mode === 'append') {
483
+ let current = '';
484
+ if (present) {
485
+ try {
486
+ current = await node_fs_1.promises.readFile(absolute, 'utf8');
487
+ }
488
+ catch {
489
+ current = '';
490
+ }
491
+ }
492
+ if (file.marker && current.includes(file.marker)) {
493
+ result.skipped.push(file.relativePath);
494
+ continue;
495
+ }
496
+ if (options.dryRun) {
497
+ result.appended.push(file.relativePath);
498
+ continue;
499
+ }
500
+ await node_fs_1.promises.mkdir(path.dirname(absolute), { recursive: true });
501
+ const separator = current.trim().length ? (current.endsWith('\n') ? '\n' : '\n\n') : '';
502
+ await node_fs_1.promises.appendFile(absolute, `${separator}${file.contents}`, 'utf8');
503
+ result.appended.push(file.relativePath);
504
+ continue;
505
+ }
506
+ if (file.mode === 'merge') {
507
+ let existing = null;
508
+ if (present) {
509
+ try {
510
+ existing = await node_fs_1.promises.readFile(absolute, 'utf8');
511
+ }
512
+ catch {
513
+ existing = null;
514
+ }
515
+ }
516
+ const merged = mergeMcpConfig(existing, { force: options.force, rev: resolvedRev });
517
+ if (merged.error) {
518
+ // Not a `skipped` entry: `--force` cannot repair invalid JSON, so the
519
+ // summary must not suggest it can.
520
+ result.warnings.push(merged.error);
521
+ result.blocked.push(file.relativePath);
522
+ continue;
523
+ }
524
+ if (!merged.changed) {
525
+ result.skipped.push(file.relativePath);
526
+ continue;
527
+ }
528
+ if (options.dryRun) {
529
+ result.written.push(file.relativePath);
530
+ continue;
531
+ }
532
+ await node_fs_1.promises.mkdir(path.dirname(absolute), { recursive: true });
533
+ await node_fs_1.promises.writeFile(absolute, merged.contents, 'utf8');
534
+ result.written.push(file.relativePath);
535
+ continue;
536
+ }
537
+ if (present && !options.force) {
538
+ result.skipped.push(file.relativePath);
539
+ continue;
540
+ }
541
+ if (options.dryRun) {
542
+ result.written.push(file.relativePath);
543
+ continue;
544
+ }
545
+ await node_fs_1.promises.mkdir(path.dirname(absolute), { recursive: true });
546
+ await node_fs_1.promises.writeFile(absolute, file.contents, 'utf8');
547
+ result.written.push(file.relativePath);
548
+ }
549
+ // A repository without a package.json will not be able to `npx github:avivgerz-hue/vibe-shield`
550
+ // as a dev dependency; it still works through npx, so this is only a warning.
551
+ if (!(await exists(path.join(rootDir, 'package.json')))) {
552
+ result.warnings.push('No package.json found — run the gate with `npx github:avivgerz-hue/vibe-shield scan`.');
553
+ }
554
+ if (!(await exists(path.join(rootDir, '.git')))) {
555
+ result.warnings.push('No .git directory found — the workflow only runs once this is a git repository.');
556
+ }
557
+ return result;
558
+ }
559
+ /** Locate the shipped `SKILL.md` (used by `init` to copy the canonical file). */
560
+ async function locateBundledSkill(startDir) {
561
+ let dir = startDir;
562
+ for (let depth = 0; depth < 8; depth += 1) {
563
+ const candidate = path.join(dir, 'SKILL.md');
564
+ const packageJson = path.join(dir, 'package.json');
565
+ if ((await exists(candidate)) && (await exists(packageJson)))
566
+ return candidate;
567
+ const parent = path.dirname(dir);
568
+ if (parent === dir)
569
+ break;
570
+ dir = parent;
571
+ }
572
+ return null;
573
+ }