From f3d6cbd4209b1c16c6048bb1f4516a1e95a74bae Mon Sep 17 00:00:00 2001 From: MDHaarith Date: Fri, 23 Oct 2026 01:31:03 +0530 Subject: [PATCH 1/2] Keep Android drop targets above decorative children - Route edge panel drops through a dedicated surface - Add regression coverage for drops handled by child views --- .../mdhaarith/airbridge/overlay/DropLayout.kt | 21 +++++++ .../mdhaarith/airbridge/overlay/EdgePanel.kt | 17 +++--- .../airbridge/overlay/DropLayoutTest.kt | 57 +++++++++++++++++++ 3 files changed, 86 insertions(+), 9 deletions(-) create mode 100644 android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/DropLayout.kt create mode 100644 android/app/src/test/java/io/github/mdhaarith/airbridge/overlay/DropLayoutTest.kt diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/DropLayout.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/DropLayout.kt new file mode 100644 index 0000000..1d76b05 --- /dev/null +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/DropLayout.kt @@ -0,0 +1,21 @@ +package io.github.mdhaarith.airbridge.overlay + +import android.content.Context +import android.view.View +import android.widget.FrameLayout + +/** A drag surface above the decorative children, using native View drag dispatch. */ +internal open class DropLayout(context: Context) : FrameLayout(context) { + val dropTarget = View(context) + + init { + addView(dropTarget, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) + } + + override fun onViewAdded(child: View) { + super.onViewAdded(child) + // ViewGroup dispatches to the frontmost interested child. The surface + // must stay above Compose, including when the hidden card becomes visible. + if (child !== dropTarget) dropTarget.bringToFront() + } +} diff --git a/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/EdgePanel.kt b/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/EdgePanel.kt index d9a3ce8..f438e2d 100644 --- a/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/EdgePanel.kt +++ b/android/app/src/main/java/io/github/mdhaarith/airbridge/overlay/EdgePanel.kt @@ -24,7 +24,6 @@ import android.view.MotionEvent import android.view.View import android.view.ViewConfiguration import android.view.WindowManager -import android.widget.FrameLayout import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ContentPaste import androidx.compose.material.icons.rounded.FileOpen @@ -174,7 +173,7 @@ class EdgePanel(private val context: Context) { } } } - val root = object : FrameLayout(context) { + val root = object : DropLayout(context) { override fun dispatchKeyEvent(event: KeyEvent): Boolean { if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_UP) { close() @@ -192,12 +191,12 @@ class EdgePanel(private val context: Context) { root.addView(compose) var receivingTarget: String? = null if (Build.VERSION.SDK_INT >= 31) { - root.setOnReceiveContentListener(DROP_TYPES) { _, payload -> + root.dropTarget.setOnReceiveContentListener(DROP_TYPES) { _, payload -> onDrop(payload.clip, grant = payload, target = receivingTarget) null } } - root.setOnDragListener { _, event -> + root.dropTarget.setOnDragListener { view, event -> val target = panelTargets.entries.firstOrNull { (id, bounds) -> (id == DropTargets.ALL || engine.peers.value.any { it.id == id }) && bounds.contains(Offset(event.x, event.y)) }?.key @@ -208,7 +207,7 @@ class EdgePanel(private val context: Context) { DragEvent.ACTION_DROP -> { receivingTarget = target panelHover = null - if (Build.VERSION.SDK_INT < 31 || !root.onDragEvent(event)) onDrop(event.clipData, target = target) + if (Build.VERSION.SDK_INT < 31 || !view.onDragEvent(event)) onDrop(event.clipData, target = target) true } else -> true @@ -471,7 +470,7 @@ class EdgePanel(private val context: Context) { * there. */ @SuppressLint("ViewConstructor") - private inner class HandleRoot(context: Context, private val rightSide: Boolean) : FrameLayout(context) { + private inner class HandleRoot(context: Context, private val rightSide: Boolean) : DropLayout(context) { private val pill = HandleView(context, rightSide, this) private val owner = OverlayOwner() private val tab = ComposeView(context).apply { @@ -497,12 +496,12 @@ class EdgePanel(private val context: Context) { // Android reads a drop for us here and lends us the right to // open the other app's files, which an overlay can't ask for itself. // (Android refuses a bare "*/*" here, so name the families.) - setOnReceiveContentListener(DROP_TYPES) { _, payload: ContentInfo -> + dropTarget.setOnReceiveContentListener(DROP_TYPES) { _, payload: ContentInfo -> onDrop(payload.clip, grant = payload, target = receivingTarget) null } } - setOnDragListener { _, event -> + dropTarget.setOnDragListener { view, event -> when (event.action) { DragEvent.ACTION_DRAG_STARTED -> if (busy()) false else { startDrag(); true } DragEvent.ACTION_DRAG_ENTERED, DragEvent.ACTION_DRAG_LOCATION -> { @@ -520,7 +519,7 @@ class EdgePanel(private val context: Context) { tabOver = false tabHovered = null // Android 12+ passes the drop, readable, to the content listener above. - if (Build.VERSION.SDK_INT < 31 || !onDragEvent(event)) onDrop(event.clipData, target = receivingTarget) + if (Build.VERSION.SDK_INT < 31 || !view.onDragEvent(event)) onDrop(event.clipData, target = receivingTarget) true } else -> true diff --git a/android/app/src/test/java/io/github/mdhaarith/airbridge/overlay/DropLayoutTest.kt b/android/app/src/test/java/io/github/mdhaarith/airbridge/overlay/DropLayoutTest.kt new file mode 100644 index 0000000..09f4d02 --- /dev/null +++ b/android/app/src/test/java/io/github/mdhaarith/airbridge/overlay/DropLayoutTest.kt @@ -0,0 +1,57 @@ +package io.github.mdhaarith.airbridge.overlay + +import android.content.ClipData +import android.net.Uri +import android.view.DragEvent +import android.view.View +import android.widget.FrameLayout +import app.cash.paparazzi.Paparazzi +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test + +class DropLayoutTest { + @get:Rule + val paparazzi = Paparazzi() + + @Test + fun deviceCardReceivesDropEvenWhenAChildHandlesDragEvents() { + // A ViewGroup does not reach its own listener when an interested child + // consumes DROP. Decorative children must not own the device card's drag. + assertEquals(emptyList(), dropOn(FrameLayout(paparazzi.context))) + assertEquals(listOf("content://photos/42"), dropOn(DropLayout(paparazzi.context))) + } + + private fun dropOn(root: FrameLayout): List { + val received = mutableListOf() + val target = if (root is DropLayout) root.dropTarget else root + target.setOnReceiveContentListener(arrayOf("image/*")) { _, payload -> + received += payload.clip.getItemAt(0).uri.toString() + null + } + target.setOnDragListener { view, event -> + if (event.action == DragEvent.ACTION_DROP) view.onDragEvent(event) else true + } + val child = View(paparazzi.context).apply { + setOnDragListener { _, _ -> true } + } + root.addView(child, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)) + val clip = ClipData.newRawUri("photo", Uri.parse("content://photos/42")) + root.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> + for (action in listOf(DragEvent.ACTION_DRAG_STARTED, DragEvent.ACTION_DRAG_LOCATION, DragEvent.ACTION_DROP, DragEvent.ACTION_DRAG_ENDED)) { + root.dispatchDragEvent(event(action, clip)) + } + } + paparazzi.snapshot(root) + return received + } + + // DragEvent.obtain is hidden from the SDK; use its fields to construct + // platform events in the existing layoutlib runtime, without a new runner. + private fun event(action: Int, clip: ClipData): DragEvent = + DragEvent::class.java.getDeclaredConstructor().apply { isAccessible = true }.newInstance().also { event -> + for ((name, value) in mapOf("mAction" to action, "mX" to 50f, "mY" to 50f, "mClipData" to clip, "mClipDescription" to clip.description)) { + DragEvent::class.java.getDeclaredField(name).apply { isAccessible = true }.set(event, value) + } + } +} From 2830085819004ef1a81f952687cf2f9b2476c1ce Mon Sep 17 00:00:00 2001 From: MDHaarith Date: Fri, 23 Oct 2026 01:59:37 +0530 Subject: [PATCH 2/2] Release versioned signed AppImages automatically - Select and stamp stable versions for Linux and Android releases - Publish signed AppImages after successful main CI runs - Update the Linux updater to install newer stable releases --- .github/scripts/release_version.py | 90 ++++++++++++++++++ .github/scripts/test_release_version.py | 48 ++++++++++ .github/workflows/ci.yml | 63 +------------ .github/workflows/release.yml | 94 +++++++++++++------ .gitignore | 1 + README.md | 23 ++++- android/app/build.gradle.kts | 4 +- .../airbridge/overlay/DropLayoutTest.kt | 4 +- docs/SECURITY.md | 4 +- linux/Cargo.lock | 2 +- linux/Cargo.toml | 2 +- linux/src/ui.rs | 2 +- linux/src/update.rs | 94 +++++++++++++------ linux/ui/app.js | 2 +- 14 files changed, 305 insertions(+), 128 deletions(-) create mode 100644 .github/scripts/release_version.py create mode 100644 .github/scripts/test_release_version.py diff --git a/.github/scripts/release_version.py b/.github/scripts/release_version.py new file mode 100644 index 0000000..6e23138 --- /dev/null +++ b/.github/scripts/release_version.py @@ -0,0 +1,90 @@ +"""Choose release tags and stamp both apps in the build checkout (no commits).""" + +import argparse +from pathlib import Path +import re +import subprocess +import tomllib + +ROOT = Path(__file__).resolve().parents[2] +VERSION = re.compile(r"v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)") + + +def parse_version(value): + match = VERSION.fullmatch(value) + if not match: + raise ValueError(f"Expected a stable version such as v0.1.5, got {value!r}") + return tuple(map(int, match.groups())) + + +def choose_version(tags, minimum, current_tags=(), requested=""): + if requested: + version = parse_version(requested) + else: + # Rerunning the same commit repairs its release instead of consuming a patch. + floor = parse_version(minimum) + existing = [parse_version(t) for t in current_tags if t.startswith("v") and VERSION.fullmatch(t) and parse_version(t) >= floor] + if existing: + version = max(existing) + else: + stable = [parse_version(t) for t in tags if t.startswith("v") and VERSION.fullmatch(t)] + latest = max(stable, default=(0, 0, 0)) + version = max(floor, (*latest[:2], latest[2] + 1)) + return ".".join(map(str, version)) + + +def version_code(version): + major, minor, patch = parse_version(version) + code = major * 1_000_000 + minor * 1_000 + patch + if minor >= 1000 or patch >= 1000 or not 1 <= code <= 2_100_000_000: + raise ValueError("Version exceeds the Android versionCode range") + return code + + +def stamp(version, root=ROOT): + code = version_code(version) + changes = { + "linux/Cargo.toml": [(r'(?m)^version = "[^"]+"$', f'version = "{version}"')], + "linux/Cargo.lock": [(r'(?m)(^name = "airbridge"\nversion = ")[^"]+("$)', rf'\g<1>{version}\2')], + "android/app/build.gradle.kts": [ + (r'(?m)^(\s*versionName = ")[^"]+("$)', rf'\g<1>{version}\2'), + (r'(?m)^(\s*versionCode = )\d+$', rf'\g<1>{code}'), + ], + } + for name, replacements in changes.items(): + path = root / name + text = path.read_text() + for pattern, replacement in replacements: + text, count = re.subn(pattern, replacement, text) + if count != 1: + raise ValueError(f"Expected one version field in {name}, found {count}") + path.write_text(text) + + +def git(*args): + return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=("select", "stamp")) + parser.add_argument("version", nargs="?", default="") + parser.add_argument("--automatic", action="store_true") + args = parser.parse_args() + if args.command == "stamp": + stamp(".".join(map(str, parse_version(args.version)))) + return + tags = git("tag", "--list").splitlines() + current = git("tag", "--points-at", "HEAD").splitlines() if args.automatic else [] + minimum = tomllib.loads((ROOT / "linux/Cargo.toml").read_text())["package"]["version"] + version = choose_version(tags, minimum, current, args.version) + version_code(version) + tag = f"v{version}" + sha = git("rev-parse", "HEAD") + if tag in tags and git("rev-parse", f"refs/tags/{tag}^{{commit}}") != sha: + raise ValueError(f"{tag} already belongs to another commit; choose a new version") + print(f"version={version}\ntag={tag}\nsha={sha}") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/test_release_version.py b/.github/scripts/test_release_version.py new file mode 100644 index 0000000..f6ec137 --- /dev/null +++ b/.github/scripts/test_release_version.py @@ -0,0 +1,48 @@ +from pathlib import Path +import tempfile +import unittest + +from release_version import ROOT, choose_version, parse_version, stamp, version_code + + +class ReleaseVersionTest(unittest.TestCase): + def test_starts_at_015_ignoring_old_main_builds(self): + self.assertEqual(choose_version(["v0.1.0", "main-45"], "0.1.5"), "0.1.5") + self.assertEqual(choose_version([], "0.1.5"), "0.1.5") + self.assertEqual(choose_version(["v0.1.0"], "0.1.5", ["v0.1.0"]), "0.1.5") + + def test_increments_numerically_and_reuses_a_tag_on_retry(self): + tags = ["v0.1.5", "v0.1.9", "v0.1.10", "v1.0.0-rc.1", "main-999"] + self.assertEqual(choose_version(tags, "0.1.5"), "0.1.11") + self.assertEqual(choose_version(tags, "0.1.5", ["v0.1.5"]), "0.1.5") + self.assertEqual(choose_version(tags + ["v0.2.0"], "0.1.5"), "0.2.1") + self.assertEqual(choose_version(tags, "0.2.0"), "0.2.0") + + def test_explicit_versions_are_validated(self): + self.assertEqual(choose_version([], "0.1.5", requested="v0.1.6"), "0.1.6") + for value in ["main-45", "0.01.5", "0.1.5\nsha=bad", "0.1.5; echo bad", "0.1.5-rc.1"]: + with self.subTest(value=value), self.assertRaises(ValueError): + parse_version(value) + self.assertLess(version_code("0.1.5"), version_code("0.1.6")) + self.assertLess(version_code("0.1.999"), version_code("0.2.0")) + with self.assertRaises(ValueError): + version_code("0.1.1000") + + def test_stamps_both_apps_and_the_lockfile(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + names = ["linux/Cargo.toml", "linux/Cargo.lock", "android/app/build.gradle.kts"] + for name in names: + target = root / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text((ROOT / name).read_text()) + stamp("0.1.6", root) + self.assertIn('version = "0.1.6"', (root / names[0]).read_text()) + self.assertIn('name = "airbridge"\nversion = "0.1.6"', (root / names[1]).read_text()) + android = (root / names[2]).read_text() + self.assertIn('versionName = "0.1.6"', android) + self.assertIn('versionCode = 1006', android) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 18cb808..d4e8ee0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,6 +28,8 @@ jobs: - uses: Swatinem/rust-cache@v2 with: workspaces: linux + - name: Release version tests + run: python3 -m unittest discover -s ../.github/scripts -p 'test_*.py' - run: cargo fmt --check - run: node tools/test-desktop-drop.js - run: cargo clippy --all-targets --locked -- -D warnings @@ -36,9 +38,6 @@ jobs: # The drop zone's pure logic and its offscreen renders (snapshots are uploaded). - run: "cargo test --locked --features edge edge::" - run: cargo build --release --locked --features webview,edge - env: - # Lets the in-app updater tell which main build this is. - AIRBRIDGE_BUILD: ${{ github.run_number }} - run: packaging/appimage.sh target/release/airbridge - uses: actions/upload-artifact@v6 with: @@ -89,61 +88,3 @@ jobs: path: | android/app/build/reports android/app/build/linux-interop.log - - release: - name: Publish main release build - needs: [linux, android] - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: write - steps: - # Reuse the release binaries from this run, after all tests have passed. - - uses: actions/download-artifact@v8 - with: - name: airbridge-linux-x86_64 - path: release - - uses: actions/download-artifact@v8 - with: - name: airbridge-android-apk - path: release - - name: Package and sign release assets - env: - UPDATE_SIGNING_KEY: ${{ secrets.UPDATE_SIGNING_KEY }} - TAG: main-${{ github.run_number }} - run: | - test -s release/airbridge-x86_64.AppImage - test -s release/app-release.apk - [ -n "$UPDATE_SIGNING_KEY" ] || { echo "UPDATE_SIGNING_KEY secret is missing; refusing to publish an unsigned build"; exit 1; } - # Artifact downloads do not preserve the Linux executable bit. - install -m755 release/airbridge-x86_64.AppImage airbridge-x86_64.AppImage - cp release/app-release.apk airbridge-android.apk - # The in-app updater checks this: the AppImage, a newline, then its tag. - umask 077 - printf '%s\n' "$UPDATE_SIGNING_KEY" > "$RUNNER_TEMP/key.pem" - { cat airbridge-x86_64.AppImage; printf '\n%s' "$TAG"; } > "$RUNNER_TEMP/message" - openssl pkeyutl -sign -rawin -inkey "$RUNNER_TEMP/key.pem" -in "$RUNNER_TEMP/message" -out airbridge-x86_64.AppImage.sig - rm -f "$RUNNER_TEMP/key.pem" "$RUNNER_TEMP/message" - test "$(stat -c %s airbridge-x86_64.AppImage.sig)" -eq 64 - - uses: softprops/action-gh-release@v3 - with: - tag_name: main-${{ github.run_number }} - name: "Main build #${{ github.run_number }}" - target_commitish: ${{ github.sha }} - prerelease: true - make_latest: false - fail_on_unmatched_files: true - body: | - Automatic prerelease from a successful main-branch CI run. - Commit: `${{ github.sha }}` - - **Downloads** - - `airbridge-android.apk`: Android 10 or newer. - - `airbridge-x86_64.AppImage`: make it executable and run it. It updates itself from the app's Update button. - - The APK uses a debug signing key; Android may require uninstalling the previous build before installation. - files: | - airbridge-x86_64.AppImage - airbridge-x86_64.AppImage.sig - airbridge-android.apk diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c07b1c3..1d7a101 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,47 +1,58 @@ name: Release on: + workflow_run: + workflows: ["CI"] + types: [completed] + branches: [main] push: tags: ["v*"] # Or run it from the Actions tab: it builds the chosen commit and creates the tag. workflow_dispatch: inputs: version: - description: "Version to release, like v0.1.0" - required: true + description: "Stable version, e.g. v0.1.5 (leave empty for the next patch)" + required: false permissions: contents: read -env: - VERSION: ${{ inputs.version || github.ref_name }} - -# Runs for one version wait for each other, so the tag check below cannot race. +# Serialize selection through publication: two main builds cannot choose the same patch. concurrency: - group: release-${{ inputs.version || github.ref_name }} + group: airbridge-release + queue: max cancel-in-progress: false jobs: prepare: name: Validate release + # workflow_run also fires for failed runs and pull requests. Only a successful + # push to this repository's main branch may trigger an automatic release. + if: >- + github.event_name != 'workflow_run' || + (github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_repository.full_name == github.repository) runs-on: ubuntu-24.04 timeout-minutes: 5 + outputs: + version: ${{ steps.version.outputs.version }} + tag: ${{ steps.version.outputs.tag }} + sha: ${{ steps.version.outputs.sha }} steps: - - name: Check the version - if: github.event_name == 'workflow_dispatch' - run: | - [[ "$VERSION" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] && git check-ref-format "refs/tags/$VERSION" || - { echo "Version must look like v1.2.3 or v1.2.3-rc.1, got $VERSION"; exit 1; } - uses: actions/checkout@v5 - - name: Check the tag is free or already here + with: + ref: ${{ github.event.workflow_run.head_sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - name: Choose the release version + id: version + env: + REQUESTED_VERSION: ${{ inputs.version || (github.event_name == 'push' && github.ref_name) || '' }} run: | - # A tag that exists stays where it is, so never attach these builds to another commit's tag. - tagged=$(git ls-remote origin "refs/tags/$VERSION^{}" | cut -f1) - tagged=${tagged:-$(git ls-remote origin "refs/tags/$VERSION" | cut -f1)} - if [ -n "$tagged" ] && [ "$tagged" != "$GITHUB_SHA" ]; then - echo "$VERSION is already tagged at $tagged, not at $GITHUB_SHA. Pick a new version." - exit 1 - fi + args=() + if [ "$GITHUB_EVENT_NAME" = workflow_run ]; then args+=(--automatic); fi + python3 .github/scripts/release_version.py select "$REQUESTED_VERSION" "${args[@]}" >> "$GITHUB_OUTPUT" linux: name: Linux release @@ -50,6 +61,13 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@v5 + with: + ref: ${{ needs.prepare.outputs.sha }} + persist-credentials: false + - name: Stamp app versions + env: + VERSION: ${{ needs.prepare.outputs.version }} + run: python3 .github/scripts/release_version.py stamp "$VERSION" - name: System libraries (native window feature) timeout-minutes: 5 run: bash .github/scripts/install-system-deps.sh libwebkit2gtk-4.1-dev libgtk-3-dev libxdo-dev libgtk-layer-shell-dev @@ -76,6 +94,13 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@v5 + with: + ref: ${{ needs.prepare.outputs.sha }} + persist-credentials: false + - name: Stamp app versions + env: + VERSION: ${{ needs.prepare.outputs.version }} + run: python3 .github/scripts/release_version.py stamp "$VERSION" - uses: actions/setup-java@v5 with: distribution: temurin @@ -94,7 +119,7 @@ jobs: publish: name: Publish release - needs: [linux, android] + needs: [prepare, linux, android] runs-on: ubuntu-24.04 timeout-minutes: 10 permissions: @@ -104,23 +129,38 @@ jobs: with: pattern: release-* merge-multiple: true - - name: Check release assets + - name: Check and sign release assets + env: + UPDATE_SIGNING_KEY: ${{ secrets.UPDATE_SIGNING_KEY }} + TAG: ${{ needs.prepare.outputs.tag }} run: | test -s airbridge-x86_64.AppImage chmod +x airbridge-x86_64.AppImage test -s airbridge-android.apk + [ -n "$UPDATE_SIGNING_KEY" ] || { echo "UPDATE_SIGNING_KEY secret is missing; refusing to publish an unsigned build"; exit 1; } + umask 077 + printf '%s\n' "$UPDATE_SIGNING_KEY" > "$RUNNER_TEMP/key.pem" + trap 'rm -f "$RUNNER_TEMP/key.pem" "$RUNNER_TEMP/message"' EXIT + # The signature binds the AppImage to its version tag. + { cat airbridge-x86_64.AppImage; printf '\n%s' "$TAG"; } > "$RUNNER_TEMP/message" + openssl pkeyutl -sign -rawin -inkey "$RUNNER_TEMP/key.pem" -in "$RUNNER_TEMP/message" -out airbridge-x86_64.AppImage.sig + test "$(stat -c %s airbridge-x86_64.AppImage.sig)" -eq 64 - uses: softprops/action-gh-release@v3 with: - tag_name: ${{ env.VERSION }} - target_commitish: ${{ github.sha }} - prerelease: ${{ contains(env.VERSION, '-') }} + tag_name: ${{ needs.prepare.outputs.tag }} + name: ${{ needs.prepare.outputs.tag }} + target_commitish: ${{ needs.prepare.outputs.sha }} + prerelease: false + make_latest: legacy + fail_on_unmatched_files: true body: | **Downloads** - `airbridge-android.apk`: the Android app (Android 10 or newer). Allow installs from your browser or file manager when asked. - - `airbridge-x86_64.AppImage`: the Linux app. Make it executable and run it (needs GTK 3 and WebKitGTK 4.1, present on most desktops). + - `airbridge-x86_64.AppImage`: the Linux app. Make it executable and run it (needs GTK 3 and WebKitGTK 4.1, present on most desktops). Updates itself from the app's Update button. - The APK is signed with a debug key made for this build, not a private release key, so a newer release may need the old app uninstalled first. See [SECURITY.md](https://github.com/${{ github.repository }}/blob/${{ env.VERSION }}/docs/SECURITY.md). + The APK is signed with a debug key made for this build, not a private release key, so a newer release may need the old app uninstalled first. See [SECURITY.md](https://github.com/${{ github.repository }}/blob/${{ needs.prepare.outputs.tag }}/docs/SECURITY.md). files: | airbridge-x86_64.AppImage + airbridge-x86_64.AppImage.sig airbridge-android.apk generate_release_notes: true diff --git a/.gitignore b/.gitignore index 4d2c4ef..fc5d702 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ android/captures/ android/.kotlin/ # Editors / OS +__pycache__/ .DS_Store *.swp .vscode/ diff --git a/README.md b/README.md index e0d9f0f..2f41eab 100644 --- a/README.md +++ b/README.md @@ -135,9 +135,10 @@ chmod +x airbridge-x86_64.AppImage && ./airbridge-x86_64.AppImage ``` It uses the system's GTK 3, WebKitGTK 4.1 and gtk-layer-shell, which most desktops already have. -When a newer build of `main` passes CI, an **Update** button appears in the toolbar. It +When a newer version is released after `main` passes CI, an **Update** button appears in the toolbar. It downloads the new AppImage, checks its Ed25519 signature against the key built into the app, -swaps the file and restarts. Unsigned or older builds are refused. +swaps the file and restarts. Unsigned or older versions are refused. +If you installed an older `main-N` AppImage, download v0.1.5 once to switch to versioned updates. #### From source @@ -319,7 +320,25 @@ on Android with LocalSend on Windows or a Mac. ## Development +### Releases + +Every successful push CI run on `main` triggers the **Release** workflow. It chooses +`v0.1.5` first, then `v0.1.6`, `v0.1.7`, and so on from the highest stable tag. +Release runs queue so they cannot choose the same version. Retries reuse the tag +already attached to that commit. Both app versions are stamped in the build checkout; +the workflow does not create version-bump commits. + +The release contains the Android APK, the Linux AppImage and its Ed25519 signature. +The repository's `UPDATE_SIGNING_KEY` secret must be configured. To choose a version +manually, run **Release** from the Actions tab with e.g. `v0.2.0`, or push that tag. +Leaving the manual version empty chooses the next patch automatically. + +### Checks + ```bash +# Release version selection and package stamping +python3 -m unittest discover -s .github/scripts -p 'test_*.py' + # Linux cd linux node tools/test-desktop-drop.js # desktop drop recipient and broadcast regression check diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 7132163..60807a4 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -15,8 +15,8 @@ android { applicationId = "io.github.mdhaarith.airbridge" minSdk = 29 targetSdk = 35 - versionCode = 3 - versionName = "0.1.2" + versionCode = 1005 + versionName = "0.1.5" } buildTypes { diff --git a/android/app/src/test/java/io/github/mdhaarith/airbridge/overlay/DropLayoutTest.kt b/android/app/src/test/java/io/github/mdhaarith/airbridge/overlay/DropLayoutTest.kt index 09f4d02..8a81048 100644 --- a/android/app/src/test/java/io/github/mdhaarith/airbridge/overlay/DropLayoutTest.kt +++ b/android/app/src/test/java/io/github/mdhaarith/airbridge/overlay/DropLayoutTest.kt @@ -6,13 +6,15 @@ import android.view.DragEvent import android.view.View import android.widget.FrameLayout import app.cash.paparazzi.Paparazzi +import app.cash.paparazzi.HtmlReportWriter import org.junit.Assert.assertEquals import org.junit.Rule import org.junit.Test class DropLayoutTest { @get:Rule - val paparazzi = Paparazzi() + // Render to drive View dispatch, without comparing an image baseline. + val paparazzi = Paparazzi(snapshotHandler = HtmlReportWriter()) @Test fun deviceCardReceivesDropEvenWhenAChildHandlesDragEvents() { diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 8c69d5d..7dcc6bd 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -61,11 +61,11 @@ requests cannot crash the app. ## Updates -The Linux AppImage updates itself only from `main-N` prereleases on GitHub, over +The Linux AppImage updates itself only from stable `vMAJOR.MINOR.PATCH` releases on GitHub, over HTTPS (system CA store, HTTPS-only redirects). CI signs each AppImage with an Ed25519 key kept in the `UPDATE_SIGNING_KEY` secret. The signature covers the file and its tag, and the public key is built into the app. A download with a -bad signature, an older or equal build number, or one that is not an ELF file +bad signature, an older or equal version, or one that is not an ELF file is rejected before anything is written. The swap is atomic (temp file, fsync, rename). Only the token-protected local UI can start an update. diff --git a/linux/Cargo.lock b/linux/Cargo.lock index d291124..1dc8724 100644 --- a/linux/Cargo.lock +++ b/linux/Cargo.lock @@ -30,7 +30,7 @@ dependencies = [ [[package]] name = "airbridge" -version = "0.1.0" +version = "0.1.5" dependencies = [ "aes", "anyhow", diff --git a/linux/Cargo.toml b/linux/Cargo.toml index 55dd2c8..9a7c7b9 100644 --- a/linux/Cargo.toml +++ b/linux/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "airbridge" -version = "0.1.0" +version = "0.1.5" edition = "2021" rust-version = "1.89" description = "AirDrop-style file and text sharing between Linux and Android (LocalSend protocol compatible)" diff --git a/linux/src/ui.rs b/linux/src/ui.rs index 131f587..5476973 100644 --- a/linux/src/ui.rs +++ b/linux/src/ui.rs @@ -671,7 +671,7 @@ async fn quit(State(app): State>) -> StatusCode { async fn check_update() -> Response { match update::check().await { Ok(available) => Json(json!({ - "current": update::current_build(), + "current": update::current_version(), "available": available, "canInstall": update::appimage().is_some(), })) diff --git a/linux/src/update.rs b/linux/src/update.rs index 66852aa..9141207 100644 --- a/linux/src/update.rs +++ b/linux/src/update.rs @@ -1,5 +1,5 @@ -//! In-app updates from the automatic `main-N` prereleases (every merge to main -//! that passed CI). Only the AppImage replaces itself; the download must carry +//! In-app updates from versioned releases (every merge to main that passed CI). +//! Only the AppImage replaces itself; the download must carry //! an Ed25519 signature from the release key, bound to its tag so an older //! build cannot be replayed as a newer one. @@ -25,11 +25,8 @@ const PUBLIC_KEY: [u8; 32] = [ /// Set once a new AppImage is in place; `main` relaunches it after shutdown. pub static RESTART: AtomicBool = AtomicBool::new(false); -/// CI run number of this build (0 for local builds). -pub fn current_build() -> u64 { - option_env!("AIRBRIDGE_BUILD") - .and_then(|b| b.parse().ok()) - .unwrap_or(0) +pub fn current_version() -> &'static str { + env!("CARGO_PKG_VERSION") } /// The AppImage file we are running from, if any. @@ -41,7 +38,6 @@ pub fn appimage() -> Option { #[derive(Serialize, Clone)] pub struct Available { - pub build: u64, pub tag: String, pub page: String, #[serde(skip)] @@ -56,6 +52,8 @@ struct Release { html_url: String, #[serde(default)] draft: bool, + #[serde(default)] + prerelease: bool, assets: Vec, } @@ -65,39 +63,58 @@ struct Asset { browser_download_url: String, } -fn main_build(tag: &str) -> Option { - tag.strip_prefix("main-")?.parse().ok() +fn version(tag: &str) -> Option<[u64; 3]> { + let mut parts = tag.strip_prefix('v')?.split('.'); + let number = |part: &str| { + if part.is_empty() + || (part.len() > 1 && part.starts_with('0')) + || !part.bytes().all(|b| b.is_ascii_digit()) + { + return None; + } + part.parse().ok() + }; + let parsed = [ + number(parts.next()?)?, + number(parts.next()?)?, + number(parts.next()?)?, + ]; + parts.next().is_none().then_some(parsed) } -/// The newest main build that is newer than this one and ships a signed AppImage. +/// The newest stable version that is newer than this one and ships a signed AppImage. pub async fn check() -> Result> { let url = format!("https://api.github.com/repos/{REPO}/releases?per_page=20"); let releases: Vec = serde_json::from_slice(&download(&url, 4 * 1024 * 1024).await?) .context("unexpected answer from GitHub")?; - Ok(newest(releases, current_build())) + Ok(newest(releases, current_version())) } -fn newest(releases: Vec, current: u64) -> Option { +fn newest(releases: Vec, current: &str) -> Option { + let current = version(&format!("v{current}"))?; releases .into_iter() - .filter(|r| !r.draft) + .filter(|r| !r.draft && !r.prerelease) .filter_map(|r| { - let build = main_build(&r.tag_name).filter(|&b| b > current)?; + let release_version = version(&r.tag_name).filter(|&v| v > current)?; let url = |name: &str| { r.assets .iter() .find(|a| a.name == name) .map(|a| a.browser_download_url.clone()) }; - Some(Available { - build, - app_url: url(ASSET)?, - sig_url: url(&format!("{ASSET}.sig"))?, - tag: r.tag_name, - page: r.html_url, - }) + Some(( + release_version, + Available { + app_url: url(ASSET)?, + sig_url: url(&format!("{ASSET}.sig"))?, + tag: r.tag_name, + page: r.html_url, + }, + )) }) - .max_by_key(|a| a.build) + .max_by_key(|(v, _)| *v) + .map(|(_, available)| available) } /// What the signature covers: the file, then a newline and its tag. @@ -165,11 +182,12 @@ mod tests { } #[test] - fn picks_the_newest_signed_main_build() { + fn picks_the_newest_signed_stable_version() { let release = |tag: &str, names: &[&str]| Release { tag_name: tag.into(), html_url: format!("https://example/{tag}"), draft: false, + prerelease: false, assets: names .iter() .map(|n| Asset { @@ -181,13 +199,31 @@ mod tests { let signed = [ASSET, "airbridge-x86_64.AppImage.sig"]; let releases = || { vec![ - release("main-50", &[ASSET]), // unsigned: skipped + release("v9.0.0", &[ASSET]), // unsigned: skipped release("main-42", &signed), - release("v0.2.0", &signed), - release("main-40", &signed), + release("v0.1.5", &signed), + release("v0.1.9", &signed), + release("v0.1.10", &signed), + release("v0.2.0-rc.1", &signed), + release("v0.01.99", &signed), + Release { + draft: true, + ..release("v1.0.0", &signed) + }, + Release { + prerelease: true, + ..release("v2.0.0", &signed) + }, ] }; - assert_eq!(newest(releases(), 41).unwrap().tag, "main-42"); - assert!(newest(releases(), 42).is_none()); + assert_eq!(newest(releases(), "0.1.5").unwrap().tag, "v0.1.10"); + assert!(newest(releases(), "0.1.10").is_none()); + assert!(newest(releases(), "0.2.0").is_none()); + assert_eq!( + newest(vec![release("v0.2.0", &signed)], "0.1.99") + .unwrap() + .tag, + "v0.2.0" + ); } } diff --git a/linux/ui/app.js b/linux/ui/app.js index 287fb03..4219634 100644 --- a/linux/ui/app.js +++ b/linux/ui/app.js @@ -70,7 +70,7 @@ async function checkUpdate() { const { available, canInstall } = await api("/update"); const btn = $("btnUpdate"); btn.hidden = !available; - if (available) btn.title = `Build #${available.build} is ready` + (canInstall ? "" : " (opens the download page)"); + if (available) btn.title = `${available.tag} is ready` + (canInstall ? "" : " (opens the download page)"); } catch (_) { /* offline: try again later */ } }