Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix: improve Android note actions and release signing

tianma-if53c757c0b84f
diff --git a/.github/workflows/mobile-build.yml b/.github/workflows/mobile-build.yml
index 4128cb50..310ca0f0 100644
--- a/.github/workflows/mobile-build.yml
+++ b/.github/workflows/mobile-build.yml
@@ -20,6 +20,7 @@ on:
- ".github/workflows/mobile-build.yml"
- "scripts/build-android-local.sh"
- "scripts/verify-android-apk-signature.mjs"
+ - "scripts/download-play-universal-apk.mjs"
permissions:
actions: read
@@ -123,6 +124,7 @@ jobs:
- name: Verify existing APK uses the pinned signer
if: steps.plan.outputs.asset_ready == 'true'
env:
+ EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: 22bf52a9501c89020f5acc966960152c826bfa64f31e578e858d088f8cd75d87,${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
CURRENT_TAG: ${{ inputs.release_tag || github.event.release.tag_name }}
GH_TOKEN: ${{ github.token }}
run: |
@@ -154,6 +156,7 @@ jobs:
- name: Copy latest compatible APK without renaming
env:
CURRENT_TAG: ${{ inputs.release_tag || github.event.release.tag_name }}
+ EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: 22bf52a9501c89020f5acc966960152c826bfa64f31e578e858d088f8cd75d87,${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
GH_TOKEN: ${{ github.token }}
PREVIOUS_TAG: ${{ needs.release-plan.outputs.previous_tag }}
run: |
@@ -243,6 +246,8 @@ jobs:
- name: Verify release APK signature
if: github.event_name == 'workflow_dispatch'
+ env:
+ EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: 22bf52a9501c89020f5acc966960152c826bfa64f31e578e858d088f8cd75d87,${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
run: node scripts/verify-android-apk-signature.mjs apps/mobile/android/app/build/outputs/apk/release/app-release.apk
- name: Upload APK
diff --git a/.github/workflows/store-delivery.yml b/.github/workflows/store-delivery.yml
index f39cd552..1c7cd37e 100644
--- a/.github/workflows/store-delivery.yml
+++ b/.github/workflows/store-delivery.yml
@@ -28,7 +28,7 @@ on:
- internal
permissions:
- contents: read
+ contents: write
concurrency:
group: edgeever-store-delivery-${{ inputs.release_tag }}
@@ -134,6 +134,9 @@ jobs:
packager: npm
token: ${{ secrets.EXPO_TOKEN }}
+ - name: Install dependencies
+ run: bun install --frozen-lockfile
+
- name: Restore Android upload keystore
env:
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
@@ -174,6 +177,28 @@ jobs:
--wait
working-directory: apps/mobile
+ - name: Download Play-signed universal APK
+ env:
+ ANDROID_PLAY_APP_SIGNER_SHA256: ${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
+ GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_BASE64: ${{ secrets.GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_BASE64 }}
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ VERSION_CODE: ${{ needs.plan.outputs.version_code }}
+ run: |
+ apk_path="$RUNNER_TEMP/edgeever-android-${RELEASE_TAG}-arm64-v8a.apk"
+ node scripts/download-play-universal-apk.mjs "$VERSION_CODE" "$apk_path"
+ echo "apk_path=$apk_path" >> "$GITHUB_ENV"
+
+ - name: Verify Play app signature
+ env:
+ EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256: ${{ secrets.ANDROID_PLAY_APP_SIGNER_SHA256 }}
+ run: node scripts/verify-android-apk-signature.mjs "$apk_path"
+
+ - name: Replace GitHub Release APK with the Play-signed build
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ inputs.release_tag }}
+ run: gh release upload "$RELEASE_TAG" "$apk_path" --repo "$GITHUB_REPOSITORY" --clobber
+
- name: Remove temporary upload keystore
if: always()
run: rm -f "$RUNNER_TEMP/edgeever-upload.p12"
diff --git a/apps/mobile/src/lib/mobile-memo-delete.test.ts b/apps/mobile/src/lib/mobile-memo-delete.test.ts
index 51d520af..4ccee714 100644
--- a/apps/mobile/src/lib/mobile-memo-delete.test.ts
+++ b/apps/mobile/src/lib/mobile-memo-delete.test.ts
@@ -35,6 +35,9 @@ mock.module("./local-mirror", () => ({
memos.set(memoId, { ...memo, isDeleted: true });
return true;
},
+ upsertLocalMemo: async (_scope: string, memo: { id: string; isDeleted?: boolean }) => {
+ memos.set(memo.id, memo);
+ },
}));
const {
@@ -137,3 +140,55 @@ test("resolves remapped temporary ids to remote deletes", async () => {
expect(deletedMemoIds).toEqual(["memo-mapped"]);
expect(memos.get("memo-mapped")?.isDeleted).toBe(true);
});
+
+test("updates the local mirror before the remote delete completes", async () => {
+ const scope = "https://one.example";
+ memos.set("memo-1", { id: "memo-1" });
+ let releaseDelete: (() => void) | undefined;
+ const remoteDelete = new Promise<void>((resolve) => {
+ releaseDelete = resolve;
+ });
+
+ const deletion = deleteMobileMemos({
+ client: {
+ deleteMemo: async () => {
+ await remoteDelete;
+ return { ok: true as const };
+ },
+ deleteMemos: async () => {
+ throw new Error("should use single delete");
+ },
+ } as never,
+ dataScope: scope,
+ syncQueueScope: scope,
+ memoIds: ["memo-1"],
+ permanent: false,
+ });
+
+ await Bun.sleep(0);
+ expect(memos.get("memo-1")?.isDeleted).toBe(true);
+ releaseDelete?.();
+ await deletion;
+});
+
+test("rolls the local mirror back when the remote delete fails", async () => {
+ const scope = "https://one.example";
+ memos.set("memo-1", { id: "memo-1" });
+
+ await expect(deleteMobileMemos({
+ client: {
+ deleteMemo: async () => {
+ throw new Error("network unavailable");
+ },
+ deleteMemos: async () => {
+ throw new Error("should use single delete");
+ },
+ } as never,
+ dataScope: scope,
+ syncQueueScope: scope,
+ memoIds: ["memo-1"],
+ permanent: false,
+ })).rejects.toThrow("network unavailable");
+
+ expect(memos.get("memo-1")).toEqual({ id: "memo-1" });
+});
diff --git a/apps/mobile/src/lib/mobile-memo-delete.ts b/apps/mobile/src/lib/mobile-memo-delete.ts
index 36efa411..9bd7120f 100644
--- a/apps/mobile/src/lib/mobile-memo-delete.ts
+++ b/apps/mobile/src/lib/mobile-memo-delete.ts
@@ -1,6 +1,6 @@
import type { createEdgeEverClient } from "@edgeever/client";
import { clearMobileMemoDraft } from "./mobile-drafts";
-import { deleteLocalMemo, resolveLocalMemo, softDeleteLocalMemo } from "./local-mirror";
+import { deleteLocalMemo, resolveLocalMemo, softDeleteLocalMemo, upsertLocalMemo } from "./local-mirror";
import { cancelMobileMemoQueueItems, listMobileSyncQueueItems } from "./sync-queue";
type MobileClient = ReturnType<typeof createEdgeEverClient>;
@@ -67,21 +67,26 @@ export const deleteMobileMemos = async ({
if (!client) {
throw new Error("当前无法连接实例,请稍后重试");
}
- if (uniqueRemoteIds.length === 1) {
- await client.deleteMemo(uniqueRemoteIds[0]!, { permanent });
- } else {
- await client.deleteMemos({ memoIds: uniqueRemoteIds, permanent });
- }
+ const originalMemos = new Map(
+ (await Promise.all(uniqueRemoteIds.map(async (memoId) => [memoId, await resolveLocalMemo(dataScope, memoId)] as const)))
+ .filter((entry): entry is readonly [string, NonNullable<typeof entry[1]>] => Boolean(entry[1]))
+ );
await Promise.all(
- uniqueRemoteIds.map(async (memoId) => {
- if (permanent) {
- await deleteLocalMemo(dataScope, memoId);
- } else {
- await softDeleteLocalMemo(dataScope, memoId);
- }
- await clearMobileMemoDraft(memoId);
- })
+ uniqueRemoteIds.map((memoId) => permanent
+ ? deleteLocalMemo(dataScope, memoId)
+ : softDeleteLocalMemo(dataScope, memoId))
);
+ try {
+ if (uniqueRemoteIds.length === 1) {
+ await client.deleteMemo(uniqueRemoteIds[0]!, { permanent });
+ } else {
+ await client.deleteMemos({ memoIds: uniqueRemoteIds, permanent });
+ }
+ } catch (error) {
+ await Promise.all(Array.from(originalMemos.values()).map((memo) => upsertLocalMemo(dataScope, memo)));
+ throw error;
+ }
+ await Promise.all(uniqueRemoteIds.map((memoId) => clearMobileMemoDraft(memoId)));
}
return {
diff --git a/apps/mobile/src/lib/mobile-memo-list-cache.test.ts b/apps/mobile/src/lib/mobile-memo-list-cache.test.ts
new file mode 100644
index 00000000..c5c6eb86
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-memo-list-cache.test.ts
@@ -0,0 +1,35 @@
+import { expect, test } from "bun:test";
+import type { ListMemosResponse } from "@edgeever/client";
+import type { InfiniteData } from "@tanstack/react-query";
+import { removeMobileMemosFromListCache } from "./mobile-memo-list-cache";
+
+const createPage = (ids: string[], totalCount: number): ListMemosResponse => ({
+ memos: ids.map((id) => ({ id }) as ListMemosResponse["memos"][number]),
+ nextCursor: null,
+ totalCount,
+});
+
+test("removes selected memos from paged mobile list caches immediately", () => {
+ const current: InfiniteData<ListMemosResponse> = {
+ pageParams: [0, 2],
+ pages: [createPage(["memo-1", "memo-2"], 3), createPage(["memo-3"], 3)],
+ };
+
+ const next = removeMobileMemosFromListCache(current, new Set(["memo-2"]));
+
+ expect(next?.pages.map((page) => page.memos.map((memo) => memo.id))).toEqual([
+ ["memo-1"],
+ ["memo-3"],
+ ]);
+ expect(next?.pages.map((page) => page.totalCount)).toEqual([2, 2]);
+ expect(current.pages[0]?.memos.map((memo) => memo.id)).toEqual(["memo-1", "memo-2"]);
+});
+
+test("preserves cache identity when none of the memo ids are present", () => {
+ const current: InfiniteData<ListMemosResponse> = {
+ pageParams: [0],
+ pages: [createPage(["memo-1"], 1)],
+ };
+
+ expect(removeMobileMemosFromListCache(current, new Set(["missing"]))).toBe(current);
+});
diff --git a/apps/mobile/src/lib/mobile-memo-list-cache.ts b/apps/mobile/src/lib/mobile-memo-list-cache.ts
new file mode 100644
index 00000000..944a716a
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-memo-list-cache.ts
@@ -0,0 +1,25 @@
+import type { ListMemosResponse } from "@edgeever/client";
+import type { InfiniteData } from "@tanstack/react-query";
+
+export const removeMobileMemosFromListCache = (
+ current: InfiniteData<ListMemosResponse> | undefined,
+ memoIds: ReadonlySet<string>
+): InfiniteData<ListMemosResponse> | undefined => {
+ if (!current || memoIds.size === 0) {
+ return current;
+ }
+
+ const removedIds = new Set(
+ current.pages.flatMap((page) => page.memos.map((memo) => memo.id)).filter((memoId) => memoIds.has(memoId))
+ );
+ if (removedIds.size === 0) {
+ return current;
+ }
+ const pages = current.pages.map((page) => ({
+ ...page,
+ memos: page.memos.filter((memo) => !removedIds.has(memo.id)),
+ totalCount: Math.max(0, page.totalCount - removedIds.size),
+ }));
+
+ return { ...current, pages };
+};
diff --git a/apps/mobile/src/screens/WorkspaceNotesView.tsx b/apps/mobile/src/screens/WorkspaceNotesView.tsx
index 3835ff09..40fd6ff4 100644
--- a/apps/mobile/src/screens/WorkspaceNotesView.tsx
+++ b/apps/mobile/src/screens/WorkspaceNotesView.tsx
@@ -1,4 +1,4 @@
-import { memo, type ReactNode } from "react";
+import { memo, useRef, type ReactNode } from "react";
import type { MemoFilterMode } from "@edgeever/client";
import { DEFAULT_MEMO_TITLE, type MemoSummary, type Notebook } from "@edgeever/shared";
import { MOBILE_UI_METRICS, toggleMobileMemoFilterMode } from "@edgeever/shared/mobile-ui";
@@ -419,6 +419,7 @@ const MemoCard = memo(function MemoCard({
}) {
const localePreference = useMobileLocale().preference;
const memoTitle = memo.title?.trim() || DEFAULT_MEMO_TITLE;
+ const handledLongPressRef = useRef(false);
const pressScale = useSharedValue(1);
const pressAnimatedStyle = useAnimatedStyle(() => ({
transform: [{ scale: pressScale.value }],
@@ -453,8 +454,17 @@ const MemoCard = memo(function MemoCard({
accessibilityLabel={memoTitle}
accessibilityRole="button"
delayLongPress={520}
- onLongPress={onLongPress}
- onPress={onPress}
+ onLongPress={() => {
+ handledLongPressRef.current = true;
+ onLongPress?.();
+ }}
+ onPress={() => {
+ if (handledLongPressRef.current) {
+ handledLongPressRef.current = false;
+ return;
+ }
+ onPress();
+ }}
onPressIn={() => {
pressScale.value = withTiming(0.985, { duration: 100 });
}}
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index b2c29d42..a74a257a 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -1,9 +1,9 @@
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
-import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type UseMutationResult } from "@tanstack/react-query";
+import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData, type QueryKey, type UseMutationResult } from "@tanstack/react-query";
import * as Clipboard from "expo-clipboard";
import Constants from "expo-constants";
import { File as ExpoFile } from "expo-file-system";
-import type { MemoFilterMode, MemoSortMode } from "@edgeever/client";
+import type { ListMemosResponse, MemoFilterMode, MemoSortMode } from "@edgeever/client";
import {
ActivityIndicator,
BookOpen,
@@ -99,6 +99,7 @@ import {
type MobileSyncQueueItem,
} from "../lib/sync-queue";
import { deleteMobileMemos } from "../lib/mobile-memo-delete";
+import { removeMobileMemosFromListCache } from "../lib/mobile-memo-list-cache";
import {
createMobileDataScope,
getLocalMemo,
@@ -222,6 +223,7 @@ type RichEditingSession = {
memo: MemoDetail;
};
type MobileMemoUpdateMutation = UseMutationResult<MemoDetail, Error, { memo: MemoDetail; payload: MobileMemoUpdatePayload }>;
+type MobileMemoListCacheSnapshot = Array<[QueryKey, InfiniteData<ListMemosResponse> | undefined]>;
export const WorkspaceScreen = ({
incomingShareError = null,
@@ -864,6 +866,30 @@ export const WorkspaceScreen = ({
void writeMobileImageCompressionEnabled(enabled);
};
+ const optimisticallyRemoveMemoIds = async (memoIds: string[]): Promise<MobileMemoListCacheSnapshot> => {
+ const queryKeys: QueryKey[] = [
+ ["mobile", "memos"],
+ ["mobile", "search"],
+ ];
+ await Promise.all(queryKeys.map((queryKey) => queryClient.cancelQueries({ queryKey })));
+ const snapshot = queryKeys.flatMap((queryKey) =>
+ queryClient.getQueriesData<InfiniteData<ListMemosResponse>>({ queryKey })
+ );
+ const memoIdSet = new Set(memoIds);
+ for (const queryKey of queryKeys) {
+ queryClient.setQueriesData<InfiniteData<ListMemosResponse>>({ queryKey }, (current) =>
+ removeMobileMemosFromListCache(current, memoIdSet)
+ );
+ }
+ return snapshot;
+ };
+
+ const restoreMemoListCache = (snapshot: MobileMemoListCacheSnapshot | undefined) => {
+ for (const [queryKey, data] of snapshot ?? []) {
+ queryClient.setQueryData(queryKey, data);
+ }
+ };
+
const invalidateWorkspace = async () => {
if (client) {
await syncMobileLocalMirror(client, dataScope);
@@ -997,6 +1023,12 @@ export const WorkspaceScreen = ({
};
const deleteMemoMutation = useMutation({
+ onMutate: async ({ memo }) => {
+ const cacheSnapshot = await optimisticallyRemoveMemoIds([memo.id]);
+ const reopenMemoId = selectedMemoId === memo.id ? memo.id : null;
+ setSelectedMemoId(null);
+ return { cacheSnapshot, reopenMemoId };
+ },
mutationFn: async ({ memo, permanent }: { memo: MemoDetail; permanent: boolean }) => {
await deleteMobileMemos({
client,
@@ -1013,7 +1045,11 @@ export const WorkspaceScreen = ({
setRichEditingSession(null);
setSelectedMemoId(null);
},
- onError: (error) => {
+ onError: (error, _variables, context) => {
+ restoreMemoListCache(context?.cacheSnapshot);
+ if (context?.reopenMemoId) {
+ setSelectedMemoId(context.reopenMemoId);
+ }
Alert.alert("删除失败", error instanceof Error ? error.message : "请检查网络后重试");
},
});
@@ -1083,6 +1119,13 @@ export const WorkspaceScreen = ({
});
const deleteMemosMutation = useMutation({
+ onMutate: async ({ memoIds }) => {
+ const cacheSnapshot = await optimisticallyRemoveMemoIds(memoIds);
+ const previousSelectionMode = selectionMode;
+ const previousSelectedMemoIds = new Set(selectedMemoIds);
+ clearSelection();
+ return { cacheSnapshot, previousSelectionMode, previousSelectedMemoIds };
+ },
mutationFn: async ({ memoIds, permanent }: { memoIds: string[]; permanent: boolean }) => {
const result = await deleteMobileMemos({
client,
@@ -1098,7 +1141,10 @@ export const WorkspaceScreen = ({
await invalidateWorkspace();
clearSelection();
},
- onError: (error) => {
+ onError: (error, _variables, context) => {
+ restoreMemoListCache(context?.cacheSnapshot);
+ setSelectionMode(context?.previousSelectionMode ?? false);
+ setSelectedMemoIds(context?.previousSelectedMemoIds ?? new Set());
Alert.alert("删除失败", error instanceof Error ? error.message : "请检查网络后重试");
},
});
diff --git a/bun.lock b/bun.lock
index c7ab6afd..29bd0a09 100644
--- a/bun.lock
+++ b/bun.lock
@@ -71,6 +71,7 @@
"concurrently": "latest",
"esbuild": "0.28.1",
"fake-indexeddb": "^6.2.5",
+ "google-auth-library": "^11.0.2",
"postcss": "latest",
"tailwindcss": "^3.4.17",
"typescript": "latest",
@@ -85,7 +86,7 @@
},
"apps/desktop": {
"name": "@edgeever/desktop",
- "version": "1.23.0",
+ "version": "1.23.1",
"dependencies": {
"electron-updater": "^6.6.2",
},
@@ -1605,6 +1606,8 @@
"big-integer": ["[email protected]", "", {}, "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg=="],
+ "bignumber.js": ["[email protected]", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],
+
"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],
"blake3-wasm": ["[email protected]", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="],
@@ -2291,6 +2294,10 @@
"fx-runner": ["[email protected]", "", { "dependencies": { "commander": "^12.1.0", "shell-quote": "1.8.4", "which": "^4.0.0", "winreg": "0.0.12" }, "bin": { "fx-runner": "bin/fx-runner" } }, "sha512-EstfdRQu04tM+SXR3pBmc0+GYKZj9FMHAvA8XAbKPzTvUeHP0v1/F3aQ10bG7EluR6phvFqsvn5Z7SvYJsEgNw=="],
+ "gaxios": ["[email protected]", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2" } }, "sha512-kB3rzJV7d9juLZh8/56QTXCwQfxyhdOMdyYk1HdQKFtF8TJTDTZQJtixWIwXdE9Jji91mC41DUNpjleo4L4eAQ=="],
+
+ "gcp-metadata": ["[email protected]", "", { "dependencies": { "gaxios": "^7.1.3", "google-logging-utils": "^2.0.0", "json-bigint": "^1.0.0" } }, "sha512-2YYnIlHaKBGT2IPg3G2M57hia9Galz15zsEOvw9T3oRf0lSn6KN6VcHQLqby7x8ksYKnjXvp3rp2KJyLCN6zfQ=="],
+
"generator-function": ["[email protected]", "", {}, "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g=="],
"gensync": ["[email protected]", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
@@ -2327,6 +2334,10 @@
"globalthis": ["[email protected]", "", { "dependencies": { "define-properties": "^1.2.1", "gopd": "^1.0.1" } }, "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ=="],
+ "google-auth-library": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.1.4", "gcp-metadata": "^9.0.0", "google-logging-utils": "^2.0.0", "jws": "^4.0.0" } }, "sha512-vzpgPutxrghPsnjrjpzLX2bdv8IOL719Rh0oEjGnQu8YCIbnbMuTTQ5zU9LcKvLdOPgCxBwppbvnhgW90Qna5Q=="],
+
+ "google-logging-utils": ["[email protected]", "", {}, "sha512-HMhaQghlOTvbcb3c4T5jmmOMtG3JUF1iOQMezaJXL86CDS+Tm2vHd0IeLFRAx3+ewd+bo9E1HFHoy17X5aJa9A=="],
+
"gopd": ["[email protected]", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"got": ["[email protected]", "", { "dependencies": { "@sindresorhus/is": "^4.0.0", "@szmarczak/http-timer": "^4.0.5", "@types/cacheable-request": "^6.0.1", "@types/responselike": "^1.0.0", "cacheable-lookup": "^5.0.3", "cacheable-request": "^7.0.2", "decompress-response": "^6.0.0", "http2-wrapper": "^1.0.0-beta.5.2", "lowercase-keys": "^2.0.0", "p-cancelable": "^2.0.0", "responselike": "^2.0.0" } }, "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g=="],
@@ -2581,6 +2592,8 @@
"jsesc": ["[email protected]", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
+ "json-bigint": ["[email protected]", "", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="],
+
"json-buffer": ["[email protected]", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
"json-merge-patch": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3" } }, "sha512-M6Vp2GN9L7cfuMXiWOmHj9bEFbeC250iVtcKQbqVgEsDVYnIsrNsbU+h/Y/PkbBQCtEa4Bez+Ebv0zfbC8ObLg=="],
@@ -3407,7 +3420,7 @@
"safe-array-concat": ["[email protected]", "", { "dependencies": { "call-bind": "^1.0.9", "call-bound": "^1.0.4", "get-intrinsic": "^1.3.0", "has-symbols": "^1.1.0", "isarray": "^2.0.5" } }, "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg=="],
- "safe-buffer": ["[email protected]", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
+ "safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"safe-push-apply": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "isarray": "^2.0.5" } }, "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA=="],
@@ -4243,8 +4256,6 @@
"compression/negotiator": ["[email protected]", "", {}, "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w=="],
- "compression/safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
-
"config-chain/ini": ["[email protected]", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="],
"connect/debug": ["[email protected]", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="],
@@ -4269,8 +4280,6 @@
"dom-serializer/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
- "ecdsa-sig-formatter/safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
-
"electron/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],
"electron-builder/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
@@ -4367,10 +4376,6 @@
"jest-worker/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],
- "jwa/safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
-
- "jws/safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
-
"katex/commander": ["[email protected]", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="],
"log-symbols/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ=="],
@@ -4459,6 +4464,8 @@
"react-native-web/memoize-one": ["[email protected]", "", {}, "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw=="],
+ "readable-stream/safe-buffer": ["[email protected]", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
+
"readdirp/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
"roarr/sprintf-js": ["[email protected]", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="],
@@ -4483,6 +4490,8 @@
"stacktrace-parser/type-fest": ["[email protected]", "", {}, "sha512-Ne2YiiGN8bmrmJJEuTWTLJR32nh/JdL1+PSicowtNb0WFpn59GK8/lfD61bVtzguz7b3PBt74nxpv/Pw5po5Rg=="],
+ "string_decoder/safe-buffer": ["[email protected]", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
+
"strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
"sucrase/commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],
diff --git a/docs/mobile-build.md b/docs/mobile-build.md
index 021b764a..e9c76d04 100644
--- a/docs/mobile-build.md
+++ b/docs/mobile-build.md
@@ -74,6 +74,15 @@ audited range includes mobile runtime code, shared mobile packages,
dependencies, native configuration, Android build tooling, or signer
verification.
+This locally signed APK prepares the Draft without requiring a Google Play
+submission. After the matching AAB is delivered, the store-delivery workflow
+downloads Google Play's signed universal APK and replaces the GitHub Release
+asset under the established filename. The Play-generated APK supports arm64
+and may contain additional ABIs; publishing it is the explicit compatibility
+exception that lets Play and GitHub installations update each other without
+uninstalling the app. The workflow pins and verifies the Play app-signing
+certificate before replacing the asset.
+
### Recommended local Play build
Routine Google Play bundles should be built on the release Mac instead of in
@@ -114,7 +123,8 @@ The GitHub Release workflow never builds or uploads a Play bundle. After a
formal Release that contains mobile changes is published, use the separate
store-delivery workflow. It builds a signed AAB from the immutable Release tag,
preserves the AAB and R8 mapping as Actions artifacts, and uploads the bundle
-through EAS Submit. See [Mobile Store Delivery](store-delivery.md).
+through EAS Submit. It then replaces the GitHub APK with the Play-signed
+universal APK. See [Mobile Store Delivery](store-delivery.md).
The upload keystore is only used to prove ownership when uploading bundles;
Google Play App Signing manages the app signing key delivered to users. Keep an
diff --git a/docs/store-delivery.md b/docs/store-delivery.md
index 8218b6b8..3e8d0213 100644
--- a/docs/store-delivery.md
+++ b/docs/store-delivery.md
@@ -34,14 +34,19 @@ Configure these GitHub repository secrets:
- `ANDROID_KEYSTORE_PASSWORD`
- `ANDROID_KEY_ALIAS`
- `ANDROID_KEY_PASSWORD`
+- `ANDROID_PLAY_APP_SIGNER_SHA256`
+- `GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_BASE64`
- `APP_STORE_CONNECT_API_KEY_ID`
- `APP_STORE_CONNECT_API_ISSUER_ID`
- `APP_STORE_CONNECT_API_KEY_P8_BASE64`
Upload the Google Play service-account key to the Android application's EAS
-Submit credentials. Configure the iOS distribution credentials and App Store
-Connect API key in EAS. Credentials and private keys must remain outside the
-repository.
+Submit credentials, and store the same service-account JSON as base64 in the
+repository secret listed above. Copy the SHA-256 fingerprint of the **app
+signing certificate** (not the upload certificate) from Play Console into
+`ANDROID_PLAY_APP_SIGNER_SHA256`. Configure the iOS distribution credentials
+and App Store Connect API key in EAS. Credentials and private keys must remain
+outside the repository.
Create these GitHub Environments:
@@ -81,6 +86,13 @@ The self-hosted release runner builds a signed AAB from the selected tag,
verifies its signature and R8 mapping, preserves both as GitHub Actions
artifacts, and uploads the AAB through EAS Submit.
+After Google Play finishes processing the bundle, the workflow downloads the
+Play-signed universal APK, verifies the pinned app-signing certificate, and
+replaces the GitHub Release Android asset. This makes installations from
+Google Play and GitHub mutually updateable. The established `arm64-v8a` asset
+name is retained for release compatibility; the Play-generated universal APK
+supports arm64 and can include additional ABIs.
+
Internal, Alpha, Beta, and Production profiles use a completed release on the
selected track. The default command targets Production; use
`--android-track internal`, `alpha`, or `beta` only when a testing delivery is
diff --git a/docs/store-delivery.zh-CN.md b/docs/store-delivery.zh-CN.md
index 16c36aa1..f596fdb0 100644
--- a/docs/store-delivery.zh-CN.md
+++ b/docs/store-delivery.zh-CN.md
@@ -32,13 +32,17 @@ GitHub Release 与移动端商店交付是两个独立操作:
- `ANDROID_KEYSTORE_PASSWORD`
- `ANDROID_KEY_ALIAS`
- `ANDROID_KEY_PASSWORD`
+- `ANDROID_PLAY_APP_SIGNER_SHA256`
+- `GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_BASE64`
- `APP_STORE_CONNECT_API_KEY_ID`
- `APP_STORE_CONNECT_API_ISSUER_ID`
- `APP_STORE_CONNECT_API_KEY_P8_BASE64`
-将 Google Play 服务账号密钥上传到 Android 应用的 EAS Submit Credentials。
-在 EAS 中配置 iOS 分发凭据和 App Store Connect API Key。凭据和私钥禁止提交
-到仓库。
+将 Google Play 服务账号密钥上传到 Android 应用的 EAS Submit Credentials,
+同时将同一份服务账号 JSON 以 base64 保存到上述仓库 Secret,并把 Play Console
+中的**应用签名证书**(不是上传证书)SHA-256 指纹保存为
+`ANDROID_PLAY_APP_SIGNER_SHA256`。在 EAS 中配置 iOS 分发凭据和 App Store
+Connect API Key。凭据和私钥禁止提交到仓库。
创建以下 GitHub Environments:
@@ -76,6 +80,11 @@ bun run publish:stores -- \
自托管发布 Runner 会从指定 tag 构建签名 AAB,验证签名和 R8 Mapping,将两者
保留为 GitHub Actions Artifacts,然后通过 EAS Submit 上传 AAB。
+Google Play 处理完 AAB 后,工作流会下载由 Play 应用签名密钥签名的通用 APK,
+核对固定的应用签名证书,并替换 GitHub Release 中的 Android 资产。这样从 Play
+和 GitHub 安装的版本可以互相覆盖升级。为保持 Release 兼容性,资产继续沿用
+`arm64-v8a` 文件名;Play 生成的通用 APK 支持 arm64,也可能包含其他 ABI。
+
Internal、Alpha、Beta 和 Production 配置都会在所选轨道创建 Completed
Release。默认命令直接使用 Production;只有明确要求测试交付时才使用
`--android-track internal`、`alpha` 或 `beta`。
diff --git a/package.json b/package.json
index e477eff8..7dc1f810 100644
--- a/package.json
+++ b/package.json
@@ -52,7 +52,7 @@
"build:desktop": "EDGE_EVER_DESKTOP_BUILD=1 bun run prepare:desktop:icons && bun run build:web && bun run build:desktop:sidecar && bun run --cwd apps/desktop dist",
"benchmark:desktop:sidecar": "bun scripts/benchmark-desktop-sidecar.mjs",
"verify:web-performance": "bun scripts/verify-web-performance.mjs",
- "test:release-planning": "bun test scripts/plan-native-release.test.mjs scripts/check-native-release-assets.test.mjs scripts/create-mac-update-metadata.test.mjs scripts/desktop-build-workflow.test.mjs scripts/report-native-build-timings.test.mjs scripts/release.test.mjs scripts/validate-store-delivery.test.mjs scripts/store-delivery.test.mjs scripts/verify-android-apk-signature.test.mjs scripts/desktop-icns.test.mjs scripts/preview-macos-dock-icon.test.mjs apps/web/src/lib/version-check.test.mjs apps/mobile/src/lib/mobile-release.test.ts",
+ "test:release-planning": "bun test scripts/plan-native-release.test.mjs scripts/check-native-release-assets.test.mjs scripts/create-mac-update-metadata.test.mjs scripts/desktop-build-workflow.test.mjs scripts/report-native-build-timings.test.mjs scripts/release.test.mjs scripts/validate-store-delivery.test.mjs scripts/store-delivery.test.mjs scripts/download-play-universal-apk.test.mjs scripts/verify-android-apk-signature.test.mjs scripts/desktop-icns.test.mjs scripts/preview-macos-dock-icon.test.mjs apps/web/src/lib/version-check.test.mjs apps/mobile/src/lib/mobile-release.test.ts",
"release": "bun scripts/release.mjs",
"publish:stores": "bun scripts/store-delivery.mjs",
"test:desktop:sidecar": "bun scripts/test-desktop-sidecar.mjs",
@@ -178,6 +178,7 @@
"concurrently": "latest",
"esbuild": "0.28.1",
"fake-indexeddb": "^6.2.5",
+ "google-auth-library": "^11.0.2",
"postcss": "latest",
"tailwindcss": "^3.4.17",
"typescript": "latest",
diff --git a/scripts/download-play-universal-apk.mjs b/scripts/download-play-universal-apk.mjs
new file mode 100644
index 00000000..fa7f2068
--- /dev/null
+++ b/scripts/download-play-universal-apk.mjs
@@ -0,0 +1,165 @@
+import { createWriteStream } from "node:fs";
+import { open } from "node:fs/promises";
+import { resolve } from "node:path";
+import { Readable } from "node:stream";
+import { pipeline } from "node:stream/promises";
+import { fileURLToPath } from "node:url";
+import { GoogleAuth } from "google-auth-library";
+
+const ANDROID_PUBLISHER_SCOPE = "https://www.googleapis.com/auth/androidpublisher";
+const DEFAULT_PACKAGE_NAME = "org.edgeever.mobile";
+const DEFAULT_POLL_ATTEMPTS = 30;
+const DEFAULT_POLL_INTERVAL_MS = 10_000;
+const DEFAULT_DOWNLOAD_TIMEOUT_MS = 10 * 60_000;
+const LOOKUP_TIMEOUT_MS = 30_000;
+
+export const normalizePlayCertificateHash = (value) => {
+ const compact = String(value ?? "").trim();
+ const hex = compact.toLowerCase().replace(/[^0-9a-f]/g, "");
+ if (hex.length === 64 && /^[0-9a-f]{64}$/.test(hex)) {
+ return hex;
+ }
+ try {
+ const decoded = Buffer.from(compact.replace(/-/g, "+").replace(/_/g, "/"), "base64");
+ return decoded.length === 32 ? decoded.toString("hex") : "";
+ } catch {
+ return "";
+ }
+};
+
+export const selectPlayUniversalApk = (response, expectedSignerSha256) => {
+ const expectedSigner = normalizePlayCertificateHash(expectedSignerSha256);
+ if (!expectedSigner) {
+ throw new Error("ANDROID_PLAY_APP_SIGNER_SHA256 must be a SHA-256 certificate fingerprint.");
+ }
+ const candidates = (response?.generatedApks ?? []).filter((candidate) =>
+ normalizePlayCertificateHash(candidate.certificateSha256Hash) === expectedSigner &&
+ candidate.generatedUniversalApk?.downloadId
+ );
+ if (candidates.length !== 1) {
+ throw new Error(`Expected one Play universal APK for signer ${expectedSigner}, found ${candidates.length}.`);
+ }
+ return {
+ downloadId: candidates[0].generatedUniversalApk.downloadId,
+ signerSha256: expectedSigner,
+ };
+};
+
+export const assertDownloadedApk = (buffer) => {
+ if (
+ !Buffer.isBuffer(buffer) ||
+ buffer.length < 4 ||
+ buffer[0] !== 0x50 ||
+ buffer[1] !== 0x4b
+ ) {
+ throw new Error("Google Play universal APK download was empty or not a ZIP archive.");
+ }
+ return buffer;
+};
+
+const getServiceAccountCredentials = () => {
+ const encoded = process.env.GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_BASE64?.trim();
+ if (!encoded) {
+ throw new Error("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_BASE64 is required.");
+ }
+ try {
+ return JSON.parse(Buffer.from(encoded, "base64").toString("utf8"));
+ } catch {
+ throw new Error("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_BASE64 is not valid base64-encoded JSON.");
+ }
+};
+
+const requestHeaders = async () => {
+ const auth = new GoogleAuth({
+ credentials: getServiceAccountCredentials(),
+ scopes: [ANDROID_PUBLISHER_SCOPE],
+ });
+ const client = await auth.getClient();
+ return client.getRequestHeaders();
+};
+
+const wait = (milliseconds) => new Promise((resolveWait) => setTimeout(resolveWait, milliseconds));
+
+export const downloadPlayUniversalApk = async ({
+ downloadTimeoutMs = DEFAULT_DOWNLOAD_TIMEOUT_MS,
+ expectedSignerSha256,
+ outputPath,
+ packageName = DEFAULT_PACKAGE_NAME,
+ pollAttempts = DEFAULT_POLL_ATTEMPTS,
+ pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
+ versionCode,
+}) => {
+ if (!Number.isSafeInteger(versionCode) || versionCode <= 0) {
+ throw new Error("versionCode must be a positive integer.");
+ }
+ const headers = await requestHeaders();
+ const baseUrl = `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${encodeURIComponent(packageName)}/generatedApks/${versionCode}`;
+ let selected = null;
+ let lastError = null;
+ for (let attempt = 1; attempt <= pollAttempts; attempt += 1) {
+ const response = await fetch(baseUrl, {
+ headers,
+ signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),
+ });
+ if (response.ok) {
+ const body = await response.json();
+ try {
+ selected = selectPlayUniversalApk(body, expectedSignerSha256);
+ break;
+ } catch (error) {
+ lastError = error;
+ }
+ } else {
+ lastError = new Error(`Google Play generated APK lookup failed with HTTP ${response.status}: ${await response.text()}`);
+ }
+ if (attempt < pollAttempts) {
+ await wait(pollIntervalMs);
+ }
+ }
+ if (!selected) {
+ throw lastError ?? new Error("Google Play did not produce a universal APK before the timeout.");
+ }
+ const downloadUrl = `${baseUrl}/downloads/${encodeURIComponent(selected.downloadId)}:download?alt=media`;
+ const downloadResponse = await fetch(downloadUrl, {
+ headers,
+ signal: AbortSignal.timeout(downloadTimeoutMs),
+ });
+ if (!downloadResponse.ok) {
+ throw new Error(`Google Play universal APK download failed with HTTP ${downloadResponse.status}: ${await downloadResponse.text()}`);
+ }
+ if (!downloadResponse.body) {
+ throw new Error("Google Play universal APK download returned no response body.");
+ }
+ await pipeline(Readable.fromWeb(downloadResponse.body), createWriteStream(outputPath));
+ const file = await open(outputPath, "r");
+ try {
+ const signature = Buffer.alloc(4);
+ const { bytesRead } = await file.read(signature, 0, signature.length, 0);
+ assertDownloadedApk(signature.subarray(0, bytesRead));
+ } finally {
+ await file.close();
+ }
+ return selected;
+};
+
+const run = async () => {
+ const [versionCodeValue, outputPath] = process.argv.slice(2);
+ const versionCode = Number(versionCodeValue);
+ if (!versionCodeValue || !outputPath) {
+ throw new Error("Usage: node scripts/download-play-universal-apk.mjs <version-code> <output-apk>");
+ }
+ const selected = await downloadPlayUniversalApk({
+ expectedSignerSha256: process.env.ANDROID_PLAY_APP_SIGNER_SHA256,
+ outputPath,
+ packageName: process.env.ANDROID_PACKAGE_NAME || DEFAULT_PACKAGE_NAME,
+ versionCode,
+ });
+ process.stdout.write(`Downloaded Google Play universal APK signed by ${selected.signerSha256}.\n`);
+};
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ run().catch((error) => {
+ console.error(`[download-play-universal-apk] failed: ${error instanceof Error ? error.message : String(error)}`);
+ process.exit(1);
+ });
+}
diff --git a/scripts/download-play-universal-apk.test.mjs b/scripts/download-play-universal-apk.test.mjs
new file mode 100644
index 00000000..e2f88b27
--- /dev/null
+++ b/scripts/download-play-universal-apk.test.mjs
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "bun:test";
+import {
+ assertDownloadedApk,
+ normalizePlayCertificateHash,
+ selectPlayUniversalApk,
+} from "./download-play-universal-apk.mjs";
+
+describe("Google Play universal APK selection", () => {
+ test("normalizes hex and base64 certificate hashes", () => {
+ const hash = "ab".repeat(32);
+ expect(normalizePlayCertificateHash(hash.toUpperCase().match(/.{2}/g).join(":"))).toBe(hash);
+ expect(normalizePlayCertificateHash(Buffer.from(hash, "hex").toString("base64"))).toBe(hash);
+ });
+
+ test("selects the universal APK for the pinned Play signer", () => {
+ const signer = "ab".repeat(32);
+ expect(selectPlayUniversalApk({
+ generatedApks: [
+ {
+ certificateSha256Hash: "cd".repeat(32),
+ generatedUniversalApk: { downloadId: "wrong-key" },
+ },
+ {
+ certificateSha256Hash: Buffer.from(signer, "hex").toString("base64"),
+ generatedUniversalApk: { downloadId: "universal-42" },
+ },
+ ],
+ }, signer)).toEqual({ downloadId: "universal-42", signerSha256: signer });
+ });
+
+ test("fails closed when the expected signer has no universal APK", () => {
+ expect(() => selectPlayUniversalApk({ generatedApks: [] }, "ab".repeat(32))).toThrow(
+ "Expected one Play universal APK",
+ );
+ });
+
+ test("rejects empty or non-APK download responses", () => {
+ expect(() => assertDownloadedApk(Buffer.alloc(0))).toThrow("empty or not a ZIP archive");
+ expect(() => assertDownloadedApk(Buffer.from("not an apk"))).toThrow("empty or not a ZIP archive");
+ const apk = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
+ expect(assertDownloadedApk(apk)).toBe(apk);
+ });
+});
diff --git a/scripts/release.mjs b/scripts/release.mjs
index 03656c92..5f15704a 100644
--- a/scripts/release.mjs
+++ b/scripts/release.mjs
@@ -40,6 +40,7 @@ export const RELEASE_VALIDATIONS = [
"scripts/release.test.mjs",
"scripts/validate-store-delivery.test.mjs",
"scripts/store-delivery.test.mjs",
+ "scripts/download-play-universal-apk.test.mjs",
"scripts/desktop-icns.test.mjs",
"apps/web/src/lib/version-check.test.mjs",
"apps/mobile/src/lib/mobile-release.test.ts",
diff --git a/scripts/store-delivery.test.mjs b/scripts/store-delivery.test.mjs
index d9728c66..4a7b9551 100644
--- a/scripts/store-delivery.test.mjs
+++ b/scripts/store-delivery.test.mjs
@@ -41,4 +41,16 @@ describe("store delivery command", () => {
expect(workflow.match(/eas-version: 21\.4\.0/g)).toHaveLength(2);
expect(workflow.match(/packager: npm/g)).toHaveLength(2);
});
+
+ test("replaces the GitHub APK with the Play-signed universal APK", () => {
+ const workflow = readFileSync(
+ new URL("../.github/workflows/store-delivery.yml", import.meta.url),
+ "utf8",
+ );
+
+ expect(workflow).toContain("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON_BASE64");
+ expect(workflow).toContain("ANDROID_PLAY_APP_SIGNER_SHA256");
+ expect(workflow).toContain("scripts/download-play-universal-apk.mjs");
+ expect(workflow).toContain('gh release upload "$RELEASE_TAG" "$apk_path"');
+ });
});
diff --git a/scripts/verify-android-apk-signature.mjs b/scripts/verify-android-apk-signature.mjs
index 91edae2e..ac525492 100644
--- a/scripts/verify-android-apk-signature.mjs
+++ b/scripts/verify-android-apk-signature.mjs
@@ -9,7 +9,21 @@ export const EDGE_EVER_ANDROID_SIGNER_SHA256 =
const normalizeFingerprint = (value) =>
value.toLowerCase().replace(/[^0-9a-f]/g, "");
-export const verifyAndroidSignerOutput = (output) => {
+export const parseAllowedAndroidSignerDigests = (value = "") => {
+ const configured = value.split(",").map(normalizeFingerprint).filter(Boolean);
+ const digests = configured.length > 0
+ ? configured
+ : [EDGE_EVER_ANDROID_SIGNER_SHA256];
+ if (digests.some((digest) => digest.length !== 64)) {
+ throw new Error("Every allowed Android signer must be a SHA-256 fingerprint.");
+ }
+ return [...new Set(digests)];
+};
+
+export const verifyAndroidSignerOutput = (
+ output,
+ allowedSignerDigests = parseAllowedAndroidSignerDigests(),
+) => {
const digestMatches = [
...output.matchAll(
/^(?:Signer #\d+|V\d+(?:\.\d+)? Signer:) certificate SHA-256 digest:\s*(.+)$/gim,
@@ -32,9 +46,9 @@ export const verifyAndroidSignerOutput = (output) => {
);
}
- if (uniqueSignerDigests[0] !== EDGE_EVER_ANDROID_SIGNER_SHA256) {
+ if (!allowedSignerDigests.includes(uniqueSignerDigests[0])) {
throw new Error(
- `Android signer mismatch: expected ${EDGE_EVER_ANDROID_SIGNER_SHA256}, received ${uniqueSignerDigests[0]}.`,
+ `Android signer mismatch: expected one of ${allowedSignerDigests.join(", ")}, received ${uniqueSignerDigests[0]}.`,
);
}
@@ -93,7 +107,10 @@ const run = () => {
let signerSha256;
try {
- signerSha256 = verifyAndroidSignerOutput(output);
+ signerSha256 = verifyAndroidSignerOutput(
+ output,
+ parseAllowedAndroidSignerDigests(process.env.EDGE_EVER_ANDROID_ALLOWED_SIGNER_SHA256),
+ );
} catch (error) {
process.stderr.write(output);
throw error;
diff --git a/scripts/verify-android-apk-signature.test.mjs b/scripts/verify-android-apk-signature.test.mjs
index c760fa2d..5c5cf27c 100644
--- a/scripts/verify-android-apk-signature.test.mjs
+++ b/scripts/verify-android-apk-signature.test.mjs
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import {
EDGE_EVER_ANDROID_SIGNER_SHA256,
+ parseAllowedAndroidSignerDigests,
verifyAndroidSignerOutput,
} from "./verify-android-apk-signature.mjs";
@@ -54,6 +55,22 @@ describe("Android APK signer verification", () => {
).toThrow("Android signer mismatch");
});
+ test("accepts an explicitly configured Play app signer", () => {
+ const playSigner = "a".repeat(64);
+ expect(
+ verifyAndroidSignerOutput(
+ `Signer #1 certificate SHA-256 digest: ${playSigner}`,
+ parseAllowedAndroidSignerDigests(`${EDGE_EVER_ANDROID_SIGNER_SHA256},${playSigner}`),
+ ),
+ ).toBe(playSigner);
+ });
+
+ test("rejects malformed configured signer fingerprints", () => {
+ expect(() => parseAllowedAndroidSignerDigests("not-a-fingerprint")).toThrow(
+ "SHA-256 fingerprint",
+ );
+ });
+
test("rejects missing or multiple signers", () => {
expect(() => verifyAndroidSignerOutput("Verified")).toThrow(
"Expected exactly one Android signer",