Help us shape the future of Go! Take the 2026 Go Developer Survey

host

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 80 Imported by: 0

Documentation

Overview

Package host contains the reusable host-adapter v1 surface for embedding the goadmin subsystem into a Go backend.

The package intentionally keeps the public API narrow: callers map their own typed config into the exported input structs, provide their own feature registry implementation, and keep project-specific runtime dependencies outside this package.

Built-in admin auth, roles, seeders, first-admin setup tokens, and default repositories stay inside goadmin; host projects integrate them through the stable facade rather than wiring internal packages directly.

Index

Constants

View Source
const (
	PermissionDomainAccountRecovery   PermissionDomain = "account_recovery"
	AssistedRecoveryAdminPath         string           = "/account-recovery"
	AssistedRecoveryCompletePath      string           = "/auth/assisted-recovery"
	AssistedRecoveryOwnerCompletePath string           = "/auth/assisted-recovery/owner"
)
View Source
const (
	ClientBundleFormatVersion = 1
	ClientExtensionAPIVersion = 1
	ClientBundleManifestPath  = "dist/admin-extensions.manifest.json"
)
View Source
const (
	PermissionDomainRoles       = integrationroles.PermissionDomainRoles
	PermissionDomainPermissions = integrationroles.PermissionDomainPermissions
	PermissionDomainAdmins      = integrationroles.PermissionDomainAdmins
	PermissionDomainDashboard   = integrationroles.PermissionDomainDashboard
	PermissionDomainOperations  = integrationroles.PermissionDomainOperations
	PermissionDomainUsers       = integrationroles.PermissionDomainUsers
	PermissionDomainUploads     = integrationroles.PermissionDomainUploads
	PermissionDomainQueues      = integrationroles.PermissionDomainQueues
)
View Source
const (
	PermissionActionRead   = integrationroles.PermissionActionRead
	PermissionActionCreate = integrationroles.PermissionActionCreate
	PermissionActionUpdate = integrationroles.PermissionActionUpdate
	PermissionActionDelete = integrationroles.PermissionActionDelete
	PermissionActionAssign = integrationroles.PermissionActionAssign
	PermissionActionSync   = integrationroles.PermissionActionSync
)
View Source
const (
	DefaultPublicRoot     = "publicstaticdata"
	DefaultStaticDataRoot = "publicdata"
	DefaultViewsRoot      = "views"
	DefaultHotFileName    = "hot"
	DefaultAuthSleep      = 300 * time.Millisecond
)
View Source
const (
	EnvAppAdminDomain                  = "APP_ADMIN_DOMAIN"
	EnvAppAdminDomainURL               = "APP_ADMIN_DOMAIN_URL"
	EnvAppAdminCSRFTokenName           = "APP_ADMIN_CSRF_TOKEN_NAME" //nolint:gosec // env var name, not a secret
	EnvAppAdminCSRFTokenTTL            = "APP_ADMIN_CSRF_TOKEN_TTL"  //nolint:gosec // env var name, not a secret
	EnvAppAdminSessionInactiveTTL      = "APP_ADMIN_SESSION_INACTIVE_TTL"
	EnvAppAdminSessionTTL              = "APP_ADMIN_SESSION_TTL"
	EnvAppAdminSessionName             = "APP_ADMIN_SESSION_NAME"
	EnvAppAdminCanonicalSessionBackend = "APP_ADMIN_CANONICAL_SESSION_BACKEND"
	EnvServerAdminAddr                 = "SERVER_ADMIN_ADDR"
	EnvServerAdminBasicAuth            = "SERVER_ADMIN_BASIC_AUTH"
	EnvGoAdminPublicRoot               = "GO_ADMIN_PUBLIC_ROOT"
	EnvGoAdminHotFile                  = "GO_ADMIN_HOT_FILE"
	EnvGoAdminViewsRoot                = "GO_ADMIN_VIEWS_ROOT"
	EnvViteAdminExtRoot                = "VITE_ADMIN_EXT_ROOT"
	EnvViteAdminExtensionManifests     = "VITE_ADMIN_EXTENSION_MANIFESTS"
	EnvViteAdminCSRFCookieName         = "VITE_ADMIN_CSRF_COOKIE_NAME"
	EnvViteAdminPublicRoot             = "VITE_ADMIN_PUBLIC_ROOT"
	EnvViteAdminTSConfigPath           = "VITE_ADMIN_TSCONFIG_PATH"
)
View Source
const FirstAdminSetupTokenKey = "setup_token"

Variables

View Source
var ErrExternalRecoveryRequired = adminservice.ErrExternalRecoveryRequired
View Source
var ErrInvalidClientBundle = errors.New("goadmin client bundle is incompatible")
View Source
var ErrPreviewBindingConflict = uploadintegration.ErrPreviewBindingConflict
View Source
var ErrSubjectPermissionDenied = errors.New("goadmin subject permission denied")

Functions

func BindPostgresPreview

func BindPostgresPreview(ctx context.Context, db StoragePgsqlClient, request PreviewBinding) error

BindPostgresPreview is the supported narrow SQL adapter for host file stores. Call it from BindPreview; it requires the managed command transaction context.

func BuildEnvNames

func BuildEnvNames() []string

BuildEnvNames returns the admin asset-build env contract for the host.

func CSRFSessionBinding added in v0.10.0

func CSRFSessionBinding(cookie string) string

CSRFSessionBinding uses the same opaque browser binding as core admin CSRF.

func Command

func Command[T any](app *App, key PermissionKey, handle func(fiber.Ctx, Actor, T) error) []fiber.Handler

Command binds a typed body after current RBAC authorization and supplies only the canonical actor. Capture business services in the handler's constructor.

func CorePublicFS

func CorePublicFS() fs.ReadFileFS

CorePublicFS returns the embedded reusable goadmin public assets.

func CoreTemplateFS

func CoreTemplateFS() fs.FS

CoreTemplateFS returns the embedded reusable goadmin templates.

func CreateSessionStore

