webserver

package
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: GPL-2.0 Imports: 58 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// APITokenScopeWorkflowRead permits immutable workflow and operation reads.
	APITokenScopeWorkflowRead = apitoken.ScopeWorkflowRead
	// APITokenScopeWorkflowWrite permits preparation and non-execution commands.
	APITokenScopeWorkflowWrite = apitoken.ScopeWorkflowWrite
	// APITokenScopeWorkflowExecute permits consuming reviewed upload plans.
	APITokenScopeWorkflowExecute = apitoken.ScopeWorkflowExecute
)
View Source
const (
	// DVDMenuCapabilityAvailable reports compatible FFmpeg dvdvideo support.
	DVDMenuCapabilityAvailable = "available"
	// DVDMenuCapabilityIncompatible reports FFmpeg without required dvdvideo support.
	DVDMenuCapabilityIncompatible = "incompatible"
	// DVDMenuCapabilityUnavailable reports that capability could not be inspected.
	DVDMenuCapabilityUnavailable = "unavailable"
)

AuthFileName is the canonical web auth file name stored beside the database.

View Source
const AuthPasswordMinLength = authmaterial.AuthPasswordMinLength

AuthPasswordMinLength defines the minimum web auth password length.

Variables

This section is empty.

Functions

func AllocateRuntimeGenerationID added in v0.3.0

func AllocateRuntimeGenerationID() uint64

AllocateRuntimeGenerationID returns a process-local monotonic identifier for one coherent runtime resource generation.

func AuthFilePath

func AuthFilePath(dbPath string) string

AuthFilePath returns the auth file path colocated with dbPath.

func BindCoreCapabilities added in v0.3.0

func BindCoreCapabilities(svc *core.Core) (CoreCapabilities, LifecycleOwner)

BindCoreCapabilities exposes svc through every production capability and returns svc separately as its lifecycle owner. A nil service yields an empty bundle and nil owner; callers must close the returned owner exactly once.

func BootstrapAuthFile

func BootstrapAuthFile(dbPath string, username string, password string) error

BootstrapAuthFile creates the canonical auth file beside dbPath.

func BrowseDirectory added in v0.3.0

func BrowseDirectory(req api.BrowseDirectoryRequest, fallbackPath string) (api.BrowseDirectoryResponse, error)

BrowseDirectory lists an unrestricted host filesystem location. Folder mode returns directories only; file mode also returns recognized video files.

func BrowseDirectoryFallback added in v0.3.0

func BrowseDirectoryFallback(dbPath string) string

BrowseDirectoryFallback returns dbPath when it names an existing directory, otherwise its existing parent directory, or an empty string when neither is usable.

func BrowseDirectoryWithinRoot added in v0.3.0

func BrowseDirectoryWithinRoot(req api.BrowseDirectoryRequest, fallbackPath string, rootPath string) (api.BrowseDirectoryResponse, error)

BrowseDirectoryWithinRoot lists a host filesystem location constrained to rootPath after absolute-path and symlink resolution. An empty root disables the constraint.

func BrowseDirectoryWithinRoots added in v0.3.0

func BrowseDirectoryWithinRoots(req api.BrowseDirectoryRequest, fallbackPath string, rootPaths []string) (api.BrowseDirectoryResponse, error)

BrowseDirectoryWithinRoots lists a host filesystem location constrained to one of rootPaths. An empty request under multiple roots returns a virtual directory containing those roots; an empty root list disables constraints.

func CapabilityAvailable added in v0.3.0

func CapabilityAvailable(capability any) bool

CapabilityAvailable reports whether capability contains a callable value, rejecting both nil interfaces and interfaces holding typed nil values.

func ChangeAuthPassword added in v0.3.2

func ChangeAuthPassword(ctx context.Context, dbPath string, currentPassword string, newPassword string) (string, error)

ChangeAuthPassword verifies and replaces the persisted WebUI password. The caller must stop the WebUI server first so in-memory sessions cannot survive. It creates one pre-change backup, revokes retained sessions, and preserves protected data during legacy key upgrades. A returned backup path remains valid when a later update step fails.

