update

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 48 Imported by: 0

Documentation

Overview

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Package update provides functionality for checking and applying updates

Index

Constants

View Source
const (
	// GitHubRepository represents a GitHub repository
	GitHubRepository = RepositoryTypeGitHub
	// GitLabRepository represents a GitLab repository
	GitLabRepository = RepositoryTypeGitLab
	// LocalRepository represents a local repository
	LocalRepository = RepositoryTypeLocal
)

Repository type constants (type defined in manager.go)

View Source
const (
	// Component types
	ComponentBinary    = "binary"
	ComponentTemplates = "templates"
	ComponentModules   = "modules"

	// Update types
	UpdateTypeFull        = "full"
	UpdateTypeIncremental = "incremental"
	UpdateTypeSecurity    = "security"

	// Bundle types
	BundleTypeFull      = "full"
	BundleTypeTemplates = "templates"
	BundleTypeModules   = "modules"
	BundleTypeMixed     = "mixed"

	// Operations
	OperationCheck    = "check"
	OperationDownload = "download"
	OperationVerify   = "verify"
	OperationInstall  = "install"
	OperationBackup   = "backup"
	OperationRollback = "rollback"

	// Error types
	ErrorTypeNetwork       = "network"
	ErrorTypeVerification  = "verification"
	ErrorTypePermission    = "permission"
	ErrorTypeCompatibility = "compatibility"
	ErrorTypeCorruption    = "corruption"
	ErrorTypeTimeout       = "timeout"
)

Constants for update operations

View Source
const (
	StatusPending   = "pending"
	StatusRunning   = "running"
	StatusCompleted = "completed"
	StatusFailed    = "failed"
	StatusCancelled = "cancelled"
	StatusSkipped   = "skipped"
)

Update status constants

View Source
const (
	PriorityLow      = "low"
	PriorityNormal   = "normal"
	PriorityHigh     = "high"
	PriorityCritical = "critical"
	PrioritySecurity = "security"
)

Priority levels for updates

View Source
const (
	PlatformLinux   = "linux"
	PlatformDarwin  = "darwin"
	PlatformWindows = "windows"
	PlatformFreeBSD = "freebsd"

	ArchAMD64 = "amd64"
	ArchARM64 = "arm64"
	Arch386   = "386"
	ArchARM   = "arm"
)

Platform and architecture constants

Variables

This section is empty.

Functions

func CalculateChecksum

func CalculateChecksum(filePath string) (string, error)

CalculateChecksum calculates the SHA-256 checksum of a file

func CalculateFileChecksum

func CalculateFileChecksum(filePath string) (string, error)

CalculateChecksum calculates the SHA256 checksum of a file

func CloseJSONLogFile

func CloseJSONLogFile(logFile *os.File) error

CloseJSONLogFile closes a JSON log file

func CreateJSONLogFile

func CreateJSONLogFile(logDir, packageID string) (*os.File, error)

CreateJSONLogFile creates a JSON log file for the update

func CreatePackage

func CreatePackage(manifestPath, outputPath string) error

CreatePackage creates a new update package with the given manifest

func DownloadWithProgress

func DownloadWithProgress(ctx context.Context, url, destPath string) error

DownloadWithProgress downloads a file with progress reporting to stdout

func DownloadWithProgressBar

func DownloadWithProgressBar(ctx context.Context, url, destPath string) error

DownloadWithProgressBar downloads a file with a progress bar

func DownloadWithSecureProgress

func DownloadWithSecureProgress(ctx context.Context, url, destPath string, pinnedCerts []PinnedCertificate) error

DownloadWithSecureProgress downloads a file with progress reporting using the secure downloader

func FormatChangeType

func FormatChangeType(changeType version.VersionChangeType) string

FormatChangeType formats a VersionChangeType as a string

func FormatDuration

func FormatDuration(duration time.Duration) string

FormatDuration formats a duration to human readable format

func FormatFileSize

func FormatFileSize(bytes int64) string

FormatFileSize formats a file size in bytes to human readable format

func FormatHashString

func FormatHashString(algorithm HashAlgorithm, hashHex string) string

FormatHashString formats a hash algorithm and hex string into a standard format

func FormatUpdateInfo

func FormatUpdateInfo(updates []UpdateInfo) string

FormatUpdateInfo formats update information for display

func FormatVersionChangeType

func FormatVersionChangeType(changeType version.VersionChangeType) string

FormatVersionChangeType formats a version change type for display

func GenerateKeyPair

func GenerateKeyPair(algorithm SignatureAlgorithm) (privateKeyPEM, publicKeyPEM string, err error)

GenerateKeyPair generates a new key pair for the specified algorithm

func GetArchString

func GetArchString() string

GetArchString returns the current architecture string

func GetCurrentVersion

func GetCurrentVersion() (string, error)

GetCurrentVersion returns the current version of the tool

func GetPlatformString

func GetPlatformString() string

GetPlatformString returns the current platform string

func HashData

func HashData(data []byte, algorithm HashAlgorithm) (string, error)

HashData is a convenience function to hash data with a specific algorithm

func HashFile

func HashFile(filePath string, algorithm HashAlgorithm) (string, error)

HashFile is a convenience function to hash a file with a specific algorithm

func IsValidComponent

func IsValidComponent(component string) bool

IsValidComponent checks if a component name is valid

func IsValidVersion

func IsValidVersion(version string) bool

IsValidVersion checks if a version string is valid

func SecureCompare

func SecureCompare(a, b string) bool

SecureCompare performs a constant-time comparison of two strings This helps prevent timing attacks that could potentially leak information about the hash values being compared

func VerifyChecksum

func VerifyChecksum(filePath, expectedChecksumHex string) error

VerifyChecksum verifies the SHA-256 checksum of a file

func VerifyDataHash

func VerifyDataHash(data []byte, expectedHash string) (bool, error)

VerifyDataHash is a convenience function to verify data's hash

func VerifyFileHash

func VerifyFileHash(filePath, expectedHash string) (bool, error)

VerifyFileHash is a convenience function to verify a file's hash

func VerifyUpdate

func VerifyUpdate(filePath, checksumHex, signatureBase64, publicKeyBase64 string) error

VerifyUpdate performs both signature and checksum verification on an update file

Types

type ApplierOptions

type ApplierOptions struct {
	// InstallDir is the directory where the tool is installed
	InstallDir string
	// TempDir is the directory for temporary files during update
	TempDir string
	// BackupDir is the directory for backups during update
	BackupDir string
	// CurrentVersions contains the current versions of components
	CurrentVersions map[string]version.Version
	// Logger is the logger for update operations
	Logger io.Writer
}

ApplierOptions contains options for the UpdateApplier

type AuditEvent

type AuditEvent struct {
	// Timestamp is the time the event occurred
	Timestamp time.Time `json:"timestamp"`
	// EventType is the type of event
	EventType string `json:"event_type"`
	// Component is the component associated with the event
	Component string `json:"component"`
	// User is the user who triggered the event
	User string `json:"user,omitempty"`
	// TransactionID is the ID of the transaction associated with the event
	TransactionID string `json:"transaction_id,omitempty"`
	// PackageID is the ID of the package associated with the event
	PackageID string `json:"package_id,omitempty"`
	// Details contains additional details about the event
	Details map[string]interface{} `json:"details,omitempty"`
}

AuditEvent represents an audit event for the update process

type AuditLogger

type AuditLogger struct {
	// Writer is the writer for audit log output
	Writer io.Writer
}

AuditLogger handles audit logging for update operations

func NewAuditLogger

func NewAuditLogger(writer io.Writer) *AuditLogger

NewAuditLogger creates a new audit logger

func (*AuditLogger) LogEvent

func (l *AuditLogger) LogEvent(eventType, component, user, transactionID, packageID string, details map[string]interface{})

LogEvent logs an audit event

type BatchDownloader

type BatchDownloader struct {
	MaxConcurrent int
	Client        *http.Client
}

BatchDownloader downloads multiple files concurrently with progress

func NewBatchDownloader

func NewBatchDownloader(maxConcurrent int) *BatchDownloader

NewBatchDownloader creates a new batch downloader

func (*BatchDownloader) Download

func (bd *BatchDownloader) Download(ctx context.Context, downloads map[string]string) []DownloadResult

Download downloads multiple files concurrently

type BinaryComponentInfo

type BinaryComponentInfo struct {
	Version      string            `json:"version"`
	Platforms    []string          `json:"platforms"`
	MinVersion   string            `json:"min_version"`
	Required     bool              `json:"required"`
	ChangelogURL string            `json:"changelog_url"`
	Checksums    map[string]string `json:"checksums"`
}

BinaryComponent represents the binary component in an update package

type BinaryUpdater

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

BinaryUpdater handles self-updating of the binary

func NewBinaryUpdater

func NewBinaryUpdater(config *Config, verifier *Verifier, logger Logger) *BinaryUpdater

NewBinaryUpdater creates a new binary updater

func (*BinaryUpdater) CanSelfUpdate

func (bu *BinaryUpdater) CanSelfUpdate() error

CanSelfUpdate checks if self-update is possible

func (*BinaryUpdater) ElevatePermissions

func (bu *BinaryUpdater) ElevatePermissions(args []string) error

ElevatePermissions attempts to elevate permissions for update

func (*BinaryUpdater) GetUpdatePermissions

func (bu *BinaryUpdater) GetUpdatePermissions() *UpdatePermissions

GetUpdatePermissions checks what permissions are needed for update

func (*BinaryUpdater) RestartApplication

func (bu *BinaryUpdater) RestartApplication() error

RestartApplication restarts the application with the new binary

func (*BinaryUpdater) RollbackUpdate

func (bu *BinaryUpdater) RollbackUpdate(backupPath string) error

RollbackUpdate rolls back to the previous version

func (*BinaryUpdater) UpdateBinary

func (bu *BinaryUpdater) UpdateBinary(ctx context.Context, release *Release) error

UpdateBinary performs a self-update of the binary

func (*BinaryUpdater) ValidateUpdate

func (bu *BinaryUpdater) ValidateUpdate(expectedVersion string) error

ValidateUpdate validates that an update was successful

type Bundle

type Bundle struct {
	Metadata   BundleMetadata    `json:"metadata"`
	Components []ComponentInfo   `json:"components"`
	Checksums  map[string]string `json:"checksums"`
	Signatures map[string]string `json:"signatures"`
	CreatedBy  string            `json:"created_by"`
	CreatedAt  time.Time         `json:"created_at"`
	ExpiresAt  *time.Time        `json:"expires_at,omitempty"`
}

Bundle represents an offline update bundle

type BundleExportOptions

type BundleExportOptions struct {
	Version          string
	Type             string
	Description      string
	SourceVersion    string
	TargetVersion    string
	Platforms        []string
	Incremental      bool
	OutputPath       string
	CreatedBy        string
	ExpiresAt        *time.Time
	IncludeBinary    bool
	IncludeTemplates bool
	IncludeModules   bool
	SignBundle       bool
	SigningKey       *rsa.PrivateKey
}

type BundleImportOptions

type BundleImportOptions struct {
	VerifyIntegrity bool
	ForceImport     bool
	CreateBackup    bool
	DryRun          bool
}

type BundleInfo

type BundleInfo struct {
	Path           string
	Size           int64
	Created        time.Time
	ComponentCount int
	Signed         bool
	Bundle         *Bundle
}

