updatecheck

package
v0.70.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package updatecheck provides centralized version checking against GitHub releases.

Index

Constants

View Source
const (
	ChannelHomebrew         = "homebrew"
	ChannelDMG              = "dmg"
	ChannelDeb              = "deb"
	ChannelRPM              = "rpm"
	ChannelDocker           = "docker"
	ChannelGoInstall        = "go-install"
	ChannelWindowsInstaller = "windows-installer"
	ChannelTarball          = "tarball"
	ChannelUnknown          = "unknown"
)

Install channel identifiers (Spec 079 FR-008 / key entity "Install channel").

View Source
const (
	// DefaultCheckInterval is the default interval between update checks.
	// At most a daily check (Spec 079 FR-018): unauthenticated GitHub API
	// calls are rate-limited and update awareness does not need to be fresher
	// than a day.
	DefaultCheckInterval = 24 * time.Hour

	// EnvDisableAutoUpdate disables all update checks when set to "true".
	EnvDisableAutoUpdate = "MCPPROXY_DISABLE_AUTO_UPDATE"

	// EnvAllowPrereleaseUpdates enables prerelease version comparison when set to "true".
	EnvAllowPrereleaseUpdates = "MCPPROXY_ALLOW_PRERELEASE_UPDATES"
)
View Source
const (
	// GitHubRepo is the repository to check for releases
	GitHubRepo = "smart-mcp-proxy/mcpproxy-go"

	// DefaultAPIBase is the public GitHub REST API root.
	DefaultAPIBase = "https://api.github.com"
)
View Source
const (
	// PolicyChannelStable offers only stable releases.
	PolicyChannelStable = "stable"
	// PolicyChannelRC also offers prereleases (docs/prerelease-builds.md).
	PolicyChannelRC = "rc"
)
View Source
const MaxArchiveMemberBytes = 512 << 20

MaxArchiveMemberBytes bounds a single extracted archive member. The core binary is ~60-90 MB; the cap exists so a malicious archive cannot fill the disk before the checksum comparison would have rejected it.

Variables

This section is empty.

Functions

func DetectChannel added in v0.48.0

func DetectChannel(ldflagsVersion string) string

DetectChannel identifies the install channel of the running binary. ldflagsVersion is the build version handed to the checker (see channelDetector.ldflagsVersion). The build-time marker wins; heuristics run in decreasing confidence order and never guess: any ambiguity yields ChannelUnknown so a wrong channel command is never surfaced (FR-009, edge case "channel mis-identification risk").

func ExtractBinary added in v0.69.0

func ExtractBinary(archivePath, memberName, destPath string) error

ExtractBinary pulls the single archive member named memberName (matched on base name, so a future archive that nests files still works) into destPath, which is created with mode 0o700 — the caller re-applies the real mode when swapping it into place. An archive that does not contain memberName is an error: callers install a specific binary, never "whatever was in there".

func FormatBehindSummary added in v0.63.0

func FormatBehindSummary(d ReleaseDelta) string

FormatBehindSummary renders the delta clause every surface prints verbatim — "8 releases / ~14 weeks behind", "59+ releases / ~18 weeks behind", "1 release behind".

It is authored once here, in Go, and shipped pre-rendered in the API payload so the Vue banner, the Swift tray, status and doctor cannot drift apart (FR-002 demands consistent framing across all of them). The raw numbers ship alongside it, so machine consumers never have to parse this string.

Returns "" when there is nothing honest to say; callers then render exactly what they render today.

func GuidanceLine added in v0.48.0

func GuidanceLine(channel, releaseURL string) string

GuidanceLine returns a human-readable guided-update line for updates that carry no safe one-line command, deep-linking the release when releaseURL is provided (FR-010). Callers must only invoke it when no update_command accompanies the update (all callers gate on that), so it never renders next to a command. The command channels (homebrew, deb, rpm, go-install) still reach this function when the offered version is a prerelease — their package managers serve stable artifacts only, so the command was suppressed (see PrereleaseUpdateCommand) — and get the generic release-page line rather than nothing.

