mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 22:57:32 +00:00
ci(native): publish the Play-signed Android APK to liketrek/trek-android for installs outside Google Play
People who install apps from GitHub (Obtainium and the like) asked for the Android app outside Google Play. After the Play upload, the release job now fetches the universal APK Google Play builds of that same bundle, signed with the Play app signing key, and publishes it with a checksum to liketrek/trek-android: one release per app version, a newer build of the same version replacing its APK. A phone can move between the Play install and this APK without uninstalling, and Play Billing and push work in it wherever Google Play services do. It runs only inside the app builds that already happen, so a server release without app changes publishes nothing. A build is held back while the app needs a newer native API than the latest server release answers, so no APK asks for a server that is not out yet. The APKs live in their own repository so app releases never show up in the server's release list or update check.
This commit is contained in:
@@ -105,9 +105,62 @@ jobs:
|
||||
track: ${{ inputs.track || 'internal' }}
|
||||
status: draft
|
||||
|
||||
# The same build for installs outside Google Play: the universal APK Google
|
||||
# Play makes of this bundle, signed with the Play app signing key, published
|
||||
# to liketrek/trek-android for Obtainium (wiki/Native-Apps.md). Held back
|
||||
# while the app needs a server version that is not released yet.
|
||||
- name: Whether the latest server release serves this build
|
||||
id: released
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
|
||||
git fetch --depth=1 origin "refs/tags/$tag:refs/tags/$tag"
|
||||
git show "$tag:server/src/nest/health/features.controller.ts" > "$RUNNER_TEMP/released-features.ts"
|
||||
node scripts/ci/android-apk-release.mjs guard "$RUNNER_TEMP/released-features.ts" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Universal APK from Google Play
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
env:
|
||||
PLAY_APK_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_APK_SERVICE_ACCOUNT_JSON }}
|
||||
APK: trek-${{ steps.version.outputs.version }}.apk
|
||||
run: |
|
||||
printf '%s' "$PLAY_APK_SERVICE_ACCOUNT_JSON" > "$RUNNER_TEMP/play-apk.json"
|
||||
node scripts/ci/android-apk-release.mjs download "$RUNNER_TEMP/play-apk.json" com.liketrek.trek \
|
||||
"${{ steps.version.outputs.build }}" "$RUNNER_TEMP/$APK"
|
||||
rm -f "$RUNNER_TEMP/play-apk.json"
|
||||
cd "$RUNNER_TEMP" && sha256sum "$APK" > "$APK.sha256"
|
||||
|
||||
- uses: actions/create-github-app-token@v3
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
id: apk-token
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: liketrek
|
||||
repositories: trek-android
|
||||
|
||||
# One release per app version: a newer build of the same version replaces
|
||||
# its APK, so the release always holds what Google Play holds for it.
|
||||
- name: Publish to liketrek/trek-android
|
||||
if: steps.released.outputs.publish == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.apk-token.outputs.token }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
BUILD: ${{ steps.version.outputs.build }}
|
||||
run: |
|
||||
apk="$RUNNER_TEMP/trek-$VERSION.apk"
|
||||
notes="TREK $VERSION for Android (build $BUILD): the build Google Play distributes, with the same signature. Connect it to your own TREK server; push and TREK Cloud need Google Play services. Changes: https://github.com/liketrek/TREK/releases"
|
||||
if gh release view "v$VERSION" -R liketrek/trek-android > /dev/null 2>&1; then
|
||||
gh release upload "v$VERSION" -R liketrek/trek-android --clobber "$apk" "$apk.sha256"
|
||||
gh release edit "v$VERSION" -R liketrek/trek-android --notes "$notes"
|
||||
else
|
||||
gh release create "v$VERSION" -R liketrek/trek-android --title "TREK $VERSION" --notes "$notes" "$apk" "$apk.sha256"
|
||||
fi
|
||||
|
||||
- name: Remove the upload key
|
||||
if: always()
|
||||
run: rm -f "$RUNNER_TEMP/upload.jks"
|
||||
run: rm -f "$RUNNER_TEMP/upload.jks" "$RUNNER_TEMP/play-apk.json"
|
||||
|
||||
ios:
|
||||
if: github.repository == 'liketrek/TREK'
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env node
|
||||
// The Android app as an APK outside Google Play, for Obtainium and the like.
|
||||
//
|
||||
// native-release.yml uploads each Android build to Google Play, which signs it
|
||||
// with the app signing key only Google holds. Google Play also builds a
|
||||
// universal APK of that bundle, signed with the same key. This script fetches
|
||||
// that APK, so the copy published in liketrek/trek-android carries the very
|
||||
// signature of the Play install: a phone can move between the two without
|
||||
// uninstalling, and Play Billing and push work in it wherever Google Play
|
||||
// services do.
|
||||
//
|
||||
// guard <features.controller.ts of the latest server release>
|
||||
// Whether this build may go out now. The app refuses a server older than
|
||||
// its MIN_NATIVE_API (client/src/native/serverAddress.ts), and a build can
|
||||
// be cut from dev before the server it needs is released. It may go out
|
||||
// once the latest server release answers a nativeApi at least that high
|
||||
// (its server/src/nest/health/features.controller.ts, which the workflow
|
||||
// writes out with git show). Prints publish=true or publish=false, for
|
||||
// $GITHUB_OUTPUT.
|
||||
//
|
||||
// download <service account json> <package> <version code> <out.apk>
|
||||
// Asks the Play Developer API for the universal APK of that version code,
|
||||
// waiting a while for Google to generate it, and writes it to <out.apk>.
|
||||
//
|
||||
// No secret is printed: the service account file is read, not echoed.
|
||||
import { createSign } from 'node:crypto';
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const APP_MIN_FILE = 'client/src/native/serverAddress.ts';
|
||||
const SERVER_API_FILE = 'server/src/nest/health/features.controller.ts';
|
||||
const API = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications';
|
||||
const REQUEST_TIMEOUT_MS = 30_000;
|
||||
const APK_TIMEOUT_MS = 5 * 60_000;
|
||||
const WAIT_STEPS_MS = [15_000, 30_000, 60_000, 120_000, 240_000];
|
||||
const MAX_APK_BYTES = 400 * 1024 * 1024;
|
||||
|
||||
/** The app's MIN_NATIVE_API in the source of serverAddress.ts; throws when it cannot be read. */
|
||||
export function appMinimumApi(source) {
|
||||
const found = /\bconst MIN_NATIVE_API = (\d+);/.exec(source);
|
||||
if (!found) throw new Error(`MIN_NATIVE_API not found in ${APP_MIN_FILE}`);
|
||||
return Number(found[1]);
|
||||
}
|
||||
|
||||
/** The nativeApi the server answers in the source of features.controller.ts; throws when it cannot be read. */
|
||||
export function serverApi(source) {
|
||||
const found = /\bnativeApi: (\d+),/.exec(source);
|
||||
if (!found) throw new Error(`nativeApi not found in ${SERVER_API_FILE}`);
|
||||
return Number(found[1]);
|
||||
}
|
||||
|
||||
/** Whether a build that needs `appMinimum` may go out while the newest server release answers `released`. */
|
||||
export function mayPublish(appMinimum, released) {
|
||||
return released >= appMinimum;
|
||||
}
|
||||
|
||||
function guard(releasedFeatures) {
|
||||
const appMinimum = appMinimumApi(readFileSync(APP_MIN_FILE, 'utf8'));
|
||||
const released = serverApi(readFileSync(releasedFeatures, 'utf8'));
|
||||
const publish = mayPublish(appMinimum, released);
|
||||
console.error(`the app needs native API ${appMinimum}, the latest release answers ${released}: ${publish ? 'publish' : 'hold back'}`);
|
||||
console.log(`publish=${publish}`);
|
||||
}
|
||||
|
||||
const b64url = (value) => Buffer.from(typeof value === 'string' ? value : JSON.stringify(value)).toString('base64url');
|
||||
|
||||
async function accessToken(account) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const unsigned = `${b64url({ alg: 'RS256', typ: 'JWT' })}.${b64url({
|
||||
iss: account.client_email,
|
||||
scope: 'https://www.googleapis.com/auth/androidpublisher',
|
||||
aud: account.token_uri,
|
||||
iat: now,
|
||||
exp: now + 600,
|
||||
})}`;
|
||||
const signature = createSign('RSA-SHA256').update(unsigned).sign(account.private_key).toString('base64url');
|
||||
const response = await fetch(account.token_uri, {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
||||
assertion: `${unsigned}.${signature}`,
|
||||
}),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok || typeof body.access_token !== 'string') {
|
||||
throw new Error(`Google refused the service account: HTTP ${response.status} ${body.error ?? ''}`);
|
||||
}
|
||||
return body.access_token;
|
||||
}
|
||||
|
||||
/** The download id of the universal APK in a generatedApks.list answer, or null while Google has none yet. */
|
||||
export function universalDownloadId(answer) {
|
||||
for (const generated of answer?.generatedApks ?? []) {
|
||||
const id = generated?.generatedUniversalApk?.downloadId;
|
||||
if (typeof id === 'string' && id.length > 0) return id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
async function download(accountFile, pkg, versionCode, out) {
|
||||
if (!/^[\w.]+$/.test(pkg) || !/^\d+$/.test(versionCode)) throw new Error('package or version code malformed');
|
||||
const token = await accessToken(JSON.parse(readFileSync(accountFile, 'utf8')));
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const base = `${API}/${pkg}/generatedApks/${versionCode}`;
|
||||
let id = null;
|
||||
for (let attempt = 0; id === null; attempt++) {
|
||||
const response = await fetch(base, { headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
||||
const body = await response.json();
|
||||
// 404 while Google has not processed the bundle yet; anything else is final.
|
||||
if (!response.ok && response.status !== 404) {
|
||||
throw new Error(`generatedApks.list: HTTP ${response.status} ${body.error?.message ?? ''}`);
|
||||
}
|
||||
id = response.ok ? universalDownloadId(body) : null;
|
||||
if (id === null) {
|
||||
if (attempt >= WAIT_STEPS_MS.length) throw new Error(`no universal APK for version code ${versionCode} yet`);
|
||||
console.error(`waiting for Google to build the universal APK of ${versionCode}`);
|
||||
await sleep(WAIT_STEPS_MS[attempt]);
|
||||
}
|
||||
}
|
||||
const response = await fetch(`${base}/downloads/${encodeURIComponent(id)}:download?alt=media`, {
|
||||
headers,
|
||||
signal: AbortSignal.timeout(APK_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) throw new Error(`generatedApks.download: HTTP ${response.status}`);
|
||||
const apk = Buffer.from(await response.arrayBuffer());
|
||||
// An APK is a zip archive; anything else is an error page.
|
||||
if (apk.length > MAX_APK_BYTES || apk.subarray(0, 2).toString('latin1') !== 'PK') {
|
||||
throw new Error(`the download is not an APK (${apk.length} bytes)`);
|
||||
}
|
||||
writeFileSync(out, apk);
|
||||
console.error(`wrote ${out} (${apk.length} bytes)`);
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
const [command, ...args] = process.argv.slice(2);
|
||||
try {
|
||||
if (command === 'guard' && args.length === 1) guard(args[0]);
|
||||
else if (command === 'download' && args.length === 4) await download(...args);
|
||||
else throw new Error('usage: android-apk-release.mjs guard <features.controller.ts> | download <account.json> <package> <code> <out.apk>');
|
||||
} catch (err) {
|
||||
console.error(`::error::${err instanceof Error ? err.message : String(err)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { appMinimumApi, mayPublish, serverApi, universalDownloadId } from './android-apk-release.mjs';
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, it } from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const read = (path) => readFileSync(fileURLToPath(new URL(`../../${path}`, import.meta.url)), 'utf8');
|
||||
|
||||
describe('android-apk-release', () => {
|
||||
it('reads the native API the app needs and the one the server answers from the real files', () => {
|
||||
const appMinimum = appMinimumApi(read('client/src/native/serverAddress.ts'));
|
||||
const answered = serverApi(read('server/src/nest/health/features.controller.ts'));
|
||||
assert.ok(Number.isInteger(appMinimum) && appMinimum >= 1);
|
||||
// A commit never needs more than the server it ships with.
|
||||
assert.ok(answered >= appMinimum);
|
||||
});
|
||||
|
||||
it('refuses to guess when a constant moved', () => {
|
||||
assert.throws(() => appMinimumApi('export const MIN_API = 3;'), /MIN_NATIVE_API not found/);
|
||||
assert.throws(() => serverApi('nativeApi = 3'), /nativeApi not found/);
|
||||
});
|
||||
|
||||
it('holds back a build that needs a server not released yet', () => {
|
||||
assert.equal(mayPublish(3, 3), true);
|
||||
assert.equal(mayPublish(3, 4), true);
|
||||
assert.equal(mayPublish(4, 3), false);
|
||||
});
|
||||
|
||||
it('finds the universal APK in a generatedApks answer, and nothing in one without it', () => {
|
||||
assert.equal(
|
||||
universalDownloadId({ generatedApks: [{ generatedSplitApks: [{}] }, { generatedUniversalApk: { downloadId: 'abc' } }] }),
|
||||
'abc',
|
||||
);
|
||||
assert.equal(universalDownloadId({ generatedApks: [{ generatedSplitApks: [{}] }] }), null);
|
||||
assert.equal(universalDownloadId({}), null);
|
||||
assert.equal(universalDownloadId(null), null);
|
||||
});
|
||||
});
|
||||
+5
-1
@@ -2,7 +2,9 @@
|
||||
|
||||
**TREK Travel Planner** is the TREK app for iPhone, iPad and Android, from the App Store and Google Play. It is a client for your TREK server: it asks for the server's address once and then shows the TREK interface that server delivers, in the version the server runs, with the same data, the same accounts and the same settings as in the browser. On the home screen it is called **TREK**.
|
||||
|
||||
The browser keeps working as before, and installing TREK from the browser as a web app is still possible; see [Offline-Mode-and-PWA](Offline-Mode-and-PWA). The app adds what a browser cannot do well on a phone: signing in with single sign-on and passkeys, the system share sheet for exports, haptics, and on iOS a start without network.
|
||||
The browser keeps working as before, and installing TREK from the browser as a web app is still possible; see [Offline-Mode-and-PWA](Offline-Mode-and-PWA).
|
||||
|
||||
Without Google Play, the Android app is also published as an APK at [liketrek/trek-android](https://github.com/liketrek/trek-android), for example for [Obtainium](https://github.com/ImranR98/Obtainium). It is the build Google Play distributes, with the same signature, so a phone can move between the two without uninstalling. Push notifications and TREK Cloud subscriptions need Google Play services; without them the app works without those two. The app adds what a browser cannot do well on a phone: signing in with single sign-on and passkeys, the system share sheet for exports, haptics, and on iOS a start without network.
|
||||
|
||||
## Connecting to a server
|
||||
|
||||
@@ -121,6 +123,7 @@ The apps are built from `client/`: Capacitor wraps the address screen in `client
|
||||
- **Every pull request** that touches the native code runs `.github/workflows/native.yml`: an unsigned Android debug and release build (the release build runs R8 with `client/android/app/proguard-rules.pro`), an iOS simulator build with Xcode 26, and a check of the store texts and images.
|
||||
- **A release** runs `.github/workflows/native-release.yml`, by hand (choose the Play track) or on a `v*` tag. A tag pushed by another workflow with the default token does not start it, so after a release run it by hand on the tag. It builds the signed Android App Bundle and sends it to the chosen Google Play testing track as a draft, and archives the iOS app and uploads it to App Store Connect, where it appears in TestFlight. Promoting a build to production happens in the two consoles.
|
||||
- **Version numbers**: both stores get the version from `client/package.json` without a prerelease suffix, and the workflow run number plus 1000 as the build number. A prerelease reuses its version with a higher build number and stays on the internal track and in TestFlight.
|
||||
- **The APK outside Google Play**: after the upload, the same job fetches the universal APK Google Play builds of that bundle (signed with the Play app signing key) and publishes it to [liketrek/trek-android](https://github.com/liketrek/trek-android), one release per app version, a newer build of the same version replacing its APK. `scripts/ci/android-apk-release.mjs` holds a build back while the app needs a newer native API than the latest server release answers.
|
||||
- **The `store` environment** holds every secret and needs the approval of a required reviewer before a job starts. It only runs in liketrek/TREK, never for a pull request.
|
||||
|
||||
### Secrets in the `store` environment
|
||||
@@ -130,6 +133,7 @@ The apps are built from `client/`: Capacitor wraps the address screen in `client
|
||||
| ANDROID_UPLOAD_KEYSTORE_B64 | The upload keystore, base64 encoded |
|
||||
| ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD | Its password, key alias and key password |
|
||||
| PLAY_SERVICE_ACCOUNT_JSON | The Google Cloud service account with "Release to testing tracks" in Play Console |
|
||||
| PLAY_APK_SERVICE_ACCOUNT_JSON | The Google Cloud service account allowed to download the APKs Google Play generates, for liketrek/trek-android |
|
||||
| APPLE_TEAM_ID | The Apple Developer team of [APPLE ORGANISATION ACCOUNT] |
|
||||
| ASC_KEY_ID, ASC_ISSUER_ID, ASC_KEY_P8_B64 | The App Store Connect team API key (App Manager role), the .p8 file base64 encoded |
|
||||
|
||||
|
||||
Reference in New Issue
Block a user