plugin

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 80 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CompatOK                   = "compatible"
	CompatIncompatiblePlatform = "incompatible_platform"
	CompatIncompatibleSkinloom = "incompatible_skinloom"
	CompatIncompatibleAPI      = "incompatible_api"
	CompatIncompatibleProtocol = "incompatible_protocol"
	CompatIncompatibleGo       = "incompatible_go"
	CompatMissingDependency    = "missing_dependency"
	CompatConflictDependency   = "conflict_dependency"
	CompatCyclicDependency     = "cyclic_dependency"
	CompatYanked               = "yanked"
	CompatBlocked              = "blocked"
)

Compatibility reason codes returned by the 5-dimensional compatibility engine.

View Source
const (
	// NativePluginName is the hashicorp/go-plugin plugin map key for SkinLoom Tier 2 plugins.
	NativePluginName = "skinloom"

	// HeaderProxyToken carries the ephemeral 256-bit shared secret between host
	// ReverseProxy and a native plugin's local HTTP/WebSocket listener.
	HeaderProxyToken = "X-SkinLoom-Proxy-Token"
)
View Source
const (
	DefaultFetchTimeout      = 10 * time.Second
	DefaultFetchMaxRespBytes = 5 * 1024 * 1024 // 5 MiB

)
View Source
const (
	KindPlugin = "plugin"
	KindTheme  = "theme"

	RuntimeJS     = "js"
	RuntimeNative = "native"

	CurrentAPIVersion            = 1
	CurrentNativeProtocolVersion = 1

	MaxPluginKVKeys     = 1000
	MaxPluginKVValBytes = 64 * 1024
	MaxPluginDocs       = 50000
	MaxPluginFileBytes  = 50 * 1024 * 1024
)
View Source
const (
	// MaxPackageBytes caps a Tier 1 JS/theme .slp archive size (20 MiB).
	MaxPackageBytes = 20 * 1024 * 1024
	// MaxUnpackedPackageBytes caps total decompressed bytes extracted from a JS/theme .slp archive (Zip Bomb defense).
	MaxUnpackedPackageBytes = 20 * 1024 * 1024
	// MaxPackageFileBytes caps any individual non-binary file inside an .slp archive (10 MiB).
	MaxPackageFileBytes = 10 * 1024 * 1024
	// MaxServerBundleBytes caps server.js bundle size (5 MiB).
	MaxServerBundleBytes = 5 * 1024 * 1024
	// MaxPackageEntries caps the total number of archive entries.
	MaxPackageEntries = 4096

	// MaxNativeSinglePackageBytes caps a single-platform Tier 2 native .slp archive (50 MiB).
	MaxNativeSinglePackageBytes = 50 * 1024 * 1024
	// MaxNativeFatPackageBytes caps a multi-platform Tier 2 fat .slp archive (150 MiB).
	MaxNativeFatPackageBytes = 150 * 1024 * 1024
	// MaxNativeUnpackedSingleBytes caps decompressed bytes for a single-platform native .slp (100 MiB).
	MaxNativeUnpackedSingleBytes = 100 * 1024 * 1024
	// MaxNativeUnpackedFatBytes caps decompressed bytes for a multi-platform fat native .slp (256 MiB).
	MaxNativeUnpackedFatBytes = 256 * 1024 * 1024
	// MaxNativeBinaryBytes caps an individual compiled Go binary inside a native .slp (64 MiB).
	MaxNativeBinaryBytes = 64 * 1024 * 1024
)
View Source
const (
	// Normal permissions
	PermStorageKV    = "storage.kv"
	PermStorageDocs  = "storage.docs"
	PermStorageFiles = "storage.files"
	PermCron         = "cron"
	PermAdminUI      = "admin.ui"
	PermUsersRead    = "users.read"
	PermPlayersRead  = "players.read"
	PermTexturesRead = "textures.read"
	PermNotifySend   = "notify.send"

	// Sensitive permissions
	PermHTTPFetch       = "http.fetch"
	PermMailSend        = "mail.send"
	PermPlayersWrite    = "players.write"
	PermTexturesWrite   = "textures.write"
	PermClosetWrite     = "closet.write"
	PermScoreWrite      = "score.write"
	PermUsersWrite      = "users.write"
	PermRoutesPublic    = "routes.public"
	PermYggdrasilExtend = "yggdrasil.extend"
	PermCDNProvider     = "cdn.provider"
	PermCaptchaProvider = "captcha.provider"
	PermStorageSQL      = "storage.sql"
	PermHTTPStream      = "http.stream"
	PermProviderSearch  = "provider.search"
	PermProviderRender  = "provider.render"

	// High-risk permissions
	PermUsersBan        = "users.ban"
	PermAuthProvider    = "auth.provider"
	PermAuthPassword    = "auth.password"
	PermProviderStorage = "provider.storage"
	PermNativeExec      = "native.exec"
)
View Source
const (
	// DefaultRegistryCacheTTL is the default in-memory and disk cache duration for index.v1.json.
	DefaultRegistryCacheTTL = 15 * time.Minute
	// DefaultRegistryPatrolInterval is the background check interval for blocked plugins.
	DefaultRegistryPatrolInterval = 6 * time.Hour
	// MaxRegistryIndexBytes caps index.v1.json payload size (16 MiB).
	MaxRegistryIndexBytes = 16 * 1024 * 1024
	// MaxRegistrySigBytes caps index.v1.json.sig payload size (4 KiB).
	MaxRegistrySigBytes = 4 * 1024
)
View Source
const DefaultCircuitThreshold = 5

DefaultCircuitThreshold is the number of consecutive runtime failures before a plugin is automatically tripped into failed status and unloaded.

View Source
const OfficialPublicKeyPEM = `-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAw8HIDMjyzCMx8asCu1gY4+jELLPbsVcwCbig9AyHm4g=
-----END PUBLIC KEY-----`

OfficialPublicKeyPEM is the built-in Ed25519 SPKI public key used for official packages. Its corresponding private key is held offline outside this repository.

Variables

View Source
var (
	// ErrFetchDenied indicates an outbound HTTP call violated http.allow or SSRF protection.
	ErrFetchDenied = errors.New("outbound fetch denied")
	// ErrFetchTooLarge indicates an outbound HTTP response exceeded 5 MiB.
	ErrFetchTooLarge = errors.New("outbound fetch response exceeds 5 MiB limit")
)
View Source
var (
	// ErrBadPackage indicates a malformed, oversized, tampered, or unsafe .slp archive.
	ErrBadPackage = errors.New("invalid plugin package")
	// ErrUntrustedPackage indicates an unsigned or unknown-signer .slp archive without allowUnsigned.
	ErrUntrustedPackage = errors.New("plugin package signature is missing or untrusted")
	// ErrUnsignedNativeForbidden indicates an unsigned or untrusted Tier 2 native binary
	// package was rejected by production security policy.
	ErrUnsignedNativeForbidden = errors.New("unsigned or untrusted native plugin is forbidden in production mode")
)
View Source
var (
	// ErrInvalidSettings indicates a plugin settings patch failed manifest schema validation.
	ErrInvalidSettings = errors.New("invalid plugin settings")
	// ErrMissingDependency indicates a required plugin dependency is missing or inactive.
	ErrMissingDependency = errors.New("missing plugin dependency")
)
View Source
var (
	// ErrRegistrySignatureInvalid indicates index.v1.json failed Ed25519 signature verification.
	ErrRegistrySignatureInvalid = errors.New("registry index signature verification failed")
	// ErrMarketPackageNotFound indicates the requested plugin/theme or version was not found in the market.
	ErrMarketPackageNotFound = errors.New("market package not found")
	// ErrMarketPackageBlocked indicates the requested plugin/theme version is on the registry blocklist.
	ErrMarketPackageBlocked = errors.New("market package is blocked by security policy")
	// ErrMarketPackageIncompatible indicates the requested package is incompatible with the host environment.
	ErrMarketPackageIncompatible = errors.New("market package is incompatible with host environment")
)
View Source
var (
	// ErrUnknownCollection means the collection was not declared in plugin.json.
	ErrUnknownCollection = errors.New("unknown plugin collection")
	// ErrUniqueConstraint means a string:unique indexed field collided with an existing doc.
	ErrUniqueConstraint = errors.New("unique constraint violation")
	// ErrQuotaExceeded means a plugin storage quota limit was reached.
	ErrQuotaExceeded = errors.New("plugin storage quota exceeded")
)
View Source
var (
	// ErrFileNotFound means a plugin private file key does not exist.
	ErrFileNotFound = errors.New("plugin file not found")
	// ErrInvalidFileKey means the file key is unsafe or traverses directories.
	ErrInvalidFileKey = errors.New("invalid plugin file key")
)
View Source
var (
	ErrBadManifest = errors.New("plugin: invalid manifest")
)
View Source
var ErrPermissionDenied = errors.New("permission denied")

ErrPermissionDenied indicates a plugin invoked a capability it lacks permission for.

View Source
var FormScopes = []string{
	"auth.register",
	"auth.login",
	"user.profile",
	"texture.upload",
	"player.create",
}

FormScopes lists host forms where plugins may declaratively append input fields.

View Source
var NativeHandshake = hplugin.HandshakeConfig{
	ProtocolVersion:  CurrentNativeProtocolVersion,
	MagicCookieKey:   "SKINLOOM_NATIVE_PLUGIN",
	MagicCookieValue: "skinloom-plugin-v1",
}

NativeHandshake defines the protocol handshake shared by SkinLoom host and sdk/go.

View Source
var PluginSettingTypes = []string{
	"string",
	"text",
	"markdown",
	"number",
	"boolean",
	"select",
	"multiselect",
	"color",
	"image",
	"secret",
	"json",
	"list",
	"group",
	"choice",
}

PluginSettingTypes lists all supported setting field types in plugin.json.