func CurrentApplicationInfo added in v0.3.0

func CurrentApplicationInfo(ctx context.Context, provider api.DVDMenuCapabilityProvider) api.ApplicationInfo

CurrentApplicationInfo adds path-free DVD menu capability diagnostics to the shared application build/runtime information. It bounds the probe to ten seconds and returns unavailable status when ctx or provider is nil, including an interface containing a typed nil pointer.

func NormalizeBaseURL added in v0.2.1

func NormalizeBaseURL(raw string) (string, error)

NormalizeBaseURL validates and canonicalizes a browser-visible Web UI base URL. Empty/root values mean root deployment. Path-only values are returned as normalized paths without a trailing slash; absolute http(s) URLs keep a trailing slash for browser-open behavior and have query/fragment stripped.

func SaveCLIConfig

func SaveCLIConfig(dbPath string, cfg CLIConfig) error

SaveCLIConfig writes normalized serve settings next to dbPath.

func UpdateBrowseRoots added in v0.3.2

func UpdateBrowseRoots(ctx context.Context, dbPath string, values []string, allowUnrestricted bool) (int, string, error)

UpdateBrowseRoots replaces the persisted WebUI browse policy. Paths must be existing directories; unrestricted access cannot be combined with roots. The caller must stop the WebUI server first to avoid concurrent auth writes. A returned backup path remains valid when persistence later fails.

func ValidateBrowseSelection added in v0.3.0

func ValidateBrowseSelection(path string, wantDir bool) error

ValidateBrowseSelection requires an existing host path of the requested file or directory kind.

Types

type APITokenCredential added in v0.3.0

type APITokenCredential struct {
	Token   string
	OwnerID string
	Scopes  []APITokenScope
}

APITokenCredential configures one runtime-only bearer credential. Token is hashed during server construction and is never retained or serialized.

func ParseAPITokenEnvironment added in v0.3.0

func ParseAPITokenEnvironment(token string, ownerID string, rawScopes string) ([]APITokenCredential, error)

ParseAPITokenEnvironment constructs one runtime credential from serve-mode environment values without retaining the plaintext outside server startup.

type APITokenScope added in v0.3.0

type APITokenScope = apitoken.Scope

APITokenScope is one independently grantable third-party API permission.

type ActivationError added in v0.3.0

type ActivationError struct {
	Stage ActivationStage
	Err   error
}

ActivationError preserves the failed activation stage and wrapped cause.

func (*ActivationError) Error added in v0.3.0

func (e *ActivationError) Error() string

func (*ActivationError) Unwrap added in v0.3.0

func (e *ActivationError) Unwrap() error

Unwrap returns the stage cause.

type ActivationStage added in v0.3.0

type ActivationStage string

ActivationStage identifies the failed stage of a runtime activation.

const (
	ActivationStageNormalize       ActivationStage = "normalize candidate"
	ActivationStageValidateStored  ActivationStage = "validate stored config"
	ActivationStageValidateRuntime ActivationStage = "validate runtime config"
	ActivationStageBuild           ActivationStage = "build runtime generation"
	ActivationStageCookies         ActivationStage = "maintain cookies"
	ActivationStagePersist         ActivationStage = "persist stored config"
)

type Backend

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

Backend owns the embedded web API runtime.

func NewBackendWithContext

func NewBackendWithContext(ctx context.Context, cfg config.Config, hub *eventHub) (*Backend, error)

NewBackendWithContext opens the shared repository, creates the logger, and starts the core service when cfg validates. Invalid config keeps settings routes usable while core-backed routes report the initialization error.

func (*Backend) BrowseDirectory

func (b *Backend) BrowseDirectory(path string, mode string) (api.BrowseDirectoryResponse, error)

BrowseDirectory lists a host filesystem directory for the requested frontend browse mode.

func (*Backend) BrowseDirectoryWithinRoot

func (b *Backend) BrowseDirectoryWithinRoot(path string, mode string, root string) (api.BrowseDirectoryResponse, error)