type BundleManager

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

BundleManager handles offline update bundles

func NewBundleManager

func NewBundleManager(config *Config, logger Logger) *BundleManager

NewBundleManager creates a new bundle manager

func (*BundleManager) ExportBundle

func (bm *BundleManager) ExportBundle(options *BundleExportOptions) (*BundleInfo, error)

ExportBundle exports an offline update bundle

func (*BundleManager) ImportBundle

func (bm *BundleManager) ImportBundle(bundlePath string, options *BundleImportOptions) (*ImportResult, error)

ImportBundle imports an offline update bundle

type BundleMetadata

type BundleMetadata struct {
	Version       string   `json:"version"`
	BundleType    string   `json:"bundle_type"`
	Description   string   `json:"description"`
	SourceVersion string   `json:"source_version"`
	TargetVersion string   `json:"target_version"`
	Platforms     []string `json:"platforms"`
	Incremental   bool     `json:"incremental"`
}

BundleMetadata contains metadata about a bundle

type Changelog

type Changelog struct {
	Project     string           `json:"project"`
	Format      string           `json:"format"`
	LastUpdated time.Time        `json:"last_updated"`
	Entries     []ChangelogEntry `json:"entries"`
}

Changelog represents a collection of changelog entries

type ChangelogEntry

type ChangelogEntry struct {
	Version     string    `json:"version"`
	Date        time.Time `json:"date"`
	Type        string    `json:"type"` // added, changed, fixed, removed, security
	Category    string    `json:"category"`
	Title       string    `json:"title"`
	Description string    `json:"description"`
	Impact      string    `json:"impact"`
	Breaking    bool      `json:"breaking"`
	Security    bool      `json:"security"`
	References  []string  `json:"references"`
}

ChangelogEntry represents an entry in a changelog

type ChangelogManager

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

ChangelogManager handles changelog operations

func NewChangelogManager

func NewChangelogManager(config *Config, logger Logger) *ChangelogManager

NewChangelogManager creates a new changelog manager

func (*ChangelogManager) CreateChangelogEntry

func (cm *ChangelogManager) CreateChangelogEntry(entry ChangelogEntry) error

CreateChangelogEntry creates a new changelog entry

func (*ChangelogManager) DisplayChangelog

func (cm *ChangelogManager) DisplayChangelog(changelog *Changelog)

DisplayChangelog displays changelog in a formatted way

func (*ChangelogManager) DisplayChangesSince

func (cm *ChangelogManager) DisplayChangesSince(sinceVersion string) error

DisplayChangesSince displays changes since a version

func (*ChangelogManager) GetChangelog

func (cm *ChangelogManager) GetChangelog(version string) (*Changelog, error)

GetChangelog retrieves and parses the changelog

func (*ChangelogManager) GetChangesSince

func (cm *ChangelogManager) GetChangesSince(sinceVersion string) ([]ChangelogEntry, error)

GetChangesSince gets changelog entries since a specific version

func (*ChangelogManager) GetLatestChanges

func (cm *ChangelogManager) GetLatestChanges(count int) ([]ChangelogEntry, error)

GetLatestChanges gets the most recent changelog entries

type Checker

type Checker interface {
	CheckForUpdates() (*VersionInfo, error)
	GetCurrentVersion() string
	GetLatestVersion() (string, error)
}

Checker interface for checking updates

type ComplianceInfo

type ComplianceInfo struct {
	Version  string   `json:"version"`
	Coverage []string `json:"coverage,omitempty"`
	Controls []string `json:"controls,omitempty"`
}

ComplianceInfo represents compliance information for standards

type ComplianceMap

type ComplianceMap struct {
	OWASPLLMTop10 ComplianceInfo `json:"owasp_llm_top10"`
	ISO42001      ComplianceInfo `json:"iso_42001"`
}

ComplianceMap represents a map of compliance standards to their information

type ComponentInfo

type ComponentInfo struct {
	Name        string `json:"name"`
	Version     string `json:"version"`
	Type        string `json:"type"`
	Path        string `json:"path"`
	Size        int64  `json:"size"`
	Checksum    string `json:"checksum"`
	Required    bool   `json:"required"`
	Description string `json:"description"`
}

ComponentInfo represents information about a component

type ComponentType

type ComponentType string

ComponentType represents the type of component in an update package

const (
	// BinaryComponent represents the core binary component
	BinaryComponent ComponentType = "binary"
	// TemplatesComponent represents the templates component
	TemplatesComponent ComponentType = "templates"
	// ModulesComponent represents the modules component
	ModulesComponent ComponentType = "modules"
)

type ComponentUpdate

type ComponentUpdate struct {
	Component      string
	Available      bool
	CurrentVersion string
	LatestVersion  string
	ChangelogURL   string
	ReleaseNotes   string
	UpdateSize     int64
	Critical       bool
	SecurityUpdate bool
}

ComponentUpdate represents an available update for a component

type ComponentVersionChecker

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

ComponentVersionChecker handles version checking for all components

func NewComponentVersionChecker

func NewComponentVersionChecker(config *Config, logger Logger) *ComponentVersionChecker

NewComponentVersionChecker creates a new component version checker

func (*ComponentVersionChecker) CheckBinaryUpdate

func (vc *ComponentVersionChecker) CheckBinaryUpdate(ctx context.Context) (*ComponentUpdate, error)

CheckBinaryUpdate checks for binary updates

func (*ComponentVersionChecker) CheckModuleUpdates

func (vc *ComponentVersionChecker) CheckModuleUpdates(ctx context.Context) (*ComponentUpdate, error)

CheckModuleUpdates checks for module updates

func (*ComponentVersionChecker) CheckTemplateUpdates

func (vc *ComponentVersionChecker) CheckTemplateUpdates(ctx context.Context) (*ComponentUpdate, error)

CheckTemplateUpdates checks for template updates

func (*ComponentVersionChecker) GetLatestBinaryRelease

func (vc *ComponentVersionChecker) GetLatestBinaryRelease(ctx context.Context) (*Release, error)

GetLatestBinaryRelease gets the latest binary release

type Components

type Components struct {
	Binary    BinaryComponentInfo    `json:"binary"`
	Templates TemplatesComponentInfo `json:"templates"`
	Modules   []ModuleComponentInfo  `json:"modules"`
	Patches   PatchesInfo            `json:"patches,omitempty"`
}

Components represents all components in an update package

type Config

type Config struct {
	// Binary update settings
	BinaryUpdateEnabled bool
	BinaryRepo          string
	BinaryUpdateURL     string

	// Template update settings
	TemplateUpdateEnabled bool
	TemplateRepos         []RepositoryConfig
	TemplateDirectory     string

	// Module update settings
	ModuleUpdateEnabled bool
	ModuleRepos         []RepositoryConfig
	ModuleDirectory     string

	// Security settings
	VerifySignatures     bool
	TrustedKeys          []string
	ChecksumVerification bool

	// General settings
	AutoUpdate          bool
	UpdateCheckInterval time.Duration
	BackupEnabled       bool
	BackupDirectory     string

	// Network settings
	Timeout    time.Duration
	MaxRetries int
	ProxyURL   string
	UserAgent  string
}

Config holds update configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default update configuration

type ConnectionSecurityOptions

type ConnectionSecurityOptions struct {
	// Whether to enable certificate pinning
	EnableCertificatePinning bool
	// Pinned certificates by host
	PinnedCertificates []PinnedCertificate
	// Whether to check certificate revocation
	CheckRevocation bool
	// Minimum TLS version
	MinTLSVersion uint16
	// Cipher suites (nil means use defaults)
	CipherSuites []uint16
	// Whether to enable HTTP/2
	EnableHTTP2 bool
	// Timeout for connections
	ConnectionTimeout time.Duration
	// Timeout for TLS handshake
	TLSHandshakeTimeout time.Duration
	// Timeout for idle connections
	IdleConnectionTimeout time.Duration
	// Maximum number of idle connections
	MaxIdleConnections int
	// Maximum number of idle connections per host
	MaxIdleConnectionsPerHost int
	// Retry configuration
	RetryConfig RetryConfig
}

ConnectionSecurityOptions contains security options for connections

func DefaultConnectionSecurityOptions

func DefaultConnectionSecurityOptions() *ConnectionSecurityOptions

DefaultConnectionSecurityOptions returns the default security options

type ConsoleNotificationHandler

type ConsoleNotificationHandler struct {
	// Writer is the writer for notification output
	Writer io.Writer
}

ConsoleNotificationHandler handles notifications by writing to a console

func NewConsoleNotificationHandler

func NewConsoleNotificationHandler(writer io.Writer) *ConsoleNotificationHandler

NewConsoleNotificationHandler creates a new console notification handler

func (*ConsoleNotificationHandler) HandleNotification

func (h *ConsoleNotificationHandler) HandleNotification(notification *Notification) error

HandleNotification handles a notification by writing to the console

type CustomizationManager

type CustomizationManager struct {
	// Registry is the customization registry
	Registry *customization.Registry
	// Detector detects user customizations
	Detector *customization.Detector
	// Preserver preserves and reapplies user customizations
	Preserver *customization.Preserver
	// InstallDir is the directory where the tool is installed
	InstallDir string
	// BackupDir is the directory for backups during update
	BackupDir string
	// Logger is the logger for customization operations
	Logger *os.File
}

CustomizationManager manages the preservation and reapplication of user customizations during the update process.

func NewCustomizationManager

func NewCustomizationManager(installDir, backupDir string, logger *os.File) (*CustomizationManager, error)

NewCustomizationManager creates a new customization manager

func (*CustomizationManager) DetectCustomizations

func (m *CustomizationManager) DetectCustomizations() error

DetectCustomizations detects user customizations in the installation directory

func (*CustomizationManager) PreserveCustomizations

func (m *CustomizationManager) PreserveCustomizations() error

PreserveCustomizations preserves user customizations before update

func (*CustomizationManager) ReapplyCustomizations

func (m *CustomizationManager) ReapplyCustomizations(updatedTemplates, updatedModules []string) error

ReapplyCustomizations reapplies user customizations after update

type DetailedVersionInfo

type DetailedVersionInfo struct {
	Version        string    `json:"version"`
	ReleaseDate    time.Time `json:"releaseDate"`
	ChangelogURL   string    `json:"changelogURL"`
	ReleaseNotes   string    `json:"releaseNotes"`
	DownloadURL    string    `json:"downloadURL"`
	Signature      string    `json:"signature"`
	ChecksumSHA256 string    `json:"checksumSHA256"`
	Required       bool      `json:"required"`
	MinVersion     string    `json:"minVersion,omitempty"`
}

DetailedVersionInfo contains detailed information about a specific version

type DowngradeProtection

type DowngradeProtection struct {
	// Policy is the current security policy
	Policy *SecurityPolicy

	// PolicyPath is the path to the security policy file
	PolicyPath string

	// Verifier is used to verify policy signatures
	Verifier *SignatureVerifier

	// KeyStore is used to store and retrieve cryptographic keys
	KeyStore *keystore.FileKeyStore
}

DowngradeProtection provides protection against cryptographic downgrade attacks

func NewDowngradeProtection

func NewDowngradeProtection(policyPath string, keyStore *keystore.FileKeyStore) (*DowngradeProtection, error)