View Source
var Slots = []SlotDef{

	{
		Name:        "site.header.actions",
		Area:        "site",
		Description: "Action buttons or status badges rendered in the top site header bar.",
	},
	{
		Name:        "site.footer",
		Area:        "site",
		Description: "Custom links or widgets rendered inside the global footer.",
	},
	{
		Name:        "site.banner",
		Area:        "site",
		Description: "Dismissible or announcement banner rendered directly beneath the site header.",
	},

	{
		Name:        "auth.login.below",
		Area:        "auth",
		Description: "Content or notices rendered underneath the sign-in form.",
	},
	{
		Name:        "auth.login.providers",
		Area:        "auth",
		Description: "External identity provider sign-in buttons rendered on the login page.",
		Props: []SlotProp{
			{Name: "next", TypeScript: "string", Optional: true, Description: "Post-login redirect path."},
		},
	},
	{
		Name:        "auth.register.below",
		Area:        "auth",
		Description: "Content or notices rendered underneath the registration form.",
	},
	{
		Name:        "auth.register.providers",
		Area:        "auth",
		Description: "External identity provider sign-up buttons rendered on the registration page.",
		Props: []SlotProp{
			{Name: "next", TypeScript: "string", Optional: true, Description: "Post-registration redirect path."},
		},
	},

	{
		Name:        "user.dashboard.widgets",
		Area:        "user",
		Description: "Dashboard cards displayed on the signed-in user overview page.",
	},
	{
		Name:        "user.profile.sections",
		Area:        "user",
		Description: "Additional profile or security sections appended in user settings.",
	},
	{
		Name:        "user.player.actions",
		Area:        "user",
		Description: "Per-player action buttons rendered next to rename/texture controls.",
		Props: []SlotProp{
			{Name: "playerId", TypeScript: "number"},
			{Name: "name", TypeScript: "string"},
			{Name: "uuid", TypeScript: "string"},
		},
	},
	{
		Name:        "user.closet.item.actions",
		Area:        "user",
		Description: "Action controls rendered on each texture card in the user's closet.",
		Props: []SlotProp{
			{Name: "textureId", TypeScript: "number"},
			{Name: "name", TypeScript: "string"},
			{Name: "type", TypeScript: "'steve' | 'alex' | 'cape'"},
		},
	},

	{
		Name:        "skinlib.card.badges",
		Area:        "skinlib",
		Description: "Inline badges rendered on skin library texture cards.",
		Props: []SlotProp{
			{Name: "textureId", TypeScript: "number"},
			{Name: "name", TypeScript: "string"},
			{Name: "type", TypeScript: "'steve' | 'alex' | 'cape'"},
			{Name: "public", TypeScript: "boolean"},
			{Name: "likes", TypeScript: "number"},
		},
	},
	{
		Name:        "skinlib.detail.sidebar",
		Area:        "skinlib",
		Description: "Cards rendered inside the skin detail page sidebar.",
		Props: []SlotProp{
			{Name: "textureId", TypeScript: "number"},
			{Name: "name", TypeScript: "string"},
			{Name: "type", TypeScript: "'steve' | 'alex' | 'cape'"},
			{Name: "public", TypeScript: "boolean"},
			{Name: "uploaderId", TypeScript: "number | null", Optional: true},
		},
	},
	{
		Name:        "skinlib.detail.below",
		Area:        "skinlib",
		Description: "Full-width sections rendered below the skin detail viewer.",
		Props: []SlotProp{
			{Name: "textureId", TypeScript: "number"},
			{Name: "name", TypeScript: "string"},
			{Name: "type", TypeScript: "'steve' | 'alex' | 'cape'"},
			{Name: "public", TypeScript: "boolean"},
		},
	},
	{
		Name:        "skinlib.upload.below",
		Area:        "skinlib",
		Description: "Content or hints rendered below the texture upload form.",
	},

	{
		Name:        "admin.dashboard.widgets",
		Area:        "admin",
		Description: "Metric or status widgets rendered on the admin overview dashboard.",
	},
	{
		Name:        "admin.user.actions",
		Area:        "admin",
		Description: "Row actions rendered for each account in the admin user management table.",
		Props: []SlotProp{
			{Name: "userId", TypeScript: "number"},
			{Name: "email", TypeScript: "string"},
			{Name: "nickname", TypeScript: "string"},
			{Name: "role", TypeScript: "'user' | 'admin' | 'superadmin'"},
			{Name: "status", TypeScript: "'active' | 'banned' | 'deleted'"},
		},
	},
	{
		Name:        "admin.user.tabs",
		Area:        "admin",
		Description: "Extra view tabs rendered alongside the admin user management workspace.",
	},
	{
		Name:        "admin.texture.actions",
		Area:        "admin",
		Description: "Moderator action menu entries on a texture page or moderation list.",
		Props: []SlotProp{
			{Name: "textureId", TypeScript: "number"},
			{Name: "name", TypeScript: "string"},
			{Name: "public", TypeScript: "boolean"},
			{Name: "uploaderId", TypeScript: "number | null", Optional: true},
		},
	},
	{
		Name:        "admin.status.cards",
		Area:        "admin",
		Description: "Diagnostic cards rendered on the admin system status page.",
	},
}

Slots is the canonical catalog of the 20 frontend extension slots.

View Source
var ThemeOverrideTargets = []string{
	"site.header",
	"site.footer",
	"site.logo",
	"auth.background",
	"home.hero",
	"texture.card",
	"player.card",
}

ThemeOverrideTargets lists the 7 built-in UI components that themes may replace client-side via theme.overrides (design 09 §0, §3.2).

Functions

func AllPermissions

func AllPermissions() map[string]PermissionDef

AllPermissions returns a copy of all recognized permission definitions.

func ExtractPackageFiles

func ExtractPackageFiles(pkg *ParsedPackage, destDir string) error

ExtractPackageFiles atomically writes a parsed package's regular files into destDir.

func ParseEd25519PublicKey

func ParseEd25519PublicKey(spec string) (ed25519.PublicKey, error)

ParseEd25519PublicKey decodes a PEM SPKI, base64 SPKI/raw, or 64-hex Ed25519 public key.

func PublicKeyFingerprint

func PublicKeyFingerprint(pub ed25519.PublicKey) string

PublicKeyFingerprint returns a short stable SHA-256 fingerprint for an Ed25519 public key.

func SafeSQLPrefix

func SafeSQLPrefix(pluginID string) (string, error)

SafeSQLPrefix derives the unforgeable SQL table prefix "plg_<safe_id>_" from a validated kebab-case plugin identifier.

func SafeSQLSchema

func SafeSQLSchema(pluginID string) (string, error)

SafeSQLSchema derives the optional PostgreSQL schema name "plg_<safe_id>".

func ValidateFileKey

func ValidateFileKey(key string) (string, error)

ValidateFileKey verifies and normalizes a slash-separated relative asset/file key.

func WithRequestLocale

func WithRequestLocale(ctx context.Context, locale string) context.Context

WithRequestLocale attaches the current HTTP/UI locale so ctx.t translates for the visitor's language when no explicit locale argument is given.

Types

type BlockedPluginAction

type BlockedPluginAction struct {
	PluginID   string `json:"pluginId"`
	Version    string `json:"version"`
	Reason     string `json:"reason"`
	RegistryID string `json:"registryId"`
}

BlockedPluginAction records an installed plugin that was automatically disabled due to a registry block rule.

type CachedRegistryIndex

type CachedRegistryIndex struct {
	Source       settings.RegistrySource `json:"source"`
	Index        *RegistryIndex          `json:"index"`
	RawBytes     []byte                  `json:"-"`
	Signature    string                  `json:"signature,omitempty"`
	Verified     bool                    `json:"verified"`
	Official     bool                    `json:"official"`
	ActiveMirror string                  `json:"activeMirror"`
	FetchedAt    time.Time               `json:"fetchedAt"`
}

CachedRegistryIndex holds a verified registry index alongside fetch telemetry.

type CircuitBreaker

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

CircuitBreaker tracks consecutive execution failures for one plugin.

func NewCircuitBreaker

func NewCircuitBreaker(threshold int) *CircuitBreaker

NewCircuitBreaker constructs a CircuitBreaker; threshold <= 0 defaults to 5.

func (*CircuitBreaker) RecordFailure

func (c *CircuitBreaker) RecordFailure(err error) (justTripped bool)

RecordFailure records an internal/runtime failure (timeouts, OOM, uncaught exceptions) and returns true on the exact failure that trips the breaker.

func (*CircuitBreaker) RecordSuccess

func (c *CircuitBreaker) RecordSuccess()

RecordSuccess clears any streak of consecutive non-user errors.

func (*CircuitBreaker) Reset

func (c *CircuitBreaker) Reset()

Reset restores the breaker to closed state after an administrator re-enables the plugin.

func (*CircuitBreaker) State

func (c *CircuitBreaker) State() (consecutive int, tripped bool, lastError string, lastFailAt time.Time)

State snapshots the circuit breaker status.

type CollectionSpec

type CollectionSpec struct {
	Indexes map[string]string `json:"indexes,omitempty"`
}

type CompatIssue

type CompatIssue struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

CompatIssue describes one failed dimension check.

type CompatReport

type CompatReport struct {
	Compatible bool          `json:"compatible"`
	Status     string        `json:"status"` // CompatOK or primary failure code
	Issues     []CompatIssue `json:"issues,omitempty"`
}

CompatReport summarizes compatibility of a single manifest or version.

func CheckManifestCompat

func CheckManifestCompat(mf *Manifest, env HostEnv) CompatReport

CheckManifestCompat evaluates a local/uploaded plugin.json manifest against env across all 5 dimensions (platform, SkinLoom version, API/protocol version, Go baseline, installed deps).

type CronSchedule

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

CronSchedule represents a parsed 5-field cron schedule (minute hour dom month dow).

func ParseCron

func ParseCron(expr string) (CronSchedule, error)

ParseCron parses standard 5-field cron expressions and common @macros.

func (CronSchedule) Matches

func (c CronSchedule) Matches(t time.Time) bool

Matches reports whether t (truncated to minute) satisfies the schedule.

type DBAllocator

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

DBAllocator provisions isolated SQL storage spaces for native plugins across SQLite (dedicated <DataDir>/plugins-data/<id>/plugin.db in WAL mode), MySQL/MariaDB (shared or dedicated DSN + plg_<safe_id>_ prefix), and PostgreSQL (shared or dedicated DSN + plg_<safe_id>_ prefix or optional schema).

func NewDBAllocator

func NewDBAllocator(opts DBAllocatorOptions) *DBAllocator

NewDBAllocator creates a PluginDBAllocator.

func (*DBAllocator) Allocate

func (a *DBAllocator) Allocate(ctx context.Context, pluginID string) (*PluginDBConfig, error)

Allocate prepares and returns the isolated database configuration for pluginID.

func (*DBAllocator) Purge

func (a *DBAllocator) Purge(ctx context.Context, pluginID string) error

Purge cleanly drops all isolated SQL objects belonging strictly to pluginID (SQLite plugin.db files, or MySQL/PostgreSQL tables matching plg_<safe_id>_* and optional PostgreSQL schema plg_<safe_id>), never touching core tables.

func (*DBAllocator) SQLiteFilePath

func (a *DBAllocator) SQLiteFilePath(pluginID string) (string, error)

SQLiteFilePath returns the isolated SQLite database file path for pluginID.

type DBAllocatorOptions

type DBAllocatorOptions struct {
	MainDriver string
	MainDSN    string
	MainSQL    *sql.DB
	Override   config.PluginDatabase
	DataDir    string
}

DBAllocatorOptions configures the three-dialect native plugin database allocator.

type DependencyPlan

type DependencyPlan struct {
	// Install lists dependencies that are not yet installed (or need upgrade) in
	// dependency-first order, excluding the root target itself.
	Install []DependencyStep `json:"install,omitempty"`
}