func CreateSessionStore(rdb redis.ClientContract, cfg AdminConfig) (fiber.Handler, *session.Store)

CreateSessionStore exposes the built-in admin session storage wiring behind the stable host package.

func EnableExternalAdminRecovery added in v0.12.0

func EnableExternalAdminRecovery(c fiber.Ctx)

EnableExternalAdminRecovery opts this request into the recovery response marker. Call only from middleware of a host that registered the guarded recovery endpoint; never derive this opt-in from a browser request header.

func IsFinalizedUpload

func IsFinalizedUpload(file File) bool

IsFinalizedUpload reports whether a recorded artifact is ready for admin delivery.

func IsLocalEnv

func IsLocalEnv(env string) bool

IsLocalEnv reports whether the host should behave like a local/dev runtime.

func NewAdminSeed

func NewAdminSeed(
	auth *AuthAdapter,
	accounts ...AdminSeedAccount,
) *adminseed.Seed

NewAdminSeed exposes the built-in admin seed through the stable host package.

func NewLocalAssistedRecovery added in v0.13.0

func NewLocalAssistedRecovery(adapter *AuthAdapter, origin string) (*goauth.AssistedRecovery, error)

func NewRolesSeed

NewRolesSeed exposes the built-in roles seed through the stable host package.

func NewUploadEventPublisher

func NewUploadEventPublisher(stream EventStream) uploadhost.EventPublisher

NewUploadEventPublisher bridges standalone upload notifications to the admin stream.

func RuntimeEnvNames

func RuntimeEnvNames() []string

RuntimeEnvNames returns the backend/admin runtime env contract for the host.

func ValidateClientBundle

func ValidateClientBundle(
	requirements []ClientExtensionRequirement,
	manifest ClientBundleManifest,
) error

ValidateClientBundle rejects missing, duplicate, incompatible, or drifted extensions.

func ValidateClientBundleForRegistry

func ValidateClientBundleForRegistry(registry Registry, manifest ClientBundleManifest) error

ValidateClientBundleForRegistry validates all structured feature requirements.

func WithBreadcrumbs

func WithBreadcrumbs(c fiber.Ctx, app *App, extra Menu, crumbs []Breadcrumb)

WithBreadcrumbs overrides breadcrumbs for the current request and filters links against the current admin's allowed menu routes.

Types

type Actor

type Actor struct {
	AdminID   int64  `json:"adminId"`
	SubjectID string `json:"subjectId"`
}

Actor is the narrow authenticated-admin identity exposed to host features. It intentionally carries no permissions; features must authorize actions through the runtime permission guard instead of trusting session claims.

func (Actor) IsZero

func (a Actor) IsZero() bool

IsZero reports whether the actor lacks its canonical admin identity.

type AdminConfig

type AdminConfig = goadminconfig.Config

func BuildConfig

func BuildConfig(input AdminConfigInput, defaults PathDefaults) AdminConfig

BuildConfig resolves host defaults into the goadmin runtime config.

type AdminConfigInput

type AdminConfigInput struct {
	Env                     string
	BaseDomain              string
	BaseDomainURL           string
	Domain                  string
	DomainURL               string
	Addr                    string
	BasicAuth               []string
	CSRFTokenName           string
	CSRFTokenTTL            time.Duration
	SessionInactiveTTL      time.Duration
	SessionTTL              time.Duration
	SessionName             string
	CanonicalSessionBackend string
	PublicRoot              string
	StaticDataRoot          string
	HotFile                 string
	ViewsRoot               string
}

AdminConfigInput is the host-owned input mapped into goadmin config.

type AdminSeedAccount

type AdminSeedAccount = adminseed.Account

type AdminUUID

type AdminUUID = identity.UserID

type AfterProcessFunc

type AfterProcessFunc = uploadhost.AfterProcessFunc

type AfterProcessHandler

type AfterProcessHandler interface {
	HandleAfterProcess(ctx context.Context, payload string, fnCall AfterProcessFunc) error
}

AfterProcessHandler handles upload after-process payloads for built-in admin jobs.

type AfterProcessPayload

type AfterProcessPayload = uploadhost.AfterProcessPayload

type AfterProcessService

type AfterProcessService = uploadhost.AfterProcessService

type App

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

App wraps the internal admin runtime so host-mounted features do not import unstable adminapp packages.

func WrapApp

func WrapApp(app *adminapp.App) *App

WrapApp exposes the stable host-facing app wrapper for extension builders.

func (*App) AdminCSRFRequest added in v0.10.0

func (a *App) AdminCSRFRequest(c fiber.Ctx) (CSRFRequest, error)

AdminCSRFRequest returns the current canonical admin browser binding for a host-owned form. It performs native authentication; metadata alone is not proof.

func (*App) BeginExternalAdminRecovery added in v0.12.0

func (a *App) BeginExternalAdminRecovery(c fiber.Ctx) (*ExternalAdminRecovery, error)

BeginExternalAdminRecovery captures an opaque native fence before SDK Verify. It is never an authentication result. Hosts must guard the dedicated endpoint against cross-origin requests and must not expose the snapshot to the browser.

func (*App) CompleteExternalAdminRecovery added in v0.12.0

func (a *App) CompleteExternalAdminRecovery(c fiber.Ctx, recovery *ExternalAdminRecovery, fresh ExternalBinding) error

CompleteExternalAdminRecovery replaces verified provider evidence in place. It never creates a canonical login, rotates the cookie or extends the signed absolute lifetime. Obtain AdminCSRFRequest afterwards before reporting success.

func (*App) ComposeFileURL

func (a *App) ComposeFileURL(raw string) string

ComposeFileURL composes a file URL using the admin runtime's configured file URL rules.

func (*App) ComposeFileURLFallback

func (a *App) ComposeFileURLFallback(primary, fallback string) string

ComposeFileURLFallback composes a file URL with a fallback path.

func (*App) CurrentActor

func (a *App) CurrentActor(ctx context.Context) (Actor, bool)

