updater
import "github.com/tangoui/tango/service/updater"本页由
site/tools/apigen从源码注释生成(按 darwin 构建标签选文件),请勿手改。
Package updater keeps a Tango desktop app up to date: it fetches a signed update manifest, refuses anything older than what it runs (or has seen), downloads a binary patch or the full release, verifies it, installs it once the app quits, and rolls back if the new version does not confirm that it starts.
u := &updater.Updater{
ManifestURL: "https://example.com/notes/latest.json",
PublicKey: "…", // from tan keygen
Version: "1.3.2",
AppID: "com.example.notes",
OnEvent: func(e updater.Event) { … }, // drive your own UI
}
outcome, _ := u.Confirm() // early in every launch
rel, err := u.Check(ctx) // nil, nil: up to date
p, err := u.Download(ctx, rel, "") // patch first, full file as fallback
err = u.Apply(p) // then quit; the new version starts
See docs/updates.md for the manifest format, the security model and how each platform installs an update. tan release-manifest builds and signs the manifest and patches.
常量
const (
// FormatApp: a .zip or .tar.gz holding one macOS .app bundle, which
// replaces the running bundle.
FormatApp = "app"
// FormatDir: a .tar.gz or .zip holding one directory, whose contents
// replace the Linux install directory the executable runs from.
FormatDir = "dir"
// FormatAppImage: a Linux AppImage that replaces $APPIMAGE.
FormatAppImage = "appimage"
// FormatExe: a Windows executable that replaces the running one.
FormatExe = "exe"
// FormatNSIS: a Windows NSIS installer, run silently (/S).
FormatNSIS = "nsis"
// FormatMSI: a Windows Installer package, run with msiexec /qn.
FormatMSI = "msi"
)Formats of update files (Asset.Format).
const DefaultClockSkew = 10 * time.MinuteDefaultClockSkew is how long after its "expires" a manifest is still accepted when Updater.ClockSkew is zero.
const DefaultConfirmTimeout = 60 * time.SecondDefaultConfirmTimeout is how long the helper waits for the new version to call Confirm when Updater.ConfirmTimeout is zero.
变量
var ErrBadSignature = errors.New("updater: manifest signature does not verify")ErrBadSignature is returned when a manifest's signature does not verify with any of the Updater's public keys.
var ErrDowngrade = errors.New("updater: refusing to downgrade")ErrDowngrade is returned by Check for a manifest older than the running version, older than Updater.MinVersion, or older than a manifest it accepted before.
var ErrExpired = errors.New("updater: manifest expired")ErrExpired is returned by Check for a manifest past its "expires" (or without one where Updater.RequireExpiry, or an earlier manifest, asks for it).
var ErrNotWritable = errors.New("updater: the app's folder is not writable")ErrNotWritable is returned by Apply when the folder holding the app cannot be written by the user, so the update cannot be installed in place (Apply never asks for elevated rights).
var ErrPatchBase = errors.New("updater: patch does not apply to this file")ErrPatchBase is returned by Patch when the patch was made from a file other than old.
var ErrUnsupported = errors.New("updater: cannot update this installation")ErrUnsupported is returned where the app cannot be updated in place (unsupported platform, not running from a bundle, AppImage or install directory of the manifest's format).
函数
func CompareVersions
func CompareVersions(a, b string) (int, error)CompareVersions returns -1, 0 or +1 as semantic version a is older than, the same as or newer than b. A leading "v" is allowed.
func Diff
func Diff(old, new []byte) ([]byte, error)Diff returns a patch that turns old into new.
func DiffTree
func DiffTree(oldDir, newDir string, w io.Writer) errorDiffTree writes to w a tree patch that turns the tree at oldDir into the tree at newDir. A tree patch is a gzip-compressed tar archive: an index (index.json) listing the new tree, where each file is copied unchanged from an old file with the same content, patched (Diff) from the old file at the same path, or stored whole; then the patches and stored files.
func GenerateKey
func GenerateKey() (publicKey, privateKey string, err error)GenerateKey returns a new signing key pair, base64-encoded. Embed the public key in the app (Updater.PublicKey); keep the private key secret and pass it to SignManifest when publishing a release.
func PackTree
func PackTree(dir, out string) (err error)PackTree writes the directory dir as a gzip-compressed tar archive to out, with dir's base name as the top directory (Notes.app/...), the layout Apply expects for macOS bundles and Linux install directories. Entries are in path order with fixed times and owners, so packing the same tree twice gives the same archive.
func Patch
func Patch(old, patch []byte) ([]byte, error)Patch applies a patch made by Diff to old and returns the new file, whose SHA-256 digest it checks against the one recorded in the patch. It returns ErrPatchBase when old is not the file the patch was made from. The new file may be up to 2 GiB; for patches from an untrusted source use PatchMax with the size the new file is expected to have.
func PatchMax
func PatchMax(old, patch []byte, maxSize int64) ([]byte, error)PatchMax is Patch for a new file of at most maxSize bytes: a patch that claims a larger output is refused before anything is allocated for it. A malformed patch is an error, never a panic, and memory use stays within about twice the new file's size plus the patch.
func PatchTree
func PatchTree(oldDir string, r io.Reader, outDir string) (digest string, err error)PatchTree builds in outDir, which must not exist, the tree that the tree patch r makes from the tree at oldDir, and returns the new tree's digest after checking it against the one the patch records. Old files are read and new ones written through os.Root, so neither the patch nor symlinks in either tree reach outside them. outDir is removed on error.
func PublicKeyOf
func PublicKeyOf(privateKey string) (string, error)PublicKeyOf returns the public key of privateKey (GenerateKey's private key, or a base64 32-byte seed).
func SignManifest
func SignManifest(privateKey string, m *Manifest) ([]byte, error)SignManifest validates m and returns the signed envelope to publish.
func TreeDigest
func TreeDigest(dir string) (string, error)TreeDigest returns the hex SHA-256 digest of the directory tree at dir: of a listing, in path order, of every directory, symlink (with its target) and regular file (with its executable bit and content digest) below dir. Ownership, times and other permission bits do not count, so a tree unpacked from an archive and the tree it was packed from have the same digest. Other file types are errors.
func Unpack
func Unpack(archive, dst string) (string, error)Unpack extracts archive (.tar.gz, .tgz or .zip holding one top-level directory, as PackTree writes) into the existing directory dst and returns the path of that top directory. Entries may not escape dst.
类型
Asset
type Asset struct {
Format string `json:"format"`
File
// TreeSHA256 is the TreeDigest of the unpacked directory (formats app
// and dir), which a tree patch must reproduce.
TreeSHA256 string `json:"tree_sha256,omitempty"`
Patches []PatchAsset `json:"patches,omitempty"`
}Asset is one platform's update: the full file and patches from earlier versions.
Event
type Event struct {
Kind EventKind `json:"kind"`
Release *Release `json:"release,omitempty"`
Patch bool `json:"patch,omitempty"`
Done int64 `json:"done,omitempty"`
Total int64 `json:"total,omitempty"`
Error string `json:"error,omitempty"`
}Event reports progress to the app's update UI.
EventKind
type EventKind stringEventKind names an Event.
const (
EventChecking EventKind = "checking" // Check started
EventAvailable EventKind = "available" // a newer release exists (Release set)
EventUpToDate EventKind = "up-to-date" // no newer release
EventDownloading EventKind = "downloading" // a download started (Patch: is it the patch)
EventProgress EventKind = "progress" // Done of Total bytes (Total -1 if unknown)
EventPatchFailed EventKind = "patch-failed" // the patch failed (Error); falling back to the full file
EventVerified EventKind = "verified" // the release is downloaded and verified
EventReady EventKind = "ready" // Apply staged the update: quit to restart into it
EventError EventKind = "error" // a step failed (Error)
)File
type File struct {
URL string `json:"url"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
}File is a downloadable file.
func FileInfo
func FileInfo(path, url string) (File, error)FileInfo returns the File entry (size and digest) for the file at path, with url as its URL.
Manifest
type Manifest struct {
// App is the application id. When Updater.AppID is set the manifest
// must name the same app, so one app's manifest cannot be served to
// another app signed with the same key.
App string `json:"app,omitempty"`
Version string `json:"version"`
PubDate time.Time `json:"pub_date"`
// Expires, if set, is when the manifest stops being valid (RFC 3339,
// covered by the signature like every other field). Updater.Check
// refuses an expired manifest, which bounds how long an attacker can
// replay an old one to hold the app back. Re-sign the manifest (tan
// sign-update) before it expires, even without a new release.
Expires time.Time `json:"expires,omitzero"`
Notes string `json:"notes,omitempty"`
// Platforms maps GOOS-GOARCH to that platform's files.
Platforms map[string]Asset `json:"platforms"`
}Manifest describes the latest release. It is published inside a signed envelope (see SignManifest), so every URL and digest in it is covered by the release key:
{
"manifest": {
"app": "com.example.notes",
"version": "1.4.0",
"pub_date": "2026-11-01T12:00:00Z",
"expires": "2026-12-01T12:00:00Z",
"notes": "Faster startup.",
"platforms": {
"darwin-arm64": {
"format": "app",
"url": "Notes-1.4.0-darwin-arm64.app.tar.gz", "size": 9123456, "sha256": "…",
"tree_sha256": "…",
"patches": [{"from": "1.3.0", "url": "Notes-1.3.0-to-1.4.0-darwin-arm64.patch", "size": 81234, "sha256": "…"}]
},
"windows-amd64": {"format": "exe", "url": "Notes-1.4.0-windows-amd64.exe", "size": 8000000, "sha256": "…"},
"linux-amd64": {"format": "appimage", "url": "Notes-1.4.0-linux-amd64.AppImage", "size": 9000000, "sha256": "…"}
}
},
"signature": "…"
}
Platform keys are GOOS-GOARCH. A relative url is resolved against the manifest's URL. sha256 is a file's hex digest; tree_sha256 is the TreeDigest of the unpacked directory for the directory formats.
func ParseManifest
func ParseManifest(b []byte) (*Manifest, error)ParseManifest decodes and validates an unsigned manifest, as written by hand or by a release script before tan sign-update signs it.
func VerifyManifest
func VerifyManifest(envelope []byte, publicKeys ...string) (*Manifest, error)VerifyManifest checks the envelope's signature against publicKeys (any one may match, which allows rotating keys) and only then decodes and validates the manifest.
func (*Manifest) Validate
func (m *Manifest) Validate() errorValidate checks that m is complete and well formed.
Outcome
type Outcome struct {
Status Status `json:"status"`
From string `json:"from,omitempty"`
To string `json:"to,omitempty"`
Reason string `json:"reason,omitempty"` // for StatusRolledBack
}Outcome is what Confirm found.
PatchAsset
type PatchAsset struct {
From string `json:"from"`
File
}PatchAsset turns version From's installation into this release: a binary patch (Diff) of the file for formats exe and appimage, a tree patch (DiffTree) for app and dir.
Payload
type Payload struct {
Release *Release
// Path is the full file (an archive, AppImage, executable or
// installer) or, after a tree patch, the patched directory.
Path string
// Patched reports whether Path was made from a patch.
Patched bool
}Payload is a downloaded, verified release ready for Apply.
Release
type Release struct {
Version string `json:"version"`
Notes string `json:"notes,omitempty"`
PubDate time.Time `json:"pubDate"`
Format string `json:"format"`
Full File `json:"full"` // URL absolute
TreeSHA256 string `json:"-"` // formats app and dir
Patch *File `json:"patch,omitempty"` // from the running version, if published
}Release is a newer release found by Check, with this platform's files.
SignedManifest
type SignedManifest struct {
Manifest json.RawMessage `json:"manifest"`
Signature string `json:"signature"`
}SignedManifest is the published envelope.
Status
type Status stringStatus is the outcome Confirm reports for the last update.
const (
// StatusNone: no update was pending.
StatusNone Status = "none"
// StatusUpdated: this process is the new version; the update is
// confirmed and the previous version will be removed.
StatusUpdated Status = "updated"
// StatusRolledBack: the new version did not confirm in time (or asked
// for a rollback, or could not be installed) and the previous version,
// this process, was restored.
StatusRolledBack Status = "rolled_back"
// StatusPending: an update is still being installed (this process is
// the old version and the helper has not swapped yet).
StatusPending Status = "pending"
)Updater
type Updater struct {
// ManifestURL is where the signed manifest is published.
ManifestURL string
// PublicKey verifies the manifest's signature (tan keygen's .pub).
PublicKey string
// PublicKeys are further accepted keys, for rotating keys: ship the
// new key alongside the old one before signing with it.
PublicKeys []string
// Version is the running app's semantic version.
Version string
// MinVersion, if set, is the oldest release the app accepts: older
// manifests are refused even if newer than Version (say, releases
// with a known flaw).
MinVersion string
// AppID is the app's id. When set, the manifest's "app" must be
// present and match, and state is kept under it (see StateDir). Set
// it whenever more than one app shares a signing key.
AppID string
// RequireExpiry refuses manifests without "expires". When false (the
// default, so manifests signed before expiry existed keep working), a
// manifest without it is accepted until the app has once accepted one
// with it (remembered with StateDir or AppID); an expired manifest is
// always refused. Turn it on once every published manifest carries
// expires (tan release-manifest and tan sign-update write it).
RequireExpiry bool
// ClockSkew is how far past "expires" a manifest is still accepted,
// for clocks running fast; DefaultClockSkew if zero, none if negative.
ClockSkew time.Duration
// Platform selects the manifest entry; runtime.GOOS-runtime.GOARCH if
// empty.
Platform string
// Client makes the requests; http.DefaultClient if nil.
Client *http.Client
// Target is the installation to update: the .app bundle (macOS), the
// executable (Windows), the AppImage or the install directory (Linux).
// If empty it is found from the running executable (and $APPIMAGE).
Target string
// StateDir keeps the update state (pending update, confirmation, the
// newest manifest seen). Default: <user config dir>/tango-updater/
// <AppID or executable name>. Remembering the newest manifest (which
// stops replays of older ones) needs StateDir or AppID set.
StateDir string
// ConfirmTimeout is how long after relaunching the helper waits for
// the new version's Confirm before rolling back; DefaultConfirmTimeout
// if zero.
ConfirmTimeout time.Duration
// InstallerArgs are extra arguments for FormatNSIS and FormatMSI
// installers (after /S, or after /i <file> /qn).
InstallerArgs []string
// OnEvent, if set, receives progress events for the app's own UI. It
// is called on the goroutine running Check, Download or Apply.
OnEvent func(Event)
}Updater checks for, downloads and installs releases. Set the fields before use; an Updater is not safe for concurrent use.
func (*Updater) Apply
func (u *Updater) Apply(p *Payload) errorApply installs a Payload from Download once the app has exited, and starts the new version. Quit the app promptly after Apply returns nil (EventReady): a helper process waits for this process to exit, moves the current installation aside, puts the new one in its place and starts it. If the new version does not call Confirm within ConfirmTimeout (or calls Rollback), the helper restores the previous installation and starts it again; Confirm then reports StatusRolledBack.
By format (see docs/updates.md):
- app (macOS): the new bundle is staged next to the running one, cleared of the quarantine attribute and its code signature checked (same Team ID as the running app when that is signed), then swapped in and opened with /usr/bin/open.
- appimage, dir (Linux): the new AppImage or install directory replaces $APPIMAGE or the executable's directory.
- exe (Windows): the new executable is written next to the running one; the helper renames the old one aside, renames the new one into place and starts it, deleting the old one once confirmed.
- nsis, msi (Windows): the helper runs the installer silently (setup.exe /S /D=<dir>, msiexec /i … /qn) and starts the app.
Apply returns ErrUnsupported where the app cannot be updated in place (mobile; not running from a bundle, AppImage or matching install), and ErrNotWritable when the app's folder is not writable.
func (*Updater) Check
func (u *Updater) Check(ctx context.Context) (*Release, error)Check fetches the manifest, verifies its signature and returns the release it describes if it is newer than u.Version, or nil, nil if it is the same version. Manifests older than the running version, older than MinVersion or older than one accepted before fail with ErrDowngrade; expired manifests (see Updater.RequireExpiry) fail with ErrExpired; a newer release without a file for this platform is an error.
func (*Updater) Confirm
func (u *Updater) Confirm() (Outcome, error)Confirm reports how the last update went. Call it early in every launch, once the app has started well enough to count as working: in the new version it confirms the update, so the helper keeps it and deletes the previous version; if it is not called within Updater.ConfirmTimeout of the relaunch, the helper puts the previous version back and starts it. In the restored previous version it returns StatusRolledBack once.
func (*Updater) Download
func (u *Updater) Download(ctx context.Context, rel *Release, dir string) (*Payload, error)Download fetches rel into dir (a new temporary directory if empty) and verifies it. If rel has a patch from the running version and the installation is intact, the patch is downloaded and applied to it, and the result checked against the full release's digest; if any of that fails (EventPatchFailed), the full file is downloaded instead.
func (*Updater) Rollback
func (u *Updater) Rollback() errorRollback asks for the previous version to be restored, from a new version that has not called Confirm yet (say, a data migration failed). Quit after it returns nil: the helper waits for this process to exit, puts the previous version back and starts it.
func (*Updater) Update
func (u *Updater) Update(ctx context.Context) (*Release, error)Update checks, downloads and applies in one go, and returns the release it staged (nil if up to date). Quit the app after it returns a release.