DependencyPlan holds the topologically ordered cascade-install steps required before activating a target plugin.

func ResolveDependencyPlan

func ResolveDependencyPlan(
	targetID, targetVersion string,
	env HostEnv,
	catalog map[string]RegistryPackage,
) (*DependencyPlan, error)

ResolveDependencyPlan resolves the full transitive dependency tree for targetID@targetVersion, returning an ordered install plan or an error describing missing, conflicting, or cyclic deps.

func ResolveDependencyPlanWithBlocked

func ResolveDependencyPlanWithBlocked(
	targetID, targetVersion string,
	env HostEnv,
	catalog map[string]RegistryPackage,
	blocked map[string]RegistryBlocked,
) (*DependencyPlan, error)

ResolveDependencyPlanWithBlocked resolves the transitive dependency tree while enforcing registry blocklist rules on the target and all transitive dependencies.

type DependencyStep

type DependencyStep struct {
	ID          string            `json:"id"`
	Version     string            `json:"version"`
	ArtifactKey string            `json:"artifactKey,omitempty"`
	Artifact    *RegistryArtifact `json:"artifact,omitempty"`
}

DependencyStep is one plugin version to install in topological order.

type DocCollection

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

DocCollection queries and mutates one plugin document collection via slot columns.

func (*DocCollection) Count

func (c *DocCollection) Count(ctx context.Context, filter map[string]any) (int64, error)

Count counts documents matching filter (all filter fields must be indexed).

func (*DocCollection) DeleteOne

func (c *DocCollection) DeleteOne(ctx context.Context, filter map[string]any) (bool, error)

DeleteOne deletes the first matching document and returns whether one was deleted.

func (*DocCollection) Find

func (c *DocCollection) Find(ctx context.Context, filter map[string]any, opts FindOpts) (*FindResult, error)

Find executes an indexed query with cursor pagination and indexed sorting.

func (*DocCollection) FindOne

func (c *DocCollection) FindOne(ctx context.Context, filter map[string]any) (map[string]any, error)

FindOne returns the first matching document or nil.

func (*DocCollection) InsertOne

func (c *DocCollection) InsertOne(ctx context.Context, doc map[string]any) (map[string]any, error)

InsertOne inserts a document, extracting indexed fields into u1..t2 and returning ErrUniqueConstraint on u1/u2 collisions.

func (*DocCollection) UpdateMany

func (c *DocCollection) UpdateMany(ctx context.Context, filter, patch map[string]any) (int, error)

UpdateMany updates all matching documents (up to 1000 per call) and returns count.

func (*DocCollection) UpdateOne

func (c *DocCollection) UpdateOne(ctx context.Context, filter, patch map[string]any) (bool, error)

UpdateOne updates the first matching document and returns whether one matched.

type DocStore

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

DocStore manages all declared collections for a single plugin on plugin_docs.

func NewDocStore

func NewDocStore(pluginID string, client *ent.Client, spec StorageManifest, perms *PermissionSet) (*DocStore, error)

NewDocStore compiles declared collection index mappings for pluginID.

func (*DocStore) Collection

func (ds *DocStore) Collection(name string) (*DocCollection, error)

Collection returns a bound collection handle if declared in manifest.

type Driver

type Driver interface {
	Init(ctx context.Context, cfg DriverInitConfig) (*DriverRegistrations, error)
	Lifecycle(ctx context.Context, method string, payload any) error
	InvokeGuard(ctx context.Context, handlerID, hookName string, payload any) error
	InvokeFilter(ctx context.Context, handlerID, hookName string, value, payload any) (any, error)
	InvokeEvent(ctx context.Context, handlerID, hookName string, payload any) error
	InvokeHTTP(ctx context.Context, handlerID string, req map[string]any) (any, error)
	InvokeCron(ctx context.Context, handlerID, jobName string) error
	InvokeService(ctx context.Context, handlerID, serviceName, callerID string, args ...any) (any, error)
	InvokeExtension(ctx context.Context, kind, id, handlerID string, args ...any) (any, error)
	NotifySettings(ctx context.Context, newSettings map[string]any) error
	ProxyHandler() http.Handler
	Stats() DriverStats
	DrainAndClose(timeout time.Duration) error
}

Driver abstracts backend plugin execution across Tier 1 (QuickJS-NG/WASM) and Tier 2 (hashicorp/go-plugin native OS subprocess with bidirectional gRPC).

type DriverInitConfig

type DriverInitConfig struct {
	Runtime    *pluginRuntime
	Settings   map[string]any
	DBConfig   *PluginDBConfig
	DataDir    string
	RuntimeDir string
}

DriverInitConfig passes host-resolved runtime context into Driver.Init.

type DriverRegistrations

type DriverRegistrations struct {
	Hooks               []hookBinding
	Routes              []routeBinding
	AuthProviders       []authProviderBinding
	PasswordVerifiers   []passwordVerifierBinding
	CaptchaProviders    []captchaBinding
	CDNProviders        []cdnBinding
	YggdrasilMetas      []yggMetaBinding
	Crons               []cronBinding
	Services            []serviceBinding
	HasSettingsOnChange bool
	StorageProvider     storage.Store
	SearchProvider      texture.SearchProvider
	RenderProvider      render.Provider
}

DriverRegistrations captures every hook, route, cron job, service, extension, and native infrastructure provider declared by a plugin during Init.

type DriverStats

type DriverStats struct {
	Runtime string          `json:"runtime"` // "js" | "native"
	Pool    *jsrt.PoolStats `json:"pool,omitempty"`
	Native  *NativeStats    `json:"native,omitempty"`
}

DriverStats reports runtime-specific health and execution telemetry.

type EnginesSpec

type EnginesSpec struct {
	Skinloom string `json:"skinloom,omitempty"`
	Go       string `json:"go,omitempty"`
}

type FetchRequest

