Compare commits

..
4 Commits
Author SHA1 Message Date
gmp 45c1c34982 Android: bind the IOpenPgpService2 service; declare <queries> in manifest.
The v1 action (org.openintents.openpgp.IOpenPgpService) resolves in
Keychain 6.0.4 but its binder does not implement the IOpenPgpService2
AIDL descriptor that OpenPgpApi calls through, so every call died with
SecurityException: Binder invocation to an incorrect interface. Bind
the IOpenPgpService2 service first (v1 and the very old
api.OpenPgpService actions remain as fallbacks).

Android 11+ package visibility also hid Keychain's services entirely:
resolveService/bindService found nothing from the app even with
MANAGE_EXTERNAL_STORAGE granted, so the build now injects a <queries>
element (package + intent) into the decoded manifest.
2026-08-26 20:47:13 -04:00
gmp b4c2e19988 Android: fix OpenPGP service bind for modern Keychain.
Keychain 6.0.4 no longer exports the legacy
org.openintents.openpgp.api.OpenPgpService action, so the OpenPgpServiceConnection
from openpgp-api.jar bound nothing and every encrypt/decrypt died with a
NullPointerException in OpenPgpApi.executeApi.

Bind our own ServiceConnection against org.openintents.openpgp.IOpenPgpService
(falling back to the legacy action for older Keychain releases), and queue
API calls until the service is actually connected instead of racing the
async bind.

Also fix the //go:generate recipe: it built one jar containing both
PgpConnect and Permissions, which collides with Permissions.jar when gogio
dexes every *.jar in the repo root.
2026-08-26 18:11:10 -04:00
gmp 349445219b Android: reliable build script; GUI: fix list not drawn until first tap.
scripts/build.sh (documented in README) builds, manifest-patches
( MANAGE_EXTERNAL_STORAGE ), signs and installs the APK in one go.
Without the permission the system 'All files access' toggle is grayed
out on Android 11+.

GUI fix: the event loop only checks the 'updated' channel when it is
not blocked in w.Event(), and gioui only emits frames on invalidation
or user input, so the initial list load was never drawn until a tap.
The updater now signals non-blocking and invalidates the window itself;
the animation ticker gets the same wake-up treatment.
2026-08-24 09:23:41 -04:00
gmp 4c337ff06d Guard the JNI fragment registration against the null detach view.
Gio's GioView.onDestroyView signals detach with ViewEvent{View: 0};
handleEvent already filters these, but add defense in depth so any
caller forwarding the event unfiltered cannot drive the JNI path
(GetObjectClass on a null ref aborts the process, the recents-wipe
SIGABRT). Completes the intent of PR #1, whose handleEvent guard is
already in master from the migration commit.

