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.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Member builds in the app: GitHub device-flow sign-in, OS keychain, member releases verified like public ones
islandmedcb6a605fb632
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 13b188d7..445d3d78 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -274,24 +274,7 @@ jobs:- 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 ]+ run: tools/release/sign_sums.sh dist- name: Release notes from CHANGELOGrun: |section=${TAG#v}diff --git a/CMakeLists.txt b/CMakeLists.txtindex 286bdc8b..84027b17 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -85,6 +85,8 @@ add_library(sculptforge_core STATICsrc/core/Sha256.cppsrc/core/Ed25519.cppsrc/core/SelfUpdate.cpp+ src/core/MemberBuilds.cpp+ src/core/Keychain.cppsrc/core/BrushGallery.cppsrc/core/VertexPaint.cppsrc/core/PaintLayer.cpp@@ -214,6 +216,9 @@ else()endif()find_package(Threads REQUIRED)target_link_libraries(sculptforge_core PUBLIC glm::glm Threads::Threads)+if(UNIX AND NOT APPLE)+ target_link_libraries(sculptforge_core PRIVATE ${CMAKE_DL_LIBS}) # core/Keychain.cpp: libsecret, loaded at run time+endif()# zstd for Focus Detail tiles (core/FocusDetail.h), when the system has it; without it the tiles use our own codec.# Not on macOS: Homebrew's zstd is single-architecture and breaks the universal (x86_64 + arm64) build.find_package(PkgConfig QUIET)diff --git a/changes/feat-one-click-update.md b/changes/feat-one-click-update.mdindex 84cc84ec..40b62649 100644--- a/changes/feat-one-click-update.md+++ b/changes/feat-one-click-update.md@@ -3,6 +3,8 @@ whats_new: **One-click update**: on the Linux AppImage and on Windows (installerhas an **Update** button: it downloads the new version in the background, checks its signature and checksum, andinstalls it on **Restart now** or when you quit (**Later**). The old version is kept until the new one hasstarted, and put back if it doesn't. Package-manager installs show what to run instead.+whats_new: **Member builds in the app**: members sign in with GitHub in **Edit > Preferences > Updates > Member+ builds** (a code to enter on github.com/login/device) and get the early builds through the same Update button.highlight: One-click update, signed and checkedadded: **One-click update** (the update banner's **Update** button) for the Linux AppImage and the Windows installerand portable zip: background download with progress and Cancel, then Restart now or Later (installs at quit).@@ -12,6 +14,10 @@ added: **One-click update** (the update banner's **Update** button) for the Linufile 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.+added: **Member builds** (Preferences > Updates): GitHub sign-in with the device flow for the "SculptForge Member+ Builds" app, which can only read the member repository's releases; the token lives in the OS keychain (Windows+ Credential Manager, Secret Service on Linux; macOS later), never in settings or logs, and Sign out removes it.+ The update check then also lists the member releases; they are verified exactly like public ones.security: Release checksums (SHA256SUMS.txt) are now signed with Ed25519 (SHA256SUMS.txt.sig, a 64-byte rawsignature); the release workflow checks the signing secret against the key compiled into the app.testers:@@ -22,6 +28,8 @@ testers:`<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 newversion starts.+ - Member: Preferences > Updates > Sign in with GitHub, enter the code on github.com/login/device; "Signed in as"+ shows your login; Check for updates offers the newest member build; Sign out, restart: still signed out.- 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 indiff --git a/docs/design/one-click-update.md b/docs/design/one-click-update.mdindex 6880963c..ff49ea9a 100644--- a/docs/design/one-click-update.md+++ b/docs/design/one-click-update.md@@ -61,10 +61,29 @@ Developer ID and notarization: download the `.dmg` (same chain), `hdiutil attach`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)+## Member builds (src/core/MemberBuilds.*, src/core/Keychain.*)-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).+Membership = read access to the private repository islandmed/sculptforge-insiders (where betas are published). No+server of ours.++- **Sign-in**: GitHub's device flow for the GitHub App "SculptForge Member Builds" (client ID `Iv23liK7goArrLDUGKEk`,+ compiled in; public). The app is installed only on sculptforge-insiders with Contents: read (+ Metadata), so its+ user-to-server token reaches only repositories both the app and the user can access: that one, read-only. No client+ secret (device flow and its refresh need none); the app's private key exists only because GitHub requires one and+ is never used. POSTs go to exactly `github.com/login/device/code` and `github.com/login/oauth/access_token`, no+ redirects followed. The page the user opens is fixed (`github.com/login/device`); an answer naming another is refused.+- **Membership check**: after sign-in, `GET /repos/islandmed/sculptforge-insiders/releases`: 200 = member; 403/404 =+ not a member, and the token is dropped, never stored.+- **Token storage**: OS keychain only (Windows Credential Manager `SculptForge/member-builds`; Secret Service via+ libsecret, loaded at run time; macOS Keychain to follow). No keychain: in memory until quit. Never in the+ preferences (they hold only "signed in" and the login name) or logs. Access tokens expire (8 h); the refresh token is+ single-use, so each refresh stores the new pair at once, under a mutex. A refused refresh or a 401 signs out.+- **Where the token goes**: only to the member API URLs (`api.github.com/repos/islandmed/sculptforge-insiders/releases`,+ `.../releases/assets/<number>`, `api.github.com/user`), checked per hop; never to the asset host a redirect points at.+- **Same verification**: a member build's SHA256SUMS.txt, .sig and package are fetched as assets of its release; the+ same Ed25519 key, the same versioned file name, hash, size cap and install path as public releases. release.yml signs+ the betas' sums with the same step (tools/release/sign_sums.sh).+- **Sign out**: removes the keychain entry and forgets the tokens. (Revoking on GitHub needs the client secret, so the+ user can also revoke at github.com/settings/apps/authorizations.)+- **Network**: the member check runs only inside the update check (daily or Help > Check for updates) and only when+ signed in; sign-in only when clicked; UI tests use a stand-in code and send nothing.diff --git a/docs/guide/installing.md b/docs/guide/installing.mdindex 5362ce58..7b826297 100644--- a/docs/guide/installing.md+++ b/docs/guide/installing.md@@ -232,6 +232,14 @@ kept beside the new one (the AppImage as `<name>.AppImage.old`, the portable folnew version has started once, then removed; if the new version doesn't start, the old one is put back. TheWindows installer asks for permission to change Program Files, as installing does.+**Member builds.** Members get each release early. In **Edit > Preferences > Updates > Member builds**, click+**Sign in with GitHub**: SculptForge shows a short code; open **github.com/login/device**, sign in with the GitHub+account that accepted the invitation to the member repository, and enter the code. From then on the update check+also offers the member builds, and **Update** installs them exactly like releases, with the same signature check.+The sign-in can only read the member repository's releases (nothing else on your GitHub account), it is kept in your+system's keychain (Windows Credential Manager, or the Secret Service on Linux such as GNOME Keyring or KWallet; never+in SculptForge's settings), and **Sign out** removes it. Without a keychain the sign-in lasts until you quit.+Installs that belong to a package manager are never replaced by the app: the AUR package (Omarchy's too) buildswithout 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.diff --git a/src/ai/Http.cpp b/src/ai/Http.cppindex 6428bf19..065a4d19 100644--- a/src/ai/Http.cpp+++ b/src/ai/Http.cpp@@ -54,7 +54,8 @@ std::string multipartBody(const std::vector<MultipartField>& fields, std::stringnamespace {// 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,+HttpResponse getOnce(const std::string& method, const std::string& url, const std::vector<std::string>& headers,+ const std::string& body, int stallSeconds, const std::function<bool(const char*, size_t)>& onData,const std::function<bool(uint64_t, uint64_t)>& onProgress, std::string& location);} // namespace@@ -85,11 +86,37 @@ HttpResponse followRedirects(const std::string& url, const std::function<bool(coHttpResponse 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 httpGetRestricted(url, allowed, {}, stallSeconds, onData, onProgress);+}++HttpResponse httpGetRestricted(const std::string& url, const std::function<bool(const std::string&)>& allowed,+ const std::function<std::vector<std::string>(const std::string&)>& headersFor,+ 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);+ return getOnce("GET", u, headersFor ? headersFor(u) : std::vector<std::string>{}, {}, stallSeconds, onData,+ onProgress, location);});}+HttpResponse httpPostNoRedirect(const std::string& url, const std::vector<std::string>& headers, const std::string& body,+ int timeoutSeconds) {+ std::string received, location;+ HttpResponse r;+ if (url.rfind("https://", 0) != 0) {+ r.error = "refused to send to " + url.substr(0, 200);+ return r;+ }+ r = getOnce("POST", url, headers, body, timeoutSeconds, [&](const char* d, size_t n) {+ if (received.size() + n > (1u << 20)) return false; // (a sign-in answer is a few hundred bytes)+ received.append(d, n);+ return true;+ }, {}, location);+ if (r.status >= 300 && r.status < 400 && r.error.empty()) r.error = "unexpected redirect";+ r.body = std::move(received);+ return r;+}+#if defined(_WIN32)namespace {@@ -187,7 +214,8 @@ std::string narrow(const std::wstring& w) {return s;}-HttpResponse getOnce(const std::string& url, int stallSeconds, const std::function<bool(const char*, size_t)>& onData,+HttpResponse getOnce(const std::string& method, const std::string& url, const std::vector<std::string>& headers,+ const std::string& body, 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;@@ -218,7 +246,7 @@ HttpResponse getOnce(const std::string& url, int stallSeconds, const std::functir.error = lastError("WinHttpConnect");return r;}- Handle request{WinHttpOpenRequest(connection.h, L"GET", fullPath.c_str(), nullptr, WINHTTP_NO_REFERER,+ Handle request{WinHttpOpenRequest(connection.h, widen(method).c_str(), fullPath.c_str(), nullptr, WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE)};if (!request.h) {r.error = lastError("WinHttpOpenRequest");@@ -227,7 +255,11 @@ HttpResponse getOnce(const std::string& url, int stallSeconds, const std::functiDWORD never = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; // each hop is checked by the callerWinHttpSetOption(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) ||+ std::wstring allHeaders;+ for (const auto& h : headers) allHeaders += widen(h) + L"\r\n";+ if (!WinHttpSendRequest(request.h, allHeaders.empty() ? WINHTTP_NO_ADDITIONAL_HEADERS : allHeaders.c_str(), DWORD(-1L),+ body.empty() ? WINHTTP_NO_REQUEST_DATA : const_cast<char*>(body.data()), DWORD(body.size()),+ DWORD(body.size()), 0) ||!WinHttpReceiveResponse(request.h, nullptr)) {r.error = lastError("HTTP request");return r;@@ -244,7 +276,7 @@ HttpResponse getOnce(const std::string& url, int stallSeconds, const std::functilocation = narrow(loc);return r;}- if (status != 200) return r;+ if (status != 200 && method == "GET") return r; // (a POST's error answer is read: it says why)uint64_t total = 0, received = 0;wchar_t len[32] = {};DWORD lenSize = sizeof len;@@ -346,6 +378,7 @@ struct RestrictedSink {CURL* curl;const std::function<bool(const char*, size_t)>* onData;const std::function<bool(uint64_t, uint64_t)>* onProgress;+ bool anyAnswer = false; // a POST's error answer is read too (it says why)bool stopped = false;};@@ -357,7 +390,7 @@ bool finalAnswer(CURL* curl) {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->anyAnswer && !finalAnswer(sink->curl)) return size * count; // a redirect's or an error's bodyif (!(*sink->onData)(data, size * count)) {sink->stopped = true;return 0;@@ -373,7 +406,8 @@ int restrictedProgress(void* user, curl_off_t total, curl_off_t now, curl_off_t,return 1;}-HttpResponse getOnce(const std::string& url, int stallSeconds, const std::function<bool(const char*, size_t)>& onData,+HttpResponse getOnce(const std::string& method, const std::string& url, const std::vector<std::string>& headers,+ const std::string& body, 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;@@ -384,9 +418,17 @@ HttpResponse getOnce(const std::string& url, int stallSeconds, const std::functir.error = "curl_easy_init failed";return r;}- RestrictedSink sink{curl, &onData, &onProgress};+ RestrictedSink sink{curl, &onData, &onProgress, method == "POST"};+ curl_slist* list = nullptr;+ for (const auto& h : headers) list = curl_slist_append(list, h.c_str());curl_easy_setopt(curl, CURLOPT_URL, url.c_str());- curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);+ if (method == "POST") {+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.data());+ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, long(body.size()));+ } else {+ curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);+ }#if LIBCURL_VERSION_NUM >= 0x075500curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, "https");#else@@ -412,6 +454,7 @@ HttpResponse getOnce(const std::string& url, int stallSeconds, const std::functichar* target = nullptr;if (r.status >= 300 && r.status < 400 && curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &target) == CURLE_OK && target)location = target;+ curl_slist_free_all(list);curl_easy_cleanup(curl);return r;}@@ -430,8 +473,9 @@ HttpResponse httpRequestStream(const std::string&, const std::string&, const stdnamespace {-HttpResponse getOnce(const std::string&, int, const std::function<bool(const char*, size_t)>&,- const std::function<bool(uint64_t, uint64_t)>&, std::string&) {+HttpResponse getOnce(const std::string&, const std::string&, const std::vector<std::string>&, 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)";diff --git a/src/ai/Http.h b/src/ai/Http.hindex 00f4e591..a56364aa 100644--- a/src/ai/Http.h+++ b/src/ai/Http.h@@ -36,6 +36,15 @@ HttpResponse httpRequestStream(const std::string& method, const std::string& urlHttpResponse 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 = {});+// The same with headers chosen per hop: `headersFor(url)` (credentials only to the host they belong to, never to+// the place a redirect points at).+HttpResponse httpGetRestricted(const std::string& url, const std::function<bool(const std::string& url)>& allowed,+ const std::function<std::vector<std::string>(const std::string& url)>& headersFor,+ int stallSeconds, const std::function<bool(const char* data, size_t size)>& onData,+ const std::function<bool(uint64_t received, uint64_t total)>& onProgress = {});+// A POST to exactly `url` (https, certificates checked, no redirects followed): sign-in endpoints.+HttpResponse httpPostNoRedirect(const std::string& url, const std::vector<std::string>& headers, const std::string& body,+ int timeoutSeconds);// 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);diff --git a/src/app/App.h b/src/app/App.hindex 7c864822..209d0295 100644--- a/src/app/App.h+++ b/src/app/App.h@@ -1275,6 +1275,8 @@ private:bool ok = false;UpdateInfo info;std::string error;+ std::string memberError; // the member check's problem (the public check may still have worked)+ bool memberSignedOut = false; // the sign-in ran out or was revoked: signed out};void startUpdateCheck(bool manual);void pollUpdateCheck();@@ -1313,6 +1315,23 @@ private:double confirmStartAt_ = 0.0; // > 0: this version was just installed; confirmed once it has run this longstd::shared_ptr<ai::ChildProcess> restartChild_;double restartDeadline_ = 0.0;+ // Member builds (PanelUpdate.cpp, core/MemberBuilds.h): GitHub sign-in (device flow) in Preferences > Updates;+ // the update check then also lists the member repository's releases. The token is in the OS keychain only.+ struct MemberAuth; // the tokens, shared with worker threads+ struct MemberSignIn;+ void drawMemberBuildsSection(); // Preferences > Updates+ // (Worker threads.) Adds the newest member build to the job's answer when it is newer; a usable access token+ // (from the keychain, refreshed when it has run out; false and `signedOut` when the sign-in is gone).+ static void checkMemberBuilds(MemberAuth& auth, UpdateJob& job);+ static bool memberAccessToken(MemberAuth& auth, std::string& token, std::string& error, bool& signedOut);+ void startMemberSignIn();+ void memberSignOut();+ std::shared_ptr<MemberAuth> memberAuth_;+ std::shared_ptr<MemberSignIn> memberSignIn_;+ bool memberBuilds_ = false; // signed in (and the token is in the keychain); saved in the preferences+ std::string memberLogin_; // the GitHub login shown ("Signed in as ..."); saved; not a secret+ bool memberSessionOnly_ = false; // signed in, but no keychain kept it: not saved, gone at quit+ std::string memberStatus_;int autosaveMinutes_ = 5; // 0 = offfloat autosaveTimer_ = 0.0f;uint64_t autosaveRevision_ = ~uint64_t(0);diff --git a/src/app/PanelProject.cpp b/src/app/PanelProject.cppindex a3cc15d1..ac2d8098 100644--- a/src/app/PanelProject.cpp+++ b/src/app/PanelProject.cpp@@ -108,6 +108,8 @@ void App::initProject() {checkUpdates_ = prefs["check_updates"].asBool(checkUpdates_);updateCheckedAt_ = int64_t(prefs["update_checked_at"].asNumber(0));if (prefs["update_skipped"].isString()) updateSkipped_ = prefs["update_skipped"].asString();+ memberBuilds_ = prefs["member_builds"].asBool(false); // (the token itself is in the keychain only)+ if (prefs["member_login"].isString()) memberLogin_ = prefs["member_login"].asString().substr(0, 39);if (prefs["update_channel"].isString())updateChannel_ = prefs["update_channel"].asString() == "preview" ? UpdateChannel::Preview : UpdateChannel::Stable;sculptSeconds_ = addSculptTime(prefs["sculpt_seconds"].asNumber(0.0), 0.0);@@ -191,6 +193,8 @@ void App::saveProjectPrefs() {prefs.set("update_checked_at", double(updateCheckedAt_));if (!updateSkipped_.empty()) prefs.set("update_skipped", updateSkipped_);prefs.set("update_channel", std::string(updateChannel_ == UpdateChannel::Preview ? "preview" : "stable"));+ prefs.set("member_builds", memberBuilds_ && !memberSessionOnly_);+ if (memberBuilds_ && !memberSessionOnly_ && !memberLogin_.empty()) prefs.set("member_login", memberLogin_);prefs.set("sculpt_seconds", std::floor(sculptSeconds_)); // for the one support reminder (Support.h); stays hereprefs.set("support_reminder_done", supportReminderDone_);prefs.set("support_card", supportCardPrefs_.enabled); // the support card at launch (Support.h)@@ -725,7 +729,9 @@ void App::startUpdateCheck(bool manual) {std::string source = feed && *feed ? feed : kUpdateFeedUrl;// Detached: a slow network never holds up quitting (the job is shared, so it outlives the app if it must).const UpdateChannel channel = updateChannel_;- std::thread([job, source, channel] {+ // Member builds only when signed in, and never in UI tests (the network).+ const std::shared_ptr<MemberAuth> member = memberBuilds_ && options_.uiTest.empty() ? memberAuth_ : nullptr;+ std::thread([job, source, channel, member] {std::string body;if (source.rfind("https://", 0) == 0 || source.rfind("http://", 0) == 0) {ai::HttpResponse r = ai::httpRequest("GET", source, {"Accept: application/json"}, {}, 15);@@ -739,6 +745,7 @@ void App::startUpdateCheck(bool manual) {else job->error = "can't read " + source;}if (job->error.empty()) job->ok = parseUpdateFeed(body, job->info, job->error, channel);+ if (member) checkMemberBuilds(*member, *job); // (PanelUpdate.cpp)job->done = true;}).detach();}@@ -747,6 +754,13 @@ void App::pollUpdateCheck() {if (!updateJob_ || !updateJob_->done) return;const std::shared_ptr<UpdateJob> job = std::move(updateJob_);updateJob_.reset();+ if (job->memberSignedOut) { // (the token is already gone from the keychain)+ memberBuilds_ = false;+ memberStatus_ = "Your member sign-in has run out: sign in again for member builds.";+ saveProjectPrefs();+ } else if (!job->memberError.empty()) {+ memberStatus_ = "Couldn't check member builds: " + job->memberError;+ }if (!job->ok) {updateStatus_ = "Couldn't check for updates: " + job->error;if (job->manual) status_ = updateStatus_;@@ -840,6 +854,9 @@ void App::drawUpdatesSection() {ui::ActionButton(*this, "help.check_updates", ImVec2(-1, 0));if (updateJob_) ImGui::TextDisabled("%s", tr("Checking..."));else if (!updateStatus_.empty()) ImGui::TextWrapped("%s", updateStatus_.c_str());+#if SF_UPDATE_CHECK+ drawMemberBuildsSection(); // (PanelUpdate.cpp)+#endif}} // namespace sfdiff --git a/src/app/PanelUpdate.cpp b/src/app/PanelUpdate.cppindex 64e3fd23..f091438e 100644--- a/src/app/PanelUpdate.cpp+++ b/src/app/PanelUpdate.cpp@@ -8,12 +8,16 @@#include "app/Ui.h"#include "ai/Http.h"#include "ai/Process.h"+#include "core/Keychain.h"+#include "core/MemberBuilds.h"#include <imgui.h>#include <algorithm>#include <array>+#include <chrono>#include <cstdlib>#include <filesystem>#include <fstream>+#include <mutex>#include <thread>#if defined(_WIN32)#define WIN32_LEAN_AND_MEAN@@ -23,10 +27,50 @@namespace sf {+// The member sign-in's tokens, shared with the worker threads (one refresh at a time: a refresh token works once).+struct App::MemberAuth {+ std::mutex mutex;+ member::Tokens tokens;+ bool loaded = false; // the keychain was read+};++// A sign-in in progress (device flow): the code to show, then the outcome.+struct App::MemberSignIn {+ std::mutex mutex;+ std::string userCode; // shown once GitHub has answered+ int64_t expiresAt = 0;+ std::atomic<bool> cancel{false}, done{false};+ bool ok = false, saved = false;+ std::string login, error;+};+namespace {namespace fs = std::filesystem;+int64_t unixNow() {+ return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();+}++// GET a member API URL with the token (and nothing else); the body when it answered 200.+ai::HttpResponse memberGet(const std::string& url, const std::string& token, size_t cap) {+ std::string body;+ ai::HttpResponse r = ai::httpGetRestricted(+ url, member::isMemberApiUrl, [&token](const std::string& u) { return member::headersFor(u, token); }, 30,+ [&](const char* d, size_t n) {+ if (body.size() + n > cap) return false;+ body.append(d, n);+ return true;+ });+ r.body = std::move(body);+ return r;+}++ai::HttpResponse postGitHub(const char* url, const std::string& body) {+ return ai::httpPostNoRedirect(url, {"Accept: application/json", "Content-Type: application/x-www-form-urlencoded"},+ body, 30);+}+double nowSeconds() { return double(SDL_GetTicksNS()) * 1e-9; }fs::path fsPath(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); }@@ -35,11 +79,16 @@ bool releaseKey(uint8_t key[32]) { return update::parseHexKey(update::kUpdatePubconstexpr double kConfirmAfterSeconds = 5.0; // a new version that has run this long counts as startedconstexpr 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};+// The release files over HTTPS, every hop checked (core/SelfUpdate.h); a member build's token goes only to the+// member API URLs, never to the asset host a redirect points at.+update::Fetch releaseFetcher(std::string token) {+ return [token](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, [&token](const std::string& u) { return member::headersFor(u, token); }, 60,+ onData, onProgress);+ return update::FetchResult{r.status, r.error};+ };}} // namespace@@ -73,6 +122,7 @@ bool App::selfUpdateOffered(const UpdateInfo& u) {}void App::initSelfUpdate() {+ if (!memberAuth_) memberAuth_ = std::make_shared<MemberAuth>();const std::string note = updateNotePath();if (note.empty() || !options_.uiTest.empty()) return;update::Pending p;@@ -99,6 +149,19 @@ void App::initSelfUpdate() {}void App::tickSelfUpdate() {+ if (memberSignIn_ && memberSignIn_->done) {+ const std::shared_ptr<MemberSignIn> job = std::move(memberSignIn_);+ if (job->ok) {+ memberBuilds_ = true;+ memberSessionOnly_ = !job->saved; // (no keychain: signed in until quitting, nothing saved)+ memberLogin_ = job->login;+ memberStatus_ = job->saved ? "" : "Signed in until you quit: this system has no keychain to keep it in.";+ saveProjectPrefs();+ startUpdateCheck(true); // what's there for members now+ } else if (!job->cancel) {+ memberStatus_ = "Couldn't sign in: " + job->error;+ }+ }if (confirmStartAt_ > 0.0 && nowSeconds() >= confirmStartAt_) {confirmStartAt_ = 0.0;update::confirmStarted(updateNotePath()); // (the old version, watching, sees the note go and quits)@@ -153,10 +216,23 @@ void App::startSelfUpdate(const UpdateInfo& u) {}const update::Install install = updateInstall();const std::string version = u.version;+ const std::map<std::string, std::string> files = u.member ? u.files : std::map<std::string, std::string>{};+ const std::shared_ptr<MemberAuth> auth = u.member ? memberAuth_ : nullptr;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();+ std::thread([d, install, version, k, files, auth] {+ std::string token;+ if (auth) {+ bool signedOut = false;+ if (!memberAccessToken(*auth, token, d->error, signedOut) || files.empty()) {+ if (d->error.empty()) d->error = "the member build has no files";+ d->done = true;+ return;+ }+ }+ update::downloadUpdate(version, install, k.data(), releaseFetcher(token), *d, files);+ }).detach();}bool App::installSelfUpdate(bool relaunch, std::string& error) {@@ -302,4 +378,210 @@ bool App::drawSelfUpdate(const UpdateInfo& u, bool& close) {return false;}+// --- Member builds ---++bool App::memberAccessToken(MemberAuth& auth, std::string& token, std::string& error, bool& signedOut) {+ std::lock_guard<std::mutex> lock(auth.mutex);+ if (!auth.loaded) {+ auth.loaded = true;+ std::string secret;+ if (keychain::load(member::kKeychainAccount, secret)) member::tokensFromSecret(secret, auth.tokens);+ }+ const int64_t now = unixNow();+ if (!auth.tokens.usable(now)) {+ if (!auth.tokens.refreshable(now)) {+ signedOut = true;+ auth.tokens = {};+ keychain::erase(member::kKeychainAccount);+ error = "signed out";+ return false;+ }+ const ai::HttpResponse r = postGitHub(member::kTokenUrl, member::refreshBody(auth.tokens.refresh));+ if (!r.error.empty() || r.status != 200) { // (no answer: try again next time; the refresh token is unused)+ error = r.error.empty() ? "GitHub answered " + std::to_string(r.status) : r.error;+ return false;+ }+ member::Tokens fresh;+ switch (member::parseTokenReply(r.body, now, fresh, error)) {+ case member::TokenReply::Ok:+ auth.tokens = fresh;+ keychain::store(member::kKeychainAccount, member::tokensToSecret(fresh)); // (the old refresh token is spent)+ break;+ case member::TokenReply::Expired:+ case member::TokenReply::Denied:+ signedOut = true;+ auth.tokens = {};+ keychain::erase(member::kKeychainAccount);+ error = "signed out";+ return false;+ default:+ if (error.empty()) error = "GitHub didn't renew the sign-in";+ return false;+ }+ }+ token = auth.tokens.access;+ return true;+}++void App::checkMemberBuilds(MemberAuth& auth, UpdateJob& job) {+ std::string token, error;+ bool signedOut = false;+ if (!memberAccessToken(auth, token, error, signedOut)) {+ job.memberSignedOut = signedOut;+ if (!signedOut) job.memberError = error;+ return;+ }+ const ai::HttpResponse r = memberGet(member::kReleasesUrl, token, 4u << 20);+ if (r.status == 401) { // revoked (or the app was uninstalled from the repository)+ std::lock_guard<std::mutex> lock(auth.mutex);+ auth.tokens = {};+ keychain::erase(member::kKeychainAccount);+ job.memberSignedOut = true;+ return;+ }+ if (r.status != 200) {+ job.memberError = r.status == 404 || r.status == 403 ? "this GitHub account has no access to member builds"+ : r.error.empty() ? "GitHub answered " + std::to_string(r.status) : r.error;+ return;+ }+ UpdateInfo best;+ if (!member::parseMemberReleases(r.body, best, error)) return; // (no member build yet: nothing to offer)+ if (!job.ok || compareVersions(best.version, job.info.version) > 0) {+ job.info = std::move(best);+ job.ok = true;+ job.error.clear();+ }+}++void App::startMemberSignIn() {+ if (memberSignIn_ && !memberSignIn_->done) return;+ if (!memberAuth_) memberAuth_ = std::make_shared<MemberAuth>();+ auto job = std::make_shared<MemberSignIn>();+ memberSignIn_ = job;+ memberStatus_.clear();+ if (!options_.uiTest.empty()) { // UI tests: the code screen, no network+ job->userCode = "TEST-CODE";+ job->expiresAt = unixNow() + 900;+ return;+ }+ const std::shared_ptr<MemberAuth> auth = memberAuth_;+ std::thread([job, auth] {+ struct Done {+ MemberSignIn& j;+ ~Done() { j.done = true; }+ } done{*job};+ ai::HttpResponse r = postGitHub(member::kDeviceCodeUrl, member::deviceCodeBody());+ member::DeviceCode code;+ if (r.status != 200 || !member::parseDeviceCode(r.body, unixNow(), code, job->error)) {+ if (job->error.empty()) job->error = r.error.empty() ? "GitHub answered " + std::to_string(r.status) : r.error;+ return;+ }+ {+ std::lock_guard<std::mutex> lock(job->mutex);+ job->userCode = code.userCode;+ job->expiresAt = code.expiresAt;+ }+ int interval = code.interval;+ member::Tokens tokens;+ while (true) { // GitHub's pace: one poll per interval until the user has entered the code (or not)+ for (int i = 0; i < interval * 10; ++i) {+ if (job->cancel) return;+ std::this_thread::sleep_for(std::chrono::milliseconds(100));+ }+ if (unixNow() >= code.expiresAt) {+ job->error = "the code ran out: sign in again";+ return;+ }+ r = postGitHub(member::kTokenUrl, member::pollBody(code.deviceCode));+ if (!r.error.empty()) continue; // (a dropped connection: the next poll)+ const member::TokenReply reply = member::parseTokenReply(r.body, unixNow(), tokens, job->error);+ if (reply == member::TokenReply::Ok) break;+ if (reply == member::TokenReply::Pending) continue;+ if (reply == member::TokenReply::SlowDown) {+ interval += 5;+ continue;+ }+ if (reply == member::TokenReply::Expired) job->error = "the code ran out: sign in again";+ else if (reply == member::TokenReply::Denied) job->error = "the sign-in was declined on GitHub";+ return;+ }+ // Signed in to GitHub; a member is one who can see the member repository's releases.+ r = memberGet(member::kReleasesUrl, tokens.access, 4u << 20);+ if (r.status != 200) {+ job->error = r.status == 404 || r.status == 403+ ? "this GitHub account has no access to member builds (Insider or Studio membership, "+ "with the invitation to the member repository accepted)"+ : r.error.empty() ? "GitHub answered " + std::to_string(r.status) : r.error;+ return; // (the token is dropped)+ }+ r = memberGet(member::kUserUrl, tokens.access, 64u << 10);+ if (r.status == 200) job->login = member::parseLogin(r.body);+ job->saved = keychain::store(member::kKeychainAccount, member::tokensToSecret(tokens));+ {+ std::lock_guard<std::mutex> lock(auth->mutex);+ auth->tokens = tokens;+ auth->loaded = true;+ }+ job->ok = true;+ }).detach();+}++void App::memberSignOut() {+ if (memberSignIn_) memberSignIn_->cancel = true;+ memberSignIn_.reset();+ memberBuilds_ = memberSessionOnly_ = false;+ memberLogin_.clear();+ memberStatus_ = "Signed out.";+ saveProjectPrefs();+ const std::shared_ptr<MemberAuth> auth = memberAuth_;+ if (auth) {+ std::lock_guard<std::mutex> lock(auth->mutex);+ auth->tokens = {};+ auth->loaded = true; // (nothing more to read)+ }+ if (options_.uiTest.empty()) std::thread([] { keychain::erase(member::kKeychainAccount); }).detach();+}++void App::drawMemberBuildsSection() {+ ImGui::Spacing();+ ImGui::SeparatorText(tr("Member builds"));+ ui::HelpText("Member builds", nullptr,+ "Insider and Studio members get each release early. Sign in with the GitHub account that has the "+ "invitation to the member repository: SculptForge then also offers the member builds, checked with "+ "the same signature as every release. The sign-in can only read that repository's releases; it is "+ "kept in your system's keychain and Sign out removes it.",+ "Preferences > Updates");+ const bool signedIn = memberBuilds_;+ if (memberSignIn_) {+ std::string code;+ {+ std::lock_guard<std::mutex> lock(memberSignIn_->mutex);+ code = memberSignIn_->userCode;+ }+ if (code.empty()) {+ ImGui::TextDisabled("%s", tr("Asking GitHub..."));+ } else {+ ImGui::TextWrapped("%s", tr("On GitHub, enter this code:"));+ if (ImFont* big = guide_.bodyBoldFont()) ImGui::PushFont(big);+ ImGui::TextUnformatted(code.c_str());+ if (guide_.bodyBoldFont()) ImGui::PopFont();+ ImGui::SameLine();+ if (ImGui::Button(tr("Copy##member.copy"))) SDL_SetClipboardText(code.c_str());+ if (ImGui::Button(tr("Open github.com/login/device##member.open"))) SDL_OpenURL(member::kVerifyUrl);+ ImGui::TextDisabled("%s", tr("Waiting for GitHub..."));+ }+ if (ImGui::Button(tr("Cancel##member.cancel"))) {+ memberSignIn_->cancel = true;+ if (!options_.uiTest.empty()) memberSignIn_->done = true;+ }+ } else if (signedIn) {+ if (memberLogin_.empty()) ImGui::TextUnformatted(tr("Signed in with GitHub."));+ else ImGui::Text(tr("Signed in as %s on GitHub."), memberLogin_.c_str());+ if (ImGui::Button(tr("Sign out##member.sign_out"))) memberSignOut();+ } else {+ if (ImGui::Button(tr("Sign in with GitHub##member.sign_in"))) startMemberSignIn();+ }+ if (!memberStatus_.empty()) ImGui::TextWrapped("%s", memberStatus_.c_str());+}+} // namespace sfdiff --git a/src/core/Keychain.cpp b/src/core/Keychain.cppnew file mode 100644index 00000000..ebc40a2e--- /dev/null+++ b/src/core/Keychain.cpp@@ -0,0 +1,166 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/Keychain.h"++#include <cstring>++#if defined(_WIN32)+#define WIN32_LEAN_AND_MEAN+#define NOMINMAX+#include <windows.h>+#include <wincred.h>+#elif defined(__linux__)+#include <dlfcn.h>+#include <mutex>+#endif++namespace sf::keychain {++#if defined(_WIN32)++namespace {++std::wstring target(const std::string& account) {+ const std::string t = "SculptForge/" + account;+ return std::wstring(t.begin(), t.end()); // (ASCII account names only)+}++} // namespace++bool store(const std::string& account, const std::string& secret) {+ if (secret.size() > CRED_MAX_CREDENTIAL_BLOB_SIZE) return false;+ std::wstring name = target(account);+ CREDENTIALW c{};+ c.Type = CRED_TYPE_GENERIC;+ c.TargetName = name.data();+ c.CredentialBlobSize = DWORD(secret.size());+ c.CredentialBlob = reinterpret_cast<LPBYTE>(const_cast<char*>(secret.data()));+ c.Persist = CRED_PERSIST_LOCAL_MACHINE; // this user on this PC (not roamed to other PCs)+ wchar_t user[] = L"SculptForge";+ c.UserName = user;+ return CredWriteW(&c, 0) != FALSE;+}++bool load(const std::string& account, std::string& secret) {+ PCREDENTIALW c = nullptr;+ if (!CredReadW(target(account).c_str(), CRED_TYPE_GENERIC, 0, &c) || !c) return false;+ secret.assign(reinterpret_cast<const char*>(c->CredentialBlob), c->CredentialBlobSize);+ SecureZeroMemory(c->CredentialBlob, c->CredentialBlobSize);+ CredFree(c);+ return true;+}++bool erase(const std::string& account) {+ return CredDeleteW(target(account).c_str(), CRED_TYPE_GENERIC, 0) != FALSE || GetLastError() == ERROR_NOT_FOUND;+}++#elif defined(__linux__)++// libsecret's C API, declared here so nothing links against it: a system without it simply has no keychain.+namespace {++struct SchemaAttribute {+ const char* name;+ int type; // SECRET_SCHEMA_ATTRIBUTE_STRING = 0+};+struct Schema {+ const char* name;+ int flags; // SECRET_SCHEMA_NONE = 0+ SchemaAttribute attributes[32];+ int reserved;+ void* reserved1[7];+};+struct GErrorC {+ unsigned domain;+ int code;+ char* message;+};++using StoreFn = int (*)(const Schema*, const char*, const char*, const char*, void*, GErrorC**, ...);+using LookupFn = char* (*)(const Schema*, void*, GErrorC**, ...);+using ClearFn = int (*)(const Schema*, void*, GErrorC**, ...);+using FreeFn = void (*)(char*);+using ErrorFreeFn = void (*)(GErrorC*);++struct Secret {+ StoreFn store = nullptr;+ LookupFn lookup = nullptr;+ ClearFn clear = nullptr;+ FreeFn free = nullptr;+ ErrorFreeFn errorFree = nullptr;+ bool ok = false;+};++const Secret& secretLib() {+ static Secret s;+ static std::once_flag once;+ std::call_once(once, [] {+ void* h = dlopen("libsecret-1.so.0", RTLD_NOW | RTLD_LOCAL);+ if (!h) return;+ s.store = reinterpret_cast<StoreFn>(dlsym(h, "secret_password_store_sync"));+ s.lookup = reinterpret_cast<LookupFn>(dlsym(h, "secret_password_lookup_sync"));+ s.clear = reinterpret_cast<ClearFn>(dlsym(h, "secret_password_clear_sync"));+ s.free = reinterpret_cast<FreeFn>(dlsym(h, "secret_password_free"));+ s.errorFree = reinterpret_cast<ErrorFreeFn>(dlsym(h, "g_error_free")); // (GLib, loaded with it)+ s.ok = s.store && s.lookup && s.clear && s.free && s.errorFree;+ });+ return s;+}++const Schema* schema() {+ static Schema sc = [] {+ Schema x{};+ x.name = "app.sculptforge.Secret";+ x.attributes[0] = {"account", 0};+ return x;+ }();+ return ≻+}++bool done(const Secret& s, GErrorC* error, int result) {+ if (error) s.errorFree(error); // (its message is not logged: it can name the item)+ return result && !error;+}++} // namespace++bool store(const std::string& account, const std::string& secret) {+ const Secret& s = secretLib();+ if (!s.ok) return false;+ GErrorC* error = nullptr;+ const int r = s.store(schema(), nullptr, "SculptForge member builds (GitHub sign-in)", secret.c_str(), nullptr, &error,+ "account", account.c_str(), static_cast<char*>(nullptr));+ return done(s, error, r);+}++bool load(const std::string& account, std::string& secret) {+ const Secret& s = secretLib();+ if (!s.ok) return false;+ GErrorC* error = nullptr;+ char* p = s.lookup(schema(), nullptr, &error, "account", account.c_str(), static_cast<char*>(nullptr));+ if (error) s.errorFree(error);+ if (!p) return false;+ secret = p;+ std::memset(p, 0, std::strlen(p));+ s.free(p);+ return true;+}++bool erase(const std::string& account) {+ const Secret& s = secretLib();+ if (!s.ok) return true; // nothing could have been stored+ GErrorC* error = nullptr;+ const int r = s.clear(schema(), nullptr, &error, "account", account.c_str(), static_cast<char*>(nullptr));+ (void)r; // false also means "there was none"+ return !error ? true : (s.errorFree(error), false);+}++#else // macOS: the Keychain follows (Security framework); until then the sign-in isn't kept between sessions.++bool store(const std::string&, const std::string&) { return false; }+bool load(const std::string&, std::string&) { return false; }+bool erase(const std::string&) { return true; }++#endif++} // namespace sf::keychaindiff --git a/src/core/Keychain.h b/src/core/Keychain.hnew file mode 100644index 00000000..3311e5c8--- /dev/null+++ b/src/core/Keychain.h@@ -0,0 +1,18 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// A secret in the operating system's keychain (the member-builds sign-in, core/MemberBuilds.h): Windows Credential+// Manager, the Secret Service on Linux (libsecret, loaded at run time: GNOME Keyring, KWallet, KeePassXC), macOS+// Keychain later. Where there is none, nothing is stored: the sign-in lasts until the app quits. Secrets never go+// to files, the preferences or the log. These calls can wait on the keychain (an unlock prompt): worker threads only.+#pragma once++#include <string>++namespace sf::keychain {++bool store(const std::string& account, const std::string& secret); // false: not stored (no keychain, or it refused)+bool load(const std::string& account, std::string& secret); // false: none stored+bool erase(const std::string& account); // true when nothing is stored afterwards++} // namespace sf::keychaindiff --git a/src/core/MemberBuilds.cpp b/src/core/MemberBuilds.cppnew file mode 100644index 00000000..b53ad562--- /dev/null+++ b/src/core/MemberBuilds.cpp@@ -0,0 +1,182 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/MemberBuilds.h"++#include "core/Json.h"+#include "core/SelfUpdate.h"++#include <algorithm>+#include <cctype>+#include <cmath>++namespace sf::member {++namespace {++bool allDigits(const std::string& s) {+ return !s.empty() && s.size() <= 20 && std::all_of(s.begin(), s.end(), [](char c) { return std::isdigit(static_cast<unsigned char>(c)); });+}++std::string formEncode(const std::string& s) {+ static const char* hex = "0123456789ABCDEF";+ std::string out;+ for (unsigned char c : s) {+ if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') out += char(c);+ else out += '%', out += hex[c >> 4], out += hex[c & 15];+ }+ return out;+}++std::string str(const Json& j, const char* key) { return j[key].isString() ? j[key].asString() : std::string(); }++// Tokens are short printable strings; anything else is not a token.+bool tokenLike(const std::string& s) {+ return !s.empty() && s.size() <= 512 &&+ std::all_of(s.begin(), s.end(), [](char c) { return c > 32 && c < 127 && c != '"' && c != '\\'; });+}++} // namespace++bool isMemberAssetUrl(const std::string& url) {+ const std::string prefix = kAssetUrlPrefix;+ return url.size() > prefix.size() && url.compare(0, prefix.size(), prefix) == 0 && allDigits(url.substr(prefix.size()));+}++bool isMemberApiUrl(const std::string& url) { return url == kReleasesUrl || url == kUserUrl || isMemberAssetUrl(url); }++std::vector<std::string> headersFor(const std::string& url, const std::string& accessToken) {+ if (!isMemberApiUrl(url) || accessToken.empty()) return {};+ return {"Authorization: Bearer " + accessToken,+ isMemberAssetUrl(url) ? "Accept: application/octet-stream" : "Accept: application/vnd.github+json",+ "X-GitHub-Api-Version: 2022-11-28"};+}++bool parseDeviceCode(const std::string& json, int64_t now, DeviceCode& out, std::string& error) {+ Json j;+ if (!Json::parse(json, j, error) || !j.isObject()) {+ if (error.empty()) error = "GitHub's answer isn't JSON";+ return false;+ }+ if (j["error"].isString()) {+ error = j["error"].asString() == "device_flow_disabled" ? "sign-in is switched off for the app"+ : "GitHub refused: " + j["error"].asString().substr(0, 60);+ return false;+ }+ out.deviceCode = str(j, "device_code");+ out.userCode = str(j, "user_code");+ out.interval = std::clamp(int(j["interval"].asNumber(5)), 1, 60);+ out.expiresAt = now + int64_t(std::clamp(j["expires_in"].asNumber(900), 60.0, 3600.0));+ // The page to open is ours to choose (kVerifyUrl), not the answer's: it is checked to be the same place.+ const std::string uri = str(j, "verification_uri");+ if (!tokenLike(out.deviceCode) || out.userCode.empty() || out.userCode.size() > 16 || uri != kVerifyUrl) {+ error = "GitHub's sign-in answer is not what was expected";+ return false;+ }+ return true;+}++TokenReply parseTokenReply(const std::string& json, int64_t now, Tokens& tokens, std::string& error) {+ Json j;+ std::string err;+ if (!Json::parse(json, j, err) || !j.isObject()) {+ error = "GitHub's answer isn't JSON";+ return TokenReply::Error;+ }+ const std::string e = str(j, "error");+ if (e == "authorization_pending") return TokenReply::Pending;+ if (e == "slow_down") return TokenReply::SlowDown;+ if (e == "expired_token" || e == "bad_refresh_token" || e == "token_expired") return TokenReply::Expired;+ if (e == "access_denied") return TokenReply::Denied;+ if (!e.empty()) {+ error = "GitHub refused: " + e.substr(0, 60);+ return TokenReply::Error;+ }+ Tokens t;+ t.access = str(j, "access_token");+ t.refresh = str(j, "refresh_token");+ if (!tokenLike(t.access) || (!t.refresh.empty() && !tokenLike(t.refresh)) ||+ (j["token_type"].isString() && j["token_type"].asString() != "bearer")) {+ error = "GitHub's answer has no usable token";+ return TokenReply::Error;+ }+ if (j["expires_in"].isNumber()) t.accessExpiresAt = now + int64_t(j["expires_in"].asNumber(0));+ if (j["refresh_token_expires_in"].isNumber()) t.refreshExpiresAt = now + int64_t(j["refresh_token_expires_in"].asNumber(0));+ tokens = std::move(t);+ return TokenReply::Ok;+}++std::string deviceCodeBody() { return "client_id=" + formEncode(kClientId); }+std::string pollBody(const std::string& deviceCode) {+ return "client_id=" + formEncode(kClientId) + "&device_code=" + formEncode(deviceCode) ++ "&grant_type=" + formEncode("urn:ietf:params:oauth:grant-type:device_code");+}+std::string refreshBody(const std::string& refreshToken) {+ return "client_id=" + formEncode(kClientId) + "&grant_type=refresh_token&refresh_token=" + formEncode(refreshToken);+}++std::string tokensToSecret(const Tokens& t) {+ Json j = Json::object();+ j.set("access", t.access);+ j.set("refresh", t.refresh);+ j.set("access_expires", double(t.accessExpiresAt));+ j.set("refresh_expires", double(t.refreshExpiresAt));+ return j.dump();+}++bool tokensFromSecret(const std::string& secret, Tokens& t) {+ Json j;+ std::string err;+ if (!Json::parse(secret, j, err) || !j.isObject()) return false;+ Tokens r;+ r.access = str(j, "access");+ r.refresh = str(j, "refresh");+ r.accessExpiresAt = int64_t(j["access_expires"].asNumber(0));+ r.refreshExpiresAt = int64_t(j["refresh_expires"].asNumber(0));+ if (!tokenLike(r.access) || (!r.refresh.empty() && !tokenLike(r.refresh))) return false;+ t = std::move(r);+ return true;+}++bool parseMemberReleases(const std::string& json, UpdateInfo& out, std::string& error) {+ Json j;+ if (!Json::parse(json, j, error) || !j.isArray()) {+ if (error.empty()) error = "the member release list isn't one";+ return false;+ }+ bool found = false;+ for (const Json& r : j.items()) {+ if (!r.isObject() || r["draft"].asBool(false)) continue;+ std::string tag = str(r, "tag_name");+ if (tag.size() < 2 || tag[0] != 'v' || !update::safeVersion(tag.substr(1))) continue;+ const std::string version = tag.substr(1);+ if (found && compareVersions(version, out.version) <= 0) continue;+ UpdateInfo info;+ info.version = version;+ info.member = true;+ info.downloadUrl = "https://github.com/islandmed/sculptforge-insiders/releases/tag/" + tag; // (built here, not read)+ info.notesUrl = info.downloadUrl;+ info.highlights.push_back("Member build (the next release, early)");+ for (const Json& a : r["assets"].items()) {+ const std::string name = str(a, "name");+ const double id = a["id"].asNumber(-1);+ if (name.empty() || name.size() > 128 || !(id >= 1) || id > 9e15 || std::floor(id) != id) continue;+ info.files[name] = std::string(kAssetUrlPrefix) + std::to_string(int64_t(id));+ }+ out = std::move(info);+ found = true;+ }+ if (!found) error = "no member build yet";+ return found;+}++std::string parseLogin(const std::string& json) {+ Json j;+ std::string err;+ if (!Json::parse(json, j, err) || !j.isObject()) return {};+ const std::string login = str(j, "login");+ const bool ok = !login.empty() && login.size() <= 39 &&+ std::all_of(login.begin(), login.end(), [](char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '-'; });+ return ok ? login : std::string();+}++} // namespace sf::memberdiff --git a/src/core/MemberBuilds.h b/src/core/MemberBuilds.hnew file mode 100644index 00000000..65b5c817--- /dev/null+++ b/src/core/MemberBuilds.h@@ -0,0 +1,79 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Member builds: Insider and Studio members are read collaborators on the private repository+// islandmed/sculptforge-insiders, where the Insider previews are published. Preferences > Updates > Member builds+// signs in with GitHub's device flow for the GitHub App "SculptForge Member Builds", which is installed only on that+// repository with Contents: read. Its user-to-server token reaches only repositories both the app and the user can+// access, so it can read that repository's releases and nothing else. No server of ours, no client secret (the+// device flow and its refresh don't use one), and the app's private key is never used.+// The token lives in the OS keychain (core/Keychain.h), never in the preferences or logs. Member builds are checked+// exactly like public ones (core/SelfUpdate.h): the same SHA256SUMS.txt + Ed25519 signature, the same key.+#pragma once++#include "core/UpdateCheck.h"++#include <cstdint>+#include <string>+#include <vector>++namespace sf::member {++inline constexpr const char* kClientId = "Iv23liK7goArrLDUGKEk"; // public (GitHub App "SculptForge Member Builds")+inline constexpr const char* kDeviceCodeUrl = "https://github.com/login/device/code";+inline constexpr const char* kTokenUrl = "https://github.com/login/oauth/access_token";+inline constexpr const char* kVerifyUrl = "https://github.com/login/device"; // where the user types the code+inline constexpr const char* kReleasesUrl = "https://api.github.com/repos/islandmed/sculptforge-insiders/releases?per_page=20";+inline constexpr const char* kUserUrl = "https://api.github.com/user";+inline constexpr const char* kAssetUrlPrefix = "https://api.github.com/repos/islandmed/sculptforge-insiders/releases/assets/";+inline constexpr const char* kKeychainAccount = "member-builds"; // (core/Keychain.h)++// The member API URLs the app may call with the token: the release list, one asset by number, the signed-in user.+bool isMemberApiUrl(const std::string& url);+bool isMemberAssetUrl(const std::string& url);+// Headers for a request to `url`: the token only for the member API URLs above (never for a redirect's target).+std::vector<std::string> headersFor(const std::string& url, const std::string& accessToken);++struct DeviceCode {+ std::string deviceCode; // secret-ish: only sent back to GitHub+ std::string userCode; // shown: "WDJB-MJHT"+ int interval = 5; // seconds between polls+ int64_t expiresAt = 0; // unix time+};+bool parseDeviceCode(const std::string& json, int64_t now, DeviceCode& out, std::string& error);++struct Tokens {+ std::string access, refresh;+ int64_t accessExpiresAt = 0, refreshExpiresAt = 0; // unix time; 0 = doesn't expire+ bool usable(int64_t now) const { return !access.empty() && (accessExpiresAt == 0 || now < accessExpiresAt - 60); }+ bool refreshable(int64_t now) const { return !refresh.empty() && (refreshExpiresAt == 0 || now < refreshExpiresAt); }+};++enum class TokenReply {+ Ok, // `tokens` filled+ Pending, // the user hasn't entered the code yet: poll again after the interval+ SlowDown, // poll less often (interval + 5 s)+ Expired, // the code (or the refresh token) is no longer valid: sign in again+ Denied, // the user said no+ Error, // anything else (`error` says what; never the token)+};+// GitHub's answer from kTokenUrl (to a device poll or a refresh).+TokenReply parseTokenReply(const std::string& json, int64_t now, Tokens& tokens, std::string& error);++// Form bodies for kDeviceCodeUrl and kTokenUrl.+std::string deviceCodeBody();+std::string pollBody(const std::string& deviceCode);+std::string refreshBody(const std::string& refreshToken);++// What the keychain holds (a small JSON object), and back.+std::string tokensToSecret(const Tokens& t);+bool tokensFromSecret(const std::string& secret, Tokens& t);++// The newest usable release in the member repository's list (GET kReleasesUrl): drafts skipped, the tag must be a+// safe version ("v0.11.1-preview.3"), and its files are reachable as kAssetUrlPrefix + asset id (UpdateInfo::files).+bool parseMemberReleases(const std::string& json, UpdateInfo& out, std::string& error);++// The login from GET kUserUrl ("" when the answer isn't one).+std::string parseLogin(const std::string& json);++} // namespace sf::memberdiff --git a/src/core/SelfUpdate.cpp b/src/core/SelfUpdate.cppindex b606af34..f1db9c82 100644--- a/src/core/SelfUpdate.cpp+++ b/src/core/SelfUpdate.cpp@@ -4,6 +4,7 @@#include "core/Ed25519.h"#include "core/Json.h"+#include "core/MemberBuilds.h"#include "core/Sha256.h"#include <algorithm>@@ -81,6 +82,10 @@ bool isReleaseAssetHostUrl(const std::string& url) {return false;}+bool allowedUpdateUrl(const std::string& url) {+ return isReleaseDownloadUrl(url) || isReleaseAssetHostUrl(url) || member::isMemberApiUrl(url);+}+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) {@@ -289,19 +294,29 @@ bool fetchSmall(const Fetch& fetch, const std::string& url, size_t cap, Download} // namespacevoid downloadUpdate(const std::string& version, const Install& install, const uint8_t key[32], const Fetch& fetch,- Download& d) {+ Download& d, const std::map<std::string, std::string>& memberFiles) {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()) {+ // A public release's files by their fixed URLs; a member build's by the asset URLs its release lists.+ const auto urlOf = [&](const std::string& name) -> std::string {+ if (memberFiles.empty()) return releaseFileUrl(version, name);+ const auto it = memberFiles.find(name);+ return it != memberFiles.end() && member::isMemberAssetUrl(it->second) && safeVersion(version) ? it->second : "";+ };+ const std::string file = versionedAsset(install.asset, version), sumsUrl = urlOf("SHA256SUMS.txt"),+ sigUrl = urlOf("SHA256SUMS.txt.sig"), packageUrl = file.empty() ? "" : urlOf(file);+ if (!selfUpdates(install.kind)) {d.error = "this install can't update itself";return;}+ if (sumsUrl.empty() || sigUrl.empty() || packageUrl.empty()) {+ d.error = "the release doesn't have " + (sumsUrl.empty() ? std::string("SHA256SUMS.txt") : sigUrl.empty() ? std::string("a signature") : file);+ return;+ }std::string sums, sig;if (!fetchSmall(fetch, sumsUrl, kMaxSumsBytes, d, sums) || !fetchSmall(fetch, sigUrl, 1024, d, sig)) return;if (!sumsSignatureValid(sums, sig, key)) {diff --git a/src/core/SelfUpdate.h b/src/core/SelfUpdate.hindex 3848eb53..b0d3ce6d 100644--- a/src/core/SelfUpdate.h+++ b/src/core/SelfUpdate.h@@ -18,6 +18,7 @@#include <atomic>#include <cstdint>#include <functional>+#include <map>#include <string>namespace sf::update {@@ -39,7 +40,8 @@ inline constexpr const char* kUpdatePublicKeyHex = "";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); }+// (Member builds add their API URLs: member::isMemberApiUrl.)+bool allowedUpdateUrl(const std::string& 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.@@ -116,8 +118,9 @@ struct Download {// 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.+// `memberFiles` (a member build, core/MemberBuilds.h): the files by name as member API URLs; empty: the public release.void downloadUpdate(const std::string& version, const Install& install, const uint8_t key[32], const Fetch& fetch,- Download& out);+ Download& out, const std::map<std::string, std::string>& memberFiles = {});// 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);diff --git a/src/core/UpdateCheck.h b/src/core/UpdateCheck.hindex 6ecc9d6b..173b3488 100644--- a/src/core/UpdateCheck.h+++ b/src/core/UpdateCheck.h@@ -6,6 +6,7 @@#pragma once#include <cstdint>+#include <map>#include <string>#include <vector>@@ -21,6 +22,8 @@ struct UpdateInfo {std::string downloadUrl; // the download pagestd::string notesUrl; // what's newstd::vector<std::string> highlights; // a few short lines for the banner+ bool member = false; // a member build (core/MemberBuilds.h)+ std::map<std::string, std::string> files; // member builds: release file name -> its API URL};// Which releases the update check offers (Preferences > Updates): Stable, or Preview, which adds the betasdiff --git a/tests/test_self_update.cpp b/tests/test_self_update.cppindex 427a5823..cc8a26ee 100644--- a/tests/test_self_update.cpp+++ b/tests/test_self_update.cpp@@ -8,6 +8,7 @@#include "ai/Http.h"#include "core/Ed25519.h"+#include "core/MemberBuilds.h"#include "core/SelfUpdate.h"#include "core/Sha256.h"@@ -74,6 +75,7 @@ void writeAll(const fs::path& p, const std::string& s) { std::ofstream(p, std::i// 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::map<std::string, std::string> assetNames; // member asset id -> file namestd::vector<std::string> asked;uint64_t claimTotal = 0; // a Content-Length that differs from the body (a cut-short download)Fetch fetch() {@@ -81,11 +83,13 @@ struct FakeReleases {const std::function<bool(uint64_t, uint64_t)>& onProgress) {asked.push_back(url);FetchResult r;- if (!isReleaseDownloadUrl(url)) {+ if (!allowedUpdateUrl(url)) {r.error = "refused";return r;}- const auto it = files.find(url.substr(url.rfind('/') + 1));+ std::string name = url.substr(url.rfind('/') + 1);+ if (member::isMemberAssetUrl(url)) name = assetNames.count(name) ? assetNames[name] : "";+ const auto it = files.find(name);if (it == files.end()) {r.status = 404;return r;@@ -470,3 +474,114 @@ TEST(self_update_windows_helper) {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}++// --- Member builds (core/MemberBuilds.cpp) ---++TEST(member_builds_urls_and_headers) {+ using namespace sf::member;+ CHECK(isMemberApiUrl("https://api.github.com/repos/islandmed/sculptforge-insiders/releases?per_page=20"));+ CHECK(isMemberApiUrl("https://api.github.com/user"));+ CHECK(isMemberAssetUrl("https://api.github.com/repos/islandmed/sculptforge-insiders/releases/assets/123456"));+ for (const char* u : {"https://api.github.com/repos/islandmed/sculptforge-insiders/releases/assets/12a",+ "https://api.github.com/repos/islandmed/sculptforge-insiders/releases/assets/",+ "https://api.github.com/repos/islandmed/sculptforge-insiders/releases/assets/1/../../x",+ "https://api.github.com/repos/islandmed/SculptForge/releases?per_page=20",+ "https://api.github.com/repos/islandmed/sculptforge-insiders/contents/secrets",+ "https://api.github.com/user/repos", "https://api.github.com.evil.example/user",+ "http://api.github.com/user"})+ CHECK(!isMemberApiUrl(u) && !allowedUpdateUrl(u));+ // The token goes to the member API only: never to the asset host, the public release URLs or anywhere else.+ const auto h = headersFor("https://api.github.com/repos/islandmed/sculptforge-insiders/releases/assets/5", "ghu_x");+ CHECK(h.size() == 3 && h[0] == "Authorization: Bearer ghu_x" && h[1] == "Accept: application/octet-stream");+ CHECK(headersFor(kReleasesUrl, "ghu_x")[1] == "Accept: application/vnd.github+json");+ for (const char* u : {"https://release-assets.githubusercontent.com/a?sig=1", "https://objects.githubusercontent.com/a",+ "https://github.com/islandmed/SculptForge/releases/download/v1.0.0/SHA256SUMS.txt",+ "https://evil.example/x"})+ CHECK(headersFor(u, "ghu_x").empty());+ // A redirect from the member API to the asset host is followed, without the token (headersFor per hop).+ std::vector<std::vector<std::string>> sent;+ const std::string asset = std::string(kAssetUrlPrefix) + "77";+ const ai::HttpResponse r = ai::followRedirects(asset, allowedUpdateUrl, [&](const std::string& url, std::string& loc) {+ sent.push_back(headersFor(url, "ghu_x"));+ ai::HttpResponse a;+ if (url == asset) a.status = 302, loc = "https://release-assets.githubusercontent.com/x?sig=1";+ else a.status = 200;+ return a;+ });+ CHECK(r.status == 200 && sent.size() == 2 && sent[0].size() == 3 && sent[1].empty());+}++TEST(member_builds_device_flow_answers) {+ using namespace sf::member;+ DeviceCode c;+ std::string err;+ CHECK(parseDeviceCode(R"({"device_code":"3584d83530557fdd1f46af8289938c8ef79f9dc5","user_code":"WDJB-MJHT",+ "verification_uri":"https://github.com/login/device","expires_in":900,"interval":5})", 1000, c, err));+ CHECK(c.userCode == "WDJB-MJHT" && c.interval == 5 && c.expiresAt == 1900);+ // Another page to open than GitHub's own: refused (the app opens kVerifyUrl only anyway).+ CHECK(!parseDeviceCode(R"({"device_code":"abc","user_code":"WDJB-MJHT","verification_uri":"https://evil.example/login/device"})",+ 0, c, err));+ CHECK(!parseDeviceCode(R"({"error":"device_flow_disabled"})", 0, c, err) && err.find("switched off") != std::string::npos);+ CHECK(pollBody("a b") == "client_id=Iv23liK7goArrLDUGKEk&device_code=a%20b&grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code");+ CHECK(refreshBody("ghr_1").find("grant_type=refresh_token&refresh_token=ghr_1") != std::string::npos);+ CHECK(refreshBody("x").find("client_secret") == std::string::npos); // (a device-flow app has none)++ Tokens t;+ CHECK(parseTokenReply(R"({"error":"authorization_pending"})", 0, t, err) == TokenReply::Pending);+ CHECK(parseTokenReply(R"({"error":"slow_down","interval":10})", 0, t, err) == TokenReply::SlowDown);+ CHECK(parseTokenReply(R"({"error":"expired_token"})", 0, t, err) == TokenReply::Expired);+ CHECK(parseTokenReply(R"({"error":"bad_refresh_token"})", 0, t, err) == TokenReply::Expired);+ CHECK(parseTokenReply(R"({"error":"access_denied"})", 0, t, err) == TokenReply::Denied);+ CHECK(parseTokenReply("<html>", 0, t, err) == TokenReply::Error && err.find("ghu_") == std::string::npos);+ CHECK(parseTokenReply(R"({"access_token":"","token_type":"bearer"})", 0, t, err) == TokenReply::Error);+ CHECK(parseTokenReply(R"({"access_token":"ghu_abc","expires_in":28800,"refresh_token":"ghr_def",+ "refresh_token_expires_in":15897600,"token_type":"bearer","scope":""})", 100, t, err) == TokenReply::Ok);+ CHECK(t.access == "ghu_abc" && t.refresh == "ghr_def" && t.accessExpiresAt == 28900 && t.refreshExpiresAt == 15897700);+ CHECK(t.usable(100) && !t.usable(28890) && t.refreshable(28890) && !t.refreshable(15897700));+ Tokens back;+ CHECK(tokensFromSecret(tokensToSecret(t), back) && back.access == t.access && back.refresh == t.refresh &&+ back.accessExpiresAt == t.accessExpiresAt && back.refreshExpiresAt == t.refreshExpiresAt);+ CHECK(!tokensFromSecret("{}", back) && !tokensFromSecret("not json", back));+ CHECK(parseLogin(R"({"login":"some-member","id":1})") == "some-member");+ CHECK(parseLogin(R"({"login":"<script>"})").empty());+}++TEST(member_builds_release_list) {+ using namespace sf::member;+ const char* list = R"([+ {"tag_name":"v99.0.0-preview.2","draft":true,"assets":[]},+ {"tag_name":"v99.0.0-preview.1","draft":false,"assets":[+ {"id":11,"name":"SHA256SUMS.txt"},{"id":12,"name":"SHA256SUMS.txt.sig"},+ {"id":13,"name":"SculptForge-99.0.0-x86_64.AppImage"},{"id":"14","name":"bad-id"},{"id":1.5,"name":"half"}]},+ {"tag_name":"v98.0.0-preview.9","draft":false,"assets":[]},+ {"tag_name":"v99.0.0/../x","assets":[]}, {"tag_name":"latest","assets":[]}, 7])";+ UpdateInfo u;+ std::string err;+ CHECK(parseMemberReleases(list, u, err));+ CHECK(u.version == "99.0.0-preview.1" && u.member && u.files.size() == 3); // the draft and odd entries skipped+ CHECK(u.files["SculptForge-99.0.0-x86_64.AppImage"] == std::string(kAssetUrlPrefix) + "13");+ CHECK(u.downloadUrl == "https://github.com/islandmed/sculptforge-insiders/releases/tag/v99.0.0-preview.1");+ CHECK(!parseMemberReleases("[]", u, err) && !parseMemberReleases("{}", u, err));++ // A member build downloads and verifies exactly like a public one: same signature, same key, versioned name.+ Sandbox s("sf_member_download");+ FakeReleases f = goodRelease();+ f.assetNames = {{"11", "SHA256SUMS.txt"}, {"12", "SHA256SUMS.txt.sig"}, {"13", "SculptForge-99.0.0-x86_64.AppImage"}};+ uint8_t k[32];+ CHECK(parseHexKey(kTestKey, k));+ Download d;+ downloadUpdate("99.0.0-preview.1", s.install, k, f.fetch(), d, u.files);+ CHECK(d.ok && d.sha256 == kPackageSha);+ for (const auto& url : f.asked) CHECK(isMemberAssetUrl(url)); // nothing public, nothing else+ // Tampered member files fail the same way.+ f.files["SHA256SUMS.txt.sig"][3] ^= 1;+ Download bad;+ downloadUpdate("99.0.0-preview.1", s.install, k, f.fetch(), bad, u.files);+ CHECK(!bad.ok && readAll(s.install.target) == "old version");+ // A file list that points anywhere but the member asset URLs is not used.+ Download elsewhere;+ std::map<std::string, std::string> evil = u.files;+ evil["SHA256SUMS.txt"] = "https://evil.example/SHA256SUMS.txt";+ downloadUpdate("99.0.0-preview.1", s.install, k, f.fetch(), elsewhere, evil);+ CHECK(!elsewhere.ok && !elsewhere.error.empty());+}diff --git a/tests/ui/self_update.sfui b/tests/ui/self_update.sfuiindex 2fe1e717..fda9b067 100644--- a/tests/ui/self_update.sfui+++ b/tests/ui/self_update.sfui@@ -31,4 +31,20 @@ click "Copy##update.copy"expect_clipboard "yay -Syu sculptforge"click "Later"expect_not "Skip this version"++# Preferences > Updates > Member builds: GitHub's device flow shows a code to enter on github.com (a UI test gets a+# stand-in code and sends nothing); Cancel goes back to Sign in.+click "Preferences##palette.preferences"+click "Updates##preferences.updates"+expect_text "Member builds"+expect "Sign in with GitHub##member.sign_in"+click "Sign in with GitHub##member.sign_in"+expect_text "On GitHub, enter this code:"+expect_text "TEST-CODE"+expect "Open github.com/login/device##member.open"+shot member-sign-in+click "Copy##member.copy"+expect_clipboard "TEST-CODE"+click "Cancel##member.cancel"+expect "Sign in with GitHub##member.sign_in"expect_value http_requests == 0diff --git a/tools/release/sign_sums.sh b/tools/release/sign_sums.shnew file mode 100755index 00000000..e07fb96b--- /dev/null+++ b/tools/release/sign_sums.sh@@ -0,0 +1,28 @@+#!/usr/bin/env bash+# Signs DIST/SHA256SUMS.txt for one-click update (src/core/SelfUpdate.h): DIST/SHA256SUMS.txt.sig, a raw 64-byte+# Ed25519 signature, made with the private key in $UPDATE_SIGNING_KEY (a PEM; the repository secret). Used by+# release.yml for public releases and member betas alike (the same key, the same check in the app).+# tools/release/sign_sums.sh DIST [SOURCE_DIR] SOURCE_DIR: the checkout whose kUpdatePublicKeyHex must match+# No secret: a warning while the app has no key yet, an error once it has one.+set -euo pipefail+dist=$1+src=${2:-.}+pub=$(sed -n 's/.*kUpdatePublicKeyHex = "\([0-9a-f]*\)".*/\1/p' "$src/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:-empty})"; 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" >/dev/null+[ "$(wc -c < "$dist/SHA256SUMS.txt.sig")" -eq 64 ]+chmod 644 "$dist/SHA256SUMS.txt.sig"+echo "signed SHA256SUMS.txt ($pub)"