Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix(server): serve /openapi.json and /help on the full-server front door, and answer unrouted paths with the JSON error envelope on both muxes instead of a plain-text 404 (PIN-291)

Luigi Agosticf67fddf1d19
diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.go
index 3a805e3e..ba8da234 100644
--- a/internal/handlers/openapi.go
+++ b/internal/handlers/openapi.go
@@ -9,6 +9,17 @@ import (
)
func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
+ httpx.JSON(w, 200, h.openAPIDocument(""))
+}
+
+// ServeOpenAPI writes the spec with an optional info.description. A proxy front
+// door serves the catalogue-derived instance surface it forwards to, so it states
+// the scope of what the document does and does not enumerate.
+func (h *Handlers) ServeOpenAPI(w http.ResponseWriter, description string) {
+ httpx.JSON(w, 200, h.openAPIDocument(description))
+}
+
+func (h *Handlers) openAPIDocument(description string) map[string]any {
security := h.endpointSecurityStates()
paths := map[string]map[string]any{}
@@ -92,13 +103,17 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {
}
}
- httpx.JSON(w, 200, map[string]any{
- "openapi": "3.0.0",
- "info": map[string]any{
- "title": "Pinchtab API",
- "version": "0.7.x-local",
- },
+ info := map[string]any{
+ "title": "Pinchtab API",
+ "version": "0.7.x-local",
+ }
+ if description != "" {
+ info["description"] = description
+ }
+ return map[string]any{
+ "openapi": "3.0.0",
+ "info": info,
"x-pinchtab-security": security,
"paths": paths,
- })
+ }
}
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
index b9651143..e52f5dc8 100644
--- a/internal/server/bridge.go
+++ b/internal/server/bridge.go
@@ -97,7 +97,7 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {
actStore,
"bridge",
handlers.SecurityHeadersMiddleware(live,
- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(live, mux))),
+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(live, notFoundEnvelope(mux)))),
),
)),
),
diff --git a/internal/server/front_door_openapi.go b/internal/server/front_door_openapi.go
new file mode 100644
index 00000000..4d2a1188
--- /dev/null
+++ b/internal/server/front_door_openapi.go
@@ -0,0 +1,29 @@
+package server
+
+import (
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/handlers"
+)
+
+// frontDoorOpenAPIScope is the info.description carried by the spec the front door
+// serves. The document is the catalogue-derived instance surface the front door
+// forwards to; the orchestrator's own management routes are registered
+// imperatively rather than in the shared route catalogue, so enumerating them
+// here would add a second hand-maintained route list — the drift this endpoint
+// exists to avoid — and they are named as a scope instead.
+const frontDoorOpenAPIScope = "Browser-automation API reachable through the pinchtab server front door; requests are forwarded to the active instance. The front door also serves orchestrator management routes under /instances/ and /profiles/, which are not enumerated in this document."
+
+// registerFrontDoorOpenAPI answers GET /openapi.json and its /help alias on the
+// front door, which otherwise fall through to the mux's plain-text 404. It reads
+// the live config per request so capability states track a dashboard save, and
+// builds the same document the bridge serves from the shared route catalogue —
+// one generator, two ports — carrying the scope note.
+func registerFrontDoorOpenAPI(mux *http.ServeMux, live *config.Live) {
+ serve := func(w http.ResponseWriter, _ *http.Request) {
+ (&handlers.Handlers{Config: live.Get()}).ServeOpenAPI(w, frontDoorOpenAPIScope)
+ }
+ mux.HandleFunc("GET /openapi.json", serve)
+ mux.HandleFunc("GET /help", serve)
+}
diff --git a/internal/server/front_door_openapi_test.go b/internal/server/front_door_openapi_test.go
new file mode 100644
index 00000000..21074dd7
--- /dev/null
+++ b/internal/server/front_door_openapi_test.go
@@ -0,0 +1,64 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// The reported defect: /openapi.json and /help answered a plain-text 404 on the
+// full-server front door while the bridge served them. This pins both on the
+// front-door mux so the two registration surfaces cannot drift apart again.
+func TestFrontDoorServesOpenAPIAndHelp(t *testing.T) {
+ mux := http.NewServeMux()
+ registerFrontDoorOpenAPI(mux, config.NewLive(&config.RuntimeConfig{}))
+ handler := notFoundEnvelope(mux)
+
+ for _, path := range []string{"/openapi.json", "/help"} {
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("GET %s: status = %d, want 200: %s", path, w.Code, w.Body.String())
+ }
+ var doc map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {
+ t.Fatalf("GET %s: body is not JSON (%v): %s", path, err, w.Body.String())
+ }
+ if doc["openapi"] == nil || doc["paths"] == nil {
+ t.Errorf("GET %s: not an OpenAPI document: %v", path, doc)
+ }
+ info, _ := doc["info"].(map[string]any)
+ if info == nil || info["description"] == nil {
+ t.Errorf("GET %s: the front-door spec must state its scope in info.description: %v", path, doc["info"])
+ }
+ }
+}
+
+// The scope note must actually name the surface it does not enumerate, so a
+// caller reading a 200 is not told the instance surface is the whole API.
+func TestFrontDoorOpenAPIStatesItsScope(t *testing.T) {
+ mux := http.NewServeMux()
+ registerFrontDoorOpenAPI(mux, config.NewLive(&config.RuntimeConfig{}))
+
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/openapi.json", nil))
+
+ var doc struct {
+ Info struct {
+ Description string `json:"description"`
+ } `json:"info"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &doc); err != nil {
+ t.Fatalf("body is not JSON: %v", err)
+ }
+ for _, want := range []string{"/instances", "/profiles"} {
+ if !strings.Contains(doc.Info.Description, want) {
+ t.Errorf("scope note does not name %q as also-served-but-unenumerated: %q", want, doc.Info.Description)
+ }
+ }
+}
diff --git a/internal/server/notfound.go b/internal/server/notfound.go
new file mode 100644
index 00000000..d9b679ef
--- /dev/null
+++ b/internal/server/notfound.go
@@ -0,0 +1,46 @@
+package server
+
+import (
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/httpx"
+)
+
+// notFoundEnvelope wraps a mux so a path it does not route answers the JSON error
+// envelope every other failure uses, instead of net/http's plain-text
+// "404 page not found" / "405 method not allowed". A registered handler still
+// wins — including the coded per-family refusals like the bridge-mode session
+// family — because it matches a pattern and this fallback fires only when none
+// does. The mux's own not-found/method handler is run against a throwaway writer
+// only to recover the status it would have written, so a wrong-method request
+// stays a 405.
+func notFoundEnvelope(mux *http.ServeMux) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ matched, pattern := mux.Handler(r)
+ if pattern != "" {
+ matched.ServeHTTP(w, r)
+ return
+ }
+
+ probe := &statusProbe{header: http.Header{}}
+ matched.ServeHTTP(probe, r)
+ status := probe.status
+ if status == 0 {
+ status = http.StatusNotFound
+ }
+ code := "not_found"
+ if status == http.StatusMethodNotAllowed {
+ code = "method_not_allowed"
+ }
+ httpx.ErrorCode(w, status, code, "no route for "+r.Method+" "+r.URL.Path, false, nil)
+ })
+}
+
+type statusProbe struct {
+ header http.Header
+ status int
+}
+
+func (p *statusProbe) Header() http.Header { return p.header }
+func (p *statusProbe) Write(b []byte) (int, error) { return len(b), nil }
+func (p *statusProbe) WriteHeader(status int) { p.status = status }
diff --git a/internal/server/notfound_test.go b/internal/server/notfound_test.go
new file mode 100644
index 00000000..33245bd1
--- /dev/null
+++ b/internal/server/notfound_test.go
@@ -0,0 +1,108 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func decodeEnvelope(t *testing.T, w *httptest.ResponseRecorder) (code, message string) {
+ t.Helper()
+ var resp struct {
+ Code string `json:"code"`
+ Error string `json:"error"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("body is not the JSON error envelope (%v): %s", err, w.Body.String())
+ }
+ return resp.Code, resp.Error
+}
+
+// An unrouted path used to escape the JSON contract as net/http's plain-text
+// "404 page not found". Every other failure on the same server answers the
+// envelope, so an unrouted one must too.
+func TestUnroutedPathAnswersTheJSONEnvelope(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /health", func(w http.ResponseWriter, _ *http.Request) {})
+ handler := notFoundEnvelope(mux)
+
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/nope", nil))
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+ if strings.Contains(w.Body.String(), "404 page not found") {
+ t.Fatalf("still the bare mux 404, which breaks the JSON contract: %s", w.Body.String())
+ }
+ code, message := decodeEnvelope(t, w)
+ if code != "not_found" {
+ t.Errorf("code = %q, want not_found", code)
+ }
+ if message == "" {
+ t.Error("the not-found refusal carries no message")
+ }
+}
+
+// The generic fallback is a floor, not a replacement: a registered coded refusal
+// still matches a pattern and must keep winning. The bridge-mode session family
+// is the codebase's own example of a known-absent family answered with a code
+// and a remedy, and it must not be flattened into the generic not_found body.
+func TestCodedRefusalsWinOverTheGenericFallback(t *testing.T) {
+ mux := http.NewServeMux()
+ RegisterSessionsUnavailableInBridgeMode(mux)
+ handler := notFoundEnvelope(mux)
+
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/sessions", nil))
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+ code, _ := decodeEnvelope(t, w)
+ if code != CodeSessionsUnavailableInBridgeMode {
+ t.Fatalf("code = %q, want %q — the coded refusal was flattened into the generic fallback", code, CodeSessionsUnavailableInBridgeMode)
+ }
+}
+
+// A matched route serves normally; the wrapper only fires when nothing is routed.
+func TestMatchedRouteIsUntouched(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /health", func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte("live"))
+ })
+ handler := notFoundEnvelope(mux)
+
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/health", nil))
+
+ if w.Code != http.StatusOK || w.Body.String() != "live" {
+ t.Fatalf("matched route not served: status=%d body=%q", w.Code, w.Body.String())
+ }
+}
+
+// A request for a real path under an unregistered method is not "no such path":
+// the wrapper preserves the 405 the mux would have written rather than reporting
+// a 404, while still answering the JSON envelope.
+func TestWrongMethodStaysA405Envelope(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /openapi.json", func(w http.ResponseWriter, _ *http.Request) {})
+ handler := notFoundEnvelope(mux)
+
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/openapi.json", nil))
+
+ if w.Code != http.StatusMethodNotAllowed {
+ t.Fatalf("status = %d, want 405", w.Code)
+ }
+ if strings.Contains(w.Body.String(), "method not allowed\n") {
+ t.Fatalf("still the bare mux 405 plain text: %s", w.Body.String())
+ }
+ code, _ := decodeEnvelope(t, w)
+ if code != "method_not_allowed" {
+ t.Errorf("code = %q, want method_not_allowed", code)
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index bc106470..f35ceabf 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -283,6 +283,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
mux.HandleFunc("GET /health", configAPI.HandleHealth)
registerFrontDoorMetrics(mux)
+ registerFrontDoorOpenAPI(mux, live)
mux.HandleFunc("GET /health/background", func(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, http.StatusOK, map[string]string{
"status": "ok",
@@ -292,7 +293,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
})
})
- handler := FrontDoorHandler(live, liveActivity, sessions, sessionStore, mux)
+ handler := FrontDoorHandler(live, liveActivity, sessions, sessionStore, notFoundEnvelope(mux))
if cfg.VerboseBanner {
cli.LogSecurityWarnings(cfg)
}