fix(browse): extension token bootstrap moves to pinned-origin POST; /health carries no token

GET /health is now liveness/status only in every mode — both token
carve-outs (headed-mode disjunct AND chrome-extension:// Origin
disjunct) are removed. Token bootstrap is POST /extension-token on the
local listener: the Origin header must be exactly
chrome-extension://<GSTACK_EXTENSION_ID> and the Host header's hostname
must parse to 127.0.0.1 or localhost (parsed via new URL, never literal
equality — Host arrives as '127.0.0.1:34567'). Wrong origin/host → 403
with no detail. The tunnel surface 404s the endpoint (not in
TUNNEL_PATHS, verified by test).

The extension ID is pinned by a new "key" field (RSA public key) in
extension/manifest.json; browse/scripts/extension-id.ts reproduces the
ID derivation (first 16 bytes of SHA-256 of the DER public key, hex
mapped 0-9a-f → a-p). The private key is not committed anywhere —
unpacked/baked-in loads only need the public key.

Extension side: background.js bootstraps and refreshes the token via
POST /extension-token (403 → disconnected state); sidepanel.js direct
connect path does the same; sidepanel-terminal.js's dead /health token
fallback (read AUTH_TOKEN/authToken keys the server never sent,
hardcoded port) is replaced with the window.gstackAuthToken path.