BrowseDirectoryWithinRoot lists a directory only when it remains within the authorized host root.

func (*Backend) BrowseDirectoryWithinRoots

func (b *Backend) BrowseDirectoryWithinRoots(path string, mode string, roots []string) (api.BrowseDirectoryResponse, error)

BrowseDirectoryWithinRoots lists a directory only when it remains within an authorized host root.

func (*Backend) Close

func (b *Backend) Close() error

Close stops active background work and releases runtime, repository, and log resources.

func (*Backend) DeleteHistoryRelease

func (b *Backend) DeleteHistoryRelease(sourcePath string) error

DeleteHistoryRelease purges persisted history and managed artifacts for one source path.

func (*Backend) DeleteTrackerAuth added in v0.2.1

func (b *Backend) DeleteTrackerAuth(ctx context.Context, tracker string) (api.TrackerAuthStatus, error)

DeleteTrackerAuth removes stored tracker cookies and tracker-specific auth state with ctx, then returns the refreshed local status.

func (*Backend) DetectDiscType

func (b *Backend) DetectDiscType(ctx context.Context, path string) (string, error)

DetectDiscType classifies the selected host filesystem release path.

func (*Backend) DiscoverPlaylists

func (b *Backend) DiscoverPlaylists(ctx context.Context, path string) ([]api.PlaylistInfo, error)

DiscoverPlaylists returns Blu-ray playlists available under the selected release path.

func (*Backend) ExportConfig

func (b *Backend) ExportConfig() (string, error)

ExportConfig returns the exportable config, using plaintext secrets only when auth material for the exported snapshot's DB path explicitly allows unencrypted export.

func (*Backend) GetApplicationInfo

func (b *Backend) GetApplicationInfo() (api.ApplicationInfo, error)

GetApplicationInfo returns build/runtime metadata plus a bounded, path-free DVD menu capability probe for embedded-web diagnostics.

func (*Backend) GetConfig

func (b *Backend) GetConfig() (string, error)

GetConfig returns the current exportable config as JSON with encrypted secret fields for browser settings consumers.

func (*Backend) GetDefaultConfig

func (b *Backend) GetDefaultConfig() (string, error)

GetDefaultConfig returns the built-in configuration serialized for the settings editor.

func (*Backend) GetHistoryOverview

func (b *Backend) GetHistoryOverview(sourcePath string) (api.HistoryOverview, error)

GetHistoryOverview returns persisted upload and asset detail for one source path.

func (*Backend) GetImageHostPolicyMetadata

func (b *Backend) GetImageHostPolicyMetadata() (imagehostpolicy.Metadata, error)

GetImageHostPolicyMetadata returns image-host policy metadata consumed by settings and upload UI.

func (*Backend) GetLogExclusions

func (b *Backend) GetLogExclusions() ([]string, error)

GetLogExclusions returns persisted frontend log-filter patterns.

func (*Backend) GetLogPath

func (b *Backend) GetLogPath() (string, error)

GetLogPath returns the host filesystem path of the active application log.

func (*Backend) GetRecentLogs

func (b *Backend) GetRecentLogs(limit int) ([]logging.Entry, error)

GetRecentLogs returns up to limit sanitized recent log entries.

func (*Backend) GetReleaseWorkflowCapabilities added in v0.3.0

func (b *Backend) GetReleaseWorkflowCapabilities(
	ownerID string,
	scopes []string,
	uploadOptionSchemaHash string,
) (api.ReleaseWorkflowCapabilities, error)

GetReleaseWorkflowCapabilities returns authenticated, non-secret integration metadata for composite-workflow API clients.

func (*Backend) GetTrackerAuthStatus added in v0.2.1

func (b *Backend) GetTrackerAuthStatus(tracker string) (api.TrackerAuthStatus, error)

GetTrackerAuthStatus reports local auth state for tracker from the current runtime config and persisted cookie/auth state.

func (*Backend) ImportConfig

