From bff218d82e2f5593fc5b6366c4ed70c24a1f89af Mon Sep 17 00:00:00 2001 From: vii Date: Wed, 2 Dec 2026 08:23:10 -0600 Subject: [PATCH 1/4] feat(update): let Nightcap update itself Ported from the Mac version's updater. `mocktail_updater nightcap` checks GitHub (cached 6 hours), verifies the signed SHA256SUMS and installs the AppImage, deb or Fedora rpm. Flatpak, Arch and Nix get their own update command instead. - When Roblox refuses the installed build and the newest one failed its test launch with this Nightcap, launch asks to update first. - Settings gets updates.nightcap (auto/notify/off) and a version row with Check/Update. - The release workflow signs SHA256SUMS and publishes the release only after every file is uploaded. --- .github/workflows/release.yml | 25 +- .gitignore | 1 + CHANGELOG.md | 10 + CMakeLists.txt | 21 + config/mocktail.example.yaml | 5 + include/runtime/payload_update_preflight.h | 36 ++ include/ui/settings_model.h | 2 + include/update/http_download.h | 1 + include/update/nightcap_install_method.h | 48 ++ include/update/nightcap_release.h | 52 +++ include/update/nightcap_self_update.h | 69 +++ include/update/update_config.h | 2 + packaging/release/nightcap-release.pub | 3 + src/main.cc | 97 ++++ src/runtime/payload_update_preflight.cc | 233 +++++++++- src/runtime/runtime_config_bootstrap.cc | 5 + src/ui/mocktail_settings.cc | 121 +++++ src/ui/settings_model.cc | 20 + src/update/http_download.cc | 8 +- src/update/main.cc | 87 +++- src/update/nightcap_install_method.cc | 277 +++++++++++ src/update/nightcap_release.cc | 219 +++++++++ src/update/nightcap_self_update.cc | 507 +++++++++++++++++++++ src/update/update_config.cc | 8 + src/update/update_coordinator.cc | 26 ++ tests/CMakeLists.txt | 13 + tests/native_packaging_test.sh | 3 + tests/native_update_helper_fixture.cc | 16 + tests/native_update_test.cc | 38 +- tests/nightcap_install_method_test.cc | 172 +++++++ tests/nightcap_release_test.cc | 157 +++++++ tests/nightcap_self_update_test.cc | 339 ++++++++++++++ tests/payload_update_preflight_test.cc | 143 ++++++ tests/runtime_config_file_test.cc | 5 + tests/settings_model_test.cc | 20 +- 35 files changed, 2765 insertions(+), 24 deletions(-) create mode 100644 include/update/nightcap_install_method.h create mode 100644 include/update/nightcap_release.h create mode 100644 include/update/nightcap_self_update.h create mode 100644 packaging/release/nightcap-release.pub create mode 100644 src/update/nightcap_install_method.cc create mode 100644 src/update/nightcap_release.cc create mode 100644 src/update/nightcap_self_update.cc create mode 100644 tests/nightcap_install_method_test.cc create mode 100644 tests/nightcap_release_test.cc create mode 100644 tests/nightcap_self_update_test.cc diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23df72345..7f8f99be4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,6 +35,7 @@ jobs: name: Publish GitHub release if: startsWith(github.ref, 'refs/tags/v') needs: [build, flatpak] + environment: release runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: @@ -54,6 +55,7 @@ jobs: shell: bash env: GH_TOKEN: ${{ github.token }} + RELEASE_SIGNING_KEY: ${{ secrets.NIGHTCAP_RELEASE_SIGNING_KEY }} run: | set -Eeuo pipefail tag="${GITHUB_REF_NAME}" @@ -80,10 +82,30 @@ jobs: for asset in "${assets[@]}"; do sha256sum "$asset" > "$asset.sha256" done + for asset in "${assets[@]}"; do cat "$asset.sha256"; done > SHA256SUMS ) + uploads+=(release/SHA256SUMS) + # Nightcap installs a release only when this signature checks out + # against the key built into it. + public_key=packaging/release/nightcap-release.pub + if [[ -n "${RELEASE_SIGNING_KEY}" ]]; then + key_file="$(mktemp -p "${RUNNER_TEMP}")" + trap 'rm -f -- "${key_file}"' EXIT + printf '%s\n' "${RELEASE_SIGNING_KEY}" > "${key_file}" + openssl pkeyutl -sign -inkey "${key_file}" -rawin \ + -in release/SHA256SUMS -out release/SHA256SUMS.sig + openssl pkeyutl -verify -pubin -inkey "${public_key}" -rawin \ + -in release/SHA256SUMS -sigfile release/SHA256SUMS.sig + uploads+=(release/SHA256SUMS.sig) + elif [[ -f "${public_key}" ]]; then + echo "::error::NIGHTCAP_RELEASE_SIGNING_KEY is not set; Nightcap only installs signed releases" + exit 1 + fi ./scripts/release_notes.sh "$tag" > release/notes.md + # A new release stays a draft until every file is up: Nightcap caches + # the latest release's file list for 6 hours. if ! gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then - gh release create "$tag" --repo "$GITHUB_REPOSITORY" \ + gh release create "$tag" --repo "$GITHUB_REPOSITORY" --draft \ --title "Nightcap $tag" --notes-file release/notes.md || gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null fi @@ -91,6 +113,7 @@ jobs: --title "Nightcap $tag" --notes-file release/notes.md gh release upload "$tag" --repo "$GITHUB_REPOSITORY" --clobber \ "${uploads[@]}" + gh release edit "$tag" --repo "$GITHUB_REPOSITORY" --draft=false # nightcap-bin downloads the pacman package from the release page, so this # waits for the upload. diff --git a/.gitignore b/.gitignore index e631edeaa..f44b9b856 100644 --- a/.gitignore +++ b/.gitignore @@ -142,6 +142,7 @@ desktop.ini .env.* !.env.example *.pem +/.release-keys/ cookies*.txt *credentials* *secret* diff --git a/CHANGELOG.md b/CHANGELOG.md index fd9966cc2..f1a02c355 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,16 @@ Release notes on GitHub are taken from the matching section here. ## [Unreleased] +### Added + +- Nightcap updates itself. It checks GitHub at most every 6 hours, and the AppImage installs a new + release in the background; the deb and Fedora rpm install it through pkexec. Settings has a Nightcap + version row with Check and Update, and `updates.nightcap` (`auto`, `notify` or `off`) picks how much + it does. Flatpak, Arch and Nix installs show their own update command instead. +- When Roblox stops letting the installed version join and the newest one fails its test launch with + this Nightcap, Nightcap asks to update itself before starting, then restarts on the new release. + Releases are checked against a signed `SHA256SUMS` before anything is installed. + ### Fixed - With Vulkan on NVIDIA under Wayland, joining a game no longer crashes when the window changes size diff --git a/CMakeLists.txt b/CMakeLists.txt index 9a2e19b9d..aabea75be 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -212,6 +212,9 @@ add_library(mocktail_update STATIC src/update/file_lock.cc src/update/http_download.cc src/update/host_abi_deriver.cc + src/update/nightcap_install_method.cc + src/update/nightcap_release.cc + src/update/nightcap_self_update.cc src/update/payload_integrity.cc src/update/payload_store.cc src/update/pinned_apk_provider.cc @@ -236,9 +239,27 @@ target_link_libraries(mocktail_update PUBLIC ) mocktail_apply_compile_options(mocktail_update) +set(MOCKTAIL_RELEASE_KEY + "${PROJECT_SOURCE_DIR}/packaging/release/nightcap-release.pub" CACHE FILEPATH + "Ed25519 public key (PEM) that signs each release's SHA256SUMS; without it Nightcap cannot update itself") +set(_nightcap_release_key "") +if(EXISTS "${MOCKTAIL_RELEASE_KEY}") + file(READ "${MOCKTAIL_RELEASE_KEY}" _nightcap_release_key) + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + "${MOCKTAIL_RELEASE_KEY}") +else() + message(STATUS "Nightcap: no release key at ${MOCKTAIL_RELEASE_KEY}; Nightcap updates are off in this build") +endif() +file(CONFIGURE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/generated/nightcap_release_key.h" + CONTENT "#pragma once\ninline constexpr char kNightcapReleasePublicKey[] = R\"key(@_nightcap_release_key@)key\";\n" + @ONLY) + add_executable(mocktail_updater src/update/main.cc) target_link_libraries(mocktail_updater PRIVATE Mocktail::Update) +target_include_directories(mocktail_updater PRIVATE + "${CMAKE_CURRENT_BINARY_DIR}/generated") target_compile_definitions(mocktail_updater PRIVATE + "MOCKTAIL_PROJECT_VERSION=\"${PROJECT_VERSION}\"" "MOCKTAIL_DEFAULT_COMPATIBILITY_MANIFEST=\"${MOCKTAIL_DEFAULT_COMPATIBILITY_MANIFEST}\"" "MOCKTAIL_DEFAULT_SIGNING_TRUST_MANIFEST=\"${MOCKTAIL_DEFAULT_SIGNING_TRUST_MANIFEST}\"" "MOCKTAIL_DEFAULT_DOWNLOAD_SOURCES_MANIFEST=\"${MOCKTAIL_DEFAULT_DOWNLOAD_SOURCES_MANIFEST}\"" diff --git a/config/mocktail.example.yaml b/config/mocktail.example.yaml index f6d64466e..c2a1d64ad 100644 --- a/config/mocktail.example.yaml +++ b/config/mocktail.example.yaml @@ -221,3 +221,8 @@ updates: # Reserved for desktop update integrations. `mocktail_updater` itself never # launches another process after changing the active payload. launch_after_update: false + # String (default: auto): Nightcap's own updates. auto checks GitHub at + # most every 6 hours and an AppImage installs a new release by itself; + # notify only checks; off never asks GitHub. A Roblox build that needs + # a newer Nightcap still shows the update dialog. + nightcap: auto diff --git a/include/runtime/payload_update_preflight.h b/include/runtime/payload_update_preflight.h index 8cc50da8e..82aa11368 100644 --- a/include/runtime/payload_update_preflight.h +++ b/include/runtime/payload_update_preflight.h @@ -47,6 +47,42 @@ std::string QueryRobloxUpgradeAction(const std::string& version_name, using UpgradeActionQuery = std::function* cancel)>; +struct NightcapUpdateNeed { + bool required = false; + std::string installed_roblox; + std::string newest_roblox; +}; + +// Required when this build rejected the newest Roblox and Roblox refuses the +// installed one. Roblox is asked only when such a rejection is on record. +NightcapUpdateNeed AssessNightcapUpdateNeed(const RuntimePaths& paths, + std::string_view runtime_build_id, + const UpgradeActionQuery& ask_roblox); + +struct NightcapUpdaterStatus { + std::string error; + std::string installed; + std::string installed_pending; + bool newer = false; + bool can_install = false; + std::string kind; + std::string latest; + std::string command; + std::string note; +}; + +// kCached asks GitHub only when the last answer is 6 hours old; kOffline +// never asks; kForce always does. +enum class NightcapCheck { kCached, kOffline, kForce }; + +NightcapUpdaterStatus ReadNightcapUpdaterStatus(const Environment& environment, + const RuntimePaths& paths, + NightcapCheck check); + +// `mocktail_updater nightcap install` behind the update progress window. +PayloadUpdatePreflightResult RunNightcapInstall(const Environment& environment, + const RuntimePaths& paths); + class BackgroundPayloadUpdate final { public: ~BackgroundPayloadUpdate(); diff --git a/include/ui/settings_model.h b/include/ui/settings_model.h index 1b07da344..d124c4af3 100644 --- a/include/ui/settings_model.h +++ b/include/ui/settings_model.h @@ -37,6 +37,8 @@ enum class SettingKind { // textures_folder. kFolder, kCache, + // This Nightcap's version and the newest release, with Check or Update. + kNightcapRelease, // Installs a sky pack into the asset overlay, or removes it. kSky, // Picks the font that replaces Roblox's, or goes back to Roblox's. diff --git a/include/update/http_download.h b/include/update/http_download.h index 96b3937fb..3775426c2 100644 --- a/include/update/http_download.h +++ b/include/update/http_download.h @@ -29,6 +29,7 @@ struct HttpTransferRequest { int maximum_attempts = 3; long retry_delay_ms = 2000; int maximum_redirects = 5; + std::string progress_label = "Roblox"; }; struct HttpBytesResult { diff --git a/include/update/nightcap_install_method.h b/include/update/nightcap_install_method.h new file mode 100644 index 000000000..123874c73 --- /dev/null +++ b/include/update/nightcap_install_method.h @@ -0,0 +1,48 @@ +#ifndef MOCKTAIL_UPDATE_NIGHTCAP_INSTALL_METHOD_H_ +#define MOCKTAIL_UPDATE_NIGHTCAP_INSTALL_METHOD_H_ + +#include +#include +#include +#include +#include + +namespace mocktail::update { + +enum class InstallKind { kAppImage, kArch, kDeb, kRpm, kFlatpak, kNix, kSource }; + +std::string_view InstallKindName(InstallKind kind); + +struct InstallMethod { + InstallKind kind = InstallKind::kSource; + std::filesystem::path appimage; + // The system package owning the executable; only "nightcap" is a release. + std::string package; + std::string distro_version; + bool self_update = false; + // What the user runs instead, when Nightcap cannot update itself. + std::string command; + std::string reason; +}; + +struct InstallProbe { + std::filesystem::path executable; + std::optional appimage_variable; + bool flatpak = false; + std::string os_id; + std::string os_version_id; + // `manager` is pacman, dpkg or rpm; nullopt when it owns no package there. + std::function(std::string_view manager, + const std::filesystem::path& path)> + owner; + std::function has_program; + std::function writable_regular_file; +}; + +InstallMethod DetectInstallMethod(const InstallProbe& probe); + +InstallProbe SystemInstallProbe(); + +} // namespace mocktail::update + +#endif // MOCKTAIL_UPDATE_NIGHTCAP_INSTALL_METHOD_H_ diff --git a/include/update/nightcap_release.h b/include/update/nightcap_release.h new file mode 100644 index 000000000..726514a03 --- /dev/null +++ b/include/update/nightcap_release.h @@ -0,0 +1,52 @@ +#ifndef MOCKTAIL_UPDATE_NIGHTCAP_RELEASE_H_ +#define MOCKTAIL_UPDATE_NIGHTCAP_RELEASE_H_ + +#include +#include +#include +#include +#include +#include + +#include "update/nightcap_install_method.h" + +namespace mocktail::update { + +inline constexpr char kSumsAsset[] = "SHA256SUMS"; +inline constexpr char kSumsSignatureAsset[] = "SHA256SUMS.sig"; + +struct ReleaseAsset { + std::string name; + std::string url; + std::uint64_t size = 0; +}; + +struct NightcapRelease { + std::string version; + std::string page; + std::vector assets; + + const ReleaseAsset* Find(std::string_view name) const; +}; + +// Refuses drafts, prereleases, non-vX.Y.Z tags and assets off the tag's path. +std::optional ParseLatestRelease(std::string_view body, + std::string* error = nullptr); + +std::optional CompareVersions(std::string_view a, std::string_view b); + +std::optional AssetNameFor(const InstallMethod& method, + std::string_view version); + +// `sha256sum` output: "<64 hex> " lines, hashes lowercased. +std::optional> ParseSums( + std::string_view text, std::string* error = nullptr); + +// `signature` is the raw 64 bytes `openssl pkeyutl -sign -rawin` writes. +bool VerifyEd25519(std::string_view message, std::string_view signature, + std::string_view public_key_pem, + std::string* error = nullptr); + +} // namespace mocktail::update + +#endif // MOCKTAIL_UPDATE_NIGHTCAP_RELEASE_H_ diff --git a/include/update/nightcap_self_update.h b/include/update/nightcap_self_update.h new file mode 100644 index 000000000..8efa27999 --- /dev/null +++ b/include/update/nightcap_self_update.h @@ -0,0 +1,69 @@ +#ifndef MOCKTAIL_UPDATE_NIGHTCAP_SELF_UPDATE_H_ +#define MOCKTAIL_UPDATE_NIGHTCAP_SELF_UPDATE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "update/http_download.h" +#include "update/nightcap_install_method.h" + +namespace mocktail::update { + +inline constexpr char kNightcapLatestReleaseUrl[] = + "https://api.github.com/repos/CoderDayton/nightcap/releases/latest"; +// GitHub allows 60 unauthenticated API requests an hour per address. +inline constexpr std::chrono::hours kNightcapCheckInterval{6}; + +struct NightcapUpdaterEnvironment { + std::filesystem::path data_root; + std::filesystem::path cache_root; + std::string running_version; + std::string public_key_pem; + InstallMethod method; + std::function fetch; + std::function + download; + std::function&)> run; + std::function now; +}; + +struct NightcapStatus { + std::string installed; + std::optional latest; + std::string installed_pending; + std::string page; + InstallMethod method; + std::int64_t checked_at = 0; + bool newer = false; + bool can_install = false; + std::string note; + + std::string ToJson() const; +}; + +// Asks GitHub at most every kNightcapCheckInterval unless `force`; `offline` +// answers only from the last check. +std::optional CheckNightcapRelease( + const NightcapUpdaterEnvironment& environment, bool force, bool offline, + std::string* error); + +// Installs the newest release when it is newer than the running one, after +// checking SHA256SUMS against the release key and the download against it. +// Progress goes to `progress_fd` in the Roblox updater's format. +bool InstallNightcapRelease(const NightcapUpdaterEnvironment& environment, + int progress_fd, std::string* message, + std::string* error); + +NightcapUpdaterEnvironment SystemNightcapUpdaterEnvironment( + std::filesystem::path data_root, std::filesystem::path cache_root, + std::string running_version, std::string public_key_pem); + +} // namespace mocktail::update + +#endif // MOCKTAIL_UPDATE_NIGHTCAP_SELF_UPDATE_H_ diff --git a/include/update/update_config.h b/include/update/update_config.h index f52f47493..379e90837 100644 --- a/include/update/update_config.h +++ b/include/update/update_config.h @@ -11,6 +11,8 @@ struct UpdateConfig { bool automatic = true; bool launch_after_update = false; std::string source = "apk-pure"; + // auto, notify or off. + std::string nightcap = "auto"; }; struct UpdateConfigResult { diff --git a/packaging/release/nightcap-release.pub b/packaging/release/nightcap-release.pub new file mode 100644 index 000000000..e45c730c0 --- /dev/null +++ b/packaging/release/nightcap-release.pub @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEAI6sZs5m5nWNIcpudvwF+qkfDfByxFgTQA2jhDuvHiz8= +-----END PUBLIC KEY----- diff --git a/src/main.cc b/src/main.cc index 85ee01258..c44329637 100644 --- a/src/main.cc +++ b/src/main.cc @@ -490,6 +490,97 @@ void UpdateAppImageMenu(const mocktail::runtime::Environment& environment, } } +enum class NightcapGate { kPlay, kExit }; + +// Roblox stops old builds from joining. When the newest one also failed its +// test launch with this Nightcap, only a Nightcap update lets the user play. +NightcapGate RequireNightcapThatCanJoin( + const mocktail::runtime::Environment& environment, + const mocktail::runtime::RuntimePaths& paths, char* argv[]) { + // The updater records rejections against this binary; under the AppImage's + // sharun loader /proc/self/exe is the ELF interpreter instead. + const auto runtime_binary = environment.Get("MOCKTAIL_UPDATE_RUNTIME_BINARY"); + const mocktail::compat::BuildIdResult self = mocktail::compat::ReadElfBuildId( + runtime_binary && !runtime_binary->empty() ? *runtime_binary + : "/proc/self/exe"); + if (!self) return NightcapGate::kPlay; + const mocktail::runtime::NightcapUpdateNeed need = + mocktail::runtime::AssessNightcapUpdateNeed( + paths, self.build_id, mocktail::runtime::QueryRobloxUpgradeAction); + if (!need.required) return NightcapGate::kPlay; + std::cerr << " [update] Roblox stopped letting " << need.installed_roblox + << " join, and " << need.newest_roblox + << " failed its test launch with this Nightcap\n"; + if (!mocktail::runtime::FailureDialogsEnabled(environment)) { + return NightcapGate::kPlay; + } + const mocktail::runtime::NightcapUpdaterStatus status = + mocktail::runtime::ReadNightcapUpdaterStatus( + environment, paths, mocktail::runtime::NightcapCheck::kCached); + const std::string heading = "Update Nightcap"; + std::string body = "Roblox no longer lets version " + need.installed_roblox + + " join games, and Roblox " + need.newest_roblox + + " needs a newer Nightcap."; + if (!status.error.empty() || !status.newer) { + std::cerr << " [update] no newer Nightcap to install" + << (status.error.empty() ? "" : ": " + status.error) << '\n'; + (void)mocktail::runtime::ShowWarningDialog( + environment, + body + (status.error.empty() + ? "\n\nThat Nightcap isn't out yet. You can still open " + "Roblox, but joining games may fail until it is." + : "\n\nNightcap could not check for that update: " + + status.error + + "\n\nYou can still open Roblox, but joining games " + "may fail."), + heading); + return NightcapGate::kPlay; + } + if (!status.can_install) { + body += "\n\nNightcap " + status.latest + " is out. "; + body += status.command.empty() ? status.note + : "Update it with:\n" + status.command; + (void)mocktail::runtime::ShowWarningDialog(environment, body, heading); + return NightcapGate::kExit; + } + const std::optional update = mocktail::runtime::AskYesNo( + environment, heading, + body + "\n\nNightcap " + status.latest + " is ready to install.", "Quit", + "Update"); + if (!update.value_or(false)) return NightcapGate::kExit; + const mocktail::runtime::PayloadUpdatePreflightResult installed = + mocktail::runtime::RunNightcapInstall(environment, paths); + if (!installed) { + std::cerr << " [update] Nightcap update failed: " + << (installed.details.empty() ? installed.error + : installed.details) + << '\n'; + (void)mocktail::runtime::ShowFailureDialog( + environment, "Nightcap could not update itself.\n\n" + + (installed.details.empty() ? installed.error + : installed.details)); + return NightcapGate::kExit; + } + // Same path, new file: exec runs the new release with the same arguments. + const auto appimage = environment.Get("APPIMAGE"); + if (status.kind == "appimage" && appimage && !appimage->empty()) { + std::vector arguments = {const_cast(appimage->c_str())}; + for (char** argument = argv + 1; *argument != nullptr; ++argument) { + arguments.push_back(*argument); + } + arguments.push_back(nullptr); + std::cerr << " [update] starting Nightcap " << status.latest << '\n'; + execv(appimage->c_str(), arguments.data()); + std::cerr << " [update] cannot start the new AppImage: " + << std::strerror(errno) << '\n'; + } + (void)mocktail::runtime::ShowWarningDialog( + environment, + "Nightcap " + status.latest + " is installed. Start Nightcap again to play.", + "Nightcap updated"); + return NightcapGate::kExit; +} + } // namespace int main(int argc, char* argv[]) { @@ -1075,6 +1166,12 @@ int main(int argc, char* argv[]) { std::cerr << '\n'; return EXIT_FAILURE; } + if (!environment.HasNonEmpty("MOCKTAIL_ISOLATED_CANARY") && + RequireNightcapThatCanJoin(environment, paths, argv) == + NightcapGate::kExit) { + failure_dialog.MarkSuccessful(); + return EXIT_SUCCESS; + } failure_dialog.SetMessage("Nightcap could not finish starting Roblox."); background_update.Start(environment, paths, std::chrono::minutes(30), mocktail::runtime::QueryRobloxUpgradeAction); diff --git a/src/runtime/payload_update_preflight.cc b/src/runtime/payload_update_preflight.cc index b6fc6b2b6..52f56abb2 100644 --- a/src/runtime/payload_update_preflight.cc +++ b/src/runtime/payload_update_preflight.cc @@ -405,6 +405,21 @@ std::string Sentence(std::string text) { return text; } +struct UpdaterRun { + std::string error; + std::string details; + // It ran and exited unsuccessfully, as opposed to never running. + bool failed = false; +}; + +// Runs `helper `, relaying its stderr and keeping its last failure; +// `output`, when given, receives its stdout. +UpdaterRun RunUpdater(const Environment& environment, const RuntimePaths& paths, + const std::filesystem::path& helper, + const std::vector& command, + bool show_progress, std::string_view name, + std::string* output); + } // namespace std::string DescribeUpdateFailure(std::string_view details) { @@ -445,14 +460,50 @@ PayloadUpdatePreflightResult RunPayloadUpdatePreflight( } result.attempted = true; - std::string helper_string = helper.string(); - char update[] = "update"; - char startup_preflight[] = "--startup-preflight"; - char force_latest[] = "--force-run-latest"; - char* arguments[] = {helper_string.data(), update, - force_run_latest ? force_latest : startup_preflight, - nullptr}; - UpdateProgressMonitor progress = UpdateProgressMonitor::Start(environment); + const UpdaterRun run = RunUpdater( + environment, paths, helper, + {"update", force_run_latest ? "--force-run-latest" : "--startup-preflight"}, + true, "Roblox update preflight", nullptr); + result.error = run.error; + result.details = run.details; + if (run.failed) { + result.error = force_run_latest ? "forced latest Roblox run failed" + : "Roblox update preflight failed"; + } + return result; +} + +namespace { + +UpdaterRun RunUpdater(const Environment& environment, const RuntimePaths& paths, + const std::filesystem::path& helper, + const std::vector& command, + bool show_progress, std::string_view name, + std::string* output) { + UpdaterRun result; + std::vector argument_storage = {helper.string()}; + argument_storage.insert(argument_storage.end(), command.begin(), + command.end()); + std::vector arguments; + for (std::string& argument : argument_storage) { + arguments.push_back(argument.data()); + } + arguments.push_back(nullptr); + UpdateProgressMonitor progress = show_progress + ? UpdateProgressMonitor::Start(environment) + : UpdateProgressMonitor(); + int output_pipe[2] = {-1, -1}; + if (output != nullptr && pipe2(output_pipe, O_CLOEXEC) != 0) { + result.error = "cannot capture the " + std::string(name) + + " output: " + std::strerror(errno); + return result; + } + const auto close_output = [&output_pipe] { + for (int& descriptor : output_pipe) { + if (descriptor >= 0) close(descriptor); + descriptor = -1; + } + }; std::vector child_environment = ChildEnvironment(paths, progress.socket()); std::vector child_environment_pointers; @@ -478,23 +529,35 @@ PayloadUpdatePreflightResult RunPayloadUpdatePreflight( action_status = posix_spawn_file_actions_adddup2( &actions, stderr_relay.write_descriptor(), STDERR_FILENO); } + if (action_status == 0 && output_pipe[1] >= 0) { + if (!actions_initialized) { + action_status = posix_spawn_file_actions_init(&actions); + actions_initialized = action_status == 0; + } + if (action_status == 0) { + action_status = posix_spawn_file_actions_adddup2(&actions, output_pipe[1], + STDOUT_FILENO); + } + } if (action_status != 0) { if (actions_initialized) { posix_spawn_file_actions_destroy(&actions); } - result.error = "cannot prepare Roblox update progress channel: " + - std::string(std::strerror(action_status)); + close_output(); + result.error = "cannot prepare the " + std::string(name) + + " channels: " + std::string(std::strerror(action_status)); return result; } pid_t child = -1; const int spawn_status = posix_spawn( &child, helper.c_str(), actions_initialized ? &actions : nullptr, nullptr, - arguments, child_environment_pointers.data()); + arguments.data(), child_environment_pointers.data()); if (actions_initialized) { posix_spawn_file_actions_destroy(&actions); } if (spawn_status != 0) { - result.error = "cannot start Roblox update preflight: " + + close_output(); + result.error = "cannot start " + std::string(name) + ": " + std::string(std::strerror(spawn_status)); return result; } @@ -502,19 +565,32 @@ PayloadUpdatePreflightResult RunPayloadUpdatePreflight( // The child owns the write end now; the relay must observe end-of-file. stderr_relay.CloseWrite(); stderr_relay.Drain(); + // Read after stderr: the output is one short line, far below a pipe buffer. + if (output_pipe[1] >= 0) { + close(output_pipe[1]); + output_pipe[1] = -1; + std::array buffer{}; + for (;;) { + const ssize_t received = read(output_pipe[0], buffer.data(), buffer.size()); + if (received < 0 && errno == EINTR) continue; + if (received <= 0 || output->size() > 65536) break; + output->append(buffer.data(), static_cast(received)); + } + } + close_output(); int child_status = 0; while (waitpid(child, &child_status, 0) < 0) { if (errno == EINTR) { continue; } - result.error = "cannot wait for Roblox update preflight: " + + result.error = "cannot wait for " + std::string(name) + ": " + std::string(std::strerror(errno)); return result; } if (!WIFEXITED(child_status) || WEXITSTATUS(child_status) != 0) { - result.error = force_run_latest ? "forced latest Roblox run failed" - : "Roblox update preflight failed"; + result.failed = true; + result.error = std::string(name) + " failed"; result.details = stderr_relay.failure(); if (WIFSIGNALED(child_status)) { const int signal_number = WTERMSIG(child_status); @@ -534,6 +610,8 @@ PayloadUpdatePreflightResult RunPayloadUpdatePreflight( return result; } +} // namespace + std::string ReadRobloxUpgradeAction(const nlohmann::json& reply) { if (!reply.is_object()) return {}; const auto data = reply.find("data"); @@ -570,6 +648,102 @@ std::string ActiveVersionName(const RuntimePaths& paths) { } // namespace +NightcapUpdateNeed AssessNightcapUpdateNeed(const RuntimePaths& paths, + std::string_view runtime_build_id, + const UpgradeActionQuery& ask_roblox) { + NightcapUpdateNeed need; + std::ifstream state_input(paths.data_root() / "update.json"); + const auto state = nlohmann::json::parse(state_input, nullptr, false); + std::ifstream active_input(paths.active_payload_manifest()); + const auto active = nlohmann::json::parse(active_input, nullptr, false); + if (!state.is_object() || !active.is_object() || runtime_build_id.empty() || + !ask_roblox) { + return need; + } + const auto rejected = state.find("latest_rejected"); + if (rejected == state.end() || !rejected->is_object()) return need; + const auto text = [](const nlohmann::json& object, const char* key) { + const auto it = object.find(key); + return it != object.end() && it->is_string() ? it->get() + : std::string(); + }; + const auto code = [](const nlohmann::json& object) { + const auto it = object.find("version_code"); + return it != object.end() && it->is_number_unsigned() + ? it->get() + : std::uint64_t{0}; + }; + need.installed_roblox = text(active, "version_name"); + need.newest_roblox = text(*rejected, "version_name"); + if (text(*rejected, "runtime_build_id") != runtime_build_id || + code(*rejected) <= code(active) || need.installed_roblox.empty()) { + return need; + } + need.required = ask_roblox(need.installed_roblox, nullptr) == "Required"; + return need; +} + +NightcapUpdaterStatus ReadNightcapUpdaterStatus(const Environment& environment, + const RuntimePaths& paths, + NightcapCheck check) { + NightcapUpdaterStatus status; + const std::filesystem::path helper = UpdateHelper(environment); + if (helper.empty()) { + status.error = "cannot locate the Mocktail update helper"; + return status; + } + std::vector command = {"nightcap", "status"}; + if (check == NightcapCheck::kOffline) command.emplace_back("--offline"); + if (check == NightcapCheck::kForce) command.emplace_back("--force"); + std::string output; + const UpdaterRun run = RunUpdater(environment, paths, helper, command, false, + "Nightcap update check", &output); + if (!run.error.empty()) { + status.error = run.details.empty() ? run.error : run.details; + return status; + } + const auto json = nlohmann::json::parse(output, nullptr, false); + if (!json.is_object()) { + status.error = "the Nightcap update check gave no answer"; + return status; + } + const auto text = [&json](const char* key) { + const auto it = json.find(key); + return it != json.end() && it->is_string() ? it->get() + : std::string(); + }; + const auto flag = [&json](const char* key) { + const auto it = json.find(key); + return it != json.end() && it->is_boolean() && it->get(); + }; + status.installed = text("installed"); + status.installed_pending = text("installed_pending"); + status.newer = flag("newer"); + status.can_install = flag("can_install"); + status.kind = text("kind"); + status.latest = text("latest"); + status.command = text("command"); + status.note = text("note"); + return status; +} + +PayloadUpdatePreflightResult RunNightcapInstall(const Environment& environment, + const RuntimePaths& paths) { + PayloadUpdatePreflightResult result; + const std::filesystem::path helper = UpdateHelper(environment); + if (helper.empty()) { + result.error = "cannot locate the Mocktail update helper"; + return result; + } + result.attempted = true; + const UpdaterRun run = RunUpdater(environment, paths, helper, + {"nightcap", "install"}, true, + "Nightcap update", nullptr); + result.error = run.error; + result.details = run.details; + return result; +} + BackgroundPayloadUpdate::~BackgroundPayloadUpdate() { Stop(); } void BackgroundPayloadUpdate::Start(const Environment& environment, @@ -628,10 +802,12 @@ void BackgroundPayloadUpdate::Start(const Environment& environment, kIoprioLowestBestEffort); // Past most game joins, so a release found then is ready next launch. auto delay = std::min(interval, kFirstBackgroundUpdateDelay); + bool roblox_urgent = false; if (!version_name.empty()) { const std::string action = ask_roblox(version_name, &cancel_); if (action == "Required" || action == "Recommended") { delay = std::chrono::milliseconds(0); + roblox_urgent = true; std::fprintf(stderr, " [update] Roblox marks %s as %s; checking for an " "update now\n", @@ -648,13 +824,34 @@ void BackgroundPayloadUpdate::Start(const Environment& environment, .count())); } } + char nightcap[] = "nightcap"; + char automatic[] = "auto"; + char* nightcap_arguments[] = {executable.data(), nightcap, automatic, + nullptr}; + bool nightcap_checked = false; + bool roblox_checked = false; std::unique_lock lock(mutex_); while (!wake_.wait_for(lock, delay, [this] { return stopped_; })) { delay = interval; + // Nightcap's own release, once per launch, next to the first + // Roblox check: after it when Roblox needs an update, so that + // download is not held up, and before it otherwise. + char** run = arguments; + const char* what = "background check"; + if (!nightcap_checked && roblox_urgent) { + roblox_urgent = false; + delay = std::chrono::milliseconds(0); + } else if (!nightcap_checked) { + nightcap_checked = true; + run = nightcap_arguments; + what = "Nightcap check"; + if (!roblox_checked) delay = std::chrono::milliseconds(0); + } + if (run == arguments) roblox_checked = true; pid_t process = -1; const int status = posix_spawn( &process, executable.c_str(), nullptr, - attributes_ready ? &attributes : nullptr, arguments, + attributes_ready ? &attributes : nullptr, run, environment_pointers.data()); if (status != 0) continue; child_ = process; @@ -675,9 +872,9 @@ void BackgroundPayloadUpdate::Start(const Environment& environment, usage.ru_stime.tv_usec) / 1e6; std::fprintf(stderr, - " [update] background check took %.1f s, %.1f s " + " [update] %s took %.1f s, %.1f s " "CPU, peak %ld MiB, status %d\n", - seconds, cpu, usage.ru_maxrss / 1024, + what, seconds, cpu, usage.ru_maxrss / 1024, WIFEXITED(child_status) ? WEXITSTATUS(child_status) : -1); child_ = -1; diff --git a/src/runtime/runtime_config_bootstrap.cc b/src/runtime/runtime_config_bootstrap.cc index 11db33739..7aa9cda1b 100644 --- a/src/runtime/runtime_config_bootstrap.cc +++ b/src/runtime/runtime_config_bootstrap.cc @@ -240,6 +240,11 @@ device: pc-windows-11 # Reserved for desktop update integrations. `mocktail_updater` itself never # launches another process after changing the active payload. launch_after_update: false + # String (default: auto): Nightcap's own updates. auto checks GitHub at + # most every 6 hours and an AppImage installs a new release by itself; + # notify only checks; off never asks GitHub. A Roblox build that needs + # a newer Nightcap still shows the update dialog. + nightcap: auto )yaml"; std::string ErrorMessage(std::string_view action, int error_number) { diff --git a/src/ui/mocktail_settings.cc b/src/ui/mocktail_settings.cc index 01a7859f8..7ea4c0030 100644 --- a/src/ui/mocktail_settings.cc +++ b/src/ui/mocktail_settings.cc @@ -23,6 +23,7 @@ #include "mocktail/platform/sdl_window_icon_data.h" #include "runtime/custom_font.h" #include "runtime/environment.h" +#include "runtime/payload_update_preflight.h" #include "runtime/fleasion.h" #include "runtime/session_log.h" #include "runtime/roblox_cache.h" @@ -165,6 +166,9 @@ struct SettingsWindow { std::filesystem::path roblox_data_lock; Row* cache = nullptr; GtkWidget* cache_button = nullptr; + Row* nightcap = nullptr; + GtkWidget* nightcap_button = nullptr; + bool nightcap_can_install = false; std::filesystem::path asset_overlay_dir; std::filesystem::path textures_dir; std::filesystem::path sky_library; @@ -751,6 +755,7 @@ void RefreshRow(Row* row, bool keep_edit) { case SettingKind::kEditor: case SettingKind::kFolder: case SettingKind::kCache: + case SettingKind::kNightcapRelease: break; } } @@ -2294,6 +2299,108 @@ void StartCacheJob(SettingsWindow* window, bool clear) { g_object_unref(task); } +struct NightcapJob { + enum Action { kShow, kCheck, kInstall }; + Action action = kShow; + // updates.nightcap: "off" keeps the window from asking GitHub by itself. + std::string mode; + mocktail::runtime::NightcapUpdaterStatus status; + std::string install_error; +}; + +void RunNightcapJob(GTask* task, gpointer, gpointer task_data, GCancellable*) { + auto* job = static_cast(task_data); + const mocktail::runtime::ProcessEnvironment environment; + const auto paths = mocktail::runtime::RuntimePaths::FromEnvironment(environment); + using mocktail::runtime::NightcapCheck; + NightcapCheck check = job->mode == "off" ? NightcapCheck::kOffline + : NightcapCheck::kCached; + if (job->action == NightcapJob::kCheck) check = NightcapCheck::kForce; + if (job->action == NightcapJob::kInstall) { + const auto installed = mocktail::runtime::RunNightcapInstall(environment, paths); + if (!installed) { + job->install_error = + installed.details.empty() ? installed.error : installed.details; + } + check = NightcapCheck::kOffline; + } + job->status = mocktail::runtime::ReadNightcapUpdaterStatus(environment, paths, check); + g_task_return_boolean(task, TRUE); +} + +std::string NightcapSubtitle(const mocktail::runtime::NightcapUpdaterStatus& status) { + const std::string self = "Nightcap " + status.installed + "."; + if (!status.error.empty()) return "Can't check for updates: " + status.error; + if (!status.installed_pending.empty()) { + return self + " " + status.installed_pending + + " is installed; restart Nightcap to use it."; + } + if (status.newer) { + std::string text = self + " " + status.latest + " is out."; + if (status.can_install) return text; + if (!status.command.empty()) return text + " Update it with " + status.command + "."; + return status.note.empty() ? text : text + " " + status.note; + } + if (!status.latest.empty()) return self + " This is the newest release."; + return self; +} + +void StartNightcapJob(SettingsWindow* window, NightcapJob::Action action); + +void OnNightcapJobDone(GObject*, GAsyncResult* result, gpointer user_data) { + auto* window = static_cast(user_data); + GTask* task = G_TASK(result); + const auto* job = static_cast(g_task_get_task_data(task)); + (void)g_task_propagate_boolean(task, nullptr); + if (job->action == NightcapJob::kInstall) { + g_application_release(g_application_get_default()); + } + if (window->closed) return; + const auto& status = job->status; + window->nightcap_can_install = + status.error.empty() && status.newer && status.can_install && + status.installed_pending.empty(); + gtk_button_set_label(GTK_BUTTON(window->nightcap_button), + window->nightcap_can_install ? "Update" : "Check"); + if (window->nightcap_can_install) { + gtk_widget_add_css_class(window->nightcap_button, "suggested-action"); + } else { + gtk_widget_remove_css_class(window->nightcap_button, "suggested-action"); + } + gtk_widget_set_sensitive(window->nightcap_button, TRUE); + adw_action_row_set_subtitle(ADW_ACTION_ROW(window->nightcap->widget), + NightcapSubtitle(status).c_str()); + if (!job->install_error.empty()) { + ShowError(window, "Nightcap could not update itself: " + job->install_error); + } else if (job->action == NightcapJob::kInstall) { + AdwToast* toast = adw_toast_new("Nightcap is updated. Restart Nightcap to use it."); + adw_toast_set_use_markup(toast, FALSE); + adw_toast_overlay_add_toast(window->toasts, toast); + } +} + +void StartNightcapJob(SettingsWindow* window, NightcapJob::Action action) { + gtk_widget_set_sensitive(window->nightcap_button, FALSE); + if (action == NightcapJob::kInstall) { + g_application_hold(g_application_get_default()); + } + auto* job = new NightcapJob; + job->action = action; + job->mode = window->document.Value("updates.nightcap"); + GTask* task = g_task_new(nullptr, nullptr, OnNightcapJobDone, window); + g_task_set_task_data(task, job, [](gpointer data) { + delete static_cast(data); + }); + g_task_run_in_thread(task, RunNightcapJob); + g_object_unref(task); +} + +void OnNightcapButtonClicked(GtkButton*, gpointer user_data) { + auto* window = static_cast(user_data); + StartNightcapJob(window, window->nightcap_can_install ? NightcapJob::kInstall + : NightcapJob::kCheck); +} + void OnClearCacheResponse(AdwAlertDialog*, const char* response, gpointer user_data) { if (g_strcmp0(response, "clear") == 0) { @@ -2584,6 +2691,16 @@ void AddRow(SettingsWindow* window, GtkWidget* container, adw_action_row_add_suffix(ADW_ACTION_ROW(row.widget), choose); break; } + case SettingKind::kNightcapRelease: + row.widget = adw_action_row_new(); + window->nightcap = &row; + window->nightcap_button = gtk_button_new_with_label("Check"); + gtk_widget_set_valign(window->nightcap_button, GTK_ALIGN_CENTER); + adw_action_row_add_suffix(ADW_ACTION_ROW(row.widget), + window->nightcap_button); + g_signal_connect(window->nightcap_button, "clicked", + G_CALLBACK(OnNightcapButtonClicked), window); + break; case SettingKind::kCache: row.widget = adw_action_row_new(); window->cache = &row; @@ -2598,6 +2715,7 @@ void AddRow(SettingsWindow* window, GtkWidget* container, if (row.reset == nullptr && setting.kind != SettingKind::kEditor && setting.kind != SettingKind::kFolder && setting.kind != SettingKind::kCache && + setting.kind != SettingKind::kNightcapRelease && setting.kind != SettingKind::kSky && setting.kind != SettingKind::kFont && setting.kind != SettingKind::kCursor && @@ -2612,6 +2730,9 @@ void AddRow(SettingsWindow* window, GtkWidget* container, } SetRowText(row.widget, setting.title, setting.subtitle); if (setting.kind == SettingKind::kCache) StartCacheJob(window, false); + if (setting.kind == SettingKind::kNightcapRelease) { + StartNightcapJob(window, NightcapJob::kShow); + } AddToContainer(container, row.widget); if (row.custom != nullptr) { AddToContainer(container, row.custom); diff --git a/src/ui/settings_model.cc b/src/ui/settings_model.cc index abb2b5a07..d9b90955e 100644 --- a/src/ui/settings_model.cc +++ b/src/ui/settings_model.cc @@ -1140,6 +1140,25 @@ const std::vector& SettingsPages() { }, "apk-pure", {}}, + {"updates.nightcap", + "Nightcap updates", + "Automatic installs a new AppImage by itself; other installs " + "update from the row below. Off never checks GitHub.", + SettingKind::kChoice, + { + {"auto", "Automatic"}, + {"notify", "Tell me"}, + {"off", "Off"}, + }, + "auto", + {}}, + {"nightcap_release", + "Nightcap version", + "", + SettingKind::kNightcapRelease, + {}, + "", + {}}, {"updates.launch_after_update", "Start Nightcap after a scripted update", "Used by scripts/auto_update_roblox.sh.", @@ -1560,6 +1579,7 @@ bool SettingsDocument::IsChanged(const Setting& setting) const { case SettingKind::kEditor: case SettingKind::kFolder: case SettingKind::kCache: + case SettingKind::kNightcapRelease: case SettingKind::kSky: case SettingKind::kFont: case SettingKind::kCursor: diff --git a/src/update/http_download.cc b/src/update/http_download.cc index 16755b7c8..3595518a7 100644 --- a/src/update/http_download.cc +++ b/src/update/http_download.cc @@ -114,6 +114,7 @@ constexpr curl_off_t kMebibyte = 1024 * 1024; struct TransferProgress { int descriptor = -1; + std::string label; curl_off_t resumed_bytes = 0; std::chrono::steady_clock::time_point reported_at{}; curl_off_t reported_bytes = 0; @@ -145,7 +146,8 @@ int ReportTransferProgress(void* opaque, curl_off_t expected, curl_off_t now, const curl_off_t total = expected > 0 ? progress->resumed_bytes + expected : 0; std::string message = - "Downloading Roblox... " + std::to_string(received / kMebibyte) + " MiB"; + "Downloading " + progress->label + "... " + + std::to_string(received / kMebibyte) + " MiB"; if (total > 0) { message += " / " + std::to_string(total / kMebibyte) + " MiB (" + std::to_string(received * 100 / total) + "%)"; @@ -507,6 +509,7 @@ HttpDownloadResult DownloadFileAttempt(const HttpTransferRequest& request, } TransferProgress progress; progress.descriptor = progress_fd; + progress.label = request.progress_label; progress.resumed_bytes = static_cast(existing); std::string current = request.url; for (int redirect = 0; redirect <= request.maximum_redirects; ++redirect) { @@ -805,7 +808,8 @@ HttpDownloadResult DownloadFile(const HttpTransferRequest& request, } return result; } - PublishMessage(progress_fd, "Retrying Roblox download..."); + PublishMessage(progress_fd, + "Retrying " + request.progress_label + " download..."); Sleep(request.retry_delay_ms * attempt); } std::filesystem::rename(temporary, destination, filesystem_error); diff --git a/src/update/main.cc b/src/update/main.cc index bfcb410cc..2537ce900 100644 --- a/src/update/main.cc +++ b/src/update/main.cc @@ -17,6 +17,9 @@ #include "update/background_update_process.h" #include "update/compatibility_catalog.h" #include "update/host_abi_deriver.h" +#include "update/nightcap_self_update.h" +#include "update/update_config.h" +#include "nightcap_release_key.h" #include "update/payload_store.h" #include "update/update_coordinator.h" #include "update/zip_archive.h" @@ -193,7 +196,88 @@ void Usage(std::ostream& output) { " derive-host-abi OUTPUT REF_LIB REF_PROFILE CANDIDATE_DIR " "[REF_COMPAT...]\n" " status\n" - " rollback\n"; + " rollback\n" + " nightcap status [--force] [--offline]\n" + " nightcap install\n" + " nightcap auto\n"; +} + +// Nightcap's own updates; the Roblox commands above never touch it. +int NightcapCommand(const mocktail::update::UpdatePaths& paths, int argc, + char** argv) { + if (argc < 3) { + Usage(std::cerr); + return 2; + } + const std::string_view action = argv[2]; + const auto environment = mocktail::update::SystemNightcapUpdaterEnvironment( + paths.data_root, paths.cache_root, MOCKTAIL_PROJECT_VERSION, + kNightcapReleasePublicKey); + std::string error; + if (action == "status") { + bool force = false; + bool offline = false; + for (int index = 3; index < argc; ++index) { + const std::string_view option = argv[index]; + if (option == "--force") { + force = true; + } else if (option == "--offline") { + offline = true; + } else { + std::cerr << "[native-updater] unknown option: " << option << '\n'; + return 2; + } + } + const auto status = mocktail::update::CheckNightcapRelease( + environment, force, offline, &error); + if (!status) { + std::cerr << "[native-updater] " << error << '\n'; + return 1; + } + std::cout << status->ToJson() << '\n'; + return 0; + } + // One launch-time pass: obeys updates.nightcap and only an AppImage + // installs without asking, since packages need an administrator prompt. + if (action == "auto" && argc == 3) { + const auto config = mocktail::update::LoadUpdateConfig(paths.config_file); + if (!config || config.config.nightcap == "off") return 0; + const auto status = mocktail::update::CheckNightcapRelease( + environment, false, false, &error); + if (!status) { + std::cerr << "[native-updater] warning: Nightcap check: " << error + << '\n'; + return 0; + } + if (!status->newer) return 0; + if (config.config.nightcap != "auto" || !status->can_install || + status->method.kind != mocktail::update::InstallKind::kAppImage) { + std::cerr << "[native-updater] Nightcap " << *status->latest + << " is out\n"; + return 0; + } + std::string message; + if (!mocktail::update::InstallNightcapRelease(environment, -1, &message, + &error)) { + std::cerr << "[native-updater] warning: Nightcap update: " << error + << '\n'; + return 0; + } + std::cerr << "[native-updater] " << message << '\n'; + return 0; + } + if (action == "install" && argc == 3) { + std::string message; + if (!mocktail::update::InstallNightcapRelease( + environment, ProgressDescriptor(), &message, &error)) { + std::cerr << "[native-updater] " << error << '\n'; + return 1; + } + std::cerr << "[native-updater] " << message << '\n'; + return 0; + } + Usage(std::cerr); + return 2; } } // namespace @@ -207,6 +291,7 @@ int main(int argc, char** argv) { const std::string_view command = argv[1]; mocktail::update::PayloadStore store( paths.data_root, paths.compatibility_manifest, paths.runtime_binary); + if (command == "nightcap") return NightcapCommand(paths, argc, argv); if (command == "check-latest") { if (argc != 2) return 2; const mocktail::update::ProviderVersion latest = diff --git a/src/update/nightcap_install_method.cc b/src/update/nightcap_install_method.cc new file mode 100644 index 000000000..43834c994 --- /dev/null +++ b/src/update/nightcap_install_method.cc @@ -0,0 +1,277 @@ +#include "update/nightcap_install_method.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +extern char** environ; + +namespace mocktail::update { +namespace { + +using Path = std::filesystem::path; + +constexpr char kReleasePackage[] = "nightcap"; +constexpr char kFlatpakCommand[] = + "flatpak update io.github.CoderDayton.nightcap"; + +bool Under(const Path& path, std::string_view prefix) { + return path.string().rfind(prefix, 0) == 0; +} + +InstallMethod NotSelfUpdated(InstallKind kind, std::string reason, + std::string command = {}) { + InstallMethod method; + method.kind = kind; + method.reason = std::move(reason); + method.command = std::move(command); + return method; +} + +InstallMethod FromPackage(const InstallProbe& probe, InstallKind kind, + std::string package) { + InstallMethod method; + method.kind = kind; + method.package = std::move(package); + // The release .pkg and the AUR source package share the name "nightcap", + // so pacman installs always go through the AUR helper. + if (kind == InstallKind::kArch) { + method.reason = "Installed as " + method.package + + "; update it with your AUR helper."; + method.command = "paru -S " + method.package; + return method; + } + if (method.package != kReleasePackage) { + method.reason = "Installed as " + method.package + + "; update it with your package manager."; + return method; + } + if (kind == InstallKind::kRpm) { + if (probe.os_id != "fedora") { + method.reason = + "The release .rpm is built for Fedora; update with your package " + "manager."; + return method; + } + method.distro_version = probe.os_version_id; + } + if (!probe.has_program("pkexec")) { + method.reason = "Installing a package needs pkexec, which is not installed."; + return method; + } + method.self_update = true; + return method; +} + +// stdout of `argv`, or nullopt when it fails to run or exits nonzero. +std::optional Capture(const std::vector& argv) { + int pipe_fds[2]; + if (pipe2(pipe_fds, O_CLOEXEC) != 0) return std::nullopt; + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_adddup2(&actions, pipe_fds[1], STDOUT_FILENO); + posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null", + O_WRONLY, 0); + std::vector args; + for (const std::string& arg : argv) { + args.push_back(const_cast(arg.c_str())); + } + args.push_back(nullptr); + pid_t pid = -1; + const int spawned = + posix_spawnp(&pid, args[0], &actions, nullptr, args.data(), environ); + posix_spawn_file_actions_destroy(&actions); + close(pipe_fds[1]); + if (spawned != 0) { + close(pipe_fds[0]); + return std::nullopt; + } + std::string out; + std::array buffer{}; + for (ssize_t n; (n = read(pipe_fds[0], buffer.data(), buffer.size())) != 0;) { + if (n < 0) { + if (errno == EINTR) continue; + break; + } + if (out.size() < 4096) out.append(buffer.data(), static_cast(n)); + } + close(pipe_fds[0]); + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { + } + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return std::nullopt; + while (!out.empty() && (out.back() == '\n' || out.back() == ' ')) { + out.pop_back(); + } + return out; +} + +std::optional PackageOwner(std::string_view manager, + const Path& path) { + std::optional out; + if (manager == "pacman") out = Capture({"pacman", "-Qqo", path.string()}); + if (manager == "dpkg") { + // "nightcap: /usr/bin/mocktail"; a diversion or several owners are + // ambiguous. + out = Capture({"dpkg-query", "-S", path.string()}); + if (out) { + out = out->find('\n') == std::string::npos ? out->substr(0, out->find(':')) + : std::string(); + } + } + if (manager == "rpm") { + out = Capture({"rpm", "-qf", "--qf", "%{NAME}", path.string()}); + } + if (!out || out->empty() || out->find_first_of(" \n") != std::string::npos) { + return std::nullopt; + } + return out; +} + +bool OnPath(std::string_view program) { + const char* path = std::getenv("PATH"); + std::string_view dirs = path != nullptr && *path != '\0' + ? path + : "/usr/local/bin:/usr/bin:/bin"; + while (!dirs.empty()) { + const std::size_t colon = dirs.find(':'); + const std::string_view dir = dirs.substr(0, colon); + if (!dir.empty() && + access((std::string(dir) + "/" + std::string(program)).c_str(), + X_OK) == 0) { + return true; + } + if (colon == std::string_view::npos) break; + dirs.remove_prefix(colon + 1); + } + return false; +} + +std::string OsReleaseField(const std::string& text, std::string_view key) { + std::size_t at = 0; + while (at < text.size()) { + const std::size_t end = std::min(text.find('\n', at), text.size()); + std::string_view line(text.data() + at, end - at); + if (line.size() > key.size() && line.substr(0, key.size()) == key && + line[key.size()] == '=') { + line.remove_prefix(key.size() + 1); + if (line.size() >= 2 && (line.front() == '"' || line.front() == '\'') && + line.back() == line.front()) { + line = line.substr(1, line.size() - 2); + } + return std::string(line); + } + at = end + 1; + } + return {}; +} + +} // namespace + +std::string_view InstallKindName(InstallKind kind) { + switch (kind) { + case InstallKind::kAppImage: + return "appimage"; + case InstallKind::kArch: + return "arch"; + case InstallKind::kDeb: + return "deb"; + case InstallKind::kRpm: + return "rpm"; + case InstallKind::kFlatpak: + return "flatpak"; + case InstallKind::kNix: + return "nix"; + case InstallKind::kSource: + return "source"; + } + return "source"; +} + +InstallMethod DetectInstallMethod(const InstallProbe& probe) { + if (probe.flatpak) { + return NotSelfUpdated(InstallKind::kFlatpak, + "Flatpak installs its own updates.", kFlatpakCommand); + } + if (probe.appimage_variable && !probe.appimage_variable->empty()) { + InstallMethod method; + method.kind = InstallKind::kAppImage; + method.appimage = *probe.appimage_variable; + if (method.appimage.is_absolute() && + probe.writable_regular_file(method.appimage)) { + method.self_update = true; + } else { + method.reason = "Nightcap cannot replace " + method.appimage.string() + + "; download the new AppImage instead."; + } + return method; + } + if (Under(probe.executable, "/nix/store/")) { + return NotSelfUpdated( + InstallKind::kNix, + "Installed with Nix; update it through your Nix configuration."); + } + if (Under(probe.executable, "/usr/")) { + constexpr std::pair kManagers[] = { + {"pacman", InstallKind::kArch}, + {"dpkg", InstallKind::kDeb}, + {"rpm", InstallKind::kRpm}}; + for (const auto& [manager, kind] : kManagers) { + if (!probe.has_program(manager)) continue; + if (auto owner = probe.owner(manager, probe.executable)) { + return FromPackage(probe, kind, std::move(*owner)); + } + } + } + return NotSelfUpdated( + InstallKind::kSource, + "Built from source; update the checkout and build again."); +} + +InstallProbe SystemInstallProbe() { + InstallProbe probe; + std::error_code error; + probe.executable = std::filesystem::read_symlink("/proc/self/exe", error); + // APPIMAGE passes on to every child, so it names this copy only while the + // updater runs from the AppImage's own mount. + const char* appimage = std::getenv("APPIMAGE"); + const char* appdir = std::getenv("APPDIR"); + std::string mount = + appdir != nullptr ? Path(appdir).lexically_normal().string() : std::string(); + if (!mount.empty() && mount.back() != '/') mount += '/'; + if (appimage != nullptr && mount.size() > 1 && Under(probe.executable, mount)) { + probe.appimage_variable = appimage; + } + const char* flatpak_id = std::getenv("FLATPAK_ID"); + probe.flatpak = access("/.flatpak-info", F_OK) == 0 || + (flatpak_id != nullptr && *flatpak_id != '\0'); + std::ifstream os_release("/etc/os-release"); + if (!os_release) os_release.open("/usr/lib/os-release"); + const std::string text((std::istreambuf_iterator(os_release)), + std::istreambuf_iterator()); + probe.os_id = OsReleaseField(text, "ID"); + probe.os_version_id = OsReleaseField(text, "VERSION_ID"); + probe.owner = PackageOwner; + probe.has_program = [](std::string_view program) { + return OnPath(program == "dpkg" ? "dpkg-query" : program); + }; + probe.writable_regular_file = [](const Path& file) { + struct stat info {}; + return lstat(file.c_str(), &info) == 0 && S_ISREG(info.st_mode) && + access(file.parent_path().c_str(), W_OK) == 0 && + access(file.c_str(), W_OK) == 0; + }; + return probe; +} + +} // namespace mocktail::update diff --git a/src/update/nightcap_release.cc b/src/update/nightcap_release.cc new file mode 100644 index 000000000..cf9fef1ad --- /dev/null +++ b/src/update/nightcap_release.cc @@ -0,0 +1,219 @@ +#include "update/nightcap_release.h" + +#include +#include + +#include +#include +#include +#include + +namespace mocktail::update { +namespace { + +constexpr char kDownloadPrefix[] = + "https://github.com/CoderDayton/nightcap/releases/download/"; + +bool Fail(std::string* error, std::string message) { + if (error != nullptr) *error = std::move(message); + return false; +} + +std::optional> ParseVersion(std::string_view text) { + std::array parts{}; + for (std::size_t i = 0; i < parts.size(); ++i) { + const char* begin = text.data(); + const char* end = text.data() + text.size(); + const auto [next, failure] = std::from_chars(begin, end, parts[i]); + if (failure != std::errc() || next == begin || next - begin > 6) { + return std::nullopt; + } + text.remove_prefix(static_cast(next - begin)); + if (i + 1 < parts.size()) { + if (text.empty() || text.front() != '.') return std::nullopt; + text.remove_prefix(1); + } + } + if (!text.empty()) return std::nullopt; + return parts; +} + +// nlohmann's value() throws when the key holds another type. +bool TrueFlag(const nlohmann::json& object, const char* key) { + const auto it = object.find(key); + return it != object.end() && !it->is_null() && + !(it->is_boolean() && !it->get()); +} + +std::string TextOf(const nlohmann::json& object, const char* key) { + const auto it = object.find(key); + return it != object.end() && it->is_string() ? it->get() + : std::string(); +} + +bool PlainName(std::string_view name) { + if (name.empty() || name.size() > 128 || name.front() == '.') return false; + for (const char c : name) { + const bool ok = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || + c == '-' || c == '+'; + if (!ok) return false; + } + return true; +} + +std::optional LowerHex64(std::string_view text) { + if (text.size() != 64) return std::nullopt; + std::string lower(text); + for (char& c : lower) { + if (c >= 'A' && c <= 'F') c = static_cast(c - 'A' + 'a'); + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) { + return std::nullopt; + } + } + return lower; +} + +} // namespace + +const ReleaseAsset* NightcapRelease::Find(std::string_view name) const { + for (const ReleaseAsset& asset : assets) { + if (asset.name == name) return &asset; + } + return nullptr; +} + +std::optional ParseLatestRelease(std::string_view body, + std::string* error) { + const nlohmann::json json = + nlohmann::json::parse(body.begin(), body.end(), nullptr, false); + if (!json.is_object()) { + Fail(error, "GitHub returned no usable release"); + return std::nullopt; + } + if (TrueFlag(json, "draft") || TrueFlag(json, "prerelease")) { + Fail(error, "the latest release is not final"); + return std::nullopt; + } + const std::string tag = TextOf(json, "tag_name"); + if (tag.size() < 2 || tag.front() != 'v' || + !ParseVersion(std::string_view(tag).substr(1))) { + Fail(error, "the latest release tag " + tag + " is not vX.Y.Z"); + return std::nullopt; + } + NightcapRelease release; + release.version = tag.substr(1); + release.page = TextOf(json, "html_url"); + const auto assets = json.find("assets"); + if (assets == json.end() || !assets->is_array()) { + Fail(error, "the latest release lists no files"); + return std::nullopt; + } + const std::string prefix = std::string(kDownloadPrefix) + tag + "/"; + for (const nlohmann::json& item : *assets) { + if (!item.is_object()) { + Fail(error, "the latest release lists a malformed file"); + return std::nullopt; + } + ReleaseAsset asset; + asset.name = TextOf(item, "name"); + asset.url = TextOf(item, "browser_download_url"); + const auto size = item.find("size"); + if (!PlainName(asset.name) || asset.url != prefix + asset.name || + size == item.end() || !size->is_number_unsigned()) { + Fail(error, "the latest release lists an unexpected file " + asset.name); + return std::nullopt; + } + asset.size = size->get(); + release.assets.push_back(std::move(asset)); + } + return release; +} + +std::optional CompareVersions(std::string_view a, std::string_view b) { + const auto left = ParseVersion(a); + const auto right = ParseVersion(b); + if (!left || !right) return std::nullopt; + return *left < *right ? -1 : (*left > *right ? 1 : 0); +} + +std::optional AssetNameFor(const InstallMethod& method, + std::string_view version) { + const std::string v(version); + switch (method.kind) { + case InstallKind::kAppImage: + return "Nightcap-x86_64.AppImage"; + case InstallKind::kDeb: + return "nightcap_" + v + "_amd64.deb"; + case InstallKind::kRpm: + if (method.distro_version.empty() || !PlainName(method.distro_version)) { + return std::nullopt; + } + return "nightcap-" + v + "-1.fc" + method.distro_version + ".x86_64.rpm"; + case InstallKind::kArch: + case InstallKind::kFlatpak: + case InstallKind::kNix: + case InstallKind::kSource: + return std::nullopt; + } + return std::nullopt; +} + +std::optional> ParseSums( + std::string_view text, std::string* error) { + std::map sums; + while (!text.empty()) { + const std::size_t end = text.find('\n'); + const std::string_view line = text.substr(0, end); + text.remove_prefix(end == std::string_view::npos ? text.size() : end + 1); + if (line.empty()) continue; + const auto hash = line.size() >= 67 ? LowerHex64(line.substr(0, 64)) + : std::nullopt; + if (!hash || line[64] != ' ' || (line[65] != ' ' && line[65] != '*')) { + Fail(error, "SHA256SUMS has a malformed line"); + return std::nullopt; + } + const std::string name(line.substr(66)); + if (!PlainName(name)) { + Fail(error, "SHA256SUMS names an unexpected file " + name); + return std::nullopt; + } + if (!sums.emplace(name, *hash).second) { + Fail(error, "SHA256SUMS lists " + name + " twice"); + return std::nullopt; + } + } + return sums; +} + +bool VerifyEd25519(std::string_view message, std::string_view signature, + std::string_view public_key_pem, std::string* error) { + if (signature.size() != 64) { + return Fail(error, "the release signature is not 64 bytes"); + } + std::unique_ptr bio( + BIO_new_mem_buf(public_key_pem.data(), + static_cast(public_key_pem.size())), + BIO_free); + std::unique_ptr key( + bio ? PEM_read_bio_PUBKEY(bio.get(), nullptr, nullptr, nullptr) + : nullptr, + EVP_PKEY_free); + if (!key || EVP_PKEY_get_id(key.get()) != EVP_PKEY_ED25519) { + return Fail(error, "the release key is not an Ed25519 key"); + } + std::unique_ptr context( + EVP_MD_CTX_new(), EVP_MD_CTX_free); + if (!context || EVP_DigestVerifyInit(context.get(), nullptr, nullptr, + nullptr, key.get()) != 1) { + return Fail(error, "cannot check the release signature"); + } + const int verified = EVP_DigestVerify( + context.get(), reinterpret_cast(signature.data()), + signature.size(), reinterpret_cast(message.data()), + message.size()); + if (verified != 1) return Fail(error, "the release signature does not match"); + return true; +} + +} // namespace mocktail::update diff --git a/src/update/nightcap_self_update.cc b/src/update/nightcap_self_update.cc new file mode 100644 index 000000000..33fd6010f --- /dev/null +++ b/src/update/nightcap_self_update.cc @@ -0,0 +1,507 @@ +#include "update/nightcap_self_update.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "update/file_lock.h" +#include "update/nightcap_release.h" +#include "update/state_file.h" + +extern char** environ; + +namespace mocktail::update { +namespace { + +using Path = std::filesystem::path; + +constexpr std::size_t kMaxAssetBytes = std::size_t{1} << 30; +constexpr std::size_t kMaxSumsBytes = 64 * 1024; +const std::vector kDownloadHosts = { + "github.com", "release-assets.githubusercontent.com", + "objects.githubusercontent.com"}; + +bool Fail(std::string* error, std::string message) { + if (error != nullptr) *error = std::move(message); + return false; +} + +void Say(int descriptor, const std::string& message) { + if (descriptor < 0) return; + const std::string packet = "P" + message; + (void)send(descriptor, packet.data(), packet.size(), MSG_NOSIGNAL); +} + +Path StoreRoot(const NightcapUpdaterEnvironment& env) { + return env.data_root / "self-update"; +} + +HttpTransferRequest SmallRequest(std::string url, std::size_t limit) { + HttpTransferRequest request; + request.url = std::move(url); + request.allowed_hosts = kDownloadHosts; + request.maximum_bytes = limit; + request.connect_timeout_ms = 5000; + request.transfer_timeout_ms = 20000; + request.maximum_attempts = 2; + return request; +} + +std::string StringField(const nlohmann::json& object, const char* key) { + const auto it = object.find(key); + return it != object.end() && it->is_string() ? it->get() + : std::string(); +} + +std::optional Sha256File(const Path& file) { + const int descriptor = open(file.c_str(), O_RDONLY | O_CLOEXEC); + if (descriptor < 0) return std::nullopt; + std::unique_ptr context( + EVP_MD_CTX_new(), EVP_MD_CTX_free); + bool ok = context && EVP_DigestInit_ex(context.get(), EVP_sha256(), nullptr); + std::vector buffer(1 << 16); + while (ok) { + const ssize_t got = read(descriptor, buffer.data(), buffer.size()); + if (got == 0) break; + if (got < 0) { + ok = errno == EINTR; + continue; + } + ok = EVP_DigestUpdate(context.get(), buffer.data(), + static_cast(got)) == 1; + } + close(descriptor); + unsigned char digest[EVP_MAX_MD_SIZE]; + unsigned int length = 0; + if (!ok || EVP_DigestFinal_ex(context.get(), digest, &length) != 1) { + return std::nullopt; + } + std::string hex; + constexpr char kDigits[] = "0123456789abcdef"; + for (unsigned int i = 0; i < length; ++i) { + hex.push_back(kDigits[digest[i] >> 4]); + hex.push_back(kDigits[digest[i] & 15]); + } + return hex; +} + +bool CopyFile(const Path& from, const Path& to, std::string* error) { + const int in = open(from.c_str(), O_RDONLY | O_CLOEXEC); + if (in < 0) return Fail(error, "cannot read " + from.string() + ": " + std::strerror(errno)); + const int out = open(to.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); + if (out < 0) { + const int saved = errno; + close(in); + return Fail(error, "cannot create " + to.string() + ": " + std::strerror(saved)); + } + std::string failure; + std::vector buffer(1 << 16); + for (;;) { + const ssize_t got = read(in, buffer.data(), buffer.size()); + if (got == 0) break; + if (got < 0) { + if (errno == EINTR) continue; + failure = "cannot read " + from.string() + ": " + std::strerror(errno); + break; + } + for (ssize_t done = 0; done < got && failure.empty();) { + const ssize_t wrote = write(out, buffer.data() + done, + static_cast(got - done)); + if (wrote < 0 && errno == EINTR) continue; + if (wrote <= 0) { + failure = "cannot write " + to.string() + ": " + std::strerror(errno); + } else { + done += wrote; + } + } + if (!failure.empty()) break; + } + if (failure.empty() && fsync(out) != 0) { + failure = "cannot sync " + to.string() + ": " + std::strerror(errno); + } + close(in); + if (close(out) != 0 && failure.empty()) { + failure = "cannot write " + to.string() + ": " + std::strerror(errno); + } + if (!failure.empty()) { + (void)unlink(to.c_str()); + return Fail(error, failure); + } + return true; +} + +void SyncDirectory(const Path& directory) { + const int descriptor = + open(directory.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (descriptor < 0) return; + (void)fsync(descriptor); + close(descriptor); +} + +std::string PkexecFailure(int status) { + if (status == 126) return "the administrator prompt was dismissed"; + if (status == 127) { + return "the administrator password was not accepted, or no " + "authentication agent is running"; + } + if (status < 0) return "the package manager could not be started"; + return "the package manager exited with status " + std::to_string(status); +} + +std::optional FetchLatest( + const NightcapUpdaterEnvironment& env, std::string* error) { + HttpTransferRequest request = SmallRequest(kNightcapLatestReleaseUrl, 512 * 1024); + request.allowed_hosts = {"api.github.com"}; + request.headers = {"Accept: application/vnd.github+json"}; + const HttpBytesResult reply = env.fetch(request); + if (!reply) { + Fail(error, "cannot reach GitHub: " + reply.error); + return std::nullopt; + } + auto release = ParseLatestRelease(reply.bytes, error); + if (!release) return std::nullopt; + nlohmann::json assets = nlohmann::json::array(); + for (const ReleaseAsset& asset : release->assets) assets.push_back(asset.name); + std::error_code ignored; + std::filesystem::create_directories(StoreRoot(env), ignored); + (void)WriteStateFile(StoreRoot(env) / "latest.json", + {{"checked_at", env.now()}, + {"version", release->version}, + {"page", release->page}, + {"assets", assets}}); + return release; +} + +// A release this process is too old to be, installed by an earlier run of +// this same install; another copy's update does not replace this one. +std::string PendingVersion(const NightcapUpdaterEnvironment& env) { + const nlohmann::json installed = + ReadStateFile(StoreRoot(env) / "installed.json"); + if (!installed.is_object() || + StringField(installed, "kind") != InstallKindName(env.method.kind) || + StringField(installed, "appimage") != env.method.appimage.string()) { + return {}; + } + const std::string version = StringField(installed, "version"); + return CompareVersions(version, env.running_version).value_or(0) > 0 + ? version + : std::string(); +} + +struct Verified { + std::string asset; + std::string sha256; + const ReleaseAsset* file = nullptr; +}; + +std::optional VerifyRelease(const NightcapUpdaterEnvironment& env, + const NightcapRelease& release, + std::string* error) { + const auto name = AssetNameFor(env.method, release.version); + const ReleaseAsset* asset = name ? release.Find(*name) : nullptr; + if (asset == nullptr) { + Fail(error, "Nightcap " + release.version + " has no download for this install"); + return std::nullopt; + } + const ReleaseAsset* sums = release.Find(kSumsAsset); + const ReleaseAsset* signature = release.Find(kSumsSignatureAsset); + if (sums == nullptr || signature == nullptr) { + Fail(error, "Nightcap " + release.version + " is not signed"); + return std::nullopt; + } + const HttpBytesResult sums_text = env.fetch(SmallRequest(sums->url, kMaxSumsBytes)); + if (!sums_text) { + Fail(error, "cannot download SHA256SUMS: " + sums_text.error); + return std::nullopt; + } + const HttpBytesResult signature_bytes = + env.fetch(SmallRequest(signature->url, 1024)); + if (!signature_bytes) { + Fail(error, "cannot download SHA256SUMS.sig: " + signature_bytes.error); + return std::nullopt; + } + if (!VerifyEd25519(sums_text.bytes, signature_bytes.bytes, env.public_key_pem, + error)) { + return std::nullopt; + } + const auto table = ParseSums(sums_text.bytes, error); + if (!table) return std::nullopt; + const auto entry = table->find(*name); + if (entry == table->end()) { + Fail(error, "the signed SHA256SUMS does not list " + *name); + return std::nullopt; + } + return Verified{*name, entry->second, asset}; +} + +// The new file goes next to the AppImage and is renamed over it, so the +// AppImage is whole at every moment and the running copy keeps its open file. +bool InstallAppImage(const NightcapUpdaterEnvironment& env, const Path& file, + const std::string& sha256, std::string* error) { + const Path target = env.method.appimage; + const Path previous = target.string() + ".previous"; + const std::string incoming_prefix = "." + target.filename().string() + ".new-"; + const Path incoming = + target.parent_path() / (incoming_prefix + std::to_string(getpid())); + // A run stopped mid-copy leaves its own copy behind. + std::error_code listing; + for (const auto& entry : + std::filesystem::directory_iterator(target.parent_path(), listing)) { + if (entry.path().filename().string().rfind(incoming_prefix, 0) == 0) { + (void)unlink(entry.path().c_str()); + } + } + if (!CopyFile(file, incoming, error)) return false; + if (chmod(incoming.c_str(), 0755) != 0) { + const int saved = errno; + (void)unlink(incoming.c_str()); + return Fail(error, "cannot make " + incoming.string() + + " executable: " + std::strerror(saved)); + } + if (Sha256File(incoming) != sha256) { + (void)unlink(incoming.c_str()); + return Fail(error, incoming.string() + " does not match the signed SHA256SUMS"); + } + (void)unlink(previous.c_str()); + if (link(target.c_str(), previous.c_str()) != 0) { + std::fprintf(stderr, "[native-updater] warning: cannot keep %s: %s\n", + previous.c_str(), std::strerror(errno)); + } + if (rename(incoming.c_str(), target.c_str()) != 0) { + const int saved = errno; + (void)unlink(incoming.c_str()); + return Fail(error, "cannot replace " + target.string() + ": " + + std::strerror(saved)); + } + SyncDirectory(target.parent_path()); + return true; +} + +bool InstallPackage(const NightcapUpdaterEnvironment& env, const Path& file, + std::string* error) { + std::vector argv = {"pkexec"}; + switch (env.method.kind) { + case InstallKind::kDeb: + argv.insert(argv.end(), {"apt-get", "install", "-y"}); + break; + case InstallKind::kRpm: + argv.insert(argv.end(), {"dnf", "install", "-y"}); + break; + default: + return Fail(error, "Nightcap cannot install this kind of update"); + } + argv.push_back(file.string()); + const int status = env.run ? env.run(argv) : -1; + if (status != 0) return Fail(error, PkexecFailure(status)); + return true; +} + +int RunProgram(const std::vector& argv) { + std::vector args; + for (const std::string& arg : argv) args.push_back(const_cast(arg.c_str())); + args.push_back(nullptr); + pid_t pid = -1; + if (posix_spawnp(&pid, args[0], nullptr, nullptr, args.data(), environ) != 0) { + return -1; + } + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { + } + return WIFEXITED(status) ? WEXITSTATUS(status) : -1; +} + +} // namespace + +std::string NightcapStatus::ToJson() const { + return nlohmann::json{ + {"installed", installed}, + {"latest", latest ? nlohmann::json(*latest) : nlohmann::json(nullptr)}, + {"installed_pending", installed_pending}, + {"page", page}, + {"kind", std::string(InstallKindName(method.kind))}, + {"package", method.package}, + {"checked_at", checked_at}, + {"newer", newer}, + {"can_install", can_install}, + {"command", method.command}, + {"note", note}} + .dump(); +} + +std::optional CheckNightcapRelease( + const NightcapUpdaterEnvironment& env, bool force, bool offline, + std::string* error) { + NightcapStatus status; + status.installed = env.running_version; + status.installed_pending = PendingVersion(env); + status.method = env.method; + std::vector assets; + const nlohmann::json last = ReadStateFile(StoreRoot(env) / "latest.json"); + const auto checked_at = last.is_object() ? last.find("checked_at") : last.end(); + const std::int64_t checked = + last.is_object() && checked_at != last.end() && + checked_at->is_number_integer() + ? checked_at->get() + : 0; + const auto age = std::chrono::seconds(env.now() - checked); + const bool stale = !last.is_object() || age < std::chrono::seconds(0) || + age >= kNightcapCheckInterval; + std::optional release; + if (!offline && (force || stale)) { + std::string fetch_error; + release = FetchLatest(env, &fetch_error); + if (!release && (force || !last.is_object())) { + Fail(error, fetch_error); + return std::nullopt; + } + } + if (release) { + status.latest = release->version; + status.page = release->page; + status.checked_at = env.now(); + for (const ReleaseAsset& asset : release->assets) assets.push_back(asset.name); + } else if (last.is_object()) { + if (const std::string version = StringField(last, "version"); !version.empty()) { + status.latest = version; + } + status.page = StringField(last, "page"); + status.checked_at = checked; + if (const auto names = last.find("assets"); + names != last.end() && names->is_array()) { + for (const nlohmann::json& name : *names) { + if (name.is_string()) assets.push_back(name.get()); + } + } + } + const std::string effective = status.installed_pending.empty() + ? env.running_version + : status.installed_pending; + status.newer = status.latest && + CompareVersions(*status.latest, effective).value_or(0) > 0; + if (!env.method.self_update) { + status.note = env.method.reason; + } else if (env.public_key_pem.empty()) { + status.note = "This build has no release key, so it cannot check a download."; + } else if (status.newer) { + const auto listed = [&assets](const std::string& name) { + return std::find(assets.begin(), assets.end(), name) != assets.end(); + }; + const auto asset = AssetNameFor(env.method, *status.latest); + status.can_install = asset && listed(*asset) && listed(kSumsAsset) && + listed(kSumsSignatureAsset); + if (!status.can_install) { + status.note = "Nightcap " + *status.latest + " has no download for this install."; + } + } + return status; +} + +bool InstallNightcapRelease(const NightcapUpdaterEnvironment& env, + int progress_fd, std::string* message, + std::string* error) { + if (!env.method.self_update) return Fail(error, env.method.reason); + if (env.public_key_pem.empty()) { + return Fail(error, "this build has no release key, so it cannot check a download"); + } + // The launch-time pass and the Settings button can both get here. + std::error_code ignored; + std::filesystem::create_directories(StoreRoot(env), ignored); + struct Lock { + int descriptor; + ~Lock() { + if (descriptor >= 0) close(descriptor); + } + } lock{open((StoreRoot(env) / ".install.lock").c_str(), + O_WRONLY | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600)}; + std::string lock_error = "cannot open the Nightcap update lock"; + if (lock.descriptor < 0 || + !LockExclusiveWithin(lock.descriptor, std::chrono::minutes(10), + "Nightcap update lock", &lock_error)) { + return Fail(error, lock_error); + } + Say(progress_fd, "Checking for a new Nightcap..."); + const auto release = FetchLatest(env, error); + if (!release) return false; + const std::string pending = PendingVersion(env); + const std::string effective = pending.empty() ? env.running_version : pending; + if (CompareVersions(release->version, effective).value_or(0) <= 0) { + if (message != nullptr) { + *message = pending.empty() + ? "Nightcap " + effective + " is the newest release" + : "Nightcap " + pending + " is installed; restart Nightcap to use it"; + } + return true; + } + const auto verified = VerifyRelease(env, *release, error); + if (!verified) return false; + + HttpTransferRequest request; + request.url = verified->file->url; + request.allowed_hosts = kDownloadHosts; + request.maximum_bytes = kMaxAssetBytes; + request.transfer_timeout_ms = 0; + request.progress_label = "Nightcap " + release->version; + const Path directory = env.cache_root / "nightcap" / release->version; + std::filesystem::create_directories(directory, ignored); + const Path file = directory / verified->asset; + const HttpDownloadResult download = env.download(request, file, progress_fd); + const auto discard = [&] { std::filesystem::remove_all(env.cache_root / "nightcap", ignored); }; + if (!download) { + discard(); + return Fail(error, "cannot download " + verified->asset + ": " + download.error); + } + if (download.sha256 != verified->sha256 || + download.bytes_written != verified->file->size) { + discard(); + return Fail(error, verified->asset + " does not match the signed SHA256SUMS"); + } + + Say(progress_fd, "Installing Nightcap " + release->version + "..."); + const bool installed = env.method.kind == InstallKind::kAppImage + ? InstallAppImage(env, file, verified->sha256, error) + : InstallPackage(env, file, error); + discard(); + if (!installed) return false; + (void)WriteStateFile(StoreRoot(env) / "installed.json", + {{"version", release->version}, + {"kind", std::string(InstallKindName(env.method.kind))}, + {"appimage", env.method.appimage.string()}, + {"installed_at", env.now()}}); + if (message != nullptr) { + *message = "Installed Nightcap " + release->version + + "; it starts the next time Nightcap opens"; + } + return true; +} + +NightcapUpdaterEnvironment SystemNightcapUpdaterEnvironment( + std::filesystem::path data_root, std::filesystem::path cache_root, + std::string running_version, std::string public_key_pem) { + NightcapUpdaterEnvironment env; + env.data_root = std::move(data_root); + env.cache_root = std::move(cache_root); + env.running_version = std::move(running_version); + env.public_key_pem = std::move(public_key_pem); + env.method = DetectInstallMethod(SystemInstallProbe()); + env.fetch = DownloadBytes; + env.download = [](const HttpTransferRequest& request, const Path& destination, + int progress_fd) { + return DownloadFile(request, destination, progress_fd); + }; + env.run = RunProgram; + env.now = [] { return static_cast(std::time(nullptr)); }; + return env; +} + +} // namespace mocktail::update diff --git a/src/update/update_config.cc b/src/update/update_config.cc index 6d057d6fa..94f3ff858 100644 --- a/src/update/update_config.cc +++ b/src/update/update_config.cc @@ -165,6 +165,14 @@ UpdateConfigResult LoadUpdateConfig(const std::filesystem::path& path) { result.error = "updates.launch_after_update must be true or false"; break; } + } else if (key == "nightcap") { + result.config.nightcap = Scalar(value); + if (result.config.nightcap != "auto" && + result.config.nightcap != "notify" && + result.config.nightcap != "off") { + result.error = "updates.nightcap must be auto, notify or off"; + break; + } } else if (key == "source") { result.config.source = Scalar(value); // `apk-pure` predates the fallback chain and still selects it, so an diff --git a/src/update/update_coordinator.cc b/src/update/update_coordinator.cc index 9ab640bbd..3e46441eb 100644 --- a/src/update/update_coordinator.cc +++ b/src/update/update_coordinator.cc @@ -1001,6 +1001,26 @@ UpdateResult RunUpdate(const UpdatePaths& paths, const UpdateRequest& request, std::filesystem::remove_all(workspace, filesystem_error); }; + // Read at launch: a newer Roblox that this Nightcap build failed to run + // means Nightcap itself needs updating. + const auto note_rejected = [&](const Candidate& candidate) { + const compat::BuildIdResult runtime = + compat::ReadElfBuildId(paths.runtime_binary.string()); + if (!runtime) return; + // An older fallback rejected later in the same pass must not hide it. + const auto previous = state.find("latest_rejected"); + if (previous != state.end() && previous->is_object() && + previous->value("runtime_build_id", nlohmann::json()) == + runtime.build_id && + StoredVersion(*previous).version_code > candidate.staged.version_code) { + return; + } + state["latest_rejected"] = { + {"payload_id", candidate.staged.payload_id}, + {"version_name", candidate.staged.version_name}, + {"version_code", candidate.staged.version_code}, + {"runtime_build_id", runtime.build_id}}; + }; std::string blocked; std::size_t attempt = 0; // Includes a rejected payload: it stays staged so the next launch @@ -1053,6 +1073,7 @@ UpdateResult RunUpdate(const UpdatePaths& paths, const UpdateRequest& request, return finish(); } if (rejected) { + note_rejected(candidate); blocked = description + " already failed probation with this runtime"; continue; } @@ -1101,6 +1122,10 @@ UpdateResult RunUpdate(const UpdatePaths& paths, const UpdateRequest& request, candidate_rejected = !candidate_error.empty() && !retryable; } if (candidate_error.empty() && promoted) { + if (StoredVersion(state["latest_rejected"]).version_code <= + promoted.version_code) { + state.erase("latest_rejected"); + } result.changed = !current || current.payload_id != promoted.payload_id; result.payload_id = promoted.payload_id; result.message = @@ -1120,6 +1145,7 @@ UpdateResult RunUpdate(const UpdatePaths& paths, const UpdateRequest& request, if (candidate_rejected) { RecordRejection(paths, candidate, request.canary_graphics_backend, candidate_error); + note_rejected(candidate); } blocked = description + " was rejected: " + candidate_error; } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2a56b5968..66249e11b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -140,6 +140,19 @@ target_include_directories(android_log_observer_test PRIVATE ) mocktail_apply_compile_options(android_log_observer_test) +foreach(nightcap_test + nightcap_release_test + nightcap_install_method_test + nightcap_self_update_test) + add_executable(${nightcap_test} ${nightcap_test}.cc) + target_link_libraries(${nightcap_test} PRIVATE + Mocktail::Update + GTest::gtest_main + ) + mocktail_apply_compile_options(${nightcap_test}) + gtest_discover_tests(${nightcap_test}) +endforeach() + add_executable(native_update_helper_fixture native_update_helper_fixture.cc) add_executable(native_progress_helper_fixture native_progress_helper_fixture.cc) mocktail_apply_compile_options(native_update_helper_fixture) diff --git a/tests/native_packaging_test.sh b/tests/native_packaging_test.sh index 4b9e0203b..be7266b39 100755 --- a/tests/native_packaging_test.sh +++ b/tests/native_packaging_test.sh @@ -221,6 +221,9 @@ for expected in \ 'needs: [build, flatpak]' \ 'Nightcap-x86_64.flatpak' \ 'gh release upload' \ + 'release/SHA256SUMS' \ + 'release/SHA256SUMS.sig' \ + 'openssl pkeyutl -sign' \ 'uses: ./.github/workflows/aur-publish.yml'; do grep -Fq -- "${expected}" "${RELEASE_WORKFLOW}" || Fail "release workflow is missing: ${expected}" diff --git a/tests/native_update_helper_fixture.cc b/tests/native_update_helper_fixture.cc index e08738a71..fa431b94b 100644 --- a/tests/native_update_helper_fixture.cc +++ b/tests/native_update_helper_fixture.cc @@ -32,6 +32,22 @@ int IntegerEnvironment(const char* name, int fallback) { } // namespace int main(int argc, char** argv) { + const char* order_capture = Environment("MOCKTAIL_TEST_UPDATE_ORDER_CAPTURE"); + if (order_capture[0] != '\0' && argc > 1) { + std::ofstream(order_capture, std::ios::app) << argv[1] << '\n'; + } + if (argc == 3 && std::string_view(argv[1]) == "nightcap") { + const char* nightcap_capture = Environment("MOCKTAIL_TEST_NIGHTCAP_CAPTURE"); + if (nightcap_capture[0] != '\0') { + std::ofstream(nightcap_capture, std::ios::app) << argv[2] << '\n'; + } + if (std::string_view(argv[2]) == "status") { + std::puts(Environment("MOCKTAIL_TEST_NIGHTCAP_STATUS")); + } + const char* diagnostics = Environment("MOCKTAIL_TEST_UPDATE_STDERR"); + if (diagnostics[0] != '\0') std::fprintf(stderr, "%s\n", diagnostics); + return IntegerEnvironment("MOCKTAIL_TEST_UPDATE_EXIT", 0); + } if (argc != 3 || std::string_view(argv[1]) != "update" || (std::string_view(argv[2]) != "--startup-preflight" && std::string_view(argv[2]) != "--force-run-latest" && diff --git a/tests/native_update_test.cc b/tests/native_update_test.cc index 935b977c6..b2430eefc 100644 --- a/tests/native_update_test.cc +++ b/tests/native_update_test.cc @@ -154,12 +154,14 @@ TEST(NativeUpdateConfigTest, ReadsOnlyTypedUpdaterSection) { "updates:\n" " automatic: false\n" " source: apk-pure\n" - " launch_after_update: true\n"); + " launch_after_update: true\n" + " nightcap: notify\n"); const UpdateConfigResult result = LoadUpdateConfig(config); ASSERT_TRUE(result) << result.error; EXPECT_TRUE(result.file_loaded); EXPECT_FALSE(result.config.automatic); EXPECT_TRUE(result.config.launch_after_update); + EXPECT_EQ(result.config.nightcap, "notify"); EXPECT_EQ(result.config.source, "apk-pure"); EXPECT_TRUE(result.warnings.empty()); } @@ -184,6 +186,16 @@ TEST(NativeUpdateConfigTest, MissingFileUsesSafeDefaults) { EXPECT_FALSE(result.file_loaded); EXPECT_TRUE(result.config.automatic); EXPECT_EQ(result.config.source, "apk-pure"); + EXPECT_EQ(result.config.nightcap, "auto"); +} + +TEST(NativeUpdateConfigTest, RejectsUnknownNightcapMode) { + TemporaryDirectory temporary; + const auto config = temporary.root() / "config.yaml"; + Write(config, "version: 1\nupdates:\n nightcap: always\n"); + const UpdateConfigResult result = LoadUpdateConfig(config); + EXPECT_FALSE(result); + EXPECT_NE(result.error.find("updates.nightcap"), std::string::npos); } TEST(NativeUpdateConfigTest, RejectsUnsupportedSource) { @@ -933,6 +945,30 @@ TEST_F(UpdateCoordinatorDownloadTest, EXPECT_EQ(ReadFile(paths.data_root / "current.json"), original); } EXPECT_FALSE(std::filesystem::is_empty(paths.data_root / "rejections")); + const auto state = ReadStateFile(paths.data_root / "update.json"); + ASSERT_TRUE(state.contains("latest_rejected")); + EXPECT_EQ(state["latest_rejected"]["version_code"], 200); + EXPECT_EQ(state["latest_rejected"]["runtime_build_id"], + compat::ReadElfBuildId(paths.runtime_binary.string()).build_id); +} + +TEST_F(UpdateCoordinatorDownloadTest, InstallingTheRejectedBuildClearsIt) { + paths.runtime_binary = std::filesystem::read_symlink("/proc/self/exe"); + paths.runtime_launcher = temporary.root() / "canary.sh"; + Write(paths.runtime_launcher, "#!/bin/sh\nexit 1\n"); + ASSERT_EQ(chmod(paths.runtime_launcher.c_str(), 0700), 0); + UpdateRequest request; + request.startup_preflight = true; + ASSERT_TRUE(RunUpdate(paths, request, &provider)); + ASSERT_TRUE(ReadStateFile(paths.data_root / "update.json") + .contains("latest_rejected")); + std::filesystem::remove_all(paths.data_root / "rejections"); + request.run_canary = false; + const auto result = RunUpdate(paths, request, &provider); + ASSERT_TRUE(result) << result.error; + EXPECT_TRUE(result.changed); + EXPECT_FALSE(ReadStateFile(paths.data_root / "update.json") + .contains("latest_rejected")); } TEST_F(UpdateCoordinatorDownloadTest, diff --git a/tests/nightcap_install_method_test.cc b/tests/nightcap_install_method_test.cc new file mode 100644 index 000000000..e9c204437 --- /dev/null +++ b/tests/nightcap_install_method_test.cc @@ -0,0 +1,172 @@ +#include + +#include + +#include +#include +#include +#include + +#include "update/nightcap_install_method.h" + +namespace mocktail::update { +namespace { + +struct Machine { + std::filesystem::path executable = "/usr/lib/mocktail/mocktail_updater"; + std::optional appimage; + bool flatpak = false; + std::string os_id = "arch"; + std::string os_version_id; + std::map owners; + std::set programs = {"pkexec"}; + std::set writable; + + InstallMethod Detect() const { + InstallProbe probe; + probe.executable = executable; + probe.appimage_variable = appimage; + probe.flatpak = flatpak; + probe.os_id = os_id; + probe.os_version_id = os_version_id; + probe.owner = [this](std::string_view manager, + const std::filesystem::path&) + -> std::optional { + const auto it = owners.find(std::string(manager)); + if (it == owners.end()) return std::nullopt; + return it->second; + }; + probe.has_program = [this](std::string_view program) { + return programs.count(std::string(program)) != 0 || + owners.count(std::string(program)) != 0; + }; + probe.writable_regular_file = [this](const std::filesystem::path& file) { + return writable.count(file.string()) != 0; + }; + return DetectInstallMethod(probe); + } +}; + +TEST(NightcapInstallMethod, FlatpakIsUpdatedByFlatpak) { + Machine machine; + machine.flatpak = true; + machine.executable = "/app/lib/mocktail/mocktail_updater"; + const InstallMethod method = machine.Detect(); + EXPECT_EQ(method.kind, InstallKind::kFlatpak); + EXPECT_FALSE(method.self_update); + EXPECT_EQ(method.command, "flatpak update io.github.CoderDayton.nightcap"); +} + +TEST(NightcapInstallMethod, WritableAppImageUpdatesItself) { + Machine machine; + machine.executable = "/tmp/.mount_NightcXYZ/usr/lib/mocktail/mocktail_updater"; + machine.appimage = "/home/u/Apps/Nightcap-x86_64.AppImage"; + machine.writable = {"/home/u/Apps/Nightcap-x86_64.AppImage"}; + const InstallMethod method = machine.Detect(); + EXPECT_EQ(method.kind, InstallKind::kAppImage); + EXPECT_TRUE(method.self_update); + EXPECT_EQ(method.appimage, + std::filesystem::path("/home/u/Apps/Nightcap-x86_64.AppImage")); +} + +TEST(NightcapInstallMethod, ReadOnlyAppImageSaysWhy) { + Machine machine; + machine.executable = "/tmp/.mount_NightcXYZ/usr/lib/mocktail/mocktail_updater"; + machine.appimage = "/opt/Nightcap-x86_64.AppImage"; + const InstallMethod method = machine.Detect(); + EXPECT_EQ(method.kind, InstallKind::kAppImage); + EXPECT_FALSE(method.self_update); + EXPECT_NE(method.reason.find("/opt/Nightcap-x86_64.AppImage"), + std::string::npos); +} + +// The release .pkg and the AUR source package are both "nightcap", so a +// pacman install never replaces itself; the AUR helper does it. +TEST(NightcapInstallMethod, ArchStaysWithTheAurHelper) { + for (const char* name : {"nightcap", "nightcap-bin", "nightcap-git"}) { + Machine machine; + machine.owners = {{"pacman", name}}; + const InstallMethod method = machine.Detect(); + EXPECT_EQ(method.kind, InstallKind::kArch) << name; + EXPECT_FALSE(method.self_update) << name; + EXPECT_EQ(method.command, std::string("paru -S ") + name) << name; + } +} + +TEST(NightcapInstallMethod, DebAndFedoraRpmInstallThroughPkexec) { + Machine deb; + deb.os_id = "ubuntu"; + deb.owners = {{"dpkg", "nightcap"}}; + EXPECT_EQ(deb.Detect().kind, InstallKind::kDeb); + EXPECT_TRUE(deb.Detect().self_update); + + Machine rpm; + rpm.os_id = "fedora"; + rpm.os_version_id = "44"; + rpm.owners = {{"rpm", "nightcap"}}; + const InstallMethod method = rpm.Detect(); + EXPECT_EQ(method.kind, InstallKind::kRpm); + EXPECT_TRUE(method.self_update); + EXPECT_EQ(method.distro_version, "44"); +} + +TEST(NightcapInstallMethod, OtherPackagesAndRpmOutsideFedoraAreNotReplaced) { + Machine suse; + suse.os_id = "opensuse-tumbleweed"; + suse.owners = {{"rpm", "nightcap"}}; + EXPECT_EQ(suse.Detect().kind, InstallKind::kRpm); + EXPECT_FALSE(suse.Detect().self_update); + + Machine distro; + distro.os_id = "debian"; + distro.owners = {{"dpkg", "mocktail"}}; + EXPECT_FALSE(distro.Detect().self_update); + EXPECT_NE(distro.Detect().reason.find("mocktail"), std::string::npos); +} + +TEST(NightcapInstallMethod, PackagesNeedPkexec) { + Machine machine; + machine.os_id = "ubuntu"; + machine.programs.clear(); + machine.owners = {{"dpkg", "nightcap"}}; + const InstallMethod method = machine.Detect(); + EXPECT_EQ(method.kind, InstallKind::kDeb); + EXPECT_FALSE(method.self_update); + EXPECT_NE(method.reason.find("pkexec"), std::string::npos); +} + +TEST(NightcapInstallMethod, NixAndSourceBuildsAreNotUpdated) { + Machine nix; + nix.executable = "/nix/store/abc-nightcap-0.6.0/lib/mocktail/mocktail_updater"; + EXPECT_EQ(nix.Detect().kind, InstallKind::kNix); + EXPECT_FALSE(nix.Detect().self_update); + + Machine local; + local.executable = "/home/u/.local/lib/mocktail/mocktail_updater"; + local.owners = {{"pacman", "nightcap"}}; + EXPECT_EQ(local.Detect().kind, InstallKind::kSource); + EXPECT_FALSE(local.Detect().self_update); + + Machine unowned; + EXPECT_EQ(unowned.Detect().kind, InstallKind::kSource); +} + +TEST(NightcapInstallMethod, AppImageVariableCountsOnlyFromItsOwnMount) { + std::error_code error; + const std::filesystem::path self = + std::filesystem::read_symlink("/proc/self/exe", error); + ASSERT_FALSE(error); + ::setenv("APPIMAGE", "/home/u/Other.AppImage", 1); + ::setenv("APPDIR", "/tmp/.mount_Other", 1); + EXPECT_FALSE(SystemInstallProbe().appimage_variable); + ::unsetenv("APPDIR"); + EXPECT_FALSE(SystemInstallProbe().appimage_variable); + ::setenv("APPDIR", (self.parent_path().string() + "/").c_str(), 1); + EXPECT_EQ(SystemInstallProbe().appimage_variable, + std::optional("/home/u/Other.AppImage")); + ::unsetenv("APPIMAGE"); + ::unsetenv("APPDIR"); +} + +} // namespace +} // namespace mocktail::update diff --git a/tests/nightcap_release_test.cc b/tests/nightcap_release_test.cc new file mode 100644 index 000000000..aba681687 --- /dev/null +++ b/tests/nightcap_release_test.cc @@ -0,0 +1,157 @@ +#include + +#include +#include + +#include +#include + +#include "update/nightcap_release.h" + +namespace mocktail::update { +namespace { + +struct KeyPair { + std::string public_pem; + std::unique_ptr key{nullptr, + EVP_PKEY_free}; + + KeyPair() { + key.reset(EVP_PKEY_Q_keygen(nullptr, nullptr, "ED25519")); + BIO* bio = BIO_new(BIO_s_mem()); + PEM_write_bio_PUBKEY(bio, key.get()); + char* data = nullptr; + const long size = BIO_get_mem_data(bio, &data); + public_pem.assign(data, static_cast(size)); + BIO_free(bio); + } + + std::string Sign(const std::string& message) const { + std::string signature(64, '\0'); + std::size_t length = signature.size(); + EVP_MD_CTX* context = EVP_MD_CTX_new(); + EVP_DigestSignInit(context, nullptr, nullptr, nullptr, key.get()); + EVP_DigestSign(context, reinterpret_cast(signature.data()), + &length, + reinterpret_cast(message.data()), + message.size()); + EVP_MD_CTX_free(context); + return signature; + } +}; + +TEST(NightcapRelease, SignatureFromTheReleaseKeyVerifies) { + const KeyPair pair; + const std::string sums = + std::string(64, 'a') + " Nightcap-x86_64.AppImage\n"; + std::string error; + EXPECT_TRUE(VerifyEd25519(sums, pair.Sign(sums), pair.public_pem, &error)) + << error; +} + +// Made by `openssl pkeyutl -sign -rawin`, the command the release signs with. +TEST(NightcapRelease, OpensslCommandSignatureVerifies) { + const std::string public_pem = + "-----BEGIN PUBLIC KEY-----\n" + "MCowBQYDK2VwAyEAJQUlTw34vZAtCkwe48D6RZSfofKp3gSMBaMTWb7lJGw=\n" + "-----END PUBLIC KEY-----\n"; + const std::string hex = + "2228d5274d8fa3a3adf08e6a64749740b50a6b008f9575a03f824e6dd6e795fa" + "be48dfe8546dfa178f39ac0859122912a6d445618d9cff732bfc7c507dce990c"; + std::string signature; + for (std::size_t i = 0; i < hex.size(); i += 2) { + signature.push_back( + static_cast(std::stoi(hex.substr(i, 2), nullptr, 16))); + } + EXPECT_TRUE(VerifyEd25519("abc Nightcap-Mac-x86_64.AppImage\n", signature, + public_pem)); + EXPECT_FALSE(VerifyEd25519("abd Nightcap-Mac-x86_64.AppImage\n", signature, + public_pem)); +} + +TEST(NightcapRelease, TamperedSumsOrOtherKeysFail) { + const KeyPair pair; + const KeyPair other; + const std::string sums = + std::string(64, 'a') + " Nightcap-x86_64.AppImage\n"; + const std::string signature = pair.Sign(sums); + std::string tampered = sums; + tampered[0] = 'b'; + EXPECT_FALSE(VerifyEd25519(tampered, signature, pair.public_pem)); + EXPECT_FALSE(VerifyEd25519(sums, signature, other.public_pem)); + EXPECT_FALSE(VerifyEd25519(sums, signature.substr(0, 63), pair.public_pem)); + EXPECT_FALSE(VerifyEd25519(sums, signature, "")); +} + +TEST(NightcapRelease, SumsParseOnlyWellFormedLines) { + const std::string a(64, 'a'); + const std::string b(64, 'B'); + std::string error; + const auto sums = + ParseSums(a + " one.AppImage\n" + b + " *two.deb\n", &error); + ASSERT_TRUE(sums) << error; + EXPECT_EQ(sums->at("one.AppImage"), a); + EXPECT_EQ(sums->at("two.deb"), std::string(64, 'b')); + EXPECT_FALSE(ParseSums("abc one.AppImage\n")); + EXPECT_FALSE(ParseSums(a + " ../escape\n")); + EXPECT_FALSE(ParseSums(a + " one\n" + a + " one\n")); +} + +TEST(NightcapRelease, LatestReleaseKeepsItsAssets) { + const std::string body = R"({"tag_name":"v0.6.0","draft":false,"prerelease":false, + "html_url":"https://github.com/CoderDayton/nightcap/releases/tag/v0.6.0", + "assets":[{"name":"SHA256SUMS","size":300, + "browser_download_url":"https://github.com/CoderDayton/nightcap/releases/download/v0.6.0/SHA256SUMS"}]})"; + std::string error; + const auto release = ParseLatestRelease(body, &error); + ASSERT_TRUE(release) << error; + EXPECT_EQ(release->version, "0.6.0"); + ASSERT_NE(release->Find("SHA256SUMS"), nullptr); + EXPECT_EQ(release->Find("SHA256SUMS")->size, 300U); + EXPECT_EQ(release->Find("missing"), nullptr); +} + +TEST(NightcapRelease, LatestReleaseRefusesDraftsOddTagsAndForeignUrls) { + EXPECT_FALSE(ParseLatestRelease( + R"({"tag_name":"v0.6.0","draft":true,"assets":[]})")); + EXPECT_FALSE(ParseLatestRelease( + R"({"tag_name":"v0.6.0","prerelease":true,"assets":[]})")); + EXPECT_FALSE(ParseLatestRelease(R"({"tag_name":"nightly","assets":[]})")); + EXPECT_FALSE(ParseLatestRelease( + R"({"tag_name":"v0.6.0","assets":[{"name":"../x","size":1, + "browser_download_url":"https://github.com/x"}]})")); + EXPECT_FALSE(ParseLatestRelease( + R"({"tag_name":"v0.6.0","assets":[{"name":"SHA256SUMS","size":1, + "browser_download_url":"https://example.com/v0.6.0/SHA256SUMS"}]})")); + EXPECT_FALSE(ParseLatestRelease("not json")); +} + +TEST(NightcapRelease, VersionsCompareNumerically) { + EXPECT_EQ(CompareVersions("0.10.0", "0.9.9"), 1); + EXPECT_EQ(CompareVersions("1.0.0", "1.0.0"), 0); + EXPECT_EQ(CompareVersions("0.1.0", "0.1.1"), -1); + EXPECT_FALSE(CompareVersions("0.1", "0.1.0").has_value()); + EXPECT_FALSE(CompareVersions("unknown", "0.1.0").has_value()); +} + +TEST(NightcapRelease, EachInstallPicksItsAsset) { + InstallMethod method; + method.kind = InstallKind::kAppImage; + EXPECT_EQ(AssetNameFor(method, "0.6.0"), "Nightcap-x86_64.AppImage"); + method.kind = InstallKind::kDeb; + EXPECT_EQ(AssetNameFor(method, "0.6.0"), "nightcap_0.6.0_amd64.deb"); + method.kind = InstallKind::kRpm; + method.distro_version = "45"; + EXPECT_EQ(AssetNameFor(method, "0.6.0"), + "nightcap-0.6.0-1.fc45.x86_64.rpm"); + method.distro_version = ""; + EXPECT_FALSE(AssetNameFor(method, "0.6.0")); + for (const InstallKind kind : {InstallKind::kArch, InstallKind::kFlatpak, + InstallKind::kNix, InstallKind::kSource}) { + method.kind = kind; + EXPECT_FALSE(AssetNameFor(method, "0.6.0")); + } +} + +} // namespace +} // namespace mocktail::update diff --git a/tests/nightcap_self_update_test.cc b/tests/nightcap_self_update_test.cc new file mode 100644 index 000000000..7a5481b2a --- /dev/null +++ b/tests/nightcap_self_update_test.cc @@ -0,0 +1,339 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "update/nightcap_self_update.h" + +namespace mocktail::update { +namespace { + +namespace fs = std::filesystem; + +constexpr char kDownload[] = + "https://github.com/CoderDayton/nightcap/releases/download/"; + +std::string Sha256Hex(const std::string& bytes) { + unsigned char digest[SHA256_DIGEST_LENGTH]; + SHA256(reinterpret_cast(bytes.data()), bytes.size(), + digest); + std::string hex; + constexpr char kDigits[] = "0123456789abcdef"; + for (const unsigned char byte : digest) { + hex.push_back(kDigits[byte >> 4]); + hex.push_back(kDigits[byte & 15]); + } + return hex; +} + +std::string ReadAll(const fs::path& path) { + std::ifstream input(path, std::ios::binary); + std::ostringstream out; + out << input.rdbuf(); + return out.str(); +} + +void WriteAll(const fs::path& path, const std::string& bytes) { + std::ofstream(path, std::ios::binary) << bytes; +} + +struct ReleaseKey { + std::string public_pem; + std::unique_ptr key{nullptr, + EVP_PKEY_free}; + ReleaseKey() { + key.reset(EVP_PKEY_Q_keygen(nullptr, nullptr, "ED25519")); + BIO* bio = BIO_new(BIO_s_mem()); + PEM_write_bio_PUBKEY(bio, key.get()); + char* data = nullptr; + const long size = BIO_get_mem_data(bio, &data); + public_pem.assign(data, static_cast(size)); + BIO_free(bio); + } + std::string Sign(const std::string& message) const { + std::string signature(64, '\0'); + std::size_t length = signature.size(); + EVP_MD_CTX* context = EVP_MD_CTX_new(); + EVP_DigestSignInit(context, nullptr, nullptr, nullptr, key.get()); + EVP_DigestSign(context, reinterpret_cast(signature.data()), + &length, + reinterpret_cast(message.data()), + message.size()); + EVP_MD_CTX_free(context); + return signature; + } +}; + +// GitHub as the updater sees it: one release, its files, and a call count. +struct FakeGithub { + std::string version = "0.6.0"; + std::map files; + int api_calls = 0; + std::vector downloads; + + std::string LatestJson() const { + std::string assets; + for (const auto& [name, bytes] : files) { + if (!assets.empty()) assets += ","; + assets += R"({"name":")" + name + R"(","size":)" + + std::to_string(bytes.size()) + + R"(,"browser_download_url":")" + kDownload + "v" + version + + "/" + name + R"("})"; + } + return R"({"tag_name":"v)" + version + + R"(","html_url":"https://github.com/CoderDayton/nightcap/releases/tag/v)" + + version + R"(","assets":[)" + assets + "]}"; + } + + void Publish(const ReleaseKey& key, const std::string& asset, + const std::string& bytes) { + files[asset] = bytes; + const std::string sums = Sha256Hex(bytes) + " " + asset + "\n"; + files["SHA256SUMS"] = sums; + files["SHA256SUMS.sig"] = key.Sign(sums); + } +}; + +class NightcapSelfUpdateTest : public ::testing::Test { + protected: + void SetUp() override { + root_ = fs::temp_directory_path() / + ("nightcap-self-update-" + std::to_string(::getpid()) + "-" + + ::testing::UnitTest::GetInstance()->current_test_info()->name()); + fs::remove_all(root_); + fs::create_directories(root_ / "apps"); + appimage_ = root_ / "apps/Nightcap-x86_64.AppImage"; + WriteAll(appimage_, "old nightcap"); + ::chmod(appimage_.c_str(), 0755); + + env_.data_root = root_ / "data"; + env_.cache_root = root_ / "cache"; + env_.running_version = "0.5.6"; + env_.public_key_pem = key_.public_pem; + env_.method.kind = InstallKind::kAppImage; + env_.method.appimage = appimage_; + env_.method.self_update = true; + env_.now = [this] { return now_; }; + env_.fetch = [this](const HttpTransferRequest& request) { + HttpBytesResult result; + if (request.url.find("api.github.com") != std::string::npos) { + ++github_.api_calls; + result.bytes = github_.LatestJson(); + return result; + } + const std::string name = request.url.substr(request.url.rfind('/') + 1); + const auto it = github_.files.find(name); + if (it == github_.files.end()) { + result.error = "404 " + name; + } else { + result.bytes = it->second; + } + return result; + }; + env_.download = [this](const HttpTransferRequest& request, + const fs::path& destination, int) { + HttpDownloadResult result; + const std::string name = request.url.substr(request.url.rfind('/') + 1); + github_.downloads.push_back(name); + const std::string bytes = github_.files.at(name); + fs::create_directories(destination.parent_path()); + WriteAll(destination, bytes); + result.bytes_written = bytes.size(); + result.sha256 = Sha256Hex(bytes); + return result; + }; + env_.run = [this](const std::vector& argv) { + ran_.push_back(argv); + return 0; + }; + } + + void TearDown() override { fs::remove_all(root_); } + + fs::path root_; + fs::path appimage_; + ReleaseKey key_; + FakeGithub github_; + std::int64_t now_ = 1'000'000; + std::vector> ran_; + NightcapUpdaterEnvironment env_; +}; + +TEST_F(NightcapSelfUpdateTest, CheckAsksGithubAtMostEverySixHours) { + github_.Publish(key_, "Nightcap-x86_64.AppImage", "new nightcap"); + std::string error; + auto status = CheckNightcapRelease(env_, false, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_EQ(status->latest, "0.6.0"); + EXPECT_TRUE(status->newer); + EXPECT_TRUE(status->can_install); + EXPECT_EQ(github_.api_calls, 1); + + now_ += 5 * 3600; + status = CheckNightcapRelease(env_, false, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_EQ(status->latest, "0.6.0"); + EXPECT_EQ(github_.api_calls, 1); + + now_ += 3600; + ASSERT_TRUE(CheckNightcapRelease(env_, false, false, &error)) << error; + EXPECT_EQ(github_.api_calls, 2); + ASSERT_TRUE(CheckNightcapRelease(env_, true, false, &error)) << error; + EXPECT_EQ(github_.api_calls, 3); +} + +TEST_F(NightcapSelfUpdateTest, OfflineCheckNeverAsksGithub) { + std::string error; + auto status = CheckNightcapRelease(env_, true, true, &error); + ASSERT_TRUE(status) << error; + EXPECT_FALSE(status->latest); + EXPECT_FALSE(status->newer); + EXPECT_EQ(github_.api_calls, 0); +} + +TEST_F(NightcapSelfUpdateTest, CheckExplainsWhatCannotInstall) { + github_.Publish(key_, "nightcap_0.6.0_amd64.deb", "deb"); + std::string error; + auto status = CheckNightcapRelease(env_, true, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_TRUE(status->newer); + EXPECT_FALSE(status->can_install); + EXPECT_NE(status->note.find("no download"), std::string::npos); + + env_.method = {}; + env_.method.kind = InstallKind::kArch; + env_.method.command = "paru -S nightcap"; + env_.method.reason = "update it with your AUR helper"; + status = CheckNightcapRelease(env_, false, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_FALSE(status->can_install); + EXPECT_EQ(status->note, "update it with your AUR helper"); + EXPECT_NE(status->ToJson().find(R"("command":"paru -S nightcap")"), + std::string::npos); + + env_.method.kind = InstallKind::kAppImage; + env_.method.self_update = true; + env_.public_key_pem.clear(); + status = CheckNightcapRelease(env_, false, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_FALSE(status->can_install); + EXPECT_NE(status->note.find("release key"), std::string::npos); +} + +TEST_F(NightcapSelfUpdateTest, AppImageIsReplacedAndTheOldOneKept) { + github_.Publish(key_, "Nightcap-x86_64.AppImage", "new nightcap"); + std::string message; + std::string error; + ASSERT_TRUE(InstallNightcapRelease(env_, -1, &message, &error)) << error; + EXPECT_EQ(ReadAll(appimage_), "new nightcap"); + EXPECT_EQ(ReadAll(appimage_.string() + ".previous"), "old nightcap"); + struct stat info {}; + ASSERT_EQ(::stat(appimage_.c_str(), &info), 0); + EXPECT_EQ(info.st_mode & 0777, 0755U); + EXPECT_NE(message.find("0.6.0"), std::string::npos); + + // The next check knows it is installed and waiting for a restart. + auto status = CheckNightcapRelease(env_, false, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_EQ(status->installed_pending, "0.6.0"); + EXPECT_FALSE(status->can_install); +} + +TEST_F(NightcapSelfUpdateTest, BadSignatureOrHashLeavesTheAppImageAlone) { + github_.Publish(key_, "Nightcap-x86_64.AppImage", "new nightcap"); + const ReleaseKey stranger; + github_.files["SHA256SUMS.sig"] = stranger.Sign(github_.files["SHA256SUMS"]); + std::string message; + std::string error; + EXPECT_FALSE(InstallNightcapRelease(env_, -1, &message, &error)); + EXPECT_NE(error.find("signature"), std::string::npos) << error; + EXPECT_TRUE(github_.downloads.empty()); + EXPECT_EQ(ReadAll(appimage_), "old nightcap"); + + github_.Publish(key_, "Nightcap-x86_64.AppImage", "new nightcap"); + github_.files["Nightcap-x86_64.AppImage"] = "evil nightcap"; + error.clear(); + EXPECT_FALSE(InstallNightcapRelease(env_, -1, &message, &error)); + EXPECT_NE(error.find("SHA256SUMS"), std::string::npos) << error; + EXPECT_EQ(ReadAll(appimage_), "old nightcap"); +} + +TEST_F(NightcapSelfUpdateTest, UnsignedReleaseIsRefused) { + github_.Publish(key_, "Nightcap-x86_64.AppImage", "new nightcap"); + github_.files.erase("SHA256SUMS.sig"); + std::string message; + std::string error; + EXPECT_FALSE(InstallNightcapRelease(env_, -1, &message, &error)); + EXPECT_NE(error.find("not signed"), std::string::npos) << error; + EXPECT_EQ(ReadAll(appimage_), "old nightcap"); + + // The check does not offer an update it would refuse. + auto status = CheckNightcapRelease(env_, true, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_TRUE(status->newer); + EXPECT_FALSE(status->can_install); +} + +TEST_F(NightcapSelfUpdateTest, AnotherCopysUpdateDoesNotStandInForThisOne) { + github_.Publish(key_, "Nightcap-x86_64.AppImage", "new nightcap"); + std::string message; + std::string error; + ASSERT_TRUE(InstallNightcapRelease(env_, -1, &message, &error)) << error; + + const fs::path other = root_ / "apps/Other.AppImage"; + WriteAll(other, "old nightcap"); + env_.method.appimage = other; + auto status = CheckNightcapRelease(env_, false, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_TRUE(status->installed_pending.empty()); + EXPECT_TRUE(status->can_install); + ASSERT_TRUE(InstallNightcapRelease(env_, -1, &message, &error)) << error; + EXPECT_EQ(ReadAll(other), "new nightcap"); +} + +TEST_F(NightcapSelfUpdateTest, NothingNewerInstallsNothing) { + github_.version = "0.5.6"; + github_.Publish(key_, "Nightcap-x86_64.AppImage", "same nightcap"); + std::string message; + std::string error; + ASSERT_TRUE(InstallNightcapRelease(env_, -1, &message, &error)) << error; + EXPECT_NE(message.find("newest"), std::string::npos) << message; + EXPECT_TRUE(github_.downloads.empty()); + EXPECT_EQ(ReadAll(appimage_), "old nightcap"); +} + +TEST_F(NightcapSelfUpdateTest, PackagesInstallThroughPkexec) { + env_.method = {}; + env_.method.kind = InstallKind::kDeb; + env_.method.package = "nightcap"; + env_.method.self_update = true; + github_.Publish(key_, "nightcap_0.6.0_amd64.deb", "deb bytes"); + std::string message; + std::string error; + ASSERT_TRUE(InstallNightcapRelease(env_, -1, &message, &error)) << error; + ASSERT_EQ(ran_.size(), 1U); + ASSERT_EQ(ran_[0].size(), 5U); + EXPECT_EQ(ran_[0][0], "pkexec"); + EXPECT_EQ(ran_[0][1], "apt-get"); + EXPECT_EQ(fs::path(ran_[0][4]).filename(), "nightcap_0.6.0_amd64.deb"); + + env_.run = [](const std::vector&) { return 126; }; + fs::remove_all(env_.data_root / "self-update"); + error.clear(); + EXPECT_FALSE(InstallNightcapRelease(env_, -1, &message, &error)); + EXPECT_NE(error.find("dismissed"), std::string::npos) << error; +} + +} // namespace +} // namespace mocktail::update diff --git a/tests/payload_update_preflight_test.cc b/tests/payload_update_preflight_test.cc index dd3e8ab35..3ae9cf08f 100644 --- a/tests/payload_update_preflight_test.cc +++ b/tests/payload_update_preflight_test.cc @@ -144,6 +144,30 @@ TEST(BackgroundPayloadUpdateTest, DownloadsWithoutActivatingAndStopsItsChild) { EXPECT_LT(std::chrono::steady_clock::now() - before, std::chrono::seconds(1)); } +TEST(BackgroundPayloadUpdateTest, ChecksNightcapOnceBeforeRoblox) { + TemporaryDirectory temporary; + const auto nightcap = temporary.root() / "nightcap"; + const auto roblox = temporary.root() / "argument"; + ScopedVariable nightcap_capture("MOCKTAIL_TEST_NIGHTCAP_CAPTURE", + nightcap.string()); + ScopedVariable roblox_capture("MOCKTAIL_TEST_UPDATE_ARGUMENT_CAPTURE", + roblox.string()); + const auto environment = NativeEnvironment(); + BackgroundPayloadUpdate update; + update.Start(environment, RuntimePaths::FromEnvironment(environment), + std::chrono::milliseconds(10)); + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(3); + while (ReadLines(roblox).empty() && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + update.Stop(); + EXPECT_EQ(ReadLines(roblox), std::vector{"--download-only"}); + EXPECT_EQ(ReadLines(nightcap), std::vector{"auto"}); +} + TEST(BackgroundPayloadUpdateTest, StopsAChildThatInheritedAnIgnoredSigterm) { TemporaryDirectory temporary; const auto capture = temporary.root() / "argument"; @@ -225,6 +249,100 @@ void WriteActivePayload(const std::filesystem::path& data_home, << R"({"schema_version":1,"version_name":")" << version_name << R"("})"; } +struct NeedFixture { + TemporaryDirectory temporary; + std::filesystem::path root = temporary.root() / "mocktail"; + MapEnvironment environment = + NativeEnvironment({{"XDG_DATA_HOME", temporary.root().string()}}); + int asked = 0; + std::string answer = "Required"; + + NeedFixture() { + std::filesystem::create_directories(root); + std::ofstream(root / "current.json") + << R"({"schema_version":1,"version_name":"2.748.1527","version_code":1527})"; + } + + void Reject(int code, const std::string& build_id) { + std::ofstream(root / "update.json") + << nlohmann::json{{"latest_rejected", + {{"version_name", "2.750." + std::to_string(code)}, + {"version_code", code}, + {"runtime_build_id", build_id}}}} + .dump(); + } + + NightcapUpdateNeed Assess() { + return AssessNightcapUpdateNeed( + RuntimePaths::FromEnvironment(environment), "abc123", + [this](const std::string& version, const std::atomic*) { + ++asked; + EXPECT_EQ(version, "2.748.1527"); + return answer; + }); + } +}; + +TEST(NightcapUpdateNeedTest, NothingRejectedNeverAsksRoblox) { + NeedFixture fixture; + EXPECT_FALSE(fixture.Assess().required); + EXPECT_EQ(fixture.asked, 0); +} + +TEST(NightcapUpdateNeedTest, RequiredWhenRobloxRefusesTheOldOneAndTheNewFailed) { + NeedFixture fixture; + fixture.Reject(1600, "abc123"); + const NightcapUpdateNeed need = fixture.Assess(); + EXPECT_TRUE(need.required); + EXPECT_EQ(need.installed_roblox, "2.748.1527"); + EXPECT_EQ(need.newest_roblox, "2.750.1600"); +} + +TEST(NightcapUpdateNeedTest, NotRequiredWhileTheOldOneStillJoins) { + NeedFixture fixture; + fixture.Reject(1600, "abc123"); + for (const char* answer : {"Recommended", "None", ""}) { + fixture.answer = answer; + EXPECT_FALSE(fixture.Assess().required) << answer; + } +} + +TEST(NightcapUpdateNeedTest, ARejectionByAnotherBuildOrOfAnOlderRobloxDoesNotCount) { + NeedFixture fixture; + fixture.Reject(1600, "another-build"); + EXPECT_FALSE(fixture.Assess().required); + fixture.Reject(1527, "abc123"); + EXPECT_FALSE(fixture.Assess().required); + EXPECT_EQ(fixture.asked, 0); +} + +TEST(NightcapUpdaterStatusTest, ReadsTheUpdatersAnswer) { + TemporaryDirectory temporary; + ScopedVariable status( + "MOCKTAIL_TEST_NIGHTCAP_STATUS", + R"({"can_install":true,"command":"","kind":"appimage","latest":"0.6.0","newer":true,"note":""})"); + const auto environment = NativeEnvironment(); + const NightcapUpdaterStatus read = ReadNightcapUpdaterStatus( + environment, RuntimePaths::FromEnvironment(environment), + NightcapCheck::kCached); + ASSERT_TRUE(read.error.empty()) << read.error; + EXPECT_TRUE(read.can_install); + EXPECT_TRUE(read.newer); + EXPECT_EQ(read.kind, "appimage"); + EXPECT_EQ(read.latest, "0.6.0"); +} + +TEST(NightcapUpdaterStatusTest, InstallReportsTheUpdatersReason) { + ScopedVariable failure("MOCKTAIL_TEST_UPDATE_STDERR", + "[native-updater] the release signature does not match"); + ScopedVariable exit_code("MOCKTAIL_TEST_UPDATE_EXIT", "1"); + const auto environment = NativeEnvironment(); + const PayloadUpdatePreflightResult result = RunNightcapInstall( + environment, RuntimePaths::FromEnvironment(environment)); + EXPECT_FALSE(result); + EXPECT_EQ(result.details, "the release signature does not match"); +} + TEST(RobloxUpgradeActionTest, ReadsTheActionFromTheVersionEndpoint) { EXPECT_EQ(ReadRobloxUpgradeAction(nlohmann::json::parse( R"({"activeVersion":"x","data":{"UpgradeAction":"Required"}})")), @@ -323,6 +441,31 @@ TEST(BackgroundPayloadUpdateTest, StopInterruptsASlowUpgradeQuestion) { EXPECT_FALSE(std::filesystem::exists(capture)); } +TEST(BackgroundPayloadUpdateTest, ARequiredRobloxUpdateGoesBeforeNightcaps) { + TemporaryDirectory temporary; + WriteActivePayload(temporary.root(), "2.742.1059"); + const auto order = temporary.root() / "order"; + ScopedVariable order_capture("MOCKTAIL_TEST_UPDATE_ORDER_CAPTURE", + order.string()); + const auto environment = + NativeEnvironment({{"XDG_DATA_HOME", temporary.root().string()}}); + BackgroundPayloadUpdate update; + update.Start(environment, RuntimePaths::FromEnvironment(environment), + std::chrono::minutes(30), + [](const std::string&, const std::atomic*) { + return std::string("Required"); + }); + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(3); + while (ReadLines(order).size() < 2 && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + update.Stop(); + EXPECT_EQ(ReadLines(order), (std::vector{"update", "nightcap"})); +} + TEST(BackgroundPayloadUpdateTest, CancelsTheScheduledCheckImmediately) { const auto environment = NativeEnvironment(); BackgroundPayloadUpdate update; diff --git a/tests/runtime_config_file_test.cc b/tests/runtime_config_file_test.cc index f09518fb4..f3a778fae 100644 --- a/tests/runtime_config_file_test.cc +++ b/tests/runtime_config_file_test.cc @@ -215,6 +215,11 @@ TEST(RuntimeConfigBootstrapTest, "# Reserved for desktop update integrations. `mocktail_updater` " "itself never\n # launches another process after changing the " "active payload.\n launch_after_update: false", + "# String (default: auto): Nightcap's own updates. auto checks " + "GitHub at\n # most every 6 hours and an AppImage installs a new " + "release by itself;\n # notify only checks; off never asks " + "GitHub. A Roblox build that needs\n # a newer Nightcap still " + "shows the update dialog.\n nightcap: auto", }) { EXPECT_NE(defaults.find(documented_setting), std::string::npos) << documented_setting; diff --git a/tests/settings_model_test.cc b/tests/settings_model_test.cc index 5e2cbc622..6a0e6fe0b 100644 --- a/tests/settings_model_test.cc +++ b/tests/settings_model_test.cc @@ -197,7 +197,8 @@ TEST_F(SettingsModelTest, EveryConfigKeyHasARow) { "integrations.discord_rpc.images.large_text", "integrations.discord_rpc.images.small", "integrations.discord_rpc.images.small_text", "updates.automatic", - "updates.source", "updates.launch_after_update"}) { + "updates.source", "updates.launch_after_update", + "updates.nightcap"}) { keys.emplace_back(key, key); } for (const auto& [key, row] : keys) { @@ -273,6 +274,22 @@ TEST_F(SettingsModelTest, CursorsAreGreyedOutWhileTheSystemCursorIsOn) { EXPECT_TRUE(document.IsActive("font")); } +TEST_F(SettingsModelTest, NightcapsOwnReleaseSitsUnderItsUpdateSetting) { + const Setting& release = Find("nightcap_release"); + EXPECT_EQ(release.kind, SettingKind::kNightcapRelease); + for (const SettingsPage& page : SettingsPages()) { + for (const SettingsGroup& group : page.groups) { + for (std::size_t i = 0; i + 1 < group.settings.size(); ++i) { + if (group.settings[i].key == "updates.nightcap") { + EXPECT_EQ(&group.settings[i + 1], &release); + return; + } + } + } + } + ADD_FAILURE() << "updates.nightcap has no row"; +} + TEST_F(SettingsModelTest, TheAdvancedPageClearsTheRobloxCache) { const SettingsPage& advanced = SettingsPages().back(); const Setting& cache = Find("roblox_cache"); @@ -1365,6 +1382,7 @@ std::optional ChangedSample(const Setting& setting) { case SettingKind::kEditor: case SettingKind::kFolder: case SettingKind::kCache: + case SettingKind::kNightcapRelease: case SettingKind::kSky: case SettingKind::kFont: case SettingKind::kCursor: From 6b63dd55217cf27cc5d748e56df9d747bd059b40 Mon Sep 17 00:00:00 2001 From: vii Date: Wed, 2 Dec 2026 09:26:52 -0600 Subject: [PATCH 2/4] feat(settings): add an About page and a night theme, and finish self-update - Settings gets an About page with the version, the Roblox build, Check/Update, links and the log, plus a version pill next to the name that turns into Update when a release is out. The window is always dark, in neutral greys with one muted violet accent. - Installs that update by command (Flatpak, Arch, the release deb/rpm without pkexec) show it with a copy button, in Settings and in the launch dialog. Arch names the AUR helper that is installed. - The release signature covers the tag, so old signed files can't be republished as a newer release. - The restarted AppImage gets the launch's own environment, partial copies are cleaned up, and the launch gate re-checks GitHub before saying no fix is out. --- .github/workflows/release.yml | 11 +- CHANGELOG.md | 14 +- include/runtime/failure_dialog.h | 6 +- include/runtime/payload_update_preflight.h | 3 + include/update/nightcap_release.h | 2 + include/update/nightcap_self_update.h | 4 + src/main.cc | 59 +++-- src/runtime/failure_dialog.cc | 15 +- src/runtime/payload_update_preflight.cc | 4 - src/ui/mocktail_failure_dialog.cc | 40 +++- src/ui/mocktail_settings.cc | 253 +++++++++++++++++++-- src/ui/settings_model.cc | 47 ++-- src/update/main.cc | 1 + src/update/nightcap_install_method.cc | 27 ++- src/update/nightcap_release.cc | 3 +- src/update/nightcap_self_update.cc | 65 ++++-- tests/failure_dialog_test.cc | 11 +- tests/nightcap_install_method_test.cc | 31 +++ tests/nightcap_self_update_test.cc | 71 +++++- tests/settings_model_test.cc | 39 ++-- 20 files changed, 586 insertions(+), 120 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7f8f99be4..4a35c78c9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -86,16 +86,19 @@ jobs: ) uploads+=(release/SHA256SUMS) # Nightcap installs a release only when this signature checks out - # against the key built into it. + # against the key built into it. The tag is signed with the sums so + # an old release's files cannot be republished under a newer tag. public_key=packaging/release/nightcap-release.pub if [[ -n "${RELEASE_SIGNING_KEY}" ]]; then key_file="$(mktemp -p "${RUNNER_TEMP}")" - trap 'rm -f -- "${key_file}"' EXIT + signed="$(mktemp -p "${RUNNER_TEMP}")" + trap 'rm -f -- "${key_file}" "${signed}"' EXIT printf '%s\n' "${RELEASE_SIGNING_KEY}" > "${key_file}" + { printf 'nightcap %s\n' "$tag"; cat release/SHA256SUMS; } > "${signed}" openssl pkeyutl -sign -inkey "${key_file}" -rawin \ - -in release/SHA256SUMS -out release/SHA256SUMS.sig + -in "${signed}" -out release/SHA256SUMS.sig openssl pkeyutl -verify -pubin -inkey "${public_key}" -rawin \ - -in release/SHA256SUMS -sigfile release/SHA256SUMS.sig + -in "${signed}" -sigfile release/SHA256SUMS.sig uploads+=(release/SHA256SUMS.sig) elif [[ -f "${public_key}" ]]; then echo "::error::NIGHTCAP_RELEASE_SIGNING_KEY is not set; Nightcap only installs signed releases" diff --git a/CHANGELOG.md b/CHANGELOG.md index f1a02c355..cdad56198 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,16 @@ Release notes on GitHub are taken from the matching section here. ### Added - Nightcap updates itself. It checks GitHub at most every 6 hours, and the AppImage installs a new - release in the background; the deb and Fedora rpm install it through pkexec. Settings has a Nightcap - version row with Check and Update, and `updates.nightcap` (`auto`, `notify` or `off`) picks how much - it does. Flatpak, Arch and Nix installs show their own update command instead. + release in the background; the deb and Fedora rpm install it through pkexec. Settings has a new About + page with the version, Roblox build, Check/Update and links, and a version pill beside the name that + turns into Update when a release is out. `updates.nightcap` (`auto`, `notify` or `off`) picks how much + it does. Flatpak, Arch and Nix installs show their own update command to copy instead; on Arch it + names the AUR helper you have, or the `makepkg` steps without one. +- Settings is always dark, in neutral greys with one muted violet accent. - When Roblox stops letting the installed version join and the newest one fails its test launch with - this Nightcap, Nightcap asks to update itself before starting, then restarts on the new release. - Releases are checked against a signed `SHA256SUMS` before anything is installed. + this Nightcap, Nightcap asks to update itself before starting. The AppImage then restarts on the new + release; a deb or rpm asks to be started again. Releases are checked against a signed `SHA256SUMS` + before anything is installed. ### Fixed diff --git a/include/runtime/failure_dialog.h b/include/runtime/failure_dialog.h index 8856dbe7d..d5af51dd8 100644 --- a/include/runtime/failure_dialog.h +++ b/include/runtime/failure_dialog.h @@ -15,10 +15,12 @@ bool FailureDialogsEnabled(const Environment& environment); bool ShowFailureDialog(const Environment& environment, std::string_view message); -// The heading defaults to "Signed out". +// The heading defaults to "Signed out". A `command` is shown under the +// message with a button that copies it. bool ShowWarningDialog(const Environment& environment, std::string_view message, - std::string_view heading = {}); + std::string_view heading = {}, + std::string_view command = {}); std::optional AskYesNo(const Environment& environment, std::string_view heading, std::string_view body, std::string_view decline, diff --git a/include/runtime/payload_update_preflight.h b/include/runtime/payload_update_preflight.h index 82aa11368..20efd7fe9 100644 --- a/include/runtime/payload_update_preflight.h +++ b/include/runtime/payload_update_preflight.h @@ -47,6 +47,9 @@ std::string QueryRobloxUpgradeAction(const std::string& version_name, using UpgradeActionQuery = std::function* cancel)>; +// The installed Roblox version, e.g. "2.746.123"; empty when none is. +std::string ActiveVersionName(const RuntimePaths& paths); + struct NightcapUpdateNeed { bool required = false; std::string installed_roblox; diff --git a/include/update/nightcap_release.h b/include/update/nightcap_release.h index 726514a03..af3cf369b 100644 --- a/include/update/nightcap_release.h +++ b/include/update/nightcap_release.h @@ -12,6 +12,8 @@ namespace mocktail::update { +inline constexpr char kReleaseDownloadPrefix[] = + "https://github.com/CoderDayton/nightcap/releases/download/"; inline constexpr char kSumsAsset[] = "SHA256SUMS"; inline constexpr char kSumsSignatureAsset[] = "SHA256SUMS.sig"; diff --git a/include/update/nightcap_self_update.h b/include/update/nightcap_self_update.h index 8efa27999..d93ae50a7 100644 --- a/include/update/nightcap_self_update.h +++ b/include/update/nightcap_self_update.h @@ -53,6 +53,10 @@ std::optional CheckNightcapRelease( const NightcapUpdaterEnvironment& environment, bool force, bool offline, std::string* error); +// Removes the partial AppImage copy a stopped install left beside the +// AppImage. Does nothing while another install holds the lock. +void CleanUpInterruptedInstall(const NightcapUpdaterEnvironment& environment); + // Installs the newest release when it is newer than the running one, after // checking SHA256SUMS against the release key and the download against it. // Progress goes to `progress_fd` in the Roblox updater's format. diff --git a/src/main.cc b/src/main.cc index c44329637..cc8bbcdc8 100644 --- a/src/main.cc +++ b/src/main.cc @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -490,13 +491,13 @@ void UpdateAppImageMenu(const mocktail::runtime::Environment& environment, } } -enum class NightcapGate { kPlay, kExit }; +enum class NightcapGate { kPlay, kExit, kFailed }; // Roblox stops old builds from joining. When the newest one also failed its // test launch with this Nightcap, only a Nightcap update lets the user play. NightcapGate RequireNightcapThatCanJoin( const mocktail::runtime::Environment& environment, - const mocktail::runtime::RuntimePaths& paths, char* argv[]) { + const mocktail::runtime::RuntimePaths& paths) { // The updater records rejections against this binary; under the AppImage's // sharun loader /proc/self/exe is the ELF interpreter instead. const auto runtime_binary = environment.Get("MOCKTAIL_UPDATE_RUNTIME_BINARY"); @@ -514,9 +515,15 @@ NightcapGate RequireNightcapThatCanJoin( if (!mocktail::runtime::FailureDialogsEnabled(environment)) { return NightcapGate::kPlay; } - const mocktail::runtime::NightcapUpdaterStatus status = + mocktail::runtime::NightcapUpdaterStatus status = mocktail::runtime::ReadNightcapUpdaterStatus( environment, paths, mocktail::runtime::NightcapCheck::kCached); + // The last check can be 6 hours old, older than the release that fixes this. + if (status.error.empty() && !status.newer && + status.installed_pending.empty()) { + status = mocktail::runtime::ReadNightcapUpdaterStatus( + environment, paths, mocktail::runtime::NightcapCheck::kForce); + } const std::string heading = "Update Nightcap"; std::string body = "Roblox no longer lets version " + need.installed_roblox + " join games, and Roblox " + need.newest_roblox + @@ -538,9 +545,9 @@ NightcapGate RequireNightcapThatCanJoin( } if (!status.can_install) { body += "\n\nNightcap " + status.latest + " is out. "; - body += status.command.empty() ? status.note - : "Update it with:\n" + status.command; - (void)mocktail::runtime::ShowWarningDialog(environment, body, heading); + body += status.command.empty() ? status.note : "Update it with:"; + (void)mocktail::runtime::ShowWarningDialog(environment, body, heading, + status.command); return NightcapGate::kExit; } const std::optional update = mocktail::runtime::AskYesNo( @@ -559,20 +566,25 @@ NightcapGate RequireNightcapThatCanJoin( environment, "Nightcap could not update itself.\n\n" + (installed.details.empty() ? installed.error : installed.details)); - return NightcapGate::kExit; + return NightcapGate::kFailed; } - // Same path, new file: exec runs the new release with the same arguments. + // Same path, new file. The launch as it was started, read from /proc, so + // this session's own setenv choices (Fleasion off while its proxy was + // down, say) do not carry over. const auto appimage = environment.Get("APPIMAGE"); - if (status.kind == "appimage" && appimage && !appimage->empty()) { - std::vector arguments = {const_cast(appimage->c_str())}; - for (char** argument = argv + 1; *argument != nullptr; ++argument) { - arguments.push_back(*argument); - } - arguments.push_back(nullptr); + const std::optional launch = + mocktail::runtime::ReadLaunchCommand(getpid()); + if (status.kind == "appimage" && appimage && !appimage->empty() && launch && + !launch->environment.empty()) { std::cerr << " [update] starting Nightcap " << status.latest << '\n'; - execv(appimage->c_str(), arguments.data()); - std::cerr << " [update] cannot start the new AppImage: " - << std::strerror(errno) << '\n'; + // exec drops whatever stdio still buffers. + std::cout.flush(); + std::fflush(nullptr); + std::string error; + if (!mocktail::runtime::ReplaceProcess(*appimage, *launch, &error)) { + std::cerr << " [update] cannot start the new AppImage: " << error + << '\n'; + } } (void)mocktail::runtime::ShowWarningDialog( environment, @@ -1166,11 +1178,14 @@ int main(int argc, char* argv[]) { std::cerr << '\n'; return EXIT_FAILURE; } - if (!environment.HasNonEmpty("MOCKTAIL_ISOLATED_CANARY") && - RequireNightcapThatCanJoin(environment, paths, argv) == - NightcapGate::kExit) { - failure_dialog.MarkSuccessful(); - return EXIT_SUCCESS; + if (!environment.HasNonEmpty("MOCKTAIL_ISOLATED_CANARY")) { + const NightcapGate gate = + RequireNightcapThatCanJoin(environment, paths); + if (gate != NightcapGate::kPlay) { + // The gate showed its own dialog. + failure_dialog.MarkSuccessful(); + return gate == NightcapGate::kFailed ? EXIT_FAILURE : EXIT_SUCCESS; + } } failure_dialog.SetMessage("Nightcap could not finish starting Roblox."); background_update.Start(environment, paths, std::chrono::minutes(30), diff --git a/src/runtime/failure_dialog.cc b/src/runtime/failure_dialog.cc index 5bb6d19a4..658ee9685 100644 --- a/src/runtime/failure_dialog.cc +++ b/src/runtime/failure_dialog.cc @@ -172,16 +172,21 @@ bool ShowFailureDialog(const Environment& environment, } bool ShowWarningDialog(const Environment& environment, - std::string_view message, std::string_view heading) { + std::string_view message, std::string_view heading, + std::string_view command) { if (!FailureDialogsEnabled(environment)) { return false; } const std::filesystem::path helper = DialogHelper(environment); if (helper.empty()) return false; - if (heading.empty()) return SpawnOneShot(helper, "--warning", message); - return SpawnAndWait(helper, {"--warning", std::string(message), - std::string(heading)}) - .has_value(); + if (heading.empty() && command.empty()) { + return SpawnOneShot(helper, "--warning", message); + } + std::vector arguments = { + "--warning", std::string(message), + heading.empty() ? std::string("Signed out") : std::string(heading)}; + if (!command.empty()) arguments.emplace_back(command); + return SpawnAndWait(helper, arguments).has_value(); } void PrepareSignalSafeFailureMessage(std::string_view message) { diff --git a/src/runtime/payload_update_preflight.cc b/src/runtime/payload_update_preflight.cc index 52f56abb2..94132346d 100644 --- a/src/runtime/payload_update_preflight.cc +++ b/src/runtime/payload_update_preflight.cc @@ -634,8 +634,6 @@ std::string QueryRobloxUpgradeAction(const std::string& version_name, return reply ? ReadRobloxUpgradeAction(*reply) : std::string(); } -namespace { - std::string ActiveVersionName(const RuntimePaths& paths) { std::ifstream input(paths.active_payload_manifest()); const auto manifest = nlohmann::json::parse(input, nullptr, false); @@ -646,8 +644,6 @@ std::string ActiveVersionName(const RuntimePaths& paths) { : std::string(); } -} // namespace - NightcapUpdateNeed AssessNightcapUpdateNeed(const RuntimePaths& paths, std::string_view runtime_build_id, const UpgradeActionQuery& ask_roblox) { diff --git a/src/ui/mocktail_failure_dialog.cc b/src/ui/mocktail_failure_dialog.cc index ae4c220e8..508790bea 100644 --- a/src/ui/mocktail_failure_dialog.cc +++ b/src/ui/mocktail_failure_dialog.cc @@ -238,11 +238,44 @@ void OnDialogResponse(AdwAlertDialog*, const char* response, g_object_unref(folder); } +void OnCopyCommand(GtkButton* button, gpointer command) { + gdk_clipboard_set_text(gtk_widget_get_clipboard(GTK_WIDGET(button)), + static_cast(command)); + gtk_button_set_label(button, "Copied"); +} + +// The command in a monospace box, with a button that copies it. +GtkWidget* NewCommandBox(const char* command) { + GtkWidget* label = gtk_label_new(command); + gtk_label_set_selectable(GTK_LABEL(label), TRUE); + gtk_label_set_wrap(GTK_LABEL(label), TRUE); + gtk_label_set_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); + gtk_label_set_xalign(GTK_LABEL(label), 0.0f); + gtk_widget_set_hexpand(label, TRUE); + gtk_widget_set_focusable(label, FALSE); + gtk_widget_add_css_class(label, "monospace"); + GtkWidget* copy = gtk_button_new_with_label("Copy"); + gtk_widget_set_valign(copy, GTK_ALIGN_CENTER); + g_signal_connect(copy, "clicked", G_CALLBACK(OnCopyCommand), + const_cast(command)); + GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 12); + gtk_widget_add_css_class(box, "card"); + gtk_widget_set_margin_top(box, 6); + gtk_widget_set_margin_start(label, 12); + gtk_widget_set_margin_top(label, 8); + gtk_widget_set_margin_bottom(label, 8); + gtk_widget_set_margin_end(copy, 8); + gtk_box_append(GTK_BOX(box), label); + gtk_box_append(GTK_BOX(box), copy); + return box; +} + int ShowDialog(std::string_view requested_message, const char* heading = "Nightcap", const char* response_label = "Close", std::string_view log_folder = {}, - std::string_view details = {}) { + std::string_view details = {}, + const char* command = nullptr) { if (!InitializeUi(UiStyle::kDialog)) { return EXIT_FAILURE; } @@ -271,6 +304,8 @@ int ShowDialog(std::string_view requested_message, gtk_widget_add_css_class(details_label, "monospace"); gtk_widget_add_css_class(details_label, "mocktail-failure-details"); adw_alert_dialog_set_extra_child(alert, details_label); + } else if (command != nullptr && g_utf8_validate(command, -1, nullptr)) { + adw_alert_dialog_set_extra_child(alert, NewCommandBox(command)); } if (!state.log_folder.empty() && g_utf8_validate(state.log_folder.c_str(), -1, nullptr)) { @@ -511,6 +546,9 @@ int main(int argc, char* argv[]) { if ((argc == 3 || argc == 4) && std::string_view(argv[1]) == "--warning") { return ShowDialog(argv[2], argc == 4 ? argv[3] : "Signed out", "Continue"); } + if (argc == 5 && std::string_view(argv[1]) == "--warning") { + return ShowDialog(argv[2], argv[3], "Close", {}, {}, argv[4]); + } if (argc == 6 && std::string_view(argv[1]) == "--question") { return AskQuestion(argv[2], argv[3], argv[4], argv[5]); } diff --git a/src/ui/mocktail_settings.cc b/src/ui/mocktail_settings.cc index 7ea4c0030..4854ab532 100644 --- a/src/ui/mocktail_settings.cc +++ b/src/ui/mocktail_settings.cc @@ -59,8 +59,44 @@ using mocktail::ui::SettingsPage; using mocktail::platform::kApplicationId; +// Night theme: always dark, neutral greys and one muted violet accent. Dialogs +// read the same variables, so they match. constexpr char kWindowStyle[] = R"( +:root { + --accent-bg-color: #5b4a9c; --accent-color: #a594e0; --accent-fg-color: #ffffff; + --window-bg-color: #1f1f23; --window-fg-color: #e6e6ea; + --view-bg-color: #1f1f23; --view-fg-color: #e6e6ea; + --headerbar-bg-color: #1f1f23; --headerbar-backdrop-color: #1f1f23; + --headerbar-fg-color: #e6e6ea; + --sidebar-bg-color: #242429; --sidebar-backdrop-color: #242429; + --sidebar-fg-color: #e6e6ea; + --card-bg-color: #26262b; --card-fg-color: #e6e6ea; + --popover-bg-color: #2a2a30; --popover-fg-color: #e6e6ea; + --dialog-bg-color: #26262b; --dialog-fg-color: #e6e6ea; +} .navigation-sidebar > row { min-height: 44px; margin: 1px 6px; padding: 0 14px; } +.navigation-sidebar > row:selected { + background-color: var(--accent-bg-color); color: #ffffff; +} +list.boxed-list, .card { + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.07); +} +.version-pill { + border-radius: 99px; padding: 2px 10px; min-height: 0; + background-color: rgba(255, 255, 255, 0.07); font-size: smaller; +} +.version-pill .dot { + min-width: 6px; min-height: 6px; border-radius: 99px; + background-color: rgba(230, 230, 234, 0.4); +} +.version-pill.update { background-color: var(--accent-bg-color); color: #ffffff; } +.version-pill.update .dot { background-color: #ffffff; } +.about-name { font-size: 2em; font-weight: 700; } +.about-version { color: rgba(230, 230, 234, 0.6); } +.about-roblox { + border-radius: 99px; padding: 2px 12px; font-size: smaller; + background-color: rgba(255, 255, 255, 0.07); +} .sidebar-title { font-size: 1.15em; text-shadow: 0 1px 2px alpha(black, 0.35); } .sidebar-logo { -gtk-icon-shadow: 0 1px 2px alpha(black, 0.35); } .notice-bar { @@ -168,7 +204,14 @@ struct SettingsWindow { GtkWidget* cache_button = nullptr; Row* nightcap = nullptr; GtkWidget* nightcap_button = nullptr; + GtkWidget* nightcap_command = nullptr; bool nightcap_can_install = false; + // The newest release, once a check has found one; empty before. + std::string nightcap_latest; + GtkListBox* sidebar = nullptr; + GtkWidget* version_pill = nullptr; + GtkLabel* version_pill_label = nullptr; + std::string roblox_version; std::filesystem::path asset_overlay_dir; std::filesystem::path textures_dir; std::filesystem::path sky_library; @@ -2329,24 +2372,49 @@ void RunNightcapJob(GTask* task, gpointer, gpointer task_data, GCancellable*) { } std::string NightcapSubtitle(const mocktail::runtime::NightcapUpdaterStatus& status) { - const std::string self = "Nightcap " + status.installed + "."; if (!status.error.empty()) return "Can't check for updates: " + status.error; if (!status.installed_pending.empty()) { - return self + " " + status.installed_pending + - " is installed; restart Nightcap to use it."; + return status.installed_pending + + " is installed. Restart Nightcap to use it."; } if (status.newer) { - std::string text = self + " " + status.latest + " is out."; + std::string text = status.latest + " is out."; if (status.can_install) return text; - if (!status.command.empty()) return text + " Update it with " + status.command + "."; + if (!status.command.empty()) return text + " Update it with the command below."; return status.note.empty() ? text : text + " " + status.note; } - if (!status.latest.empty()) return self + " This is the newest release."; - return self; + if (!status.latest.empty()) return "You have the newest release."; + return "Not checked yet."; } void StartNightcapJob(SettingsWindow* window, NightcapJob::Action action); +// The sidebar's foot: this version, or the release waiting for the user. +void ShowVersionPill(SettingsWindow* window, + const mocktail::runtime::NightcapUpdaterStatus& status) { + if (window->version_pill == nullptr) return; + const bool waiting = status.error.empty() && status.newer && + status.installed_pending.empty(); + // Beside the name there is room for a word or a version, no more. + std::string text = mocktail::runtime::CurrentSessionBuildInformation().version; + std::string tooltip = "About Nightcap and its updates"; + if (!status.installed_pending.empty()) { + text = "Restart"; + tooltip = "Nightcap " + status.installed_pending + + " is installed. Restart Nightcap to use it."; + } else if (waiting) { + text = "Update"; + tooltip = "Nightcap " + status.latest + " is out"; + } + gtk_label_set_text(window->version_pill_label, text.c_str()); + gtk_widget_set_tooltip_text(window->version_pill, tooltip.c_str()); + if (waiting || !status.installed_pending.empty()) { + gtk_widget_add_css_class(window->version_pill, "update"); + } else { + gtk_widget_remove_css_class(window->version_pill, "update"); + } +} + void OnNightcapJobDone(GObject*, GAsyncResult* result, gpointer user_data) { auto* window = static_cast(user_data); GTask* task = G_TASK(result); @@ -2370,6 +2438,13 @@ void OnNightcapJobDone(GObject*, GAsyncResult* result, gpointer user_data) { gtk_widget_set_sensitive(window->nightcap_button, TRUE); adw_action_row_set_subtitle(ADW_ACTION_ROW(window->nightcap->widget), NightcapSubtitle(status).c_str()); + if (status.error.empty()) window->nightcap_latest = status.latest; + ShowVersionPill(window, status); + const bool show_command = status.error.empty() && status.newer && + !status.can_install && !status.command.empty(); + adw_action_row_set_subtitle(ADW_ACTION_ROW(window->nightcap_command), + status.command.c_str()); + gtk_widget_set_visible(window->nightcap_command, show_command); if (!job->install_error.empty()) { ShowError(window, "Nightcap could not update itself: " + job->install_error); } else if (job->action == NightcapJob::kInstall) { @@ -2395,6 +2470,15 @@ void StartNightcapJob(SettingsWindow* window, NightcapJob::Action action) { g_object_unref(task); } +void OnCopyNightcapCommand(AdwActionRow* row, gpointer user_data) { + auto* window = static_cast(user_data); + gdk_clipboard_set_text(gtk_widget_get_clipboard(GTK_WIDGET(row)), + adw_action_row_get_subtitle(row)); + AdwToast* toast = adw_toast_new("Copied the update command"); + adw_toast_set_timeout(toast, 2); + adw_toast_overlay_add_toast(window->toasts, toast); +} + void OnNightcapButtonClicked(GtkButton*, gpointer user_data) { auto* window = static_cast(user_data); StartNightcapJob(window, window->nightcap_can_install ? NightcapJob::kInstall @@ -2700,6 +2784,17 @@ void AddRow(SettingsWindow* window, GtkWidget* container, window->nightcap_button); g_signal_connect(window->nightcap_button, "clicked", G_CALLBACK(OnNightcapButtonClicked), window); + row.custom = adw_action_row_new(); + SetRowText(row.custom, "Update command", {}); + adw_action_row_set_subtitle_selectable(ADW_ACTION_ROW(row.custom), TRUE); + gtk_list_box_row_set_activatable(GTK_LIST_BOX_ROW(row.custom), TRUE); + gtk_widget_set_tooltip_text(row.custom, "Click to copy"); + adw_action_row_add_suffix(ADW_ACTION_ROW(row.custom), + gtk_image_new_from_icon_name("edit-copy-symbolic")); + g_signal_connect(row.custom, "activated", + G_CALLBACK(OnCopyNightcapCommand), window); + gtk_widget_set_visible(row.custom, FALSE); + window->nightcap_command = row.custom; break; case SettingKind::kCache: row.widget = adw_action_row_new(); @@ -2799,20 +2894,27 @@ std::string DecorationLayoutWithoutIcon() { // The Nightcap artwork beside the name. The artwork is built in, so it shows // whether or not the icon theme has Nightcap's icon installed. -GtkWidget* BuildSidebarTitle() { - // The artwork has clear space around it, so the gap to the name is small. - GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4); +GtkWidget* NewLogo(int size, const char* css_class) { + GtkWidget* image = nullptr; GBytes* bytes = g_bytes_new_static( mocktail::platform::internal::kMocktailWindowIconPng, mocktail::platform::internal::kMocktailWindowIconPngSize); if (GdkTexture* texture = gdk_texture_new_from_bytes(bytes, nullptr)) { - GtkWidget* image = gtk_image_new_from_paintable(GDK_PAINTABLE(texture)); - gtk_image_set_pixel_size(GTK_IMAGE(image), 28); - gtk_widget_add_css_class(image, "sidebar-logo"); - gtk_box_append(GTK_BOX(box), image); + image = gtk_image_new_from_paintable(GDK_PAINTABLE(texture)); + gtk_image_set_pixel_size(GTK_IMAGE(image), size); + gtk_widget_add_css_class(image, css_class); g_object_unref(texture); } g_bytes_unref(bytes); + return image; +} + +GtkWidget* BuildSidebarTitle() { + // The artwork has clear space around it, so the gap to the name is small. + GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4); + if (GtkWidget* image = NewLogo(28, "sidebar-logo")) { + gtk_box_append(GTK_BOX(box), image); + } GtkWidget* label = gtk_label_new("Nightcap"); gtk_widget_add_css_class(label, "title"); gtk_widget_add_css_class(label, "sidebar-title"); @@ -2820,8 +2922,40 @@ GtkWidget* BuildSidebarTitle() { return box; } +void OnVersionPillClicked(GtkButton*, gpointer user_data) { + auto* window = static_cast(user_data); + const int last = static_cast(mocktail::ui::SettingsPages().size()) - 1; + gtk_list_box_select_row(window->sidebar, + gtk_list_box_get_row_at_index(window->sidebar, last)); + adw_navigation_split_view_set_show_content(window->split, TRUE); +} + +GtkWidget* BuildVersionPill(SettingsWindow* window) { + GtkWidget* dot = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + gtk_widget_add_css_class(dot, "dot"); + gtk_widget_set_valign(dot, GTK_ALIGN_CENTER); + GtkWidget* label = gtk_label_new( + mocktail::runtime::CurrentSessionBuildInformation().version.c_str()); + gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END); + window->version_pill_label = GTK_LABEL(label); + GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8); + gtk_box_append(GTK_BOX(box), dot); + gtk_box_append(GTK_BOX(box), label); + GtkWidget* pill = gtk_button_new(); + gtk_button_set_child(GTK_BUTTON(pill), box); + gtk_widget_add_css_class(pill, "flat"); + gtk_widget_add_css_class(pill, "version-pill"); + gtk_widget_set_tooltip_text(pill, "About Nightcap and its updates"); + SetAccessibleLabel(pill, "About Nightcap"); + g_signal_connect(pill, "clicked", G_CALLBACK(OnVersionPillClicked), window); + gtk_widget_set_focus_on_click(pill, FALSE); + window->version_pill = pill; + return pill; +} + GtkWidget* BuildSidebar(SettingsWindow* window) { GtkWidget* list = gtk_list_box_new(); + window->sidebar = GTK_LIST_BOX(list); gtk_widget_add_css_class(list, "navigation-sidebar"); gtk_list_box_set_selection_mode(GTK_LIST_BOX(list), GTK_SELECTION_BROWSE); gtk_list_box_set_header_func(GTK_LIST_BOX(list), SetSidebarHeader, nullptr, @@ -2856,6 +2990,10 @@ GtkWidget* BuildSidebar(SettingsWindow* window) { adw_header_bar_set_decoration_layout(ADW_HEADER_BAR(header), layout.c_str()); } GtkWidget* title = BuildSidebarTitle(); + GtkWidget* pill = BuildVersionPill(window); + gtk_widget_set_valign(pill, GTK_ALIGN_CENTER); + gtk_widget_set_margin_start(pill, 6); + gtk_box_append(GTK_BOX(title), pill); gtk_widget_set_margin_start(title, 4); adw_header_bar_pack_start(ADW_HEADER_BAR(header), title); GtkWidget* toolbar = adw_toolbar_view_new(); @@ -2940,9 +3078,81 @@ void OnCopyLog(GtkButton* button, gpointer user_data) { adw_toast_overlay_add_toast(window->toasts, toast); } +GtkWidget* BuildAboutHero(const SettingsWindow& window) { + GtkWidget* hero = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); + gtk_widget_set_halign(hero, GTK_ALIGN_CENTER); + gtk_widget_set_margin_top(hero, 12); + if (GtkWidget* logo = NewLogo(112, "about-logo")) { + gtk_box_append(GTK_BOX(hero), logo); + } + GtkWidget* name = gtk_label_new("Nightcap"); + gtk_widget_add_css_class(name, "about-name"); + gtk_box_append(GTK_BOX(hero), name); + GtkWidget* version = gtk_label_new(BuildVersionText().c_str()); + gtk_label_set_selectable(GTK_LABEL(version), TRUE); + gtk_widget_add_css_class(version, "about-version"); + gtk_box_append(GTK_BOX(hero), version); + if (!window.roblox_version.empty()) { + GtkWidget* roblox = + gtk_label_new(("Roblox " + window.roblox_version).c_str()); + gtk_widget_add_css_class(roblox, "about-roblox"); + gtk_widget_set_halign(roblox, GTK_ALIGN_CENTER); + gtk_widget_set_margin_top(roblox, 4); + gtk_box_append(GTK_BOX(hero), roblox); + } + return hero; +} + +constexpr char kRepositoryUrl[] = "https://github.com/CoderDayton/nightcap"; + +void OnLinkActivated(AdwActionRow* row, gpointer user_data) { + auto* window = static_cast(user_data); + const char* link = + static_cast(g_object_get_data(G_OBJECT(row), "link")); + std::string url = kRepositoryUrl; + if (g_strcmp0(link, "notes") == 0) { + url += window->nightcap_latest.empty() + ? "/releases" + : "/releases/tag/v" + window->nightcap_latest; + } else if (g_strcmp0(link, "issues") == 0) { + url += "/issues"; + } + GtkUriLauncher* launcher = gtk_uri_launcher_new(url.c_str()); + gtk_uri_launcher_launch(launcher, GTK_WINDOW(window->widget), nullptr, + nullptr, nullptr); + g_object_unref(launcher); +} + +GtkWidget* BuildLinksGroup(SettingsWindow* window) { + GtkWidget* group = adw_preferences_group_new(); + adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(group), "Links"); + const struct { + const char* link; + const char* title; + const char* subtitle; + } links[] = { + {"notes", "What's new", "The newest release's notes on GitHub"}, + {"source", "Source code", "github.com/CoderDayton/nightcap"}, + {"issues", "Report a bug", "Attach the log copied below"}, + }; + for (const auto& link : links) { + GtkWidget* row = adw_action_row_new(); + adw_preferences_row_set_title(ADW_PREFERENCES_ROW(row), link.title); + adw_action_row_set_subtitle(ADW_ACTION_ROW(row), link.subtitle); + gtk_list_box_row_set_activatable(GTK_LIST_BOX_ROW(row), TRUE); + adw_action_row_add_suffix( + ADW_ACTION_ROW(row), + gtk_image_new_from_icon_name("adw-external-link-symbolic")); + g_object_set_data(G_OBJECT(row), "link", const_cast(link.link)); + g_signal_connect(row, "activated", G_CALLBACK(OnLinkActivated), window); + adw_preferences_group_add(ADW_PREFERENCES_GROUP(group), row); + } + return group; +} + GtkWidget* BuildAboutGroup(SettingsWindow* window) { GtkWidget* group = adw_preferences_group_new(); - adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(group), "About"); + adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(group), "Support"); GtkWidget* row = adw_action_row_new(); adw_preferences_row_set_title(ADW_PREFERENCES_ROW(row), "Version"); adw_action_row_set_subtitle(ADW_ACTION_ROW(row), BuildVersionText().c_str()); @@ -2988,6 +3198,9 @@ GtkWidget* BuildPages(SettingsWindow* window) { gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(page_widget), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(page_widget), clamp); + if (page.name == "about") { + gtk_box_append(GTK_BOX(groups), BuildAboutHero(*window)); + } for (const SettingsGroup& group : page.groups) { GtkWidget* group_widget = adw_preferences_group_new(); adw_preferences_group_set_title(ADW_PREFERENCES_GROUP(group_widget), @@ -3042,7 +3255,8 @@ GtkWidget* BuildPages(SettingsWindow* window) { } gtk_box_append(GTK_BOX(groups), group_widget); } - if (page.name == "advanced") { + if (page.name == "about") { + gtk_box_append(GTK_BOX(groups), BuildLinksGroup(window)); gtk_box_append(GTK_BOX(groups), BuildAboutGroup(window)); } gtk_stack_add_named(GTK_STACK(stack), page_widget, @@ -3167,6 +3381,8 @@ void OnActivate(GtkApplication* application, gpointer user_data) { return; } + adw_style_manager_set_color_scheme(adw_style_manager_get_default(), + ADW_COLOR_SCHEME_FORCE_DARK); GtkCssProvider* style = gtk_css_provider_new(); gtk_css_provider_load_from_string(style, kWindowStyle); gtk_style_context_add_provider_for_display( @@ -3177,8 +3393,8 @@ void OnActivate(GtkApplication* application, gpointer user_data) { GtkWidget* window_widget = adw_application_window_new(application); window->widget = window_widget; gtk_window_set_title(GTK_WINDOW(window_widget), "Nightcap Settings"); - // Fits a 1366x768 screen with a panel. - gtk_window_set_default_size(GTK_WINDOW(window_widget), 1040, 760); + // Taller than a 1366x768 screen; window managers shrink it to fit there. + gtk_window_set_default_size(GTK_WINDOW(window_widget), 1040, 800); gtk_widget_set_size_request(window_widget, 360, 420); gtk_window_set_icon_name(GTK_WINDOW(window_widget), kApplicationId); g_signal_connect(window_widget, "close-request", @@ -3230,6 +3446,7 @@ int main(int argc, char* argv[]) { window.font_dir = paths.custom_font_dir(); window.logs_root = paths.logs_root(); window.roblox_data_lock = mocktail::runtime::RobloxDataLockPath(paths); + window.roblox_version = mocktail::runtime::ActiveVersionName(paths); window.restart_program = absolute_path(mocktail::runtime::kRestartProgramVariable); diff --git a/src/ui/settings_model.cc b/src/ui/settings_model.cc index d9b90955e..24e8011b1 100644 --- a/src/ui/settings_model.cc +++ b/src/ui/settings_model.cc @@ -1140,25 +1140,6 @@ const std::vector& SettingsPages() { }, "apk-pure", {}}, - {"updates.nightcap", - "Nightcap updates", - "Automatic installs a new AppImage by itself; other installs " - "update from the row below. Off never checks GitHub.", - SettingKind::kChoice, - { - {"auto", "Automatic"}, - {"notify", "Tell me"}, - {"off", "Off"}, - }, - "auto", - {}}, - {"nightcap_release", - "Nightcap version", - "", - SettingKind::kNightcapRelease, - {}, - "", - {}}, {"updates.launch_after_update", "Start Nightcap after a scripted update", "Used by scripts/auto_update_roblox.sh.", @@ -1236,6 +1217,34 @@ const std::vector& SettingsPages() { {}}, }}, }}, + {"about", + "About", + "help-about-symbolic", + "Other", + { + {"Updates", + { + {"nightcap_release", + "Newest release", + "", + SettingKind::kNightcapRelease, + {}, + "", + {}}, + {"updates.nightcap", + "Install updates", + "Automatic installs a new AppImage by itself; other installs " + "update from the row above. Off never checks GitHub.", + SettingKind::kChoice, + { + {"auto", "Automatic"}, + {"notify", "Tell me"}, + {"off", "Off"}, + }, + "auto", + {}}, + }}, + }}, }; return pages; } diff --git a/src/update/main.cc b/src/update/main.cc index 2537ce900..9aa64efca 100644 --- a/src/update/main.cc +++ b/src/update/main.cc @@ -240,6 +240,7 @@ int NightcapCommand(const mocktail::update::UpdatePaths& paths, int argc, // One launch-time pass: obeys updates.nightcap and only an AppImage // installs without asking, since packages need an administrator prompt. if (action == "auto" && argc == 3) { + mocktail::update::CleanUpInterruptedInstall(environment); const auto config = mocktail::update::LoadUpdateConfig(paths.config_file); if (!config || config.config.nightcap == "off") return 0; const auto status = mocktail::update::CheckNightcapRelease( diff --git a/src/update/nightcap_install_method.cc b/src/update/nightcap_install_method.cc index 43834c994..88955c1f4 100644 --- a/src/update/nightcap_install_method.cc +++ b/src/update/nightcap_install_method.cc @@ -1,5 +1,7 @@ #include "update/nightcap_install_method.h" +#include + #include #include #include @@ -46,9 +48,21 @@ InstallMethod FromPackage(const InstallProbe& probe, InstallKind kind, // The release .pkg and the AUR source package share the name "nightcap", // so pacman installs always go through the AUR helper. if (kind == InstallKind::kArch) { - method.reason = "Installed as " + method.package + - "; update it with your AUR helper."; - method.command = "paru -S " + method.package; + const std::pair helpers[] = { + {"paru", "paru -S "}, {"yay", "yay -S "}, {"pikaur", "pikaur -S "}, + {"aura", "aura -A "}, {"trizen", "trizen -S "}}; + for (const auto& [helper, install] : helpers) { + if (probe.has_program(helper)) { + method.reason = "Installed from the AUR as " + method.package + + "; update it with " + helper + "."; + method.command = install + method.package; + return method; + } + } + method.reason = "Installed from the AUR as " + method.package + + "; build the new release with makepkg."; + method.command = "git clone https://aur.archlinux.org/" + method.package + + ".git && cd " + method.package + " && makepkg -si"; return method; } if (method.package != kReleasePackage) { @@ -107,9 +121,12 @@ std::optional Capture(const std::vector& argv) { } close(pipe_fds[0]); int status = 0; - while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { + pid_t waited = -1; + while ((waited = waitpid(pid, &status, 0)) < 0 && errno == EINTR) { + } + if (waited != pid || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + return std::nullopt; } - if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return std::nullopt; while (!out.empty() && (out.back() == '\n' || out.back() == ' ')) { out.pop_back(); } diff --git a/src/update/nightcap_release.cc b/src/update/nightcap_release.cc index cf9fef1ad..14e4561d6 100644 --- a/src/update/nightcap_release.cc +++ b/src/update/nightcap_release.cc @@ -11,8 +11,7 @@ namespace mocktail::update { namespace { -constexpr char kDownloadPrefix[] = - "https://github.com/CoderDayton/nightcap/releases/download/"; +constexpr const char* kDownloadPrefix = kReleaseDownloadPrefix; bool Fail(std::string* error, std::string message) { if (error != nullptr) *error = std::move(message); diff --git a/src/update/nightcap_self_update.cc b/src/update/nightcap_self_update.cc index 33fd6010f..601d3b8f0 100644 --- a/src/update/nightcap_self_update.cc +++ b/src/update/nightcap_self_update.cc @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -231,8 +232,10 @@ std::optional VerifyRelease(const NightcapUpdaterEnvironment& env, Fail(error, "cannot download SHA256SUMS.sig: " + signature_bytes.error); return std::nullopt; } - if (!VerifyEd25519(sums_text.bytes, signature_bytes.bytes, env.public_key_pem, - error)) { + // The tag is signed with the sums: the AppImage's name never changes, so an + // old release's signed files could otherwise be republished as a new one. + if (!VerifyEd25519("nightcap v" + release.version + "\n" + sums_text.bytes, + signature_bytes.bytes, env.public_key_pem, error)) { return std::nullopt; } const auto table = ParseSums(sums_text.bytes, error); @@ -245,23 +248,31 @@ std::optional VerifyRelease(const NightcapUpdaterEnvironment& env, return Verified{*name, entry->second, asset}; } +std::string IncomingPrefix(const Path& target) { + return "." + target.filename().string() + ".new-"; +} + +// Callers hold the install lock, so no copy here is still being written. +void RemoveIncomingCopies(const Path& target) { + const std::string prefix = IncomingPrefix(target); + std::error_code listing; + for (const auto& entry : + std::filesystem::directory_iterator(target.parent_path(), listing)) { + if (entry.path().filename().string().rfind(prefix, 0) == 0) { + (void)unlink(entry.path().c_str()); + } + } +} + // The new file goes next to the AppImage and is renamed over it, so the // AppImage is whole at every moment and the running copy keeps its open file. bool InstallAppImage(const NightcapUpdaterEnvironment& env, const Path& file, const std::string& sha256, std::string* error) { const Path target = env.method.appimage; const Path previous = target.string() + ".previous"; - const std::string incoming_prefix = "." + target.filename().string() + ".new-"; const Path incoming = - target.parent_path() / (incoming_prefix + std::to_string(getpid())); - // A run stopped mid-copy leaves its own copy behind. - std::error_code listing; - for (const auto& entry : - std::filesystem::directory_iterator(target.parent_path(), listing)) { - if (entry.path().filename().string().rfind(incoming_prefix, 0) == 0) { - (void)unlink(entry.path().c_str()); - } - } + target.parent_path() / (IncomingPrefix(target) + std::to_string(getpid())); + RemoveIncomingCopies(target); if (!CopyFile(file, incoming, error)) return false; if (chmod(incoming.c_str(), 0755) != 0) { const int saved = errno; @@ -316,8 +327,10 @@ int RunProgram(const std::vector& argv) { return -1; } int status = 0; - while (waitpid(pid, &status, 0) < 0 && errno == EINTR) { + pid_t waited = -1; + while ((waited = waitpid(pid, &status, 0)) < 0 && errno == EINTR) { } + if (waited != pid) return -1; return WIFEXITED(status) ? WEXITSTATUS(status) : -1; } @@ -391,6 +404,19 @@ std::optional CheckNightcapRelease( CompareVersions(*status.latest, effective).value_or(0) > 0; if (!env.method.self_update) { status.note = env.method.reason; + // The release's own deb or Fedora rpm on a machine without pkexec. + const auto asset = status.newer && env.method.package == "nightcap" + ? AssetNameFor(env.method, *status.latest) + : std::nullopt; + if (asset && std::find(assets.begin(), assets.end(), *asset) != assets.end()) { + const std::string url = + std::string(kReleaseDownloadPrefix) + "v" + *status.latest + "/" + *asset; + if (env.method.kind == InstallKind::kDeb) { + status.method.command = "curl -LO " + url + " && sudo apt install ./" + *asset; + } else if (env.method.kind == InstallKind::kRpm) { + status.method.command = "sudo dnf install " + url; + } + } } else if (env.public_key_pem.empty()) { status.note = "This build has no release key, so it cannot check a download."; } else if (status.newer) { @@ -407,6 +433,19 @@ std::optional CheckNightcapRelease( return status; } +void CleanUpInterruptedInstall(const NightcapUpdaterEnvironment& env) { + if (env.method.kind != InstallKind::kAppImage || env.method.appimage.empty()) { + return; + } + const int lock = open((StoreRoot(env) / ".install.lock").c_str(), + O_WRONLY | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); + if (lock < 0) return; + if (flock(lock, LOCK_EX | LOCK_NB) == 0) { + RemoveIncomingCopies(env.method.appimage); + } + close(lock); +} + bool InstallNightcapRelease(const NightcapUpdaterEnvironment& env, int progress_fd, std::string* message, std::string* error) { diff --git a/tests/failure_dialog_test.cc b/tests/failure_dialog_test.cc index 9255b0b4b..f57ef020f 100644 --- a/tests/failure_dialog_test.cc +++ b/tests/failure_dialog_test.cc @@ -52,7 +52,7 @@ class FakeDialogHelper final { "capture = '" << capture_.string() << "'\n" - "if len(sys.argv) in (3, 4) and sys.argv[1] in " + "if len(sys.argv) in (3, 4, 5) and sys.argv[1] in " "('--message', '--warning'):\n" " with open(capture, 'a', encoding='utf-8') as stream:\n" " stream.write(':'.join(sys.argv[1:]) + '\\n')\n" @@ -150,10 +150,13 @@ TEST(FailureDialogTest, OneShotPassesAUserFacingMessage) { ASSERT_TRUE(ShowFailureDialog(environment, "Already running.")); ASSERT_TRUE(ShowWarningDialog(environment, "Sign in again.")); ASSERT_TRUE(ShowWarningDialog(environment, "Mount it.", "Home folder")); + ASSERT_TRUE(ShowWarningDialog(environment, "Update it.", "Update Nightcap", + "yay -S nightcap-bin")); EXPECT_EQ(ReadLines(helper.capture()), - std::vector({"--message:Already running.", - "--warning:Sign in again.", - "--warning:Mount it.:Home folder"})); + std::vector( + {"--message:Already running.", "--warning:Sign in again.", + "--warning:Mount it.:Home folder", + "--warning:Update it.:Update Nightcap:yay -S nightcap-bin"})); } TEST(FailureDialogTest, MonitorDismissesAfterSuccessfulShutdown) { diff --git a/tests/nightcap_install_method_test.cc b/tests/nightcap_install_method_test.cc index e9c204437..485768433 100644 --- a/tests/nightcap_install_method_test.cc +++ b/tests/nightcap_install_method_test.cc @@ -86,6 +86,7 @@ TEST(NightcapInstallMethod, ArchStaysWithTheAurHelper) { for (const char* name : {"nightcap", "nightcap-bin", "nightcap-git"}) { Machine machine; machine.owners = {{"pacman", name}}; + machine.programs = {"pkexec", "paru"}; const InstallMethod method = machine.Detect(); EXPECT_EQ(method.kind, InstallKind::kArch) << name; EXPECT_FALSE(method.self_update) << name; @@ -93,6 +94,36 @@ TEST(NightcapInstallMethod, ArchStaysWithTheAurHelper) { } } +TEST(NightcapInstallMethod, ArchNamesTheAurHelperThatIsInstalled) { + const std::pair helpers[] = { + {"yay", "yay -S nightcap-bin"}, + {"pikaur", "pikaur -S nightcap-bin"}, + {"aura", "aura -A nightcap-bin"}, + {"trizen", "trizen -S nightcap-bin"}, + }; + for (const auto& [helper, command] : helpers) { + Machine machine; + machine.owners = {{"pacman", "nightcap-bin"}}; + machine.programs = {"pkexec", helper}; + EXPECT_EQ(machine.Detect().command, command) << helper; + } + Machine both; + both.owners = {{"pacman", "nightcap-bin"}}; + both.programs = {"yay", "paru"}; + EXPECT_EQ(both.Detect().command, "paru -S nightcap-bin"); +} + +TEST(NightcapInstallMethod, ArchWithoutAnAurHelperBuildsWithMakepkg) { + Machine machine; + machine.owners = {{"pacman", "nightcap-bin"}}; + machine.programs = {"pkexec"}; + const InstallMethod method = machine.Detect(); + EXPECT_EQ(method.command, + "git clone https://aur.archlinux.org/nightcap-bin.git && " + "cd nightcap-bin && makepkg -si"); + EXPECT_EQ(method.reason.find("AUR helper"), std::string::npos); +} + TEST(NightcapInstallMethod, DebAndFedoraRpmInstallThroughPkexec) { Machine deb; deb.os_id = "ubuntu"; diff --git a/tests/nightcap_self_update_test.cc b/tests/nightcap_self_update_test.cc index 7a5481b2a..03282d5c8 100644 --- a/tests/nightcap_self_update_test.cc +++ b/tests/nightcap_self_update_test.cc @@ -4,7 +4,10 @@ #include #include #include +#include +#include #include +#include #include #include @@ -101,7 +104,7 @@ struct FakeGithub { files[asset] = bytes; const std::string sums = Sha256Hex(bytes) + " " + asset + "\n"; files["SHA256SUMS"] = sums; - files["SHA256SUMS.sig"] = key.Sign(sums); + files["SHA256SUMS.sig"] = key.Sign("nightcap v" + version + "\n" + sums); } }; @@ -250,10 +253,43 @@ TEST_F(NightcapSelfUpdateTest, AppImageIsReplacedAndTheOldOneKept) { EXPECT_FALSE(status->can_install); } +TEST_F(NightcapSelfUpdateTest, AStoppedInstallsCopyIsRemovedUnlessOneIsRunning) { + const fs::path stray = root_ / "apps/.Nightcap-x86_64.AppImage.new-4242"; + const fs::path other = root_ / "apps/.Other.AppImage.new-4242"; + WriteAll(stray, "half a nightcap"); + WriteAll(other, "not ours"); + fs::create_directories(env_.data_root / "self-update"); + const int held = ::open((env_.data_root / "self-update/.install.lock").c_str(), + O_WRONLY | O_CREAT | O_CLOEXEC, 0600); + ASSERT_GE(held, 0); + ASSERT_EQ(::flock(held, LOCK_EX | LOCK_NB), 0); + CleanUpInterruptedInstall(env_); + EXPECT_TRUE(fs::exists(stray)); + ::close(held); + + CleanUpInterruptedInstall(env_); + EXPECT_FALSE(fs::exists(stray)); + EXPECT_TRUE(fs::exists(other)); + EXPECT_EQ(ReadAll(appimage_), "old nightcap"); +} + +TEST_F(NightcapSelfUpdateTest, AnOldReleasesSignedFilesCannotPoseAsANewOne) { + github_.version = "0.5.0"; + github_.Publish(key_, "Nightcap-x86_64.AppImage", "old release"); + github_.version = "0.6.0"; + std::string message; + std::string error; + EXPECT_FALSE(InstallNightcapRelease(env_, -1, &message, &error)); + EXPECT_NE(error.find("signature"), std::string::npos) << error; + EXPECT_TRUE(github_.downloads.empty()); + EXPECT_EQ(ReadAll(appimage_), "old nightcap"); +} + TEST_F(NightcapSelfUpdateTest, BadSignatureOrHashLeavesTheAppImageAlone) { github_.Publish(key_, "Nightcap-x86_64.AppImage", "new nightcap"); const ReleaseKey stranger; - github_.files["SHA256SUMS.sig"] = stranger.Sign(github_.files["SHA256SUMS"]); + github_.files["SHA256SUMS.sig"] = + stranger.Sign("nightcap v0.6.0\n" + github_.files["SHA256SUMS"]); std::string message; std::string error; EXPECT_FALSE(InstallNightcapRelease(env_, -1, &message, &error)); @@ -313,6 +349,37 @@ TEST_F(NightcapSelfUpdateTest, NothingNewerInstallsNothing) { EXPECT_EQ(ReadAll(appimage_), "old nightcap"); } +TEST_F(NightcapSelfUpdateTest, ReleasePackagesWithoutPkexecGetTheirCommand) { + github_.Publish(key_, "nightcap_0.6.0_amd64.deb", "deb"); + github_.files["nightcap-0.6.0-1.fc44.x86_64.rpm"] = "rpm"; + const std::string download = + "https://github.com/CoderDayton/nightcap/releases/download/v0.6.0/"; + std::string error; + + env_.method = {}; + env_.method.kind = InstallKind::kDeb; + env_.method.package = "nightcap"; + auto status = CheckNightcapRelease(env_, true, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_FALSE(status->can_install); + EXPECT_EQ(status->method.command, + "curl -LO " + download + "nightcap_0.6.0_amd64.deb && " + "sudo apt install ./nightcap_0.6.0_amd64.deb"); + + env_.method.kind = InstallKind::kRpm; + env_.method.distro_version = "44"; + status = CheckNightcapRelease(env_, false, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_EQ(status->method.command, + "sudo dnf install " + download + "nightcap-0.6.0-1.fc44.x86_64.rpm"); + + // A distro's own package is not the release's to replace. + env_.method.package = "nightcap-distro"; + status = CheckNightcapRelease(env_, false, false, &error); + ASSERT_TRUE(status) << error; + EXPECT_TRUE(status->method.command.empty()); +} + TEST_F(NightcapSelfUpdateTest, PackagesInstallThroughPkexec) { env_.method = {}; env_.method.kind = InstallKind::kDeb; diff --git a/tests/settings_model_test.cc b/tests/settings_model_test.cc index 6a0e6fe0b..b05ea4627 100644 --- a/tests/settings_model_test.cc +++ b/tests/settings_model_test.cc @@ -119,7 +119,8 @@ TEST_F(SettingsModelTest, PagesListEverySettingOnce) { EXPECT_EQ(titles, (std::vector{ "Graphics", "Input", "Appearance", "Sounds", "Files", "Performance", "Audio", - "Network", "Discord", "Fleasion", "Advanced"})); + "Network", "Discord", "Fleasion", "Advanced", + "About"})); } TEST_F(SettingsModelTest, OnlyTextureCompressionAsksBeforeItIsTurnedOff) { @@ -218,7 +219,7 @@ TEST_F(SettingsModelTest, PagesOfOneSectionAreNextToEachOther) { } TEST_F(SettingsModelTest, TheAdvancedPageOpensTheConfigFolder) { - const SettingsPage& advanced = SettingsPages().back(); + const SettingsPage& advanced = SettingsPages()[SettingsPages().size() - 2]; ASSERT_EQ(advanced.name, "advanced"); const Setting& folder = Find("config_folder"); EXPECT_EQ(folder.kind, SettingKind::kFolder); @@ -274,24 +275,34 @@ TEST_F(SettingsModelTest, CursorsAreGreyedOutWhileTheSystemCursorIsOn) { EXPECT_TRUE(document.IsActive("font")); } -TEST_F(SettingsModelTest, NightcapsOwnReleaseSitsUnderItsUpdateSetting) { - const Setting& release = Find("nightcap_release"); - EXPECT_EQ(release.kind, SettingKind::kNightcapRelease); +const SettingsPage& PageNamed(std::string_view name) { for (const SettingsPage& page : SettingsPages()) { - for (const SettingsGroup& group : page.groups) { - for (std::size_t i = 0; i + 1 < group.settings.size(); ++i) { - if (group.settings[i].key == "updates.nightcap") { - EXPECT_EQ(&group.settings[i + 1], &release); - return; - } - } + if (page.name == name) return page; + } + ADD_FAILURE() << "no page " << name; + return SettingsPages().front(); +} + +TEST_F(SettingsModelTest, TheLastPageIsAboutWithNightcapsOwnUpdates) { + const SettingsPage& about = SettingsPages().back(); + EXPECT_EQ(about.name, "about"); + EXPECT_EQ(about.section, "Other"); + ASSERT_FALSE(about.groups.empty()); + const auto& settings = about.groups.front().settings; + ASSERT_EQ(settings.size(), 2u); + EXPECT_EQ(&settings[0], &Find("nightcap_release")); + EXPECT_EQ(settings[0].kind, SettingKind::kNightcapRelease); + EXPECT_EQ(&settings[1], &Find("updates.nightcap")); + for (const SettingsGroup& group : PageNamed("advanced").groups) { + for (const Setting& setting : group.settings) { + EXPECT_NE(setting.key, "updates.nightcap"); + EXPECT_NE(setting.key, "nightcap_release"); } } - ADD_FAILURE() << "updates.nightcap has no row"; } TEST_F(SettingsModelTest, TheAdvancedPageClearsTheRobloxCache) { - const SettingsPage& advanced = SettingsPages().back(); + const SettingsPage& advanced = PageNamed("advanced"); const Setting& cache = Find("roblox_cache"); EXPECT_EQ(cache.kind, SettingKind::kCache); bool on_advanced = false; From 0e33fb83159583a97479a4afdb2249293aacc1ca Mon Sep 17 00:00:00 2001 From: vii Date: Wed, 2 Dec 2026 09:33:15 -0600 Subject: [PATCH 3/4] fix(update): say a release is unsigned instead of having no download --- src/update/nightcap_self_update.cc | 4 +++- tests/nightcap_self_update_test.cc | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/update/nightcap_self_update.cc b/src/update/nightcap_self_update.cc index 601d3b8f0..1e8bfe8e3 100644 --- a/src/update/nightcap_self_update.cc +++ b/src/update/nightcap_self_update.cc @@ -427,7 +427,9 @@ std::optional CheckNightcapRelease( status.can_install = asset && listed(*asset) && listed(kSumsAsset) && listed(kSumsSignatureAsset); if (!status.can_install) { - status.note = "Nightcap " + *status.latest + " has no download for this install."; + status.note = asset && listed(*asset) + ? "It is not signed, so it cannot be installed." + : "It has no download for this install."; } } return status; diff --git a/tests/nightcap_self_update_test.cc b/tests/nightcap_self_update_test.cc index 03282d5c8..2d732525f 100644 --- a/tests/nightcap_self_update_test.cc +++ b/tests/nightcap_self_update_test.cc @@ -319,6 +319,7 @@ TEST_F(NightcapSelfUpdateTest, UnsignedReleaseIsRefused) { ASSERT_TRUE(status) << error; EXPECT_TRUE(status->newer); EXPECT_FALSE(status->can_install); + EXPECT_NE(status->note.find("not signed"), std::string::npos) << status->note; } TEST_F(NightcapSelfUpdateTest, AnotherCopysUpdateDoesNotStandInForThisOne) { From 3dc06ad32bcf5061973129a09010e055b45b796c Mon Sep 17 00:00:00 2001 From: vii Date: Wed, 2 Dec 2026 09:50:52 -0600 Subject: [PATCH 4/4] fix(update): close the launch check cleanly and keep commands unhyphenated --- include/runtime/failure_dialog.h | 5 +++-- src/main.cc | 5 +++-- src/runtime/failure_dialog.cc | 6 +++--- src/ui/mocktail_failure_dialog.cc | 8 +++++++- tests/failure_dialog_test.cc | 5 ++++- 5 files changed, 20 insertions(+), 9 deletions(-) diff --git a/include/runtime/failure_dialog.h b/include/runtime/failure_dialog.h index d5af51dd8..edce3989f 100644 --- a/include/runtime/failure_dialog.h +++ b/include/runtime/failure_dialog.h @@ -16,11 +16,12 @@ bool FailureDialogsEnabled(const Environment& environment); bool ShowFailureDialog(const Environment& environment, std::string_view message); // The heading defaults to "Signed out". A `command` is shown under the -// message with a button that copies it. +// message with a button that copies it. The button says Close instead of +// Continue when there is a command or Nightcap `quits` after the dialog. bool ShowWarningDialog(const Environment& environment, std::string_view message, std::string_view heading = {}, - std::string_view command = {}); + std::string_view command = {}, bool quits = false); std::optional AskYesNo(const Environment& environment, std::string_view heading, std::string_view body, std::string_view decline, diff --git a/src/main.cc b/src/main.cc index cc8bbcdc8..58af613a3 100644 --- a/src/main.cc +++ b/src/main.cc @@ -547,7 +547,7 @@ NightcapGate RequireNightcapThatCanJoin( body += "\n\nNightcap " + status.latest + " is out. "; body += status.command.empty() ? status.note : "Update it with:"; (void)mocktail::runtime::ShowWarningDialog(environment, body, heading, - status.command); + status.command, /*quits=*/true); return NightcapGate::kExit; } const std::optional update = mocktail::runtime::AskYesNo( @@ -589,7 +589,7 @@ NightcapGate RequireNightcapThatCanJoin( (void)mocktail::runtime::ShowWarningDialog( environment, "Nightcap " + status.latest + " is installed. Start Nightcap again to play.", - "Nightcap updated"); + "Nightcap updated", {}, /*quits=*/true); return NightcapGate::kExit; } @@ -1184,6 +1184,7 @@ int main(int argc, char* argv[]) { if (gate != NightcapGate::kPlay) { // The gate showed its own dialog. failure_dialog.MarkSuccessful(); + if (gate == NightcapGate::kExit) support_bundle_guard.Disarm(); return gate == NightcapGate::kFailed ? EXIT_FAILURE : EXIT_SUCCESS; } } diff --git a/src/runtime/failure_dialog.cc b/src/runtime/failure_dialog.cc index 658ee9685..f91990b72 100644 --- a/src/runtime/failure_dialog.cc +++ b/src/runtime/failure_dialog.cc @@ -173,19 +173,19 @@ bool ShowFailureDialog(const Environment& environment, bool ShowWarningDialog(const Environment& environment, std::string_view message, std::string_view heading, - std::string_view command) { + std::string_view command, bool quits) { if (!FailureDialogsEnabled(environment)) { return false; } const std::filesystem::path helper = DialogHelper(environment); if (helper.empty()) return false; - if (heading.empty() && command.empty()) { + if (heading.empty() && command.empty() && !quits) { return SpawnOneShot(helper, "--warning", message); } std::vector arguments = { "--warning", std::string(message), heading.empty() ? std::string("Signed out") : std::string(heading)}; - if (!command.empty()) arguments.emplace_back(command); + if (!command.empty() || quits) arguments.emplace_back(command); return SpawnAndWait(helper, arguments).has_value(); } diff --git a/src/ui/mocktail_failure_dialog.cc b/src/ui/mocktail_failure_dialog.cc index 508790bea..e9cab08fb 100644 --- a/src/ui/mocktail_failure_dialog.cc +++ b/src/ui/mocktail_failure_dialog.cc @@ -250,6 +250,11 @@ GtkWidget* NewCommandBox(const char* command) { gtk_label_set_selectable(GTK_LABEL(label), TRUE); gtk_label_set_wrap(GTK_LABEL(label), TRUE); gtk_label_set_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); + // A hyphen at a break would read as part of the command. + PangoAttrList* attributes = pango_attr_list_new(); + pango_attr_list_insert(attributes, pango_attr_insert_hyphens_new(FALSE)); + gtk_label_set_attributes(GTK_LABEL(label), attributes); + pango_attr_list_unref(attributes); gtk_label_set_xalign(GTK_LABEL(label), 0.0f); gtk_widget_set_hexpand(label, TRUE); gtk_widget_set_focusable(label, FALSE); @@ -304,7 +309,8 @@ int ShowDialog(std::string_view requested_message, gtk_widget_add_css_class(details_label, "monospace"); gtk_widget_add_css_class(details_label, "mocktail-failure-details"); adw_alert_dialog_set_extra_child(alert, details_label); - } else if (command != nullptr && g_utf8_validate(command, -1, nullptr)) { + } else if (command != nullptr && *command != '\0' && + g_utf8_validate(command, -1, nullptr)) { adw_alert_dialog_set_extra_child(alert, NewCommandBox(command)); } if (!state.log_folder.empty() && diff --git a/tests/failure_dialog_test.cc b/tests/failure_dialog_test.cc index f57ef020f..98387e1cf 100644 --- a/tests/failure_dialog_test.cc +++ b/tests/failure_dialog_test.cc @@ -152,11 +152,14 @@ TEST(FailureDialogTest, OneShotPassesAUserFacingMessage) { ASSERT_TRUE(ShowWarningDialog(environment, "Mount it.", "Home folder")); ASSERT_TRUE(ShowWarningDialog(environment, "Update it.", "Update Nightcap", "yay -S nightcap-bin")); + ASSERT_TRUE(ShowWarningDialog(environment, "Rebuild it.", "Update Nightcap", + {}, /*quits=*/true)); EXPECT_EQ(ReadLines(helper.capture()), std::vector( {"--message:Already running.", "--warning:Sign in again.", "--warning:Mount it.:Home folder", - "--warning:Update it.:Update Nightcap:yay -S nightcap-bin"})); + "--warning:Update it.:Update Nightcap:yay -S nightcap-bin", + "--warning:Rebuild it.:Update Nightcap:"})); } TEST(FailureDialogTest, MonitorDismissesAfterSuccessfulShutdown) {