Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

One-click update: Update button on the update banner (AppImage, Windows), signed and checked

islandmedb72613e31eda
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3d9b517d..13b188d7 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -271,6 +271,27 @@ jobs:
run: python3 -m zipfile -c dist/sculptforge_maya.zip integrations/maya/sculptforge_maya.py integrations/maya/README.md
- name: Checksums
run: cd dist && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt
+ - name: Sign the checksums (one-click update checks SHA256SUMS.txt.sig, src/core/SelfUpdate.h)
+ env:
+ UPDATE_SIGNING_KEY: ${{ secrets.UPDATE_SIGNING_KEY }}
+ run: |
+ pub=$(sed -n 's/.*kUpdatePublicKeyHex = "\([0-9a-f]*\)".*/\1/p' src/core/SelfUpdate.h)
+ if [ -z "$UPDATE_SIGNING_KEY" ]; then
+ [ -z "$pub" ] || { echo "::error::the app checks updates with key $pub but the UPDATE_SIGNING_KEY secret is not set"; exit 1; }
+ echo "::warning::no UPDATE_SIGNING_KEY secret: no SHA256SUMS.txt.sig (one-click update stays off until the key exists)"
+ exit 0
+ fi
+ umask 077
+ key=$(mktemp)
+ trap 'rm -f "$key" "$key.pub"' EXIT
+ printf '%s\n' "$UPDATE_SIGNING_KEY" > "$key"
+ # The secret must be the private half of the key compiled into the app: a mismatch fails here, not in the field.
+ have=$(openssl pkey -in "$key" -pubout -outform DER | tail -c 32 | od -An -tx1 -v | tr -d ' \n')
+ [ "$have" = "$pub" ] || { echo "::error::UPDATE_SIGNING_KEY's public key ($have) is not kUpdatePublicKeyHex ($pub)"; exit 1; }
+ openssl pkeyutl -sign -inkey "$key" -rawin -in dist/SHA256SUMS.txt -out dist/SHA256SUMS.txt.sig
+ openssl pkey -in "$key" -pubout -out "$key.pub"
+ openssl pkeyutl -verify -pubin -inkey "$key.pub" -rawin -in dist/SHA256SUMS.txt -sigfile dist/SHA256SUMS.txt.sig
+ [ "$(stat -c %s dist/SHA256SUMS.txt.sig)" = 64 ]
- name: Release notes from CHANGELOG
run: |
section=${TAG#v}
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d3b5a5dc..286bdc8b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -83,6 +83,8 @@ add_library(sculptforge_core STATIC
src/core/Precision.cpp
src/core/PathStroke.cpp
src/core/Sha256.cpp
+ src/core/Ed25519.cpp
+ src/core/SelfUpdate.cpp
src/core/BrushGallery.cpp
src/core/VertexPaint.cpp
src/core/PaintLayer.cpp
@@ -397,6 +399,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/PanelMaya.cpp
src/app/PanelPhone.cpp
src/app/PanelProject.cpp
+ src/app/PanelUpdate.cpp
src/app/PanelParts.cpp
src/app/PanelSupport.cpp
src/app/QuickTour.cpp
diff --git a/changes/feat-one-click-update.md b/changes/feat-one-click-update.md
new file mode 100644
index 00000000..84cc84ec
--- /dev/null
+++ b/changes/feat-one-click-update.md
@@ -0,0 +1,29 @@
+---
+whats_new: **One-click update**: on the Linux AppImage and on Windows (installer or portable zip) the update banner
+ has an **Update** button: it downloads the new version in the background, checks its signature and checksum, and
+ installs it on **Restart now** or when you quit (**Later**). The old version is kept until the new one has
+ started, and put back if it doesn't. Package-manager installs show what to run instead.
+highlight: One-click update, signed and checked
+added: **One-click update** (the update banner's **Update** button) for the Linux AppImage and the Windows installer
+ and portable zip: background download with progress and Cancel, then Restart now or Later (installs at quit).
+ Files come only from SculptForge's GitHub releases (every redirect checked, TLS verified); the release's
+ SHA256SUMS.txt must carry an Ed25519 signature under the key built into the app, and the package must match its
+ checksum, before anything is written in place or run. The AppImage is replaced in one atomic rename with the old
+ file kept as `.old` until the new version has started; a new version that doesn't start is rolled back. Flatpak,
+ .deb/.rpm, AUR and Homebrew installs are never replaced (the banner names the command or says to download).
+ macOS keeps the Download button for now. See the guide's Installing > Updating.
+security: Release checksums (SHA256SUMS.txt) are now signed with Ed25519 (SHA256SUMS.txt.sig, a 64-byte raw
+ signature); the release workflow checks the signing secret against the key compiled into the app.
+testers:
+ - Linux AppImage: run an older AppImage, Help > Check for updates, click Update; the bar fills, Restart now starts
+ the new version (Help > About) and the `.old` file next to the AppImage disappears after a few seconds.
+ - Linux AppImage: Update, then Later, then quit: the next start is the new version.
+ - Windows portable zip: Update, Restart now: the folder is updated in place and the app starts again; the
+ `<folder>.old` copy is gone after the new version has run for a few seconds.
+ - Windows installer: Update, Restart now: Windows asks for permission, the installer runs silently and the new
+ version starts.
+ - Flatpak or .deb install: the banner says to update with the package manager instead of showing Update.
+---
+The Update button stays hidden until the release signing key exists (kUpdatePublicKeyHex in
+src/core/SelfUpdate.h and the UPDATE_SIGNING_KEY secret; steps in REPORT.md). Tester checks need a signed release
+newer than the build under test.
diff --git a/docs/design/one-click-update.md b/docs/design/one-click-update.md
new file mode 100644
index 00000000..6880963c
--- /dev/null
+++ b/docs/design/one-click-update.md
@@ -0,0 +1,70 @@
+# One-click update
+
+The update banner's **Update** button: `src/core/SelfUpdate.{h,cpp}` (what is trusted, the download, the swap,
+rollback), `src/core/Ed25519.cpp` (signature check), `ai::httpGetRestricted` (the network), `src/app/PanelUpdate.cpp`
+(the banner, Restart now / Later, watching the restart). Tests: `tests/test_self_update.cpp`.
+
+## Trust chain
+
+1. **Feed** (`latest.json`, unchanged): names the newest version. It can only offer a *newer* version; it chooses no
+ URLs for the updater.
+2. **Where**: `https://github.com/islandmed/SculptForge/releases/download/v<version>/<file>` only (no port, user,
+ query, `..`, escapes), and redirects only to `objects.githubusercontent.com` / `release-assets.githubusercontent.com`.
+ Every hop is checked before it is requested; https only, certificates checked (curl defaults made explicit,
+ WinHTTP defaults).
+3. **Signature**: `SHA256SUMS.txt.sig` is a raw 64-byte Ed25519 signature over `SHA256SUMS.txt`, checked with the
+ public key in `kUpdatePublicKeyHex`. Mbed TLS 3.6 (what libdatachannel links) has no Ed25519, so the check is a
+ verify-only port of TweetNaCl's arithmetic (public domain) with RFC 8032's S < L rule, tested against RFC 8032's
+ vectors and OpenSSL-made signatures. No new library, nothing fetched at build time.
+4. **Version binding**: the app downloads the *versioned* file (`SculptForge-0.12.0-x86_64.AppImage`), whose name is
+ inside the signed list, so an older release's signed files can't be replayed under a newer tag (no downgrade).
+5. **Hash**: the package is hashed as it arrives (SHA-256), capped at 1 GiB, and hashed again right before it is
+ installed (a Later install waits on disk until quit).
+
+Fail at any step: the temporary file is deleted, nothing in place changes, nothing downloaded runs.
+
+## Installing
+
+- **Linux AppImage**: download to `.<asset>.download-<version>` next to the AppImage (same filesystem), `chmod 755`,
+ hard-link the current file to `<name>.old`, write `update_pending.json` in the preferences folder, then one
+ `rename()` over the AppImage. The running app keeps its open file.
+- **Windows**: a PowerShell helper (written to %TEMP%, deletes itself) waits for the app to exit, re-checks the hash,
+ then: installer: `setup.exe /S /D=<folder>` (UAC as usual; the package was downloaded to
+ `%LOCALAPPDATA%\SculptForge\updates`); portable: unzip beside the folder, rename the folder to `.old`, move the new one in.
+- **Package managers** (Flatpak, pacman/AUR, .deb, .rpm, Homebrew, winget's portable layout) are never replaced:
+ the banner names the command or says to download the new file.
+
+## Rollback
+
+- `update_pending.json` counts starts of the new version; a start that runs 5 seconds confirms it (the `.old` copy
+ and the note go). After 3 unconfirmed starts the next start puts `.old` back and starts it.
+- **Restart now** on Linux: the old app hides its window and waits up to 90 s; if the new process exits before it
+ confirms, the old file is put back and the banner says the update didn't start.
+- Windows portable: the helper restores the folder when the new version exits with an error within 20 s.
+- Windows installer: the installer replaces files itself; if it fails (non-zero exit), the old version is left as
+ the installer left it. No rollback beyond that (documented limitation; the installer is the same one users run).
+
+## Limits (known, accepted)
+
+- Same-user malware can already replace the app; the updater doesn't defend against it (the hash re-check before
+ install narrows the window but cannot close it). The Windows installer runs elevated from a user-writable folder,
+ as any downloaded installer does.
+- The feed could hold back updates (offer nothing). It cannot make the app install anything unsigned or older.
+- Key loss or leak: ship a release with a new key (old apps then fall back to the Download button for releases
+ signed with a key they don't know).
+
+## macOS (plan only)
+
+The app is ad-hoc signed, so Gatekeeper treats each new bundle as new: replacing `/Applications/SculptForge.app`
+in place would trip quarantine/translocation and could leave a bundle that won't open. Safe path, once there is a
+Developer ID and notarization: download the `.dmg` (same chain), `hdiutil attach -nobrowse`, `ditto` the bundle to
+`SculptForge.app.new` beside the old one, verify `codesign --verify --deep --strict` and the Team ID, swap with
+`rename`, relaunch with `open -n`. Until then: Download (and `brew upgrade --cask sculptforge` for Homebrew).
+
+## Insider early builds (design only; Tony decides)
+
+Insiders get builds about two weeks early. Proposal: a third channel, `insider`, read from the feed's
+`channels.insider`, whose packages sit in a private place (not public GitHub releases). The app would need a
+membership check (a signed, expiring token from the membership portal, stored in the preferences) and a second
+allowed host. That adds an account surface and a new host to the allowlist, so it needs Tony's OK before any code;
+the signature chain above stays the same (same key, or a separate insider key).
diff --git a/docs/guide/installing.md b/docs/guide/installing.md
index d54eb8f8..5362ce58 100644
--- a/docs/guide/installing.md
+++ b/docs/guide/installing.md
@@ -213,16 +213,32 @@ The next chapter, [The interface](interface.md), explains what everything on scr
## Updating and uninstalling
-SculptForge doesn't install updates by itself, but it tells you when there is one. Once a day at start-up it
-downloads a small file from its website that names the newest version; if yours is older, a banner at the top
-of the 3D view says what's new, with **What's new**, **Download**, **Later** and **Skip this version**. Nothing
-about you or your computer is sent. **Help > Check for updates** asks right away, and **Edit > Preferences > Updates**
-turns the daily check off. Builds from a package manager (such as the AUR package) leave updates to the package
-manager and don't check.
-
-To update, download the new release and install it over the old one. Your settings, brushes and library are
-kept: they live in your user folders, not next to the program (see [Troubleshooting and FAQ](troubleshooting.md)
-for where).
+SculptForge tells you when there is a new version. Once a day at start-up it downloads a small file from its
+website that names the newest version; if yours is older, a banner at the top of the 3D view says what's new, with
+**What's new**, **Download**, **Later** and **Skip this version**. Nothing about you or your computer is sent.
+**Help > Check for updates** asks right away, and **Edit > Preferences > Updates** turns the daily check off (and
+picks the update channel: **Stable**, or **Preview** for the betas).
+
+**One-click update.** The Linux AppImage and the Windows installer and portable zip also get an **Update** button
+on the banner. It downloads the new version in the background (with a progress bar and **Cancel**), checks it, and
+then asks: **Restart now** installs it and starts the new version; **Later** installs it when you quit, so the
+next start is the new version. If you have unsaved changes, Restart now asks first, as quitting does.
+
+What the check means: the files come only from SculptForge's own GitHub releases, over a checked secure
+connection; the release's list of checksums must carry the SculptForge release signature (a key built into the
+app); and the download must match its checksum. If any of that fails, nothing is changed and nothing downloaded
+is run: the banner says what went wrong and **Download** still opens the release page. The current version is
+kept beside the new one (the AppImage as `<name>.AppImage.old`, the portable folder as `<folder>.old`) until the
+new version has started once, then removed; if the new version doesn't start, the old one is put back. The
+Windows installer asks for permission to change Program Files, as installing does.
+
+Installs that belong to a package manager are never replaced by the app: the AUR package (Omarchy's too) builds
+without the update check, a Homebrew install shows `brew upgrade --cask sculptforge`, and the Flatpak, `.deb`
+and `.rpm` files say to download the new file and open it. The macOS app shows **Download** for now.
+
+To update by hand, download the new release and install it over the old one. Either way your settings, brushes
+and library are kept: they live in your user folders, not next to the program (see
+[Troubleshooting and FAQ](troubleshooting.md) for where).
To uninstall, use your system's usual method (Settings > Apps on Windows, dragging the app to the Bin on
macOS, `sudo apt remove sculptforge` or `sudo dnf remove sculptforge` on Linux, `flatpak uninstall
diff --git a/scripts/release.sh b/scripts/release.sh
index 707ecac4..575d9b51 100755
--- a/scripts/release.sh
+++ b/scripts/release.sh
@@ -99,6 +99,10 @@ release_ready() {
gh release view "$T" -R "$REPO" --json assets -q '.assets[].name' > "$work/assets" 2>/dev/null ||
die "no GitHub release $T yet" "run the earlier steps: scripts/release.sh $V --from tag"
grep -qx SHA256SUMS.txt "$work/assets" || die "release $T has no SHA256SUMS.txt (unfinished)" "re-run the Release workflow: gh workflow run release.yml -R $REPO -f tag=$T"
+ # One-click update (src/core/SelfUpdate.h): once the app has a key, every release must carry the signature.
+ if grep -q 'kUpdatePublicKeyHex = "[0-9a-f]\{64\}"' src/core/SelfUpdate.h 2>/dev/null; then
+ grep -qx SHA256SUMS.txt.sig "$work/assets" || die "release $T has no SHA256SUMS.txt.sig: apps can't update to it in one click" "check the UPDATE_SIGNING_KEY secret, then re-run the Release workflow: gh workflow run release.yml -R $REPO -f tag=$T"
+ fi
}
# Downloads one release asset and checks it against SHA256SUMS.txt with a checksum computed here. Prints the sum.
asset_sha() {
diff --git a/src/ai/Http.cpp b/src/ai/Http.cpp
index 097ab450..6428bf19 100644
--- a/src/ai/Http.cpp
+++ b/src/ai/Http.cpp
@@ -50,6 +50,46 @@ std::string multipartBody(const std::vector<MultipartField>& fields, std::string
return body + "--" + boundary + "--\r\n";
}
+
+namespace {
+
+// One request of httpGetRestricted, no redirects followed: a 3xx answer leaves its target in `location`.
+HttpResponse getOnce(const std::string& url, int stallSeconds, const std::function<bool(const char*, size_t)>& onData,
+ const std::function<bool(uint64_t, uint64_t)>& onProgress, std::string& location);
+
+} // namespace
+
+HttpResponse followRedirects(const std::string& url, const std::function<bool(const std::string&)>& allowed,
+ const std::function<HttpResponse(const std::string&, std::string&)>& once) {
+ std::string current = url;
+ for (int hop = 0; hop < 6; ++hop) {
+ if (current.rfind("https://", 0) != 0 || !allowed(current)) {
+ HttpResponse r;
+ r.error = "refused to download from " + current.substr(0, 200);
+ return r;
+ }
+ std::string location;
+ HttpResponse r = once(current, location);
+ if (r.status < 300 || r.status >= 400 || !r.error.empty()) return r;
+ if (location.empty()) {
+ r.error = "the server answered " + std::to_string(r.status) + " without a new address";
+ return r;
+ }
+ current = location;
+ }
+ HttpResponse r;
+ r.error = "too many redirects";
+ return r;
+}
+
+HttpResponse httpGetRestricted(const std::string& url, const std::function<bool(const std::string&)>& allowed,
+ int stallSeconds, const std::function<bool(const char*, size_t)>& onData,
+ const std::function<bool(uint64_t, uint64_t)>& onProgress) {
+ return followRedirects(url, allowed, [&](const std::string& u, std::string& location) {
+ return getOnce(u, stallSeconds, onData, onProgress, location);
+ });
+}
+
#if defined(_WIN32)
namespace {
@@ -137,6 +177,110 @@ HttpResponse httpRequestStream(const std::string& method, const std::string& url
return r;
}
+namespace {
+
+std::string narrow(const std::wstring& w) {
+ if (w.empty()) return {};
+ int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), int(w.size()), nullptr, 0, nullptr, nullptr);
+ std::string s(size_t(n), '\0');
+ WideCharToMultiByte(CP_UTF8, 0, w.data(), int(w.size()), s.data(), n, nullptr, nullptr);
+ return s;
+}
+
+HttpResponse getOnce(const std::string& url, int stallSeconds, const std::function<bool(const char*, size_t)>& onData,
+ const std::function<bool(uint64_t, uint64_t)>& onProgress, std::string& location) {
+ ++gRequests;
+ HttpResponse r;
+ std::wstring wurl = widen(url);
+ URL_COMPONENTS uc{};
+ uc.dwStructSize = sizeof uc;
+ wchar_t host[256] = {}, path[8192] = {};
+ uc.lpszHostName = host;
+ uc.dwHostNameLength = 256;
+ uc.lpszUrlPath = path;
+ uc.dwUrlPathLength = 8192;
+ if (!WinHttpCrackUrl(wurl.c_str(), 0, 0, &uc) || uc.nScheme != INTERNET_SCHEME_HTTPS) {
+ r.error = "Invalid URL: " + url;
+ return r;
+ }
+ std::wstring fullPath = path;
+ if (uc.lpszExtraInfo && uc.dwExtraInfoLength) fullPath.append(uc.lpszExtraInfo, uc.dwExtraInfoLength);
+ Handle session{WinHttpOpen(L"SculptForge/0.1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME,
+ WINHTTP_NO_PROXY_BYPASS, 0)};
+ if (!session.h) {
+ r.error = lastError("WinHttpOpen");
+ return r;
+ }
+ const int ms = stallSeconds * 1000;
+ WinHttpSetTimeouts(session.h, ms, ms, ms, ms); // (each wait, not the whole download)
+ Handle connection{WinHttpConnect(session.h, host, uc.nPort, 0)};
+ if (!connection.h) {
+ r.error = lastError("WinHttpConnect");
+ return r;
+ }
+ Handle request{WinHttpOpenRequest(connection.h, L"GET", fullPath.c_str(), nullptr, WINHTTP_NO_REFERER,
+ WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE)};
+ if (!request.h) {
+ r.error = lastError("WinHttpOpenRequest");
+ return r;
+ }
+ DWORD never = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; // each hop is checked by the caller
+ WinHttpSetOption(request.h, WINHTTP_OPTION_REDIRECT_POLICY, &never, sizeof never);
+ // (Certificate checks stay on: no WINHTTP_OPTION_SECURITY_FLAGS that would ignore errors.)
+ if (!WinHttpSendRequest(request.h, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||
+ !WinHttpReceiveResponse(request.h, nullptr)) {
+ r.error = lastError("HTTP request");
+ return r;
+ }
+ DWORD status = 0, size = sizeof status;
+ WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX,
+ &status, &size, WINHTTP_NO_HEADER_INDEX);
+ r.status = long(status);
+ if (status >= 300 && status < 400) {
+ wchar_t loc[4096] = {};
+ DWORD locSize = sizeof loc;
+ if (WinHttpQueryHeaders(request.h, WINHTTP_QUERY_LOCATION, WINHTTP_HEADER_NAME_BY_INDEX, loc, &locSize,
+ WINHTTP_NO_HEADER_INDEX))
+ location = narrow(loc);
+ return r;
+ }
+ if (status != 200) return r;
+ uint64_t total = 0, received = 0;
+ wchar_t len[32] = {};
+ DWORD lenSize = sizeof len;
+ if (WinHttpQueryHeaders(request.h, WINHTTP_QUERY_CONTENT_LENGTH, WINHTTP_HEADER_NAME_BY_INDEX, len, &lenSize,
+ WINHTTP_NO_HEADER_INDEX))
+ total = _wcstoui64(len, nullptr, 10);
+ if (onProgress && !onProgress(0, total)) {
+ r.error = "cancelled";
+ return r;
+ }
+ std::string chunk;
+ while (true) {
+ DWORD available = 0;
+ if (!WinHttpQueryDataAvailable(request.h, &available)) {
+ r.error = lastError("download");
+ break;
+ }
+ if (available == 0) break;
+ chunk.resize(available);
+ DWORD read = 0;
+ if (!WinHttpReadData(request.h, chunk.data(), available, &read)) {
+ r.error = lastError("download");
+ break;
+ }
+ if (read == 0) break;
+ received += read;
+ if (!onData(chunk.data(), read) || (onProgress && !onProgress(received, total))) {
+ r.error = "cancelled";
+ break;
+ }
+ }
+ return r;
+}
+
+} // namespace
+
#elif defined(SF_HAVE_CURL)
namespace {
@@ -196,6 +340,84 @@ HttpResponse httpRequestStream(const std::string& method, const std::string& url
return r;
}
+namespace {
+
+struct RestrictedSink {
+ CURL* curl;
+ const std::function<bool(const char*, size_t)>* onData;
+ const std::function<bool(uint64_t, uint64_t)>* onProgress;
+ bool stopped = false;
+};
+
+bool finalAnswer(CURL* curl) {
+ long status = 0;
+ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
+ return status == 200;
+}
+
+size_t restrictedWrite(char* data, size_t size, size_t count, void* user) {
+ auto* sink = static_cast<RestrictedSink*>(user);
+ if (!finalAnswer(sink->curl)) return size * count; // a redirect's or an error's body: not the file
+ if (!(*sink->onData)(data, size * count)) {
+ sink->stopped = true;
+ return 0;
+ }
+ return size * count;
+}
+
+int restrictedProgress(void* user, curl_off_t total, curl_off_t now, curl_off_t, curl_off_t) {
+ auto* sink = static_cast<RestrictedSink*>(user);
+ if (!*sink->onProgress || !finalAnswer(sink->curl)) return 0;
+ if ((*sink->onProgress)(uint64_t(now), uint64_t(total))) return 0;
+ sink->stopped = true;
+ return 1;
+}
+
+HttpResponse getOnce(const std::string& url, int stallSeconds, const std::function<bool(const char*, size_t)>& onData,
+ const std::function<bool(uint64_t, uint64_t)>& onProgress, std::string& location) {
+ ++gRequests;
+ static std::once_flag once;
+ std::call_once(once, [] { curl_global_init(CURL_GLOBAL_DEFAULT); });
+ HttpResponse r;
+ CURL* curl = curl_easy_init();
+ if (!curl) {
+ r.error = "curl_easy_init failed";
+ return r;
+ }
+ RestrictedSink sink{curl, &onData, &onProgress};
+ curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
+ curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
+#if LIBCURL_VERSION_NUM >= 0x075500
+ curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, "https");
+#else
+ curl_easy_setopt(curl, CURLOPT_PROTOCOLS, long(CURLPROTO_HTTPS));
+#endif
+ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0L); // each hop is checked by the caller
+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
+ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
+ curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, long(stallSeconds));
+ curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1L); // (a stall, not the whole download, times out)
+ curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, long(stallSeconds));
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, restrictedWrite);
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &sink);
+ curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, restrictedProgress);
+ curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &sink);
+ curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
+ curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
+ curl_easy_setopt(curl, CURLOPT_USERAGENT, "SculptForge/0.1");
+ const CURLcode rc = curl_easy_perform(curl);
+ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &r.status);
+ if (sink.stopped) r.error = "cancelled";
+ else if (rc != CURLE_OK) r.error = curl_easy_strerror(rc);
+ char* target = nullptr;
+ if (r.status >= 300 && r.status < 400 && curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &target) == CURLE_OK && target)
+ location = target;
+ curl_easy_cleanup(curl);
+ return r;
+}
+
+} // namespace
+
#else
HttpResponse httpRequestStream(const std::string&, const std::string&, const std::vector<std::string>&, const std::string&, int,
@@ -206,6 +428,18 @@ HttpResponse httpRequestStream(const std::string&, const std::string&, const std
return r;
}
+namespace {
+
+HttpResponse getOnce(const std::string&, int, const std::function<bool(const char*, size_t)>&,
+ const std::function<bool(uint64_t, uint64_t)>&, std::string&) {
+ ++gRequests;
+ HttpResponse r;
+ r.error = "This build of SculptForge has no HTTP support (libcurl was not found at build time)";
+ return r;
+}
+
+} // namespace
+
#endif
} // namespace sf::ai
diff --git a/src/ai/Http.h b/src/ai/Http.h
index e731d13d..00f4e591 100644
--- a/src/ai/Http.h
+++ b/src/ai/Http.h
@@ -29,6 +29,17 @@ HttpResponse httpRequestStream(const std::string& method, const std::string& url
const std::string& body, int timeoutSeconds,
const std::function<bool(const char* data, size_t size)>& onData);
+// A GET for files that must come from known places (the updater, core/SelfUpdate.h). Redirects are followed one hop
+// at a time and every URL, the first included, must pass `allowed`; https only, certificates checked. The body reaches
+// `onData` only from the final 200 answer. `onProgress(received, total)` (total 0 while unknown) returns false to
+// cancel. `stallSeconds`: give up when nothing arrives for that long (no limit on the whole download).
+HttpResponse httpGetRestricted(const std::string& url, const std::function<bool(const std::string& url)>& allowed,
+ int stallSeconds, const std::function<bool(const char* data, size_t size)>& onData,
+ const std::function<bool(uint64_t received, uint64_t total)>& onProgress = {});
+// httpGetRestricted's redirect rule on its own (tests): `once` makes one request, a 3xx leaving its target in `location`.
+HttpResponse followRedirects(const std::string& url, const std::function<bool(const std::string& url)>& allowed,
+ const std::function<HttpResponse(const std::string& url, std::string& location)>& once);
+
// One part of a multipart/form-data body: a plain field, or a file when `fileName` is set.
struct MultipartField {
std::string name;
diff --git a/src/ai/Process.cpp b/src/ai/Process.cpp
index 2e86c2b7..91cb5c77 100644
--- a/src/ai/Process.cpp
+++ b/src/ai/Process.cpp
@@ -155,6 +155,12 @@ bool ChildProcess::start(const std::string& program, const std::vector<std::stri
return true;
}
+void ChildProcess::detach() {
+ if (process_) CloseHandle(process_);
+ process_ = nullptr;
+ started_ = false;
+}
+
bool ChildProcess::running() {
if (!started_ || finished_) return false;
if (WaitForSingleObject(process_, 0) == WAIT_TIMEOUT) return true;
@@ -245,6 +251,8 @@ bool ChildProcess::running() {
return false;
}
+void ChildProcess::detach() { started_ = false; } // (it was spawned in its own process group)
+
void ChildProcess::kill(double graceSeconds) {
if (!running()) return;
::kill(-pid_, SIGTERM);
diff --git a/src/ai/Process.h b/src/ai/Process.h
index 31ffc535..27b09081 100644
--- a/src/ai/Process.h
+++ b/src/ai/Process.h
@@ -33,6 +33,8 @@ public:
// Waits for it to end; returns the exit code.
int wait();
bool started() const { return started_; }
+ // Lets it run on after this object (and this app) is gone: the updater's relaunch.
+ void detach();
private:
bool started_ = false;
diff --git a/src/app/App.h b/src/app/App.h
index e9459413..7c864822 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -42,6 +42,7 @@
#include "core/SurfaceCursor.h"
#include "core/SpaceMouse.h"
#include "core/Tablet.h"
+#include "core/SelfUpdate.h"
#include "core/UpdateCheck.h"
#include "core/ViewCapture.h"
#include "core/WhatsNew.h"
@@ -69,6 +70,10 @@
#include <unordered_map>
#include <vector>
+namespace sf::ai {
+class ChildProcess; // ai/Process.h (the updater's restart)
+}
+
namespace sf {
struct AppOptions {
@@ -1285,6 +1290,29 @@ private:
std::shared_ptr<UpdateJob> updateJob_;
std::optional<UpdateInfo> updateAvailable_; // shown as the banner until dismissed
std::string updateStatus_; // the last check's result, for Preferences > Updates
+ // One-click update (PanelUpdate.cpp, core/SelfUpdate.h): the banner's Update button downloads and verifies the
+ // release on a worker thread, then installs it on Restart now (watching the new version start, rolling back
+ // when it doesn't) or when the app quits (Later). Package-managed installs get their command instead.
+ enum class SelfUpdateStage { Idle, Downloading, Ready, Restarting, Failed };
+ void initSelfUpdate(); // initProject: a just-installed version counts its start (and rolls back a broken one)
+ void tickSelfUpdate(); // each frame: confirms this version is up, watches a restart
+ bool drawSelfUpdate(const UpdateInfo& u, bool& close); // the banner's Update row; true: it replaces the usual buttons
+ bool selfUpdateOffered(const UpdateInfo& u);
+ void startSelfUpdate(const UpdateInfo& u);
+ void restartIntoUpdate();
+ bool installSelfUpdate(bool relaunch, std::string& error);
+ void finishSelfUpdate(); // at quit: installs an update left for Later
+ std::string updateNotePath() const { return prefDir_.empty() ? std::string() : prefDir_ + "update_pending.json"; }
+ const update::Install& updateInstall();
+ update::Install updateInstall_;
+ bool updateInstallKnown_ = false;
+ SelfUpdateStage selfUpdateStage_ = SelfUpdateStage::Idle;
+ std::shared_ptr<update::Download> selfUpdate_;
+ std::string selfUpdateVersion_, selfUpdateError_;
+ bool installAtQuit_ = false;
+ double confirmStartAt_ = 0.0; // > 0: this version was just installed; confirmed once it has run this long
+ std::shared_ptr<ai::ChildProcess> restartChild_;
+ double restartDeadline_ = 0.0;
int autosaveMinutes_ = 5; // 0 = off
float autosaveTimer_ = 0.0f;
uint64_t autosaveRevision_ = ~uint64_t(0);
diff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cpp
index 40cb7674..a3cc15d1 100644
--- a/src/app/PanelProject.cpp
+++ b/src/app/PanelProject.cpp
@@ -145,6 +145,7 @@ void App::initProject() {
startInputStyle_ = uiPrefs_.inputStyle; // a new install: SculptForge's keys until the welcome's choice
newLookCardDone_ = true; // a new install starts in the new look (or ui.json's): nothing to announce
}
+ initSelfUpdate(); // a just-installed version counts its start (PanelUpdate.cpp)
recentFiles_ = pruneRecentFiles(std::move(recentFiles_), fileExists);
saveProjectPrefs(); // records this version, so What's New shows once
updateDiscordPresence(); // on if it was left on (PanelIntegrations.cpp)
@@ -173,6 +174,7 @@ void App::initProject() {
void App::finishProject() {
if (!interactive() || prefDir_.empty()) return;
+ finishSelfUpdate(); // an update left for Later installs now
saveProjectPrefs();
std::ofstream(fsPath(prefDir_ + "clean_exit"), std::ios::binary | std::ios::trunc) << "SculptForge exited normally\n";
}
@@ -764,6 +766,7 @@ void App::pollUpdateCheck() {
void App::drawUpdateBanner() {
pollUpdateCheck(); // (here, not in tickProject: this runs every frame, UI tests included)
+ tickSelfUpdate();
if (!updateAvailable_) return;
const UpdateInfo& u = *updateAvailable_;
const CanvasRect c = canvasRect(); // top centre of the 3D view, clear of the shelves
@@ -786,21 +789,23 @@ void App::drawUpdateBanner() {
if (guide_.bodyFont()) ImGui::PopFont();
ImGui::Spacing();
bool close = false;
- if (ImGui::Button(tr("What's new"))) SDL_OpenURL(u.notesUrl.c_str());
- ImGui::SameLine();
- if (ImGui::Button(tr("Download"))) {
- SDL_OpenURL(u.downloadUrl.c_str());
- close = true;
- }
- ImGui::SameLine();
- if (ImGui::Button(tr("Become an Insider"))) openSupportPage();
- ImGui::SameLine();
- if (ImGui::Button(tr("Later"))) close = true;
- ImGui::SameLine();
- if (ImGui::Button(tr("Skip this version"))) {
- updateSkipped_ = u.version;
- saveProjectPrefs();
- close = true;
+ if (!drawSelfUpdate(u, close)) { // (PanelUpdate.cpp: Update, or the package manager's command)
+ if (ImGui::Button(tr("What's new"))) SDL_OpenURL(u.notesUrl.c_str());
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Download"))) {
+ SDL_OpenURL(u.downloadUrl.c_str());
+ close = true;
+ }
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Become an Insider"))) openSupportPage();
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Later"))) close = true;
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Skip this version"))) {
+ updateSkipped_ = u.version;
+ saveProjectPrefs();
+ close = true;
+ }
}
if (close) updateAvailable_.reset();
}
diff --git a/src/app/PanelUpdate.cpp b/src/app/PanelUpdate.cpp
new file mode 100644
index 00000000..64e3fd23
--- /dev/null
+++ b/src/app/PanelUpdate.cpp
@@ -0,0 +1,305 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// One-click update: the update banner's Update button (core/SelfUpdate.h says what is trusted and why). The
+// download runs on a worker thread; installing happens on Restart now, or when the app quits after Later.
+#include "app/App.h"
+#include "app/I18n.h"
+#include "app/Ui.h"
+#include "ai/Http.h"
+#include "ai/Process.h"
+#include <imgui.h>
+#include <algorithm>
+#include <array>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <thread>
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#define NOMINMAX
+#include <windows.h> // GetCurrentProcessId
+#endif
+
+namespace sf {
+
+namespace {
+
+namespace fs = std::filesystem;
+
+double nowSeconds() { return double(SDL_GetTicksNS()) * 1e-9; }
+fs::path fsPath(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); }
+
+bool releaseKey(uint8_t key[32]) { return update::parseHexKey(update::kUpdatePublicKeyHex, key); }
+
+constexpr double kConfirmAfterSeconds = 5.0; // a new version that has run this long counts as started
+constexpr double kRestartWaitSeconds = 90.0; // how long the old version waits for the new one to say so
+
+// The release files over HTTPS, every hop checked (core/SelfUpdate.h).
+update::FetchResult fetchRelease(const std::string& url, const std::function<bool(const char*, size_t)>& onData,
+ const std::function<bool(uint64_t, uint64_t)>& onProgress) {
+ const ai::HttpResponse r = ai::httpGetRestricted(url, update::allowedUpdateUrl, 60, onData, onProgress);
+ return {r.status, r.error};
+}
+
+} // namespace
+
+const update::Install& App::updateInstall() {
+ if (updateInstallKnown_ && options_.uiTest.empty()) return updateInstall_; // (UI tests switch installs)
+ updateInstallKnown_ = true;
+ updateInstall_ = update::detectInstall(update::currentInstallProbe());
+ // UI tests only: how the banner looks on other installs (nothing is downloaded in a UI test).
+ const char* kind = options_.uiTest.empty() ? nullptr : std::getenv("SF_UPDATE_TEST_INSTALL");
+ if (kind) {
+ update::Install t;
+ if (std::string(kind) == "appimage") {
+ t.kind = update::InstallKind::AppImage;
+ t.target = "/nonexistent/SculptForge.AppImage";
+ t.asset = "SculptForge-linux-x86_64.AppImage";
+ } else if (std::string(kind) == "pacman") {
+ t.kind = update::InstallKind::PackageManager;
+ t.manager = "pacman";
+ t.command = "yay -Syu sculptforge";
+ }
+ updateInstall_ = t;
+ }
+ return updateInstall_;
+}
+
+bool App::selfUpdateOffered(const UpdateInfo& u) {
+ uint8_t key[32];
+ const bool keyed = releaseKey(key) || !options_.uiTest.empty(); // no key compiled in yet: Download only
+ return keyed && update::selfUpdates(updateInstall().kind) && update::safeVersion(u.version);
+}
+
+void App::initSelfUpdate() {
+ const std::string note = updateNotePath();
+ if (note.empty() || !options_.uiTest.empty()) return;
+ update::Pending p;
+ std::string error;
+ switch (update::checkPendingAtStart(note, appFullVersion(), p, error)) {
+ case update::StartCheck::Counting:
+ confirmStartAt_ = nowSeconds() + kConfirmAfterSeconds;
+ break;
+ case update::StartCheck::RolledBack: {
+ // SculptForge p.version never got going: the previous version is back in place; start it instead.
+ SDL_Log("update: %s didn't start %d times; rolled back to %s", p.version.c_str(), update::kMaxUnconfirmedStarts,
+ p.from.c_str());
+ ai::ChildProcess child;
+ std::string err;
+ if (child.start(p.target, {}, "", {}, err)) child.detach();
+ running_ = false;
+ break;
+ }
+ case update::StartCheck::Abandoned:
+ if (!error.empty()) SDL_Log("update: %s", error.c_str());
+ break;
+ case update::StartCheck::Nothing: break;
+ }
+}
+
+void App::tickSelfUpdate() {
+ if (confirmStartAt_ > 0.0 && nowSeconds() >= confirmStartAt_) {
+ confirmStartAt_ = 0.0;
+ update::confirmStarted(updateNotePath()); // (the old version, watching, sees the note go and quits)
+ }
+ if (selfUpdateStage_ == SelfUpdateStage::Downloading && selfUpdate_ && selfUpdate_->done) {
+ if (selfUpdate_->ok) {
+ selfUpdateStage_ = SelfUpdateStage::Ready;
+ } else {
+ selfUpdateStage_ = selfUpdate_->error == "cancelled" ? SelfUpdateStage::Idle : SelfUpdateStage::Failed;
+ selfUpdateError_ = selfUpdate_->error;
+ selfUpdate_.reset();
+ }
+ }
+ if (selfUpdateStage_ != SelfUpdateStage::Restarting || !restartChild_) return;
+ // The new version is starting: it removes the note once it is up. Exiting before that is a failed start.
+ std::error_code ec;
+ if (!fs::exists(fsPath(updateNotePath()), ec) || nowSeconds() > restartDeadline_) {
+ restartChild_->detach();
+ restartChild_.reset();
+ running_ = false;
+ return;
+ }
+ if (restartChild_->running()) return;
+ const int code = restartChild_->exitCode();
+ restartChild_.reset();
+ update::Pending p;
+ std::string error;
+ const bool restored = update::readPending(updateNotePath(), p) && update::rollback(p, updateNotePath(), error);
+ SDL_Log("update: %s exited with %d before it was up; %s", selfUpdateVersion_.c_str(), code,
+ restored ? "the previous version is back" : error.c_str());
+ if (window_) SDL_ShowWindow(window_);
+ selfUpdateStage_ = SelfUpdateStage::Failed;
+ selfUpdateError_ = restored ? "SculptForge " + selfUpdateVersion_ + " didn't start, so this version was kept"
+ : "SculptForge " + selfUpdateVersion_ + " didn't start: " + error;
+ selfUpdate_.reset();
+}
+
+void App::startSelfUpdate(const UpdateInfo& u) {
+ if (selfUpdateStage_ == SelfUpdateStage::Downloading) return;
+ selfUpdateVersion_ = u.version;
+ selfUpdateError_.clear();
+ installAtQuit_ = false;
+ auto d = std::make_shared<update::Download>();
+ selfUpdate_ = d;
+ selfUpdateStage_ = SelfUpdateStage::Downloading;
+ if (!options_.uiTest.empty()) return; // UI tests see the progress, never the network (Cancel ends it)
+ uint8_t key[32];
+ if (!releaseKey(key)) {
+ d->error = "this build has no update key";
+ d->done = true;
+ return;
+ }
+ const update::Install install = updateInstall();
+ const std::string version = u.version;
+ std::array<uint8_t, 32> k;
+ std::copy(key, key + 32, k.begin());
+ // Detached like the update check: quitting never waits for it (the job is shared, so it outlives the app).
+ std::thread([d, install, version, k] { update::downloadUpdate(version, install, k.data(), fetchRelease, *d); }).detach();
+}
+
+bool App::installSelfUpdate(bool relaunch, std::string& error) {
+ if (!selfUpdate_ || !selfUpdate_->ok) {
+ error = "nothing downloaded";
+ return false;
+ }
+ const update::Install& install = updateInstall();
+ if (install.kind == update::InstallKind::AppImage) {
+ if (!update::installAppImage(install, *selfUpdate_, selfUpdateVersion_, appFullVersion(), updateNotePath(), error))
+ return false;
+ if (!relaunch) return true;
+ auto child = std::make_shared<ai::ChildProcess>();
+ if (!child->start(install.target, {}, "", {}, error)) {
+ update::Pending p;
+ std::string ignored;
+ if (update::readPending(updateNotePath(), p)) update::rollback(p, updateNotePath(), ignored);
+ return false;
+ }
+ restartChild_ = child;
+ restartDeadline_ = nowSeconds() + kRestartWaitSeconds;
+ return true;
+ }
+#if defined(_WIN32)
+ if (install.kind == update::InstallKind::WindowsInstaller || install.kind == update::InstallKind::WindowsPortable) {
+ // A helper finishes the job once this process has ended (Windows can't replace a running program).
+ if (install.kind == update::InstallKind::WindowsPortable &&
+ !update::writePending(updateNotePath(), {selfUpdateVersion_, appFullVersion(), install.target, install.target + ".old", 0})) {
+ error = "can't write the update note";
+ return false;
+ }
+ std::error_code ec;
+ const fs::path script = fs::temp_directory_path(ec) / ("sculptforge-update-" + std::to_string(GetCurrentProcessId()) + ".ps1");
+ {
+ std::ofstream f(script, std::ios::binary | std::ios::trunc);
+ f << update::windowsHelperScript(install, *selfUpdate_, GetCurrentProcessId(), relaunch);
+ if (!f) {
+ error = "can't write the update helper";
+ return false;
+ }
+ }
+ ai::ChildProcess helper;
+ const std::u8string s = script.u8string();
+ if (!helper.start("powershell.exe", {"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", std::string(s.begin(), s.end())},
+ "", {}, error))
+ return false;
+ helper.detach();
+ if (relaunch) running_ = false;
+ return true;
+ }
+#endif
+ error = "this install can't update itself";
+ return false;
+}
+
+void App::restartIntoUpdate() {
+ confirmDiscard([this] { // (unsaved changes: Save, Discard or Cancel first)
+ saveProjectPrefs();
+ std::string error;
+ if (!installSelfUpdate(true, error)) {
+ selfUpdateStage_ = SelfUpdateStage::Failed;
+ selfUpdateError_ = error;
+ selfUpdate_.reset();
+ return;
+ }
+ selfUpdateStage_ = SelfUpdateStage::Restarting;
+ if (restartChild_ && window_) SDL_HideWindow(window_); // (shown again if the new version doesn't start)
+ });
+}
+
+void App::finishSelfUpdate() {
+ if (!installAtQuit_ || selfUpdateStage_ != SelfUpdateStage::Ready || !options_.uiTest.empty()) return;
+ std::string error;
+ if (!installSelfUpdate(false, error)) SDL_Log("update: not installed: %s", error.c_str());
+}
+
+bool App::drawSelfUpdate(const UpdateInfo& u, bool& close) {
+ const update::Install& install = updateInstall();
+ const bool thisVersion = selfUpdateVersion_ == u.version;
+ if (thisVersion && selfUpdateStage_ == SelfUpdateStage::Downloading && selfUpdate_) {
+ const uint64_t got = selfUpdate_->received, total = selfUpdate_->total;
+ char label[64];
+ if (total) std::snprintf(label, sizeof label, "%.0f / %.0f MB", double(got) / 1e6, double(total) / 1e6);
+ else std::snprintf(label, sizeof label, "%.0f MB", double(got) / 1e6);
+ ImGui::TextUnformatted(tr("Downloading the update..."));
+ ImGui::ProgressBar(total ? float(double(got) / double(total)) : 0.0f, ImVec2(320.0f * uiScale_, 0), label);
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Cancel##update.cancel"))) {
+ selfUpdate_->cancel = true;
+ if (!options_.uiTest.empty()) selfUpdate_->error = "cancelled", selfUpdate_->done = true;
+ }
+ return true;
+ }
+ if (thisVersion && selfUpdateStage_ == SelfUpdateStage::Ready) {
+ ImGui::Text(tr("SculptForge %s is downloaded and checked."), u.version.c_str());
+ if (installAtQuit_) {
+ ImGui::TextDisabled("%s", tr("It installs when you quit."));
+ if (ImGui::Button(tr("Restart now##update.restart"))) restartIntoUpdate();
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Hide##update.hide"))) close = true;
+ return true;
+ }
+ if (ImGui::Button(tr("Restart now##update.restart"))) restartIntoUpdate();
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Later##update.later"))) installAtQuit_ = true;
+ ui::HelpText("Later", nullptr, "Install it when you quit SculptForge; the next start is the new version.",
+ "Update banner");
+ return true;
+ }
+ if (thisVersion && selfUpdateStage_ == SelfUpdateStage::Restarting) {
+ ImGui::Text(tr("Starting SculptForge %s..."), u.version.c_str());
+ return true;
+ }
+ if (thisVersion && selfUpdateStage_ == SelfUpdateStage::Failed) {
+ ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.95f, 0.55f, 0.45f, 1.0f));
+ ImGui::TextWrapped(tr("The update didn't work: %s."), selfUpdateError_.c_str());
+ ImGui::PopStyleColor();
+ ImGui::TextDisabled("%s", tr("Nothing was changed. Download it from the website instead, or try again."));
+ }
+ if (install.kind == update::InstallKind::PackageManager) {
+ // Never replaced from here: the package manager owns these files.
+ ImGui::Text(tr("Update with your package manager (%s)"), install.manager.c_str());
+ if (!install.command.empty()) {
+ ImGui::SetNextItemWidth(320.0f * uiScale_);
+ std::string cmd = install.command;
+ ImGui::InputText("##update.command", cmd.data(), cmd.size() + 1, ImGuiInputTextFlags_ReadOnly);
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Copy##update.copy"))) SDL_SetClipboardText(install.command.c_str());
+ } else {
+ ImGui::TextDisabled("%s", tr("Download the new package from the website and open it."));
+ }
+ }
+ if (selfUpdateOffered(u)) {
+ if (ImGui::Button((std::string(tr(selfUpdateStage_ == SelfUpdateStage::Failed && thisVersion ? "Try again" : "Update")) +
+ "##update.update").c_str()))
+ startSelfUpdate(u);
+ ui::HelpText("Update", nullptr,
+ "Download the new version from SculptForge's GitHub releases, check its signature and checksum, "
+ "and install it. The current version is kept until the new one has started.",
+ "Update banner");
+ ImGui::SameLine();
+ }
+ return false;
+}
+
+} // namespace sf
diff --git a/src/core/Ed25519.cpp b/src/core/Ed25519.cpp
new file mode 100644
index 00000000..778677b1
--- /dev/null
+++ b/src/core/Ed25519.cpp
@@ -0,0 +1,312 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Ed25519.h"
+
+#include <cstring>
+#include <vector>
+
+namespace sf {
+
+namespace {
+
+// --- SHA-512 (FIPS 180-4) ---
+
+constexpr uint64_t kRound[80] = {
+ 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
+ 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
+ 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
+ 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
+ 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
+ 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
+ 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
+ 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
+ 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
+ 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
+ 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
+ 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
+ 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
+ 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
+ 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
+ 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
+ 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
+ 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
+ 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
+ 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL,
+};
+
+constexpr uint64_t rotr(uint64_t x, int n) { return (x >> n) | (x << (64 - n)); }
+
+void compress(uint64_t h[8], const uint8_t* block) {
+ uint64_t w[80];
+ for (int i = 0; i < 16; ++i) {
+ w[i] = 0;
+ for (int k = 0; k < 8; ++k) w[i] = w[i] << 8 | block[i * 8 + k];
+ }
+ for (int i = 16; i < 80; ++i) {
+ const uint64_t s0 = rotr(w[i - 15], 1) ^ rotr(w[i - 15], 8) ^ (w[i - 15] >> 7);
+ const uint64_t s1 = rotr(w[i - 2], 19) ^ rotr(w[i - 2], 61) ^ (w[i - 2] >> 6);
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1;
+ }
+ uint64_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
+ for (int i = 0; i < 80; ++i) {
+ const uint64_t t1 = hh + (rotr(e, 14) ^ rotr(e, 18) ^ rotr(e, 41)) + ((e & f) ^ (~e & g)) + kRound[i] + w[i];
+ const uint64_t t2 = (rotr(a, 28) ^ rotr(a, 34) ^ rotr(a, 39)) + ((a & b) ^ (a & c) ^ (b & c));
+ hh = g, g = f, f = e, e = d + t1, d = c, c = b, b = a, a = t1 + t2;
+ }
+ h[0] += a, h[1] += b, h[2] += c, h[3] += d, h[4] += e, h[5] += f, h[6] += g, h[7] += hh;
+}
+
+// --- GF(2^255 - 19): 16 limbs of 16 bits (TweetNaCl) ---
+
+using i64 = long long;
+using gf = i64[16];
+
+constexpr gf gf0 = {0}, gf1 = {1};
+constexpr gf D = {0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,
+ 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203}; // -121665/121666
+constexpr gf D2 = {0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,
+ 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406}; // 2d
+constexpr gf X = {0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,
+ 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169}; // the base point
+constexpr gf Y = {0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
+ 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666};
+constexpr gf I = {0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,
+ 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83}; // sqrt(-1)
+
+void set(gf r, const gf a) { std::memcpy(r, a, sizeof(gf)); }
+
+void carry(gf o) {
+ for (int i = 0; i < 16; ++i) {
+ o[i] += i64(1) << 16;
+ const i64 c = o[i] >> 16;
+ o[(i + 1) * (i < 15)] += c - 1 + 37 * (c - 1) * (i == 15);
+ o[i] -= c * (i64(1) << 16);
+ }
+}
+
+void select(gf p, gf q, int b) {
+ const i64 c = ~(i64(b) - 1);
+ for (int i = 0; i < 16; ++i) {
+ const i64 t = c & (p[i] ^ q[i]);
+ p[i] ^= t, q[i] ^= t;
+ }
+}
+
+void pack(uint8_t* o, const gf n) {
+ gf m, t;
+ set(t, n);
+ carry(t), carry(t), carry(t);
+ for (int j = 0; j < 2; ++j) {
+ m[0] = t[0] - 0xffed;
+ for (int i = 1; i < 15; ++i) {
+ m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
+ m[i - 1] &= 0xffff;
+ }
+ m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
+ const int b = int((m[15] >> 16) & 1);
+ m[14] &= 0xffff;
+ select(t, m, 1 - b);
+ }
+ for (int i = 0; i < 16; ++i) o[2 * i] = uint8_t(t[i] & 0xff), o[2 * i + 1] = uint8_t(t[i] >> 8);
+}
+
+bool differ(const gf a, const gf b) {
+ uint8_t c[32], d[32];
+ pack(c, a), pack(d, b);
+ return std::memcmp(c, d, 32) != 0;
+}
+
+int parity(const gf a) {
+ uint8_t d[32];
+ pack(d, a);
+ return d[0] & 1;
+}
+
+void unpack(gf o, const uint8_t* n) {
+ for (int i = 0; i < 16; ++i) o[i] = n[2 * i] + (i64(n[2 * i + 1]) << 8);
+ o[15] &= 0x7fff;
+}
+
+void add(gf o, const gf a, const gf b) { for (int i = 0; i < 16; ++i) o[i] = a[i] + b[i]; }
+void sub(gf o, const gf a, const gf b) { for (int i = 0; i < 16; ++i) o[i] = a[i] - b[i]; }
+
+void mul(gf o, const gf a, const gf b) {
+ i64 t[31] = {};
+ for (int i = 0; i < 16; ++i)
+ for (int j = 0; j < 16; ++j) t[i + j] += a[i] * b[j];
+ for (int i = 0; i < 15; ++i) t[i] += 38 * t[i + 16];
+ for (int i = 0; i < 16; ++i) o[i] = t[i];
+ carry(o), carry(o);
+}
+
+void square(gf o, const gf a) { mul(o, a, a); }
+
+void invert(gf o, const gf in) {
+ gf c;
+ set(c, in);
+ for (int a = 253; a >= 0; --a) {
+ square(c, c);
+ if (a != 2 && a != 4) mul(c, c, in);
+ }
+ set(o, c);
+}
+
+void pow2523(gf o, const gf in) {
+ gf c;
+ set(c, in);
+ for (int a = 250; a >= 0; --a) {
+ square(c, c);
+ if (a != 1) mul(c, c, in);
+ }
+ set(o, c);
+}
+
+// --- The curve, in extended coordinates (X, Y, Z, T) ---
+
+void addPoint(gf p[4], gf q[4]) {
+ gf a, b, c, d, t, e, f, g, h;
+ sub(a, p[1], p[0]), sub(t, q[1], q[0]), mul(a, a, t);
+ add(b, p[0], p[1]), add(t, q[0], q[1]), mul(b, b, t);
+ mul(c, p[3], q[3]), mul(c, c, D2);
+ mul(d, p[2], q[2]), add(d, d, d);
+ sub(e, b, a), sub(f, d, c), add(g, d, c), add(h, b, a);
+ mul(p[0], e, f), mul(p[1], h, g), mul(p[2], g, f), mul(p[3], e, h);
+}
+
+void swapPoints(gf p[4], gf q[4], int b) { for (int i = 0; i < 4; ++i) select(p[i], q[i], b); }
+
+void packPoint(uint8_t* r, gf p[4]) {
+ gf tx, ty, zi;
+ invert(zi, p[2]);
+ mul(tx, p[0], zi), mul(ty, p[1], zi);
+ pack(r, ty);
+ r[31] ^= uint8_t(parity(tx) << 7);
+}
+
+void scalarMult(gf p[4], gf q[4], const uint8_t* s) {
+ set(p[0], gf0), set(p[1], gf1), set(p[2], gf1), set(p[3], gf0);
+ for (int i = 255; i >= 0; --i) {
+ const int b = (s[i / 8] >> (i & 7)) & 1;
+ swapPoints(p, q, b);
+ addPoint(q, p);
+ addPoint(p, p);
+ swapPoints(p, q, b);
+ }
+}
+
+void scalarBase(gf p[4], const uint8_t* s) {
+ gf q[4];
+ set(q[0], X), set(q[1], Y), set(q[2], gf1), mul(q[3], X, Y);
+ scalarMult(p, q, s);
+}
+
+// The group order L = 2^252 + 27742317777372353535851937790883648493, little-endian.
+constexpr i64 L[32] = {0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10};
+
+void modL(uint8_t* r, i64 x[64]) {
+ for (int i = 63; i >= 32; --i) {
+ i64 c = 0;
+ int j = i - 32;
+ for (; j < i - 12; ++j) {
+ x[j] += c - 16 * x[i] * L[j - (i - 32)];
+ c = (x[j] + 128) >> 8;
+ x[j] -= c * 256;
+ }
+ x[j] += c;
+ x[i] = 0;
+ }
+ i64 c = 0;
+ for (int j = 0; j < 32; ++j) {
+ x[j] += c - (x[31] >> 4) * L[j];
+ c = x[j] >> 8;
+ x[j] &= 255;
+ }
+ for (int j = 0; j < 32; ++j) x[j] -= c * L[j];
+ for (int i = 0; i < 32; ++i) {
+ x[i + 1] += x[i] >> 8;
+ r[i] = uint8_t(x[i] & 255);
+ }
+}
+
+void reduce(uint8_t* r) { // 64 bytes in, mod L in the first 32
+ i64 x[64];
+ for (int i = 0; i < 64; ++i) x[i] = i64(r[i]);
+ std::memset(r, 0, 64);
+ modL(r, x);
+}
+
+// -A from its 32-byte encoding; false when it isn't a point.
+bool unpackNegated(gf r[4], const uint8_t p[32]) {
+ gf t, chk, num, den, den2, den4, den6;
+ set(r[2], gf1);
+ unpack(r[1], p);
+ square(num, r[1]);
+ mul(den, num, D);
+ sub(num, num, r[2]);
+ add(den, r[2], den);
+ square(den2, den), square(den4, den2), mul(den6, den4, den2);
+ mul(t, den6, num), mul(t, t, den);
+ pow2523(t, t);
+ mul(t, t, num), mul(t, t, den), mul(t, t, den);
+ mul(r[0], t, den);
+ square(chk, r[0]), mul(chk, chk, den);
+ if (differ(chk, num)) mul(r[0], r[0], I);
+ square(chk, r[0]), mul(chk, chk, den);
+ if (differ(chk, num)) return false;
+ if (parity(r[0]) == (p[31] >> 7)) sub(r[0], gf0, r[0]);
+ mul(r[3], r[0], r[1]);
+ return true;
+}
+
+// S < L (RFC 8032 5.1.7: a larger S would let one signature be rewritten into others).
+bool belowOrder(const uint8_t s[32]) {
+ for (int i = 31; i >= 0; --i)
+ if (s[i] != L[i]) return s[i] < L[i];
+ return false;
+}
+
+} // namespace
+
+void sha512(const void* data, size_t size, uint8_t out[64]) {
+ uint64_t h[8] = {0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
+ 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
+ const auto* bytes = static_cast<const uint8_t*>(data);
+ size_t i = 0;
+ for (; i + 128 <= size; i += 128) compress(h, bytes + i);
+ // Final block(s): the remaining bytes, 0x80, zeros, then the 128-bit bit length (big-endian).
+ uint8_t tail[256] = {};
+ const size_t rest = size - i;
+ std::memcpy(tail, bytes + i, rest);
+ tail[rest] = 0x80;
+ const size_t tailLen = rest < 112 ? 128 : 256;
+ const uint64_t bits = uint64_t(size) * 8;
+ for (int k = 0; k < 8; ++k) tail[tailLen - 1 - k] = uint8_t(bits >> (8 * k));
+ tail[tailLen - 9] = uint8_t(uint64_t(size) >> 61);
+ compress(h, tail);
+ if (tailLen == 256) compress(h, tail + 128);
+ for (int w = 0; w < 8; ++w)
+ for (int k = 0; k < 8; ++k) out[w * 8 + k] = uint8_t(h[w] >> (56 - 8 * k));
+}
+
+bool ed25519Verify(const uint8_t signature[64], const void* message, size_t size, const uint8_t publicKey[32]) {
+ gf p[4], q[4];
+ if (!belowOrder(signature + 32) || !unpackNegated(q, publicKey)) return false;
+ // h = SHA-512(R || A || M) mod L; the signature holds when [S]B - [h]A encodes to R.
+ std::vector<uint8_t> m(64 + size);
+ std::memcpy(m.data(), signature, 32);
+ std::memcpy(m.data() + 32, publicKey, 32);
+ if (size) std::memcpy(m.data() + 64, message, size);
+ uint8_t h[64], t[32];
+ sha512(m.data(), m.size(), h);
+ reduce(h);
+ scalarMult(p, q, h);
+ scalarBase(q, signature + 32);
+ addPoint(p, q);
+ packPoint(t, p);
+ uint8_t diff = 0; // (constant time, though nothing here is secret)
+ for (int i = 0; i < 32; ++i) diff |= uint8_t(t[i] ^ signature[i]);
+ return diff == 0;
+}
+
+} // namespace sf
diff --git a/src/core/Ed25519.h b/src/core/Ed25519.h
new file mode 100644
index 00000000..09f0f1d1
--- /dev/null
+++ b/src/core/Ed25519.h
@@ -0,0 +1,20 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Ed25519 signature checking (RFC 8032) and the SHA-512 it is built on, for the updater: a release's SHA256SUMS.txt
+// is signed by the release workflow and the app checks it with a public key compiled in (core/SelfUpdate.h). Verify
+// only: the app never signs. The field and group arithmetic is TweetNaCl's (public domain, Bernstein et al.), with
+// RFC 8032's extra rule that S must be below the group order; tests/test_self_update.cpp runs RFC 8032's vectors.
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace sf {
+
+void sha512(const void* data, size_t size, uint8_t out[64]);
+
+// True when `signature` (R || S, 64 bytes) signs `message` under `publicKey` (32 bytes).
+bool ed25519Verify(const uint8_t signature[64], const void* message, size_t size, const uint8_t publicKey[32]);
+
+} // namespace sf
diff --git a/src/core/SelfUpdate.cpp b/src/core/SelfUpdate.cpp
new file mode 100644
index 00000000..b606af34
--- /dev/null
+++ b/src/core/SelfUpdate.cpp
@@ -0,0 +1,558 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/SelfUpdate.h"
+
+#include "core/Ed25519.h"
+#include "core/Json.h"
+#include "core/Sha256.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#elif defined(__APPLE__)
+#include <mach-o/dyld.h>
+#endif
+
+namespace sf::update {
+
+namespace fs = std::filesystem;
+
+namespace {
+
+fs::path fsPath(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); }
+std::string pathString(const fs::path& p) {
+ const std::u8string u = p.u8string();
+ return std::string(u.begin(), u.end());
+}
+
+bool urlChar(char c) {
+ return std::isalnum(static_cast<unsigned char>(c)) || c == '.' || c == '-' || c == '_' || c == '+';
+}
+
+bool safeName(const std::string& s) {
+ return !s.empty() && s.size() <= 128 && s != "." && s != ".." && s.find("..") == std::string::npos &&
+ std::all_of(s.begin(), s.end(), urlChar);
+}
+
+std::string readFile(const fs::path& p) {
+ std::ifstream f(p, std::ios::binary);
+ return f ? std::string(std::istreambuf_iterator<char>(f), {}) : std::string();
+}
+
+std::string hashFile(const fs::path& p) {
+ std::ifstream f(p, std::ios::binary);
+ if (!f) return {};
+ Sha256 h;
+ char buf[1 << 16];
+ while (f) {
+ f.read(buf, sizeof buf);
+ if (f.gcount() > 0) h.update(buf, size_t(f.gcount()));
+ }
+ return h.hex();
+}
+
+} // namespace
+
+// --- Where files may come from ---
+
+bool isReleaseDownloadUrl(const std::string& url) {
+ const std::string prefix = kReleaseDownloadPrefix;
+ if (url.compare(0, prefix.size(), prefix) != 0) return false;
+ const std::string rest = url.substr(prefix.size());
+ const size_t slash = rest.find('/');
+ if (slash == std::string::npos) return false;
+ return safeName(rest.substr(0, slash)) && safeName(rest.substr(slash + 1)); // <tag>/<file>, one level only
+}
+
+bool isReleaseAssetHostUrl(const std::string& url) {
+ // Where GitHub serves release files from (it has moved once: objects. until 2025, release-assets. since).
+ for (const char* host : {"https://objects.githubusercontent.com/", "https://release-assets.githubusercontent.com/"}) {
+ const size_t n = std::char_traits<char>::length(host);
+ if (url.size() > n && url.compare(0, n, host) == 0) return url.find('\\') == std::string::npos;
+ }
+ return false;
+}
+
+bool safeVersion(const std::string& version) {
+ if (version.empty() || version.size() > 40 || !std::isdigit(static_cast<unsigned char>(version[0]))) return false;
+ return std::all_of(version.begin(), version.end(), [](char c) {
+ return std::isalnum(static_cast<unsigned char>(c)) || c == '.' || c == '-';
+ }) && version.find("..") == std::string::npos;
+}
+
+std::string releaseFileUrl(const std::string& version, const std::string& file) {
+ if (!safeVersion(version) || !safeName(file)) return {};
+ return std::string(kReleaseDownloadPrefix) + "v" + version + "/" + file;
+}
+
+// --- What a release must prove ---
+
+std::string versionedAsset(const std::string& asset, const std::string& version) {
+ if (!safeVersion(version)) return {};
+ const std::string v = version.substr(0, version.find('-')); // packages carry the version without its prerelease
+ if (asset == "SculptForge-linux-x86_64.AppImage") return "SculptForge-" + v + "-x86_64.AppImage";
+ if (asset == "SculptForge-linux-arm64.AppImage") return "SculptForge-" + v + "-aarch64.AppImage";
+ if (asset == "SculptForge-windows-x86_64-setup.exe") return "SculptForge-" + v + "-windows-x86_64.exe";
+ if (asset == "SculptForge-windows-x86_64-portable.zip") return "SculptForge-" + v + "-windows-x86_64.zip";
+ return {};
+}
+
+bool parseHexKey(const std::string& hex, uint8_t key[32]) {
+ if (hex.size() != 64) return false;
+ for (size_t i = 0; i < 32; ++i) {
+ int v = 0;
+ for (int k = 0; k < 2; ++k) {
+ const char c = char(std::tolower(static_cast<unsigned char>(hex[i * 2 + k])));
+ if (c >= '0' && c <= '9') v = v * 16 + (c - '0');
+ else if (c >= 'a' && c <= 'f') v = v * 16 + (c - 'a' + 10);
+ else return false;
+ }
+ key[i] = uint8_t(v);
+ }
+ return true;
+}
+
+bool sumsSignatureValid(const std::string& sums, const std::string& signature, const uint8_t key[32]) {
+ return signature.size() == 64 && !sums.empty() &&
+ ed25519Verify(reinterpret_cast<const uint8_t*>(signature.data()), sums.data(), sums.size(), key);
+}
+
+std::string sumFor(const std::string& sums, const std::string& file) {
+ std::string found;
+ int count = 0;
+ size_t i = 0;
+ while (i < sums.size()) { // sha256sum's lines: "<64 hex> <name>" (or " *<name>" in binary mode)
+ size_t e = sums.find('\n', i);
+ if (e == std::string::npos) e = sums.size();
+ std::string line = sums.substr(i, e - i);
+ i = e + 1;
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ if (line.size() < 67 || line[64] != ' ' || (line[65] != ' ' && line[65] != '*')) continue;
+ std::string hash = line.substr(0, 64);
+ if (!std::all_of(hash.begin(), hash.end(), [](char c) { return std::isxdigit(static_cast<unsigned char>(c)); }))
+ continue;
+ if (line.substr(66) != file) continue;
+ for (auto& c : hash) c = char(std::tolower(static_cast<unsigned char>(c)));
+ found = hash;
+ ++count;
+ }
+ return count == 1 ? found : std::string();
+}
+
+// --- What kind of install this is ---
+
+InstallProbe currentInstallProbe() {
+ InstallProbe p;
+#if defined(_WIN32)
+ p.os = "windows";
+ wchar_t buf[MAX_PATH * 4];
+ const DWORD n = GetModuleFileNameW(nullptr, buf, DWORD(std::size(buf)));
+ if (n > 0 && n < std::size(buf)) p.exePath = pathString(fs::path(std::wstring(buf, n)));
+ if (const wchar_t* local = _wgetenv(L"LOCALAPPDATA"); local && *local) p.localAppData = pathString(fs::path(local));
+#elif defined(__APPLE__)
+ p.os = "macos";
+ char buf[4096];
+ uint32_t size = sizeof buf;
+ if (_NSGetExecutablePath(buf, &size) == 0) {
+ std::error_code ec;
+ const fs::path c = fs::weakly_canonical(buf, ec);
+ p.exePath = ec ? std::string(buf) : pathString(c);
+ }
+#else
+ p.os = "linux";
+ std::error_code ec;
+ const fs::path exe = fs::read_symlink("/proc/self/exe", ec);
+ if (!ec) p.exePath = pathString(exe);
+ if (const char* a = std::getenv("APPIMAGE")) p.appImage = a;
+ if (const char* f = std::getenv("FLATPAK_ID")) p.flatpakId = f;
+#endif
+#if defined(__aarch64__) || defined(_M_ARM64)
+ p.arch = "arm64";
+#else
+ p.arch = "x86_64";
+#endif
+ p.exists = [](const std::string& path) {
+ std::error_code ec;
+ return fs::exists(fsPath(path), ec);
+ };
+ return p;
+}
+
+Install detectInstall(const InstallProbe& probe) {
+ Install in;
+ const auto exists = [&](const std::string& path) { return probe.exists && probe.exists(path); };
+ if (probe.os == "linux") {
+ if (!probe.flatpakId.empty() || exists("/.flatpak-info")) {
+ in.kind = InstallKind::PackageManager;
+ in.manager = "Flatpak"; // installed from our .flatpak file: `flatpak update` doesn't reach it, a new file does
+ return in;
+ }
+ if (!probe.appImage.empty() && probe.appImage[0] == '/' && exists(probe.appImage)) {
+ in.kind = InstallKind::AppImage;
+ in.target = probe.appImage;
+ in.asset = probe.arch == "arm64" ? "SculptForge-linux-arm64.AppImage" : "SculptForge-linux-x86_64.AppImage";
+ return in;
+ }
+ if (probe.exePath.rfind("/usr/", 0) == 0 || probe.exePath.rfind("/opt/", 0) == 0) {
+ in.kind = InstallKind::PackageManager;
+ if (exists("/usr/bin/pacman")) {
+ in.manager = "pacman";
+ in.command = "yay -Syu sculptforge"; // the AUR package (Omarchy's too)
+ } else if (exists("/usr/bin/dpkg")) {
+ in.manager = ".deb"; // from the download page: no repository to upgrade from
+ } else if (exists("/usr/bin/rpm")) {
+ in.manager = ".rpm";
+ } else {
+ in.manager = "your package manager";
+ }
+ }
+ return in;
+ }
+ if (probe.os == "macos") {
+ if (exists("/opt/homebrew/Caskroom/sculptforge") || exists("/usr/local/Caskroom/sculptforge")) {
+ in.kind = InstallKind::PackageManager;
+ in.manager = "Homebrew";
+ in.command = "brew upgrade --cask sculptforge";
+ return in;
+ }
+ const size_t app = probe.exePath.find(".app/Contents/MacOS/");
+ if (app != std::string::npos) {
+ in.kind = InstallKind::MacApp;
+ in.target = probe.exePath.substr(0, app + 4);
+ in.asset = "SculptForge-macos.dmg";
+ }
+ return in;
+ }
+ if (probe.os == "windows") {
+ const fs::path exe = fsPath(probe.exePath);
+ if (exe.empty() || exe.parent_path().filename() != "bin") return in; // a build folder, not a package
+ const fs::path root = exe.parent_path().parent_path();
+ in.target = pathString(root);
+ if (probe.exePath.find("\\WinGet\\Packages\\") != std::string::npos) {
+ in.kind = InstallKind::PackageManager;
+ in.manager = "winget";
+ in.command = "winget upgrade SculptForge";
+ } else if (exists(pathString(root / "Uninstall.exe"))) {
+ // (winget's installer-type packages land here too: running the new installer updates the same entry
+ // in Installed apps that winget reads, so both stay in step.)
+ in.kind = InstallKind::WindowsInstaller;
+ in.asset = "SculptForge-windows-x86_64-setup.exe";
+ if (!probe.localAppData.empty()) in.stagingDir = pathString(fsPath(probe.localAppData) / "SculptForge" / "updates");
+ else in.kind = InstallKind::None;
+ } else {
+ in.kind = InstallKind::WindowsPortable;
+ in.asset = "SculptForge-windows-x86_64-portable.zip";
+ }
+ return in;
+ }
+ return in;
+}
+
+// --- The download ---
+
+std::string stagingPath(const Install& install, const std::string& version) {
+ const std::string name = "." + install.asset + ".download-" + version;
+ if (!install.stagingDir.empty()) return pathString(fsPath(install.stagingDir) / name);
+ if (install.kind == InstallKind::WindowsPortable) return pathString(fsPath(install.target) / name);
+ return pathString(fsPath(install.target).parent_path() / name); // next to the AppImage: one rename away
+}
+
+namespace {
+
+// A small file of the release (SHA256SUMS.txt, its signature) into memory, at most `cap` bytes.
+bool fetchSmall(const Fetch& fetch, const std::string& url, size_t cap, Download& d, std::string& out) {
+ out.clear();
+ bool tooBig = false;
+ const FetchResult r = fetch(
+ url,
+ [&](const char* data, size_t n) {
+ if (out.size() + n > cap) return !(tooBig = true);
+ out.append(data, n);
+ return !d.cancel.load();
+ },
+ [&](uint64_t, uint64_t total) { return total <= cap && !d.cancel.load(); });
+ if (d.cancel) d.error = "cancelled";
+ else if (tooBig || (!r.error.empty() && out.size() >= cap)) d.error = url.substr(url.rfind('/') + 1) + " is too large";
+ else if (!r.error.empty()) d.error = r.error;
+ else if (r.status != 200) d.error = "the server answered " + std::to_string(r.status) + " for " + url.substr(url.rfind('/') + 1);
+ return d.error.empty();
+}
+
+} // namespace
+
+void downloadUpdate(const std::string& version, const Install& install, const uint8_t key[32], const Fetch& fetch,
+ Download& d) {
+ struct Done {
+ Download& d;
+ ~Done() { d.done = true; }
+ } done{d};
+ d.ok = false;
+ d.error.clear();
+ const std::string sumsUrl = releaseFileUrl(version, "SHA256SUMS.txt"), sigUrl = releaseFileUrl(version, "SHA256SUMS.txt.sig"),
+ file = versionedAsset(install.asset, version), packageUrl = releaseFileUrl(version, file);
+ if (!selfUpdates(install.kind) || sumsUrl.empty() || packageUrl.empty()) {
+ d.error = "this install can't update itself";
+ return;
+ }
+ std::string sums, sig;
+ if (!fetchSmall(fetch, sumsUrl, kMaxSumsBytes, d, sums) || !fetchSmall(fetch, sigUrl, 1024, d, sig)) return;
+ if (!sumsSignatureValid(sums, sig, key)) {
+ d.error = "the release's signature doesn't match: nothing was installed";
+ return;
+ }
+ d.sha256 = sumFor(sums, file);
+ if (d.sha256.empty()) {
+ d.error = "the release doesn't list " + file;
+ return;
+ }
+
+ const fs::path staged = fsPath(stagingPath(install, version));
+ std::error_code ec;
+ fs::create_directories(staged.parent_path(), ec);
+ fs::remove(staged, ec); // (a download that was cut short)
+ std::ofstream out(staged, std::ios::binary | std::ios::trunc);
+ if (!out) {
+ d.error = "can't write to " + pathString(staged.parent_path());
+ return;
+ }
+ Sha256 hash;
+ uint64_t received = 0;
+ bool tooBig = false, writeFailed = false;
+ const FetchResult r = fetch(
+ packageUrl,
+ [&](const char* data, size_t n) {
+ if (received + n > kMaxPackageBytes) return !(tooBig = true);
+ out.write(data, std::streamsize(n));
+ if (!out) return !(writeFailed = true);
+ hash.update(data, n);
+ received += n;
+ d.received = received;
+ return !d.cancel.load();
+ },
+ [&](uint64_t, uint64_t total) {
+ if (total > kMaxPackageBytes) return !(tooBig = true);
+ if (total) d.total = total;
+ return !d.cancel.load();
+ });
+ out.close();
+ const uint64_t total = d.total;
+ if (d.cancel) d.error = "cancelled";
+ else if (tooBig) d.error = file + " is larger than " + std::to_string(kMaxPackageBytes >> 20) + " MB";
+ else if (writeFailed || !out) d.error = "couldn't write the download (is the disk full?)";
+ else if (!r.error.empty()) d.error = r.error;
+ else if (r.status != 200) d.error = "the server answered " + std::to_string(r.status) + " for " + file;
+ else if (total && received != total) d.error = "the download was cut short";
+ else if (hash.hex() != d.sha256) d.error = "the download doesn't match the release's checksum: nothing was installed";
+ if (!d.error.empty()) {
+ fs::remove(staged, ec);
+ return;
+ }
+ d.staged = pathString(staged);
+ d.ok = true;
+}
+
+// --- Installing, the first start, rolling back ---
+
+bool readPending(const std::string& notePath, Pending& p) {
+ Json j;
+ std::string err;
+ const std::string text = readFile(fsPath(notePath));
+ if (text.empty() || !Json::parse(text, j, err) || !j.isObject()) return false;
+ p.version = j["version"].isString() ? j["version"].asString() : "";
+ p.from = j["from"].isString() ? j["from"].asString() : "";
+ p.target = j["target"].isString() ? j["target"].asString() : "";
+ p.backup = j["backup"].isString() ? j["backup"].asString() : "";
+ p.starts = int(j["starts"].asNumber(0));
+ return !p.version.empty() && !p.target.empty() && p.backup == p.target + ".old";
+}
+
+bool writePending(const std::string& notePath, const Pending& p) {
+ Json j = Json::object();
+ j.set("version", p.version);
+ j.set("from", p.from);
+ j.set("target", p.target);
+ j.set("backup", p.backup);
+ j.set("starts", p.starts);
+ const fs::path path = fsPath(notePath), tmp = fsPath(notePath + ".tmp");
+ {
+ std::ofstream f(tmp, std::ios::binary | std::ios::trunc);
+ if (!(f << j.dump())) return false;
+ }
+ std::error_code ec;
+ fs::rename(tmp, path, ec);
+ return !ec;
+}
+
+bool installAppImage(const Install& install, const Download& d, const std::string& version,
+ const std::string& fromVersion, const std::string& notePath, std::string& error) {
+ const fs::path staged = fsPath(d.staged), target = fsPath(install.target), backup = fsPath(install.target + ".old");
+ std::error_code ec;
+ if (install.kind != InstallKind::AppImage || d.staged.empty() || staged.parent_path() != target.parent_path()) {
+ error = "nothing to install";
+ return false;
+ }
+ if (hashFile(staged) != d.sha256 || d.sha256.empty()) { // (it sat on disk since the download)
+ fs::remove(staged, ec);
+ error = "the download changed since it was checked: nothing was installed";
+ return false;
+ }
+ fs::permissions(staged, fs::perms::owner_all | fs::perms::group_read | fs::perms::group_exec |
+ fs::perms::others_read | fs::perms::others_exec, ec);
+ if (ec) {
+ error = "can't make the new version executable: " + ec.message();
+ return false;
+ }
+ // The current file stays as .old (a hard link: the same file under a second name; a copy where links don't work).
+ fs::remove(backup, ec);
+ fs::create_hard_link(target, backup, ec);
+ if (ec) {
+ ec.clear();
+ fs::copy_file(target, backup, fs::copy_options::overwrite_existing, ec);
+ if (ec) {
+ error = "can't keep the current version as a backup: " + ec.message();
+ return false;
+ }
+ }
+ Pending p{version, fromVersion, install.target, install.target + ".old", 0};
+ if (!writePending(notePath, p)) {
+ fs::remove(backup, ec);
+ error = "can't write the update note";
+ return false;
+ }
+ fs::rename(staged, target, ec); // one step: the target is the old file or the new one, never half of either
+ if (ec) {
+ error = "can't replace " + install.target + ": " + ec.message();
+ fs::remove(fsPath(notePath), ec);
+ std::error_code ec2;
+ fs::remove(backup, ec2);
+ return false;
+ }
+ return true;
+}
+
+bool rollback(const Pending& p, const std::string& notePath, std::string& error) {
+ std::error_code ec;
+ const fs::path target = fsPath(p.target), backup = fsPath(p.backup);
+ if (!fs::exists(backup, ec)) {
+ error = "the previous version (" + p.backup + ") is gone";
+ fs::remove(fsPath(notePath), ec);
+ return false;
+ }
+ if (fs::is_directory(backup, ec)) { // a Windows portable folder: the failed one is set aside first
+ const fs::path failed = fsPath(p.target + ".failed");
+ fs::remove_all(failed, ec);
+ fs::rename(target, failed, ec);
+ if (ec) {
+ error = "can't move the new version aside: " + ec.message();
+ return false;
+ }
+ }
+ fs::rename(backup, target, ec);
+ if (ec) {
+ error = "can't put the previous version back: " + ec.message();
+ return false;
+ }
+ fs::remove(fsPath(notePath), ec);
+ return true;
+}
+
+StartCheck checkPendingAtStart(const std::string& notePath, const std::string& runningVersion, Pending& p,
+ std::string& error) {
+ if (!readPending(notePath, p)) {
+ std::error_code ec;
+ fs::remove(fsPath(notePath), ec); // (none, or not ours)
+ return StartCheck::Nothing;
+ }
+ if (p.version != runningVersion) {
+ std::error_code ec;
+ fs::remove(fsPath(notePath), ec);
+ return StartCheck::Abandoned;
+ }
+ ++p.starts;
+ if (p.starts > kMaxUnconfirmedStarts) {
+ if (rollback(p, notePath, error)) return StartCheck::RolledBack;
+ std::error_code ec;
+ fs::remove(fsPath(notePath), ec); // (no endless retries)
+ return StartCheck::Abandoned;
+ }
+ writePending(notePath, p);
+ return StartCheck::Counting;
+}
+
+void confirmStarted(const std::string& notePath) {
+ Pending p;
+ std::error_code ec;
+ if (readPending(notePath, p)) fs::remove_all(fsPath(p.backup), ec);
+ fs::remove(fsPath(notePath), ec);
+}
+
+// --- Windows ---
+
+namespace {
+
+std::string psQuote(const std::string& s) { // a PowerShell literal: '...' with ' doubled
+ std::string out = "'";
+ for (char c : s) out += c == '\'' ? std::string("''") : std::string(1, c);
+ return out + "'";
+}
+
+} // namespace
+
+std::string windowsHelperScript(const Install& install, const Download& d, unsigned long pid, bool relaunch) {
+ const bool portable = install.kind == InstallKind::WindowsPortable;
+ std::string s;
+ s += "# SculptForge update helper (written by the app; deletes itself)\n";
+ s += "$ErrorActionPreference = 'Stop'\n";
+ s += "$staged = " + psQuote(d.staged) + "\n";
+ s += "$sha = " + psQuote(d.sha256) + "\n";
+ s += "$root = " + psQuote(install.target) + "\n";
+ s += "$exe = Join-Path $root 'bin\\sculptforge.exe'\n";
+ s += "try { Wait-Process -Id " + std::to_string(pid) + " -Timeout 600 } catch {}\n";
+ s += "Start-Sleep -Milliseconds 500\n";
+ s += "if ((Get-FileHash -Algorithm SHA256 -LiteralPath $staged).Hash.ToLower() -ne $sha) {\n"
+ " Remove-Item -LiteralPath $staged -Force; exit 2 }\n";
+ if (!portable) {
+ // NSIS: /S silent, /D= the folder (last, unquoted). Windows asks for permission when the folder needs it.
+ s += "$p = Start-Process -FilePath $staged -ArgumentList \"/S /D=$root\" -Wait -PassThru\n";
+ s += "Remove-Item -LiteralPath $staged -Force -ErrorAction SilentlyContinue\n";
+ s += "if ($p.ExitCode -ne 0) { exit 3 }\n";
+ if (relaunch) s += "Start-Process -FilePath $exe\n";
+ s += "Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue\n";
+ return s;
+ }
+ s += "$new = \"$root.new\"; $old = \"$root.old\"\n";
+ s += "Remove-Item -LiteralPath $new -Recurse -Force -ErrorAction SilentlyContinue\n";
+ s += "Expand-Archive -LiteralPath $staged -DestinationPath $new -Force\n";
+ s += "$top = Get-ChildItem -LiteralPath $new -Directory | Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName "
+ "'bin\\sculptforge.exe') } | Select-Object -First 1\n";
+ s += "$src = if ($top) { $top.FullName } elseif (Test-Path -LiteralPath (Join-Path $new 'bin\\sculptforge.exe')) { $new } "
+ "else { Remove-Item -LiteralPath $new -Recurse -Force; exit 4 }\n";
+ s += "Remove-Item -LiteralPath $old -Recurse -Force -ErrorAction SilentlyContinue\n";
+ // Files still in use (an Explorer window, an antivirus scan) make the first rename fail: a few tries.
+ s += "$moved = $false\n";
+ s += "for ($i = 0; $i -lt 20 -and -not $moved; $i++) {\n"
+ " try { Move-Item -LiteralPath $root -Destination $old; $moved = $true } catch { Start-Sleep -Milliseconds 500 } }\n";
+ s += "if (-not $moved) { Remove-Item -LiteralPath $new -Recurse -Force; exit 5 }\n";
+ s += "Move-Item -LiteralPath $src -Destination $root\n";
+ s += "if ($src -ne $new) { Remove-Item -LiteralPath $new -Recurse -Force -ErrorAction SilentlyContinue }\n";
+ if (relaunch) {
+ // A new version that exits with an error within 20 seconds is rolled back and the old one started again.
+ s += "$p = Start-Process -FilePath $exe -PassThru\n";
+ s += "Start-Sleep -Seconds 20\n";
+ s += "if ($p.HasExited -and $p.ExitCode -ne 0) {\n"
+ " Move-Item -LiteralPath $root -Destination \"$root.failed\"; Move-Item -LiteralPath $old -Destination $root\n"
+ " Start-Process -FilePath $exe }\n";
+ }
+ s += "Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue\n";
+ return s;
+}
+
+} // namespace sf::update
diff --git a/src/core/SelfUpdate.h b/src/core/SelfUpdate.h
new file mode 100644
index 00000000..3848eb53
--- /dev/null
+++ b/src/core/SelfUpdate.h
@@ -0,0 +1,163 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// One-click update (the update banner's Update button, app/PanelProject.cpp). What it trusts, in order:
+// 1. Files come only from https://github.com/islandmed/SculptForge/releases/download/<tag>/<file>, and a redirect
+// only to GitHub's release asset hosts (ai::httpGetRestricted checks every hop; certificates are checked).
+// 2. The release's SHA256SUMS.txt must carry a valid Ed25519 signature (SHA256SUMS.txt.sig, made by the release
+// workflow) under the public key compiled into the app (kUpdatePublicKeyHex below).
+// 3. The package's SHA-256 must be the one SHA256SUMS.txt names; it is checked again right before installing.
+// Until all three pass nothing is written in place and nothing downloaded runs. The package goes to a temporary
+// file next to what it replaces (same folder, so the final rename is one atomic step); the old version is kept as
+// "<name>.old" until the new one has started once, and put back when it doesn't start.
+// Package-managed installs (Flatpak, pacman/AUR, .deb/.rpm, Homebrew) are never replaced: the banner names the
+// command instead. Linux AppImage and Windows (installer and portable zip) update themselves; macOS opens the
+// download page (see docs/design/one-click-update.md).
+#pragma once
+
+#include <atomic>
+#include <cstdint>
+#include <functional>
+#include <string>
+
+namespace sf::update {
+
+inline constexpr const char* kReleaseDownloadPrefix = "https://github.com/islandmed/SculptForge/releases/download/";
+inline constexpr uint64_t kMaxPackageBytes = uint64_t(1) << 30; // 1 GiB (an AppImage is ~150 MB)
+inline constexpr size_t kMaxSumsBytes = 256 * 1024;
+inline constexpr int kMaxUnconfirmedStarts = 3; // a new version that never got going this often is rolled back
+
+// The public half of the release signing key (Ed25519, 32 bytes as hex). Empty: no key yet, and the Update button
+// stays off (the banner's Download link still works). The private half is the repository secret UPDATE_SIGNING_KEY,
+// used only by .github/workflows/release.yml.
+inline constexpr const char* kUpdatePublicKeyHex = "";
+
+// --- Where files may come from ---
+
+// https://github.com/islandmed/SculptForge/releases/download/<tag>/<file>: nothing else (no port, user, query,
+// "..", backslash or percent-escape).
+bool isReleaseDownloadUrl(const std::string& url);
+// GitHub's release asset hosts, where the URL above redirects (https only, exact host names).
+bool isReleaseAssetHostUrl(const std::string& url);
+inline bool allowedUpdateUrl(const std::string& url) { return isReleaseDownloadUrl(url) || isReleaseAssetHostUrl(url); }
+// A release version safe to put in a URL ("0.12.0", "0.12.0-beta.1").
+bool safeVersion(const std::string& version);
+// The download URL of `file` in release v<version>; "" when the version or file name isn't safe.
+std::string releaseFileUrl(const std::string& version, const std::string& file);
+
+// --- What a release must prove ---
+
+// The release file that is downloaded for `asset` (a version-less name such as SculptForge-linux-x86_64.AppImage):
+// its versioned twin, SculptForge-0.12.0-x86_64.AppImage. Its line in the signed SHA256SUMS.txt ties the package to
+// that version, so an older release's signed files can't be passed off as a newer one's. "" for unknown assets.
+std::string versionedAsset(const std::string& asset, const std::string& version);
+
+bool parseHexKey(const std::string& hex, uint8_t key[32]);
+// The signature (64 raw bytes) over SHA256SUMS.txt's exact bytes.
+bool sumsSignatureValid(const std::string& sums, const std::string& signature, const uint8_t key[32]);
+// The lowercase SHA-256 SHA256SUMS.txt lists for `file` ("" when it isn't listed exactly once).
+std::string sumFor(const std::string& sums, const std::string& file);
+
+// --- What kind of install this is ---
+
+enum class InstallKind {
+ None, // built from source, or somewhere that can't be told apart: the Download link only
+ AppImage, // target: the .AppImage file
+ WindowsInstaller, // target: the install folder (bin\sculptforge.exe, Uninstall.exe)
+ WindowsPortable, // target: the unzipped folder (bin\sculptforge.exe, no uninstaller)
+ MacApp, // target: the .app bundle (not self-updated yet)
+ PackageManager, // Flatpak, pacman/AUR, .deb/.rpm, Homebrew: `command` says what to run
+};
+
+struct Install {
+ InstallKind kind = InstallKind::None;
+ std::string target; // what gets replaced
+ std::string stagingDir; // where the download goes when not next to the target (Windows installer: %LOCALAPPDATA%)
+ std::string asset; // the release file that replaces it (version-less; versionedAsset names the download)
+ std::string command; // PackageManager: the update command, "" when there is none (e.g. a downloaded .deb)
+ std::string manager; // PackageManager: "Flatpak", "pacman", ...
+};
+
+// What detectInstall looks at, so tests can describe any machine.
+struct InstallProbe {
+ std::string os; // "linux", "windows", "macos"
+ std::string arch; // "x86_64", "arm64"
+ std::string exePath; // this program, absolute
+ std::string appImage; // $APPIMAGE (set by the AppImage runtime)
+ std::string flatpakId; // $FLATPAK_ID
+ std::string localAppData; // %LOCALAPPDATA% (Windows)
+ std::function<bool(const std::string&)> exists;
+};
+InstallProbe currentInstallProbe(); // this process
+Install detectInstall(const InstallProbe& probe);
+inline bool selfUpdates(InstallKind k) {
+ return k == InstallKind::AppImage || k == InstallKind::WindowsInstaller || k == InstallKind::WindowsPortable;
+}
+
+// --- The download (a worker thread) ---
+
+struct FetchResult {
+ long status = 0;
+ std::string error;
+};
+// GET `url` (the app: ai::httpGetRestricted with allowedUpdateUrl). onData false or onProgress false stop it.
+using Fetch = std::function<FetchResult(const std::string& url, const std::function<bool(const char*, size_t)>& onData,
+ const std::function<bool(uint64_t received, uint64_t total)>& onProgress)>;
+
+struct Download {
+ std::atomic<uint64_t> received{0}, total{0};
+ std::atomic<bool> cancel{false};
+ std::atomic<bool> done{false};
+ bool ok = false;
+ std::string error;
+ std::string staged; // the verified package, next to the install's target
+ std::string sha256; // what SHA256SUMS.txt says it is (checked again before installing)
+};
+
+// SHA256SUMS.txt, its signature, then the package into a temporary file in the target's folder, hashed as it
+// arrives. Fails (removing the temporary file) on any doubt; on success `out.staged` is ready to install.
+void downloadUpdate(const std::string& version, const Install& install, const uint8_t key[32], const Fetch& fetch,
+ Download& out);
+
+// The temporary file a package is downloaded to (dot-file next to the target, or inside the target folder).
+std::string stagingPath(const Install& install, const std::string& version);
+
+// --- Installing, the first start, rolling back ---
+
+// The note an install leaves for the next start (<prefs>/update_pending.json).
+struct Pending {
+ std::string version; // the new one
+ std::string from; // the one it replaced
+ std::string target;
+ std::string backup; // target + ".old"
+ int starts = 0; // starts of `version` that haven't been confirmed yet
+};
+bool readPending(const std::string& notePath, Pending& out);
+bool writePending(const std::string& notePath, const Pending& p);
+
+// Linux AppImage: checks the staged file's hash again, makes it executable, keeps the current file as <target>.old
+// and renames the new one over the target (one atomic step; the running app keeps its open file). Writes the note.
+bool installAppImage(const Install& install, const Download& d, const std::string& version,
+ const std::string& fromVersion, const std::string& notePath, std::string& error);
+
+// Puts the backup back over the target. The note is removed.
+bool rollback(const Pending& p, const std::string& notePath, std::string& error);
+
+enum class StartCheck {
+ Nothing, // no note
+ Counting, // this is the new version's start number p.starts: confirmStarted() once it is up
+ RolledBack, // it never got going (kMaxUnconfirmedStarts): the old version is back, run p.target again
+ Abandoned, // another version is running (the user started the .old one): the note is dropped
+};
+// At startup, before anything that could crash.
+StartCheck checkPendingAtStart(const std::string& notePath, const std::string& runningVersion, Pending& p,
+ std::string& error);
+// The new version is up: the backup and the note go.
+void confirmStarted(const std::string& notePath);
+
+// Windows: the PowerShell helper that waits for this process (`pid`) to end, checks the staged package's hash again,
+// installs it (the installer silently, or the zip unpacked beside the folder and swapped in, the old folder kept
+// as .old), starts the new version when `relaunch`, and rolls a portable folder back if the new one exits at once.
+std::string windowsHelperScript(const Install& install, const Download& d, unsigned long pid, bool relaunch);
+
+} // namespace sf::update
diff --git a/src/core/Sha256.cpp b/src/core/Sha256.cpp
index eb1778dc..8d74a5e9 100644
--- a/src/core/Sha256.cpp
+++ b/src/core/Sha256.cpp
@@ -2,7 +2,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/Sha256.h"
-#include <array>
+#include <algorithm>
+#include <cstring>
namespace sf {
@@ -19,7 +20,7 @@ constexpr uint32_t kRound[64] = {
constexpr uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
-void compress(std::array<uint32_t, 8>& h, const uint8_t* block) {
+void compress(uint32_t* h, const uint8_t* block) {
uint32_t w[64];
for (int i = 0; i < 16; ++i)
w[i] = uint32_t(block[i * 4]) << 24 | uint32_t(block[i * 4 + 1]) << 16 | uint32_t(block[i * 4 + 2]) << 8 |
@@ -55,27 +56,42 @@ void compress(std::array<uint32_t, 8>& h, const uint8_t* block) {
} // namespace
std::string sha256Hex(const void* data, size_t size) {
- std::array<uint32_t, 8> h = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
- 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
+ Sha256 h;
+ h.update(data, size);
+ return h.hex();
+}
+
+void Sha256::update(const void* data, size_t size) {
const auto* bytes = static_cast<const uint8_t*>(data);
- size_t i = 0;
- for (; i + 64 <= size; i += 64) compress(h, bytes + i);
+ total_ += size;
+ while (size) {
+ if (used_ == 0 && size >= 64) { // whole blocks straight from the input
+ compress(h_, bytes);
+ bytes += 64, size -= 64;
+ continue;
+ }
+ const size_t n = std::min(size, 64 - used_);
+ std::memcpy(block_ + used_, bytes, n);
+ used_ += n, bytes += n, size -= n;
+ if (used_ == 64) compress(h_, block_), used_ = 0;
+ }
+}
+std::string Sha256::hex() {
// Final block(s): the remaining bytes, 0x80, zeros, then the bit length (big-endian).
uint8_t tail[128] = {};
- const size_t rest = size - i;
- for (size_t k = 0; k < rest; ++k) tail[k] = bytes[i + k];
- tail[rest] = 0x80;
- const size_t tailLen = rest < 56 ? 64 : 128;
- const uint64_t bits = uint64_t(size) * 8;
+ std::memcpy(tail, block_, used_);
+ tail[used_] = 0x80;
+ const size_t tailLen = used_ < 56 ? 64 : 128;
+ const uint64_t bits = total_ * 8;
for (int k = 0; k < 8; ++k) tail[tailLen - 1 - k] = uint8_t(bits >> (8 * k));
- compress(h, tail);
- if (tailLen == 128) compress(h, tail + 64);
+ compress(h_, tail);
+ if (tailLen == 128) compress(h_, tail + 64);
static const char* hex = "0123456789abcdef";
std::string out;
out.reserve(64);
- for (uint32_t v : h)
+ for (uint32_t v : h_)
for (int k = 28; k >= 0; k -= 4) out += hex[(v >> k) & 0xf];
return out;
}
diff --git a/src/core/Sha256.h b/src/core/Sha256.h
index 387cece0..e4202aec 100644
--- a/src/core/Sha256.h
+++ b/src/core/Sha256.h
@@ -13,6 +13,18 @@ namespace sf {
// Lowercase hex digest of `size` bytes.
std::string sha256Hex(const void* data, size_t size);
+
+// The same digest fed in pieces (downloads hashed as they arrive).
+class Sha256 {
+public:
+ void update(const void* data, size_t size);
+ std::string hex(); // ends the hash; the object is then spent
+private:
+ uint32_t h_[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
+ uint8_t block_[64] = {};
+ size_t used_ = 0;
+ uint64_t total_ = 0;
+};
inline std::string sha256Hex(const std::string& data) { return sha256Hex(data.data(), data.size()); }
} // namespace sf
diff --git a/tests/test_self_update.cpp b/tests/test_self_update.cpp
new file mode 100644
index 00000000..427a5823
--- /dev/null
+++ b/tests/test_self_update.cpp
@@ -0,0 +1,472 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// One-click update (src/core/SelfUpdate.cpp, src/core/Ed25519.cpp, ai::httpGetRestricted): only GitHub's release
+// URLs, only a correctly signed SHA256SUMS.txt, only a package with its hash; the swap and the rollback. No network:
+// the downloads are served by a stand-in for the HTTP client.
+#include "TestHarness.h"
+
+#include "ai/Http.h"
+#include "core/Ed25519.h"
+#include "core/SelfUpdate.h"
+#include "core/Sha256.h"
+
+#include <algorithm>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <map>
+
+using namespace sf;
+using namespace sf::update;
+namespace fs = std::filesystem;
+
+namespace {
+
+std::string unhex(const std::string& h) {
+ std::string out;
+ for (size_t i = 0; i + 1 < h.size(); i += 2) out += char(std::stoi(h.substr(i, 2), nullptr, 16));
+ return out;
+}
+
+std::string sha512Hex(const std::string& m) {
+ uint8_t h[64];
+ sha512(m.data(), m.size(), h);
+ std::string out;
+ for (uint8_t b : h) out += "0123456789abcdef"[b >> 4], out += "0123456789abcdef"[b & 15];
+ return out;
+}
+
+bool verifyHex(const std::string& sig, const std::string& msg, const std::string& pub) {
+ const std::string s = unhex(sig), k = unhex(pub);
+ return ed25519Verify(reinterpret_cast<const uint8_t*>(s.data()), msg.data(), msg.size(),
+ reinterpret_cast<const uint8_t*>(k.data()));
+}
+
+// A throwaway key made for these tests with `openssl genpkey -algorithm ed25519` (its private half was deleted);
+// the release key is a different one.
+const char* kTestKey = "8fc8ddda8872fb72046720804a580631de32313bbfcd8bdeb6643b07f7f28f9b";
+// `openssl pkeyutl -sign -rawin` over kSums with that key.
+const char* kSumsSig = "7271a9be01ee009bf04ba28f25565ef8e8d330805b7815ffc191b562160f9c17"
+ "0262079ecbeb03c720243feb54d46cafbc2ace96af88d7dcc68afed8d9354b08";
+const char* kPackageSha = "7176548d1467e12004d6e347ab751951139b1f34afd56bf9985d0edd26939ac8";
+const std::string kSums = std::string(kPackageSha) + " SculptForge-99.0.0-x86_64.AppImage\n" + kPackageSha +
+ " SculptForge-linux-x86_64.AppImage\n" + kPackageSha + " SculptForge-99.0.0-windows-x86_64.zip\n" +
+ std::string(64, '0') + " SHA256SUMS-other.txt\n";
+
+std::string package() { // what kPackageSha is the hash of (124000 bytes)
+ std::string p;
+ char line[64];
+ for (int i = 0; i < 4000; ++i) {
+ std::snprintf(line, sizeof line, "SculptForge test package %05d\n", i);
+ p += line;
+ }
+ return p;
+}
+
+std::string readAll(const fs::path& p) {
+ std::ifstream f(p, std::ios::binary);
+ return std::string(std::istreambuf_iterator<char>(f), {});
+}
+
+void writeAll(const fs::path& p, const std::string& s) { std::ofstream(p, std::ios::binary | std::ios::trunc) << s; }
+
+// Serves release files from a map, in 4 KiB pieces, like the network would; records every URL asked for.
+struct FakeReleases {
+ std::map<std::string, std::string> files; // file name -> body
+ std::vector<std::string> asked;
+ uint64_t claimTotal = 0; // a Content-Length that differs from the body (a cut-short download)
+ Fetch fetch() {
+ return [this](const std::string& url, const std::function<bool(const char*, size_t)>& onData,
+ const std::function<bool(uint64_t, uint64_t)>& onProgress) {
+ asked.push_back(url);
+ FetchResult r;
+ if (!isReleaseDownloadUrl(url)) {
+ r.error = "refused";
+ return r;
+ }
+ const auto it = files.find(url.substr(url.rfind('/') + 1));
+ if (it == files.end()) {
+ r.status = 404;
+ return r;
+ }
+ r.status = 200;
+ const std::string& body = it->second;
+ const uint64_t total = claimTotal && it->first.find("AppImage") != std::string::npos ? claimTotal : body.size();
+ if (!onProgress(0, total)) return r;
+ for (size_t i = 0; i < body.size(); i += 4096) {
+ const size_t n = std::min<size_t>(4096, body.size() - i);
+ if (!onData(body.data() + i, n) || !onProgress(i + n, total)) {
+ r.error = "stopped";
+ return r;
+ }
+ }
+ return r;
+ };
+ }
+};
+
+struct Sandbox {
+ fs::path dir;
+ Install install;
+ std::string note;
+ explicit Sandbox(const char* name) {
+ dir = tempPath(name);
+ std::error_code ec;
+ fs::remove_all(dir, ec);
+ fs::create_directories(dir / "Apps");
+ fs::create_directories(dir / "prefs");
+ writeAll(dir / "Apps" / "SculptForge.AppImage", "old version");
+ install.kind = InstallKind::AppImage;
+ install.target = (dir / "Apps" / "SculptForge.AppImage").string();
+ install.asset = "SculptForge-linux-x86_64.AppImage";
+ note = (dir / "prefs" / "update_pending.json").string();
+ }
+ ~Sandbox() {
+ std::error_code ec;
+ fs::remove_all(dir, ec);
+ }
+ size_t filesIn(const char* sub) const {
+ size_t n = 0;
+ for (const auto& e : fs::directory_iterator(dir / sub)) n += e.is_regular_file();
+ return n;
+ }
+};
+
+FakeReleases goodRelease() {
+ FakeReleases f;
+ f.files["SHA256SUMS.txt"] = kSums;
+ f.files["SHA256SUMS.txt.sig"] = unhex(kSumsSig);
+ f.files["SculptForge-99.0.0-x86_64.AppImage"] = package();
+ return f;
+}
+
+void download(Sandbox& s, FakeReleases& f, Download& d, const char* key = kTestKey) {
+ uint8_t k[32];
+ CHECK(parseHexKey(key, k));
+ downloadUpdate("99.0.0", s.install, k, f.fetch(), d);
+ CHECK(d.done);
+}
+
+} // namespace
+
+TEST(self_update_sha_vectors) {
+ CHECK(sha512Hex("abc") == "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"
+ "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
+ // Lengths around the block and padding edges (hashlib's digests).
+ const std::map<size_t, std::string> expect = {
+ {0, "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"},
+ {111, "3dfde1184fd99f233f98be4250f4edb9b535157909b668334370742204d97e047f1fd6a74bb5ba447f337286f421d9af957811f7ef62a458771457da126cb65e"},
+ {112, "acc96c509e6d01787330a4c6a241e2cda9dcc2529dbe4288dbbcc3812133233c4698831127cf6ed0b333632b22715a5ce53a0a1002a684367b71c98aa6d1d900"},
+ {128, "31f33a52b36dc2e70c83b604fa999a5cabf33bf70e4556fbed7bff10870c1b7b241dd3f15d1ade24599f068fc58ab51e0028b0f0c98895c23358e8dee032ce06"},
+ {239, "d5e023834c68aeb6e8eef9619ed5fb6fd8b3df796b49d18dce5f6fae76f3f6cae8ddf055611c4031bf5fe6aa68708360f5de1fe69a77055eb55612c5509d5e19"},
+ {1000, "76f1e766ac03deff8c614780dc1f26825ad762f92fbba09e2552cd70b2d6333816e7edec5d8820e8460601ea18d55b4fb154528db99a0bf17670f15f74c82cb7"}};
+ for (const auto& [n, hex] : expect) {
+ std::string m;
+ for (size_t i = 0; i < n; ++i) m += char((i * 7 + 1) & 255);
+ CHECK(sha512Hex(m) == hex);
+ // The streaming SHA-256 agrees with the one-shot one, whatever the pieces.
+ Sha256 h;
+ for (size_t i = 0; i < n; i += 37) h.update(m.data() + i, std::min<size_t>(37, n - i));
+ CHECK(h.hex() == sha256Hex(m));
+ }
+}
+
+TEST(self_update_ed25519_rfc8032) {
+ // RFC 8032 section 7.1, tests 1 to 3.
+ CHECK(verifyHex("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
+ "", "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"));
+ CHECK(verifyHex("92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
+ unhex("72"), "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"));
+ CHECK(verifyHex("6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a",
+ unhex("af82"), "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025"));
+ // The wrong message, a changed signature, the wrong key.
+ CHECK(!verifyHex("92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
+ unhex("73"), "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"));
+ CHECK(!verifyHex("92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c01",
+ unhex("72"), "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"));
+ CHECK(!verifyHex("92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
+ unhex("72"), "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"));
+ // S at or above the group order is refused (RFC 8032 5.1.7), even when R would otherwise match: S + L.
+ CHECK(!verifyHex("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155"
+ "4c8c7872aa064e049dbb3013fbf29380d25bf5f0595bbe24655141438e7a101b",
+ "", "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"));
+ // The signed sums of the tests below.
+ CHECK(verifyHex(kSumsSig, kSums, kTestKey));
+}
+
+TEST(self_update_urls) {
+ CHECK(releaseFileUrl("0.12.0", "SHA256SUMS.txt") ==
+ "https://github.com/islandmed/SculptForge/releases/download/v0.12.0/SHA256SUMS.txt");
+ CHECK(releaseFileUrl("0.12.0-beta.1", "SculptForge-linux-x86_64.AppImage") ==
+ "https://github.com/islandmed/SculptForge/releases/download/v0.12.0-beta.1/SculptForge-linux-x86_64.AppImage");
+ for (const char* v : {"", "../0.12", "0.12/../../x", "0.12.0?x=1", "0.12.0#x", "v0.12", "0.12.0 ", "0.12..0", "0.12%2f"})
+ CHECK(releaseFileUrl(v, "SHA256SUMS.txt").empty());
+ CHECK(releaseFileUrl("0.12.0", "../SHA256SUMS.txt").empty());
+ CHECK(releaseFileUrl("0.12.0", "a/b").empty());
+
+ CHECK(allowedUpdateUrl("https://github.com/islandmed/SculptForge/releases/download/v0.12.0/SHA256SUMS.txt"));
+ CHECK(allowedUpdateUrl("https://release-assets.githubusercontent.com/github-production-release-asset/1/2?sp=r&sig=x"));
+ CHECK(allowedUpdateUrl("https://objects.githubusercontent.com/github-production-release-asset-2e65be/1/2?X-Amz=1"));
+ for (const char* u : {
+ "http://github.com/islandmed/SculptForge/releases/download/v0.12.0/SHA256SUMS.txt", // not https
+ "https://github.com.evil.example/islandmed/SculptForge/releases/download/v1/x", // lookalike host
+ "https://[email protected]/islandmed/SculptForge/releases/download/v1/x", // user info
+ "https://github.com:8443/islandmed/SculptForge/releases/download/v1/x", // a port
+ "https://github.com/islandmed/SculptForgeX/releases/download/v1/x", // another repo
+ "https://github.com/someone/SculptForge/releases/download/v1/x", // a fork
+ "https://github.com/islandmed/SculptForge/releases/download/v1/../../../evil/x", // climbing out
+ "https://github.com/islandmed/SculptForge/releases/download/v1/x?y", // a query
+ "https://github.com/islandmed/SculptForge/releases/download/v1/a/b", // deeper
+ "https://github.com/islandmed/SculptForge/releases/download/v1/%2e%2e", // escapes
+ "https://github.com/islandmed/SculptForge/archive/main.zip", // not a release file
+ "https://evil.githubusercontent.com/x", // another subdomain
+ "https://objects.githubusercontent.com.evil.example/x", //
+ "https://raw.githubusercontent.com/islandmed/SculptForge/main/x", // anyone's files
+ "https://sculptforge.app/SculptForge.AppImage", //
+ "file:///etc/passwd", ""})
+ CHECK(!allowedUpdateUrl(u));
+}
+
+TEST(self_update_redirects_checked_every_hop) {
+ const std::string start = "https://github.com/islandmed/SculptForge/releases/download/v1.0.0/SHA256SUMS.txt";
+ std::vector<std::string> asked;
+ auto server = [&](std::map<std::string, std::string> redirects) {
+ return [&asked, redirects](const std::string& url, std::string& location) {
+ asked.push_back(url);
+ ai::HttpResponse r;
+ const auto it = redirects.find(url);
+ if (it != redirects.end()) {
+ r.status = 302;
+ location = it->second;
+ } else {
+ r.status = 200;
+ }
+ return r;
+ };
+ };
+ // GitHub's own redirect is followed.
+ ai::HttpResponse r = ai::followRedirects(start, allowedUpdateUrl,
+ server({{start, "https://release-assets.githubusercontent.com/a?b=c"}}));
+ CHECK(r.status == 200 && r.error.empty() && asked.size() == 2);
+ // A redirect anywhere else is refused before it is requested (also plain http, and a second hop away).
+ for (const char* evil : {"https://evil.example/x", "http://release-assets.githubusercontent.com/a",
+ "https://github.com/someone/SculptForge/releases/download/v1/x"}) {
+ asked.clear();
+ r = ai::followRedirects(start, allowedUpdateUrl, server({{start, evil}}));
+ CHECK(r.error.find("refused") != std::string::npos && asked.size() == 1);
+ }
+ asked.clear();
+ const std::string cdn = "https://release-assets.githubusercontent.com/a";
+ r = ai::followRedirects(start, allowedUpdateUrl, server({{start, cdn}, {cdn, "https://evil.example/y"}}));
+ CHECK(!r.error.empty() && asked.size() == 2);
+ // A first URL that isn't allowed is never requested at all, and endless redirects end.
+ asked.clear();
+ r = ai::followRedirects("https://evil.example/SHA256SUMS.txt", allowedUpdateUrl, server({}));
+ CHECK(!r.error.empty() && asked.empty());
+ r = ai::followRedirects(start, allowedUpdateUrl, server({{start, start}}));
+ CHECK(r.error == "too many redirects");
+ // The real client refuses a disallowed URL without sending anything.
+ const uint64_t before = ai::httpRequestCount();
+ r = ai::httpGetRestricted("https://evil.example/x", allowedUpdateUrl, 5, [](const char*, size_t) { return true; });
+ CHECK(!r.error.empty() && ai::httpRequestCount() == before);
+}
+
+TEST(self_update_sums) {
+ CHECK(sumFor(kSums, "SculptForge-linux-x86_64.AppImage") == kPackageSha);
+ // The versioned names are what's downloaded: an older release's signed sums can't pass for a newer one's.
+ CHECK(versionedAsset("SculptForge-linux-x86_64.AppImage", "0.12.0") == "SculptForge-0.12.0-x86_64.AppImage");
+ CHECK(versionedAsset("SculptForge-linux-arm64.AppImage", "0.12.0-beta.2") == "SculptForge-0.12.0-aarch64.AppImage");
+ CHECK(versionedAsset("SculptForge-windows-x86_64-setup.exe", "1.0.0") == "SculptForge-1.0.0-windows-x86_64.exe");
+ CHECK(versionedAsset("SculptForge-windows-x86_64-portable.zip", "1.0.0") == "SculptForge-1.0.0-windows-x86_64.zip");
+ CHECK(versionedAsset("SculptForge-macos.dmg", "1.0.0").empty());
+ CHECK(sumFor(kSums, "SculptForge-linux-arm64.AppImage").empty());
+ CHECK(sumFor(kSums, "SHA256SUMS").empty()); // whole names only
+ const std::string twice = kSums + std::string(64, 'a') + " SculptForge-linux-x86_64.AppImage\n";
+ CHECK(sumFor(twice, "SculptForge-linux-x86_64.AppImage").empty()); // listed twice: not trusted
+ CHECK(sumFor(std::string(kPackageSha) + " *x.zip\r\n", "x.zip") == kPackageSha); // binary mode, CRLF
+ CHECK(sumFor("zz" + std::string(62, '0') + " x.zip\n", "x.zip").empty());
+}
+
+TEST(self_update_detects_installs) {
+ std::vector<std::string> present;
+ InstallProbe p;
+ p.exists = [&](const std::string& f) { return std::find(present.begin(), present.end(), f) != present.end(); };
+ p.os = "linux", p.arch = "x86_64", p.exePath = "/tmp/.mount_SculptXYZ/usr/bin/sculptforge";
+ p.appImage = "/home/u/Apps/SculptForge.AppImage";
+ present = {p.appImage};
+ Install in = detectInstall(p);
+ CHECK(in.kind == InstallKind::AppImage && in.target == p.appImage && in.asset == "SculptForge-linux-x86_64.AppImage");
+ p.arch = "arm64";
+ CHECK(detectInstall(p).asset == "SculptForge-linux-arm64.AppImage");
+ p.flatpakId = "org.sculptforge.SculptForge";
+ in = detectInstall(p);
+ CHECK(in.kind == InstallKind::PackageManager && in.manager == "Flatpak" && in.command.empty()); // (a file install)
+ p.flatpakId.clear(), p.appImage.clear(), p.exePath = "/usr/bin/sculptforge";
+ present = {"/usr/bin/pacman"};
+ in = detectInstall(p);
+ CHECK(in.kind == InstallKind::PackageManager && in.manager == "pacman" && !in.command.empty());
+ present = {"/usr/bin/dpkg"};
+ in = detectInstall(p);
+ CHECK(in.kind == InstallKind::PackageManager && in.command.empty()); // a downloaded .deb: download the next
+ p.exePath = "/home/u/src/SculptForge/build/sculptforge"; // built from source
+ CHECK(detectInstall(p).kind == InstallKind::None);
+
+ p.os = "windows", p.arch = "x86_64", p.localAppData = "C:\\Users\\u\\AppData\\Local";
+ p.exePath = "C:\\Program Files\\SculptForge\\bin\\sculptforge.exe";
+ present = {(fs::path("C:\\Program Files\\SculptForge") / "Uninstall.exe").string()};
+#if defined(_WIN32)
+ in = detectInstall(p);
+ CHECK(in.kind == InstallKind::WindowsInstaller && in.asset == "SculptForge-windows-x86_64-setup.exe");
+ CHECK(stagingPath(in, "9.0.0").rfind("C:\\Users\\u\\AppData\\Local", 0) == 0);
+ present.clear();
+ in = detectInstall(p);
+ CHECK(in.kind == InstallKind::WindowsPortable && in.asset == "SculptForge-windows-x86_64-portable.zip");
+#endif
+ p.os = "macos", p.exePath = "/Applications/SculptForge.app/Contents/MacOS/sculptforge";
+ present.clear();
+ in = detectInstall(p);
+ CHECK(in.kind == InstallKind::MacApp && in.target == "/Applications/SculptForge.app" && !selfUpdates(in.kind));
+ present = {"/opt/homebrew/Caskroom/sculptforge"};
+ CHECK(detectInstall(p).command == "brew upgrade --cask sculptforge");
+}
+
+TEST(self_update_downloads_and_installs) {
+ Sandbox s("sf_self_update_ok");
+ FakeReleases f = goodRelease();
+ Download d;
+ download(s, f, d);
+ CHECK(d.ok && d.error.empty() && d.sha256 == kPackageSha && d.received == package().size());
+ CHECK(f.asked.size() == 3 && f.asked[2] == releaseFileUrl("99.0.0", "SculptForge-99.0.0-x86_64.AppImage"));
+ CHECK(fs::path(d.staged).parent_path() == fs::path(s.install.target).parent_path()); // next to it: one rename
+ CHECK(readAll(s.install.target) == "old version"); // nothing in place yet
+ std::string error;
+ CHECK(installAppImage(s.install, d, "99.0.0", "1.0.0", s.note, error));
+ CHECK(readAll(s.install.target) == package() && readAll(s.install.target + ".old") == "old version");
+ CHECK(!fs::exists(d.staged));
+#if !defined(_WIN32)
+ CHECK((fs::status(s.install.target).permissions() & fs::perms::owner_exec) != fs::perms::none);
+#endif
+ // The new version's first start counts, and once it is up the backup goes.
+ Pending p;
+ CHECK(checkPendingAtStart(s.note, "99.0.0", p, error) == StartCheck::Counting && p.starts == 1 && p.from == "1.0.0");
+ confirmStarted(s.note);
+ CHECK(!fs::exists(s.note) && !fs::exists(s.install.target + ".old") && readAll(s.install.target) == package());
+ CHECK(checkPendingAtStart(s.note, "99.0.0", p, error) == StartCheck::Nothing);
+}
+
+TEST(self_update_refuses_bad_releases) {
+ struct Case {
+ const char* what;
+ std::function<void(FakeReleases&)> spoil;
+ const char* key;
+ };
+ const std::vector<Case> cases = {
+ {"bad signature", [](FakeReleases& f) { f.files["SHA256SUMS.txt.sig"][5] ^= 1; }, kTestKey},
+ {"sums changed after signing", [](FakeReleases& f) { f.files["SHA256SUMS.txt"][0] = 'f'; }, kTestKey},
+ {"signed by another key", [](FakeReleases&) {}, "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"},
+ {"no signature", [](FakeReleases& f) { f.files.erase("SHA256SUMS.txt.sig"); }, kTestKey},
+ {"short signature", [](FakeReleases& f) { f.files["SHA256SUMS.txt.sig"].resize(63); }, kTestKey},
+ {"bad hash", [](FakeReleases& f) { f.files["SculptForge-99.0.0-x86_64.AppImage"][1000] ^= 1; }, kTestKey},
+ {"truncated", [](FakeReleases& f) { f.files["SculptForge-99.0.0-x86_64.AppImage"].resize(100000); }, kTestKey},
+ {"cut short (Content-Length)", [](FakeReleases& f) { f.claimTotal = package().size() + 10; }, kTestKey},
+ {"too large", [](FakeReleases& f) { f.claimTotal = kMaxPackageBytes + 1; }, kTestKey},
+ {"huge sums", [](FakeReleases& f) { f.files["SHA256SUMS.txt"] += std::string(kMaxSumsBytes, ' '); }, kTestKey},
+ {"an older release's sums", [](FakeReleases& f) { // signed, but naming 98.0.0's files
+ f.files["SHA256SUMS.txt"] = std::string(kPackageSha) + " SculptForge-98.0.0-x86_64.AppImage\n";
+ }, kTestKey},
+ {"package missing", [](FakeReleases& f) { f.files.erase("SculptForge-99.0.0-x86_64.AppImage"); }, kTestKey},
+ };
+ for (const Case& c : cases) {
+ Sandbox s("sf_self_update_bad");
+ FakeReleases f = goodRelease();
+ c.spoil(f);
+ Download d;
+ download(s, f, d, c.key);
+ if (d.ok) std::fprintf(stderr, "self_update_refuses_bad_releases: %s was accepted\n", c.what);
+ CHECK(!d.ok && !d.error.empty() && d.staged.empty());
+ // Nothing written in place, no temporary file left, nothing to install.
+ CHECK(readAll(s.install.target) == "old version" && s.filesIn("Apps") == 1);
+ std::string error;
+ CHECK(!installAppImage(s.install, d, "99.0.0", "1.0.0", s.note, error) && !fs::exists(s.note));
+ CHECK(readAll(s.install.target) == "old version");
+ }
+ // A bad signature stops it before the package is even requested.
+ Sandbox s("sf_self_update_bad_sig");
+ FakeReleases f = goodRelease();
+ f.files["SHA256SUMS.txt.sig"][0] ^= 1;
+ Download d;
+ download(s, f, d);
+ CHECK(f.asked.size() == 2);
+ // No key compiled in yet: the release key's constant parses (once set) or is empty (Update button off).
+ uint8_t k[32];
+ CHECK(std::string(kUpdatePublicKeyHex).empty() || parseHexKey(kUpdatePublicKeyHex, k));
+}
+
+TEST(self_update_cancel_and_tamper) {
+ {
+ Sandbox s("sf_self_update_cancel");
+ FakeReleases f = goodRelease();
+ Download d;
+ d.cancel = true;
+ download(s, f, d);
+ CHECK(!d.ok && d.error == "cancelled" && s.filesIn("Apps") == 1);
+ }
+ // The staged file is checked again when it is installed (it waited on disk until quitting).
+ Sandbox s("sf_self_update_tamper");
+ FakeReleases f = goodRelease();
+ Download d;
+ download(s, f, d);
+ CHECK(d.ok);
+ writeAll(d.staged, "something else");
+ std::string error;
+ CHECK(!installAppImage(s.install, d, "99.0.0", "1.0.0", s.note, error) && !error.empty());
+ CHECK(readAll(s.install.target) == "old version" && !fs::exists(s.note) && s.filesIn("Apps") == 1);
+}
+
+TEST(self_update_rolls_back) {
+ Sandbox s("sf_self_update_rollback");
+ FakeReleases f = goodRelease();
+ Download d;
+ download(s, f, d);
+ std::string error;
+ CHECK(installAppImage(s.install, d, "99.0.0", "1.0.0", s.note, error));
+ // The new version keeps dying before it is up: after kMaxUnconfirmedStarts tries the old one is put back.
+ Pending p;
+ for (int i = 1; i <= kMaxUnconfirmedStarts; ++i)
+ CHECK(checkPendingAtStart(s.note, "99.0.0", p, error) == StartCheck::Counting && p.starts == i);
+ CHECK(checkPendingAtStart(s.note, "99.0.0", p, error) == StartCheck::RolledBack);
+ CHECK(readAll(s.install.target) == "old version" && !fs::exists(s.install.target + ".old") && !fs::exists(s.note));
+ // An explicit rollback (the old app saw the new one exit at once) does the same.
+ Download d2;
+ download(s, f, d2);
+ CHECK(installAppImage(s.install, d2, "99.0.0", "1.0.0", s.note, error));
+ CHECK(readPending(s.note, p) && rollback(p, s.note, error));
+ CHECK(readAll(s.install.target) == "old version" && !fs::exists(s.note));
+ // The old version started instead (the user ran the .old file): the note is dropped, nothing is moved.
+ Download d3;
+ download(s, f, d3);
+ CHECK(installAppImage(s.install, d3, "99.0.0", "1.0.0", s.note, error));
+ CHECK(checkPendingAtStart(s.note, "1.0.0", p, error) == StartCheck::Abandoned && !fs::exists(s.note));
+ CHECK(readAll(s.install.target) == package());
+}
+
+TEST(self_update_windows_helper) {
+ Install in;
+ in.kind = InstallKind::WindowsPortable;
+ in.target = "C:\\Users\\o'brien\\SculptForge";
+ in.asset = "SculptForge-windows-x86_64-portable.zip";
+ Download d;
+ d.staged = in.target + "\\.x.download-9.0.0";
+ d.sha256 = kPackageSha;
+ const std::string s = windowsHelperScript(in, d, 1234, true);
+ CHECK(s.find("$root = 'C:\\Users\\o''brien\\SculptForge'") != std::string::npos); // quoted: no injection
+ CHECK(s.find("Wait-Process -Id 1234") != std::string::npos);
+ CHECK(s.find("Get-FileHash") < s.find("Expand-Archive")); // the hash is checked again before anything changes
+ CHECK(s.find("Expand-Archive") < s.find("Move-Item -LiteralPath $root -Destination $old"));
+ CHECK(s.find("$p.ExitCode -ne 0") != std::string::npos); // rollback when the new one fails
+ in.kind = InstallKind::WindowsInstaller;
+ const std::string i = windowsHelperScript(in, d, 1234, false);
+ CHECK(i.find("\"/S /D=$root\"") != std::string::npos && i.find("Get-FileHash") < i.find("Start-Process"));
+ CHECK(i.find("Start-Process -FilePath $exe") == std::string::npos); // Later: no relaunch
+}
diff --git a/tests/ui/self_update.sfui b/tests/ui/self_update.sfui
new file mode 100644
index 00000000..2fe1e717
--- /dev/null
+++ b/tests/ui/self_update.sfui
@@ -0,0 +1,34 @@
+# One-click update (PanelUpdate.cpp): on an AppImage the banner has Update, which shows the download's progress and
+# Cancel; a package manager's install names its command instead and has no Update. UI tests never download
+# (SF_UPDATE_TEST_INSTALL only works in them), and nothing is sent: no request at all.
+run ui_look look=classic layout=classic
+run new_sphere subdivisions=3
+env SF_UPDATE_FEED $SCRIPT_DIR/data/update_newer.json
+env SF_UPDATE_TEST_INSTALL appimage
+click "Help##palette.help"
+click "Check for updates##help.check_updates"
+wait_idle 20
+expect_text "SculptForge 99.0.0 is available"
+expect "Update##update.update"
+expect "Download"
+shot update-oneclick
+click "Update##update.update"
+expect_text "Downloading the update..."
+expect "Cancel##update.cancel"
+expect_not "Skip this version"
+shot update-oneclick-progress
+click "Cancel##update.cancel"
+expect "Update##update.update"
+expect "Skip this version"
+
+env SF_UPDATE_TEST_INSTALL pacman
+wait 0.2
+expect_text "Update with your package manager (pacman)"
+expect "Copy##update.copy"
+expect_not "Update##update.update"
+shot update-package-manager
+click "Copy##update.copy"
+expect_clipboard "yay -Syu sculptforge"
+click "Later"
+expect_not "Skip this version"
+expect_value http_requests == 0