Files
ClaudeandClaude Opus 5 4909edee2d Deployr 0.1.0: cross-platform application deployment CLI
Replaces Ninite for endpoint software: one catalog, one command line, and the
same behaviour on Windows, macOS and Linux. Single static binary, no server and
no agent, driven from an RMM script runner or by hand.

- catalog of ~50 apps compiled into the binary, extendable with YAML overlays
  in catalog.d or via --catalog, no rebuild required
- providers: winget, choco, brew, cask, apt, dnf/yum, zypper, pacman, flatpak,
  snap, plus direct vendor downloads (msi/exe/msu/dmg/pkg/deb/rpm/zip/tar.gz/
  AppImage)
- sources are tried in order and fall through, so one catalog entry covers
  winget on Windows, a cask on macOS and the vendor .deb on Debian
- provider-independent detection (registry, paths, commands) makes runs
  idempotent even for software installed by hand
- unattended by construction: stdin closed, silent flags, per-command timeouts
- handles the traps that break naive wrappers: winget missing under SYSTEM,
  Homebrew refusing root, 1641/3010 reboot exits, "already installed" reported
  as failure
- --json summary on stdout with progress on stderr, and RMM-friendly exit codes
  (0 ok, 1 failed, 2 usage, 3 privileges)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 16:55:13 -05:00

216 lines
5.4 KiB
Go

// Package download fetches vendor installers with retries and optional
// checksum pinning.
package download
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
"git.starwarslab.us/ATOM_IT/Deployr/internal/version"
)
// ErrChecksumMissing is returned when --require-checksum is set and the
// catalog entry has no sha256.
var ErrChecksumMissing = errors.New("no sha256 in catalog and checksum verification is required")
// Options controls a download.
type Options struct {
URL string
SHA256 string
Dir string // destination directory
Filename string // override the derived filename
Timeout time.Duration // whole-transfer budget
RequireChecksum bool
Attempts int
Log *logx.Logger
}
// Fetch downloads a file and returns its path on disk. The transfer lands in a
// .part file and is renamed only after the checksum passes, so a killed run can
// never leave a truncated installer that looks complete.
func Fetch(ctx context.Context, o Options) (string, error) {
if o.Attempts <= 0 {
o.Attempts = 3
}
if o.Timeout <= 0 {
o.Timeout = 20 * time.Minute
}
if o.SHA256 == "" && o.RequireChecksum {
return "", ErrChecksumMissing
}
if err := os.MkdirAll(o.Dir, 0o755); err != nil {
return "", fmt.Errorf("create download dir: %w", err)
}
name := o.Filename
if name == "" {
name = filenameFromURL(o.URL)
}
dest := filepath.Join(o.Dir, name)
// A cached copy is only trustworthy when the catalog pins a checksum.
if o.SHA256 != "" {
if sum, err := hashFile(dest); err == nil && strings.EqualFold(sum, o.SHA256) {
if o.Log != nil {
o.Log.Debugf("using cached download %s", dest)
}
return dest, nil
}
}
var lastErr error
for attempt := 1; attempt <= o.Attempts; attempt++ {
if attempt > 1 {
delay := time.Duration(attempt-1) * 3 * time.Second
if o.Log != nil {
o.Log.Debugf("retrying download in %s (attempt %d/%d)", delay, attempt, o.Attempts)
}
select {
case <-ctx.Done():
return "", ctx.Err()
case <-time.After(delay):
}
}
p, err := fetchOnce(ctx, o, dest)
if err == nil {
return p, nil
}
lastErr = err
if errors.Is(err, context.Canceled) {
break
}
}
return "", lastErr
}
func fetchOnce(ctx context.Context, o Options, dest string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, o.Timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, o.URL, nil)
if err != nil {
return "", fmt.Errorf("bad url %q: %w", o.URL, err)
}
req.Header.Set("User-Agent", "deployr/"+version.Version)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", fmt.Errorf("download %s: %w", o.URL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("download %s: HTTP %s", o.URL, resp.Status)
}
// Many vendors serve an evergreen URL that redirects to a versioned file;
// prefer the real name so the cache directory stays readable.
if o.Filename == "" {
if n := filenameFromResponse(resp); n != "" {
dest = filepath.Join(o.Dir, n)
}
}
part := dest + ".part"
f, err := os.Create(part)
if err != nil {
return "", fmt.Errorf("create %s: %w", part, err)
}
hasher := sha256.New()
written, err := io.Copy(io.MultiWriter(f, hasher), resp.Body)
closeErr := f.Close()
if err != nil {
os.Remove(part)
return "", fmt.Errorf("download %s: %w", o.URL, err)
}
if closeErr != nil {
os.Remove(part)
return "", closeErr
}
if written == 0 {
os.Remove(part)
return "", fmt.Errorf("download %s: empty response", o.URL)
}
sum := hex.EncodeToString(hasher.Sum(nil))
if o.SHA256 != "" && !strings.EqualFold(sum, o.SHA256) {
os.Remove(part)
return "", fmt.Errorf("checksum mismatch for %s: expected %s, got %s", o.URL, o.SHA256, sum)
}
if err := os.Rename(part, dest); err != nil {
os.Remove(part)
return "", fmt.Errorf("finalise %s: %w", dest, err)
}
if o.Log != nil {
o.Log.Debugf("downloaded %s (%.1f MB, sha256 %s)", dest, float64(written)/(1<<20), sum[:16])
}
return dest, nil
}
func filenameFromResponse(resp *http.Response) string {
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
if _, params, err := mime.ParseMediaType(cd); err == nil {
if n := sanitize(params["filename"]); n != "" {
return n
}
}
}
// resp.Request reflects the final URL after redirects.
if resp.Request != nil && resp.Request.URL != nil {
return filenameFromURL(resp.Request.URL.String())
}
return ""
}
func filenameFromURL(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return "installer.bin"
}
name := sanitize(path.Base(u.Path))
if name == "" || name == "." || name == "/" {
return "installer.bin"
}
return name
}
// sanitize strips any directory component so a hostile or sloppy
// Content-Disposition header cannot write outside the cache directory.
func sanitize(name string) string {
name = strings.TrimSpace(name)
name = strings.ReplaceAll(name, "\\", "/")
name = path.Base(name)
if name == "." || name == "/" || name == ".." {
return ""
}
return name
}
func hashFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}