kernel

package module
v1.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package kernel is the public contract of Lesstruct v1 ("everything is a module").

Kernel owns the Module lifecycle, the Principal identity shape, the module registry, and the database driver/dialect contracts. It imports nothing from Lesstruct modules or internals, so dependencies always point one way: modules import kernel, the composition root imports everything.

Versioning: the kernel is an independent Go module tagged kernel/vX.Y.Z. Semver rules, stability classes, and the deprecation flow live in docs/kernel-versioning.md. The one rule to internalize: adding a method to an exported interface is a breaking change — prefer new narrow interfaces over widening existing ones.

Terminology: "modules" are compile-time Go modules (Tier 1). "Plugins" are the sandboxed WASM extensions (Tier 2) and live outside this package.

Package kernel session cookie contract: the browser session cookie name plus the HTTPS-detection helper shared by middleware, auth handlers, and app wiring.

Index

Constants

View Source
const (
	// SessionCookieName is the HttpOnly browser session cookie. It is
	// namespaced away from the storefront token keys.
	SessionCookieName = "lesstruct_jwt"

	// AuthHintCookieName is the JS-readable presence hint mirroring the
	// session cookie. It carries a fixed sentinel, never a token or PII,
	// so anonymous page loads can skip profile probes without a request.
	AuthHintCookieName = "lesstruct_auth"
)

Variables

View Source
var (
	ErrDuplicateModule    = errors.New("kernel: duplicate module")
	ErrMissingDependency  = errors.New("kernel: missing module dependency")
	ErrCircularDependency = errors.New("kernel: circular module dependency")
	ErrNilKernel          = errors.New("kernel: host cannot be nil")
	ErrNilModule          = errors.New("kernel: module cannot be nil")
)
View Source
var ErrInvalidPrincipalID = errors.New("kernel: invalid principal ID")

ErrInvalidPrincipalID marks a principal whose ID is not a decimal user ID.

Functions

func Capabilities

func Capabilities[T any](r *Registry) []T

Capabilities collects every registered module implementing capability T in registry name order. It is the discovery mechanism modules use instead of a service locator.

func ClearSessionCookie added in v1.1.0

func ClearSessionCookie(w http.ResponseWriter, r *http.Request)

ClearSessionCookie clears the browser session cookie with matching attributes so the deletion replaces the session cookie. It also clears the auth hint with the same scope so later loads behave as anonymous.

func ContextWithPrincipal

func ContextWithPrincipal(
	ctx context.Context,
	principal Principal,
) context.Context

ContextWithPrincipal stores the principal in the context.

func RequestIsHTTPS added in v1.1.0

func RequestIsHTTPS(r *http.Request) bool

RequestIsHTTPS reports whether the visitor reached the site over TLS. X-Forwarded-Proto wins when present so deployments behind a TLS-terminating reverse proxy see the client-facing scheme; otherwise the connection state decides. Only the first forwarded value is used.

func SetSessionCookie added in v1.1.0

func SetSessionCookie(
	w http.ResponseWriter,
	r *http.Request,
	token string,
	expires time.Time,
)

SetSessionCookie writes the browser session cookie. The cookie is HttpOnly, SameSite=Lax, Path=/, and Secure exactly on HTTPS so plain-HTTP localhost keeps working. Lifetime matches the token expiry. It also writes the JS-readable auth hint with the same scope and expiry so the storefront can skip anonymous profile probes; the hint carries a fixed sentinel, never the token.

Types

type AdminExtensionManifest

type AdminExtensionManifest struct {
	MenuEntries      []AdminMenuEntry
	SettingsSections []string
	EditorExtensions []string
}

AdminExtensionManifest is the declarative UI a feature module contributes to the admin shell: navigation, settings sections, and editor extensions. One shell renders everything; modules never ship their own mini-SPA.

func (AdminExtensionManifest) Validate

func (m AdminExtensionManifest) Validate() error

Validate ensures a manifest's entries are well-formed: menu entries need a label, an absolute path, and no duplicate paths. It mirrors the shell's own checks so module authors catch malformed manifests in unit tests (see kernel/conformance CheckAdminExtension for the third-party fixture).

type AdminExtensionProvider

type AdminExtensionProvider interface {
	Module
	AdminManifest() AdminExtensionManifest
}

AdminExtensionProvider contributes UI to the admin shell via manifest.

type AdminMenuEntry

type AdminMenuEntry struct {
	Label string
	Path  string
	Icon  string
}

AdminMenuEntry is one navigation item contributed to the admin shell.

type CapabilityResolver

type CapabilityResolver func(principal Principal, capability string) bool

CapabilityResolver maps a principal plus a capability name (for example "content.publish") to an allow/deny decision.

Implemented by the users module. The kernel never resolves roles itself.

type ContentTypeProvider

type ContentTypeProvider interface {
	Module
	PostTypes() []PostTypeDef
}