NewDowngradeProtection creates a new DowngradeProtection instance

func (*DowngradeProtection) CreateSecureClient

func (dp *DowngradeProtection) CreateSecureClient() (*SecureClient, error)

CreateSecureClient creates a secure HTTP client that complies with the security policy

func (*DowngradeProtection) EnforceSecurityPolicy

func (dp *DowngradeProtection) EnforceSecurityPolicy(options *ConnectionSecurityOptions)

EnforceSecurityPolicy applies the security policy to a connection security options object

func (*DowngradeProtection) LoadPolicy

func (dp *DowngradeProtection) LoadPolicy() error

LoadPolicy loads the security policy from disk

func (*DowngradeProtection) SavePolicy

func (dp *DowngradeProtection) SavePolicy() error

SavePolicy saves the security policy to disk

func (*DowngradeProtection) SignPolicy

func (dp *DowngradeProtection) SignPolicy(privateKeyID string) error

SignPolicy signs the security policy

func (*DowngradeProtection) UpdateAllowedSignatureAlgorithms

func (dp *DowngradeProtection) UpdateAllowedSignatureAlgorithms(algorithms []SignatureAlgorithm) error

UpdateAllowedSignatureAlgorithms updates the allowed signature algorithms

func (*DowngradeProtection) UpdateMinimumKeySize

func (dp *DowngradeProtection) UpdateMinimumKeySize(algorithm string, keySize int) error

UpdateMinimumKeySize updates the minimum key size for an algorithm

func (*DowngradeProtection) UpdateMinimumVersion

func (dp *DowngradeProtection) UpdateMinimumVersion(componentType, versionStr string) error

UpdateMinimumVersion updates the minimum version requirement for a component type

func (*DowngradeProtection) ValidateConnectionSecurity

func (dp *DowngradeProtection) ValidateConnectionSecurity(options *ConnectionSecurityOptions) error

ValidateConnectionSecurity validates that the connection security options meet the policy requirements

func (*DowngradeProtection) ValidateKeySize

func (dp *DowngradeProtection) ValidateKeySize(algorithm string, keySize int) error

ValidateKeySize validates that a key size meets the policy requirements

func (*DowngradeProtection) ValidateSignatureAlgorithm

func (dp *DowngradeProtection) ValidateSignatureAlgorithm(algorithm SignatureAlgorithm) error

ValidateSignatureAlgorithm validates that a signature algorithm meets the policy requirements

func (*DowngradeProtection) ValidateUpdatePackage

func (dp *DowngradeProtection) ValidateUpdatePackage(pkg *UpdatePackage) error

ValidateUpdatePackage validates that an update package meets the security policy requirements

func (*DowngradeProtection) ValidateVersion

func (dp *DowngradeProtection) ValidateVersion(componentType, versionStr string) error

ValidateVersion validates that a version meets the minimum version requirement

type DownloadOptions

type DownloadOptions struct {
	// Whether to verify TLS certificates
	VerifyCertificate bool
	// Number of retry attempts
	RetryAttempts int
	// Delay between retries (exponential backoff will be applied)
	RetryDelay time.Duration
	// Timeout for the entire download
	Timeout time.Duration
	// Progress callback
	ProgressCallback func(totalBytes, downloadedBytes int64, percentage float64)
	// Whether to resume a partial download if possible
	Resume bool
	// Custom HTTP headers
	Headers map[string]string
}

DownloadOptions represents options for downloading files

func DefaultDownloadOptions

func DefaultDownloadOptions() *DownloadOptions

DefaultDownloadOptions returns the default download options

type DownloadProgress

type DownloadProgress struct {
	URL             string
	Filename        string
	TotalBytes      int64
	DownloadedBytes int64
	Speed           float64
	ETA             time.Duration
	StartTime       time.Time
}

DownloadProgress represents download progress

type DownloadResult

type DownloadResult struct {
	URL      string
	Path     string
	Size     int64
	Duration time.Duration
	Error    error
}

DownloadResult represents the result of a download operation

type DownloadStats

type DownloadStats struct {
	TotalDownloads      int
	TotalBytes          int64
	SuccessfulDownloads int
	FailedDownloads     int
	AverageSpeed        float64
	TotalTime           time.Duration
}

DownloadStats represents download statistics

type Downloader

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

Downloader handles secure downloading of files

func NewDownloader

func NewDownloader(options *DownloadOptions) *Downloader

NewDownloader creates a new Downloader

func (*Downloader) Download

func (d *Downloader) Download(ctx context.Context, url, destPath string, options *DownloadOptions) error

Download downloads a file from the given URL to the destination path

type EnhancedVersionManifest

type EnhancedVersionManifest struct {
	Core struct {
		Version         string    `json:"version"`
		ReleaseDate     time.Time `json:"releaseDate"`
		ChangelogURL    string    `json:"changelogURL"`
		ReleaseNotes    string    `json:"releaseNotes"`
		DownloadURL     string    `json:"downloadURL"`
		Signature       string    `json:"signature"`
		ChecksumSHA256  string    `json:"checksumSHA256"`
		Size            int64     `json:"size"`
		Dependencies    []string  `json:"dependencies"`
		BreakingChanges bool      `json:"breakingChanges"`
	} `json:"core"`
	Templates struct {
		Version         string    `json:"version"`
		ReleaseDate     time.Time `json:"releaseDate"`
		ChangelogURL    string    `json:"changelogURL"`
		ReleaseNotes    string    `json:"releaseNotes"`
		DownloadURL     string    `json:"downloadURL"`
		Signature       string    `json:"signature"`
		ChecksumSHA256  string    `json:"checksumSHA256"`
		Size            int64     `json:"size"`
		Dependencies    []string  `json:"dependencies"`
		BreakingChanges bool      `json:"breakingChanges"`
	} `json:"templates"`
	Modules []struct {
		ID              string    `json:"id"`
		Name            string    `json:"name"`
		Version         string    `json:"version"`
		ReleaseDate     time.Time `json:"releaseDate"`
		ChangelogURL    string    `json:"changelogURL"`
		ReleaseNotes    string    `json:"releaseNotes"`
		DownloadURL     string    `json:"downloadURL"`
		Signature       string    `json:"signature"`
		ChecksumSHA256  string    `json:"checksumSHA256"`
		Size            int64     `json:"size"`
		Dependencies    []string  `json:"dependencies"`
		BreakingChanges bool      `json:"breakingChanges"`
	} `json:"modules"`
}

EnhancedVersionManifest extends VersionManifest with additional fields

type ExtendedUpdateInfo

type ExtendedUpdateInfo struct {
	Component       string                    `json:"component"`
	CurrentVersion  version.Version           `json:"current_version"`
	LatestVersion   version.Version           `json:"latest_version"`
	ChangeType      version.VersionChangeType `json:"change_type"`
	ChangelogURL    string                    `json:"changelog_url"`
	ReleaseDate     time.Time                 `json:"release_date"`
	ReleaseNotes    string                    `json:"release_notes"`
	DownloadURL     string                    `json:"download_url"`
	Signature       string                    `json:"signature"`
	ChecksumSHA256  string                    `json:"checksum_sha256"`
	Required        bool                      `json:"required"`
	SecurityFixes   bool                      `json:"security_fixes"`
	Size            int64                     `json:"size"`
	Dependencies    []string                  `json:"dependencies"`
	BreakingChanges bool                      `json:"breaking_changes"`
}

ExtendedUpdateInfo represents information about an available update with additional fields

func MergeExtendedUpdates

func MergeExtendedUpdates(updateLists ...[]ExtendedUpdateInfo) []ExtendedUpdateInfo

MergeExtendedUpdates merges and deduplicates extended update lists

type ExtendedUpdateNotifier

type ExtendedUpdateNotifier interface {
	UpdateNotifier
	NotifyAvailableUpdate(ctx context.Context, versionInfo *UpdateVersionInfo) error
	NotifyRequiredUpdate(ctx context.Context, versionInfo *UpdateVersionInfo) error
	NotifySecurityUpdate(ctx context.Context, versionInfo *UpdateVersionInfo, details string) error
}

ExtendedUpdateNotifier extends the UpdateNotifier interface with additional notification methods

type FileVerificationResult

type FileVerificationResult struct {
	Verified       bool
	ChecksumValid  bool
	SignatureValid bool
	Algorithm      string
	KeyID          string
	Error          error
}

FileVerificationResult represents the result of a file verification

type GitHubCommit

type GitHubCommit struct {
	SHA    string `json:"sha"`
	Commit struct {
		Message string `json:"message"`
		Author  struct {
			Date string `json:"date"`
		} `json:"author"`
	} `json:"commit"`
}

type GitHubRelease

type GitHubRelease struct {
	TagName     string `json:"tag_name"`
	Name        string `json:"name"`
	Body        string `json:"body"`
	Draft       bool   `json:"draft"`
	Prerelease  bool   `json:"prerelease"`
	CreatedAt   string `json:"created_at"`
	PublishedAt string `json:"published_at"`
	Assets      []struct {
		Name               string `json:"name"`
		BrowserDownloadURL string `json:"browser_download_url"`
		Size               int64  `json:"size"`
		ContentType        string `json:"content_type"`
	} `json:"assets"`
	HTMLURL string `json:"html_url"`
}

GitHubRelease represents a GitHub release response

type GitHubRepoInfo

type GitHubRepoInfo struct {
	Owner string
	Repo  string
}

type GitLabCommit

type GitLabCommit struct {
	ID           string    `json:"id"`
	Title        string    `json:"title"`
	Message      string    `json:"message"`
	AuthoredDate time.Time `json:"authored_date"`
}

type GitLabRelease

type GitLabRelease struct {
	TagName     string `json:"tag_name"`
	Name        string `json:"name"`
	Description string `json:"description"`
	CreatedAt   string `json:"created_at"`
	ReleasedAt  string `json:"released_at"`
	Assets      struct {
		Links []struct {
			Name string `json:"name"`
			URL  string `json:"url"`
		} `json:"links"`
	} `json:"assets"`
	WebURL string `json:"web_url"`
}

GitLabRelease represents a GitLab release response

type GitLabRepoInfo

type GitLabRepoInfo struct {
	Host  string
	Owner string
	Repo  string
}

type HashAlgorithm

type HashAlgorithm string

HashAlgorithm represents supported hash algorithms

const (
	// SHA256 represents the SHA-256 hash algorithm
	SHA256 HashAlgorithm = "sha256"
	// SHA512 represents the SHA-512 hash algorithm
	SHA512 HashAlgorithm = "sha512"
	// SHA1 represents the SHA-1 hash algorithm (not recommended for security-critical applications)
	SHA1 HashAlgorithm = "sha1"
	// MD5 represents the MD5 hash algorithm (not recommended for security-critical applications)
	MD5 HashAlgorithm = "md5"
	// BLAKE2b represents the BLAKE2b hash algorithm
	BLAKE2b HashAlgorithm = "blake2b"
	// BLAKE2s represents the BLAKE2s hash algorithm
	BLAKE2s HashAlgorithm = "blake2s"
)

func ParseHashString

func ParseHashString(hashStr string) (HashAlgorithm, string, error)

ParseHashString parses a hash string in the format "algorithm:hash"

type HashGenerator

type HashGenerator struct {
	Algorithm HashAlgorithm
	// contains filtered or unexported fields
}

