Add the browser UI, terminal menu, and one-liner bootstrap
Deployr is now installable and drivable the way winutil is: one PowerShell or
shell line, no prior setup on the machine.
irm .../scripts/install.ps1 | iex
curl -fsSL .../scripts/install.sh | sh
The bootstrap self-elevates, picks the right binary for the machine's
architecture, verifies it against the release SHA256SUMS, puts it on PATH and
opens the UI. Arguments pass through for unattended use.
`deployr ui` serves a point-and-click page on loopback and opens a browser at
it: apps grouped by category, profile bundles, a filter box, and per-app
progress streamed live over SSE as the engine runs. A browser page rather than a
native window because it is the only GUI that behaves the same on all three
platforms without a toolkit or cgo, so the binary stays one static file.
It is not a hole in the endpoint: loopback-only on an OS-assigned port, a
session token minted per run and required on every request, plus Origin and
Host checks so no other page can drive a tool that installs software as SYSTEM.
A run keeps going if the tab closes -- aborting mid-installer is worse than
finishing without a spectator.
`deployr menu` is the same thing as a numbered terminal picker, for a machine
reached over SSH or a recovery console where no browser exists.
Engine gains optional OnAppStart/OnResult hooks, which is what makes progress
streamable instead of a report that only shows up at the end.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
77f88afd7a
commit
af2a96e072
8 files changed
+1460
-3
No files matched your search
@@ -11,6 +11,46 @@ There is no server and no agent. Deployr is a single static executable you drop
|
|||||||
on a machine — by hand, or through your RMM's script runner — and it exits with
|
on a machine — by hand, or through your RMM's script runner — and it exits with
|
||||||
a status code your automation can branch on.
|
a status code your automation can branch on.
|
||||||
|
|
||||||
|
## One-liner
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
irm https://git.starwarslab.us/ATOM_IT/Deployr/raw/branch/main/scripts/install.ps1 | iex
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -fsSL https://git.starwarslab.us/ATOM_IT/Deployr/raw/branch/main/scripts/install.sh | sh
|
||||||
|
```
|
||||||
|
|
||||||
|
That elevates if needed, downloads the right binary for the machine, verifies it
|
||||||
|
against the release checksums, puts it on PATH, and opens the UI.
|
||||||
|
|
||||||
|
To skip the UI and just run something, pass arguments through:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
& ([scriptblock]::Create((irm https://git.starwarslab.us/ATOM_IT/Deployr/raw/branch/main/scripts/install.ps1))) install @standard
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -fsSL https://git.starwarslab.us/ATOM_IT/Deployr/raw/branch/main/scripts/install.sh | sh -s -- install @standard
|
||||||
|
```
|
||||||
|
|
||||||
|
## The UI
|
||||||
|
|
||||||
|
`deployr ui` serves a point-and-click interface on loopback and opens your
|
||||||
|
browser at it. Checkboxes grouped by category, one-click profile bundles, a
|
||||||
|
filter box, and live per-app progress streamed from the engine as it runs.
|
||||||
|
|
||||||
|
It is a browser page rather than a native window for one reason: it is the only
|
||||||
|
GUI that behaves identically on Windows, macOS and Linux without a toolkit or
|
||||||
|
cgo, so the binary stays a single static file. It binds `127.0.0.1` on a random
|
||||||
|
port, requires a session token minted at startup, and rejects cross-origin and
|
||||||
|
non-loopback requests — nothing is exposed to the network.
|
||||||
|
|
||||||
|
On a machine with no browser (SSH, recovery console), `deployr menu` gives you
|
||||||
|
the same thing as a numbered terminal picker.
|
||||||
|
|
||||||
|
## The CLI
|
||||||
|
|
||||||
```
|
```
|
||||||
deployr install chrome 7zip vlc
|
deployr install chrome 7zip vlc
|
||||||
deployr install @standard --json
|
deployr install @standard --json
|
||||||
@@ -60,6 +100,8 @@ deployr doctor
|
|||||||
|
|
||||||
| Command | What it does |
|
| Command | What it does |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
|
| `deployr ui` | Open the point-and-click interface in a browser |
|
||||||
|
| `deployr menu` | Pick apps from a terminal menu (no browser needed) |
|
||||||
| `deployr install <app...>` | Install applications that are not already present |
|
| `deployr install <app...>` | Install applications that are not already present |
|
||||||
| `deployr update <app...>` | Update installed applications (`--all` for everything present) |
|
| `deployr update <app...>` | Update installed applications (`--all` for everything present) |
|
||||||
| `deployr uninstall <app...>` | Remove applications |
|
| `deployr uninstall <app...>` | Remove applications |
|
||||||
@@ -211,13 +253,16 @@ internal/detect is it already installed (registry, paths, commands)
|
|||||||
internal/download vendor downloads with retries and checksum pinning
|
internal/download vendor downloads with retries and checksum pinning
|
||||||
internal/platform OS, arch, elevation, well-known directories
|
internal/platform OS, arch, elevation, well-known directories
|
||||||
internal/run non-interactive command execution with timeouts
|
internal/run non-interactive command execution with timeouts
|
||||||
internal/cli command line parsing and output rendering
|
internal/ui local web UI (embedded page, SSE progress, token auth)
|
||||||
|
internal/cli command line parsing, terminal menu, output rendering
|
||||||
|
scripts/install.* one-liner bootstrap for Windows and Unix
|
||||||
```
|
```
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
Working: catalog, all providers, install/update/uninstall/status/list/info/
|
Working: catalog, all providers, install/update/uninstall/status/list/info/
|
||||||
doctor, JSON output, overlays, RMM exit codes.
|
doctor, the browser UI and terminal menu, the bootstrap one-liners, JSON output,
|
||||||
|
overlays, RMM exit codes.
|
||||||
|
|
||||||
Not built yet: a central dashboard (deliberately — this is the standalone CLI),
|
Not built yet: a central dashboard (deliberately — this is the standalone tool),
|
||||||
scheduled self-updates, and per-app version pinning.
|
scheduled self-updates, and per-app version pinning.
|
||||||
@@ -125,6 +125,10 @@ func Main(args []string) int {
|
|||||||
rest := args[1:]
|
rest := args[1:]
|
||||||
|
|
||||||
switch cmd {
|
switch cmd {
|
||||||
|
case "ui", "gui":
|
||||||
|
return uiCommand(ctx, rest)
|
||||||
|
case "menu":
|
||||||
|
return menuCommand(ctx, rest)
|
||||||
case "install", "i":
|
case "install", "i":
|
||||||
return actionCommand(ctx, "install", rest)
|
return actionCommand(ctx, "install", rest)
|
||||||
case "update", "upgrade":
|
case "update", "upgrade":
|
||||||
@@ -211,6 +215,8 @@ USAGE
|
|||||||
deployr <command> [flags] [apps...]
|
deployr <command> [flags] [apps...]
|
||||||
|
|
||||||
COMMANDS
|
COMMANDS
|
||||||
|
ui open the point-and-click interface in a browser
|
||||||
|
menu pick apps from a terminal menu (no browser needed)
|
||||||
install <app|@profile>... install applications
|
install <app|@profile>... install applications
|
||||||
update <app|@profile>... update installed applications (--all for everything present)
|
update <app|@profile>... update installed applications (--all for everything present)
|
||||||
uninstall <app|@profile>... remove applications
|
uninstall <app|@profile>... remove applications
|
||||||
@@ -230,6 +236,7 @@ COMMON FLAGS
|
|||||||
--timeout 30m per-installer timeout
|
--timeout 30m per-installer timeout
|
||||||
|
|
||||||
EXAMPLES
|
EXAMPLES
|
||||||
|
deployr ui
|
||||||
deployr install chrome 7zip vlc
|
deployr install chrome 7zip vlc
|
||||||
deployr install @standard --json
|
deployr install @standard --json
|
||||||
deployr update --all
|
deployr update --all
|
||||||
|
|||||||
@@ -0,0 +1,323 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"text/tabwriter"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/detect"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/engine"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/ui"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/version"
|
||||||
|
)
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------- ui ---
|
||||||
|
|
||||||
|
func uiCommand(ctx context.Context, args []string) int {
|
||||||
|
var g globals
|
||||||
|
fs := flag.NewFlagSet("deployr ui", flag.ContinueOnError)
|
||||||
|
g.register(fs)
|
||||||
|
addr := fs.String("addr", "127.0.0.1:0", "address to serve the UI on (loopback only by default)")
|
||||||
|
noBrowser := fs.Bool("no-browser", false, "do not open a browser, just print the URL")
|
||||||
|
allowUnelevated := fs.Bool("allow-unelevated", false, "start even without administrator/root rights")
|
||||||
|
names, err := parseFlags(fs, args)
|
||||||
|
if err != nil {
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
if len(names) > 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: ui takes no arguments")
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
cat, err := loadCatalog(g.catalogs)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
log := g.newLogger()
|
||||||
|
defer log.Close()
|
||||||
|
|
||||||
|
// The UI warns about this in the page too, but a technician who launched it
|
||||||
|
// from the wrong shell deserves to hear it before the browser opens.
|
||||||
|
if !platform.IsElevated() && !*allowUnelevated && !g.dryRun && runtime.GOOS == "windows" {
|
||||||
|
log.Errorf("administrator rights are required: %s", platform.PrivilegeHint())
|
||||||
|
log.Errorf("pass --allow-unelevated to open the UI anyway")
|
||||||
|
return ExitPrivilege
|
||||||
|
}
|
||||||
|
|
||||||
|
err = ui.Serve(ctx, ui.Config{
|
||||||
|
Catalog: cat,
|
||||||
|
Log: log,
|
||||||
|
Addr: *addr,
|
||||||
|
NoBrowser: *noBrowser,
|
||||||
|
Timeout: g.timeout,
|
||||||
|
DryRun: g.dryRun,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Errorf("%v", err)
|
||||||
|
return ExitFailure
|
||||||
|
}
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ menu ---
|
||||||
|
|
||||||
|
// menuCommand is the terminal equivalent of the UI, for machines reached over
|
||||||
|
// SSH or a bare recovery console where no browser exists.
|
||||||
|
func menuCommand(ctx context.Context, args []string) int {
|
||||||
|
var g globals
|
||||||
|
fs := flag.NewFlagSet("deployr menu", flag.ContinueOnError)
|
||||||
|
g.registerAction(fs)
|
||||||
|
names, err := parseFlags(fs, args)
|
||||||
|
if err != nil {
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
if len(names) > 0 {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr: menu takes no arguments")
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
cat, err := loadCatalog(g.catalogs)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "deployr:", err)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
apps := cat.ForPlatform(runtime.GOOS)
|
||||||
|
if len(apps) == 0 {
|
||||||
|
fmt.Fprintf(os.Stderr, "deployr: the catalog has no apps for %s\n", runtime.GOOS)
|
||||||
|
return ExitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
installed := map[string]string{}
|
||||||
|
present := map[string]bool{}
|
||||||
|
for _, app := range apps {
|
||||||
|
ok, ver := detect.Installed(app.TargetFor(runtime.GOOS).Detect)
|
||||||
|
present[app.ID] = ok
|
||||||
|
installed[app.ID] = ver
|
||||||
|
}
|
||||||
|
|
||||||
|
printMenu(cat, apps, present, installed)
|
||||||
|
|
||||||
|
in := bufio.NewScanner(os.Stdin)
|
||||||
|
chosen, ok := promptSelection(in, cat, apps, present)
|
||||||
|
if !ok {
|
||||||
|
fmt.Println("nothing selected")
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
action, ok := promptAction(in)
|
||||||
|
if !ok {
|
||||||
|
fmt.Println("cancelled")
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
log := g.newLogger()
|
||||||
|
defer log.Close()
|
||||||
|
|
||||||
|
if code := checkPrivileges(&g, log); code != ExitOK {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("\n%s %d app(s)...\n\n", action, len(chosen))
|
||||||
|
summary := engine.Run(ctx, chosen, engine.Config{
|
||||||
|
Action: engine.Action(action),
|
||||||
|
DryRun: g.dryRun,
|
||||||
|
Force: g.force,
|
||||||
|
Strict: g.strict,
|
||||||
|
Timeout: g.timeout,
|
||||||
|
CacheDir: platform.CacheDir(),
|
||||||
|
RequireChecksum: g.requireChecksum,
|
||||||
|
KeepDownloads: g.keepDownloads,
|
||||||
|
OnlyProvider: g.only,
|
||||||
|
Log: log,
|
||||||
|
})
|
||||||
|
fmt.Println()
|
||||||
|
log.Infof("%s", summaryLine(summary))
|
||||||
|
if summary.RebootRequired {
|
||||||
|
log.Infof("a reboot is required to finish")
|
||||||
|
}
|
||||||
|
return summary.ExitCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
func printMenu(cat *catalog.Catalog, apps []*catalog.App, present map[string]bool, installed map[string]string) {
|
||||||
|
fmt.Printf("\n%s\n%s (%s/%s)\n\n", version.String(), platform.Hostname(), runtime.GOOS, runtime.GOARCH)
|
||||||
|
|
||||||
|
byCat := map[string][]*catalog.App{}
|
||||||
|
for _, app := range apps {
|
||||||
|
key := "other"
|
||||||
|
if len(app.Categories) > 0 {
|
||||||
|
key = app.Categories[0]
|
||||||
|
}
|
||||||
|
byCat[key] = append(byCat[key], app)
|
||||||
|
}
|
||||||
|
cats := make([]string, 0, len(byCat))
|
||||||
|
for c := range byCat {
|
||||||
|
cats = append(cats, c)
|
||||||
|
}
|
||||||
|
sort.Strings(cats)
|
||||||
|
|
||||||
|
// Numbering follows the display order so what the operator types matches
|
||||||
|
// what they are looking at.
|
||||||
|
index := menuIndex(apps)
|
||||||
|
position := map[string]int{}
|
||||||
|
for i, app := range index {
|
||||||
|
position[app.ID] = i + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||||
|
for _, c := range cats {
|
||||||
|
fmt.Fprintf(w, " %s\n", strings.ToUpper(c))
|
||||||
|
for _, app := range byCat[c] {
|
||||||
|
state := ""
|
||||||
|
if present[app.ID] {
|
||||||
|
state = "[installed"
|
||||||
|
if v := installed[app.ID]; v != "" {
|
||||||
|
state += " " + v
|
||||||
|
}
|
||||||
|
state += "]"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " %3d)\t%s\t%s\t%s\n", position[app.ID], app.ID, app.Name, state)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w)
|
||||||
|
}
|
||||||
|
w.Flush()
|
||||||
|
|
||||||
|
if profiles := cat.ProfileNames(); len(profiles) > 0 {
|
||||||
|
fmt.Printf(" profiles: @%s\n\n", strings.Join(profiles, " @"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// menuIndex is the stable, numbered ordering of the menu: grouped by category
|
||||||
|
// exactly as printMenu displays it.
|
||||||
|
func menuIndex(apps []*catalog.App) []*catalog.App {
|
||||||
|
byCat := map[string][]*catalog.App{}
|
||||||
|
for _, app := range apps {
|
||||||
|
key := "other"
|
||||||
|
if len(app.Categories) > 0 {
|
||||||
|
key = app.Categories[0]
|
||||||
|
}
|
||||||
|
byCat[key] = append(byCat[key], app)
|
||||||
|
}
|
||||||
|
cats := make([]string, 0, len(byCat))
|
||||||
|
for c := range byCat {
|
||||||
|
cats = append(cats, c)
|
||||||
|
}
|
||||||
|
sort.Strings(cats)
|
||||||
|
|
||||||
|
var out []*catalog.App
|
||||||
|
for _, c := range cats {
|
||||||
|
out = append(out, byCat[c]...)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func promptSelection(in *bufio.Scanner, cat *catalog.Catalog, apps []*catalog.App, present map[string]bool) ([]*catalog.App, bool) {
|
||||||
|
index := menuIndex(apps)
|
||||||
|
|
||||||
|
fmt.Print("Select apps (numbers, ranges like 4-9, ids, @profile), " +
|
||||||
|
"'missing' for everything not installed, 'installed', 'all', or 'q' to quit\n> ")
|
||||||
|
if !in.Scan() {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
line := strings.TrimSpace(in.Text())
|
||||||
|
if line == "" || strings.EqualFold(line, "q") || strings.EqualFold(line, "quit") {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var chosen []*catalog.App
|
||||||
|
add := func(app *catalog.App) {
|
||||||
|
if !seen[app.ID] {
|
||||||
|
seen[app.ID] = true
|
||||||
|
chosen = append(chosen, app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, field := range strings.Fields(line) {
|
||||||
|
switch {
|
||||||
|
case strings.EqualFold(field, "all"):
|
||||||
|
for _, app := range index {
|
||||||
|
add(app)
|
||||||
|
}
|
||||||
|
case strings.EqualFold(field, "missing"):
|
||||||
|
for _, app := range index {
|
||||||
|
if !present[app.ID] {
|
||||||
|
add(app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case strings.EqualFold(field, "installed"):
|
||||||
|
for _, app := range index {
|
||||||
|
if present[app.ID] {
|
||||||
|
add(app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case strings.Contains(field, "-") && !strings.HasPrefix(field, "@"):
|
||||||
|
lo, hi, ok := parseRange(field, len(index))
|
||||||
|
if !ok {
|
||||||
|
fmt.Fprintf(os.Stderr, " ignoring %q\n", field)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for i := lo; i <= hi; i++ {
|
||||||
|
add(index[i-1])
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if n, err := strconv.Atoi(field); err == nil {
|
||||||
|
if n < 1 || n > len(index) {
|
||||||
|
fmt.Fprintf(os.Stderr, " ignoring out-of-range %d\n", n)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
add(index[n-1])
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
resolved, unknown := cat.Resolve([]string{field})
|
||||||
|
if len(unknown) > 0 {
|
||||||
|
fmt.Fprintf(os.Stderr, " ignoring unknown %q\n", field)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, app := range resolved {
|
||||||
|
if app.TargetFor(runtime.GOOS) != nil {
|
||||||
|
add(app)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return chosen, len(chosen) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseRange(field string, max int) (int, int, bool) {
|
||||||
|
parts := strings.SplitN(field, "-", 2)
|
||||||
|
lo, err1 := strconv.Atoi(strings.TrimSpace(parts[0]))
|
||||||
|
hi, err2 := strconv.Atoi(strings.TrimSpace(parts[1]))
|
||||||
|
if err1 != nil || err2 != nil || lo < 1 || hi > max || lo > hi {
|
||||||
|
return 0, 0, false
|
||||||
|
}
|
||||||
|
return lo, hi, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func promptAction(in *bufio.Scanner) (string, bool) {
|
||||||
|
fmt.Print("\nAction: [i]nstall (default), [u]pdate, [r]emove, [q]uit\n> ")
|
||||||
|
if !in.Scan() {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
switch strings.ToLower(strings.TrimSpace(in.Text())) {
|
||||||
|
case "", "i", "install":
|
||||||
|
return "install", true
|
||||||
|
case "u", "update", "upgrade":
|
||||||
|
return "update", true
|
||||||
|
case "r", "remove", "uninstall":
|
||||||
|
return "uninstall", true
|
||||||
|
default:
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -54,6 +54,14 @@ type Config struct {
|
|||||||
KeepDownloads bool
|
KeepDownloads bool
|
||||||
OnlyProvider string // restrict every app to a single provider
|
OnlyProvider string // restrict every app to a single provider
|
||||||
Log *logx.Logger
|
Log *logx.Logger
|
||||||
|
|
||||||
|
// OnAppStart, when set, is called just before an app is processed. The UI
|
||||||
|
// uses it to show what is happening during a long installer run.
|
||||||
|
OnAppStart func(app *catalog.App)
|
||||||
|
// OnResult, when set, is called as each app finishes, before the run
|
||||||
|
// continues. It is what makes progress streamable instead of a report that
|
||||||
|
// only appears at the end.
|
||||||
|
OnResult func(Result)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attempt records one source that was tried and did not work out.
|
// Attempt records one source that was tried and did not work out.
|
||||||
@@ -119,6 +127,9 @@ func Run(ctx context.Context, apps []*catalog.App, cfg Config) Summary {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, app := range apps {
|
for _, app := range apps {
|
||||||
|
if cfg.OnAppStart != nil {
|
||||||
|
cfg.OnAppStart(app)
|
||||||
|
}
|
||||||
res := runOne(ctx, app, cfg)
|
res := runOne(ctx, app, cfg)
|
||||||
sum.Results = append(sum.Results, res)
|
sum.Results = append(sum.Results, res)
|
||||||
|
|
||||||
@@ -138,6 +149,9 @@ func Run(ctx context.Context, apps []*catalog.App, cfg Config) Summary {
|
|||||||
if cfg.Log != nil {
|
if cfg.Log != nil {
|
||||||
logResult(cfg.Log, res)
|
logResult(cfg.Log, res)
|
||||||
}
|
}
|
||||||
|
if cfg.OnResult != nil {
|
||||||
|
cfg.OnResult(res)
|
||||||
|
}
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,345 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="referrer" content="no-referrer">
|
||||||
|
<title>Deployr</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
color-scheme: light dark;
|
||||||
|
--bg: #0f1115;
|
||||||
|
--panel: #161a21;
|
||||||
|
--panel-2: #1c212a;
|
||||||
|
--line: #272d38;
|
||||||
|
--text: #e6e9ef;
|
||||||
|
--muted: #98a1b3;
|
||||||
|
--accent: #4f9cf9;
|
||||||
|
--ok: #3fb950;
|
||||||
|
--warn: #d29922;
|
||||||
|
--fail: #f85149;
|
||||||
|
--radius: 10px;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: light) {
|
||||||
|
:root {
|
||||||
|
--bg: #f4f6fa; --panel: #ffffff; --panel-2: #f0f3f8; --line: #dde3ec;
|
||||||
|
--text: #12151b; --muted: #5b6577; --accent: #1c6ed4;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
.hidden { display: none !important; }
|
||||||
|
body {
|
||||||
|
margin: 0; background: var(--bg); color: var(--text);
|
||||||
|
font: 14px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||||
|
}
|
||||||
|
code, .mono { font-family: ui-monospace, "Cascadia Code", Consolas, "SF Mono", monospace; }
|
||||||
|
|
||||||
|
header {
|
||||||
|
position: sticky; top: 0; z-index: 10;
|
||||||
|
background: var(--panel); border-bottom: 1px solid var(--line);
|
||||||
|
padding: 14px 20px; display: flex; align-items: center; gap: 16px; flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.brand { font-size: 18px; font-weight: 650; letter-spacing: -0.01em; }
|
||||||
|
.brand span { color: var(--accent); }
|
||||||
|
.meta { color: var(--muted); font-size: 12.5px; }
|
||||||
|
.spacer { flex: 1 1 auto; }
|
||||||
|
|
||||||
|
.banner { padding: 10px 20px; font-size: 13px; border-bottom: 1px solid var(--line); }
|
||||||
|
.banner.warn { background: color-mix(in srgb, var(--warn) 16%, var(--panel)); }
|
||||||
|
.banner.info { background: color-mix(in srgb, var(--accent) 14%, var(--panel)); }
|
||||||
|
.banner.hidden { display: none; }
|
||||||
|
|
||||||
|
main { display: grid; grid-template-columns: minmax(0,1fr) 380px; gap: 20px; padding: 20px; align-items: start; }
|
||||||
|
@media (max-width: 1000px) { main { grid-template-columns: minmax(0,1fr); } }
|
||||||
|
|
||||||
|
.card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); }
|
||||||
|
.card h2 { margin: 0; padding: 14px 16px; font-size: 13px; text-transform: uppercase;
|
||||||
|
letter-spacing: 0.07em; color: var(--muted); border-bottom: 1px solid var(--line); }
|
||||||
|
|
||||||
|
.controls { display: flex; gap: 10px; flex-wrap: wrap; padding: 14px 16px; align-items: center; }
|
||||||
|
input[type=search] {
|
||||||
|
flex: 1 1 220px; min-width: 180px; padding: 9px 12px; border-radius: 8px;
|
||||||
|
border: 1px solid var(--line); background: var(--panel-2); color: var(--text); font: inherit;
|
||||||
|
}
|
||||||
|
input[type=search]:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
|
||||||
|
|
||||||
|
button {
|
||||||
|
font: inherit; padding: 8px 14px; border-radius: 8px; cursor: pointer;
|
||||||
|
border: 1px solid var(--line); background: var(--panel-2); color: var(--text);
|
||||||
|
}
|
||||||
|
button:hover:not(:disabled) { border-color: var(--accent); }
|
||||||
|
button:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||||
|
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }
|
||||||
|
button.danger:hover:not(:disabled) { border-color: var(--fail); color: var(--fail); }
|
||||||
|
button.chip { padding: 5px 11px; border-radius: 999px; font-size: 12.5px; }
|
||||||
|
button.chip.on { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||||
|
|
||||||
|
.profiles { display: flex; gap: 8px; flex-wrap: wrap; padding: 0 16px 14px; }
|
||||||
|
|
||||||
|
.cat { padding: 6px 16px 2px; font-size: 11.5px; letter-spacing: 0.08em;
|
||||||
|
text-transform: uppercase; color: var(--muted); }
|
||||||
|
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||||
|
gap: 8px; padding: 6px 16px 16px; }
|
||||||
|
|
||||||
|
label.app {
|
||||||
|
display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px;
|
||||||
|
border: 1px solid var(--line); border-radius: 8px; background: var(--panel-2); cursor: pointer;
|
||||||
|
}
|
||||||
|
label.app:hover { border-color: var(--accent); }
|
||||||
|
label.app.checked { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, var(--panel-2)); }
|
||||||
|
label.app input { margin-top: 3px; accent-color: var(--accent); }
|
||||||
|
.app-name { font-weight: 550; }
|
||||||
|
.app-sub { color: var(--muted); font-size: 12px; }
|
||||||
|
.tag { font-size: 11px; padding: 1px 7px; border-radius: 999px; border: 1px solid var(--line);
|
||||||
|
color: var(--muted); white-space: nowrap; }
|
||||||
|
.tag.installed { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 50%, var(--line)); }
|
||||||
|
|
||||||
|
.actions { display: flex; gap: 10px; flex-wrap: wrap; padding: 14px 16px; border-top: 1px solid var(--line); }
|
||||||
|
.count { color: var(--muted); align-self: center; }
|
||||||
|
|
||||||
|
#log { margin: 0; padding: 12px 16px; max-height: 60vh; overflow: auto;
|
||||||
|
font-family: ui-monospace, Consolas, monospace; font-size: 12.5px; }
|
||||||
|
.row { display: flex; gap: 8px; padding: 3px 0; align-items: baseline; }
|
||||||
|
.row .st { flex: 0 0 52px; }
|
||||||
|
.st.ok { color: var(--ok); } .st.skip { color: var(--muted); }
|
||||||
|
.st.fail { color: var(--fail); } .st.run { color: var(--accent); }
|
||||||
|
.row .who { flex: 0 0 130px; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.row .why { color: var(--muted); flex: 1 1 auto; word-break: break-word; }
|
||||||
|
.summary { margin: 10px 16px 16px; padding: 10px 12px; border-radius: 8px;
|
||||||
|
background: var(--panel-2); border: 1px solid var(--line); }
|
||||||
|
.empty { padding: 16px; color: var(--muted); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header>
|
||||||
|
<div class="brand">deploy<span>r</span></div>
|
||||||
|
<div class="meta" id="meta">loading…</div>
|
||||||
|
<div class="spacer"></div>
|
||||||
|
<button id="quit" title="Stop the local server and close">quit</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="banner warn hidden" id="elevate">
|
||||||
|
Not running as administrator — installs will fail. Close this and re-run deployr from an elevated shell.
|
||||||
|
</div>
|
||||||
|
<div class="banner info hidden" id="dryrun">
|
||||||
|
Dry run: nothing on this machine will be changed.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<section class="card">
|
||||||
|
<h2>Applications</h2>
|
||||||
|
<div class="controls">
|
||||||
|
<input type="search" id="search" placeholder="Filter by name, id or category…" autocomplete="off">
|
||||||
|
<button id="sel-none">clear</button>
|
||||||
|
<button id="sel-installed">select installed</button>
|
||||||
|
<button id="sel-missing">select missing</button>
|
||||||
|
</div>
|
||||||
|
<div class="profiles" id="profiles"></div>
|
||||||
|
<div id="apps"></div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="primary" id="do-install">Install selected</button>
|
||||||
|
<button id="do-update">Update selected</button>
|
||||||
|
<button class="danger" id="do-uninstall">Uninstall selected</button>
|
||||||
|
<span class="count" id="count">0 selected</span>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>Progress</h2>
|
||||||
|
<div id="log"><div class="empty">Nothing has run yet.</div></div>
|
||||||
|
<div class="summary hidden" id="summary"></div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const token = new URLSearchParams(location.search).get('t') || '';
|
||||||
|
const api = (path, opts = {}) => fetch(path, {
|
||||||
|
...opts,
|
||||||
|
headers: { 'X-Deployr-Token': token, 'Content-Type': 'application/json', ...(opts.headers || {}) },
|
||||||
|
});
|
||||||
|
|
||||||
|
let state = { apps: [], profiles: {} };
|
||||||
|
const selected = new Set();
|
||||||
|
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
const esc = s => String(s ?? '').replace(/[&<>"']/g, c =>
|
||||||
|
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
const res = await api('/api/state');
|
||||||
|
if (!res.ok) { $('meta').textContent = 'error: ' + await res.text(); return; }
|
||||||
|
state = await res.json();
|
||||||
|
|
||||||
|
$('meta').innerHTML = `${esc(state.version)} · <span class="mono">${esc(state.host)}</span> · ` +
|
||||||
|
`${esc(state.os)}/${esc(state.arch)} · ${state.installed} of ${state.apps.length} installed`;
|
||||||
|
$('elevate').classList.toggle('hidden', state.elevated);
|
||||||
|
$('dryrun').classList.toggle('hidden', !state.dry_run);
|
||||||
|
|
||||||
|
renderProfiles();
|
||||||
|
renderApps();
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderProfiles() {
|
||||||
|
const names = Object.keys(state.profiles).sort();
|
||||||
|
$('profiles').innerHTML = names.length
|
||||||
|
? names.map(n => `<button class="chip" data-profile="${esc(n)}">@${esc(n)}</button>`).join('')
|
||||||
|
: '';
|
||||||
|
document.querySelectorAll('[data-profile]').forEach(btn => {
|
||||||
|
btn.onclick = () => {
|
||||||
|
const members = state.profiles[btn.dataset.profile] || [];
|
||||||
|
const allOn = members.every(id => selected.has(id));
|
||||||
|
members.forEach(id => allOn ? selected.delete(id) : selected.add(id));
|
||||||
|
renderApps();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function visibleApps() {
|
||||||
|
const q = $('search').value.trim().toLowerCase();
|
||||||
|
if (!q) return state.apps;
|
||||||
|
return state.apps.filter(a =>
|
||||||
|
a.id.includes(q) || a.name.toLowerCase().includes(q) ||
|
||||||
|
(a.category || '').includes(q) || (a.description || '').toLowerCase().includes(q));
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderApps() {
|
||||||
|
const apps = visibleApps();
|
||||||
|
const byCat = {};
|
||||||
|
for (const a of apps) (byCat[a.category] ||= []).push(a);
|
||||||
|
|
||||||
|
const html = Object.keys(byCat).sort().map(cat => `
|
||||||
|
<div class="cat">${esc(cat)}</div>
|
||||||
|
<div class="grid">${byCat[cat].map(appCard).join('')}</div>`).join('');
|
||||||
|
|
||||||
|
$('apps').innerHTML = html || '<div class="empty">No apps match that filter.</div>';
|
||||||
|
|
||||||
|
document.querySelectorAll('label.app input').forEach(box => {
|
||||||
|
box.onchange = () => {
|
||||||
|
box.checked ? selected.add(box.value) : selected.delete(box.value);
|
||||||
|
box.closest('label').classList.toggle('checked', box.checked);
|
||||||
|
updateCount();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Profile chips light up when every member is selected.
|
||||||
|
document.querySelectorAll('[data-profile]').forEach(btn => {
|
||||||
|
const members = state.profiles[btn.dataset.profile] || [];
|
||||||
|
btn.classList.toggle('on', members.length > 0 && members.every(id => selected.has(id)));
|
||||||
|
});
|
||||||
|
updateCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
function appCard(a) {
|
||||||
|
const on = selected.has(a.id);
|
||||||
|
const tag = a.installed
|
||||||
|
? `<span class="tag installed">${esc(a.version || 'installed')}</span>`
|
||||||
|
: `<span class="tag">${esc(a.provider)}</span>`;
|
||||||
|
return `
|
||||||
|
<label class="app${on ? ' checked' : ''}">
|
||||||
|
<input type="checkbox" value="${esc(a.id)}"${on ? ' checked' : ''}>
|
||||||
|
<span>
|
||||||
|
<span class="app-name">${esc(a.name)}</span> ${tag}<br>
|
||||||
|
<span class="app-sub mono">${esc(a.id)}</span>
|
||||||
|
</span>
|
||||||
|
</label>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCount() {
|
||||||
|
const n = selected.size;
|
||||||
|
$('count').textContent = `${n} selected`;
|
||||||
|
for (const id of ['do-install', 'do-update', 'do-uninstall']) $(id).disabled = n === 0 || running;
|
||||||
|
}
|
||||||
|
|
||||||
|
let running = false;
|
||||||
|
|
||||||
|
async function run(action) {
|
||||||
|
if (!selected.size || running) return;
|
||||||
|
running = true;
|
||||||
|
updateCount();
|
||||||
|
$('summary').classList.add('hidden');
|
||||||
|
$('log').innerHTML = '';
|
||||||
|
logRow('run', action, `${selected.size} app(s)`);
|
||||||
|
|
||||||
|
const res = await api('/api/run', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ action, apps: [...selected] }),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
logRow('fail', action, await res.text());
|
||||||
|
running = false;
|
||||||
|
updateCount();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function logRow(status, who, why) {
|
||||||
|
const first = $('log').querySelector('.empty');
|
||||||
|
if (first) first.remove();
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'row';
|
||||||
|
div.innerHTML = `<span class="st ${esc(status)}">[${esc(status)}]</span>` +
|
||||||
|
`<span class="who mono">${esc(who)}</span><span class="why">${esc(why)}</span>`;
|
||||||
|
$('log').appendChild(div);
|
||||||
|
$('log').scrollTop = $('log').scrollHeight;
|
||||||
|
return div;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = new Map();
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
const es = new EventSource(`/api/events?t=${encodeURIComponent(token)}`);
|
||||||
|
es.onmessage = ev => {
|
||||||
|
const msg = JSON.parse(ev.data);
|
||||||
|
if (msg.kind === 'start') {
|
||||||
|
pending.set(msg.app, logRow('run', msg.app, 'working…'));
|
||||||
|
} else if (msg.kind === 'result') {
|
||||||
|
const r = msg.result;
|
||||||
|
// The message usually already carries the version ("already installed
|
||||||
|
// (1.2.3)"), so only fall back to the bare version when there is none.
|
||||||
|
const bits = [];
|
||||||
|
if (r.provider) bits.push('via ' + r.provider);
|
||||||
|
if (r.message) bits.push(r.message);
|
||||||
|
else if (r.version) bits.push(r.version);
|
||||||
|
const detail = r.error || bits.join(' ');
|
||||||
|
const row = pending.get(msg.app);
|
||||||
|
if (row) { row.remove(); pending.delete(msg.app); }
|
||||||
|
logRow(r.status === 'n/a' ? 'skip' : r.status, msg.app, detail);
|
||||||
|
} else if (msg.kind === 'done') {
|
||||||
|
const s = msg.summary;
|
||||||
|
running = false;
|
||||||
|
updateCount();
|
||||||
|
const el = $('summary');
|
||||||
|
el.classList.remove('hidden');
|
||||||
|
el.innerHTML = `<b>${s.changed} changed</b>, ${s.skipped} skipped, ` +
|
||||||
|
`<b>${s.failed} failed</b>, ${s.unsupported} n/a in ${(s.duration_ms / 1000).toFixed(1)}s` +
|
||||||
|
(s.reboot_required ? '<br>A reboot is required to finish.' : '');
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
es.onerror = () => { /* EventSource retries on its own */ };
|
||||||
|
}
|
||||||
|
|
||||||
|
$('search').oninput = renderApps;
|
||||||
|
$('sel-none').onclick = () => { selected.clear(); renderApps(); };
|
||||||
|
$('sel-installed').onclick = () => {
|
||||||
|
state.apps.filter(a => a.installed).forEach(a => selected.add(a.id)); renderApps();
|
||||||
|
};
|
||||||
|
$('sel-missing').onclick = () => {
|
||||||
|
state.apps.filter(a => !a.installed).forEach(a => selected.add(a.id)); renderApps();
|
||||||
|
};
|
||||||
|
$('do-install').onclick = () => run('install');
|
||||||
|
$('do-update').onclick = () => run('update');
|
||||||
|
$('do-uninstall').onclick = () => {
|
||||||
|
if (confirm(`Uninstall ${selected.size} application(s)?`)) run('uninstall');
|
||||||
|
};
|
||||||
|
$('quit').onclick = async () => {
|
||||||
|
await api('/api/quit', { method: 'POST' });
|
||||||
|
document.body.innerHTML = '<main><section class="card"><div class="empty">' +
|
||||||
|
'Deployr has stopped. You can close this tab.</div></section></main>';
|
||||||
|
};
|
||||||
|
|
||||||
|
load();
|
||||||
|
connect();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
// Package ui serves deployr's point-and-click interface as a small local web
|
||||||
|
// app. A browser page is the only GUI that works identically on Windows, macOS
|
||||||
|
// and Linux without dragging a toolkit -- and without cgo -- so the binary stays
|
||||||
|
// a single static file you can drop on any endpoint.
|
||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"embed"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os/exec"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/catalog"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/detect"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/engine"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/logx"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/platform"
|
||||||
|
"git.starwarslab.us/ATOM_IT/Deployr/internal/version"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed assets/*
|
||||||
|
var assets embed.FS
|
||||||
|
|
||||||
|
// Config controls the UI server.
|
||||||
|
type Config struct {
|
||||||
|
Catalog *catalog.Catalog
|
||||||
|
Log *logx.Logger
|
||||||
|
// Addr is the listen address. Defaults to 127.0.0.1:0 -- loopback only, on
|
||||||
|
// a port the OS picks, so two technicians on one terminal server do not
|
||||||
|
// collide and nothing is exposed to the network.
|
||||||
|
Addr string
|
||||||
|
// NoBrowser suppresses opening the default browser.
|
||||||
|
NoBrowser bool
|
||||||
|
// Timeout is per-installer, passed through to the engine.
|
||||||
|
Timeout time.Duration
|
||||||
|
// DryRun plans without changing the machine.
|
||||||
|
DryRun bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server is a running UI instance.
|
||||||
|
type Server struct {
|
||||||
|
cfg Config
|
||||||
|
token string
|
||||||
|
url string
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
running bool
|
||||||
|
subs map[chan event]struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type event struct {
|
||||||
|
Kind string `json:"kind"` // start, result, done, log
|
||||||
|
App string `json:"app,omitempty"`
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
Result *engine.Result `json:"result,omitempty"`
|
||||||
|
Summary *engine.Summary `json:"summary,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve starts the UI and blocks until the context is cancelled or the page
|
||||||
|
// asks to shut down.
|
||||||
|
func Serve(ctx context.Context, cfg Config) error {
|
||||||
|
if cfg.Addr == "" {
|
||||||
|
cfg.Addr = "127.0.0.1:0"
|
||||||
|
}
|
||||||
|
tokenBytes := make([]byte, 24)
|
||||||
|
if _, err := rand.Read(tokenBytes); err != nil {
|
||||||
|
return fmt.Errorf("generate session token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
s := &Server{
|
||||||
|
cfg: cfg,
|
||||||
|
token: hex.EncodeToString(tokenBytes),
|
||||||
|
subs: map[chan event]struct{}{},
|
||||||
|
}
|
||||||
|
|
||||||
|
ln, err := net.Listen("tcp", cfg.Addr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("listen on %s: %w", cfg.Addr, err)
|
||||||
|
}
|
||||||
|
s.url = fmt.Sprintf("http://%s/?t=%s", ln.Addr().String(), s.token)
|
||||||
|
|
||||||
|
shutdown := make(chan struct{})
|
||||||
|
srv := &http.Server{
|
||||||
|
Handler: s.routes(shutdown),
|
||||||
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) && cfg.Log != nil {
|
||||||
|
cfg.Log.Errorf("ui server: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if cfg.Log != nil {
|
||||||
|
cfg.Log.Infof("Deployr UI: %s", s.url)
|
||||||
|
cfg.Log.Infof("press Ctrl+C to stop")
|
||||||
|
}
|
||||||
|
if !cfg.NoBrowser {
|
||||||
|
openBrowser(s.url, cfg.Log)
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
case <-shutdown:
|
||||||
|
}
|
||||||
|
|
||||||
|
stopCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
return srv.Shutdown(stopCtx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// URL is the address the UI is served on, including the session token.
|
||||||
|
func (s *Server) URL() string { return s.url }
|
||||||
|
|
||||||
|
func (s *Server) routes(shutdown chan struct{}) http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
|
||||||
|
mux.HandleFunc("GET /", s.guard(s.handleIndex))
|
||||||
|
mux.HandleFunc("GET /api/state", s.guard(s.handleState))
|
||||||
|
mux.HandleFunc("POST /api/run", s.guard(s.handleRun))
|
||||||
|
mux.HandleFunc("GET /api/events", s.guard(s.handleEvents))
|
||||||
|
mux.HandleFunc("POST /api/quit", s.guard(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
select {
|
||||||
|
case <-shutdown:
|
||||||
|
default:
|
||||||
|
close(shutdown)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
|
||||||
|
return mux
|
||||||
|
}
|
||||||
|
|
||||||
|
// guard enforces the session token and rejects cross-origin requests. Without
|
||||||
|
// this, any web page the technician has open could drive a tool that installs
|
||||||
|
// software as SYSTEM.
|
||||||
|
func (s *Server) guard(next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if origin := r.Header.Get("Origin"); origin != "" {
|
||||||
|
if !strings.HasSuffix(origin, r.Host) {
|
||||||
|
http.Error(w, "cross-origin requests are not allowed", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A Host header that is not our loopback listener means someone
|
||||||
|
// resolved a name to 127.0.0.1 to reach us (DNS rebinding).
|
||||||
|
if !isLoopbackHost(r.Host) {
|
||||||
|
http.Error(w, "unexpected host", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token := r.URL.Query().Get("t")
|
||||||
|
if token == "" {
|
||||||
|
token = r.Header.Get("X-Deployr-Token")
|
||||||
|
}
|
||||||
|
if subtle.ConstantTimeCompare([]byte(token), []byte(s.token)) != 1 {
|
||||||
|
http.Error(w, "invalid or missing session token", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isLoopbackHost(host string) bool {
|
||||||
|
h, _, err := net.SplitHostPort(host)
|
||||||
|
if err != nil {
|
||||||
|
h = host
|
||||||
|
}
|
||||||
|
if h == "localhost" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
ip := net.ParseIP(h)
|
||||||
|
return ip != nil && ip.IsLoopback()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleIndex(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
page, err := assets.ReadFile("assets/index.html")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
w.Write(page)
|
||||||
|
}
|
||||||
|
|
||||||
|
type stateApp struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Description string `json:"description,omitempty"`
|
||||||
|
Category string `json:"category"`
|
||||||
|
Homepage string `json:"homepage,omitempty"`
|
||||||
|
Installed bool `json:"installed"`
|
||||||
|
Version string `json:"version,omitempty"`
|
||||||
|
Provider string `json:"provider"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type state struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
Host string `json:"host"`
|
||||||
|
OS string `json:"os"`
|
||||||
|
Arch string `json:"arch"`
|
||||||
|
Elevated bool `json:"elevated"`
|
||||||
|
DryRun bool `json:"dry_run"`
|
||||||
|
Running bool `json:"running"`
|
||||||
|
Apps []stateApp `json:"apps"`
|
||||||
|
Profiles map[string][]string `json:"profiles"`
|
||||||
|
Installed int `json:"installed"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleState(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
st := state{
|
||||||
|
Version: version.Version,
|
||||||
|
Host: platform.Hostname(),
|
||||||
|
OS: runtime.GOOS,
|
||||||
|
Arch: runtime.GOARCH,
|
||||||
|
Elevated: platform.IsElevated(),
|
||||||
|
DryRun: s.cfg.DryRun,
|
||||||
|
Profiles: map[string][]string{},
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
st.Running = s.running
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
for _, app := range s.cfg.Catalog.ForPlatform(runtime.GOOS) {
|
||||||
|
target := app.TargetFor(runtime.GOOS)
|
||||||
|
installed, ver := detect.Installed(target.Detect)
|
||||||
|
if installed {
|
||||||
|
st.Installed++
|
||||||
|
}
|
||||||
|
category := "other"
|
||||||
|
if len(app.Categories) > 0 {
|
||||||
|
category = app.Categories[0]
|
||||||
|
}
|
||||||
|
provider := ""
|
||||||
|
if len(target.Sources) > 0 {
|
||||||
|
provider = target.Sources[0].Provider
|
||||||
|
}
|
||||||
|
st.Apps = append(st.Apps, stateApp{
|
||||||
|
ID: app.ID, Name: app.Name, Description: app.Description,
|
||||||
|
Category: category, Homepage: app.Homepage,
|
||||||
|
Installed: installed, Version: ver, Provider: provider,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only offer profiles that actually have members on this platform.
|
||||||
|
supported := map[string]bool{}
|
||||||
|
for _, a := range st.Apps {
|
||||||
|
supported[a.ID] = true
|
||||||
|
}
|
||||||
|
for name, members := range s.cfg.Catalog.Profiles {
|
||||||
|
var usable []string
|
||||||
|
for _, id := range members {
|
||||||
|
if supported[id] {
|
||||||
|
usable = append(usable, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(usable) > 0 {
|
||||||
|
st.Profiles[name] = usable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, st)
|
||||||
|
}
|
||||||
|
|
||||||
|
type runRequest struct {
|
||||||
|
Action string `json:"action"`
|
||||||
|
Apps []string `json:"apps"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleRun(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req runRequest
|
||||||
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch engine.Action(req.Action) {
|
||||||
|
case engine.ActionInstall, engine.ActionUpdate, engine.ActionUninstall:
|
||||||
|
default:
|
||||||
|
http.Error(w, "unknown action "+req.Action, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
apps, unknown := s.cfg.Catalog.Resolve(req.Apps)
|
||||||
|
if len(unknown) > 0 {
|
||||||
|
http.Error(w, "unknown apps: "+strings.Join(unknown, ", "), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(apps) == 0 {
|
||||||
|
http.Error(w, "nothing selected", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
if s.running {
|
||||||
|
s.mu.Unlock()
|
||||||
|
http.Error(w, "a run is already in progress", http.StatusConflict)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.running = true
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
go s.execute(engine.Action(req.Action), apps)
|
||||||
|
w.WriteHeader(http.StatusAccepted)
|
||||||
|
}
|
||||||
|
|
||||||
|
// execute runs the engine and fans results out to every connected page. It
|
||||||
|
// deliberately uses its own context: closing the browser tab must not abort an
|
||||||
|
// installer that is already writing to the machine.
|
||||||
|
func (s *Server) execute(action engine.Action, apps []*catalog.App) {
|
||||||
|
defer func() {
|
||||||
|
s.mu.Lock()
|
||||||
|
s.running = false
|
||||||
|
s.mu.Unlock()
|
||||||
|
}()
|
||||||
|
|
||||||
|
summary := engine.Run(context.Background(), apps, engine.Config{
|
||||||
|
Action: action,
|
||||||
|
DryRun: s.cfg.DryRun,
|
||||||
|
Timeout: s.cfg.Timeout,
|
||||||
|
CacheDir: platform.CacheDir(),
|
||||||
|
Log: s.cfg.Log,
|
||||||
|
OnAppStart: func(app *catalog.App) {
|
||||||
|
s.broadcast(event{Kind: "start", App: app.ID, Name: app.Name})
|
||||||
|
},
|
||||||
|
OnResult: func(res engine.Result) {
|
||||||
|
r := res
|
||||||
|
s.broadcast(event{Kind: "result", App: res.App, Name: res.Name, Result: &r})
|
||||||
|
},
|
||||||
|
})
|
||||||
|
s.broadcast(event{Kind: "done", Summary: &summary})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) {
|
||||||
|
flusher, ok := w.(http.Flusher)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "text/event-stream")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
w.Header().Set("Connection", "keep-alive")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
flusher.Flush()
|
||||||
|
|
||||||
|
ch := make(chan event, 64)
|
||||||
|
s.mu.Lock()
|
||||||
|
s.subs[ch] = struct{}{}
|
||||||
|
s.mu.Unlock()
|
||||||
|
defer func() {
|
||||||
|
s.mu.Lock()
|
||||||
|
delete(s.subs, ch)
|
||||||
|
s.mu.Unlock()
|
||||||
|
}()
|
||||||
|
|
||||||
|
// A comment line every 20s keeps proxies and impatient browsers from
|
||||||
|
// dropping an idle stream during a long installer.
|
||||||
|
ping := time.NewTicker(20 * time.Second)
|
||||||
|
defer ping.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-r.Context().Done():
|
||||||
|
return
|
||||||
|
case <-ping.C:
|
||||||
|
fmt.Fprint(w, ": ping\n\n")
|
||||||
|
flusher.Flush()
|
||||||
|
case ev := <-ch:
|
||||||
|
data, err := json.Marshal(ev)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "data: %s\n\n", data)
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// broadcast delivers an event to every open page, dropping it for any listener
|
||||||
|
// that has fallen behind rather than blocking the install.
|
||||||
|
func (s *Server) broadcast(ev event) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
for ch := range s.subs {
|
||||||
|
select {
|
||||||
|
case ch <- ev:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, v any) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
json.NewEncoder(w).Encode(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// openBrowser asks the desktop to open the UI. A failure is not fatal: the URL
|
||||||
|
// is printed either way, which is all a headless or SSH session needs.
|
||||||
|
func openBrowser(url string, log *logx.Logger) {
|
||||||
|
var cmd *exec.Cmd
|
||||||
|
switch runtime.GOOS {
|
||||||
|
case "windows":
|
||||||
|
cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
|
||||||
|
case "darwin":
|
||||||
|
cmd = exec.Command("/usr/bin/open", url)
|
||||||
|
default:
|
||||||
|
cmd = exec.Command("xdg-open", url)
|
||||||
|
}
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
if log != nil {
|
||||||
|
log.Debugf("could not open a browser (%v); open the URL above yourself", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go cmd.Wait()
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Deployr bootstrap. Downloads the right binary for this machine, verifies it,
|
||||||
|
installs it, and opens the UI.
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
Designed to be run straight off the web, the way winutil is:
|
||||||
|
|
||||||
|
irm https://git.starwarslab.us/ATOM_IT/Deployr/raw/branch/main/scripts/install.ps1 | iex
|
||||||
|
|
||||||
|
With no arguments it installs deployr and opens the point-and-click UI.
|
||||||
|
To pass arguments through instead, create a scriptblock:
|
||||||
|
|
||||||
|
& ([scriptblock]::Create((irm <url>))) install @standard
|
||||||
|
|
||||||
|
Or set $env:DEPLOYR_ARGS before piping to iex:
|
||||||
|
|
||||||
|
$env:DEPLOYR_ARGS = 'install chrome 7zip'; irm <url> | iex
|
||||||
|
|
||||||
|
.PARAMETER DeployrArgs
|
||||||
|
Arguments to pass to deployr. Defaults to opening the UI.
|
||||||
|
|
||||||
|
.PARAMETER Version
|
||||||
|
Release tag to install. Defaults to the latest release.
|
||||||
|
|
||||||
|
.PARAMETER InstallOnly
|
||||||
|
Install the binary and exit without running anything.
|
||||||
|
#>
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[Parameter(ValueFromRemainingArguments = $true)]
|
||||||
|
[string[]]$DeployrArgs,
|
||||||
|
[string]$Version = "latest",
|
||||||
|
[switch]$InstallOnly
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
$ProgressPreference = "SilentlyContinue" # Invoke-WebRequest is ~10x faster without the progress bar
|
||||||
|
|
||||||
|
$Repo = "https://git.starwarslab.us/ATOM_IT/Deployr"
|
||||||
|
$Dir = Join-Path $env:ProgramData "Deployr"
|
||||||
|
$Exe = Join-Path $Dir "deployr.exe"
|
||||||
|
|
||||||
|
function Write-Step { param([string]$Message) Write-Host " $Message" -ForegroundColor Cyan }
|
||||||
|
function Write-Ok { param([string]$Message) Write-Host " $Message" -ForegroundColor Green }
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Deployr bootstrap" -ForegroundColor White
|
||||||
|
Write-Host " ------------------------------------------------" -ForegroundColor DarkGray
|
||||||
|
|
||||||
|
# --- privileges ---------------------------------------------------------
|
||||||
|
# Installing software machine-wide needs an elevated token. Relaunch rather
|
||||||
|
# than failing halfway through a run.
|
||||||
|
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||||
|
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
|
||||||
|
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||||
|
Write-Step "Elevating..."
|
||||||
|
$argLine = if ($DeployrArgs) { ($DeployrArgs -join ' ') } else { '' }
|
||||||
|
# -File cannot be used here: this script may only exist in memory. Re-fetch
|
||||||
|
# it in the elevated process instead. (-Verb RunAs with -File also fails
|
||||||
|
# silently for a script on a mapped drive.)
|
||||||
|
$bootstrap = "`$env:DEPLOYR_ARGS='$argLine'; irm $Repo/raw/branch/main/scripts/install.ps1 | iex"
|
||||||
|
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($bootstrap))
|
||||||
|
Start-Process -FilePath "powershell.exe" -Verb RunAs -ArgumentList @(
|
||||||
|
"-NoProfile", "-ExecutionPolicy", "Bypass", "-NoExit", "-EncodedCommand", $encoded
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
# Arguments arrive through the environment when the script was piped to iex.
|
||||||
|
if (-not $DeployrArgs -and $env:DEPLOYR_ARGS) {
|
||||||
|
$DeployrArgs = $env:DEPLOYR_ARGS -split '\s+' | Where-Object { $_ }
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- architecture -------------------------------------------------------
|
||||||
|
$arch = switch ($env:PROCESSOR_ARCHITECTURE) {
|
||||||
|
"AMD64" { "amd64" }
|
||||||
|
"ARM64" { "arm64" }
|
||||||
|
"x86" { if ([Environment]::Is64BitOperatingSystem) { "amd64" } else { throw "32-bit Windows is not supported" } }
|
||||||
|
default { throw "unsupported architecture: $env:PROCESSOR_ARCHITECTURE" }
|
||||||
|
}
|
||||||
|
$asset = "deployr_windows_$arch.exe"
|
||||||
|
Write-Step "Platform: windows/$arch"
|
||||||
|
|
||||||
|
# --- resolve the release ------------------------------------------------
|
||||||
|
# "latest" is not a real download path in Gitea, so resolve it through the API
|
||||||
|
# and take the asset URLs the release actually published.
|
||||||
|
$apiRepo = "$($Repo -replace '/([^/]+)/([^/]+)$', '/api/v1/repos/$1/$2')"
|
||||||
|
$releaseUrl = if ($Version -eq "latest") { "$apiRepo/releases/latest" } else { "$apiRepo/releases/tags/$Version" }
|
||||||
|
|
||||||
|
Write-Step "Resolving release ($Version) ..."
|
||||||
|
$release = Invoke-RestMethod -Uri $releaseUrl -UseBasicParsing -TimeoutSec 60
|
||||||
|
$assetUrl = ($release.assets | Where-Object { $_.name -eq $asset }).browser_download_url
|
||||||
|
$sumsUrl = ($release.assets | Where-Object { $_.name -eq "SHA256SUMS" }).browser_download_url
|
||||||
|
if (-not $assetUrl) { throw "release $($release.tag_name) has no asset named $asset" }
|
||||||
|
Write-Ok "Release $($release.tag_name)"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Force -Path $Dir | Out-Null
|
||||||
|
|
||||||
|
# --- download -----------------------------------------------------------
|
||||||
|
$tmp = Join-Path $env:TEMP "deployr-$([guid]::NewGuid().ToString('N')).exe"
|
||||||
|
try {
|
||||||
|
Write-Step "Downloading $asset ..."
|
||||||
|
Invoke-WebRequest -Uri $assetUrl -OutFile $tmp -UseBasicParsing -TimeoutSec 300
|
||||||
|
|
||||||
|
# Checksums ship with every release; verify when we can reach them, but do
|
||||||
|
# not fail the whole bootstrap if only the sums file is missing.
|
||||||
|
$expected = $null
|
||||||
|
if ($sumsUrl) {
|
||||||
|
try {
|
||||||
|
$sums = (Invoke-WebRequest -Uri $sumsUrl -UseBasicParsing -TimeoutSec 60).Content
|
||||||
|
foreach ($line in $sums -split "`n") {
|
||||||
|
$parts = ($line.Trim() -split '\s+')
|
||||||
|
if ($parts.Count -ge 2 -and ($parts[-1] -replace '^\*|^\./', '') -eq $asset) { $expected = $parts[0] }
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
Write-Warning " could not fetch SHA256SUMS: $($_.Exception.Message)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($expected) {
|
||||||
|
$actual = (Get-FileHash $tmp -Algorithm SHA256).Hash.ToLower()
|
||||||
|
if ($actual -ne $expected.ToLower()) {
|
||||||
|
throw "checksum mismatch for ${asset}: expected $expected, got $actual"
|
||||||
|
}
|
||||||
|
Write-Ok "Checksum verified"
|
||||||
|
}
|
||||||
|
|
||||||
|
# A running deployr.exe cannot be overwritten; move it aside instead.
|
||||||
|
if (Test-Path $Exe) {
|
||||||
|
try { Remove-Item $Exe -Force }
|
||||||
|
catch { Move-Item $Exe "$Exe.old" -Force -ErrorAction SilentlyContinue }
|
||||||
|
}
|
||||||
|
Move-Item $tmp $Exe -Force
|
||||||
|
Write-Ok "Installed to $Exe"
|
||||||
|
} finally {
|
||||||
|
if (Test-Path $tmp) { Remove-Item $tmp -Force -ErrorAction SilentlyContinue }
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- PATH ---------------------------------------------------------------
|
||||||
|
$machinePath = [Environment]::GetEnvironmentVariable("Path", "Machine")
|
||||||
|
if ($machinePath -notlike "*$Dir*") {
|
||||||
|
[Environment]::SetEnvironmentVariable("Path", "$machinePath;$Dir", "Machine")
|
||||||
|
Write-Ok "Added $Dir to the system PATH"
|
||||||
|
}
|
||||||
|
if ($env:Path -notlike "*$Dir*") { $env:Path = "$env:Path;$Dir" }
|
||||||
|
|
||||||
|
Write-Host " ------------------------------------------------" -ForegroundColor DarkGray
|
||||||
|
& $Exe version
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
if ($InstallOnly) {
|
||||||
|
Write-Host " Run 'deployr ui' for the interface, or 'deployr --help' for commands." -ForegroundColor DarkGray
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $DeployrArgs) { $DeployrArgs = @("ui") }
|
||||||
|
|
||||||
|
& $Exe @DeployrArgs
|
||||||
|
exit $LASTEXITCODE
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
# Deployr bootstrap for macOS and Linux.
|
||||||
|
#
|
||||||
|
# curl -fsSL https://git.starwarslab.us/ATOM_IT/Deployr/raw/branch/main/scripts/install.sh | sh
|
||||||
|
#
|
||||||
|
# With no arguments it installs deployr and opens the UI. To pass arguments
|
||||||
|
# through, use `sh -s --`:
|
||||||
|
#
|
||||||
|
# curl -fsSL <url> | sh -s -- install @standard
|
||||||
|
#
|
||||||
|
# Environment:
|
||||||
|
# DEPLOYR_VERSION release tag to install (default: latest)
|
||||||
|
# DEPLOYR_PREFIX install directory (default: /usr/local/bin)
|
||||||
|
# DEPLOYR_INSTALL_ONLY=1 install without running anything
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
REPO="https://git.starwarslab.us/ATOM_IT/Deployr"
|
||||||
|
VERSION="${DEPLOYR_VERSION:-latest}"
|
||||||
|
PREFIX="${DEPLOYR_PREFIX:-/usr/local/bin}"
|
||||||
|
BIN="$PREFIX/deployr"
|
||||||
|
|
||||||
|
say() { printf ' %s\n' "$*"; }
|
||||||
|
die() { printf ' error: %s\n' "$*" >&2; exit 1; }
|
||||||
|
|
||||||
|
# Only escalate when we actually need to write to the prefix, so a user-local
|
||||||
|
# install never prompts for a password it does not need.
|
||||||
|
SUDO=""
|
||||||
|
if [ ! -w "$(dirname "$BIN")" ] 2>/dev/null || [ ! -d "$PREFIX" ]; then
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
command -v sudo >/dev/null 2>&1 || die "need root to write $PREFIX (set DEPLOYR_PREFIX to a writable directory)"
|
||||||
|
SUDO="sudo"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '\n Deployr bootstrap\n ------------------------------------------------\n'
|
||||||
|
|
||||||
|
case "$(uname -s)" in
|
||||||
|
Darwin) OS="darwin" ;;
|
||||||
|
Linux) OS="linux" ;;
|
||||||
|
*) die "unsupported operating system: $(uname -s)" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
case "$(uname -m)" in
|
||||||
|
x86_64|amd64) ARCH="amd64" ;;
|
||||||
|
arm64|aarch64) ARCH="arm64" ;;
|
||||||
|
*) die "unsupported architecture: $(uname -m)" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
ASSET="deployr_${OS}_${ARCH}"
|
||||||
|
say "Platform: $OS/$ARCH"
|
||||||
|
|
||||||
|
TMP="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$TMP"' EXIT
|
||||||
|
|
||||||
|
fetch() {
|
||||||
|
if command -v curl >/dev/null 2>&1; then
|
||||||
|
curl -fsSL --retry 3 --connect-timeout 20 -o "$2" "$1"
|
||||||
|
elif command -v wget >/dev/null 2>&1; then
|
||||||
|
wget -q -O "$2" "$1"
|
||||||
|
else
|
||||||
|
die "neither curl nor wget is available"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# "latest" is not a real download path in Gitea: resolve the release through the
|
||||||
|
# API and use the asset URLs it publishes.
|
||||||
|
API="$(printf '%s' "$REPO" | sed -E 's#/([^/]+)/([^/]+)$#/api/v1/repos/\1/\2#')"
|
||||||
|
if [ "$VERSION" = "latest" ]; then
|
||||||
|
RELEASE_URL="$API/releases/latest"
|
||||||
|
else
|
||||||
|
RELEASE_URL="$API/releases/tags/$VERSION"
|
||||||
|
fi
|
||||||
|
|
||||||
|
say "Resolving release ($VERSION) ..."
|
||||||
|
fetch "$RELEASE_URL" "$TMP/release.json" || die "could not reach $RELEASE_URL"
|
||||||
|
|
||||||
|
# Pull one asset's download URL out of the release JSON without needing jq.
|
||||||
|
asset_url() {
|
||||||
|
tr ',' '\n' < "$TMP/release.json" \
|
||||||
|
| grep -F "browser_download_url" \
|
||||||
|
| sed -E 's/.*"browser_download_url" *: *"([^"]+)".*/\1/' \
|
||||||
|
| grep -E "/$1\$" \
|
||||||
|
| head -n 1
|
||||||
|
}
|
||||||
|
|
||||||
|
ASSET_URL="$(asset_url "$ASSET")"
|
||||||
|
SUMS_URL="$(asset_url 'SHA256SUMS')"
|
||||||
|
[ -n "$ASSET_URL" ] || die "this release has no asset named $ASSET"
|
||||||
|
|
||||||
|
say "Downloading $ASSET ..."
|
||||||
|
fetch "$ASSET_URL" "$TMP/deployr" || die "download failed"
|
||||||
|
|
||||||
|
# Verify against the release checksums when they are reachable.
|
||||||
|
if [ -n "$SUMS_URL" ] && fetch "$SUMS_URL" "$TMP/SHA256SUMS" 2>/dev/null; then
|
||||||
|
EXPECTED="$(awk -v a="$ASSET" '{ n=$NF; sub(/^[*.\/]+/,"",n); if (n==a) print $1 }' "$TMP/SHA256SUMS")"
|
||||||
|
if [ -n "$EXPECTED" ]; then
|
||||||
|
if command -v sha256sum >/dev/null 2>&1; then
|
||||||
|
ACTUAL="$(sha256sum "$TMP/deployr" | cut -d' ' -f1)"
|
||||||
|
else
|
||||||
|
ACTUAL="$(shasum -a 256 "$TMP/deployr" | cut -d' ' -f1)"
|
||||||
|
fi
|
||||||
|
[ "$ACTUAL" = "$EXPECTED" ] || die "checksum mismatch: expected $EXPECTED, got $ACTUAL"
|
||||||
|
say "Checksum verified"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
say "warning: could not fetch SHA256SUMS, skipping verification"
|
||||||
|
fi
|
||||||
|
|
||||||
|
chmod 0755 "$TMP/deployr"
|
||||||
|
$SUDO mkdir -p "$PREFIX"
|
||||||
|
$SUDO install -m 0755 "$TMP/deployr" "$BIN"
|
||||||
|
say "Installed to $BIN"
|
||||||
|
|
||||||
|
# macOS quarantines anything downloaded by a browser-facing tool; strip it so
|
||||||
|
# Gatekeeper does not block the binary on first run.
|
||||||
|
if [ "$OS" = "darwin" ] && command -v xattr >/dev/null 2>&1; then
|
||||||
|
$SUDO xattr -d com.apple.quarantine "$BIN" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf ' ------------------------------------------------\n'
|
||||||
|
"$BIN" version
|
||||||
|
printf '\n'
|
||||||
|
|
||||||
|
[ "${DEPLOYR_INSTALL_ONLY:-}" = "1" ] && exit 0
|
||||||
|
|
||||||
|
if [ "$#" -gt 0 ]; then
|
||||||
|
exec $SUDO "$BIN" "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# The UI needs root to install anything, but it must not run the browser as
|
||||||
|
# root -- deployr opens that as the invoking user itself.
|
||||||
|
exec $SUDO "$BIN" ui
|
||||||
Reference in new issue
Block a user