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
This commit is contained in:
Garry Tan
2026-03-27 22:13:45 -07:00
parent 11695e3aca
commit e16bf23ca0
6 changed files with 114 additions and 40 deletions

1
.gitignore vendored
View File

@@ -6,6 +6,7 @@ bin/gstack-global-discover
.claude/skills/ .claude/skills/
.agents/ .agents/
.context/ .context/
extension/.auth.json
.gstack-worktrees/ .gstack-worktrees/
/tmp/ /tmp/
*.log *.log

View File

@@ -211,7 +211,7 @@ export class BrowserManager {
* The browser launches headed with a visible window — the user sees * The browser launches headed with a visible window — the user sees
* every action Claude takes in real time. * every action Claude takes in real time.
*/ */
async launchHeaded(): Promise<void> { async launchHeaded(authToken?: string): Promise<void> {
// Clear old state before repopulating // Clear old state before repopulating
this.pages.clear(); this.pages.clear();
this.refMap.clear(); this.refMap.clear();
@@ -223,6 +223,17 @@ export class BrowserManager {
if (extensionPath) { if (extensionPath) {
launchArgs.push(`--disable-extensions-except=${extensionPath}`); launchArgs.push(`--disable-extensions-except=${extensionPath}`);
launchArgs.push(`--load-extension=${extensionPath}`); launchArgs.push(`--load-extension=${extensionPath}`);
// Write auth token for extension bootstrap (read via chrome.runtime.getURL)
if (authToken) {
const fs = require('fs');
const path = require('path');
const authFile = path.join(extensionPath, '.auth.json');
try {
fs.writeFileSync(authFile, JSON.stringify({ token: authToken }), { mode: 0o600 });
} catch (err: any) {
console.warn(`[browse] Could not write .auth.json: ${err.message}`);
}
}
} }
// Launch headed Chromium via Playwright's persistent context. // Launch headed Chromium via Playwright's persistent context.
@@ -751,6 +762,20 @@ export class BrowserManager {
if (extensionPath) { if (extensionPath) {
launchArgs.push(`--disable-extensions-except=${extensionPath}`); launchArgs.push(`--disable-extensions-except=${extensionPath}`);
launchArgs.push(`--load-extension=${extensionPath}`); launchArgs.push(`--load-extension=${extensionPath}`);
// Write auth token for extension bootstrap during handoff
if (this.serverPort) {
try {
const { resolveConfig } = require('./config');
const config = resolveConfig();
const stateFile = path.join(config.stateDir, 'browse.json');
if (fs.existsSync(stateFile)) {
const stateData = JSON.parse(fs.readFileSync(stateFile, 'utf-8'));
if (stateData.token) {
fs.writeFileSync(path.join(extensionPath, '.auth.json'), JSON.stringify({ token: stateData.token }), { mode: 0o600 });
}
}
} catch {}
}
console.log(`[browse] Handoff: loading extension from ${extensionPath}`); console.log(`[browse] Handoff: loading extension from ${extensionPath}`);
} else { } else {
console.log('[browse] Handoff: extension not found — headed mode without side panel'); console.log('[browse] Handoff: extension not found — headed mode without side panel');

View File

@@ -805,7 +805,7 @@ async function start() {
if (!skipBrowser) { if (!skipBrowser) {
const headed = process.env.BROWSE_HEADED === '1'; const headed = process.env.BROWSE_HEADED === '1';
if (headed) { if (headed) {
await browserManager.launchHeaded(); await browserManager.launchHeaded(AUTH_TOKEN);
console.log(`[browse] Launched headed Chromium with extension`); console.log(`[browse] Launched headed Chromium with extension`);
} else { } else {
await browserManager.launch(); await browserManager.launch();
@@ -819,9 +819,9 @@ async function start() {
fetch: async (req) => { fetch: async (req) => {
const url = new URL(req.url); const url = new URL(req.url);
// Cookie picker routes — no auth required (localhost-only) // Cookie picker routes — HTML page unauthenticated, data/action routes require auth
if (url.pathname.startsWith('/cookie-picker')) { if (url.pathname.startsWith('/cookie-picker')) {
return handleCookiePickerRoute(url, req, browserManager); return handleCookiePickerRoute(url, req, browserManager, AUTH_TOKEN);
} }
// Health check — no auth required, does NOT reset idle timer // Health check — no auth required, does NOT reset idle timer
@@ -833,7 +833,7 @@ async function start() {
uptime: Math.floor((Date.now() - startTime) / 1000), uptime: Math.floor((Date.now() - startTime) / 1000),
tabs: browserManager.getTabCount(), tabs: browserManager.getTabCount(),
currentUrl: browserManager.getCurrentUrl(), currentUrl: browserManager.getCurrentUrl(),
token: AUTH_TOKEN, // Extension uses this for Bearer auth // token removed — see .auth.json for extension bootstrap
chatEnabled: true, chatEnabled: true,
agent: { agent: {
status: agentStatus, status: agentStatus,
@@ -848,8 +848,14 @@ async function start() {
}); });
} }
// Refs endpoint — no auth required (localhost-only), does NOT reset idle timer // Refs endpoint — auth required, does NOT reset idle timer
if (url.pathname === '/refs') { if (url.pathname === '/refs') {
if (!validateAuth(req)) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
const refs = browserManager.getRefMap(); const refs = browserManager.getRefMap();
return new Response(JSON.stringify({ return new Response(JSON.stringify({
refs, refs,
@@ -857,15 +863,20 @@ async function start() {
mode: browserManager.getConnectionMode(), mode: browserManager.getConnectionMode(),
}), { }), {
status: 200, status: 200,
headers: { headers: { 'Content-Type': 'application/json' },
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
}); });
} }
// Activity stream — SSE, no auth (localhost-only), does NOT reset idle timer // Activity stream — SSE, auth required, does NOT reset idle timer
if (url.pathname === '/activity/stream') { if (url.pathname === '/activity/stream') {
// Inline auth: accept Bearer header OR ?token= query param (EventSource can't send headers)
const streamToken = url.searchParams.get('token');
if (!validateAuth(req) && streamToken !== AUTH_TOKEN) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
const afterId = parseInt(url.searchParams.get('after') || '0', 10); const afterId = parseInt(url.searchParams.get('after') || '0', 10);
const encoder = new TextEncoder(); const encoder = new TextEncoder();
@@ -913,21 +924,23 @@ async function start() {
'Content-Type': 'text/event-stream', 'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache', 'Cache-Control': 'no-cache',
'Connection': 'keep-alive', 'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
}, },
}); });
} }
// Activity history — REST, no auth (localhost-only), does NOT reset idle timer // Activity history — REST, auth required, does NOT reset idle timer
if (url.pathname === '/activity/history') { if (url.pathname === '/activity/history') {
if (!validateAuth(req)) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
const limit = parseInt(url.searchParams.get('limit') || '50', 10); const limit = parseInt(url.searchParams.get('limit') || '50', 10);
const { entries, totalAdded } = getActivityHistory(limit); const { entries, totalAdded } = getActivityHistory(limit);
return new Response(JSON.stringify({ entries, totalAdded, subscribers: getSubscriberCount() }), { return new Response(JSON.stringify({ entries, totalAdded, subscribers: getSubscriberCount() }), {
status: 200, status: 200,
headers: { headers: { 'Content-Type': 'application/json' },
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
}); });
} }
@@ -1139,6 +1152,23 @@ async function start() {
fs.renameSync(tmpFile, config.stateFile); fs.renameSync(tmpFile, config.stateFile);
browserManager.serverPort = port; browserManager.serverPort = port;
// Clean up stale state files (older than 7 days)
try {
const stateDir = path.join(config.stateDir, 'browse-states');
if (fs.existsSync(stateDir)) {
const SEVEN_DAYS = 7 * 24 * 60 * 60 * 1000;
for (const file of fs.readdirSync(stateDir)) {
const filePath = path.join(stateDir, file);
const stat = fs.statSync(filePath);
if (Date.now() - stat.mtimeMs > SEVEN_DAYS) {
fs.unlinkSync(filePath);
console.log(`[browse] Deleted stale state file: ${file}`);
}
}
}
} catch {}
console.log(`[browse] Server running on http://127.0.0.1:${port} (PID: ${process.pid})`); console.log(`[browse] Server running on http://127.0.0.1:${port} (PID: ${process.pid})`);
console.log(`[browse] State file: ${config.stateFile}`); console.log(`[browse] State file: ${config.stateFile}`);
console.log(`[browse] Idle timeout: ${IDLE_TIMEOUT_MS / 1000}s`); console.log(`[browse] Idle timeout: ${IDLE_TIMEOUT_MS / 1000}s`);

View File

@@ -66,10 +66,11 @@ function writeToInbox(message: string, pageUrl?: string, sessionId?: string): vo
// ─── Auth ──────────────────────────────────────────────────────── // ─── Auth ────────────────────────────────────────────────────────
async function refreshToken(): Promise<string | null> { async function refreshToken(): Promise<string | null> {
// Read token from state file (same-user, mode 0o600) instead of /health
try { try {
const resp = await fetch(`${SERVER_URL}/health`, { signal: AbortSignal.timeout(3000) }); const stateFile = process.env.BROWSE_STATE_FILE ||
if (!resp.ok) return null; path.join(process.env.HOME || '/tmp', '.gstack', 'browse.json');
const data = await resp.json() as any; const data = JSON.parse(fs.readFileSync(stateFile, 'utf-8'));
authToken = data.token || null; authToken = data.token || null;
return authToken; return authToken;
} catch { } catch {

View File

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

View File

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