HashGenerator handles the generation of cryptographic hashes

func NewHashGenerator

func NewHashGenerator(algorithm HashAlgorithm) (*HashGenerator, error)

NewHashGenerator creates a new HashGenerator with the specified algorithm

func (*HashGenerator) HashData

func (g *HashGenerator) HashData(data []byte) (*HashResult, error)

HashData calculates the hash of the provided data

func (*HashGenerator) HashFile

func (g *HashGenerator) HashFile(filePath string) (*HashResult, error)

HashFile calculates the hash of a file

type HashResult

type HashResult struct {
	Algorithm HashAlgorithm // The algorithm used
	Hash      []byte        // Raw hash bytes
	HexString string        // Hex-encoded hash string
	FilePath  string        // Path to the file that was hashed (if applicable)
	Timestamp time.Time     // When the hash was generated
}

HashResult represents the result of a hash operation

func (*HashResult) String

func (hr *HashResult) String() string

String returns a formatted string representation of the hash result

type HashVerifier

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

HashVerifier handles verification of cryptographic hashes

func NewHashVerifier

func NewHashVerifier() (*HashVerifier, error)

NewHashVerifier creates a new HashVerifier

func (*HashVerifier) GenerateDataHashes

func (v *HashVerifier) GenerateDataHashes(data []byte) (map[HashAlgorithm]*HashResult, error)

GenerateDataHashes generates hashes for data using all supported algorithms

func (*HashVerifier) GenerateFileHashes

func (v *HashVerifier) GenerateFileHashes(filePath string) (map[HashAlgorithm]*HashResult, error)

GenerateFileHashes generates hashes for a file using all supported algorithms

func (*HashVerifier) VerifyDataHash

func (v *HashVerifier) VerifyDataHash(data []byte, expectedHash string) (bool, error)

VerifyDataHash verifies the hash of data

func (*HashVerifier) VerifyFileHash

func (v *HashVerifier) VerifyFileHash(filePath, expectedHash string) (bool, error)

VerifyFileHash verifies the hash of a file

type ImportResult

type ImportResult struct {
	Success           bool
	ComponentsUpdated []string
	Errors            []string
	BackupPath        string
	RestartRequired   bool
}

type InstallationInfo

type InstallationInfo struct {
	BinaryPath    string    `json:"binary_path"`
	BinarySize    int64     `json:"binary_size"`
	BinaryModTime time.Time `json:"binary_mod_time"`
	TemplateDir   string    `json:"template_dir"`
	TemplateCount int       `json:"template_count"`
	ModuleDir     string    `json:"module_dir"`
	ModuleCount   int       `json:"module_count"`
	BackupDir     string    `json:"backup_dir"`
	Platform      string    `json:"platform"`
	Architecture  string    `json:"architecture"`
}

InstallationInfo contains information about the current installation

type Installer

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

Installer handles installation of updates

func NewInstaller

func NewInstaller(config *Config, logger Logger) *Installer

NewInstaller creates a new installer

func (*Installer) CleanupInstallation

func (i *Installer) CleanupInstallation() error

CleanupInstallation cleans up installation artifacts

func (*Installer) GetInstallationInfo

func (i *Installer) GetInstallationInfo() (*InstallationInfo, error)

GetInstallationInfo returns information about the current installation

func (*Installer) InstallBinary

func (i *Installer) InstallBinary(binaryPath string) error

InstallBinary installs a new binary

func (*Installer) InstallModules

func (i *Installer) InstallModules(moduleFiles map[string]string) error

InstallModules installs module updates

func (*Installer) InstallTemplates

func (i *Installer) InstallTemplates(templateFiles map[string]string) error

InstallTemplates installs template updates

func (*Installer) RemoveObsoleteFiles

func (i *Installer) RemoveObsoleteFiles(obsoleteFiles []string, baseDir string) error

RemoveObsoleteFiles removes files that are no longer needed

func (*Installer) ValidateInstallation

func (i *Installer) ValidateInstallation(component string) error

ValidateInstallation validates that an installation was successful

type IntegrityReport

type IntegrityReport struct {
	FilePath         string
	ChecksumValid    bool
	ExpectedChecksum string
	ActualChecksum   string
	SignatureValid   bool
	SignatureError   error
	FileSize         int64
	VerifiedAt       string
}

IntegrityReport represents the result of integrity verification

func VerifyIntegrity

func VerifyIntegrity(filePath, expectedChecksum, signature, publicKey string) (*IntegrityReport, error)

VerifyIntegrity performs comprehensive integrity verification

type IntegrityVerifier

type IntegrityVerifier struct {
	// Logger is the logger for verification operations
	Logger io.Writer
}

IntegrityVerifier handles verification of update package integrity

func NewIntegrityVerifier

func NewIntegrityVerifier(logger io.Writer) *IntegrityVerifier

NewIntegrityVerifier creates a new integrity verifier

func (*IntegrityVerifier) VerifyCompatibility

func (v *IntegrityVerifier) VerifyCompatibility(pkg *UpdatePackage, currentVersions map[string]version.Version) (*VerificationResult, error)

VerifyCompatibility verifies that the update package is compatible with the current installation

func (*IntegrityVerifier) VerifyPackage

func (v *IntegrityVerifier) VerifyPackage(pkg *UpdatePackage) (*VerificationResult, error)

VerifyPackage verifies the integrity of an update package

type JSONNotificationHandler

type JSONNotificationHandler struct {
	// Writer is the writer for JSON notification output
	Writer io.Writer
}

JSONNotificationHandler handles notifications by writing JSON to a writer

func NewJSONNotificationHandler

func NewJSONNotificationHandler(writer io.Writer) *JSONNotificationHandler

NewJSONNotificationHandler creates a new JSON notification handler

func (*JSONNotificationHandler) HandleNotification

func (h *JSONNotificationHandler) HandleNotification(notification *Notification) error

HandleNotification handles a notification by writing JSON to the writer

type KeyInfo

type KeyInfo struct {
	ID        string `json:"id"`
	KeySize   int    `json:"key_size"`
	Algorithm string `json:"algorithm"`
	Usage     string `json:"usage"`
}

KeyInfo represents information about a cryptographic key

type LogEntry

type LogEntry struct {
	// Timestamp is the time the log entry was created
	Timestamp time.Time `json:"timestamp"`
	// Level is the severity level of the log entry
	Level LogLevel `json:"level"`
	// Message is the log message
	Message string `json:"message"`
	// Component is the component that generated the log entry
	Component string `json:"component"`
	// TransactionID is the ID of the transaction associated with the log entry
	TransactionID string `json:"transaction_id,omitempty"`
	// Details contains additional details about the log entry
	Details map[string]interface{} `json:"details,omitempty"`
}

LogEntry represents a single log entry

type LogLevel

type LogLevel string

LogLevel represents the severity level of a log entry

const (
	// LogLevelDebug is for debug messages
	LogLevelDebug LogLevel = "debug"
	// LogLevelInfo is for informational messages
	LogLevelInfo LogLevel = "info"
	// LogLevelWarning is for warning messages
	LogLevelWarning LogLevel = "warning"
	// LogLevelError is for error messages
	LogLevelError LogLevel = "error"
)

type Logger

type Logger interface {
	Info(msg string)
	Error(msg string, err error)
	Debug(msg string)
	Warn(msg string)
}

Logger interface for update operations

type LoggerOptions

type LoggerOptions struct {
	// Writer is the writer for log output
	Writer io.Writer
	// JSONWriter is the writer for JSON log output
	JSONWriter io.Writer
	// MinLevel is the minimum log level to output
	MinLevel LogLevel
	// IncludeDetails determines whether to include details in log output
	IncludeDetails bool
}

LoggerOptions contains options for the UpdateLogger

type Manager

type Manager interface {
	Checker
	PerformUpdate(request UpdateRequest) (*UpdateResponse, error)
	GetUpdateHistory() ([]UpdateResult, error)
	Rollback(component string, version string) error
}

Manager interface for managing updates

type ManagerUpdateResult

type ManagerUpdateResult struct {
	Component    string
	Success      bool
	OldVersion   string
	NewVersion   string
	ChangelogURL string
	FilesUpdated []string
	Error        error
	Duration     time.Duration
}

ManagerUpdateResult represents the result of an update operation

type ModuleComponentInfo

type ModuleComponentInfo struct {
	ID           string             `json:"id"`
	Name         string             `json:"name"`
	Version      string             `json:"version"`
	MinVersion   string             `json:"min_version"`
	Required     bool               `json:"required"`
	ChangelogURL string             `json:"changelog_url"`
	Checksum     string             `json:"checksum"`
	Dependencies []ModuleDependency `json:"dependencies"`
}

ModuleComponent represents a module component in an update package

type ModuleDependency

type ModuleDependency struct {
	ID         string `json:"id"`
	MinVersion string `json:"min_version"`
}

ModuleDependency represents a dependency for a module

type ModuleInfo

type ModuleInfo struct {
	Name           string            `json:"name"`
	Version        string            `json:"version"`
	Provider       string            `json:"provider"`
	Author         string            `json:"author"`
	Description    string            `json:"description"`
	Capabilities   []string          `json:"capabilities"`
	Dependencies   []string          `json:"dependencies"`
	MinToolVersion string            `json:"min_tool_version"`
	MaxToolVersion string            `json:"max_tool_version"`
	Metadata       map[string]string `json:"metadata"`
	FilePath       string            `json:"file_path"`
	Size           int64             `json:"size"`
	Checksum       string            `json:"checksum"`
	LastUpdated    time.Time         `json:"last_updated"`
}

ModuleInfo represents information about a provider module

type ModuleManifest

type ModuleManifest struct {
	Version     string                 `json:"version"`
	LastUpdated time.Time              `json:"last_updated"`
	Modules     map[string]ModuleInfo  `json:"modules"`
	Providers   map[string][]string    `json:"providers"`
	Statistics  map[string]interface{} `json:"statistics"`
	Repository  RepositoryMetadata     `json:"repository"`
}

ModuleManifest represents a module repository manifest

type Notification

type Notification struct {
	// Type is the type of notification
	Type NotificationType `json:"type"`
	// Timestamp is the time the notification was created
	Timestamp time.Time `json:"timestamp"`
	// Message is the notification message
	Message string `json:"message"`
	// TransactionID is the ID of the transaction associated with the notification
	TransactionID string `json:"transaction_id,omitempty"`
	// PackageID is the ID of the package associated with the notification
	PackageID string `json:"package_id,omitempty"`
	// Component is the component associated with the notification
	Component string `json:"component,omitempty"`
	// Details contains additional details about the notification
	Details map[string]interface{} `json:"details,omitempty"`
}

Notification represents a notification about an update event

type NotificationHandler

type NotificationHandler interface {
	// HandleNotification handles a notification
	HandleNotification(notification *Notification) error
}

NotificationHandler is an interface for handling notifications

type NotificationIntegration

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

NotificationIntegration provides integration between the update system and notification system

func NewNotificationIntegration

func NewNotificationIntegration(notifier ExtendedUpdateNotifier) *NotificationIntegration

NewNotificationIntegration creates a new notification integration

func (*NotificationIntegration) HandleUpdateCheck

func (n *NotificationIntegration) HandleUpdateCheck(ctx context.Context, versionInfo *UpdateVersionInfo) error

