Skip to content

Commit 0f5f177

Browse files
MrPickeringclaude
andauthored
UI: stop tracking a file and surface git history findings (#8)
Fixing a git-tracked or historically-leaked secret meant dropping to a terminal even though the UI already detected it. Adds a "stop tracking" button (git rm --cached + gitignore) for TRACKED files, and a per-project "scan git history" button that surfaces the deep history scan the CLI's protect/history commands already do but the UI never called — including secrets in files deleted long ago, which the fast per-file chip can't see. Session-Id: 25b49055-f165-4d21-bec2-c530592f3ffe Agent: claude-code Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 2aa6b9b commit 0f5f177

4 files changed

Lines changed: 153 additions & 3 deletions

File tree

‎src/scanner.js‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,14 @@ export function addGitignoreEntry(projectPath, fileName) {
349349
return true;
350350
}
351351

352+
// Removes a file from git's index without touching the working copy, then makes sure it can't
353+
// be re-added by accident. Does NOT touch history — the remedy text callers show must say so.
354+
export function untrackFile(projectPath, filePath) {
355+
execFileSync('git', ['rm', '--cached', '--ignore-unmatch', filePath], { cwd: projectPath, stdio: 'pipe' });
356+
const gitignoreAdded = addGitignoreEntry(projectPath, path.basename(filePath));
357+
return { gitignoreAdded };
358+
}
359+
352360
function groupByProject(files) {
353361
const projects = new Map();
354362
for (const file of files) {

‎src/server.js‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ import { randomBytes, timingSafeEqual } from 'node:crypto';
2626
import fs from 'node:fs';
2727
import path from 'node:path';
2828
import { fileURLToPath } from 'node:url';
29-
import { scanDirectories, addGitignoreEntry, detectSensitiveKeys } from './scanner.js';
29+
import { scanDirectories, addGitignoreEntry, detectSensitiveKeys, untrackFile } from './scanner.js';
30+
import { scanHistories, historyFindings } from './history.js';
3031

3132
const __dirname = path.dirname(fileURLToPath(import.meta.url));
3233

@@ -239,10 +240,18 @@ export function createEnviewServer({ roots, port = 4174, token, maxDepth = 4 })
239240
// Only files discovered by a scan may be touched. A path arriving in a request is checked
240241
// against this set rather than sanitised — an allowlist cannot be escaped by clever encoding.
241242
let allowed = new Set();
243+
// Same principle for project directories: the history endpoint shells out to `git` inside a
244+
// client-supplied path, so that path must be one this scan actually found, not merely resolved.
245+
// Includes the configured roots themselves, not just discovered project paths — a repo whose
246+
// only .env was deleted long ago has no current file to be discovered by, but its history is
247+
// exactly what this endpoint exists to find (mirrors the CLI's `history` command, which unions
248+
// discovered project paths with the roots for the same reason).
249+
let allowedProjects = new Set();
242250

243251
const refresh = () => {
244252
const projects = scanDirectories(roots, { maxDepth });
245253
allowed = new Set(projects.flatMap((p) => p.files.map((f) => path.resolve(f.filePath))));
254+
allowedProjects = new Set([...projects.map((p) => p.path), ...roots].map((p) => path.resolve(p)));
246255
return projects;
247256
};
248257
refresh();
@@ -253,6 +262,12 @@ export function createEnviewServer({ roots, port = 4174, token, maxDepth = 4 })
253262
return allowed.has(resolved) ? resolved : null;
254263
};
255264

265+
const resolveAllowedProject = (projectPath) => {
266+
if (!projectPath) return null;
267+
const resolved = path.resolve(String(projectPath));
268+
return allowedProjects.has(resolved) ? resolved : null;
269+
};
270+
256271
const server = createServer(async (request, response) => {
257272
const url = new URL(request.url, `http://127.0.0.1:${port}`);
258273

@@ -355,10 +370,26 @@ export function createEnviewServer({ roots, port = 4174, token, maxDepth = 4 })
355370
json(response, 200, { ok: true, added });
356371
return;
357372
}
373+
if (body.action === 'untrack') {
374+
const result = untrackFile(path.dirname(filePath), filePath);
375+
json(response, 200, { ok: true, untracked: true, ...result });
376+
return;
377+
}
358378
json(response, 400, { error: `unknown action ${body.action}` });
359379
return;
360380
}
361381

382+
// Deliberately on-demand and scoped to one project, not folded into /api/projects: this
383+
// walks `git log --all`, the explicitly slow path (see history.js) — fine for one repo on
384+
// a click, not fine for every repo on every page load.
385+
if (url.pathname === '/api/history' && request.method === 'GET') {
386+
const projectPath = resolveAllowedProject(url.searchParams.get('path'));
387+
if (!projectPath) { json(response, 404, { error: 'unknown project' }); return; }
388+
const histories = scanHistories([projectPath], { detectSensitive: detectSensitiveKeys });
389+
json(response, 200, { findings: historyFindings(histories) });
390+
return;
391+
}
392+
362393
json(response, 404, { error: 'not found' });
363394
} catch (error) {
364395
json(response, 500, { error: error.message });

‎src/ui/index.html‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,11 @@
5555
background:var(--panel2);border:1px solid var(--line);border-radius:10px;padding:10px 16px;font:12px var(--mono);pointer-events:none;z-index:50}
5656
#toast.show{opacity:1;transform:translateX(-50%) translateY(0)}
5757
.banner{max-width:1240px;margin:0 auto 18px;padding:12px 16px;border:1px solid rgba(251,191,36,.3);background:rgba(251,191,36,.06);border-radius:10px;color:#e8d9ae;font-size:12.5px}
58+
.path{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
59+
.history-panel{margin:0 0 14px}
60+
.history-panel:empty{display:none}
61+
.history-finding{padding:10px 0;border-bottom:1px solid var(--line)}
62+
.history-finding:last-child{border-bottom:0}
5863
</style>
5964
</head>
6065
<body>
@@ -141,7 +146,8 @@ <h1>🦅 en<span>view</span></h1>
141146
app.innerHTML = data.projects.map((p) => `
142147
<section class="project">
143148
<h2>${esc(p.name)}</h2>
144-
<p class="path">${esc(p.path)}</p>
149+
<p class="path">${esc(p.path)} <button data-act="scan-history" data-project="${esc(p.path)}">scan git history</button></p>
150+
<div class="history-panel"></div>
145151
${p.files.map((f) => `
146152
<div class="file">
147153
<div class="file-head">
@@ -169,6 +175,7 @@ <h2>${esc(p.name)}</h2>
169175
<button data-act="add" class="primary">+ add variable</button>
170176
${!f.hasExample ? '<button data-act="generate-example">generate .env.example</button>' : ""}
171177
${f.inGitRepo && !f.gitIgnored ? '<button data-act="gitignore">add to .gitignore</button>' : ""}
178+
${f.gitTracked ? '<button data-act="untrack" class="danger" title="git rm --cached + gitignore. Does not touch history — rotate the values too.">stop tracking</button>' : ""}
172179
</div>
173180
</div>`).join("")}
174181
</section>`).join("");
@@ -245,10 +252,37 @@ <h2>${esc(p.name)}</h2>
245252
const act = button.dataset.act;
246253
const row = button.closest(".row");
247254
const foot = button.closest(".file-foot");
248-
const file = (row || foot).dataset.file;
255+
// scan-history is scoped to the whole project, not a file — neither row nor foot applies.
256+
const file = (row || foot)?.dataset.file;
249257
const key = row?.dataset.key;
250258

251259
try {
260+
if (act === "scan-history") {
261+
const panel = button.closest(".project").querySelector(".history-panel");
262+
button.disabled = true;
263+
button.textContent = "scanning…";
264+
try {
265+
const { findings } = await api(`/api/history?path=${encodeURIComponent(button.dataset.project)}`);
266+
panel.innerHTML = findings.length
267+
? findings.map((f) => `<div class="history-finding">
268+
<b>${esc(f.file)}</b> ${f.stillTracked ? '<span class="chip bad">still tracked</span>' : '<span class="chip warn">removed, still in history</span>'}
269+
${f.keys.length ? `<div class="k">${f.keys.map(esc).join(", ")}</div>` : ""}
270+
<p class="note">${esc(f.remedy)}</p>
271+
</div>`).join("")
272+
: '<p class="note">No risky paths found in this repo’s history.</p>';
273+
} finally {
274+
button.disabled = false;
275+
button.textContent = "scan git history";
276+
}
277+
return;
278+
}
279+
if (act === "untrack") {
280+
if (!confirm(`Untrack ${file.split(/[\\/]/).pop()} from git?\n\nRuns "git rm --cached" and adds it to .gitignore. This does NOT remove it from git history — rotate any real secrets in this file regardless.`)) return;
281+
const result = await api("/api/action", { method: "POST", body: JSON.stringify({ file, action: "untrack" }) });
282+
toast(result.gitignoreAdded ? "untracked + added to .gitignore" : "untracked");
283+
load();
284+
return;
285+
}
252286
if (act === "reveal") {
253287
const cell = row.querySelector(".v");
254288
if (cell.classList.contains("shown")) {

‎test/run.mjs‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,46 @@ check(".env.example keeps keys", /^API_KEY=$/m.test(example), example);
134134
check(".env.example strips every value", !example.includes("sk-test") && !example.includes("hello world"), example);
135135
check(".env.example keeps comments", example.includes("# a comment that must survive"));
136136

137+
// ---------------------------------------------------------------- untrack
138+
console.log("\n--- untrack ---");
139+
{
140+
const { execFileSync } = await import("node:child_process");
141+
const repo = mkdtempSync(join(tmpdir(), "enview-untrack-"));
142+
const run = (...args) => execFileSync("git", args, { cwd: repo, stdio: "pipe" });
143+
run("init", "-q");
144+
run("config", "user.email", "t@t.test");
145+
run("config", "user.name", "t");
146+
writeFileSync(join(repo, ".env"), "SECRET=still-tracked-value\n"); // gitleaks:allow — synthetic fixture
147+
run("add", "-A");
148+
run("commit", "-qm", "oops, committed a secret");
149+
150+
const isTracked = () => {
151+
try { execFileSync("git", ["ls-files", "--error-unmatch", ".env"], { cwd: repo, stdio: "pipe" }); return true; }
152+
catch { return false; }
153+
};
154+
check("fixture starts tracked", isTracked());
155+
156+
const inRepo = await startEnviewUi({ roots: [repo], port: 4184, maxDepth: 2 });
157+
const untrackCall = (path, opts = {}) => fetch(`http://127.0.0.1:4184${path}`, {
158+
...opts,
159+
headers: { "x-enview-token": inRepo.token, "content-type": "application/json", ...(opts.headers || {}) },
160+
});
161+
162+
const res = await (await untrackCall("/api/action", {
163+
method: "POST",
164+
body: JSON.stringify({ file: join(repo, ".env"), action: "untrack" }),
165+
})).json();
166+
check("untrack reports ok", res.ok === true, JSON.stringify(res));
167+
check("untrack adds to .gitignore", res.gitignoreAdded === true);
168+
check("file no longer tracked by git", !isTracked());
169+
check(".gitignore contains the filename", readFileSync(join(repo, ".gitignore"), "utf-8").includes(".env"));
170+
check("working copy content is untouched", readFileSync(join(repo, ".env"), "utf-8") === "SECRET=still-tracked-value\n");
171+
check("no backup written — git rm --cached never touches file contents", !readdirSync(repo).some((f) => f.startsWith(".env.bak.")));
172+
173+
inRepo.server.close();
174+
rmSync(repo, { recursive: true, force: true });
175+
}
176+
137177
// ---------------------------------------------------------------- git history
138178
console.log("\n--- git history ---");
139179
{
@@ -163,6 +203,43 @@ console.log("\n--- git history ---");
163203
rmSync(repo, { recursive: true, force: true });
164204
}
165205

206+
// ---------------------------------------------------------------- history endpoint
207+
// Same fixture shape as the CLI-level history scan above, but exercised through the UI's own
208+
// HTTP endpoint — the thing the browser button actually calls.
209+
console.log("\n--- history endpoint ---");
210+
{
211+
const { execFileSync } = await import("node:child_process");
212+
const repo = mkdtempSync(join(tmpdir(), "enview-history-api-"));
213+
const run = (...args) => execFileSync("git", args, { cwd: repo, stdio: "pipe" });
214+
run("init", "-q");
215+
run("config", "user.email", "t@t.test");
216+
run("config", "user.name", "t");
217+
writeFileSync(join(repo, ".env"), "OPENAI_API_KEY=sk-endpoint-secret-value\n"); // gitleaks:allow — synthetic fixture
218+
run("add", "-A");
219+
run("commit", "-qm", "oops");
220+
rmSync(join(repo, ".env"));
221+
writeFileSync(join(repo, ".gitignore"), ".env\n");
222+
run("add", "-A");
223+
run("commit", "-qm", "remove env");
224+
225+
const inRepo = await startEnviewUi({ roots: [repo], port: 4185, maxDepth: 2 });
226+
const historyCall = (path) => fetch(`http://127.0.0.1:4185${path}`, { headers: { "x-enview-token": inRepo.token } });
227+
228+
const badRes = await historyCall(`/api/history?path=${encodeURIComponent(dir)}`);
229+
check("path outside this server's scan allowlist is rejected", badRes.status === 404, `got ${badRes.status}`);
230+
231+
const body = await (await historyCall(`/api/history?path=${encodeURIComponent(repo)}`)).json();
232+
const found = body.findings.find((f) => f.file === ".env");
233+
check("history endpoint finds the deleted secret", !!found, JSON.stringify(body));
234+
check("reports it is no longer tracked", found?.stillTracked === false);
235+
check("recovers the key name", !!found?.keys.includes("OPENAI_API_KEY"), JSON.stringify(found));
236+
check("remedy text present", typeof found?.remedy === "string" && found.remedy.length > 0);
237+
check("never returns the historical value", !JSON.stringify(body).includes("sk-endpoint-secret-value"));
238+
239+
inRepo.server.close();
240+
rmSync(repo, { recursive: true, force: true });
241+
}
242+
166243
// ---------------------------------------------------------------- gitignore detection
167244
// This is the check that was silently wrong on Windows for every file. It agrees with git or
168245
// it is worthless, so the test asserts both directions.

0 commit comments

Comments
 (0)