Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
Add signed Android APKs to production releases (#7274)
Peter Chinman03a8ad6e7377
diff --git a/.github/workflows/release-production.yml b/.github/workflows/release-production.ymlindex a18b60bea6..6a86847eb5 100644--- a/.github/workflows/release-production.yml+++ b/.github/workflows/release-production.yml@@ -11,6 +11,111 @@ env:MODE: "production"jobs:+ build-android:+ name: Build signed Android APK+ runs-on: ubuntu-24.04+ permissions:+ contents: read+ timeout-minutes: 90+ env:+ CI: "true"+ RELEASE_TAG: ${{ github.event.release.tag_name }}+ steps:+ - name: Checkout release+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - name: Install Android SDK components+ shell: bash+ run: |+ set -euo pipefail+ export JAVA_HOME="$JAVA_HOME_21_X64"+ export PATH="$JAVA_HOME/bin:$PATH"+ "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \+ 'platforms;android-36' 'build-tools;36.0.0' 'ndk;30.0.16248370'+ echo "JAVA_HOME=$JAVA_HOME" >> "$GITHUB_ENV"+ echo "NDK_HOME=$ANDROID_HOME/ndk/30.0.16248370" >> "$GITHUB_ENV"+ - name: Setup Nix+ uses: ./.github/actions/setup-nix+ - name: Setup prerequisites+ uses: ./.github/actions/setup-reqs-web+ - name: Prepare version and signing+ id: metadata+ working-directory: apps/web+ env:+ DOPPLER_TOKEN: ${{ secrets.ANDROID_RELEASE_DOPPLER_TOKEN }}+ run: |+ set -euo pipefail+ filename=$(bun scripts/android-release.ts metadata "$RELEASE_TAG" "$RUNNER_TEMP/android-release.json")+ echo "filename=$filename" >> "$GITHUB_OUTPUT"+ bun scripts/android-release.ts signing "$RUNNER_TEMP/android-signing" \+ tauri/src-tauri/gen/android/keystore.properties+ bun scripts/android-firebase.ts build --doppler "$RUNNER_TEMP/android-google-services.json"+ - name: Build production APK+ working-directory: apps/web+ env:+ VITE_SEGMENT_WRITE_KEY: ${{ secrets.SEGMENT_WRITE_KEY_PRODUCTION }}+ VITE_POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}+ VITE_OTEL_EXPORTER_URL: https://macro-prox-prod.macroverse.workers.dev/i/otlp/v1/traces+ VITE_OTEL_ENV: prod+ run: |+ just android-build --firebase-config "$RUNNER_TEMP/android-google-services.json" \+ --apk true --aab false --ci --config "$RUNNER_TEMP/android-release.json"+ - name: Verify and collect APK+ working-directory: apps/web+ env:+ APK_FILENAME: ${{ steps.metadata.outputs.filename }}+ run: |+ set -euo pipefail+ mapfile -t apks < <(find tauri/src-tauri/gen/android/app/build/outputs/apk -type f -name '*-release.apk')+ if [ "${#apks[@]}" -ne 1 ]; then+ echo "Expected exactly one signed ARM64 release APK, found ${#apks[@]}" >&2+ exit 1+ fi+ bun scripts/android-release.ts verify "$RELEASE_TAG" "${apks[0]}" \+ "$ANDROID_HOME/build-tools/36.0.0" "$RUNNER_TEMP/android-signing/certificate-sha256"+ mkdir -p "$GITHUB_WORKSPACE/android-artifacts"+ cp "${apks[0]}" "$GITHUB_WORKSPACE/android-artifacts/$APK_FILENAME"+ \cd "$GITHUB_WORKSPACE/android-artifacts"+ sha256sum "$APK_FILENAME" > "$APK_FILENAME.sha256"+ - name: Upload verified Android artifact+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02+ with:+ name: android-release+ path: android-artifacts/*+ if-no-files-found: error+ retention-days: 30+ - name: Remove signing material+ if: always()+ run: |+ rm -f apps/web/tauri/src-tauri/gen/android/keystore.properties \+ apps/web/tauri/src-tauri/gen/android/app/google-services.json \+ "$RUNNER_TEMP/android-google-services.json"+ rm -rf "$RUNNER_TEMP/android-signing"+ - name: Teardown Nix+ if: always()+ uses: ./.github/actions/teardown-nix++ upload-android:+ name: Publish Android release artifact+ needs: [build-android, deploy, deploy-sync-service, deploy-ai-editing-worker]+ runs-on: ubuntu-24.04+ permissions:+ contents: write+ steps:+ - name: Download verified Android artifact+ uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0+ with:+ name: android-release+ path: android-artifacts+ - name: Attach APK and checksum to release+ uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65+ with:+ tag_name: ${{ github.event.release.tag_name }}+ files: android-artifacts/*+ fail_on_unmatched_files: true+deploy-cloud-storage:name: Deploy Cloud Storage Servicesuses: ./.github/workflows/deploy_all_services.ymldiff --git a/apps/web/scripts/android-release.test.ts b/apps/web/scripts/android-release.test.tsnew file mode 100644index 0000000000..6b392aa3bb--- /dev/null+++ b/apps/web/scripts/android-release.test.ts@@ -0,0 +1,197 @@+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ androidPackage,+ androidReleaseMetadata,+ parseAndroidSigning,+ propertyValue,+ provisionAndroidSigning,+ verifyAndroidApk,+} from './android-release';++vi.mock('node:child_process', () => ({ execFileSync: vi.fn() }));+afterEach(() => vi.mocked(execFileSync).mockReset());++const keystore = Buffer.from('fake keystore for tests');+const signing = {+ package_name: androidPackage,+ keystore_base64: keystore.toString('base64'),+ keystore_sha256: createHash('sha256').update(keystore).digest('hex'),+ certificate_sha256: 'ab'.repeat(32),+ key_alias: 'upload',+ key_password: 'test-password',+ store_password: 'test-store-password',+};++describe('Android release versions', () => {+ it('assigns deterministic increasing codes across revisions, days, and years', () => {+ const tags = [+ 'v2026.9.28.0',+ 'v2026.9.28.99',+ 'v2026.9.29.0',+ 'v2027.1.1.0',+ ];+ const codes = tags.map((tag) => androidReleaseMetadata(tag).versionCode);+ expect(codes).toEqual([2026092800, 2026092899, 2026092900, 2027010100]);+ expect(androidReleaseMetadata(tags[0])).toEqual({+ version: '2026.9.28-0',+ versionCode: 2026092800,+ filename: 'macro-v2026.9.28.0-android-arm64.apk',+ });+ expect(androidReleaseMetadata('v2099.12.31.99').versionCode).toBeLessThan(+ 2100000000+ );+ });++ it.each([+ 'main',+ 'v2026.2.29.0',+ 'v2026.13.1.0',+ 'v2026.9.28.100',+ 'v2100.1.1.0',+ 'v2026.9.28.0\n',+ ])('rejects invalid tag %j', (tag) => {+ expect(() => androidReleaseMetadata(tag)).toThrow();+ });+});++describe('Android signing provisioning', () => {+ it('rejects malformed secrets and incorrect keystore checksums without exposing values', () => {+ for (const contents of [+ '{secret-password',+ JSON.stringify({+ ...signing,+ package_name: 'wrong',+ key_password: 'secret-password',+ }),+ JSON.stringify({ ...signing, keystore_sha256: '0'.repeat(64) }),+ ]) {+ expect(() => parseAndroidSigning(contents)).toThrow(+ /Invalid Android|checksum mismatch/+ );+ expect(() => parseAndroidSigning(contents)).not.toThrow(+ /secret-password/+ );+ }+ });++ it('escapes Java properties whitespace, separators, backslashes and Unicode', () => {+ expect(propertyValue(' a\\b\n:=#!é')).toBe(+ '\\u0020a\\u005cb\\u000a\\u003a\\u003d\\u0023\\u0021\\u00e9'+ );+ });++ it('writes private files, links Gradle configuration, and preserves existing files', async () => {+ const root = await mkdtemp(join(tmpdir(), 'android-signing-test-'));+ try {+ const directory = join(root, 'private');+ const properties = join(root, 'keystore.properties');+ await provisionAndroidSigning(+ JSON.stringify(signing),+ directory,+ properties+ );+ expect(await readFile(join(directory, 'upload-keystore.jks'))).toEqual(+ keystore+ );+ expect((await stat(directory)).mode & 0o777).toBe(0o700);+ for (const file of [+ 'upload-keystore.jks',+ 'keystore.properties',+ 'certificate-sha256',+ ]) {+ expect((await stat(join(directory, file))).mode & 0o777).toBe(0o600);+ }+ expect(await readFile(properties, 'utf8')).toContain('keyAlias=upload\n');+ const existing = join(root, 'existing.properties');+ await writeFile(existing, 'keep this');+ await expect(+ provisionAndroidSigning(+ JSON.stringify(signing),+ join(root, 'other'),+ existing+ )+ ).rejects.toThrow();+ expect(await readFile(existing, 'utf8')).toBe('keep this');+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+});++describe('APK verification', () => {+ const metadata = androidReleaseMetadata('v2026.9.28.0');+ const badging = `package: name='${androidPackage}' versionCode='${metadata.versionCode}' versionName='${metadata.version}' platformBuildVersionName='16'\nnative-code: 'arm64-v8a'\n`;++ function mockTools(+ badge = badging,+ certificate = signing.certificate_sha256+ ) {+ vi.mocked(execFileSync)+ .mockReturnValueOnce(+ `Signer #1 certificate SHA-256 digest: ${certificate}\n`+ )+ .mockReturnValueOnce(Buffer.from(''))+ .mockReturnValueOnce(badge);+ }++ it('accepts the expected signed release', () => {+ mockTools();+ expect(() =>+ verifyAndroidApk(+ 'release.apk',+ '/sdk',+ signing.certificate_sha256,+ metadata+ )+ ).not.toThrow();+ });++ it('rejects a different signing certificate', () => {+ mockTools(badging, 'cd'.repeat(32));+ expect(() =>+ verifyAndroidApk(+ 'release.apk',+ '/sdk',+ signing.certificate_sha256,+ metadata+ )+ ).toThrow(/certificate/);+ });++ it.each([+ badging.replace(androidPackage, 'com.wrong.app'),+ badging.replace(String(metadata.versionCode), '1'),+ badging.replace(metadata.version, '1.0.0'),+ badging.replace('arm64-v8a', 'x86_64'),+ `${badging}application-debuggable\n`,+ ])('rejects incorrect APK metadata', (badge) => {+ mockTools(badge);+ expect(() =>+ verifyAndroidApk(+ 'release.apk',+ '/sdk',+ signing.certificate_sha256,+ metadata+ )+ ).toThrow(/incorrect/);+ });++ it('fails when apksigner fails verification', () => {+ vi.mocked(execFileSync).mockImplementation(() => {+ throw new Error('Invalid signature');+ });+ expect(() =>+ verifyAndroidApk(+ 'release.apk',+ '/sdk',+ signing.certificate_sha256,+ metadata+ )+ ).toThrow('Invalid signature');+ });+});diff --git a/apps/web/scripts/android-release.ts b/apps/web/scripts/android-release.tsnew file mode 100644index 0000000000..4e551290ff--- /dev/null+++ b/apps/web/scripts/android-release.ts@@ -0,0 +1,207 @@+import { execFileSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdir, readFile, symlink, writeFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { z } from 'zod';++export const androidPackage = 'com.macro.app.prod';++export function androidReleaseMetadata(tag: string) {+ const match = /^v(20\d{2})\.(\d{1,2})\.(\d{1,2})\.(\d{1,2})$/.exec(tag);+ if (!match) throw new Error('Expected release tag vYYYY.M.D.N (N: 0–99)');+ const [year, month, day, revision] = match.slice(1).map(Number);+ const date = new Date(Date.UTC(year, month - 1, day));+ if (+ date.getUTCFullYear() !== year ||+ date.getUTCMonth() !== month - 1 ||+ date.getUTCDate() !== day+ )+ throw new Error('Release tag must contain a valid calendar date');+ // YYYYMMDDNN stays below Android's 2,100,000,000 limit through 2099.+ // Rebuilding a tag keeps its code; later dated releases always increase it.+ const versionCode = (year * 10000 + month * 100 + day) * 100 + revision;+ return {+ version: `${year}.${month}.${day}-${revision}`,+ versionCode,+ filename: `macro-${tag}-android-arm64.apk`,+ };+}++const signingSchema = z.object({+ package_name: z.literal(androidPackage),+ keystore_base64: z+ .string()+ .min(1)+ .regex(/^[A-Za-z0-9+/]+={0,2}$/),+ keystore_sha256: z.string().regex(/^[a-fA-F0-9]{64}$/),+ certificate_sha256: z.string().regex(/^(?:[a-fA-F0-9]{2}:?){32}$/),+ key_alias: z.string().min(1),+ key_password: z.string().min(1),+ store_password: z.string().min(1),+});++export function parseAndroidSigning(contents: string) {+ // Never include the input or parser diagnostics in an error: they contain secrets.+ let input: unknown;+ try {+ input = JSON.parse(contents);+ } catch {+ throw new Error('Invalid Android signing JSON');+ }+ const parsed = signingSchema.safeParse(input);+ if (!parsed.success) throw new Error('Invalid Android signing configuration');+ const signing = parsed.data;+ const keystore = Buffer.from(signing.keystore_base64, 'base64');+ if (+ createHash('sha256').update(keystore).digest('hex') !==+ signing.keystore_sha256.toLowerCase()+ )+ throw new Error('Android keystore checksum mismatch');+ return { signing, keystore };+}++// java.util.Properties.load(InputStream) is Latin-1, with backslash escapes.+export function propertyValue(value: string) {+ return value.replace(+ /[\\\s:=#!\u0080-\uffff]/g,+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`+ );+}++export async function provisionAndroidSigning(+ contents: string,+ directory: string,+ propertiesPath: string+) {+ const { signing, keystore } = parseAndroidSigning(contents);+ await mkdir(directory, { mode: 0o700 });+ const keystorePath = join(resolve(directory), 'upload-keystore.jks');+ const properties = {+ storeFile: keystorePath,+ storePassword: signing.store_password,+ keyAlias: signing.key_alias,+ keyPassword: signing.key_password,+ };+ await writeFile(keystorePath, keystore, { mode: 0o600, flag: 'wx' });+ const privateProperties = join(directory, 'keystore.properties');+ await writeFile(+ privateProperties,+ Object.entries(properties)+ .map(([key, value]) => `${key}=${propertyValue(value)}\n`)+ .join(''),+ { mode: 0o600, flag: 'wx' }+ );+ await writeFile(+ join(directory, 'certificate-sha256'),+ signing.certificate_sha256.replaceAll(':', '').toLowerCase(),+ { mode: 0o600, flag: 'wx' }+ );+ // Fail rather than replacing a developer's existing signing configuration.+ await symlink(resolve(privateProperties), propertiesPath);+}++function fetchSigning() {+ try {+ return execFileSync(+ 'doppler',+ [+ 'secrets',+ 'get',+ 'ANDROID_UPLOAD_SIGNING_JSON',+ '--project',+ 'android-release',+ '--config',+ 'prd',+ '--plain',+ '--raw',+ '--no-check-version',+ ],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }+ );+ } catch {+ throw new Error(+ 'Unable to fetch Android signing credentials. DOPPLER_TOKEN must have read access to android-release/prd.'+ );+ }+}++export function verifyAndroidApk(+ apk: string,+ buildTools: string,+ expectedCertificate: string,+ metadata: ReturnType<typeof androidReleaseMetadata>+) {+ const certificates = execFileSync(+ join(buildTools, 'apksigner'),+ ['verify', '--verbose', '--print-certs', apk],+ { encoding: 'utf8' }+ );+ const fingerprints = [+ ...certificates.matchAll(+ /^Signer #\d+ certificate SHA-256 digest: ([a-fA-F0-9]+)$/gm+ ),+ ].map((match) => match[1].toLowerCase());+ if (+ fingerprints.length !== 1 ||+ fingerprints[0] !== expectedCertificate.trim()+ )+ throw new Error(+ 'APK was not signed with the expected Android release certificate'+ );+ execFileSync(join(buildTools, 'zipalign'), ['-c', '-P', '16', '4', apk]);+ const badging = execFileSync(+ join(buildTools, 'aapt'),+ ['dump', 'badging', apk],+ {+ encoding: 'utf8',+ }+ );+ const expected = `package: name='${androidPackage}' versionCode='${metadata.versionCode}' versionName='${metadata.version}'`;+ if (+ !badging.startsWith(expected) ||+ !/^native-code: 'arm64-v8a'\s*$/m.test(badging) ||+ /^application-debuggable/m.test(badging)+ )+ throw new Error(+ 'APK package, version, architecture, or release mode is incorrect'+ );+}++if (import.meta.main) {+ const [command, ...args] = process.argv.slice(2);+ try {+ if (command === 'metadata' && args.length === 2) {+ const [tag, destination] = args;+ const metadata = androidReleaseMetadata(tag);+ await writeFile(+ destination,+ JSON.stringify({+ version: metadata.version,+ bundle: { android: { versionCode: metadata.versionCode } },+ })+ );+ console.log(metadata.filename);+ } else if (command === 'signing' && args.length === 2) {+ await provisionAndroidSigning(fetchSigning(), args[0], args[1]);+ } else if (command === 'verify' && args.length === 4) {+ const [tag, apk, buildTools, certificateFile] = args;+ verifyAndroidApk(+ apk,+ buildTools,+ await readFile(certificateFile, 'utf8'),+ androidReleaseMetadata(tag)+ );+ } else {+ throw new Error(+ 'Usage: android-release.ts metadata TAG CONFIG | signing DIRECTORY PROPERTIES | verify TAG APK BUILD_TOOLS CERTIFICATE_FILE'+ );+ }+ } catch (error) {+ console.error(+ error instanceof Error+ ? error.message+ : 'Android release preparation failed'+ );+ process.exitCode = 1;+ }+}diff --git a/docs/ANDROID_DEVELOPMENT.md b/docs/ANDROID_DEVELOPMENT.mdindex eb9aaa67d9..824da3ea88 100644--- a/docs/ANDROID_DEVELOPMENT.md+++ b/docs/ANDROID_DEVELOPMENT.md@@ -53,11 +53,26 @@ Release builds require the signing configuration below and produce signed artifa## Release signing-Obtain the existing upload keystore and signing credentials from the release-maintainers. Keep them outside the checkout and provision them securely for CI.+The existing upload keystore and signing credentials are stored in Doppler+`android-release/prd`, secret `ANDROID_UPLOAD_SIGNING_JSON`. It contains+`keystore_base64`, `keystore_sha256`, `certificate_sha256`, `package_name`,+`key_alias`, `key_password`, and `store_password`. Keep them outside the checkout+and provision them securely for CI.Coordinate key replacement with Play Console; do not generate a new key forroutine builds.+With Doppler access, provision signing from `apps/web` (the private destination+directory must not already exist):++```sh+bun scripts/android-release.ts signing /absolute/private/path/android-signing tauri/src-tauri/gen/android/keystore.properties+```++This validates the package and keystore checksum, writes owner-only files, and+symlinks Gradle's properties file. It refuses to replace existing configuration.+The destination's parent must exist. Do not print the secret JSON in terminals or+CI logs.+Gradle reads ignored `tauri/src-tauri/gen/android/keystore.properties`:```properties@@ -94,6 +109,36 @@ The upload certificate identifies locally signed artifacts. When Google createsthe Play App Signing key, Play-delivered APKs use that separate certificate; addits fingerprint to production associations before testing Play-installed links.+### Production release APKs++`.github/workflows/release-production.yml` builds an ARM64 signed APK alongside+each production deployment, from the release commit. It uses production services,+the pinned production Firebase config, and the normal OTA-enabled release build.+The GitHub Actions `ANDROID_RELEASE_DOPPLER_TOKEN` secret must have read access to+`android-release/prd`, including both the signing JSON and pinned Firebase secret.+CI passes this dedicated read-only service token as `DOPPLER_TOKEN` only during+configuration retrieval. Signing files live in the runner's temporary directory+and are removed even when the build fails; only APK/checksum files are uploaded.++Release tags must follow `vYYYY.M.D.N`, with a valid date, years 2000–2099, and a+daily revision from 0–99. Android's `versionCode` is `YYYYMMDDNN` (for example,+`v2026.9.28.1` becomes `2026092801`), and `versionName` is `2026.9.28-1`.+New releases must increase the date/revision; a rerun retains the same version.+Always keep the signing key to allow upgrades over earlier distributed APKs.++Before upload, CI verifies the signing certificate, package/version, ARM64 ABI,+non-debuggable manifest, and 16 KiB ZIP alignment. Publishing waits for the web,+cloud-storage, sync-service, and AI editing worker deployments. Android failures+fail their job without blocking web/backend rollout. CI verification does not+replace the device qualification described above.++The public GitHub release receives `macro-<tag>-android-arm64.apk` and+`macro-<tag>-android-arm64.apk.sha256`. Share the APK's release download link;+recipients do not need GitHub access. They open the downloaded APK and allow+installation from that browser/file manager when Android prompts. Subsequent+APKs install as updates when the certificate matches and the version increases.+Play Store migration must preserve app-signing compatibility with these APKs.+## FirebaseThe launcher fetches Firebase configuration before both development and releasediff --git a/rust-toolchain.toml b/rust-toolchain.tomlindex 36e8e39bef..ba277d9173 100644--- a/rust-toolchain.toml+++ b/rust-toolchain.toml@@ -20,4 +20,6 @@ targets = [# installing it from a CI step would appear to succeed and then fail at link# time."aarch64-apple-ios-sim",+ # Signed Android APKs in the production release workflow.+ "aarch64-linux-android",]