diff --git a/.github/ci-policy.md b/.github/ci-policy.md index 805aa2b4e4..4a363e9832 100644 --- a/.github/ci-policy.md +++ b/.github/ci-policy.md @@ -16,7 +16,9 @@ differ: "main push" venues are nightly venues, and post-merge evidence for a commit is the next nightly run whose head contains it. Deploys are not CI and keep their push trigger: `container-images` (image -publish) and `mcpx docs` (GitHub Pages). Jobs that only ran on `push` +publish), `mcpx docs` (GitHub Pages), and `pm-console android` (the app's +release, on pushes that touch the app; owner's instruction of 2026-11-22 +that the app is built and released by Actions without a person). Jobs that only ran on `push` were widened to `schedule` where the nightly run must do the same work: the id arm64 world-snapshot job, the mcpx `basic: test` job, the mcpx and mcpx-conformance `ON_MAIN` recording, and the Go module tidy commit. To @@ -98,7 +100,7 @@ never a state that persists by default. | Workflow | Automatic venue | Manual | | ------------------------- | --------------------- | ------ | | workflow-lint | none | yes | -| pm-console-android | none | yes | +| pm-console-android | main push, path gated | yes | | proxy-port-fallbacks | none | yes | | fleet-search-parity-guard | none | yes | | fleet-rust-tests | nightly schedule | yes | diff --git a/.github/workflows/pm-console-android.yml b/.github/workflows/pm-console-android.yml index aeb2f582e5..8c5c7ae2d2 100644 --- a/.github/workflows/pm-console-android.yml +++ b/.github/workflows/pm-console-android.yml @@ -1,60 +1,86 @@ name: pm-console android -# Builds the PM console's Android app (pm-stack/console/android): a -# Trusted Web Activity over https://pm.security.cab. Manual only: it is -# run when the app changes, which is rarely, since the app is the site. +# CI tier policy: see .github/ci-policy.md. This is a release, not CI, +# so it keeps a push trigger (restricted to main, and to the app's own +# files). # -# With the signing secrets set, the APK is signed here and attached to -# the release. Without them the build is unsigned and kept as an -# artifact, to be signed by pm-stack/console/android/sign.sh on the -# machine that holds the key. +# Builds, signs and releases the PM console's Android app +# (pm-stack/console/android): a Trusted Web Activity over +# https://pm.security.cab, plus what only an installed app has. It runs +# on every push to main that touches the app, and by hand. +# +# The version is the commit's (build.sh): a code that rises with the +# commit's time, so each build installs over the one before. +# +# Signing needs the app's key, as two secrets of the pm-console-android +# environment: PM_CONSOLE_ANDROID_KEYSTORE_B64 and +# PM_CONSOLE_ANDROID_KEYSTORE_PASSWORD. An environment, not the +# repository, so that it can be limited to runs on main. Putting the key +# there is the owner's to do, by hand; no script or agent holds or moves +# it (pm-stack/console/android/README.md). +# +# With the key: the APK is signed here, checked against the certificate +# the site lists (signing-fingerprint.txt), and released twice with +# nobody involved: as pm-console-android-v, which is never +# changed again, and as pm-console-android, whose address stays the same +# and always holds the newest build. The site hands out the second. +# +# Without the key: the build is unsigned and kept as an artifact, and +# the run says so. Nothing is released. on: + push: + branches: [main] + paths: + - "pm-stack/console/android/**" + - ".github/workflows/pm-console-android.yml" workflow_dispatch: - inputs: - publish: - description: "Attach the APK to the release pm-console-android (signed builds only)" - type: boolean - default: true permissions: contents: read +# Releases run one at a time, in order. +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: false + jobs: build: - name: "build: APK" + name: "build, sign and release the APK" runs-on: ubuntu-latest timeout-minutes: 25 + environment: pm-console-android permissions: contents: write steps: - uses: actions/checkout@v7 - - name: Build, and sign when the signing secrets are set + - name: Build, and sign when this environment holds the key id: build env: KEYSTORE_B64: ${{ secrets.PM_CONSOLE_ANDROID_KEYSTORE_B64 }} PM_ANDROID_KEYSTORE_PASSWORD: ${{ secrets.PM_CONSOLE_ANDROID_KEYSTORE_PASSWORD }} run: | bash pm-stack/console/android/build.sh - if [ -f pm-stack/console/android/app/build/outputs/apk/release/pm-console.apk ]; then + out=pm-stack/console/android/app/build/outputs/apk/release + { + echo "version_name=$(sed -n 1p "$out/version")" + echo "version_code=$(sed -n 2p "$out/version")" + } >>"$GITHUB_OUTPUT" + if [ -f "$out/pm-console.apk" ]; then echo "signed=true" >>"$GITHUB_OUTPUT" else echo "signed=false" >>"$GITHUB_OUTPUT" - echo "::notice::Built unsigned: the signing secrets are not set. Sign the artifact with pm-stack/console/android/sign.sh on the machine that holds the key." + echo "::notice::Built unsigned: this environment does not hold the signing key, so nothing is released. See pm-stack/console/android/README.md, Giving GitHub the key." + echo "Built $(sed -n 1p "$out/version") unsigned: the signing key is not here, so nothing was released." >>"$GITHUB_STEP_SUMMARY" fi - uses: actions/upload-artifact@v7 with: name: ${{ steps.build.outputs.signed == 'true' && 'pm-console-apk' || 'pm-console-apk-unsigned' }} path: pm-stack/console/android/app/build/outputs/apk/release/*.apk if-no-files-found: error - - name: Attach to the release - if: inputs.publish && steps.build.outputs.signed == 'true' + - name: Release + if: steps.build.outputs.signed == 'true' && github.ref == 'refs/heads/main' env: GH_TOKEN: ${{ github.token }} - run: | - apk=pm-stack/console/android/app/build/outputs/apk/release/pm-console.apk - if ! gh release view pm-console-android >/dev/null 2>&1; then - gh release create pm-console-android --latest=false \ - --title "PM console for Android" \ - --notes "The PM stack's console as an Android app. It opens https://pm.security.cab/console/ and signs in the way the site does. Install pm-console.apk; later builds install over it." - fi - gh release upload pm-console-android "$apk" --clobber + VERSION_NAME: ${{ steps.build.outputs.version_name }} + VERSION_CODE: ${{ steps.build.outputs.version_code }} + run: bash pm-stack/console/android/release.sh pm-stack/console/android/app/build/outputs/apk/release/pm-console.apk diff --git a/.github/workflows/pm-stack-tests.yml b/.github/workflows/pm-stack-tests.yml index f196a384a9..4c799e4751 100644 --- a/.github/workflows/pm-stack-tests.yml +++ b/.github/workflows/pm-stack-tests.yml @@ -98,6 +98,14 @@ jobs: - name: Test pm-git-sync rebuild markers run: bash pm-stack/scripts/pm-git-sync-markers.test.sh + # The Android app's release (pm-stack/console/android/release.sh), + # against a stand-in for gh: the numbered release is made once and + # never changed, the fixed address always ends up on the newest + # build and never goes back, and a run started again changes + # nothing. + - name: Test the Android app's release script + run: bash pm-stack/console/android/release.test.sh + # Script suite for #5993: pm-stack/scripts/ # tailnet-bindings.test.sh (the #781 regression pin for the # Pad/Grist tailnet bindings) was run by no workflow. The diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index e1542489a2..8413b174ec 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -212,7 +212,9 @@ never falls behind the site. Around that it uses what only an installed app has: a home-screen widget, dictation from a shortcut or a quick-settings tile, text shared or selected in any app, long-press shortcuts, and notifications shown as its own. The `pm-console-android` -workflow builds it and the host signs it. Once the signed file is on the -host, More, Phones offers it to the signed-in owner at -`/console/pm-console.apk`, so the phone gets the app from the site it -opens. See its README. +workflow builds it on every change to it. Once the owner has given +GitHub the signing key, the workflow signs and releases each build by +itself, and More, Phones offers the newest release to the signed-in +owner at `/console/pm-console.apk`, so the phone gets the app from the +site it opens. Until then the host signs, and its build is what is +offered. See its README. diff --git a/pm-stack/console/android/README.md b/pm-stack/console/android/README.md index 76a9b4e705..5d4ed9b58c 100644 --- a/pm-stack/console/android/README.md +++ b/pm-stack/console/android/README.md @@ -45,52 +45,80 @@ under More, Phones, and the widget then goes back to "Tap to link". If the two disagree the app still works, with a browser bar at the top. -## Build +## Build and release + +GitHub Actions builds the app on every push to `main` that touches it +(`.github/workflows/pm-console-android.yml`), and by hand: ```bash -gh workflow run pm-console-android.yml # builds the APK in CI -bash pm-stack/console/android/build.sh # locally: needs JAVA_HOME (17 or 21) and ANDROID_HOME -bash pm-stack/console/android/sign.sh app-release-unsigned.apk # sign a CI build with the key on this machine +gh workflow run pm-console-android.yml +bash pm-stack/console/android/build.sh # here: needs JAVA_HOME (17 or 21) and ANDROID_HOME ``` -The signing key is on the pm-stack host at -`~/.local/state/pm-console/android/release.p12`, and it stays there. The -workflow builds an unsigned APK and keeps it as the artifact -`pm-console-apk-unsigned`; `sign.sh` on the host signs it, checks the -certificate against `signing-fingerprint.txt`, and the signed -`pm-console.apk` is uploaded to the release: +A build names its own version from its commit (`build.sh`): a code that +rises with the commit's time, so each build installs over the one +before, and a name that says the day and the commit. + +What happens next depends on who holds the signing key. + +**GitHub holds it.** The build is signed in the workflow, checked +against the certificate in `signing-fingerprint.txt`, and released by +`release.sh` with nobody involved, twice: + +- `pm-console-android-v`: that build. Once made it is never + changed. +- `pm-console-android`: one address that always holds the newest build + and is never taken back to an older one. The site hands this one out. + +Each carries `pm-console.apk`, `pm-console.apk.sha256` and a +`version.json` (name, code, commit, sha256, size, when, certificate). + +**Only the laptop holds it** (how it starts). The workflow's build is +unsigned, kept as the artifact `pm-console-apk-unsigned`, and the run +says nothing was released. It can be signed and put in place by hand: ```bash gh run download -n pm-console-apk-unsigned -D /tmp/pm-apk nix shell nixpkgs#apksigner -c bash pm-stack/console/android/sign.sh /tmp/pm-apk/app-release-unsigned.apk -gh release upload pm-console-android /tmp/pm-apk/pm-console.apk --clobber +install -m 644 /tmp/pm-apk/pm-console.apk ~/.local/state/pm-console/android/pm-console.apk ``` -If the repository secrets `PM_CONSOLE_ANDROID_KEYSTORE_B64` and -`PM_CONSOLE_ANDROID_KEYSTORE_PASSWORD` are ever set, the workflow signs -and publishes by itself instead, and fails unless the certificate -matches. Losing the key means a new key, a new fingerprint and a +### Giving GitHub the key + +The key is on the pm-stack host at +`~/.local/state/pm-console/android/release.p12`, with its password in +`keystore-password` beside it. The workflow signs once the +`pm-console-android` environment of the repository holds two secrets: + +- `PM_CONSOLE_ANDROID_KEYSTORE_B64`: the keystore, base64; +- `PM_CONSOLE_ANDROID_KEYSTORE_PASSWORD`: its password. + +Putting them there is the owner's to do, by hand, with `gh secret set +--env pm-console-android` or in the repository's settings. No script, +workflow or agent here holds or moves the key, on purpose. The +environment is made by the workflow's first run; limiting it to the +`main` branch (Settings, Environments) keeps a workflow on any other +branch from reading the key. + +A build signed by any other key fails in `build.sh` before anything is +released. Losing the key means a new key, a new fingerprint and a reinstall; nothing else depends on it. ## Install On the phone, open `https://pm.security.cab/console/`, sign in, and go to -More, Phones, "Download the app". That downloads the signed build from -the host (`/console/pm-console.apk`, owner only); open it to install. -Later builds install over it. +More, Phones, "Download the app" (`/console/pm-console.apk`, owner +only). What that is, in order: + +1. the build GitHub released, fetched from the release and checked + against its `version.json`; this needs nothing of the laptop; +2. otherwise the laptop's signed build + (`~/.local/state/pm-console/android/pm-console.apk`), or the copy of + it kept at Cloudflare when the laptop is away. + +The page says which it is. Later builds install over it. The native parts are checked by compiling the build and reading its merged manifest; the site's side of each (the Ask box taking handed-over words, linking a phone, the summary) is tested in `test/`. They have not been exercised by an automated run on a device. - -The console serves whatever signed build is at -`~/.local/state/pm-console/android/pm-console.apk` on the host, so -putting a new build in place is the whole release: - -```bash -install -m 644 /tmp/pm-apk/pm-console.apk ~/.local/state/pm-console/android/pm-console.apk -``` - -The same file can also be attached to the GitHub release -`pm-console-android` for a copy outside the host. diff --git a/pm-stack/console/android/app/build.gradle b/pm-stack/console/android/app/build.gradle index a483d9744f..af3178cb23 100644 --- a/pm-stack/console/android/app/build.gradle +++ b/pm-stack/console/android/app/build.gradle @@ -12,6 +12,11 @@ plugins { def site = 'https://pm.security.cab' def keystore = System.getenv('PM_ANDROID_KEYSTORE') +// A release names its own version (build.sh works both out from the +// commit, so a later build always installs over an earlier one). A +// build with neither set is a check that the project builds. +def releaseCode = System.getenv('PM_ANDROID_VERSION_CODE') +def releaseName = System.getenv('PM_ANDROID_VERSION_NAME') android { namespace 'today.developing.pmconsole' @@ -21,8 +26,8 @@ android { applicationId 'today.developing.pmconsole' minSdk 24 targetSdk 34 - versionCode 3 - versionName '0.3.0' + versionCode releaseCode ? releaseCode.toInteger() : 3 + versionName releaseName ?: '0.3.0' manifestPlaceholders = [hostName: 'pm.security.cab', defaultUrl: "${site}/console/"] // The app's half of the link to the site. The site's half is // /.well-known/assetlinks.json, served by pm-console. diff --git a/pm-stack/console/android/build.sh b/pm-stack/console/android/build.sh index f5d00fb447..7d07956d12 100755 --- a/pm-stack/console/android/build.sh +++ b/pm-stack/console/android/build.sh @@ -13,12 +13,28 @@ # asset-links file, and an APK signed by anything else would open with a # browser bar. Without them the result is an unsigned APK, for a check # that the project builds. +# +# The version is the commit's: the code rises with the commit's time, so +# a later build always installs over an earlier one, and the name says +# the day and the commit. Both are written to +# app/build/outputs/apk/release/version (name, then code). Set +# PM_ANDROID_VERSION_CODE and PM_ANDROID_VERSION_NAME to choose them. set -euo pipefail cd "$(dirname "$0")" GRADLE_VERSION="${GRADLE_VERSION:-8.9}" OUT=app/build/outputs/apk/release +if [ -z "${PM_ANDROID_VERSION_CODE:-}" ] || [ -z "${PM_ANDROID_VERSION_NAME:-}" ]; then + if stamp="$(git log -1 --format=%ct 2>/dev/null)" && [ -n "$stamp" ]; then + # Ten-second steps since 2020: far below Android's ceiling for + # centuries, and two commits are never closer than that in practice. + PM_ANDROID_VERSION_CODE="$(((stamp - 1577836800) / 10))" + PM_ANDROID_VERSION_NAME="$(date -u -d "@$stamp" +%Y.%m.%d)-$(git rev-parse --short=7 HEAD)" + export PM_ANDROID_VERSION_CODE PM_ANDROID_VERSION_NAME + fi +fi + export JAVA_HOME="${JAVA_HOME_17_X64:-${JAVA_HOME_21_X64:-${JAVA_HOME:-}}}" if [ -z "$JAVA_HOME" ] || [ -z "${ANDROID_HOME:-}" ]; then echo "build.sh: JAVA_HOME and ANDROID_HOME must be set" >&2 @@ -43,6 +59,8 @@ if [ -n "${KEYSTORE_B64:-}" ] && [ -n "${PM_ANDROID_KEYSTORE_PASSWORD:-}" ]; the fi "$GRADLE" --no-daemon --console=plain assembleRelease +printf '%s\n%s\n' "${PM_ANDROID_VERSION_NAME:-0.3.0}" "${PM_ANDROID_VERSION_CODE:-3}" >"$OUT/version" +echo "build.sh: version ${PM_ANDROID_VERSION_NAME:-0.3.0} (code ${PM_ANDROID_VERSION_CODE:-3})" if [ -z "${PM_ANDROID_KEYSTORE:-}" ]; then echo "build.sh: built unsigned: $(ls $OUT/*.apk)" diff --git a/pm-stack/console/android/release.sh b/pm-stack/console/android/release.sh new file mode 100644 index 0000000000..116ed72ebb --- /dev/null +++ b/pm-stack/console/android/release.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# release.sh — publish a signed build of the PM console APK. +# +# Usage: bash release.sh +# +# Inputs (environment): +# VERSION_NAME, VERSION_CODE the build's version (build.sh writes both) +# GITHUB_SHA, GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_SERVER_URL +# as a workflow run has them +# Needs gh, signed in with leave to write releases (GH_TOKEN), and python3. +# +# Two releases come of it: +# pm-console-android-v this build. Once made it is never changed. +# pm-console-android one address that always holds the newest +# build; the site hands out +# releases/download/pm-console-android/pm-console.apk +# Each carries pm-console.apk, pm-console.apk.sha256 and version.json +# (name, code, commit, sha256, size, when, and the signing certificate). +# Neither is marked as the repository's latest release: other things in +# this repository have releases of their own. +# +# Running it again for a build already released changes nothing in the +# numbered release; the fixed address is brought up to that release if +# it was behind, and is never taken back to an older build. +set -euo pipefail + +if [ "$#" -ne 1 ]; then + echo "usage: bash release.sh " >&2 + exit 2 +fi +here="$(cd "$(dirname "$0")" && pwd)" +apk="$1" +name="${VERSION_NAME:-}" +code="${VERSION_CODE:-}" +sha="${GITHUB_SHA:-}" +repo="${GITHUB_REPOSITORY:-}" + +[ -f "$apk" ] || { + echo "release.sh: not found: $apk" >&2 + exit 1 +} +if ! printf '%s' "$code" | grep -Eq '^[1-9][0-9]{0,9}$'; then + echo "release.sh: VERSION_CODE must be a whole number" >&2 + exit 2 +fi +if ! printf '%s' "$name" | grep -Eq '^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$'; then + echo "release.sh: VERSION_NAME is not a version name" >&2 + exit 2 +fi +if ! printf '%s' "$sha" | grep -Eq '^[0-9a-f]{40}$'; then + echo "release.sh: GITHUB_SHA must be a full commit id" >&2 + exit 2 +fi +if ! printf '%s' "$repo" | grep -Eq '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'; then + echo "release.sh: GITHUB_REPOSITORY must be owner/name" >&2 + exit 2 +fi + +numbered="pm-console-android-v$code" +fixed="pm-console-android" +run_url="${GITHUB_SERVER_URL:-https://github.com}/$repo/actions/runs/${GITHUB_RUN_ID:-0}" +certificate="$(tr -d '[:space:]' <"$here/signing-fingerprint.txt")" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +mkdir "$work/new" "$work/was" + +exists() { + gh release view "$1" --repo "$repo" >/dev/null 2>&1 +} + +# The code a release's version.json gives, or 0 if it has none. +code_of() { + rm -rf "$work/was" && mkdir "$work/was" + if ! gh release download "$1" --repo "$repo" --dir "$work/was" --pattern version.json --clobber >/dev/null 2>&1; then + echo 0 + return + fi + python3 -c 'import json, sys +try: + code = json.load(open(sys.argv[1]))["code"] + print(code if isinstance(code, int) and code > 0 else 0) +except Exception: + print(0)' "$work/was/version.json" +} + +if exists "$numbered"; then + # Released before (the run was started again). What was released then + # is the build of this version; this run's own file is set aside. + gh release download "$numbered" --repo "$repo" --dir "$work/new" \ + --pattern pm-console.apk --pattern pm-console.apk.sha256 --pattern version.json --clobber + for f in pm-console.apk pm-console.apk.sha256 version.json; do + [ -f "$work/new/$f" ] || { + echo "release.sh: release $numbered exists without $f; not touching it" >&2 + exit 1 + } + done + # Its own account of itself is what the fixed address is told. + name="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["name"])' "$work/new/version.json")" + echo "release.sh: $numbered was released before; left as it is" +else + cp "$apk" "$work/new/pm-console.apk" + digest="$(sha256sum "$work/new/pm-console.apk" | cut -d' ' -f1)" + printf '%s pm-console.apk\n' "$digest" >"$work/new/pm-console.apk.sha256" + python3 -c 'import json, os, sys, time +name, code, commit, digest, certificate, path, out = sys.argv[1:8] +json.dump( + { + "name": name, + "code": int(code), + "commit": commit, + "sha256": digest, + "size": os.path.getsize(path), + "built": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "certificate": certificate, + }, + open(out, "w"), + indent=2, +) +open(out, "a").write("\n")' "$name" "$code" "$sha" "$digest" "$certificate" "$work/new/pm-console.apk" "$work/new/version.json" + gh release create "$numbered" --repo "$repo" --target "$sha" --latest=false \ + --title "PM console for Android $name" \ + --notes "The PM console as an Android app, build $name (version code $code), from commit $sha. + +Built, signed and released by $run_url. Signed by the certificate $certificate, the one the site lists, so it installs over earlier builds. + +The newest build is always at https://github.com/$repo/releases/download/$fixed/pm-console.apk" \ + "$work/new/pm-console.apk" "$work/new/pm-console.apk.sha256" "$work/new/version.json" + echo "release.sh: released $numbered" +fi + +notes="The PM console as an Android app: always the newest build, now $name (version code $code). It opens https://pm.security.cab/console/ and signs in the way the site does. Install pm-console.apk; each build installs over the one before. + +Every build is also kept under its own release, pm-console-android-v. This one: https://github.com/$repo/releases/tag/$numbered" + +if exists "$fixed"; then + was="$(code_of "$fixed")" + if [ "$was" -gt "$code" ]; then + echo "release.sh: $fixed already holds a newer build (code $was); left as it is" + exit 0 + fi + # The build first and its description last: someone reading in between + # finds a description that does not match the file, and waits. + gh release upload "$fixed" --repo "$repo" --clobber "$work/new/pm-console.apk" "$work/new/pm-console.apk.sha256" + gh release upload "$fixed" --repo "$repo" --clobber "$work/new/version.json" + gh release edit "$fixed" --repo "$repo" --draft=false --latest=false --title "PM console for Android" --notes "$notes" + # The tag follows the build it now holds. If it cannot be moved the + # release still holds the right files, which is what is read. + gh api -X PATCH "repos/$repo/git/refs/tags/$fixed" -f sha="$sha" -F force=true >/dev/null 2>&1 || + echo "release.sh: could not move the tag $fixed to $sha; the release holds the new build all the same" +else + gh release create "$fixed" --repo "$repo" --target "$sha" --latest=false \ + --title "PM console for Android" --notes "$notes" \ + "$work/new/pm-console.apk" "$work/new/pm-console.apk.sha256" "$work/new/version.json" +fi +echo "release.sh: $fixed holds $name (code $code)" +if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then + echo "Released $name (code $code) as \`$numbered\`; \`$fixed\` holds it." >>"$GITHUB_STEP_SUMMARY" +fi diff --git a/pm-stack/console/android/release.test.sh b/pm-stack/console/android/release.test.sh new file mode 100644 index 0000000000..7946bc8eaa --- /dev/null +++ b/pm-stack/console/android/release.test.sh @@ -0,0 +1,242 @@ +#!/usr/bin/env bash +# release.test.sh — pins what release.sh does to the two releases, with +# a stand-in for gh that keeps releases in a directory and writes down +# every call: the numbered release is made once and never changed, the +# fixed address always ends up holding the newest build and never an +# older one, a run started again changes nothing, and nothing is asked +# of GitHub on bad input. +set -euo pipefail + +if [ "$#" -gt 0 ]; then + echo "usage: release.test.sh (it takes no arguments)" >&2 + exit 2 +fi + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +state="$tmp/github" +mkdir -p "$tmp/bin" "$state" + +# ---- a stand-in for gh ------------------------------------------------------ +cat >"$tmp/bin/gh" <<'GH' +#!/usr/bin/env bash +# Releases live under $GH_STATE//: draft, target, latest, title, +# notes, assets/. Tags under $GH_STATE/.tags/. Every call is logged. +set -euo pipefail +echo "$*" >>"$GH_STATE/.log" +if [ "$1" = "api" ]; then + [ -e "$GH_STATE/.tag-cannot-move" ] && exit 1 + path="" sha="" + for arg in "$@"; do + case "$arg" in + repos/*) path="$arg" ;; + sha=*) sha="${arg#sha=}" ;; + esac + done + mkdir -p "$GH_STATE/.tags" + echo "$sha" >"$GH_STATE/.tags/${path##*/}" + exit 0 +fi +[ "$1" = "release" ] || exit 64 +verb="$2" tag="$3" +shift 3 +dir="$GH_STATE/$tag" +files=() patterns=() out="" +while [ "$#" -gt 0 ]; do + case "$1" in + --repo) shift ;; + --target) target="$2" && shift ;; + --title) title="$2" && shift ;; + --notes) notes="$2" && shift ;; + --dir) out="$2" && shift ;; + --pattern) patterns+=("$2") && shift ;; + --latest=false) latest=false ;; + --draft=false) draft=false ;; + --clobber) ;; + --*) exit 64 ;; + *) files+=("$1") ;; + esac + shift +done +case "$verb" in +view) + [ -d "$dir" ] + ;; +create) + [ ! -d "$dir" ] || exit 1 + mkdir -p "$dir/assets" + echo false >"$dir/draft" + echo "${latest:-true}" >"$dir/latest" + echo "${target:-}" >"$dir/target" + echo "${title:-}" >"$dir/title" + echo "${notes:-}" >"$dir/notes" + cp "${files[@]}" "$dir/assets/" + ;; +upload) + [ -d "$dir" ] || exit 1 + cp "${files[@]}" "$dir/assets/" + ;; +download) + [ -d "$dir" ] || exit 1 + found=0 + for pattern in "${patterns[@]}"; do + if [ -f "$dir/assets/$pattern" ]; then + cp "$dir/assets/$pattern" "$out/" + found=1 + fi + done + [ "$found" -eq 1 ] + ;; +edit) + [ -d "$dir" ] || exit 1 + [ -n "${draft:-}" ] && echo "$draft" >"$dir/draft" + [ -n "${latest:-}" ] && echo "$latest" >"$dir/latest" + [ -n "${title:-}" ] && echo "$title" >"$dir/title" + [ -n "${notes:-}" ] && echo "$notes" >"$dir/notes" + true + ;; +*) exit 64 ;; +esac +GH +chmod +x "$tmp/bin/gh" + +export PATH="$tmp/bin:$PATH" GH_STATE="$state" +export GITHUB_REPOSITORY="example/code" GITHUB_RUN_ID=42 GITHUB_SERVER_URL="https://github.com" +unset GITHUB_STEP_SUMMARY + +fail() { + echo "FAIL: $*" >&2 + exit 1 +} +same() { cmp -s "$1" "$2" || fail "$3"; } +sha_a="$(printf 'a%.0s' {1..40})" +sha_b="$(printf 'b%.0s' {1..40})" +fixed="$state/pm-console-android" +field() { python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))[sys.argv[2]])' "$1" "$2"; } +release() { # release + VERSION_NAME="$2" VERSION_CODE="$3" GITHUB_SHA="$4" bash "$here/release.sh" "$1" +} +calls() { wc -l <"$state/.log"; } + +printf 'build one' >"$tmp/one.apk" +printf 'build one, built again' >"$tmp/one-again.apk" +printf 'build two!' >"$tmp/two.apk" + +# 1. The first release, with the draft that is there today: a release +# of its own for the build, and the draft published holding it. +mkdir -p "$fixed/assets" +echo true >"$fixed/draft" +echo true >"$fixed/latest" +printf 'signed on the laptop' >"$fixed/assets/pm-console.apk" +release "$tmp/one.apk" 2026.11.23-aaaaaaa 100 "$sha_a" >/dev/null +one="$state/pm-console-android-v100" +[ -d "$one" ] || fail "1: no release was made for the build itself" +same "$one/assets/pm-console.apk" "$tmp/one.apk" "1: the numbered release does not hold the build" +same "$fixed/assets/pm-console.apk" "$tmp/one.apk" "1: the fixed address does not hold the build" +[ "$(cat "$fixed/draft")" = false ] || fail "1: the fixed release is still a draft" +[ "$(cat "$fixed/latest")" = false ] || fail "1: the fixed release was marked the repository's latest" +[ "$(cat "$one/latest")" = false ] || fail "1: the numbered release was marked the repository's latest" +[ "$(cat "$one/target")" = "$sha_a" ] || fail "1: the numbered release is not at the build's commit" +[ "$(cat "$state/.tags/pm-console-android")" = "$sha_a" ] || fail "1: the fixed tag was not moved to the build's commit" +[ "$(field "$fixed/assets/version.json" code)" = 100 ] || fail "1: version.json gives the wrong code" +[ "$(field "$fixed/assets/version.json" name)" = 2026.11.23-aaaaaaa ] || fail "1: version.json gives the wrong name" +[ "$(field "$fixed/assets/version.json" commit)" = "$sha_a" ] || fail "1: version.json gives the wrong commit" +[ "$(field "$fixed/assets/version.json" size)" = 9 ] || fail "1: version.json gives the wrong size" +want="$(sha256sum "$tmp/one.apk" | cut -d' ' -f1)" +[ "$(field "$fixed/assets/version.json" sha256)" = "$want" ] || fail "1: version.json gives the wrong sha256" +[ "$(cat "$fixed/assets/pm-console.apk.sha256")" = "$want pm-console.apk" ] || fail "1: the .sha256 file is not what sha256sum -c reads" +[ "$(field "$fixed/assets/version.json" certificate)" = "$(tr -d '[:space:]' <"$here/signing-fingerprint.txt")" ] || fail "1: version.json does not name the signing certificate" +# At the fixed address the build goes up before its description. +apk_at="$(grep -n "release upload pm-console-android .*pm-console.apk" "$state/.log" | head -1 | cut -d: -f1)" +json_at="$(grep -n "release upload pm-console-android .*version.json" "$state/.log" | head -1 | cut -d: -f1)" +[ -n "$apk_at" ] && [ -n "$json_at" ] && [ "$apk_at" -lt "$json_at" ] || fail "1: version.json was put up before the build it describes" + +# 2. The same build's run started again, and the build came out a few +# bytes different: nothing is changed anywhere. +before="$(calls)" +release "$tmp/one-again.apk" 2026.11.23-aaaaaaa 100 "$sha_a" >/dev/null +same "$one/assets/pm-console.apk" "$tmp/one.apk" "2: a numbered release was changed after it was made" +same "$fixed/assets/pm-console.apk" "$tmp/one.apk" "2: the fixed address took a second build of the same version" +if sed -n "$((before + 1)),\$p" "$state/.log" | grep -q "release create\|release upload pm-console-android-v"; then + fail "2: the numbered release was written to again" +fi + +# 3. A later build: its own release, and the fixed address moves to it. +release "$tmp/two.apk" 2026.11.24-bbbbbbb 200 "$sha_b" >/dev/null +two="$state/pm-console-android-v200" +same "$two/assets/pm-console.apk" "$tmp/two.apk" "3: the second build has no release of its own" +same "$fixed/assets/pm-console.apk" "$tmp/two.apk" "3: the fixed address did not move to the newer build" +same "$one/assets/pm-console.apk" "$tmp/one.apk" "3: the first numbered release was changed" +[ "$(field "$fixed/assets/version.json" code)" = 200 ] || fail "3: the fixed address describes the older build" +[ "$(cat "$state/.tags/pm-console-android")" = "$sha_b" ] || fail "3: the fixed tag did not follow" +grep -q "now 2026.11.24-bbbbbbb" "$fixed/notes" || fail "3: the fixed release's notes do not name the build it holds" + +# 4. The older build's run started again after the newer one is out: +# the fixed address is not taken back. +release "$tmp/one.apk" 2026.11.23-aaaaaaa 100 "$sha_a" >/dev/null +same "$fixed/assets/pm-console.apk" "$tmp/two.apk" "4: the fixed address went back to an older build" +[ "$(field "$fixed/assets/version.json" code)" = 200 ] || fail "4: the fixed address describes an older build" +[ "$(cat "$state/.tags/pm-console-android")" = "$sha_b" ] || fail "4: the fixed tag went back" + +# 5. A run that died between the two releases: the numbered one is out +# and the fixed address is behind. The next run brings it up, with +# the build that was released, not its own. +printf 'build three' >"$tmp/three.apk" +printf 'build three, built again' >"$tmp/three-again.apk" +rm -rf "$fixed" +release "$tmp/three.apk" 2026.11.25-ccccccc 300 "$sha_b" >/dev/null +rm -rf "$fixed" +mkdir -p "$fixed/assets" +cp "$two/assets/"* "$fixed/assets/" +echo false >"$fixed/draft" +release "$tmp/three-again.apk" 2026.11.25-ccccccc 300 "$sha_b" >/dev/null +same "$fixed/assets/pm-console.apk" "$tmp/three.apk" "5: the fixed address was not brought up to the released build" +[ "$(field "$fixed/assets/version.json" code)" = 300 ] || fail "5: the fixed address still describes the older build" + +# 6. No fixed release at all: it is made. +rm -rf "$fixed" +printf 'build four' >"$tmp/four.apk" +release "$tmp/four.apk" 2026.11.26-ddddddd 400 "$sha_a" >/dev/null +same "$fixed/assets/pm-console.apk" "$tmp/four.apk" "6: the fixed release was not made" +[ "$(cat "$fixed/latest")" = false ] || fail "6: a new fixed release was marked the repository's latest" + +# 7. The tag cannot be moved: the release still holds the build, and the run does not fail. +touch "$state/.tag-cannot-move" +printf 'build five' >"$tmp/five.apk" +out="$(release "$tmp/five.apk" 2026.11.27-eeeeeee 500 "$sha_b")" || fail "7: a tag that cannot be moved failed the release" +same "$fixed/assets/pm-console.apk" "$tmp/five.apk" "7: the fixed address does not hold the build" +printf '%s' "$out" | grep -q "could not move the tag" || fail "7: nothing was said about the tag" +rm "$state/.tag-cannot-move" + +# 8. A numbered release that is there but incomplete is not built upon, +# and the run says which file it lacks before touching anything. +rm "$state/pm-console-android-v500/assets/pm-console.apk.sha256" +before="$(calls)" +if said="$(release "$tmp/five.apk" 2026.11.27-eeeeeee 500 "$sha_b" 2>&1)"; then + fail "8: an incomplete numbered release was accepted" +fi +printf '%s' "$said" | grep -q "exists without pm-console.apk.sha256" || fail "8: it did not say what the release lacks" +if sed -n "$((before + 1)),\$p" "$state/.log" | grep -q "release upload\|release edit\|release create"; then + fail "8: something was written on top of an incomplete release" +fi + +# 9. Bad input stops it before GitHub is asked anything. +before="$(calls)" +bad() { # bad [] + if release "${5:-$tmp/one.apk}" "$2" "$3" "$4" >/dev/null 2>&1; then fail "9: accepted $1"; fi + [ "$(calls)" = "$before" ] || fail "9: asked GitHub something on $1" +} +bad "a code that is not a number" 2026.11.23-aaaaaaa "12; echo" "$sha_a" +bad "a code of zero" 2026.11.23-aaaaaaa 0 "$sha_a" +bad "no code" 2026.11.23-aaaaaaa "" "$sha_a" +bad "a name with a space" "2026 11" 100 "$sha_a" +bad "a name that is an option" "--draft" 100 "$sha_a" +bad "a short commit id" 2026.11.23-aaaaaaa 100 aaaaaaa +bad "a file that is not there" 2026.11.23-aaaaaaa 100 "$sha_a" "$tmp/none.apk" +if GITHUB_REPOSITORY="not a repo" release "$tmp/one.apk" 2026.11.23-aaaaaaa 100 "$sha_a" >/dev/null 2>&1; then + fail "9: accepted a repository that is not owner/name" +fi +if bash "$here/release.sh" >/dev/null 2>&1; then fail "9: ran with no file named"; fi + +echo "release.test.sh: ok" diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 365b055fbb..2b3a79eed7 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -23,6 +23,8 @@ import { DIRECT_ACTIONS, DIRECT_READ_SECTIONS, directClasses, directRead } from import { Devices, KeyedLimiter, Limiter } from "../../src/devices.ts"; import { type Act, DOC_NAMES, type DocName, Docs, Stamped } from "../../src/docs.ts"; import { + type AndroidRelease, + androidRelease, APK_LIMIT, type ApkReport, apkReport, @@ -97,6 +99,15 @@ const APK_PIECES = Math.ceil(APK_LIMIT / APK_CHUNK); const APK_RETRY_MS = 10 * 60_000; /** With no report for this long, the laptop is not there to ask. */ const HOST_QUIET_MS = 60_000; +/** The GitHub release whose address always holds the app's newest build. */ +const RELEASE_TAG = "pm-console-android"; +/** GitHub is asked what that release holds no more often than this, */ +const RELEASE_EVERY_MS = 10 * 60_000; +/** this soon again when it could not be asked, */ +const RELEASE_RETRY_MS = 60_000; +/** and is given this long to answer, and this long to send the build. */ +const RELEASE_ASK_MS = 8_000; +const RELEASE_FETCH_MS = 25_000; interface ApkMeta { sha256: string; @@ -193,6 +204,9 @@ export class Edge { private keptApk: (ApkMeta & { chunks: number }) | null | undefined; /** The build that could not be kept when it was last sent, and when. */ private apkFailed: { sha256: string; at: number } | null = null; + /** What GitHub last said of the released build, when, and whether it + * could be asked at all. */ + private released: { at: number; asked: boolean; found: AndroidRelease | null } | null = null; private syncRefused: KeyedLimiter; readonly docs: Docs; readonly push: Push; @@ -243,6 +257,65 @@ export class Edge { // ---- the Android build ------------------------------------------------- + /** Where the release with the fixed address keeps a file. */ + private releaseUrl(cfg: EdgeConfig, file: string): string { + return `https://github.com/${cfg.repo}/releases/download/${RELEASE_TAG}/${file}`; + } + + /** The newest build GitHub Actions has released, by its own + * description, or null when none is published. GitHub is not asked on + * every request; when it cannot be asked, what was last known stands. */ + private async androidRelease(cfg: EdgeConfig): Promise { + const now = this.now(); + const known = this.released; + if (known && now - known.at < (known.asked ? RELEASE_EVERY_MS : RELEASE_RETRY_MS)) return known.found; + try { + const res = await this.fetchImpl(this.releaseUrl(cfg, "version.json"), { + redirect: "follow", + signal: AbortSignal.timeout(RELEASE_ASK_MS), + }); + if (res.status === 404) this.released = { at: now, asked: true, found: null }; + else if (res.ok) this.released = { at: now, asked: true, found: androidRelease(await res.json()) }; + else throw new Error(`http ${res.status}`); + } catch { + this.released = { at: now, asked: false, found: known?.found ?? null }; + } + return this.released.found; + } + + /** The released build, as a download, or null if it did not arrive as + * its description says (GitHub out of reach, or the description read + * while a new build was being put up). */ + private async serveRelease(cfg: EdgeConfig, release: AndroidRelease): Promise { + try { + const res = await this.fetchImpl(this.releaseUrl(cfg, "pm-console.apk"), { + redirect: "follow", + signal: AbortSignal.timeout(RELEASE_FETCH_MS), + }); + if (!res.ok) return null; + const bytes = new Uint8Array(await res.arrayBuffer()); + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + const sha256 = [...digest].map((b) => b.toString(16).padStart(2, "0")).join(""); + if (bytes.byteLength !== release.size || sha256 !== release.sha256) { + // The description is out of step with the file: read it again + // next time instead of trusting it for ten minutes. + this.released = null; + return null; + } + return new Response(bytes, { + headers: { + "Content-Type": "application/vnd.android.package-archive", + "Content-Disposition": 'attachment; filename="pm-console.apk"', + "Cache-Control": "no-store", + "X-Build": release.name, + ...SECURITY, + }, + }); + } catch { + return null; + } + } + /** What the app is told of the copy kept here. */ private async apkState(): Promise<{ at: number; current: boolean } | null> { const kept = await this.apkKept(); @@ -915,10 +988,16 @@ export class Edge { return next("asset", { path: `${BASE}/${rest}`, type: STATIC[rest] }); } if (method === "GET" && rest === "pm-console.apk") { - // The newest build is the laptop's. The copy here is served when - // it is that build, or when the laptop is not there to ask. After - // a restart, when the laptop was last heard from has to be read - // back first, or it would look as if it never had been. + // A build GitHub Actions has released comes first: it is the + // newest there is, and getting it needs nothing of the laptop. + const release = await this.androidRelease(cfg); + const released = release ? await this.serveRelease(cfg, release) : null; + if (released) return released; + // Otherwise the newest build is the laptop's. The copy here is + // served when it is that build, or when the laptop is not there + // to ask. After a restart, when the laptop was last heard from + // has to be read back first, or it would look as if it never had + // been. await this.ready(); const kept = await this.apkKept(); const latest = await this.apkLatest(); @@ -957,6 +1036,15 @@ export class Edge { headers.set("X-Host-Seen", String(this.hostSeen ?? 0)); return new Response(res.body, { status: res.status, headers }); } + if (seg.length === 1 && seg[0] === "android") { + // Where a download would come from: the build GitHub released, + // if there is one, and the copy of the laptop's build kept here. + const release = await this.androidRelease(cfg); + return json({ + release: release && { name: release.name, code: release.code, built: release.built }, + copy: await this.apkState(), + }); + } if (seg.length === 1 && seg[0] === "push") return json(await this.push.status()); if (seg.length === 1 && seg[0] === "devices") return json(await this.phones.devices.list()); // Everything else is read from the host as it is now. diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 6735247cce..5496d3a0f9 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -1148,6 +1148,9 @@ async function viewPhone(sub) { history.replaceState(null, "", "#more/phone"); } const devices = await api("devices"); + // Where a download would come from. Only the edge can say; the + // laptop serving the app itself has no such answer. + const android = await api("android").catch(() => null); // The phone has collected its token: the request is finished. if (linkApprovedAt !== null && devices.length > linkApprovedAt) { linkRequest = null; @@ -1235,21 +1238,38 @@ async function viewPhone(sub) { h("li", {}, h("b", {}, "Shortcuts. "), "Long-press the icon for Ask, Needs me and Now."), h("li", {}, h("b", {}, "Notifications. "), "Turn them on under Notifications; they arrive as the app's own."), ), - me.androidApp ? h("div", { class: "row end" }, h("a", { class: "button", href: "/console/pm-console.apk" }, "Download the app")) : null, - // Served from Cloudflare's copy when the laptop is away: say so - // when that copy is not the laptop's newest build. - me.androidBuild && !me.androidBuild.current - ? h( - "p", - { class: "meta" }, - `With the laptop away you get the copy kept at Cloudflare, built ${ago(new Date(me.androidBuild.at).toISOString())}. The laptop has a newer build, which will be here once it has reported again.`, - ) + me.androidApp || android?.release + ? h("div", { class: "row end" }, h("a", { class: "button", href: "/console/pm-console.apk" }, "Download the app")) : null, + androidNote(me, android), ), ); return out; } +/** What is said under the download: which build it is and who made it. */ +export function androidSource(me, android) { + // Released by GitHub Actions: that is what the download is. + if (android?.release) return { by: "github", name: android.release.name, at: android.release.built }; + // Served from Cloudflare's copy when the laptop is away: worth saying + // only when that copy is not the laptop's newest build. + if (me?.androidBuild && !me.androidBuild.current) return { by: "copy", at: new Date(me.androidBuild.at).toISOString() }; + return null; +} + +function androidNote(me, android) { + const source = androidSource(me, android); + if (!source) return null; + if (source.by === "github") { + return h("p", { class: "meta" }, `Build ${source.name}, built, signed and released by GitHub ${ago(source.at)}. It installs over the one you have.`); + } + return h( + "p", + { class: "meta" }, + `With the laptop away you get the copy kept at Cloudflare, built ${ago(source.at)}. The laptop has a newer build, which will be here once it has reported again.`, + ); +} + const QUEUE_STATES = ["blocked", "queued", "claimed", "parked"]; let queueState = { status: "blocked", q: "" }; async function viewQueue() { diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index 5daf14e4ac..aac3b63389 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -127,6 +127,38 @@ export function apkReport(value: unknown): ApkReport | null { }; } +/** A released build of the Android app, as the version.json beside it + * in the GitHub release describes it (android/release.sh writes it). */ +export interface AndroidRelease { + name: string; + code: number; + sha256: string; + size: number; + /** When it was released, as an ISO time. */ + built: string; +} + +/** The largest released build that is passed on. */ +export const RELEASE_LIMIT = 32 * 1024 * 1024; + +/** A release's description as GitHub may serve it, or null. */ +export function androidRelease(value: unknown): AndroidRelease | null { + const v = value as Record | null; + if (!v || typeof v !== "object") return null; + if (typeof v.name !== "string" || !/^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/.test(v.name)) return null; + if (typeof v.code !== "number" || !Number.isSafeInteger(v.code) || v.code <= 0) return null; + if (typeof v.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(v.sha256)) return null; + if (typeof v.size !== "number" || !Number.isSafeInteger(v.size) || v.size <= 0 || v.size > RELEASE_LIMIT) return null; + if (typeof v.built !== "string" || Number.isNaN(Date.parse(v.built))) return null; + return { + name: v.name, + code: v.code, + sha256: v.sha256, + size: v.size, + built: new Date(Date.parse(v.built)).toISOString(), + }; +} + export interface SyncResponse { ok: true; /** Someone has the app open: keep every section fresh. */ diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 1099accf40..77614f388f 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -3,7 +3,8 @@ // Oracles: the elapsed-time phrases and the device labels are written // out here by hand for real inputs (two real browser names). import { expect, test } from "bun:test"; -import { ago, awayState, band, deviceLabel, endpointMark, subscriptionState } from "../public/app.js"; +import { ago, androidSource, awayState, band, deviceLabel, endpointMark, subscriptionState } from "../public/app.js"; +import { androidRelease } from "../src/edge-proto.ts"; import { contact, endpointMark as serverMark } from "../src/push.ts"; test("elapsed time reads as a phrase on its own, never 'just now ago'", () => { @@ -105,3 +106,62 @@ test("the Laptop away screen reads the edge's own account of itself", () => { // Ready without the flag is not ready: the flag is what the owner turned. expect(awayState({ edge: true, directEnabled: false, directReady: true })).toMatchObject({ on: false, ready: false }); }); + +test("the Phones screen says which build a download is, and who made it", () => { + const release = { name: "2026.11.23-a3a547e", code: 21755935, built: "2026-11-23T02:00:00.000Z" }; + // A build GitHub released is what is handed out, whatever the laptop has. + expect(androidSource({ androidBuild: { at: 1, current: false } }, { release, copy: null })).toEqual({ + by: "github", + name: "2026.11.23-a3a547e", + at: "2026-11-23T02:00:00.000Z", + }); + // No release: the copy at Cloudflare is worth a word only when it is not the laptop's newest. + const at = Date.parse("2026-11-22T11:31:06Z"); + expect(androidSource({ androidBuild: { at, current: false } }, { release: null, copy: null })).toEqual({ + by: "copy", + at: "2026-11-22T11:31:06.000Z", + }); + expect(androidSource({ androidBuild: { at, current: true } }, { release: null, copy: null })).toBeNull(); + // Served by the laptop itself, which cannot say where a download comes from. + expect(androidSource({ androidApp: true }, null)).toBeNull(); + expect(androidSource(null, null)).toBeNull(); +}); + +test("a release's description is taken only when it is one", () => { + const good = { + name: "2026.11.23-a3a547e", + code: 21755935, + commit: "a".repeat(40), + sha256: "b".repeat(64), + size: 445978, + built: "2026-11-23T02:00:00Z", + certificate: "8B:82", + }; + expect(androidRelease(good)).toEqual({ + name: "2026.11.23-a3a547e", + code: 21755935, + sha256: "b".repeat(64), + size: 445978, + built: "2026-11-23T02:00:00.000Z", + }); + const bad: Record[] = [ + { name: "../../etc/passwd" }, + { name: "x" }, + { name: "" }, + { name: 7 }, + { code: 0 }, + { code: -4 }, + { code: 1.5 }, + { code: "21755935" }, + { sha256: "B".repeat(64) }, + { sha256: "b".repeat(63) }, + { size: 0 }, + { size: 33 * 1024 * 1024 }, + { size: "445978" }, + { built: "yesterday" }, + { built: 1795400000 }, + ]; + for (const change of bad) expect(androidRelease({ ...good, ...change })).toBeNull(); + for (const not of [null, undefined, "", "version", 4, [], "Not Found"]) + expect(androidRelease(not)).toBeNull(); +}); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 35555f294b..f2eae05f00 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -59,9 +59,27 @@ async function setup(options: { direct?: boolean } = {}) { cfg.issuers = [ISSUER]; const pushes: { url: string; body: Uint8Array; authorization: string }[] = []; const pushFailures = { remaining: 0 }; + /** The release GitHub holds at the app's fixed address: its + * description and its file, either of which may be missing; whether + * GitHub can be reached at all; and every file asked for, in order. */ + const github: { version: unknown; apk: Uint8Array | null; down: boolean; asked: string[] } = { + version: null, + apk: null, + down: false, + asked: [], + }; + const releaseBase = `https://github.com/${cfg.repo}/releases/download/pm-console-android/`; const outward = async (url: string | URL | Request, init?: { body?: unknown; headers?: Record }) => { const u = String(url); if (u === ISSUER.jwksUri) return { ok: true, status: 200, json: async () => ({ keys: [access.jwk] }) }; + if (u.startsWith(releaseBase)) { + const file = u.slice(releaseBase.length); + github.asked.push(file); + if (github.down) throw new Error("github: connection reset"); + if (file === "version.json" && github.version !== null) return new Response(JSON.stringify(github.version)); + if (file === "pm-console.apk" && github.apk) return new Response(github.apk); + return new Response("Not Found", { status: 404 }); + } if (u.startsWith("https://fcm.googleapis.com/")) { pushes.push({ url: u, body: init?.body as Uint8Array, authorization: init?.headers?.Authorization ?? "" }); if (pushFailures.remaining > 0) { @@ -745,6 +763,7 @@ async function setup(options: { direct?: boolean } = {}) { core, hostReads, build, + github, reportSizes, failing, gate, @@ -1540,6 +1559,128 @@ describe("the Android build", () => { } }); + /** A release as android/release.sh describes it, for these bytes. */ + const described = async (bytes: Uint8Array, name: string, code: number) => { + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + return { + name, + code, + commit: "a".repeat(40), + sha256: [...digest].map((b) => b.toString(16).padStart(2, "0")).join(""), + size: bytes.byteLength, + built: "2026-11-22T11:00:00Z", + certificate: "8B:82", + }; + }; + + test("a build GitHub has released is handed out first, and needs nothing of the laptop", async () => { + const w = await setup(); + await w.hostReads(); + // The laptop has an older build of its own, and the edge a copy of it. + w.build.bytes = apk(1); + w.build.at = w.now.t; + await report(w); + await report(w); + // No release is published: the download is the copy, as before, and the app is told there is none. + expect((await download(w)).bytes).toEqual(apk(1)); + let said = (await (await w.browse("/console/api/android")).json()) as Record; + expect(said).toEqual({ release: null, copy: { at: w.build.at, current: true } }); + // GitHub Actions releases a build. The edge asks again within ten minutes and hands that out. + w.github.apk = apk(9, 450_000); + w.github.version = await described(w.github.apk, "2026.11.23-a3a547e", 21755935); + w.now.t += 10 * 60_000; + w.hostSaw.length = 0; + const got = await download(w); + expect(got.res.status).toBe(200); + expect(got.bytes).toEqual(apk(9, 450_000)); + expect(got.res.headers.get("content-type")).toBe("application/vnd.android.package-archive"); + expect(got.res.headers.get("content-disposition")).toBe('attachment; filename="pm-console.apk"'); + expect(got.res.headers.get("x-build")).toBe("2026.11.23-a3a547e"); + expect(w.hostSaw).toEqual([]); + said = (await (await w.browse("/console/api/android")).json()) as Record; + expect(said.release).toEqual({ name: "2026.11.23-a3a547e", code: 21755935, built: "2026-11-22T11:00:00.000Z" }); + // The laptop gone, the edge restarted, and no copy of the laptop's build at all: still handed out. + w.net.hostUp = false; + w.stored.delete("apk"); + w.edge.now = w.makeEdge(); + w.now.t += 60 * 60_000; + expect((await download(w)).bytes).toEqual(apk(9, 450_000)); + // Only the owner gets it. + expect((await w.browse("/console/pm-console.apk", { token: null })).status).not.toBe(200); + expect((await w.browse("/console/api/android", { token: null })).status).not.toBe(200); + }); + + test("a released build that is not the one described is not handed out", async () => { + const w = await setup(); + await w.hostReads(); + w.build.bytes = apk(1); + w.build.at = w.now.t; + await report(w); + await report(w); + // A new build is half put up: the file is the new one, the description still the old one's. + w.github.apk = apk(9, 450_000); + w.github.version = await described(apk(8, 440_000), "2026.11.22-0000000", 21000000); + w.hostSaw.length = 0; + let got = await download(w); + // What arrived does not match: the laptop's build is handed out instead. + expect(got.bytes).toEqual(apk(1)); + // And the description is read again at the next request, not trusted for ten minutes. + w.github.version = await described(w.github.apk, "2026.11.23-a3a547e", 21755935); + got = await download(w); + expect(got.bytes).toEqual(apk(9, 450_000)); + // The file gone missing, cut short, or the right length and the + // wrong bytes, is the same: not handed out. + w.github.apk = apk(9, 449_999); + expect((await download(w)).bytes).toEqual(apk(1)); + w.github.apk = apk(7, 450_000); + expect((await download(w)).bytes).toEqual(apk(1)); + w.github.apk = null; + expect((await download(w)).bytes).toEqual(apk(1)); + // A description that is not one (no size, a path for a name) is no release. + w.now.t += 10 * 60_000; + w.github.apk = apk(9, 450_000); + w.github.version = { ...(await described(w.github.apk, "../../etc", 1)), size: undefined }; + expect((await download(w)).bytes).toEqual(apk(1)); + expect(((await (await w.browse("/console/api/android")).json()) as Record).release).toBeNull(); + }); + + test("GitHub is asked now and then, not on every request, and what it last said stands while it is out of reach", async () => { + const w = await setup(); + await w.hostReads(); + await report(w); + const ask = async () => ((await (await w.browse("/console/api/android")).json()) as Record).release; + // Nothing published. Asked once, however many times the app asks. + for (let i = 0; i < 5; i++) expect(await ask()).toBeNull(); + expect(w.github.asked).toEqual(["version.json"]); + // A release goes up. It is seen at the next asking, ten minutes on. + w.github.apk = apk(9, 450_000); + w.github.version = await described(w.github.apk, "2026.11.23-a3a547e", 21755935); + w.now.t += 9 * 60_000; + expect(await ask()).toBeNull(); + w.now.t += 60_000; + expect((await ask())?.name).toBe("2026.11.23-a3a547e"); + expect(w.github.asked).toEqual(["version.json", "version.json"]); + // GitHub goes out of reach. The release is still known, and GitHub is tried again each minute, not each request. + w.github.down = true; + w.now.t += 10 * 60_000; + for (let i = 0; i < 5; i++) expect((await ask())?.name).toBe("2026.11.23-a3a547e"); + expect(w.github.asked.length).toBe(3); + w.now.t += 60_000; + expect((await ask())?.name).toBe("2026.11.23-a3a547e"); + expect(w.github.asked.length).toBe(4); + // With GitHub out of reach the file cannot be fetched either: the download falls back to the laptop. + w.build.bytes = apk(1); + w.build.at = w.now.t; + w.hostSaw.length = 0; + await w.browse("/console/pm-console.apk"); + expect(w.hostSaw).toEqual(["GET /console/pm-console.apk"]); + // Back in reach, and the release withdrawn: that is believed too. + w.github.down = false; + w.github.version = null; + w.now.t += 60_000; + expect(await ask()).toBeNull(); + }); + test("a copy whose replacement stops half-way is not handed out as either build", async () => { const w = await setup(); await w.hostReads();