CurrentActor returns the canonical actor for the current admin request. It is safe on unauthenticated contexts and never panics.

func (*App) CurrentLocalAuth added in v0.13.0

func (a *App) CurrentLocalAuth(c fiber.Ctx) (goauth.AuthContext, error)

func (*App) DetachAdmin added in v0.10.0

func (a *App) DetachAdmin(c fiber.Ctx) error

DetachAdmin clears canonical native authority without provider logout. Hosts use it after successful RP-cookie logout or failed admission cleanup.

func (*App) ExternalAdminBinding added in v0.10.0

func (a *App) ExternalAdminBinding(c fiber.Ctx) (*ExternalBinding, error)

ExternalAdminBinding reads only protected server metadata; it grants no access.

func (*App) Guard

func (a *App) Guard(domain PermissionDomain, action PermissionAction) fiber.Handler

Guard returns a permission-guarded middleware for the provided action.

func (*App) LinkExternalAdminIdentity added in v0.10.0

func (a *App) LinkExternalAdminIdentity(c fiber.Ctx, binding ExternalBinding) (goauth.IdentityLink, error)

LinkExternalAdminIdentity explicitly enrolls a verified external identity through the current fresh canonical admin session. Host routes own CSRF and explicit confirmation. No email auto-link or admin provisioning occurs.

func (*App) Logger

func (a *App) Logger() logger.Logger

Logger returns the app logger.

func (*App) LoginExternalAdmin added in v0.10.0

func (a *App) LoginExternalAdmin(c fiber.Ctx, binding ExternalBinding) (string, error)

LoginExternalAdmin creates a canonical admin browser session only for an existing confirmed canonical identity link and current local membership. The opaque return value is server-only, not a page prop or bearer API token.

func (*App) LogoutAdmin added in v0.10.0

func (a *App) LogoutAdmin(c fiber.Ctx) error

LogoutAdmin is explicit user intent. Host routes MUST enforce authentication, CSRF and origin BEFORE calling this; it must precede provider Verify/Check.

func (*App) Outbox

func (a *App) Outbox() OutboxPutter

Outbox returns the outbox putter used by the admin runtime.

func (*App) PermissionDefinitions

func (a *App) PermissionDefinitions() []PermissionDefinition

PermissionDefinitions returns the current runtime permission catalog.

func (*App) PersistFlash added in v0.11.0

func (a *App) PersistFlash(c fiber.Ctx) error

PersistFlash saves only Inertia's redirect-surviving flash values. Public extension routes that finish before the core Inertia middleware must call it after setting flash and before redirecting. Ordinary protected routes already persist through the middleware and do not need this method. The native session bridge follows a newly issued authentication cookie.

func (*App) Redirect

func (a *App) Redirect(c fiber.Ctx, url string) error

Redirect performs an Inertia redirect.

func (*App) RedirectBack

func (a *App) RedirectBack(c fiber.Ctx) error

RedirectBack redirects to the previous location.

func (*App) RedirectBackWithValidationErrors

func (a *App) RedirectBackWithValidationErrors(c fiber.Ctx, errors goinertia.ValidationErrors) error

RedirectBackWithValidationErrors redirects back and persists validation errors.

func (*App) Render

func (a *App) Render(c fiber.Ctx, page string, props map[string]any) error

Render renders an Inertia page.

func (*App) TxManager

func (a *App) TxManager() outbox.StoragePgsqlTxManager

TxManager returns the transaction manager used by the admin runtime.

func (*App) Unwrap

func (a *App) Unwrap() *adminapp.App

Unwrap returns the internal admin app for goadmin-owned internals only.

func (*App) WithFlashError

func (a *App) WithFlashError(c fiber.Ctx, message string)

WithFlashError stores an error flash message.

func (*App) WithFlashInfo

func (a *App) WithFlashInfo(c fiber.Ctx, message string)

WithFlashInfo stores an info flash message.

func (*App) WithFlashOld

func (a *App) WithFlashOld(c fiber.Ctx, data map[string]any)

WithFlashOld stores old form data for the next request.

func (*App) WithFlashSuccess

func (a *App) WithFlashSuccess(c fiber.Ctx, message string)

WithFlashSuccess stores a success flash message.

func (*App) WithFlashWarning

func (a *App) WithFlashWarning(c fiber.Ctx, message string)

WithFlashWarning stores a warning flash message.

func (*App) WithProp

func (a *App) WithProp(c fiber.Ctx, key string, value any)

WithProp stores a shared prop for the current request.

func (*App) WithValidationErrors

func (a *App) WithValidationErrors(c fiber.Ctx, errors goinertia.ValidationErrors)

WithValidationErrors exposes validation errors for the current request.

type AssistedRecoveryAuthorization added in v0.13.0

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

func NewAssistedRecoveryAuthorization added in v0.13.0

func NewAssistedRecoveryAuthorization(adapter *AuthAdapter) (*AssistedRecoveryAuthorization, error)

func (*AssistedRecoveryAuthorization) AuthorizeAssistedRecovery added in v0.13.0

func (p *AssistedRecoveryAuthorization) AuthorizeAssistedRecovery(
	ctx context.Context, actor goauth.AuthContext, target goauth.SubjectID, reason, evidence string,
) error

AuthorizeAssistedRecovery rechecks the exact dedicated grant on the managed auth handle, independently of any super-admin bypass at the UI route. Identity evidence is an operator attestation recorded in the mandatory security audit.

func (*AssistedRecoveryAuthorization) AuthorizeOwnerAssistedRecovery added in v0.13.0

func (p *AssistedRecoveryAuthorization) AuthorizeOwnerAssistedRecovery(ctx context.Context, subject goauth.SubjectID) error

AuthorizeOwnerAssistedRecovery is deliberately absent from all HTTP commands. Locking membership/role populations prevents a concurrent second owner from appearing between the sole-owner check and invitation issuance. Subject-table locking also fences activation of an already assigned but disabled owner.

type AssistedRecoveryCommands added in v0.13.0