HandleUpdateCheck processes the results of a version check and creates notifications

func (*NotificationIntegration) NotifyUpdateFailure

func (n *NotificationIntegration) NotifyUpdateFailure(ctx context.Context, fromVersion, toVersion string, err error) error

NotifyUpdateFailure creates a notification for a failed update

func (*NotificationIntegration) NotifyUpdateSuccess

func (n *NotificationIntegration) NotifyUpdateSuccess(ctx context.Context, fromVersion, toVersion string) error

NotifyUpdateSuccess creates a notification for a successful update

type NotificationManager

type NotificationManager struct {
	// Handlers is the list of notification handlers
	Handlers []NotificationHandler
}

NotificationManager manages notification handlers

func NewNotificationManager

func NewNotificationManager() *NotificationManager

NewNotificationManager creates a new notification manager

func (*NotificationManager) AddHandler

func (m *NotificationManager) AddHandler(handler NotificationHandler)

AddHandler adds a notification handler

func (*NotificationManager) NotifyComponentUpdated

func (m *NotificationManager) NotifyComponentUpdated(transactionID, packageID, component, componentID string, details map[string]interface{}) error

NotifyComponentUpdated sends a notification that a component has been updated

func (*NotificationManager) NotifyUpdateCompleted

func (m *NotificationManager) NotifyUpdateCompleted(transactionID, packageID string, details map[string]interface{}) error

NotifyUpdateCompleted sends a notification that an update has completed

func (*NotificationManager) NotifyUpdateFailed

func (m *NotificationManager) NotifyUpdateFailed(transactionID, packageID, reason string, details map[string]interface{}) error

NotifyUpdateFailed sends a notification that an update has failed

func (*NotificationManager) NotifyUpdateRolledBack

func (m *NotificationManager) NotifyUpdateRolledBack(transactionID, packageID string, details map[string]interface{}) error

NotifyUpdateRolledBack sends a notification that an update has been rolled back

func (*NotificationManager) NotifyUpdateStarted

func (m *NotificationManager) NotifyUpdateStarted(transactionID, packageID string, details map[string]interface{}) error

NotifyUpdateStarted sends a notification that an update has started

func (*NotificationManager) NotifyVerificationFailed

func (m *NotificationManager) NotifyVerificationFailed(packageID, reason string, details map[string]interface{}) error

NotifyVerificationFailed sends a notification that a verification has failed

func (*NotificationManager) SendNotification

func (m *NotificationManager) SendNotification(notification *Notification) error

SendNotification sends a notification to all handlers

type NotificationType

type NotificationType string

NotificationType represents the type of notification

const (
	// UpdateStarted indicates an update has started
	UpdateStarted NotificationType = "update_started"
	// UpdateCompleted indicates an update has completed successfully
	UpdateCompleted NotificationType = "update_completed"
	// UpdateFailed indicates an update has failed
	UpdateFailed NotificationType = "update_failed"
	// UpdateRolledBack indicates an update has been rolled back
	UpdateRolledBack NotificationType = "update_rolled_back"
	// ComponentUpdated indicates a component has been updated
	ComponentUpdated NotificationType = "component_updated"
	// VerificationFailed indicates a verification has failed
	VerificationFailed NotificationType = "verification_failed"
)

type PackageManifest

type PackageManifest struct {
	SchemaVersion string        `json:"schema_version"`
	PackageID     string        `json:"package_id"`
	PackageType   PackageType   `json:"package_type"`
	CreatedAt     time.Time     `json:"created_at"`
	ExpiresAt     time.Time     `json:"expires_at"`
	Publisher     Publisher     `json:"publisher"`
	Components    Components    `json:"components"`
	Compliance    ComplianceMap `json:"compliance"`
	Signature     string        `json:"signature"`
}

PackageManifest represents the manifest of an update package

type PackageType

type PackageType string

PackageType represents the type of update package

const (
	// FullPackage represents a full update package containing complete files
	FullPackage PackageType = "full"
	// DifferentialPackage represents a differential update package containing patches
	DifferentialPackage PackageType = "differential"
)

type PatchInfo

type PatchInfo struct {
	FromVersion string            `json:"from_version"`
	ToVersion   string            `json:"to_version"`
	Platforms   []string          `json:"platforms,omitempty"`
	Checksums   map[string]string `json:"checksums,omitempty"`
	Checksum    string            `json:"checksum,omitempty"`
	ID          string            `json:"id,omitempty"`
}

PatchInfo represents information about a patch in a differential update

type PatchesInfo

type PatchesInfo struct {
	Binary    []PatchInfo `json:"binary,omitempty"`
	Templates []PatchInfo `json:"templates,omitempty"`
	Modules   []PatchInfo `json:"modules,omitempty"`
}

PatchesInfo represents all patches in a differential update

type PinnedCertificate

type PinnedCertificate struct {
	Host            string   // Hostname
	PublicKeyHashes []string // SHA-256 hashes of the public key in base64
	SubjectName     string   // Expected subject name
	Issuer          string   // Expected issuer
}

PinnedCertificate represents a pinned certificate for a specific host

type ProgressCallback

type ProgressCallback func(*DownloadProgress)

ProgressCallback is called during download progress

type Publisher

type Publisher struct {
	Name        string `json:"name"`
	URL         string `json:"url"`
	PublicKeyID string `json:"public_key_id"`
}

Publisher represents the publisher of an update package

type Release

type Release struct {
	Version      string
	Name         string
	Description  string
	ChangelogURL string
	ReleaseDate  time.Time
	Assets       []ReleaseAsset
	Prerelease   bool
	Draft        bool
	TagName      string
}

Release represents a software release

type ReleaseAsset

type ReleaseAsset struct {
	Name         string
	DownloadURL  string
	Size         int64
	ContentType  string
	Checksum     string
	SignatureURL string
	Platform     string
	Architecture string
}

ReleaseAsset represents a downloadable asset from a release

type RepositoryConfig

type RepositoryConfig struct {
	Name     string
	URL      string
	Branch   string
	Token    string
	Type     RepositoryType
	Priority int
}

RepositoryConfig defines a source for updates

type RepositoryInfo

type RepositoryInfo struct {
	// Type of repository (github, gitlab, local)
	Type RepositoryType
	// URL of the repository
	URL string
	// Local path where the repository is cloned
	LocalPath string
	// Current version (commit hash or tag)
	CurrentVersion string
	// Latest available version
	LatestVersion string
	// Whether the repository has updates available
	HasUpdates bool
	// Last sync time
	LastSync time.Time
}

RepositoryInfo represents information about a template repository

type RepositoryManager

type RepositoryManager struct {
	// Base directory for repositories
	BaseDir string
	// Map of repository information by name
	Repositories map[string]*RepositoryInfo
}

RepositoryManager handles operations on template repositories

func NewRepositoryManager

func NewRepositoryManager(baseDir string) *RepositoryManager

NewRepositoryManager creates a new RepositoryManager

func (*RepositoryManager) AddRepository

func (rm *RepositoryManager) AddRepository(name string, repoType RepositoryType, url string) (*RepositoryInfo, error)

AddRepository adds a repository to the manager

func (*RepositoryManager) GetRepository

func (rm *RepositoryManager) GetRepository(name string) (*RepositoryInfo, error)

GetRepository returns a repository by name

func (*RepositoryManager) GetTemplateVersion

func (rm *RepositoryManager) GetTemplateVersion(name string) (version.Version, error)

GetTemplateVersion returns the version of the templates in a repository

func (*RepositoryManager) ListRepositories

func (rm *RepositoryManager) ListRepositories() []*RepositoryInfo

ListRepositories returns a list of all repositories

func (*RepositoryManager) RemoveRepository

func (rm *RepositoryManager) RemoveRepository(name string) error

RemoveRepository removes a repository

func (*RepositoryManager) SyncRepository

func (rm *RepositoryManager) SyncRepository(name string) error

