Documentation
¶
Overview ¶
Package session tracks Scout browser sessions on disk (~/.scout/sessions/<hash>/), detects orphans via gops, and exposes platform-specific process-liveness checks.
Index ¶
- Constants
- Variables
- func AddJobStep(sessionID string, step JobStep) error
- func CleanOrphans() (int, error)deprecated
- func CleanStaleSessions() (int, error)
- func CompleteJob(sessionID string, output string) error
- func DataDir(id string) string
- func DefaultConsolePath(id string) string
- func DefaultHARPath(id string) string
- func DefaultHijackPath(id string) string
- func DefaultWSPath(id string) string
- func Dir(id string) string
- func DomainHash(rawURL string) string
- func FailJob(sessionID string, errMsg string) error
- func FindBrowsersUsingDataDir(dataDir string) []int
- func GetSessionsDir() string
- func Hash(rawURL, label string) string
- func IsIP(s string) bool
- func IsScoutProcess(pid int) bool
- func MonitorsPath(id string) string
- func PendingCleanup() []string
- func PendingCleanupCount() int
- func ProcessAlive(pid int) bool
- func ProcessParentPID(pid int) (int, bool)
- func ProcessStartToken(pid int) (string, bool)
- func RecordCleanupFailure(path string)
- func RemoveInfo(id string)
- func RemoveJob(sessionID string) error
- func Reset(id string) error
- func ResetAll() (int, error)
- func RootDomain(rawURL string) string
- func ScoutProcessInfo(pid int) *goprocess.P
- func StartCleanupRetrier(done <-chan struct{})
- func StartJob(sessionID string) error
- func StartOrphanWatchdog(interval time.Duration, done <-chan struct{})
- func StartReaperWatchdog(interval time.Duration, done <-chan struct{})
- func UpdateJobProgress(sessionID string, current, total int, message string) error
- func WriteInfo(id string, info *SessionInfo) error
- func WriteJob(sessionID string, job *Job) error
- func WriteMonitors(id string, cfg *MonitorConfig) error
- type Job
- type JobStatus
- type JobStep
- type LockGuard
- type MonitorConfig
- type MonitorRule
- type MonitorSink
- type Progress
- type ReapStats
- type SessionInfo
- type SessionListing
Constants ¶
const DefaultCleanupRetryInterval = 60 * time.Second
DefaultCleanupRetryInterval is the base interval between retry sweeps. Each sweep walks all pending dirs once with a short per-dir budget.
const DefaultOrphanCheckInterval = 2 * time.Minute
DefaultOrphanCheckInterval is the default interval for periodic orphan checks.
const DefaultReaperInterval = DefaultOrphanCheckInterval
DefaultReaperInterval is the default interval for the process-wide reaper watchdog. Mirrors the previous per-browser orphan check cadence.
const DefaultReusableLifetime = 7 * 24 * time.Hour
DefaultReusableLifetime is the default expiration window for reusable sessions when callers don't specify one. Seven days is long enough for typical multi-day workflows but short enough that abandoned sessions get cleaned eventually.
const LockFileName = "scout.lock"
LockFileName is the per-session zero-byte file that carries the OS-level advisory lock.
Variables ¶
var ErrCorruptInfo = errors.New("scout: corrupt scout.pid")
ErrCorruptInfo is returned when the magic matches but the body is malformed (wrong version, truncated, etc.).
var ErrLegacyFormat = errors.New("scout: legacy scout.pid format")
ErrLegacyFormat is returned by unmarshalBinary when the file does not begin with the v1 magic. Callers (startup purge) use this to identify and remove legacy JSON-format scout.pid files.
var SessionsDir = defaultSessionsDir
SessionsDir is the function that returns the base directory for session data. It is a variable so tests can override it.
Functions ¶
func AddJobStep ¶ added in v0.57.0
AddJobStep appends a step to the job and auto-updates progress.
func CleanOrphans
deprecated
CleanOrphans scans SessionsDir for sessions whose scout owner has died and kills the orphaned browser, removing the folder. Returns the number of browser processes killed.
Deprecated: CleanOrphans is now a thin wrapper over ReapOnce, which is the single canonical reaping pass. Prefer ReapOnce()/StartReaperWatchdog directly. This wrapper is retained for source compatibility and will be removed after 2026-07-15 (tracked in docs/BACKLOG.md).
func CleanStaleSessions ¶ added in v0.57.0
CleanStaleSessions removes leftover session directories on startup. It removes:
- All non-reusable sessions unconditionally (kills browser if still alive)
- Reusable sessions where both scout and browser processes are dead
- Orphaned directories that have no scout.pid file at all
Only explicitly reusable sessions with a live process are preserved. Returns the number of sessions cleaned.
func CompleteJob ¶ added in v0.57.0
CompleteJob marks a job as completed with output and timestamp.
func DataDir ¶ added in v0.57.0
DataDir returns the browser user-data directory for a given session ID. This is the subdirectory where Chrome stores its profile data, separated from session metadata (scout.pid, job.json) at the parent level.
func DefaultConsolePath ¶ added in v1.1.0
DefaultConsolePath returns "console.log" inside the session dir.
func DefaultHARPath ¶ added in v1.1.0
DefaultHARPath returns "har.json" inside the session dir.
func DefaultHijackPath ¶ added in v1.1.0
DefaultHijackPath returns "hijack.jsonl" inside the session dir.
func DefaultWSPath ¶ added in v1.1.0
DefaultWSPath returns "ws.jsonl" inside the session dir.
func DomainHash ¶
DomainHash returns a short SHA-256 hash (first 16 hex chars) of the root domain.
func FindBrowsersUsingDataDir ¶ added in v1.1.0
FindBrowsersUsingDataDir scans running processes for chrome/brave/msedge/ chromium binaries whose command line references the given user-data-dir. Returns the PIDs that match.
Used by `scout session audit` to detect orphan browsers holding a CORRUPT session dir (no scout.pid) so they can be killed before removing the dir.
Linux: reads /proc/<pid>/cmdline. Windows: reads command lines via gops + win32 ProcessQuery. Darwin/BSD: returns nil — sysctl-based cmdline read not implemented.
func GetSessionsDir ¶
func GetSessionsDir() string
GetSessionsDir returns the base directory for session data: ~/.scout/sessions. This is cross-platform: it uses os.UserHomeDir which resolves to %USERPROFILE% on Windows, $HOME on Unix/macOS.
func Hash ¶
Hash returns a deterministic hash for a session directory name. The label (typically the browser name) is always included in the digest so that different browsers produce different session directories even for the same URL.
func IsScoutProcess ¶
IsScoutProcess checks if a PID belongs to a running scout (Go) process using gops. This is more reliable than OS-level ProcessAlive for scout PIDs because it avoids false positives from PID reuse by confirming the process is a Go binary whose executable name contains "scout".
func MonitorsPath ¶ added in v1.1.0
MonitorsPath returns the absolute path to the sidecar for session id.
func PendingCleanup ¶ added in v1.1.0
func PendingCleanup() []string
PendingCleanup returns a snapshot of the dirs currently queued for background retry. Backs `scout session list --pending`. The returned slice is a copy and safe to retain.
func PendingCleanupCount ¶ added in v1.1.0
func PendingCleanupCount() int
PendingCleanupCount reports how many dirs are queued for retry. Stays accurate mid-sweep because retryPending removes paths one-by-one rather than draining the whole queue up front.
func ProcessAlive ¶
ProcessAlive checks if a process with the given PID is still running.
func ProcessParentPID ¶ added in v1.1.0
ProcessParentPID returns the parent process PID for the given PID. Linux: parses /proc/<pid>/stat field 4 (ppid). Darwin/BSD: returns (0, false) — sysctl-based ppid not implemented.
func ProcessStartToken ¶ added in v1.1.0
ProcessStartToken returns an opaque platform-specific token uniquely identifying the process instance running at the given PID. Two processes that ran at the same PID at different times yield different tokens, so callers can detect PID reuse.
Linux: parses /proc/<pid>/stat field 22 (starttime in clock ticks since boot). Format: "linux:<starttime-ticks>".
Darwin/BSD: returns ("", false) — sysctl-based start time is not implemented. verifyProcess degrades to ProcessAlive-only on these.
func RecordCleanupFailure ¶ added in v1.1.0
func RecordCleanupFailure(path string)
RecordCleanupFailure enqueues path for background retry. Exported wrapper over recordCleanupFailure so package engine's Browser.Close can enqueue a session dir whose single-shot RemoveAll lost to a Windows file lock, instead of leaking it. Safe to call from any goroutine.
func RemoveInfo ¶
func RemoveInfo(id string)
RemoveInfo removes the scout.pid file from a session directory.
func Reset ¶
Reset removes an entire session directory (all browser data + scout.pid). If the session's browser process is still running, it is killed first. On Windows, retries removal if files are still locked by Chrome.
func ResetAll ¶
ResetAll removes all session directories under SessionsDir, including orphaned directories without scout.pid. Returns the number of sessions removed.
func RootDomain ¶
RootDomain extracts the registrable (eTLD+1) domain from a URL, using the Mozilla Public Suffix List via golang.org/x/net/publicsuffix.
Examples:
"https://sub.admin.mysite.com/path" → "mysite.com" "https://app.mysite.co.uk/path" → "mysite.co.uk" "https://x.gov.uk/path" → "x.gov.uk" "https://192.168.1.1:8080/path" → "192.168.1.1"
Hardening M4 — replaces the previous hand-curated two-part-TLD map which missed entries like co.il, gov.uk, ac.uk and would have collapsed unrelated domains into the same session directory.
func ScoutProcessInfo ¶
ScoutProcessInfo returns gops info for a scout PID, or nil if not found.
func StartCleanupRetrier ¶ added in v1.1.0
func StartCleanupRetrier(done <-chan struct{})
StartCleanupRetrier launches a background goroutine that periodically retries removing dirs that CleanStaleSessions could not clean (typically because AV / Search Indexer was holding files). Stops when done is closed.
Successful removals are logged at INFO. The retry interval grows up to 10 minutes after consecutive failures on the same dir, then resets when that dir finally goes away.
func StartOrphanWatchdog ¶
StartOrphanWatchdog starts a background goroutine that periodically calls CleanOrphans to kill dangling browser processes whose scout owner has died. It stops when the done channel is closed. Returns immediately.
func StartReaperWatchdog ¶ added in v1.1.0
StartReaperWatchdog starts a single process-wide goroutine that runs ReapOnce every interval until done is closed. It REPLACES the per-browser StartOrphanWatchdog fan-out — one ticker scans every folder, so N live browsers no longer mean N redundant watchdogs. Returns immediately.
func UpdateJobProgress ¶ added in v0.57.0
UpdateJobProgress updates the progress fields on a job.
func WriteInfo ¶
func WriteInfo(id string, info *SessionInfo) error
WriteInfo writes the session info as a fixed-width binary v1 record to <SessionsDir>/<id>/scout.pid. Writes happen in place (truncate + write) rather than via atomic rename so the same file can carry an OS-level advisory lock (LockFileEx / flock) for concurrent-access safety.
Mode 0o600/0o700 keep other local users out of Chrome's cookie database or scraper auth tokens stored under the session's data/ subdir.
Hardening M1 — see docs/quality/SESSION_HARDENING.md.
func WriteJob ¶ added in v0.57.0
WriteJob writes the job as JSON to <SessionsDir>/<sessionID>/job.json. Uses restrictive modes (0o700/0o600) — see WriteInfo. M1 hardening.
func WriteMonitors ¶ added in v1.1.0
func WriteMonitors(id string, cfg *MonitorConfig) error
WriteMonitors persists cfg to <session>/monitors.json. Pretty-printed for human readability (this file is operator-facing, not hot-path).
Types ¶
type Job ¶ added in v0.57.0
type Job struct {
ID string `json:"id"`
Type string `json:"type"`
Status JobStatus `json:"status"`
TargetURLs []string `json:"target_urls,omitempty"`
Command string `json:"command,omitempty"`
StartedAt time.Time `json:"started_at"`
UpdatedAt time.Time `json:"updated_at"`
CompletedAt time.Time `json:"completed_at,omitzero"`
Progress *Progress `json:"progress,omitempty"`
Steps []JobStep `json:"steps,omitempty"`
Error string `json:"error,omitempty"`
Output string `json:"output,omitempty"`
}
Job holds all metadata for a session job, stored as job.json inside the session's data directory.
type JobStatus ¶ added in v0.57.0
type JobStatus string
JobStatus represents the current state of a job.
type JobStep ¶ added in v0.57.0
type JobStep struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
StartedAt time.Time `json:"started_at"`
CompletedAt time.Time `json:"completed_at"`
Error string `json:"error,omitempty"`
}
JobStep represents a single step within a job.
type LockGuard ¶ added in v1.1.0
type LockGuard struct {
// contains filtered or unexported fields
}
LockGuard represents an acquired session lock. Call Release to drop it. Releases are idempotent. The underlying OS lock is held via an open file handle on <session>/scout.lock; closing the handle releases the lock.
The lock file is intentionally separate from scout.pid so the metadata file can be truncated and re-written freely without invalidating the long-lived OS-level range lock held by the owning scout process.
Hardening M3 (revised) — replaces the legacy `.lock` mkdir-mutex with an OS-level advisory lock (LockFileEx on Windows, flock on Unix). The OS reclaims the lock automatically if the holder crashes — no more stale lock dirs to garbage-collect.
func AcquireLock ¶ added in v1.1.0
AcquireLock takes an exclusive cross-process advisory lock on a session's scout.lock file. Creates the file (zero-length) if it does not yet exist so callers can lock before any metadata is written.
Returns immediately on success or contention — no spin-wait loop. If the lock is held elsewhere, returns an error with the session id for the caller to act on (audit/list use AcquireSharedLock instead).
func AcquireSharedLock ¶ added in v1.1.0
AcquireSharedLock takes a shared advisory lock on scout.pid. Multiple readers (audit, list) may hold the shared lock concurrently while no writer holds the exclusive lock.
type MonitorConfig ¶ added in v1.1.0
type MonitorConfig struct {
HAR MonitorSink `json:"har"`
Hijack MonitorSink `json:"hijack"`
Console MonitorSink `json:"console"`
WS MonitorSink `json:"ws"`
Blocks []MonitorRule `json:"blocks,omitempty"`
}
MonitorConfig is the per-session sidecar describing which monitors are active for a given browser session. Persisted as <session>/monitors.json. Read by session-destroy paths to know which artifacts (HAR, hijack stream, console log, ws stream) need finalizing before the dir is reaped, and by audit / list tooling to surface monitor status.
func ReadMonitors ¶ added in v1.1.0
func ReadMonitors(id string) (*MonitorConfig, error)
ReadMonitors loads monitors.json. Returns a zero MonitorConfig (not an error) when the file is absent — sessions created before this sidecar existed silently report "no monitors" rather than crashing destroy.
type MonitorRule ¶ added in v1.1.0
MonitorRule mirrors engine.BlockRule for on-disk persistence.
type MonitorSink ¶ added in v1.1.0
type MonitorSink struct {
Enabled bool `json:"enabled"`
Path string `json:"path,omitempty"` // relative to session dir, e.g. "har.json"
WithBodies bool `json:"with_bodies,omitempty"`
}
MonitorSink describes one monitor's enabled state + on-disk artifact path.
type Progress ¶ added in v0.57.0
type Progress struct {
CurrentStep int `json:"current_step"`
TotalSteps int `json:"total_steps"`
Percentage float64 `json:"percentage"`
Message string `json:"message,omitempty"`
}
Progress tracks the current progress of a job.
type ReapStats ¶ added in v1.1.0
ReapStats tallies the result of a single ReapOnce pass.
- Scanned: total session folders examined.
- Killed: browser processes killed (recorded BrowserPID + path-bounded holders found via FindBrowsersUsingDataDir).
- Removed: session folders successfully removed.
- Pending: folders whose removal failed and were enqueued for the background retrier (RecordCleanupFailure).
func ReapOnce ¶ added in v1.1.0
func ReapOnce() ReapStats
ReapOnce performs one canonical reaping pass over GetSessionsDir(). It is the single source of truth for "is this folder ownerless, and if so kill any browser holding it and remove it." CleanStaleSessions and CleanOrphans are thin wrappers over this; the startup path, the watchdog, and the daemon reconcile all call it so behavior is identical wherever it runs.
Ownership rule (a folder is PRESERVED iff):
- scout.pid parses AND the recorded ScoutPID is a live, identity-verified scout process (IsScoutProcess), OR
- the session is reusable and not yet expired (IsExpired() == false).
Every other folder is reaped:
- Missing / corrupt / legacy scout.pid (ReadInfo error) — the un-killable-zombie case: we cannot classify by metadata, so we still scan-and-kill any browser whose --user-data-dir is under this folder (path-bounded via FindBrowsersUsingDataDir) and remove the folder.
- Owner (ScoutPID) dead or unverifiable — kill recorded BrowserPID (with an immediate-before-kill liveness re-check to shrink the TOCTOU window), scan-and-kill path-bounded holders, remove the folder.
All kills are best-effort and logged; never fatal. Removal failures are enqueued via RecordCleanupFailure so the retrier (and eventual force-break) reaps them later. The pass is idempotent and safe to run concurrently from startup and the watchdog (folder-level guarding via scout.lock).
func ReapSession ¶ added in v1.1.0
ReapSession force-reaps a single session dir by id: kills any browser holding its data dir (recorded PID + path-bounded scan, self-pid-guarded) and removes the dir. For the CLI enforcement path (audit --kill / doctor --fix).
scout.pid is read best-effort; if missing/corrupt (the CORRUPT zombie case) browserPID is 0 and the kill falls through to the path-bounded scan via FindBrowsersUsingDataDir — so the zombie IS killed even when scout.pid is unreadable. This is the fix for the defect where the CLI path missed such zombies.
type SessionInfo ¶
type SessionInfo struct {
ScoutPID int `json:"scout_pid"`
BrowserPID int `json:"browser_pid"`
BrowserParentPID int `json:"browser_parent_pid,omitempty"`
BrowserStartToken string `json:"browser_start_token,omitempty"`
Reusable bool `json:"reusable"`
CreatedAt time.Time `json:"created_at"`
LastUsed time.Time `json:"last_used"`
// ExpiresAt is REQUIRED for Reusable sessions — persistent sessions
// must have a bounded lifetime so they don't accumulate forever. Zero
// for non-reusable (ephemeral) sessions.
ExpiresAt time.Time `json:"expires_at,omitempty"`
Headless bool `json:"headless"`
Browser string `json:"browser"`
DomainHash string `json:"domain_hash,omitempty"`
Domain string `json:"domain,omitempty"`
Exec string `json:"exec,omitempty"`
BuildVersion string `json:"build_version,omitempty"`
}
SessionInfo holds all metadata for a browser session, stored as scout.pid inside the session's directory using the fixed-width binary v1 layout defined in info_binary.go. JSON tags are retained for ad-hoc tooling (e.g. `scout session audit --json` still emits JSON) but on-disk storage is binary.
func ReadInfo ¶
func ReadInfo(id string) (*SessionInfo, error)
ReadInfo reads the session info from <SessionsDir>/<id>/scout.pid in the v1 binary format. Legacy JSON-format files yield ErrLegacyFormat so the startup purge can identify and remove them under hard cutover.
Refuses to return data from a session directory that is not owned by the current user — H4 hardening against pre-planted directories with predictable hash names. When the directory does not exist, returns the underlying os.IsNotExist error so callers (CleanOrphans, FindByDomain) can distinguish "absent" from "foreign".
func (*SessionInfo) IsExpired ¶ added in v1.1.0
func (s *SessionInfo) IsExpired() bool
IsExpired reports whether a reusable session has passed its expiration. Returns false for non-reusable sessions (they're cleaned on Close) and for reusable sessions with no ExpiresAt set (legacy data — treated as not-yet-expired to avoid surprise deletion).
type SessionListing ¶
type SessionListing struct {
ID string
Dir string
Info *SessionInfo
Job *Job
}
SessionListing pairs a session ID with its directory and info.
func FindByDomain ¶
func FindByDomain(rawURL string) *SessionListing
FindByDomain looks up a session by domain hash directory name. Since the dir name IS the domain hash, this is a direct path check — no scanning.
func FindReusable ¶
func FindReusable(browser string, headless bool) *SessionListing
FindReusable scans session dirs for a matching reusable session.
func List ¶
func List() ([]SessionListing, error)
List reads all <dir>/scout.pid files under SessionsDir.
Per M5: distinguishes missing scout.pid (orphan dir, silently skipped) from corrupt scout.pid (logged via slog so operators can detect tampering or crash damage) from foreign-owned directories (also logged — see H4).