type AssistedRecoveryCommands interface {
	Initiate(ctx context.Context, request goauth.AssistedRecoveryRequest) error
	Complete(ctx context.Context, request goauth.AssistedRecoveryCompletion) error
}

type AssistedRecoveryConfig added in v0.13.0

type AssistedRecoveryConfig struct {
	Commands      AssistedRecoveryCommands
	OwnerCommands AssistedRecoveryCommands
	Origin        string
}

type AuthAdapter

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

AuthAdapter owns goadmin's supported integration with goauth v0.2. Hosts do not construct concrete auth repositories or import goadmin implementation packages.

func NewAuthAdapter

func NewAuthAdapter(config AuthAdapterConfig) (*AuthAdapter, error)

func (*AuthAdapter) Close

func (a *AuthAdapter) Close() error

func (*AuthAdapter) Runtime

func (a *AuthAdapter) Runtime() *postgres.Runtime

Runtime exposes the supported PostgreSQL goauth adapter for custom host wiring such as OIDC and user-realm endpoints.

type AuthAdapterConfig

type AuthAdapterConfig struct {
	Database           StoragePgsqlClient
	TxManager          StoragePgsqlTxManager
	Runtime            goauth.Config
	AutoMigrate        bool
	NotificationSender goauth.NotificationSender
	NotificationWorker postgres.NotificationWorkerConfig
}

AuthAdapterConfig is the single host-facing DI contract for goauth Runtime, admin memberships, and RBAC.

type AuthMailConfig

type AuthMailConfig struct {
	PasswordRecovery []PasswordRecoveryRoutes
	Sender           goauth.NotificationSender
	Worker           postgres.NotificationWorkerConfig
	// BorrowedWorker means the host already supervises this Runtime's delivery.
	BorrowedWorker bool
}

type Badge

type Badge = menu.Badge

type BatchRequest

type BatchRequest = uploadhost.BatchRequest

type BootstrapConfig

type BootstrapConfig = bootstrap.Config

func BuildBootstrapConfig

func BuildBootstrapConfig(input BootstrapConfigInput) BootstrapConfig

BuildBootstrapConfig derives the reusable bootstrap.Config from host inputs.

type BootstrapConfigInput

type BootstrapConfigInput struct {
	Admin        AdminConfigInput
	PathDefaults PathDefaults
	Server       ServerConfigInput
}

BootstrapConfigInput combines admin and server settings for bootstrap.Config.

type BootstrapOptionsInput

type BootstrapOptionsInput struct {
	Env        string
	Registry   FeatureRegistry
	TemplateFS fs.FS
	PublicFS   fs.ReadFileFS
	AuthSleep  time.Duration
}

BootstrapOptionsInput maps host assets and registry wiring into bootstrap options.

type BootstrapOptionsPlan

type BootstrapOptionsPlan struct {
	AuthSleep             time.Duration
	Menu                  Menu
	PermissionDefinitions []PermissionDefinition
	TemplateFS            fs.FS
	PublicFS              fs.ReadFileFS
	IncludePublicFS       bool
	ExtensionBuilders     []ExtensionBuilder
}

BootstrapOptionsPlan is an inspectable representation of bootstrap options.

func BuildBootstrapOptionsPlan

func BuildBootstrapOptionsPlan(input BootstrapOptionsInput) BootstrapOptionsPlan

BuildBootstrapOptionsPlan resolves registry/assets into an inspectable plan.

func (BootstrapOptionsPlan) Options

func (p BootstrapOptionsPlan) Options() []Option

Options converts the plan into goadmin bootstrap options.

type Breadcrumb struct {
	Name string `json:"name"`
	Href string `json:"href,omitempty"`
}

Breadcrumb represents one item in the breadcrumb trail.

type CSRFClaims

type CSRFClaims = csrfservice.Claims

type CSRFConfig

type CSRFConfig struct {
	AppDomain      string
	SecretKey      string
	AllowedOrigins []string
	TokenTTL       time.Duration
}

CSRFConfig contains the stable CSRF settings needed by the embedded admin.

type CSRFRequest

type CSRFRequest = csrfservice.Request

type CSRFService

type CSRFService = csrfservice.Service

func NewCSRFService

func NewCSRFService(cfg CSRFConfig, lg Logger) (*CSRFService, error)

NewCSRFService creates the CSRF service used by the embedded admin runtime.

type CSRFToken

type CSRFToken = csrfservice.Token

type ClientBundleExtension

type ClientBundleExtension struct {
	Key         string   `json:"key"`
	APIVersion  int      `json:"apiVersion"`
	Fingerprint string   `json:"fingerprint"`
	Requires    []string `json:"requires,omitempty"`
}

ClientBundleExtension is one build-time extension recorded in the emitted bundle manifest.

type ClientBundleManifest

type ClientBundleManifest struct {
	FormatVersion int                     `json:"formatVersion"`
	Extensions    []ClientBundleExtension `json:"extensions"`
}

ClientBundleManifest is the runtime-verifiable output of the admin UI builder.

func LoadClientBundleManifest

func LoadClientBundleManifest(publicFS fs.FS) (ClientBundleManifest, error)

LoadClientBundleManifest reads and validates the standard embedded manifest path.

type ClientBundleValidation

type ClientBundleValidation struct {
	Requirements []ClientExtensionRequirement
	Manifest     ClientBundleManifest
}

ClientBundleValidation connects host/server requirements to a built client manifest.

func BuildClientBundleValidation

func BuildClientBundleValidation(
	registry Registry,
	publicFS fs.FS,
) (*ClientBundleValidation, error)

BuildClientBundleValidation binds a feature registry to an embedded build manifest and checks that the client files required by the built-in templates are present. New runs this check against Config.Public so assembly fails before boot when a required server/client extension pair has drifted.

type ClientError

type ClientError = uploadhost.ClientError

type ClientExtensionRequirement

type ClientExtensionRequirement struct {
	Key         string `json:"key"`
	APIVersion  int    `json:"apiVersion"`
	Fingerprint string `json:"fingerprint"`
}