ContentTypeProvider registers content types (post, page, product, ...).

type DroppedModule

type DroppedModule struct {
	// Name is the dropped module's registry key.
	Name string
	// Direct is true when the module itself was named in disabled, false
	// when it cascaded from a disabled requirement.
	Direct bool
	// Cause names the disabled module that forced the drop: the module
	// itself when Direct, otherwise the unavailable requirement.
	Cause string
}

DroppedModule names one module Prune removed from the candidate list.

type DualAuthProvider added in v1.1.0

type DualAuthProvider interface {
	Module
	RegisterDualRoutes(r DualAuthRegistrar)
}

DualAuthProvider is implemented by modules whose admin surface both realms must serve with the same handler methods — typically commerce surfaces an AI agent operates with an API key while the admin SPA drives them with a JWT cookie. Patterns must be full /api/v1/... paths (the mount point carries no sub-router prefix) and must not collide with any other registration. Handlers keep their in-handler capability checks, which resolve API-key principals exactly like JWT ones — a non-admin key answers 403 on both realms with no extra middleware.

type DualAuthRegistrar added in v1.1.0

type DualAuthRegistrar interface {
	Get(pattern string, h http.HandlerFunc)
	Post(pattern string, h http.HandlerFunc)
	Put(pattern string, h http.HandlerFunc)
	Delete(pattern string, h http.HandlerFunc)
	Patch(pattern string, h http.HandlerFunc)
}

DualAuthRegistrar is the narrow route sink core passes to dual-realm modules: only the flat verb registrations a shared admin path needs. Core mounts every registration twice — once on the agent stack (Bearer API key auth plus per-key rate limits) and once on the browser stack (CSRF plus JWT auth) — dispatched by credential at the shared path, exactly like the media co-owned paths. Chi routes by path, not auth realm, so registering the same path twice would shadow instead of dispatch; going through this sink keeps the two chains in one place.

type Host

type Host struct {
	// contains filtered or unexported fields
}

Host is the default Kernel implementation handed to Module.Init.

func NewHost

func NewHost(logger Logger) *Host

NewHost creates a Kernel host with a fresh bus and registry.

func (*Host) Logger

func (h *Host) Logger() Logger

Logger returns the shared logger.

func (*Host) Registry

func (h *Host) Registry() *Registry

Registry returns the module registry for capability discovery.

type Kernel

type Kernel interface {
	Logger() Logger
	Registry() *Registry
}

Kernel is the minimal host surface a module receives at Init.

type Logger

type Logger interface {
	Info(format string, args ...any)
	Error(format string, args ...any)
}

Logger is the printf-style logging contract modules use.

Core adapts *util.Logger to it; tests and fixtures may supply any sink. Messages use fmt-style verbs, matching the util.Logger convention.

type Migrator

type Migrator interface {
	Module
	Migrations() fs.FS
}

Migrator ships namespaced migrations as an embedded filesystem.

Layout convention: {sqlite,postgresql,mysql}/NNN_name.{up,down}.sql. The core migration runner selects the subdir via Driver.MigrationDir.

type Module

type Module interface {
	Name() string
	Version() string
	Requires() []string
	Optional() []string
	Init(kernel Kernel) error
	Shutdown() error
}

Module is the only interface every Lesstruct module must implement.

Name is the stable registry key ("users", "comments", "site-ssr"). Requires lists hard dependencies resolved topologically at startup; Optional lists soft dependencies the module degrades without. Init wires the module (routes, subscriptions, services); Shutdown releases it.

type PostTypeDef

type PostTypeDef struct {
	Slug      string
	Name      string
	Protected bool
}

PostTypeDef is the minimal post-type registration the kernel understands. Richer definitions (fields, templates) live in the posttypes module. Protected marks slugs reserved by built-in modules (post, page, media, comment): the kernel index records them so later phases can refuse overrides, and config entries may not hide them.

type Principal

type Principal struct {
	ID       string
	Username string
	Roles    []string
}

Principal is the minimal identity every auth module injects into requests.

The kernel owns this shape — never a concrete user type — so identity stays a module concern (users/auth) while route protection stays declarative.

func PrincipalFromContext

func PrincipalFromContext(ctx context.Context) (principal Principal, ok bool)

PrincipalFromContext reads the principal back. ok is false on anonymous requests, where no auth module ran.

func (Principal) HasRole

func (p Principal) HasRole(role string) bool

HasRole reports whether the principal carries the given role.

func (Principal) IsAnonymous

func (p Principal) IsAnonymous() bool

IsAnonymous reports whether no identity module populated the principal.

type PruneResult

type PruneResult struct {
	Kept    []Module
	Dropped []DroppedModule
}

PruneResult is the outcome of Prune: the modules to register plus every dropped module with its reason.

func Prune

func Prune(candidates []Module, disabled []string) PruneResult