type FetchRequest struct {
	Method  string            `json:"method,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    string            `json:"body,omitempty"`
	Timeout int               `json:"timeoutMs,omitempty"`
}

FetchRequest models JS ctx.fetch(url, init) options.

type FetchResponse

type FetchResponse struct {
	OK         bool              `json:"ok"`
	Status     int               `json:"status"`
	StatusText string            `json:"statusText"`
	Headers    map[string]string `json:"headers"`
	URL        string            `json:"url"`
	BodyText   string            `json:"bodyText"`
	BodyBase64 string            `json:"bodyBase64"`
}

FetchResponse is returned back into the JS sandbox.

type Fetcher

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

Fetcher executes SSRF-hardened outbound HTTP requests for one plugin.

func NewFetcher

func NewFetcher(allowHosts []string, perms *PermissionSet) *Fetcher

NewFetcher creates an SSRF-safe outbound fetcher scoped to allowHosts.

func (*Fetcher) Fetch

func (f *Fetcher) Fetch(ctx context.Context, rawURL string, opts FetchRequest) (*FetchResponse, error)

Fetch performs a guarded outbound HTTP call subject to http.fetch, allowlist, SSRF IP filtering, timeout, and 5 MiB response cap.

type FileStore

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

FileStore isolates plugin-private files under <dataDir>/plugins-data/<id>/files/ with path traversal guards, symlink refusal, and total byte quota enforcement. Keeping public/private files inside a dedicated files/ subdirectory isolates them from native plugin SQLite databases (plugin.db) and internal DataDir state.

func NewFileStore

func NewFileStore(pluginID, dataDir string, maxBytes int64, perms *PermissionSet) *FileStore

NewFileStore constructs a plugin-scoped file store isolated under <dataDir>/plugins-data/<id>/files/.

func (*FileStore) Delete

func (f *FileStore) Delete(_ context.Context, key string) (bool, error)

Delete removes a file by key.

func (*FileStore) Get

func (f *FileStore) Get(_ context.Context, key string) ([]byte, error)

Get reads data for key from the plugin's private file space.

func (*FileStore) Put

func (f *FileStore) Put(_ context.Context, key string, data []byte) (string, error)

Put writes data to the plugin's private file space and returns its public asset path.

func (*FileStore) URL

func (f *FileStore) URL(key string) (string, error)

URL returns the public HTTP asset path for a private file key.

type FindOpts

type FindOpts struct {
	Sort   map[string]int `json:"sort,omitempty"` // field -> 1 (asc) | -1 (desc)
	Limit  int            `json:"limit,omitempty"`
	Cursor string         `json:"cursor,omitempty"`
}

FindOpts configures pagination and indexed sorting for Find.

type FindResult

type FindResult struct {
	Items      []map[string]any `json:"items"`
	NextCursor string           `json:"nextCursor,omitempty"`
}

FindResult is a page of documents returned by Find.

type FormDef

type FormDef struct {
	Name        string        `json:"name"`
	Type        string        `json:"type"`
	Label       LocalizedText `json:"label"`
	Description LocalizedText `json:"description,omitempty"`
	Placeholder LocalizedText `json:"placeholder,omitempty"`
	Required    bool          `json:"required,omitempty"`
	MaxLength   int           `json:"maxLength,omitempty"`
	Options     []string      `json:"options,omitempty"`
}

type FrontendBlock

type FrontendBlock struct {
	Type         string         `json:"type"`
	Label        string         `json:"label,omitempty"`
	DefaultProps map[string]any `json:"defaultProps,omitempty"`
}

FrontendBlock describes one custom homepage block declared by a plugin.

type FrontendFormField

type FrontendFormField struct {
	Name        string   `json:"name"`
	Type        string   `json:"type"`
	Label       string   `json:"label"`
	Description string   `json:"description,omitempty"`
	Placeholder string   `json:"placeholder,omitempty"`
	Required    bool     `json:"required,omitempty"`
	MaxLength   int      `json:"maxLength,omitempty"`
	Options     []string `json:"options,omitempty"`
}

FrontendFormField is one localized form field appended by a plugin for a host form scope.

type FrontendMenu

type FrontendMenu struct {
	Area  string `json:"area"`
	Path  string `json:"path"`
	Title string `json:"title"`
	Icon  string `json:"icon,omitempty"`
	Order int    `json:"order"`
	Role  string `json:"role,omitempty"`
}

FrontendMenu is one localized navigation contribution declared by an active plugin.

type FrontendPlugin

type FrontendPlugin struct {
	ID        string                         `json:"id"`
	Kind      string                         `json:"kind"`
	Version   string                         `json:"version"`
	Rev       string                         `json:"rev"`
	Name      string                         `json:"name"`
	Entry     string                         `json:"entry,omitempty"`
	Style     string                         `json:"style,omitempty"`
	Slots     []string                       `json:"slots,omitempty"`
	Menus     []FrontendMenu                 `json:"menus,omitempty"`
	Forms     map[string][]FrontendFormField `json:"forms,omitempty"`
	Blocks    []FrontendBlock                `json:"blocks,omitempty"`
	Settings  map[string]any                 `json:"settings,omitempty"`
	Messages  map[string]string              `json:"messages,omitempty"`
	Overrides []string                       `json:"overrides,omitempty"`
}

FrontendPlugin summarizes everything the frontend runtime needs for one active plugin.

type HTTPManifest

type HTTPManifest struct {
	Allow        []string `json:"allow,omitempty"`
	MaxBodyBytes int64    `json:"maxBodyBytes,omitempty"`
}

type HooksManifest

type HooksManifest struct {
	Guard  []string `json:"guard,omitempty"`
	Filter []string `json:"filter,omitempty"`
	Event  []string `json:"event,omitempty"`
}

type HostEnv

type HostEnv struct {
	OS                    string            `json:"os"`
	Arch                  string            `json:"arch"`
	SkinloomVersion       string            `json:"skinloomVersion"`
	APIVersion            int               `json:"apiVersion"`
	NativeProtocolVersion int               `json:"nativeProtocolVersion"`
	GoVersion             string            `json:"goVersion"`
	Installed             map[string]string `json:"installed,omitempty"`
	AllowDevSkinloom      bool              `json:"-"`
}

HostEnv captures the running SkinLoom node's 5-dimensional compatibility context.

func CurrentHostEnv

func CurrentHostEnv(installed map[string]string) HostEnv

CurrentHostEnv snapshots the local process's environment and installed plugins.

func (HostEnv) Platform

func (e HostEnv) Platform() string

Platform returns "<os>/<arch>".

type InstallOptions

type InstallOptions struct {
	GrantedPermissions []string
	GrantAllDeclared   bool
	AllowUnsigned      bool
	Enable             bool
	Source             string            // "package" | "market" (defaults to "package")
	RegistrySource     string            // optional market registry URL for multi-arch fallback
	PlatformPackages   map[string]string // optional extra platform -> sha256 entries
	ExtraTrustedKeys   []string          // optional registry-scoped public keys
}

InstallOptions controls `.slp` package verification and permission approval during installation.

type JSDriver

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

JSDriver executes Tier 1 TypeScript/JavaScript plugins inside a bounded QuickJS-NG/Wazero isolate pool.

func NewJSDriver

func NewJSDriver(engine jsrt.Engine, bundleCode []byte) *JSDriver

NewJSDriver creates a JSDriver backed by engine for bundleCode.

func (*JSDriver) DrainAndClose

func (d *JSDriver) DrainAndClose(timeout time.Duration) error

func (*JSDriver) Init

func (*JSDriver) InvokeCron

func (d *JSDriver) InvokeCron(ctx context.Context, handlerID, _ string) error

func (*JSDriver) InvokeEvent

func (d *JSDriver) InvokeEvent(ctx context.Context, handlerID, _ string, payload any) error

func (*JSDriver) InvokeExtension

func (d *JSDriver) InvokeExtension(ctx context.Context, kind, _, handlerID string, args ...any) (any, error)

func (*JSDriver) InvokeFilter

func (d *JSDriver) InvokeFilter(ctx context.Context, handlerID, _ string, value, payload any) (any, error)

func (*JSDriver) InvokeGuard

func (d *JSDriver) InvokeGuard(ctx context.Context, handlerID, _ string, payload any) error

func (*JSDriver) InvokeHTTP

func (d *JSDriver) InvokeHTTP(ctx context.Context, handlerID string, req map[string]any) (any, error)

func (*JSDriver) InvokeService

func (d *JSDriver) InvokeService(ctx context.Context, handlerID, _, _ string, args ...any) (any, error)

func (*JSDriver) Lifecycle

func (d *JSDriver) Lifecycle(ctx context.Context, method string, payload any) error

func (*JSDriver) NotifySettings

func (d *JSDriver) NotifySettings(ctx context.Context, newSettings map[string]any) error

func (*JSDriver) ProxyHandler

func (d *JSDriver) ProxyHandler() http.Handler

func (*JSDriver) Stats

func (d *JSDriver) Stats() DriverStats

type KVEntry

type KVEntry struct {
	Key   string `json:"key"`
	Value any    `json:"value"`
}

KVEntry is one item returned by ctx.kv.list.

type KVStore

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

KVStore implements plugin-isolated key/value storage backed by plugin_kv.

func NewKVStore

func NewKVStore(pluginID string, client *ent.Client, maxKeys int, perms *PermissionSet) *KVStore

NewKVStore returns a plugin-scoped KV store guarded by storage.kv permission.

func (*KVStore) Delete

func (s *KVStore) Delete(ctx context.Context, key string) (bool, error)

Delete removes key for this plugin.

func (*KVStore) Get

func (s *KVStore) Get(ctx context.Context, key string) (any, error)

Get returns the decoded JSON value for key, or nil if missing or expired.

func (*KVStore) Incr

func (s *KVStore) Incr(ctx context.Context, key string, delta float64) (float64, error)

Incr atomically increments (or creates) a numeric KV value by delta.

func (*KVStore) List

func (s *KVStore) List(ctx context.Context, prefix string, limit int) ([]KVEntry, error)

List returns non-expired keys matching prefix.

func (*KVStore) Set

func (s *KVStore) Set(ctx context.Context, key string, val any, ttlSeconds float64) error

Set stores a JSON value under key with optional TTL (seconds <= 0 means no expiry).

type LocalizedText

type LocalizedText map[string]string

LocalizedText supports either a plain JSON string ("My Plugin") or a locale map ({"zh-CN": "...", "en": "..."}).

func (LocalizedText) Resolve

func (l LocalizedText) Resolve(locale string) string

Resolve selects the best localized value with en -> zh-CN -> any fallback.

func (*LocalizedText) UnmarshalJSON

func (l *LocalizedText) UnmarshalJSON(data []byte) error

type LogEntry

type LogEntry struct {
	Time    time.Time `json:"time"`
	Level   string    `json:"level"`
	Message string    `json:"message"`
}

LogEntry is one captured line emitted through ctx.log.

type Manager

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

Manager coordinates plugin installation, two-phase atomic activation, hot enable/disable/uninstall, HTTP route dispatch, static assets, and circuit breaking.

func NewManager

func NewManager(deps ManagerDeps) (*Manager, error)

NewManager creates a plugin manager. If deps.Engine is nil, a dedicated jsrt engine is initialized.

func (*Manager) AllowUnsignedNative

func (m *Manager) AllowUnsignedNative() bool

AllowUnsignedNative reports whether dev-mode unsigned native plugins are permitted.

func (*Manager) AssetHandler

func (m *Manager) AssetHandler() http.Handler

AssetHandler serves static assets under /plugins-assets/{id}/{rev?}/... and plugin-private written files under /plugins-assets/{id}/_files/{key...}.

func (*Manager) CallService

func (m *Manager) CallService(ctx context.Context, callerID, targetID, svcName string, args ...any) (any, error)

CallService invokes an exported service method on another active plugin (ctx.services.use).

func (*Manager) Disable

func (m *Manager) Disable(ctx context.Context, id string) error

Disable atomically removes the plugin from the hook bus and route table, runs onDisable, and drains in-flight JS executions.

func (*Manager) Enable

func (m *Manager) Enable(ctx context.Context, id string) error

Enable activates an installed plugin cleanly and resets any tripped circuit breaker.

func (*Manager) FrontendPlugins

func (m *Manager) FrontendPlugins(locale string) []FrontendPlugin

FrontendPlugins returns localized frontend metadata and asset URLs for all active plugins sorted deterministically by ID. Secret settings fields are omitted.

func (*Manager) Get

func (m *Manager) Get(ctx context.Context, id string) (*PluginInfo, bool)

Get returns summary info for one installed plugin.

func (*Manager) HasTrustedThemeWeb

func (m *Manager) HasTrustedThemeWeb(themeID string) bool

HasTrustedThemeWeb reports whether themeID is currently enabled as a trusted plugin-managed theme bundle with a web entry.

func (*Manager) InspectPackage

func (m *Manager) InspectPackage(ctx context.Context, pkgBytes []byte, locale string) (*PackageInspectResult, error)

InspectPackage validates an uploaded .slp package and builds a pre-install inspection report.

func (*Manager) InstallPackage

func (m *Manager) InstallPackage(ctx context.Context, pkgBytes []byte, opts InstallOptions) (*PluginInfo, error)

InstallPackage verifies an .slp archive, extracts it cleanly, persists the archive blob in storage.Store for multi-replica sync, and atomically installs/upgrades the plugin or theme.

func (*Manager) List

func (m *Manager) List(ctx context.Context) ([]PluginInfo, error)

List returns all installed plugins sorted by ID without N+1 DB lookups.

func (*Manager) LoadDevJS

func (m *Manager) LoadDevJS(
	ctx context.Context,
	manifestRaw []byte,
	serverJS []byte,
	staticFiles map[string][]byte,
	grantedPerms []string,
	enable bool,
) (*PluginInfo, error)

LoadDevJS loads an unpacked Tier 1 JS plugin or theme during local development (skinloom-plugin dev), enforcing size bounds and theme validation and marking the bundle source as "local".

func (*Manager) LoadDevNative

func (m *Manager) LoadDevNative(
	ctx context.Context,
	manifestRaw []byte,
	files map[string][]byte,
	grantedPerms []string,
	enable bool,
) (*PluginInfo, error)

LoadDevNative writes an unsigned local-development native Go plugin build (binary + web/assets/locales) into a versioned staging directory under <dataDir>/plugins-dev/<id>/<rev>/ and atomically hot-reloads it. Requires Manager.AllowUnsignedNative() (dev mode).

func (*Manager) LoadFromBytes

func (m *Manager) LoadFromBytes(
	ctx context.Context,
	manifestRaw []byte,
	serverJS []byte,
	staticFiles map[string][]byte,
	grantedPerms []string,
	enable bool,
) (*PluginInfo, error)

LoadFromBytes registers an in-memory plugin manifest + JS bundle (+ optional static files like web/index.js or locales/en.json), saves DB state, and activates it atomically.

func (*Manager) LoadFromDir

func (m *Manager) LoadFromDir(ctx context.Context, dir string, enable bool) (*PluginInfo, error)

LoadFromDir loads an unpacked plugin directory from disk, persists its metadata, and optionally enables it atomically.

func (*Manager) PluginSettingsView

func (m *Manager) PluginSettingsView(ctx context.Context, id, locale string) (*PluginSettingsResponse, error)

PluginSettingsView returns the plugin's declared setting fields and redacted stored values.

func (*Manager) Registry

func (m *Manager) Registry() *RegistryClient

Registry returns the manager's RegistryClient, initializing it lazily if needed.

func (*Manager) ReloadPlugin

func (m *Manager) ReloadPlugin(ctx context.Context, id string) (*PluginInfo, error)

ReloadPlugin reloads a plugin or theme cleanly from disk or shared storage.

func (*Manager) ServePluginAPI

func (m *Manager) ServePluginAPI(w http.ResponseWriter, r *http.Request, id, subpath string, viewer Viewer, locale string)

ServePluginAPI dispatches HTTP requests arriving under /api/plugins/{id}/*.

func (*Manager) SetPlatformPackageFetcher

func (m *Manager) SetPlatformPackageFetcher(fn PlatformPackageFetcher)

SetPlatformPackageFetcher installs or replaces the callback used by multi-arch SyncCluster to fetch missing architecture packages from a plugin's registry_source.

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown drains all active plugin pools and closes the owned jsrt engine.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context) error

Start scans DB-registered plugins and themes, pulls missing packages from Store, and activates enabled items in dependency order.

func (*Manager) SyncCluster

func (m *Manager) SyncCluster(ctx context.Context) error

SyncCluster reconciles this node's in-memory runtimes and local extracted bundles with the shared DB `plugins` table and shared package `storage.Store`.

func (*Manager) TriggerCron

func (m *Manager) TriggerCron(ctx context.Context, pluginID, jobName string) error

TriggerCron immediately runs a scheduled cron job on an enabled plugin.

func (*Manager) Uninstall

func (m *Manager) Uninstall(ctx context.Context, id string, purge bool) error

Uninstall disables the plugin, invokes onUninstall, removes bundle metadata, and when purge is true wipes KV, documents, and private files.

func (*Manager) UpdateSettings

func (m *Manager) UpdateSettings(ctx context.Context, id string, next map[string]any) error

UpdateSettings updates a plugin's persisted settings (preserving omitted/redacted secrets), notifies ctx.settings.onChange, and broadcasts a cluster config bump.

type ManagerDeps

type ManagerDeps struct {
	DB                     *ent.Client
	Bus                    *hook.Bus
	Settings               *settings.Service
	Accounts               *account.Service
	Players                *player.Service
	Textures               *texture.Service
	Renders                *render.Service
	Notify                 *notify.Service
	Mailer                 *mail.Mailer
	Captcha                *captcha.Service
	CDN                    *cdn.Service
	Yggdrasil              *yggdrasil.Service
	Store                  storage.Store
	StorageHook            *storage.SwappableStore
	Themes                 *theme.Registry
	Engine                 jsrt.Engine
	DBAllocator            *DBAllocator
	DataDir                string
	HostPlatform           string // optional override (defaults to runtime.GOOS+"/"+runtime.GOARCH)
	TrustedPublicKeys      []string
	AllowUnsignedNative    bool
	NativeDriverFactory    func(manifest *Manifest, dir string) Driver
	PlatformPackageFetcher PlatformPackageFetcher
	Log                    *slog.Logger
}

ManagerDeps injects host services required by the plugin runtime.

type Manifest

type Manifest struct {
	Schema      string        `json:"$schema,omitempty"`
	ID          string        `json:"id"`
	Kind        string        `json:"kind"`              // "plugin" | "theme"
	Runtime     string        `json:"runtime,omitempty"` // "js" (default) | "native"
	Version     string        `json:"version"`
	Name        LocalizedText `json:"name"`
	Description LocalizedText `json:"description,omitempty"`
	Authors     []string      `json:"authors,omitempty"`
	License     string        `json:"license,omitempty"`
	Homepage    string        `json:"homepage,omitempty"`
	Repository  string        `json:"repository,omitempty"`
	Icon        string        `json:"icon,omitempty"`
	Screenshot  string        `json:"screenshot,omitempty"`
	Extends     string        `json:"extends,omitempty"`
	Engines     EnginesSpec   `json:"engines,omitempty"`
	APIVersion  int           `json:"apiVersion"`

	Server               string               `json:"server,omitempty"`
	Native               *NativeSpec          `json:"native,omitempty"`
	Web                  string               `json:"web,omitempty"`
	Permissions          []string             `json:"permissions,omitempty"`
	HTTP                 HTTPManifest         `json:"http,omitempty"`
	Hooks                HooksManifest        `json:"hooks,omitempty"`
	Routes               RoutesManifest       `json:"routes,omitempty"`
	Storage              StorageManifest      `json:"storage,omitempty"`
	Settings             map[string]any       `json:"settings,omitempty"`
	Menus                []MenuDef            `json:"menus,omitempty"`
	Forms                map[string][]FormDef `json:"forms,omitempty"`
	Blocks               map[string]any       `json:"blocks,omitempty"`
	Slots                []string             `json:"slots,omitempty"`
	Dependencies         map[string]string    `json:"dependencies,omitempty"`
	OptionalDependencies map[string]string    `json:"optionalDependencies,omitempty"`
	Services             []string             `json:"services,omitempty"`
	Theme                json.RawMessage      `json:"theme,omitempty"`
}

Manifest models plugin.json for both plugins and themes (docs/design/05 §3).

func ParseManifest

func ParseManifest(raw []byte) (*Manifest, error)

ParseManifest parses and validates plugin.json bytes strictly.

func (*Manifest) EffectivePermissions

func (m *Manifest) EffectivePermissions() []string

EffectivePermissions returns declared permissions, implicitly appending PermNativeExec ("native.exec") for native runtime plugins so every UI/policy check highlights native OS subprocess execution as high risk.

func (*Manifest) EffectiveQuotas

func (m *Manifest) EffectiveQuotas() QuotaSpec

EffectiveLimits returns resolved storage quotas bounded by system caps.

func (*Manifest) EffectiveRuntime

func (m *Manifest) EffectiveRuntime() string

EffectiveRuntime returns "native" or "js" (default when omitted).

func (*Manifest) HasDependency

func (m *Manifest) HasDependency(id string) bool

HasDependency reports whether id is listed in dependencies or optionalDependencies.

func (*Manifest) HasHook

func (m *Manifest) HasHook(kind hook.Kind, name string) bool

HasHook reports whether name was declared under the given hook kind.

func (*Manifest) NativeExecutableCandidates

func (m *Manifest) NativeExecutableCandidates(goos, goarch string) []string

NativeExecutableCandidates returns ordered relative paths to search inside a native plugin bundle for the given target GOOS/GOARCH.

func (*Manifest) ResolveNativeExecutable

func (m *Manifest) ResolveNativeExecutable(dir, goos, goarch string) (string, error)

ResolveNativeExecutable locates the native plugin binary on disk under dir for the given GOOS/GOARCH while enforcing directory containment.

func (*Manifest) Validate

func (m *Manifest) Validate() error

Validate checks manifest invariants across identifiers, API version, entry paths, permissions, hooks, allowlists, and doc collection slot limits.

type MarketDependencyInspectItem

type MarketDependencyInspectItem struct {
	ID                      string           `json:"id"`
	Name                    string           `json:"name"`
	Version                 string           `json:"version"`
	Runtime                 string           `json:"runtime"`
	Official                bool             `json:"official"`
	Permissions             PermissionGroups `json:"permissions"`
	RequiresHighRiskConfirm bool             `json:"requiresHighRiskConfirm"`
}

MarketDependencyInspectItem summarizes a transitive dependency that will be cascade-installed.

type MarketFilter

type MarketFilter struct {
	Query          string
	Kind           string // "" | "all" | "plugin" | "theme"
	Runtime        string // "" | "all" | "js" | "native"
	Category       string // "" | "all" | "recommended" | "official" | "security" | "score" | "migration" | "theme" | ...
	CompatibleOnly bool
	Locale         string
	ForceRefresh   bool
}

MarketFilter specifies search and filter criteria for listing market packages.

type MarketHostEnv

type MarketHostEnv struct {
	OS                    string `json:"os"`
	Arch                  string `json:"arch"`
	Platform              string `json:"platform"`
	SkinloomVersion       string `json:"skinloomVersion"`
	GoVersion             string `json:"goVersion"`
	APIVersion            int    `json:"apiVersion"`
	NativeProtocolVersion int    `json:"nativeProtocolVersion"`
	AllowUnsignedNative   bool   `json:"allowUnsignedNative"`
}

MarketHostEnv summarizes the running SkinLoom server's environment for market filtering.

type MarketInspectRequest

type MarketInspectRequest struct {
	RegistryID string `json:"registryId,omitempty"`
	ID         string `json:"id"`
	Version    string `json:"version,omitempty"`
}

MarketInspectRequest identifies a market package and optional version to pre-inspect.

type MarketInspectResult

type MarketInspectResult struct {
	*PackageInspectResult
	RegistryID            string                        `json:"registryId"`
	OfficialRegistry      bool                          `json:"officialRegistry"`
	Compatibility         VersionCompatResult           `json:"compatibility"`
	DependencyPlan        *DependencyPlan               `json:"dependencyPlan,omitempty"`
	DependenciesToInstall []MarketDependencyInspectItem `json:"dependenciesToInstall,omitempty"`
}

MarketInspectResult extends PackageInspectResult with market compatibility and cascade dependency info.

type MarketInstallRequest

type MarketInstallRequest struct {
	RegistryID          string   `json:"registryId,omitempty"`
	ID                  string   `json:"id"`
	Version             string   `json:"version,omitempty"`
	GrantedPermissions  []string `json:"grantedPermissions,omitempty"`
	GrantAll            bool     `json:"grantAll,omitempty"`
	AllowUnsigned       bool     `json:"allowUnsigned,omitempty"`
	Disabled            bool     `json:"disabled,omitempty"`
	InstallDependencies *bool    `json:"installDependencies,omitempty"`
}

MarketInstallRequest specifies a market package to download, verify, and install (with optional cascade dependencies).

type MarketInstallResult

type MarketInstallResult struct {
	Plugin                *PluginInfo   `json:"plugin"`
	InstalledDependencies []*PluginInfo `json:"installedDependencies,omitempty"`
}

MarketInstallResult returns the installed target plugin and any cascade-installed dependencies.

type MarketListResult

type MarketListResult struct {
	HostEnv    MarketHostEnv          `json:"hostEnv"`
	Registries []MarketRegistryStatus `json:"registries"`
	Packages   []MarketPackageView    `json:"packages"`
}

MarketListResult contains the host environment, registry statuses, and filtered market packages.

type MarketPackageView

type MarketPackageView struct {
	RegistryID              string               `json:"registryId"`
	RegistryName            string               `json:"registryName"`
	ID                      string               `json:"id"`
	Kind                    string               `json:"kind"`
	Runtime                 string               `json:"runtime"`
	Category                string               `json:"category,omitempty"`
	Official                bool                 `json:"official"`
	Name                    string               `json:"name"`
	RawName                 LocalizedText        `json:"rawName"`
	Description             string               `json:"description,omitempty"`
	RawDescription          LocalizedText        `json:"rawDescription,omitempty"`
	Authors                 []string             `json:"authors,omitempty"`
	License                 string               `json:"license,omitempty"`
	Homepage                string               `json:"homepage,omitempty"`
	Repository              string               `json:"repository,omitempty"`
	Icon                    string               `json:"icon,omitempty"`
	Latest                  string               `json:"latest"`
	Installed               bool                 `json:"installed"`
	InstalledVersion        string               `json:"installedVersion,omitempty"`
	InstalledStatus         string               `json:"installedStatus,omitempty"`
	UpgradeAvailable        bool                 `json:"upgradeAvailable"`
	Compatibility           PackageCompatSummary `json:"compatibility"`
	RecommendedArtifact     *RegistryArtifact    `json:"recommendedArtifact,omitempty"`
	RecommendedPlatform     string               `json:"recommendedPlatform,omitempty"`
	SupportedPlatforms      []string             `json:"supportedPlatforms,omitempty"`
	Permissions             PermissionGroups     `json:"permissions"`
	RequiresHighRiskConfirm bool                 `json:"requiresHighRiskConfirm"`
	Versions                []MarketVersionView  `json:"versions"`
}

MarketPackageView describes a plugin or theme in the market with resolved host compatibility.

type MarketRefreshResult

type MarketRefreshResult struct {
	HostEnv        MarketHostEnv          `json:"hostEnv"`
	Registries     []MarketRegistryStatus `json:"registries"`
	Packages       []MarketPackageView    `json:"packages"`
	BlockedActions []BlockedPluginAction  `json:"blockedActions,omitempty"`
}

MarketRefreshResult returns the refreshed market state and any blocked plugins that were hot-disabled.

type MarketRegistryStatus

type MarketRegistryStatus struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	Official     bool   `json:"official"`
	Enabled      bool   `json:"enabled"`
	Verified     bool   `json:"verified"`
	ActiveMirror string `json:"activeMirror,omitempty"`
	FetchedAt    string `json:"fetchedAt,omitempty"`
	PackageCount int    `json:"packageCount"`
	Error        string `json:"error,omitempty"`
}

MarketRegistryStatus reports the live status of one configured market registry source.

type MarketVersionView

type MarketVersionView struct {
	Version               string            `json:"version"`
	PublishedAt           string            `json:"publishedAt,omitempty"`
	Yanked                bool              `json:"yanked,omitempty"`
	Changelog             string            `json:"changelog,omitempty"`
	APIVersion            int               `json:"apiVersion"`
	NativeProtocolVersion int               `json:"nativeProtocolVersion,omitempty"`
	Engines               EnginesSpec       `json:"engines,omitempty"`
	Permissions           []string          `json:"permissions,omitempty"`
	Dependencies          map[string]string `json:"dependencies,omitempty"`
	OptionalDependencies  map[string]string `json:"optionalDependencies,omitempty"`
	Platforms             []string          `json:"platforms,omitempty"`
	Compatible            bool              `json:"compatible"`
	Status                string            `json:"status"`
	Issues                []CompatIssue     `json:"issues,omitempty"`
}

MarketVersionView summarizes one published version of a market package and its compatibility.

type MenuDef struct {
	Area  string        `json:"area"` // user | admin | explore
	Path  string        `json:"path"`
	Title LocalizedText `json:"title"`
	Icon  string        `json:"icon,omitempty"`
	Order int           `json:"order,omitempty"`
	Role  string        `json:"role,omitempty"`
}

type NativeDatabaseSpec

type NativeDatabaseSpec struct {
	Required bool `json:"required,omitempty"`
}

NativeDatabaseSpec declares whether a native plugin requests host-isolated SQL storage.

type NativeDriver

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

NativeDriver runs a Tier 2 Go native plugin in an isolated OS child process managed by hashicorp/go-plugin, providing bidirectional gRPC, exponential backoff crash supervision, smooth hot-upgrade draining, and optional local HTTP/WebSocket streaming reverse proxy.

func NewNativeDriver

func NewNativeDriver(opts NativeDriverOptions) *NativeDriver

NewNativeDriver creates a NativeDriver with the given options.

func (*NativeDriver) DrainAndClose

func (d *NativeDriver) DrainAndClose(timeout time.Duration) error

func (*NativeDriver) Init

func (*NativeDriver) InvokeCron

func (d *NativeDriver) InvokeCron(ctx context.Context, handlerID, jobName string) error

func (*NativeDriver) InvokeEvent

func (d *NativeDriver) InvokeEvent(ctx context.Context, handlerID, hookName string, payload any) error

func (*NativeDriver) InvokeExtension

func (d *NativeDriver) InvokeExtension(ctx context.Context, kind, id, handlerID string, args ...any) (any, error)

func (*NativeDriver) InvokeFilter

func (d *NativeDriver) InvokeFilter(ctx context.Context, handlerID, hookName string, value, payload any) (any, error)

func (*NativeDriver) InvokeGuard

func (d *NativeDriver) InvokeGuard(ctx context.Context, handlerID, hookName string, payload any) error

func (*NativeDriver) InvokeHTTP

func (d *NativeDriver) InvokeHTTP(ctx context.Context, handlerID string, req map[string]any) (any, error)

func (*NativeDriver) InvokeService

func (d *NativeDriver) InvokeService(ctx context.Context, handlerID, serviceName, callerID string, args ...any) (any, error)

func (*NativeDriver) Lifecycle

func (d *NativeDriver) Lifecycle(ctx context.Context, method string, payload any) error

func (*NativeDriver) NotifySettings

func (d *NativeDriver) NotifySettings(ctx context.Context, newSettings map[string]any) error

func (*NativeDriver) ProxyHandler

func (d *NativeDriver) ProxyHandler() http.Handler

ProxyHandler returns an HTTP/WebSocket streaming ReverseProxy handler backed by the active native plugin's local Unix socket / loopback listener, or nil when httpProxy is disabled.

func (*NativeDriver) Stats

func (d *NativeDriver) Stats() DriverStats

type NativeDriverOptions

type NativeDriverOptions struct {
	Executable     string // optional override; otherwise resolved from manifest.native.executable
	ExtraArgs      []string
	ExtraEnv       []string
	HealthInterval time.Duration
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
}

NativeDriverOptions tunes subprocess launch and crash supervision behavior.

type NativeGRPCPlugin

type NativeGRPCPlugin struct {
	hplugin.NetRPCUnsupportedPlugin
	Impl *NativeServerImpl
}

NativeGRPCPlugin implements hashicorp/go-plugin's GRPCPlugin for SkinLoom Tier 2 plugins.

func (*NativeGRPCPlugin) GRPCClient

func (p *NativeGRPCPlugin) GRPCClient(_ context.Context, broker *hplugin.GRPCBroker, cc *grpc.ClientConn) (any, error)

func (*NativeGRPCPlugin) GRPCServer

func (p *NativeGRPCPlugin) GRPCServer(broker *hplugin.GRPCBroker, s *grpc.Server) error

type NativeServerImpl

NativeServerImpl groups the gRPC server implementations hosted inside a native plugin process.

type NativeSpec

type NativeSpec struct {
	ProtocolVersion int                 `json:"protocolVersion"`
	Executable      string              `json:"executable"`
	Platforms       []string            `json:"platforms,omitempty"`
	HTTPProxy       bool                `json:"httpProxy,omitempty"`
	Database        *NativeDatabaseSpec `json:"database,omitempty"`
}

NativeSpec declares native Go subprocess execution details for runtime == "native".

type NativeStats

type NativeStats struct {
	PID            int       `json:"pid"`
	Running        bool      `json:"running"`
	StartedAt      time.Time `json:"startedAt,omitempty"`
	UptimeSeconds  int64     `json:"uptimeSeconds"`
	Restarts       int       `json:"restarts"`
	MemoryRSSBytes uint64    `json:"memoryRssBytes,omitempty"`
	HTTPProxy      bool      `json:"httpProxy,omitempty"`
	DBDriver       string    `json:"dbDriver,omitempty"`
	DBPrefix       string    `json:"dbPrefix,omitempty"`
}

NativeStats reports OS subprocess telemetry for Tier 2 native Go plugins.

type PackageCompatSummary

type PackageCompatSummary struct {
	Compatible         bool                 `json:"compatible"`
	Status             string               `json:"status"`
	RecommendedVersion string               `json:"recommendedVersion,omitempty"`
	Recommended        *VersionCompatResult `json:"recommended,omitempty"`
	InstalledVersion   string               `json:"installedVersion,omitempty"`
	UpgradeAvailable   bool                 `json:"upgradeAvailable,omitempty"`
	SupportedPlatforms []string             `json:"supportedPlatforms,omitempty"`
	Issues             []CompatIssue        `json:"issues,omitempty"`
}

PackageCompatSummary captures the best installable version and overall compatibility for a package.

func SelectBestVersion

func SelectBestVersion(
	pkg RegistryPackage,
	env HostEnv,
	catalog map[string]RegistryPackage,
	blocked map[string]RegistryBlocked,
) PackageCompatSummary

SelectBestVersion evaluates all releases of pkg (highest SemVer first) and returns the best compatible version, upgrade availability, and platform summary.

type PackageInspectResult

type PackageInspectResult struct {
	ID                      string              `json:"id"`
	Kind                    string              `json:"kind"`
	Runtime                 string              `json:"runtime"`
	Version                 string              `json:"version"`
	Name                    string              `json:"name"`
	Description             string              `json:"description,omitempty"`
	Authors                 []string            `json:"authors,omitempty"`
	Homepage                string              `json:"homepage,omitempty"`
	IsUpgrade               bool                `json:"isUpgrade"`
	CurrentVersion          string              `json:"currentVersion,omitempty"`
	HasServer               bool                `json:"hasServer"`
	HasWeb                  bool                `json:"hasWeb"`
	RoutesCount             int                 `json:"routesCount"`
	HooksCount              int                 `json:"hooksCount"`
	Slots                   []string            `json:"slots,omitempty"`
	SettingsCount           int                 `json:"settingsCount"`
	Dependencies            map[string]string   `json:"dependencies,omitempty"`
	HostPlatform            string              `json:"hostPlatform"`
	SupportedPlatforms      []string            `json:"supportedPlatforms,omitempty"`
	PlatformCompatible      bool                `json:"platformCompatible"`
	AllowUnsignedNative     bool                `json:"allowUnsignedNative,omitempty"`
	NativeInstallBlocked    bool                `json:"nativeInstallBlocked,omitempty"`
	NativeBlockReason       string              `json:"nativeBlockReason,omitempty"`
	ArchiveSHA256           string              `json:"archiveSha256"`
	ArchiveBytes            int                 `json:"archiveBytes"`
	Verification            PackageVerification `json:"verification"`
	Permissions             PermissionGroups    `json:"permissions"`
	RequiresHighRiskConfirm bool                `json:"requiresHighRiskConfirm"`
	Warnings                []string            `json:"warnings,omitempty"`
}

PackageInspectResult contains pre-install inspection metadata returned to administrators or the CLI.

type PackageVerification

type PackageVerification struct {
	HasChecksums bool     `json:"hasChecksums"`
	Signed       bool     `json:"signed"`
	Verified     bool     `json:"verified"`
	Trusted      bool     `json:"trusted"`
	Official     bool     `json:"official,omitempty"`
	Signer       string   `json:"signer,omitempty"`
	KeyID        string   `json:"keyId,omitempty"`
	Warnings     []string `json:"warnings,omitempty"`
}

PackageVerification summarizes integrity and Ed25519 signature verification of an .slp package.

type ParsedPackage

type ParsedPackage struct {
	ArchiveSHA256      string
	ArchiveBytes       []byte
	Manifest           *Manifest
	Files              map[string][]byte // normalized regular files excluding checksums.txt and signature
	ServerJS           []byte
	Verification       PackageVerification
	Warnings           []string
	SupportedPlatforms []string // platforms declared and/or present in archive
	ContainedPlatforms []string // platforms whose executable is actually present in this archive
	NativeExecutables  []string // archive-relative paths of native binaries present
	HostCompatible     bool     // true for JS/themes, or when host GOOS/GOARCH executable is present
}

ParsedPackage holds verified, extracted in-memory files from an .slp archive.

func ParsePackage

func ParsePackage(pkgBytes []byte, extraTrustedKeys []string) (*ParsedPackage, error)

ParsePackage safely unpacks, validates size/path bounds, checks SHA-256 checksums, and verifies Ed25519 signatures for an .slp archive against the current host OS/Arch.

func ParsePackageForPlatform

func ParsePackageForPlatform(pkgBytes []byte, extraTrustedKeys []string, hostPlatform string) (*ParsedPackage, error)

ParsePackageForPlatform unpacks and validates an .slp archive while checking Tier 2 native binary presence against hostPlatform (e.g. "linux/amd64").

func (*ParsedPackage) ValidateTheme

func (p *ParsedPackage) ValidateTheme(base *theme.Registry) ([]string, error)

ValidateTheme validates a KindTheme parsed package against theme.Check without touching disk.

type PermissionDef

type PermissionDef struct {
	Name        string   `json:"name"`
	Tier        RiskTier `json:"tier"`
	Description string   `json:"description"`
	NativeOnly  bool     `json:"nativeOnly,omitempty"`
}

PermissionDef describes a known capability permission and its risk tier.

func LookupPermission

func LookupPermission(name string) (PermissionDef, bool)

LookupPermission resolves a declared permission constant and its risk tier.

type PermissionGroups

type PermissionGroups struct {
	Normal    []PermissionItem `json:"normal"`
	Sensitive []PermissionItem `json:"sensitive"`
	HighRisk  []PermissionItem `json:"high_risk"`
}

PermissionGroups partitions a plugin's requested permissions by risk tier.

func ClassifyPermissions

func ClassifyPermissions(declared []string, prevDeclared []string, prevGranted []string, isUpgrade bool) (PermissionGroups, bool)

ClassifyPermissions groups requested manifest permissions by risk tier and upgrade state.

type PermissionItem

type PermissionItem struct {
	Name        string   `json:"name"`
	Tier        RiskTier `json:"tier"`
	Description string   `json:"description"`
	Granted     bool     `json:"granted,omitempty"`
	Added       bool     `json:"added,omitempty"`
}

PermissionItem describes one permission requested by a plugin package.

type PermissionSet

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

PermissionSet tracks both declared (manifest.permissions) and runtime-granted permissions for a plugin instance.

func NewPermissionSet

func NewPermissionSet(declared, granted []string) *PermissionSet

NewPermissionSet creates a PermissionSet. If granted is nil, declared permissions default to granted (local/auto-approved development loading); otherwise runtime requires perm in BOTH declared and granted.

func (*PermissionSet) Check

func (ps *PermissionSet) Check(perm string) error

Check verifies perm is both declared and granted, returning ErrPermissionDenied if not.

func (*PermissionSet) Has

func (ps *PermissionSet) Has(perm string) bool

Has reports whether perm is enabled for this plugin.

type PlatformPackageFetcher

type PlatformPackageFetcher func(ctx context.Context, registrySource, pluginID, version, platform string) ([]byte, error)

PlatformPackageFetcher downloads a platform-specific .slp archive from a registry source during multi-arch SyncCluster when the shared storage.Store does not yet contain a package for this node's GOOS/GOARCH.

type PluginDBConfig

type PluginDBConfig struct {
	Driver string `json:"driver"` // "sqlite" | "mysql" | "postgres"
	DSN    string `json:"dsn"`
	Prefix string `json:"prefix"` // "plg_<safe_id>_"
	Schema string `json:"schema,omitempty"`
}

PluginDBConfig holds the isolated relational database connection details and mandatory table prefix handed to a Tier 2 native plugin during Init.

type PluginDriver

type PluginDriver = Driver

PluginDriver is an alias for Driver matching the dual-tier architecture design doc.

type PluginInfo

type PluginInfo struct {
	ID                 string            `json:"id"`
	Kind               string            `json:"kind"`
	Runtime            string            `json:"runtime,omitempty"`
	Version            string            `json:"version"`
	Status             string            `json:"status"`
	Error              string            `json:"error,omitempty"`
	Source             string            `json:"source"`
	RegistrySource     string            `json:"registrySource,omitempty"`
	PackageSHA256      string            `json:"packageSha256,omitempty"`
	PlatformPackages   map[string]string `json:"platformPackages,omitempty"`
	GrantedPermissions []string          `json:"grantedPermissions"`
	Settings           map[string]any    `json:"settings,omitempty"`
	Manifest           *Manifest         `json:"manifest,omitempty"`
	Routes             []routeBinding    `json:"routes,omitempty"`
	Stats              *jsrt.PoolStats   `json:"stats,omitempty"`
	NativeStats        *NativeStats      `json:"nativeStats,omitempty"`
	Usage              *PluginUsage      `json:"usage,omitempty"`
	RecentLogs         []LogEntry        `json:"recentLogs,omitempty"`
	CircuitTripped     bool              `json:"circuitTripped,omitempty"`
	ConsecutiveErrors  int               `json:"consecutiveErrors,omitempty"`
}

PluginInfo summarizes an installed plugin's manifest and live runtime state.

type PluginSettingFieldView

type PluginSettingFieldView struct {
	Key         string         `json:"key"`
	Type        string         `json:"type"`
	Label       string         `json:"label,omitempty"`
	Description string         `json:"description,omitempty"`
	Value       any            `json:"value"`
	Default     any            `json:"default,omitempty"`
	IsSet       bool           `json:"isSet"`
	Secret      bool           `json:"secret"`
	Options     []string       `json:"options,omitempty"`
	Required    bool           `json:"required,omitempty"`
	Min         *float64       `json:"min,omitempty"`
	Max         *float64       `json:"max,omitempty"`
	Step        *float64       `json:"step,omitempty"`
	Order       int            `json:"order,omitempty"`
	Fields      map[string]any `json:"fields,omitempty"`
	Item        map[string]any `json:"item,omitempty"`
}

PluginSettingFieldView describes one declared plugin setting field and its redacted value.

type PluginSettingsResponse

type PluginSettingsResponse struct {
	PluginID string                   `json:"pluginId"`
	Fields   []PluginSettingFieldView `json:"fields"`
	Values   map[string]any           `json:"values"`
}

PluginSettingsResponse returns ordered setting schema definitions alongside redacted stored values.

type PluginUsage

type PluginUsage struct {
	KVKeys     int   `json:"kvKeys"`
	Docs       int   `json:"docs"`
	FilesBytes int64 `json:"filesBytes"`
}

PluginUsage summarizes persistent storage currently used by a plugin.

type QuotaSpec

type QuotaSpec struct {
	KVKeys     int   `json:"kvKeys,omitempty"`
	Docs       int   `json:"docs,omitempty"`
	FilesBytes int64 `json:"filesBytes,omitempty"`
}

type RegistryArtifact

type RegistryArtifact struct {
	URLs      []string `json:"urls"`
	SHA256    string   `json:"sha256"`
	Size      int64    `json:"size"`
	Signature string   `json:"signature,omitempty"`
}

RegistryArtifact describes one downloadable platform .slp archive in index.v1.json.

type RegistryBlocked

type RegistryBlocked struct {
	ID       string `json:"id"`
	Versions string `json:"versions,omitempty"` // SemVer range or "*" / empty for all versions
	Reason   string `json:"reason"`
}

RegistryBlocked describes a malicious/revoked package entry in index.v1.json.

func (RegistryBlocked) MatchesVersion

func (b RegistryBlocked) MatchesVersion(version string) bool

MatchesVersion reports whether this block rule applies to version.

type RegistryClient

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

RegistryClient manages multi-source index fetching, Ed25519 signature verification, 15-minute memory/disk caching, 5-dimensional compatibility filtering, blocked-plugin enforcement, and failover artifact downloading.

func NewRegistryClient

func NewRegistryClient(mgr *Manager) *RegistryClient

NewRegistryClient creates a RegistryClient bound to mgr.

func (*RegistryClient) ConfiguredRegistries

func (c *RegistryClient) ConfiguredRegistries() []settings.RegistrySource

ConfiguredRegistries returns the list of configured registry sources from site settings (falling back to DefaultPluginRegistries).

func (*RegistryClient) EnforceBlockedPlugins

func (c *RegistryClient) EnforceBlockedPlugins(ctx context.Context) ([]BlockedPluginAction, error)

EnforceBlockedPlugins checks all installed plugins against signature-verified registry blocklists. Any enabled plugin matching a block rule is immediately hot-disabled, recorded in AuditLog, and reported to all superadmins via in-app notification.

func (*RegistryClient) FetchAllIndexes

func (c *RegistryClient) FetchAllIndexes(ctx context.Context, forceRefresh bool) (
	entries []*CachedRegistryIndex,
	statuses []MarketRegistryStatus,
	catalog map[string]RegistryPackage,
	blocked map[string]RegistryBlocked,
	blockedSource map[string]string,
)

FetchAllIndexes fetches all configured and enabled registries, returning their statuses, merged catalog, and verified blocklist rules.

func (*RegistryClient) FetchPlatformPackage

func (c *RegistryClient) FetchPlatformPackage(
	ctx context.Context,
	registrySource, pluginID, version, platform string,
) ([]byte, error)

FetchPlatformPackage implements PlatformPackageFetcher so multi-architecture cluster nodes can automatically download and verify their own GOOS/GOARCH .slp package from the market registry during SyncCluster.

func (*RegistryClient) FetchSourceIndex

func (c *RegistryClient) FetchSourceIndex(ctx context.Context, src settings.RegistrySource, forceRefresh bool) (*CachedRegistryIndex, error)

FetchSourceIndex fetches, verifies, and caches index.v1.json for a single RegistrySource.

func (*RegistryClient) HostEnv

func (c *RegistryClient) HostEnv(ctx context.Context) (HostEnv, map[string]string)

HostEnv builds the 5-dimensional HostEnv snapshot including all installed plugins/themes.

func (*RegistryClient) InspectFromMarket

func (c *RegistryClient) InspectFromMarket(ctx context.Context, req MarketInspectRequest, locale string) (*MarketInspectResult, error)

InspectFromMarket downloads the host-compatible .slp artifact for a market package, verifies its SHA-256 and Ed25519 signature, runs InspectPackage, and resolves cascade dependencies.

func (*RegistryClient) InstallFromMarket

func (c *RegistryClient) InstallFromMarket(ctx context.Context, req MarketInstallRequest) (*MarketInstallResult, error)

InstallFromMarket resolves any missing cascade dependencies, downloads and verifies each required .slp package from the market, and installs/upgrades them in topological order.

func (*RegistryClient) ListPackages

func (c *RegistryClient) ListPackages(ctx context.Context, filter MarketFilter) (*MarketListResult, error)

ListPackages fetches market indexes and evaluates 5-dimensional compatibility and filters.

func (*RegistryClient) MarketHostEnvSummary

func (c *RegistryClient) MarketHostEnvSummary(ctx context.Context) MarketHostEnv

MarketHostEnvSummary returns the serializable host environment summary for API/UI responses.

func (*RegistryClient) RefreshAndEnforce

func (c *RegistryClient) RefreshAndEnforce(ctx context.Context, locale string) (*MarketRefreshResult, error)

RefreshAndEnforce forces a market index refresh across all enabled registries and immediately executes the blocked-plugin check.

func (*RegistryClient) SetCacheTTL

func (c *RegistryClient) SetCacheTTL(ttl time.Duration)

SetCacheTTL overrides the index cache TTL (default 15 minutes).

func (*RegistryClient) SetHTTPClient

func (c *RegistryClient) SetHTTPClient(hc *http.Client)

SetHTTPClient overrides the HTTP client used for registry and artifact requests.

func (*RegistryClient) SetOfficialPublicKey

func (c *RegistryClient) SetOfficialPublicKey(pubKeySpec string)

SetOfficialPublicKey overrides the built-in official Ed25519 public key (used by unit/E2E tests).

func (*RegistryClient) SetPatrolInterval

func (c *RegistryClient) SetPatrolInterval(d time.Duration)

SetPatrolInterval overrides the periodic blocked-plugin patrol interval (default 6 hours).

func (*RegistryClient) SetRegistriesForTest

func (c *RegistryClient) SetRegistriesForTest(sources []settings.RegistrySource)

SetRegistriesForTest overrides the configured registry sources when settings.Service is not wired.

func (*RegistryClient) StartPatrolLoop

func (c *RegistryClient) StartPatrolLoop()

StartPatrolLoop launches the periodic (default 6h) background check for blocked plugins.

func (*RegistryClient) StopPatrolLoop

func (c *RegistryClient) StopPatrolLoop()

StopPatrolLoop stops the periodic blocked-plugin patrol goroutine and waits for it to exit.

type RegistryIndex

type RegistryIndex struct {
	SchemaVersion int               `json:"schemaVersion"`
	GeneratedAt   string            `json:"generatedAt"`
	RegistryID    string            `json:"registryId"`
	Mirrors       []string          `json:"mirrors,omitempty"`
	Packages      []RegistryPackage `json:"packages"`
	Blocked       []RegistryBlocked `json:"blocked,omitempty"`
}

RegistryIndex models the signed index.v1.json document published by a SkinLoom market registry.

type RegistryPackage

type RegistryPackage struct {
	ID          string            `json:"id"`
	Kind        string            `json:"kind"`
	Runtime     string            `json:"runtime,omitempty"` // "js" (default) | "native"
	Category    string            `json:"category,omitempty"`
	Official    bool              `json:"official,omitempty"`
	Name        LocalizedText     `json:"name"`
	Description LocalizedText     `json:"description,omitempty"`
	Authors     []string          `json:"authors,omitempty"`
	License     string            `json:"license,omitempty"`
	Homepage    string            `json:"homepage,omitempty"`
	Repository  string            `json:"repository,omitempty"`
	Icon        string            `json:"icon,omitempty"`
	Latest      string            `json:"latest,omitempty"`
	Versions    []RegistryVersion `json:"versions"`
}

RegistryPackage describes one plugin or theme entry in index.v1.json.

func (RegistryPackage) EffectiveRuntime

func (p RegistryPackage) EffectiveRuntime() string

EffectiveRuntime returns "native" or "js" (default).

type RegistryVersion

type RegistryVersion struct {
	Version               string                      `json:"version"`
	APIVersion            int                         `json:"apiVersion"`
	NativeProtocolVersion int                         `json:"nativeProtocolVersion,omitempty"`
	Engines               EnginesSpec                 `json:"engines,omitempty"`
	Permissions           []string                    `json:"permissions,omitempty"`
	Dependencies          map[string]string           `json:"dependencies,omitempty"`
	OptionalDependencies  map[string]string           `json:"optionalDependencies,omitempty"`
	PublishedAt           string                      `json:"publishedAt,omitempty"`
	Yanked                bool                        `json:"yanked,omitempty"`
	Changelog             string                      `json:"changelog,omitempty"`
	Artifacts             map[string]RegistryArtifact `json:"artifacts"`
}

RegistryVersion describes one published release of a plugin/theme in index.v1.json.

type RiskTier

type RiskTier string

RiskTier classifies plugin permission severity for installation UI and policy checks.

const (
	RiskNormal    RiskTier = "normal"
	RiskSensitive RiskTier = "sensitive"
	RiskHighRisk  RiskTier = "high_risk"
)

type RoutesManifest

type RoutesManifest struct {
	Public []string `json:"public,omitempty"`
}

type Semver

type Semver struct {
	Major      int
	Minor      int
	Patch      int
	Prerelease string
	Build      string
}

Semver represents a parsed semantic version (major.minor.patch[-prerelease][+build]).

func ParseSemver

func ParseSemver(raw string) (Semver, error)

ParseSemver parses standard SemVer strings as well as Go toolchain strings like "go1.26.10", "go1.26", or partial versions like "1.26" (normalized to 1.26.0).

func (Semver) Compare

func (v Semver) Compare(o Semver) int

Compare compares v and o according to SemVer 2.0 precedence rules (ignoring build metadata). Returns -1 if v < o, 0 if v == o, +1 if v > o.

func (Semver) String

func (v Semver) String() string

String formats v in canonical major.minor.patch[-prerelease] form.

type SemverRange

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

SemverRange is a parsed disjunction (||) of conjunctions (AND) of comparators.

func ParseSemverRange

func ParseSemverRange(expr string) (*SemverRange, error)

ParseSemverRange parses npm/Go-style SemVer constraints:

  • "*", "", "x"
  • ">=1.0.0 <2.0.0", ">=1.0.0, <2.0.0"
  • "^1.2.3", "~1.2.3", "1.x", "1.2.*"
  • "1.0.0 - 2.0.0"
  • ">=1.0.0 <2.0.0 || >=3.0.0"

func (*SemverRange) Match

func (r *SemverRange) Match(v Semver) bool

Match reports whether v satisfies the SemVer range. Following SemVer/npm range semantics, a candidate with a prerelease tag only matches a non-empty comparator group when at least one comparator in that group explicitly targets a prerelease with the same major.minor.patch tuple (preventing e.g. ^1.0.0 from accidentally matching breaking 2.0.0-alpha.1 releases).

func (*SemverRange) MatchString

func (r *SemverRange) MatchString(raw string) bool

MatchString parses raw as a Semver and evaluates Match.

func (*SemverRange) String

func (r *SemverRange) String() string

String returns the original expression.

type SlotDef

type SlotDef struct {
	Name        string
	Area        string // site | auth | user | skinlib | admin
	Description string
	Props       []SlotProp
}

SlotDef describes one versioned frontend extension slot rendered by the SkinLoom web app.

func LookupSlot

func LookupSlot(name string) (SlotDef, bool)

LookupSlot looks up a canonical UI slot definition by name.

type SlotProp

type SlotProp struct {
	Name        string
	TypeScript  string // e.g. "number", "'steve' | 'alex' | 'cape'", "string | null"
	Optional    bool
	Description string
}

SlotProp describes one React prop passed by the host to components mounted in a Slot.

type StorageManifest

type StorageManifest struct {
	Collections map[string]CollectionSpec `json:"collections,omitempty"`
	Quota       QuotaSpec                 `json:"quota,omitempty"`
}

type TrustedKey

type TrustedKey struct {
	Fingerprint string            `json:"fingerprint"`
	Label       string            `json:"label"`
	Official    bool              `json:"official,omitempty"`
	PublicKey   ed25519.PublicKey `json:"-"`
}

TrustedKey describes an Ed25519 public key trusted to verify .slp packages.

func ResolveTrustedKeys

func ResolveTrustedKeys(extraSpecs []string) []TrustedKey

ResolveTrustedKeys returns the built-in official key plus any valid configured custom keys.

type UnindexedFieldError

type UnindexedFieldError struct {
	Collection string
	Field      string
}

UnindexedFieldError explains why a query/sort failed so plugin authors know to declare the field under storage.collections.<name>.indexes in plugin.json.

func (*UnindexedFieldError) Error

func (e *UnindexedFieldError) Error() string

type VersionCompatResult

type VersionCompatResult struct {
	Version        string            `json:"version"`
	Compatible     bool              `json:"compatible"`
	Status         string            `json:"status"`
	Issues         []CompatIssue     `json:"issues,omitempty"`
	ArtifactKey    string            `json:"artifactKey,omitempty"`
	Artifact       *RegistryArtifact `json:"artifact,omitempty"`
	DependencyPlan *DependencyPlan   `json:"dependencyPlan,omitempty"`
}

VersionCompatResult extends CompatReport with resolved platform artifact and dependency plan.

func CheckVersionCompat

func CheckVersionCompat(
	pkg RegistryPackage,
	ver RegistryVersion,
	env HostEnv,
	catalog map[string]RegistryPackage,
) VersionCompatResult

CheckVersionCompat runs all 5 compatibility dimensions for one registry release, including full transitive dependency tree resolution against installed plugins + catalog.

func CheckVersionCompatWithBlocked

func CheckVersionCompatWithBlocked(
	pkg RegistryPackage,
	ver RegistryVersion,
	env HostEnv,
	catalog map[string]RegistryPackage,
	blocked map[string]RegistryBlocked,
) VersionCompatResult

CheckVersionCompatWithBlocked runs all 5 compatibility dimensions for one registry release while enforcing registry blocklist rules on both the target package and transitive dependencies.

type Viewer

type Viewer struct {
	Authenticated bool
	UserID        int64
	Email         string
	Nickname      string
	Role          string // user | admin | superadmin
	Admin         bool
	Superadmin    bool
}

Viewer describes the authenticated caller of /api/plugins/<id>/*.

Jump to

Keyboard shortcuts

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