SyncRepository syncs a repository (clone if it doesn't exist, pull if it does)

type RepositoryMetadata

type RepositoryMetadata struct {
	URL         string    `json:"url"`
	Branch      string    `json:"branch"`
	Commit      string    `json:"commit"`
	LastUpdated time.Time `json:"last_updated"`
	Size        int64     `json:"size"`
	FileCount   int       `json:"file_count"`
}

RepositoryMetadata contains metadata about a repository

type RepositoryStatus

type RepositoryStatus struct {
	Name        string    `json:"name"`
	URL         string    `json:"url"`
	Type        string    `json:"type"`
	Available   bool      `json:"available"`
	LastChecked time.Time `json:"last_checked"`
	LastUpdated time.Time `json:"last_updated"`
	ItemCount   int       `json:"item_count"`
	TotalSize   int64     `json:"total_size"`
	Error       string    `json:"error,omitempty"`
	Version     string    `json:"version"`
}

RepositoryStatus represents the status of a repository

type RepositoryType

type RepositoryType string

RepositoryType represents the type of repository

const (
	RepositoryTypeGitHub RepositoryType = "github"
	RepositoryTypeGitLab RepositoryType = "gitlab"
	RepositoryTypeHTTP   RepositoryType = "http"
	RepositoryTypeLocal  RepositoryType = "local"
)

type RepositoryUpdater

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

RepositoryUpdater handles updating from various repository sources

func NewRepositoryUpdater

func NewRepositoryUpdater(config *Config, downloader *Downloader, verifier *Verifier, logger Logger) *RepositoryUpdater

NewRepositoryUpdater creates a new repository updater

func (*RepositoryUpdater) UpdateFromGitHub

func (ru *RepositoryUpdater) UpdateFromGitHub(ctx context.Context, repo RepositoryConfig, targetDir string) ([]string, error)

UpdateFromGitHub updates templates/modules from GitHub repository

func (*RepositoryUpdater) UpdateFromGitLab

func (ru *RepositoryUpdater) UpdateFromGitLab(ctx context.Context, repo RepositoryConfig, targetDir string) ([]string, error)

UpdateFromGitLab updates templates/modules from GitLab repository

func (*RepositoryUpdater) UpdateFromHTTP

func (ru *RepositoryUpdater) UpdateFromHTTP(ctx context.Context, repo RepositoryConfig, targetDir string) ([]string, error)

UpdateFromHTTP updates from HTTP repository

func (*RepositoryUpdater) UpdateFromLocal

func (ru *RepositoryUpdater) UpdateFromLocal(ctx context.Context, repo RepositoryConfig, targetDir string) ([]string, error)

UpdateFromLocal updates from local repository

type RetryConfig

type RetryConfig struct {
	// Maximum number of retry attempts
	MaxRetries int
	// Initial delay before first retry
	InitialDelay time.Duration
	// Maximum delay between retries
	MaxDelay time.Duration
	// Whether to use exponential backoff
	UseExponentialBackoff bool
	// Jitter factor (0.0-1.0) to add randomness to retry delays
	JitterFactor float64
	// Status codes that should trigger a retry
	RetryableStatusCodes []int
	// Network errors that should trigger a retry
	RetryableNetworkErrors []string
}

RetryConfig contains configuration for retry behavior

type SecureClient

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

SecureClient provides a secure HTTP client with enhanced security features

func NewSecureClient

func NewSecureClient(options *ConnectionSecurityOptions) (*SecureClient, error)

NewSecureClient creates a new SecureClient with the specified options

func (*SecureClient) AddPinnedCertificate

func (c *SecureClient) AddPinnedCertificate(pinnedCert PinnedCertificate)

AddPinnedCertificate adds a pinned certificate to the client

func (*SecureClient) Do

func (c *SecureClient) Do(req *http.Request) (*http.Response, error)

Do performs an HTTP request with retry logic

func (*SecureClient) Get

func (c *SecureClient) Get(ctx context.Context, url string, headers map[string]string) (*http.Response, error)

Get performs a GET request with the secure client

func (*SecureClient) GetPinnedCertificates

func (c *SecureClient) GetPinnedCertificates() []PinnedCertificate

GetPinnedCertificates returns a copy of the pinned certificates

func (*SecureClient) GetRetryConfig

func (c *SecureClient) GetRetryConfig() RetryConfig

GetRetryConfig returns a copy of the retry configuration

func (*SecureClient) Head

func (c *SecureClient) Head(ctx context.Context, url string, headers map[string]string) (*http.Response, error)

Head performs a HEAD request with the secure client

func (*SecureClient) RemovePinnedCertificate

func (c *SecureClient) RemovePinnedCertificate(host string)

RemovePinnedCertificate removes a pinned certificate for a host

func (*SecureClient) UpdateRetryConfig

func (c *SecureClient) UpdateRetryConfig(retryConfig RetryConfig)

UpdateRetryConfig updates the retry configuration

type SecureDownloadOptions

type SecureDownloadOptions struct {
	// Security options for the connection
	SecurityOptions *ConnectionSecurityOptions
	// Progress callback
	ProgressCallback func(totalBytes, downloadedBytes int64, percentage float64)
	// Whether to resume a partial download if possible
	Resume bool
	// Custom HTTP headers
	Headers map[string]string
	// Chunk size for downloading (0 means no chunking)
	ChunkSize int64
	// Verify file after download
	VerifyAfterDownload bool
}

SecureDownloadOptions represents options for secure downloading

func DefaultSecureDownloadOptions

func DefaultSecureDownloadOptions() *SecureDownloadOptions

DefaultSecureDownloadOptions returns the default secure download options

type SecureDownloader

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

SecureDownloader provides secure downloading functionality

func NewSecureDownloader

func NewSecureDownloader(options *SecureDownloadOptions) (*SecureDownloader, error)

NewSecureDownloader creates a new SecureDownloader

func (*SecureDownloader) Download

func (d *SecureDownloader) Download(ctx context.Context, url, destPath string, options *SecureDownloadOptions) error

Download securely downloads a file from the given URL to the destination path

type SecurityPolicy

type SecurityPolicy struct {
	// MinimumTLSVersion is the minimum allowed TLS version
	MinimumTLSVersion uint16 `json:"minimum_tls_version"`

	// AllowedCipherSuites is the list of allowed TLS cipher suites
	AllowedCipherSuites []uint16 `json:"allowed_cipher_suites"`

	// AllowedSignatureAlgorithms is the list of allowed signature algorithms
	AllowedSignatureAlgorithms []SignatureAlgorithm `json:"allowed_signature_algorithms"`

	// MinimumKeySize maps algorithm types to their minimum key sizes in bits
	MinimumKeySize map[string]int `json:"minimum_key_size"`

	// RequireCertificatePinning indicates whether certificate pinning is required
	RequireCertificatePinning bool `json:"require_certificate_pinning"`

	// RequireRevocationCheck indicates whether certificate revocation checking is required
	RequireRevocationCheck bool `json:"require_revocation_check"`

	// MinimumVersions maps component types to their minimum allowed versions
	MinimumVersions map[string]string `json:"minimum_versions"`

	// LastUpdateTime is when the policy was last updated
	LastUpdateTime time.Time `json:"last_update_time"`

	// PolicyVersion is the version of the security policy
	PolicyVersion string `json:"policy_version"`

	// PolicySignature is the cryptographic signature of the policy
	PolicySignature string `json:"policy_signature"`

	// RequireSignatureVerification indicates whether signature verification is required
	RequireSignatureVerification bool `json:"require_signature_verification"`
}

SecurityPolicy defines the minimum security requirements for cryptographic operations

func DefaultSecurityPolicy

func DefaultSecurityPolicy() *SecurityPolicy

DefaultSecurityPolicy returns the default security policy

type SignatureAlgorithm

type SignatureAlgorithm string

SignatureAlgorithm represents the type of signature algorithm

const (
	// Ed25519Algorithm represents the Ed25519 signature algorithm
	Ed25519Algorithm SignatureAlgorithm = "ed25519"
	// RSAAlgorithm represents the RSA signature algorithm
	RSAAlgorithm SignatureAlgorithm = "rsa"
	// ECDSAAlgorithm represents the ECDSA signature algorithm
	ECDSAAlgorithm SignatureAlgorithm = "ecdsa"
)

type SignatureGenerator

type SignatureGenerator struct {
	// Algorithm is the signature algorithm used
	Algorithm SignatureAlgorithm
	// PrivateKey is the private key used for signing
	PrivateKey interface{}
}

SignatureGenerator handles the generation of digital signatures

func NewSignatureGenerator

func NewSignatureGenerator(privateKeyData string) (*SignatureGenerator, error)

NewSignatureGenerator creates a new SignatureGenerator with the given private key

func (*SignatureGenerator) GenerateSignature

func (g *SignatureGenerator) GenerateSignature(filePath string) (string, error)

GenerateSignature generates a digital signature for a file

func (*SignatureGenerator) GenerateSignatureForData

func (g *SignatureGenerator) GenerateSignatureForData(data []byte) (string, error)

GenerateSignatureForData generates a digital signature for the provided data

type SignatureVerifier

type SignatureVerifier struct {
	// Algorithm is the signature algorithm used
	Algorithm SignatureAlgorithm
	// PublicKey is the public key used for verification
	PublicKey interface{}
}

SignatureVerifier handles verification of update signatures

func NewSignatureVerifier

func NewSignatureVerifier(publicKeyData string) (*SignatureVerifier, error)

NewSignatureVerifier creates a new SignatureVerifier with the given public key

func (*SignatureVerifier) VerifySignature

func (v *SignatureVerifier) VerifySignature(filePath, signatureBase64 string) error

VerifySignature verifies the signature of a file

type TemplateInfo

type TemplateInfo struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Version     string            `json:"version"`
	Category    string            `json:"category"`
	Author      string            `json:"author"`
	Description string            `json:"description"`
	Tags        []string          `json:"tags"`
	Severity    string            `json:"severity"`
	Metadata    map[string]string `json:"metadata"`
	FilePath    string            `json:"file_path"`
	Size        int64             `json:"size"`
	Checksum    string            `json:"checksum"`
	LastUpdated time.Time         `json:"last_updated"`
}

TemplateInfo represents information about a template

type TemplateManifest

type TemplateManifest struct {
	Version     string                  `json:"version"`
	LastUpdated time.Time               `json:"last_updated"`
	Templates   map[string]TemplateInfo `json:"templates"`
	Categories  map[string][]string     `json:"categories"`
	Statistics  map[string]interface{}  `json:"statistics"`
	Repository  RepositoryInfo          `json:"repository"`
}

TemplateManifest represents a template repository manifest

type TemplatesComponentInfo

type TemplatesComponentInfo struct {
	Version       string   `json:"version"`
	MinVersion    string   `json:"min_version"`
	Required      bool     `json:"required"`
	ChangelogURL  string   `json:"changelog_url"`
	Checksum      string   `json:"checksum"`
	Categories    []string `json:"categories"`
	TemplateCount int      `json:"template_count"`
}

TemplatesComponent represents the templates component in an update package

type TransactionStatus

type TransactionStatus string

TransactionStatus represents the status of an update transaction

const (
	// TransactionPending indicates the transaction is pending
	TransactionPending TransactionStatus = "pending"
	// TransactionInProgress indicates the transaction is in progress
	TransactionInProgress TransactionStatus = "in_progress"
	// TransactionCommitted indicates the transaction is committed
	TransactionCommitted TransactionStatus = "committed"
	// TransactionRolledBack indicates the transaction is rolled back
	TransactionRolledBack TransactionStatus = "rolled_back"
	// TransactionFailed indicates the transaction failed
	TransactionFailed TransactionStatus = "failed"
)

type UpdateApplier

type UpdateApplier struct {
	// InstallDir is the directory where the tool is installed
	InstallDir string
	// TempDir is the directory for temporary files during update
	TempDir string
	// BackupDir is the directory for backups during update
	BackupDir string
	// CurrentVersions contains the current versions of components
	CurrentVersions map[string]version.Version
	// Logger is the logger for update operations
	Logger io.Writer
}

UpdateApplier handles applying updates from packages

func NewUpdateApplier

func NewUpdateApplier(options *ApplierOptions) (*UpdateApplier, error)

NewUpdateApplier creates a new UpdateApplier

func (*UpdateApplier) ApplyUpdate

func (a *UpdateApplier) ApplyUpdate(ctx context.Context, pkg *UpdatePackage) error

ApplyUpdate applies an update from the given package

func (*UpdateApplier) UpdateWithCustomizationPreservation

func (a *UpdateApplier) UpdateWithCustomizationPreservation(ctx context.Context, pkg *UpdatePackage) error

UpdateWithCustomizationPreservation extends the UpdateApplier to add customization preservation

type UpdateCheck

type UpdateCheck struct {
	CheckTime        time.Time
	UpdatesAvailable bool
	Components       map[string]*ComponentUpdate
}

UpdateCheck represents the result of checking for updates

type UpdateComponent

type UpdateComponent string

UpdateComponent represents a component being updated

const (
	// BinaryUpdateComponent represents the binary component
	BinaryUpdateComponent UpdateComponent = "binary"
	// TemplatesUpdateComponent represents the templates component
	TemplatesUpdateComponent UpdateComponent = "templates"
	// ModuleUpdateComponent represents a module component
	ModuleUpdateComponent UpdateComponent = "module"
)

type UpdateDownloader

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

UpdateDownloader handles downloading files for updates

func NewUpdateDownloader

func NewUpdateDownloader(config *Config, logger Logger) *UpdateDownloader

NewUpdateDownloader creates a new update downloader

func (*UpdateDownloader) CleanupTempFiles

func (d *UpdateDownloader) CleanupTempFiles() error

CleanupTempFiles removes temporary download files

func (*UpdateDownloader) DownloadArchive

func (d *UpdateDownloader) DownloadArchive(ctx context.Context, url, destDir string, progressCallback ProgressCallback) error

DownloadArchive downloads and extracts an archive

func (*UpdateDownloader) DownloadFile

func (d *UpdateDownloader) DownloadFile(ctx context.Context, url, filename string) (string, error)

DownloadFile downloads a file from the given URL

func (*UpdateDownloader) DownloadFileToPath

func (d *UpdateDownloader) DownloadFileToPath(ctx context.Context, url, destPath string, progressCallback ProgressCallback) error

DownloadFileToPath downloads a file to a specific path

func (*UpdateDownloader) DownloadFileWithProgress

func (d *UpdateDownloader) DownloadFileWithProgress(ctx context.Context, url, filename string, progressCallback ProgressCallback) (string, error)

DownloadFileWithProgress downloads a file with progress callback

