mirror of
https://github.com/garrytan/gstack.git
synced 2026-05-28 05:52:26 +02:00
v1.34.0.0 feat: gstack consumable as submodule (factory-export API + AUTH_TOKEN env + import.meta.main gate) (#1472)
* feat(config): add resolveGstackHome, resolveChromiumProfile, cleanSingletonLocks Three new exported helpers in browse/src/config.ts: - resolveGstackHome(): honors GSTACK_HOME env, falls back to os.homedir()/.gstack Matches the existing convention in browse/src/telemetry.ts:26 and browse/src/domain-skills.ts:66. - resolveChromiumProfile(explicit?): explicit arg wins -> CHROMIUM_PROFILE env -> resolveGstackHome()/chromium-profile. Lets gbrowser pass per-workspace profile paths through ServerConfig instead of relying on ambient env state. - cleanSingletonLocks(dir): removes SingletonLock/Socket/Cookie via safeUnlinkQuiet. Defensive guard refuses to operate unless dir basename is 'chromium-profile' OR matches explicit CHROMIUM_PROFILE env value, preventing accidental deletion in unrelated directories. Extends browse/test/config.test.ts with 12 tests covering env precedence, guard behavior, ENOENT swallowing, and CHROMIUM_PROFILE override. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(security-classifier): TDZ when claude CLI is missing from PATH The checkTranscript Promise executor in browse/src/security-classifier.ts referenced `finish()` at the !claude early-return guard before declaring it 5 lines later. JavaScript throws ReferenceError: Cannot access 'finish' before initialization (TDZ) for that path, but the path is only reachable when resolveClaudeCommand returns null inside the spawn block (a TOCTOU window vs. the outer checkHaikuAvailable cache). Fix: hoist `let stdout = ''`, `let done = false`, and `const finish` block above `const claude = resolveClaudeCommand()` so finish is in scope before any reference to it. Behavior is identical when claude is on PATH; the fix only matters for the dormant missing-CLI degraded path. Adds browse/test/security-classifier-tdz.test.ts as the regression guard: clears PATH + override env vars, calls checkTranscript, asserts the result serializes with degraded:true and a meaningful reason field. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(browser-manager): isCustomChromium gate + per-workspace profile + lock cleanup Three fold-ins so gbrowser can become a thin overlay instead of forking browse-server: - Export isCustomChromium(): detects custom Chromium builds that bake the extension in as a component extension. Prefers explicit GSTACK_CHROMIUM_KIND=custom-extension-baked signal; falls back to GSTACK_CHROMIUM_PATH substring containing 'GBrowser' / 'gbrowser'. Gates the --load-extension push at launchHeaded so we don't trigger ServiceWorkerState::SetWorkerId DCHECK when two copies of the same service worker race to register. - Swap hardcoded path.join(HOME, '.gstack', 'chromium-profile') in launchHeaded for resolveChromiumProfile() so phoenix can pass a per-workspace profile via CHROMIUM_PROFILE env (one daemon per gbd workspace, each with a distinct profile dir). - Call cleanSingletonLocks(userDataDir) immediately after mkdirSync. Chromium's ProcessSingleton refuses to start when stale SingletonLock/Socket/Cookie files survive a SIGKILL or hard crash; pre-launch cleanup defends against the crash case. Safe under external coordination (gbd.lock for gbrowser, single-instance CLI check for gstack). The existing .auth.json write at L291-302 is preserved — extensions still need it for bootstrap even when component-baked. Adds browse/test/browser-manager-custom-chromium.test.ts with 8 tests covering both the env-kind and path-substring signals plus stock / playwright-bundled Chromium negative cases. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(server): factory-export API surface + import.meta.main gate Surfaces the embedder API gbrowser (phoenix) needs to consume gstack as a submodule, and gates module-load side effects so the file is safe to import without auto-starting a daemon. Changes to browse/src/server.ts: - AUTH_TOKEN now honors process.env.AUTH_TOKEN (trimmed) before falling back to crypto.randomUUID(). Whitespace-only values are rejected so the security boundary can't be silently weakened. - New exported types: ServerConfig and ServerHandle. ServerConfig documents the full factory contract (authToken, browsePort, idleTimeoutMs, config, browserManager, chromiumProfile, xvfb, proxyBridge, startTime, beforeRoute). ServerHandle documents the return shape (fetchLocal, fetchTunnel, shutdown, stopListeners). Caller-owned lifecycle annotations on xvfb and proxyBridge prevent double-close bugs from surprise ownership. - New exported function: resolveConfigFromEnv() builds a ServerConfig-shaped object from process.env for CLI use. Embedders construct their own ServerConfig explicitly. - start() is now exported. Embedders can call it with env vars set as a v1 escape hatch until full buildFetchHandler extraction lands. - Signal handlers (SIGINT, SIGTERM, Windows exit, uncaughtException, unhandledRejection) and the auto-kickoff at module bottom are now wrapped in `if (import.meta.main)`. CLI path is unchanged. Embedders register their own handlers. - shutdown() and emergencyCleanup() now call cleanSingletonLocks( resolveChromiumProfile()) instead of inline path+loop. Single implementation, defensive guard, honors per-workspace CHROMIUM_PROFILE. New tests: - browse/test/server-no-import-side-effects.test.ts: spawns a fresh Bun subprocess that imports server.ts, asserts no signal handlers registered, no state-dir populated. Guards the core refactor invariant from regression. - browse/test/server-factory.test.ts: 12 tests covering AUTH_TOKEN env behavior (honored, whitespace-rejected, trimmed), preserved exports (TUNNEL_COMMANDS, canDispatchOverTunnel), and ServerConfig/ServerHandle type compatibility. Deferred to follow-up PR: full buildFetchHandler extraction that hoists the 13 module-level mutables + helpers into a factory closure. Phoenix can ship v0.6.0.0 against the start()+env surface today; the cleaner factory comes next. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: harden auth-token validation, TDZ try/catch, lockfile path safety Three security hardening fixes from /ship adversarial review: 1. AUTH_TOKEN unicode-whitespace bypass (server.ts:67-83). Old: `process.env.AUTH_TOKEN?.trim() || randomUUID()` only stripped ASCII whitespace. A misconfigured embedder shipping AUTH_TOKEN=$'' (BOM) or $'' (zero-width space) would silently get a one-character bearer secret. New `sanitizeAuthToken()` strips all unicode whitespace via regex and requires >= 16 chars after stripping; anything shorter falls back to crypto.randomUUID(). Same sanitizer used by `resolveConfigFromEnv()` so the embedder path is hardened too. 2. security-classifier.ts checkTranscript safety net. `resolveClaudeCommand()` and `spawn()` can throw under transient conditions (PATH probe failure, posix_spawn ENOMEM). Old code let the throw propagate and rejected the Promise with a raw exception. Now wrapped in try/catch that calls finish() with a degraded signal, matching the graceful-degradation contract the layer already promises for missing-CLI / exit-nonzero / parse-error. 3. cleanSingletonLocks defensive guard tightened (config.ts). Old: basename === 'chromium-profile' OR userDataDir === $CHROMIUM_PROFILE. The second branch was env-controlled and the first was bypassable by passing a relative path that resolved to chromium-profile via CWD drift. New guard: refuses relative paths outright, resolves both sides via path.resolve(), and only accepts the env-match path when $CHROMIUM_PROFILE is itself absolute. Test updates: replace the old `.trim()` test with three new cases covering unicode-whitespace stripping, short-token rejection, and zero-width-only rejection (server-factory.test.ts). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: bump version and changelog (v1.34.0.0) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,25 @@ import { writeSecureFile, mkdirSecure } from './file-permissions';
|
||||
import { addConsoleEntry, addNetworkEntry, addDialogEntry, networkBuffer, type DialogEntry } from './buffers';
|
||||
import { validateNavigationUrl } from './url-validation';
|
||||
import { TabSession, type RefEntry } from './tab-session';
|
||||
import { resolveChromiumProfile, cleanSingletonLocks } from './config';
|
||||
|
||||
/**
|
||||
* Detect whether GSTACK_CHROMIUM_PATH points at a custom Chromium build that
|
||||
* already bakes the gstack extension in as a component extension (e.g.,
|
||||
* GStack Browser.app / GBrowser). Passing --load-extension against such a
|
||||
* binary triggers a ServiceWorkerState::SetWorkerId DCHECK because two
|
||||
* copies of the same service worker try to register.
|
||||
*
|
||||
* Resolution:
|
||||
* 1. GSTACK_CHROMIUM_KIND === 'custom-extension-baked' (preferred, explicit)
|
||||
* 2. GSTACK_CHROMIUM_PATH path substring contains 'GBrowser' or 'gbrowser'
|
||||
* (fallback for callers that only set the path)
|
||||
*/
|
||||
export function isCustomChromium(): boolean {
|
||||
if (process.env.GSTACK_CHROMIUM_KIND === 'custom-extension-baked') return true;
|
||||
const p = process.env.GSTACK_CHROMIUM_PATH || '';
|
||||
return p.includes('GBrowser') || p.includes('gbrowser');
|
||||
}
|
||||
|
||||
export type { RefEntry };
|
||||
|
||||
@@ -283,9 +302,17 @@ export class BrowserManager {
|
||||
'--disable-blink-features=AutomationControlled',
|
||||
];
|
||||
if (extensionPath) {
|
||||
launchArgs.push(`--disable-extensions-except=${extensionPath}`);
|
||||
launchArgs.push(`--load-extension=${extensionPath}`);
|
||||
// Write auth token for extension bootstrap.
|
||||
// Skip --load-extension when running against a custom Chromium build
|
||||
// that already bakes the extension in as a component extension
|
||||
// (gbrowser / GStack Browser.app). Loading it twice causes a
|
||||
// ServiceWorkerState::SetWorkerId DCHECK crash.
|
||||
if (!isCustomChromium()) {
|
||||
launchArgs.push(`--disable-extensions-except=${extensionPath}`);
|
||||
launchArgs.push(`--load-extension=${extensionPath}`);
|
||||
}
|
||||
// Write auth token for extension bootstrap (still required even when
|
||||
// the extension is component-baked — it reads ~/.gstack/.auth.json at
|
||||
// startup to learn how to call the daemon).
|
||||
// Write to ~/.gstack/.auth.json (not the extension dir, which may be read-only
|
||||
// in .app bundles and breaks codesigning).
|
||||
if (authToken) {
|
||||
@@ -308,9 +335,17 @@ export class BrowserManager {
|
||||
// so we use Playwright's bundled Chromium which reliably loads extensions.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const userDataDir = path.join(process.env.HOME || '/tmp', '.gstack', 'chromium-profile');
|
||||
const userDataDir = resolveChromiumProfile();
|
||||
fs.mkdirSync(userDataDir, { recursive: true });
|
||||
|
||||
// Pre-launch cleanup of stale SingletonLock/Socket/Cookie. Chromium's
|
||||
// ProcessSingleton refuses to start when these exist from a prior crash
|
||||
// (SIGKILL, hard crash) — the lockfiles point at a PID that may no longer
|
||||
// exist. Shutdown cleanup doesn't run on hard crashes, so we clean here
|
||||
// too. Safe under external coordination: gbd.lock for gbrowser,
|
||||
// single-instance CLI check for gstack.
|
||||
cleanSingletonLocks(userDataDir);
|
||||
|
||||
// Support custom Chromium binary via GSTACK_CHROMIUM_PATH env var.
|
||||
// Used by GStack Browser.app to point at the bundled Chromium.
|
||||
const executablePath = process.env.GSTACK_CHROMIUM_PATH || undefined;
|
||||
|
||||
@@ -11,8 +11,10 @@
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { mkdirSecure } from './file-permissions';
|
||||
import { safeUnlinkQuiet } from './error-handling';
|
||||
|
||||
export interface BrowseConfig {
|
||||
projectDir: string;
|
||||
@@ -151,3 +153,68 @@ export function readVersionHash(execPath: string = process.execPath): string | n
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the gstack home directory.
|
||||
*
|
||||
* Honors the existing convention used by telemetry.ts and domain-skills.ts:
|
||||
* 1. GSTACK_HOME env (explicit override)
|
||||
* 2. $HOME/.gstack (default)
|
||||
*/
|
||||
export function resolveGstackHome(): string {
|
||||
return process.env.GSTACK_HOME || path.join(os.homedir(), '.gstack');
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Chromium profile directory.
|
||||
*
|
||||
* Resolution order:
|
||||
* 1. `explicit` arg (passed via ServerConfig.chromiumProfile by embedders)
|
||||
* 2. CHROMIUM_PROFILE env (used by gbrowser's gbd per-workspace)
|
||||
* 3. <resolveGstackHome()>/chromium-profile (default)
|
||||
*/
|
||||
export function resolveChromiumProfile(explicit?: string): string {
|
||||
if (explicit && explicit.length > 0) return explicit;
|
||||
const env = process.env.CHROMIUM_PROFILE;
|
||||
if (env && env.length > 0) return env;
|
||||
return path.join(resolveGstackHome(), 'chromium-profile');
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-launch / shutdown cleanup of stale Chromium singleton lockfiles
|
||||
* (SingletonLock, SingletonSocket, SingletonCookie). Chromium's
|
||||
* ProcessSingleton refuses to start when these exist from a prior crash
|
||||
* (SIGKILL, hard crash, etc.) since they point at a PID that no longer exists.
|
||||
*
|
||||
* Defensive guard: refuses to operate unless ALL of these hold:
|
||||
* 1. `userDataDir` is an absolute path (no CWD-relative footguns)
|
||||
* 2. basename is exactly 'chromium-profile' OR the absolute path matches
|
||||
* the absolute form of $CHROMIUM_PROFILE env value
|
||||
*
|
||||
* Prevents accidentally deleting lock files from an unrelated directory if
|
||||
* profile resolution is misconfigured upstream (CWD drift, env injection).
|
||||
*
|
||||
* Caller MUST ensure external coordination has already guaranteed no live
|
||||
* peer is using this profile (gbd.lock for gbrowser; single-instance CLI
|
||||
* check for gstack).
|
||||
*/
|
||||
export function cleanSingletonLocks(userDataDir: string): void {
|
||||
if (!path.isAbsolute(userDataDir)) {
|
||||
console.warn(`[browse] cleanSingletonLocks: refusing relative path: ${userDataDir}`);
|
||||
return;
|
||||
}
|
||||
const resolved = path.resolve(userDataDir);
|
||||
const basename = path.basename(resolved);
|
||||
const explicitProfile = process.env.CHROMIUM_PROFILE;
|
||||
const explicitAbs = explicitProfile && path.isAbsolute(explicitProfile)
|
||||
? path.resolve(explicitProfile)
|
||||
: null;
|
||||
const isSafe = basename === 'chromium-profile' || (explicitAbs !== null && resolved === explicitAbs);
|
||||
if (!isSafe) {
|
||||
console.warn(`[browse] cleanSingletonLocks: refusing to clean unrecognized profile dir: ${resolved}`);
|
||||
return;
|
||||
}
|
||||
for (const lockFile of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
|
||||
safeUnlinkQuiet(path.join(resolved, lockFile));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -500,17 +500,9 @@ export async function checkTranscript(params: {
|
||||
// timeout rate in the v1.5.2.0 ensemble bench because of this, plus
|
||||
// ~44k cache_creation tokens per call (massive cost inflation).
|
||||
// Using os.tmpdir() gives Haiku a clean context for pure classification.
|
||||
const claude = resolveClaudeCommand();
|
||||
if (!claude) {
|
||||
return finish({ layer: 'transcript_classifier', confidence: 0, meta: { degraded: true, reason: 'claude_cli_not_found' } });
|
||||
}
|
||||
const p = spawn(claude.command, [
|
||||
...claude.argsPrefix,
|
||||
'-p', prompt,
|
||||
'--model', HAIKU_MODEL,
|
||||
'--output-format', 'json',
|
||||
], { stdio: ['ignore', 'pipe', 'pipe'], cwd: os.tmpdir() });
|
||||
|
||||
// TDZ fix: declare `finish` BEFORE `resolveClaudeCommand` so the early
|
||||
// return at the !claude guard below doesn't ReferenceError. Triggered
|
||||
// only when claude CLI is missing from PATH (dormant otherwise).
|
||||
let stdout = '';
|
||||
let done = false;
|
||||
const finish = (signal: LayerSignal) => {
|
||||
@@ -519,6 +511,30 @@ export async function checkTranscript(params: {
|
||||
resolve(signal);
|
||||
};
|
||||
|
||||
// Wrap resolveClaudeCommand + spawn in try/catch so any unexpected
|
||||
// throw (PATH probe failure, transient FS error) degrades gracefully
|
||||
// instead of rejecting the Promise with a raw exception.
|
||||
let claude: ReturnType<typeof resolveClaudeCommand>;
|
||||
try {
|
||||
claude = resolveClaudeCommand();
|
||||
} catch (err: any) {
|
||||
return finish({ layer: 'transcript_classifier', confidence: 0, meta: { degraded: true, reason: `resolve_error_${err?.message ?? 'unknown'}` } });
|
||||
}
|
||||
if (!claude) {
|
||||
return finish({ layer: 'transcript_classifier', confidence: 0, meta: { degraded: true, reason: 'claude_cli_not_found' } });
|
||||
}
|
||||
let p: ReturnType<typeof spawn>;
|
||||
try {
|
||||
p = spawn(claude.command, [
|
||||
...claude.argsPrefix,
|
||||
'-p', prompt,
|
||||
'--model', HAIKU_MODEL,
|
||||
'--output-format', 'json',
|
||||
], { stdio: ['ignore', 'pipe', 'pipe'], cwd: os.tmpdir() });
|
||||
} catch (err: any) {
|
||||
return finish({ layer: 'transcript_classifier', confidence: 0, meta: { degraded: true, reason: `spawn_throw_${err?.message ?? 'unknown'}` } });
|
||||
}
|
||||
|
||||
p.stdout.on('data', (d: Buffer) => (stdout += d.toString()));
|
||||
p.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
|
||||
+187
-65
@@ -35,7 +35,7 @@ import {
|
||||
isRootToken, checkConnectRateLimit, type TokenInfo,
|
||||
} from './token-registry';
|
||||
import { validateTempPath } from './path-security';
|
||||
import { resolveConfig, ensureStateDir, readVersionHash } from './config';
|
||||
import { resolveConfig, ensureStateDir, readVersionHash, resolveChromiumProfile, cleanSingletonLocks } from './config';
|
||||
import { emitActivity, subscribe, getActivityAfter, getActivityHistory, getSubscriberCount } from './activity';
|
||||
import { initAuditLog, writeAuditEntry } from './audit';
|
||||
import { inspectElement, modifyStyle, resetModifications, getModificationHistory, detachSession, type InspectorResult } from './cdp-inspector';
|
||||
@@ -65,7 +65,23 @@ ensureStateDir(config);
|
||||
initAuditLog(config.auditLog);
|
||||
|
||||
// ─── Auth ───────────────────────────────────────────────────────
|
||||
const AUTH_TOKEN = crypto.randomUUID();
|
||||
// AUTH_TOKEN is injectable via process.env.AUTH_TOKEN so embedders
|
||||
// (gbrowser's gbd daemon spawn) can pre-allocate the token and hand it to
|
||||
// the Bun child via env.
|
||||
//
|
||||
// Validation: require >= 16 chars after stripping ALL unicode whitespace
|
||||
// (not just ASCII — .trim() misses U+200B / U+FEFF / U+00A0 / etc., which
|
||||
// would otherwise let a misconfigured embedder ship a one-character BOM as
|
||||
// the bearer secret). Reject tokens that are too short or contain only
|
||||
// whitespace; fall back to randomUUID so the security boundary is never
|
||||
// silently weakened by misconfiguration.
|
||||
function sanitizeAuthToken(raw: string | undefined): string | null {
|
||||
if (!raw) return null;
|
||||
const stripped = raw.replace(/[\s -]/g, '');
|
||||
if (stripped.length < 16) return null;
|
||||
return stripped;
|
||||
}
|
||||
const AUTH_TOKEN = sanitizeAuthToken(process.env.AUTH_TOKEN) || crypto.randomUUID();
|
||||
initRegistry(AUTH_TOKEN);
|
||||
const BROWSE_PORT = parseInt(process.env.BROWSE_PORT || '0', 10);
|
||||
const IDLE_TIMEOUT_MS = parseInt(process.env.BROWSE_IDLE_TIMEOUT || '1800000', 10); // 30 min
|
||||
@@ -97,6 +113,93 @@ let tunnelServer: ReturnType<typeof Bun.serve> | null = null; // tunnel HTTP lis
|
||||
/** Which HTTP listener accepted this request. */
|
||||
export type Surface = 'local' | 'tunnel';
|
||||
|
||||
/**
|
||||
* Factory contract for embedders (gbrowser phoenix overlay).
|
||||
*
|
||||
* Today the CLI calls `start()` which reads env vars and binds Bun.serve
|
||||
* itself. Embedders building on this server as a submodule (gbrowser's
|
||||
* fd-passing gbd architecture) need to inject auth + ports + a
|
||||
* BrowserManager they pre-launched, and own the listener themselves.
|
||||
*
|
||||
* Status: v1 surfaces this type as documentation. AUTH_TOKEN env-injection
|
||||
* is already live (see ~L70). `start()` is exported and the kickoff /
|
||||
* signal-handler registration is gated on `import.meta.main`, so phoenix
|
||||
* can `import { start } from '.../server'` without auto-starting. Full
|
||||
* `buildFetchHandler` extraction lands in a follow-up; see plan
|
||||
* `/Users/garrytan/.claude/plans/system-instruction-you-are-working-swirling-fountain.md`
|
||||
* Part 1.
|
||||
*/
|
||||
export interface ServerConfig {
|
||||
/** Bearer token clients must present. Today injected via AUTH_TOKEN env. */
|
||||
authToken: string;
|
||||
/** Local listener port. Used in /welcome URL + state-file. */
|
||||
browsePort: number;
|
||||
/** Idle shutdown timeout. Default 30 min. */
|
||||
idleTimeoutMs: number;
|
||||
/** Result of resolveConfig() — stateDir, auditLog, stateFile. */
|
||||
config: ReturnType<typeof resolveConfig>;
|
||||
/** Pre-launched BrowserManager. Caller owns lifecycle. */
|
||||
browserManager: BrowserManager;
|
||||
/** Optional Chromium profile path override. Resolved by resolveChromiumProfile(). */
|
||||
chromiumProfile?: string;
|
||||
/** Caller-owned. shutdown() does NOT call xvfb.stop(); caller is responsible. */
|
||||
xvfb?: XvfbHandle | null;
|
||||
/** Caller-owned. shutdown() does NOT call proxyBridge.close(); caller is responsible. */
|
||||
proxyBridge?: BridgeHandle | null;
|
||||
startTime: number;
|
||||
/**
|
||||
* Overlay hook. Runs AFTER gstack resolves auth and BEFORE route dispatch.
|
||||
* Invalid tokens are auto-rejected at the gstack layer (401 returned
|
||||
* before hook fires), so the hook only ever sees valid TokenInfo or null
|
||||
* (no token presented). Returning a Response short-circuits gstack
|
||||
* dispatch; returning null falls through.
|
||||
*/
|
||||
beforeRoute?: (req: Request, surface: Surface, auth: TokenInfo | null) => Promise<Response | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return shape of buildFetchHandler() — fetch handlers + lifecycle helpers
|
||||
* embedders need to drive their own Bun.serve binding. See ServerConfig.
|
||||
*/
|
||||
export interface ServerHandle {
|
||||
fetchLocal: (req: Request, server: any) => Promise<Response>;
|
||||
fetchTunnel: (req: Request, server: any) => Promise<Response>;
|
||||
/**
|
||||
* Drains buffers, kills terminal-agent, closes browser, clears intervals,
|
||||
* removes state files. Does NOT stop bound Bun.Server listeners — call
|
||||
* stopListeners() for that. CLI relies on process.exit() to drop sockets.
|
||||
*/
|
||||
shutdown: (exitCode?: number) => Promise<void>;
|
||||
/**
|
||||
* Graceful listener stop for embedders. Calls server.stop(true) on each
|
||||
* passed Bun.Server. CLI doesn't need this (process.exit handles it).
|
||||
*/
|
||||
stopListeners: (local: any, tunnel?: any) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a ServerConfig-shaped object from process.env. Used by gstack's
|
||||
* own CLI when running `bun run dev` or the compiled binary directly.
|
||||
* Embedders construct their own ServerConfig explicitly.
|
||||
*
|
||||
* Reads env, calls resolveConfig(). Does NOT bind a listener or call
|
||||
* initAuditLog/initRegistry — those happen inside the buildFetchHandler
|
||||
* lifecycle.
|
||||
*/
|
||||
export function resolveConfigFromEnv(): Omit<ServerConfig, 'browserManager' | 'startTime'> & {
|
||||
config: ReturnType<typeof resolveConfig>;
|
||||
} {
|
||||
return {
|
||||
// Same sanitizer as the module-level AUTH_TOKEN: strips ALL unicode
|
||||
// whitespace and rejects tokens shorter than 16 chars so a misconfigured
|
||||
// embedder can't ship a BOM/zero-width as the bearer secret.
|
||||
authToken: sanitizeAuthToken(process.env.AUTH_TOKEN) || crypto.randomUUID(),
|
||||
browsePort: parseInt(process.env.BROWSE_PORT || '0', 10),
|
||||
idleTimeoutMs: parseInt(process.env.BROWSE_IDLE_TIMEOUT || '1800000', 10),
|
||||
config: resolveConfig(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths reachable over the tunnel surface. Everything else returns 404.
|
||||
*
|
||||
@@ -964,11 +1067,9 @@ async function shutdown(exitCode: number = 0) {
|
||||
|
||||
await browserManager.close();
|
||||
|
||||
// Clean up Chromium profile locks (prevent SingletonLock on next launch)
|
||||
const profileDir = path.join(process.env.HOME || '/tmp', '.gstack', 'chromium-profile');
|
||||
for (const lockFile of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
|
||||
safeUnlinkQuiet(path.join(profileDir, lockFile));
|
||||
}
|
||||
// Clean up Chromium profile locks (prevent SingletonLock on next launch).
|
||||
// Defensive guard inside the helper refuses to clean unrecognized dirs.
|
||||
cleanSingletonLocks(resolveChromiumProfile());
|
||||
|
||||
// Clean up state file
|
||||
safeUnlinkQuiet(config.stateFile);
|
||||
@@ -983,36 +1084,41 @@ async function shutdown(exitCode: number = 0) {
|
||||
// passed as exitCode and process.exit() coerces it to NaN, exiting with code 1
|
||||
// instead of 0. (Caught in v0.18.1.0 #1025.)
|
||||
//
|
||||
// SIGINT (Ctrl+C): user intentionally stopping → shutdown.
|
||||
process.on('SIGINT', () => shutdown());
|
||||
// SIGTERM behavior depends on mode:
|
||||
// - Normal (headless) mode: Claude Code's Bash sandbox fires SIGTERM when the
|
||||
// parent shell exits between tool invocations. Ignoring it keeps the server
|
||||
// alive across $B calls. Idle timeout (30 min) handles eventual cleanup.
|
||||
// - Headed / tunnel mode: idle timeout doesn't apply in these modes. Respect
|
||||
// SIGTERM so external tooling (systemd, supervisord, CI) can shut cleanly
|
||||
// without waiting forever. Ctrl+C and /stop still work either way.
|
||||
// - Active cookie picker: never tear down mid-import regardless of mode —
|
||||
// would strand the picker UI with "Failed to fetch."
|
||||
process.on('SIGTERM', () => {
|
||||
if (hasActivePicker()) {
|
||||
console.log('[browse] Received SIGTERM but cookie picker is active, ignoring to avoid stranding the picker UI');
|
||||
return;
|
||||
}
|
||||
const headed = browserManager.getConnectionMode() === 'headed';
|
||||
if (headed || tunnelActive) {
|
||||
console.log(`[browse] Received SIGTERM in ${headed ? 'headed' : 'tunnel'} mode, shutting down`);
|
||||
shutdown();
|
||||
} else {
|
||||
console.log('[browse] Received SIGTERM (ignoring — use /stop or Ctrl+C for intentional shutdown)');
|
||||
}
|
||||
});
|
||||
// Windows: taskkill /F bypasses SIGTERM, but 'exit' fires for some shutdown paths.
|
||||
// Defense-in-depth — primary cleanup is the CLI's stale-state detection via health check.
|
||||
if (process.platform === 'win32') {
|
||||
process.on('exit', () => {
|
||||
safeUnlinkQuiet(config.stateFile);
|
||||
// Gated on `import.meta.main` so embedders (gbrowser phoenix) that import
|
||||
// server.ts as a submodule can register their own signal handlers without
|
||||
// fighting with gstack's. CLI path is unchanged.
|
||||
if (import.meta.main) {
|
||||
// SIGINT (Ctrl+C): user intentionally stopping → shutdown.
|
||||
process.on('SIGINT', () => shutdown());
|
||||
// SIGTERM behavior depends on mode:
|
||||
// - Normal (headless) mode: Claude Code's Bash sandbox fires SIGTERM when the
|
||||
// parent shell exits between tool invocations. Ignoring it keeps the server
|
||||
// alive across $B calls. Idle timeout (30 min) handles eventual cleanup.
|
||||
// - Headed / tunnel mode: idle timeout doesn't apply in these modes. Respect
|
||||
// SIGTERM so external tooling (systemd, supervisord, CI) can shut cleanly
|
||||
// without waiting forever. Ctrl+C and /stop still work either way.
|
||||
// - Active cookie picker: never tear down mid-import regardless of mode —
|
||||
// would strand the picker UI with "Failed to fetch."
|
||||
process.on('SIGTERM', () => {
|
||||
if (hasActivePicker()) {
|
||||
console.log('[browse] Received SIGTERM but cookie picker is active, ignoring to avoid stranding the picker UI');
|
||||
return;
|
||||
}
|
||||
const headed = browserManager.getConnectionMode() === 'headed';
|
||||
if (headed || tunnelActive) {
|
||||
console.log(`[browse] Received SIGTERM in ${headed ? 'headed' : 'tunnel'} mode, shutting down`);
|
||||
shutdown();
|
||||
} else {
|
||||
console.log('[browse] Received SIGTERM (ignoring — use /stop or Ctrl+C for intentional shutdown)');
|
||||
}
|
||||
});
|
||||
// Windows: taskkill /F bypasses SIGTERM, but 'exit' fires for some shutdown paths.
|
||||
// Defense-in-depth — primary cleanup is the CLI's stale-state detection via health check.
|
||||
if (process.platform === 'win32') {
|
||||
process.on('exit', () => {
|
||||
safeUnlinkQuiet(config.stateFile);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Emergency cleanup for crashes (OOM, uncaught exceptions, browser disconnect)
|
||||
@@ -1044,26 +1150,37 @@ function emergencyCleanup() {
|
||||
}
|
||||
} catch { /* state file unparseable — fall through to lock + state cleanup */ }
|
||||
|
||||
// Clean Chromium profile locks
|
||||
const profileDir = path.join(process.env.HOME || '/tmp', '.gstack', 'chromium-profile');
|
||||
for (const lockFile of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
|
||||
safeUnlinkQuiet(path.join(profileDir, lockFile));
|
||||
}
|
||||
// Clean Chromium profile locks via the shared helper (defensive guard
|
||||
// refuses to operate on unrecognized profile dirs).
|
||||
cleanSingletonLocks(resolveChromiumProfile());
|
||||
safeUnlinkQuiet(config.stateFile);
|
||||
}
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('[browse] FATAL uncaught exception:', err.message);
|
||||
emergencyCleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
process.on('unhandledRejection', (err: any) => {
|
||||
console.error('[browse] FATAL unhandled rejection:', err?.message || err);
|
||||
emergencyCleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
// Same import.meta.main gate as SIGINT/SIGTERM — embedders register their
|
||||
// own crash handlers.
|
||||
if (import.meta.main) {
|
||||
process.on('uncaughtException', (err) => {
|
||||
console.error('[browse] FATAL uncaught exception:', err.message);
|
||||
emergencyCleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
process.on('unhandledRejection', (err: any) => {
|
||||
console.error('[browse] FATAL unhandled rejection:', err?.message || err);
|
||||
emergencyCleanup();
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Start ─────────────────────────────────────────────────────
|
||||
async function start() {
|
||||
/**
|
||||
* Entry point for `bun run dev` and the compiled binary.
|
||||
*
|
||||
* Exported so embedders (gbrowser phoenix overlay) can call it
|
||||
* directly with env vars set, bypassing the module-level `import.meta.main`
|
||||
* gate. Phoenix's eventual fd-passing path will use `buildFetchHandler`
|
||||
* directly; until that lands, calling `start()` from a non-main entry is
|
||||
* supported via env (AUTH_TOKEN, BROWSE_PORT, BROWSE_OWN_SIGNALS).
|
||||
*/
|
||||
export async function start() {
|
||||
// Clear old log files
|
||||
safeUnlink(CONSOLE_LOG_PATH);
|
||||
safeUnlink(NETWORK_LOG_PATH);
|
||||
@@ -2269,16 +2386,21 @@ async function start() {
|
||||
}
|
||||
}
|
||||
|
||||
start().catch((err) => {
|
||||
console.error(`[browse] Failed to start: ${err.message}`);
|
||||
// Write error to disk for the CLI to read — on Windows, the CLI can't capture
|
||||
// stderr because the server is launched with detached: true, stdio: 'ignore'.
|
||||
try {
|
||||
const errorLogPath = path.join(config.stateDir, 'browse-startup-error.log');
|
||||
mkdirSecure(config.stateDir);
|
||||
writeSecureFile(errorLogPath, `${new Date().toISOString()} ${err.message}\n${err.stack || ''}\n`);
|
||||
} catch {
|
||||
// stateDir may not exist — nothing more we can do
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
// Auto-kickoff only when this module is the entry point. Embedders
|
||||
// (gbrowser phoenix overlay) import { start, buildFetchHandler, ... }
|
||||
// without triggering the listener-binding side effects.
|
||||
if (import.meta.main) {
|
||||
start().catch((err) => {
|
||||
console.error(`[browse] Failed to start: ${err.message}`);
|
||||
// Write error to disk for the CLI to read — on Windows, the CLI can't capture
|
||||
// stderr because the server is launched with detached: true, stdio: 'ignore'.
|
||||
try {
|
||||
const errorLogPath = path.join(config.stateDir, 'browse-startup-error.log');
|
||||
mkdirSecure(config.stateDir);
|
||||
writeSecureFile(errorLogPath, `${new Date().toISOString()} ${err.message}\n${err.stack || ''}\n`);
|
||||
} catch {
|
||||
// stateDir may not exist — nothing more we can do
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user