ClientExtensionRequirement is the server feature fingerprint that must be present in the built admin UI bundle.

type Config

type Config struct {
	Admin                AdminConfig
	Server               ServerConfig
	Auth                 goauth.Config
	CSRF                 CSRFConfig
	FirstAdminSetupToken FirstAdminSetupToken
	Templates            fs.FS
	Public               fs.ReadFileFS
	Options              []Option
}

Config describes the core. Optional infrastructure is configured by modules.

type DeleteRequest

type DeleteRequest = uploadhost.DeleteRequest

type Dependencies

type Dependencies struct {
	ExternalAuthority   ExternalSessionAuthority
	LocalAdminAdmission LocalAdminAdmission
	Database            StoragePgsqlClient
	TxManager           StoragePgsqlTxManager
	Logger              Logger
	Auth                *AuthAdapter
	Sessions            *SessionStore
	SessionRedis        RedisClient
	CSRF                *CSRFService
	LoginAudit          LoginAuditWriter
	SubjectPermissions  *SubjectPermissionChecker
}

Dependencies are borrowed. New creates admin-owned adapter/session wrappers when Auth/Sessions are omitted; it never closes the host PostgreSQL/Redis pool.

type EventStream

type EventStream = eventstream.EventStream

type Extension

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

Extension is a small reusable bootstrap extension implementation for host features.

func NewExtension

func NewExtension() *Extension

NewExtension creates an empty reusable extension.

func (*Extension) Handlers

func (e *Extension) Handlers() []server.Handler

Handlers returns the extension handlers.

func (*Extension) Middlewares added in v0.10.0

func (e *Extension) Middlewares() []fiber.Handler

func (*Extension) Register

func (e *Extension) Register(app *fiber.App)

Register mounts direct Fiber callbacks.

func (*Extension) RegisterPublic

func (e *Extension) RegisterPublic(app *fiber.App)

RegisterPublic mounts callbacks before the admin authentication middleware.

func (*Extension) WithHandlers

func (e *Extension) WithHandlers(handlers ...server.Handler) *Extension

WithHandlers appends HTTP handlers that should be mounted into the admin server.

func (*Extension) WithMiddlewares added in v0.10.0

func (e *Extension) WithMiddlewares(handlers ...fiber.Handler) *Extension

WithMiddlewares adds host boundaries before every core/static/public route.

func (*Extension) WithPublicRegister

func (e *Extension) WithPublicRegister(registered ...func(*fiber.App)) *Extension

WithPublicRegister appends host-owned routes that must remain outside the embedded admin authentication middleware.

func (*Extension) WithRegister

func (e *Extension) WithRegister(registered ...func(*fiber.App)) *Extension

WithRegister appends raw Fiber registration callbacks.

type ExtensionBuilder

type ExtensionBuilder func(app *App) (*Extension, error)

ExtensionBuilder builds a feature extension against the stable host app wrapper.

type ExternalAdminRecovery added in v0.12.0

type ExternalAdminRecovery = adminservice.ExternalAdminRecovery

type ExternalBinding added in v0.10.0

type ExternalBinding = adminservice.ExternalBinding

type ExternalProof added in v0.10.0

type ExternalProof = adminservice.ExternalProof

type ExternalSessionAuthority added in v0.10.0

type ExternalSessionAuthority = adminservice.ExternalSessionAuthority

type Feature

type Feature interface {
	Descriptor() FeatureDescriptor
	Build(siteMenu Menu) ExtensionBuilder
}

Feature represents a host-mounted admin plugin that contributes menu and routes.

type FeatureDescriptor

type FeatureDescriptor struct {
	Key                   string
	Menu                  Menu
	Permissions           []PermissionKey
	PermissionDefinitions []PermissionDefinition
	ClientExtensions      []string
	ClientRequirements    []ClientExtensionRequirement
	Rebuild               RebuildBehavior
}

FeatureDescriptor is the stable host-facing contract for project admin features.

type FeatureRegistry

type FeatureRegistry interface {
	Menu() Menu
	PermissionDefinitions() []PermissionDefinition
	ExtensionBuilders(siteMenu Menu) []ExtensionBuilder
}

FeatureRegistry is the narrow host-facing registry contract consumed here.

type File

type File = uploadhost.File

type FileData

type FileData = uploadhost.FileData

type FileEventAfterJob

type FileEventAfterJob = uploadhost.FileEventAfterJob

type FileLoader

type FileLoader interface {
	LoadPreview(ctx context.Context, fileID int64) (*uploadhost.File, error)
	LoadPreviewURL(ctx context.Context, fileID int64) (string, error)
}

FileLoader resolves file previews for built-in admin screens.

type FileRepo

type FileRepo = uploadhost.FileRepo

type FileRepository

type FileRepository interface {
	GetByID(ctx context.Context, id int64) (uploadhost.File, error)
	Update(ctx context.Context, id int64, file uploadhost.File) error
	List(ctx context.Context, filters uploadhost.ListFilters) ([]uploadhost.File, int, error)
}

FileRepository is the host-supplied files storage contract used by built-in admin screens.

func NewPostgresFileRepository

func NewPostgresFileRepository(repo FileRepository, db StoragePgsqlClient) (FileRepository, error)

NewPostgresFileRepository adds indexed delivery and transactional preview binding to a host's existing file store. Both use the core PostgreSQL pool.

type FileUploadConfig

type FileUploadConfig = uploadhost.FileUploadConfig

type FirstAdminSetupToken

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

FirstAdminSetupToken is an opaque host configuration value for the static first-admin bootstrap token. It retains only a SHA-256 hash of the raw token.

func NewFirstAdminSetupToken

func NewFirstAdminSetupToken(raw string) (FirstAdminSetupToken, error)

NewFirstAdminSetupToken validates and hashes a host-supplied bootstrap token. An empty value disables static first-admin bootstrap.

type FirstAdminSetupTokenConfig