func (b *Backend) ImportConfig(fileName, fileContent string) (string, []string, error)

ImportConfig imports browser-uploaded config content, validates the saved and env-applied runtime forms, builds the replacement runtime, migrates shared cookies, then persists the non-env config before installing the runtime. Runtime build, migration, or save failures leave the persisted config and active runtime unchanged.

func (*Backend) ImportTrackerAuthCookieContent added in v0.2.1

func (b *Backend) ImportTrackerAuthCookieContent(ctx context.Context, tracker string, fileName string, content string) (api.TrackerAuthStatus, error)

ImportTrackerAuthCookieContent imports browser-supplied cookie content with the request context and the shared raw content size limit.

func (*Backend) ListHistory

func (b *Backend) ListHistory() ([]api.HistoryEntry, error)

ListHistory returns persisted release history in repository-defined order.

func (*Backend) ListTrackerAuthCapabilities added in v0.2.1

func (b *Backend) ListTrackerAuthCapabilities() ([]api.TrackerAuthCapability, error)

ListTrackerAuthCapabilities returns browser-visible tracker auth support from the current runtime config.

func (*Backend) ListTrackerCatalog added in v0.3.0

func (b *Backend) ListTrackerCatalog() (api.TrackerCatalog, error)

ListTrackerCatalog returns ordered tracker identity, config schemas, and local configured state without exposing current credential values.

func (*Backend) LoginTrackerAuth added in v0.2.1

func (b *Backend) LoginTrackerAuth(ctx context.Context, tracker string, req api.TrackerAuthLoginRequest) (api.TrackerAuthStatus, error)

LoginTrackerAuth attempts credential-based tracker auth with ctx and returns status for missing credentials, unsupported login, or 2FA.

func (*Backend) RenderDescription

func (b *Backend) RenderDescription(raw string) (string, error)

RenderDescription converts tracker markup into sanitized preview HTML.

func (*Backend) SaveConfig

func (b *Backend) SaveConfig(payload string) error

SaveConfig decodes encrypted browser settings and delegates the complete config/runtime transition to the shared runtime activator.

func (*Backend) StartLogStream

func (b *Backend) StartLogStream(sessionID string) (string, error)

StartLogStream subscribes the browser session to live log events. Active streams are rebound when settings replace the runtime logger. If no logger or event hub is installed, it returns an error without registering a stream.

func (*Backend) StopLogStream

func (b *Backend) StopLogStream(sessionID string, streamID string) error

StopLogStream stops streamID only when it belongs to sessionID. Unknown streams and streams owned by other sessions are treated as no-ops.

func (*Backend) StopSessionLogStreams

func (b *Backend) StopSessionLogStreams(sessionID string)

StopSessionLogStreams closes all active log streams owned by sessionID.

func (*Backend) SubmitTrackerAuth2FA added in v0.2.1

func (b *Backend) SubmitTrackerAuth2FA(ctx context.Context, challengeID string, code string) (api.TrackerAuthStatus, error)

SubmitTrackerAuth2FA completes an active manual 2FA challenge with ctx and returns the refreshed tracker auth status.

func (*Backend) TestTrackerAuth added in v0.2.1

func (b *Backend) TestTrackerAuth(ctx context.Context, tracker string) (api.TrackerAuthStatus, error)

TestTrackerAuth validates tracker auth with ctx so canceled web requests stop remote validation and persistence work.

func (*Backend) UpdateLogExclusions

func (b *Backend) UpdateLogExclusions(patterns []string) error

UpdateLogExclusions validates and persists frontend log-filter patterns.

type CLIConfig

type CLIConfig struct {
	Host           string   `json:"host"`
	Port           int      `json:"port"`
	OpenBrowser    bool     `json:"open_browser"`
	TrustedProxies []string `json:"trusted_proxies"`
	BaseURL        string   `json:"base_url"`
	SessionTTL     int      `json:"session_ttl"`
}

CLIConfig stores the serve settings that can come from persisted web config, environment variables, or CLI flags.

func DefaultCLIConfig

