Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(ci): upload signed Android bundles to Play drafts (#1182)

Genercbbcc9d45b69
diff --git a/.github/workflows/mobile-release.yml b/.github/workflows/mobile-release.yml
index 27d254e35..f43ed12ef 100644
--- a/.github/workflows/mobile-release.yml
+++ b/.github/workflows/mobile-release.yml
@@ -7,13 +7,23 @@ on:
- "src/desktop/.deploy-version-mobile"
workflow_dispatch:
inputs:
+ ios:
+ description: Build iOS (disable for an Android-only run)
+ required: true
+ default: true
+ type: boolean
upload:
description: Upload the signed IPA to App Store Connect for TestFlight processing
required: true
default: false
type: boolean
android:
- description: Build and attach the signed Android APK
+ description: Build signed Android APK and AAB
+ required: true
+ default: false
+ type: boolean
+ play_upload:
+ description: Upload the verified AAB as a Google Play internal draft
required: true
default: false
type: boolean
@@ -25,6 +35,7 @@ concurrency:
jobs:
build-ios:
name: Build signed iOS IPA
+ if: github.event_name == 'push' || inputs.ios == true
runs-on: xcode-27
timeout-minutes: 45
permissions:
@@ -244,12 +255,15 @@ jobs:
--apiIssuer "$APPLE_API_ISSUER"
build-android:
- name: Build signed Android APK
- if: github.event_name == 'push' || inputs.android == true
+ name: Build signed Android APK and AAB
+ if: github.event_name == 'push' || inputs.android == true || inputs.play_upload == true
runs-on: ubuntu-latest
timeout-minutes: 45
permissions:
contents: write
+ id-token: write
+ env:
+ ANDROID_RELEASE_CERTIFICATE_SHA256: 9DC6EDE94BA663EEC9EC98FF7BAFD55E248B6C4BC2157FCF042DF59B0E410806
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
@@ -355,12 +369,13 @@ jobs:
echo "SIGNING_KEY_PASSWORD=$ANDROID_KEY_PASSWORD"
} >> "$GITHUB_ENV"
- - name: Build signed universal APK
+ - name: Build signed universal APK and AAB
working-directory: src/desktop
run: |
set -euo pipefail
pnpm tauri android build \
--apk \
+ --aab \
--ci \
--target aarch64 armv7 \
--config "{\"bundle\":{\"android\":{\"versionCode\":${GITHUB_RUN_NUMBER}}}}"
@@ -389,7 +404,7 @@ jobs:
signature=$($apksigner verify --verbose --print-certs "$apk_source")
grep -F 'Verifies' <<<"$signature"
normalized_signature=$(tr '[:lower:]' '[:upper:]' <<<"$signature" | tr -d ':')
- grep -F '9DC6EDE94BA663EEC9EC98FF7BAFD55E248B6C4BC2157FCF042DF59B0E410806' <<<"$normalized_signature"
+ grep -F "$ANDROID_RELEASE_CERTIFICATE_SHA256" <<<"$normalized_signature"
manifest_path="$RUNNER_TEMP/android-manifest-tree.txt"
$aapt dump xmltree "$apk_source" AndroidManifest.xml > "$manifest_path"
@@ -458,15 +473,44 @@ jobs:
echo "name=$apk_name" >> "$GITHUB_OUTPUT"
echo "path=$apk_path" >> "$GITHUB_OUTPUT"
- - name: Upload signed APK artifact
+ - name: Verify and stage signed Android App Bundle
+ id: aab
+ shell: bash
+ env:
+ EXPECTED_VERSION: ${{ steps.version.outputs.value }}
+ run: |
+ set -euo pipefail
+ bundletool="$RUNNER_TEMP/bundletool-all-1.18.3.jar"
+ curl --fail --location --retry 2 --connect-timeout 15 --max-time 180 \
+ --output "$bundletool" \
+ https://github.com/google/bundletool/releases/download/1.18.3/bundletool-all-1.18.3.jar
+ echo "a099cfa1543f55593bc2ed16a70a7c67fe54b1747bb7301f37fdfd6d91028e29 $bundletool" | sha256sum --check --strict
+ aab_path="$RUNNER_TEMP/Alook_${EXPECTED_VERSION}_android.aab"
+ receipt_path="$RUNNER_TEMP/android-bundle-receipt.json"
+ python3 scripts/ci/verify-android-bundle.py \
+ --bundle src/desktop/src-tauri/gen/android/app/build/outputs/bundle/universalRelease/app-universal-release.aab \
+ --bundletool "$bundletool" \
+ --version-name "$EXPECTED_VERSION" \
+ --version-code "$GITHUB_RUN_NUMBER" \
+ --certificate-sha256 "$ANDROID_RELEASE_CERTIFICATE_SHA256" \
+ --output "$aab_path" \
+ --receipt "$receipt_path"
+ echo "path=$aab_path" >> "$GITHUB_OUTPUT"
+ echo "receipt=$receipt_path" >> "$GITHUB_OUTPUT"
+
+ - name: Upload signed Android artifacts
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: alook-android-${{ github.run_id }}
- path: ${{ steps.apk.outputs.path }}
+ path: |
+ ${{ steps.apk.outputs.path }}
+ ${{ steps.aab.outputs.path }}
+ ${{ steps.aab.outputs.receipt }}
if-no-files-found: error
retention-days: 14
- name: Resolve GitHub release
+ if: github.event_name == 'push'
id: release
shell: bash
env:
@@ -484,12 +528,14 @@ jobs:
exit 1
- name: Attach APK to GitHub release
+ if: github.event_name == 'push'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: v${{ steps.version.outputs.value }}
run: gh release upload "$TAG" "${{ steps.apk.outputs.path }}#${{ steps.apk.outputs.name }}" --repo "$GITHUB_REPOSITORY" --clobber
- name: Append Android download to release body
+ if: github.event_name == 'push'
env:
APK_NAME: ${{ steps.apk.outputs.name }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -519,3 +565,41 @@ jobs:
EOF
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --notes-file "$notes_file"
+
+ - name: Verify Google Play authentication inputs
+ if: github.event_name == 'push' || inputs.play_upload == true
+ env:
+ GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
+ GOOGLE_PLAY_SERVICE_ACCOUNT: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
+ run: |
+ set -euo pipefail
+ test -n "$GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER"
+ test -n "$GOOGLE_PLAY_SERVICE_ACCOUNT"
+
+ - name: Authenticate Google Play upload
+ if: github.event_name == 'push' || inputs.play_upload == true
+ id: play_auth
+ uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3
+ with:
+ workload_identity_provider: ${{ vars.GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER }}
+ service_account: ${{ vars.GOOGLE_PLAY_SERVICE_ACCOUNT }}
+ token_format: access_token
+ access_token_scopes: https://www.googleapis.com/auth/androidpublisher
+ create_credentials_file: false
+ export_environment_variables: false
+
+ - name: Upload and confirm Google Play internal draft
+ if: github.event_name == 'push' || inputs.play_upload == true
+ env:
+ GOOGLE_PLAY_ACCESS_TOKEN: ${{ steps.play_auth.outputs.access_token }}
+ BUNDLE_RECEIPT: ${{ steps.aab.outputs.receipt }}
+ run: node scripts/ci/upload-google-play.mjs "$BUNDLE_RECEIPT" "$RUNNER_TEMP/google-play-result.json"
+
+ - name: Upload Google Play result receipt
+ if: always() && (github.event_name == 'push' || inputs.play_upload == true)
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
+ with:
+ name: alook-google-play-${{ github.run_id }}
+ path: ${{ runner.temp }}/google-play-result.json
+ if-no-files-found: warn
+ retention-days: 14
diff --git a/.gitignore b/.gitignore
index a104f3bb9..00251cf65 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,6 +6,7 @@ bundled/
.turbo/
.wrangler/
.env
+gha-creds-*.json
.env.*
!.env.example
.next/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index dae42849f..e02d33f5b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -2,6 +2,16 @@
Thanks for your interest in contributing to Alook. This guide covers everything you need to get started.
+## Android release and Play draft upload
+
+`Mobile Release` keeps the mobile-version marker trigger and existing iOS upload path. Android builds signed APK and AAB files together, using the shared release version and `GITHUB_RUN_NUMBER` as their version code. The Android artifact contains both files and the verified AAB receipt. Automatic marker pushes also attach the APK to the GitHub Release. Manual runs leave the public APK and Release body unchanged.
+
+For an Android-only manual run, disable `ios` and enable `android`. Leave `play_upload` false for the first build-only bundle needed by Play Console. After the first website upload, matching Play final signing key and API permissions are established, enable `play_upload` to build and upload an internal-track draft. Automatic mobile release pushes request the same draft upload. This does not publish a production release. No product version bump is needed for a manual workflow check.
+
+Configure repository variables `GOOGLE_PLAY_WORKLOAD_IDENTITY_PROVIDER` and `GOOGLE_PLAY_SERVICE_ACCOUNT` for GitHub OIDC through the Play service account. Restrict WIF to this repository's immutable IDs, `refs/heads/main`, and the Mobile Release workflow; grant only the required Alook testing-track permissions in Play. A short-lived `androidpublisher` access token is obtained after building. Missing configuration fails a requested upload. Never commit credentials or upload `gha-creds-*.json`.
+
+The AAB must pass official bundletool validation, trusted JDK signature verification, and package/version/ARM/certificate checks. Upload consumes the same hashed bytes, checks the Play-returned version/hash, commits only an internal draft and confirms it through a new read edit. Existing in-review changes cause an error instead of review cancellation. A failed commit can have an unknown external outcome; inspect its receipt and Play Console before starting another operation. A rerun retains its version code, so start a new workflow run after that code has already been uploaded. Offline tests do not establish actual signing, upload, account readiness or the final Play signing certificate.
+
## Prerequisites
- **Node.js** ≥ 18
diff --git a/scripts/ci/upload-google-play.mjs b/scripts/ci/upload-google-play.mjs
new file mode 100644
index 000000000..4e0b885e3
--- /dev/null
+++ b/scripts/ci/upload-google-play.mjs
@@ -0,0 +1,107 @@
+import { createHash } from "node:crypto"
+import { readFileSync, writeFileSync } from "node:fs"
+import { pathToFileURL } from "node:url"
+
+const packageName = "ai.alook.android"
+const editsUrl = `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageName}/edits`
+const uploadUrl = `https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${packageName}/edits`
+
+export async function uploadDraft(receipt, bytes, token, request = fetch, progress = {}) {
+ if (!token) throw new Error("Missing Google Play access token")
+ if (receipt.package !== packageName || !Number.isSafeInteger(receipt.versionCode) || receipt.versionCode < 1 ||
+ receipt.bytes !== bytes.length || createHash("sha256").update(bytes).digest("hex") !== receipt.sha256) {
+ throw new Error("Google Play input differs from the verified bundle receipt")
+ }
+ const api = async (method, url, body, media = false) => {
+ const response = await request(url, {
+ method,
+ headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": media ? "application/octet-stream" : "application/json" }) },
+ body: body === undefined ? undefined : media ? body : JSON.stringify(body),
+ signal: AbortSignal.timeout(media ? 300_000 : 60_000),
+ })
+ if (!response.ok) throw new Error(`Google Play ${method} failed with HTTP ${response.status} at ${progress.stage}`)
+ return response.status === 204 ? {} : response.json()
+ }
+ const edit = async () => {
+ const value = await api("POST", editsUrl, {})
+ if (typeof value.id !== "string" || !value.id) throw new Error("Google Play returned no edit identity")
+ return value.id
+ }
+ const path = id => `${editsUrl}/${encodeURIComponent(id)}`
+ let editId
+ let readId
+ let originalError
+ try {
+ progress.stage = "create-edit"
+ editId = await edit()
+ progress.editId = editId
+ progress.stage = "version-admission"
+ const bundles = await api("GET", `${path(editId)}/bundles`)
+ const apks = await api("GET", `${path(editId)}/apks`)
+ const existing = [...(bundles.bundles ?? []), ...(apks.apks ?? [])]
+ if (existing.some(row => !Number.isSafeInteger(row.versionCode) || row.versionCode >= receipt.versionCode)) {
+ throw new Error("Android versionCode must exceed existing Play bundles/APKs; start a new workflow run instead of rerunning an uploaded version")
+ }
+ progress.stage = "upload-bundle"
+ const uploaded = await api("POST", `${uploadUrl}/${encodeURIComponent(editId)}/bundles?uploadType=media`, bytes, true)
+ if (uploaded.versionCode !== receipt.versionCode || uploaded.sha256 !== receipt.sha256) {
+ throw new Error("Google Play upload version/hash differs from the verified bundle")
+ }
+ progress.stage = "update-internal-draft"
+ const current = await api("GET", `${path(editId)}/tracks/internal`)
+ if (current.track !== "internal") throw new Error("Google Play returned a different track")
+ const draft = { name: `${receipt.versionName} (${receipt.versionCode})`, versionCodes: [String(receipt.versionCode)], status: "draft" }
+ const track = { track: "internal", releases: [...(current.releases ?? []).filter(row => row.status !== "draft"), draft] }
+ await api("PUT", `${path(editId)}/tracks/internal`, track)
+ progress.stage = "commit-draft"
+ progress.commitState = "unknown"
+ const committed = await api("POST", `${path(editId)}:commit?changesNotSentForReview=true&changesInReviewBehavior=ERROR_IF_IN_REVIEW`)
+ if (committed.id !== editId) throw new Error("Google Play returned a different committed edit")
+ progress.committed = true
+ progress.commitState = "confirmed"
+ progress.stage = "readback"
+ readId = await edit()
+ const observed = await api("GET", `${path(readId)}/tracks/internal`)
+ const observedBundles = await api("GET", `${path(readId)}/bundles`)
+ if (observed.track !== "internal" || !observed.releases?.some(row => row.status === "draft" && row.versionCodes?.includes(String(receipt.versionCode))) ||
+ !observedBundles.bundles?.some(row => row.versionCode === receipt.versionCode && row.sha256 === receipt.sha256)) {
+ throw new Error("Committed internal draft/bundle was not confirmed by Google Play readback")
+ }
+ progress.stage = "confirmed"
+ progress.readback = true
+ return { package: packageName, track: "internal", status: "draft", versionCode: receipt.versionCode,
+ sha256: receipt.sha256, editId, committed: true, readback: true }
+ } catch (error) {
+ originalError = error
+ throw error
+ } finally {
+ const cleanupErrors = []
+ const cleanupIds = [readId, progress.commitState === "unknown" || progress.committed ? undefined : editId].filter(Boolean)
+ for (const id of cleanupIds) {
+ try { await api("DELETE", path(id)) } catch (error) { cleanupErrors.push(error) }
+ }
+ if (cleanupErrors.length) {
+ progress.cleanupFailed = true
+ throw new AggregateError([...(originalError ? [originalError] : []), ...cleanupErrors],
+ `${originalError ? originalError.message + "; " : ""}Google Play edit cleanup failed`)
+ }
+ }
+}
+
+export async function main(args = process.argv.slice(2)) {
+ if (args.length !== 2) throw new Error("Expected verified bundle receipt and upload result paths")
+ const receipt = JSON.parse(readFileSync(args[0], "utf8"))
+ const progress = { stage: "input", committed: false, commitState: "not-attempted", readback: false }
+ try {
+ const result = await uploadDraft(receipt, readFileSync(receipt.path), process.env.GOOGLE_PLAY_ACCESS_TOKEN, fetch, progress)
+ writeFileSync(args[1], JSON.stringify(result, null, 2) + "\n")
+ process.stdout.write(JSON.stringify(result) + "\n")
+ } catch (error) {
+ writeFileSync(args[1], JSON.stringify({ ...progress, success: false }, null, 2) + "\n")
+ throw error
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ main().catch(error => { process.stderr.write(`${error.message}\n`); process.exitCode = 1 })
+}
diff --git a/scripts/ci/upload-google-play.test.ts b/scripts/ci/upload-google-play.test.ts
new file mode 100644
index 000000000..b4ccd23c9
--- /dev/null
+++ b/scripts/ci/upload-google-play.test.ts
@@ -0,0 +1,151 @@
+import { createHash } from "node:crypto"
+import { readFileSync } from "node:fs"
+import { resolve } from "node:path"
+import { describe, expect, it } from "vitest"
+import { uploadDraft } from "./upload-google-play.mjs"
+
+const bytes = Buffer.from("independent signed bundle bytes")
+const hash = createHash("sha256").update(bytes).digest("hex")
+const receipt = { package: "ai.alook.android", versionName: "0.1.63", versionCode: 10, bytes: bytes.length, sha256: hash }
+const previous = { name: "active", versionCodes: ["9"], status: "completed" }
+const oldDraft = { name: "old", versionCodes: ["8"], status: "draft" }
+const publishedDraft = { name: "0.1.63 (10)", versionCodes: ["10"], status: "draft" }
+
+function fixture(overrides: Record<number, unknown> = {}, failedAt = -1) {
+ const payloads = [
+ { id: "write-edit" }, { bundles: [{ versionCode: 9 }] }, { apks: [{ versionCode: 8 }] },
+ { versionCode: 10, sha256: hash }, { track: "internal", releases: [previous, oldDraft] },
+ { track: "internal", releases: [previous, publishedDraft] }, { id: "write-edit" }, { id: "read-edit" },
+ { track: "internal", releases: [previous, publishedDraft] }, { bundles: [{ versionCode: 10, sha256: hash }] },
+ ]
+ const calls: { url: string, options: RequestInit }[] = []
+ const request = async (url: string, options: RequestInit) => {
+ const index = calls.length
+ calls.push({ url, options })
+ if (options.method === "DELETE") return new Response(null, { status: 204 })
+ if (index === failedAt) return new Response("untrusted server error", { status: 403 })
+ return Response.json(Object.hasOwn(overrides, index) ? overrides[index] : payloads[index])
+ }
+ return { calls, request }
+}
+
+describe("verified bundle to Google Play internal draft", () => {
+ it("uploads the bound bytes, preserves active releases and reads the committed draft/hash back", async () => {
+ const { calls, request } = fixture()
+ const progress: Record<string, unknown> = {}
+ const result = await uploadDraft(receipt, bytes, "offline-token", request, progress)
+ expect(result).toEqual({ package: "ai.alook.android", track: "internal", status: "draft", versionCode: 10,
+ sha256: hash, editId: "write-edit", committed: true, readback: true })
+ expect(calls.map(call => [call.options.method, new URL(call.url).pathname])).toEqual([
+ ["POST", "/androidpublisher/v3/applications/ai.alook.android/edits"],
+ ["GET", "/androidpublisher/v3/applications/ai.alook.android/edits/write-edit/bundles"],
+ ["GET", "/androidpublisher/v3/applications/ai.alook.android/edits/write-edit/apks"],
+ ["POST", "/upload/androidpublisher/v3/applications/ai.alook.android/edits/write-edit/bundles"],
+ ["GET", "/androidpublisher/v3/applications/ai.alook.android/edits/write-edit/tracks/internal"],
+ ["PUT", "/androidpublisher/v3/applications/ai.alook.android/edits/write-edit/tracks/internal"],
+ ["POST", "/androidpublisher/v3/applications/ai.alook.android/edits/write-edit:commit"],
+ ["POST", "/androidpublisher/v3/applications/ai.alook.android/edits"],
+ ["GET", "/androidpublisher/v3/applications/ai.alook.android/edits/read-edit/tracks/internal"],
+ ["GET", "/androidpublisher/v3/applications/ai.alook.android/edits/read-edit/bundles"],
+ ["DELETE", "/androidpublisher/v3/applications/ai.alook.android/edits/read-edit"],
+ ])
+ expect(calls[3].options.body).toBe(bytes)
+ expect(new URL(calls[3].url).searchParams.get("uploadType")).toBe("media")
+ expect(JSON.parse(calls[5].options.body as string)).toEqual({ track: "internal", releases: [previous, publishedDraft] })
+ expect(calls[6].options.body).toBeUndefined()
+ expect(Object.fromEntries(new URL(calls[6].url).searchParams)).toEqual({
+ changesNotSentForReview: "true", changesInReviewBehavior: "ERROR_IF_IN_REVIEW",
+ })
+ expect(JSON.stringify(result)).not.toContain("offline-token")
+ expect(progress).toMatchObject({ stage: "confirmed", committed: true, commitState: "confirmed", readback: true })
+ })
+
+ it.each([
+ { ...receipt, package: "wrong.app" }, { ...receipt, versionCode: 0 },
+ { ...receipt, bytes: 1 }, { ...receipt, sha256: "0".repeat(64) },
+ ])("refuses an unbound input before any external edit: %j", async altered => {
+ const { request, calls } = fixture()
+ await expect(uploadDraft(altered, bytes, "offline-token", request)).rejects.toThrow("verified bundle receipt")
+ expect(calls).toHaveLength(0)
+ })
+
+ it("rejects missing auth without exposing or calling it", async () => {
+ const { request, calls } = fixture()
+ await expect(uploadDraft(receipt, bytes, "", request)).rejects.toThrow("Missing Google Play access token")
+ expect(calls).toHaveLength(0)
+ })
+
+ it.each([10, 11])("refuses reused or lower version code when Play already has %s", async versionCode => {
+ const { request, calls } = fixture({ 1: { bundles: [{ versionCode }] } })
+ await expect(uploadDraft(receipt, bytes, "offline-token", request)).rejects.toThrow("start a new workflow run")
+ expect(calls.filter(call => call.options.method === "POST")).toHaveLength(1)
+ expect(calls.at(-1)?.options.method).toBe("DELETE")
+ })
+
+ it.each([
+ [3, { versionCode: 10, sha256: "0".repeat(64) }, "upload version/hash"],
+ [3, { versionCode: 11, sha256: hash }, "upload version/hash"],
+ [4, { track: "production" }, "different track"],
+ [8, { track: "internal", releases: [{ status: "completed", versionCodes: ["10"] }] }, "readback"],
+ [9, { bundles: [{ versionCode: 10, sha256: "0".repeat(64) }] }, "readback"],
+ ] as const)("retains failure at independent response boundary %s", async (index, response, error) => {
+ const { request, calls } = fixture({ [index]: response })
+ const progress: Record<string, unknown> = {}
+ await expect(uploadDraft(receipt, bytes, "offline-token", request, progress)).rejects.toThrow(error)
+ if (index < 6) expect(calls.some(call => call.url.includes(":commit"))).toBe(false)
+ else expect(progress).toMatchObject({ committed: true, commitState: "confirmed", stage: "readback" })
+ expect(JSON.stringify(progress)).not.toContain("offline-token")
+ })
+
+ it.each([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])("propagates HTTP failure at step %s without retrying mutation", async failedAt => {
+ const { request, calls } = fixture({}, failedAt)
+ const progress: Record<string, unknown> = {}
+ await expect(uploadDraft(receipt, bytes, "offline-token", request, progress)).rejects.toThrow("HTTP 403")
+ expect(calls.filter(call => call.url.includes(":commit"))).toHaveLength(failedAt >= 6 ? 1 : 0)
+ if (failedAt === 6) {
+ expect(progress.commitState).toBe("unknown")
+ expect(calls.at(-1)?.options.method).toBe("POST")
+ }
+ })
+
+ it("preserves confirmed business state when read-edit cleanup fails", async () => {
+ const { request } = fixture()
+ const progress: Record<string, unknown> = {}
+ const failingCleanup = async (url: string, options: RequestInit) => options.method === "DELETE"
+ ? new Response(null, { status: 503 }) : request(url, options)
+ await expect(uploadDraft(receipt, bytes, "offline-token", failingCleanup, progress)).rejects.toThrow("cleanup failed")
+ expect(progress).toMatchObject({ committed: true, readback: true, cleanupFailed: true })
+ })
+})
+
+describe("actual Mobile Release job admission", () => {
+ const workflow = readFileSync(resolve(import.meta.dirname, "../../.github/workflows/mobile-release.yml"), "utf8")
+ const condition = (job: string) => {
+ const expression = workflow.split(` ${job}:\n`)[1].match(/^ if: (.+)$/m)![1]
+ return new Function("github", "inputs", `return ${expression}`) as (github: { event_name: string }, inputs: object) => boolean
+ }
+ it.each([
+ ["push", {}, true, true],
+ ["workflow_dispatch", { ios: false, android: true }, false, true],
+ ["workflow_dispatch", { ios: true, android: false, play_upload: false }, true, false],
+ ["workflow_dispatch", { ios: false, android: false, play_upload: true }, false, true],
+ ])("admits requested platforms for %s %j", (event_name, inputs, ios, android) => {
+ expect(condition("build-ios")({ event_name }, inputs)).toBe(ios)
+ expect(condition("build-android")({ event_name }, inputs)).toBe(android)
+ })
+
+ it.each([
+ ["push", {}, [true, true, true]],
+ ["workflow_dispatch", { ios: false, android: true, play_upload: false }, [false, false, false]],
+ ["workflow_dispatch", { ios: false, android: true, play_upload: true }, [false, false, false]],
+ ])("protects public Release writes for %s %j", (event_name, inputs, expected) => {
+ const operations = ["Resolve GitHub release", "Attach APK to GitHub release", "Append Android download to release body"]
+ const admitted = operations.map(name => {
+ const step = workflow.split(` - name: ${name}\n`)[1].split(" - name:")[0]
+ const expression = step.match(/^ if: (.+)$/m)?.[1]
+ const run = new Function("github", "inputs", `return ${expression ?? "true"}`)
+ return run({ event_name }, inputs)
+ })
+ expect(admitted).toEqual(expected)
+ })
+})
diff --git a/scripts/ci/verify-android-bundle.py b/scripts/ci/verify-android-bundle.py
new file mode 100644
index 000000000..1abf54639
--- /dev/null
+++ b/scripts/ci/verify-android-bundle.py
@@ -0,0 +1,81 @@
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import ssl
+import subprocess
+import xml.etree.ElementTree as ET
+import zipfile
+
+
+ANDROID = "{http://schemas.android.com/apk/res/android}"
+
+
+def native(command):
+ result = subprocess.run(command, capture_output=True, text=True, timeout=120)
+ if result.returncode:
+ raise ValueError(f"{Path(command[0]).name} failed ({result.returncode}): {result.stderr.strip()}")
+ return result.stdout
+
+
+def metadata(manifest, names, certificate, version_name, version_code, expected_certificate):
+ root = ET.fromstring(manifest)
+ if root.tag != "manifest" or root.get("package") != "ai.alook.android":
+ raise ValueError("Unexpected Android bundle package")
+ if root.get(ANDROID + "versionName") != version_name or root.get(ANDROID + "versionCode") != str(version_code):
+ raise ValueError("Android bundle version differs from this release")
+ application = root.find("application")
+ if application is None or application.get(ANDROID + "debuggable") == "true":
+ raise ValueError("Android bundle must contain a release application")
+ abis = sorted({name.split("/")[2] for name in names if re.fullmatch(r"base/lib/[^/]+/[^/]+\.so", name)})
+ if abis != ["arm64-v8a", "armeabi-v7a"]:
+ raise ValueError("Android bundle must contain both release ARM architectures")
+ certificates = re.findall(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", certificate, re.S)
+ if not certificates:
+ raise ValueError("Android bundle has no signing certificate")
+ fingerprint = hashlib.sha256(ssl.PEM_cert_to_DER_cert(certificates[0])).hexdigest().upper()
+ if fingerprint != expected_certificate.replace(":", "").upper():
+ raise ValueError("Android bundle signing certificate differs from the direct APK")
+ return dict(package="ai.alook.android", versionName=version_name, versionCode=version_code,
+ certificateSha256=fingerprint, abis=abis)
+
+
+def verify(args):
+ if not re.fullmatch(r"[1-9][0-9]*", args.version_code) or int(args.version_code) > 2100000000:
+ raise ValueError("Invalid Android versionCode")
+ for key in ["SIGNING_STORE_FILE", "SIGNING_STORE_PASSWORD"]:
+ if not os.environ.get(key):
+ raise ValueError(f"Missing Android verification input: {key}")
+ source, output = Path(args.bundle), Path(args.output).resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with source.open("rb") as incoming, output.open("xb") as outgoing:
+ shutil.copyfileobj(incoming, outgoing)
+ native(["jarsigner", "-verify", "-strict", "-keystore", os.environ["SIGNING_STORE_FILE"],
+ "-storepass:env", "SIGNING_STORE_PASSWORD", str(output)])
+ certificate = native(["keytool", "-J-Duser.language=en", "-printcert", "-jarfile", str(output), "-rfc"])
+ native(["java", "-jar", args.bundletool, "validate", "--bundle", str(output)])
+ manifest = native(["java", "-jar", args.bundletool, "dump", "manifest", "--bundle", str(output), "--module", "base"])
+ with zipfile.ZipFile(output) as archive:
+ result = metadata(manifest, archive.namelist(), certificate, args.version_name,
+ int(args.version_code), args.certificate_sha256)
+ result.update(path=str(output), bytes=output.stat().st_size, sha256=hashlib.sha256(output.read_bytes()).hexdigest())
+ Path(args.receipt).write_text(json.dumps(result, indent=2) + "\n")
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ for name in ["bundle", "bundletool", "version-name", "version-code", "certificate-sha256", "output", "receipt"]:
+ parser.add_argument("--" + name, required=True)
+ args = parser.parse_args()
+ try:
+ print(json.dumps(verify(args)))
+ except (ValueError, OSError, subprocess.SubprocessError, ET.ParseError, zipfile.BadZipFile) as error:
+ parser.exit(1, f"Android bundle verification failed: {error}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/ci/verify-android-bundle.test.ts b/scripts/ci/verify-android-bundle.test.ts
new file mode 100644
index 000000000..025d25f59
--- /dev/null
+++ b/scripts/ci/verify-android-bundle.test.ts
@@ -0,0 +1,92 @@
+import { createHash } from "node:crypto"
+import { spawnSync } from "node:child_process"
+import { resolve } from "node:path"
+import { describe, expect, it } from "vitest"
+
+const helper = resolve(import.meta.dirname, "verify-android-bundle.py")
+const certificate = "-----BEGIN CERTIFICATE-----\naW5kZXBlbmRlbnQgdGVzdCBjZXJ0aWZpY2F0ZSBieXRlcw==\n-----END CERTIFICATE-----"
+const fingerprint = createHash("sha256").update("independent test certificate bytes").digest("hex").toUpperCase()
+const manifest = '<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ai.alook.android" android:versionName="0.1.63" android:versionCode="10"><application android:debuggable="false"/></manifest>'
+const names = ["base/lib/arm64-v8a/libapp.so", "base/lib/armeabi-v7a/libapp.so"]
+
+function run(overrides: Record<string, unknown> = {}, nativeFailure = "") {
+ return spawnSync("python3", ["-c", `
+import argparse, hashlib, importlib.util, json, os, pathlib, sys, tempfile, zipfile
+sys.dont_write_bytecode = True
+spec = importlib.util.spec_from_file_location("bundle_verifier", sys.argv[1])
+module = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(module)
+fixture = json.load(sys.stdin)
+calls = []
+def native(command):
+ calls.append(command)
+ if command[0] == fixture["nativeFailure"]:
+ raise ValueError("controlled native rejection")
+ if command[0] == "keytool": return fixture["certificate"]
+ if "dump" in command: return fixture["manifest"]
+ return ""
+module.native = native
+with tempfile.TemporaryDirectory(prefix="alook-bundle-metadata-") as root:
+ root = pathlib.Path(root)
+ source, staged, receipt = [root / name for name in ["input.aab", "staged.aab", "receipt.json"]]
+ with zipfile.ZipFile(source, "w") as bundle:
+ for name in fixture["names"]: bundle.writestr(name, b"fixture native bytes")
+ os.environ["SIGNING_STORE_FILE"] = str(root / "offline.jks")
+ os.environ["SIGNING_STORE_PASSWORD"] = "offline-fixture-password"
+ args = argparse.Namespace(bundle=str(source), output=str(staged), receipt=str(receipt),
+ bundletool="offline-bundletool.jar", version_name="0.1.63", version_code="10",
+ certificate_sha256=fixture["fingerprint"])
+ try:
+ result = module.verify(args)
+ assert staged.read_bytes() == source.read_bytes()
+ assert result["sha256"] == hashlib.sha256(staged.read_bytes()).hexdigest()
+ print(json.dumps({"result": result, "calls": calls, "receipt": json.loads(receipt.read_text())}))
+ except Exception as error:
+ print(json.dumps({"error": str(error), "calls": calls, "receiptExists": receipt.exists()}))
+ sys.exit(1)
+`, helper], {
+ encoding: "utf8", input: JSON.stringify({ certificate, fingerprint, manifest, names, nativeFailure, ...overrides }),
+ timeout: 10_000,
+ })
+}
+
+describe("AAB metadata and native-command boundary with controlled tools", () => {
+ it("binds staged bytes, decoded identity, version, ABI and certificate to the receipt", () => {
+ const execution = run()
+ expect(execution.status, execution.stderr).toBe(0)
+ const { result, calls, receipt } = JSON.parse(execution.stdout)
+ expect(result).toMatchObject({ package: "ai.alook.android", versionName: "0.1.63", versionCode: 10,
+ certificateSha256: fingerprint, abis: ["arm64-v8a", "armeabi-v7a"] })
+ expect(receipt).toEqual(result)
+ expect(calls[0].slice(0, 3)).toEqual(["jarsigner", "-verify", "-strict"])
+ expect(calls[0]).toContain("-storepass:env")
+ expect(calls.map((command: string[]) => command[0])).toEqual(["jarsigner", "keytool", "java", "java"])
+ expect(execution.stdout).not.toContain("offline-fixture-password")
+ })
+
+ it.each([
+ [{ manifest: manifest.replace("ai.alook.android", "wrong.app") }, "package"],
+ [{ manifest: manifest.replace('versionCode="10"', 'versionCode="11"') }, "version"],
+ [{ manifest: manifest.replace('versionName="0.1.63"', 'versionName="0.1.62"') }, "version"],
+ [{ manifest: manifest.replace('debuggable="false"', 'debuggable="true"') }, "release application"],
+ [{ names: [names[0]] }, "ARM architectures"],
+ [{ names: [...names, "base/lib/x86/libapp.so"] }, "ARM architectures"],
+ [{ certificate: "Not a signed jar file" }, "no signing certificate"],
+ [{ fingerprint: "0".repeat(64) }, "signing certificate differs"],
+ ] as const)("rejects the isolated metadata violation %j", (override, error) => {
+ const execution = run(override)
+ expect(execution.status).toBe(1)
+ const result = JSON.parse(execution.stdout)
+ expect(result.error).toContain(error)
+ expect(result.receiptExists).toBe(false)
+ })
+
+ it.each(["jarsigner", "keytool", "java"])("stops receipt publication after %s rejects", tool => {
+ const execution = run({}, tool)
+ expect(execution.status).toBe(1)
+ const result = JSON.parse(execution.stdout)
+ expect(result.error).toBe("controlled native rejection")
+ expect(result.calls.at(-1)[0]).toBe(tool)
+ expect(result.receiptExists).toBe(false)
+ })
+})
diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.ts
index 32a0b946c..df6d89a18 100644
--- a/scripts/ci/workflow-contract.test.ts
+++ b/scripts/ci/workflow-contract.test.ts
@@ -1349,7 +1349,7 @@ describe("Mobile release availability", () => {
expect(build).toBeGreaterThan(restore)
})
- it("attaches a signed Android APK to --mobile GitHub releases without Google Play", () => {
+ it("keeps signed Android APK downloads on --mobile GitHub releases", () => {
expect(desktopAndroidConfig.identifier).toBe("ai.alook.android")
expect(androidGradle).toContain('namespace = "ai.alook.android"')
expect(androidGradle).toContain('applicationId = "ai.alook.android"')
@@ -1390,7 +1390,6 @@ describe("Mobile release availability", () => {
expect(mobileReleaseWorkflow).toContain("## Android")
expect(mobileReleaseWorkflow).toContain("[Download signed APK](${base}/${APK_NAME})")
expect(mobileReleaseWorkflow).toContain('gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --notes-file "$notes_file"')
- expect(mobileReleaseWorkflow).not.toContain("Google Play")
})
})
diff --git a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
index 0d92a7d46..bad4f4b77 100644
--- a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
+++ b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
@@ -946,12 +946,14 @@ test("forum post actions stay discoverable on mobile without changing permission
const unauthorizedCard = unauthorized.page.getByTestId(tid.forumThreadCard(primaryPostId))
await expect(unauthorizedCard).toBeVisible({ timeout: 20_000 })
for (const post of postCases) {
+ await expect(unauthorized.page.getByTestId(tid.forumThreadCard(post.id))).toHaveAttribute("role", "button")
await expect(unauthorized.page.getByTestId(tid.forumThreadTagBtn(post.id))).toHaveCount(0)
await expect(unauthorized.page.getByTestId(tid.forumThreadArchiveBtn(post.id))).toHaveCount(0)
await expect(unauthorized.page.getByTestId(tid.forumThreadDeleteBtn(post.id))).toHaveCount(0)
}
await unauthorized.page.setViewportSize({ width: 320, height: 844 })
for (const post of postCases) {
+ await expect(unauthorized.page.getByTestId(tid.forumThreadCard(post.id))).toHaveAttribute("role", "button")
await expect(unauthorized.page.getByTestId(tid.forumThreadTagBtn(post.id))).toHaveCount(0)
await expect(unauthorized.page.getByTestId(tid.forumThreadArchiveBtn(post.id))).toHaveCount(0)
await expect(unauthorized.page.getByTestId(tid.forumThreadDeleteBtn(post.id))).toHaveCount(0)