type FirstAdminSetupTokenConfig struct {
	SetupURL     string
	TTL          time.Duration
	SecretOutput *os.File
}

type FirstAdminSetupTokenResult

type FirstAdminSetupTokenResult struct {
	SetupURL string
}

func IssueFirstAdminSetupToken

IssueFirstAdminSetupToken creates a short-lived one-time token and writes the secret only to a prevalidated operator-controlled output channel.

type InMemoryEventStream

type InMemoryEventStream = inmemeventstream.Service

InMemoryEventStream is the default in-process event stream implementation for starter hosts.

func NewEventStream

func NewEventStream() *InMemoryEventStream

NewEventStream creates the default in-memory event stream.

type Item

type Item = menu.Item

type Job

type Job = outbox.Job

type JobsConfig

type JobsConfig struct {
	Borrowed Outbox
	Owned    OutboxRuntime
	Worker   OutboxConfig
}

JobsConfig either borrows an already supervised host queue or creates an admin-owned queue. Borrowed workers are never started, drained or closed here.

type ListFilters

type ListFilters = uploadhost.ListFilters

type LocalAdminAdmission added in v0.10.0

type LocalAdminAdmission = adminservice.LocalAdminAdmission

type LocalUploadsConfig

type LocalUploadsConfig struct {
	Root    string
	BaseURL string
}

LocalUploadsConfig contains local-disk upload settings for a clean admin host.

type LocalUploadsRuntime

type LocalUploadsRuntime struct {
	Repositories Repositories
	Uploads      Uploads
	Storage      uploadhost.Storage
	Jobs         []outbox.Job
}

LocalUploadsRuntime groups dependencies and jobs required by the admin host. Register Jobs before starting the host-owned outbox worker.

func NewLocalUploads

NewLocalUploads builds the original-only async upload runtime. It owns no workers.

type Logger

type Logger = logger.Logger

func DiscardLogger

func DiscardLogger() Logger

DiscardLogger returns a logger that drops all output.

type LoginAuditRecord

type LoginAuditRecord = adminloginaudit.Record

type LoginAuditWriter

type LoginAuditWriter = adminloginaudit.Writer
type Menu = menu.Menu

type Module

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

Module is an immutable assembly contribution. Product dependencies belong in a Feature constructor; only the narrow App facade is passed to its builder.

func AccessModule

func AccessModule() Module

func AssistedRecoveryModule added in v0.13.0

func AssistedRecoveryModule(cfg AssistedRecoveryConfig) Module

AssistedRecoveryModule is explicit opt-in. It neither grants its dedicated permission nor substitutes the ordinary user/admin update permission.

func AuthMailModule

func AuthMailModule(cfg AuthMailConfig) Module

func DefinedFeatureModule

func DefinedFeatureModule(d ModuleDescriptor, feature Feature) Module

DefinedFeatureModule also declares route ownership for preflight conflict checks.

func FeatureModule

func FeatureModule(feature Feature, requires ...string) Module

FeatureModule mounts a host feature and declares its module dependencies.

func JobsModule

func JobsModule(cfg JobsConfig) Module

func NotificationsModule

func NotificationsModule(manager NotificationManager) Module

func QueuesModule

func QueuesModule() Module

func RealtimeModule

func RealtimeModule(stream EventStream) Module

RealtimeModule borrows a supplied stream. A nil stream creates one owned by each runtime, which shuts it down after its WebSocket handler.

func UploadsModule

func UploadsModule(cfg UploadsConfig) Module

func (Module) Descriptor

func (m Module) Descriptor() ModuleDescriptor

type ModuleDescriptor

type ModuleDescriptor struct {
	Key      string
	Requires []string
	// Routes includes a method and a Fiber path, for example "GET /reports/:id".
	// Parameter and wildcard overlaps are rejected conservatively.
	Routes []string
	// RouteNamespaces reserves a literal path and all descendants, for every method.
	RouteNamespaces []string
}

ModuleDescriptor declares dependencies and HTTP ownership relative to the admin mount.

type NotificationConfig

type NotificationConfig = notifyhub.Config

type NotificationManager

type NotificationManager = notify.NotificationManager

func NewNotificationManager

func NewNotificationManager(cfg NotificationConfig) (NotificationManager, error)

NewNotificationManager validates and creates a NotifyHub transport without sending requests. The host owns any HTTP client supplied through cfg.

type ObjectID

type ObjectID = uploadhost.ObjectID

type ObjectType

type ObjectType = uploadhost.ObjectType

type Option

type Option = bootstrap.Option

func BuildBootstrapOptions

func BuildBootstrapOptions(input BootstrapOptionsInput) []Option

BuildBootstrapOptions converts the resolved plan into bootstrap options.

func WithUploadTransport

func WithUploadTransport(transport UploadTransport) Option

WithUploadTransport mounts a narrow permission-guarded TUS surface on the embedded admin server. The transport may use its own resumable-upload store.

type Outbox

type Outbox interface {
	OutboxPutter
	RegisterJob(job outbox.Job) error
	MustRegisterJob(job outbox.Job)
}

Outbox combines enqueueing and job registration for built-in admin jobs.

func NewOutbox

NewOutbox creates the built-in admin outbox service.

type OutboxConfig

type OutboxConfig struct {
	Workers    int
	IdleTime   time.Duration
	ReserveFor time.Duration
}

OutboxConfig contains queue worker settings for built-in admin jobs.

type OutboxPutter

type OutboxPutter interface {
	Put(ctx context.Context, name, payload string, availableAt time.Time) (outbox.JobID, error)
}

OutboxPutter is the host-facing contract for enqueueing admin side effects.

type OutboxRuntime

type OutboxRuntime interface {
	Outbox
	Run(ctx context.Context) error
	Readiness(ctx context.Context) error
	BeginDrain()
}

OutboxRuntime adds worker lifecycle control to the enqueue and registration facade. The host must run the worker and include Readiness in its process health check.

func NewOutboxRuntime

NewOutboxRuntime creates the built-in admin outbox with its worker lifecycle.

