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
feat(lenses): serve lens frames under the sandbox CSP
Claude1687e0fde666
diff --git a/CLAUDE.md b/CLAUDE.mdindex 25f52cf6..dcc2e7b9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -15,7 +15,7 @@ Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes.- `plugins`: TypeScript sources for the managed runtime plugins/extensions (`opencode-beacon`, `cline-beacon`, `pi-beacon`, `omp-beacon`, `openclaw-beacon`, `prime-beacon`, `omo-beacon`), each mirrored into an embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`.- `agent-skills`: publishable Agent Skills plugin for the traces-to-memory workflow (`beacon-memory-recall`, `beacon-memory-distill`, `beacon-memory-promote`) with manifests for Claude Code, Agent Plugins (Codex, Copilot, VS Code, Kiro, Devin), Cursor, Kimi Code, and Gemini CLI. At the repo root, `.claude-plugin/marketplace.json` is read by most harnesses, `.cursor-plugin/marketplace.json` by Cursor, and `package.json` (`pi.skills` only) makes the repo a Pi/Prime Agent package; keep that root `package.json` free of dependencies and scripts. `cli/beacon/cmd/agent_skills_test.go` checks every `beacon` command and flag the skills name against the real command tree, so rename a command and update the skills together.- `rules` and `spec/threat-rules`: the open rule corpus and the Threat Rules format it conforms to.-- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`); the lens frame host, built-in lenses and `beacon lenses` CLI are not built yet.+- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`), lists lenses at `/api/lenses`, and serves each lens at `/lenses/frame/<id>` under the spec's CSP with `lenses/prelude.js` (which defines `window.beacon`) injected ahead of it; that route is the only one that may be framed. Built-in lenses are `cli/beacon/internal/endpoint/dashboard/lenses/*.lens.html`, and `activity` is byte-identical to the spec example (a test enforces it). The session-page tabs and the `beacon lenses` CLI are not built yet.- `beacon-sandbox`: harness that runs a real Claude Code session in a disposable sandbox and checks what Beacon captured. See `beacon-sandbox/AGENTS.md`.- `packaging`: macOS, Linux, and Windows packaging and deployment assets.- `docs`: the published documentation site (docs.asymptotelabs.ai).diff --git a/cli/beacon/internal/endpoint/dashboard/lenses.go b/cli/beacon/internal/endpoint/dashboard/lenses.gonew file mode 100644index 00000000..40b3fb5c--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/lenses.go@@ -0,0 +1,172 @@+package dashboard++import (+ "bytes"+ "embed"+ "fmt"+ "io/fs"+ "net/http"+ "path"+ "sort"+ "strings"++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++// Built-in lenses ship inside the binary. Each is a complete lens file, held to the same spec as a+// user's: the registry parses and validates its manifest at startup rather than trusting it.+//+//go:embed lenses/*.lens.html+var builtinLensFiles embed.FS++//go:embed lenses/prelude.js+var lensPreludeJS string++//go:embed lenses/tokens.css+var lensTokensCSS string++// lensFrameCSP is the policy spec/lenses/SPEC.md promises. The sandbox directive repeats the+// iframe's sandbox attribute, so a lens URL opened on its own -- outside the dashboard's frame --+// still runs in an opaque origin with no network.+const lensFrameCSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; " ++ "img-src data: blob:; font-src data:; media-src data: blob:; connect-src 'none'; " ++ "form-action 'none'; base-uri 'none'; frame-ancestors 'self'; sandbox allow-scripts"++// 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"++// LensInfo is one lens as the dashboard lists it.+type LensInfo struct {+ ID string `json:"id"`+ Title string `json:"title"`+ Description string `json:"description,omitempty"`+ Icon string `json:"icon,omitempty"`+ Version int `json:"version"`+ Source string `json:"source"`+}++// LensListResponse is the /api/lenses payload.+type LensListResponse struct {+ Lenses []LensInfo `json:"lenses"`+}++type lens struct {+ info LensInfo+ html []byte+}++type lensRegistry struct {+ byID map[string]lens+ order []string+}++// loadBuiltinLenses reads every built-in lens. A built-in that breaks the spec is a build defect,+// so it fails dashboard startup instead of being skipped.+func loadBuiltinLenses(files fs.FS) (*lensRegistry, error) {+ names, err := fs.Glob(files, "lenses/*.lens.html")+ if err != nil {+ return nil, err+ }+ registry := &lensRegistry{byID: map[string]lens{}}+ for _, name := range names {+ html, err := fs.ReadFile(files, name)+ 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)+ 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,+ }+ registry.order = append(registry.order, manifest.ID)+ }+ sort.Strings(registry.order)+ return registry, nil+}++func (r *lensRegistry) list() LensListResponse {+ out := LensListResponse{Lenses: make([]LensInfo, 0, len(r.order))}+ for _, id := range r.order {+ out.Lenses = append(out.Lenses, r.byID[id].info)+ }+ return out+}++// lensPrelude is what the dashboard puts ahead of every lens: the style tokens, then the script+// that defines window.beacon. Both are inline because the frame's CSP allows nothing else.+func lensPrelude() []byte {+ return []byte("<style>" + lensTokensCSS + "</style><script>" + lensPreludeJS + "</script>")+}++// withLensPrelude inserts the prelude right after the lens's doctype, so the document keeps its+// standards mode and the prelude still runs before any lens script. A prelude ahead of <html> is+// parsed into <head>, which is where it belongs.+func withLensPrelude(html []byte) []byte {+ prelude := lensPrelude()+ rest := bytes.TrimPrefix(html, []byte("\xef\xbb\xbf"))+ trimmed := bytes.TrimLeft(rest, " \t\r\n")+ if len(trimmed) >= len("<!doctype") && strings.EqualFold(string(trimmed[:len("<!doctype")]), "<!doctype") {+ if end := bytes.IndexByte(trimmed, '>'); end >= 0 {+ head := trimmed[:end+1]+ out := make([]byte, 0, len(html)+len(prelude))+ out = append(out, head...)+ out = append(out, prelude...)+ return append(out, trimmed[end+1:]...)+ }+ }+ out := make([]byte, 0, len(html)+len(prelude))+ out = append(out, prelude...)+ return append(out, rest...)+}++// serveLensFrame serves one lens as the document of a sandboxed frame. It replaces the dashboard's+// own security headers: the dashboard refuses to be framed at all, and a lens must be framed by+// the dashboard and by nothing else.+func (r *lensRegistry) serveLensFrame(w http.ResponseWriter, req *http.Request) {+ if req.Method != http.MethodGet && req.Method != http.MethodHead {+ methodNotAllowed(w)+ return+ }+ id := strings.TrimPrefix(req.URL.Path, lensFramePrefix)+ found, ok := r.byID[id]+ if !ok {+ http.NotFound(w, req)+ return+ }+ h := w.Header()+ h.Set("Content-Security-Policy", lensFrameCSP)+ h.Del("X-Frame-Options")+ h.Set("Content-Type", "text/html; charset=utf-8")+ h.Set("Cache-Control", "no-store")+ h.Set("Cross-Origin-Resource-Policy", "same-origin")+ w.WriteHeader(http.StatusOK)+ if req.Method == http.MethodHead {+ return+ }+ _, _ = w.Write(withLensPrelude(found.html))+}diff --git a/cli/beacon/internal/endpoint/dashboard/lenses/activity.lens.html b/cli/beacon/internal/endpoint/dashboard/lenses/activity.lens.htmlnew file mode 100644index 00000000..4f0b45cf--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/lenses/activity.lens.html@@ -0,0 +1,120 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>Activity</title>+<script type="application/beacon-lens+json">+{+ "id": "activity",+ "title": "Activity",+ "description": "Counts what the agent did in this trace, lists the commands it ran, and links each rule finding to its evidence.",+ "icon": "list",+ "version": 1,+ "api": "beacon.lens.v1",+ "author": "Beacon"+}+</script>+<style>+ /* The host defines the --beacon-* tokens; the fallbacks keep the file readable on its own. */+ body {+ margin: 0;+ color: var(--beacon-text, #111827);+ font: 400 13px/1.5 var(--beacon-font-sans, ui-sans-serif, system-ui, sans-serif);+ }+ h2 { margin: 16px 0 6px; font-size: 13px; font-weight: 400; color: var(--beacon-muted, #6b7280); }+ h2:first-child { margin-top: 0; }+ table { width: 100%; border-collapse: collapse; }+ th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid var(--beacon-line, rgba(0,0,0,0.1)); font-weight: 400; }+ th { color: var(--beacon-muted, #6b7280); }+ .num { text-align: right; font-variant-numeric: tabular-nums; }+ code { font: 13px var(--beacon-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace); }+ .fail { color: var(--beacon-danger, #b91c1c); }+ .muted { color: var(--beacon-muted, #6b7280); }+</style>+</head>+<body>+<p id="status" class="muted">Loading trace…</p>+<main id="root" hidden></main>+<script>+(function () {+ "use strict";+ var root = document.getElementById("root");+ var status = document.getElementById("status");++ // Every element is built with textContent: trace content is untrusted and never parsed as HTML.+ function el(tag, text, className) {+ var node = document.createElement(tag);+ if (text !== undefined && text !== null) node.textContent = String(text);+ if (className) node.className = className;+ return node;+ }+ function table(headers, rows) {+ var t = el("table");+ var head = t.appendChild(el("tr"));+ headers.forEach(function (h) { head.appendChild(el("th", h.label, h.num ? "num" : "")); });+ rows.forEach(function (cells) {+ var tr = t.appendChild(el("tr"));+ cells.forEach(function (cell) { tr.appendChild(cell); });+ });+ return t;+ }+ var fmt = new Intl.NumberFormat();++ function render(data) {+ var trace = (data && data.trace) || {};+ var events = Array.isArray(trace.events) ? trace.events : [];+ var byId = {};+ var counts = {};+ events.forEach(function (e) {+ if (e && e.id) byId[e.id] = e;+ var type = (e && e.type) || "other";+ counts[type] = (counts[type] || 0) + 1;+ });++ root.appendChild(el("h2", "Events by type"));+ root.appendChild(table([{ label: "Type" }, { label: "Count", num: true }], Object.keys(counts).sort().map(function (type) {+ return [el("td", type), el("td", fmt.format(counts[type]), "num")];+ })));++ var commands = events.filter(function (e) { return e && e.command && e.command.command; });+ root.appendChild(el("h2", "Commands"));+ if (commands.length === 0) {+ root.appendChild(el("p", "No commands in this trace.", "muted"));+ } else {+ root.appendChild(table([{ label: "#", num: true }, { label: "Command" }, { label: "Exit", num: true }], commands.map(function (e) {+ var code = e.command.exit_code;+ var exit = el("td", code === undefined || code === null ? "—" : code, code ? "num fail" : "num");+ var cmd = el("td");+ cmd.appendChild(el("code", e.command.command));+ return [el("td", e.number, "num"), cmd, exit];+ })));+ }++ root.appendChild(el("h2", "Findings"));+ if (!data.findings) {+ root.appendChild(el("p", "This trace was not scanned.", "muted"));+ } else if (!data.findings.items || data.findings.items.length === 0) {+ root.appendChild(el("p", "No rule matched (" + fmt.format(data.findings.rules_evaluated || 0) + " rules evaluated).", "muted"));+ } else {+ root.appendChild(table([{ label: "Severity" }, { label: "Rule" }, { label: "Evidence" }], data.findings.items.map(function (f) {+ var evidence = (f.event_ids || []).map(function (id) {+ return byId[id] ? "#" + byId[id].number : "outside this bundle";+ }).join(", ");+ return [el("td", f.severity || "—"), el("td", f.title || f.rule_id), el("td", evidence || "—")];+ })));+ }++ if (data.truncated) {+ root.appendChild(el("p", "Showing " + fmt.format(events.length) + " of " + fmt.format((trace.range && trace.range.total_events) || events.length) + " events.", "muted"));+ }+ status.hidden = true;+ root.hidden = false;+ }++ window.beacon.getTrace().then(render, function (err) {+ status.textContent = "Could not load this trace: " + ((err && err.message) || err);+ });+})();+</script>+</body>+</html>diff --git a/cli/beacon/internal/endpoint/dashboard/lenses/prelude.js b/cli/beacon/internal/endpoint/dashboard/lenses/prelude.jsnew file mode 100644index 00000000..a68e5703--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/lenses/prelude.js@@ -0,0 +1,114 @@+// Lens frame prelude. The dashboard injects this ahead of every lens, so it runs before any lens+// code. It defines window.beacon and owns the frame's half of the host protocol:+//+// host -> window one postMessage {type: "beacon.lens.connect", version: 1} carrying a+// MessagePort, and nothing else.+// frame -> port {type: "getTrace"} the lens asked for its data+// {type: "resize", height: n} document height changed+// {type: "error", message: s} uncaught error or unhandled rejection+// port -> frame {type: "trace", data: {...}} the LensDataV1+// {type: "traceError", message: s}+//+// Trace data only ever crosses the private port. Everything that arrives here is checked, because+// the host is the only party allowed to talk to the frame and anything else is ignored.+(function () {+ "use strict";+ var TIMEOUT_MS = 10000;+ var port = null;+ var pending = [];+ var tracePromise = null;+ var settle = null;++ function send(message) {+ if (port) {+ port.postMessage(message);+ } else {+ pending.push(message);+ }+ }++ function onPortMessage(event) {+ var message = event.data;+ if (!message || typeof message !== "object" || !settle) return;+ if (message.type === "trace") {+ settle(null, message.data);+ } else if (message.type === "traceError") {+ settle(new Error(String(message.message || "the dashboard could not load this trace")));+ }+ }++ // Registered first and in the capture phase, so this listener sees the connect message before any+ // lens listener can, and stops it there: the port is the frame's only channel to the host.+ window.addEventListener("message", function onConnect(event) {+ var message = event.data;+ if (event.source !== window.parent || !message || message.type !== "beacon.lens.connect" || !event.ports || !event.ports[0]) {+ return;+ }+ event.stopImmediatePropagation();+ window.removeEventListener("message", onConnect, true);+ port = event.ports[0];+ port.onmessage = onPortMessage;+ while (pending.length) port.postMessage(pending.shift());+ }, true);++ function getTrace() {+ if (!tracePromise) {+ tracePromise = new Promise(function (resolve, reject) {+ var timer = setTimeout(function () {+ settle(new Error("the dashboard did not send this trace within " + TIMEOUT_MS / 1000 + " seconds"));+ }, TIMEOUT_MS);+ settle = function (err, data) {+ clearTimeout(timer);+ settle = null;+ if (err) {+ reject(err);+ } else {+ resolve(data);+ }+ };+ });+ send({ type: "getTrace" });+ }+ return tracePromise;+ }++ Object.defineProperty(window, "beacon", {+ value: Object.freeze({ getTrace: getTrace }),+ writable: false,+ configurable: false,+ enumerable: true+ });++ // The host sizes the frame to its content. Report the document height whenever it changes.+ var lastHeight = -1;+ function reportHeight() {+ var root = document.documentElement;+ var height = Math.ceil(Math.max(root ? root.scrollHeight : 0, document.body ? document.body.scrollHeight : 0));+ if (height !== lastHeight) {+ lastHeight = height;+ send({ type: "resize", height: height });+ }+ }+ function observeSize() {+ if (typeof ResizeObserver === "function") {+ new ResizeObserver(reportHeight).observe(document.documentElement);+ }+ reportHeight();+ }+ if (document.readyState === "loading") {+ document.addEventListener("DOMContentLoaded", observeSize);+ } else {+ observeSize();+ }++ function reportError(message) {+ send({ type: "error", message: String(message).slice(0, 500) });+ }+ window.addEventListener("error", function (event) {+ reportError(event.message || "error");+ });+ window.addEventListener("unhandledrejection", function (event) {+ var reason = event.reason;+ reportError((reason && reason.message) || reason || "unhandled rejection");+ });+})();diff --git a/cli/beacon/internal/endpoint/dashboard/lenses/tokens.css b/cli/beacon/internal/endpoint/dashboard/lenses/tokens.cssnew file mode 100644index 00000000..6dccd2e0--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/lenses/tokens.css@@ -0,0 +1,13 @@+:root {+ --beacon-text: #111827;+ --beacon-muted: #6b7280;+ --beacon-line: rgba(0, 0, 0, 0.1);+ --beacon-panel-soft: #f9fafb;+ --beacon-accent: #036aa2;+ --beacon-accent-soft: #e2f0f8;+ --beacon-danger: #b91c1c;+ --beacon-warn: #92400e;+ --beacon-ok: #047857;+ --beacon-font-sans: "Familjen Grotesk", ui-sans-serif, system-ui, sans-serif;+ --beacon-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+}diff --git a/cli/beacon/internal/endpoint/dashboard/lenses_test.go b/cli/beacon/internal/endpoint/dashboard/lenses_test.gonew file mode 100644index 00000000..1f2e874e--- /dev/null+++ b/cli/beacon/internal/endpoint/dashboard/lenses_test.go@@ -0,0 +1,248 @@+package dashboard++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"+ "testing"+ "testing/fstest"+)++// lensSpecDir locates spec/lenses from this file, so tests compare against what the spec publishes.+func lensSpecDir(t *testing.T) string {+ t.Helper()+ _, thisFile, _, ok := runtime.Caller(0)+ if !ok {+ t.Fatal("runtime.Caller failed")+ }+ for dir := filepath.Dir(thisFile); ; {+ candidate := filepath.Join(dir, "spec", "lenses")+ if _, err := os.Stat(filepath.Join(candidate, "VERSION")); err == nil {+ return candidate+ }+ parent := filepath.Dir(dir)+ if parent == dir {+ t.Fatal("could not locate spec/lenses/VERSION")+ }+ dir = parent+ }+}++func lensTestHandler(t *testing.T) http.Handler {+ t.Helper()+ handler, err := Handler(Options{UserMode: true, LogPath: filepath.Join(t.TempDir(), "runtime.jsonl")})+ if err != nil {+ t.Fatal(err)+ }+ return handler+}++func serve(handler http.Handler, method, url string) *httptest.ResponseRecorder {+ rec := httptest.NewRecorder()+ handler.ServeHTTP(rec, httptest.NewRequest(method, url, nil))+ return rec+}++// The activity built-in is the spec's example lens, byte for byte, so the example an agent copies+// is one the dashboard actually runs.+func TestBuiltinActivityLensIsTheSpecExample(t *testing.T) {+ embedded, err := builtinLensFiles.ReadFile("lenses/activity.lens.html")+ if err != nil {+ t.Fatal(err)+ }+ example, err := os.ReadFile(filepath.Join(lensSpecDir(t), "examples", "activity.lens.html"))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(embedded, example) {+ t.Fatal("lenses/activity.lens.html drifted from spec/lenses/examples/activity.lens.html; copy the example over")+ }+}++func TestBuiltinLensesLoad(t *testing.T) {+ registry, err := loadBuiltinLenses(builtinLensFiles)+ if err != nil {+ t.Fatal(err)+ }+ activity, ok := registry.byID["activity"]+ if !ok || activity.info.Source != LensSourceBuiltin || activity.info.Title != "Activity" {+ t.Fatalf("activity lens = %#v, %v", activity.info, ok)+ }+}++func TestLoadBuiltinLensesRejectsABrokenLens(t *testing.T) {+ manifest := func(id, api string) string {+ return `<!doctype html><script type="application/beacon-lens+json">{"id":"` + id + `","title":"T","version":1,"api":"` + api + `"}</script>`+ }+ cases := map[string]fstest.MapFS{+ "no manifest": {"lenses/a.lens.html": {Data: []byte("<!doctype html><p>hi")}},+ "invalid manifest": {"lenses/a.lens.html": {Data: []byte(manifest("a", "beacon.lens.v9"))}},+ "file name mismatch": {"lenses/a.lens.html": {Data: []byte(manifest("b", "beacon.lens.v1"))}},+ }+ for name, files := range cases {+ t.Run(name, func(t *testing.T) {+ if _, err := loadBuiltinLenses(files); err == nil {+ t.Fatal("loadBuiltinLenses accepted a broken built-in")+ }+ })+ }+}++func TestLensListEndpoint(t *testing.T) {+ handler := lensTestHandler(t)+ rec := serve(handler, http.MethodGet, "/api/lenses")+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d", rec.Code)+ }+ var resp LensListResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatal(err)+ }+ found := false+ for _, l := range resp.Lenses {+ if l.ID == "activity" && l.Source == LensSourceBuiltin && l.Version >= 1 {+ found = true+ }+ }+ if !found {+ t.Fatalf("lenses = %#v, want the activity built-in", resp.Lenses)+ }+ if rec := serve(handler, http.MethodPost, "/api/lenses"); rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("POST status = %d, want 405", rec.Code)+ }+}++func TestLensFrameIsServedSandboxedWithThePrelude(t *testing.T) {+ handler := lensTestHandler(t)+ rec := serve(handler, http.MethodGet, "/lenses/frame/activity")+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d", rec.Code)+ }+ h := rec.Header()+ if got := h.Get("Content-Security-Policy"); got != lensFrameCSP {+ t.Fatalf("CSP = %q", got)+ }+ for _, directive := range []string{"default-src 'none'", "connect-src 'none'", "frame-ancestors 'self'", "sandbox allow-scripts"} {+ if !strings.Contains(lensFrameCSP, directive) {+ t.Errorf("frame CSP lacks %q", directive)+ }+ }+ if strings.Contains(lensFrameCSP, "allow-same-origin") || strings.Contains(lensFrameCSP, "unsafe-eval") {+ t.Error("frame CSP must not grant allow-same-origin or unsafe-eval")+ }+ if got := h.Get("X-Frame-Options"); got != "" {+ t.Fatalf("X-Frame-Options = %q; the dashboard must be able to frame a lens", got)+ }+ if got := h.Get("Content-Type"); got != "text/html; charset=utf-8" {+ t.Fatalf("Content-Type = %q", got)+ }+ if h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Cache-Control") != "no-store" {+ t.Fatalf("headers = %v", h)+ }++ body := rec.Body.String()+ if !strings.HasPrefix(body, "<!doctype html><style>") {+ t.Fatalf("frame does not start with the doctype then the prelude: %.80q", body)+ }+ prelude := strings.Index(body, "Object.defineProperty(window, \"beacon\"")+ firstLensScript := strings.Index(body, "window.beacon.getTrace()")+ if prelude < 0 || firstLensScript < 0 || prelude > firstLensScript {+ t.Fatal("window.beacon must be defined before the lens's own script")+ }+ if !strings.Contains(body, `<script type="application/beacon-lens+json">`) {+ t.Fatal("frame lost the lens's manifest")+ }++ head := serve(handler, http.MethodHead, "/lenses/frame/activity")+ if head.Code != http.StatusOK || head.Body.Len() != 0 {+ t.Fatalf("HEAD = %d with %d bytes", head.Code, head.Body.Len())+ }+ for _, url := range []string{"/lenses/frame/nope", "/lenses/frame/", "/lenses/frame/activity/extra", "/lenses/frame/ACTIVITY"} {+ if rec := serve(handler, http.MethodGet, url); rec.Code != http.StatusNotFound {+ t.Errorf("GET %s = %d, want 404", url, rec.Code)+ }+ }+ if rec := serve(handler, http.MethodPost, "/lenses/frame/activity"); rec.Code != http.StatusMethodNotAllowed {+ t.Fatalf("POST status = %d, want 405", rec.Code)+ }+}++// The frame route loosens framing for itself only. Every other page keeps refusing to be framed.+func TestDashboardPagesStillRefuseFraming(t *testing.T) {+ handler := lensTestHandler(t)+ for _, url := range []string{"/", "/session.html", "/api/lenses"} {+ rec := serve(handler, http.MethodGet, url)+ if rec.Header().Get("X-Frame-Options") != "DENY" || !strings.Contains(rec.Header().Get("Content-Security-Policy"), "frame-ancestors 'none'") {+ t.Errorf("%s headers = %v, want framing refused", url, rec.Header())+ }+ }+}++func TestWithLensPrelude(t *testing.T) {+ prelude := string(lensPrelude())+ cases := map[string]struct{ in, want string }{+ "doctype": {"<!doctype html><p>x", "<!doctype html>" + prelude + "<p>x"},+ "doctype upper case": {"<!DOCTYPE html>\n<p>x", "<!DOCTYPE html>" + prelude + "\n<p>x"},+ "leading whitespace": {"\n <!doctype html><p>x", "<!doctype html>" + prelude + "<p>x"},+ "byte order mark": {"\xef\xbb\xbf<!doctype html><p>x", "<!doctype html>" + prelude + "<p>x"},+ "no doctype": {"<html><p>x", prelude + "<html><p>x"},+ "doctype not first": {"<p>x<!doctype html>", prelude + "<p>x<!doctype html>"},+ }+ for name, tc := range cases {+ t.Run(name, func(t *testing.T) {+ if got := string(withLensPrelude([]byte(tc.in))); got != tc.want {+ t.Fatalf("withLensPrelude(%q) = %q", tc.in, got)+ }+ })+ }+}++// The prelude is inlined into <script> and <style> elements, so it must never contain the text that+// would close them early.+func TestLensPreludeCannotCloseItsOwnElements(t *testing.T) {+ if strings.Contains(strings.ToLower(lensPreludeJS), "</script") {+ t.Fatal("prelude.js contains </script")+ }+ if strings.Contains(strings.ToLower(lensTokensCSS), "</style") {+ t.Fatal("tokens.css contains </style")+ }+}++// The tokens the spec documents are the tokens the dashboard defines, with the same values.+func TestLensTokensMatchTheSpec(t *testing.T) {+ spec, err := os.ReadFile(filepath.Join(lensSpecDir(t), "SPEC.md"))+ if err != nil {+ t.Fatal(err)+ }+ row := regexp.MustCompile("(?m)^\\s*\\| `(--beacon-[a-z-]+)` \\| (.+?) \\|$")+ css := regexp.MustCompile(`(?m)^\s*(--beacon-[a-z-]+):\s*(.+?);$`)+ defined := map[string]string{}+ for _, m := range css.FindAllStringSubmatch(lensTokensCSS, -1) {+ defined[m[1]] = m[2]+ }+ documented := row.FindAllStringSubmatch(string(spec), -1)+ if len(documented) == 0 {+ t.Fatal("no token rows found in SPEC.md")+ }+ if len(documented) != len(defined) {+ t.Errorf("SPEC.md documents %d tokens, tokens.css defines %d", len(documented), len(defined))+ }+ for _, m := range documented {+ name, value := m[1], m[2]+ got, ok := defined[name]+ if !ok {+ t.Errorf("%s is documented but not defined", name)+ continue+ }+ // Literal values are written in backticks; prose descriptions (the font stack) are not.+ if strings.HasPrefix(value, "`") && strings.Trim(value, "`") != got {+ t.Errorf("%s: spec %s, tokens.css %q", name, value, got)+ }+ }+}diff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.goindex 7642b091..9717eb9c 100644--- a/cli/beacon/internal/endpoint/dashboard/server.go+++ b/cli/beacon/internal/endpoint/dashboard/server.go@@ -90,6 +90,10 @@ func Handler(opts Options) (http.Handler, error) {if err != nil {return nil, err}+ lenses, err := loadBuiltinLenses(builtinLensFiles)+ if err != nil {+ return nil, err+ }mux := http.NewServeMux()mux.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {@@ -232,6 +236,14 @@ func Handler(opts Options) (http.Handler, error) {}writeJSON(w, trace)})+ mux.HandleFunc("/api/lenses", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ methodNotAllowed(w)+ return+ }+ writeJSON(w, lenses.list())+ })+ mux.HandleFunc(lensFramePrefix, lenses.serveLensFrame)// Lens data is what one lens frame receives from window.beacon.getTrace(). The session page// fetches it and hands it to the frame over a MessageChannel; the frame itself never calls// this route, because its sandbox and CSP give it no network.