Fixes: recents-wipe crash defense (PR #1 superseded).
2026-08-21 15:29:24 -04:00
7 changed files with 297 additions and 18 deletions
BIN
View File
Binary file not shown.
+89 -7
View File
@@ -5,14 +5,17 @@ import java.lang.String;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import android.os.Handler; import android.os.Handler;
import android.os.IBinder;
import java.io.InputStream; import java.io.InputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError; import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.OpenPgpSignatureResult; import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.util.OpenPgpApi; import org.openintents.openpgp.util.OpenPgpApi;
import org.openintents.openpgp.util.OpenPgpServiceConnection; import android.content.ComponentName;
import android.content.ServiceConnection;
import android.content.Context; import android.content.Context;
import android.content.ClipboardManager; import android.content.ClipboardManager;
import android.content.ClipData; import android.content.ClipData;
@@ -36,9 +39,71 @@ public class PgpConnect extends Fragment {
Context ctx; Context ctx;
Handler handler; Handler handler;
ClipboardManager cb; ClipboardManager cb;
OpenPgpServiceConnection mServiceConnection; IOpenPgpService2 mService;
final int PERMISSIONS_REQUEST = 1; final int PERMISSIONS_REQUEST = 1;
// The OpenPgpApi in openpgp-api.jar calls through the IOpenPgpService2
// AIDL interface, so we must bind the service that implements that
// descriptor: org.openintents.openpgp.IOpenPgpService2 (Keychain >= 11 /
// standalone 5.x-6.x). The v1 action (IOpenPgpService) does not implement
// the v2 descriptor and dies with a SecurityException; the very old
// org.openintents.openpgp.api.OpenPgpService action (used by
// OpenPgpServiceConnection) no longer exists. Try in that order.
static final String[] SERVICE_ACTIONS = {
"org.openintents.openpgp.IOpenPgpService2",
"org.openintents.openpgp.IOpenPgpService",
"org.openintents.openpgp.api.OpenPgpService",
};
final ServiceConnection mConnection = new ServiceConnection() {
@Override public void onServiceConnected(ComponentName name, IBinder service) {
mService = IOpenPgpService2.Stub.asInterface(service);
Log.d("gio", "OpenPGP service connected: " + name);
}
@Override public void onServiceDisconnected(ComponentName name) {
mService = null;
Log.d("gio", "OpenPGP service disconnected");
}
};
private void bindOpenPgp() {
Intent bindIntent = null;
for (String action : SERVICE_ACTIONS) {
Intent i = new Intent(action);
i.setPackage("org.sufficientlysecure.keychain");
if (ctx.getPackageManager().resolveService(i, 0) != null) {
bindIntent = i;
break;
}
}
if (bindIntent == null) {
Log.e("gio", "No OpenPGP service found in org.sufficientlysecure.keychain");
return;
}
Log.d("gio", "Binding OpenPGP service: " + bindIntent.getAction());
ctx.bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
}
// executeApi needs a live service; the bind is asynchronous, so if the
// service is not connected yet, retry on the main looper (up to ~10 s)
// instead of calling into a null service.
private void runWhenConnected(final int chint, final Runnable task, final int attempt) {
if (mService != null) {
task.run();
return;
}
if (attempt > 33) {
Log.e("gio", "OpenPGP service never connected");
stringResult(chint, null);
return;
}
handler.postDelayed(new Runnable() {
public void run() {
runWhenConnected(chint, task, attempt + 1);
}
}, 300);
}
public PgpConnect(View view) { public PgpConnect(View view) {
Log.d("gio", "PgpConnect()"); Log.d("gio", "PgpConnect()");
this.ctx = view.getContext(); this.ctx = view.getContext();
@@ -60,8 +125,7 @@ public class PgpConnect extends Fragment {
if (ctx instanceof Activity) { if (ctx instanceof Activity) {
Log.d("gio", "It's an Activity!"); Log.d("gio", "It's an Activity!");
} }
mServiceConnection = new OpenPgpServiceConnection(ctx, "org.sufficientlysecure.keychain"); bindOpenPgp();
mServiceConnection.bindToService();
cb = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE); cb = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
if (ctx.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ctx.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ctx.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ctx.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST); requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST);
@@ -156,9 +220,15 @@ public class PgpConnect extends Fragment {
private void _getid(Intent data, int chint) { private void _getid(Intent data, int chint) {
Log.d("gio","_getid"); Log.d("gio","_getid");
runWhenConnected(chint, new Runnable() {
public void run() { doGetid(data, chint); }
}, 0);
}
private void doGetid(Intent data, int chint) {
InputStream is = null; InputStream is = null;
ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mServiceConnection.getService()); OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os); Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) { switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: { case OpenPgpApi.RESULT_CODE_SUCCESS: {
@@ -193,10 +263,16 @@ public class PgpConnect extends Fragment {
} }
private void _decrypt(Intent data, int chint) { private void _decrypt(Intent data, int chint) {
Log.d("gio","_decrypt"); Log.d("gio","_decrypt");
runWhenConnected(chint, new Runnable() {
public void run() { doDecrypt(data, chint); }
}, 0);
}
private void doDecrypt(Intent data, int chint) {
byte []dat = data.getByteArrayExtra("DATA"); byte []dat = data.getByteArrayExtra("DATA");
InputStream is = new ByteArrayInputStream(dat); InputStream is = new ByteArrayInputStream(dat);
ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mServiceConnection.getService()); OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os); Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) { switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: { case OpenPgpApi.RESULT_CODE_SUCCESS: {
@@ -246,10 +322,16 @@ public class PgpConnect extends Fragment {
private void _encrypt(Intent data, int chint) { private void _encrypt(Intent data, int chint) {
Log.d("gio","_encrypt"); Log.d("gio","_encrypt");
runWhenConnected(chint, new Runnable() {
public void run() { doEncrypt(data, chint); }
}, 0);
}
private void doEncrypt(Intent data, int chint) {
byte []dat = data.getByteArrayExtra("DATA"); byte []dat = data.getByteArrayExtra("DATA");
InputStream is = new ByteArrayInputStream(dat); InputStream is = new ByteArrayInputStream(dat);
ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(this.ctx, mServiceConnection.getService()); OpenPgpApi api = new OpenPgpApi(this.ctx, mService);
Intent result = api.executeApi(data, is, os); Intent result = api.executeApi(data, is, os);
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) { switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: { case OpenPgpApi.RESULT_CODE_SUCCESS: {
+28
View File
@@ -32,3 +32,31 @@ p, err := store.Decrypt("myPass")
Also included is a simple GUI front-end using [Gio](https://gioui.org) Also included is a simple GUI front-end using [Gio](https://gioui.org)
that works on MacOS and Android. See `cmd/passgo-gui`. that works on MacOS and Android. See `cmd/passgo-gui`.
## Building the Android APK
Use `scripts/build.sh` — do not build by hand:
```sh
./scripts/build.sh phone # build + install on the phone
./scripts/build.sh phone --no-install
./scripts/build.sh emu # emulator build (amd64)
```
It outputs `cmd/passgo-gui/passgo-gui.apk` (APKs are git-ignored and
regenerated by the script). The script, in order:
1. `gogio -target android -targetsdk 34` (from `~/go/bin`; packages the
Go code plus the `*.jar` JNI classes found in `cmd/passgo-gui/`),
2. apktool decode → inject `MANAGE_EXTERNAL_STORAGE` into the manifest
(gogio's hardcoded permission table lacks it, and without it the
system "All files access" toggle is grayed out on Android 11+) →
apktool rebuild,
3. sign with the debug keystore (`~/.android/debug.keystore`),
4. `adb install -r`.
Prereqs: JDK, Go + gogio, Android SDK at `~/android-sdk`
(platform-tools + build-tools 35.0.0). apktool v3.0.3 is auto-downloaded
to `~/android-sdk/tools/apktool.jar` if missing. The script checks each
prereq and says what is missing. The phone is reached via adb over the
WireGuard address (see the global AGENTS.md).
+49 -7
View File
@@ -10,6 +10,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"sync/atomic"
"time" "time"
"gioui.org/app" "gioui.org/app"
@@ -99,7 +100,7 @@ func main() {
} }
reload = make(chan struct{}) reload = make(chan struct{})
updated = make(chan struct{}) updated = make(chan struct{}, 1)
chdir = make(chan struct{}) chdir = make(chan struct{})
passch = make(chan []byte) passch = make(chan []byte)
@@ -127,6 +128,7 @@ var (
chdir chan struct{} chdir chan struct{}
passch chan []byte passch chan []byte
th *material.Theme th *material.Theme
win atomic.Pointer[app.Window]
) )
func Updater() { func Updater() {
@@ -140,7 +142,20 @@ func Updater() {
mux.Lock() mux.Lock()
l = ltmp l = ltmp
mux.Unlock() mux.Unlock()
updated <- struct{}{} // Non-blocking: if a refresh is already pending it will pick up
// the latest list, so dropping the duplicate is fine.
select {
case updated <- struct{}{}:
default:
}
// Wake the window: the event loop blocks in w.Event(), which only
// returns when the window is invalidated or the user interacts
// with it. Without this, a list refresh signalled while the loop
// is blocked (e.g. the initial load on startup) would not be
// drawn until the next tap.
if w := win.Load(); w != nil {
w.Invalidate()
}
} }
update() update()
@@ -212,6 +227,7 @@ func eventLoop() {
w.Option( w.Option(
app.Size(unit.Dp(250), unit.Dp(500)), app.Size(unit.Dp(250), unit.Dp(500)),
app.Title("passgo")) app.Title("passgo"))
win.Store(w)
var margincs layout.Constraints var margincs layout.Constraints
@@ -401,18 +417,49 @@ func eventLoop() {
noidLabel := material.Label(th, unit.Sp(fontSize), noidLabelText) noidLabel := material.Label(th, unit.Sp(fontSize), noidLabelText)
idLabel := material.Label(th, unit.Sp(fontSize), "Select ID") idLabel := material.Label(th, unit.Sp(fontSize), "Select ID")
// timing variables used for the "copied to clipboard" animation
// (seconds relative to overlayStart)
fade1a, fade1b := 1.5, 2.0
start2 := float64(Config.ClearDelay)
fade2a, end := start2+1.5, start2+2.0
anim := &time.Ticker{} anim := &time.Ticker{}
var animDone chan struct{}
animating := false animating := false
animOn := func() { animOn := func() {
log(Info, "animOn()") log(Info, "animOn()")
anim = time.NewTicker(time.Second / 90) anim = time.NewTicker(time.Second / 90)
animating = true animating = true
w.Invalidate() w.Invalidate()
// The event loop blocks in w.Event() between frames, so ticks it
// misses never trigger a redraw and the fade would freeze. Wake
// the window on each tick, but only while a fade is actually
// visible.
t := anim
animDone = make(chan struct{})
d := animDone
go func() {
for {
select {
case <-t.C:
x := time.Since(overlayStart).Seconds()
if (x >= fade1a && x < fade1b) || (x > fade2a && x < end) {
w.Invalidate()
}
case <-d:
return
}
}
}()
} }
animOff := func() { animOff := func() {
log(Info, "animOff()") log(Info, "animOff()")
anim.Stop() anim.Stop()
animating = false animating = false
if animDone != nil { // stops the wake-up goroutine started by animOn
close(animDone)
animDone = nil
}
} }
var listPage, idPage, insertPage, confirmPage, confPage, promptPage, page func(C) D var listPage, idPage, insertPage, confirmPage, confPage, promptPage, page func(C) D
@@ -427,11 +474,6 @@ func eventLoop() {
lpf1 := &layout.Flex{Axis: layout.Horizontal} lpf1 := &layout.Flex{Axis: layout.Horizontal}
listPage = func(gtx C) D { listPage = func(gtx C) D {
// timing variables used for animation
fade1a, fade1b := 1.5, 2.0
start2 := float64(Config.ClearDelay)
fade2a, end := start2+1.5, start2+2.0
c2 := layout.Rigid(func(gtx C) D { c2 := layout.Rigid(func(gtx C) D {
c21 := layout.Flexed(1, func(gtx C) D { c21 := layout.Flexed(1, func(gtx C) D {
return material.Editor(th, FilterEd, "filter").Layout(gtx) return material.Editor(th, FilterEd, "filter").Layout(gtx)
+10 -4
View File
@@ -1,10 +1,10 @@
//go:build android //go:build android
// +build android // +build android
//go:generate mkdir -p classes // Regenerate PgpConnect.jar and Permissions.jar (gogio dexes every *.jar in
//go:generate javac -nowarn -classpath $ANDROID_HOME/platforms/android-35/android.jar:openpgp-api.jar -d classes PgpConnect.java Permissions.java // the repo root; the two classes must stay in separate jars). ANDROID_HOME
//go:generate jar cf PgpConnect.jar -C classes . // must be set. Note: go generate skips this file on non-android hosts.
//go:generate rm -rf classes //go:generate sh -c 'mkdir -p classes && javac -nowarn -classpath "$ANDROID_HOME/platforms/android-35/android.jar:openpgp-api.jar" -d classes PgpConnect.java Permissions.java && (cd classes && jar cf ../../PgpConnect.jar st/wow/git/passgo/PgpConnect* && jar cf ../../Permissions.jar st/wow/git/passgo/Permissions*) && rm -rf classes'
package passgo package passgo
@@ -51,6 +51,9 @@ func Java_st_wow_git_passgo_PgpConnect_installComplete(env *C.JNIEnv, class C.jc
func InitPgp(view uintptr) { func InitPgp(view uintptr) {
log.Printf("InitPgp()") log.Printf("InitPgp()")
if view == 0 {
return // detach signal; nothing to register
}
jvm = app.JavaVM() jvm = app.JavaVM()
SetJVM(jvm) // why? SetJVM(jvm) // why?
RunInJVM(func(env *JNIEnv) { RunInJVM(func(env *JNIEnv) {
@@ -63,6 +66,9 @@ func InitPgp(view uintptr) {
// screen on Android 11+) so the app can read the store in shared storage. // screen on Android 11+) so the app can read the store in shared storage.
func InitPermissions(view uintptr) { func InitPermissions(view uintptr) {
log.Printf("InitPermissions()") log.Printf("InitPermissions()")
if view == 0 {
return // detach signal; nothing to register
}
RunInJVM(func(env *JNIEnv) { RunInJVM(func(env *JNIEnv) {
C.registerPermissionsFragment(env, (C.jobject)(unsafe.Pointer(view))) C.registerPermissionsFragment(env, (C.jobject)(unsafe.Pointer(view)))
}) })
+9
View File
@@ -7,6 +7,12 @@
void void
registerFragment(JNIEnv *env, jobject view) { registerFragment(JNIEnv *env, jobject view) {
if (view == NULL) {
// Detach signal (Gio sends ViewEvent{View: 0} when the view is
// destroyed, e.g. on a recents-wipe); the Go side already
// filters these, but GetObjectClass(null) aborts the process.
return;
}
jclass cls = (*env)->GetObjectClass(env, view); jclass cls = (*env)->GetObjectClass(env, view);
jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;"); jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;");
jobject ctx = (*env)->CallObjectMethod(env, view, mid); jobject ctx = (*env)->CallObjectMethod(env, view, mid);
@@ -23,6 +29,9 @@ registerFragment(JNIEnv *env, jobject view) {
void void
registerPermissionsFragment(JNIEnv *env, jobject view) { registerPermissionsFragment(JNIEnv *env, jobject view) {
if (view == NULL) {
return; // detach signal; see registerFragment
}
jclass cls = (*env)->GetObjectClass(env, view); jclass cls = (*env)->GetObjectClass(env, view);
jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;"); jmethodID mid = (*env)->GetMethodID(env, cls, "getContext", "()Landroid/content/Context;");
jobject ctx = (*env)->CallObjectMethod(env, view, mid); jobject ctx = (*env)->CallObjectMethod(env, view, mid);
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env bash
# Build (and optionally install) the passgo-gui Android APK.
#
# Usage:
# ./scripts/build.sh [phone|emu] # build + install (default: phone)
# ./scripts/build.sh phone --no-install # build only
#
# Output: cmd/passgo-gui/passgo-gui.apk
#
# Prereqs on this workstation:
# - JDK (java on PATH)
# - Go + gogio (~/go/bin)
# - Android SDK at ~/android-sdk (platform-tools, build-tools 35.0.0)
# - debug keystore at ~/.android/debug.keystore
# apktool is not a prerequisite: if it is missing, the script downloads
# v3.0.3 to the stable location ~/android-sdk/tools/apktool.jar.
#
# Why the apktool detour: gogio's manifest permissions come from a hardcoded
# table (only the legacy READ/WRITE_EXTERNAL_STORAGE). On Android 11+ the
# "All files access" settings toggle is grayed out unless the app declares
# MANAGE_EXTERNAL_STORAGE, which Permissions.java opens at startup. So we
# decode the gogio APK, inject the permission, rebuild, and re-sign with
# the debug key.
set -euo pipefail
REPO=$(cd "$(dirname "$0")/.." && pwd)
export ANDROID_HOME=${ANDROID_HOME:-$HOME/android-sdk}
export PATH=$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/build-tools/35.0.0:$HOME/go/bin
MODE=${1:-phone}
INSTALL=1
[ "${2:-}" = "--no-install" ] && INSTALL=0
case "$MODE" in
phone) ARCH="arm64,arm";;
emu) ARCH="amd64";;
*) echo "usage: $0 [phone|emu] [--no-install]" >&2; exit 1;;
esac
die() { echo "ERROR: $*" >&2; exit 1; }
command -v java >/dev/null 2>&1 || die "java not found"
command -v gogio >/dev/null 2>&1 || die "gogio not found (need ~/go/bin)"
command -v apksigner >/dev/null 2>&1 || die "apksigner not found (need $ANDROID_HOME/build-tools/35.0.0)"
command -v adb >/dev/null 2>&1 || die "adb not found (need $ANDROID_HOME/platform-tools)"
[ -f "$HOME/.android/debug.keystore" ] || die "debug keystore missing: $HOME/.android/debug.keystore"
# apktool: auto-download to a stable location if missing.
APKTOOL="$ANDROID_HOME/tools/apktool.jar"
if [ ! -f "$APKTOOL" ]; then
echo "=== apktool missing; downloading v3.0.3 to $APKTOOL ==="
mkdir -p "$ANDROID_HOME/tools"
curl -fsSL -o "$APKTOOL" \
https://github.com/iBotPeaches/Apktool/releases/download/v3.0.3/apktool_3.0.3.jar \
|| die "apktool download failed"
fi
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
echo "=== gogio (Go -> APK) ==="
# targetSdk 34: targeting 35 makes Android 15 force edge-to-edge, which the
# app does not handle.
(cd "$REPO/cmd/passgo-gui" && gogio -target android -targetsdk 34 -arch "$ARCH" -o "$WORK/passgo-raw.apk" .)
[ -f "$WORK/passgo-raw.apk" ] || die "gogio did not produce an APK"
echo "=== apktool decode + inject MANAGE_EXTERNAL_STORAGE ==="
java -jar "$APKTOOL" d "$WORK/passgo-raw.apk" -o "$WORK/decoded" -f >/dev/null
python3 - "$WORK/decoded/AndroidManifest.xml" << 'PYEOF'
import sys, pathlib
p = pathlib.Path(sys.argv[1])
t = p.read_text()
perm = '<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>'
if perm not in t:
t = t.replace(" <application", " " + perm + "\n <application", 1)
if perm not in t:
sys.exit("ERROR: failed to inject MANAGE_EXTERNAL_STORAGE")
# Android 11+ package visibility: without <queries> the app cannot even
# resolve (let alone bind) Keychain's OpenPGP service.
queries = """ <queries>
<package android:name="org.sufficientlysecure.keychain"/>
<intent>
<action android:name="org.openintents.openpgp.IOpenPgpService2"/>
</intent>
</queries>
"""
if "<queries>" not in t:
t = t.replace(" <application", queries + " <application", 1)
if "<queries>" not in t:
sys.exit("ERROR: failed to inject <queries>")
p.write_text(t)
print("manifest: MANAGE_EXTERNAL_STORAGE + <queries> present")
PYEOF
echo "=== apktool rebuild ==="
java -jar "$APKTOOL" b "$WORK/decoded" -o "$WORK/passgo-unsigned.apk" >/dev/null
echo "=== sign ==="
apksigner sign \
--ks "$HOME/.android/debug.keystore" --ks-pass pass:android \
--key-pass pass:android --ks-key-alias androiddebugkey \
--out "$REPO/cmd/passgo-gui/passgo-gui.apk" "$WORK/passgo-unsigned.apk"
# ADB_SERIAL selects the device when several are attached (adb devices).
ADB="adb${ADB_SERIAL:+ -s $ADB_SERIAL}"
if [ "$INSTALL" = "1" ]; then
echo "=== install ==="
$ADB get-state >/dev/null 2>&1 || die "no adb device (connect the phone; set ADB_SERIAL if several are attached)"
$ADB install -r "$REPO/cmd/passgo-gui/passgo-gui.apk"
fi
echo "=== DONE: $REPO/cmd/passgo-gui/passgo-gui.apk ==="