type PasswordRecoveryRoutes added in v0.11.0

type PasswordRecoveryRoutes = authrecovery.Routes

type PathDefaults

type PathDefaults struct {
	PublicRoot     string
	StaticDataRoot string
	ViewsRoot      string
}

PathDefaults declares the filesystem defaults for a concrete host project.

type PermissionAction

type PermissionAction = integrationroles.PermissionAction

type PermissionDefinition

type PermissionDefinition = integrationroles.PermissionDefinition

func CorePermissionDefinitions

func CorePermissionDefinitions() []PermissionDefinition

CorePermissionDefinitions returns the built-in reusable admin permission catalog.

func NewPermissionDefinition

func NewPermissionDefinition(key PermissionKey, description string) PermissionDefinition

NewPermissionDefinition creates a host-facing permission definition.

type PermissionDomain

type PermissionDomain = integrationroles.PermissionDomain

type PermissionGuard

type PermissionGuard interface {
	AdminGuard(key PermissionKey, opts ...integrationroles.PermissionGuardOption) fiber.Handler
}

PermissionGuard is the host-facing permission guard contract used by custom features.

type PermissionKey

type PermissionKey = integrationroles.PermissionKey

func NewPermissionKey

func NewPermissionKey(domain PermissionDomain, action PermissionAction) PermissionKey

NewPermissionKey creates a host-facing permission key without importing internal shared packages.

type PgSessionRuntime

type PgSessionRuntime struct {
	Middleware fiber.Handler
	Store      *session.Store
	// contains filtered or unexported fields
}

PgSessionRuntime owns browser-session maintenance, borrowing the host database.

func NewPostgresSessions

func NewPostgresSessions(cfg AdminConfig, db *sql.DB) (*PgSessionRuntime, error)

NewPostgresSessions creates the admin browser session store without starting workers or opening connections. Migrate the database before using the store.

func (*PgSessionRuntime) Run

func (r *PgSessionRuntime) Run(ctx context.Context) error

Run performs periodic bounded expiry cleanup until the host cancels ctx. The caller owns the worker goroutine and must wait for Run before shutdown.

type PgsqlConfig

type PgsqlConfig struct {
	DSN      string
	Address  string
	Username string
	Password string
	Database string
	SSLMode  string
	Env      string
}

PgsqlConfig contains the minimal PostgreSQL settings needed by a clean host.

type PreviewBinding

type PreviewBinding = uploadintegration.PreviewBinding

type ReaderRequest

type ReaderRequest = uploadhost.ReaderRequest

type ReaderUploadInput

type ReaderUploadInput = uploadhost.ReaderUploadInput

type RebuildBehavior

type RebuildBehavior struct {
	PublicContent            bool
	TriggersRoutesRegenerate bool
	TriggersFrontendDirty    bool
}

RebuildBehavior documents how a feature affects public-site rebuild flows.

type RedisClient

type RedisClient = redis.ClientContract

func NewRedisClient

func NewRedisClient(ctx context.Context, cfg RedisConfig) (RedisClient, error)

NewRedisClient creates the Redis client used by admin sessions.

type RedisConfig

type RedisConfig struct {
	DSN          string
	Addrs        []string
	ClientName   string
	ConnTimeout  time.Duration
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	Database     int
	PoolSize     int
	Username     string
	Password     string
	DisableCheck bool
}

RedisConfig contains the minimal Redis settings needed by a clean host.

type Registry

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

Registry keeps host features together and exposes a stable integration surface.

func NewRegistry

func NewRegistry(features ...Feature) Registry

NewRegistry creates a host-facing feature registry.

func (Registry) ClientExtensionRequirements

func (r Registry) ClientExtensionRequirements() ([]ClientExtensionRequirement, error)

ClientExtensionRequirements returns validated, uniquely owned client modules.

func (Registry) Descriptors

func (r Registry) Descriptors() []FeatureDescriptor

Descriptors returns cloned feature descriptors for inspection and tests.

func (Registry) ExtensionBuilders

func (r Registry) ExtensionBuilders(siteMenu Menu) []ExtensionBuilder

ExtensionBuilders resolves feature builders against the provided site menu.

func (Registry) Features

func (r Registry) Features() []Feature

Features returns a shallow clone of the registered features.

func (Registry) Menu

func (r Registry) Menu() Menu

Menu merges the menu contributions from every registered feature.

func (Registry) PermissionDefinitions

func (r Registry) PermissionDefinitions() []PermissionDefinition

PermissionDefinitions returns merged host feature permissions for runtime/bootstrap wiring.

type Repositories

type Repositories struct {
	FileRepo        FileRepository
	FileLoader      FileLoader
	AdminLoginAudit LoginAuditWriter
}

Repositories are host-owned data services used by the embedded admin runtime.

type RolePreset

type RolePreset = integrationroles.RolePreset

type RolesSeedOption

type RolesSeedOption = integrationroles.SeedOption

func WithPermissionDefinitions

func WithPermissionDefinitions(definitions ...PermissionDefinition) RolesSeedOption

WithPermissionDefinitions appends host-owned permissions to the built-in roles seed catalog.

func WithRolePresets

func WithRolePresets(presets ...RolePreset) RolesSeedOption

WithRolePresets appends host-owned canonical roles to the built-in roles seed.

type RolesService

type RolesService interface {
	IsSuperAdmin(ctx context.Context, adminID int64) bool
	GetRolesAdmin(ctx context.Context, adminID int64) ([]integrationroles.Role, error)
	GetPermissions(ctx context.Context, roles []integrationroles.Role) (map[int64]map[int64]integrationroles.Permission, error)
	AdminGuardCheck(ctx context.Context, adminID int64, key PermissionKey, opts ...integrationroles.PermissionGuardOption) bool
	AdminCan(ctx context.Context, adminID int64, domain PermissionDomain, action PermissionAction) bool
}

RolesService is the host-facing role service contract used by custom features and breadcrumb gating.

type Runtime