func (*UpdateDownloader) GetDownloadStats

func (d *UpdateDownloader) GetDownloadStats() *DownloadStats

GetDownloadStats returns download statistics

func (*UpdateDownloader) GetFileSize

func (d *UpdateDownloader) GetFileSize(ctx context.Context, url string) (int64, error)

GetFileSize gets the size of a remote file without downloading

func (*UpdateDownloader) VerifyFileSize

func (d *UpdateDownloader) VerifyFileSize(filePath string, expectedSize int64) error

VerifyFileSize verifies that a downloaded file has the expected size

type UpdateError

type UpdateError struct {
	Component string
	Operation string
	Message   string
	Err       error
	Fatal     bool
	Retry     bool
}

UpdateError represents an error during update

func (*UpdateError) Error

func (e *UpdateError) Error() string

Error implements the error interface

func (*UpdateError) Unwrap

func (e *UpdateError) Unwrap() error

Unwrap returns the underlying error

type UpdateExecutionOptions

type UpdateExecutionOptions struct {
	// InstallDir is the directory where the tool is installed
	InstallDir string
	// TempDir is the directory for temporary files during update
	TempDir string
	// BackupDir is the directory for backups during update
	BackupDir string
	// LogDir is the directory for log files
	LogDir string
	// CurrentVersions contains the current versions of components
	CurrentVersions map[string]version.Version
	// Logger is the logger for update operations
	Logger io.Writer
	// MinLogLevel is the minimum log level to output
	MinLogLevel LogLevel
	// IncludeLogDetails determines whether to include details in log output
	IncludeLogDetails bool
	// NotificationHandlers is the list of notification handlers
	NotificationHandlers []NotificationHandler
	// User is the user performing the update
	User string
	// PreUpdateHooks are functions to run before the update
	PreUpdateHooks []UpdateHook
	// PostUpdateHooks are functions to run after the update
	PostUpdateHooks []UpdateHook
	// VerificationHooks are functions to run for verification
	VerificationHooks []VerificationHook
}

UpdateExecutionOptions contains options for update execution

type UpdateExecutor

type UpdateExecutor struct {
	// InstallDir is the directory where the tool is installed
	InstallDir string
	// TempDir is the directory for temporary files during update
	TempDir string
	// BackupDir is the directory for backups during update
	BackupDir string
	// LogDir is the directory for log files
	LogDir string
	// CurrentVersions contains the current versions of components
	CurrentVersions map[string]version.Version
	// Logger is the logger for update operations
	Logger *UpdateLogger
	// AuditLogger is the logger for audit events
	AuditLogger *AuditLogger
	// NotificationManager is the manager for notifications
	NotificationManager *NotificationManager
	// Verifier is the integrity verifier
	Verifier *IntegrityVerifier
	// User is the user performing the update
	User string
	// PreUpdateHooks are functions to run before the update
	PreUpdateHooks []UpdateHook
	// PostUpdateHooks are functions to run after the update
	PostUpdateHooks []UpdateHook
	// VerificationHooks are functions to run for verification
	VerificationHooks []VerificationHook
}

UpdateExecutor handles the execution of updates

func NewUpdateExecutor

func NewUpdateExecutor(options *UpdateExecutionOptions) (*UpdateExecutor, error)

NewUpdateExecutor creates a new update executor

func (*UpdateExecutor) ExecuteUpdate

func (e *UpdateExecutor) ExecuteUpdate(ctx context.Context, pkg *UpdatePackage) error

ExecuteUpdate executes an update from the given package

type UpdateHook

type UpdateHook func(ctx context.Context, transaction *UpdateTransaction) error

UpdateHook is a function that runs before or after an update

type UpdateInfo

type UpdateInfo struct {
	Component      string
	CurrentVersion version.Version
	LatestVersion  version.Version
	ChangeType     version.VersionChangeType
	ChangelogURL   string
	ReleaseDate    time.Time
	ReleaseNotes   string
	DownloadURL    string
	Signature      string
	ChecksumSHA256 string
	Required       bool // Indicates if this update is required
	SecurityFixes  bool // Indicates if this update contains security fixes
}

UpdateInfo represents information about an available update

func MergeUpdates

func MergeUpdates(githubUpdates, gitlabUpdates []UpdateInfo) []UpdateInfo

MergeUpdates combines updates from multiple sources, with priority rules

type UpdateLogger

type UpdateLogger struct {
	// Writer is the writer for log output
	Writer io.Writer
	// JSONWriter is the writer for JSON log output
	JSONWriter io.Writer
	// MinLevel is the minimum log level to output
	MinLevel LogLevel
	// IncludeDetails determines whether to include details in log output
	IncludeDetails bool
}

UpdateLogger handles logging for update operations

func NewUpdateLogger

func NewUpdateLogger(options *LoggerOptions) *UpdateLogger

NewUpdateLogger creates a new update logger

func (*UpdateLogger) Debug

func (l *UpdateLogger) Debug(component, message string, transactionID string, details map[string]interface{})

Debug logs a debug message

func (*UpdateLogger) Error

func (l *UpdateLogger) Error(component, message string, transactionID string, details map[string]interface{})

Error logs an error message

func (*UpdateLogger) Info

func (l *UpdateLogger) Info(component, message string, transactionID string, details map[string]interface{})

Info logs an informational message

func (*UpdateLogger) Log

func (l *UpdateLogger) Log(level LogLevel, component, message string, transactionID string, details map[string]interface{})

Log logs a message

func (*UpdateLogger) Warning

func (l *UpdateLogger) Warning(component, message string, transactionID string, details map[string]interface{})

Warning logs a warning message

type UpdateManager

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

UpdateManager handles all update operations for the tool

func NewUpdateManager

func NewUpdateManager(config *Config, logger Logger) *UpdateManager

NewManager creates a new update manager

func (*UpdateManager) ApplyUpdates

func (m *UpdateManager) ApplyUpdates(ctx context.Context, components []string) (*UpdateSummary, error)

ApplyUpdates applies all available updates

func (*UpdateManager) CheckForUpdates

func (m *UpdateManager) CheckForUpdates(ctx context.Context) (*UpdateCheck, error)

CheckForUpdates checks for available updates for all components

type UpdateManifest

type UpdateManifest struct {
	Version      string            `json:"version"`
	Components   []ComponentInfo   `json:"components"`
	Checksums    map[string]string `json:"checksums"`
	Signatures   map[string]string `json:"signatures"`
	Timestamp    time.Time         `json:"timestamp"`
	MinVersion   string            `json:"min_version"`
	MaxVersion   string            `json:"max_version"`
	ChangelogURL string            `json:"changelog_url"`
}

UpdateManifest represents metadata about updates

type UpdateNotifier

type UpdateNotifier interface {
	HandleUpdateCheck(ctx context.Context, versionInfo *UpdateVersionInfo) error
	NotifyUpdateSuccess(ctx context.Context, fromVersion, toVersion string) error
	NotifyUpdateFailure(ctx context.Context, fromVersion, toVersion string, err error) error
}

UpdateNotifier defines the interface for notifying about updates

type UpdateOperation

type UpdateOperation struct {
	// Component is the component being updated
	Component UpdateComponent
	// ComponentID is the ID of the component (e.g., module ID)
	ComponentID string
	// SourcePath is the path to the source files
	SourcePath string
	// DestinationPath is the path to the destination files
	DestinationPath string
	// BackupPath is the path to the backup files
	BackupPath string
	// Status is the status of the operation
	Status TransactionStatus
	// Error is any error that occurred during the operation
	Error error
	// Timestamp is the time the operation was performed
	Timestamp time.Time
}

UpdateOperation represents an operation in an update transaction

type UpdateOptions

type UpdateOptions struct {
	Components        []string
	ForceUpdate       bool
	SkipVerification  bool
	SkipBackup        bool
	DryRun            bool
	Verbose           bool
	AutoConfirm       bool
	IncludePrerelease bool
	MaxRetries        int
	Timeout           time.Duration
	ProgressCallback  func(*UpdateProgress)
	ErrorCallback     func(*UpdateError) bool // Return true to continue
}

UpdateOptions represents options for update operations

type UpdatePackage

type UpdatePackage struct {
	Manifest    PackageManifest
	PackagePath string
	// contains filtered or unexported fields
}

UpdatePackage represents an update package

func OpenPackage

func OpenPackage(path string) (*UpdatePackage, error)

OpenPackage opens an update package from the given path

func (*UpdatePackage) Close

func (p *UpdatePackage) Close() error

Close closes the update package

func (*UpdatePackage) ExtractDirectory

func (p *UpdatePackage) ExtractDirectory(dirPath, destPath string) error

ExtractDirectory extracts a directory from the package to the given path

func (*UpdatePackage) ExtractFile

func (p *UpdatePackage) ExtractFile(filePath, destPath string) error

ExtractFile extracts a file from the package to the given path

func (*UpdatePackage) GetBinaryPatchPath

func (p *UpdatePackage) GetBinaryPatchPath(platform, fromVersion, toVersion string) string

GetBinaryPatchPath returns the path to a binary patch in the package

func (*UpdatePackage) GetBinaryPath

func (p *UpdatePackage) GetBinaryPath(platform string) string

GetBinaryPath returns the path to the binary in the package for the given platform

func (*UpdatePackage) GetModulePatchPath

func (p *UpdatePackage) GetModulePatchPath(moduleID, fromVersion, toVersion string) string

GetModulePatchPath returns the path to a module patch in the package

func (*UpdatePackage) GetModulePath

func (p *UpdatePackage) GetModulePath(moduleID string) string

GetModulePath returns the path to a module in the package

func (*UpdatePackage) GetTemplatesPatchPath

func (p *UpdatePackage) GetTemplatesPatchPath(fromVersion, toVersion string) string

GetTemplatesPatchPath returns the path to a templates patch in the package

func (*UpdatePackage) GetTemplatesPath

func (p *UpdatePackage) GetTemplatesPath() string

GetTemplatesPath returns the path to the templates in the package

func (*UpdatePackage) HasRequiredUpdates

func (p *UpdatePackage) HasRequiredUpdates() bool

HasRequiredUpdates checks if the package contains any required updates

func (*UpdatePackage) IsCompatible

func (p *UpdatePackage) IsCompatible(currentVersions map[string]version.Version) (bool, error)

IsCompatible checks if the update package is compatible with the current version

func (*UpdatePackage) Verify

func (p *UpdatePackage) Verify(publicKey ed25519.PublicKey) error

Verify verifies the integrity and authenticity of the update package

type UpdatePermissions

type UpdatePermissions struct {
	CanWriteExecutable bool
	CanWriteDirectory  bool
	RequiresElevation  bool
	RunningAsRoot      bool
	Platform           string
}

UpdatePermissions represents the permissions available for updating

type UpdateProgress

type UpdateProgress struct {
	Component     string
	Operation     string
	Progress      float64
	Total         int64
	Current       int64
	Message       string
	StartTime     time.Time
	EstimatedTime time.Duration
}

UpdateProgress represents progress of an update operation

type UpdateRequest

type UpdateRequest struct {
	Components []string `json:"components,omitempty"` // ["core", "templates", "modules"]
	Force      bool     `json:"force,omitempty"`
	DryRun     bool     `json:"dry_run,omitempty"`
}

UpdateRequest represents an update operation request