func IncludePrereleasesForBuild added in v0.61.0

func IncludePrereleasesForBuild(buildVersion string, cfgPrerelease bool) bool

IncludePrereleasesForBuild applies the full channel precedence for a build version. The running build's own version is authoritative (issue: a stable user must never be offered an RC; an RC user may be offered stable or the next RC). This deliberately overrides the config/env opt-in for RELEASED builds, so a stale `channel: rc` config left over from a previously-installed RC cannot resurrect RC offers on a stable build. Shared by the daemon's Checker and `mcpproxy update` so both resolve the same channel (Spec 079 FR-023).

func ParseChecksums added in v0.69.0

func ParseChecksums(r io.Reader) (map[string]string, error)

ParseChecksums parses a sha256sum-format manifest into name -> lowercase hex digest. The grammar is the one coreutils writes and `sha256sum -c` reads:

<64-hex><space><mode><name>

where <mode> is ' ' (text) or '*' (binary) and <name> is every remaining byte of the line, verbatim. The name is taken as-is rather than tokenised, because everything after those two separator bytes is significant: a name may contain spaces, may begin with '*', and may begin with "./". Treating any of those as syntax would file an entry under a name the manifest never published — i.e. hand back a digest for a different file than the one asked about.

A name containing a backslash, newline or carriage return is written by coreutils in escaped form, marked by a backslash before the digest.

Unparseable lines are skipped rather than failing the whole file: the manifest is generated by CI and a future extra line must not break verification of the entry we need. Three things are NOT tolerated, because each could make a name resolve to a digest published for some other file:

  • a manifest with no usable entries (never read as "nothing to verify"),
  • the same name listed twice with different digests,
  • a manifest large enough to have been truncated by the read cap.

func PrereleaseUpdateCommand added in v0.48.0

func PrereleaseUpdateCommand(channel, version string) string

PrereleaseUpdateCommand returns the one-line update command when the offered release is a prerelease. Prereleases are published only to the GitHub pre-release channel (docs/prerelease-builds.md) — the Homebrew tap and apt/dnf repos serve stable artifacts, and Go's `@latest` module query resolves to the newest stable release — so the generic UpdateCommand output would not deliver the advertised version (FR-009: never emit a command that could be wrong). Only go-install can name the exact version; every other channel returns "" and falls back to guidance/release-URL.

func PromoteGoInstallVersion added in v0.61.0

func PromoteGoInstallVersion(version, channel string) string

PromoteGoInstallVersion is the production-wired form of promoteGoInstallVersion, shared with `mcpproxy update` so the CLI resolves the same build identity (and therefore the same channel precedence) as the daemon's checker (Spec 079 FR-023).

func UpdateCommand added in v0.48.0

func UpdateCommand(channel string) string

UpdateCommand returns the exact one-line update command for the given install channel, or "" when no command can be safely offered (Spec 079 FR-009: never emit a channel-specific command that could be wrong).

Only package-manager/toolchain channels and the self-managed tarball channel get a command; dmg, windows-installer, docker, and unknown installs get guidance text via GuidanceLine instead.

func VerifyFileSHA256 added in v0.69.0

func VerifyFileSHA256(path, wantHex string) error

VerifyFileSHA256 hard-fails unless path hashes to wantHex.

Types

type Asset

type Asset struct {
	// Name is the asset filename (e.g., "mcpproxy-v1.2.3-darwin-arm64.tar.gz")
	Name string `json:"name"`

	// BrowserDownloadURL is the direct download URL
	BrowserDownloadURL string `json:"browser_download_url"`

	// ContentType is the MIME type of the asset
	ContentType string `json:"content_type"`

	// Size is the file size in bytes
	Size int64 `json:"size"`
}