type Runtime struct {
	Server *Server
	Auth   *AuthAdapter
	// contains filtered or unexported fields
}

Runtime owns assembled workers and HTTP lifetime. Construction is inert.

func New

func New(ctx context.Context, cfg Config, deps Dependencies, modules ...Module) (_ *Runtime, err error)

New assembles an admin core with exactly the requested modules.

func (*Runtime) App

func (r *Runtime) App() *fiber.App

App exposes the underlying Fiber app for host tests; product features use the SDK.

func (*Runtime) Close

func (r *Runtime) Close() error

Close cancels and joins a running runtime, then closes only owned wrappers.

func (*Runtime) Readiness

func (r *Runtime) Readiness(ctx context.Context) error

func (*Runtime) Run

func (r *Runtime) Run(ctx context.Context, listeners ...net.Listener) error

Run starts each owned worker once. A worker exiting unexpectedly cancels and joins every sibling and the server before Run returns.

type Section

type Section = menu.Section

type Server

type Server = server.Server

type ServerConfig

type ServerConfig = bootstrap.ServerConfig

type ServerConfigInput

type ServerConfigInput struct {
	Addr                  string
	AllowOrigins          []string
	MaxRequest            int
	BodyLimit             int
	Expiration            time.Duration
	ReadTimeout           time.Duration
	WriteTimeout          time.Duration
	IdleTimeout           time.Duration
	DisableStartupMessage bool
	Prefork               bool
	TLSCert               string
	TLSKey                string
}

ServerConfigInput is the host-owned transport/server input for the admin runtime.

type ServerHandler

type ServerHandler = server.Handler

ServerHandler is the stable handler contract accepted by host extensions.

type Services

type Services struct {
	ExternalAuthority   ExternalSessionAuthority
	LocalAdminAdmission LocalAdminAdmission
	DB                  outbox.StoragePgsqlClient
	TxManager           outbox.StoragePgsqlTxManager
	Logger              logger.Logger
	CSRF                *CSRFService
	EventStream         eventstream.EventStream
	Outbox              Outbox
	SessionStore        *session.Store
	SessionRedis        redis.ClientContract
	Notifier            notify.NotificationManager
	// SubjectPermissions may be prebuilt and shared with transport-neutral
	// features such as gocms. Install builds it when omitted.
	SubjectPermissions *SubjectPermissionChecker
}

Services collects external infrastructure that the embedded admin mounts onto.

type SessionStore

type SessionStore = session.Store

type SetupSecretOutputKind

type SetupSecretOutputKind string
const (
	SetupSecretOutputTTY  SetupSecretOutputKind = "tty"
	SetupSecretOutputFile SetupSecretOutputKind = "file"
	SetupSecretOutputPipe SetupSecretOutputKind = "pipe"
)

func ValidateSetupSecretOutput

func ValidateSetupSecretOutput(output *os.File) (SetupSecretOutputKind, error)

ValidateSetupSecretOutput rejects stdout/stderr and any output channel whose filesystem permissions could disclose a first-admin setup token.

type SingleRequest

type SingleRequest = uploadhost.SingleRequest

type StoragePgsqlClient

type StoragePgsqlClient = outbox.StoragePgsqlClient

func NewPgsqlClient

func NewPgsqlClient(ctx context.Context, cfg PgsqlConfig, lg Logger) (StoragePgsqlClient, error)

NewPgsqlClient creates the PostgreSQL client used by the admin runtime.

type StoragePgsqlTxManager

type StoragePgsqlTxManager = outbox.StoragePgsqlTxManager

func NewTxManager

NewTxManager creates a transaction manager for the PostgreSQL client.

type SubjectPermissionChecker

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

SubjectPermissionChecker authorizes a canonical subject without exposing goauth role repositories or session claims to embedded features.

func NewSubjectPermissionChecker

func NewSubjectPermissionChecker(
	ctx context.Context,
	db StoragePgsqlClient,
	_ StoragePgsqlTxManager,
	lg Logger,
) (*SubjectPermissionChecker, error)

NewSubjectPermissionChecker builds the shared roles guard used by goadmin and transport-neutral embedded features.

func (*SubjectPermissionChecker) CheckPermission

func (c *SubjectPermissionChecker) CheckPermission(
	ctx context.Context,
	subjectID string,
	key PermissionKey,
) error

type TaskUploader

type TaskUploader = uploadhost.TaskUploader

type TusStore

type TusStore = uploadhost.TusStore

type URLConfigInput

type URLConfigInput struct {
	FilesBaseURL string
	FilesBucket  string
}

URLConfigInput is the minimal host-facing URL contract needed by bootstrap.

type URLConfigs

type URLConfigs = bootstrap.URLConfigs

func BuildURLConfigs

func BuildURLConfigs(input URLConfigInput) URLConfigs

BuildURLConfigs maps the minimal URL contract into bootstrap.URLConfigs.

type UploadContext

type UploadContext = uploadhost.UploadContext

type UploadStrategy

type UploadStrategy = uploadhost.UploadStrategy

type UploadTransport

type UploadTransport = bootstrap.UploadTransport

type UploadedFile

type UploadedFile = uploadhost.UploadedFile

type Uploads

type Uploads struct {
	Service      uploadhost.TaskUploader
	TusStore     uploadhost.TusStore
	AfterProcess AfterProcessHandler
}

Uploads groups upload services required by built-in admin file flows.

type UploadsConfig

type UploadsConfig struct {
	Repository FileRepository
	Loader     FileLoader
	Uploads    Uploads
	URLs       URLConfigs
	Jobs       []Job

	// Strategies adds named contexts to the canonical /files upload handler.
	// Names use 1-64 lowercase ASCII letters, digits, hyphens or underscores,
	// beginning with a letter. Built-in contexts cannot be replaced.
	// The map is copied; strategy instances remain host-owned and must be safe
	// for concurrent requests.
	Strategies map[string]UploadStrategy
}

type UserID

type UserID = uploadhost.UserID

Jump to

Keyboard shortcuts

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