cc-safe-setup 5.3.0 → 5.4.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.
@@ -0,0 +1,685 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Claude Code Safety Audit & Setup Generator</title>
7
+ <meta name="description" content="Audit your Claude Code settings and generate safety hooks — 100% in your browser. No npm required.">
8
+ <style>
9
+ * { box-sizing: border-box; margin: 0; padding: 0; }
10
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0d1117; color: #c9d1d9; min-height: 100vh; padding: 2rem; }
11
+ .container { max-width: 800px; margin: 0 auto; }
12
+ h1 { font-size: 1.5rem; margin-bottom: 0.5rem; color: #f0f6fc; }
13
+ h2 { font-size: 1.2rem; margin: 1.5rem 0 0.75rem; color: #f0f6fc; }
14
+ h3 { font-size: 1rem; margin: 1rem 0 0.5rem; color: #c9d1d9; }
15
+ .subtitle { color: #8b949e; margin-bottom: 2rem; }
16
+ textarea { width: 100%; height: 180px; background: #161b22; border: 1px solid #30363d; border-radius: 6px; color: #c9d1d9; font-family: monospace; font-size: 13px; padding: 1rem; resize: vertical; }
17
+ textarea::placeholder { color: #484f58; }
18
+ .btn { background: #238636; color: #fff; border: none; padding: 0.6rem 1.2rem; border-radius: 6px; font-size: 0.9rem; cursor: pointer; margin-top: 0.75rem; margin-right: 0.5rem; }
19
+ .btn:hover { background: #2ea043; }
20
+ .btn-secondary { background: #30363d; }
21
+ .btn-secondary:hover { background: #484f58; }
22
+ .btn-sm { padding: 0.3rem 0.6rem; font-size: 0.75rem; margin-top: 0; }
23
+ .results { margin-top: 1.5rem; }
24
+ .score { font-size: 2rem; font-weight: bold; margin: 1rem 0; }
25
+ .score.good { color: #3fb950; }
26
+ .score.mid { color: #d29922; }
27
+ .score.bad { color: #f85149; }
28
+ .risk { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 1rem; margin: 0.5rem 0; }
29
+ .risk .severity { font-weight: bold; margin-right: 0.5rem; }
30
+ .risk .severity.critical, .risk .severity.high { color: #f85149; }
31
+ .risk .severity.medium { color: #d29922; }
32
+ .risk .severity.low { color: #8b949e; }
33
+ .risk .fix { color: #8b949e; font-family: monospace; font-size: 12px; margin-top: 0.5rem; }
34
+ .good-item { color: #3fb950; margin: 0.25rem 0; }
35
+ .privacy { color: #484f58; font-size: 12px; margin-top: 2rem; text-align: center; }
36
+ a { color: #58a6ff; text-decoration: none; }
37
+ .tabs { display: flex; gap: 0; margin-top: 2rem; border-bottom: 1px solid #30363d; }
38
+ .tab { padding: 0.6rem 1.2rem; cursor: pointer; color: #8b949e; border-bottom: 2px solid transparent; font-size: 0.9rem; }
39
+ .tab.active { color: #f0f6fc; border-bottom-color: #f78166; }
40
+ .tab:hover { color: #c9d1d9; }
41
+ .tab-content { display: none; }
42
+ .tab-content.active { display: block; }
43
+ .code-block { position: relative; background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 1rem; margin: 0.5rem 0; overflow-x: auto; }
44
+ .code-block pre { font-family: monospace; font-size: 12px; white-space: pre; color: #c9d1d9; margin: 0; }
45
+ .code-block .copy-btn { position: absolute; top: 0.5rem; right: 0.5rem; background: #30363d; color: #c9d1d9; border: 1px solid #484f58; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 11px; cursor: pointer; }
46
+ .code-block .copy-btn:hover { background: #484f58; }
47
+ .hook-card { background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 1rem; margin: 0.5rem 0; }
48
+ .hook-card summary { cursor: pointer; font-weight: bold; color: #f0f6fc; }
49
+ .hook-card summary:hover { color: #58a6ff; }
50
+ .hook-card .desc { color: #8b949e; font-size: 0.85rem; margin-top: 0.25rem; }
51
+ .setup-steps { counter-reset: step; list-style: none; padding: 0; }
52
+ .setup-steps li { counter-increment: step; padding: 0.75rem 0 0.75rem 2.5rem; position: relative; border-left: 2px solid #30363d; margin-left: 1rem; }
53
+ .setup-steps li::before { content: counter(step); position: absolute; left: -1rem; top: 0.65rem; width: 2rem; height: 2rem; background: #238636; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 0.8rem; font-weight: bold; }
54
+ .setup-steps li:last-child { border-left: 2px solid transparent; }
55
+ .badge-row { display: flex; gap: 0.5rem; margin: 1rem 0; flex-wrap: wrap; }
56
+ .badge { display: inline-block; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: bold; }
57
+ .badge-green { background: #238636; color: #fff; }
58
+ .badge-yellow { background: #9e6a03; color: #fff; }
59
+ .badge-red { background: #da3633; color: #fff; }
60
+ .empty-state { text-align: center; padding: 3rem 1rem; color: #484f58; }
61
+ .empty-state p { margin: 0.5rem 0; }
62
+ </style>
63
+ </head>
64
+ <body>
65
+ <div class="container">
66
+ <h1>Claude Code Safety Audit</h1>
67
+ <p class="subtitle">Audit your setup and generate safety hooks — 100% in your browser. No npm required.</p>
68
+
69
+ <textarea id="settings" placeholder='{
70
+ "permissions": { "allow": ["Bash(git:*)"] },
71
+ "hooks": {
72
+ "PreToolUse": [{ "matcher": "Bash", "hooks": [{"type":"command","command":"..."}] }]
73
+ }
74
+ }'></textarea>
75
+ <br>
76
+ <button class="btn" onclick="runAudit()">Run Audit</button>
77
+ <button class="btn btn-secondary" onclick="generateFresh()">Generate Fresh Setup</button>
78
+
79
+ <div class="results" id="results"></div>
80
+
81
+ <div class="tabs" id="tabs" style="display:none">
82
+ <div class="tab active" onclick="switchTab('audit')">Audit Results</div>
83
+ <div class="tab" onclick="switchTab('fix')">Fix & Generate</div>
84
+ <div class="tab" onclick="switchTab('manual')">Manual Install Guide</div>
85
+ </div>
86
+
87
+ <div class="tab-content active" id="tab-audit"></div>
88
+ <div class="tab-content" id="tab-fix"></div>
89
+ <div class="tab-content" id="tab-manual"></div>
90
+
91
+ <h2 style="margin-top:2rem">Hook Builder</h2>
92
+ <p class="subtitle">Build a custom hook without writing code.</p>
93
+
94
+ <div style="display:flex;gap:1rem;flex-wrap:wrap;margin:.5rem 0">
95
+ <div style="flex:1;min-width:200px">
96
+ <label style="color:#8b949e;font-size:.8rem">What should the hook do?</label>
97
+ <select id="hb-action" style="width:100%;padding:.5rem;background:#161b22;border:1px solid #30363d;border-radius:4px;color:#c9d1d9;margin-top:.25rem">
98
+ <option value="block">Block a command</option>
99
+ <option value="warn">Warn about a command</option>
100
+ <option value="approve">Auto-approve a command</option>
101
+ </select>
102
+ </div>
103
+ <div style="flex:2;min-width:300px">
104
+ <label style="color:#8b949e;font-size:.8rem">Command pattern (regex)</label>
105
+ <input id="hb-pattern" placeholder="e.g. rm\s+-rf, git push --force, npm publish" style="width:100%;padding:.5rem;background:#161b22;border:1px solid #30363d;border-radius:4px;color:#c9d1d9;margin-top:.25rem;font-family:monospace;font-size:.85rem">
106
+ </div>
107
+ </div>
108
+ <div style="margin:.5rem 0">
109
+ <label style="color:#8b949e;font-size:.8rem">Message shown to Claude</label>
110
+ <input id="hb-message" placeholder="e.g. Run tests before publishing" style="width:100%;padding:.5rem;background:#161b22;border:1px solid #30363d;border-radius:4px;color:#c9d1d9;margin-top:.25rem">
111
+ </div>
112
+ <button class="btn" onclick="buildHook()">Generate Hook</button>
113
+
114
+ <div id="hb-result" style="margin-top:1rem"></div>
115
+
116
+ <p class="privacy">100% client-side. Your settings never leave this page. <a href="https://github.com/yurukusa/cc-safe-setup">Source</a> · <a href="https://www.npmjs.com/package/cc-safe-setup">npm</a> · <a href="ecosystem.html">Compare all hook projects</a></p>
117
+ </div>
118
+
119
+ <script>
120
+ // Hook metadata for generation
121
+ const HOOKS = {
122
+ 'destructive-guard': {
123
+ trigger: 'PreToolUse', matcher: 'Bash',
124
+ name: 'Destructive Command Blocker',
125
+ desc: 'Blocks rm -rf /, git reset --hard, git clean -fd, PowerShell Remove-Item'
126
+ },
127
+ 'branch-guard': {
128
+ trigger: 'PreToolUse', matcher: 'Bash',
129
+ name: 'Branch Push Protector',
130
+ desc: 'Blocks push to main/master and force-push on all branches'
131
+ },
132
+ 'secret-guard': {
133
+ trigger: 'PreToolUse', matcher: 'Bash',
134
+ name: 'Secret Leak Prevention',
135
+ desc: 'Blocks git add .env, credential files, git add . with .env present'
136
+ },
137
+ 'comment-strip': {
138
+ trigger: 'PreToolUse', matcher: 'Bash',
139
+ name: 'Bash Comment Stripper',
140
+ desc: 'Strips comments that break permission allowlists'
141
+ },
142
+ 'cd-git-allow': {
143
+ trigger: 'PreToolUse', matcher: 'Bash',
144
+ name: 'cd+git Auto-Approver',
145
+ desc: 'Auto-approves read-only cd + git compound commands'
146
+ },
147
+ 'syntax-check': {
148
+ trigger: 'PostToolUse', matcher: 'Edit|Write',
149
+ name: 'Post-Edit Syntax Validator',
150
+ desc: 'Checks Python, Shell, JSON, YAML, JS syntax after edits'
151
+ },
152
+ 'context-monitor': {
153
+ trigger: 'PostToolUse', matcher: '',
154
+ name: 'Context Window Monitor',
155
+ desc: 'Graduated warnings at 40%/25%/20%/15% context remaining'
156
+ },
157
+ 'api-error-alert': {
158
+ trigger: 'Stop', matcher: '',
159
+ name: 'API Error Alert',
160
+ desc: 'Desktop notification + log when session stops from API errors'
161
+ }
162
+ };
163
+
164
+ let lastAuditState = null;
165
+
166
+ function switchTab(name) {
167
+ document.querySelectorAll('.tab').forEach((t,i) => {
168
+ t.classList.toggle('active', ['audit','fix','manual'][i] === name);
169
+ });
170
+ document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
171
+ document.getElementById('tab-' + name).classList.add('active');
172
+ }
173
+
174
+ function copyText(id) {
175
+ const el = document.getElementById(id);
176
+ const text = el.textContent || el.innerText;
177
+ navigator.clipboard.writeText(text).then(() => {
178
+ const btn = el.closest('.code-block').querySelector('.copy-btn');
179
+ btn.textContent = 'Copied!';
180
+ setTimeout(() => btn.textContent = 'Copy', 1500);
181
+ });
182
+ }
183
+
184
+ function escHtml(s) { return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
185
+
186
+ function runAudit() {
187
+ const raw = document.getElementById('settings').value.trim();
188
+ const el = document.getElementById('results');
189
+
190
+ if (!raw) {
191
+ generateFresh();
192
+ return;
193
+ }
194
+
195
+ let settings;
196
+ try {
197
+ settings = JSON.parse(raw);
198
+ } catch(e) {
199
+ el.innerHTML = '<p style="color:#f85149">Invalid JSON. Paste your settings.json content.</p>';
200
+ return;
201
+ }
202
+
203
+ const {risks, good, score, missing} = analyzeSettings(settings);
204
+ lastAuditState = {settings, risks, good, score, missing};
205
+
206
+ // Show tabs
207
+ document.getElementById('tabs').style.display = 'flex';
208
+
209
+ renderAuditTab(risks, good, score);
210
+ renderFixTab(settings, risks, missing);
211
+ renderManualTab();
212
+ switchTab('audit');
213
+ el.innerHTML = '';
214
+ }
215
+
216
+ function generateFresh() {
217
+ const emptySettings = {};
218
+ const {risks, good, score, missing} = analyzeSettings(emptySettings);
219
+ lastAuditState = {settings: emptySettings, risks, good, score, missing};
220
+
221
+ document.getElementById('tabs').style.display = 'flex';
222
+ document.getElementById('results').innerHTML = '';
223
+
224
+ renderAuditTab(risks, good, score);
225
+ renderFixTab(emptySettings, risks, Object.keys(HOOKS));
226
+ renderManualTab();
227
+ switchTab('fix');
228
+ }
229
+
230
+ function analyzeSettings(settings) {
231
+ const risks = [];
232
+ const good = [];
233
+ const missing = [];
234
+
235
+ const preHooks = settings.hooks?.PreToolUse || [];
236
+ const postHooks = settings.hooks?.PostToolUse || [];
237
+ const stopHooks = settings.hooks?.Stop || [];
238
+ const allCmds = JSON.stringify(preHooks).toLowerCase();
239
+ const postCmds = JSON.stringify(postHooks).toLowerCase();
240
+ const stopCmds = JSON.stringify(stopHooks).toLowerCase();
241
+
242
+ if (preHooks.length === 0) {
243
+ risks.push({ severity: 'CRITICAL', issue: 'No PreToolUse hooks — rm -rf, git reset --hard run unchecked', fix: 'npx cc-safe-setup' });
244
+ missing.push('destructive-guard', 'branch-guard', 'secret-guard', 'comment-strip', 'cd-git-allow');
245
+ } else {
246
+ good.push('PreToolUse hooks (' + preHooks.length + ')');
247
+ if (!allCmds.match(/destructive|guard|block|rm.*rf|reset.*hard/)) {
248
+ risks.push({ severity: 'HIGH', issue: 'No destructive command blocker', fix: 'npx cc-safe-setup' });
249
+ missing.push('destructive-guard');
250
+ } else good.push('Destructive command protection');
251
+
252
+ if (!allCmds.match(/branch|push|main|master/)) {
253
+ risks.push({ severity: 'HIGH', issue: 'No branch push protection', fix: 'npx cc-safe-setup' });
254
+ missing.push('branch-guard');
255
+ } else good.push('Branch push protection');
256
+
257
+ if (!allCmds.match(/secret|env|credential/)) {
258
+ risks.push({ severity: 'HIGH', issue: 'No secret leak protection (.env commits)', fix: 'npx cc-safe-setup' });
259
+ missing.push('secret-guard');
260
+ } else good.push('Secret leak protection');
261
+
262
+ if (!allCmds.match(/comment|strip/)) missing.push('comment-strip');
263
+ if (!allCmds.match(/cd.*git.*allow|auto.*approv/)) missing.push('cd-git-allow');
264
+ }
265
+
266
+ if (!allCmds.match(/database|wipe|migrate|prisma/)) {
267
+ risks.push({ severity: 'MEDIUM', issue: 'No database wipe protection', fix: 'npx cc-safe-setup --install-example block-database-wipe' });
268
+ } else good.push('Database wipe protection');
269
+
270
+ if (postHooks.length === 0) {
271
+ risks.push({ severity: 'MEDIUM', issue: 'No PostToolUse hooks (no syntax checking)', fix: 'npx cc-safe-setup' });
272
+ missing.push('syntax-check', 'context-monitor');
273
+ } else {
274
+ good.push('PostToolUse hooks (' + postHooks.length + ')');
275
+ if (!postCmds.match(/syntax|check|py_compile|node.*check/)) missing.push('syntax-check');
276
+ if (!postCmds.match(/context|monitor|capacity/)) missing.push('context-monitor');
277
+ }
278
+
279
+ if (stopHooks.length === 0) {
280
+ missing.push('api-error-alert');
281
+ } else {
282
+ good.push('Stop hooks (' + stopHooks.length + ')');
283
+ }
284
+
285
+ const allows = settings.permissions?.allow || [];
286
+ if (allows.includes('Bash(*)')) {
287
+ risks.push({ severity: 'MEDIUM', issue: 'Bash(*) in allow list — all commands auto-approved', fix: 'Use specific patterns like Bash(git:*) instead' });
288
+ }
289
+
290
+ const denies = settings.permissions?.deny || [];
291
+ if (denies.length > 0) good.push('Deny rules (' + denies.length + ')');
292
+
293
+ const mode = settings.defaultMode;
294
+ if (mode === 'bypassPermissions') {
295
+ risks.push({ severity: 'HIGH', issue: 'bypassPermissions — all permission checks disabled', fix: 'Use dontAsk with hooks instead' });
296
+ } else if (mode === 'dontAsk') {
297
+ good.push('dontAsk mode (auto-approve, hooks still run)');
298
+ }
299
+
300
+ if (settings.sandbox?.enabled === false) {
301
+ risks.push({ severity: 'MEDIUM', issue: 'Sandbox disabled', fix: 'Re-enable or use excludedCommands' });
302
+ }
303
+
304
+ const score = Math.max(0, 100 - risks.reduce((s, r) => {
305
+ if (r.severity === 'CRITICAL') return s + 30;
306
+ if (r.severity === 'HIGH') return s + 20;
307
+ if (r.severity === 'MEDIUM') return s + 10;
308
+ return s + 5;
309
+ }, 0));
310
+
311
+ return {risks, good, score, missing: [...new Set(missing)]};
312
+ }
313
+
314
+ function renderAuditTab(risks, good, score) {
315
+ const scoreClass = score >= 80 ? 'good' : score >= 50 ? 'mid' : 'bad';
316
+ let html = '<div class="score ' + scoreClass + '">Safety Score: ' + score + '/100</div>';
317
+
318
+ if (good.length > 0) {
319
+ html += '<h3 style="color:#3fb950">Working</h3>';
320
+ html += good.map(g => '<div class="good-item">' + g + '</div>').join('');
321
+ }
322
+
323
+ if (risks.length > 0) {
324
+ html += '<h3 style="margin-top:1rem">Risks (' + risks.length + ')</h3>';
325
+ html += risks.map(r =>
326
+ '<div class="risk"><span class="severity ' + r.severity.toLowerCase() + '">[' + r.severity + ']</span> ' + escHtml(r.issue) +
327
+ '<div class="fix">Fix: ' + escHtml(r.fix) + '</div></div>'
328
+ ).join('');
329
+ }
330
+
331
+ if (risks.length === 0) {
332
+ html += '<p style="color:#3fb950;margin-top:1rem">No risks detected. Your setup looks solid.</p>';
333
+ }
334
+
335
+ document.getElementById('tab-audit').innerHTML = html;
336
+ }
337
+
338
+ function renderFixTab(settings, risks, missing) {
339
+ if (missing.length === 0) {
340
+ document.getElementById('tab-fix').innerHTML = '<p style="color:#3fb950;margin-top:1rem">All 8 hooks detected. Nothing to add.</p>';
341
+ return;
342
+ }
343
+
344
+ // Generate the settings.json patch
345
+ const patch = generateSettingsPatch(settings, missing);
346
+ const installScript = generateInstallScript(missing);
347
+
348
+ let html = '<h2>Quick Fix</h2>';
349
+ html += '<p style="color:#8b949e;margin-bottom:1rem">Missing ' + missing.length + ' hook(s). Choose your install method:</p>';
350
+
351
+ // Option 1: npx
352
+ html += '<h3>Option 1: One command (recommended)</h3>';
353
+ html += '<div class="code-block"><button class="copy-btn" onclick="copyText(\'npx-cmd\')">Copy</button><pre id="npx-cmd">npx cc-safe-setup</pre></div>';
354
+
355
+ // Option 2: Generated settings.json
356
+ html += '<h3>Option 2: Copy settings.json patch</h3>';
357
+ html += '<p style="color:#8b949e;font-size:0.85rem;margin:0.25rem 0">Merge this into your <code>~/.claude/settings.json</code>:</p>';
358
+ html += '<div class="code-block"><button class="copy-btn" onclick="copyText(\'settings-patch\')">Copy</button><pre id="settings-patch">' + escHtml(JSON.stringify(patch, null, 2)) + '</pre></div>';
359
+
360
+ // Option 3: Full install script
361
+ html += '<h3>Option 3: Shell script (no npm needed)</h3>';
362
+ html += '<p style="color:#8b949e;font-size:0.85rem;margin:0.25rem 0">Run this in your terminal. Creates hook scripts and updates settings.json:</p>';
363
+ html += '<div class="code-block" style="max-height:400px;overflow-y:auto"><button class="copy-btn" onclick="copyText(\'install-script\')">Copy</button><pre id="install-script">' + escHtml(installScript) + '</pre></div>';
364
+
365
+ // Hook details
366
+ html += '<h3 style="margin-top:1.5rem">Hooks being added</h3>';
367
+ for (const id of missing) {
368
+ const h = HOOKS[id];
369
+ if (!h) continue;
370
+ html += '<div class="hook-card"><summary>' + escHtml(h.name) + '</summary>';
371
+ html += '<div class="desc">' + escHtml(h.desc) + ' &middot; Trigger: ' + h.trigger + (h.matcher ? ' &middot; Matcher: ' + h.matcher : '') + '</div></div>';
372
+ }
373
+
374
+ document.getElementById('tab-fix').innerHTML = html;
375
+ }
376
+
377
+ function renderManualTab() {
378
+ let html = '<h2>Manual Installation Guide</h2>';
379
+ html += '<p style="color:#8b949e;margin-bottom:1rem">Step-by-step for setting up Claude Code safety hooks without any tools.</p>';
380
+
381
+ html += '<ol class="setup-steps">';
382
+ html += '<li><strong>Create the hooks directory</strong><div class="code-block"><pre>mkdir -p ~/.claude/hooks</pre></div></li>';
383
+ html += '<li><strong>Create hook scripts</strong><br><span style="color:#8b949e;font-size:0.85rem">Use the "Fix & Generate" tab to get the script content, or run <code>npx cc-safe-setup --dry-run</code> to preview.</span></li>';
384
+ html += '<li><strong>Make scripts executable</strong><div class="code-block"><pre>chmod +x ~/.claude/hooks/*.sh</pre></div></li>';
385
+ html += '<li><strong>Update settings.json</strong><br><span style="color:#8b949e;font-size:0.85rem">Add the hook entries from "Fix & Generate" tab to <code>~/.claude/settings.json</code>.</span></li>';
386
+ html += '<li><strong>Restart Claude Code</strong><br><span style="color:#8b949e;font-size:0.85rem">Close and reopen Claude Code. Hooks activate on restart.</span></li>';
387
+ html += '<li><strong>Verify</strong><div class="code-block"><pre>npx cc-safe-setup --verify</pre></div><span style="color:#8b949e;font-size:0.85rem">Or test manually: try <code>rm -rf /</code> in Claude Code — the hook should block it.</span></li>';
388
+ html += '</ol>';
389
+
390
+ html += '<h3 style="margin-top:1.5rem">Requirements</h3>';
391
+ html += '<ul style="margin-left:1.5rem;color:#8b949e;font-size:0.85rem">';
392
+ html += '<li><code>jq</code> — for JSON parsing in hooks (<code>brew install jq</code> / <code>apt install jq</code>)</li>';
393
+ html += '<li><code>bash</code> — hooks are bash scripts</li>';
394
+ html += '<li>Claude Code v2.1+ — for hooks support</li>';
395
+ html += '</ul>';
396
+
397
+ html += '<h3 style="margin-top:1.5rem">Hooks Reference</h3>';
398
+ for (const [id, h] of Object.entries(HOOKS)) {
399
+ html += '<div class="hook-card"><details><summary>' + escHtml(h.name) + ' <span style="color:#484f58;font-weight:normal;font-size:0.8rem">(' + id + '.sh)</span></summary>';
400
+ html += '<div class="desc" style="margin-top:0.5rem">' + escHtml(h.desc) + '</div>';
401
+ html += '<div style="margin-top:0.25rem;font-size:0.8rem;color:#484f58">Trigger: ' + h.trigger + (h.matcher ? ' | Matcher: ' + h.matcher : ' | Matcher: (all)') + '</div>';
402
+ html += '</details></div>';
403
+ }
404
+
405
+ document.getElementById('tab-manual').innerHTML = html;
406
+ }
407
+
408
+ function generateSettingsPatch(existing, missing) {
409
+ const patch = JSON.parse(JSON.stringify(existing || {}));
410
+ if (!patch.hooks) patch.hooks = {};
411
+ if (!patch.hooks.PreToolUse) patch.hooks.PreToolUse = [];
412
+ if (!patch.hooks.PostToolUse) patch.hooks.PostToolUse = [];
413
+ if (!patch.hooks.Stop) patch.hooks.Stop = [];
414
+
415
+ for (const id of missing) {
416
+ const h = HOOKS[id];
417
+ if (!h) continue;
418
+ const entry = {
419
+ matcher: h.matcher,
420
+ hooks: [{ type: 'command', command: '~/.claude/hooks/' + id + '.sh' }]
421
+ };
422
+ if (h.trigger === 'PreToolUse') patch.hooks.PreToolUse.push(entry);
423
+ else if (h.trigger === 'PostToolUse') patch.hooks.PostToolUse.push(entry);
424
+ else if (h.trigger === 'Stop') patch.hooks.Stop.push(entry);
425
+ }
426
+
427
+ // Clean empty arrays
428
+ if (patch.hooks.PreToolUse.length === 0) delete patch.hooks.PreToolUse;
429
+ if (patch.hooks.PostToolUse.length === 0) delete patch.hooks.PostToolUse;
430
+ if (patch.hooks.Stop.length === 0) delete patch.hooks.Stop;
431
+
432
+ return patch;
433
+ }
434
+
435
+ function generateInstallScript(missing) {
436
+ let script = '#!/bin/bash\n';
437
+ script += '# Claude Code Safety Hooks — Generated by https://yurukusa.github.io/cc-safe-setup/\n';
438
+ script += '# Run: bash install-safety-hooks.sh\n\n';
439
+ script += 'set -euo pipefail\n\n';
440
+ script += 'HOOK_DIR="$HOME/.claude/hooks"\n';
441
+ script += 'SETTINGS="$HOME/.claude/settings.json"\n\n';
442
+ script += '# Check jq\n';
443
+ script += 'if ! command -v jq &>/dev/null; then\n';
444
+ script += ' echo "Error: jq is required. Install with: brew install jq / apt install jq"\n';
445
+ script += ' exit 1\n';
446
+ script += 'fi\n\n';
447
+ script += 'mkdir -p "$HOOK_DIR"\n\n';
448
+
449
+ // Write each hook script
450
+ for (const id of missing) {
451
+ const h = HOOKS[id];
452
+ if (!h) continue;
453
+ script += '# --- ' + h.name + ' ---\n';
454
+ script += 'cat > "$HOOK_DIR/' + id + '.sh" << \'HOOKEOF\'\n';
455
+ script += getMinimalHookScript(id);
456
+ script += '\nHOOKEOF\n';
457
+ script += 'chmod +x "$HOOK_DIR/' + id + '.sh"\n';
458
+ script += 'echo "Installed: ' + id + '.sh"\n\n';
459
+ }
460
+
461
+ // Update settings.json
462
+ script += '# --- Update settings.json ---\n';
463
+ script += 'if [ ! -f "$SETTINGS" ]; then\n';
464
+ script += ' echo "{}" > "$SETTINGS"\n';
465
+ script += 'fi\n\n';
466
+
467
+ // Build jq command to merge hooks
468
+ const pre = missing.filter(id => HOOKS[id]?.trigger === 'PreToolUse');
469
+ const post = missing.filter(id => HOOKS[id]?.trigger === 'PostToolUse');
470
+ const stop = missing.filter(id => HOOKS[id]?.trigger === 'Stop');
471
+
472
+ if (pre.length > 0) {
473
+ script += '# Add PreToolUse hooks\n';
474
+ for (const id of pre) {
475
+ const h = HOOKS[id];
476
+ script += 'jq \'.hooks.PreToolUse += [{"matcher":"' + h.matcher + '","hooks":[{"type":"command","command":"\'$HOOK_DIR\'/' + id + '.sh"}]}]\' "$SETTINGS" > /tmp/cc-settings-tmp.json && mv /tmp/cc-settings-tmp.json "$SETTINGS"\n';
477
+ }
478
+ script += '\n';
479
+ }
480
+
481
+ if (post.length > 0) {
482
+ script += '# Add PostToolUse hooks\n';
483
+ for (const id of post) {
484
+ const h = HOOKS[id];
485
+ script += 'jq \'.hooks.PostToolUse += [{"matcher":"' + h.matcher + '","hooks":[{"type":"command","command":"\'$HOOK_DIR\'/' + id + '.sh"}]}]\' "$SETTINGS" > /tmp/cc-settings-tmp.json && mv /tmp/cc-settings-tmp.json "$SETTINGS"\n';
486
+ }
487
+ script += '\n';
488
+ }
489
+
490
+ if (stop.length > 0) {
491
+ script += '# Add Stop hooks\n';
492
+ for (const id of stop) {
493
+ script += 'jq \'.hooks.Stop += [{"matcher":"","hooks":[{"type":"command","command":"\'$HOOK_DIR\'/' + id + '.sh"}]}]\' "$SETTINGS" > /tmp/cc-settings-tmp.json && mv /tmp/cc-settings-tmp.json "$SETTINGS"\n';
494
+ }
495
+ script += '\n';
496
+ }
497
+
498
+ script += 'echo ""\n';
499
+ script += 'echo "Done. ' + missing.length + ' safety hooks installed."\n';
500
+ script += 'echo "Restart Claude Code to activate."\n';
501
+
502
+ return script;
503
+ }
504
+
505
+ function getMinimalHookScript(id) {
506
+ // Minimal but functional versions of each hook
507
+ const scripts = {
508
+ 'destructive-guard': `#!/bin/bash
509
+ INPUT=$(cat)
510
+ COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null)
511
+ [ -z "$COMMAND" ] && exit 0
512
+ [ "\${CC_ALLOW_DESTRUCTIVE:-0}" = "1" ] && exit 0
513
+ SAFE_DIRS="\${CC_SAFE_DELETE_DIRS:-node_modules:dist:build:.cache:__pycache__:coverage:.next}"
514
+ # rm -rf on sensitive paths
515
+ if echo "$COMMAND" | grep -qE 'rm\\s+(-[rf]+\\s+)*(\\/$|\\/\\s|\\/home|\\/etc|\\/usr|~\\/|~\\s*$|\\.\\.\\/|\\.\\s*$)'; then
516
+ SAFE=0
517
+ IFS=':' read -ra D <<< "$SAFE_DIRS"
518
+ for d in "\${D[@]}"; do echo "$COMMAND" | grep -qE "rm\\s+.*\${d}\\s*$" && SAFE=1 && break; done
519
+ [ "$SAFE" = 0 ] && echo "BLOCKED: rm on sensitive path. Command: $COMMAND" >&2 && exit 2
520
+ fi
521
+ # git reset --hard
522
+ echo "$COMMAND" | grep -qE '(^|;|&&)\\s*git\\s+reset\\s+--hard' && echo "BLOCKED: git reset --hard" >&2 && exit 2
523
+ # git clean
524
+ echo "$COMMAND" | grep -qE '(^|;|&&)\\s*git\\s+clean\\s+-[a-z]*[fd]' && echo "BLOCKED: git clean" >&2 && exit 2
525
+ # PowerShell destructive
526
+ echo "$COMMAND" | grep -qiE 'Remove-Item.*-Recurse.*-Force|rd\\s+/s\\s+/q' && echo "BLOCKED: Destructive PowerShell command" >&2 && exit 2
527
+ # git checkout --force
528
+ echo "$COMMAND" | grep -qE '(^|;|&&)\\s*git\\s+(checkout|switch)\\s+.*(--force|-f\\b)' && echo "BLOCKED: git checkout --force" >&2 && exit 2
529
+ exit 0`,
530
+
531
+ 'branch-guard': `#!/bin/bash
532
+ INPUT=$(cat)
533
+ COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null)
534
+ [ -z "$COMMAND" ] && exit 0
535
+ echo "$COMMAND" | grep -qE '^\\s*git\\s+push' || exit 0
536
+ # Force push
537
+ if [ "\${CC_ALLOW_FORCE_PUSH:-0}" != "1" ]; then
538
+ echo "$COMMAND" | grep -qE 'git\\s+push\\s+.*(-f\\b|--force\\b|--force-with-lease)' && echo "BLOCKED: Force push" >&2 && exit 2
539
+ fi
540
+ # Protected branches
541
+ PROTECTED="\${CC_PROTECT_BRANCHES:-main:master}"
542
+ IFS=':' read -ra B <<< "$PROTECTED"
543
+ for b in "\${B[@]}"; do
544
+ echo "$COMMAND" | grep -qwE "origin\\s+\${b}|\${b}\\s|\${b}$" && echo "BLOCKED: Push to protected branch $b" >&2 && exit 2
545
+ done
546
+ exit 0`,
547
+
548
+ 'secret-guard': `#!/bin/bash
549
+ INPUT=$(cat)
550
+ COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null)
551
+ [ -z "$COMMAND" ] && exit 0
552
+ echo "$COMMAND" | grep -qE '^\\s*git\\s+add' || exit 0
553
+ # Direct .env staging
554
+ echo "$COMMAND" | grep -qiE 'git\\s+add\\s+.*\\.env(\\s|$|\\.)' && echo "BLOCKED: .env file staging" >&2 && exit 2
555
+ # Credential files
556
+ echo "$COMMAND" | grep -qiE 'git\\s+add\\s+.*(credentials|\\.pem|\\.key|\\.p12|id_rsa|id_ed25519)' && echo "BLOCKED: Credential file staging" >&2 && exit 2
557
+ # git add . with .env present
558
+ if echo "$COMMAND" | grep -qE 'git\\s+add\\s+(-A|--all|\\.)(\\s|$)'; then
559
+ [ -f ".env" ] || [ -f ".env.local" ] && echo "BLOCKED: git add . with .env present" >&2 && exit 2
560
+ fi
561
+ exit 0`,
562
+
563
+ 'comment-strip': `#!/bin/bash
564
+ INPUT=$(cat)
565
+ COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null)
566
+ [ -z "$COMMAND" ] && exit 0
567
+ CLEAN=$(echo "$COMMAND" | sed '/^[[:space:]]*#/d; /^[[:space:]]*$/d')
568
+ [ "$CLEAN" = "$COMMAND" ] && exit 0
569
+ [ -z "$CLEAN" ] && exit 0
570
+ jq -n --arg cmd "$CLEAN" '{"hookSpecificOutput":{"hookEventName":"PreToolUse","updatedInput":{"command":$cmd}}}'`,
571
+
572
+ 'cd-git-allow': `#!/bin/bash
573
+ INPUT=$(cat)
574
+ COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty' 2>/dev/null)
575
+ [ -z "$COMMAND" ] && exit 0
576
+ echo "$COMMAND" | grep -qE '^\\s*cd\\s+.*&&\\s*git\\s' || exit 0
577
+ GIT_CMD=$(echo "$COMMAND" | grep -oP '&&\\s*git\\s+\\K\\S+')
578
+ for safe in log diff status branch show rev-parse tag remote; do
579
+ [ "$GIT_CMD" = "$safe" ] && jq -n '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","permissionDecisionReason":"cd+git auto-approved"}}' && exit 0
580
+ done
581
+ exit 0`,
582
+
583
+ 'syntax-check': `#!/bin/bash
584
+ INPUT=$(cat)
585
+ FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty' 2>/dev/null)
586
+ [ -z "$FILE_PATH" ] || [ ! -f "$FILE_PATH" ] && exit 0
587
+ EXT="\${FILE_PATH##*.}"
588
+ case "$EXT" in
589
+ py) python3 -m py_compile "$FILE_PATH" 2>&1 || echo "SYNTAX ERROR (Python): $FILE_PATH" >&2 ;;
590
+ sh|bash) bash -n "$FILE_PATH" 2>&1 || echo "SYNTAX ERROR (Shell): $FILE_PATH" >&2 ;;
591
+ json) command -v jq &>/dev/null && { jq empty "$FILE_PATH" 2>&1 || echo "SYNTAX ERROR (JSON): $FILE_PATH" >&2; } ;;
592
+ js) command -v node &>/dev/null && { node --check "$FILE_PATH" 2>&1 || echo "SYNTAX ERROR (JS): $FILE_PATH" >&2; } ;;
593
+ esac
594
+ exit 0`,
595
+
596
+ 'context-monitor': `#!/bin/bash
597
+ COUNTER_FILE="/tmp/cc-context-monitor-count"
598
+ COUNT=$(cat "$COUNTER_FILE" 2>/dev/null || echo 0)
599
+ COUNT=$((COUNT + 1))
600
+ echo "$COUNT" > "$COUNTER_FILE"
601
+ [ $((COUNT % 5)) -ne 0 ] && exit 0
602
+ # Estimate context usage from tool call count (~180 calls = full context)
603
+ PCT=$(( 100 - (COUNT * 100 / 180) ))
604
+ [ "$PCT" -lt 0 ] && PCT=0
605
+ if [ "$PCT" -le 15 ]; then
606
+ echo "EMERGENCY: Context ~\${PCT}% remaining. Run /compact NOW." >&2
607
+ elif [ "$PCT" -le 25 ]; then
608
+ echo "WARNING: Context ~\${PCT}% remaining. Finish current task." >&2
609
+ elif [ "$PCT" -le 40 ]; then
610
+ echo "CAUTION: Context ~\${PCT}% remaining." >&2
611
+ fi
612
+ exit 0`,
613
+
614
+ 'api-error-alert': `#!/bin/bash
615
+ INPUT=$(cat)
616
+ REASON=$(echo "$INPUT" | jq -r '.stop_reason // "unknown"' 2>/dev/null)
617
+ [ "$REASON" = "user" ] || [ "$REASON" = "normal" ] || [ -z "$REASON" ] && exit 0
618
+ LOG="\${CC_ERROR_ALERT_LOG:-$HOME/.claude/session-errors.log}"
619
+ mkdir -p "$(dirname "$LOG")" 2>/dev/null
620
+ echo "[$(date -Iseconds)] Session stopped: reason=$REASON" >> "$LOG"
621
+ exit 0`
622
+ };
623
+
624
+ return scripts[id] || '#!/bin/bash\nexit 0';
625
+ }
626
+
627
+ function buildHook() {
628
+ const action = document.getElementById('hb-action').value;
629
+ const pattern = document.getElementById('hb-pattern').value.trim();
630
+ const message = document.getElementById('hb-message').value.trim() || 'Blocked by hook';
631
+ const el = document.getElementById('hb-result');
632
+
633
+ if (!pattern) { el.innerHTML = '<p style="color:#f85149">Enter a command pattern.</p>'; return; }
634
+
635
+ let script = '#!/bin/bash\n';
636
+ script += 'INPUT=$(cat)\n';
637
+ script += 'COMMAND=$(echo "$INPUT" | jq -r \'.tool_input.command // empty\' 2>/dev/null)\n';
638
+ script += '[ -z "$COMMAND" ] && exit 0\n\n';
639
+
640
+ if (action === 'block') {
641
+ script += 'if echo "$COMMAND" | grep -qE \'' + pattern.replace(/'/g, "'\\''") + '\'; then\n';
642
+ script += ' echo "BLOCKED: ' + message.replace(/"/g, '\\"') + '" >&2\n';
643
+ script += ' echo "Command: $COMMAND" >&2\n';
644
+ script += ' exit 2\n';
645
+ script += 'fi\n';
646
+ } else if (action === 'warn') {
647
+ script += 'if echo "$COMMAND" | grep -qE \'' + pattern.replace(/'/g, "'\\''") + '\'; then\n';
648
+ script += ' echo "WARNING: ' + message.replace(/"/g, '\\"') + '" >&2\n';
649
+ script += ' echo "Command: $COMMAND" >&2\n';
650
+ script += 'fi\n';
651
+ } else if (action === 'approve') {
652
+ script += 'if echo "$COMMAND" | grep -qE \'' + pattern.replace(/'/g, "'\\''") + '\'; then\n';
653
+ script += ' jq -n \'{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","permissionDecisionReason":"' + message.replace(/"/g, '\\"') + '"}}\'\n';
654
+ script += 'fi\n';
655
+ }
656
+ script += 'exit 0';
657
+
658
+ const settings = {
659
+ hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: '~/.claude/hooks/custom-hook.sh' }] }] }
660
+ };
661
+
662
+ el.innerHTML = '<h3>Hook Script</h3>' +
663
+ '<div class="code-block"><button class="copy-btn" onclick="copyText(\'hb-script\')">Copy</button><pre id="hb-script">' + escHtml(script) + '</pre></div>' +
664
+ '<h3>settings.json entry</h3>' +
665
+ '<div class="code-block"><button class="copy-btn" onclick="copyText(\'hb-settings\')">Copy</button><pre id="hb-settings">' + escHtml(JSON.stringify(settings, null, 2)) + '</pre></div>' +
666
+ '<p style="color:#8b949e;font-size:.8rem;margin-top:.5rem">Save the script as <code>~/.claude/hooks/custom-hook.sh</code>, run <code>chmod +x</code>, and merge the settings entry.</p>';
667
+ }
668
+
669
+ // Auto-load from URL parameter: ?config=base64encodedJSON
670
+ (function() {
671
+ const params = new URLSearchParams(window.location.search);
672
+ const config = params.get('config');
673
+ if (config) {
674
+ try {
675
+ const json = atob(config);
676
+ document.getElementById('settings').value = json;
677
+ runAudit();
678
+ } catch(e) {
679
+ console.error('Invalid config parameter');
680
+ }
681
+ }
682
+ })();
683
+ </script>
684
+ </body>
685
+ </html>