Asset represents a downloadable file attached to a release.

type Checker

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

Checker performs background version checks against GitHub releases.

func New

func New(logger *zap.Logger, version string) *Checker

New creates a new update checker.

func (*Checker) CheckNow

func (c *Checker) CheckNow() *VersionInfo

CheckNow performs an immediate update check against GitHub. This bypasses the periodic check interval and updates the cached version info. Returns the updated VersionInfo after the check completes. When update checking is disabled (update_check.enabled=false or MCPPROXY_DISABLE_AUTO_UPDATE=true) no network check is performed and nil is returned (Spec 079 FR-015: disabled means no check and no nudge anywhere, including the manual /api/v1/info?refresh=true path).

func (*Checker) Enabled added in v0.47.0

func (c *Checker) Enabled() bool

Enabled reports whether update checking is effectively enabled: the MCPPROXY_DISABLE_AUTO_UPDATE environment kill-switch wins over the config value (Spec 079 FR-014 precedence: env > config).

func (*Checker) GetVersionInfo

func (c *Checker) GetVersionInfo() *VersionInfo

GetVersionInfo returns the current version information. Thread-safe. Returns nil when update checking is disabled (config or env): with no check running there is no meaningful update state, and FR-015 requires zero nudge on every surface — /api/v1/info then omits the update object entirely, so the Web UI banner/badge and CLI annotations naturally disappear.

func (*Checker) IncludePrereleases added in v0.47.0

func (c *Checker) IncludePrereleases() bool

IncludePrereleases reports whether prerelease versions are offered: MCPPROXY_ALLOW_PRERELEASE_UPDATES=true wins over the config channel (Spec 079 FR-014 precedence: env > config); otherwise channel=rc opts in.

func (*Checker) Policy added in v0.54.0

func (c *Checker) Policy() Policy

Policy reports the checker's effective policy. Safe for concurrent use and cheap enough to call per request; both environment overrides are read live so the answer always matches what the checker itself would do right now.

func (*Checker) SetCheckFunc

func (c *Checker) SetCheckFunc(fn func() (*GitHubRelease, error))

SetCheckFunc sets a custom check function. Primarily for testing.

func (*Checker) SetCheckInterval

func (c *Checker) SetCheckInterval(interval time.Duration)

SetCheckInterval sets the interval between update checks. Primarily for testing.

func (*Checker) SetConfig added in v0.47.0

func (c *Checker) SetConfig(enabled, includePrereleases bool)

SetConfig applies the update_check config block (Spec 079 FR-012): enabled gates both the background poll and CheckNow; includePrereleases selects the release channel (stable vs rc).

Precedence (FR-014, documented in docs/features/version-updates.md): the environment switches win over config — MCPPROXY_DISABLE_AUTO_UPDATE=true force-disables even with enabled=true, and MCPPROXY_ALLOW_PRERELEASE_UPDATES=true force-includes prereleases even with channel=stable. The spec leaves precedence open; env-wins is the safe operator-override reading.

Safe to call at any time (config hot-reload). When the background loop is running, a change that leaves checking enabled (re-enable or channel switch) triggers a prompt background re-check instead of waiting up to a full checkInterval.

func (*Checker) SetDeltaFunc added in v0.63.0

func (c *Checker) SetDeltaFunc(fn func(latest *GitHubRelease) (*ReleaseDelta, error))

SetDeltaFunc sets a custom FR-002 delta resolver. Primarily for testing.

func (*Checker) Start

func (c *Checker) Start(ctx context.Context)

Start begins the background update checker. It performs an initial check immediately and then checks every checkInterval. The checker respects MCPPROXY_DISABLE_AUTO_UPDATE environment variable.

type GitHubClient

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

GitHubClient handles communication with the GitHub Releases API.

func NewGitHubClient

func NewGitHubClient(logger *zap.Logger) *GitHubClient

NewGitHubClient creates a new GitHub API client.

