//go:build windows // Luminary launcher (Go). // // Optional: when a Go toolchain is available, windows/build.mjs compiles this // into Luminary.exe and ships it instead of the PowerShell entry points. It // does the same jobs as Luminary.ps1, with one difference: being a real // process it can stay in the background and clean up after the server exits. // // Usage: // // Luminary.exe start (or reuse) the local engine and open the browser // Luminary.exe -stop stop the local engine started from this folder // Luminary.exe -repair re-download node.exe and verify it against version.txt // // The design and the edge cases are described in ../DESIGN.md. package main import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "net" "net/http" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "syscall" "time" "unsafe" ) const ( firstPort = 8787 lastPort = 8887 healthPath = "/api/health" startupWait = 120 * time.Second pollEvery = 700 * time.Millisecond minNodeMajor = 24 // CREATE_NO_WINDOW keeps the console-based node.exe from flashing a window // even though the launcher itself is linked with -H windowsgui. createNoWindow = 0x08000000 // PROCESS_QUERY_LIMITED_INFORMATION is enough to tell whether a pid is alive // and needs no debug privilege. processQueryLimitedInformation = 0x1000 ) var ( root = bundleRoot() logsDir = filepath.Join(root, "logs") // A -H windowsgui binary has no console, so a missing file would otherwise // fail silently. MessageBoxW is the only feedback a user can see. user32 = syscall.NewLazyDLL("user32.dll") messageBoxW = user32.NewProc("MessageBoxW") // Health is a loopback call: no proxy, no DNS, no internet. The default // transport honours HTTP_PROXY, so a stale corporate proxy or PAC script // would make every probe fail and the launcher would kill a server that was // already answering. client = &http.Client{ Timeout: 2 * time.Second, Transport: &http.Transport{ Proxy: nil, DialContext: (&net.Dialer{Timeout: 2 * time.Second}).DialContext, }, } downloadClient = &http.Client{Timeout: 10 * time.Minute} nodePinRE = regexp.MustCompile(`^node\s+v?(\d+\.\d+\.\d+)\s+win-x64(?:\s+sha256\s+([0-9a-f]{64}))?(?:\s+size\s+(\d+))?`) ) type runtimeInfo struct { PID int `json:"pid"` Port int `json:"port"` URL string `json:"url"` Data string `json:"data"` Node string `json:"node"` Started string `json:"started"` } type nodeRuntime struct { path string label string system bool } var browserOnly = false func main() { args := os.Args[1:] browserOnly = hasFlag(args, "-browser", "--browser") switch { case hasFlag(args, "-repair", "--repair", "/repair"): if err := repair(); err != nil { writeLog("launcher.log", "repair: "+err.Error()) showError("node.exe could not be restored.\n\n" + err.Error()) os.Exit(1) } showInfo("node.exe is restored and matches the checksum in version.txt.\n\n" + filepath.Join(root, "node.exe")) return case hasFlag(args, "-stop", "--stop", "/stop"): if err := stop(); err != nil { showError(err.Error()) os.Exit(1) } showInfo("Luminary stopped.") return } if err := run(); err != nil { writeLog("launcher.log", "error: "+err.Error()) showError(err.Error()) os.Exit(1) } } func hasFlag(args []string, names ...string) bool { for _, arg := range args { for _, name := range names { if strings.EqualFold(arg, name) { return true } } } return false } func showError(text string) { showMessage(text, 0x10) } func ask(text string) bool { title, titleErr := syscall.UTF16PtrFromString("Luminary") body, bodyErr := syscall.UTF16PtrFromString(text) if titleErr != nil || bodyErr != nil { return false } // MB_YESNO | MB_ICONQUESTION | MB_SETFOREGROUND; IDYES is 6. result, _, _ := messageBoxW.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), 0x04|0x20|0x10000) return result == 6 } func showInfo(text string) { showMessage(text, 0x40) } func showMessage(text string, kind uintptr) { title, titleErr := syscall.UTF16PtrFromString("Luminary") body, bodyErr := syscall.UTF16PtrFromString(text) if titleErr != nil || bodyErr != nil { return } // MB_SETFOREGROUND so the dialog is not hidden behind the browser. messageBoxW.Call(0, uintptr(unsafe.Pointer(body)), uintptr(unsafe.Pointer(title)), kind|0x10000) } func run() error { nodeExe := filepath.Join(root, "node.exe") appDir := filepath.Join(root, "app") entry := filepath.Join(appDir, "server", "index.mjs") required := []struct { name string path string }{ {"app\\server\\index.mjs", entry}, {"app\\dist\\index.html", filepath.Join(appDir, "dist", "index.html")}, } var missing []string for _, file := range required { info, err := os.Stat(file.path) if err != nil { missing = append(missing, file.name) continue } if info.Size() == 0 { // What a half-done extraction or an antivirus leaves behind. missing = append(missing, file.name+" (empty)") } } if len(missing) > 0 { return fmt.Errorf("this folder is not a complete Luminary bundle (missing: %s).\n\n"+ "Right-click the zip you downloaded, choose \"Extract All...\", then run "+ "Luminary.exe from the extracted Luminary folder. If files disappeared "+ "after extracting, antivirus or SmartScreen removed them: restore them "+ "from quarantine and extract again.", strings.Join(missing, ", ")) } node, err := resolveNode(nodeExe) if err != nil { // The only download Luminary can need is its own runtime. Offer it here // so a customer who never reads the README still gets a working install. if ask("Luminary needs its Node.js 24 runtime, but node.exe is missing from this bundle.\n\n" + "Download it now from nodejs.org (about 90 MB)?") { if repairErr := repair(); repairErr != nil { return fmt.Errorf("the runtime download failed: %w", repairErr) } node, err = resolveNode(nodeExe) } if err != nil { return fmt.Errorf("%w\n\nRun \"Luminary.exe -repair\" to download the pinned runtime "+ "again, or install Node.js 24 from nodejs.org.", err) } } if node.system { message := fmt.Sprintf("The bundled node.exe is missing or damaged, so Luminary is using %s.\n\n"+ "Run \"Luminary.exe -repair\" to restore the pinned runtime.", node.label) writeLog("launcher.log", "warning: "+message) showInfo(message) } // Already running, or still booting: health is the liveness test, so a stale // runtime.json from a crash falls through to a fresh start instead of // blocking it, and a second double-click waits instead of starting a second // server on the same catalog. if info, ok := readRuntime(); ok { if healthy(info.Port) { openApp(info.URL) return nil } if processAlive(info.PID) { deadline := time.Now().Add(startupWait) for time.Now().Before(deadline) { if healthy(info.Port) { openApp(info.URL) return nil } if !processAlive(info.PID) { break } time.Sleep(pollEvery) } if processAlive(info.PID) { return fmt.Errorf("Luminary is already starting (pid %d) but is not answering on its "+ "local port %d. See %s.", info.PID, info.Port, filepath.Join(dataDirectory(), "logs", "server.err.log")) } } } dataDir := dataDirectory() if err := os.MkdirAll(dataDir, 0o755); err != nil { return fmt.Errorf("cannot create the data directory %s: %w", dataDir, err) } logDir, err := ensureLogDir(dataDir) if err != nil { return err } port, err := freePort() if err != nil { return err } url := fmt.Sprintf("http://127.0.0.1:%d", port) stdout, err := openLog(logDir, "server.out.log") if err != nil { return err } defer stdout.Close() stderr, err := openLog(logDir, "server.err.log") if err != nil { return err } defer stderr.Close() cmd := exec.Command(node.path, entry) cmd.Dir = appDir cmd.Stdout = stdout cmd.Stderr = stderr cmd.Env = append(os.Environ(), "PORT="+strconv.Itoa(port), "HOST=127.0.0.1", "NODE_ENV=production", "LUMINARY_DATA="+dataDir, // Desktop mode: one local admin, no signup or sign-in. Loopback only, // so this never exposes a passwordless account to the network. "LUMINARY_LOCAL=1", ) cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow} if err := cmd.Start(); err != nil { return fmt.Errorf("cannot start %s: %w", node.path, err) } info := runtimeInfo{ PID: cmd.Process.Pid, Port: port, URL: url, Data: dataDir, Node: node.path, Started: time.Now().Format(time.RFC3339), } writeRuntime(info) deadline := time.Now().Add(startupWait) for time.Now().Before(deadline) { if healthy(port) { openApp(url) // Stay alive for the server's lifetime so runtime.json is removed // on quit and a crash is written to the launcher log. The exit // code is deliberately ignored: "Stop" force-kills the child. _ = cmd.Wait() removeRuntime() writeLog("launcher.log", "local engine exited") return nil } time.Sleep(pollEvery) } _ = cmd.Process.Kill() removeRuntime() return fmt.Errorf("Luminary's local engine did not answer within %s; see %s", startupWait, filepath.Join(logDir, "server.err.log")) } // --- runtime resolution ------------------------------------------------------- func nodePin() (version, hash string, size int64) { data, err := os.ReadFile(filepath.Join(root, "version.txt")) if err != nil { return "", "", 0 } for _, line := range strings.Split(string(data), "\n") { match := nodePinRE.FindStringSubmatch(strings.TrimSpace(line)) if match == nil { continue } version = match[1] hash = match[2] if match[3] != "" { size, _ = strconv.ParseInt(match[3], 10, 64) } return version, hash, size } return "", "", 0 } // The bundled runtime wins; a system Node 24+ is a fallback, never a preference. func resolveNode(bundled string) (nodeRuntime, error) { if info, err := os.Stat(bundled); err == nil && info.Size() > 0 { _, _, pinnedSize := nodePin() if pinnedSize == 0 || info.Size() == pinnedSize { return nodeRuntime{path: bundled, label: "the bundled node.exe"}, nil } } seen := map[string]bool{} for _, candidate := range systemNodeCandidates() { key := strings.ToLower(candidate) if seen[key] { continue } seen[key] = true info, err := os.Stat(candidate) if err != nil || info.Size() == 0 { continue } if major, ok := nodeMajor(candidate); ok && major >= minNodeMajor { return nodeRuntime{ path: candidate, label: fmt.Sprintf("the system Node %d at %s", major, candidate), system: true, }, nil } } return nodeRuntime{}, fmt.Errorf("node.exe is missing from the bundle and no Node.js %d+ was found on this machine", minNodeMajor) } func systemNodeCandidates() []string { var candidates []string if found, err := exec.LookPath("node.exe"); err == nil { candidates = append(candidates, found) } if found, err := exec.LookPath("node"); err == nil { candidates = append(candidates, found) } if dir := os.Getenv("ProgramFiles"); dir != "" { candidates = append(candidates, filepath.Join(dir, "nodejs", "node.exe")) } if dir := os.Getenv("ProgramFiles(x86)"); dir != "" { candidates = append(candidates, filepath.Join(dir, "nodejs", "node.exe")) } if dir := os.Getenv("LOCALAPPDATA"); dir != "" { candidates = append(candidates, filepath.Join(dir, "Programs", "nodejs", "node.exe")) } if dir := os.Getenv("NVM_SYMLINK"); dir != "" { candidates = append(candidates, filepath.Join(dir, "node.exe")) } return candidates } func nodeMajor(exe string) (int, bool) { cmd := exec.Command(exe, "--version") cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: createNoWindow} out, err := cmd.Output() if err != nil { return 0, false } raw := strings.TrimPrefix(strings.TrimSpace(string(out)), "v") parts := strings.SplitN(raw, ".", 2) major, err := strconv.Atoi(parts[0]) if err != nil || major <= 0 { return 0, false } return major, true } // --- repair ------------------------------------------------------------------- func repair() error { nodeExe := filepath.Join(root, "node.exe") if info, ok := readRuntime(); ok && (healthy(info.Port) || processAlive(info.PID)) { return fmt.Errorf("Luminary is running (pid %d). Stop it first: Luminary.exe -stop", info.PID) } version, expected, _ := nodePin() if version == "" { return fmt.Errorf("version.txt does not record a node version, so there is nothing to re-download. Extract the zip again instead.") } if expected == "" { hash, err := publishedHash(version) if err != nil { return err } expected = hash } url := os.Getenv("LUMINARY_NODE_URL") if url == "" { url = fmt.Sprintf("https://nodejs.org/dist/v%s/win-x64/node.exe", version) } writeLog("launcher.log", "repair: downloading "+url) response, err := downloadClient.Get(url) if err != nil { return fmt.Errorf("cannot download node.exe: %w", err) } defer response.Body.Close() if response.StatusCode != http.StatusOK { return fmt.Errorf("cannot download node.exe: %s answered %s", url, response.Status) } temp := filepath.Join(root, "node.exe.new") file, err := os.Create(temp) if err != nil { return fmt.Errorf("cannot write next to the launcher: %w", err) } hasher := sha256.New() _, copyErr := io.Copy(io.MultiWriter(file, hasher), response.Body) closeErr := file.Close() if copyErr != nil { _ = os.Remove(temp) return fmt.Errorf("the download stopped early: %w", copyErr) } if closeErr != nil { _ = os.Remove(temp) return fmt.Errorf("cannot finish writing node.exe: %w", closeErr) } actual := hex.EncodeToString(hasher.Sum(nil)) if !strings.EqualFold(actual, expected) { _ = os.Remove(temp) return fmt.Errorf("the downloaded node.exe does not match the expected checksum (got %s, want %s). Nothing was changed.", actual, expected) } // Windows will not rename over an existing file; a running server is already // refused above, so the old copy is not in use here. _ = os.Remove(nodeExe) if err := os.Rename(temp, nodeExe); err != nil { _ = os.Remove(temp) return fmt.Errorf("cannot replace node.exe: %w", err) } writeLog("launcher.log", fmt.Sprintf("repair: restored node v%s sha256 %s", version, actual)) return nil } func publishedHash(version string) (string, error) { url := fmt.Sprintf("https://nodejs.org/dist/v%s/SHASUMS256.txt", version) response, err := downloadClient.Get(url) if err != nil { return "", fmt.Errorf("cannot fetch the published checksum: %w", err) } defer response.Body.Close() if response.StatusCode != http.StatusOK { return "", fmt.Errorf("cannot fetch the published checksum: %s answered %s", url, response.Status) } body, err := io.ReadAll(response.Body) if err != nil { return "", fmt.Errorf("cannot read the published checksum: %w", err) } for _, line := range strings.Split(string(body), "\n") { fields := strings.Fields(line) if len(fields) >= 2 && fields[1] == "win-x64/node.exe" { return strings.ToLower(fields[0]), nil } } return "", fmt.Errorf("no win-x64/node.exe checksum for v%s", version) } // --- commands ----------------------------------------------------------------- func stop() error { info, ok := readRuntime() if !ok { showInfo("Luminary is not running.") return nil } // /T also takes down sharp's helper processes and the denoise workers. if err := exec.Command("taskkill.exe", "/PID", strconv.Itoa(info.PID), "/T", "/F").Run(); err != nil && processAlive(info.PID) { return fmt.Errorf("cannot stop pid %d: %w", info.PID, err) } removeRuntime() return nil } // --- helpers ------------------------------------------------------------------ func bundleRoot() string { exe, err := os.Executable() if err != nil { return "." } return filepath.Dir(exe) } func dataDirectory() string { if dir := strings.TrimSpace(os.Getenv("LUMINARY_DATA")); dir != "" { return dir } base := os.Getenv("LOCALAPPDATA") if base == "" { base = filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local") } return filepath.Join(base, "Luminary", "data") } // A bundle on read-only media still has to boot; the logs move next to the data. func ensureLogDir(dataDir string) (string, error) { if err := os.MkdirAll(logsDir, 0o755); err == nil { return logsDir, nil } fallback := filepath.Join(dataDir, "logs") if err := os.MkdirAll(fallback, 0o755); err != nil { return "", fmt.Errorf("cannot create a log directory: %w", err) } return fallback, nil } func freePort() (int, error) { for port := firstPort; port <= lastPort; port++ { listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port)) if err == nil { listener.Close() return port, nil } } return 0, fmt.Errorf("no free TCP port between %d and %d", firstPort, lastPort) } func healthy(port int) bool { response, err := client.Get(fmt.Sprintf("http://127.0.0.1:%d%s", port, healthPath)) if err != nil { return false } defer response.Body.Close() return response.StatusCode == http.StatusOK } func processAlive(pid int) bool { handle, err := syscall.OpenProcess(processQueryLimitedInformation, false, uint32(pid)) if err != nil { return false } syscall.CloseHandle(handle) return true } func openBrowser(url string) { // FileProtocolHandler goes through the user's default browser without // needing a protocol registration of our own. _ = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() } // Edge ships with Windows 10/11, so a chromeless app window costs no extra // runtime. Chrome is the second choice; anything else falls back to a tab. func findAppBrowser() string { candidates := []string{} add := func(dir string, rest ...string) { if dir != "" { candidates = append(candidates, filepath.Join(append([]string{dir}, rest...)...)) } } for _, key := range []string{"ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA"} { add(os.Getenv(key), "Microsoft", "Edge", "Application", "msedge.exe") } for _, key := range []string{"LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"} { add(os.Getenv(key), "Google", "Chrome", "Application", "chrome.exe") } for _, candidate := range candidates { if info, err := os.Stat(candidate); err == nil && info.Size() > 0 { return candidate } } return "" } // --app gives a window with no tabs and no address bar, in its own profile, so // it reads as a desktop app rather than a web page. -browser opts out. func openApp(url string) { if browserOnly || strings.EqualFold(os.Getenv("LUMINARY_WINDOW"), "browser") { openBrowser(url) return } // A native WebView2 host, when the bundle ships one, is the real app window: // its own icon, no browser branding at all. native := filepath.Join(root, "LuminaryWindow.exe") if info, err := os.Stat(native); err == nil && info.Size() > 0 { if err := exec.Command(native, "--url", url).Start(); err == nil { return } } exe := findAppBrowser() if exe == "" { openBrowser(url) return } profile := filepath.Join(dataDirectory(), "window-profile") if err := os.MkdirAll(profile, 0o755); err != nil { openBrowser(url) return } // --no-proxy-server: the window only ever loads 127.0.0.1, so a proxy or // PAC script on the machine must not intercept or stall it when the // network is down. cmd := exec.Command(exe, "--app="+url, "--user-data-dir="+profile, "--window-size=1500,950", "--no-first-run", "--no-default-browser-check", "--no-proxy-server", "--disable-features=Translate", ) if err := cmd.Start(); err != nil { openBrowser(url) } } // The state file lives in the bundle folder so a copied bundle is self-contained. // On read-only media (write-protected USB, Program Files for a non-admin user) // it moves next to the data, which is always writable. func runtimePath() string { probe := filepath.Join(root, ".write-test") if err := os.WriteFile(probe, nil, 0o644); err == nil { _ = os.Remove(probe) return filepath.Join(root, "runtime.json") } return filepath.Join(dataDirectory(), "runtime.json") } func readRuntime() (runtimeInfo, bool) { var info runtimeInfo data, err := os.ReadFile(runtimePath()) if err != nil { return info, false } if json.Unmarshal(data, &info) != nil || info.PID == 0 || info.Port == 0 { return info, false } return info, true } func writeRuntime(info runtimeInfo) { data, err := json.MarshalIndent(info, "", " ") if err != nil { return } _ = os.WriteFile(runtimePath(), append(data, '\n'), 0o644) } func removeRuntime() { _ = os.Remove(runtimePath()) } func openLog(dir, name string) (*os.File, error) { return os.OpenFile(filepath.Join(dir, name), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) } func writeLog(name, message string) { dir, err := ensureLogDir(dataDirectory()) if err != nil { return } file, err := openLog(dir, name) if err != nil { return } defer file.Close() fmt.Fprintf(file, "%s %s\n", time.Now().Format(time.RFC3339), message) }