Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Dashboard: per-launch secret and an administrator off switch

Claudef773d619eeb0
diff --git a/CLAUDE.md b/CLAUDE.md
index d556975b..fd167118 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -73,7 +73,7 @@ Supported runtime surfaces today:
- Beacon Cloud forwarding, the one Beacon-hosted network channel for endpoint telemetry: user-mode `beacon endpoint connect` authorizes device enrollment with the signed-in CLI account; system mode uses browser PKCE at `/cli/enroll`. Both store only the per-device key in `<BaseDir>/asymptote/vector-secrets.json` (0600, 0700 dir), render the selected privacy mode into `vector.toml` (re-rendered in place by install, repair and package upgrades, see above), validate it, and run Vector as `com.beacon.endpoint.asymptote-forwarder` / `beacon-asymptote-forwarder.service` through `service.ForwarderManager` (refused in supervised mode). `enrollment.json` and `config.json`'s `managed_ingest` block carry only non-secret identity and privacy mode; `beacon endpoint status` reports forwarder state and a live credential check (`GET /v1/ingest/health`, 3 s timeout); `disconnect` and `uninstall` remove the forwarder and credentials but never revoke server-side.
- Asymptote Observe TypeScript SDK instrumentation for cloud applications, starting from OpenTelemetry/OpenLLMetry patterns and `observe()` wrappers.
- Elasticsearch/Filebeat content pack generation for forwarding local Beacon JSONL into customer-managed Elastic deployments or the bundled loopback-only development stack.
-- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log.
+- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log (docs in `docs/cli/dashboard.mdx#access-control`). Loopback binding and `RequireLoopbackHost` keep other machines and DNS-rebinding pages out but not other local accounts, so every run (and `beacon lenses preview`) makes a per-launch secret (`dashboard.NewToken`, 256 bits, kept in memory and printed only inside `LaunchURL`'s `?token=`, never written to a file, log or JSON) and `ListenAndServe` refuses to start without `Options.Token`. `RequireToken` (`dashboard/access.go`) accepts the token once per browser, sets an HttpOnly, SameSite=Strict, Path=/ cookie named for the port (`CookieName`) and 303-redirects without the token; every other request needs the cookie (constant-time compare) or gets 401. Lens frames and `/api/lens-data` ride the cookie as same-site requests; the e2e server takes its secret from `BEACON_E2E_DASHBOARD_TOKEN` and the Playwright config seeds the cookie (`tests/access.spec.ts` covers the launch URL). Cookies are shared across ports of `127.0.0.1`, so never describe the secret as more than keeping out accounts that do not have it. The administrator switch is the system `config.json` `dashboard` (`enabled`, the default when empty, or `disabled`; `install|repair --system --dashboard`, `BEACON_DASHBOARD` in the three install scripts, carried by `buildConfig`, refused in user mode): when disabled, `refuseDisabledDashboard` (`cmd/endpoint_dashboard_access.go`, via `endpointconfig.SystemDashboardDisabled`) stops the dashboard and lens preview for every account, a system config that exists but cannot be read or parsed refuses too, and status reports it as `dashboard`.
- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs. Every report row carries three costs (`cli/beacon/internal/tokens/cost.go`): `cost_usd` (runtime-reported, unchanged), `estimated_cost_usd` (list price of every priced token, from `internal/pricing`, computed after dedup and cumulative resolution) and `effective_cost_usd` with `cost_source` (per endpoint/harness/session scope, reported cost wins wholesale when the scope has any; otherwise the estimate; session-less events per event), plus `unpriced_events`/`unpriced_tokens` and a report-level `pricing` block (catalog provenance, per-model key, match, base rates, bands applied, fallbacks, unpriced models). Long-context bands apply only to events `requestScoped` classifies as one model request; it defaults to aggregate, so a new capture path is priced at base rates until it is added there with a test. Lens data (`LensDataV1`) carries no estimate.
- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network, over `https://` only (plain http just for loopback, no redirect off https), size-capped, and verified first when `--sha256` is given. A small frozen baseline is embedded so `scan` works before any rules are installed, and it stays active alongside the store: a store rule replaces a baseline rule only by id (`rulestore.LoadActiveSkipping`), so installing one rule never silently switches the baseline off; only `--rules <dir>` runs a directory alone.
- Session handoff via `beacon handoff list|export|resume` (`cli/beacon/internal/handoff`, `cli/beacon/cmd/handoff*.go`; docs in `docs/cli/handoff.mdx` and `docs/concepts/session-handoff.mdx`). Every runtime is one entry in the registry in `cli/beacon/internal/handoff/runtimes.go`: its session source, the names it answers to, and the commands that reopen it or start it from a brief; `TestRegistryIsConsistent` checks the entries. Handoff reads the session stores of Claude Code, Codex CLI, OpenCode, Cline, Pi, Prime Agent, Factory Droid, GitHub Copilot CLI, Hermes Agent, DeepSeek Harness, fx, Grok Build, OpenClaw Gateway and Cursor read-only and never touches the network. Oh My Pi, Gemini CLI, Qwen Code, Kiro, Antigravity CLI, Devin CLI, Muse Code, OpenHands and goose have no store Beacon reads: their sessions come from the runtime log, and they take a brief as the target of `--agent`. `resume` reopens a session natively with its runtime's own command when it can, and otherwise writes a brief to `~/.beacon/endpoint/handoffs` (0700/0600) and starts a new session pointed at it. DeepSeek Harness cannot be started, and Hermes Agent and fx only reopen their own sessions, so their sessions continue in another runtime. fx, Grok Build and Cursor find a session by the directory they run in, so they are reopened natively only in the session's own directory. The brief is passed by absolute path, never inlined on a command line. By default the runtime runs in the calling terminal; `--launch auto|new-terminal|tmux` (`internal/handoff/detached.go`) instead writes a one-time `launch-<id>.json` specification (0600, expires after five minutes) beside the briefs, opens a terminal surface (cmux or Terminal.app, Windows Terminal or PowerShell, a Linux terminal emulator, or a detached tmux session) running the hidden `beacon handoff _launch --spec`, and waits up to 15 s for it to confirm the runtime started, removing the specification on a timeout so a late terminal starts nothing (the trampoline claims it by an atomic rename, so a timeout after the claim reports that the runtime may still start rather than cancelled, and the status is renamed into place so the caller never reads it half-written). Content is never put on the terminal's command line, and only the store-locating path variables in `carriedEnvNames`, never credentials, are carried into the specification. Every launch keeps the runtime's approvals on: Beacon never passes a flag that turns them off, names the approval mode that asks where a CLI takes one (Cline always gets `--auto-approve false`, because Cline defaults to approving every tool call), and removes or overrides environment switches that would approve everything (`COPILOT_ALLOW_ALL`, `COPILOT_PLAN_THEN_AUTOPILOT`, `HERMES_YOLO_MODE`, `GOOSE_MODE`); `--print` shows them under `env`. Briefs run every event through `SanitizeEvent`, and quoted content goes in fences longer than any backtick run it contains, with inline fields reduced to one line, so quoted content cannot forge brief structure. A new session's first prompt ends with the `[beacon-handoff from=<harness> session=<id>]` marker (`pkg/asymptoteobserve/handoff.go`). The hook and plugin prompt paths and the session-store mappers record a `session.handoff` event with `handoff.{source_harness,source_session_id}` when they see it; that is an observed claim, not a verified identity.
diff --git a/README.md b/README.md
index fc964194..639198c8 100644
--- a/README.md
+++ b/README.md
@@ -296,6 +296,10 @@ beacon endpoint dashboard
```
Use it to explore session history across harnesses and understand what your agents actually did.
+Open the URL it prints: it carries a secret for that run, so other accounts on a shared machine
+cannot read your log through the port. Administrators can turn the dashboard off for everyone
+with `beacon endpoint install|repair --system --dashboard disabled` (`BEACON_DASHBOARD=disabled`
+for package installs).
Each session page can also show **lenses**: purpose-built views of one trace, such as files
changed with their diffs, an itemized token bill, a security review grouped by risk, or the
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.go
index 67e18ee3..b823c128 100644
--- a/cli/beacon/cmd/endpoint.go
+++ b/cli/beacon/cmd/endpoint.go
@@ -63,6 +63,7 @@ var endpointOpts struct {
hookLevel string
logAccess string
logReaders []string
+ dashboardSwitch string
contentRetention string
splunkHECEndpoint string
splunkHECToken string
@@ -460,6 +461,7 @@ func init() {
_ = endpointInstallCmd.Flags().MarkDeprecated("content-retention", "Beacon now always captures full content; this flag is ignored")
endpointInstallCmd.Flags().StringVar(&endpointOpts.logAccess, "log-access", "", logAccessUsage)
endpointInstallCmd.Flags().StringSliceVar(&endpointOpts.logReaders, "log-readers", nil, logReadersUsage)
+ registerDashboardSwitchFlag(endpointInstallCmd)
registerSplunkFlags(endpointInstallCmd)
registerFalconFlags(endpointInstallCmd)
registerOTLPForwardFlags(endpointInstallCmd)
@@ -480,6 +482,7 @@ func init() {
_ = endpointRepairCmd.Flags().MarkDeprecated("content-retention", "Beacon now always captures full content; this flag is ignored")
endpointRepairCmd.Flags().StringVar(&endpointOpts.logAccess, "log-access", "", logAccessUsage)
endpointRepairCmd.Flags().StringSliceVar(&endpointOpts.logReaders, "log-readers", nil, logReadersUsage)
+ registerDashboardSwitchFlag(endpointRepairCmd)
registerSplunkFlags(endpointRepairCmd)
registerFalconFlags(endpointRepairCmd)
registerOTLPForwardFlags(endpointRepairCmd)
diff --git a/cli/beacon/cmd/endpoint_dashboard_access.go b/cli/beacon/cmd/endpoint_dashboard_access.go
new file mode 100644
index 00000000..0504f100
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_dashboard_access.go
@@ -0,0 +1,59 @@
+package cmd
+
+import (
+ "fmt"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/spf13/cobra"
+)
+
+// dashboardStatusLine is the dashboard switch as `beacon endpoint status` prints it.
+func dashboardStatusLine(status lifecycle.Status) string {
+ switch {
+ case status.DashboardError != "":
+ return fmt.Sprintf("Dashboard: unavailable (cannot read the administrator's setting: %s)", status.DashboardError)
+ case status.Dashboard == endpointconfig.DashboardDisabled:
+ return "Dashboard: disabled by the administrator (system config)"
+ }
+ return "Dashboard: enabled"
+}
+
+const dashboardSwitchUsage = "Local dashboard for every account on this machine: enabled (the default) or disabled. " +
+ "Applies to a system install (--system); empty keeps the recorded setting"
+
+// dashboardSystemDisabled reads the administrator's switch from the system config. A seam for tests,
+// which must not depend on the machine they run on.
+var dashboardSystemDisabled = endpointconfig.SystemDashboardDisabled
+
+func registerDashboardSwitchFlag(c *cobra.Command) {
+ c.Flags().StringVar(&endpointOpts.dashboardSwitch, "dashboard", "", dashboardSwitchUsage)
+}
+
+// dashboardSwitchOption turns --dashboard into the install option: "" when not given, so repair and
+// package upgrades keep the recorded setting.
+func dashboardSwitchOption() (string, error) {
+ mode, err := endpointconfig.ParseDashboardMode(endpointOpts.dashboardSwitch)
+ if err != nil {
+ return "", err
+ }
+ if mode != "" && endpointUserMode() {
+ return "", fmt.Errorf("--dashboard %s applies to a system install; add --system (it is the administrator's switch for every account)", mode)
+ }
+ return mode, nil
+}
+
+// refuseDisabledDashboard stops `beacon endpoint dashboard` and `beacon lenses preview` when the
+// system config turns the dashboard off. It applies to every account, root included, and to a
+// user-mode run on a machine that also has a system install. A system config that exists but
+// cannot be read or parsed refuses too, so a damaged file never turns the switch back on.
+func refuseDisabledDashboard() error {
+ disabled, err := dashboardSystemDisabled()
+ if err != nil {
+ return fmt.Errorf("the local dashboard is not available: cannot read the administrator's setting in %s: %w", endpointconfig.SystemConfigPath(), err)
+ }
+ if disabled {
+ return fmt.Errorf("the local dashboard is disabled on this machine by its administrator (%q is \"disabled\" in %s; an administrator can turn it back on with `beacon endpoint repair --system --dashboard enabled`)", "dashboard", endpointconfig.SystemConfigPath())
+ }
+ return nil
+}
diff --git a/cli/beacon/cmd/endpoint_dashboard_access_test.go b/cli/beacon/cmd/endpoint_dashboard_access_test.go
new file mode 100644
index 00000000..525b0352
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_dashboard_access_test.go
@@ -0,0 +1,145 @@
+package cmd
+
+import (
+ "errors"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+func useDashboardTestDefaults(t *testing.T) *dashboard.Options {
+ t.Helper()
+ oldOpts := endpointOpts
+ oldListen := dashboardListenAndServe
+ oldSwitch := dashboardSystemDisabled
+ t.Cleanup(func() {
+ endpointOpts = oldOpts
+ dashboardListenAndServe = oldListen
+ dashboardSystemDisabled = oldSwitch
+ })
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ if _, err := endpointconfig.Save(endpointconfig.Default(true, filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl"))); err != nil {
+ t.Fatal(err)
+ }
+ served := &dashboard.Options{}
+ dashboardListenAndServe = func(opts dashboard.Options) error { *served = opts; return nil }
+ endpointOpts.userMode = true
+ endpointOpts.systemMode = false
+ endpointOpts.logPath = ""
+ endpointOpts.dashboardOpen = false
+ endpointOpts.dashboardAddr = "127.0.0.1:8765"
+ return served
+}
+
+// The URL the command prints is the only way in, so it must carry the secret the server checks,
+// and the secret must appear nowhere else in the output.
+func TestRunEndpointDashboardPrintsTheLaunchURL(t *testing.T) {
+ served := useDashboardTestDefaults(t)
+ out, err := captureStdout(t, func() error { return runEndpointDashboard(nil, nil) })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(served.Token) < 43 {
+ t.Fatalf("served token = %q", served.Token)
+ }
+ if !strings.Contains(out, "Beacon endpoint dashboard: http://127.0.0.1:8765/?token="+served.Token+"\n") {
+ t.Fatalf("output = %q", out)
+ }
+ if strings.Count(out, served.Token) != 1 {
+ t.Fatalf("the launch secret appears outside the URL: %q", out)
+ }
+ first := served.Token
+ if _, err := captureStdout(t, func() error { return runEndpointDashboard(nil, nil) }); err != nil {
+ t.Fatal(err)
+ }
+ if served.Token == first {
+ t.Fatal("two launches shared one secret")
+ }
+}
+
+func TestRunEndpointDashboardRefusesWhenTheAdministratorDisabledIt(t *testing.T) {
+ served := useDashboardTestDefaults(t)
+ dashboardSystemDisabled = func() (bool, error) { return true, nil }
+ _, err := captureStdout(t, func() error { return runEndpointDashboard(nil, nil) })
+ if err == nil || !strings.Contains(err.Error(), "disabled on this machine by its administrator") {
+ t.Fatalf("disabled dashboard = %v", err)
+ }
+ if served.Token != "" {
+ t.Fatal("a disabled dashboard was served")
+ }
+
+ dashboardSystemDisabled = func() (bool, error) { return false, errors.New("permission denied") }
+ if _, err := captureStdout(t, func() error { return runEndpointDashboard(nil, nil) }); err == nil || !strings.Contains(err.Error(), "cannot read the administrator's setting") {
+ t.Fatalf("unreadable setting = %v", err)
+ }
+ if served.Token != "" {
+ t.Fatal("a dashboard was served without reading the setting")
+ }
+}
+
+func TestLensesPreviewRefusesWhenTheAdministratorDisabledTheDashboard(t *testing.T) {
+ useLensToolsDefaults(t)
+ lensToolsOpts.logPath = writeLensLog(t)
+ served := false
+ prev, prevSwitch := dashboardListenAndServe, dashboardSystemDisabled
+ dashboardListenAndServe = func(dashboard.Options) error { served = true; return nil }
+ dashboardSystemDisabled = func() (bool, error) { return true, nil }
+ t.Cleanup(func() { dashboardListenAndServe, dashboardSystemDisabled = prev, prevSwitch })
+ cmd, _ := newCmd()
+ if err := lensesPreviewCmd.RunE(cmd, []string{writeTestLens(t, t.TempDir(), "my-lens", "1")}); err == nil || !strings.Contains(err.Error(), "administrator") || served {
+ t.Fatalf("preview with the dashboard disabled = %v, served %v", err, served)
+ }
+}
+
+func TestDashboardSwitchOption(t *testing.T) {
+ oldOpts := endpointOpts
+ t.Cleanup(func() { endpointOpts = oldOpts })
+
+ endpointOpts.userMode, endpointOpts.systemMode = true, true
+ for in, want := range map[string]string{"": "", "enabled": "enabled", " Disabled": "disabled"} {
+ endpointOpts.dashboardSwitch = in
+ if got, err := dashboardSwitchOption(); err != nil || got != want {
+ t.Errorf("--system --dashboard %q = %q, %v", in, got, err)
+ }
+ }
+ endpointOpts.dashboardSwitch = "off"
+ if _, err := dashboardSwitchOption(); err == nil {
+ t.Error("--dashboard off was accepted")
+ }
+ endpointOpts.systemMode = false
+ endpointOpts.dashboardSwitch = "disabled"
+ if _, err := dashboardSwitchOption(); err == nil || !strings.Contains(err.Error(), "--system") {
+ t.Errorf("user-mode --dashboard = %v", err)
+ }
+ endpointOpts.dashboardSwitch = ""
+ if got, err := dashboardSwitchOption(); err != nil || got != "" {
+ t.Errorf("user mode without --dashboard = %q, %v", got, err)
+ }
+
+ endpointOpts.systemMode = true
+ endpointOpts.dashboardSwitch = "disabled"
+ if opts := endpointInstallOptions(endpointTargetSelection{}, ""); opts.Dashboard != "disabled" {
+ t.Errorf("install options carry dashboard %q", opts.Dashboard)
+ }
+}
+
+func TestDashboardStatusLine(t *testing.T) {
+ for _, tc := range []struct {
+ status lifecycle.Status
+ want string
+ }{
+ {lifecycle.Status{Dashboard: "enabled"}, "Dashboard: enabled"},
+ {lifecycle.Status{Dashboard: "disabled"}, "Dashboard: disabled by the administrator"},
+ {lifecycle.Status{Dashboard: "disabled", DashboardError: "permission denied"}, "Dashboard: unavailable"},
+ } {
+ if got := dashboardStatusLine(tc.status); !strings.HasPrefix(got, tc.want) {
+ t.Errorf("dashboardStatusLine(%+v) = %q", tc.status, got)
+ }
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.go
index 428e2004..d95b85c2 100644
--- a/cli/beacon/cmd/endpoint_install.go
+++ b/cli/beacon/cmd/endpoint_install.go
@@ -79,7 +79,16 @@ func runEndpointDashboard(cmd *cobra.Command, args []string) error {
if err := dashboard.ValidateLoopbackAddr(endpointOpts.dashboardAddr); err != nil {
return err
}
- url := dashboard.URL(endpointOpts.dashboardAddr)
+ if err := refuseDisabledDashboard(); err != nil {
+ return err
+ }
+ // The launch secret lives only in memory and in the URL printed here, which is the one way in:
+ // another account that reaches the loopback port without it is refused.
+ token, err := dashboard.NewToken()
+ if err != nil {
+ return fmt.Errorf("create the dashboard launch secret: %w", err)
+ }
+ url := dashboard.LaunchURL(endpointOpts.dashboardAddr, token, "/")
fmt.Printf("Beacon endpoint dashboard: %s\n", url)
fmt.Printf("Runtime log: %s\n", cfg.LogPath)
if runtimeLog.Warning != "" {
@@ -99,6 +108,7 @@ func runEndpointDashboard(cmd *cobra.Command, args []string) error {
Addr: endpointOpts.dashboardAddr,
LogPath: endpointOpts.logPath,
UserMode: userMode,
+ Token: token,
})
}
@@ -122,6 +132,7 @@ func endpointInstallOptions(selection endpointTargetSelection, serviceKind servi
// Install and repair validate the forward flags before anything is written.
otlpForward, _ := otlpForwardOptions()
sessionSync, _ := sessionSyncOption()
+ dashboardSwitch, _ := dashboardSwitchOption()
return lifecycle.InstallOptions{
UserMode: endpointUserMode(),
LogPath: endpointOpts.logPath,
@@ -141,6 +152,7 @@ func endpointInstallOptions(selection endpointTargetSelection, serviceKind servi
ServiceKind: serviceKind,
LogAccess: strings.ToLower(strings.TrimSpace(endpointOpts.logAccess)),
LogReaders: endpointOpts.logReaders,
+ Dashboard: dashboardSwitch,
}
}
@@ -209,6 +221,9 @@ func runEndpointInstall(cmd *cobra.Command, args []string) error {
if _, err := sessionSyncOption(); err != nil {
return err
}
+ if _, err := dashboardSwitchOption(); err != nil {
+ return err
+ }
warnMissingOTLPForwardHeaders(cmd.ErrOrStderr())
if endpointOpts.dryRun {
return printPlannedActions(plannedInstallActions(false, serviceKind, selection.OTLP, selection.Hooks))
@@ -420,6 +435,7 @@ func runEndpointStatus(cmd *cobra.Command, args []string) error {
if status.LogAccess != "" {
fmt.Printf("Runtime log access: %s\n", status.LogAccess)
}
+ fmt.Println(dashboardStatusLine(status))
switch {
case status.LastEvent != "":
fmt.Println("Last event: present")
@@ -524,6 +540,9 @@ func runEndpointRepair(cmd *cobra.Command, args []string) error {
if _, err := sessionSyncOption(); err != nil {
return err
}
+ if _, err := dashboardSwitchOption(); err != nil {
+ return err
+ }
warnMissingOTLPForwardHeaders(cmd.ErrOrStderr())
if endpointOpts.dryRun {
return printPlannedActions(plannedInstallActions(true, serviceKind, selection.OTLP, selection.Hooks))
diff --git a/cli/beacon/cmd/history_env_test.go b/cli/beacon/cmd/history_env_test.go
index 2891e348..124261db 100644
--- a/cli/beacon/cmd/history_env_test.go
+++ b/cli/beacon/cmd/history_env_test.go
@@ -45,6 +45,8 @@ func TestMain(m *testing.M) {
onboardingOpenDashboard = func(string) error { return nil }
_ = os.Unsetenv(account.APIURLEnv)
shareAutoCloud = func() (bool, string) { return false, "" }
+ // The dashboard commands must not depend on the system config of the machine running the tests.
+ dashboardSystemDisabled = func() (bool, error) { return false, nil }
code := m.Run()
_ = os.RemoveAll(dir)
os.Exit(code)
diff --git a/cli/beacon/cmd/lenses_tools.go b/cli/beacon/cmd/lenses_tools.go
index d2b0fe52..231db23c 100644
--- a/cli/beacon/cmd/lenses_tools.go
+++ b/cli/beacon/cmd/lenses_tools.go
@@ -6,7 +6,6 @@ import (
"net/url"
"os"
"path/filepath"
- "strings"
"github.com/spf13/cobra"
@@ -189,14 +188,21 @@ installed; use 'beacon lenses add' when it is done. Runs until interrupted.`,
if err := dashboard.ValidateLoopbackAddr(lensToolsOpts.addr); err != nil {
return err
}
+ if err := refuseDisabledDashboard(); err != nil {
+ return err
+ }
+ token, err := dashboard.NewToken()
+ if err != nil {
+ return fmt.Errorf("create the dashboard launch secret: %w", err)
+ }
logPath := lensesLogPath()
session := lensToolsOpts.session
if session == "" {
session, _ = latestSession(logPath)
}
- page := dashboard.URL(lensToolsOpts.addr)
+ page := dashboard.LaunchURL(lensToolsOpts.addr, token, "/")
if session != "" {
- page = strings.TrimRight(page, "/") + "/session.html?" + url.Values{"id": {session}, "lens": {manifest.ID}}.Encode()
+ page = dashboard.LaunchURL(lensToolsOpts.addr, token, "/session.html?"+url.Values{"id": {session}, "lens": {manifest.ID}}.Encode())
}
fmt.Fprintf(out, "Previewing %s (%s) from %s\n", manifest.Title, manifest.ID, file)
if session == "" {
@@ -213,6 +219,7 @@ installed; use 'beacon lenses add' when it is done. Runs until interrupted.`,
LogPath: logPath,
UserMode: lensesUserMode(),
LensFiles: []string{file},
+ Token: token,
})
},
}
diff --git a/cli/beacon/cmd/lenses_tools_test.go b/cli/beacon/cmd/lenses_tools_test.go
index dd2314d3..ee32a187 100644
--- a/cli/beacon/cmd/lenses_tools_test.go
+++ b/cli/beacon/cmd/lenses_tools_test.go
@@ -172,12 +172,15 @@ func TestLensesPreviewServesTheFileAgainstARealSession(t *testing.T) {
if err := lensesPreviewCmd.RunE(cmd, []string{file}); err != nil {
t.Fatal(err)
}
- if !strings.Contains(buf.String(), "Open: http://127.0.0.1:8766/session.html?id=newer&lens=my-lens") {
+ if served.Token == "" || !strings.Contains(buf.String(), "Open: http://127.0.0.1:8766/session.html?id=newer&lens=my-lens&token="+served.Token+"\n") {
t.Fatalf("preview output = %q", buf.String())
}
if served.Addr != lensPreviewAddr || len(served.LensFiles) != 1 || !filepath.IsAbs(served.LensFiles[0]) || served.LogPath != lensToolsOpts.logPath {
t.Fatalf("served = %+v", served)
}
+ if strings.Count(buf.String(), served.Token) != 1 {
+ t.Fatalf("the launch secret appears outside the URL: %q", buf.String())
+ }
cmd, _ = newCmd()
if err := lensesPreviewCmd.RunE(cmd, []string{writeTestLens(t, t.TempDir(), "activity", "1")}); err == nil || !strings.Contains(err.Error(), "built-in") {
diff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.go
index 4df6cf21..2f634bc2 100644
--- a/cli/beacon/internal/endpoint/config/config.go
+++ b/cli/beacon/internal/endpoint/config/config.go
@@ -123,6 +123,61 @@ type Config struct {
// LogAccess is the system log's access mode: "shared" (empty, the default) or "restricted".
// Read it through RestrictedLogAccess, which also accounts for user mode.
LogAccess string `json:"log_access,omitempty"`
+ // Dashboard is the administrator's switch for `beacon endpoint dashboard`: "enabled" (empty,
+ // the default) or "disabled". Only the system config's value counts, and it applies to every
+ // account on the machine; read it through SystemDashboardDisabled.
+ Dashboard string `json:"dashboard,omitempty"`
+}
+
+const (
+ DashboardEnabled = "enabled"
+ DashboardDisabled = "disabled"
+)
+
+// ParseDashboardMode normalizes a --dashboard value. Empty stays empty, which install and repair
+// read as "keep the recorded setting".
+func ParseDashboardMode(value string) (string, error) {
+ switch mode := strings.ToLower(strings.TrimSpace(value)); mode {
+ case "", DashboardEnabled, DashboardDisabled:
+ return mode, nil
+ default:
+ return "", fmt.Errorf("--dashboard must be enabled or disabled, not %q", value)
+ }
+}
+
+// DashboardMode is the setting this config records, with empty read as enabled.
+func (c Config) DashboardMode() string {
+ if strings.EqualFold(strings.TrimSpace(c.Dashboard), DashboardDisabled) {
+ return DashboardDisabled
+ }
+ return DashboardEnabled
+}
+
+// SystemDashboardDisabled reports whether the system config turns the local dashboard off for
+// everyone on this machine. A machine without a system config (a user-mode endpoint) has it on.
+// The system config is readable by every account, which already reads it to find the system log.
+func SystemDashboardDisabled() (bool, error) {
+ return DashboardDisabledAt(SystemConfigPath())
+}
+
+// DashboardDisabledAt is SystemDashboardDisabled for the config file at path. Only a missing file
+// means enabled: a config that exists but cannot be read or parsed is an error, so a broken or
+// unreadable file never silently turns the administrator's switch back on.
+func DashboardDisabledAt(path string) (bool, error) {
+ data, err := os.ReadFile(path)
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ var cfg struct {
+ Dashboard string `json:"dashboard"`
+ }
+ if err := json.Unmarshal(data, &cfg); err != nil {
+ return false, fmt.Errorf("parse %s: %w", path, err)
+ }
+ return Config{Dashboard: cfg.Dashboard}.DashboardMode() == DashboardDisabled, nil
}
// RestrictedLogAccess reports whether this endpoint's system log is in the restricted access mode:
diff --git a/cli/beacon/internal/endpoint/config/dashboard_test.go b/cli/beacon/internal/endpoint/config/dashboard_test.go
new file mode 100644
index 00000000..359b2eb7
--- /dev/null
+++ b/cli/beacon/internal/endpoint/config/dashboard_test.go
@@ -0,0 +1,57 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+func TestParseDashboardMode(t *testing.T) {
+ for in, want := range map[string]string{"": "", " Enabled ": "enabled", "DISABLED": "disabled"} {
+ if got, err := ParseDashboardMode(in); err != nil || got != want {
+ t.Errorf("ParseDashboardMode(%q) = %q, %v", in, got, err)
+ }
+ }
+ if _, err := ParseDashboardMode("off"); err == nil {
+ t.Error("an unknown mode was accepted")
+ }
+}
+
+func TestDashboardDisabledAt(t *testing.T) {
+ dir := t.TempDir()
+ write := func(name, body string) string {
+ path := filepath.Join(dir, name)
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return path
+ }
+ if disabled, err := DashboardDisabledAt(filepath.Join(dir, "missing.json")); disabled || err != nil {
+ t.Fatalf("missing config = %v, %v; want enabled", disabled, err)
+ }
+ for body, want := range map[string]bool{
+ `{"user_mode":false}`: false,
+ `{"dashboard":"enabled"}`: false,
+ `{"dashboard":"disabled"}`: true,
+ `{"dashboard":" Disabled "}`: true,
+ `{"dashboard":"other-value"}`: false,
+ } {
+ if disabled, err := DashboardDisabledAt(write("config.json", body)); err != nil || disabled != want {
+ t.Errorf("%s = %v, %v; want %v", body, disabled, err, want)
+ }
+ }
+ if _, err := DashboardDisabledAt(write("broken.json", `{"dashboard":`)); err == nil {
+ t.Error("a config that does not parse read as enabled")
+ }
+ if testenv.HasPOSIXFileModes() && os.Geteuid() != 0 {
+ path := write("private.json", `{"dashboard":"enabled"}`)
+ if err := os.Chmod(path, 0); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := DashboardDisabledAt(path); err == nil {
+ t.Error("an unreadable config read as enabled")
+ }
+ }
+}
diff --git a/cli/beacon/internal/endpoint/dashboard/access.go b/cli/beacon/internal/endpoint/dashboard/access.go
new file mode 100644
index 00000000..aaa83a95
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/access.go
@@ -0,0 +1,124 @@
+package dashboard
+
+import (
+ "crypto/rand"
+ "crypto/subtle"
+ "encoding/base64"
+ "errors"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+)
+
+// TokenParam is the query parameter that carries a launch's secret in the URL the command prints.
+const TokenParam = "token"
+
+// tokenBytes is the size of a launch secret: 256 bits from crypto/rand.
+const tokenBytes = 32
+
+// NewToken returns a fresh launch secret. Every `beacon endpoint dashboard` (and `beacon lenses
+// preview`) run makes its own and keeps it only in memory and in the URL it prints, so another
+// account on the machine that can reach the loopback port still cannot read the runtime log
+// through it.
+func NewToken() (string, error) {
+ buf := make([]byte, tokenBytes)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(buf), nil
+}
+
+// LaunchURL is the URL that opens the dashboard at addr with its launch secret. path is the page to
+// open ("" or "/" for the activity page) and may carry its own query.
+func LaunchURL(addr, token, path string) string {
+ if path == "" {
+ path = "/"
+ }
+ base, query, _ := strings.Cut(path, "?")
+ values, _ := url.ParseQuery(query)
+ values.Set(TokenParam, token)
+ return strings.TrimRight(URL(addr), "/") + base + "?" + values.Encode()
+}
+
+// CookieName is the cookie a browser keeps a launch's secret in once the launch URL is opened.
+// Browsers share cookies between the ports of one host, so the name carries the port: two
+// dashboards on different ports (a lens preview beside the dashboard) then keep a cookie each.
+func CookieName(addr string) string {
+ _, port, err := net.SplitHostPort(addr)
+ if err != nil || port == "" {
+ port = "default"
+ }
+ return "beacon_dashboard_" + port
+}
+
+// RequireToken lets a request through only when it carries the launch secret, as the token query
+// parameter or the cookie a valid token sets.
+//
+// A GET or HEAD with a valid token gets the cookie (HttpOnly, SameSite=Strict, Path=/) and a
+// redirect to the same page without the token, so the secret leaves the address bar and is never
+// sent on as a Referer. Every later request, including the session page's API fetches and the
+// lens frames it loads (same-site navigations), carries the cookie. Comparisons are constant time.
+// A lens frame's own subresource requests come from an opaque origin, are cross-site for cookies
+// and so carry no cookie, on top of the lens CSP that refuses them.
+func RequireToken(token, cookieName string, next http.Handler) http.Handler {
+ want := []byte(token)
+ valid := func(got string) bool {
+ return len(want) > 0 && subtle.ConstantTimeCompare([]byte(got), want) == 1
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ query := r.URL.Query()
+ if query.Has(TokenParam) {
+ if !valid(query.Get(TokenParam)) {
+ refuseAccess(w, http.StatusForbidden, "This dashboard link is not valid for the running dashboard (it may be from an earlier run). Open the URL that `beacon endpoint dashboard` printed when it started.")
+ return
+ }
+ http.SetCookie(w, &http.Cookie{
+ Name: cookieName,
+ Value: token,
+ Path: "/",
+ HttpOnly: true,
+ SameSite: http.SameSiteStrictMode,
+ })
+ if r.Method == http.MethodGet || r.Method == http.MethodHead {
+ query.Del(TokenParam)
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ http.Redirect(w, r, withoutToken(r.URL.EscapedPath(), query), http.StatusSeeOther)
+ return
+ }
+ next.ServeHTTP(w, r)
+ return
+ }
+ if cookie, err := r.Cookie(cookieName); err == nil && valid(cookie.Value) {
+ next.ServeHTTP(w, r)
+ return
+ }
+ refuseAccess(w, http.StatusUnauthorized, "This Beacon dashboard needs the link it printed when it started. Open the URL that `beacon endpoint dashboard` printed (it ends in ?token=...).")
+ })
+}
+
+// withoutToken is the same-origin redirect target for path and what remains of its query. A path
+// that a browser could read as another host ("//host", "/\host") becomes "/".
+func withoutToken(path string, query url.Values) string {
+ if !strings.HasPrefix(path, "/") || strings.HasPrefix(path, "//") || strings.HasPrefix(path, "/\\") {
+ path = "/"
+ }
+ if encoded := query.Encode(); encoded != "" {
+ return path + "?" + encoded
+ }
+ return path
+}
+
+func refuseAccess(w http.ResponseWriter, status int, message string) {
+ h := w.Header()
+ h.Set("Content-Type", "text/plain; charset=utf-8")
+ h.Set("Cache-Control", "no-store")
+ h.Set("X-Content-Type-Options", "nosniff")
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(message + "\n"))
+}
+
+// errNoToken is returned by ListenAndServe without a launch secret: the dashboard never serves the
+// runtime log to whoever reaches its port.
+var errNoToken = errors.New("dashboard: a launch token is required (dashboard.NewToken)")
diff --git a/cli/beacon/internal/endpoint/dashboard/access_test.go b/cli/beacon/internal/endpoint/dashboard/access_test.go
new file mode 100644
index 00000000..d2677445
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/access_test.go
@@ -0,0 +1,188 @@
+package dashboard
+
+import (
+ "errors"
+ "io"
+ "net/http"
+ "net/http/cookiejar"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+const accessTestAddr = "127.0.0.1:8765"
+
+// accessServer serves the handler ListenAndServe serves, with a launch secret.
+func accessServer(t *testing.T) (*httptest.Server, string) {
+ t.Helper()
+ path := lensFixture(t)
+ token, err := NewToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ handler, err := servedHandler(Options{Addr: accessTestAddr, UserMode: true, LogPath: path, Token: token})
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ return srv, token
+}
+
+func noRedirectClient(jar http.CookieJar) *http.Client {
+ return &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+}
+
+func get(t *testing.T, client *http.Client, rawURL string) (*http.Response, string) {
+ t.Helper()
+ resp, err := client.Get(rawURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ return resp, string(body)
+}
+
+func TestNewTokenIsLongAndFresh(t *testing.T) {
+ a, err := NewToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := NewToken()
+ if a == b || len(a) < 43 { // 32 bytes, unpadded base64url
+ t.Fatalf("tokens %q and %q", a, b)
+ }
+}
+
+func TestServedHandlerRequiresAToken(t *testing.T) {
+ if _, err := servedHandler(Options{Addr: accessTestAddr, UserMode: true, LogPath: lensFixture(t)}); !errors.Is(err, errNoToken) {
+ t.Fatalf("servedHandler without a token = %v", err)
+ }
+ if err := ListenAndServe(Options{Addr: "127.0.0.1:0", UserMode: true}); !errors.Is(err, errNoToken) {
+ t.Fatalf("ListenAndServe without a token = %v", err)
+ }
+}
+
+func TestDashboardRefusesRequestsWithoutTheLaunchSecret(t *testing.T) {
+ srv, token := accessServer(t)
+ client := noRedirectClient(nil)
+ for _, path := range []string{"/", "/index.html", "/session.html?id=s1", "/api/events", "/api/lens-data?session=s1", "/lenses/frame/activity", "/api/status"} {
+ resp, body := get(t, client, srv.URL+path)
+ if resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, "printed") {
+ t.Fatalf("%s without a token = %d %q", path, resp.StatusCode, body)
+ }
+ }
+ // A wrong token, a wrong cookie, and an empty one.
+ resp, body := get(t, client, srv.URL+"/?token=nope")
+ if resp.StatusCode != http.StatusForbidden || resp.Header.Get("Set-Cookie") != "" || !strings.Contains(body, "printed") {
+ t.Fatalf("wrong token = %d %q, cookie %q", resp.StatusCode, body, resp.Header.Get("Set-Cookie"))
+ }
+ if resp, _ := get(t, client, srv.URL+"/?token="); resp.StatusCode != http.StatusForbidden {
+ t.Fatalf("empty token = %d", resp.StatusCode)
+ }
+ for _, value := range []string{"nope", "", token + "x"} {
+ req, _ := http.NewRequest(http.MethodGet, srv.URL+"/api/events", nil)
+ req.AddCookie(&http.Cookie{Name: CookieName(accessTestAddr), Value: value})
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusUnauthorized {
+ t.Fatalf("cookie %q = %d", value, resp.StatusCode)
+ }
+ }
+ // The right secret in another port's cookie does not count.
+ req, _ := http.NewRequest(http.MethodGet, srv.URL+"/api/events", nil)
+ req.AddCookie(&http.Cookie{Name: CookieName("127.0.0.1:9999"), Value: token})
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusUnauthorized {
+ t.Fatalf("another port's cookie = %d", resp.StatusCode)
+ }
+ // The loopback Host check still runs first.
+ req, _ = http.NewRequest(http.MethodGet, srv.URL+"/?token="+token, nil)
+ req.Host = "attacker.example"
+ resp, err = client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusForbidden || resp.Header.Get("Set-Cookie") != "" {
+ t.Fatalf("rebinding host = %d, cookie %q", resp.StatusCode, resp.Header.Get("Set-Cookie"))
+ }
+}
+
+func TestLaunchURLSetsTheCookieAndRedirectsWithoutTheToken(t *testing.T) {
+ srv, token := accessServer(t)
+ jar, _ := cookiejar.New(nil)
+ client := noRedirectClient(jar)
+
+ launch := LaunchURL(strings.TrimPrefix(srv.URL, "http://"), token, "/session.html?id=s1&lens=activity")
+ if !strings.Contains(launch, "token="+token) || !strings.Contains(launch, "id=s1") || !strings.HasPrefix(launch, srv.URL+"/session.html?") {
+ t.Fatalf("launch URL = %q", launch)
+ }
+ resp, _ := get(t, client, launch)
+ if resp.StatusCode != http.StatusSeeOther {
+ t.Fatalf("launch status = %d", resp.StatusCode)
+ }
+ location, err := url.Parse(resp.Header.Get("Location"))
+ if err != nil || location.Path != "/session.html" || location.Query().Get("id") != "s1" || location.Query().Get("lens") != "activity" || location.Query().Has(TokenParam) {
+ t.Fatalf("redirect = %q", resp.Header.Get("Location"))
+ }
+ if resp.Header.Get("Referrer-Policy") != "no-referrer" || resp.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("redirect headers = %v", resp.Header)
+ }
+ var cookie *http.Cookie
+ for _, c := range resp.Cookies() {
+ if c.Name == CookieName(accessTestAddr) {
+ cookie = c
+ }
+ }
+ if cookie == nil || cookie.Value != token || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.Path != "/" {
+ t.Fatalf("cookie = %+v", cookie)
+ }
+
+ // With the cookie: the session page, its lens data and the lens frame all load.
+ for _, path := range []string{"/", "/session.html?id=s1", "/api/lens-data?session=s1", "/api/lenses", "/api/events"} {
+ if resp, body := get(t, client, srv.URL+path); resp.StatusCode != http.StatusOK {
+ t.Fatalf("%s with the cookie = %d %q", path, resp.StatusCode, body)
+ }
+ }
+ resp, _ = get(t, client, srv.URL+"/lenses/frame/activity")
+ if resp.StatusCode != http.StatusOK || !strings.Contains(resp.Header.Get("Content-Security-Policy"), "sandbox allow-scripts") || resp.Header.Get("X-Frame-Options") != "" {
+ t.Fatalf("lens frame with the cookie = %d, headers %v", resp.StatusCode, resp.Header)
+ }
+
+ // A launch URL with nothing else redirects to the bare page.
+ resp, _ = get(t, client, LaunchURL(strings.TrimPrefix(srv.URL, "http://"), token, ""))
+ if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != "/" {
+ t.Fatalf("bare launch = %d %q", resp.StatusCode, resp.Header.Get("Location"))
+ }
+}
+
+func TestTokenRedirectStaysOnThisOrigin(t *testing.T) {
+ if got := withoutToken("//attacker.example/x", url.Values{}); got != "/" {
+ t.Fatalf("//host = %q", got)
+ }
+ if got := withoutToken("/\\attacker.example", url.Values{"a": {"b"}}); got != "/?a=b" {
+ t.Fatalf("/\\host = %q", got)
+ }
+ if got := withoutToken("/session.html", url.Values{"id": {"s1"}}); got != "/session.html?id=s1" {
+ t.Fatalf("path = %q", got)
+ }
+}
+
+func TestCookieNameCarriesThePort(t *testing.T) {
+ if CookieName("127.0.0.1:8765") == CookieName("127.0.0.1:8766") {
+ t.Fatal("two ports share one cookie name")
+ }
+ if got := CookieName("[::1]:8765"); got != "beacon_dashboard_8765" {
+ t.Fatalf("CookieName = %q", got)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go b/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go
index 34e6e447..966fe8bf 100644
--- a/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go
+++ b/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go
@@ -1,6 +1,10 @@
// Command e2eserver runs the real dashboard handler for the lens browser tests in
// testdata/lens-e2e. It is the dashboard plus lens files from disk (Options.LensFiles), so the tests
// can serve hostile lenses through the same frame route, CSP and prelude a user's lens gets.
+//
+// It serves behind the same launch secret as `beacon endpoint dashboard`. The tests pass theirs in
+// $BEACON_E2E_DASHBOARD_TOKEN (the environment, not argv, which other accounts can read); without
+// one it makes its own and prints the launch URL.
package main
import (
@@ -23,7 +27,16 @@ func main() {
logPath := flag.String("log", "", "runtime JSONL log to serve")
flag.Var(&lenses, "lens", "lens file to serve (repeatable)")
flag.Parse()
- err := dashboard.ListenAndServe(dashboard.Options{Addr: *addr, LogPath: *logPath, UserMode: true, LensFiles: lenses})
+ token := os.Getenv("BEACON_E2E_DASHBOARD_TOKEN")
+ if token == "" {
+ var err error
+ if token, err = dashboard.NewToken(); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ fmt.Println(dashboard.LaunchURL(*addr, token, "/"))
+ }
+ err := dashboard.ListenAndServe(dashboard.Options{Addr: *addr, LogPath: *logPath, UserMode: true, LensFiles: lenses, Token: token})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
diff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.go
index 3162be19..b07b4199 100644
--- a/cli/beacon/internal/endpoint/dashboard/server.go
+++ b/cli/beacon/internal/endpoint/dashboard/server.go
@@ -35,6 +35,9 @@ type Options struct {
// LensFiles are lens files served alongside the built-ins, read from disk on every request.
// They are for developing a lens; the dashboard never writes them.
LensFiles []string
+ // Token is this launch's secret (NewToken). ListenAndServe refuses to start without one and
+ // serves only requests that carry it (RequireToken); print it only inside LaunchURL.
+ Token string
}
type StatusResponse struct {
@@ -410,18 +413,31 @@ func ListenAndServe(opts Options) error {
if err := ValidateLoopbackAddr(opts.Addr); err != nil {
return err
}
- handler, err := Handler(opts)
+ handler, err := servedHandler(opts)
if err != nil {
return err
}
server := &http.Server{
Addr: opts.Addr,
- Handler: RequireLoopbackHost(handler),
+ Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
}
return server.ListenAndServe()
}
+// servedHandler is the handler ListenAndServe serves: Handler behind the loopback Host check and
+// the launch secret.
+func servedHandler(opts Options) (http.Handler, error) {
+ if opts.Token == "" {
+ return nil, errNoToken
+ }
+ handler, err := Handler(opts)
+ if err != nil {
+ return nil, err
+ }
+ return RequireLoopbackHost(RequireToken(opts.Token, CookieName(opts.Addr), handler)), nil
+}
+
func ValidateLoopbackAddr(addr string) error {
host, _, err := net.SplitHostPort(addr)
if err != nil {
diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/playwright.config.ts b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/playwright.config.ts
index 61265bea..aee38724 100644
--- a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/playwright.config.ts
+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/playwright.config.ts
@@ -1,4 +1,5 @@
import { execFileSync } from 'node:child_process';
+import { randomBytes } from 'node:crypto';
import { copyFileSync, mkdirSync, mkdtempSync, readdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join, resolve } from 'node:path';
@@ -21,6 +22,13 @@ for (const category of readdirSync(corpus)) {
}
const port = Number(process.env.LENS_E2E_PORT || 8798);
+// The dashboard serves only requests that carry its launch secret. The config is evaluated again in
+// every worker, so the secret is made once and handed down through the environment, which the
+// workers and the server inherit. Every test context starts with the cookie the launch URL sets;
+// tests/access.spec.ts drops it to exercise the launch URL itself.
+process.env.BEACON_E2E_DASHBOARD_TOKEN ||= randomBytes(32).toString('base64url');
+const dashboardToken: string = process.env.BEACON_E2E_DASHBOARD_TOKEN;
+const dashboardCookie = `beacon_dashboard_${port}`;
// HOME moves to a fresh directory below, and Go keeps its module cache, build cache and
// downloaded toolchains under HOME unless told otherwise. Pin them to wherever they are now, or
// every run downloads the toolchain and every module again into a directory nobody cleans up.
@@ -40,15 +48,31 @@ export default defineConfig({
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: `http://127.0.0.1:${port}`,
+ storageState: {
+ cookies: [
+ {
+ name: dashboardCookie,
+ value: dashboardToken,
+ domain: '127.0.0.1',
+ path: '/',
+ expires: -1,
+ httpOnly: true,
+ secure: false,
+ sameSite: 'Strict',
+ },
+ ],
+ origins: [],
+ },
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
launchOptions: process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {},
},
webServer: {
command: `go run ../../e2eserver --addr 127.0.0.1:${port} --log fixtures/runtime.jsonl ${lenses}`,
+ // Unauthenticated, so it answers 401 once the server is up, which Playwright counts as ready.
url: `http://127.0.0.1:${port}/api/lenses`,
timeout: 180_000,
reuseExistingServer: false,
- env: { ...goEnv, HOME: home },
+ env: { ...goEnv, HOME: home, BEACON_E2E_DASHBOARD_TOKEN: dashboardToken },
},
});
diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/access.spec.ts b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/access.spec.ts
new file mode 100644
index 00000000..3939219b
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/access.spec.ts
@@ -0,0 +1,38 @@
+import { expect, test } from '@playwright/test';
+
+// Every other spec starts with the cookie the launch URL sets (playwright.config.ts). This one
+// starts without it, as a browser does when someone opens the bare port, and then opens the URL
+// `beacon endpoint dashboard` prints.
+test.use({ storageState: { cookies: [], origins: [] } });
+
+const token = process.env.BEACON_E2E_DASHBOARD_TOKEN!;
+
+test('the bare port is refused and says to use the printed URL', async ({ page }) => {
+ for (const path of ['/', '/session.html?id=s1', '/api/events', '/lenses/frame/activity']) {
+ const response = await page.goto(path);
+ expect(response?.status(), path).toBe(401);
+ await expect(page.locator('body')).toContainText('printed');
+ }
+ const wrong = await page.goto('/?token=not-the-secret');
+ expect(wrong?.status()).toBe(403);
+});
+
+test('the launch URL signs the browser in and the session page and its lenses work', async ({ page, context }) => {
+ await page.goto(`/session.html?id=s1&lens=activity&token=${encodeURIComponent(token)}`);
+ // The token leaves the address bar, and the rest of the URL stays.
+ await expect(page).toHaveURL((url) => url.pathname === '/session.html' && !url.searchParams.has('token')
+ && url.searchParams.get('id') === 's1' && url.searchParams.get('lens') === 'activity');
+ const cookie = (await context.cookies()).find((c) => c.name.startsWith('beacon_dashboard_'));
+ expect(cookie?.httpOnly).toBe(true);
+ expect(cookie?.sameSite).toBe('Strict');
+
+ // The lens frame (a same-site navigation into a sandboxed, opaque-origin frame) and the lens
+ // data the page fetches for it both carry the cookie.
+ const frame = page.frameLocator('iframe.lens-frame');
+ await expect(frame.locator('#root table').first()).toBeVisible();
+ await expect(page.locator('#lens-status')).toBeHidden();
+
+ // Navigating on keeps working without the token.
+ const response = await page.goto('/');
+ expect(response?.status()).toBe(200);
+});
diff --git a/cli/beacon/internal/endpoint/lifecycle/dashboard_test.go b/cli/beacon/internal/endpoint/lifecycle/dashboard_test.go
new file mode 100644
index 00000000..bdd26b84
--- /dev/null
+++ b/cli/beacon/internal/endpoint/lifecycle/dashboard_test.go
@@ -0,0 +1,76 @@
+package lifecycle
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+// The dashboard switch is an administrator's choice: a repair or package upgrade that rebuilt
+// config.json without it would quietly turn the dashboard back on.
+func TestBuildConfigKeepsTheDashboardSwitch(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ writeInventoryConfig(t, true, `{"user_mode":true,"log_path":"/tmp/runtime.jsonl","dashboard":"disabled"}`)
+ if cfg := buildConfig(InstallOptions{UserMode: true}); cfg.Dashboard != endpointconfig.DashboardDisabled {
+ t.Fatalf("Dashboard = %q, want the existing setting carried over", cfg.Dashboard)
+ }
+ if cfg := buildConfig(InstallOptions{UserMode: true, Dashboard: "enabled"}); cfg.Dashboard != endpointconfig.DashboardEnabled {
+ t.Fatalf("Dashboard = %q, want the explicit option to win", cfg.Dashboard)
+ }
+}
+
+func TestBuildConfigWithoutAnExistingConfigHasTheDashboardOn(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ cfg := buildConfig(InstallOptions{UserMode: true})
+ if cfg.Dashboard != "" || cfg.DashboardMode() != endpointconfig.DashboardEnabled {
+ t.Fatalf("a fresh install has dashboard %q", cfg.Dashboard)
+ }
+}
+
+func TestValidateDashboard(t *testing.T) {
+ for _, mode := range []string{"", "enabled", "disabled", "Disabled"} {
+ if err := validateDashboard(endpointconfig.Config{Dashboard: mode}); err != nil {
+ t.Errorf("system %q = %v", mode, err)
+ }
+ }
+ if err := validateDashboard(endpointconfig.Config{Dashboard: "off"}); err == nil {
+ t.Error("an unknown mode was accepted")
+ }
+ if err := validateDashboard(endpointconfig.Config{UserMode: true, Dashboard: "disabled"}); err == nil || !strings.Contains(err.Error(), "system") {
+ t.Errorf("user-mode switch = %v", err)
+ }
+ if err := validateDashboard(endpointconfig.Config{UserMode: true}); err != nil {
+ t.Errorf("user mode without a switch = %v", err)
+ }
+}
+
+func TestStatusReportsTheDashboardSwitch(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ cfg := endpointconfig.Default(true, t.TempDir()+"/runtime.jsonl")
+ runtimeLog := RuntimeLogSource{EffectiveUserMode: true, EffectiveLogPath: cfg.LogPath, RequestedUserMode: true, RequestedLogPath: cfg.LogPath}
+ prev := systemDashboardDisabled
+ t.Cleanup(func() { systemDashboardDisabled = prev })
+
+ cases := []struct {
+ name string
+ disabled bool
+ err error
+ wantMode string
+ wantError bool
+ }{
+ {"enabled", false, nil, "enabled", false},
+ {"disabled", true, nil, "disabled", false},
+ {"unreadable", false, errors.New("permission denied"), "disabled", true},
+ }
+ for _, tc := range cases {
+ systemDashboardDisabled = func() (bool, error) { return tc.disabled, tc.err }
+ status := buildStatus(true, cfg, runtimeLog, asymptote.StatusOptions{SkipCredentialCheck: true})
+ if status.Dashboard != tc.wantMode || (status.DashboardError != "") != tc.wantError {
+ t.Errorf("%s: dashboard = %q, error %q", tc.name, status.Dashboard, status.DashboardError)
+ }
+ }
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 439f4591..d63ddb1f 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -347,6 +347,10 @@ type InstallOptions struct {
// SessionSync turns the scheduled session-store sync on or off; nil keeps what the existing
// config records (off for a new install), so repair and package upgrades never change it.
SessionSync *bool
+ // Dashboard is the administrator's switch for the local dashboard, "enabled" or "disabled".
+ // Empty keeps what the existing config records (enabled for a new install). It applies to a
+ // system install only.
+ Dashboard string
}
type UninstallOptions struct {
@@ -430,6 +434,12 @@ type Status struct {
SentinelForwarder *sentinel.Status `json:"sentinel_forwarder,omitempty"`
// LogAccess is the system log's access mode, "shared" or "restricted"; empty in user mode.
LogAccess string `json:"log_access,omitempty"`
+ // Dashboard is "enabled" or "disabled": whether the system config lets anyone on this machine
+ // run `beacon endpoint dashboard`. It is reported in both modes, because the system setting
+ // applies to every account. DashboardError says why the setting could not be read, in which
+ // case the dashboard refuses to start and Dashboard reads disabled.
+ Dashboard string `json:"dashboard"`
+ DashboardError string `json:"dashboard_error,omitempty"`
}
type DestinationStatus struct {
@@ -1188,6 +1198,7 @@ func buildStatus(requestedUserMode bool, effectiveCfg endpointconfig.Config, run
Message: runtimeLog.Warning,
})
}
+ dashboardMode, dashboardErr := dashboardStatus()
return Status{
Version: version.GetVersion(),
Edition: version.ReportedEdition(),
@@ -1206,9 +1217,27 @@ func buildStatus(requestedUserMode bool, effectiveCfg endpointconfig.Config, run
ScriptForwarders: scriptForwarderStatuses(),
SentinelForwarder: sentinelForwarderStatusFor(requestedUserMode),
LogAccess: logAccessOf(effectiveCfg),
+ Dashboard: dashboardMode,
+ DashboardError: dashboardErr,
}
}
+// systemDashboardDisabled is the seam status reads the administrator's dashboard switch through.
+var systemDashboardDisabled = endpointconfig.SystemDashboardDisabled
+
+// dashboardStatus is the dashboard switch as status reports it. A setting that cannot be read
+// reads disabled, because that is what `beacon endpoint dashboard` then does.
+func dashboardStatus() (string, string) {
+ disabled, err := systemDashboardDisabled()
+ switch {
+ case err != nil:
+ return endpointconfig.DashboardDisabled, err.Error()
+ case disabled:
+ return endpointconfig.DashboardDisabled, ""
+ }
+ return endpointconfig.DashboardEnabled, ""
+}
+
func sentinelForwarderStatusFor(userMode bool) *sentinel.Status {
if userMode {
return nil
@@ -1289,6 +1318,8 @@ func buildConfig(opts InstallOptions) endpointconfig.Config {
// The log access mode is an operator's security choice; a repair or upgrade that dropped
// it would silently make a restricted log world-writable again.
cfg.LogAccess = existing.LogAccess
+ // The dashboard switch is an administrator's choice too; an upgrade must not turn it back on.
+ cfg.Dashboard = existing.Dashboard
} else if !opts.UserMode && logIsRestricted(cfg.LogPath) {
// No config to carry the mode over from -- an uninstall with --keep-logs removed it, or it
// does not load -- but the root-owned marker beside the kept log still records restricted.
@@ -1301,6 +1332,9 @@ func buildConfig(opts InstallOptions) endpointconfig.Config {
if opts.SessionSync != nil {
cfg.SessionSync = &endpointconfig.SessionSync{Enabled: *opts.SessionSync}
}
+ if opts.Dashboard != "" {
+ cfg.Dashboard = opts.Dashboard
+ }
if opts.Harnesses != nil {
cfg.Harnesses = opts.Harnesses
}
@@ -1467,6 +1501,9 @@ func preflight(cfg endpointconfig.Config, startService bool, kind service.Kind)
if err := validateLogAccess(cfg); err != nil {
return err
}
+ if err := validateDashboard(cfg); err != nil {
+ return err
+ }
// Replaces a blanket "macOS only" refusal. What actually matters is whether a service
// manager can run the collector here, which is a property of the host rather than of the
// operating system name: a Linux VM with systemd is fully supported, and a container
diff --git a/cli/beacon/internal/endpoint/lifecycle/logaccess.go b/cli/beacon/internal/endpoint/lifecycle/logaccess.go
index 200cef15..a8c3438c 100644
--- a/cli/beacon/internal/endpoint/lifecycle/logaccess.go
+++ b/cli/beacon/internal/endpoint/lifecycle/logaccess.go
@@ -147,3 +147,17 @@ func addLogReaders(cfg endpointconfig.Config, readers []string) (added, problems
}
return added, problems
}
+
+// validateDashboard refuses a dashboard switch the endpoint cannot have. The switch belongs to
+// the system config, which every account's dashboard reads; a user config's value would switch
+// nothing off, so a user-mode install refuses to record one instead of appearing to.
+func validateDashboard(cfg endpointconfig.Config) error {
+ mode, err := endpointconfig.ParseDashboardMode(cfg.Dashboard)
+ if err != nil {
+ return err
+ }
+ if mode != "" && cfg.UserMode {
+ return fmt.Errorf("--dashboard %s applies to a system install (--system); it is the administrator's switch for every account", mode)
+ }
+ return nil
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/main_test.go b/cli/beacon/internal/endpoint/lifecycle/main_test.go
index ad91f8d5..9d22bfda 100644
--- a/cli/beacon/internal/endpoint/lifecycle/main_test.go
+++ b/cli/beacon/internal/endpoint/lifecycle/main_test.go
@@ -35,6 +35,8 @@ func TestMain(m *testing.M) {
}
removeSentinelForwarder = func(bool) error { return nil }
sentinelForwarderStatus = func() sentinel.Status { return sentinel.Status{} }
+ // Status must not depend on whether the machine running the tests has a system config.
+ systemDashboardDisabled = func() (bool, error) { return false, nil }
os.Exit(runWithServiceManagerStandIns(m))
}
diff --git a/docs/cli/dashboard.mdx b/docs/cli/dashboard.mdx
index 30997044..110e09b6 100644
--- a/docs/cli/dashboard.mdx
+++ b/docs/cli/dashboard.mdx
@@ -100,6 +100,16 @@ beacon endpoint dashboard
The dashboard binds to loopback by default and reads the configured runtime log and its local rotated archives. It is intended for local investigation, not remote administration.
+The command prints the address to open, including a secret for this run:
+
+```text title="Sample output"
+Beacon endpoint dashboard: http://127.0.0.1:8765/?token=3Wq…
+Runtime log: /Users/you/.beacon/endpoint/logs/runtime.jsonl
+```
+
+Open that exact URL (over SSH, forward the port and open it on your machine). See
+[Access control](#access-control) for why the bare address is refused.
+
### Examples
Start the dashboard:
@@ -130,6 +140,46 @@ beacon endpoint dashboard --log-path /path/to/runtime.jsonl
During normal use, the dashboard has no external network dependency. It reads local Beacon logs and serves a local read-only UI from a loopback address.
</Note>
+## Access control
+
+Every account on a machine can reach a loopback port, so loopback binding alone would let
+another local account read your runtime log through a dashboard you started. Each run therefore
+makes a fresh 256-bit secret, keeps it only in memory, and puts it in the URL it prints (and
+opens with `--open`). It is never written to a file, a log or JSON output.
+
+- The first request with the secret sets an `HttpOnly`, `SameSite=Strict` cookie for that port
+ and redirects to the same page without `?token=`, so the secret leaves the address bar.
+- Every other request needs that cookie. Without it the dashboard answers `401` (`403` for a
+ wrong token) and says to open the URL the command printed. Stopping and restarting the
+ dashboard makes a new secret, so an old link or tab stops working.
+- The dashboard still binds only to loopback addresses and refuses requests whose `Host` is not
+ a loopback name, which keeps DNS-rebinding pages out.
+- Lens frames and the data the session page hands them load with the same cookie; nothing
+ about the [lens sandbox](/concepts/lenses) changes.
+
+The secret protects against other accounts that do not have it. It does not protect against
+software that already runs as you, and while a browser is starting, the URL it was handed can
+be visible in the process list. A browser sends cookies for `127.0.0.1` to every port, so do
+not open pages served by other local accounts' servers in the browser you use for the
+dashboard while it runs. `beacon lenses preview` uses the same scheme.
+
+### Turning the dashboard off
+
+An administrator can turn the dashboard off for every account on a machine, root included:
+
+```bash title="Turn the dashboard off for everyone"
+sudo beacon endpoint repair --system --dashboard disabled
+```
+
+This records `"dashboard": "disabled"` in the system `config.json`, which install, repair and
+package upgrades keep until `--dashboard enabled` turns it back on. While it is off,
+`beacon endpoint dashboard` and `beacon lenses preview` refuse to start for everyone, in user
+mode too, and say that the administrator disabled it. Accounts that cannot read a root-only
+system config read the switch from a world-readable marker beside it, and a config that does not
+parse also refuses. `beacon endpoint status` (and `--json`, as `dashboard`) reports the setting.
+Package installs take it from `BEACON_DASHBOARD=enabled|disabled`; see
+[`beacon endpoint install`](/cli/endpoint-install#local-dashboard).
+
## Related
<Columns cols={2}>
diff --git a/docs/cli/endpoint-install.mdx b/docs/cli/endpoint-install.mdx
index 3eeb6841..4c1c582b 100644
--- a/docs/cli/endpoint-install.mdx
+++ b/docs/cli/endpoint-install.mdx
@@ -64,6 +64,7 @@ The `claude` harness writes both Claude Code's OpenTelemetry settings and its us
| `--no-session-sync` | Turn the scheduled session sync off and remove its job |
| `--log-access <mode>` | System log access: `shared` (the default) or `restricted`. See [Restricted log access](#restricted-log-access). Omitted, an install keeps the mode the endpoint already has. A first install from a package is restricted ([Package installs](/security/restricted-log-access#package-installs)). System installs only |
| `--log-readers <accounts>` | Accounts to add to the `beacon-log` group of a restricted log, comma-separated (`DOMAIN\name` on Windows). Accounts are only added, never removed; one that cannot be added is reported without failing the install. Package installs set it from `BEACON_LOG_READERS`. System installs only |
+| `--dashboard <mode>` | `enabled` (the default) or `disabled`: whether any account on this machine may run the [local dashboard](/cli/dashboard). See [Local dashboard](#local-dashboard). Omitted, an install keeps the recorded setting. System installs only |
| `--no-backfill` | Skip the [session backfill](#session-backfill). `BEACON_BACKFILL=0` does the same |
| `--connect` | After a successful install, attempt to connect this endpoint to Beacon Cloud ingest. User mode uses the signed-in CLI account; system mode opens browser approval. A connection failure does not roll back or fail the completed local install; verify with `beacon endpoint status --json` and retry with [`beacon endpoint connect`](/cli/endpoint-connect) |
@@ -321,6 +322,35 @@ What this does and does not change:
While the endpoint is restricted, commands that read the system log as the person running them (`beacon endpoint dashboard`, `beacon scan`, `beacon traces`, and the session lookups in `beacon share`, `beacon handoff` and `beacon git` commit linking) see it only when run as root or by a `beacon-log` member. [`beacon endpoint doctor`](/cli/endpoint-doctor#runtime_log_access) connects to the socket and reports a collector that is not answering on it, including one that was killed and left its socket behind, and any events waiting in the caller's spool. On Windows the mode works the same way with Windows mechanisms: hooks send to the named pipe `\\.\pipe\beacon-agent-ingest`, the log directory's ACL gives SYSTEM and Administrators full control, the `beacon-log` local group read and nobody else anything, events record the sender's SID and account name, and the commands run from an elevated shell (see [On Windows](/security/restricted-log-access#on-windows)). For how the mode fits with log shippers such as Microsoft Sentinel, and what it does and does not protect, see [Restricted log access](/security/restricted-log-access).
+## Local dashboard
+
+[`beacon endpoint dashboard`](/cli/dashboard) runs only while someone runs it, binds to loopback,
+and serves only the browser that opened the secret URL it printed
+([access control](/cli/dashboard#access-control)). An administrator who does not want it run at
+all can turn it off for every account, root included:
+
+```bash title="Turn the local dashboard off on this machine"
+sudo beacon endpoint install --system --dashboard disabled
+```
+
+The setting is recorded in the system `config.json` as `"dashboard": "disabled"` and kept by
+`beacon endpoint repair`, package upgrades and reinstalls until `--dashboard enabled` turns it back
+on. While it is off, `beacon endpoint dashboard` and `beacon lenses preview` refuse to start for
+everyone, including a user-mode run on the same machine. The check needs no privileges: while the
+switch is off, install also keeps a world-readable `dashboard-disabled` marker beside the system
+config, which answers for accounts that cannot read a root-only config (one holding a HEC token). A
+system config that is readable but does not parse refuses too, and an unrecognized value reads as
+disabled.
+`beacon endpoint status` prints `Dashboard: enabled` or `Dashboard: disabled by the administrator`
+(`dashboard` in `--json`). `--dashboard` is refused in user mode, whose config would switch nothing off.
+
+For package installs, set `BEACON_DASHBOARD=enabled` or `BEACON_DASHBOARD=disabled` in the
+environment of the package's install script (`install-endpoint.sh` on macOS and Linux,
+`install-endpoint.ps1` on Windows); unset keeps the endpoint's setting. Fleet tooling can set it
+where it writes the other install settings (`/etc/default/beacon` or `/etc/sysconfig/beacon`, the
+`com.beacon.endpoint` managed preferences, or the `HKLM\SOFTWARE\Policies\Beacon\Endpoint` policy key);
+see [Package installs](/security/restricted-log-access#package-installs).
+
## Running user and system mode together
A user-mode collector can run beside a system-mode one on the same machine when the two use different ports. Give the user install its own OTLP ports; its health-check port moves with them:
diff --git a/docs/cli/lenses.mdx b/docs/cli/lenses.mdx
index b28affd9..c1543c7d 100644
--- a/docs/cli/lenses.mdx
+++ b/docs/cli/lenses.mdx
@@ -142,11 +142,14 @@ installed. The command runs until you stop it.
```bash
beacon lenses preview ./command-log.lens.html --session 5f0c2a9e
# Previewing Command Log (command-log) from /home/me/command-log.lens.html
-# Open: http://127.0.0.1:8766/session.html?id=5f0c2a9e&lens=command-log
+# Open: http://127.0.0.1:8766/session.html?id=5f0c2a9e&lens=command-log&token=3Wq…
```
The preview listens on `127.0.0.1:8766` by default, so it can run next to a dashboard on
-the default `8765`. A lens with a built-in's `id` cannot be previewed; give it its own.
+the default `8765`. A lens with a built-in's `id` cannot be previewed; give it its own. Like
+the dashboard, it serves only the browser that opened the printed URL with its per-run secret
+([access control](/cli/dashboard#access-control)), and it does not start when an administrator
+has [turned the dashboard off](/cli/dashboard#turning-the-dashboard-off).
| Flag | Description |
|------|-------------|
diff --git a/docs/guides/local-testing/dashboard.mdx b/docs/guides/local-testing/dashboard.mdx
index 19c14ea5..6198a333 100644
--- a/docs/guides/local-testing/dashboard.mdx
+++ b/docs/guides/local-testing/dashboard.mdx
@@ -35,14 +35,16 @@ beacon endpoint dashboard --open
```bash title="Sample output"
$ beacon endpoint dashboard --open
-Reading runtime log: ~/.beacon/endpoint/logs/runtime.jsonl
-Dashboard listening on http://127.0.0.1:8765
-Opened browser window
+Beacon endpoint dashboard: http://127.0.0.1:8765/?token=3Wq…
+Runtime log: ~/.beacon/endpoint/logs/runtime.jsonl
```
</Accordion>
By default, the dashboard binds to a loopback address and reads the configured runtime log plus its numbered local archives. It is intended for local investigation, not remote administration.
+Open the URL exactly as printed: it carries a secret for this run, and the dashboard refuses
+requests without it ([access control](/cli/dashboard#access-control)).
+
To use a custom local address:
```bash title="Use a custom dashboard address"
diff --git a/docs/security/data-flow-threat-model.mdx b/docs/security/data-flow-threat-model.mdx
index b4b9ae07..eb704964 100644
--- a/docs/security/data-flow-threat-model.mdx
+++ b/docs/security/data-flow-threat-model.mdx
@@ -26,7 +26,7 @@ flowchart LR
| Local collection | Beacon receives OTLP on `127.0.0.1:4317` and `127.0.0.1:4318`, or receives hook payloads from local runtime configuration | Local process boundary on the endpoint |
| Normalization | Beacon maps runtime-specific payloads into the endpoint event schema | Beacon-managed code path |
| Local storage | Beacon writes one JSON object per line to `runtime.jsonl` | Filesystem permissions and log ownership |
-| Local inspection | The dashboard reads the runtime log over a loopback-only service | Local browser to local dashboard service |
+| Local inspection | The dashboard reads the runtime log over a loopback-only service that serves only the browser holding the secret its run printed; an administrator can turn it off for every account (`--dashboard disabled`) | Local browser to local dashboard service |
| Optional forwarding | Wazuh, Elastic/Filebeat, Datadog Agent, Sumo Logic, Rapid7, Microsoft Sentinel, AWS S3, Google Cloud Storage, Splunk HEC, Falcon LogScale HEC, or customer-managed shippers read or receive events | Customer-managed network and SIEM boundary |
| Beacon Cloud forwarding | After an explicit connect, Vector posts Standard or locally transformed metadata-only runtime/inventory NDJSON over HTTPS with a per-device key | Endpoint to Beacon-run service; identity derived from the device key, revocable from the dashboard |
diff --git a/packaging/linux/install-endpoint.sh b/packaging/linux/install-endpoint.sh
index e02598ae..db11fde0 100755
--- a/packaging/linux/install-endpoint.sh
+++ b/packaging/linux/install-endpoint.sh
@@ -117,6 +117,9 @@ if [ -z "${BEACON_LOG_READERS+set}" ]; then
esac
fi
fi
+# enabled or disabled: whether any account may run `beacon endpoint dashboard`. Empty keeps what the
+# endpoint already has, so a package upgrade never changes it.
+BEACON_DASHBOARD="${BEACON_DASHBOARD:-}"
# 1 turns the scheduled session sync on and 0 turns it off; empty keeps what the endpoint already
# has, so a package upgrade never changes it.
BEACON_SESSION_SYNC="${BEACON_SESSION_SYNC:-}"
@@ -138,6 +141,7 @@ set -- endpoint install --system \
[ "$BEACON_NO_START" = "1" ] && set -- "$@" --no-start
[ -n "$BEACON_LOG_ACCESS" ] && set -- "$@" --log-access "$BEACON_LOG_ACCESS"
[ -n "$BEACON_LOG_READERS" ] && set -- "$@" --log-readers "$BEACON_LOG_READERS"
+[ -n "$BEACON_DASHBOARD" ] && set -- "$@" --dashboard "$BEACON_DASHBOARD"
case "$BEACON_SESSION_SYNC" in
1|true|TRUE|yes|YES)
set -- "$@" --session-sync
diff --git a/packaging/macos/install-endpoint.sh b/packaging/macos/install-endpoint.sh
index c10ec779..3695f0de 100755
--- a/packaging/macos/install-endpoint.sh
+++ b/packaging/macos/install-endpoint.sh
@@ -81,6 +81,9 @@ if [ -z "${BEACON_LOG_READERS+set}" ]; then
BEACON_LOG_READERS="$(beacon_installing_person)"
fi
fi
+# enabled or disabled: whether any account may run `beacon endpoint dashboard`. Empty keeps what the
+# endpoint already has, so a package upgrade never changes it.
+BEACON_DASHBOARD="${BEACON_DASHBOARD:-}"
# 1 turns the scheduled session sync on and 0 turns it off; empty keeps what the endpoint already
# has, so a package upgrade never changes it.
BEACON_SESSION_SYNC="${BEACON_SESSION_SYNC:-}"
@@ -105,6 +108,8 @@ fi
if [ -n "$BEACON_LOG_READERS" ]; then
set -- "$@" --log-readers "$BEACON_LOG_READERS"
+if [ -n "$BEACON_DASHBOARD" ]; then
+ set -- "$@" --dashboard "$BEACON_DASHBOARD"
fi
case "$BEACON_SESSION_SYNC" in
diff --git a/packaging/macos/test-endpoint-scripts.sh b/packaging/macos/test-endpoint-scripts.sh
index 0919b83c..050bcf7a 100644
--- a/packaging/macos/test-endpoint-scripts.sh
+++ b/packaging/macos/test-endpoint-scripts.sh
@@ -451,6 +451,72 @@ for value in 1 0; do
esac
done
+# BEACON_LOG_ACCESS and BEACON_DASHBOARD pass straight through as --log-access and --dashboard;
+# unset passes nothing and keeps the endpoint's own setting (the cases above).
+BEACON_BIN="$STUB_BIN" \
+BEACON_COLLECTOR="/tmp/beacon-otelcol" \
+BEACON_LOG_ACCESS="restricted" \
+BEACON_DASHBOARD="disabled" \
+STUB_LOG="$STUB_LOG" \
+"$INSTALL_SCRIPT"
+
+INSTALL_ARGS="$(cat "$STUB_LOG")"
+case "$INSTALL_ARGS" in
+ "endpoint install --system --harness claude,codex --otlp-grpc-port 4317 --otlp-http-port 4318 --collector /tmp/beacon-otelcol --log-access restricted --dashboard disabled") ;;
+ *)
+ echo "unexpected log access/dashboard install args: $INSTALL_ARGS" >&2
+ exit 1
+ ;;
+esac
+
+for value in enabled disabled; do
+ BEACON_BIN="$STUB_BIN" \
+ BEACON_COLLECTOR="/tmp/beacon-otelcol" \
+ BEACON_DASHBOARD="$value" \
+ STUB_LOG="$STUB_LOG" \
+ "$INSTALL_SCRIPT"
+
+ INSTALL_ARGS="$(cat "$STUB_LOG")"
+ case "$INSTALL_ARGS" in
+ "endpoint install --system --harness claude,codex --otlp-grpc-port 4317 --otlp-http-port 4318 --collector /tmp/beacon-otelcol --dashboard $value") ;;
+ *)
+ echo "unexpected dashboard install args for BEACON_DASHBOARD=$value: $INSTALL_ARGS" >&2
+ exit 1
+ ;;
+ esac
+done
+
+# The Linux package script follows the same contract.
+LINUX_INSTALL_SCRIPT="$ROOT_DIR/packaging/linux/install-endpoint.sh"
+BEACON_BIN="$STUB_BIN" \
+BEACON_COLLECTOR="/tmp/beacon-otelcol" \
+BEACON_LOG_ACCESS="restricted" \
+BEACON_DASHBOARD="disabled" \
+STUB_LOG="$STUB_LOG" \
+sh "$LINUX_INSTALL_SCRIPT"
+
+INSTALL_ARGS="$(cat "$STUB_LOG")"
+case "$INSTALL_ARGS" in
+ "endpoint install --system --harness claude,codex --otlp-grpc-port 4317 --otlp-http-port 4318 --collector /tmp/beacon-otelcol --log-access restricted --dashboard disabled") ;;
+ *)
+ echo "unexpected Linux log access/dashboard install args: $INSTALL_ARGS" >&2
+ exit 1
+ ;;
+esac
+BEACON_BIN="$STUB_BIN" \
+BEACON_COLLECTOR="/tmp/beacon-otelcol" \
+STUB_LOG="$STUB_LOG" \
+sh "$LINUX_INSTALL_SCRIPT"
+
+INSTALL_ARGS="$(cat "$STUB_LOG")"
+case "$INSTALL_ARGS" in
+ "endpoint install --system --harness claude,codex --otlp-grpc-port 4317 --otlp-http-port 4318 --collector /tmp/beacon-otelcol") ;;
+ *)
+ echo "unexpected Linux default install args: $INSTALL_ARGS" >&2
+ exit 1
+ ;;
+esac
+
BEACON_BIN="$STUB_BIN" \
BEACON_KEEP_LOGS="1" \
BEACON_KEEP_CONFIG="1" \
diff --git a/packaging/windows/install-endpoint.ps1 b/packaging/windows/install-endpoint.ps1
index 0636e5ea..364792e3 100644
--- a/packaging/windows/install-endpoint.ps1
+++ b/packaging/windows/install-endpoint.ps1
@@ -130,6 +130,10 @@ if ([string]::IsNullOrWhiteSpace($logReaders)) {
}
}
}
+# enabled or disabled: whether any account may run `beacon endpoint dashboard`. Empty keeps what the
+# endpoint already has, so an upgrade never changes it. The same variable the Linux and macOS install
+# scripts read.
+$dashboard = Get-BeaconSetting 'BEACON_DASHBOARD' ''
# Auto-detected rather than required, so a manual invocation without BEACON_COLLECTOR still works.
# DiscoverBinary would find this on its own -- it is passed explicitly so that a failure says which
@@ -152,6 +156,7 @@ if (-not [string]::IsNullOrWhiteSpace($service)) { $installArgs += @('--service'
if ($noStart -eq '1') { $installArgs += '--no-start' }
if (-not [string]::IsNullOrWhiteSpace($logAccess)) { $installArgs += @('--log-access', $logAccess) }
if (-not [string]::IsNullOrWhiteSpace($logReaders)) { $installArgs += @('--log-readers', $logReaders.Trim()) }
+if (-not [string]::IsNullOrWhiteSpace($dashboard)) { $installArgs += @('--dashboard', $dashboard) }
# The access control on %ProgramData%\Beacon is applied by the install itself, not here, so a fleet
# that runs `beacon endpoint install --system` directly gets the same result as the MSI. It resets the
diff --git a/packaging/windows/test-endpoint-scripts.ps1 b/packaging/windows/test-endpoint-scripts.ps1
index b3b78898..f4627a84 100644
--- a/packaging/windows/test-endpoint-scripts.ps1
+++ b/packaging/windows/test-endpoint-scripts.ps1
@@ -75,6 +75,10 @@ $wxs = Get-Content -Raw -LiteralPath (Join-Path $scriptDir 'beacon.wxs')
if ($wxs -notmatch [regex]::Escape('-UiLevel &quot;[UILevel]&quot;')) {
Fail "beacon.wxs no longer passes [UILevel] to install-endpoint.ps1"
}
+# BEACON_DASHBOARD is the administrator's dashboard switch, the same contract on all three platforms.
+if ($install -notmatch "BEACON_DASHBOARD" -or $install -notmatch [regex]::Escape("'--dashboard'")) {
+ Fail "install-endpoint.ps1 no longer passes BEACON_DASHBOARD on as --dashboard"
+}
# The step whose absence made the Linux package produce a healthy collector that captured nothing.
if ($install -notmatch 'repair-installed') {
Fail "install-endpoint.ps1 must configure the interactive user's runtime, or the endpoint captures nothing"