func DefaultCLIConfig() CLIConfig

DefaultCLIConfig returns the serve settings used when no persisted web config exists or persisted fields are omitted.

func LoadCLIConfig

func LoadCLIConfig(dbPath string) (CLIConfig, error)

LoadCLIConfig reads persisted serve settings from the directory containing dbPath. BaseURL is intentionally left unvalidated so env or CLI overrides can replace stale stored values before final validation.

type CoreCapabilities added in v0.3.0

type CoreCapabilities struct {
	ReleaseWorkflow ReleaseWorkflowCapability
	Description     DescriptionCapability
	Playlists       PlaylistCapability
	History         HistoryCapability
	DiagnosticProbe DiagnosticProbeCapability
}

CoreCapabilities is the explicit WebUI workflow bundle. Each field is a narrow view of one concrete core; lifecycle ownership remains separate. Fields are independently optional so consumers and tests can supply only the workflows they invoke. Production bindings populate every field.

func (CoreCapabilities) Available added in v0.3.0

func (c CoreCapabilities) Available() bool

Available reports whether at least one capability is installed. It does not validate that a bundle contains every capability a caller needs.

type DescriptionCapability added in v0.3.0

type DescriptionCapability interface {
	RenderDescription(context.Context, string) (string, error)
}

DescriptionCapability renders raw description markup without mutating release state.

type DiagnosticProbeCapability added in v0.3.0

type DiagnosticProbeCapability interface {
	DVDMenuCapability(context.Context) (api.DVDMenuEngineInfo, error)
}

DiagnosticProbeCapability reports availability of optional runtime tooling.

type HistoryCapability added in v0.3.0

type HistoryCapability interface {
	ListHistory(context.Context) ([]api.HistoryEntry, error)
	GetHistoryOverview(context.Context, string) (api.HistoryOverview, error)
	DeleteHistoryRelease(context.Context, string) error
	DeleteAllHistoryReleases(context.Context) (int, error)
}

HistoryCapability reads and deletes persisted release history.

type LifecycleOwner added in v0.3.0

type LifecycleOwner interface{ Close() error }

LifecycleOwner is the sole shutdown handle for resources behind a capability bundle. Capability interfaces intentionally omit Close so borrowing one never implies ownership.

type Options

type Options struct {
	// LiveTest preserves process-owned effect restrictions across runtime changes.
	LiveTest *api.LiveTestPolicy
	// Config supplies the application configuration used by the backend.
	Config config.Config
	// CLIConfig supplies persisted or command-line web server settings.
	CLIConfig CLIConfig
	// DevelopmentNoAuth enables the development-only auth bypass for loopback hosts.
	DevelopmentNoAuth bool
	// APITokens supplies optional runtime-only compatibility credentials for /api/v1.
	// Persisted credentials are loaded from web-auth.json.
	APITokens []APITokenCredential
}

Options configures the embedded web UI server.

type PlaylistCapability added in v0.3.0

type PlaylistCapability interface {
	DiscoverPlaylists(context.Context, string) ([]api.PlaylistInfo, error)
}

PlaylistCapability discovers BDMV playlists for one preparation source.

type ReleaseWorkflowCapability added in v0.3.0