func (*GitHubClient) GetLatestRelease

func (c *GitHubClient) GetLatestRelease() (*GitHubRelease, error)

GetLatestRelease fetches the latest stable release from GitHub.

func (*GitHubClient) GetLatestReleaseIncludingPrereleases

func (c *GitHubClient) GetLatestReleaseIncludingPrereleases() (*GitHubRelease, error)

GetLatestReleaseIncludingPrereleases fetches the latest release including prereleases.

func (*GitHubClient) GetRelease

func (c *GitHubClient) GetRelease(includePrereleases bool) (*GitHubRelease, error)

GetRelease fetches the appropriate release based on whether prereleases should be included.

func (*GitHubClient) GetReleaseByTag added in v0.54.0

func (c *GitHubClient) GetReleaseByTag(tag string) (*GitHubRelease, error)

GetReleaseByTag fetches one specific release by its git tag. `mcpproxy update --version vX.Y.Z` needs it: the latest/list endpoints cannot address an older (or a specific prerelease) tag, and FR-022 allows a deliberate downgrade only when the user names the exact version.

func (*GitHubClient) GetReleaseByTagContext added in v0.63.0

func (c *GitHubClient) GetReleaseByTagContext(ctx context.Context, tag string) (*GitHubRelease, error)

GetReleaseByTagContext is GetReleaseByTag bounded by ctx. The delta scan uses it so its budget covers the request itself, not merely the decision to start one.

func (*GitHubClient) ListReleases added in v0.63.0

func (c *GitHubClient) ListReleases(ctx context.Context, perPage int) ([]GitHubRelease, error)

ListReleases fetches one page of the releases list, newest-created first.

The result is cached against the response ETag: GitHub answers a repeat request carrying If-None-Match with 304 and no body, which does not count against the rate limit. That matters because `CheckNow` (the tray's "Check for Updates", `/api/v1/info?refresh=true`) deliberately bypasses the failure backoff and is user-triggerable at will, and because many installs behind one office egress IP share a single 60-request hourly bucket.

func (*GitHubClient) SetAPIBase added in v0.54.0

func (c *GitHubClient) SetAPIBase(base string)

SetAPIBase overrides the REST API root (tests, self-hosted mirrors). An empty value restores the public GitHub API.

type GitHubRelease

type GitHubRelease struct {
	// TagName is the git tag for this release (e.g., "v1.2.3")
	TagName string `json:"tag_name"`

	// Name is the release title
	Name string `json:"name"`

	// Body is the release notes in markdown format
	Body string `json:"body"`

	// Prerelease indicates if this is a prerelease
	Prerelease bool `json:"prerelease"`

	// HTMLURL is the URL to view the release on GitHub
	HTMLURL string `json:"html_url"`

	// PublishedAt is the publication timestamp
	PublishedAt string `json:"published_at"`

	// Assets is the list of downloadable files
	Assets []Asset `json:"assets"`
}

GitHubRelease represents a release from the GitHub Releases API. This matches the structure returned by: - GET /repos/{owner}/{repo}/releases/latest - GET /repos/{owner}/{repo}/releases

type InfoResponseUpdate

type InfoResponseUpdate struct {
	// Available indicates if an update is available
	Available bool `json:"available"`

	// LatestVersion is the latest version (empty if not checked)
	LatestVersion string `json:"latest_version,omitempty"`

	// ReleaseURL is the GitHub release page URL
	ReleaseURL string `json:"release_url,omitempty"`

	// CheckedAt is when the last check occurred
	CheckedAt *time.Time `json:"checked_at,omitempty"`

	// IsPrerelease indicates if latest is a prerelease
	IsPrerelease bool `json:"is_prerelease,omitempty"`

	// CheckError is set if the last check failed
	CheckError string `json:"check_error,omitempty"`

	// InstallChannel is the detected distribution channel (Spec 079 FR-008)
	InstallChannel string `json:"install_channel,omitempty"`

	// UpdateCommand is the channel's one-line update command, only present
	// when an update is available and the channel has one (Spec 079 FR-009)
	UpdateCommand string `json:"update_command,omitempty"`

	// NudgesSuppressed tells UI surfaces to stay quiet in CI /
	// non-interactive contexts (Spec 079 FR-019)
	NudgesSuppressed bool `json:"nudges_suppressed,omitempty"`

	// Spec 079 FR-002 delta — see the matching fields on VersionInfo.
	ReleasesBehind          *int   `json:"releases_behind,omitempty"`
	ReleasesBehindSaturated bool   `json:"releases_behind_saturated,omitempty"`
	WeeksBehind             *int   `json:"weeks_behind,omitempty"`
	BehindSummary           string `json:"behind_summary,omitempty"`
}

InfoResponseUpdate is the update field added to the /api/v1/info response. This structure is serialized to JSON for API responses.

type Policy added in v0.54.0

type Policy struct {
	// Enabled is the effective kill-switch state: update_check.enabled with
	// MCPPROXY_DISABLE_AUTO_UPDATE=true winning over it. When false, no
	// surface may perform an automatic check. A USER-INITIATED check ("Check
	// for Updates") stays available — this field governs automatic behaviour,
	// which is what FR-015 asks for.
	Enabled bool `json:"enabled"`

	// Channel is the release channel this install tracks: "stable" or "rc".
	Channel string `json:"channel"`

	// NudgesSuppressed is the CI / non-interactive rule (Spec 079 FR-019):
	// machine-readable fields keep reporting the facts, UI surfaces stay
	// quiet.
	NudgesSuppressed bool `json:"nudges_suppressed"`
}

Policy is the effective, hot-reloadable update policy visible to clients.

func UnavailablePolicy added in v0.54.0

func UnavailablePolicy() Policy

UnavailablePolicy is the policy to report when there is no checker at all (server edition, tests, a runtime constructed without one). Automatic checks cannot happen, so Enabled is false — reported as a fact rather than left for the client to guess. Nudge suppression is still answered from the environment, since that rule is about the context, not about the checker.

type ReleaseDelta added in v0.63.0

type ReleaseDelta struct {
	// ReleasesBehind counts releases on the OFFERED channel that are newer
	// than the running version and no newer than the offered one.
	ReleasesBehind int

	// Saturated marks ReleasesBehind as a lower bound: the running version
	// predates the scanned window, so releases older than it were never seen.
	//
	// Note this flag catches the common case, not every case. The scan reads
	// one page ordered by created_at, so a release that is semver-in-range but
	// was CREATED long ago (a late-published backport, say) can fall off the
	// page and be missed without setting this flag — the count would then be
	// one short and not marked as a bound. Spec 079's own assumption (L159)
	// allows an approximation where an exact count is unavailable, and the
	// figure is motivational rather than load-bearing, so this is accepted
	// deliberately rather than paged for.
	Saturated bool

	// WeeksBehind is whole weeks between the two releases' publish dates.
	// Only meaningful when WeeksKnown is true.
	WeeksBehind int

	// WeeksKnown is false when either publish date was missing, unparseable,
	// or ordered backwards (a backport published after a newer minor).
	WeeksKnown bool
}

ReleaseDelta is how far the running build is behind the offered release.

The two "known" flags exist because zero is a legitimate value for both figures and must stay distinguishable from "we could not work it out".

func ComputeReleaseDelta added in v0.63.0

func ComputeReleaseDelta(current, latest string, page []GitHubRelease, currentRelease *GitHubRelease, includePrereleases bool) (ReleaseDelta, bool)

ComputeReleaseDelta works out how far `current` is behind `latest` given one page of releases and, optionally, the running version's own release record (used only when that version is absent from the page).

It returns ok=false when no honest statement can be made — an invalid version on either side, or a `latest` that is not actually newer. Callers treat !ok as "emit nothing" rather than as an error: FR-016 forbids a negative delta and FR-006 forbids letting a missing delta degrade anything.

type VersionInfo

type VersionInfo struct {
	// CurrentVersion is the version of the running MCPProxy instance.
	// Format: semver with "v" prefix (e.g., "v1.2.3") or "development"
	CurrentVersion string `json:"current_version"`

	// LatestVersion is the latest version available on GitHub releases.
	// Empty if update check has not completed yet.
	LatestVersion string `json:"latest_version,omitempty"`

	// UpdateAvailable is true if LatestVersion > CurrentVersion.
	// Computed via semver comparison.
	UpdateAvailable bool `json:"available"`

	// ReleaseURL is the URL to the GitHub release page for the latest version.
	ReleaseURL string `json:"release_url,omitempty"`

	// CheckedAt is the timestamp of the last successful update check.
	CheckedAt *time.Time `json:"checked_at,omitempty"`

	// IsPrerelease indicates if the latest version is a prerelease.
	IsPrerelease bool `json:"is_prerelease,omitempty"`

	// CheckError contains the error message if the last check failed.
	// Empty string if no error.
	CheckError string `json:"check_error,omitempty"`

	// InstallChannel identifies the distribution channel of the running
	// binary (homebrew, dmg, deb, rpm, docker, go-install,
	// windows-installer, tarball, or unknown). Detected once at startup and
	// always populated, even when no update is available (Spec 079 FR-008,
	// additive per FR-021).
	InstallChannel string `json:"install_channel,omitempty"`

	// UpdateCommand is the exact one-line update command for InstallChannel.
	// Only set when UpdateAvailable is true AND the channel has a safe
	// command (homebrew, deb, rpm, go-install); empty otherwise (Spec 079
	// FR-009, additive per FR-021). When the offered version is a
	// prerelease, only go-install gets a command (version-pinned) — the
	// package-manager channels serve stable artifacts only.
	UpdateCommand string `json:"update_command,omitempty"`

	// NudgesSuppressed tells UI surfaces (Web UI banner, tray indicator) to
	// stay quiet: the process runs in a CI / non-interactive context where a
	// nudge is noise. Machine-readable consumers still get the full facts
	// (Spec 079 FR-019, additive per FR-021).
	NudgesSuppressed bool `json:"nudges_suppressed,omitempty"`

	// ReleasesBehind counts releases on the offered channel between the
	// running version and the offered one. A pointer because "unknown" and a
	// value must stay distinguishable.
	ReleasesBehind *int `json:"releases_behind,omitempty"`

	// ReleasesBehindSaturated marks ReleasesBehind as a lower bound: the
	// running build predates the scanned release window. Surfaces render
	// "N+ releases".
	ReleasesBehindSaturated bool `json:"releases_behind_saturated,omitempty"`

	// WeeksBehind is whole weeks between the two releases' publish dates.
	// A pointer because 0 is legitimate — a same-week release is one release
	// and zero weeks behind — and must not be confused with "unknown".
	WeeksBehind *int `json:"weeks_behind,omitempty"`

	// BehindSummary is the pre-rendered clause every surface prints verbatim,
	// e.g. "8 releases / ~14 weeks behind". Rendered once in Go
	// (FormatBehindSummary) precisely so the CLI, the Web UI banner and the
	// tray cannot word it differently; the raw numbers above sit alongside it
	// so machine consumers never parse prose.
	BehindSummary string `json:"behind_summary,omitempty"`
}

VersionInfo represents the current version and update availability. This is stored in-memory only and refreshed on startup + every DefaultCheckInterval (24h; stretched by backoff after failed checks).

func (*VersionInfo) ToAPIResponse

func (v *VersionInfo) ToAPIResponse() *InfoResponseUpdate

ToAPIResponse converts VersionInfo to the API response format.

Jump to

Keyboard shortcuts

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