Prune removes disabled modules and their transitive dependents from the candidate list. It is a pure function over Requires edges: no registry mutation, no I/O, deterministic output in candidate order.

A module named in disabled drops as Direct. Any other module whose Requires names a dropped or disabled module drops as a cascade, naming the unavailable requirement as Cause. Modules whose hard dependency is merely absent (not disabled) are KEPT: the registry still fails fast on those at InitAll, unchanged. Nil candidates are skipped.

type PublicRouteProvider

type PublicRouteProvider interface {
	Module
	RegisterPublicRoutes(router chi.Router)
}

PublicRouteProvider mounts HTTP routes onto the shared Chi router. Core passes the public router (no auth chain), so everything mounted here is anonymous. Prefer RouteProvider unless the endpoint is genuinely public.

The method is deliberately named differently from RouteProvider's so one module can serve both surfaces and core can discover each independently: a single RegisterRoutes method would satisfy both interfaces at once and mount the same routes twice.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry is the module graph: it stores modules, resolves their Requires edges into a deterministic init order, and runs lifecycle transitions. Register order never matters; InitAll always topologically sorts.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty module registry.

func (*Registry) Get

func (r *Registry) Get(name string) (Module, bool)

Get returns the module registered under name.

func (*Registry) InitAll

func (r *Registry) InitAll(kernel Kernel) error

InitAll resolves the dependency graph and calls Init on every module in topological order. A hard Requires edge to an unregistered module fails fast; an Optional edge to one is silently skipped. The first Init error aborts the transition and leaves Initialized false; already-initialized modules are NOT rolled back — the caller owns that (at startup the process exits, so there is nothing to roll back to). InitAll is a single-shot startup transition, not safe for concurrent use.

func (*Registry) InitOrder

func (r *Registry) InitOrder() []string

InitOrder returns the topological init order from the last InitAll, or nil when InitAll has not run.

func (*Registry) Initialized

func (r *Registry) Initialized() bool

Initialized reports whether InitAll completed successfully.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns every registered module name in sorted order.

func (*Registry) Register

func (r *Registry) Register(module Module) error

Register adds a module under its Name. Duplicate names are rejected.

func (*Registry) ShutdownAll

func (r *Registry) ShutdownAll() error

ShutdownAll calls Shutdown in reverse init order, collecting every error with errors.Join. Modules never initialized are skipped.

type RoleProvider

type RoleProvider interface {
	Module
	Capabilities() []string
}

RoleProvider contributes capability strings to the permission registry.

type RouteProvider

type RouteProvider interface {
	Module
	RegisterRoutes(router chi.Router)
}

RouteProvider mounts HTTP routes onto the shared Chi router. Core passes the protected router (auth middleware pre-chained), so everything mounted here requires authentication. For anonymous surfaces, implement PublicRouteProvider instead.

type ThemePageProvider added in v1.1.0

type ThemePageProvider interface {
	ThemePages() []string
}

ThemePageProvider is implemented by themes that ship standalone pages the site-ssr engine serves at fixed public paths. Keys are slash-separated paths without a leading slash ("cart", "orders/track"); each maps to the embedded page file named after the key with slashes replaced by hyphens ("cart.gohtml", "orders-track.gohtml"). The optional interface keeps existing themes source-compatible.

type ThemeProvider

type ThemeProvider interface {
	Module
	ThemeFiles() fs.FS
	ThemeFuncs() template.FuncMap
}

ThemeProvider registers a base theme consumed by the site-ssr engine: embedded layouts and CSS, template funcs, and site-root files.

Directories

Path Synopsis
Package capability defines the Published Language of authorization: the capability names every module checks and the users module resolves.
Package capability defines the Published Language of authorization: the capability names every module checks and the users module resolves.
Package conformance ships embeddable test suites that third-party module authors run against their kernel-contract implementations.
Package conformance ships embeddable test suites that third-party module authors run against their kernel-contract implementations.
Package httpx is the kernel's HTTP response envelope: the one wire format every module writes.
Package httpx is the kernel's HTTP response envelope: the one wire format every module writes.
Package legal carries the storefront's conventional legal-document vocabulary: which documents a compliant store publishes, how those documents resolve against the published page set in a given language, and the consent evidence recorded when a visitor affirms them.
Package legal carries the storefront's conventional legal-document vocabulary: which documents a compliant store publishes, how those documents resolve against the published page set in a given language, and the consent evidence recorded when a visitor affirms them.
Package pii is the shared application-level PII primitive: AES-256-GCM field encryption with deterministic HMAC blind indexes for exact-match lookups.
Package pii is the shared application-level PII primitive: AES-256-GCM field encryption with deterministic HMAC blind indexes for exact-match lookups.
Package posttype is the kernel's content-type discovery index.
Package posttype is the kernel's content-type discovery index.
Package storage defines the file-storage contract for media-like resources.
Package storage defines the file-storage contract for media-like resources.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL