update

package
v0.0.0-...-cab72fd Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0

Documentation

Overview

Package update finds, verifies and installs new releases of WittyMediaServer from its GitHub releases.

Nothing is installed unless the release's checksum list carries a valid Ed25519 signature from a key built into this program, and the downloaded archive matches its checksum. Installing replaces the program's files next to the running ones and never touches the data folder.

Index

Constants

View Source
const (
	MethodApply     = "apply"     // Update now: the server replaces its own files
	MethodInstaller = "installer" // Download the installer, then run it
	MethodDocker    = "docker"    // pull the new image and recreate the container
)

How an admin updates this copy, in Status.Method.

View Source
const (
	InstallerDownloading = "downloading"
	InstallerVerifying   = "verifying"
	InstallerReady       = "ready"
	InstallerFailed      = "failed"
)

Installer phases.

View Source
const (
	// Repo is where releases are published.
	Repo = "wittywilla/WittyMediaServer"
	// ReleasesPage is shown when a release can't be installed from the app.
	ReleasesPage = "https://github.com/" + Repo + "/releases"
)
View Source
const (
	PhaseIdle        = "idle"
	PhaseDownloading = "downloading"
	PhaseVerifying   = "verifying"
	PhaseInstalling  = "installing"
	PhaseRestarting  = "restarting"
	PhaseFailed      = "failed"
)

Phases of an update, shown in Settings.

View Source
const ExitRestart = 75

ExitRestart is the exit code with which the server asks the program that started it (the tray app, systemd) to start it again after an update.

View Source
const StageDir = ".update"

StageDir is the folder inside the program folder where an update is downloaded and unpacked (on the same drive, so files move instantly).

Variables

View Source
var ErrBadSignature = errors.New("the release's signature does not match a trusted key; it was not installed")

ErrBadSignature: the checksum list is not signed by a trusted key.

View Source
var ErrNotFound = errors.New("GitHub answered 404 Not Found")

ErrNotFound: GitHub has no such repository or file.

Functions

func ArchiveName

func ArchiveName(ver, goos, goarch string) string

ArchiveName is the release package for a platform, as built by scripts/build-release.sh.

func Cleanup

func Cleanup(dir string)

Cleanup runs at start: it deletes the files an update set aside (those still in use stay listed for next time) and anything left in the staging folder by an update that did not finish. It only ever deletes *.old files it recorded and its own staging folder.

func Compare

func Compare(a, b string) int

Compare orders two versions: -1 if a is older than b, 0 if equal, 1 if newer. A pre-release (0.4.0-alpha) comes before its release (0.4.0). Versions that cannot be read sort before everything else.

func Extract

func Extract(archive, dest string, maxTotal int64) error

Extract unpacks a release package (.tar.gz, or else a zip, which may follow a program as in the Windows setup) into dest, without its top-level folder. Links, absolute paths and paths that climb out of dest are refused; anything a package must never bring (see SkipPath) is left out. At most maxTotal bytes are written.

func FileSHA256

func FileSHA256(path string) (string, error)

FileSHA256 returns the lowercase hex SHA-256 of a file.

func InstallerName

func InstallerName(ver, goos, goarch, kind string) string

InstallerName is the release file that updates a copy installed as kind, or "" when the release has none for this system.

func ModuleCatalog

func ModuleCatalog() string

ModuleCatalog is where the signed list of modules is.

func ModuleKeys

func ModuleKeys() []ed25519.PublicKey

ModuleKeys are the keys a plugin's release may be signed with. A key that signs only plugins lives in many repositories' secrets; it never appears in TrustedKeys, so if it leaks it still can't sign a server.

func ParseSums

func ParseSums(b []byte) (map[string]string, error)

ParseSums reads a sha256sum-style list ("<hex> <name>" or "<hex> *<name>") into name → lowercase hex digest.

func RecordOld

func RecordOld(dir string, olds []string) error

RecordOld adds replaced files to the list Cleanup removes.

func Sign

func Sign(key ed25519.PrivateKey, sums []byte) []byte

Sign returns the .sig file contents for a checksum list.

func SkipPath

func SkipPath(rel string) bool

skipPath: files a package must never bring into the program folder. The data folder holds the library, accounts and progress of a copy run in place, and wms.json is its owner's configuration.

func SumsName

func SumsName(ver string) string

SumsName is a release's checksum list.

func Swap

func Swap(dir, staged string, protect []string) ([]string, error)

Swap moves every file under staged into dir. A file it replaces is first renamed to <name>.old (Windows lets a running program be renamed, not overwritten) and deleted on the next start by Cleanup. Nothing inside protect, the data folder or wms.json is ever written, and files that are not in the package are left alone. If a step fails, every file is put back as it was.

func TrustedKeys

func TrustedKeys() []ed25519.PublicKey

TrustedKeys are the keys a release must be signed with.

func Valid

func Valid(s string) bool

Valid reports whether s is a version this package can compare.

func VerifySums

func VerifySums(sums, sig []byte, keys []ed25519.PublicKey) error

VerifySums checks sig (the .sig file: base64 of an Ed25519 signature) against the exact bytes of the checksum list.

func WithdrawalsAsset

func WithdrawalsAsset() string

WithdrawalsAsset is the list's file on that release; its signature adds .sig.

Types

type Asset

type Asset struct {
	Name    string `json:"name"`
	URL     string `json:"url"`
	Size    int64  `json:"size"`
	Updated string `json:"updated,omitempty"` // when it was uploaded, as GitHub says it
}

Asset is one file attached to a release.

type Change

type Change struct {
	Version string `json:"version"`
	Notes   string `json:"notes"`
}

Change is what one version changed, in Markdown.

type Fetcher

type Fetcher struct {
	UserAgent string
	Transport http.RoundTripper
}

Fetcher downloads from GitHub, and from nowhere else. Plugins' releases use it too (internal/modules), so everything this server installs comes the same way.

func (*Fetcher) Get

func (f *Fetcher) Get(ctx context.Context, raw string, accept string) (*http.Response, error)

Get asks for an address; the caller closes the answer's body.

func (*Fetcher) ReleaseByTag

func (f *Fetcher) ReleaseByTag(ctx context.Context, repo, tag string) (*GHRelease, error)

ReleaseByTag asks for one release of a repository by its tag.

func (*Fetcher) Releases

func (f *Fetcher) Releases(ctx context.Context, repo string) ([]GHRelease, error)

Releases lists a repository's releases, newest first as GitHub gives them.

func (*Fetcher) ReleasesSince

func (f *Fetcher) ReleasesSince(ctx context.Context, repo, etag string) (rels []GHRelease, newEtag string, unchanged bool, err error)

ReleasesSince lists a repository's releases unless they are unchanged since the answer that carried etag; then unchanged is true and the list is nil. newEtag goes with the next call.

func (*Fetcher) Small

func (f *Fetcher) Small(ctx context.Context, raw string, limit int64) ([]byte, error)

Small downloads a small file completely, refusing anything larger than limit.

type GHAsset

type GHAsset struct {
	Name    string `json:"name"`
	Size    int64  `json:"size"`
	URL     string `json:"browser_download_url"`
	Updated string `json:"updated_at,omitempty"`
}

GHAsset is one file of a release, in GitHub's list.

type GHRelease

type GHRelease struct {
	TagName     string    `json:"tag_name"`
	Name        string    `json:"name"`
	Body        string    `json:"body"`
	HTMLURL     string    `json:"html_url"`
	Draft       bool      `json:"draft"`
	Prerelease  bool      `json:"prerelease"`
	PublishedAt time.Time `json:"published_at"`
	Assets      []GHAsset `json:"assets"`
}

GHRelease is one entry of GitHub's list of a repository's releases.

type Info

type Info struct {
	Version    string `json:"version"`
	Title      string `json:"title"`
	Notes      string `json:"notes"`
	URL        string `json:"url"`
	Published  int64  `json:"published,omitempty"` // unix ms
	Prerelease bool   `json:"prerelease"`
	Signed     bool   `json:"signed"`
	Size       int64  `json:"size"`
	// Changes is what changed in each version after the running one, newest first.
	Changes []Change `json:"changes,omitempty"`
}

Info describes the newest release for this system.

type Installer

type Installer struct {
	Name  string `json:"name"`
	Size  int64  `json:"size"`
	Phase string `json:"phase,omitempty"`
	Done  int64  `json:"done,omitempty"`
	Error string `json:"error,omitempty"`
	// Once it's checked: where it is on the server's computer, and for packages a package
	// manager installs, the command that installs it.
	Path    string `json:"path,omitempty"`
	Command string `json:"command,omitempty"`
}

Installer is the installer for this copy and where its download stands.

type RateLimited

type RateLimited struct{ Until time.Time }

RateLimited: GitHub asked this network to wait. Asking again before Until only makes the wait longer, so callers hold off until then.

func (*RateLimited) Error

func (e *RateLimited) Error() string

type Release

type Release struct {
	Version    string
	Title      string
	Notes      string
	Page       string
	Published  time.Time
	Prerelease bool
	Archive    Asset            // the package for this OS and architecture
	Sums       Asset            // wittymediaserver-<version>-SHA256SUMS.txt
	Sig        Asset            // its .sig
	Assets     map[string]Asset // every file, by name (the installers among them)
}

Release is a published version with the files this system needs.

func (*Release) Signed

func (r *Release) Signed() bool

Signed: the release carries a checksum list and its signature.

type Status

type Status struct {
	Current string `json:"current"`
	Latest  *Info  `json:"latest,omitempty"` // only when newer than Current
	// Withdrawn is why the running version was taken back, by the project's signed list.
	Withdrawn  string `json:"withdrawn,omitempty"`
	CheckedAt  int64  `json:"checkedAt,omitempty"`
	CheckError string `json:"checkError,omitempty"`
	Phase      string `json:"phase"`
	Done       int64  `json:"done,omitempty"` // bytes downloaded
	Total      int64  `json:"total,omitempty"`
	Error      string `json:"error,omitempty"` // why the last install failed
	CanApply   bool   `json:"canApply"`
	Reason     string `json:"reason,omitempty"` // why this copy can't update itself
	Page       string `json:"page"`
	// Method is how an admin updates this copy (MethodApply, MethodInstaller, MethodDocker),
	// or "" when only the release page can help.
	Method    string     `json:"method,omitempty"`
	Installer *Installer `json:"installer,omitempty"` // with MethodInstaller
	Image     string     `json:"image,omitempty"`     // with MethodDocker: the image to pull
}

Status is what Settings shows.

type Updater

type Updater struct {
	// Tasks is where an update shows in the activity panel. May be nil.
	Tasks *tasks.Registry

	Current   string            // the running version
	Dir       string            // the program's top folder
	Protect   []string          // folders and files never written (data, cache, config…)
	Transport http.RoundTripper // internet-only transport for GitHub
	Log       *slog.Logger
	// Restart is called once the new files are in place; it should stop the
	// server and start the new version.
	Restart func()
	// DownloadDir is where an installer is kept for the admin to run. Empty: none is offered.
	DownloadDir string
	// contains filtered or unexported fields
}

Updater checks for, downloads and installs releases.

func New

func New(current, dir string, protect []string, tr http.RoundTripper, log *slog.Logger) *Updater

New prepares an updater for the program in dir.

func (*Updater) Apply

func (u *Updater) Apply() error

Apply starts installing the newest release in the background. Progress is in Status; on success Restart is called.

func (*Updater) Available

func (u *Updater) Available() string

Available returns the newer version found by the last check, or "".

func (*Updater) Check

func (u *Updater) Check(ctx context.Context, maxAge time.Duration) Status

Check asks GitHub for releases unless the last answer is younger than maxAge. Concurrent calls share one request.

func (*Updater) CleanDownloads

func (u *Updater) CleanDownloads()

CleanDownloads, at start, removes installers that are no longer newer than what runs.

func (*Updater) FetchInstaller

func (u *Updater) FetchInstaller() error

FetchInstaller starts downloading the newest release's installer in the background. Progress is in Status().Installer.

func (*Updater) InstallerFile

func (u *Updater) InstallerFile() (path, name string, ok bool)

InstallerFile is the checked installer, once it's ready, and only while it's the one for the newest version found.

func (*Updater) Kind

func (u *Updater) Kind() string

Kind says how this copy was installed.

func (*Updater) LoadWithdrawals

func (u *Updater) LoadWithdrawals(file string)

LoadWithdrawals reads the list kept from earlier checks. Without a place to keep it, a list is only remembered until the server next starts.

func (*Updater) Run

func (u *Updater) Run(ctx context.Context, enabled func() bool)

Run checks at start (after a short pause) and then twice a day while enabled() says automatic checks are on.

func (*Updater) Status

func (u *Updater) Status() Status

Status returns the last known state.

Jump to

Keyboard shortcuts

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