type UpdateResponse

type UpdateResponse struct {
	Status   string         `json:"status"`
	Updates  []UpdateResult `json:"updates"`
	Messages []string       `json:"messages,omitempty"`
}

UpdateResponse contains update operation results

type UpdateResult

type UpdateResult struct {
	Component  string `json:"component"`
	OldVersion string `json:"old_version"`
	NewVersion string `json:"new_version"`
	Status     string `json:"status"`
	Message    string `json:"message,omitempty"`
}

UpdateResult represents the result of updating a component

type UpdateStatistics

type UpdateStatistics struct {
	TotalUpdates       int            `json:"total_updates"`
	SuccessfulUpdates  int            `json:"successful_updates"`
	FailedUpdates      int            `json:"failed_updates"`
	LastUpdateTime     time.Time      `json:"last_update_time"`
	AverageUpdateTime  time.Duration  `json:"average_update_time"`
	TotalDownloadSize  int64          `json:"total_download_size"`
	UpdatesByComponent map[string]int `json:"updates_by_component"`
	ErrorsByType       map[string]int `json:"errors_by_type"`
}

UpdateStatistics represents statistics about updates

type UpdateSummary

type UpdateSummary struct {
	Results         []ManagerUpdateResult
	TotalDuration   time.Duration
	Success         bool
	RestartRequired bool
}

UpdateSummary contains summary of all updates

type UpdateTransaction

type UpdateTransaction struct {
	// ID is the unique identifier for the transaction
	ID string
	// PackageID is the ID of the update package
	PackageID string
	// Status is the status of the transaction
	Status TransactionStatus
	// Operations is the list of operations in the transaction
	Operations []*UpdateOperation
	// StartTime is the time the transaction started
	StartTime time.Time
	// EndTime is the time the transaction ended
	EndTime time.Time
	// Logger is the logger for transaction operations
	Logger io.Writer
	// SessionDir is the directory for temporary files during the transaction
	SessionDir string
	// BackupDir is the directory for backups during the transaction
	BackupDir string
}

UpdateTransaction represents a transaction for applying an update

func NewUpdateTransaction

func NewUpdateTransaction(packageID, sessionDir, backupDir string, logger io.Writer) *UpdateTransaction

NewUpdateTransaction creates a new update transaction

func (*UpdateTransaction) AddOperation

func (t *UpdateTransaction) AddOperation(component UpdateComponent, componentID, sourcePath, destPath, backupPath string) *UpdateOperation

AddOperation adds an operation to the transaction

func (*UpdateTransaction) Begin

func (t *UpdateTransaction) Begin() error

Begin begins the transaction

func (*UpdateTransaction) Commit

func (t *UpdateTransaction) Commit() error

Commit commits the transaction

func (*UpdateTransaction) ExecuteOperation

func (t *UpdateTransaction) ExecuteOperation(ctx context.Context, operation *UpdateOperation) error

ExecuteOperation executes an operation in the transaction

func (*UpdateTransaction) GetFailedOperations

func (t *UpdateTransaction) GetFailedOperations() []*UpdateOperation

GetFailedOperations returns operations that failed

func (*UpdateTransaction) GetOperationsByComponent

func (t *UpdateTransaction) GetOperationsByComponent(component UpdateComponent) []*UpdateOperation

GetOperationsByComponent returns operations for a specific component

func (*UpdateTransaction) GetOperationsByStatus

func (t *UpdateTransaction) GetOperationsByStatus(status TransactionStatus) []*UpdateOperation

GetOperationsByStatus returns operations with a specific status

func (*UpdateTransaction) GetSummary

func (t *UpdateTransaction) GetSummary() map[string]interface{}

GetSummary returns a summary of the transaction

func (*UpdateTransaction) HasFailedOperations

func (t *UpdateTransaction) HasFailedOperations() bool

HasFailedOperations returns true if any operations failed

func (*UpdateTransaction) Rollback

func (t *UpdateTransaction) Rollback() error

Rollback rolls back the transaction

type UpdateVersionInfo

type UpdateVersionInfo struct {
	CurrentVersion  string
	LatestVersion   string
	UpdateAvailable bool
	RequiredUpdate  bool
	SecurityFixes   bool
	ReleaseDate     string
	ChangelogURL    string
	DownloadURL     string
	Updates         []UpdateInfo
}

UpdateVersionInfo contains information about the current and latest versions

type VerificationHook

type VerificationHook func(ctx context.Context, pkg *UpdatePackage) (*VerificationResult, error)

VerificationHook is a function that runs for verification

type VerificationResult

type VerificationResult struct {
	// Success indicates whether the verification was successful
	Success bool
	// Message contains a human-readable message about the verification
	Message string
	// Details contains additional details about the verification
	Details map[string]interface{}
}

VerificationResult represents the result of a verification operation

type Verifier

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

Verifier handles cryptographic verification of updates

func NewVerifier

func NewVerifier(config *Config, logger Logger) *Verifier

NewVerifier creates a new verifier

func (*Verifier) AddTrustedKey

func (v *Verifier) AddTrustedKey(keyData string) error

AddTrustedKey adds a trusted public key

func (*Verifier) CreateChecksum

func (v *Verifier) CreateChecksum(filePath string, algorithm string) error

CreateChecksum creates a checksum file for a given file

func (*Verifier) GetKeyInfo

func (v *Verifier) GetKeyInfo(keyID string) (*KeyInfo, error)

GetKeyInfo returns information about a trusted key

func (*Verifier) ListTrustedKeys

func (v *Verifier) ListTrustedKeys() []string

ListTrustedKeys returns a list of trusted key IDs

func (*Verifier) RemoveTrustedKey

func (v *Verifier) RemoveTrustedKey(keyID string) error

RemoveTrustedKey removes a trusted public key

func (*Verifier) VerifyBundle

func (v *Verifier) VerifyBundle(bundlePath string) (*FileVerificationResult, error)

VerifyBundle verifies an entire update bundle

func (*Verifier) VerifyFile

func (v *Verifier) VerifyFile(filePath, expectedChecksum, signatureURL string) error

VerifyFile verifies a file's integrity and authenticity

type VersionCheckRequest

type VersionCheckRequest struct {
	ClientID        string            `json:"clientId"`
	CurrentVersions map[string]string `json:"currentVersions"`
	Components      []string          `json:"components"`
	Timestamp       time.Time         `json:"timestamp"`
	Signature       string            `json:"signature,omitempty"`
}

VersionCheckRequest represents a request to check for updates

type VersionCheckResponse

type VersionCheckResponse struct {
	Versions        map[string]DetailedVersionInfo `json:"versions"`
	ServerTimestamp time.Time                      `json:"serverTimestamp"`
	Signature       string                         `json:"signature,omitempty"`
}

VersionCheckResponse represents a response from the version check API

type VersionCheckService

type VersionCheckService struct {
	BaseURL         string
	HTTPClient      *http.Client
	ClientID        string
	SecretKey       []byte
	CurrentVersions map[string]version.Version
	MaxClockSkew    time.Duration
}

VersionCheckService provides enhanced version checking functionality

func NewVersionCheckService

func NewVersionCheckService(baseURL, clientID string, secretKey []byte, currentVersions map[string]version.Version) *VersionCheckService

NewVersionCheckService creates a new VersionCheckService

func (*VersionCheckService) CheckVersions

func (s *VersionCheckService) CheckVersions(ctx context.Context, components []string) ([]UpdateInfo, error)

CheckVersions checks for available updates with enhanced security

type VersionChecker

type VersionChecker struct {
	UpdateServerURL string
	HTTPClient      *http.Client
	CurrentVersions map[string]version.Version
	Notifier        UpdateNotifier
}

VersionChecker provides functionality to check for updates

func NewVersionChecker

func NewVersionChecker(ctx context.Context) (*VersionChecker, error)

NewVersionChecker creates a new VersionChecker

func NewVersionCheckerWithURL

func NewVersionCheckerWithURL(updateServerURL string, currentVersions map[string]version.Version) *VersionChecker

NewVersionCheckerWithURL creates a new VersionChecker with the given update server URL and current versions

func (*VersionChecker) CheckForUpdates

func (vc *VersionChecker) CheckForUpdates() ([]UpdateInfo, error)

CheckForUpdates checks if updates are available for components

func (*VersionChecker) CheckForUpdatesContext

func (vc *VersionChecker) CheckForUpdatesContext(ctx context.Context) ([]ExtendedUpdateInfo, error)

CheckForUpdatesContext checks for updates with context support

func (*VersionChecker) CheckVersion

func (vc *VersionChecker) CheckVersion(ctx context.Context) (*UpdateVersionInfo, error)

CheckVersion checks if updates are available and returns version information

func (*VersionChecker) SetNotifier

func (vc *VersionChecker) SetNotifier(notifier UpdateNotifier)

SetNotifier sets the notifier for the version checker

type VersionInfo

type VersionInfo struct {
	Current         string    `json:"current"`
	Latest          string    `json:"latest,omitempty"`
	UpdateAvailable bool      `json:"update_available"`
	ReleaseDate     time.Time `json:"release_date,omitempty"`
	Changelog       string    `json:"changelog_url,omitempty"`
}

VersionInfo contains version information

type VersionManifest

type VersionManifest struct {
	Core struct {
		Version        string    `json:"version"`
		ReleaseDate    time.Time `json:"releaseDate"`
		ChangelogURL   string    `json:"changelogURL"`
		ReleaseNotes   string    `json:"releaseNotes"`
		DownloadURL    string    `json:"downloadURL"`
		Signature      string    `json:"signature"`
		ChecksumSHA256 string    `json:"checksumSHA256"`
	} `json:"core"`
	Templates struct {
		Version        string    `json:"version"`
		ReleaseDate    time.Time `json:"releaseDate"`
		ChangelogURL   string    `json:"changelogURL"`
		DownloadURL    string    `json:"downloadURL"`
		Signature      string    `json:"signature"`
		ChecksumSHA256 string    `json:"checksumSHA256"`
	} `json:"templates"`
	Modules []struct {
		ID             string    `json:"id"`
		Name           string    `json:"name"`
		Version        string    `json:"version"`
		ReleaseDate    time.Time `json:"releaseDate"`
		ChangelogURL   string    `json:"changelogURL"`
		DownloadURL    string    `json:"downloadURL"`
		Signature      string    `json:"signature"`
		ChecksumSHA256 string    `json:"checksumSHA256"`
	} `json:"modules"`
}

VersionManifest represents the version information from the update server

type WebhookNotificationHandler

type WebhookNotificationHandler struct {
	// URL is the URL of the webhook
	URL string
	// Headers are the HTTP headers to include in the webhook request
	Headers map[string]string
}

WebhookNotificationHandler handles notifications by sending them to a webhook

func NewWebhookNotificationHandler

func NewWebhookNotificationHandler(url string, headers map[string]string) *WebhookNotificationHandler

NewWebhookNotificationHandler creates a new webhook notification handler

func (*WebhookNotificationHandler) HandleNotification

func (h *WebhookNotificationHandler) HandleNotification(notification *Notification) error

HandleNotification handles a notification by sending it to a webhook

Directories

Path Synopsis
Example program demonstrating the usage of downgrade protection
Example program demonstrating the usage of downgrade protection

Jump to

Keyboard shortcuts

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