type ReleaseWorkflowCapability interface {
	ContinueReleaseWorkflow(context.Context, string, api.ContinueReleaseWorkflowRequest) (releaseworkflow.CommandResult, error)
	StartReleaseWorkflowUpload(context.Context, string, api.CreateReleaseWorkflowUploadRequest) (releaseworkflow.CommandResult, error)
	SubmitReleaseWorkflowUploadFeedback(
		context.Context,
		string,
		api.WorkflowID,
		api.ReleaseWorkflowUploadFeedback,
	) (releaseworkflow.CommandResult, error)
	ExecuteReleaseWorkflow(context.Context, string, releaseworkflow.Command) (releaseworkflow.CommandResult, error)
	StartReleaseWorkflow(context.Context, string, releaseworkflow.Command) (api.WorkflowOperationStatus, error)
	CurrentReleaseWorkflow(context.Context, string, api.WorkflowID) (releaseworkflow.CommandResult, error)
	ReleaseWorkflowOperation(context.Context, string, api.WorkflowID, api.WorkflowOperationID) (api.WorkflowOperationStatus, error)
	CancelReleaseWorkflowOperation(context.Context, string, api.WorkflowID, api.WorkflowOperationID) (api.WorkflowOperationStatus, error)
	ReleaseWorkflowMediaPlan(context.Context, string, api.WorkflowID) (api.MediaPlan, error)
	PreviewReleaseWorkflowFrame(context.Context, string, api.WorkflowID, api.WorkflowRevision, string, float64) (api.FramePreview, error)
	OpenReleaseWorkflowPreview(context.Context, string, api.WorkflowID, api.PublicResourceID) (releaseworkflow.MediaArtifactContent, error)
	StageReleaseWorkflowMediaResource(
		context.Context,
		string,
		api.WorkflowID,
		api.WorkflowRevision,
		releaseworkflow.StagedMediaContent,
	) (api.WorkflowResourceRef, error)
	OpenReleaseWorkflowMediaArtifact(
		context.Context,
		string,
		api.WorkflowID,
		api.MediaArtifactSetRef,
		api.PublicResourceID,
	) (releaseworkflow.MediaArtifactContent, error)
}

ReleaseWorkflowCapability owns the authenticated browser workflow command/query boundary.

type RetiredRuntime added in v0.3.0

type RetiredRuntime struct {
	Owner  LifecycleOwner
	Logger *logging.Logger
}

RetiredRuntime owns the resources replaced by one successful installation.

func (RetiredRuntime) Close added in v0.3.0

func (r RetiredRuntime) Close()

Close releases the replaced runtime after its installer has finished all transport-specific rebinding.

type RuntimeActivator added in v0.3.0

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

RuntimeActivator serializes and owns the complete config-candidate to active runtime transition for one WebUI host.

func NewRuntimeActivator added in v0.3.0

func NewRuntimeActivator(repo *db.SQLiteRepository, fixedDBPath string, installer RuntimeInstaller) (*RuntimeActivator, error)

NewRuntimeActivator constructs an activator for one already-open repository and one host-specific runtime installer.

func (*RuntimeActivator) Activate added in v0.3.0

func (a *RuntimeActivator) Activate(ctx context.Context, candidate config.Config) error

Activate normalizes, validates, builds, maintains, persists, and publishes a config candidate as one serialized runtime transition.

type RuntimeGeneration added in v0.3.0

type RuntimeGeneration struct {
	ID           uint64
	Config       config.Config
	Capabilities CoreCapabilities
	Owner        LifecycleOwner
	Logger       *logging.Logger
}

RuntimeGeneration groups one activated config generation's workflow bundle, lifecycle owner, and logger. Capabilities borrow the core; the runtime activator transfers Owner and Logger to the installer as one generation.

type RuntimeInstaller added in v0.3.0

type RuntimeInstaller interface {
	Install(RuntimeGeneration) RetiredRuntime
}

RuntimeInstaller atomically publishes one complete runtime generation and returns resources that can be retired after transport rebinding completes. Install must not fail.

type Server

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

Server owns the embedded web UI HTTP server, backend services, auth stores, and event hub.

func New

func New(opts Options) (*Server, error)

New constructs a server from application and web CLI configuration. It rejects development no-auth mode for non-loopback hosts.

func (*Server) Close

func (s *Server) Close() error

Close releases session and backend resources owned by the server.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run binds the configured TCP address and serves until ctx is cancelled or a shutdown signal arrives.

func (*Server) RunAfterListen added in v0.2.0

func (s *Server) RunAfterListen(ctx context.Context, afterListen func() error) error

RunAfterListen runs the server and calls afterListen once the TCP listener has bound successfully, before HTTP serving starts. If afterListen fails, the listener is closed and the server does not start accepting requests.

Jump to

Keyboard shortcuts

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