fix: security audit remediation — 12 fixes, 20 tests (v0.13.1.0) (#595)

* fix: remove auth token from /health, secure extension bootstrap (CRITICAL-02 + HIGH-03)

- Remove token from /health response (was leaked to any localhost process)
- Write .auth.json to extension dir for Manifest V3 bootstrap
- sidebar-agent reads token from state file via BROWSE_STATE_FILE env var
- Remove getToken handler from extension (token via health broadcast)
- Extension loads token before first health poll to prevent race condition

* fix: require auth on cookie-picker data routes (CRITICAL-01)

- Add Bearer token auth gate on all /cookie-picker/* data/action routes
- GET /cookie-picker HTML page stays unauthenticated (UI shell)
- Token embedded in served HTML for picker's fetch calls
- CORS preflight now allows Authorization header

* fix: add state file TTL and plaintext cookie warning (HIGH-02)

- Add savedAt timestamp to state save output
- Warn on load if state file older than 7 days
- Auto-delete stale state files (>7 days) on server startup
- Warning about plaintext cookie storage in save message

* fix: innerHTML XSS in extension content script and sidepanel (MEDIUM-01)

- content.js: replace innerHTML with createElement/textContent for ref panel
- sidepanel.js: escape entry.command with escapeHtml() in activity feed
- Both found by security audit + Codex adversarial red team

* fix: symlink bypass in validateReadPath (MEDIUM-02)

- Always resolve to absolute path first (fixes relative path bypass)
- Use realpathSync to follow symlinks before boundary check
- Throw on non-ENOENT realpathSync failures (explicit over silent)
- Resolve SAFE_DIRECTORIES through realpathSync (macOS /tmp → /private/tmp)
- Resolve directory part for non-existent files (ENOENT with symlinked parent)

* fix: freeze hook symlink bypass and prefix collision (MEDIUM-03)

- Add POSIX-portable path resolution (cd + pwd -P, works on macOS)
- Fix prefix collision: /project-evil no longer matches /project freeze dir
- Use trailing slash in boundary check to require directory boundary

* fix: shell script injection in gstack-config and telemetry (MEDIUM-04)

- gstack-config: validate keys (alphanumeric+underscore only)
- gstack-config: use grep -F (fixed string) instead of -E (regex)
- gstack-config: escape sed special chars in values, drop newlines
- gstack-telemetry-log: sanitize REPO_SLUG and BRANCH via json_safe()

* test: 20 security tests for audit remediation

- server-auth: verify token removed from /health, auth on /refs, /activity/*
- cookie-picker: auth required on data routes, HTML page unauthenticated
- path-validation: symlink bypass blocked, realpathSync failure throws
- gstack-config: regex key rejected, sed special chars preserved
- state-ttl: savedAt timestamp, 7-day TTL warning
- telemetry: branch/repo with quotes don't corrupt JSON
- adversarial: sidepanel escapes entry.command, freeze prefix collision

* chore: bump version and changelog (v0.13.1.0)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: tone down changelog — defense in depth, not catastrophic bugs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Garry Tan
2026-03-28 08:35:24 -06:00
committed by GitHub
parent 78bc1d1968
commit 7450b5160b
24 changed files with 489 additions and 67 deletions

View File

@@ -30,6 +30,19 @@ function getBaseUrl() {
return serverPort ? `http://127.0.0.1:${serverPort}` : null;
}
// ─── Auth Token Bootstrap ─────────────────────────────────────
async function loadAuthToken() {
if (authToken) return;
try {
const resp = await fetch(chrome.runtime.getURL('.auth.json'));
if (resp.ok) {
const data = await resp.json();
if (data.token) authToken = data.token;
}
} catch {}
}
// ─── Health Polling ────────────────────────────────────────────
async function checkHealth() {
@@ -39,13 +52,14 @@ async function checkHealth() {
return;
}
// Retry loading auth token if we don't have one yet
if (!authToken) await loadAuthToken();
try {
const resp = await fetch(`${base}/health`, { signal: AbortSignal.timeout(3000) });
if (!resp.ok) { setDisconnected(); return; }
const data = await resp.json();
if (data.status === 'healthy') {
// Capture auth token from health response
if (data.token) authToken = data.token;
// Forward chatEnabled so sidepanel can show/hide chat tab
setConnected({ ...data, chatEnabled: !!data.chatEnabled });
} else {
@@ -62,8 +76,8 @@ function setConnected(healthData) {
chrome.action.setBadgeBackgroundColor({ color: '#F59E0B' });
chrome.action.setBadgeText({ text: ' ' });
// Broadcast health to popup and side panel
chrome.runtime.sendMessage({ type: 'health', data: healthData }).catch(() => {});
// Broadcast health to popup and side panel (include token for sidepanel auth)
chrome.runtime.sendMessage({ type: 'health', data: { ...healthData, token: authToken } }).catch(() => {});
// Notify content scripts on connection change
if (wasDisconnected) {
@@ -74,7 +88,7 @@ function setConnected(healthData) {
function setDisconnected() {
const wasConnected = isConnected;
isConnected = false;
authToken = null;
// Keep authToken — it comes from .auth.json, not /health
chrome.action.setBadgeText({ text: '' });
chrome.runtime.sendMessage({ type: 'health', data: null }).catch(() => {});
@@ -128,7 +142,9 @@ async function fetchAndRelayRefs() {
if (!base || !isConnected) return;
try {
const resp = await fetch(`${base}/refs`, { signal: AbortSignal.timeout(3000) });
const headers = {};
if (authToken) headers['Authorization'] = `Bearer ${authToken}`;
const resp = await fetch(`${base}/refs`, { signal: AbortSignal.timeout(3000), headers });
if (!resp.ok) return;
const data = await resp.json();
@@ -163,10 +179,7 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
return true;
}
if (msg.type === 'getToken') {
sendResponse({ token: authToken });
return true;
}
// getToken handler removed — token distributed via health broadcast
if (msg.type === 'fetchRefs') {
fetchAndRelayRefs().then(() => sendResponse({ ok: true }));
@@ -237,7 +250,10 @@ chrome.runtime.onInstalled.addListener(async () => {
// ─── Startup ────────────────────────────────────────────────────
loadPort().then(() => {
checkHealth();
healthInterval = setInterval(checkHealth, 10000);
// Load auth token BEFORE first health poll (token no longer in /health response)
loadAuthToken().then(() => {
loadPort().then(() => {
checkHealth();
healthInterval = setInterval(checkHealth, 10000);
});
});

View File

@@ -103,7 +103,16 @@ function renderRefPanel(refs) {
for (const ref of refs.slice(0, 30)) { // Show max 30 in panel
const row = document.createElement('div');
row.className = 'gstack-ref-panel-row';
row.innerHTML = `<span class="gstack-ref-panel-id">${ref.ref}</span> <span class="gstack-ref-panel-role">${ref.role}</span> <span class="gstack-ref-panel-name">"${ref.name}"</span>`;
const idSpan = document.createElement('span');
idSpan.className = 'gstack-ref-panel-id';
idSpan.textContent = ref.ref;
const roleSpan = document.createElement('span');
roleSpan.className = 'gstack-ref-panel-role';
roleSpan.textContent = ref.role;
const nameSpan = document.createElement('span');
nameSpan.className = 'gstack-ref-panel-name';
nameSpan.textContent = '"' + ref.name + '"';
row.append(idSpan, document.createTextNode(' '), roleSpan, document.createTextNode(' '), nameSpan);
list.appendChild(row);
}
if (refs.length > 30) {

View File

@@ -413,7 +413,7 @@ function createEntryElement(entry) {
div.innerHTML = `
<div class="entry-header">
<span class="entry-time">${formatTime(entry.timestamp)}</span>
<span class="entry-command">${entry.command || entry.type}</span>
<span class="entry-command">${escapeHtml(entry.command || entry.type)}</span>
</div>
${argsText ? `<div class="entry-args">${escapeHtml(argsText)}</div>` : ''}
${entry.type === 'command_end' ? `
@@ -469,7 +469,8 @@ function connectSSE() {
if (!serverUrl) return;
if (eventSource) { eventSource.close(); eventSource = null; }
const url = `${serverUrl}/activity/stream?after=${lastId}`;
const tokenParam = serverToken ? `&token=${serverToken}` : '';
const url = `${serverUrl}/activity/stream?after=${lastId}${tokenParam}`;
eventSource = new EventSource(url);
eventSource.addEventListener('activity', (e) => {
@@ -493,7 +494,9 @@ function connectSSE() {
async function fetchRefs() {
if (!serverUrl) return;
try {
const resp = await fetch(`${serverUrl}/refs`, { signal: AbortSignal.timeout(3000) });
const headers = {};
if (serverToken) headers['Authorization'] = `Bearer ${serverToken}`;
const resp = await fetch(`${serverUrl}/refs`, { signal: AbortSignal.timeout(3000), headers });
if (!resp.ok) return;
const data = await resp.json();
@@ -594,10 +597,8 @@ function tryConnect() {
chrome.runtime.sendMessage({ type: 'getPort' }, (resp) => {
if (resp && resp.port && resp.connected) {
const url = `http://127.0.0.1:${resp.port}`;
// Get the token from background
chrome.runtime.sendMessage({ type: 'getToken' }, (tokenResp) => {
updateConnection(url, tokenResp?.token);
});
// Token arrives via health broadcast from background.js
updateConnection(url, null);
} else {
setTimeout(tryConnect, 2000);
}