MIGRATION NOTE: the manifest key pins the extension ID, so existing
installs' side-panel local state (saved port, snoozes) resets once —
explained in-product via a one-time notice (flag
gstack_id_migrated_v162). After upgrading the server, restart the
browser so the old service worker stops polling for a token GET /health
no longer serves.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
(cherry picked from commit e9a0b6847a2d17fe6656a4686b4efd0c8380eb09)
This commit is contained in:
Garry Tan
2026-08-12 15:31:49 -07:00
parent 2ae38785a1
commit a2751b7cf2
14 changed files with 471 additions and 94 deletions
+63 -30
View File
@@ -32,22 +32,34 @@ function getBaseUrl() {
// ─── Auth Token Bootstrap ─────────────────────────────────────
// Token bootstrap: POST /extension-token. The server validates our Origin
// (chrome-extension://<pinned id> — the manifest "key" pins the ID) before
// releasing the token. GET /health is liveness/status only and never
// carries a token. Returns true on success, false on failure; a 403 means
// the server doesn't trust this extension identity — treat as disconnected
// rather than retrying forever with a stale token.
async function loadAuthToken() {
if (authToken) return;
// Get token from browse server /health endpoint (localhost-only, safe).
// Previously read from .auth.json in extension dir, but that breaks
// read-only .app bundles and codesigning.
const base = getBaseUrl();
if (!base) return;
if (!base) return false;
try {
const resp = await fetch(`${base}/health`, { signal: AbortSignal.timeout(3000) });
const resp = await fetch(`${base}/extension-token`, {
method: 'POST',
signal: AbortSignal.timeout(3000),
});
if (resp.status === 403) {
console.error('[gstack bg] /extension-token 403 — extension identity not trusted by server');
authToken = null;
setDisconnected();
return false;
}
if (resp.ok) {
const data = await resp.json();
if (data.token) authToken = data.token;
if (data.token) { authToken = data.token; return true; }
}
} catch (err) {
console.error('[gstack bg] Failed to load auth token:', err.message);
}
return false;
}
// ─── Health Polling ────────────────────────────────────────────
@@ -59,17 +71,16 @@ 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') {
// Always refresh auth token from /health — the server generates a new
// token on each restart, so the old one becomes stale.
if (data.token) authToken = data.token;
// Always refresh the auth token — the server generates a new token
// on each restart, so the old one becomes stale. loadAuthToken()
// already flips to disconnected on a 403.
const gotToken = await loadAuthToken();
if (!gotToken && !authToken) return;
// Forward chatEnabled so sidepanel can show/hide chat tab
setConnected({ ...data, chatEnabled: !!data.chatEnabled });
} else {
@@ -577,27 +588,49 @@ chrome.tabs.onUpdated.addListener((_id, changeInfo) => {
}
});
// ─── v1.62 identity-pin migration notice ────────────────────────
//
// The manifest "key" added in v1.62 pins the extension ID, which changes
// the ID for existing installs — chrome.storage.local is keyed by
// extension ID, so panel-local state (saved port, snoozes) resets once.
// Explain that in-product, one time.
async function announceIdentityPinOnce() {
try {
const data = await chrome.storage.local.get('gstack_id_migrated_v162');
if (data.gstack_id_migrated_v162) return;
console.log('[gstack] gstack sidebar: extension identity pinned in v1.62 — panel state reset once.');
chrome.runtime.sendMessage({
type: 'gstack-migration-notice',
message: 'gstack sidebar: extension identity pinned in v1.62 — panel state reset once.',
}).catch(() => {
// Expected: panel not open. The console line above still lands.
});
await chrome.storage.local.set({ gstack_id_migrated_v162: true });
} catch (err) {
console.debug('[gstack] identity-pin notice failed (non-fatal):', err.message);
}
}
// ─── Startup ────────────────────────────────────────────────────
// Fast-retry health check on startup. The server may not be listening yet
// (Chromium launches before Bun.serve starts). Retry every 1s for the
// first 15 seconds, then switch to 10s polling.
loadAuthToken().then(() => {
loadPort().then(() => {
let startupAttempts = 0;
const startupCheck = setInterval(async () => {
startupAttempts++;
await checkHealth();
if (isConnected || startupAttempts >= 15) {
clearInterval(startupCheck);
// Switch to slow polling now that we're connected (or gave up)
if (!healthInterval) {
healthInterval = setInterval(checkHealth, 10000);
}
if (!isConnected) {
console.log('[gstack] Startup health checks failed after 15 attempts, falling back to 10s polling');
}
announceIdentityPinOnce();
loadPort().then(() => {
let startupAttempts = 0;
const startupCheck = setInterval(async () => {
startupAttempts++;
await checkHealth();
if (isConnected || startupAttempts >= 15) {
clearInterval(startupCheck);
// Switch to slow polling now that we're connected (or gave up)
if (!healthInterval) {
healthInterval = setInterval(checkHealth, 10000);
}
}, 1000);
});
if (!isConnected) {
console.log('[gstack] Startup health checks failed after 15 attempts, falling back to 10s polling');
}
}
}, 1000);
});
+1
View File
@@ -3,6 +3,7 @@
"name": "gstack browse",
"version": "0.1.0",
"description": "Live activity feed and @ref overlays for gstack browse",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApp4uyDmQADJ/MPoKybEvBPpuGWxsXiNMo5jJFFaEaC3yPJnB4y8E0UuvE56n2KlQzaqlnBOt4T8w0ApTbNABZpEnSGQJVmkbT8a62WXefYZm79bMgzW/bNIZ4QYWNEAtZb0wvncMNSOyU9mga1s3eGWtukHs2Zf5spXRLQGV/on9l8iN9QPRM/VB0AxtUc2DTYjwkTGCAOMFiaq02miP0/hW6AeltBW9R0aHgbnJw2H2YVrgQXRvGxD1DMQe6NzGVVqKGhpUdYGPw4ONWOKijdignz+j+90HSrCK06HUy80jiKAYmdZePnn++N5meIJY+bWk7RqxS6er8Ow2U65TywIDAQAB",
"permissions": ["sidePanel", "storage", "activeTab", "scripting", "tabs"],
"host_permissions": ["http://127.0.0.1:*/", "ws://127.0.0.1:*/"],
"action": {
+8 -15
View File
@@ -504,7 +504,8 @@
window.gstackScanForPTYInject = async function (text, origin) {
if (!text) return { allow: false, verdict: 'BLOCK', reasons: ['empty-text'] };
try {
const resp = await fetch('http://127.0.0.1:34567/pty-inject-scan', {
const serverPort = getServerPort() || 34567;
const resp = await fetch(`http://127.0.0.1:${serverPort}/pty-inject-scan`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -529,21 +530,13 @@
};
// The auth token for /pty-inject-scan comes from the same source the
// sidepanel uses for /pty-session — a runtime fetch from /health (which
// already returns AUTH_TOKEN in headed mode per CLAUDE.md's v1.1 TODO).
// We don't echo the token here; this helper is a thin proxy around the
// existing pattern.
// sidepanel uses for /pty-session — window.gstackAuthToken, set by
// sidepanel.js after the pinned-origin POST /extension-token bootstrap.
// The old fallback here fetched /health and read token keys the server
// never sent (AUTH_TOKEN/authToken) — dead code since /health stopped
// carrying any token.
async function getAuthTokenForScan() {
if (window.__gstackPtyScanToken) return window.__gstackPtyScanToken;
try {
const resp = await fetch('http://127.0.0.1:34567/health');
const body = await resp.json();
const token = body.AUTH_TOKEN || body.authToken || '';
if (token) window.__gstackPtyScanToken = token;
return token;
} catch {
return '';
}
return getAuthToken() || '';
}
async function connect() {
+44 -12
View File
@@ -1304,21 +1304,36 @@ async function tryConnect() {
});
if (healthResp.ok) {
const data = await healthResp.json();
if (data.status === 'healthy' && data.token) {
if (data.status === 'healthy') {
// /health is liveness-only — the token comes from the pinned-origin
// POST /extension-token bootstrap (our chrome-extension:// Origin
// is validated server-side against the manifest-pinned ID).
const tokenResp = await fetch(`http://127.0.0.1:${port}/extension-token`, {
method: 'POST',
signal: AbortSignal.timeout(2000),
});
const tokenData = tokenResp.ok ? await tokenResp.json() : null;
if (tokenData?.token) {
setLoadingStatus(
`Server healthy on port ${port}, connecting...`,
`token: yes (from /extension-token)\nStarting SSE + activity feed...`
);
updateConnection(`http://127.0.0.1:${port}`, tokenData.token);
// The SEC shield used to drive off /health.security via the chat
// path's classifier; with the chat path ripped, the indicator is
// not driven yet. Leaving the shield element hidden by default.
return;
}
setLoadingStatus(
`Server healthy on port ${port}, connecting...`,
`token: yes (from /health)\nStarting SSE + activity feed...`
`Server healthy but token bootstrap failed (attempt ${connectAttempts})`,
`POST /extension-token → ${tokenResp.status}${tokenResp.status === 403 ? ' (extension identity not trusted)' : ''}`
);
} else {
setLoadingStatus(
`Server responded but not healthy (attempt ${connectAttempts})`,
`status: ${data.status}`
);
updateConnection(`http://127.0.0.1:${port}`, data.token);
// The SEC shield used to drive off /health.security via the chat
// path's classifier; with the chat path ripped, the indicator is
// not driven yet. Leaving the shield element hidden by default.
return;
}
setLoadingStatus(
`Server responded but not healthy (attempt ${connectAttempts})`,
`status: ${data.status}\ntoken: ${data.token ? 'yes' : 'no'}`
);
} else {
setLoadingStatus(
`Server returned ${healthResp.status} (attempt ${connectAttempts})`,
@@ -1355,6 +1370,23 @@ chrome.runtime.onMessage.addListener((msg) => {
fetchRefs();
}
}
// One-time v1.62 identity-pin notice from background.js. Transient banner —
// no dedicated element in sidepanel.html since this fires once per install.
if (msg.type === 'gstack-migration-notice' && msg.message) {
console.log('[gstack sidebar]', msg.message);
try {
const banner = document.createElement('div');
banner.textContent = msg.message;
banner.style.cssText =
'position:fixed;left:8px;right:8px;bottom:40px;z-index:9999;' +
'background:#1f2937;color:#f5a623;border:1px solid #f5a623;' +
'border-radius:6px;padding:8px 10px;font-size:12px;text-align:left;';
document.body.appendChild(banner);
setTimeout(() => banner.remove(), 8000);
} catch (err) {
console.debug('[gstack sidebar] migration banner failed:', err && err.message);
}
}
if (msg.type === 'inspectResult') {
inspectorPickerActive = false;
inspectorPickBtn.classList.remove('active');