What changed, and why it matters
This commit adds the first Apple-signed macOS desktop build pipeline for LNbits. It is a feature commit about packaging, code signing, and notarization. There is no direct evidence in the diff of a vulnerability or malicious change. The main security-relevant aspect is that the new build process handles Apple Developer ID certificates and private keys, so mistakes in how those secrets are managed could affect release integrity. The code appears to take several protective measures: it uses a temporary keychain, strips credentials from child process environments, redacts secrets in logs, validates entitlements, and verifies signatures before publishing.
Treat this as a normal feature commit. Reviewers should verify that CI secrets are scoped only to the signed build job, that the temporary keychain cleanup cannot be skipped on failure, and that the entitlement policy cannot be silently overridden via MACOS_ENTITLEMENTS_FILE. No immediate security patch is indicated by the diff itself.
Security signals we found
New code handles Apple Developer ID certificate/private key (P12) and Apple ID credentials
Secrets are redacted from subprocess output and removed from child environments
Temporary keychain is created with restricted permissions and cleaned up on exit
Entitlements are deliberately minimal and validated against a documented policy
Recursive code signing verifies every nested Mach-O binary and bundle
Notarization status must be 'Accepted' before stapling; failures stop publication
Final DMG is mounted read-only and verified with codesign, Gatekeeper, stapler, and smoke tests
No debug, library-validation-disable, DYLD, or Electron entitlements are used
Build rejects Rosetta and requires native architecture builds
No project runtime code or wallet logic is modified
Evidence from the diff
The commit introduces a complete macOS release pipeline under .github/packaging/macos/: credentials.py manages a disposable keychain and P12 import; common.py provides a Runner that redacts secrets and sanitizes subprocess environments; signing.py recursively signs Mach-O binaries and nested bundles, verifies Developer ID requirements, team IDs, hardened runtime flags, secure timestamps, and entitlements; dmg.py creates a compressed UDZO DMG; release.py orchestrates build, sign, notarize, staple, mount, and smoke-test steps; verify.py checks bundled data, architecture, Gatekeeper assessment, and runs smoke tests. The desktop launcher gains a hidden –smoke-test-gui flag and a launcher_smoke.py helper that exercises Tk and Wasmtime. Tests are added for credential handling, redaction, keychain cleanup, signing requirements, and DMG creation. The entitlements are minimal: allow-unsigned-executable-memory for Python/Wasmtime, allow-jit for Node (plus unsigned-memory on x86_64), and none for Phoenixd or libraries. The commit does not change LNbits server code, wallet logic, or dependencies; it is purely packaging infrastructure.
Changed components
.github/packaging/build.py.github/packaging/desktop.py.github/packaging/launcher_smoke.py.github/packaging/macos/common.py.github/packaging/macos/credentials.py.github/packaging/macos/dmg.py.github/packaging/macos/release.py.github/packaging/macos/signing.py.github/packaging/macos/verify.py.github/packaging/macos/smoke_launcher.py.github/packaging/prepare_sidecars.py.github/packaging/smoke_sidecars.py.github/workflows/macos.yml.github/workflows/release-rc.yml.github/workflows/release.ymlMakefileInspect captured patch +3248 / −125
diff --git a/.github/packaging/README.md b/.github/packaging/README.md
new file mode 100644
index 0000000..73ccc38
--- /dev/null
+++ b/.github/packaging/README.md
@@ -0,0 +1,80 @@
+# Desktop funding sources
+
+The desktop launcher offers **Neither** and **Spark L2** on all platforms, plus
+**Phoenixd** on macOS and Linux. Choose an unused daemon port, then launch LNbits.
+Neither starts LNbits using its normal funding settings. Spark/Phoenixd start locally, wait for
+an authenticated wallet API response, and configure the existing LNbits backend.
+Python, Node.js and the daemons do not need to be installed by the user.
+An internet connection is needed for either funding service.
+
+Managed funding requires a new local SQLite data folder on first setup. An
+existing LNbits database cannot be attached to a newly generated backing wallet,
+and changing between Spark and Phoenixd requires a separate data folder. These
+guards prevent existing user balances being backed by a different wallet.
+External database URLs are not supported in managed mode. Neither retains the
+normal LNbits database and funding configuration options.
+
+## Persistence and backup
+
+The selected provider and port are remembered in `funding/profile.json` within
+the chosen LNbits data folder. Selecting Neither explicitly skips daemon startup
+for that launch. Each provider's identity is generated once:
+
+- Spark: 24 words in `funding/spark/seed.dat`.
+- Phoenixd: 12 words in `funding/phoenixd/seed.dat`, alongside its database and
+ `phoenix.conf`.
+
+Restarting, updating the app, or changing the daemon port reuses the same seed.
+A missing or invalid seed in an existing profile stops startup; the launcher
+never silently generates a replacement. Back up the **whole data folder** with
+the app stopped, and keep an offline copy of the seed. The files contain secrets;
+store backups privately. Never run two Phoenix instances with the same seed.
+The launcher prevents concurrent managed launches using the same data folder.
+
+The daemon binds to `127.0.0.1` and requires a random API password/key generated
+for each launch. Connection settings are authoritative for the managed LNbits
+worker, so stale saved backend settings cannot override the selected daemon.
+Change the managed port/provider in the launcher, rather than LNbits admin.
+
+Closing the launcher stops LNbits first, then the daemon. LNbits' own restart
+keeps the daemon running. A daemon failure stops LNbits and reports an error;
+there is no automatic switch to another funding source. The daemon supervisor
+also shuts down when its launcher pipe closes unexpectedly.
+
+Phoenixd first setup asks users to acknowledge seed backup and automatic
+liquidity fees/fee credit. See [ACINQ's liquidity documentation](https://phoenix.acinq.co/server/auto-liquidity).
+Logs are under `logs/desktop.log`, `logs/spark.log` or `logs/phoenixd.log`.
+
+Headless examples (using the same persistent `LNBITS_DATA_FOLDER` each time):
+
+```sh
+LNbits --headless --funding-source spark --funding-port 8765 --port 5000
+LNbits --headless --funding-source phoenixd --funding-port 9740 --accept-phoenixd-terms
+```
+
+The terms flag is needed only for Phoenixd's first headless setup. Omit
+`--funding-source` on later launches to reuse the saved provider and port.
+
+## Build and verification
+
+`build.py` on macOS prepares runtimes before invoking PyInstaller. `sidecars/pins.json`
+pins Node 24.21.0, Phoenixd 0.9.0 and Spark sidecar v0.1.5 with SHA-256 checksums.
+Spark is downloaded at its fixed release commit; its tag and revision appear
+in the build log and are included in the bundled `sidecars/pins.json`.
+Downloads occur at build time only. A failed download or checksum mismatch fails
+the build without falling back to a branch or a newer release. Update the Spark
+release, revision and checksum together when deliberately upgrading it.
+Builds require npm. Build on the target Mac architecture using the release workflow.
+
+Spark uses the selected release's own manifest and lockfile with `npm ci`.
+An npm audit fails the build on high or critical production dependency advisories;
+dependency fixes should be published in a new Spark release. Mobile-only SDK
+libraries are excluded; runtime JS/WASM and dependency licenses are retained.
+Phoenixd's Apache license is included separately.
+
+`make test-desktop` covers launcher controls, persistence, ownership, readiness,
+settings precedence, restart and shutdown. `smoke_sidecars.py` tests native
+versions, Spark authentication and shutdown without initializing a real wallet
+or sending payments. macOS CI runs it against the final read-only DMG. `smoke.py` tests the packaged
+LNbits server separately. Live network readiness and actual payments should
+also be checked on each target platform before releasing to users.
diff --git a/.github/packaging/build.py b/.github/packaging/build.py
index 9b1d722..f387631 100644
--- a/.github/packaging/build.py
+++ b/.github/packaging/build.py
@@ -21,7 +21,8 @@ if sys.platform == "darwin":
if Path(name).name.startswith(("libssl.", "libcrypto.")):
raise RuntimeError(
"macOS packaging requires cryptography with static OpenSSL. "
- "Clear its uv cache and reinstall with OPENSSL_STATIC=1."
+ "Clear its uv cache and reinstall with OPENSSL_STATIC=1; "
+ "see .github/packaging/macos/README.md."
)
prepare_sidecars()
@@ -89,6 +90,8 @@ if sys.platform == "win32":
if sys.platform == "darwin":
args += [
"--windowed",
+ "--additional-hooks-dir",
+ str(Path(__file__).resolve().parent / "macos/hooks"),
"--osx-bundle-identifier=com.lnbits.desktop",
f"--icon={Path(__file__).resolve().parent / 'linux/AppDir/lnbits.png'}",
]
@@ -97,6 +100,10 @@ if sys.platform == "darwin":
if entitlements := os.environ.get("MACOS_ENTITLEMENTS_FILE"):
args += ["--osx-entitlements-file", entitlements]
for package in packages:
+ if sys.platform == "darwin" and package == "embit":
+ # The macOS hook selects embit's native prebuild; --collect-all would
+ # independently re-add every other platform's library to the app.
+ continue
args += ["--collect-all", package]
for package in ("breez_sdk", "breez_sdk_liquid"):
if importlib.util.find_spec(package):
diff --git a/.github/packaging/desktop.py b/.github/packaging/desktop.py
index f7e2175..4878a71 100644
--- a/.github/packaging/desktop.py
+++ b/.github/packaging/desktop.py
@@ -252,7 +252,7 @@ class Server:
return code
-def gui(): # noqa: C901 - UI callbacks share the window and server lifecycle.
+def gui(smoke=False): # noqa: C901 - Shared UI callbacks.
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
@@ -496,6 +496,11 @@ def gui(): # noqa: C901 - UI callbacks share the window and server lifecycle.
root.protocol("WM_DELETE_WINDOW", close)
if sys.platform == "darwin":
root.createcommand("tk::mac::Quit", close)
+ smoke_state = None
+ if smoke:
+ from launcher_smoke import schedule
+
+ smoke_state = schedule(root)
try:
root.mainloop()
finally:
@@ -504,6 +509,9 @@ def gui(): # noqa: C901 - UI callbacks share the window and server lifecycle.
while server.poll() is None:
time.sleep(0.1)
+ if smoke_state and (not smoke_state["ready"] or smoke_state["timeout"]):
+ raise RuntimeError("Packaged launcher smoke test failed")
+
def windows_terminal():
import ctypes
@@ -578,7 +586,11 @@ def main():
action="store_true",
help="Acknowledge Phoenixd backup and automatic liquidity terms on first setup",
)
+ parser.add_argument("--smoke-test-gui", action="store_true", help=argparse.SUPPRESS)
args = parser.parse_args()
+ if args.smoke_test_gui:
+ gui(smoke=True)
+ return
if args.gui or (not args.headless and should_show_gui()):
gui()
return
diff --git a/.github/packaging/launcher_smoke.py b/.github/packaging/launcher_smoke.py
new file mode 100644
index 0000000..282d11e
--- /dev/null
+++ b/.github/packaging/launcher_smoke.py
@@ -0,0 +1,51 @@
+"""Automate the packaged Tk window and exercise Wasmtime under hardened runtime."""
+
+import time
+
+
+def schedule(root):
+ from tkinter import ttk
+
+ import wasmtime
+
+ # This executes generated code, rather than merely importing the library.
+ store = wasmtime.Store()
+ module = wasmtime.Module(
+ store.engine, '(module (func (export "answer") (result i32) i32.const 42))'
+ )
+ instance = wasmtime.Instance(store, module, [])
+ if instance.exports(store)["answer"](store) != 42:
+ raise RuntimeError("Packaged Wasmtime execution failed")
+ state = {"launched": False, "ready": False, "timeout": False}
+ deadline = time.monotonic() + 120
+
+ def interact():
+ buttons = [
+ child
+ for frame in root.winfo_children()
+ for child in frame.winfo_children()
+ if isinstance(child, ttk.Button)
+ ]
+ launch = next(
+ button
+ for button in buttons
+ if button.cget("text") in ("Launch LNbits", "Stop LNbits", "Close")
+ )
+ browser = next(
+ button for button in buttons if button.cget("text") == "Open in browser"
+ )
+ if not state["launched"]:
+ launch.invoke()
+ state["launched"] = True
+ elif str(browser.cget("state")) == "normal":
+ state["ready"] = True
+ root.tk.call("tk::mac::Quit")
+ return
+ elif time.monotonic() > deadline:
+ state["timeout"] = True
+ root.tk.call("tk::mac::Quit")
+ return
+ root.after(100, interact)
+
+ root.after(100, interact)
+ return state
diff --git a/.github/packaging/macos/.env.macos-release.example b/.github/packaging/macos/.env.macos-release.example
new file mode 100644
index 0000000..0223b9f
--- /dev/null
+++ b/.github/packaging/macos/.env.macos-release.example
@@ -0,0 +1,7 @@
+# Mock values only. Replace all six; do not source this file.
+BUILD_CERTIFICATE_BASE64=bW9jay1wMTItbm90LWEtY2VydGlmaWNhdGU=
+P12_PASSWORD=mock-p12-password
+KEYCHAIN_PASSWORD=mock-temporary-keychain-password
+APPLE_ID=developer@example.invalid
+APPLE_TEAM_ID=MOCKTEAM01
+APPLE_APP_SPECIFIC_PASSWORD=mock-app-specific-password
diff --git a/.github/packaging/macos/README.md b/.github/packaging/macos/README.md
new file mode 100644
index 0000000..0b88582
--- /dev/null
+++ b/.github/packaging/macos/README.md
@@ -0,0 +1,296 @@
+# macOS release packaging
+
+The Python/PyInstaller and Tkinter app supports macOS 15 or later, with separate
+native Apple Silicon (`arm64`) and Intel (`x86_64`) builds. Its bundle identifier
+is `com.lnbits.desktop`. Each image contains `LNbits.app`, an Applications
+shortcut, and instructions appropriate to its signing status. User data lives
+outside the app in `~/Library/Application Support/LNbits` by default.
+
+The macOS packaging and bundled funding implementation was selectively ported
+from [arcbtc/lnbits at f664f0d](https://github.com/arcbtc/lnbits/tree/f664f0db96bd469405126852a7cd7a3ee42399fd).
+The original checkout already had the shared desktop entry point, but no macOS
+workflow, DMG builder, or sidecars. The port includes the required packaging
+helpers and tests; it does not import wallet changes, package version changes,
+or Python dependency/lockfile updates. Bundled funding is enabled only for
+macOS in this checkout. See [funding documentation](../README.md) for the pinned
+Node, Phoenixd and Spark versions, persistence, licensing, and offline checks.
+
+## Prerequisites
+
+Build on the target Mac architecture, without Rosetta. Install Python 3.12 with
+Tk (`python3 -c 'import tkinter'` must work), Node/npm 24, uv, Rust/Cargo,
+Homebrew `openssl@3`, and current Xcode command-line tools. Accept Xcode's license
+and check `xcrun notarytool --version`. Signing requires an Apple Developer
+Program membership, a valid Developer ID Application certificate **with its
+private key**, and access to Apple's authentication, timestamp, and notarization
+services. Native dependency downloads and npm audit also require network access.
+
+Homebrew installs Tk separately from Python. If importing `tkinter` fails with
+`ModuleNotFoundError: No module named '_tkinter'`, install the matching package:
+
+```sh
+brew install python-tk@3.12
+python3 -c 'import sys, tkinter; print(sys.executable); print(tkinter.TkVersion)'
+```
+
+Make sure `python3` selects that Homebrew Python 3.12. Installing a package named
+`tkinter` with pip does not provide this native Python module. Preparation checks
+Tk before installing dependencies, asks `uv` to use the checked interpreter, and
+checks Tk again inside the project environment before packaging.
+
+The command prepares locked dependencies and frontend assets, preserving the
+fork's static OpenSSL check. Intel's locked cryptography release is built from
+source. We clear its uv cache and reinstall with `OPENSSL_STATIC=1` and Homebrew's
+`OPENSSL_DIR`, then reject native bindings that still link shared `libssl` or
+`libcrypto`. This prevents PyInstaller from substituting an incompatible Python
+OpenSSL library. See [cryptography's build instructions](https://cryptography.io/en/latest/installation/#building-cryptography-on-macos).
+No project dependency or version update is needed.
+
+## Certificate and credentials
+
+In Keychain Access, find your **Developer ID Application: Name (TEAMID)** entry
+under My Certificates. Expand it and confirm that its private key is present.
+Export the certificate **and private key** as a password-protected `.p12`. A
+Developer ID Installer or Apple Development certificate will not work. Export
+only one current matching Developer ID Application identity; expired, untrusted,
+wrong-team, missing-private-key, or ambiguous matching identities fail the build.
+
+Base64-encode that export into a private file, without displaying it:
+
+```sh
+umask 077
+base64 -i /private/path/DeveloperID.p12 -o /private/path/certificate.base64
+```
+
+Keep both files private. Use these exact six names locally and as GitHub Actions
+repository/environment secrets:
+
+| Name | Value |
+| ----------------------------- | -------------------------------------------------------------------------------------------------------- |
+| `BUILD_CERTIFICATE_BASE64` | Base64-encoded P12 containing the certificate and private key; use a single line in the local file. |
+| `P12_PASSWORD` | The password chosen when exporting the P12. |
+| `KEYCHAIN_PASSWORD` | A separate strong password for the disposable build keychain; this is not your login password. |
+| `APPLE_ID` | The Apple account email associated with the developer team. |
+| `APPLE_TEAM_ID` | The ten-character Team ID from the Apple Developer account, matching the certificate. |
+| `APPLE_APP_SPECIFIC_PASSWORD` | An app-specific password generated at account.apple.com for this Apple account, not its normal password. |
+
+`.env.macos-release` is explicitly ignored by Git and is separate from LNbits'
+runtime `.env`. A tracked [example](.env.macos-release.example) contains mock
+values. A private mock local file was created during implementation only if it
+did not already exist. To initialize a fresh checkout without overwriting a file:
+
+```sh
+python3 - <<'PY'
+import os
+from pathlib import Path
+try:
+ fd = os.open('.env.macos-release', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+except FileExistsError:
+ pass
+else:
+ with os.fdopen(fd, 'w') as stream:
+ stream.write(Path('.github/packaging/macos/.env.macos-release.example').read_text())
+PY
+```
+
+Edit the local file privately and replace all six mock values. It must have mode
+`0600` (`chmod 600 .env.macos-release`). Use `NAME=value` or `NAME="value"`, one per
+line. There is no shell evaluation, variable expansion, multiline value syntax,
+or inline comment syntax. Do not `source` it or put these values in LNbits'
+runtime configuration. The release process reads it explicitly and removes all
+six variables from frontend, dependency, PyInstaller, and smoke-test subprocess
+environments. It never includes the file in the application.
+
+## Exact local commands
+
+From the repository root, build an ad-hoc development DMG without Apple credentials:
+
+```sh
+make build-macos
+```
+
+After configuring `.env.macos-release`, build a signed release artifact:
+
+```sh
+make build-macos-release
+```
+
+Both commands build the current Mac's native architecture and produce
+`dist/LNbits-v<VERSION>-macOS-<ARCH>.dmg` and `.dmg.sha256`. Version normalization
+is unchanged: for example, `1.6.2-rc1` becomes `1.6.2rc1` in the filename and
+`1.6.2` in the app metadata. Neither command publishes or creates a release.
+Build on each architecture; this is not a universal binary or a cross compiler.
+
+The original development entry points remain available after dependency setup:
+
+```sh
+uv run --no-sync python .github/packaging/build.py
+uv run --no-sync python .github/packaging/macos/dmg.py
+```
+
+The latter finalizes, ad-hoc signs and checks the existing app, then verifies the
+final mounted image. It does not submit anything to Apple. Merely setting
+`MACOS_CODESIGN_IDENTITY` on `build.py` does not notarize a release.
+
+## Shared release sequence and cleanup
+
+`macos/release.py` implements both local and CI release operations:
+
+1. Build the app, preserving dependency checks, then finalize all metadata.
+ Spark dependency prebuilds are filtered to the target Mac architecture before
+ packaging, removing other architectures and mobile/other-platform binaries.
+ The macOS PyInstaller hook likewise selects embit's matching libsecp256k1
+ prebuild as a binary. Check required data and every native architecture before
+ signing or submitting anything to Apple; repeat these checks on the final image.
+2. Decode the P12 inside a unique mode-0700 temporary directory, create/unlock a
+ temporary keychain, import the identity, remove the P12, and set the
+ `apple-tool:,apple:,codesign:` key partition list for unattended signing.
+ Save the original keychain search list, and store validated notarytool
+ credentials in this temporary keychain.
+3. Select exactly one valid Developer ID Application identity for the team.
+ Recursively detect Mach-O code by file magic, including files collected as
+ data inside Spark. Sign native files and nested bundles from the inside out,
+ then sign `LNbits.app`. All final signatures explicitly specify that identity
+ and temporary keychain, hardened runtime where applicable, and Apple's default
+ `--timestamp`. PyInstaller's preliminary ad-hoc signatures and signing
+ warnings are superseded only by successful explicit signing and verification.
+4. Verify every nested signature's Developer ID requirement, team, hardened
+ runtime, secure timestamp and exact entitlement policy. Create a temporary ZIP
+ with `ditto`, submit it once to `notarytool`, retain the submission ID, and wait
+ at most 30 minutes for JSON status exactly `Accepted`. Staple and validate the
+ app ticket. The ZIP is removed; the app is never modified or re-signed again.
+5. Copy that stapled app with `ditto` (preserving tickets, xattrs and symlinks) into
+ an uncompressed temporary HFS+ image with Spotlight indexing disabled, then
+ convert it to the final compressed UDZO DMG. Each image operation has a
+ 20-minute timeout, elapsed-time progress, and sanitized `hdiutil` diagnostics.
+ Only the final compressed DMG is signed and submitted to Apple. Require `Accepted`, then
+ staple and validate the DMG. There are **two submissions**, one for the app ZIP
+ and one for the final image. The DMG is not rebuilt after notarization.
+6. Verify final image integrity, signature, ticket and Gatekeeper assessment.
+ Mount that exact image read-only and verify the contained app with
+ `codesign --verify --deep --strict`, Developer ID/team requirements, Gatekeeper,
+ stapler, native architecture and required bundled data checks. Run the existing
+ sidecar authentication/shutdown and packaged server smoke checks, plus packaged
+ Tk launcher/quit and Wasmtime execution checks, with disposable external data.
+7. Detach the image, restore and verify the original keychain search list, delete
+ the keychain and temporary directory, then generate and recheck the SHA-256
+ checksum against the final stapled DMG bytes. Any failure, including cleanup,
+ fails the release and removes the attempted DMG/checksum.
+
+A private recovery journal under `build/` contains paths and the original search
+list, never credentials. Normal exceptions and SIGINT/SIGTERM trigger cleanup.
+After an uncatchable termination or machine restart, recover before building:
+
+```sh
+python3 .github/packaging/macos/release.py --cleanup
+```
+
+Do not run concurrent local builds using the same checkout. CI uses a journal in
+`RUNNER_TEMP` and an `always()` cleanup step **before** artifact upload. The journal
+is retained if cleanup fails, so recovery can be retried. For a custom journal,
+pass `--state /path/to/state.json` to both the build and cleanup commands.
+Verification mount paths are resolved before comparison with `hdiutil`, including
+the `/var` and `/private/var` aliases. If verification and cleanup both fail, the
+original verification error is preserved and sanitized cleanup diagnostics are
+reported separately. Fixes that change bundled content require rebuilding the app;
+`--skip-build` reuses the existing contents.
+
+## Entitlements
+
+The policy is deliberately smaller than upstream general-purpose runtimes'
+entitlement lists:
+
+- **LNbits/Python executable and enclosing app:**
+ `com.apple.security.cs.allow-unsigned-executable-memory`. The locked Wasmtime
+ runtime publishes compiled WebAssembly code using ordinary `mmap` and
+ `mprotect(PROT_EXEC)`, without `MAP_JIT`; `allow-jit` alone does not cover that
+ path. See the [Wasmtime v45 implementation](https://github.com/bytecodealliance/wasmtime/blob/v45.0.0/crates/wasmtime/src/runtime/vm/sys/unix/mmap.rs).
+- **Node executable:** `com.apple.security.cs.allow-jit` on both architectures,
+ plus `com.apple.security.cs.allow-unsigned-executable-memory` on **x86_64 only**.
+ The pinned Node 24.21.0 crashes during V8 code-range initialization on Intel
+ macOS 26.6.2 with `allow-jit` alone (`OS::SetPermissions`, `SIGTRAP`). A controlled
+ comparison of hardened, ad-hoc-signed copies reproduced the crash with only
+ `allow-jit` and passed JavaScript execution when the unsigned-memory exception
+ was added. This exception is scoped to Intel Node; arm64 retains `allow-jit`
+ alone. See [Apple's unsigned executable memory entitlement](https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.security.cs.allow-unsigned-executable-memory)
+ and the [pinned Node entitlement list](https://github.com/nodejs/node/blob/v24.21.0/tools/osx-entitlements.plist).
+ All shipped native add-ons are re-signed by the same team, so loading them does
+ not require disabling library validation.
+- **Phoenixd, Python/Tk libraries, extensions and other native libraries:** no
+ executable-memory exceptions. The [Phoenixd distribution](https://github.com/ACINQ/phoenixd)
+ uses Kotlin/Native on macOS rather than a JVM JIT. Entitlements belong on the
+ host executable, not each loaded library.
+
+No debug entitlement, disabled library validation, disabled executable-page
+protection, DYLD environment exception, or Electron entitlements are enabled.
+`MACOS_ENTITLEMENTS_FILE` can select a Python plist only if its contents equal
+this policy; an override cannot silently broaden a release. If set on the shared
+release script, `MACOS_CODESIGN_IDENTITY` must equal the selected certificate's
+fingerprint. Credential-based selection remains authoritative.
+
+These choices must still be confirmed in real Developer ID builds on **both**
+architectures. The mounted smoke checks execute Wasmtime-generated code and Node
+and exercise the native Phoenixd executable; failures stop publication. The Node
+probe evaluates JavaScript before starting Spark, because `node --version` does
+not initialize V8 and can succeed with broken JIT permissions. It clears inherited
+`NODE_OPTIONS` so `--jitless` cannot hide the failure. Both Spark and Phoenixd are
+launched through the bundled Node supervisor. Validate a downloaded signed build
+on a physical Intel Mac, including macOS 26, as well as the macOS 15 CI runners.
+
+## GitHub Actions
+
+`macos.yml` retains `macos-15` (arm64) and `macos-15-intel` (x86_64). Automatic builds
+run through the stable and RC release workflows. Temporarily, same-repository pull
+requests also build signed artifacts for testing, without attaching them to a
+release. Fork PRs are skipped because they do not receive the Apple secrets.
+Remove the `pull_request` trigger when returning to release-only automatic builds.
+Every CI build, including manual runs, requires Developer ID signing and
+notarization. There is no unsigned CI option. All six GitHub Actions secrets must
+be configured; missing or invalid credentials fail the build.
+
+For a manual `workflow_dispatch`, leave the release tag empty for signed, notarized
+**artifact-only** builds. Supplying a release tag also attaches the verified assets
+to that release. The stable and RC callers explicitly pass all six secrets.
+Unsigned development builds remain available locally through `make build-macos`.
+
+Credentials are scoped to the signed build step. Dependency preparation and
+launcher/packaging tests run separately without them. CI calls the same release
+implementation as `make build-macos-release`. Upload requires successful signing,
+notarization, final-image smoke checks, checksum generation, and cleanup.
+
+## Troubleshooting and release validation
+
+- **Identity/import failure:** export the certificate with its private key, check
+ P12 password, certificate expiry, trust chain and team, and remove ambiguous
+ matching certificates from the exported P12. The login keychain is not used to
+ silently fill in missing credentials.
+- **Authentication failure (401/403):** verify Apple ID, Team ID, app-specific
+ password, developer membership and any pending Apple agreements. Store-credentials
+ validates the account before submission. Do not paste secrets into build logs.
+- **Timestamp failure:** allow Apple's timestamp service through the network or
+ proxy and check the system clock. The command uses `--timestamp` without a
+ custom URL; never work around a release failure by omitting timestamps.
+- **Notarization rejection or timeout:** logs show a sanitized operation name,
+ submission ID and status, and rejection diagnostics where available. `Accepted`
+ is the only passing status. A timeout fails the build even if Apple's service
+ later completes. Investigate that ID in Apple's tools before retrying; the
+ pipeline never automatically submits the same artifact again.
+- **Gatekeeper or smoke failure:** check the exact image on the matching native
+ architecture; do not disable Gatekeeper or broaden entitlements without finding
+ the failing executable/runtime requirement.
+- **DMG creation timeout:** the log distinguishes image creation from compression
+ and reports staging size and available disk space. Long operations print a
+ heartbeat every 30 seconds and retain sanitized tool output on failure. A timeout
+ stops the tool's process group and fails the build; it never uploads a partial image.
+
+Run `make test-desktop` for mocked Apple-tool tests, identity validation,
+notarization/signing order, failure and cleanup gates, checksum generation,
+launcher controls, and bundled funding lifecycle tests. No test uses real Apple
+credentials or submits real notarization. CI additionally tests the final mounted
+contents. Before distribution, test an actually downloaded/quarantined signed DMG
+on macOS 15 on each architecture: drag to Applications, open normally, configure,
+start, install an extension, stop, restart and quit. Hosted CI and mocks cannot
+establish real Apple acceptance, quarantine behavior or every runtime on both Macs.
+
+See [Apple's notarization workflow](https://developer.apple.com/documentation/security/customizing-the-notarization-workflow)
+and [code-signing guidance](https://developer.apple.com/documentation/technotes/tn3161-inside-code-signing-certificates).
diff --git a/.github/packaging/macos/Read me unsigned.txt b/.github/packaging/macos/Read me unsigned.txt
new file mode 100644
index 0000000..141cbee
--- /dev/null
+++ b/.github/packaging/macos/Read me unsigned.txt
@@ -0,0 +1,44 @@
+LNbits for macOS
+
+Requires macOS 15 or later. Use the arm64 download for Apple Silicon
+(M-series) Macs and the x86_64 download for Intel Macs.
+
+Installation
+Drag LNbits.app to Applications, eject this disk image, and open LNbits
+from Applications. Choose your settings, click Launch LNbits, then
+Open in browser. Python and Node.js do not need to be installed.
+
+These builds are not Apple Developer ID signed or notarized. macOS may
+block the first launch. If you trust the download, attempt to open it,
+then use System Settings > Privacy & Security > Open Anyway and confirm.
+You do not need to disable Gatekeeper or System Integrity Protection.
+
+Data and updates
+Wallets, settings, extensions and logs are stored separately from the app,
+by default in ~/Library/Application Support/LNbits. The launcher lets you
+choose another data folder. Keep that folder backed up.
+
+Bundled funding
+Choose Spark L2, Phoenixd or Neither in the launcher. First setup of a bundled
+funding source requires a new data folder. The app starts the selected daemon
+and configures LNbits automatically. The funding seed persists in
+funding/spark/seed.dat (24 words) or funding/phoenixd/seed.dat (12 words).
+Back up the entire data folder and keep a private offline seed backup.
+Never run another Phoenix instance with the same seed. Phoenixd first setup
+asks you to acknowledge its automatic liquidity fees and fee-credit terms.
+Closing the launcher stops both LNbits and its funding daemon.
+
+To update, stop LNbits and quit the app before replacing it in Applications.
+Replacing or removing the app does not remove your data folder.
+Keep the launcher open while using LNbits. Stop LNbits or quit the launcher
+to shut down its server.
+
+Terminal usage
+/Applications/LNbits.app/Contents/MacOS/LNbits --headless --port 5001
+/Applications/LNbits.app/Contents/MacOS/LNbits --gui
+
+Logs are in the selected data folder under logs/desktop.log.
+Custom SSL_CERT_FILE or SSL_CERT_DIR environment settings are respected.
+
+Project: https://lnbits.com
+Source: https://github.com/lnbits/lnbits
diff --git a/.github/packaging/macos/Read me.txt b/.github/packaging/macos/Read me.txt
new file mode 100644
index 0000000..0b4dede
--- /dev/null
+++ b/.github/packaging/macos/Read me.txt
@@ -0,0 +1,44 @@
+LNbits for macOS
+
+Requires macOS 15 or later. Use the arm64 download for Apple Silicon
+(M-series) Macs and the x86_64 download for Intel Macs.
+
+Installation
+Drag LNbits.app to Applications, eject this disk image, and open LNbits
+from Applications. Choose your settings, click Launch LNbits, then
+Open in browser. Python and Node.js do not need to be installed.
+
+This release is Apple Developer ID signed and notarized. Both the app and
+the disk image carry stapled Apple notarization tickets. Open the app normally;
+no Gatekeeper bypass is needed. If macOS rejects it, verify the download checksum
+and contact the release maintainer.
+
+Data and updates
+Wallets, settings, extensions and logs are stored separately from the app,
+by default in ~/Library/Application Support/LNbits. The launcher lets you
+choose another data folder. Keep that folder backed up.
+
+Bundled funding
+Choose Spark L2, Phoenixd or Neither in the launcher. First setup of a bundled
+funding source requires a new data folder. The app starts the selected daemon
+and configures LNbits automatically. The funding seed persists in
+funding/spark/seed.dat (24 words) or funding/phoenixd/seed.dat (12 words).
+Back up the entire data folder and keep a private offline seed backup.
+Never run another Phoenix instance with the same seed. Phoenixd first setup
+asks you to acknowledge its automatic liquidity fees and fee-credit terms.
+Closing the launcher stops both LNbits and its funding daemon.
+
+To update, stop LNbits and quit the app before replacing it in Applications.
+Replacing or removing the app does not remove your data folder.
+Keep the launcher open while using LNbits. Stop LNbits or quit the launcher
+to shut down its server.
+
+Terminal usage
+/Applications/LNbits.app/Contents/MacOS/LNbits --headless --port 5001
+/Applications/LNbits.app/Contents/MacOS/LNbits --gui
+
+Logs are in the selected data folder under logs/desktop.log.
+Custom SSL_CERT_FILE or SSL_CERT_DIR environment settings are respected.
+
+Project: https://lnbits.com
+Source: https://github.com/lnbits/lnbits
diff --git a/.github/packaging/macos/common.py b/.github/packaging/macos/common.py
new file mode 100644
index 0000000..645936f
--- /dev/null
+++ b/.github/packaging/macos/common.py
@@ -0,0 +1,195 @@
+"""Sanitized subprocess boundary shared by macOS build and release tools."""
+
+import base64
+import contextlib
+import json
+import os
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.parse
+
+CREDENTIAL_NAMES = (
+ "BUILD_CERTIFICATE_BASE64",
+ "P12_PASSWORD",
+ "KEYCHAIN_PASSWORD",
+ "APPLE_ID",
+ "APPLE_TEAM_ID",
+ "APPLE_APP_SPECIFIC_PASSWORD",
+)
+
+
+class ReleaseError(Exception):
+ """A safe, actionable release failure (never includes a command line)."""
+
+
+def error_message(error):
+ if isinstance(error, ReleaseError):
+ return str(error)
+ return f"Release operation failed ({type(error).__name__})"
+
+
+@contextlib.contextmanager
+def cleanup_on_exit(action, runner):
+ try:
+ yield
+ except BaseException:
+ try:
+ action()
+ except Exception as error:
+ # Keep the original failing operation; report secondary failures too.
+ print(
+ runner.redact(f"Cleanup also failed: {error_message(error)}"),
+ file=sys.stderr,
+ )
+ raise
+ else:
+ # Cleanup alone must still fail the release and prevent publication.
+ action()
+
+
+def clean_environment(environment):
+ return {
+ name: value
+ for name, value in environment.items()
+ if name not in CREDENTIAL_NAMES
+ and name not in ("MACOS_CODESIGN_IDENTITY", "MACOS_ENTITLEMENTS_FILE")
+ }
+
+
+class Runner:
+ def __init__(self, credentials=None):
+ values = [os.environ.get(name, "") for name in CREDENTIAL_NAMES]
+ values += list((credentials or {}).values())
+ self.secrets = set()
+ for value in filter(None, values):
+ self.secrets.update(
+ (value, json.dumps(value)[1:-1], urllib.parse.quote(value, safe=""))
+ )
+ certificate = (credentials or {}).get("BUILD_CERTIFICATE_BASE64", "")
+ if certificate:
+ self.secrets.add("".join(certificate.split()))
+ self.environment = clean_environment(os.environ)
+ self.environment["MACOSX_DEPLOYMENT_TARGET"] = "15.0"
+
+ def redact(self, text):
+ if isinstance(text, bytes):
+ text = text.decode(errors="replace")
+ for secret in sorted(self.secrets, key=len, reverse=True):
+ text = text.replace(secret, "[REDACTED]")
+ # No ANSI/control sequences in CI diagnostics.
+ return "".join(c for c in text if c in "\n\t" or c.isprintable())
+
+ def run(
+ self, operation, *args, timeout=300, env=None, check=True, log_output=False
+ ):
+ print(self.redact(f"macOS: {operation}"), flush=True)
+ environment = dict(self.environment, **(env or {}))
+ # Sanitize using credentials inherited by this process, even if a caller
+ # supplied a different environment for the child.
+ try:
+ if log_output:
+ result = self.run_logged(operation, args, timeout, environment)
+ else:
+ result = subprocess.run( # noqa: S603
+ [str(arg) for arg in args],
+ env=clean_environment(environment),
+ stdin=subprocess.DEVNULL,
+ capture_output=True,
+ text=True,
+ errors="replace",
+ timeout=timeout,
+ check=False,
+ )
+ except subprocess.TimeoutExpired as exc:
+ diagnostic = self.redact(exc.stdout or "") + self.redact(exc.stderr or "")
+ raise ReleaseError(
+ f"{operation}: timed out. {diagnostic[-6000:]}"
+ ) from None
+ except OSError:
+ raise ReleaseError(f"{operation}: could not execute tool") from None
+ if check and result.returncode:
+ diagnostic = self.redact(result.stdout + result.stderr)
+ raise ReleaseError(
+ f"{operation}: exit {result.returncode}. {diagnostic[-6000:]}"
+ ) from None
+ return result
+
+ def run_logged(self, operation, args, timeout, environment):
+ """Heartbeat long builds; redact complete output without logging arguments."""
+ started = time.monotonic()
+ command = [str(arg) for arg in args]
+ # A private temporary file avoids pipes held open by tool subprocesses.
+ with tempfile.TemporaryFile() as log:
+ with subprocess.Popen( # noqa: S603
+ command,
+ env=clean_environment(environment),
+ stdin=subprocess.DEVNULL,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+ start_new_session=os.name == "posix",
+ ) as process:
+ try:
+ while True:
+ remaining = timeout - (time.monotonic() - started)
+ if remaining <= 0:
+ raise subprocess.TimeoutExpired(command, timeout)
+ try:
+ process.wait(timeout=min(30, remaining))
+ break
+ except subprocess.TimeoutExpired:
+ elapsed = time.monotonic() - started
+ print(
+ self.redact(
+ f"macOS: {operation}: running for {elapsed:.0f}s "
+ f"(limit {timeout}s)"
+ ),
+ flush=True,
+ )
+ except BaseException as error:
+ # Stop this tool's process group, never unrelated disk helpers.
+ try:
+ if os.name == "posix":
+ os.killpg(process.pid, signal.SIGKILL)
+ else:
+ process.kill()
+ except ProcessLookupError:
+ pass
+ process.wait(timeout=10)
+ if isinstance(error, subprocess.TimeoutExpired):
+ log.seek(0)
+ error.output = log.read()
+ raise
+ log.seek(0)
+ output = log.read().decode(errors="replace")
+ elapsed = time.monotonic() - started
+ print(
+ self.redact(
+ f"macOS: {operation}: exit {process.returncode} after {elapsed:.1f}s"
+ ),
+ flush=True,
+ )
+ if output:
+ print(self.redact(output)[-12000:], flush=True)
+ return subprocess.CompletedProcess(command, process.returncode, output, "")
+
+
+def validate_credentials(values):
+ missing = [name for name in CREDENTIAL_NAMES if not values.get(name, "").strip()]
+ if missing:
+ raise ReleaseError("Missing release credentials: " + ", ".join(missing))
+ import re
+
+ if not re.fullmatch(r"[A-Z0-9]{10}", values["APPLE_TEAM_ID"]):
+ raise ReleaseError("APPLE_TEAM_ID must be a ten-character Apple team ID")
+ try:
+ certificate = base64.b64decode(
+ "".join(values["BUILD_CERTIFICATE_BASE64"].split()), validate=True
+ )
+ except ValueError:
+ raise ReleaseError("BUILD_CERTIFICATE_BASE64 is not valid base64") from None
+ if not certificate:
+ raise ReleaseError("BUILD_CERTIFICATE_BASE64 is empty")
+ return certificate
diff --git a/.github/packaging/macos/credentials.py b/.github/packaging/macos/credentials.py
new file mode 100644
index 0000000..766676b
--- /dev/null
+++ b/.github/packaging/macos/credentials.py
@@ -0,0 +1,302 @@
+"""Private, recoverable release credentials and temporary keychain lifecycle."""
+
+import json
+import os
+import re
+import shlex
+import shutil
+import stat
+import tempfile
+from pathlib import Path
+
+from macos.common import (
+ CREDENTIAL_NAMES,
+ ReleaseError,
+ error_message,
+ validate_credentials,
+)
+
+PROFILE = "lnbits-notarization"
+
+
+def load_credentials(env_file=None):
+ if env_file is None:
+ return {name: os.environ.get(name, "") for name in CREDENTIAL_NAMES}
+ path = Path(env_file)
+ if path.is_symlink() or not path.is_file():
+ raise ReleaseError("Expected a regular .env.macos-release file")
+ if stat.S_IMODE(path.stat().st_mode) != 0o600:
+ raise ReleaseError("Set .env.macos-release permissions to 0600")
+ values = {}
+ # Deliberately not shell-sourced and never passed through runtime dotenv.
+ for line in path.read_text(encoding="utf-8").splitlines():
+ if not line.strip() or line.lstrip().startswith("#"):
+ continue
+ name, separator, value = line.partition("=")
+ name, value = name.strip(), value.strip()
+ if not separator or name not in CREDENTIAL_NAMES or name in values:
+ raise ReleaseError("Invalid or duplicate key in .env.macos-release")
+ if value[:1] in ("'", '"'):
+ if len(value) < 2 or value[-1] != value[0]:
+ raise ReleaseError("Unclosed quote in .env.macos-release")
+ value = value[1:-1]
+ values[name] = value
+ return values
+
+
+def select_identity(output, team):
+ identities = re.findall(
+ r'^\s*\d+\) ([A-Fa-f0-9]{40}) "Developer ID Application: [^"\n]+ '
+ r'\(([A-Z0-9]{10})\)"\s*$',
+ output,
+ re.MULTILINE,
+ )
+ matches = {
+ fingerprint.upper() for fingerprint, owner in identities if owner == team
+ }
+ if len(matches) != 1:
+ raise ReleaseError(
+ "Select signing identity: expected exactly one valid Developer ID "
+ "Application identity for APPLE_TEAM_ID; check certificate expiry, "
+ "private key, team and duplicate certificates"
+ )
+ return matches.pop()
+
+
+class Session:
+ def __init__(self, path, runner):
+ self.path = Path(path).resolve()
+ self.runner = runner
+ self.state = {
+ "directory": None,
+ "keychain": None,
+ "search_list": None,
+ "mount": None,
+ }
+
+ def begin(self):
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ descriptor = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ except FileExistsError:
+ raise ReleaseError(
+ "A release session already exists; run the documented cleanup command"
+ ) from None
+ with os.fdopen(descriptor, "w") as stream:
+ json.dump(self.state, stream)
+
+ def save(self):
+ with tempfile.NamedTemporaryFile(
+ mode="w", dir=self.path.parent, delete=False
+ ) as stream:
+ temporary = Path(stream.name)
+ try:
+ os.chmod(temporary, 0o600)
+ json.dump(self.state, stream)
+ stream.flush()
+ os.fsync(stream.fileno())
+ except BaseException:
+ temporary.unlink(missing_ok=True)
+ raise
+ try:
+ os.replace(temporary, self.path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+ def setup(self, credentials):
+ certificate = validate_credentials(credentials)
+ original = self.runner.run(
+ "Read keychain search list",
+ "/usr/bin/security",
+ "list-keychains",
+ "-d",
+ "user",
+ )
+ self.state["search_list"] = shlex.split(original.stdout)
+ directory = Path(tempfile.mkdtemp(prefix="lnbits-release-"))
+ directory.chmod(0o700)
+ keychain = directory / "signing.keychain-db"
+ self.state.update(directory=str(directory), keychain=str(keychain))
+ self.save()
+ p12 = directory / "certificate.p12"
+ with p12.open("xb") as stream:
+ p12.chmod(0o600)
+ stream.write(certificate)
+ password = credentials["KEYCHAIN_PASSWORD"]
+ self.runner.run(
+ "Create temporary keychain",
+ "/usr/bin/security",
+ "create-keychain",
+ "-p",
+ password,
+ keychain,
+ )
+ self.runner.run(
+ "Unlock temporary keychain",
+ "/usr/bin/security",
+ "unlock-keychain",
+ "-p",
+ password,
+ keychain,
+ )
+ self.runner.run(
+ "Set keychain timeout",
+ "/usr/bin/security",
+ "set-keychain-settings",
+ "-lut",
+ "21600",
+ keychain,
+ )
+ # Keep original entries accessible; every final codesign also uses --keychain.
+ self.runner.run(
+ "Add temporary keychain",
+ "/usr/bin/security",
+ "list-keychains",
+ "-d",
+ "user",
+ "-s",
+ keychain,
+ *self.state["search_list"],
+ )
+ try:
+ self.runner.run(
+ "Import Developer ID certificate",
+ "/usr/bin/security",
+ "import",
+ p12,
+ "-k",
+ keychain,
+ "-P",
+ credentials["P12_PASSWORD"],
+ "-T",
+ "/usr/bin/codesign",
+ "-T",
+ "/usr/bin/security",
+ )
+ finally:
+ p12.unlink(missing_ok=True)
+ self.runner.run(
+ "Allow unattended codesign",
+ "/usr/bin/security",
+ "set-key-partition-list",
+ "-S",
+ "apple-tool:,apple:,codesign:",
+ "-s",
+ "-k",
+ password,
+ keychain,
+ )
+ result = self.runner.run(
+ "Select signing identity",
+ "/usr/bin/security",
+ "find-identity",
+ "-v",
+ "-p",
+ "codesigning",
+ keychain,
+ )
+ identity = select_identity(result.stdout, credentials["APPLE_TEAM_ID"])
+ self.runner.run(
+ "Store notarization credentials",
+ "/usr/bin/xcrun",
+ "notarytool",
+ "store-credentials",
+ PROFILE,
+ "--keychain",
+ keychain,
+ "--apple-id",
+ credentials["APPLE_ID"],
+ "--team-id",
+ credentials["APPLE_TEAM_ID"],
+ "--password",
+ credentials["APPLE_APP_SPECIFIC_PASSWORD"],
+ )
+ return identity
+
+ def cleanup(self):
+ errors = []
+ for action in (self.detach, self.restore_search_list, self.delete_keychain):
+ try:
+ action()
+ except Exception as error:
+ # Continue every cleanup operation; retain state for recovery.
+ errors.append(
+ f"{action.__name__}: {self.runner.redact(error_message(error))}"
+ )
+ if errors:
+ raise ReleaseError("Cleanup failed: " + ", ".join(errors))
+ if self.state["directory"] and Path(self.state["directory"]).exists():
+ shutil.rmtree(self.state["directory"])
+ self.path.unlink(missing_ok=True)
+
+ def restore_search_list(self):
+ original = self.state["search_list"]
+ if original is None:
+ return
+ self.runner.run(
+ "Restore keychain search list",
+ "/usr/bin/security",
+ "list-keychains",
+ "-d",
+ "user",
+ "-s",
+ *original,
+ )
+ restored = self.runner.run(
+ "Verify restored keychain search list",
+ "/usr/bin/security",
+ "list-keychains",
+ "-d",
+ "user",
+ )
+ if shlex.split(restored.stdout) != original:
+ raise ReleaseError("Keychain search list restoration did not match")
+ self.state["search_list"] = None
+ self.save()
+
+ def delete_keychain(self):
+ keychain = self.state["keychain"]
+ if keychain and Path(keychain).exists():
+ self.runner.run(
+ "Delete temporary keychain",
+ "/usr/bin/security",
+ "delete-keychain",
+ keychain,
+ )
+ if Path(keychain).exists():
+ raise ReleaseError("Temporary keychain still exists after deletion")
+ self.state["keychain"] = None
+ self.save()
+
+ def detach(self):
+ mount = self.state["mount"]
+ if not mount:
+ return
+ # hdiutil reports /private/var even when tempfile used its /var alias.
+ mount = Path(mount).resolve()
+ # An attach failure can still leave a mounted device. Query actual state.
+ import plistlib
+
+ result = self.runner.run(
+ "Inspect mounted images", "/usr/bin/hdiutil", "info", "-plist"
+ )
+ mounted = any(
+ Path(entity["mount-point"]).resolve() == mount
+ for item in plistlib.loads(result.stdout.encode()).get("images", [])
+ for entity in item.get("system-entities", [])
+ if entity.get("mount-point")
+ )
+ if mounted:
+ self.runner.run("Detach final DMG", "/usr/bin/hdiutil", "detach", mount)
+ if mount.exists():
+ mount.rmdir()
+ self.state["mount"] = None
+ self.save()
+
+
+def cleanup(path, runner):
+ session = Session(path, runner)
+ if not session.path.exists():
+ return
+ session.state = json.loads(session.path.read_text())
+ session.cleanup()
diff --git a/.github/packaging/macos/dmg.py b/.github/packaging/macos/dmg.py
index 76e44fd..97f35fd 100644
--- a/.github/packaging/macos/dmg.py
+++ b/.github/packaging/macos/dmg.py
@@ -1,82 +1,128 @@
-"""Create a versioned, verified DMG from the PyInstaller app on macOS."""
+"""Finalize metadata before signing; image creation never edits the staged app."""
import hashlib
-import os
import platform
import plistlib
import shutil
-import subprocess
import sys
import tempfile
from pathlib import Path
import tomllib
-from packaging.version import Version
-def run(*args):
- subprocess.run(args, check=True) # noqa: S603
+def output_path():
+ from packaging.version import Version
+ version = Version(
+ tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
+ )
+ return Path("dist", f"LNbits-v{version}-macOS-{platform.machine()}.dmg").resolve()
+
+
+def finalize_app(app):
+ from packaging.version import Version
-def main():
- if sys.platform != "darwin":
- raise SystemExit("Build the DMG on macOS.")
version = Version(
tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
)
- output = Path("dist", f"LNbits-v{version}-macOS-{platform.machine()}.dmg").resolve()
- identity = os.environ.get("MACOS_CODESIGN_IDENTITY") or "-"
+ plist = app / "Contents/Info.plist"
+ info = plistlib.loads(plist.read_bytes())
+ info.update(
+ CFBundleIdentifier="com.lnbits.desktop",
+ CFBundleDisplayName="LNbits",
+ CFBundleShortVersionString=version.base_version,
+ CFBundleVersion=version.base_version,
+ LSMinimumSystemVersion="15.0",
+ LSApplicationCategoryType="public.app-category.finance",
+ NSHighResolutionCapable=True,
+ )
+ plist.write_bytes(plistlib.dumps(info))
+
+
+def create(app, output, runner, *, signed):
with tempfile.TemporaryDirectory(prefix="lnbits-dmg-") as directory:
- staging = Path(directory)
- app = staging / "LNbits.app"
- shutil.copytree("dist/LNbits.app", app, symlinks=True)
- plist = app / "Contents/Info.plist"
- with plist.open("rb") as stream:
- info = plistlib.load(stream)
- info.update(
- CFBundleDisplayName="LNbits",
- CFBundleShortVersionString=version.base_version,
- CFBundleVersion=version.base_version,
- LSMinimumSystemVersion="15.0",
- LSApplicationCategoryType="public.app-category.finance",
- NSHighResolutionCapable=True,
- )
- with plist.open("wb") as stream:
- plistlib.dump(info, stream)
- # Updating Info.plist invalidates the outer bundle signature. Nested
- # binaries retain the signatures applied by PyInstaller during the build.
- signing = ["/usr/bin/codesign", "--force", "--sign", identity]
- if identity != "-":
- signing += ["--options", "runtime", "--timestamp"]
- if entitlements := os.environ.get("MACOS_ENTITLEMENTS_FILE"):
- signing += ["--entitlements", entitlements]
- run(*signing, str(app))
- run("/usr/bin/codesign", "--verify", "--deep", "--strict", str(app))
+ workspace = Path(directory)
+ staging = workspace / "contents"
+ staging.mkdir()
+ uncompressed = workspace / "uncompressed.dmg"
+ # ditto preserves the stapled ticket, resource forks, xattrs and symlinks.
+ runner.run("Copy finalized app", "/usr/bin/ditto", app, staging / "LNbits.app")
(staging / "Applications").symlink_to("/Applications")
- run(
+ instructions = "Read me.txt" if signed else "Read me unsigned.txt"
+ shutil.copyfile(Path(__file__).with_name(instructions), staging / "Read me.txt")
+ runner.run(
+ "Inspect DMG staging size", "/usr/bin/du", "-sh", staging, log_output=True
+ )
+ runner.run(
+ "Inspect DMG free space",
+ "/bin/df",
+ "-h",
+ workspace,
+ output.parent,
+ log_output=True,
+ )
+ # Separate filesystem creation from compression on slower Intel runners.
+ # The intermediate image is outside the source folder and is never signed
+ # or notarized. Conversion finishes before the final DMG release sequence.
+ runner.run(
+ "Create uncompressed DMG",
"/usr/bin/hdiutil",
"create",
"-volname",
"LNbits",
"-srcfolder",
- str(staging),
+ staging,
"-fs",
"HFS+",
"-format",
+ "UDRW",
+ "-nospotlight",
+ "-verbose",
+ "-puppetstrings",
+ "-ov",
+ uncompressed,
+ timeout=1200,
+ log_output=True,
+ )
+ runner.run(
+ "Compress final DMG",
+ "/usr/bin/hdiutil",
+ "convert",
+ uncompressed,
+ "-format",
"UDZO",
+ "-tasks",
+ "2",
+ "-verbose",
+ "-puppetstrings",
"-ov",
- str(output),
+ "-o",
+ output,
+ timeout=1200,
+ log_output=True,
)
- run("/usr/bin/hdiutil", "verify", str(output))
+
+
+def checksum(output):
digest = hashlib.sha256()
with output.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
- output.with_suffix(".dmg.sha256").write_text(
- f"{digest.hexdigest()} {output.name}\n", encoding="utf-8"
- )
- print(output)
+ return f"{digest.hexdigest()} {output.name}\n"
+
+
+def write_checksum(output):
+ path = output.with_suffix(".dmg.sha256")
+ path.write_text(checksum(output), encoding="utf-8")
+ if path.read_text(encoding="utf-8") != checksum(output):
+ path.unlink()
+ raise RuntimeError("Final DMG checksum verification failed")
if __name__ == "__main__":
- main()
+ # Keep the old unsigned command, routed through the single verification path.
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+ from macos.release import main
+
+ main(["--unsigned", "--skip-build"])
diff --git a/.github/packaging/macos/entitlements/node-x86_64.plist b/.github/packaging/macos/entitlements/node-x86_64.plist
new file mode 100644
index 0000000..26b12f2
--- /dev/null
+++ b/.github/packaging/macos/entitlements/node-x86_64.plist
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+</dict>
+</plist>
diff --git a/.github/packaging/macos/entitlements/node.plist b/.github/packaging/macos/entitlements/node.plist
new file mode 100644
index 0000000..d35e43a
--- /dev/null
+++ b/.github/packaging/macos/entitlements/node.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.cs.allow-jit</key>
+ <true/>
+</dict>
+</plist>
diff --git a/.github/packaging/macos/entitlements/python.plist b/.github/packaging/macos/entitlements/python.plist
new file mode 100644
index 0000000..a1c430a
--- /dev/null
+++ b/.github/packaging/macos/entitlements/python.plist
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
+ <true/>
+</dict>
+</plist>
diff --git a/.github/packaging/macos/hooks/hook-embit.py b/.github/packaging/macos/hooks/hook-embit.py
new file mode 100644
index 0000000..3bba734
--- /dev/null
+++ b/.github/packaging/macos/hooks/hook-embit.py
@@ -0,0 +1,25 @@
+"""Collect embit's native Mac library without its other platform prebuilds."""
+
+import platform
+from pathlib import Path
+
+from PyInstaller.utils.hooks import collect_all
+
+datas, binaries, hiddenimports = collect_all("embit")
+library = f"libsecp256k1_darwin_{platform.machine()}.dylib"
+native = {
+ (source, destination)
+ for source, destination in [*datas, *binaries]
+ if Path(source).name == library
+}
+if not native:
+ raise RuntimeError(f"Missing native embit prebuild: {library}")
+
+# Include the selected library as code, even if collect_all classified it as data.
+datas = [
+ entry for entry in datas if not Path(entry[0]).name.startswith("libsecp256k1_")
+]
+binaries = [
+ entry for entry in binaries if not Path(entry[0]).name.startswith("libsecp256k1_")
+] + sorted(native)
+print(f"macOS: Selected embit native library: {library}", flush=True)
diff --git a/.github/packaging/macos/release.py b/.github/packaging/macos/release.py
new file mode 100644
index 0000000..64e8c3d
--- /dev/null
+++ b/.github/packaging/macos/release.py
@@ -0,0 +1,252 @@
+"""One local/CI build, signing, notarization and verification pipeline. No upload."""
+
+import argparse
+import os
+import platform
+import signal
+import sys
+from pathlib import Path
+
+if __package__ in (None, ""):
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from macos import dmg
+from macos.common import (
+ ReleaseError,
+ Runner,
+ cleanup_on_exit,
+ error_message,
+ validate_credentials,
+)
+from macos.credentials import Session, cleanup, load_credentials
+from macos.signing import notarize, sign, sign_app, staple, verify_app
+from macos.verify import bundled_data, verify_image
+
+
+def check_python_tk(runner, *python):
+ result = runner.run(
+ "Check Python/Tk",
+ *python,
+ "-c",
+ "import tkinter; import tomllib; tkinter.Tcl().eval('info patchlevel')",
+ check=False,
+ )
+ if result.returncode:
+ raise ReleaseError(
+ "Check Python/Tk: the selected Python needs working Tk support. "
+ "For Homebrew Python 3.12, run `brew install python-tk@3.12`, "
+ "then retry the build using that Python."
+ )
+
+
+def prepare(runner):
+ check_python_tk(runner, sys.executable)
+ runner.run("Install locked frontend dependencies", "npm", "ci", timeout=900)
+ runner.run("Build frontend assets", "npm", "run", "bundle", timeout=300)
+ runner.run(
+ "Format frontend manifest",
+ "./node_modules/.bin/prettier",
+ "-w",
+ "./lnbits/static/vendor.json",
+ )
+ runner.run(
+ "Verify frontend assets", "git", "diff", "--exit-code", "--", "lnbits/static"
+ )
+ runner.run("Clear cryptography cache", "uv", "cache", "clean", "cryptography")
+ openssl = runner.run(
+ "Locate static OpenSSL", "brew", "--prefix", "openssl@3"
+ ).stdout.strip()
+ runner.run(
+ "Install locked Python dependencies",
+ "uv",
+ "sync",
+ "--python",
+ sys.executable,
+ "--locked",
+ "--no-dev",
+ "--no-editable",
+ "--reinstall-package",
+ "cryptography",
+ env={"OPENSSL_STATIC": "1", "OPENSSL_DIR": openssl},
+ timeout=1800,
+ )
+ check_python_tk(runner, "uv", "run", "--no-sync", "python")
+ runner.run(
+ "Install existing PyInstaller pin",
+ "uv",
+ "pip",
+ "install",
+ "pyinstaller==6.22.2",
+ timeout=300,
+ )
+
+
+def build_application(runner):
+ result = runner.run(
+ "Build PyInstaller application",
+ "uv",
+ "run",
+ "--no-sync",
+ "python",
+ ".github/packaging/build.py",
+ timeout=1800,
+ log_output=True,
+ )
+ # PyInstaller may warn about native data it did not sign. No release is
+ # accepted until our independent recursive signing and verification passes.
+ warnings = [
+ line
+ for line in (result.stdout + result.stderr).splitlines()
+ if "sign" in line.lower() and "warn" in line.lower()
+ ]
+ if warnings:
+ print(
+ runner.redact(
+ "PyInstaller signing warnings require explicit verification:\n"
+ + "\n".join(warnings)
+ )
+ )
+
+
+def release(runner, session, *, signed, credentials, arch, skip_build=False):
+ output = None
+ session.begin()
+ try:
+ with cleanup_on_exit(session.cleanup, runner):
+ output = dmg.output_path()
+ output.unlink(missing_ok=True)
+ output.with_suffix(".dmg.sha256").unlink(missing_ok=True)
+ if not skip_build:
+ build_application(runner)
+ app = Path("dist/LNbits.app").resolve()
+ dmg.finalize_app(app)
+ # Catch packaging errors before signing, Apple submissions or DMG work.
+ bundled_data(runner, app, arch)
+ if signed:
+ identity = session.setup(credentials)
+ configured = os.environ.get("MACOS_CODESIGN_IDENTITY")
+ if configured and configured != identity:
+ raise ReleaseError(
+ "MACOS_CODESIGN_IDENTITY must match the selected "
+ "certificate fingerprint"
+ )
+ keychain = session.state["keychain"]
+ sign_app(runner, app, identity, keychain, arch)
+ verify_app(runner, app, credentials["APPLE_TEAM_ID"], arch)
+ archive = Path(session.state["directory"]) / "LNbits.zip"
+ runner.run(
+ "Archive signed app",
+ "/usr/bin/ditto",
+ "-c",
+ "-k",
+ "--sequesterRsrc",
+ "--keepParent",
+ app,
+ archive,
+ timeout=600,
+ )
+ notarize(runner, archive, keychain)
+ archive.unlink()
+ staple(runner, app)
+ else:
+ sign_app(runner, app, "-", None, arch)
+ # This only copies the finalized app, preserving its ticket.
+ dmg.create(app, output, runner, signed=signed)
+ if signed:
+ sign(runner, output, identity, keychain, runtime=False)
+ notarize(runner, output, keychain)
+ staple(runner, output)
+ verify_image(
+ runner,
+ session,
+ output,
+ arch,
+ credentials["APPLE_TEAM_ID"] if signed else None,
+ )
+ # Cleanup is a publication gate too; never leave a successful checksum
+ # beside a failed release. Re-read the completed image to verify it.
+ dmg.write_checksum(output)
+ except BaseException:
+ if output:
+ output.with_suffix(".dmg.sha256").unlink(missing_ok=True)
+ output.unlink(missing_ok=True)
+ raise
+ print(
+ f"Verified {'signed and notarized' if signed else 'ad-hoc'} artifact: {output}"
+ )
+
+
+def interrupted(signum, _frame):
+ raise ReleaseError(f"Release interrupted by signal {signum}; cleaning up")
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ mode = parser.add_mutually_exclusive_group()
+ mode.add_argument(
+ "--unsigned", action="store_true", help="Ad-hoc development build"
+ )
+ mode.add_argument(
+ "--ci", action="store_true", help="Read the six credentials from CI environment"
+ )
+ parser.add_argument("--env-file", default=".env.macos-release")
+ parser.add_argument(
+ "--prepared", action="store_true", help="Dependencies/frontend already prepared"
+ )
+ parser.add_argument("--prepare-only", action="store_true")
+ parser.add_argument(
+ "--skip-build", action="store_true", help="Package an existing dist/LNbits.app"
+ )
+ parser.add_argument(
+ "--cleanup", action="store_true", help="Recover an interrupted release session"
+ )
+ parser.add_argument(
+ "--state",
+ default=os.environ.get("MACOS_RELEASE_STATE", "build/macos-release-state.json"),
+ )
+ args = parser.parse_args(argv)
+ runner = Runner()
+ try:
+ if sys.platform != "darwin" or platform.machine() not in ("arm64", "x86_64"):
+ raise ReleaseError("Build on a native arm64 or x86_64 Mac")
+ for sig in (signal.SIGTERM, signal.SIGINT):
+ signal.signal(sig, interrupted)
+ if args.cleanup:
+ cleanup(args.state, runner)
+ return
+ credentials = {}
+ if not args.unsigned and not args.prepare_only:
+ credentials = load_credentials(None if args.ci else args.env_file)
+ runner = Runner(credentials)
+ validate_credentials(credentials)
+ translated = runner.run(
+ "Check native architecture",
+ "/usr/sbin/sysctl",
+ "-in",
+ "sysctl.proc_translated",
+ check=False,
+ )
+ if translated.stdout.strip() == "1":
+ raise ReleaseError(
+ "Rosetta is not supported; use native Python and a native terminal"
+ )
+ if not args.prepared and not args.skip_build:
+ prepare(runner)
+ if args.prepare_only:
+ return
+ release(
+ runner,
+ Session(args.state, runner),
+ signed=not args.unsigned,
+ credentials=credentials,
+ arch=platform.machine(),
+ skip_build=args.skip_build,
+ )
+ except Exception as exc:
+ # No unredacted exception repr, traceback or credential-bearing argv.
+ print(runner.redact(error_message(exc)), file=sys.stderr)
+ raise SystemExit(1) from None
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.github/packaging/macos/signing.py b/.github/packaging/macos/signing.py
new file mode 100644
index 0000000..35f5d60
--- /dev/null
+++ b/.github/packaging/macos/signing.py
@@ -0,0 +1,212 @@
+"""Sign and verify actual bundled code, including native files collected as data."""
+
+import json
+import os
+import plistlib
+import re
+from pathlib import Path
+
+from macos.common import ReleaseError
+from macos.credentials import PROFILE
+
+MACH_MAGICS = {
+ b"\xfe\xed\xfa\xce",
+ b"\xce\xfa\xed\xfe",
+ b"\xfe\xed\xfa\xcf",
+ b"\xcf\xfa\xed\xfe",
+ b"\xca\xfe\xba\xbe",
+ b"\xbe\xba\xfe\xca",
+ b"\xca\xfe\xba\xbf",
+ b"\xbf\xba\xfe\xca",
+}
+ENTITLEMENTS = Path(__file__).with_name("entitlements")
+
+
+def native_files(app):
+ files = []
+ for directory, _, names in os.walk(app, followlinks=False):
+ for name in names:
+ path = Path(directory) / name
+ if path.is_symlink() or not path.is_file():
+ continue
+ with path.open("rb") as stream:
+ if stream.read(4) in MACH_MAGICS:
+ files.append(path)
+ if not files:
+ raise ReleaseError("No Mach-O code found in application")
+ return sorted(files, key=lambda p: (-len(p.parts), str(p)))
+
+
+def code_targets(app):
+ files = native_files(app)
+ bundles = set()
+ for path in files:
+ for parent in path.parents:
+ if parent == app:
+ break
+ if parent.suffix in (".framework", ".app", ".xpc", ".bundle"):
+ bundles.add(parent)
+ return [*sorted([*files, *bundles], key=lambda p: (-len(p.parts), str(p))), app]
+
+
+def entitlement_file(path, app, arch):
+ if path == app or path == app / "Contents/MacOS/LNbits":
+ default = ENTITLEMENTS / "python.plist"
+ configured = os.environ.get("MACOS_ENTITLEMENTS_FILE")
+ if configured:
+ candidate = Path(configured).resolve()
+ if plistlib.loads(candidate.read_bytes()) != plistlib.loads(
+ default.read_bytes()
+ ):
+ raise ReleaseError(
+ "MACOS_ENTITLEMENTS_FILE must match the documented Python policy"
+ )
+ return candidate
+ return default
+ if path.name == "node":
+ # The pinned Intel Node needs this extra exception for V8 code-range
+ # initialization under hardened runtime; allow-jit alone can SIGTRAP.
+ return ENTITLEMENTS / (
+ "node-x86_64.plist" if arch == "x86_64" else "node.plist"
+ )
+ return None
+
+
+def requirement(team, *, app=False):
+ result = (
+ "anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.13] "
+ f'exists and certificate leaf[subject.OU] = "{team}"'
+ )
+ if app:
+ result += ' and identifier "com.lnbits.desktop"'
+ return result
+
+
+def sign(runner, path, identity, keychain=None, entitlements=None, *, runtime=True):
+ args = ["/usr/bin/codesign", "--force", "--sign", identity]
+ if identity != "-":
+ args += ["--keychain", str(keychain), "--timestamp"]
+ if runtime:
+ args += ["--options", "runtime"]
+ if entitlements:
+ args += ["--entitlements", str(entitlements)]
+ runner.run("Sign code" if runtime else "Sign DMG", *args, path)
+
+
+def verify_code(runner, path, team, *, app=False, runtime=True, entitlements=None):
+ args = ["/usr/bin/codesign", "--verify", "--strict", "--all-architectures"]
+ if app:
+ args += ["--deep"]
+ # Without the leading '=', codesign treats the requirement as a file path.
+ args += ["-R", "=" + requirement(team, app=app), path]
+ runner.run("Verify Developer ID signature", *args)
+ details = runner.run(
+ "Inspect signature", "/usr/bin/codesign", "--display", "--verbose=4", path
+ )
+ details = details.stdout + details.stderr
+ if f"TeamIdentifier={team}\n" not in details or not re.search(
+ r"^Timestamp=.+", details, re.M
+ ):
+ raise ReleaseError("Signature is missing the expected team or secure timestamp")
+ if runtime and not re.search(r"flags=.*\bruntime\b", details):
+ raise ReleaseError("Signature is missing hardened runtime")
+ if runtime:
+ result = runner.run(
+ "Inspect entitlements",
+ "/usr/bin/codesign",
+ "--display",
+ "--entitlements",
+ ":-",
+ path,
+ )
+ actual = plistlib.loads(result.stdout.encode()) if result.stdout.strip() else {}
+ expected = plistlib.loads(entitlements.read_bytes()) if entitlements else {}
+ if actual != expected:
+ raise ReleaseError(
+ "Signed entitlements differ from the minimal runtime policy"
+ )
+
+
+def sign_app(runner, app, identity, keychain, arch):
+ for path in code_targets(app):
+ sign(runner, path, identity, keychain, entitlement_file(path, app, arch))
+
+
+def verify_app(runner, app, team, arch):
+ for path in code_targets(app):
+ verify_code(
+ runner,
+ path,
+ team,
+ app=path == app,
+ entitlements=entitlement_file(path, app, arch),
+ )
+
+
+def notarize(runner, artifact, keychain):
+ authentication = ["--keychain", keychain, "--keychain-profile", PROFILE]
+ # Separate submit and wait retain the ID even when waiting times out. There
+ # is one submission for the app ZIP and one for the final signed DMG.
+ result = runner.run(
+ "Submit notarization",
+ "/usr/bin/xcrun",
+ "notarytool",
+ "submit",
+ artifact,
+ *authentication,
+ "--output-format",
+ "json",
+ timeout=900,
+ )
+ try:
+ submission = json.loads(result.stdout)["id"]
+ if not re.fullmatch(r"[a-fA-F0-9-]{36}", submission):
+ raise ValueError
+ except (ValueError, KeyError, TypeError):
+ raise ReleaseError(
+ "Notarization submission did not return a valid JSON ID"
+ ) from None
+ print(f"Notarization submission: {submission}", flush=True)
+ result = runner.run(
+ f"Wait for notarization {submission}",
+ "/usr/bin/xcrun",
+ "notarytool",
+ "wait",
+ submission,
+ *authentication,
+ "--timeout",
+ "30m",
+ "--output-format",
+ "json",
+ timeout=1860,
+ check=False,
+ )
+ try:
+ status = json.loads(result.stdout)["status"]
+ except (ValueError, KeyError, TypeError):
+ status = "Unknown"
+ print(runner.redact(f"Notarization {submission}: {status}"), flush=True)
+ if result.returncode or status != "Accepted":
+ log = runner.run(
+ f"Fetch notarization log {submission}",
+ "/usr/bin/xcrun",
+ "notarytool",
+ "log",
+ submission,
+ *authentication,
+ timeout=120,
+ check=False,
+ )
+ diagnostic = runner.redact(
+ result.stdout + result.stderr + log.stdout + log.stderr
+ )
+ raise ReleaseError(
+ f"Notarization {submission} was not Accepted. {diagnostic[-12000:]}"
+ )
+
+
+def staple(runner, artifact):
+ runner.run("Staple ticket", "/usr/bin/xcrun", "stapler", "staple", artifact)
+ runner.run(
+ "Validate stapled ticket", "/usr/bin/xcrun", "stapler", "validate", artifact
+ )
diff --git a/.github/packaging/macos/smoke_launcher.py b/.github/packaging/macos/smoke_launcher.py
new file mode 100644
index 0000000..f222488
--- /dev/null
+++ b/.github/packaging/macos/smoke_launcher.py
@@ -0,0 +1,58 @@
+"""Exercise the mounted launcher with external disposable data and no wallet."""
+
+import os
+import signal
+import socket
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+def stop_launcher(process):
+ if process.poll() is not None:
+ return
+ # The launcher and its multiprocessing worker own this process group.
+ # Give Tk/server shutdown a chance before escalating after a timeout.
+ os.killpg(process.pid, signal.SIGTERM)
+ try:
+ process.wait(timeout=40)
+ except subprocess.TimeoutExpired:
+ os.killpg(process.pid, signal.SIGKILL)
+ process.wait(timeout=10)
+
+
+def main(binary):
+ with tempfile.TemporaryDirectory(prefix="lnbits-launcher-smoke-") as directory:
+ with socket.create_server(("127.0.0.1", 0)) as sock:
+ port = sock.getsockname()[1]
+ environment = dict(
+ os.environ,
+ HOST="127.0.0.1",
+ PORT=str(port),
+ DEBUG="false",
+ LNBITS_DATA_FOLDER=directory,
+ LNBITS_EXTENSIONS_PATH=directory,
+ LNBITS_BACKEND_WALLET_CLASS="FakeWallet",
+ LNBITS_EXTENSIONS_DEFAULT_INSTALL="[]",
+ )
+ process = subprocess.Popen( # noqa: S603
+ [binary, "--smoke-test-gui"],
+ env=environment,
+ cwd=directory,
+ start_new_session=True,
+ )
+ try:
+ if process.wait(timeout=180):
+ raise RuntimeError("Packaged GUI smoke process failed")
+ finally:
+ stop_launcher(process)
+ if not (Path(directory) / "database.sqlite3").is_file():
+ raise RuntimeError("Packaged GUI did not start LNbits")
+ with socket.socket() as sock:
+ if sock.connect_ex(("127.0.0.1", port)) == 0:
+ raise RuntimeError("Server survived packaged launcher shutdown")
+
+
+if __name__ == "__main__":
+ main(str(Path(sys.argv[1]).resolve()))
diff --git a/.github/packaging/macos/verify.py b/.github/packaging/macos/verify.py
new file mode 100644
index 0000000..8393f17
--- /dev/null
+++ b/.github/packaging/macos/verify.py
@@ -0,0 +1,151 @@
+"""Verification and smoke checks against the exact final read-only image."""
+
+import os
+import plistlib
+import sys
+import tempfile
+from pathlib import Path
+
+from macos.common import ReleaseError, cleanup_on_exit
+from macos.signing import native_files, verify_app, verify_code
+
+PACKAGING = Path(__file__).resolve().parents[1]
+REQUIRED_DATA = (
+ "certifi/cacert.pem",
+ "grpc/_cython/_credentials/roots.pem",
+ "pyinstrument/renderers/html_resources/app.css",
+ "pyinstrument/renderers/html_resources/app.js",
+ "random_username/data/adjectives.txt",
+ "random_username/data/nouns.txt",
+ "lnbits/templates/base.html",
+ "lnbits/static/bundle.min.js",
+)
+
+
+def bundled_data(runner, app, arch):
+ info = plistlib.loads((app / "Contents/Info.plist").read_bytes())
+ if (info.get("CFBundleIdentifier"), info.get("LSMinimumSystemVersion")) != (
+ "com.lnbits.desktop",
+ "15.0",
+ ):
+ raise ReleaseError("Unexpected bundle identifier or minimum macOS version")
+ resources = app / "Contents/Resources"
+ for name in REQUIRED_DATA:
+ if not (resources / name).is_file():
+ raise ReleaseError(f"Missing packaged dependency data: {name}")
+ sidecars = app / "Contents/Frameworks/sidecars"
+ for name in ("node", "phoenixd", "pins.json", "spark/server.mjs", "supervisor.mjs"):
+ if not (sidecars / name).is_file():
+ raise ReleaseError(f"Missing bundled funding component: {name}")
+ if not (sidecars / "spark/node_modules").is_dir():
+ raise ReleaseError("Missing Spark dependencies")
+ verify_architecture(runner, app, arch)
+ for _, _, files in os.walk(app):
+ if any(
+ name == ".env.macos-release" or name.endswith((".p12", ".keychain-db"))
+ for name in files
+ ):
+ raise ReleaseError("Signing material must never be bundled")
+
+
+def verify_architecture(runner, app, arch):
+ for path in native_files(app):
+ operation = f"Verify native architecture: {path.relative_to(app)}"
+ result = runner.run(operation, "/usr/bin/lipo", "-archs", path)
+ if arch not in result.stdout.split():
+ raise ReleaseError(
+ f"Wrong native architecture: {path.relative_to(app)} "
+ f"(expected {arch}; found {result.stdout.strip() or 'none'})"
+ )
+ if path == app / "Contents/MacOS/LNbits" and result.stdout.strip() != arch:
+ raise ReleaseError("Launcher must contain exactly the native architecture")
+
+
+def verify_image(runner, session, output, arch, team=None):
+ runner.run(
+ "Verify DMG integrity", "/usr/bin/hdiutil", "verify", output, timeout=600
+ )
+ if team:
+ verify_code(runner, output, team, runtime=False)
+ runner.run(
+ "Validate DMG ticket", "/usr/bin/xcrun", "stapler", "validate", output
+ )
+ runner.run(
+ "Assess DMG Gatekeeper",
+ "/usr/sbin/spctl",
+ "--assess",
+ "--type",
+ "open",
+ "--context",
+ "context:primary-signature",
+ "--verbose=2",
+ output,
+ )
+ mount = Path(tempfile.mkdtemp(prefix="lnbits-verify-")).resolve()
+ session.state["mount"] = str(mount)
+ session.save()
+ with cleanup_on_exit(session.detach, runner):
+ runner.run(
+ "Mount final DMG read-only",
+ "/usr/bin/hdiutil",
+ "attach",
+ output,
+ "-mountpoint",
+ mount,
+ "-nobrowse",
+ "-readonly",
+ "-plist",
+ )
+ if not (mount / "Applications").is_symlink() or (
+ mount / "Applications"
+ ).readlink() != Path("/Applications"):
+ raise ReleaseError("DMG is missing its Applications shortcut")
+ app = mount / "LNbits.app"
+ if team:
+ verify_app(runner, app, team, arch)
+ runner.run(
+ "Assess app Gatekeeper",
+ "/usr/sbin/spctl",
+ "--assess",
+ "--type",
+ "execute",
+ "--verbose=2",
+ app,
+ )
+ runner.run(
+ "Validate app ticket", "/usr/bin/xcrun", "stapler", "validate", app
+ )
+ else:
+ runner.run(
+ "Verify development app",
+ "/usr/bin/codesign",
+ "--verify",
+ "--deep",
+ "--strict",
+ app,
+ )
+ bundled_data(runner, app, arch)
+ python = Path(".venv/bin/python").resolve()
+ if not python.is_file():
+ python = Path(sys.executable)
+ runner.run(
+ "Smoke bundled sidecars",
+ python,
+ PACKAGING / "smoke_sidecars.py",
+ app / "Contents/Frameworks/sidecars",
+ timeout=180,
+ )
+ runner.run(
+ "Smoke packaged server and shutdown",
+ python,
+ PACKAGING / "smoke.py",
+ app / "Contents/MacOS/LNbits",
+ timeout=240,
+ )
+ runner.run(
+ "Smoke packaged launcher and JIT",
+ python,
+ PACKAGING / "macos/smoke_launcher.py",
+ app / "Contents/MacOS/LNbits",
+ timeout=240,
+ )
diff --git a/.github/packaging/prepare_sidecars.py b/.github/packaging/prepare_sidecars.py
index 20e7014..89f98a5 100644
--- a/.github/packaging/prepare_sidecars.py
+++ b/.github/packaging/prepare_sidecars.py
@@ -55,6 +55,20 @@ def unpack(archive, destination):
return next(destination.iterdir())
+def prune_prebuilds(node_modules, system, arch):
+ if system != "darwin":
+ return
+ # npm packages include other Macs and mobile platforms even with --omit=dev.
+ # Filter before PyInstaller collects these directories as application data.
+ for prebuilds in node_modules.rglob("prebuilds"):
+ for variant in prebuilds.iterdir():
+ if not variant.is_dir():
+ continue
+ platform_name, _, architectures = variant.name.partition("-")
+ if platform_name != "darwin" or arch not in architectures.split("+"):
+ shutil.rmtree(variant)
+
+
def main():
here = Path(__file__).resolve().parent
pins = json.loads((here / "sidecars/pins.json").read_text())
@@ -114,6 +128,7 @@ def main():
for directory in ("android", "ios"):
shutil.rmtree(sdk / directory, ignore_errors=True)
shutil.rmtree(spark / "node_modules/.bin", ignore_errors=True)
+ prune_prebuilds(spark / "node_modules", system, arch)
if system != "win":
version = pins["phoenixd"]["version"]
diff --git a/.github/packaging/smoke_sidecars.py b/.github/packaging/smoke_sidecars.py
index f7acab8..ec91370 100644
--- a/.github/packaging/smoke_sidecars.py
+++ b/.github/packaging/smoke_sidecars.py
@@ -17,11 +17,26 @@ def check(resources):
pins = json.loads((resources / "pins.json").read_text())
node = resources / ("node.exe" if sys.platform == "win32" else "node")
env = dict(os.environ)
+ # An inherited --jitless could hide missing executable-memory entitlements.
+ env.pop("NODE_OPTIONS", None)
if sys.platform == "linux":
env["LD_LIBRARY_PATH"] = os.pathsep.join(
filter(None, (str(resources / "lib"), env.get("LD_LIBRARY_PATH")))
)
- version = subprocess.check_output([str(node), "--version"], env=env, text=True)
+ # --version exits before V8 starts. Exercise the runtime used by both
+ # supervisors so a signed Node with insufficient JIT permissions fails here.
+ print("Check bundled Node JavaScript initialization", flush=True)
+ version = subprocess.check_output(
+ [
+ str(node),
+ "--eval",
+ "let sum = 0; for (let i = 0; i < 100000; i++) sum += i; "
+ "if (sum !== 4999950000) process.exit(1); console.log(process.version)",
+ ],
+ env=env,
+ text=True,
+ timeout=30,
+ )
assert version.strip() == f"v{pins['node']['version']}"
if sys.platform != "win32":
version = subprocess.check_output(
diff --git a/.github/packaging/test_build.py b/.github/packaging/test_build.py
index 8a80424..918b77f 100644
--- a/.github/packaging/test_build.py
+++ b/.github/packaging/test_build.py
@@ -1,6 +1,7 @@
"""Check the macOS dependency guard without building an application."""
import runpy
+import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
@@ -14,6 +15,51 @@ class BuildReadyError(Exception):
class BuildTests(unittest.TestCase):
+ def test_only_macos_uses_the_native_embit_hook(self):
+ for system in ("darwin", "linux", "win32"):
+ with self.subTest(system=system), tempfile.TemporaryDirectory() as folder:
+ bindepend = Mock()
+ bindepend.get_imports.return_value = []
+ with (
+ patch.dict(
+ "sys.modules",
+ {
+ "wasmtime": SimpleNamespace(
+ __file__=str(Path(folder) / "__init__.py")
+ ),
+ "PyInstaller": Mock(),
+ "PyInstaller.depend": Mock(),
+ "PyInstaller.depend.bindepend": bindepend,
+ },
+ ),
+ patch("prepare_sidecars.main") as prepare,
+ patch(
+ "pathlib.Path.iterdir",
+ return_value=iter([Path(folder) / "node"]),
+ ),
+ patch("sys.platform", system),
+ patch.dict("os.environ"),
+ patch(
+ "importlib.util.find_spec",
+ return_value=SimpleNamespace(origin="native.so"),
+ ),
+ patch("subprocess.run") as run,
+ ):
+ runpy.run_path(str(BUILD))
+ command = run.call_args.args[0]
+ prepare.assert_called_once_with()
+ self.assertIn(f"{Path(folder) / 'node'}:sidecars", command)
+ collections = [
+ command[i + 1]
+ for i, item in enumerate(command)
+ if item == "--collect-all"
+ ]
+ self.assertEqual("embit" in collections, system != "darwin")
+ self.assertEqual(
+ "--additional-hooks-dir" in command, system == "darwin"
+ )
+ self.assertIn("--hidden-import=embit", command)
+
def check_bindings(self, imports, error):
bindepend = Mock()
bindepend.get_imports.return_value = imports
@@ -56,3 +102,59 @@ class BuildTests(unittest.TestCase):
{("/usr/lib/libSystem.B.dylib", "/usr/lib/libSystem.B.dylib")},
BuildReadyError,
)
+
+
+class EmbitHookTests(unittest.TestCase):
+ def collect(self, arch, entries):
+ hooks = SimpleNamespace(collect_all=Mock(return_value=entries))
+ with (
+ patch.dict(
+ "sys.modules",
+ {
+ "PyInstaller": Mock(),
+ "PyInstaller.utils": Mock(),
+ "PyInstaller.utils.hooks": hooks,
+ },
+ ),
+ patch("platform.machine", return_value=arch),
+ ):
+ return runpy.run_path(str(BUILD.parent / "macos/hooks/hook-embit.py"))
+
+ def test_only_native_library_is_collected_as_code_on_each_mac(self):
+ libraries = [
+ (f"/env/embit/util/prebuilt/libsecp256k1_{suffix}", "embit/util/prebuilt")
+ for suffix in (
+ "darwin_arm64.dylib",
+ "darwin_x86_64.dylib",
+ "linux_x86_64.so",
+ "windows_amd64.dll",
+ )
+ ]
+ source = ("/env/embit/util/ctypes_secp256k1.py", "embit/util")
+ for arch in ("arm64", "x86_64"):
+ for as_data in (True, False):
+ with self.subTest(arch=arch, as_data=as_data):
+ entries = (
+ ([source, *libraries], [], ["embit.util.ctypes_secp256k1"])
+ if as_data
+ else ([source], libraries, ["embit.util.ctypes_secp256k1"])
+ )
+ hook = self.collect(arch, entries)
+ self.assertEqual(hook["datas"], [source])
+ self.assertEqual(
+ hook["binaries"],
+ [
+ (
+ f"/env/embit/util/prebuilt/libsecp256k1_darwin_{arch}.dylib",
+ "embit/util/prebuilt",
+ )
+ ],
+ )
+ self.assertEqual(hook["hiddenimports"], entries[2])
+
+ def test_missing_native_library_fails_packaging(self):
+ with self.assertRaisesRegex(RuntimeError, "Missing native embit prebuild"):
+ self.collect(
+ "arm64",
+ ([], [("libsecp256k1_darwin_x86_64.dylib", "embit/util/prebuilt")], []),
+ )
diff --git a/.github/packaging/test_dmg.py b/.github/packaging/test_dmg.py
index 5821181..2b7cf68 100644
--- a/.github/packaging/test_dmg.py
+++ b/.github/packaging/test_dmg.py
@@ -3,13 +3,14 @@
import contextlib
import hashlib
import plistlib
-import subprocess
+import shutil
import tempfile
import unittest
from pathlib import Path
-from unittest.mock import patch
+from unittest.mock import Mock, patch
-from macos import dmg
+from macos import dmg, release
+from macos.common import ReleaseError
class DmgTests(unittest.TestCase):
@@ -19,7 +20,6 @@ class DmgTests(unittest.TestCase):
self.subTest(fail_verification=fail_verification),
tempfile.TemporaryDirectory() as folder,
contextlib.chdir(folder),
- patch("macos.dmg.sys.platform", "darwin"),
patch("macos.dmg.platform.machine", return_value="arm64"),
patch.dict("os.environ", {}, clear=True),
):
@@ -31,36 +31,86 @@ class DmgTests(unittest.TestCase):
(original / "Resources").mkdir()
(original / "Frameworks").symlink_to("Resources")
output = Path("dist/LNbits-v1.6.2rc1-macOS-arm64.dmg").resolve()
+ self.assertEqual(dmg.output_path(), output)
+ signed_metadata = []
- def run(*args, output=output, fail_verification=fail_verification):
+ def sign(*args, original=original, signed_metadata=signed_metadata):
+ signed_metadata.append((original / "Info.plist").read_bytes())
+
+ def run(
+ operation,
+ *args,
+ output=output,
+ signed_metadata=signed_metadata,
+ **kwargs,
+ ):
+ if args[0] == "/usr/bin/ditto":
+ shutil.copytree(args[-2], args[-1], symlinks=True)
if args[:2] == ("/usr/bin/hdiutil", "create"):
staging = Path(args[args.index("-srcfolder") + 1])
app = staging / "LNbits.app/Contents"
info = plistlib.loads((app / "Info.plist").read_bytes())
+ self.assertEqual(
+ (app / "Info.plist").read_bytes(), signed_metadata[0]
+ )
self.assertEqual(info["CFBundleShortVersionString"], "1.6.2")
self.assertEqual(info["LSMinimumSystemVersion"], "15.0")
+ self.assertEqual(
+ info["CFBundleIdentifier"], "com.lnbits.desktop"
+ )
self.assertTrue((app / "Frameworks").is_symlink())
self.assertEqual(
(staging / "Applications").readlink(), Path("/Applications")
)
- output.write_bytes(b"disk image")
- if fail_verification and args[:2] == ("/usr/bin/hdiutil", "verify"):
- raise subprocess.CalledProcessError(1, args)
+ Path(args[-1]).write_bytes(b"uncompressed image")
+ if args[:2] == ("/usr/bin/hdiutil", "convert"):
+ output.write_bytes(b"final disk image")
+
+ def verify(*args, output=output, fail_verification=fail_verification):
+ self.assertFalse(output.with_suffix(".dmg.sha256").exists())
+ if fail_verification:
+ raise ReleaseError("Verify final DMG: rejected")
- with patch("macos.dmg.run", side_effect=run) as commands:
+ runner = Mock()
+ runner.run.side_effect = run
+ session = Mock()
+ with (
+ patch("macos.release.bundled_data"),
+ patch("macos.release.sign_app", side_effect=sign),
+ patch("macos.release.verify_image", side_effect=verify) as verified,
+ ):
if fail_verification:
- with self.assertRaises(subprocess.CalledProcessError):
- dmg.main()
+ with self.assertRaisesRegex(ReleaseError, "Verify final DMG"):
+ release.release(
+ runner,
+ session,
+ signed=False,
+ credentials={},
+ arch="arm64",
+ skip_build=True,
+ )
+ self.assertFalse(output.exists())
self.assertFalse(output.with_suffix(".dmg.sha256").exists())
else:
- dmg.main()
+ release.release(
+ runner,
+ session,
+ signed=False,
+ credentials={},
+ arch="arm64",
+ skip_build=True,
+ )
checksum = output.with_suffix(".dmg.sha256").read_text()
- digest = hashlib.sha256(b"disk image").hexdigest()
+ digest = hashlib.sha256(b"final disk image").hexdigest()
self.assertEqual(
checksum,
f"{digest} {output.name}\n",
)
- commands.assert_any_call("/usr/bin/hdiutil", "verify", str(output))
+ verified.assert_called_once_with(
+ runner, session, output, "arm64", None
+ )
+ session.cleanup.assert_called_once_with()
+ session.setup.assert_not_called()
self.assertEqual(
- plistlib.loads((original / "Info.plist").read_bytes()), metadata
+ (original / "Info.plist").read_bytes(), signed_metadata[0]
)
diff --git a/.github/packaging/test_macos_release.py b/.github/packaging/test_macos_release.py
new file mode 100644
index 0000000..2034822
--- /dev/null
+++ b/.github/packaging/test_macos_release.py
@@ -0,0 +1,1028 @@
+"""Release gates use dummy credentials and mocked tools; never contact Apple."""
+
+import base64
+import contextlib
+import hashlib
+import io
+import json
+import os
+import plistlib
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock, Mock, patch
+
+from macos import credentials, dmg, release, signing, verify
+from macos.common import CREDENTIAL_NAMES, ReleaseError, Runner, validate_credentials
+
+DUMMY = {
+ "BUILD_CERTIFICATE_BASE64": base64.b64encode(b"dummy certificate").decode(),
+ "P12_PASSWORD": "dummy-p12-secret",
+ "KEYCHAIN_PASSWORD": "dummy-keychain-secret",
+ "APPLE_ID": "dummy@example.invalid",
+ "APPLE_TEAM_ID": "ABCDEFGHIJ",
+ "APPLE_APP_SPECIFIC_PASSWORD": "dummy-apple-secret",
+}
+IDENTITY = "A" * 40
+CREATE_DMG = dmg.create
+SUBMISSION = "12345678-1234-1234-1234-123456789abc"
+
+
+def result(stdout="", stderr="", returncode=0):
+ return SimpleNamespace(stdout=stdout, stderr=stderr, returncode=returncode)
+
+
+class PythonPrerequisiteTests(unittest.TestCase):
+ def test_missing_tk_fails_before_dependency_installation_with_repair_command(self):
+ runner = Mock()
+ runner.run.return_value = result(
+ stderr="ModuleNotFoundError: No module named '_tkinter'", returncode=1
+ )
+ with self.assertRaisesRegex(ReleaseError, "brew install python-tk@3.12"):
+ release.prepare(runner)
+ self.assertEqual(runner.run.call_count, 1)
+
+ def test_dependency_environment_uses_the_checked_python_and_checks_tk_again(self):
+ runner = Mock()
+ runner.run.return_value = result("/opt/homebrew/opt/openssl@3")
+ with patch("macos.release.sys.executable", "/path/to/python3.12"):
+ release.prepare(runner)
+ calls = runner.run.call_args_list
+ self.assertEqual(calls[0].args[:2], ("Check Python/Tk", "/path/to/python3.12"))
+ sync = next(
+ call
+ for call in calls
+ if call.args[0] == "Install locked Python dependencies"
+ )
+ self.assertEqual(
+ sync.args[sync.args.index("--python") + 1], "/path/to/python3.12"
+ )
+ checks = [call for call in calls if call.args[0] == "Check Python/Tk"]
+ self.assertEqual(checks[1].args[1:5], ("uv", "run", "--no-sync", "python"))
+
+
+class CredentialTests(unittest.TestCase):
+ def test_logged_tool_output_is_redacted_without_arguments_or_child_credentials(
+ self,
+ ):
+ program = (
+ "import os, sys; "
+ f"assert not set({list(CREDENTIAL_NAMES)!r}).intersection(os.environ); "
+ "print(sys.argv[1]); print(sys.argv[2], file=sys.stderr)"
+ )
+ with (
+ patch.dict(os.environ, DUMMY),
+ patch("sys.stdout", new_callable=io.StringIO) as output,
+ ):
+ Runner(DUMMY).run(
+ "Log dummy tool",
+ sys.executable,
+ "-c",
+ program,
+ DUMMY["P12_PASSWORD"],
+ DUMMY["APPLE_ID"],
+ log_output=True,
+ )
+ self.assertIn("exit 0 after", output.getvalue())
+ self.assertIn("[REDACTED]", output.getvalue())
+ self.assertNotIn(program, output.getvalue())
+ for value in DUMMY.values():
+ self.assertNotIn(value, output.getvalue())
+
+ def test_logged_timeout_reports_progress_and_stops_its_tool_group(self):
+ process = MagicMock(pid=12345)
+ process.__enter__.return_value = process
+ process.wait.side_effect = [subprocess.TimeoutExpired(["dummy"], 2), None]
+
+ def launch(*args, **kwargs):
+ kwargs["stdout"].write(
+ ("disk helper stalled " + DUMMY["APPLE_ID"]).encode()
+ )
+ kwargs["stdout"].flush()
+ return process
+
+ with (
+ patch("macos.common.subprocess.Popen", side_effect=launch),
+ patch("macos.common.time.monotonic", side_effect=[0, 0, 1, 2]),
+ patch("macos.common.os.killpg", create=True) as kill,
+ patch("sys.stdout", new_callable=io.StringIO) as output,
+ self.assertRaises(ReleaseError) as caught,
+ ):
+ Runner(DUMMY).run(
+ "Create DMG", "dummy", DUMMY["P12_PASSWORD"], timeout=2, log_output=True
+ )
+ self.assertIn("running for 1s", output.getvalue())
+ self.assertIn("disk helper stalled [REDACTED]", str(caught.exception))
+ self.assertNotIn(DUMMY["APPLE_ID"], str(caught.exception))
+ self.assertNotIn(DUMMY["P12_PASSWORD"], str(caught.exception))
+ if os.name == "posix":
+ kill.assert_called_once_with(process.pid, release.signal.SIGKILL)
+ else:
+ process.kill.assert_called_once()
+
+ def test_each_credential_is_required_and_certificate_is_base64(self):
+ self.assertEqual(validate_credentials(DUMMY), b"dummy certificate")
+ for name in CREDENTIAL_NAMES:
+ with self.subTest(name=name), self.assertRaisesRegex(ReleaseError, name):
+ validate_credentials(dict(DUMMY, **{name: ""}))
+ for key, value in (
+ ("APPLE_TEAM_ID", "bad-team"),
+ ("BUILD_CERTIFICATE_BASE64", "!invalid!"),
+ ):
+ with self.assertRaises(ReleaseError):
+ validate_credentials(dict(DUMMY, **{key: value}))
+
+ @unittest.skipUnless(os.name == "posix", "Requires POSIX file permissions")
+ def test_local_file_is_explicit_private_and_never_shell_evaluated(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / ".env.macos-release"
+ text = "\n".join(f'{key}="{value}"' for key, value in DUMMY.items())
+ path.write_text(text)
+ path.chmod(0o600)
+ with patch.dict(os.environ, {"P12_PASSWORD": "different"}):
+ self.assertEqual(credentials.load_credentials(path), DUMMY)
+ path.write_text("P12_PASSWORD=$(do-not-execute)\n")
+ self.assertEqual(
+ credentials.load_credentials(path)["P12_PASSWORD"], "$(do-not-execute)"
+ )
+ path.chmod(0o644)
+ with self.assertRaisesRegex(ReleaseError, "0600"):
+ credentials.load_credentials(path)
+ path.chmod(0o600)
+ for invalid in (
+ "UNKNOWN=value",
+ "P12_PASSWORD=a\nP12_PASSWORD=b",
+ "P12_PASSWORD='unclosed",
+ ):
+ path.write_text(invalid)
+ with self.assertRaises(ReleaseError):
+ credentials.load_credentials(path)
+
+ def test_identity_must_be_valid_unique_developer_id_and_matching_team(self):
+ valid = (
+ f' 1) {IDENTITY} "Developer ID Application: Test '
+ f'({DUMMY["APPLE_TEAM_ID"]})"\n'
+ )
+ self.assertEqual(
+ credentials.select_identity(valid, DUMMY["APPLE_TEAM_ID"]), IDENTITY
+ )
+ for invalid in (
+ "0 valid identities found",
+ valid.replace("ABCDEFGHIJ", "WRONGTEAM1"),
+ valid.replace("Developer ID Application", "Apple Development"),
+ valid.strip() + " (CSSMERR_TP_CERT_EXPIRED)\n",
+ valid + valid.replace(IDENTITY, "B" * 40),
+ ):
+ with self.subTest(invalid=invalid), self.assertRaises(ReleaseError):
+ credentials.select_identity(invalid, DUMMY["APPLE_TEAM_ID"])
+
+ def test_child_environment_and_diagnostics_are_sanitized(self):
+ output = " ".join(DUMMY.values())
+ with (
+ patch.dict(os.environ, DUMMY),
+ patch(
+ "macos.common.subprocess.run", return_value=result(output, returncode=1)
+ ) as run,
+ ):
+ runner = Runner(DUMMY)
+ with self.assertRaises(ReleaseError) as caught:
+ runner.run(
+ "Import certificate", "security", "-p", DUMMY["P12_PASSWORD"]
+ )
+ for value in DUMMY.values():
+ self.assertNotIn(value, str(caught.exception))
+ self.assertIn("Import certificate", str(caught.exception))
+ self.assertTrue(
+ set(CREDENTIAL_NAMES).isdisjoint(run.call_args.kwargs["env"])
+ )
+ run.side_effect = subprocess.TimeoutExpired(
+ ["secret argv", *DUMMY.values()], 1, output=output.encode()
+ )
+ with self.assertRaises(ReleaseError) as caught:
+ runner.run("Wait for Apple", "xcrun")
+ self.assertNotIn("secret argv", str(caught.exception))
+ for value in DUMMY.values():
+ self.assertNotIn(value, str(caught.exception))
+
+ def test_redaction_includes_local_and_inherited_values(self):
+ inherited = "inherited-other-apple-password"
+ with patch.dict(os.environ, {"APPLE_APP_SPECIFIC_PASSWORD": inherited}):
+ runner = Runner(DUMMY)
+ text = runner.redact(inherited + " " + DUMMY["APPLE_APP_SPECIFIC_PASSWORD"])
+ self.assertEqual(text, "[REDACTED] [REDACTED]")
+
+ def test_missing_ci_credentials_fail_before_build_or_apple_tools(self):
+ with (
+ patch.dict(os.environ, {}, clear=True),
+ patch("macos.release.sys.platform", "darwin"),
+ patch("macos.release.platform.machine", return_value="arm64"),
+ patch("macos.release.signal.signal"),
+ patch("macos.release.prepare") as prepare,
+ patch("macos.release.release") as pipeline,
+ patch("sys.stderr", new_callable=io.StringIO) as error,
+ self.assertRaises(SystemExit) as caught,
+ ):
+ release.main(["--ci"])
+ self.assertEqual(caught.exception.code, 1)
+ self.assertIn("Missing release credentials", error.getvalue())
+ prepare.assert_not_called()
+ pipeline.assert_not_called()
+
+
+class SessionTests(unittest.TestCase):
+ def setUp(self):
+ self.folder = Path(self.enterContext(tempfile.TemporaryDirectory()))
+ self.runner = Mock()
+ self.runner.redact.side_effect = Runner(DUMMY).redact
+ self.original = [
+ "/Users/test/Library/Keychains/login.keychain-db",
+ "/Library/Keychains/System.keychain",
+ ]
+ self.current = self.original.copy()
+ self.session = credentials.Session(self.folder / "state.json", self.runner)
+ self.runner.run.side_effect = self.tool
+ self.session.begin()
+
+ def tool(self, operation, *args, **kwargs):
+ if operation in (
+ "Read keychain search list",
+ "Verify restored keychain search list",
+ ):
+ return result("\n".join(json.dumps(path) for path in self.current))
+ if operation == "Create temporary keychain":
+ Path(args[-1]).touch()
+ if operation in ("Add temporary keychain", "Restore keychain search list"):
+ self.current = [str(path) for path in args[args.index("-s") + 1 :]]
+ if operation == "Delete temporary keychain":
+ Path(args[-1]).unlink()
+ if operation == "Select signing identity":
+ return result(
+ f'1) {IDENTITY} "Developer ID Application: Test (ABCDEFGHIJ)"\n'
+ )
+ return result()
+
+ def test_keychain_import_partition_list_and_cleanup(self):
+ self.assertEqual(self.session.setup(DUMMY), IDENTITY)
+ private = Path(self.session.state["directory"])
+ # Windows chmod only controls the read-only flag, not POSIX permissions.
+ if os.name == "posix":
+ self.assertEqual(private.stat().st_mode & 0o777, 0o700)
+ self.assertEqual(self.session.path.stat().st_mode & 0o777, 0o600)
+ self.assertFalse((private / "certificate.p12").exists())
+ state = self.session.path.read_text()
+ self.assertTrue(all(value not in state for value in DUMMY.values()))
+ calls = self.runner.run.call_args_list
+ partition = next(
+ call for call in calls if call.args[0] == "Allow unattended codesign"
+ )
+ self.assertIn("apple-tool:,apple:,codesign:", partition.args)
+ self.session.cleanup()
+ self.assertEqual(self.current, self.original)
+ self.assertFalse(private.exists())
+ self.assertFalse(self.session.path.exists())
+ credentials.cleanup(self.session.path, self.runner) # idempotent always() step
+
+ def test_setup_failure_at_each_operation_is_cleaned(self):
+ operations = (
+ "Create temporary keychain",
+ "Unlock temporary keychain",
+ "Set keychain timeout",
+ "Add temporary keychain",
+ "Import Developer ID certificate",
+ "Allow unattended codesign",
+ "Select signing identity",
+ "Store notarization credentials",
+ )
+ self.session.cleanup()
+ for failure in operations:
+ with self.subTest(failure=failure):
+ self.session.begin()
+
+ def fail(operation, *args, failure=failure, **kwargs):
+ response = self.tool(operation, *args, **kwargs)
+ if operation == failure:
+ raise ReleaseError(operation)
+ return response
+
+ self.runner.run.side_effect = fail
+ with self.assertRaises(ReleaseError):
+ self.session.setup(DUMMY)
+ private = Path(self.session.state["directory"])
+ self.runner.run.side_effect = self.tool
+ # Recover from the on-disk journal, as an always() CI step does.
+ credentials.cleanup(self.session.path, self.runner)
+ self.assertEqual(self.current, self.original)
+ self.assertFalse(private.exists())
+ self.session = credentials.Session(
+ self.folder / "state.json", self.runner
+ )
+
+ def test_cleanup_continues_on_restore_failure_and_retains_journal(self):
+ self.session.setup(DUMMY)
+
+ def fail(operation, *args, **kwargs):
+ if operation == "Restore keychain search list":
+ raise ReleaseError("restore")
+ return self.tool(operation, *args, **kwargs)
+
+ self.runner.run.side_effect = fail
+ with self.assertRaisesRegex(ReleaseError, "restore_search_list"):
+ self.session.cleanup()
+ self.assertTrue(self.session.path.exists())
+ self.assertIsNone(self.session.state["keychain"])
+ self.runner.run.side_effect = self.tool
+ credentials.cleanup(self.session.path, self.runner)
+ self.assertFalse(self.session.path.exists())
+
+ def test_concurrent_session_is_rejected(self):
+ with self.assertRaisesRegex(ReleaseError, "already exists"):
+ credentials.Session(self.session.path, self.runner).begin()
+ self.session.cleanup()
+
+ def test_mount_recovery_and_failed_detach_preserve_recovery_path(self):
+ mount = self.folder / "mount"
+ mount.mkdir()
+ self.session.state["mount"] = str(mount)
+ self.session.save()
+ mounted = {"images": [{"system-entities": [{"mount-point": str(mount)}]}]}
+ self.runner.run.side_effect = [
+ result(plistlib.dumps(mounted).decode()),
+ ReleaseError("busy"),
+ ]
+ with self.assertRaisesRegex(ReleaseError, "busy"):
+ self.session.detach()
+ self.assertTrue(mount.exists())
+ self.assertEqual(self.session.state["mount"], str(mount))
+ self.runner.run.side_effect = [
+ result(plistlib.dumps(mounted).decode()),
+ result(),
+ ]
+ self.session.detach()
+ self.assertFalse(mount.exists())
+ self.assertIsNone(self.session.state["mount"])
+ self.session.cleanup()
+
+ def test_recovery_detaches_a_mount_reported_under_its_resolved_path(self):
+ real = self.folder.resolve() / "private"
+ mount = real / "mount"
+ mount.mkdir(parents=True)
+ (mount / "LNbits.app").mkdir()
+ alias = self.folder / "alias"
+ alias.symlink_to(real, target_is_directory=True)
+ self.session.state["mount"] = str(alias / "mount")
+ self.session.save()
+ mounted = {"images": [{"system-entities": [{"mount-point": str(mount)}]}]}
+
+ def tool(operation, *args, **kwargs):
+ if operation == "Inspect mounted images":
+ return result(plistlib.dumps(mounted).decode())
+ if operation == "Detach final DMG":
+ self.assertEqual(Path(args[-1]), mount)
+ (mount / "LNbits.app").rmdir()
+ return result()
+
+ self.runner.run.side_effect = tool
+ credentials.cleanup(self.session.path, self.runner)
+ self.assertFalse(mount.exists())
+ self.assertFalse(self.session.path.exists())
+ self.assertIn(
+ "Detach final DMG",
+ [call.args[0] for call in self.runner.run.call_args_list],
+ )
+
+ def test_cleanup_reports_sanitized_tool_errors_and_retains_recovery_state(self):
+ with (
+ patch.object(
+ self.session,
+ "detach",
+ autospec=True,
+ side_effect=ReleaseError("Detach final DMG: busy " + DUMMY["APPLE_ID"]),
+ ),
+ self.assertRaises(ReleaseError) as caught,
+ ):
+ self.session.cleanup()
+ self.assertIn("Detach final DMG: busy", str(caught.exception))
+ self.assertNotIn(DUMMY["APPLE_ID"], str(caught.exception))
+ self.assertTrue(self.session.path.exists())
+
+
+class SigningTests(unittest.TestCase):
+ def verification_requirement(self, *, app, runtime):
+ runner = Mock()
+ runner.run.side_effect = [
+ result(),
+ result(
+ stderr="TeamIdentifier=ABCDEFGHIJ\nTimestamp=Sep 16, 2026\n"
+ "flags=0x10000(runtime)\n"
+ ),
+ result(),
+ ]
+ signing.verify_code(
+ runner, Path("code"), "ABCDEFGHIJ", app=app, runtime=runtime
+ )
+ command = runner.run.call_args_list[0].args
+ return command[command.index("-R") + 1]
+
+ def test_verification_uses_inline_requirements_for_native_code_app_and_dmg(self):
+ for app, runtime in ((False, True), (True, True), (False, False)):
+ with self.subTest(app=app, runtime=runtime):
+ argument = self.verification_requirement(app=app, runtime=runtime)
+ self.assertTrue(argument.startswith("=anchor apple generic"))
+ self.assertIn(
+ "certificate leaf[field.1.2.840.113635.100.6.1.13]", argument
+ )
+ self.assertIn('certificate leaf[subject.OU] = "ABCDEFGHIJ"', argument)
+ self.assertEqual('identifier "com.lnbits.desktop"' in argument, app)
+
+ @unittest.skipUnless(
+ sys.platform == "darwin", "Requires Apple's requirement parser"
+ )
+ def test_actual_verification_arguments_compile_with_apple_requirement_parser(self):
+ with tempfile.TemporaryDirectory() as directory:
+ output = Path(directory) / "requirement.bin"
+ for app, runtime in ((False, True), (True, True), (False, False)):
+ with self.subTest(app=app, runtime=runtime):
+ argument = self.verification_requirement(app=app, runtime=runtime)
+ Runner(DUMMY).run(
+ "Compile verification requirement",
+ "/usr/bin/csreq",
+ "-r",
+ argument,
+ "-b",
+ output,
+ )
+ self.assertGreater(output.stat().st_size, 0)
+
+ def test_native_data_is_signed_inside_out_with_scoped_entitlements(self):
+ with tempfile.TemporaryDirectory() as directory:
+ app = Path(directory) / "LNbits.app"
+ paths = [
+ "Contents/MacOS/LNbits",
+ "Contents/Frameworks/Python.framework/Versions/3.12/Python",
+ "Contents/Frameworks/sidecars/node",
+ "Contents/Frameworks/sidecars/phoenixd",
+ "Contents/Resources/sidecars/spark/node_modules/native.node",
+ "Contents/Frameworks/_tkinter.so",
+ ]
+ for name in paths:
+ path = app / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"\xcf\xfa\xed\xfe" + b"dummy Mach-O")
+ (app / "Contents/Frameworks/alias").symlink_to("_tkinter.so")
+ runner = Mock()
+ signing.sign_app(
+ runner, app, IDENTITY, "/private/temp.keychain-db", "arm64"
+ )
+ calls = runner.run.call_args_list
+ signed = [call.args[-1] for call in calls]
+ self.assertEqual(signed[-1], app)
+ self.assertEqual(len(signed), len(paths) + 2) # framework and outer app
+ self.assertLess(
+ signed.index(app / paths[1]),
+ signed.index(app / "Contents/Frameworks/Python.framework"),
+ )
+ for call in calls:
+ self.assertNotIn("--deep", call.args)
+ self.assertIn("--timestamp", call.args)
+ self.assertIn("--keychain", call.args)
+ self.assertIn(IDENTITY, call.args)
+ has_entitlements = call.args[-1] in (
+ app,
+ app / paths[0],
+ app / paths[2],
+ )
+ self.assertEqual("--entitlements" in call.args, has_entitlements)
+
+ def test_team_timestamp_runtime_and_entitlements_are_required(self):
+ details = (
+ "TeamIdentifier=ABCDEFGHIJ\nTimestamp=Sep 16, 2026\n"
+ "flags=0x10000(runtime)\n"
+ )
+ runner = Mock()
+ for bad in (None, "TeamIdentifier=WRONGTEAM1", "Timestamp=", "flags=0x0"):
+ display = details
+ if bad:
+ key = bad.split("=", 1)[0]
+ display = (
+ "\n".join(
+ bad if line.startswith(key + "=") else line
+ for line in details.splitlines()
+ )
+ + "\n"
+ )
+ runner.run.side_effect = [result(), result(stderr=display), result()]
+ if bad:
+ with self.assertRaises(ReleaseError):
+ signing.verify_code(runner, Path("code"), "ABCDEFGHIJ")
+ else:
+ signing.verify_code(runner, Path("code"), "ABCDEFGHIJ")
+ runner.run.side_effect = [
+ result(),
+ result(stderr=details),
+ result(
+ plistlib.dumps({"com.apple.security.get-task-allow": True}).decode()
+ ),
+ ]
+ with self.assertRaisesRegex(ReleaseError, "entitlements"):
+ signing.verify_code(runner, Path("code"), "ABCDEFGHIJ")
+
+ def test_node_memory_entitlements_are_scoped_and_verified_per_architecture(self):
+ app = Path("LNbits.app")
+ node = app / "Contents/Frameworks/sidecars/node"
+ native = app / "Contents/Resources/sidecars/spark/native.node"
+ phoenixd = app / "Contents/Frameworks/sidecars/phoenixd"
+ policies = {
+ "arm64": {"com.apple.security.cs.allow-jit": True},
+ "x86_64": {
+ "com.apple.security.cs.allow-jit": True,
+ "com.apple.security.cs.allow-unsigned-executable-memory": True,
+ },
+ }
+ for arch, expected in policies.items():
+ with self.subTest(arch=arch):
+ runner = Mock()
+ with patch(
+ "macos.signing.code_targets", return_value=[node, native, phoenixd]
+ ):
+ signing.sign_app(runner, app, IDENTITY, "temp.keychain-db", arch)
+ node_call, *other_calls = runner.run.call_args_list
+ entitlements = Path(
+ node_call.args[node_call.args.index("--entitlements") + 1]
+ )
+ self.assertEqual(plistlib.loads(entitlements.read_bytes()), expected)
+ for call in other_calls:
+ self.assertNotIn("--entitlements", call.args)
+ for actual in policies.values():
+ runner.run.side_effect = [
+ result(),
+ result(
+ stderr="TeamIdentifier=ABCDEFGHIJ\nTimestamp=Sep 18, 2026\n"
+ "flags=0x10000(runtime)\n"
+ ),
+ result(plistlib.dumps(actual).decode()),
+ ]
+ with patch("macos.signing.code_targets", return_value=[node]):
+ if actual == expected:
+ signing.verify_app(runner, app, "ABCDEFGHIJ", arch)
+ else:
+ with self.assertRaisesRegex(ReleaseError, "entitlements"):
+ signing.verify_app(runner, app, "ABCDEFGHIJ", arch)
+
+ def test_notarization_accepts_only_exact_accepted_and_reports_id(self):
+ for status in ("Accepted", "Invalid", "In Progress", "accepted", None):
+ with self.subTest(status=status):
+ runner = Runner(DUMMY)
+ runner.run = Mock(
+ side_effect=[
+ result(json.dumps({"id": SUBMISSION})),
+ result(json.dumps({"status": status})),
+ result("diagnostic " + DUMMY["APPLE_APP_SPECIFIC_PASSWORD"]),
+ ]
+ )
+ with patch("sys.stdout", new_callable=io.StringIO) as output:
+ if status == "Accepted":
+ signing.notarize(runner, Path("app.zip"), "temp.keychain-db")
+ self.assertEqual(runner.run.call_count, 2)
+ else:
+ with self.assertRaises(ReleaseError) as caught:
+ signing.notarize(
+ runner, Path("app.zip"), "temp.keychain-db"
+ )
+ self.assertIn(SUBMISSION, str(caught.exception))
+ self.assertNotIn(
+ DUMMY["APPLE_APP_SPECIFIC_PASSWORD"], str(caught.exception)
+ )
+ self.assertIn(SUBMISSION, output.getvalue())
+ wait = runner.run.call_args_list[1]
+ self.assertIn("--timeout", wait.args)
+ self.assertLessEqual(wait.kwargs["timeout"], 1860)
+
+ def test_malformed_notary_json_and_nonzero_accepted_fail(self):
+ for submit in ("not json", "{}", '{"id": "bad id"}'):
+ runner = Mock()
+ runner.run.return_value = result(submit)
+ with self.assertRaises(ReleaseError):
+ signing.notarize(runner, Path("app.zip"), "temp.keychain-db")
+ self.assertEqual(runner.run.call_count, 1)
+ runner = Runner(DUMMY)
+ runner.run = Mock(
+ side_effect=[
+ result(json.dumps({"id": SUBMISSION})),
+ result('{"status":"Accepted"}', returncode=1),
+ result(),
+ ]
+ )
+ with self.assertRaises(ReleaseError):
+ signing.notarize(runner, Path("app.zip"), "temp.keychain-db")
+
+ def test_notarization_wait_timeout_keeps_submission_id(self):
+ runner = Runner(DUMMY)
+ runner.run = Mock(
+ side_effect=[
+ result(json.dumps({"id": SUBMISSION})),
+ ReleaseError("Wait timed out"),
+ ]
+ )
+ with patch("sys.stdout", new_callable=io.StringIO) as output:
+ with self.assertRaisesRegex(ReleaseError, "timed out"):
+ signing.notarize(runner, Path("app.zip"), "temp.keychain-db")
+ self.assertIn(SUBMISSION, output.getvalue())
+ self.assertEqual(runner.run.call_count, 2)
+
+ def test_entitlement_override_cannot_broaden_release_policy(self):
+ with tempfile.TemporaryDirectory() as directory:
+ entitlements = Path(directory) / "override.plist"
+ entitlements.write_bytes(
+ plistlib.dumps(
+ {"com.apple.security.cs.disable-library-validation": True}
+ )
+ )
+ with patch.dict(os.environ, {"MACOS_ENTITLEMENTS_FILE": str(entitlements)}):
+ with self.assertRaises(ReleaseError):
+ signing.entitlement_file(
+ Path("LNbits.app"), Path("LNbits.app"), "arm64"
+ )
+
+
+class PipelineTests(unittest.TestCase):
+ def setUp(self):
+ self.folder = Path(self.enterContext(tempfile.TemporaryDirectory()))
+ self.enterContext(contextlib.chdir(self.folder))
+ Path("pyproject.toml").write_text('[project]\nversion="1.6.2-rc1"\n')
+ self.app = Path("dist/LNbits.app").resolve()
+ (self.app / "Contents").mkdir(parents=True)
+ (self.app / "Contents/Info.plist").write_bytes(plistlib.dumps({}))
+ self.enterContext(patch("macos.dmg.platform.machine", return_value="arm64"))
+ self.output = dmg.output_path()
+ self.events = []
+ self.session = Mock(
+ state={"keychain": "temp.keychain-db", "directory": str(self.folder)}
+ )
+ self.session.setup.return_value = IDENTITY
+ self.session.cleanup.side_effect = lambda: self.events.append("cleanup")
+ self.runner = Runner(DUMMY)
+
+ def run(operation, *args, **kwargs):
+ self.events.append(operation)
+ if operation == "Archive signed app":
+ Path(args[-1]).write_bytes(b"zip")
+ return result()
+
+ self.runner.run = Mock(side_effect=run)
+ for name in ("bundled_data", "sign_app", "verify_app", "verify_image"):
+ self.enterContext(
+ patch(
+ "macos.release." + name,
+ side_effect=lambda *a, _name=name, **k: self.events.append(_name),
+ )
+ )
+ self.enterContext(
+ patch(
+ "macos.release.sign",
+ side_effect=lambda *a, **k: self.events.append("sign_dmg"),
+ )
+ )
+
+ def notarize(runner, artifact, keychain):
+ self.events.append(
+ "notarize_app" if artifact.suffix == ".zip" else "notarize_dmg"
+ )
+
+ self.notarize = self.enterContext(
+ patch("macos.release.notarize", side_effect=notarize)
+ )
+
+ def staple(runner, artifact):
+ self.events.append(
+ "staple_app" if artifact.suffix == ".app" else "staple_dmg"
+ )
+ if artifact.suffix == ".dmg":
+ artifact.write_bytes(artifact.read_bytes() + b" stapled")
+
+ self.enterContext(patch("macos.release.staple", side_effect=staple))
+
+ def create(*args, **kwargs):
+ self.events.append("create_dmg")
+ self.output.write_bytes(b"final dmg")
+
+ self.enterContext(patch("macos.dmg.create", side_effect=create))
+ self.enterContext(patch.dict(os.environ, {}, clear=True))
+
+ def test_order_checksum_and_no_app_mutation_after_stapling(self):
+ release.release(
+ self.runner,
+ self.session,
+ signed=True,
+ credentials=DUMMY,
+ arch="arm64",
+ skip_build=True,
+ )
+ self.assertEqual(
+ self.events,
+ [
+ "bundled_data",
+ "sign_app",
+ "verify_app",
+ "Archive signed app",
+ "notarize_app",
+ "staple_app",
+ "create_dmg",
+ "sign_dmg",
+ "notarize_dmg",
+ "staple_dmg",
+ "verify_image",
+ "cleanup",
+ ],
+ )
+ self.assertEqual(self.notarize.call_count, 2)
+ checksum = self.output.with_suffix(".dmg.sha256").read_text()
+ self.assertEqual(
+ checksum,
+ f'{hashlib.sha256(b"final dmg stapled").hexdigest()} {self.output.name}\n',
+ )
+ metadata = plistlib.loads((self.app / "Contents/Info.plist").read_bytes())
+ self.assertEqual(metadata["CFBundleVersion"], "1.6.2")
+ self.assertEqual(metadata["LSMinimumSystemVersion"], "15.0")
+
+ def test_failure_at_every_gate_cleans_and_removes_artifacts(self):
+ for target in (
+ "bundled_data",
+ "sign_app",
+ "verify_app",
+ "notarize",
+ "staple",
+ "dmg.create",
+ "sign",
+ "verify_image",
+ "session.cleanup",
+ ):
+ with self.subTest(target=target):
+ self.output.write_bytes(b"stale dmg")
+ self.output.with_suffix(".dmg.sha256").write_text("stale checksum")
+ if target == "session.cleanup":
+ manager = patch.object(
+ self.session, "cleanup", side_effect=ReleaseError(target)
+ )
+ else:
+ manager = patch(
+ "macos.release." + target, side_effect=ReleaseError(target)
+ )
+ with manager, self.assertRaises(ReleaseError):
+ release.release(
+ self.runner,
+ self.session,
+ signed=True,
+ credentials=DUMMY,
+ arch="arm64",
+ skip_build=True,
+ )
+ self.assertFalse(self.output.exists())
+ self.assertFalse(self.output.with_suffix(".dmg.sha256").exists())
+ self.session.cleanup.assert_called()
+
+ def test_unsigned_never_imports_credentials_or_notarizes(self):
+ release.release(
+ self.runner,
+ self.session,
+ signed=False,
+ credentials={},
+ arch="arm64",
+ skip_build=True,
+ )
+ self.session.setup.assert_not_called()
+ self.notarize.assert_not_called()
+ self.assertTrue(self.output.with_suffix(".dmg.sha256").exists())
+
+ def test_wrong_architecture_fails_before_signing_or_notarization(self):
+ with (
+ patch(
+ "macos.release.bundled_data",
+ side_effect=ReleaseError("Wrong native architecture"),
+ ),
+ patch("macos.release.sign_app") as sign_app,
+ self.assertRaisesRegex(ReleaseError, "Wrong native architecture"),
+ ):
+ release.release(
+ self.runner,
+ self.session,
+ signed=True,
+ credentials=DUMMY,
+ arch="arm64",
+ skip_build=True,
+ )
+ sign_app.assert_not_called()
+ self.session.setup.assert_not_called()
+ self.notarize.assert_not_called()
+ self.assertFalse(self.output.exists())
+
+ def test_verification_error_survives_cleanup_failure_without_a_checksum(self):
+ original = ReleaseError("Wrong native architecture: spark/native.bare")
+ with (
+ patch("macos.release.verify_image", side_effect=original),
+ patch.object(
+ self.session,
+ "cleanup",
+ side_effect=ReleaseError("Detach final DMG: " + DUMMY["P12_PASSWORD"]),
+ ),
+ patch("sys.stderr", new_callable=io.StringIO) as errors,
+ self.assertRaises(ReleaseError) as caught,
+ ):
+ release.release(
+ self.runner,
+ self.session,
+ signed=False,
+ credentials={},
+ arch="arm64",
+ skip_build=True,
+ )
+ self.assertIs(caught.exception, original)
+ self.assertIn("Detach final DMG", errors.getvalue())
+ self.assertNotIn(DUMMY["P12_PASSWORD"], errors.getvalue())
+ self.assertFalse(self.output.exists())
+ self.assertFalse(self.output.with_suffix(".dmg.sha256").exists())
+
+ def test_image_creation_copies_without_metadata_changes_or_resigning(self):
+ original = self.app / "Contents/Info.plist"
+ before = original.read_bytes()
+ actual_create = CREATE_DMG
+
+ def run(operation, *args, **kwargs):
+ self.assertNotIn("codesign", " ".join(str(arg) for arg in args))
+ if operation == "Copy finalized app":
+ shutil.copytree(args[-2], args[-1])
+ if operation == "Create uncompressed DMG":
+ staging = Path(args[args.index("-srcfolder") + 1])
+ self.assertNotIn(staging, Path(args[-1]).parents)
+ self.assertEqual(args[args.index("-format") + 1], "UDRW")
+ self.assertIn("-nospotlight", args)
+ self.assertEqual(
+ (staging / "LNbits.app/Contents/Info.plist").read_bytes(), before
+ )
+ self.assertEqual(
+ (staging / "Applications").readlink(), Path("/Applications")
+ )
+ self.assertNotIn("Open Anyway", (staging / "Read me.txt").read_text())
+
+ self.runner.run.side_effect = run
+ actual_create(self.app, self.output, self.runner, signed=True)
+ self.assertEqual(original.read_bytes(), before)
+ operations = [call.args[0] for call in self.runner.run.call_args_list]
+ self.assertLess(
+ operations.index("Create uncompressed DMG"),
+ operations.index("Compress final DMG"),
+ )
+ conversion = self.runner.run.call_args_list[-1]
+ self.assertEqual(conversion.args[conversion.args.index("-format") + 1], "UDZO")
+ self.assertEqual(conversion.args[-1], self.output)
+ self.assertTrue(conversion.kwargs["log_output"])
+
+ def test_image_creation_timeout_removes_intermediate_and_skips_conversion(self):
+ intermediate = []
+
+ def run(operation, *args, **kwargs):
+ if operation == "Copy finalized app":
+ shutil.copytree(args[-2], args[-1])
+ if operation == "Create uncompressed DMG":
+ intermediate.append(Path(args[-1]))
+ intermediate[0].touch()
+ raise ReleaseError("Create uncompressed DMG: timed out")
+
+ self.runner.run.side_effect = run
+ with self.assertRaisesRegex(ReleaseError, "timed out"):
+ CREATE_DMG(self.app, self.output, self.runner, signed=True)
+ self.assertFalse(intermediate[0].parent.exists())
+ self.assertNotIn(
+ "Compress final DMG",
+ [call.args[0] for call in self.runner.run.call_args_list],
+ )
+
+ def test_second_submission_failure_never_staples_or_checksums_dmg(self):
+ original = self.notarize.side_effect
+
+ def fail_dmg(runner, artifact, keychain):
+ original(runner, artifact, keychain)
+ if artifact.suffix == ".dmg":
+ raise ReleaseError("DMG not Accepted")
+
+ self.notarize.side_effect = fail_dmg
+ with self.assertRaisesRegex(ReleaseError, "DMG not Accepted"):
+ release.release(
+ self.runner,
+ self.session,
+ signed=True,
+ credentials=DUMMY,
+ arch="arm64",
+ skip_build=True,
+ )
+ self.assertIn("staple_app", self.events)
+ self.assertNotIn("staple_dmg", self.events)
+ self.assertEqual(self.notarize.call_count, 2)
+ self.assertFalse(self.output.with_suffix(".dmg.sha256").exists())
+ self.assertEqual(self.events[-1], "cleanup")
+
+ def test_checksum_recheck_detects_changed_final_bytes(self):
+ self.output.write_bytes(b"completed image")
+ with patch("macos.dmg.checksum", side_effect=["old bytes", "changed bytes"]):
+ with self.assertRaisesRegex(RuntimeError, "checksum verification failed"):
+ dmg.write_checksum(self.output)
+ self.assertFalse(self.output.with_suffix(".dmg.sha256").exists())
+
+
+class DeliverableTests(unittest.TestCase):
+ def test_gatekeeper_error_survives_detach_failure(self):
+ with tempfile.TemporaryDirectory() as directory:
+ mount = Path(directory) / "mount"
+ mount.mkdir()
+ (mount / "Applications").symlink_to("/Applications")
+ session = Mock(state={})
+ session.detach.side_effect = ReleaseError("Detach final DMG: busy")
+ runner = Runner(DUMMY)
+ original = ReleaseError("Assess app Gatekeeper: rejected")
+
+ def run(operation, *args, **kwargs):
+ if operation == "Assess app Gatekeeper":
+ raise original
+ return result()
+
+ runner.run = Mock(side_effect=run)
+ with (
+ patch("macos.verify.tempfile.mkdtemp", return_value=str(mount)),
+ patch("macos.verify.verify_code"),
+ patch("macos.verify.verify_app"),
+ patch("sys.stderr", new_callable=io.StringIO) as errors,
+ self.assertRaises(ReleaseError) as caught,
+ ):
+ verify.verify_image(
+ runner, session, Path("final.dmg"), "arm64", "ABCDEFGHIJ"
+ )
+ self.assertIs(caught.exception, original)
+ self.assertIn("Detach final DMG: busy", errors.getvalue())
+ session.detach.assert_called_once()
+
+ def test_mount_is_read_only_and_always_detached_on_smoke_failure(self):
+ with tempfile.TemporaryDirectory() as directory:
+ mount = Path(directory) / "mount"
+ mount.mkdir()
+ (mount / "Applications").symlink_to("/Applications")
+ session = Mock(state={})
+ runner = Mock()
+
+ def run(operation, *args, **kwargs):
+ if operation == "Smoke packaged server and shutdown":
+ raise ReleaseError("smoke failed")
+ return result()
+
+ runner.run.side_effect = run
+ with (
+ patch("macos.verify.tempfile.mkdtemp", return_value=str(mount)),
+ patch("macos.verify.verify_code"),
+ patch("macos.verify.verify_app"),
+ patch("macos.verify.bundled_data"),
+ self.assertRaisesRegex(ReleaseError, "smoke failed"),
+ ):
+ verify.verify_image(
+ runner, session, Path("final.dmg"), "arm64", "ABCDEFGHIJ"
+ )
+ session.detach.assert_called_once()
+ calls = runner.run.call_args_list
+ attach = next(
+ call for call in calls if call.args[0] == "Mount final DMG read-only"
+ )
+ self.assertIn("-readonly", attach.args)
+ self.assertIn(Path("final.dmg"), attach.args)
+ for operation in (
+ "Verify DMG integrity",
+ "Validate DMG ticket",
+ "Assess DMG Gatekeeper",
+ "Assess app Gatekeeper",
+ "Validate app ticket",
+ "Smoke bundled sidecars",
+ ):
+ self.assertIn(operation, [call.args[0] for call in calls])
+
+ def test_native_architecture_in_data_is_verified(self):
+ with tempfile.TemporaryDirectory() as directory:
+ app = Path(directory) / "LNbits.app"
+ native = app / "Contents/Resources/spark/dependencies/native.node"
+ native.parent.mkdir(parents=True)
+ native.write_bytes(b"\xcf\xfa\xed\xfe" + b"dummy Mach-O")
+ runner = Mock()
+ runner.run.return_value = result("x86_64")
+ with self.assertRaisesRegex(ReleaseError, "Wrong native architecture"):
+ verify.verify_architecture(runner, app, "arm64")
+ runner.run.return_value = result("arm64 x86_64")
+ verify.verify_architecture(runner, app, "arm64")
+ runner.run.assert_called_with(
+ f"Verify native architecture: {native.relative_to(app)}",
+ "/usr/bin/lipo",
+ "-archs",
+ native,
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/packaging/test_prepare_sidecars.py b/.github/packaging/test_prepare_sidecars.py
index 2bde24b..d028c63 100644
--- a/.github/packaging/test_prepare_sidecars.py
+++ b/.github/packaging/test_prepare_sidecars.py
@@ -12,6 +12,53 @@ import prepare_sidecars
class PrepareSidecarsTests(unittest.TestCase):
+ def test_macos_prebuilds_keep_only_the_target_architecture(self):
+ for arch in ("arm64", "x64"):
+ with self.subTest(arch=arch), tempfile.TemporaryDirectory() as folder:
+ modules = Path(folder) / "node_modules"
+ variants = (
+ "darwin-arm64",
+ "darwin-x64",
+ "darwin-x64+arm64",
+ "ios-arm64",
+ "ios-x64-simulator",
+ "linux-arm64",
+ "win32-x64",
+ )
+ for package in ("bare-buffer", "nested/node_modules/bare-crypto"):
+ root = modules / package
+ root.mkdir(parents=True)
+ (root / "index.js").write_text("// shared runtime code")
+ for variant in variants:
+ binary = root / "prebuilds" / variant / "native.bare"
+ binary.parent.mkdir(parents=True)
+ binary.write_bytes(b"native prebuild")
+ (root / "prebuilds/README.md").write_text("license information")
+ prepare_sidecars.prune_prebuilds(modules, "darwin", arch)
+ for package in ("bare-buffer", "nested/node_modules/bare-crypto"):
+ root = modules / package
+ self.assertEqual(
+ {path.name for path in (root / "prebuilds").iterdir()},
+ {f"darwin-{arch}", "darwin-x64+arm64", "README.md"},
+ )
+ self.assertEqual(
+ (
+ root / "prebuilds" / f"darwin-{arch}" / "native.bare"
+ ).read_bytes(),
+ b"native prebuild",
+ )
+ self.assertTrue((root / "index.js").is_file())
+
+ def test_other_platforms_keep_their_existing_prebuilds(self):
+ for system in ("linux", "win"):
+ with self.subTest(system=system), tempfile.TemporaryDirectory() as folder:
+ modules = Path(folder) / "node_modules"
+ binary = modules / "package/prebuilds/darwin-arm64/native.bare"
+ binary.parent.mkdir(parents=True)
+ binary.write_bytes(b"unchanged")
+ prepare_sidecars.prune_prebuilds(modules, system, "x64")
+ self.assertEqual(binary.read_bytes(), b"unchanged")
+
def test_pinned_revision_and_checksum_are_used(self):
pin = {"release": "v0.1.4", "revision": "a" * 40, "sha256": "archive-digest"}
with (
diff --git a/.github/packaging/test_smoke_sidecars.py b/.github/packaging/test_smoke_sidecars.py
new file mode 100644
index 0000000..d739634
--- /dev/null
+++ b/.github/packaging/test_smoke_sidecars.py
@@ -0,0 +1,41 @@
+"""Catch Node startup failures before starting any bundled funding service."""
+
+import json
+import os
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import smoke_sidecars
+
+
+class SidecarSmokeTests(unittest.TestCase):
+ def test_node_initialization_failure_stops_before_starting_sidecars(self):
+ with tempfile.TemporaryDirectory() as directory:
+ resources = Path(directory)
+ (resources / "pins.json").write_text(
+ json.dumps({"node": {"version": "24.21.0"}})
+ )
+ for platform, executable in (("darwin", "node"), ("win32", "node.exe")):
+ with (
+ self.subTest(platform=platform),
+ patch("smoke_sidecars.sys.platform", platform),
+ patch.dict(os.environ, {"NODE_OPTIONS": "--jitless"}),
+ patch(
+ "smoke_sidecars.subprocess.check_output",
+ side_effect=subprocess.CalledProcessError(-5, [executable]),
+ ) as probe,
+ patch("smoke_sidecars.subprocess.Popen") as start,
+ ):
+ with self.assertRaises(subprocess.CalledProcessError):
+ smoke_sidecars.check(resources)
+ probe.assert_called_once()
+ command = probe.call_args.args[0]
+ self.assertEqual(
+ command[:2], [str(resources / executable), "--eval"]
+ )
+ self.assertNotIn("NODE_OPTIONS", probe.call_args.kwargs["env"])
+ self.assertEqual(probe.call_args.kwargs["timeout"], 30)
+ start.assert_not_called()
diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
index 520d125..fd9574b 100644
--- a/.github/workflows/macos.yml
+++ b/.github/workflows/macos.yml
@@ -1,23 +1,30 @@
name: Build LNbits macOS DMG
on:
- push:
- branches:
- - "**"
- paths:
- - ".github/packaging/**"
- - ".github/workflows/macos.yml"
- - "pyproject.toml"
- - "uv.lock"
+ # Temporary: build signed artifacts for PR testing before release-only CI.
+ pull_request:
workflow_call:
inputs:
tag_name:
required: true
type: string
+ secrets:
+ BUILD_CERTIFICATE_BASE64:
+ required: true
+ P12_PASSWORD:
+ required: true
+ KEYCHAIN_PASSWORD:
+ required: true
+ APPLE_ID:
+ required: true
+ APPLE_TEAM_ID:
+ required: true
+ APPLE_APP_SPECIFIC_PASSWORD:
+ required: true
workflow_dispatch:
inputs:
tag_name:
- description: Release tag (leave empty to build this branch as an artifact)
+ description: Release tag (leave empty for an artifact-only build)
required: false
type: string
@@ -26,6 +33,8 @@ permissions:
jobs:
build:
+ # Fork PRs do not receive the Apple signing secrets.
+ if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
strategy:
fail-fast: false
matrix:
@@ -35,11 +44,13 @@ jobs:
- runner: macos-15-intel
arch: x86_64
runs-on: ${{ matrix.runner }}
- timeout-minutes: 40
+ timeout-minutes: 120
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.tag_name || github.ref }}
+ - name: Initialize release recovery path
+ run: echo "MACOS_RELEASE_STATE=$RUNNER_TEMP/lnbits-release.json" >> "$GITHUB_ENV"
- uses: actions/setup-python@v5
with:
python-version: "3.12"
@@ -48,60 +59,37 @@ jobs:
with:
node-version: "24.x"
cache: npm
- - name: Verify frontend assets
- run: |
- npm ci
- npm run bundle
- ./node_modules/.bin/prettier -w ./lnbits/static/vendor.json
- git diff --exit-code -- lnbits/static
- - name: Build application
- run: |
- # Intel builds cryptography from source; avoid sharing Python's libssl.
- uv cache clean cryptography
- OPENSSL_STATIC=1 OPENSSL_DIR="$(brew --prefix openssl@3)" \
- uv sync --locked --no-dev --no-editable --reinstall-package cryptography
- uv pip install pyinstaller==6.22.2
- uv run --no-sync python .github/packaging/build.py
- - name: Test launcher window and shutdown
- run: uv run --no-sync python -m unittest discover -s .github/packaging -v
- - name: Verify native architecture and packaged data
+ - name: Verify native runner and report build environment
env:
EXPECTED_ARCH: ${{ matrix.arch }}
run: |
- test "$(lipo -archs dist/LNbits.app/Contents/MacOS/LNbits)" = "$EXPECTED_ARCH"
- test -f dist/LNbits.app/Contents/Resources/certifi/cacert.pem
- test -f dist/LNbits.app/Contents/Resources/random_username/data/nouns.txt
- test -f dist/LNbits.app/Contents/Resources/pyinstrument/renderers/html_resources/app.js
- codesign --verify --deep --strict dist/LNbits.app
- - name: Build and verify DMG
- run: uv run --no-sync python .github/packaging/macos/dmg.py
- - name: Test application from read-only disk image
- run: |
- MOUNT_DIR="$(mktemp -d)"
- hdiutil attach dist/*.dmg -mountpoint "$MOUNT_DIR" -nobrowse -readonly
- cleanup() {
- status=$?
- # macOS can briefly keep the volume busy after the tests exit.
- for attempt in 1 2 3 4 5; do
- if hdiutil detach "$MOUNT_DIR"; then
- rmdir "$MOUNT_DIR"
- return "$status"
- fi
- echo "Disk image detach attempt $attempt/5 failed; waiting before retry."
- sleep 2
- done
- # This is a read-only test image and the smoke tests have finished.
- hdiutil detach -force "$MOUNT_DIR"
- rmdir "$MOUNT_DIR"
- return "$status"
- }
- trap cleanup EXIT
- test -L "$MOUNT_DIR/Applications"
- codesign --verify --deep --strict "$MOUNT_DIR/LNbits.app"
- uv run --no-sync python .github/packaging/smoke_sidecars.py "$MOUNT_DIR/LNbits.app/Contents/Frameworks/sidecars"
- uv run --no-sync python .github/packaging/smoke.py "$MOUNT_DIR/LNbits.app/Contents/MacOS/LNbits"
+ test "$(uname -m)" = "$EXPECTED_ARCH"
+ sw_vers
+ uname -m
+ python3 --version
+ uv --version
+ xcodebuild -version
+ df -h . "$RUNNER_TEMP"
+ - name: Prepare dependencies and verify frontend assets
+ run: python3 .github/packaging/macos/release.py --prepare-only
+ - name: Test launcher and packaging
+ run: uv run --no-sync python -m unittest discover -s .github/packaging -v
+ - name: Build signed and notarized release artifacts
+ env:
+ BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
+ P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
+ KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
+ run: uv run --no-sync python .github/packaging/macos/release.py --ci --prepared
+ # Runs before upload: any cleanup failure keeps both artifacts unpublished.
+ - name: Always clean temporary keychain and mounted image
+ if: always()
+ run: python3 .github/packaging/macos/release.py --cleanup
- name: Record signing status
- run: echo 'DMGs are ad-hoc signed, without Apple Developer ID or notarization.' >> "$GITHUB_STEP_SUMMARY"
+ run: |
+ echo 'Developer ID signed; app and DMG independently notarized, stapled and verified. Final read-only image smoke checks and checksum verification passed.' >> "$GITHUB_STEP_SUMMARY"
- uses: actions/upload-artifact@v4
with:
name: LNbits-macOS-${{ matrix.arch }}
@@ -122,9 +110,11 @@ jobs:
pattern: LNbits-macOS-*
merge-multiple: true
path: dist
- - name: Attach DMGs and checksums to release
+ - name: Attach signed DMGs and checksums to release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
TAG_NAME: ${{ inputs.tag_name }}
- run: gh release upload "$TAG_NAME" dist/*.dmg dist/*.dmg.sha256 --clobber
+ run: |
+ (cd dist && shasum -a 256 -c ./*.dmg.sha256)
+ gh release upload "$TAG_NAME" dist/*.dmg dist/*.dmg.sha256 --clobber
diff --git a/.github/workflows/release-rc.yml b/.github/workflows/release-rc.yml
index 5fa1c8c..ecd6ae6 100644
--- a/.github/workflows/release-rc.yml
+++ b/.github/workflows/release-rc.yml
@@ -93,3 +93,10 @@ jobs:
uses: ./.github/workflows/macos.yml
with:
tag_name: ${{ github.ref_name }}
+ secrets:
+ BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
+ P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
+ KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index db6c88d..5bcf9a7 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -104,3 +104,10 @@ jobs:
uses: ./.github/workflows/macos.yml
with:
tag_name: ${{ github.ref_name }}
+ secrets:
+ BUILD_CERTIFICATE_BASE64: ${{ secrets.BUILD_CERTIFICATE_BASE64 }}
+ P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
+ KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
+ APPLE_ID: ${{ secrets.APPLE_ID }}
+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
+ APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
diff --git a/.gitignore b/.gitignore
index a13beb6..50dbc31 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,3 +63,6 @@ dist
# jetbrains
.idea
.venv
+
+# Private macOS release credentials
+.env.macos-release
diff --git a/Makefile b/Makefile
index 287f6c8..4a5c38d 100644
--- a/Makefile
+++ b/Makefile
@@ -41,6 +41,16 @@ dev:
docker:
docker build -t lnbits/lnbits .
+# Native macOS builds; the release command loads .env.macos-release, never publishes.
+.PHONY: build-macos build-macos-release
+build-macos:
+ python3 .github/packaging/macos/release.py --prepare-only
+ uv run --no-sync python .github/packaging/macos/release.py --unsigned --prepared
+
+build-macos-release:
+ python3 .github/packaging/macos/release.py --prepare-only
+ uv run --no-sync python .github/packaging/macos/release.py --env-file .env.macos-release --prepared
+
test-desktop:
uv run python -m unittest discover -s .github/packaging -v
Why this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.