Skip to content

See how your app actually fits together. An interactive, plain-English map of your codebase, drawn by Claude or Codex.

Health: no false alarms on hashes or encrypted values, and mark an issue "Not a problem"

Hayden Smith1eafaca92471
diff --git a/docs/is-it-safe.md b/docs/is-it-safe.md
index 9418834..4d1f8f1 100644
--- a/docs/is-it-safe.md
+++ b/docs/is-it-safe.md
@@ -18,6 +18,7 @@ Plugins for Claude Code and Codex can run code on your computer, so it's worth a
- **The map's server** (`floorplan/serve.mjs`) listens on `127.0.0.1` only, so other machines can't reach it. It answers only to `127.0.0.1` and `localhost` at its own port, and its API needs a token that only the map page receives.
- **One outbound request: the Floorplan Cloud waitlist,** sent only if you type your email into the card on the map and click to join. It goes to `floorplan-waitlist-690500262396.us-central1.run.app` and carries your email and "just me" or "with my team". Details in [Privacy and security](privacy-and-security.md#floorplan-cloud-waitlist).
- **The map page loads nothing from the internet.** Its layout engine and fonts are built into the file. It only links to documentation, which opens when you click.
+- **Reporting a false alarm is yours to send.** If you tick the box under **Not a problem** in Health, the map opens a new GitHub issue in your browser with the text filled in, shown to you first. Nothing goes anywhere unless you submit it there.
Asking questions on the map runs Claude Code or Codex, which talk to Anthropic or OpenAI the way they always do, on your account. Floorplan itself sends nothing.
diff --git a/docs/project-files.md b/docs/project-files.md
index 9146f89..3fa9c8c 100644
--- a/docs/project-files.md
+++ b/docs/project-files.md
@@ -13,6 +13,7 @@ Floorplan writes to exactly two places in your project: the `floorplan/` folder,
| `plan.json` | Blueprints only: the planned files, endpoints and screens, who may use each endpoint, the stack, assumptions and open questions. Names and descriptions live here instead of `descriptions/` | **Yes** |
| `recent-work.json` | What was just worked on, and why. Replaced on every update | Rarely. The AI writes it |
| `custom-flows.json` | Flows requested from the map | Only to delete one |
+| `health-dismissed.json` | Health issues you marked **Not a problem**, with your reasons | Only to undo one. **Show again** on the map does it too |
| `serve.mjs` | Serves the map locally and answers questions through the Claude Code CLI or Codex | No |
| `query.mjs` | Looks things up in the map from the command line; Claude and Codex use it too | No |
| `artifact.html` | A copy for opening in the Claude app, only if you asked for one | No |
diff --git a/docs/using-the-map.md b/docs/using-the-map.md
index c1f56b7..8330b1b 100644
--- a/docs/using-the-map.md
+++ b/docs/using-the-map.md
@@ -65,6 +65,12 @@ A count of important issues, and a plain-language list of problems the scan foun
Each issue has **Show on map**, which highlights the affected files and endpoints with notes, and **Fix with Claude** (or **Fix with Codex**, for a map made in Codex), which copies a ready-made prompt naming the exact files and lines and the safe fix. It's a quick automatic check, not a security audit. On a blueprint this button is **Review** instead (see [Blueprints](#blueprints)).
+Health leaves password hashes and encrypted values alone (bcrypt, argon2, dotenvx, sops, Ansible Vault and similar), and goes by the value, so a backup with one value left unencrypted is still flagged. It can only recognise encryption that marks itself, and it can't read a `.env` file that git ignores.
+
+If an issue is wrong, press **Not a problem** and add a reason if you like. It moves to the bottom of the list and out of the count, and stays that way when the map is rebuilt. Editing elsewhere in the file won't bring it back, but it does show again if the same check finds something new in that file or the issue changes severity. **Show again** undoes it. Exported copies keep the issue set apart but leave your reason out.
+
+You can also tick the box to tell the Floorplan developer. That opens a GitHub issue for you to read, edit and send yourself, with the check's name and title, the kinds of files involved and your note. A title can name a file or an endpoint, and the preview shows you exactly what will go. It never includes your code or any values, and nothing is sent unless you send it.
+
### Recent work
Appears when Claude or Codex has just changed things. It lays the changed cards out on one board, with what you asked for, a summary of what was done, and a note on every card. Elsewhere on the map, changed cards have a green ring and a **Changed** or **New** tag, and the parts that contain them show **N changed**, so you can follow the green down from the top level.
diff --git a/skills/floorplan/assets/serve.mjs b/skills/floorplan/assets/serve.mjs
index 8770a31..d6d0061 100644
--- a/skills/floorplan/assets/serve.mjs
+++ b/skills/floorplan/assets/serve.mjs
@@ -34,6 +34,17 @@ if (has('stop')) {
process.exit(0);
}
+// Health issues marked "not a problem" on the map; build.mjs folds them into graph.json
+const dismissedFile = path.join(here, 'health-dismissed.json');
+const readDismissed = () => { try { const { dismissed } = JSON.parse(fs.readFileSync(dismissedFile, 'utf8')); return Array.isArray(dismissed) ? dismissed : []; } catch { return []; } };
+const cleanDismissal = (d) => ({
+ id: String(d.id).slice(0, 2000),
+ locations: (Array.isArray(d.locations) ? d.locations : []).slice(0, 500).map((l) => String(l).slice(0, 1000)),
+ ...(d.severity ? { severity: String(d.severity).slice(0, 20) } : {}),
+ ...(d.reason ? { reason: String(d.reason).slice(0, 1000) } : {}),
+ at: new Date().toISOString(),
+});
+
// ---------- export: a copy of the map to share ----------
// The same self-contained page, marked as exported: no Ask bar, no requests for Claude or Codex, no links into
// this computer, and only the extras asked for. Used by the map's Export button and by --export.
@@ -56,6 +67,8 @@ function exportMap(include, extraFlows = []) {
};
if (!on.includes('recent')) delete out.recent;
if (!on.includes('health')) delete out.health;
+ // dismissals made since the last build travel with the copy (the page applies them; no reasons, which are notes to self)
+ else if (out.health) { const list = readDismissed().map(({ reason, ...d }) => d); if (list.length) out.health = { ...out.health, dismissed: list }; else delete out.health.dismissed; }
const json = JSON.stringify(out).replace(/<\/(script)/gi, '<\\/$1').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
const slug = String(g.project?.name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'floorplan';
return { html: html.slice(0, a + DATA_START.length) + json + html.slice(b), name: `${slug}-map.html`, include: on, plan: !!g.meta?.blueprint };
@@ -544,6 +557,22 @@ const server = http.createServer((req, res) => {
return;
}
}
+ if (url.pathname === '/api/health/dismissed') {
+ if (req.method === 'GET') { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ dismissed: readDismissed() })); }
+ if (req.method === 'POST' || req.method === 'DELETE') {
+ let raw = '';
+ req.on('data', (d) => { raw += d; if (raw.length > 100000) req.destroy(); });
+ req.on('end', () => {
+ let body = {}; try { body = JSON.parse(raw); } catch {}
+ if (typeof body.id !== 'string') { res.writeHead(400); return res.end(); }
+ const dismissed = readDismissed().filter((x) => x.id !== body.id);
+ if (req.method === 'POST') dismissed.push(cleanDismissal(body));
+ fs.writeFileSync(dismissedFile, JSON.stringify({ dismissed }, null, 2) + '\n');
+ res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ dismissed }));
+ });
+ return;
+ }
+ }
if (url.pathname.startsWith('/api/cloud/')) {
const json = (data) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(data)); };
if (req.method === 'GET' && url.pathname === '/api/cloud/prompt') return json({ show: cloudPrompt() });
diff --git a/skills/floorplan/assets/ui/20-health.js b/skills/floorplan/assets/ui/20-health.js
index 58fadb9..4d37ece 100644
--- a/skills/floorplan/assets/ui/20-health.js
+++ b/skills/floorplan/assets/ui/20-health.js
@@ -11,6 +11,51 @@
// a blueprint (planned, not built) gets a design review of the plan instead of a code check
const PLAN = !!SC.graph.meta.blueprint;
const FIX = PLAN ? 'Resolve' : 'Fix';
+ const CHECK = PLAN ? 'design review' : 'health check';
+ const ISSUES_URL = 'https://github.com/haydenschmitty/floorplan/issues/new';
+
+ // ---------- "not a problem" ----------
+ // Saved by serve.mjs to floorplan/health-dismissed.json (build folds it into graph.health.dismissed);
+ // a map opened without the server keeps them in this browser. A dismissal covers the issue as it was: it
+ // shows again if it gets more or less serious or finds something new in a file (counted per file, so an
+ // edit higher up doesn't bring it back; the same rule as dismissalFor in lib/health.mjs).
+ const SERVER = window.FLOORPLAN_SERVER;
+ const STORE_KEY = 'health-dismissed:' + (SC.graph.meta.rootName || '');
+ const built = (SC.graph.health && SC.graph.health.dismissed) || [];
+ let dismissed = SC.exported || SERVER ? built : SC.store.get(STORE_KEY, built);
+ const locsOf = (issue) => (issue.locations || []).map((l) => `${l.file}:${l.line}`);
+ const dismissalOf = (issue) => {
+ const d = dismissed.find((x) => x.id === issue.id);
+ if (!d || (d.severity && d.severity !== issue.severity)) return null;
+ const left = new Map();
+ for (const loc of d.locations || []) { const f = String(loc).replace(/:[^:]*$/, ''); left.set(f, (left.get(f) || 0) + 1); }
+ for (const l of issue.locations || []) { const n = left.get(l.file) || 0; if (!n) return null; left.set(l.file, n - 1); }
+ return d;
+ };
+ const canDismiss = !SC.exported;
+ async function saveDismissal(issue, reason) {
+ const rec = { id: issue.id, severity: issue.severity, locations: locsOf(issue), ...(reason ? { reason } : {}) };
+ if (SERVER) {
+ const r = await fetch('/api/health/dismissed', { method: 'POST', headers: { 'content-type': 'application/json', 'x-floorplan-token': SERVER.token }, body: JSON.stringify(rec) }).then((x) => x.json()).catch(() => null);
+ if (!r) { SC.toast('Couldn’t reach the map server, so this wasn’t saved.'); return false; }
+ dismissed = r.dismissed;
+ } else {
+ dismissed = [...dismissed.filter((x) => x.id !== issue.id), { ...rec, at: new Date().toISOString() }];
+ SC.store.set(STORE_KEY, dismissed);
+ }
+ return true;
+ }
+ async function undoDismissal(issue) {
+ if (SERVER) {
+ const r = await fetch('/api/health/dismissed', { method: 'DELETE', headers: { 'content-type': 'application/json', 'x-floorplan-token': SERVER.token }, body: JSON.stringify({ id: issue.id }) }).then((x) => x.json()).catch(() => null);
+ if (!r) { SC.toast('Couldn’t reach the map server.'); return; }
+ dismissed = r.dismissed;
+ } else {
+ dismissed = dismissed.filter((x) => x.id !== issue.id);
+ SC.store.set(STORE_KEY, dismissed);
+ }
+ refresh();
+ }
const SEV = {
high: { color: 'var(--sev-high)', group: 'Fix these first', word: 'important' },
@@ -18,8 +63,9 @@
low: { color: 'var(--sev-low)', group: 'Good to tidy up', word: 'minor' },
};
const ORDER = ['high', 'medium', 'low'];
- const count = (sev) => issues.filter((i) => i.severity === sev).length;
- const urgent = count('high') + count('medium');
+ const active = () => issues.filter((i) => !dismissalOf(i));
+ const count = (sev) => active().filter((i) => i.severity === sev).length;
+ const urgent = () => count('high') + count('medium');
SC.icons.health = '<path d="M3 12h4l2.5-6 4 12 2.5-6H21"/>';
SC.icons.check = '<path d="m5 12.5 4.5 4.5L19 7.5"/>';
@@ -28,6 +74,8 @@
style.textContent = `
.hc-issue { padding: 12px 14px; border-radius: 16px; background: rgba(var(--ink), .04); margin-bottom: 8px; }
.hc-issue:last-child { margin-bottom: 0; }
+ .hc-issue.off { background: none; box-shadow: inset 0 0 0 1px rgba(var(--ink), .08); }
+ .hc-issue.off .hc-t { color: var(--text-2); }
.hc-t { display: flex; gap: 9px; align-items: flex-start; font-weight: 500; line-height: 1.4; }
.hc-t .dot { margin-top: 6px; }
.hc-d { color: var(--text-2); font-size: 12.5px; line-height: 1.55; margin: 6px 0 0 17px; }
@@ -43,6 +91,12 @@
#btn-health.calm svg.i { color: var(--ok); }
#modal .hc-hint { margin: 0; }
#modal .hc-hint b { color: var(--text); font-weight: 500; }
+ #modal .hc-why { width: 100%; min-height: 72px; resize: vertical; margin-top: 12px; background: rgba(var(--ink), .05); border: 0; border-radius: 14px; padding: 11px 13px; color: var(--text); outline: none; font: inherit; font-size: 13px; line-height: 1.5; box-sizing: border-box; }
+ #modal .hc-why:focus { background: rgba(var(--ink), .07); box-shadow: 0 0 0 1px rgba(var(--ink), .14); }
+ #modal .hc-rep { display: flex; gap: 8px; align-items: flex-start; margin-top: 12px; font-size: 13px; line-height: 1.5; color: var(--text-2); cursor: pointer; }
+ #modal .hc-rep input { margin-top: 3px; }
+ #modal .hc-prev { margin-top: 8px; display: none; }
+ #modal .hc-prev.on { display: block; }
`;
document.head.appendChild(style);
@@ -71,6 +125,38 @@
actions: [{ label: 'Copy prompt', primary: true, icon: 'copy', onClick: () => { SC.copy(issue.fix); SC.toast(`Copied. Paste it into ${A.app}.`); } }],
});
}
+ // The report is a GitHub issue the person reads and sends themselves: which check fired, its title (which
+ // can name a file or endpoint), the kinds of files involved and their note. Never code, values or the fix prompt.
+ const reportText = (issue, reason) => [
+ `**Check:** ${issue.kind} (${issue.severity})`,
+ `**What Floorplan said:** ${issue.title}`,
+ `**File types:** ${[...new Set((issue.locations || []).map((l) => (/\.[^./]+$/.exec(l.file) || [l.file.split('/').pop()])[0]))].slice(0, 6).join(', ') || 'none'}`,
+ ``,
+ `**Why it's not a problem:**`,
+ reason.slice(0, 1500) || '_(no note)_',
+ ].join('\n');
+ function notAProblem(issue) {
+ const m = SC.modal({
+ title: 'Not a problem?',
+ html: `<p class="hc-hint">Mark “${h(issue.title)}” as a false alarm and it moves to the bottom of the ${CHECK}, out of the count. It comes back if this check finds something new there.</p>
+ <textarea class="hc-why" placeholder="Why not? (optional) e.g. that value is a bcrypt hash, not the password" spellcheck="true"></textarea>
+ <label class="hc-rep"><input type="checkbox" class="hc-rep-on"><span>Also tell the Floorplan developer, so the check gets better. This opens a GitHub issue you can read and edit before sending. It includes only what’s shown below, never your code or any values.</span></label>
+ <pre class="hc-prev"></pre>`,
+ actions: [{ label: 'Mark as not a problem', primary: true, icon: 'check', keepOpen: true, onClick: async (close) => {
+ const reason = m.el.querySelector('.hc-why').value.trim();
+ const report = m.el.querySelector('.hc-rep-on').checked;
+ if (report) window.open(`${ISSUES_URL}?title=${encodeURIComponent(`False positive: ${issue.kind}`)}&body=${encodeURIComponent(reportText(issue, reason))}`, '_blank', 'noopener');
+ if (!(await saveDismissal(issue, reason))) return;
+ close();
+ refresh();
+ SC.toast(report ? 'Marked as not a problem. Thanks for the report.' : 'Marked as not a problem.');
+ } }],
+ });
+ const why = m.el.querySelector('.hc-why'), on = m.el.querySelector('.hc-rep-on'), prev = m.el.querySelector('.hc-prev');
+ const sync = () => { prev.classList.toggle('on', on.checked); prev.textContent = reportText(issue, why.value.trim()); };
+ why.addEventListener('input', sync); on.addEventListener('change', sync);
+ why.focus();
+ }
const onMap = (issue) => (issue.items || []).some((id) => SC.exists(id));
// ---------- html ----------
@@ -80,39 +166,50 @@
const shown = locs.slice(0, 3).map((l) => `${l.file}${l.line > 1 ? ':' + l.line : ''}`);
return `<div class="hc-w">${shown.map(h).join('<br>')}${locs.length > 3 ? `<br>+${locs.length - 3} more` : ''}</div>`;
};
- const issueHtml = (issue, idx, note) => `<div class="hc-issue">
+ const issueHtml = (issue, idx, note) => {
+ const d = dismissalOf(issue);
+ if (d) return `<div class="hc-issue off">
+ <div class="hc-t"><span class="dot" style="background:rgba(var(--ink),.2)"></span><span>${h(issue.title)}</span></div>
+ <div class="hc-n">Marked as not a problem${d.reason ? `: ${h(d.reason)}` : ''}</div>
+ ${canDismiss ? `<div class="hc-a"><button class="btn soft" data-hc-undo="${idx}">Show again</button></div>` : ''}
+ </div>`;
+ return `<div class="hc-issue">
<div class="hc-t"><span class="dot" style="background:${SEV[issue.severity].color}"></span><span>${h(issue.title)}</span></div>
${note ? `<div class="hc-n">${h(note)}</div>` : `<div class="hc-d">${h(issue.detail)}</div>`}
${locText(issue)}
<div class="hc-a">
${onMap(issue) ? `<button class="btn soft" data-hc-show="${idx}">${SC.iconI('search')}Show on map</button>` : ''}
${SC.exported ? '' : here(issue) ? `<button class="btn soft" data-hc-here="${idx}">${SC.iconI('spark')}Resolve on the map</button>` : `<button class="btn soft" data-hc-fix="${idx}">${SC.iconI('spark')}${FIX} with ${A.name}</button>`}
+ ${canDismiss ? `<button class="btn soft" data-hc-dismiss="${idx}">${SC.iconI('check')}Not a problem</button>` : ''}
</div>
</div>`;
+ };
const bindIssues = (el) => {
- el.querySelectorAll('[data-hc-show]').forEach((b) => b.addEventListener('click', (ev) => { ev.stopPropagation(); showOnMap(issues[+b.dataset.hcShow]); }));
- el.querySelectorAll('[data-hc-fix]').forEach((b) => b.addEventListener('click', (ev) => { ev.stopPropagation(); fixWith(issues[+b.dataset.hcFix]); }));
- el.querySelectorAll('[data-hc-here]').forEach((b) => b.addEventListener('click', (ev) => { ev.stopPropagation(); resolveHere(issues[+b.dataset.hcHere]); }));
+ const on = (attr, fn) => el.querySelectorAll(`[data-hc-${attr}]`).forEach((b) => b.addEventListener('click', (ev) => { ev.stopPropagation(); fn(issues[+b.getAttribute(`data-hc-${attr}`)]); }));
+ on('show', showOnMap); on('fix', fixWith); on('here', resolveHere); on('dismiss', notAProblem); on('undo', undoDismissal);
};
- const headline = () => urgent ? `${SC.plural(urgent, 'thing')} need${urgent === 1 ? 's' : ''} attention` : issues.length ? 'Nothing urgent' : 'No problems found';
+ const headline = () => urgent() ? `${SC.plural(urgent(), 'thing')} need${urgent() === 1 ? 's' : ''} attention` : active().length ? 'Nothing urgent' : 'No problems found';
const breakdown = () => `<div class="hc-sub">${ORDER.filter(count).map((s) => `<span><i class="dot" style="background:${SEV[s].color}"></i>${count(s)} ${SEV[s].word}</span>`).join('')}</div>`;
+ const headColor = () => urgent() ? SEV[count('high') ? 'high' : 'medium'].color : 'var(--ok)';
function listHtml() {
+ const live = active(), off = issues.filter(dismissalOf);
const top = `<div class="sec">
- <div class="ph"><span class="ico" style="--c:${urgent ? SEV[count('high') ? 'high' : 'medium'].color : 'var(--ok)'}">${SC.icon('health')}</span><span class="kindlabel">${PLAN ? 'Design review' : 'Health check'}</span></div>
+ <div class="ph"><span class="ico" style="--c:${headColor()}">${SC.icon('health')}</span><span class="kindlabel">${PLAN ? 'Design review' : 'Health check'}</span></div>
<h2 class="pt">${h(headline())}</h2>
<p class="pd">${PLAN ? 'We checked the plan for parts anyone on the internet could use, decisions the PRD leaves open, and pieces nothing connects to. Settling these now is cheaper than after it’s built.' : 'We looked for keys left in the code or sent to the browser, data and parts of your app anyone on the internet can reach (Supabase tables, Firebase rules, Stripe webhooks, endpoints), leftover files and files too big to edit safely. It’s a quick check, not a security audit.'}</p>
- ${issues.length ? breakdown() : `<div class="hc-calm">Nothing stood out. This is a quick automatic check, not a full ${PLAN ? 'design' : 'security'} review.</div>`}
+ ${live.length ? breakdown() : `<div class="hc-calm">${off.length ? `Nothing left to look at: you marked ${SC.plural(off.length, 'item')} as not a problem.` : `Nothing stood out.`} This is a quick automatic check, not a full ${PLAN ? 'design' : 'security'} review.</div>`}
<div class="actions"><button class="btn soft" data-hc-back>${SC.iconI('left')}Back</button></div>
</div>`;
const groups = ORDER.map((sev) => {
- const list = issues.map((i, idx) => [i, idx]).filter(([i]) => i.severity === sev);
+ const list = issues.map((i, idx) => [i, idx]).filter(([i]) => i.severity === sev && !dismissalOf(i));
return list.length ? `<div class="sec"><h3>${h(SEV[sev].group)} <span class="c">${list.length}</span></h3>${list.map(([i, idx]) => issueHtml(i, idx)).join('')}</div>` : '';
}).join('');
- const foot = !issues.length ? '' : SC.exported ? `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints from when this copy was exported.</div>` : `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints. ${issues.some(here)
+ const offHtml = off.length ? `<div class="sec"><h3>Marked as not a problem <span class="c">${off.length}</span></h3>${issues.map((i, idx) => [i, idx]).filter(([i]) => dismissalOf(i)).map(([i, idx]) => issueHtml(i, idx)).join('')}</div>` : '';
+ const foot = !live.length ? '' : SC.exported ? `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints from when this copy was exported.</div>` : `<div class="sec" style="color:var(--text-3);font-size:12px;line-height:1.6">These are automatic hints. ${live.some(here)
? `“Resolve on the map” puts a request in the Ask bar’s Change mode: finish or edit it, press Enter, and ${A.name} updates the plan and redraws the map. Undo puts it back.`
- : `“${FIX} with ${A.name}” gives you a request to paste into ${A.app}; ${PLAN ? 'it explains the choice and updates the plan once you decide' : 'it checks the code before changing anything'}.`}</div>`;
- return top + groups + foot;
+ : `“${FIX} with ${A.name}” gives you a request to paste into ${A.app}; ${PLAN ? 'it explains the choice and updates the plan once you decide' : 'it checks the code before changing anything'}.`} If one is wrong, “Not a problem” sets it aside.</div>`;
+ return top + groups + offHtml + foot;
}
function openList() {
isOpen = true;
@@ -125,27 +222,39 @@
// ---------- chrome ----------
const btn = SC.addHeaderButton({
- id: 'btn-health', label: PLAN ? 'Review' : 'Health', icon: urgent ? 'health' : 'check',
- title: `${PLAN ? 'Design review' : 'Health check'}: ${urgent ? headline() : 'nothing urgent'}`,
+ id: 'btn-health', label: PLAN ? 'Review' : 'Health', icon: 'health',
onClick: () => (isOpen ? closeList() : openList()),
});
- if (urgent) {
- const b = document.createElement('span');
- b.className = 'badge';
- b.textContent = urgent > 99 ? '99+' : String(urgent);
- btn.style.setProperty('--hc-badge', count('high') ? SEV.high.color : SEV.medium.color);
- btn.style.setProperty('--hc-badge-text', 'var(--on-sev-text)');
- btn.appendChild(b);
- } else btn.classList.add('calm');
- btn.setAttribute('aria-label', btn.title); // keeps its name, with the count, when only the icon shows
+ const badge = document.createElement('span');
+ badge.className = 'badge';
+ function updateButton() {
+ const n = urgent();
+ btn.title = `${PLAN ? 'Design review' : 'Health check'}: ${n ? headline() : 'nothing urgent'}`;
+ btn.querySelector('svg.i').innerHTML = SC.icons[n ? 'health' : 'check'];
+ if (n) {
+ badge.textContent = n > 99 ? '99+' : String(n);
+ btn.style.setProperty('--hc-badge', count('high') ? SEV.high.color : SEV.medium.color);
+ btn.style.setProperty('--hc-badge-text', 'var(--on-sev-text)');
+ btn.appendChild(badge);
+ } else badge.remove();
+ btn.classList.toggle('calm', !n);
+ btn.setAttribute('aria-label', btn.title); // keeps its name, with the count, when only the icon shows
+ }
+ function refresh() {
+ updateButton();
+ if (isOpen) openList(); else SC.refreshPanel();
+ }
+ updateButton();
+ // the server's list is the saved one: it may have changed since this map was built
+ if (SERVER && canDismiss) fetch('/api/health/dismissed', { headers: { 'x-floorplan-token': SERVER.token } }).then((r) => r.json()).then((r) => { if (Array.isArray(r.dismissed)) { dismissed = r.dismissed; refresh(); } }).catch(() => {});
// Selecting something else on the map while the list is open shows that item instead.
SC.on('panel', () => { if (isOpen && openedAt && where() !== openedAt) { isOpen = false; SC.closePanel(); } });
SC.addPanelSection('overview', () => ({
html: `<div class="sec"><h3>${PLAN ? 'Design review' : 'Health'}</h3><div class="list"><a class="row" data-hc-open>
- <span class="dot" style="background:${urgent ? SEV[count('high') ? 'high' : 'medium'].color : 'var(--ok)'}"></span>
- <span class="rt"><div class="rn">${h(headline())}</div><div class="rd">${issues.length ? ORDER.filter(count).map((s) => `${count(s)} ${SEV[s].word}`).join(' · ') : PLAN ? 'Quick automatic check of the plan' : 'Quick automatic check of secrets, open endpoints and leftover files'}</div></span>
+ <span class="dot" style="background:${headColor()}"></span>
+ <span class="rt"><div class="rn">${h(headline())}</div><div class="rd">${active().length ? ORDER.filter(count).map((s) => `${count(s)} ${SEV[s].word}`).join(' · ') : PLAN ? 'Quick automatic check of the plan' : 'Quick automatic check of secrets, open endpoints and leftover files'}</div></span>
<span class="rc">${SC.iconI('right')}</span></a></div></div>`,
bind: (el) => el.querySelector('[data-hc-open]')?.addEventListener('click', (ev) => { ev.preventDefault(); openList(); }),
}));
@@ -154,12 +263,13 @@
if (!itemId || typeof itemId !== 'string' || !issues.length) return '';
const hits = [];
issues.forEach((issue, idx) => {
+ if (dismissalOf(issue)) return;
const inside = (issue.items || []).filter((id) => id === itemId || (SC.exists(id) && SC.chain(id).includes(itemId)));
if (!inside.length) return;
const exact = issue.notes && inside.includes(itemId) ? issue.notes[itemId] : '';
hits.push(issueHtml(issue, idx, exact || (inside.length > 1 || inside[0] !== itemId ? `Affects ${SC.plural(inside.length, 'place')} in here` : '')));
});
if (!hits.length) return '';
- return { html: `<div class="sec"><h3>${PLAN ? 'Design review' : 'Health'} <span class="c">${hits.length}</span></h3>${hits.slice(0, 6).join('')}${hits.length > 6 ? `<div class="more" data-hc-open style="cursor:pointer">+${hits.length - 6} more in the ${PLAN ? 'design review' : 'health check'}</div>` : ''}</div>`, bind: (el) => { bindIssues(el); el.querySelector('[data-hc-open]')?.addEventListener('click', openList); } };
+ return { html: `<div class="sec"><h3>${PLAN ? 'Design review' : 'Health'} <span class="c">${hits.length}</span></h3>${hits.slice(0, 6).join('')}${hits.length > 6 ? `<div class="more" data-hc-open style="cursor:pointer">+${hits.length - 6} more in the ${CHECK}</div>` : ''}</div>`, bind: (el) => { bindIssues(el); el.querySelector('[data-hc-open]')?.addEventListener('click', openList); } };
});
})();
diff --git a/skills/floorplan/scripts/build.mjs b/skills/floorplan/scripts/build.mjs
index 12fe0be..22ca764 100644
--- a/skills/floorplan/scripts/build.mjs
+++ b/skills/floorplan/scripts/build.mjs
@@ -9,7 +9,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { compileGlob, parseArgs, fmtNum, mapDir, keepOutOfGit } from './lib/common.mjs';
import { fallbackFileName, fallbackRouteName, routeKey } from './lib/names.mjs';
-import { buildHealth } from './lib/health.mjs';
+import { buildHealth, withDismissed, dismissalFor } from './lib/health.mjs';
import { buildPlanHealth } from './lib/blueprint.mjs';
import { buildScreens } from './lib/screens.mjs';
import { writeClaudeMd } from './lib/claudemd.mjs';
@@ -418,6 +418,11 @@ const graph = {
if (!scan.blueprint) try { graph.health = buildHealth({ graph, scan, arch, root }); } catch (e) { warn(`health check failed: ${e.message}`); graph.health = { issues: [] }; }
try { graph.screens = buildScreens({ graph, scan, arch, root }); } catch (e) { warn(`screen detection failed: ${e.message}`); graph.screens = []; }
if (scan.blueprint) try { graph.health = buildPlanHealth({ graph, scan }); } catch (e) { warn(`design review failed: ${e.message}`); graph.health = { issues: [] }; }
+// issues people marked "not a problem" on the map (saved by serve.mjs) stay listed, set apart, and leave the counts
+const dismissedFile = path.join(outDir, 'health-dismissed.json');
+if (graph.health?.issues && fs.existsSync(dismissedFile)) {
+ try { graph.health = withDismissed(graph.health, JSON.parse(fs.readFileSync(dismissedFile, 'utf8')).dismissed); } catch (e) { warn(`health-dismissed.json is not valid JSON: ${e.message}`); }
+}
fs.mkdirSync(outDir, { recursive: true });
const trackedWarning = keepOutOfGit(outDir);
fs.writeFileSync(path.join(outDir, 'graph.json'), JSON.stringify(graph, null, 0));
@@ -448,7 +453,9 @@ const uiScripts = fs.existsSync(uiDir) ? fs.readdirSync(uiDir).filter((n) => n.e
const html = page(graph);
fs.writeFileSync(path.join(outDir, 'index.html'), html);
// --artifact: a copy to publish to the Claude app, without this machine's absolute path (editor links)
-if (args.artifact) fs.writeFileSync(path.join(outDir, 'artifact.html'), page({ ...graph, meta: { ...graph.meta, root: null, agent: 'claude' } }));
+// (and without the reasons on dismissed health issues, which are notes to self)
+const sharedHealth = graph.health?.dismissed ? { ...graph.health, dismissed: graph.health.dismissed.map(({ reason, ...d }) => d) } : graph.health;
+if (args.artifact) fs.writeFileSync(path.join(outDir, 'artifact.html'), page({ ...graph, ...(sharedHealth ? { health: sharedHealth } : {}), meta: { ...graph.meta, root: null, agent: 'claude' } }));
// Self-contained helpers next to the map: ask questions through the Claude Code CLI or Codex (serve.mjs)
// and the graph lookups it hands to them (query.mjs). They need only Node, not this skill.
fs.writeFileSync(path.join(outDir, 'query.mjs'), `${graphQuery}
@@ -464,7 +471,7 @@ function escapeHtml(s) { return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<'
const hs = graph.health?.summary;
if (hs && (hs.high || hs.medium || hs.low)) {
report.push(`${scan.blueprint ? 'DESIGN REVIEW' : 'HEALTH'} ${hs.high} important · ${hs.medium} worth fixing · ${hs.low} minor`);
- for (const i of graph.health.issues.filter((x) => x.severity !== 'low').slice(0, 8)) report.push(` [${i.severity}] ${i.title}`);
+ for (const i of graph.health.issues.filter((x) => x.severity !== 'low' && !dismissalFor(x, graph.health.dismissed)).slice(0, 8)) report.push(` [${i.severity}] ${i.title}`);
}
if (graph.screens?.length) report.push(`SCREENS ${graph.screens.length} detected`);
report.push(graph.recent
diff --git a/skills/floorplan/scripts/lib/health.mjs b/skills/floorplan/scripts/lib/health.mjs
index 027cd0e..a5cb39e 100644
--- a/skills/floorplan/scripts/lib/health.mjs
+++ b/skills/floorplan/scripts/lib/health.mjs
@@ -55,7 +55,8 @@ const FORMATS = [
{ re: /\bsk-ant-[a-z]+\d*-[A-Za-z0-9_\-]{40,}/g, what: 'an Anthropic (Claude) API key', svc: 'Anthropic', live: true },
{ re: /\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_\-]{16,}T3BlbkFJ[A-Za-z0-9_\-]{16,}/g, what: 'an OpenAI API key', svc: 'OpenAI', live: true },
{ re: /\bsk-(?:proj|svcacct|admin)-[A-Za-z0-9_\-]{40,}/g, what: 'an OpenAI API key', svc: 'OpenAI', live: true },
- { re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/g, what: 'a private key', svc: null, whole: true },
+ // (a passphrase-protected key, ENCRYPTED PRIVATE KEY or Proc-Type: 4,ENCRYPTED, is left alone: see encryptedKeyAt)
+ { re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/g, what: 'a private key', svc: null, whole: true },
{ re: /\bSG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43}\b/g, what: 'a SendGrid email API key', svc: 'SendGrid', live: true },
{ re: /\bsq0csp-[0-9A-Za-z_\-]{40,}/g, what: 'a Square app secret', svc: 'Square', live: true },
{ re: /\bsq0atp-[0-9A-Za-z_\-]{20,}/g, what: 'a Square access token', svc: 'Square', live: true },
@@ -92,8 +93,21 @@ const kindFromName = (name) => {
};
const mask = (v, password) => password || v.length < 12 ? `${v.length} characters` : `starts “${v.slice(0, 4)}…”, ${v.length} characters`;
+// A stored password hash isn't the password: bcrypt / argon2 / scrypt / crypt(3) ($2b$…, $argon2id$…,
+// $6$…), Django's pbkdf2_sha256$…, LDAP's {SSHA}…, and anything kept under a name that says it's a hash.
+const HASHED_VALUE = /^\$(2[abxy]?|argon2(id|i|d)|scrypt|pbkdf2[\w-]*|[156]|y|7|sha\d*|md5)\$|^(pbkdf2_sha\d+|bcrypt(_sha256)?|argon2|scrypt|sha1|md5)\$|^\{(S?SHA\d*|SMD5|CRYPT|PBKDF2[\w-]*)\}/i;
+// (HASH_SECRET, PASSWORD_HASH_KEY and HASH_SALT are the secret that makes the hash, so they don't count.)
+const HASHED_NAME = /(^|_)(hash|hashed|hashes|digest|bcrypt|argon2?|scrypt|pbkdf2)(_(?!.*(secret|key|salt|pepper|token))|$)/i;
+// Encrypted values are safe to commit (that's the point): dotenvx's encrypted:…, sops' ENC[AES256_GCM,…],
+// Ansible Vault, AWS KMS ciphertext, HashiCorp Vault transit (vault:v1:…), age and PGP armour, OpenSSL's
+// "Salted__" (U2FsdGVkX1…) and Python's Fernet (gAAAAA…).
+const ENCRYPTED_VALUE = /^encrypted:[A-Za-z0-9+/=_-]{20,}|^ENC\[[A-Z0-9_]+,data:|^\$ANSIBLE_VAULT;|^!vault\b|^AQICAH[A-Za-z0-9+/=]{40,}$|^vault:v\d+:|^-----BEGIN (AGE ENCRYPTED FILE|PGP MESSAGE)-----|^U2FsdGVkX1[A-Za-z0-9+/=]{10,}|^gAAAAA[A-Za-z0-9_=-]{40,}/;
+/** A value that's a password hash or ciphertext rather than the secret itself. */
+export const protectedValue = (v, name = '') => ENCRYPTED_VALUE.test(v) || HASHED_VALUE.test(v) || HASHED_NAME.test(snake(name));
+
function valueLooksReal(v, name) {
if (/\s/.test(v) || PLACEHOLDER.test(v)) return false;
+ if (protectedValue(v, name)) return false;
if (/^(none|null|nil|undefined|true|false|string|number|text|required|optional|bearer|basic|secret|token|password|test|dev|development|local|admin)$/i.test(v)) return false;
if (/^[A-Z][A-Z0-9_]+$/.test(v)) return false; // the NAME of an env var
if (/^env\([A-Za-z_][\w]*\)$/.test(v)) return false; // Supabase config.toml reading one: "env(S3_SECRET_KEY)"
@@ -122,6 +136,11 @@ function docLines(src, lang) {
return set;
}
+/** A PEM private key block starting at `idx` that is passphrase-protected (legacy OpenSSL headers). */
+const encryptedKeyAt = (src, idx) => /^[^\n]*\n(?:[^\n]*\n)?\s*Proc-Type:\s*4,\s*ENCRYPTED/.test(src.slice(idx, idx + 300));
+/** A key file's head holds a private key that isn't passphrase-protected. */
+const plainKeyIn = (head) => [...head.matchAll(/-----BEGIN ([A-Z ]*)PRIVATE KEY(?: BLOCK)?-----/g)].some((m) => !/ENCRYPTED/.test(m[1]) && !encryptedKeyAt(head, m.index));
+
function findSecrets(src, f, out) {
const at = lineIndex(src);
const isTest = TEST_FILE.test(f.path) || EXAMPLE_FILE.test(f.path);
@@ -134,6 +153,7 @@ function findSecrets(src, f, out) {
const v = m[0];
if (isTest && (!fm.live || fm.whole)) continue;
if (!fm.whole && (/EXAMPLE|xxxx|XXXX|0{10,}/.test(v) || entropy(v) < 3)) continue;
+ if (fm.whole && encryptedKeyAt(src, m.index)) continue;
add(at(m.index), { what: fm.what, svc: fm.svc, sev: fm.sev || 'high', hint: fm.whole ? 'private key block' : mask(v) });
}
}
@@ -390,7 +410,7 @@ export function leakyPublicVar(name) {
const m = PUBLIC_PREFIX.exec(name);
if (!m) return null;
const rest = name.slice(m[0].length);
- if (PUBLIC_BY_DESIGN.test(rest)) return null;
+ if (PUBLIC_BY_DESIGN.test(rest) || HASHED_NAME.test(rest)) return null;
const svc = PRIVATE_SERVICE.exec(rest)?.[2];
if (svc && KEYISH.test(rest)) return SERVICE_LABEL[svc] || svc.charAt(0) + svc.slice(1).toLowerCase();
if (PRIVATE_NAME.test(rest)) return /SERVICE_ROLE|SERVICE_KEY/.test(rest) ? 'Supabase' : '';
@@ -578,7 +598,7 @@ export function buildHealth({ graph, scan, arch, root }) {
if (!/\.(pem|key|p12|pfx|jks|keystore)$|^id_(rsa|dsa|ecdsa|ed25519)$|service[-_]?account.*\.json$|^credentials?\.json$|firebase-adminsdk.*\.json$|^client_secret.*\.json$|-key\.json$/i.test(base)) continue;
let head = '';
try { head = readHead(path.join(root, f.path), 65536); } catch { continue; }
- if (/PRIVATE KEY|"private_key"\s*:\s*"-----|"client_secret"\s*:\s*"[^"]{8,}/.test(head) || /\.(p12|pfx|jks|keystore)$/i.test(base)) secretFiles.push({ path: f.path, list: [{ k: 'secret', line: 1, what: 'a credentials file (a private key that logs in as your app)', sev: 'high', hint: 'whole file' }], file: true });
+ if (plainKeyIn(head) || /"private_key"\s*:\s*"-----|"client_secret"\s*:\s*"[^"]{8,}/.test(head) || /\.(p12|pfx|jks|keystore)$/i.test(base)) secretFiles.push({ path: f.path, list: [{ k: 'secret', line: 1, what: 'a credentials file (a private key that logs in as your app)', sev: 'high', hint: 'whole file' }], file: true });
}
const secretIssue = (group) => {
const locations = [], notes = {}, items = [];
@@ -677,9 +697,13 @@ export function buildHealth({ graph, scan, arch, root }) {
try { src = readHead(path.join(root, f.path), 262144); } catch { continue; }
src.split('\n').forEach((t, i) => {
const m = /^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*["']?([^"'#\s]*)/.exec(t);
- if (m && m[2] && !PLACEHOLDER.test(m[2]) && !/^\$/.test(m[2]) && leakyPublicVar(m[1]) !== null) publicVar(m[1]).defs.push({ file: f.path, line: i + 1 });
+ if (!m || !m[2] || leakyPublicVar(m[1]) === null) return;
+ // VITE_ADMIN_PASSWORD=$2b$12$… is a hash (or ciphertext), not the password
+ if (protectedValue(m[2], m[1])) publicVar(m[1]).protected = true;
+ else if (!PLACEHOLDER.test(m[2]) && !/^\$/.test(m[2])) publicVar(m[1]).defs.push({ file: f.path, line: i + 1 });
});
}
+ for (const [name, v] of publicVars) if (v.protected && !v.defs.length) publicVars.delete(name);
if (publicVars.size) {
const vars = [...publicVars.values()];
const browserSide = (p) => isFrontend(p) || /\.(jsx|tsx|vue|svelte|astro)$/.test(p);
@@ -1134,6 +1158,27 @@ export function buildHealth({ graph, scan, arch, root }) {
return { summary, issues: kept };
}
+// ---------- "not a problem": issues people dismissed from the Health panel ----------
+// serve.mjs saves them to floorplan/health-dismissed.json as { dismissed: [{ id, locations: ['file:line'], reason, at }] }.
+// A dismissal covers the issue as it was: it shows again if it gets more or less serious, or finds something new
+// in a file. It counts per file, not per line, so an edit higher up the file doesn't bring it back.
+// (assets/ui/20-health.js has the same rule for the page.)
+export function dismissalFor(issue, list) {
+ const d = (list || []).find((x) => x && x.id === issue.id);
+ if (!d || (d.severity && d.severity !== issue.severity)) return null;
+ const left = new Map();
+ for (const loc of d.locations || []) { const f = String(loc).replace(/:[^:]*$/, ''); left.set(f, (left.get(f) || 0) + 1); }
+ for (const l of issue.locations || []) { const n = left.get(l.file) || 0; if (!n) return null; left.set(l.file, n - 1); }
+ return d;
+}
+/** Folds a dismissal list into a built health result: keeps the list, recounts the summary without them. */
+export function withDismissed(health, list) {
+ const dismissed = (Array.isArray(list) ? list : []).filter((x) => x && typeof x.id === 'string');
+ const summary = { high: 0, medium: 0, low: 0 };
+ for (const i of health.issues) if (!dismissalFor(i, dismissed)) summary[i.severity]++;
+ return { ...health, summary, ...(dismissed.length ? { dismissed } : {}) };
+}
+
/** Test mode, in Firestore/Storage rules (request.time < timestamp.date(Y, M, D)) or Realtime Database rules (now < ms). */
const testModeEnd = (cond) => {
const d = /^request\.time\s*<\s*timestamp\.date\(\s*(\d{4})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\)$/.exec(cond);
diff --git a/tests/false-positives.test.mjs b/tests/false-positives.test.mjs
new file mode 100644
index 0000000..a1c44eb
--- /dev/null
+++ b/tests/false-positives.test.mjs
@@ -0,0 +1,203 @@
+// Two kinds of false alarm a user reported on the Health tab, and the way out for the rest. A password hash
+// isn't the password, and an encrypted backup isn't an exposed one. Whatever the checks still get wrong can be
+// marked "not a problem" on the map: saved next to it, set apart, out of the counts, back if the finding changes.
+// Secret-looking values are assembled at runtime so none is ever committed to this repo.
+import { test, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { lib, makeProject, shopApp, run, scanAndBuild, readGraph, cleanup, FAKE_PASSWORD } from './helpers.mjs';
+
+const { findIssues, leakyPublicVar, protectedValue, dismissalFor, withDismissed } = await lib('health.mjs');
+const secrets = (src, p = 'app/config.py', lang = 'python') => findIssues(src, { path: p, category: 'code', lang }).filter((x) => x.k === 'secret');
+const BCRYPT = '$2b$12$' + 'aBcD1e2F3g4H5i6J7k8L9m'.repeat(2) + 'n0P3q4R5s6';
+const ARGON = '$argon2id$v=19$m=65536,t=3,p=4$' + 'c2FsdHNhbHQ' + '$' + 'aGFzaGhhc2hoYXNo';
+const ARCH = { project: { name: 'App', summary: 'A sample app.' }, nodes: [{ id: 'app', label: 'App', kind: 'ui', summary: 'The app.', paths: ['**'] }] };
+const FAKE_GITHUB_TOKEN = 'ghp_' + 'aBcD' + '1e2F3g4H5i6J7k8L9m0N1o2P3q4R5s6T7u8V';
+const BLOB = 'Zm9vYmFyYmF6cXV4'.repeat(4);
+const ENCRYPTED = { dotenvx: 'encrypted:' + BLOB, sops: `ENC[AES256_GCM,data:${BLOB},iv:abc,tag:def,type:str]`, openssl: 'U2FsdGVkX1' + BLOB, fernet: 'gAAAAA' + BLOB, vault: 'vault:v1:' + BLOB };
+
+// ---------- 1. a hash isn't the password ----------
+test('a password hash is not flagged as a password', () => {
+ assert.deepEqual(secrets(`DB_PASSWORD = "${BCRYPT}"\nADMIN_PASSWORD = "${ARGON}"\n`), []);
+ assert.deepEqual(secrets(`ADMIN_PASSWORD_HASH = "${FAKE_PASSWORD}"\nhashed_password = "${FAKE_PASSWORD}"\n`), []);
+ assert.deepEqual(secrets(`const adminPasswordHash = "${FAKE_PASSWORD}";`, 'app/config.ts', 'typescript'), []);
+});
+
+test('the same password under an ordinary name is still flagged', () => {
+ assert.equal(secrets(`DB_PASSWORD = "${FAKE_PASSWORD}"`).length, 1);
+});
+
+test('a name only excuses a hash, not the secret that makes one, and never a real key format', () => {
+ for (const name of ['HASH_SECRET', 'HASH_TOKEN', 'JWT_HASH_SECRET']) assert.equal(secrets(`${name} = "${FAKE_PASSWORD}"`).length, 1, name);
+ assert.equal(secrets(`PASSWORD_HASH = "${FAKE_GITHUB_TOKEN}"`).length, 1);
+});
+
+test('a hash in a browser variable is not a leaked secret, and a password there still is', () => {
+ assert.equal(leakyPublicVar('VITE_ADMIN_PASSWORD_HASH'), null);
+ assert.notEqual(leakyPublicVar('VITE_ADMIN_PASSWORD'), null);
+});
+
+const browserVarIssues = (value) => {
+ const root = makeProject({
+ 'app/.env.production': `VITE_ADMIN_PASSWORD=${value}\n`,
+ 'app/package.json': '{"name":"a","dependencies":{"vite":"5"}}',
+ 'app/src/main.js': `console.log(import.meta.env.VITE_ADMIN_PASSWORD);\n`,
+ }, { repos: ['app'], arch: ARCH });
+ try {
+ scanAndBuild(root);
+ return readGraph(root).health.issues.filter((i) => i.kind === 'public-env-secret');
+ } finally { cleanup(root); }
+};
+
+test('a browser variable whose value is a hash raises nothing, and the same variable with a password does', () => {
+ assert.deepEqual(browserVarIssues(BCRYPT), []);
+ assert.equal(browserVarIssues(FAKE_PASSWORD).length, 1);
+});
+
+// ---------- 2. an encrypted backup isn't exposed ----------
+test('encrypted values are recognised in every common format', () => {
+ for (const [what, v] of Object.entries(ENCRYPTED)) assert.ok(protectedValue(v), what);
+ assert.ok(!protectedValue(FAKE_PASSWORD));
+ assert.ok(!protectedValue(BLOB), 'random-looking text is not proof of encryption');
+});
+
+const envIssues = (body, name = '.env.backup') => {
+ const root = makeProject({ [`app/${name}`]: body, 'app/index.js': 'console.log(1);\n' }, { repos: ['app'], arch: ARCH });
+ try {
+ scanAndBuild(root);
+ return readGraph(root).health.issues.filter((i) => i.kind === 'env-file');
+ } finally { cleanup(root); }
+};
+
+test('an encrypted .env backup is not reported as an exposed settings file', () => {
+ assert.deepEqual(envIssues(Object.entries(ENCRYPTED).map(([k, v]) => `${k.toUpperCase()}_PASSWORD=${v}`).join('\n') + '\n'), []);
+});
+
+test('a backup with one value left unencrypted is still reported, for that value only', () => {
+ const [issue, ...rest] = envIssues(`A_PASSWORD=${ENCRYPTED.sops}\nB_PASSWORD=${FAKE_PASSWORD}\n`);
+ assert.equal(rest.length, 0);
+ assert.deepEqual(issue.locations.map((l) => l.line), [2]);
+});
+
+test('a passphrase-protected private key is left alone, and a plain one is not', () => {
+ const body = 'MIIE' + 'abcd'.repeat(30);
+ assert.deepEqual(secrets(`-----BEGIN ENCRYPTED PRIVATE KEY-----\n${body}\n-----END ENCRYPTED PRIVATE KEY-----\n`, 'certs/app.txt', 'text'), []);
+ assert.deepEqual(secrets(`-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,00\n\n${body}\n-----END RSA PRIVATE KEY-----\n`, 'certs/app.txt', 'text'), []);
+ assert.equal(secrets(`-----BEGIN RSA PRIVATE KEY-----\n${body}\n-----END RSA PRIVATE KEY-----\n`, 'certs/app.txt', 'text').length, 1);
+});
+
+// ---------- 3. marking the rest "not a problem" ----------
+const issue = { id: 'secret:a.py', severity: 'high', locations: [{ file: 'a.py', line: 10 }, { file: 'b.py', line: 3 }] };
+const mark = (over = {}) => [{ id: issue.id, severity: 'high', locations: ['a.py:10', 'b.py:3'], ...over }];
+
+test('a dismissal covers the issue it was made for', () => {
+ assert.ok(dismissalFor(issue, mark()));
+ assert.equal(dismissalFor({ ...issue, id: 'secret:other.py' }, mark()), null);
+ assert.equal(dismissalFor(issue, []), null);
+ assert.equal(dismissalFor(issue, undefined), null);
+});
+
+test('an edit higher up the file, which only moves the line, does not bring it back', () => {
+ assert.ok(dismissalFor({ ...issue, locations: [{ file: 'a.py', line: 42 }, { file: 'b.py', line: 3 }] }, mark()));
+});
+
+test('it comes back when there is something new: another file, another finding in the file, or a change in severity', () => {
+ assert.equal(dismissalFor({ ...issue, locations: [...issue.locations, { file: 'c.py', line: 1 }] }, mark()), null);
+ assert.equal(dismissalFor({ ...issue, locations: [...issue.locations, { file: 'a.py', line: 99 }] }, mark()), null);
+ assert.equal(dismissalFor({ ...issue, severity: 'medium' }, mark()), null);
+ assert.ok(dismissalFor({ ...issue, locations: [issue.locations[0]] }, mark()), 'one going away is not new');
+});
+
+test('the summary leaves dismissed issues out but the issues stay listed', () => {
+ const health = { summary: { high: 2, medium: 0, low: 0 }, issues: [issue, { id: 'other', severity: 'high', locations: [] }] };
+ const out = withDismissed(health, mark());
+ assert.deepEqual(out.summary, { high: 1, medium: 0, low: 0 });
+ assert.equal(out.issues.length, 2);
+ assert.equal(out.dismissed.length, 1);
+ assert.deepEqual(withDismissed(health, 'nonsense').summary, { high: 2, medium: 0, low: 0 });
+});
+
+test('the page applies the same rule as the build', () => {
+ const ui = fs.readFileSync(new URL('../skills/floorplan/assets/ui/20-health.js', import.meta.url), 'utf8');
+ for (const piece of [`d.severity && d.severity !== issue.severity`, `String(loc).replace(/:[^:]*$/, '')`, `left.get(l.file) || 0`]) assert.ok(ui.includes(piece), piece);
+});
+
+test('a report opens a GitHub issue for the person to send, and carries no code, fix prompt or detail', () => {
+ const ui = fs.readFileSync(new URL('../skills/floorplan/assets/ui/20-health.js', import.meta.url), 'utf8');
+ const report = /const reportText = [\s\S]*?\.join\('\\n'\);/.exec(ui)[0];
+ assert.ok(!/issue\.(fix|detail|notes)/.test(report), report);
+ assert.ok(/issues\/new/.test(ui));
+ assert.ok(!/fetch\([^)]*github/.test(ui), 'the page never sends a report itself');
+});
+
+// ---------- through the build and the server ----------
+let root, server, base, token;
+const NOTE = 'that value is only a sample, see the wiki';
+const dataOf = (html) => JSON.parse(/<script>window\.FLOORPLAN = (.*?);<\/script>/s.exec(html)[1]);
+const mapFile = (name) => path.join(root, 'floorplan', name);
+const call = (method, body, headers = { 'x-floorplan-token': token }) => fetch(base + '/api/health/dismissed', { method, headers: { 'content-type': 'application/json', ...headers }, ...(body ? { body: JSON.stringify(body) } : {}) });
+const exportPage = async (include) => (await fetch(base + '/api/export', { method: 'POST', headers: { 'content-type': 'application/json', 'x-floorplan-token': token }, body: JSON.stringify({ include }) })).text();
+
+before(async () => {
+ root = shopApp();
+ run('scan.mjs', root);
+ run('build.mjs', root, '--no-claude-md');
+ const port = 20000 + Math.floor(Math.random() * 20000);
+ server = spawn(process.execPath, [mapFile('serve.mjs'), '--port', String(port), '--no-open'], {
+ cwd: root, env: { ...process.env, FLOORPLAN_CLAUDE: path.join(root, 'no-such-cli'), FLOORPLAN_CODEX: path.join(root, 'no-such-codex') },
+ });
+ base = await new Promise((resolve, reject) => {
+ let out = '';
+ const timer = setTimeout(() => reject(new Error(`server didn't start: ${out}`)), 20000);
+ server.stdout.on('data', (d) => { out += d; const m = /Floorplan: (http:\/\/\S+)/.exec(out); if (m) { clearTimeout(timer); resolve(m[1].replace(/\/$/, '')); } });
+ server.on('exit', (code) => reject(new Error(`server exited (${code}): ${out}`)));
+ });
+ token = /"token":"([0-9a-f]+)"/.exec(await (await fetch(base + '/')).text())[1];
+});
+after(async () => {
+ if (server && server.exitCode === null) await new Promise((resolve) => { server.once('exit', resolve); server.kill(); });
+ cleanup(root);
+});
+
+test('saving a dismissal needs the token', async () => {
+ assert.equal((await call('POST', { id: 'x', locations: [] }, { 'x-floorplan-token': 'wrong' })).status, 403);
+ assert.ok(!fs.existsSync(mapFile('health-dismissed.json')));
+ assert.equal((await call('POST', { locations: [] })).status, 400);
+});
+
+test('a dismissal saved on the map survives a rebuild and leaves the counts; undoing it restores them', async () => {
+ const first = readGraph(root).health;
+ const target = first.issues.find((i) => i.kind === 'secret');
+ assert.ok(target && first.summary.high > 0);
+ const rec = { id: target.id, severity: target.severity, locations: target.locations.map((l) => `${l.file}:${l.line}`), reason: NOTE };
+ assert.equal((await (await call('POST', rec)).json()).dismissed.length, 1);
+ assert.equal((await (await call('POST', rec)).json()).dismissed.length, 1, 'saving twice replaces it');
+
+ const printed = run('build.mjs', root, '--no-claude-md', '--artifact');
+ const health = readGraph(root).health;
+ assert.equal(health.summary.high, first.summary.high - 1);
+ assert.equal(health.issues.length, first.issues.length, 'it stays listed');
+ assert.equal(health.dismissed[0].reason, NOTE);
+ assert.ok(!printed.includes(`[high] ${target.title}`), 'and the build report leaves it out');
+
+ // reasons are notes to self: they stay on this computer
+ assert.ok(!fs.readFileSync(mapFile('artifact.html'), 'utf8').includes(NOTE), 'not in the copy for the Claude app');
+ const exported = await exportPage(['health']);
+ assert.ok(!exported.includes(NOTE), 'not in an exported copy');
+ assert.equal(dataOf(exported).health.dismissed[0].id, target.id, 'though the copy still sets the issue apart');
+ assert.equal(dataOf(await exportPage([])).health, undefined);
+
+ assert.deepEqual((await (await call('DELETE', { id: target.id })).json()).dismissed, []);
+ run('build.mjs', root, '--no-claude-md');
+ assert.deepEqual(readGraph(root).health.summary, first.summary);
+ assert.equal(readGraph(root).health.dismissed, undefined);
+});
+
+test('a hand-broken dismissal file warns and does not break the map', () => {
+ fs.writeFileSync(mapFile('health-dismissed.json'), '{ not json');
+ assert.ok(run('build.mjs', root, '--no-claude-md').includes('wrote'));
+ assert.ok(readGraph(root).health.issues.length > 0);
+ fs.rmSync(mapFile('health-dismissed.json'));
+});