Feat v0.9.0 multi-surface packages (#73)
All checks were successful
CI/CD / detect-changes (pull_request) Successful in 4s
CI/CD / test-runners (pull_request) Has been skipped
CI/CD / e2e-smoke (pull_request) Has been skipped
CI/CD / test-frontend (pull_request) Successful in 5s
CI/CD / test-go-pg (pull_request) Successful in 2m48s
CI/CD / test-sqlite (pull_request) Successful in 2m57s
CI/CD / build-and-deploy (pull_request) Successful in 1m23s

Packages can declare a `surfaces` array with per-path access controls,
titles, and layouts. A single package can serve a public form, an
authenticated dashboard, and an admin page — each with independent
access enforcement.

Kernel:
- Manifest validation for surfaces array (path, access, duplicates)
- Auto-synthesis from legacy auth/layout for existing packages
- Unified /s/:slug route tree (RegisterExtensionRoutes) dispatches
  between surface rendering and ext API calls
- matchSurface() with Gin-style :param support and specificity ordering
- evaluateAccess() for per-surface access checks
- Nav filters out pending_review packages (pre-existing bug fix)

Frontend:
- __SURFACE_PATH__ and __SURFACE_PARAMS__ template injection
- sw.navigate(path, params) for SPA-style intra-package routing
- surface.navigate event + popstate handling
- SDK version bumped to 0.9.0

Docs:
- MULTI-SURFACE-GUIDE.md — full developer guide
- PACKAGE-FORMAT.md — surfaces field reference
- CHANGELOG.md, ROADMAP.md updated

22 new tests (11 manifest validation, 11 route matching/nav).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-03 12:34:38 +00:00
parent 98fd3eb3e6
commit c2473efee2
12 changed files with 1075 additions and 62 deletions

View File

@@ -99,7 +99,9 @@ type PageData struct {
Theme string // "dark", "light", or "" (= use default)
SurfaceSettings any // JSON-serialized to window.__SETTINGS__
Manifest *SurfaceManifest `json:"manifest,omitempty"`
Manifest *SurfaceManifest `json:"manifest,omitempty"`
SurfacePath string `json:"-"` // matched surface path pattern, e.g. "/monitor"
SurfaceParams map[string]string `json:"-"` // extracted params, e.g. {"id": "abc"}
EnabledSurfaces []string `json:"-"`
@@ -158,29 +160,60 @@ func (e *Engine) extensionNavItems() []ExtensionNavItem {
var items []ExtensionNavItem
for _, sr := range surfaces {
if sr.Source == "core" || !sr.Enabled {
if sr.Source == "core" || !sr.Enabled || sr.Status != "active" {
continue
}
// Only surface and full types have routes — extensions are headless
if sr.Type != "surface" && sr.Type != "full" {
continue
}
route := ""
basePath := "/s/" + sr.ID
title := sr.Title
// Multi-surface: find the nav entry from surfaces array
if sr.Manifest != nil {
route, _ = sr.Manifest["route"].(string)
}
if route == "" {
route = "/s/" + sr.ID
if rawSurfaces, ok := sr.Manifest["surfaces"].([]any); ok {
navEntry := findNavSurface(rawSurfaces)
if navEntry != nil {
if p, ok := navEntry["path"].(string); ok && p != "/" {
basePath = "/s/" + sr.ID + p
}
if t, ok := navEntry["title"].(string); ok && t != "" {
title = t
}
}
}
}
items = append(items, ExtensionNavItem{
ID: sr.ID,
Title: sr.Title,
Route: route,
Title: title,
Route: basePath,
})
}
return items
}
// findNavSurface returns the surface entry to use for navigation.
// Returns the first entry with nav:true, falling back to the entry with path "/".
func findNavSurface(surfaces []any) map[string]any {
var root map[string]any
for _, raw := range surfaces {
s, ok := raw.(map[string]any)
if !ok {
continue
}
if nav, ok := s["nav"].(bool); ok && nav {
return s
}
if p, ok := s["path"].(string); ok && p == "/" {
root = s
}
}
return root
}
// browserExtensionIDs returns IDs of enabled browser-tier extensions.
// These extensions have JS scripts that should be injected into every page
// so they can register renderers with the SDK.
@@ -401,8 +434,10 @@ func (e *Engine) RenderSurface(surfaceID string) gin.HandlerFunc {
}
}
// RenderExtensionSurface handles /s/:slug — dynamic DB lookup for extension surfaces.
// No restart required after installing a surface via admin API.
// RenderExtensionSurface handles extension surface rendering with multi-surface
// support. Each surface entry in the manifest can have its own path, access
// level, title, and layout. Called by RegisterExtensionRoutes for both root
// requests (/s/:slug) and sub-path requests (/s/:slug/monitor).
func (e *Engine) RenderExtensionSurface() gin.HandlerFunc {
return func(c *gin.Context) {
slug := c.Param("slug")
@@ -410,6 +445,10 @@ func (e *Engine) RenderExtensionSurface() gin.HandlerFunc {
c.String(http.StatusNotFound, "Surface not found")
return
}
reqPath := c.Param("path")
if reqPath == "" {
reqPath = "/"
}
if e.stores.Packages == nil {
c.String(http.StatusNotFound, "Surface registry not available")
@@ -427,28 +466,70 @@ func (e *Engine) RenderExtensionSurface() gin.HandlerFunc {
return
}
if sr.Source == "core" {
// Core surfaces have their own routes — don't serve them here
c.String(http.StatusNotFound, "Surface not found: "+slug)
return
}
// ── Multi-surface resolution ─────────────────────────────
var surfacePath string
var surfaceParams map[string]string
surfaceTitle := sr.Title
surfaceAccess := "authenticated"
surfaceLayout := "single"
// Read package-level defaults
if pkgAuth, ok := sr.Manifest["auth"].(string); ok && pkgAuth != "" {
surfaceAccess = pkgAuth
}
if pkgLayout, ok := sr.Manifest["layout"].(string); ok && pkgLayout != "" {
surfaceLayout = pkgLayout
}
if rawSurfaces, ok := sr.Manifest["surfaces"].([]any); ok && len(rawSurfaces) > 0 {
matched, params := matchSurface(rawSurfaces, reqPath)
if matched == nil {
c.String(http.StatusNotFound, "Page not found")
return
}
surfacePath, _ = matched["path"].(string)
surfaceParams = params
if t, ok := matched["title"].(string); ok && t != "" {
surfaceTitle = t
}
if a, ok := matched["access"].(string); ok && a != "" {
surfaceAccess = a
}
if l, ok := matched["layout"].(string); ok && l != "" {
surfaceLayout = l
}
} else {
// Legacy package without surfaces — only serve root path
if reqPath != "/" {
c.String(http.StatusNotFound, "Page not found")
return
}
surfacePath = "/"
}
// ── Access check ─────────────────────────────────────────
if !evaluateAccess(c, surfaceAccess) {
// Redirect unauthenticated users to login; deny others with 403
if c.GetString("user_id") == "" {
c.Redirect(http.StatusTemporaryRedirect, e.cfg.BasePath+"/login")
} else {
c.String(http.StatusForbidden, "Access denied")
}
return
}
user := e.getUserContext(c)
// Build manifest from DB record
route, _ := sr.Manifest["route"].(string)
if route == "" {
route = "/s/" + sr.ID
}
layout, _ := sr.Manifest["layout"].(string)
if layout == "" {
layout = "single"
}
manifest := &SurfaceManifest{
ID: sr.ID,
Route: route,
Title: sr.Title,
Route: "/s/" + sr.ID,
Title: surfaceTitle,
Template: "surface-extension",
Layout: layout,
Layout: surfaceLayout,
Source: "extension",
}
@@ -456,6 +537,8 @@ func (e *Engine) RenderExtensionSurface() gin.HandlerFunc {
Surface: sr.ID,
User: user,
Manifest: manifest,
SurfacePath: surfacePath,
SurfaceParams: surfaceParams,
EnabledSurfaces: e.EnabledSurfaceIDs(),
ExtensionSurfaces: e.extensionNavItems(),
BrowserExtensions: e.browserExtensionIDs(),
@@ -463,6 +546,98 @@ func (e *Engine) RenderExtensionSurface() gin.HandlerFunc {
}
}
// matchSurface finds the best-matching surface entry for a request path.
// Supports Gin-style param segments (/:id matches /abc). Static segments
// are preferred over param segments. Returns nil if no surface matches.
func matchSurface(surfaces []any, reqPath string) (map[string]any, map[string]string) {
reqParts := splitPath(reqPath)
type candidate struct {
surface map[string]any
params map[string]string
score int // higher = more static segments = better match
}
var best *candidate
for _, raw := range surfaces {
s, ok := raw.(map[string]any)
if !ok {
continue
}
pattern, _ := s["path"].(string)
if pattern == "" {
continue
}
patParts := splitPath(pattern)
if len(patParts) != len(reqParts) {
continue
}
params := map[string]string{}
score := 0
matched := true
for i, pp := range patParts {
if strings.HasPrefix(pp, ":") {
params[pp[1:]] = reqParts[i]
} else if pp == reqParts[i] {
score++
} else {
matched = false
break
}
}
if !matched {
continue
}
if best == nil || score > best.score {
best = &candidate{surface: s, params: params, score: score}
}
}
if best == nil {
return nil, nil
}
return best.surface, best.params
}
// splitPath splits a URL path into non-empty segments.
// "/" → [], "/monitor" → ["monitor"], "/monitor/:id" → ["monitor", ":id"]
func splitPath(p string) []string {
var parts []string
for _, s := range strings.Split(p, "/") {
if s != "" {
parts = append(parts, s)
}
}
return parts
}
// evaluateAccess checks whether the current request meets an access requirement.
func evaluateAccess(c *gin.Context, access string) bool {
switch {
case access == "public":
return true
case access == "authenticated":
return c.GetString("user_id") != ""
case access == "admin":
return c.GetBool("is_admin")
case strings.HasPrefix(access, "group:"):
// Group membership check — look for groups set by auth middleware
group := strings.TrimPrefix(access, "group:")
if groups, exists := c.Get("user_groups"); exists {
if gs, ok := groups.([]string); ok {
for _, g := range gs {
if g == group {
return true
}
}
}
}
return false
default:
return false
}
}
// PageRouteMiddleware holds middleware handlers for each auth level.
// Passed to RegisterPageRoutes by main.go.
type PageRouteMiddleware struct {
@@ -502,8 +677,9 @@ func (e *Engine) RegisterPageRoutes(base *gin.RouterGroup, mw PageRouteMiddlewar
registerRoutes(group, s, handler)
}
// No restart needed after installing new surfaces via admin API.
group.GET("/s/:slug", e.RenderExtensionSurface())
// Extension surfaces are registered separately via
// RegisterExtensionRoutes (called from main.go) to unify
// the /s/:slug route tree with the ext API dispatcher.
}
// Admin surfaces — auth + admin role middleware
@@ -553,6 +729,63 @@ func (e *Engine) RegisterPageRoutes(base *gin.RouterGroup, mw PageRouteMiddlewar
log.Printf("[pages] Registered routes for %d surfaces", len(e.surfaces))
}
// RegisterExtensionRoutes registers the combined extension surface and ext API
// routes. A single /s/:slug/*path catch-all dispatches between:
// - /s/:slug/api/* → apiAuth middleware + extAPIHandler (JSON API)
// - /s/:slug/* → surface handler with per-surface access checks (HTML)
//
// This avoids Gin route conflicts between the catch-all and the API sub-path.
// Must be called AFTER RegisterPageRoutes (which handles core surfaces).
func (e *Engine) RegisterExtensionRoutes(
base *gin.RouterGroup,
optAuth gin.HandlerFunc,
apiAuth gin.HandlerFunc,
extAPIHandler gin.HandlerFunc,
) {
surfaceHandler := e.RenderExtensionSurface()
sGroup := base.Group("/s/:slug")
sGroup.Use(optAuth) // populate user context if token present; don't require it
// Root path: /s/:slug (no sub-path) — surface only
sGroup.GET("", surfaceHandler)
// Sub-paths: /s/:slug/* — dispatch between API and surface
sGroup.Any("/*path", func(c *gin.Context) {
subPath := c.Param("path")
// API requests: /s/:slug/api/*
if strings.HasPrefix(subPath, "/api/") || subPath == "/api" {
apiAuth(c)
if c.IsAborted() {
return
}
// Rewrite the path param so the ext API handler sees the
// API-relative path, e.g. "/api/items" → "/items"
apiPath := strings.TrimPrefix(subPath, "/api")
if apiPath == "" {
apiPath = "/"
}
for i := range c.Params {
if c.Params[i].Key == "path" {
c.Params[i].Value = apiPath
break
}
}
extAPIHandler(c)
return
}
// Surface requests: GET only
if c.Request.Method != http.MethodGet {
c.String(http.StatusMethodNotAllowed, "Method not allowed")
return
}
surfaceHandler(c)
})
}
// surfaceHandler returns the appropriate Gin handler for a surface.
func (e *Engine) surfaceHandler(s SurfaceManifest) gin.HandlerFunc {
if s.ID == "workflow" {