فهرست منبع

feat(android): 接入 JPush 推送桥接与外部分享收发插件

这批代码此前一直在本地工作区未提交,本次一并入库。
**JPush 默认关闭**(fmodeJpushEnabled=false),当前 APK 不含推送 SDK。

## JPush 推送(默认关闭)

- JPushPlugin:Capacitor 桥接,提供 getStatus/start/stop/别名管理
- JPushSdk:SDK 适配层,包裹极光 API
- JPushReceiver / JPushService / JPushClickActivity:收发与点击落地
- android/app/src/jpush/AndroidManifest.xml:隔离清单,仅开启时合并
  裁掉极光的定位/电话/存储/包查询权限与自动初始化 Provider
- proguard-rules.pro:6 个 JPush 类的 keep 规则

安全设计:
- 双开关(Gradle + 前端 JPUSH_OPTIONS.enabled),默认都关
- 启动需显式 privacyConsent
- 别名格式强校验 /^fm_[a-f0-9]{32,60}$/
- getStatus 不回传 AppKey/Token/个人信息

## 外部分享

- NativeSharePlugin:ACTION_SEND 接收(content:// 校验、单文件 800MB 上限、
  每次最多 32 个)+ 外发准备(HTTPS 白名单、禁重定向、缓存 2GB/24h)
- 配套 Android 单元测试与 instrumented 测试

## 其他

- scripts/android-cdp.mjs:CDP 连 App WebView 的调试工具
- docs/jpush-integration.md:推送接入交接文档
- .gitignore:新增 android/.kotlin/ 与 /release/

## ⚠️ 未验证项

- JPush 完整链路未打通:缺 AppKey、别名签发后台、服务端触发、厂商通道
- 外部分享未做真机端到端验证

Co-Authored-By: Claude Code <noreply@anthropic.com>
Huccct 4 روز پیش
والد
کامیت
fc73b4d611

+ 6 - 0
.gitignore

@@ -89,3 +89,9 @@ public/pdf.worker.js
 .tmp-*/
 .tmp-*
 .dev-server.log
+
+# Kotlin 编译缓存(Gradle 生成)
+android/.kotlin/
+
+# 打包产物(本地分发给测试同事用,不入库)
+/release/

+ 29 - 0
android/app/build.gradle

@@ -1,5 +1,8 @@
 apply plugin: 'com.android.application'
 
+def fmodeJpushEnabled = providers.gradleProperty('fmodeJpushEnabled').getOrElse('false').toBoolean()
+def fmodeJpushAppKey = providers.environmentVariable('JPUSH_APPKEY').getOrElse('')
+
 android {
     namespace = "cn.fmode.app"
     compileSdk = rootProject.ext.compileSdkVersion
@@ -10,12 +13,26 @@ android {
         versionCode 1
         versionName "1.0"
         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+        buildConfigField 'boolean', 'JPUSH_ENABLED', fmodeJpushEnabled.toString()
+        manifestPlaceholders += [JPUSH_APPKEY: fmodeJpushAppKey, JPUSH_CHANNEL: 'fmode', JPUSH_ENABLED: fmodeJpushEnabled.toString()]
         aaptOptions {
              // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
              // Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
             ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
         }
     }
+    buildFeatures {
+        buildConfig = true
+    }
+    if (!fmodeJpushEnabled) {
+        sourceSets.main.java {
+            exclude '**/JPushSdk.java', '**/JPushReceiver.java', '**/JPushService.java', '**/JPushClickActivity.java'
+        }
+    }
+    if (fmodeJpushEnabled && file('src/jpush/AndroidManifest.xml').exists()) {
+        sourceSets.debug.manifest.srcFile 'src/jpush/AndroidManifest.xml'
+        sourceSets.release.manifest.srcFile 'src/jpush/AndroidManifest.xml'
+    }
     buildTypes {
         release {
             minifyEnabled false
@@ -25,12 +42,24 @@ android {
 }
 
 repositories {
+    if (fmodeJpushEnabled) {
+        maven {
+            url 'https://maven.jiguang.cn/nexus/content/repositories/releases/'
+            content { includeGroup 'cn.jiguang.sdk' }
+        }
+    }
     flatDir{
         dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
     }
 }
 
 dependencies {
+    if (fmodeJpushEnabled) {
+        implementation('cn.jiguang.sdk:jpush:6.3.1') {
+            exclude group: 'cn.jiguang.sdk', module: 'jcore'
+        }
+        implementation 'cn.jiguang.sdk:jcore:5.6.0'
+    }
     implementation fileTree(include: ['*.jar'], dir: 'libs')
     implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
     implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"

+ 7 - 0
android/app/proguard-rules.pro

@@ -19,3 +19,10 @@
 # If you keep the line number information, uncomment this to
 # hide the original source file name.
 #-renamesourcefileattribute SourceFile
+
+-keep class cn.fmode.app.JPushPlugin { *; }
+-keep class cn.fmode.app.JPushPlugin$Adapter { *; }
+-keep class cn.fmode.app.JPushSdk { *; }
+-keep class cn.fmode.app.JPushReceiver { *; }
+-keep class cn.fmode.app.JPushService { *; }
+-keep class cn.fmode.app.JPushClickActivity { *; }

+ 340 - 0
android/app/src/androidTest/java/cn/fmode/app/NativeShareActivityIntegrationTest.java

@@ -0,0 +1,340 @@
+package cn.fmode.app;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.app.Activity;
+import android.app.Instrumentation;
+import android.content.ClipData;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.SystemClock;
+import androidx.core.content.FileProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.platform.app.InstrumentationRegistry;
+import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
+import androidx.test.runner.lifecycle.Stage;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.PluginCall;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class NativeShareActivityIntegrationTest {
+    private Instrumentation instrumentation;
+    private Context target;
+    private Context sender;
+    private File sources;
+    private final Set<String> ownedShares = new HashSet<>();
+
+    @Before
+    public void setUp() throws Exception {
+        instrumentation = InstrumentationRegistry.getInstrumentation();
+        target = instrumentation.getTargetContext();
+        sender = instrumentation.getContext();
+        assertFalse(target.getPackageName().equals(sender.getPackageName()));
+        sources = new File(target.getCacheDir(), "native-share-integration-" + UUID.randomUUID());
+        assertTrue(sources.mkdirs());
+        finishActivities();
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        MainActivity activity = foreground();
+        if (activity != null) {
+            NativeSharePlugin plugin = plugin(activity);
+            for (String id : ownedShares) acknowledge(plugin, id);
+        }
+        finishActivities();
+        File[] files = sources.listFiles();
+        if (files != null) for (File file : files) assertTrue(file.delete());
+        assertTrue(sources.delete());
+    }
+
+    @Test
+    public void coldSendCopiesRealFileProviderTextAndReplaysLateListener() throws Exception {
+        String title = uniqueTitle();
+        Uri source = textUri("cold.txt", "cold payload 中文");
+        Intent intent = shareIntent(Intent.ACTION_SEND, title).putExtra(Intent.EXTRA_STREAM, source)
+            .putExtra(Intent.EXTRA_TEXT, "cold accompanying text");
+        sender.startActivity(intent);
+        MainActivity activity = awaitActivity();
+        NativeSharePlugin plugin = plugin(activity);
+        JSONObject share = awaitShare(plugin, title);
+        String id = own(share);
+        assertEquals("cold accompanying text", share.getString("text"));
+        assertFile(share, 0, "cold.txt", "cold payload 中文");
+        assertFalse(share.has("errors"));
+        CaptureCall listener = new CaptureCall("addListener", new JSObject().put("eventName", "shareReceived"));
+        plugin.addListener(listener);
+        JSONObject replay = awaitEvent(listener, id);
+        assertEquals(share.getJSONArray("files").toString(), replay.getJSONArray("files").toString());
+        File cached = file(share.getJSONArray("files").getJSONObject(0));
+        acknowledge(plugin, id);
+        assertFalse(cached.exists());
+        instrumentation.runOnMainSync(() -> NativeSharePlugin.receiveIntent(activity, activity.getIntent()));
+        assertAbsent(plugin, id);
+        CaptureCall removed = new CaptureCall("removeAllListeners", new JSObject());
+        plugin.removeAllListeners(removed);
+        removed.await();
+        CaptureCall later = new CaptureCall("addListener", new JSObject().put("eventName", "shareReceived"));
+        plugin.addListener(later);
+        CaptureCall barrier = new CaptureCall("getPendingShares", new JSObject());
+        plugin.getPendingShares(barrier);
+        barrier.await();
+        for (JSObject event : later.events) assertFalse(id.equals(event.getJSONObject("share").getString("id")));
+        acknowledge(plugin, id);
+    }
+
+    @Test
+    public void hotSendMultipleDeduplicatesStreamsAndClipData() throws Exception {
+        MainActivity before = launchNormally();
+        NativeSharePlugin plugin = plugin(before);
+        String title = uniqueTitle();
+        Uri first = textUri("first.txt", "first");
+        Uri second = textUri("second.txt", "second");
+        Intent intent = shareIntent(Intent.ACTION_SEND_MULTIPLE, title)
+            .putParcelableArrayListExtra(Intent.EXTRA_STREAM, new ArrayList<>(Arrays.asList(first, second)));
+        ClipData clip = ClipData.newUri(target.getContentResolver(), "first", first);
+        clip.addItem(new ClipData.Item(second));
+        clip.addItem(new ClipData.Item(first));
+        intent.setClipData(clip);
+        sender.startActivity(intent);
+        JSONObject share = awaitShare(plugin, title);
+        own(share);
+        assertSame(before, awaitActivity());
+        assertEquals(2, share.getJSONArray("files").length());
+        assertFile(share, 0, "first.txt", "first");
+        assertFile(share, 1, "second.txt", "second");
+        acknowledge(plugin, share.getString("id"));
+        assertAbsent(plugin, share.getString("id"));
+    }
+
+    @Test
+    public void clipDataOnlyAndInvalidUrisTravelThroughSystemDelivery() throws Exception {
+        MainActivity activity = launchNormally();
+        NativeSharePlugin plugin = plugin(activity);
+        String title = uniqueTitle();
+        Intent clipOnly = shareIntent(Intent.ACTION_SEND, title);
+        clipOnly.setClipData(ClipData.newUri(target.getContentResolver(), "clip", textUri("clip.txt", "clip only")));
+        sender.startActivity(clipOnly);
+        JSONObject valid = awaitShare(plugin, title);
+        own(valid);
+        assertFile(valid, 0, "clip.txt", "clip only");
+        String invalidTitle = uniqueTitle();
+        Intent invalid = shareIntent(Intent.ACTION_SEND, invalidTitle)
+            .putExtra(Intent.EXTRA_STREAM, Uri.parse("https://not-content.invalid/private.txt"))
+            .putExtra(Intent.EXTRA_TEXT, "text must survive invalid attachment");
+        sender.startActivity(invalid);
+        JSONObject rejected = awaitShare(plugin, invalidTitle);
+        own(rejected);
+        assertEquals(0, rejected.getJSONArray("files").length());
+        assertTrue(rejected.getJSONArray("errors").toString().contains("E_URI_SCHEME"));
+        assertEquals("text must survive invalid attachment", rejected.getString("text"));
+        acknowledge(plugin, valid.getString("id"));
+        acknowledge(plugin, rejected.getString("id"));
+        assertAbsent(plugin, rejected.getString("id"));
+    }
+
+    @Test
+    public void unacknowledgedQueueSurvivesActivityFinishAndRestart() throws Exception {
+        String title = uniqueTitle();
+        sender.startActivity(shareIntent(Intent.ACTION_SEND, title)
+            .putExtra(Intent.EXTRA_STREAM, textUri("persist.txt", "persist across Activity")));
+        MainActivity firstActivity = awaitActivity();
+        JSONObject original = awaitShare(plugin(firstActivity), title);
+        String id = own(original);
+        finishActivities();
+        assertNotNull(new NativeSharePlugin.ShareStore(target).share(id));
+        MainActivity restarted = launchNormally();
+        assertFalse(firstActivity == restarted);
+        NativeSharePlugin plugin = plugin(restarted);
+        JSONObject recovered = awaitShare(plugin, title);
+        assertEquals(id, recovered.getString("id"));
+        assertFile(recovered, 0, "persist.txt", "persist across Activity");
+        assertEquals(1, countTitle(pending(plugin), title));
+        acknowledge(plugin, id);
+        finishActivities();
+        MainActivity afterAck = launchNormally();
+        assertAbsent(plugin(afterAck), id);
+        assertEquals(0, countTitle(new NativeSharePlugin.ShareStore(target).pending(), title));
+    }
+
+    private MainActivity launchNormally() throws Exception {
+        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
+            .setComponent(new ComponentName(target, MainActivity.class)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        sender.startActivity(intent);
+        return awaitActivity();
+    }
+
+    private Intent shareIntent(String action, String title) {
+        return new Intent(action).setType("text/plain").addCategory(Intent.CATEGORY_DEFAULT)
+            .setComponent(new ComponentName(target, MainActivity.class)).putExtra(Intent.EXTRA_SUBJECT, title)
+            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
+    }
+
+    private Uri textUri(String name, String text) throws Exception {
+        File file = new File(sources, name);
+        try (FileOutputStream output = new FileOutputStream(file)) { output.write(text.getBytes(StandardCharsets.UTF_8)); }
+        Uri uri = FileProvider.getUriForFile(target, target.getPackageName() + ".fileprovider", file);
+        assertEquals("content", uri.getScheme());
+        return uri;
+    }
+
+    private NativeSharePlugin plugin(MainActivity activity) throws Exception {
+        long deadline = SystemClock.elapsedRealtime() + 15000;
+        while (SystemClock.elapsedRealtime() < deadline) {
+            if (activity.getBridge() != null && activity.getBridge().getPlugin("NativeShare") != null) {
+                return (NativeSharePlugin) activity.getBridge().getPlugin("NativeShare").getInstance();
+            }
+            SystemClock.sleep(50);
+        }
+        throw new AssertionError("NativeShare was not registered by MainActivity");
+    }
+
+    private JSONObject awaitShare(NativeSharePlugin plugin, String title) throws Exception {
+        long deadline = SystemClock.elapsedRealtime() + 20000;
+        while (SystemClock.elapsedRealtime() < deadline) {
+            JSONArray shares = pending(plugin);
+            for (int index = 0; index < shares.length(); index++) {
+                JSONObject share = shares.getJSONObject(index);
+                if (title.equals(share.optString("title"))) return share;
+            }
+            SystemClock.sleep(50);
+        }
+        throw new AssertionError("System share did not reach NativeShare queue: " + title);
+    }
+
+    private static JSONArray pending(NativeSharePlugin plugin) throws Exception {
+        CaptureCall call = new CaptureCall("getPendingShares", new JSObject());
+        plugin.getPendingShares(call);
+        return call.await().getJSONArray("shares");
+    }
+
+    private static void acknowledge(NativeSharePlugin plugin, String id) throws Exception {
+        CaptureCall call = new CaptureCall("acknowledgeShare", new JSObject().put("id", id));
+        plugin.acknowledgeShare(call);
+        call.await();
+    }
+
+    private static void assertAbsent(NativeSharePlugin plugin, String id) throws Exception {
+        JSONArray shares = pending(plugin);
+        for (int index = 0; index < shares.length(); index++) assertFalse(id.equals(shares.getJSONObject(index).getString("id")));
+    }
+
+    private JSONObject awaitEvent(CaptureCall listener, String id) throws Exception {
+        long deadline = SystemClock.elapsedRealtime() + 10000;
+        while (SystemClock.elapsedRealtime() < deadline) {
+            JSObject event = listener.events.poll(200, TimeUnit.MILLISECONDS);
+            if (event != null && id.equals(event.getJSONObject("share").getString("id"))) return event.getJSONObject("share");
+        }
+        throw new AssertionError("Late shareReceived listener did not receive durable share");
+    }
+
+    private void assertFile(JSONObject share, int index, String name, String content) throws Exception {
+        JSONObject metadata = share.getJSONArray("files").getJSONObject(index);
+        assertEquals(name, metadata.getString("name"));
+        assertEquals("text/plain", metadata.getString("mimeType"));
+        assertEquals(content.getBytes(StandardCharsets.UTF_8).length, metadata.getLong("size"));
+        File file = file(metadata);
+        assertTrue(file.getCanonicalPath().startsWith(new File(target.getCacheDir(), "shared-incoming").getCanonicalPath() + "/"));
+        assertEquals(content, new String(java.nio.file.Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8));
+    }
+
+    private static File file(JSONObject metadata) throws Exception {
+        Uri uri = Uri.parse(metadata.getString("path"));
+        assertEquals("file", uri.getScheme());
+        return new File(uri.getPath());
+    }
+
+    private String own(JSONObject share) throws Exception {
+        String id = share.getString("id");
+        ownedShares.add(id);
+        return id;
+    }
+
+    private static String uniqueTitle() { return "native-share-system-" + UUID.randomUUID(); }
+
+    private static int countTitle(JSONArray shares, String title) throws Exception {
+        int matches = 0;
+        for (int index = 0; index < shares.length(); index++) if (title.equals(shares.getJSONObject(index).optString("title"))) matches++;
+        return matches;
+    }
+
+    private MainActivity foreground() {
+        AtomicReference<MainActivity> result = new AtomicReference<>();
+        instrumentation.runOnMainSync(() -> {
+            for (Activity activity : ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)) {
+                if (activity instanceof MainActivity) result.set((MainActivity) activity);
+            }
+        });
+        return result.get();
+    }
+
+    private MainActivity awaitActivity() {
+        long deadline = SystemClock.elapsedRealtime() + 20000;
+        while (SystemClock.elapsedRealtime() < deadline) {
+            MainActivity activity = foreground();
+            if (activity != null) return activity;
+            SystemClock.sleep(50);
+        }
+        throw new AssertionError("MainActivity did not resume");
+    }
+
+    private void finishActivities() {
+        instrumentation.runOnMainSync(() -> {
+            Set<Activity> activities = new HashSet<>();
+            for (Stage stage : new Stage[] {Stage.CREATED, Stage.STARTED, Stage.RESUMED, Stage.PAUSED, Stage.STOPPED}) {
+                activities.addAll(ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(stage));
+            }
+            for (Activity activity : activities) if (activity instanceof MainActivity) activity.finish();
+        });
+        instrumentation.waitForIdleSync();
+        long deadline = SystemClock.elapsedRealtime() + 10000;
+        while (foreground() != null && SystemClock.elapsedRealtime() < deadline) SystemClock.sleep(50);
+    }
+
+    private static final class CaptureCall extends PluginCall {
+        final LinkedBlockingQueue<JSObject> events = new LinkedBlockingQueue<>();
+        private final CountDownLatch finished = new CountDownLatch(1);
+        private JSObject result;
+        private String failure;
+
+        CaptureCall(String method, JSObject data) { super(null, "NativeShare", UUID.randomUUID().toString(), method, data); }
+        @Override public void resolve(JSObject data) {
+            result = data;
+            events.add(data);
+            finished.countDown();
+        }
+        @Override public void resolve() { result = new JSObject(); finished.countDown(); }
+        @Override public void reject(String message, String code) { failure = code + ": " + message; finished.countDown(); }
+        JSObject await() throws Exception {
+            assertTrue("NativeShare callback timed out", finished.await(20, TimeUnit.SECONDS));
+            if (failure != null) fail(failure);
+            return result;
+        }
+    }
+}

+ 414 - 0
android/app/src/androidTest/java/cn/fmode/app/NativeSharePluginInstrumentedTest.java

@@ -0,0 +1,414 @@
+package cn.fmode.app;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.ClipData;
+import android.content.ContentProvider;
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.Intent;
+import android.content.pm.ProviderInfo;
+import android.database.Cursor;
+import android.database.MatrixCursor;
+import android.net.Uri;
+import android.os.ParcelFileDescriptor;
+import android.os.SystemClock;
+import android.provider.OpenableColumns;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.platform.app.InstrumentationRegistry;
+import com.getcapacitor.JSObject;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.CookieHandler;
+import java.net.URI;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import javax.net.ssl.HttpsURLConnection;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class NativeSharePluginInstrumentedTest {
+    private File root;
+    private Context context;
+    private FixtureProvider provider;
+    private NativeSharePlugin.ShareStore store;
+
+    @Before
+    public void setUp() throws Exception {
+        Context target = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        root = new File(target.getCacheDir(), "native-share-test-" + UUID.randomUUID());
+        assertTrue(root.mkdirs());
+        provider = new FixtureProvider(root);
+        context = new ContextWrapper(target) {
+            @Override public Context getApplicationContext() { return this; }
+            @Override public File getCacheDir() { return mkdir(new File(root, "cache")); }
+            @Override public File getNoBackupFilesDir() { return mkdir(new File(root, "state")); }
+            @Override public ContentResolver getContentResolver() { return ContentResolver.wrap(provider); }
+        };
+        ProviderInfo info = new ProviderInfo();
+        info.authority = "cn.fmode.native-share.test";
+        provider.attachInfo(context, info);
+        store = new NativeSharePlugin.ShareStore(context);
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        assertTrue(root.getCanonicalPath().contains("native-share-test-"));
+        delete(root);
+    }
+
+    @Test
+    public void combinesStreamsAndClipDataWithoutDuplicates() throws Exception {
+        Uri first = uri("first");
+        Uri second = uri("second");
+        ArrayList<Uri> streams = new ArrayList<>(Arrays.asList(first, second));
+        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, streams)
+            .putExtra(Intent.EXTRA_TEXT, "hello").putExtra(Intent.EXTRA_SUBJECT, "title");
+        ClipData clip = new ClipData("files", new String[] {"application/octet-stream"}, new ClipData.Item(first));
+        clip.addItem(new ClipData.Item(second));
+        intent.setClipData(clip);
+        NativeSharePlugin.Incoming incoming = store.accept(intent);
+        assertEquals(2, incoming.uris.size());
+        assertEquals(0, store.pending().length());
+        store.copyIncoming(incoming);
+        JSONObject share = store.pending().getJSONObject(0);
+        assertEquals("hello", share.getString("text"));
+        assertEquals("title", share.getString("title"));
+        assertFalse(share.has("state"));
+        JSONArray files = share.getJSONArray("files");
+        assertEquals(2, files.length());
+        for (int index = 0; index < files.length(); index++) {
+            JSONObject metadata = files.getJSONObject(index);
+            assertEquals("application/pdf", metadata.getString("mimeType"));
+            assertEquals(7, metadata.getLong("size"));
+            File file = new File(Uri.parse(metadata.getString("path")).getPath());
+            assertTrue(file.getCanonicalPath().startsWith(context.getCacheDir().getCanonicalPath() + "/shared-incoming/"));
+            assertTrue(file.isFile());
+        }
+        NativeSharePlugin.ShareStore restored = new NativeSharePlugin.ShareStore(context);
+        assertEquals(1, restored.pending().length());
+        assertNull(restored.accept(new Intent(intent)));
+        restored.acknowledge(incoming.id);
+        restored.acknowledge(incoming.id);
+        assertEquals(0, restored.pending().length());
+        assertFalse(new File(context.getCacheDir(), "shared-incoming/" + incoming.id).exists());
+        NativeSharePlugin.ShareStore afterAck = new NativeSharePlugin.ShareStore(context);
+        assertEquals(0, afterAck.pending().length());
+        assertNull(afterAck.accept(new Intent(intent)));
+    }
+
+    @Test
+    public void rejectsFileUrisAndPreservesPartialSuccess() throws Exception {
+        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM,
+            new ArrayList<>(Arrays.asList(Uri.parse("file:///etc/passwd"), uri("denied"), uri("first"))));
+        NativeSharePlugin.Incoming incoming = store.accept(intent);
+        store.copyIncoming(incoming);
+        JSONObject share = store.share(incoming.id);
+        assertEquals(1, share.getJSONArray("files").length());
+        assertTrue(share.getJSONArray("errors").toString().contains("E_URI_SCHEME"));
+        assertTrue(share.getJSONArray("errors").toString().contains("E_URI_PERMISSION"));
+    }
+
+    @Test
+    public void interruptedReceiveIsDurablyReportedUntilAcknowledged() throws Exception {
+        NativeSharePlugin.Incoming incoming = store.accept(new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uri("first")));
+        NativeSharePlugin.ShareStore restored = new NativeSharePlugin.ShareStore(context);
+        assertEquals(1, restored.pending().length());
+        assertTrue(restored.share(incoming.id).getJSONArray("errors").toString().contains("E_COPY_INTERRUPTED"));
+        assertEquals(1, new NativeSharePlugin.ShareStore(context).pending().length());
+    }
+
+    @Test
+    public void recoversFileCommittedBeforeFinalJournalWrite() throws Exception {
+        NativeSharePlugin.Incoming incoming = store.accept(new Intent(Intent.ACTION_SEND));
+        File directory = mkdir(new File(context.getCacheDir(), "shared-incoming/" + incoming.id));
+        File committed = new File(directory, "001-ready.pdf");
+        write(committed, "ready");
+        File partial = new File(directory, "002-incomplete.pdf.part");
+        write(partial, "partial");
+        JSONObject pending = new JSONObject().put("path", Uri.fromFile(committed).toString()).put("name", "ready.pdf")
+            .put("mimeType", "application/pdf").put("size", 0);
+        File journal = journal(incoming.id);
+        JSONObject record = readJson(journal).put("pendingFile", pending);
+        write(journal, record.toString());
+        NativeSharePlugin.ShareStore restored = new NativeSharePlugin.ShareStore(context);
+        assertEquals(1, restored.share(incoming.id).getJSONArray("files").length());
+        assertEquals(5, restored.share(incoming.id).getJSONArray("files").getJSONObject(0).getLong("size"));
+        assertFalse(partial.exists());
+    }
+
+    @Test
+    public void expiredCacheDoesNotRemoveUnacknowledgedShare() throws Exception {
+        NativeSharePlugin.Incoming incoming = store.accept(new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uri("first"))
+            .putExtra(Intent.EXTRA_TEXT, "keep text"));
+        store.copyIncoming(incoming);
+        JSONObject record = readJson(journal(incoming.id));
+        record.put("createdAt", System.currentTimeMillis() - NativeSharePlugin.CACHE_TTL_MS - 1000);
+        write(journal(incoming.id), record.toString());
+        NativeSharePlugin.ShareStore restored = new NativeSharePlugin.ShareStore(context);
+        JSONObject share = restored.share(incoming.id);
+        assertNotNull(share);
+        assertEquals("keep text", share.getString("text"));
+        assertEquals(0, share.getJSONArray("files").length());
+        assertTrue(share.getJSONArray("errors").toString().contains("E_CACHE_EXPIRED"));
+        assertFalse(new File(context.getCacheDir(), "shared-incoming/" + incoming.id).exists());
+    }
+
+    @Test
+    public void evictedCacheAndCorruptMetadataProduceExplicitErrors() throws Exception {
+        NativeSharePlugin.Incoming incoming = store.accept(new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uri("first")));
+        store.copyIncoming(incoming);
+        File cached = new File(Uri.parse(store.share(incoming.id).getJSONArray("files").getJSONObject(0).getString("path")).getPath());
+        assertTrue(cached.delete());
+        store.maintain();
+        assertTrue(store.share(incoming.id).getJSONArray("errors").toString().contains("E_CACHE_MISSING"));
+        write(journal(incoming.id), "broken-json");
+        NativeSharePlugin.ShareStore restored = new NativeSharePlugin.ShareStore(context);
+        assertTrue(restored.share(incoming.id).getJSONArray("errors").toString().contains("E_QUEUE_CORRUPT"));
+    }
+
+    @Test
+    public void attachmentAndTextLimitsAreReported() throws Exception {
+        ArrayList<Uri> values = new ArrayList<>();
+        for (int index = 0; index < 40; index++) values.add(uri("file-" + index));
+        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, values)
+            .putExtra(Intent.EXTRA_TEXT, "a".repeat(40000));
+        NativeSharePlugin.Incoming incoming = store.accept(intent);
+        assertEquals(32, incoming.uris.size());
+        store.copyIncoming(incoming);
+        JSONObject share = store.share(incoming.id);
+        assertEquals(32, share.getJSONArray("files").length());
+        assertEquals(32768, share.getString("text").length());
+        assertTrue(share.getJSONArray("errors").toString().contains("E_TOO_MANY_FILES"));
+        assertTrue(share.getJSONArray("errors").toString().contains("E_TEXT_TRUNCATED"));
+    }
+
+    @Test
+    public void actualStreamLimitIsEnforcedEvenWithoutMetadata() throws Exception {
+        ByteArrayOutputStream output = new ByteArrayOutputStream();
+        long limit = NativeSharePlugin.MAX_FILE_BYTES;
+        InputStream stream = new InputStream() {
+            private long emitted;
+            @Override public int read() { throw new UnsupportedOperationException(); }
+            @Override public int read(byte[] buffer) {
+                if (emitted > limit) return -1;
+                int count = (int) Math.min(buffer.length, limit + 1 - emitted);
+                emitted += count;
+                return count;
+            }
+        };
+        try {
+            NativeSharePlugin.copyBounded(stream, new java.io.OutputStream() {
+                @Override public void write(int value) { }
+                @Override public void write(byte[] buffer, int offset, int length) { }
+            }, limit, SystemClock.elapsedRealtime() + 30000);
+            fail();
+        } catch (NativeSharePlugin.ShareFailure failure) {
+            assertEquals("E_FILE_TOO_LARGE", failure.code);
+        }
+        try {
+            NativeSharePlugin.copyBounded(new ByteArrayInputStream(new byte[9]), output, 8, SystemClock.elapsedRealtime() + 30000);
+            fail();
+        } catch (NativeSharePlugin.ShareFailure failure) {
+            assertEquals("E_CACHE_LIMIT", failure.code);
+            assertEquals(0, output.size());
+        }
+    }
+
+    @Test
+    public void concurrentAcceptanceAndSnapshotsRemainConsistent() throws Exception {
+        ExecutorService workers = Executors.newFixedThreadPool(4);
+        try {
+            List<Future<?>> futures = new ArrayList<>();
+            for (int index = 0; index < 20; index++) {
+                futures.add(workers.submit(() -> {
+                    try {
+                        NativeSharePlugin.Incoming incoming = store.accept(new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, "text"));
+                        store.pending();
+                        return incoming;
+                    } catch (Exception failure) {
+                        throw new RuntimeException(failure);
+                    }
+                }));
+            }
+            for (Future<?> future : futures) store.copyIncoming((NativeSharePlugin.Incoming) future.get());
+            assertEquals(20, store.pending().length());
+            assertEquals(20, new NativeSharePlugin.ShareStore(context).pending().length());
+        } finally {
+            workers.shutdownNow();
+        }
+    }
+
+    @Test
+    public void outgoingRedirectIsValidatedBeforeOpeningSecondConnection() throws Exception {
+        FakeConnection redirect = new FakeConnection(new URL("https://s3.fmode.cn/file"), 302, "https://evil.example/file", "");
+        int[] opens = {0};
+        NativeSharePlugin.ShareStore outgoing = new NativeSharePlugin.ShareStore(context, url -> { opens[0]++; return redirect; });
+        try {
+            outgoing.download("https://s3.fmode.cn/file", "file.pdf");
+            fail();
+        } catch (NativeSharePlugin.ShareFailure failure) {
+            assertEquals("E_URL_NOT_ALLOWED", failure.code);
+            assertEquals(1, opens[0]);
+            assertEquals(0, new File(context.getCacheDir(), "shared-outgoing").list().length);
+        }
+    }
+
+    @Test
+    public void outgoingDownloadUsesPrivateFileAndNoCredentials() throws Exception {
+        FakeConnection response = new FakeConnection(new URL("https://s3.fmode.cn/file"), 200, null, "payload");
+        NativeSharePlugin.ShareStore outgoing = new NativeSharePlugin.ShareStore(context, url -> response);
+        CookieHandler previous = CookieHandler.getDefault();
+        File result = outgoing.download("https://s3.fmode.cn/file", "../../unsafe.pdf");
+        assertTrue(result.isFile());
+        assertEquals(7, result.length());
+        assertTrue(result.getCanonicalPath().startsWith(new File(context.getCacheDir(), "shared-outgoing").getCanonicalPath() + "/"));
+        assertFalse(response.getInstanceFollowRedirects());
+        assertEquals("", response.getRequestProperty("Authorization"));
+        assertEquals("", response.getRequestProperty("Cookie"));
+        assertEquals(previous, CookieHandler.getDefault());
+    }
+
+    @Test
+    public void outgoingFailureCleansPartialAndRecoversAbandonedDownload() throws Exception {
+        FakeConnection response = new FakeConnection(new URL("https://s3.fmode.cn/file"), 200, null, "data") {
+            @Override public long getContentLengthLong() { return 9; }
+        };
+        NativeSharePlugin.ShareStore outgoing = new NativeSharePlugin.ShareStore(context, url -> response);
+        try {
+            outgoing.download("https://s3.fmode.cn/file", "file.pdf");
+            fail();
+        } catch (NativeSharePlugin.ShareFailure failure) {
+            assertEquals("E_DOWNLOAD_INCOMPLETE", failure.code);
+        }
+        File outgoingRoot = new File(context.getCacheDir(), "shared-outgoing");
+        assertEquals(0, outgoingRoot.list().length);
+        File abandoned = mkdir(new File(outgoingRoot, UUID.randomUUID().toString()));
+        write(new File(abandoned, "file.part"), "partial");
+        new NativeSharePlugin.ShareStore(context);
+        assertFalse(abandoned.exists());
+    }
+
+    @Test
+    public void cookiesAreIsolatedWithoutAffectingOtherThreads() throws Exception {
+        CookieHandler previous = new CookieHandler() {
+            @Override public Map<String, List<String>> get(URI uri, Map<String, List<String>> headers) {
+                return Collections.singletonMap("Cookie", Collections.singletonList("session=private"));
+            }
+            @Override public void put(URI uri, Map<String, List<String>> headers) { }
+        };
+        NativeSharePlugin.DownloadCookies isolated = new NativeSharePlugin.DownloadCookies(previous);
+        URI url = new URI("https://s3.fmode.cn/file");
+        assertTrue(isolated.get(url, Collections.emptyMap()).isEmpty());
+        ExecutorService worker = Executors.newSingleThreadExecutor();
+        try {
+            assertFalse(worker.submit(() -> isolated.get(url, Collections.emptyMap())).get().isEmpty());
+        } finally {
+            worker.shutdownNow();
+        }
+    }
+
+    private File journal(String id) {
+        return new File(context.getNoBackupFilesDir(), "native-share-queue/" + id + ".json");
+    }
+
+    private static JSONObject readJson(File file) throws Exception {
+        return new JSONObject(new String(java.nio.file.Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8));
+    }
+
+    private static Uri uri(String name) { return Uri.parse("content://cn.fmode.native-share.test/" + name); }
+
+    private static File mkdir(File file) {
+        if (!file.isDirectory() && !file.mkdirs()) throw new IllegalStateException("Cannot create test directory");
+        return file;
+    }
+
+    private static void write(File file, String value) throws IOException {
+        try (FileOutputStream output = new FileOutputStream(file)) { output.write(value.getBytes(StandardCharsets.UTF_8)); }
+    }
+
+    private static void delete(File file) throws IOException {
+        if (!file.exists()) return;
+        if (file.isDirectory()) {
+            File[] children = file.listFiles();
+            if (children != null) for (File child : children) delete(child);
+        }
+        if (!file.delete()) throw new IOException("Cannot delete test fixture");
+    }
+
+    private static final class FixtureProvider extends ContentProvider {
+        private final File root;
+
+        FixtureProvider(File root) { this.root = root; }
+        @Override public boolean onCreate() { return true; }
+        @Override public String getType(Uri uri) { return "application/octet-stream"; }
+        @Override public Cursor query(Uri uri, String[] projection, String selection, String[] args, String sort) {
+            MatrixCursor cursor = new MatrixCursor(new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE});
+            cursor.addRow(new Object[] {"../../" + uri.getLastPathSegment() + ".pdf", null});
+            return cursor;
+        }
+        @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
+            if ("denied".equals(uri.getLastPathSegment())) throw new SecurityException("Permission denied");
+            File source = new File(root, "source-" + uri.getLastPathSegment());
+            try { write(source, "payload"); } catch (IOException failure) { throw new FileNotFoundException(); }
+            return ParcelFileDescriptor.open(source, ParcelFileDescriptor.MODE_READ_ONLY);
+        }
+        @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException(); }
+        @Override public int delete(Uri uri, String where, String[] args) { throw new UnsupportedOperationException(); }
+        @Override public int update(Uri uri, ContentValues values, String where, String[] args) { throw new UnsupportedOperationException(); }
+    }
+
+    private static class FakeConnection extends HttpsURLConnection {
+        private final int status;
+        private final String location;
+        private final byte[] body;
+
+        FakeConnection(URL url, int status, String location, String body) {
+            super(url);
+            this.status = status;
+            this.location = location;
+            this.body = body.getBytes(StandardCharsets.UTF_8);
+        }
+        @Override public int getResponseCode() { return status; }
+        @Override public String getHeaderField(String name) { return "Location".equals(name) ? location : null; }
+        @Override public long getContentLengthLong() { return body.length; }
+        @Override public String getContentType() { return "application/pdf"; }
+        @Override public InputStream getInputStream() { return new ByteArrayInputStream(body); }
+        @Override public void disconnect() { }
+        @Override public boolean usingProxy() { return false; }
+        @Override public void connect() { }
+        @Override public String getCipherSuite() { return "test"; }
+        @Override public Certificate[] getLocalCertificates() { return null; }
+        @Override public Certificate[] getServerCertificates() { return null; }
+        @Override public Principal getPeerPrincipal() { return null; }
+        @Override public Principal getLocalPrincipal() { return null; }
+    }
+}

+ 30 - 0
android/app/src/jpush/AndroidManifest.xml

@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools">
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" tools:node="remove" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:node="remove" />
+    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" tools:node="remove" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" tools:node="remove" />
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:node="remove" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
+    <application>
+        <receiver android:name=".JPushReceiver" android:exported="false">
+            <intent-filter>
+                <action android:name="cn.jpush.android.intent.RECEIVER_MESSAGE" />
+                <category android:name="${applicationId}" />
+            </intent-filter>
+        </receiver>
+        <service android:name=".JPushService" android:exported="false" android:process=":pushcore">
+            <intent-filter>
+                <action android:name="cn.jiguang.user.service.action" />
+            </intent-filter>
+        </service>
+        <activity
+            android:name=".JPushClickActivity"
+            android:exported="true"
+            android:launchMode="singleTop"
+            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
+        <provider android:name="cn.jpush.android.service.InitProvider" tools:node="remove" />
+    </application>
+</manifest>

+ 11 - 0
android/app/src/main/AndroidManifest.xml

@@ -18,6 +18,17 @@
             android:launchMode="singleTask"
             android:exported="true">
 
+            <intent-filter>
+                <action android:name="android.intent.action.SEND" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <data android:mimeType="*/*" />
+            </intent-filter>
+            <intent-filter>
+                <action android:name="android.intent.action.SEND_MULTIPLE" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <data android:mimeType="*/*" />
+            </intent-filter>
+
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />

+ 42 - 0
android/app/src/main/java/cn/fmode/app/JPushClickActivity.java

@@ -0,0 +1,42 @@
+package cn.fmode.app;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+
+import com.getcapacitor.JSObject;
+
+import org.json.JSONObject;
+
+public final class JPushClickActivity extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        forward(getIntent());
+    }
+
+    @Override
+    protected void onNewIntent(Intent intent) {
+        super.onNewIntent(intent);
+        forward(intent);
+    }
+
+    private void forward(Intent intent) {
+        try {
+            if (!JPushPlugin.allowed(this) || intent == null) return;
+            String raw = intent.getStringExtra("JMessageExtra");
+            if (raw == null || raw.length() > 16384) return;
+            JSONObject message = new JSONObject(raw);
+            JSObject payload = JPushPlugin.notice("notification", message.optString("msg_id"),
+                "", "", message.optString("n_extras", "{}"));
+            Intent launch = getPackageManager().getLaunchIntentForPackage(getPackageName());
+            if (launch == null) return;
+            launch.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
+            launch.putExtra(JPushPlugin.CLICK_EXTRA, payload.toString());
+            startActivity(launch);
+        } catch (Exception ignored) {
+        } finally {
+            finish();
+        }
+    }
+}

+ 237 - 0
android/app/src/main/java/cn/fmode/app/JPushPlugin.java

@@ -0,0 +1,237 @@
+package cn.fmode.app;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.os.Handler;
+import android.os.Looper;
+
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+
+import org.json.JSONObject;
+
+import java.lang.ref.WeakReference;
+import java.util.HashMap;
+import java.util.Map;
+
+@CapacitorPlugin(name = "FmodeJPush")
+public class JPushPlugin extends Plugin {
+    public interface Adapter {
+        void start(Context context);
+        void stop(Context context);
+        String registrationId(Context context);
+        void setAlias(Context context, int sequence, String alias);
+        void deleteAlias(Context context, int sequence);
+    }
+
+    static final String CLICK_EXTRA = "fmodeJpushPayload";
+    private static WeakReference<JPushPlugin> active = new WeakReference<>(null);
+    private final Handler handler = new Handler(Looper.getMainLooper());
+    private final Map<Integer, PluginCall> aliasCalls = new HashMap<>();
+    private final Map<Integer, Runnable> aliasTimeouts = new HashMap<>();
+    private Adapter adapter;
+    private boolean started;
+    private int nextSequence;
+
+    @Override
+    public void load() {
+        active = new WeakReference<>(this);
+        consumeIntent(getActivity().getIntent());
+    }
+
+    static boolean allowed(Context context) {
+        return BuildConfig.JPUSH_ENABLED && context.getSharedPreferences("fmode-jpush", Context.MODE_PRIVATE)
+            .getBoolean("consent", false);
+    }
+
+    private String unavailableReason() {
+        if (!BuildConfig.JPUSH_ENABLED) return "disabled-by-build";
+        try {
+            PackageManager manager = getContext().getPackageManager();
+            ApplicationInfo info = manager.getApplicationInfo(getContext().getPackageName(), PackageManager.GET_META_DATA);
+            String appKey = info.metaData == null ? "" : info.metaData.getString("JPUSH_APPKEY", "");
+            if (!appKey.matches("[a-fA-F0-9]{24}")) return "missing-or-invalid-appkey";
+            manager.getReceiverInfo(new android.content.ComponentName(getContext(), "cn.fmode.app.JPushReceiver"), 0);
+            Intent callbacks = new Intent("cn.jpush.android.intent.RECEIVER_MESSAGE").setPackage(getContext().getPackageName());
+            boolean receiverRegistered = false;
+            for (android.content.pm.ResolveInfo receiver : manager.queryBroadcastReceivers(callbacks, 0)) {
+                if ("cn.fmode.app.JPushReceiver".equals(receiver.activityInfo.name)) receiverRegistered = true;
+            }
+            if (!receiverRegistered) return "receiver-filter-required";
+            manager.getServiceInfo(new android.content.ComponentName(getContext(), "cn.fmode.app.JPushService"), 0);
+            manager.getActivityInfo(new android.content.ComponentName(getContext(), "cn.fmode.app.JPushClickActivity"), 0);
+            if (manager.resolveContentProvider(getContext().getPackageName() + ".jiguang.InitProvider", 0) != null) {
+                return "remove-sdk-auto-init-provider";
+            }
+            Class.forName("cn.fmode.app.JPushSdk");
+            return null;
+        } catch (Exception | LinkageError failure) {
+            return "native-integration-required";
+        }
+    }
+
+    private JSObject status() {
+        String reason = unavailableReason();
+        JSObject result = new JSObject();
+        result.put("available", reason == null);
+        result.put("started", started);
+        if (reason != null) result.put("reason", reason);
+        return result;
+    }
+
+    @PluginMethod
+    public void getStatus(PluginCall call) {
+        call.resolve(status());
+    }
+
+    @PluginMethod
+    public void start(PluginCall call) {
+        String reason = unavailableReason();
+        if (reason != null) {
+            call.reject(reason, "JPUSH_UNAVAILABLE");
+            return;
+        }
+        if (!Boolean.TRUE.equals(call.getBoolean("privacyConsent", false))) {
+            call.reject("Privacy consent is required", "JPUSH_CONSENT_REQUIRED");
+            return;
+        }
+        try {
+            if (!started) {
+                adapter = (Adapter) Class.forName("cn.fmode.app.JPushSdk").getDeclaredConstructor().newInstance();
+                getContext().getSharedPreferences("fmode-jpush", Context.MODE_PRIVATE).edit().putBoolean("consent", true).apply();
+                adapter.start(getContext());
+                started = true;
+            }
+            call.resolve(status());
+        } catch (Exception | LinkageError failure) {
+            stopSdk();
+            call.reject("JPush initialization failed", "JPUSH_START_FAILED");
+        }
+    }
+
+    @PluginMethod
+    public void stop(PluginCall call) {
+        stopSdk();
+        call.resolve();
+    }
+
+    private void stopSdk() {
+        getContext().getSharedPreferences("fmode-jpush", Context.MODE_PRIVATE).edit().putBoolean("consent", false).apply();
+        if (adapter != null) {
+            try { adapter.stop(getContext()); } catch (RuntimeException ignored) { }
+        }
+        started = false;
+        handler.post(() -> {
+            for (PluginCall pending : aliasCalls.values()) pending.reject("Push stopped", "JPUSH_STOPPED");
+            for (Runnable timeout : aliasTimeouts.values()) handler.removeCallbacks(timeout);
+            aliasCalls.clear();
+            aliasTimeouts.clear();
+        });
+    }
+
+    @PluginMethod
+    public void getRegistrationId(PluginCall call) {
+        JSObject result = new JSObject();
+        String registrationId = started && adapter != null ? adapter.registrationId(getContext()) : null;
+        result.put("registrationId", registrationId == null || registrationId.isEmpty() ? JSONObject.NULL : registrationId);
+        call.resolve(result);
+    }
+
+    @PluginMethod
+    public void setAlias(PluginCall call) {
+        String alias = call.getString("alias", "");
+        if (!alias.matches("fm_[a-f0-9]{32,60}")) {
+            call.reject("A backend-issued opaque alias is required", "JPUSH_INVALID_ALIAS");
+            return;
+        }
+        changeAlias(call, alias);
+    }
+
+    @PluginMethod
+    public void deleteAlias(PluginCall call) {
+        changeAlias(call, null);
+    }
+
+    private void changeAlias(PluginCall call, String alias) {
+        handler.post(() -> {
+            if (!started || adapter == null) {
+                call.reject("Push has not started", "JPUSH_NOT_STARTED");
+                return;
+            }
+            int sequence = nextSequence = nextSequence >= Integer.MAX_VALUE ? 1 : nextSequence + 1;
+            Runnable timeout = () -> finishAlias(sequence, -1);
+            aliasCalls.put(sequence, call);
+            aliasTimeouts.put(sequence, timeout);
+            handler.postDelayed(timeout, 15000);
+            try {
+                if (alias == null) adapter.deleteAlias(getContext(), sequence);
+                else adapter.setAlias(getContext(), sequence, alias);
+            } catch (RuntimeException failure) {
+                finishAlias(sequence, -2);
+            }
+        });
+    }
+
+    private void finishAlias(int sequence, int errorCode) {
+        PluginCall pending = aliasCalls.remove(sequence);
+        Runnable timeout = aliasTimeouts.remove(sequence);
+        if (timeout != null) handler.removeCallbacks(timeout);
+        if (pending == null) return;
+        if (errorCode == 0) pending.resolve();
+        else pending.reject("JPush alias request failed", errorCode == -1 ? "JPUSH_ALIAS_TIMEOUT" : "JPUSH_ALIAS_FAILED");
+    }
+
+    static void aliasResult(int sequence, int errorCode) {
+        JPushPlugin plugin = active.get();
+        if (plugin != null) plugin.handler.post(() -> plugin.finishAlias(sequence, errorCode));
+    }
+
+    static void emit(String event, JSObject payload) {
+        JPushPlugin plugin = active.get();
+        if (plugin == null || !allowed(plugin.getContext())) return;
+        plugin.handler.post(() -> plugin.notifyListeners(event, payload, !"notificationReceived".equals(event)));
+    }
+
+    static JSObject notice(String kind, String messageId, String title, String body, String extras) {
+        JSObject result = new JSObject();
+        result.put("kind", kind);
+        result.put("messageId", messageId == null ? "" : messageId);
+        result.put("title", title == null ? "" : title);
+        result.put("body", body == null ? "" : body);
+        try {
+            JSONObject data = new JSONObject(extras == null ? "{}" : extras);
+            String link = data.optString("deepLink", "");
+            String key = data.optString("businessKey", "");
+            if (link.length() <= 2048 && link.startsWith("fmode://")) result.put("deepLink", link);
+            if (key.length() <= 256) result.put("businessKey", key);
+        } catch (Exception ignored) { }
+        return result;
+    }
+
+    private void consumeIntent(Intent intent) {
+        if (intent == null || !allowed(getContext())) return;
+        String raw = intent.getStringExtra(CLICK_EXTRA);
+        intent.removeExtra(CLICK_EXTRA);
+        if (raw == null || raw.length() > 16384) return;
+        try { emit("notificationOpened", new JSObject(raw)); } catch (Exception ignored) { }
+    }
+
+    @Override
+    protected void handleOnNewIntent(Intent intent) {
+        consumeIntent(intent);
+    }
+
+    @Override
+    protected void handleOnDestroy() {
+        if (active.get() == this) active.clear();
+        for (PluginCall pending : aliasCalls.values()) pending.reject("Bridge destroyed", "JPUSH_BRIDGE_DESTROYED");
+        aliasCalls.clear();
+        for (Runnable timeout : aliasTimeouts.values()) handler.removeCallbacks(timeout);
+        aliasTimeouts.clear();
+    }
+}

+ 46 - 0
android/app/src/main/java/cn/fmode/app/JPushReceiver.java

@@ -0,0 +1,46 @@
+package cn.fmode.app;
+
+import android.content.Context;
+
+import cn.jpush.android.api.CustomMessage;
+import cn.jpush.android.api.JPushMessage;
+import cn.jpush.android.api.NotificationMessage;
+import cn.jpush.android.service.JPushMessageReceiver;
+
+import com.getcapacitor.JSObject;
+
+public final class JPushReceiver extends JPushMessageReceiver {
+    @Override
+    public void onRegister(Context context, String registrationId) {
+        if (!JPushPlugin.allowed(context)) return;
+        JSObject result = new JSObject();
+        result.put("registrationId", registrationId);
+        JPushPlugin.emit("registration", result);
+    }
+
+    @Override
+    public void onMessage(Context context, CustomMessage message) {
+        if (!JPushPlugin.allowed(context)) return;
+        JPushPlugin.emit("notificationReceived", JPushPlugin.notice(
+            "message", message.messageId, message.title, message.message, message.extra));
+    }
+
+    @Override
+    public void onNotifyMessageArrived(Context context, NotificationMessage message) {
+        if (!JPushPlugin.allowed(context)) return;
+        JPushPlugin.emit("notificationReceived", JPushPlugin.notice(
+            "notification", message.msgId, message.notificationTitle, message.notificationContent, message.notificationExtras));
+    }
+
+    @Override
+    public void onNotifyMessageOpened(Context context, NotificationMessage message) {
+        if (!JPushPlugin.allowed(context)) return;
+        JPushPlugin.emit("notificationOpened", JPushPlugin.notice(
+            "notification", message.msgId, message.notificationTitle, message.notificationContent, message.notificationExtras));
+    }
+
+    @Override
+    public void onAliasOperatorResult(Context context, JPushMessage message) {
+        JPushPlugin.aliasResult(message.getSequence(), message.getErrorCode());
+    }
+}

+ 45 - 0
android/app/src/main/java/cn/fmode/app/JPushSdk.java

@@ -0,0 +1,45 @@
+package cn.fmode.app;
+
+import android.content.Context;
+
+import cn.jiguang.api.JCoreInterface;
+import cn.jiguang.api.utils.JCollectionAuth;
+import cn.jpush.android.api.JPushInterface;
+
+public final class JPushSdk implements JPushPlugin.Adapter {
+    @Override
+    public void start(Context context) {
+        JPushInterface.setDebugMode(false);
+        JCoreInterface.setDebugMode(false);
+        JCoreInterface.enableSDKLocalLog(context, false, false);
+        JCollectionAuth.setAuth(context, true);
+        JCollectionAuth.enableAutoWakeup(context, false);
+        JCollectionAuth.enableDynamicLoad(context, false);
+        JPushInterface.setThirdPushEnable(context, false);
+        JPushInterface.setGeofenceEnable(context, false);
+        JPushInterface.setDataInsightsEnable(context, false);
+        JPushInterface.init(context);
+        if (JPushInterface.isPushStopped(context)) JPushInterface.resumePush(context);
+    }
+
+    @Override
+    public void stop(Context context) {
+        JPushInterface.stopPush(context);
+        JCollectionAuth.setAuth(context, false);
+    }
+
+    @Override
+    public String registrationId(Context context) {
+        return JPushInterface.getRegistrationID(context);
+    }
+
+    @Override
+    public void setAlias(Context context, int sequence, String alias) {
+        JPushInterface.setAlias(context, sequence, alias);
+    }
+
+    @Override
+    public void deleteAlias(Context context, int sequence) {
+        JPushInterface.deleteAlias(context, sequence);
+    }
+}

+ 5 - 0
android/app/src/main/java/cn/fmode/app/JPushService.java

@@ -0,0 +1,5 @@
+package cn.fmode.app;
+
+import cn.jpush.android.service.JCommonService;
+
+public final class JPushService extends JCommonService { }

+ 4 - 0
android/app/src/main/java/cn/fmode/app/MainActivity.java

@@ -8,6 +8,8 @@ import com.getcapacitor.BridgeActivity;
 public class MainActivity extends BridgeActivity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
+        registerPlugin(NativeSharePlugin.class);
+        registerPlugin(JPushPlugin.class);
         // 注册自定义插件(2026-11-15)
         registerPlugin(AppSettingsPlugin.class);   // 跳系统设置页引导开通知权限
         registerPlugin(FmodeNotifyPlugin.class);   // 发系统通知(替代 @capacitor/local-notifications)
@@ -18,6 +20,7 @@ public class MainActivity extends BridgeActivity {
          * 否则插件注册时已错过这次事件。
          */
         pendingDeepLink = extractDeepLink(getIntent());
+        NativeSharePlugin.receiveIntent(this, getIntent());
 
         super.onCreate(savedInstanceState);
     }
@@ -33,6 +36,7 @@ public class MainActivity extends BridgeActivity {
         setIntent(intent);
         pendingDeepLink = extractDeepLink(intent);
         FmodeNotifyPlugin.pushDeepLink(pendingDeepLink);
+        NativeSharePlugin.receiveIntent(this, intent);
     }
 
     /** 当前待处理的深链(冷启动时由插件读取) */

+ 876 - 0
android/app/src/main/java/cn/fmode/app/NativeSharePlugin.java

@@ -0,0 +1,876 @@
+package cn.fmode.app;
+
+import android.app.Activity;
+import android.content.ClipData;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.SystemClock;
+import android.provider.OpenableColumns;
+import android.util.AtomicFile;
+import android.util.Base64;
+import android.webkit.MimeTypeMap;
+
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.CookieHandler;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.SecureRandom;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.net.ssl.HttpsURLConnection;
+
+@CapacitorPlugin(name = "NativeShare")
+public class NativeSharePlugin extends Plugin {
+    static final long MAX_FILE_BYTES = 800L * 1024 * 1024;
+    static final long MAX_CACHE_BYTES = 2L * 1024 * 1024 * 1024;
+    static final long CACHE_TTL_MS = TimeUnit.HOURS.toMillis(24);
+    static final long TRANSFER_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(5);
+    static final int MAX_FILES_PER_SHARE = 32;
+    static final int MAX_CACHED_FILES = 128;
+    private static final int MAX_OUTGOING_FILES = 32;
+    private static final String EVENT = "shareReceived";
+    private static final String RECEIPT_ID = "cn.fmode.app.NativeShare.id";
+    private static final String RECEIPT_MAC = "cn.fmode.app.NativeShare.receipt";
+    private static final Object LOCK = new Object();
+    private static final java.util.concurrent.ExecutorService WORKER = Executors.newSingleThreadExecutor();
+    private static final ScheduledExecutorService TIMER = Executors.newSingleThreadScheduledExecutor();
+    private static volatile NativeSharePlugin instance;
+    private static ShareStore store;
+    private static volatile String storageFailure;
+
+    @Override
+    public void load() {
+        instance = this;
+        Context context = getContext().getApplicationContext();
+        WORKER.execute(() -> {
+            try {
+                getStore(context).maintain();
+            } catch (Exception failure) {
+                storageFailure = "E_QUEUE_STORAGE: 无法恢复原生分享队列";
+            }
+        });
+    }
+
+    @Override
+    protected void handleOnDestroy() {
+        if (instance == this) instance = null;
+    }
+
+    public static void receiveIntent(Activity activity, Intent intent) {
+        if (activity == null || intent == null) return;
+        String action = intent.getAction();
+        if (!Intent.ACTION_SEND.equals(action) && !Intent.ACTION_SEND_MULTIPLE.equals(action)) return;
+        Context context = activity.getApplicationContext();
+        try {
+            ShareStore current = getStore(context);
+            Incoming incoming = current.accept(intent);
+            if (incoming == null) return;
+            WORKER.execute(() -> {
+                current.copyIncoming(incoming);
+                publish(current, incoming.id);
+            });
+        } catch (Exception failure) {
+            storageFailure = "E_QUEUE_STORAGE: 无法持久保存收到的分享,请勿关闭应用并重新分享";
+        }
+    }
+
+    @PluginMethod
+    public void getPendingShares(PluginCall call) {
+        WORKER.execute(() -> {
+            try {
+                ShareStore current = getStore(getContext());
+                current.maintain();
+                if (storageFailure != null) {
+                    call.reject(storageFailure, "E_QUEUE_STORAGE");
+                    return;
+                }
+                call.resolve(new JSObject().put("shares", current.pending()));
+            } catch (Exception failure) {
+                call.reject("无法读取原生分享队列", "E_QUEUE_STORAGE");
+            }
+        });
+    }
+
+    @Override
+    @PluginMethod(returnType = PluginMethod.RETURN_NONE)
+    public void addListener(PluginCall call) {
+        WORKER.execute(() -> {
+            boolean replay = EVENT.equals(call.getString("eventName")) && !hasListeners(EVENT);
+            super.addListener(call);
+            if (!replay) return;
+            try {
+                ShareStore current = getStore(getContext());
+                current.maintain();
+                JSONArray shares = current.pending();
+                for (int index = 0; index < shares.length(); index++) {
+                    notifyListeners(EVENT, new JSObject().put("share", shares.getJSONObject(index)));
+                }
+            } catch (Exception failure) {
+                storageFailure = "E_QUEUE_STORAGE: 无法重放原生分享队列";
+            }
+        });
+    }
+
+    @Override
+    @PluginMethod(returnType = PluginMethod.RETURN_NONE)
+    public void removeListener(PluginCall call) {
+        WORKER.execute(() -> super.removeListener(call));
+    }
+
+    @Override
+    @PluginMethod
+    public void removeAllListeners(PluginCall call) {
+        WORKER.execute(() -> super.removeAllListeners(call));
+    }
+
+    @PluginMethod
+    public void acknowledgeShare(PluginCall call) {
+        String id = call.getString("id");
+        if (!validId(id)) {
+            call.reject("id 必须是分享队列返回的 UUID", "E_INVALID_ID");
+            return;
+        }
+        WORKER.execute(() -> {
+            try {
+                getStore(getContext()).acknowledge(id);
+                call.resolve();
+            } catch (Exception failure) {
+                call.reject("无法确认分享或清理对应缓存,可使用同一 id 重试", "E_ACK_STORAGE");
+            }
+        });
+    }
+
+    @PluginMethod
+    public void prepareOutgoing(PluginCall call) {
+        String url = call.getString("url");
+        String name = call.getString("name");
+        WORKER.execute(() -> {
+            try {
+                File file = getStore(getContext()).download(url, name);
+                call.resolve(new JSObject().put("path", Uri.fromFile(file).toString()));
+            } catch (ShareFailure failure) {
+                call.reject(failure.getMessage(), failure.code);
+            } catch (SocketTimeoutException failure) {
+                call.reject("下载超时", "E_DOWNLOAD_TIMEOUT");
+            } catch (Exception failure) {
+                call.reject("下载失败,临时文件已清理", "E_DOWNLOAD_IO");
+            }
+        });
+    }
+
+    private static ShareStore getStore(Context context) throws IOException, JSONException {
+        synchronized (LOCK) {
+            if (store == null) store = new ShareStore(context.getApplicationContext());
+            return store;
+        }
+    }
+
+    private static void publish(ShareStore current, String id) {
+        NativeSharePlugin target = instance;
+        if (target == null || !target.hasListeners(EVENT)) return;
+        JSObject share = current.share(id);
+        if (share != null) target.notifyListeners(EVENT, new JSObject().put("share", share));
+    }
+
+    static boolean validId(String id) {
+        return id != null && id.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
+    }
+
+    static URL checkedUrl(String value) throws ShareFailure {
+        try {
+            if (value == null || value.length() > 16384) throw new IllegalArgumentException();
+            URI parsed = new URI(value);
+            String host = parsed.getHost();
+            if (!"https".equalsIgnoreCase(parsed.getScheme()) || parsed.getRawUserInfo() != null
+                || (parsed.getPort() != -1 && parsed.getPort() != 443) || parsed.getRawFragment() != null
+                || host == null || !Arrays.asList("s3.fmode.cn", "matrix.fmode.cn", "server.fmode.cn")
+                    .contains(host.toLowerCase(Locale.ROOT))) {
+                throw new IllegalArgumentException();
+            }
+            return parsed.toURL();
+        } catch (Exception failure) {
+            throw new ShareFailure("E_URL_NOT_ALLOWED", "仅允许 HTTPS 项目白名单域名,禁止用户凭证、非标准端口及跨域重定向");
+        }
+    }
+
+    static String sanitizeName(String input) {
+        String value = input == null ? "" : input;
+        int codePoints = value.codePointCount(0, value.length());
+        if (codePoints > 180) value = value.substring(0, value.offsetByCodePoints(0, 180));
+        value = value.replaceAll("[\\p{Cntrl}\\p{Cf}<>:\"/\\\\|?*]", "_");
+        value = value.replaceAll("^[.\\s]+|[.\\s]+$", "");
+        if (value.isEmpty()) value = "shared-file";
+        while (value.getBytes(StandardCharsets.UTF_8).length > 180) {
+            value = value.substring(0, value.offsetByCodePoints(value.length(), -1));
+        }
+        return value;
+    }
+
+    static String completeMime(String supplied, String name) {
+        String value = supplied == null ? "" : supplied.split(";", 2)[0].trim().toLowerCase(Locale.ROOT);
+        if (value.matches("[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+")
+            && !"application/octet-stream".equals(value) && !"binary/octet-stream".equals(value)) return value;
+        int separator = name.lastIndexOf('.');
+        String extension = separator >= 0 ? name.substring(separator + 1).toLowerCase(Locale.ROOT) : "";
+        String inferred = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
+        if (inferred != null) return inferred;
+        switch (extension) {
+            case "md": return "text/markdown";
+            case "csv": return "text/csv";
+            case "json": return "application/json";
+            case "heic": return "image/heic";
+            case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
+            case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
+            case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
+            default: return "application/octet-stream";
+        }
+    }
+
+    static String completeName(String name, String mime) {
+        String safe = sanitizeName(name);
+        if (!safe.contains(".")) {
+            String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime);
+            if (extension != null && extension.matches("[A-Za-z0-9]{1,12}")) safe += "." + extension;
+        }
+        return safe;
+    }
+
+    static long copyBounded(InputStream input, OutputStream output, long limit, long deadline) throws IOException {
+        byte[] buffer = new byte[64 * 1024];
+        long copied = 0;
+        while (true) {
+            if (SystemClock.elapsedRealtime() >= deadline) throw new ShareFailure("E_TRANSFER_TIMEOUT", "文件传输超时");
+            int count = input.read(buffer);
+            if (count == -1) return copied;
+            if (count == 0) continue;
+            if (count > limit - copied) {
+                if (limit < MAX_FILE_BYTES) throw new ShareFailure("E_CACHE_LIMIT", "分享缓存总量或可用空间不足");
+                throw new ShareFailure("E_FILE_TOO_LARGE", "单文件实际数据超过 800 MiB");
+            }
+            output.write(buffer, 0, count);
+            copied += count;
+        }
+    }
+
+    static final class ShareFailure extends IOException {
+        final String code;
+
+        ShareFailure(String code, String message) {
+            super(code + ": " + message);
+            this.code = code;
+        }
+    }
+
+    static final class Incoming {
+        final String id;
+        final List<Uri> uris;
+
+        Incoming(String id, List<Uri> uris) {
+            this.id = id;
+            this.uris = uris;
+        }
+    }
+
+    interface ConnectionFactory {
+        HttpsURLConnection open(URL url) throws IOException;
+    }
+
+    static final class DownloadCookies extends CookieHandler {
+        private final CookieHandler previous;
+        private final Thread owner = Thread.currentThread();
+
+        DownloadCookies(CookieHandler previous) {
+            this.previous = previous;
+        }
+
+        @Override
+        public Map<String, List<String>> get(URI uri, Map<String, List<String>> headers) throws IOException {
+            return Thread.currentThread() == owner || previous == null ? Collections.emptyMap() : previous.get(uri, headers);
+        }
+
+        @Override
+        public void put(URI uri, Map<String, List<String>> headers) throws IOException {
+            if (Thread.currentThread() != owner && previous != null) previous.put(uri, headers);
+        }
+    }
+
+    static final class ShareStore {
+        private final Context context;
+        private final File journal;
+        private final File incomingRoot;
+        private final File outgoingRoot;
+        private final byte[] receiptKey;
+        private final ConnectionFactory connections;
+        private final Map<String, JSObject> records = new LinkedHashMap<>();
+
+        ShareStore(Context context) throws IOException, JSONException {
+            this(context, url -> (HttpsURLConnection) url.openConnection());
+        }
+
+        ShareStore(Context context, ConnectionFactory connections) throws IOException, JSONException {
+            this.context = context;
+            this.connections = connections;
+            journal = directory(new File(context.getNoBackupFilesDir(), "native-share-queue"));
+            incomingRoot = directory(new File(context.getCacheDir(), "shared-incoming"));
+            outgoingRoot = directory(new File(context.getCacheDir(), "shared-outgoing"));
+            AtomicFile keyFile = new AtomicFile(new File(journal, "receipt.key"));
+            if (keyFile.getBaseFile().exists() || new File(journal, "receipt.key.bak").exists()) {
+                receiptKey = readAtomic(keyFile, 64);
+                if (receiptKey.length != 32) throw new IOException("Invalid receipt key");
+            } else {
+                receiptKey = new byte[32];
+                new SecureRandom().nextBytes(receiptKey);
+                writeAtomic(keyFile, receiptKey);
+            }
+            restore();
+        }
+
+        synchronized Incoming accept(Intent intent) throws IOException {
+            try {
+                String oldId = intent.getStringExtra(RECEIPT_ID);
+                String oldMac = intent.getStringExtra(RECEIPT_MAC);
+                if (validId(oldId) && oldMac != null && MessageDigest.isEqual(
+                    receipt(oldId).getBytes(StandardCharsets.UTF_8), oldMac.getBytes(StandardCharsets.UTF_8))) return null;
+            } catch (RuntimeException ignored) {
+            }
+            String id = UUID.randomUUID().toString();
+            JSObject record = new JSObject().put("id", id).put("state", "copying")
+                .put("createdAt", System.currentTimeMillis()).put("files", new JSONArray());
+            LinkedHashSet<Uri> uris = new LinkedHashSet<>();
+            try {
+                readText(intent, Intent.EXTRA_TEXT, "text", 32768, record);
+                readText(intent, Intent.EXTRA_SUBJECT, "title", 2048, record);
+                Object streams = intent.getExtras() == null ? null : intent.getExtras().get(Intent.EXTRA_STREAM);
+                if (streams instanceof ArrayList<?>) {
+                    List<?> values = (ArrayList<?>) streams;
+                    int count = Math.min(values.size(), 256);
+                    for (int index = 0; index < count; index++) addUri(values.get(index), uris, record);
+                    if (values.size() > count) error(record, "E_TOO_MANY_FILES: 超出分享附件数量限制");
+                } else if (streams != null) {
+                    addUri(streams, uris, record);
+                }
+                ClipData clip = intent.getClipData();
+                if (clip != null) {
+                    int count = Math.min(clip.getItemCount(), 256);
+                    for (int index = 0; index < count; index++) {
+                        Uri uri = clip.getItemAt(index).getUri();
+                        if (uri != null) addUri(uri, uris, record);
+                    }
+                    if (clip.getItemCount() > count) error(record, "E_TOO_MANY_FILES: 超出分享附件数量限制");
+                }
+            } catch (RuntimeException failure) {
+                error(record, "E_INVALID_SHARE: 无法读取分享 Intent 中的部分数据");
+            }
+            if (uris.isEmpty() && !record.has("text") && !record.has("title") && !record.has("errors")) {
+                error(record, "E_EMPTY_SHARE: 分享不包含可读取的附件或文本");
+            }
+            save(record);
+            records.put(id, record);
+            intent.putExtra(RECEIPT_ID, id);
+            intent.putExtra(RECEIPT_MAC, receipt(id));
+            return new Incoming(id, new ArrayList<>(uris));
+        }
+
+        private void readText(Intent intent, String extra, String field, int maximum, JSObject record) {
+            CharSequence value = intent.getCharSequenceExtra(extra);
+            if (value == null) return;
+            int length = Math.min(value.length(), maximum);
+            record.put(field, value.subSequence(0, length).toString());
+            if (value.length() > maximum) error(record, "E_TEXT_TRUNCATED: 分享文本超过长度限制,已截断");
+        }
+
+        private void addUri(Object value, Set<Uri> uris, JSObject record) {
+            if (!(value instanceof Uri)) {
+                error(record, "E_INVALID_STREAM: 附件必须是 content URI");
+                return;
+            }
+            Uri uri = ((Uri) value).normalizeScheme();
+            if (!"content".equals(uri.getScheme()) || uri.getAuthority() == null || uri.getAuthority().isEmpty()) {
+                error(record, "E_URI_SCHEME: 只接受 content:// 附件");
+                return;
+            }
+            if (uris.contains(uri)) return;
+            if (uris.size() >= MAX_FILES_PER_SHARE) {
+                error(record, "E_TOO_MANY_FILES: 每次最多接收 32 个附件");
+                return;
+            }
+            uris.add(uri);
+        }
+
+        void copyIncoming(Incoming incoming) {
+            JSObject record;
+            synchronized (this) {
+                record = records.get(incoming.id);
+            }
+            if (record == null) return;
+            try {
+                maintain();
+                File destination = incoming.uris.isEmpty() ? null : directory(child(incomingRoot, incoming.id));
+                int index = 0;
+                for (Uri uri : incoming.uris) {
+                    index++;
+                    try {
+                        copyUri(uri, destination, index, record);
+                    } catch (Exception failure) {
+                        error(record, "附件 " + index + " " + incomingError(failure));
+                        record.remove("pendingFile");
+                        save(record);
+                    }
+                }
+            } catch (Exception failure) {
+                error(record, incomingError(failure));
+            } finally {
+                synchronized (this) {
+                    record.put("state", "ready");
+                    try {
+                        save(record);
+                    } catch (IOException failure) {
+                        error(record, "E_QUEUE_STORAGE: 完成状态写入失败,重启后将恢复为中断分享");
+                    }
+                }
+            }
+        }
+
+        private void copyUri(Uri uri, File destination, int index, JSObject record) throws IOException, JSONException {
+            ContentResolver resolver = context.getContentResolver();
+            String name = null;
+            long advertisedSize = -1;
+            try (Cursor cursor = resolver.query(uri, new String[] {OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}, null, null, null)) {
+                if (cursor != null && cursor.moveToFirst()) {
+                    int nameColumn = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
+                    int sizeColumn = cursor.getColumnIndex(OpenableColumns.SIZE);
+                    if (nameColumn >= 0 && !cursor.isNull(nameColumn)) name = cursor.getString(nameColumn);
+                    if (sizeColumn >= 0 && !cursor.isNull(sizeColumn)) advertisedSize = cursor.getLong(sizeColumn);
+                }
+            } catch (SecurityException failure) {
+                throw failure;
+            } catch (RuntimeException failure) {
+                error(record, "附件 " + index + " E_METADATA: 无法读取附件名称或声明大小,尝试读取数据流");
+            }
+            if (advertisedSize > MAX_FILE_BYTES) throw new ShareFailure("E_FILE_TOO_LARGE", "附件声明大小超过 800 MiB");
+            if (name == null || name.trim().isEmpty()) name = "shared-file-" + index;
+            name = sanitizeName(name);
+            String suppliedMime = null;
+            try {
+                suppliedMime = resolver.getType(uri);
+            } catch (RuntimeException failure) {
+                error(record, "附件 " + index + " E_MIME: 无法读取附件类型,使用扩展名推断");
+            }
+            String mime = completeMime(suppliedMime, name);
+            name = completeName(name, mime);
+            File target = child(destination, String.format(Locale.ROOT, "%03d-%s", index, name));
+            File partial = child(destination, target.getName() + ".part");
+            long allowance = allowance(false);
+            if (advertisedSize > allowance) throw new ShareFailure("E_CACHE_LIMIT", "附件超出剩余缓存空间");
+            JSObject metadata = new JSObject().put("path", Uri.fromFile(target).toString())
+                .put("name", name).put("mimeType", mime).put("size", 0L);
+            record.put("pendingFile", metadata);
+            save(record);
+            boolean committed = false;
+            try {
+                InputStream opened = resolver.openInputStream(uri);
+                if (opened == null) throw new FileNotFoundException();
+                try (InputStream input = opened; FileOutputStream output = new FileOutputStream(partial)) {
+                    ScheduledFuture<?> timeout = TIMER.schedule(() -> closeQuietly(input), TRANSFER_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+                    try {
+                        long size = copyBounded(input, output, allowance, SystemClock.elapsedRealtime() + TRANSFER_TIMEOUT_MS);
+                        output.getFD().sync();
+                        metadata.put("size", size);
+                    } finally {
+                        timeout.cancel(false);
+                    }
+                }
+                if (!partial.renameTo(target)) throw new IOException("Cannot commit incoming file");
+                committed = true;
+                record.getJSONArray("files").put(metadata);
+                record.remove("pendingFile");
+                save(record);
+            } finally {
+                if (!committed) removeTree(incomingRoot, partial);
+            }
+        }
+
+        synchronized JSONArray pending() throws JSONException {
+            JSONArray result = new JSONArray();
+            for (JSObject record : records.values()) {
+                if ("ready".equals(record.optString("state"))) result.put(external(record));
+            }
+            return result;
+        }
+
+        synchronized JSObject share(String id) {
+            JSObject record = records.get(id);
+            return record != null && "ready".equals(record.optString("state")) ? external(record) : null;
+        }
+
+        private JSObject external(JSObject record) {
+            JSObject result = new JSObject().put("id", record.optString("id"));
+            if (record.has("text")) result.put("text", record.optString("text"));
+            if (record.has("title")) result.put("title", record.optString("title"));
+            try {
+                result.put("files", new JSONArray(record.getJSONArray("files").toString()));
+                if (record.has("errors")) result.put("errors", new JSONArray(record.getJSONArray("errors").toString()));
+            } catch (JSONException failure) {
+                result.put("files", new JSONArray()).put("errors", new JSONArray().put("E_QUEUE_CORRUPT: 分享元数据损坏"));
+            }
+            return result;
+        }
+
+        synchronized void acknowledge(String id) throws IOException {
+            JSObject record = records.get(id);
+            if (record != null) {
+                JSObject tombstone = new JSObject().put("id", id).put("state", "acked").put("files", new JSONArray());
+                save(tombstone);
+                records.remove(id);
+            }
+            removeTree(incomingRoot, child(incomingRoot, id));
+            atomic(id).delete();
+        }
+
+        synchronized void maintain() throws IOException, JSONException {
+            long now = System.currentTimeMillis();
+            for (JSObject record : records.values()) {
+                if (!"ready".equals(record.optString("state"))) continue;
+                JSONArray files = record.getJSONArray("files");
+                JSONArray kept = new JSONArray();
+                boolean expired = now - record.optLong("createdAt", 0) >= CACHE_TTL_MS;
+                for (int index = 0; index < files.length(); index++) {
+                    JSONObject metadata = files.getJSONObject(index);
+                    File file = localFile(metadata, incomingRoot, record.getString("id"));
+                    if (expired || file == null || !file.isFile() || file.length() != metadata.optLong("size", -1)) {
+                        error(record, expired ? "E_CACHE_EXPIRED: 分享附件缓存已超过 24 小时,文本和错误记录保留至确认"
+                            : "E_CACHE_MISSING: 分享附件缓存丢失或不完整,请重新分享");
+                    } else {
+                        kept.put(metadata);
+                    }
+                }
+                if (kept.length() != files.length()) {
+                    record.put("files", kept);
+                    save(record);
+                }
+                if (expired) removeTree(incomingRoot, child(incomingRoot, record.getString("id")));
+            }
+            cleanOrphans(incomingRoot, now, true);
+            cleanOrphans(outgoingRoot, now, false);
+        }
+
+        private void cleanOrphans(File root, long now, boolean incoming) throws IOException {
+            for (File directory : children(root)) {
+                if (!validId(directory.getName())) continue;
+                if (incoming && records.containsKey(directory.getName())) continue;
+                if (now - directory.lastModified() >= CACHE_TTL_MS) removeTree(root, directory);
+            }
+        }
+
+        private void restore() throws IOException, JSONException {
+            Set<String> ids = new HashSet<>();
+            for (File file : children(journal)) {
+                String base = file.getName().replaceFirst("\\.json(?:\\.bak|\\.new)?$", "");
+                if (validId(base)) ids.add(base);
+            }
+            List<JSObject> restored = new ArrayList<>();
+            for (String id : ids) {
+                JSObject record;
+                try {
+                    record = new JSObject(new String(readAtomic(atomic(id), 512 * 1024), StandardCharsets.UTF_8));
+                    if (!id.equals(record.getString("id")) || record.optJSONArray("files") == null) throw new JSONException("Invalid record");
+                } catch (JSONException failure) {
+                    record = new JSObject().put("id", id).put("state", "ready").put("createdAt", System.currentTimeMillis())
+                        .put("files", new JSONArray());
+                    error(record, "E_QUEUE_CORRUPT: 分享元数据损坏,原记录未被静默丢弃");
+                    save(record);
+                } catch (FileNotFoundException failure) {
+                    continue;
+                }
+                if ("acked".equals(record.optString("state"))) {
+                    removeTree(incomingRoot, child(incomingRoot, id));
+                    atomic(id).delete();
+                    continue;
+                }
+                if (!"ready".equals(record.optString("state"))) {
+                    JSONObject pending = record.optJSONObject("pendingFile");
+                    if (pending != null) {
+                        File committed = localFile(pending, incomingRoot, id);
+                        if (committed != null && committed.isFile()) {
+                            pending.put("size", committed.length());
+                            record.getJSONArray("files").put(pending);
+                        }
+                    }
+                    record.remove("pendingFile");
+                    error(record, "E_COPY_INTERRUPTED: 上次接收被进程退出中断,已完成附件保留,未完成附件请重新分享");
+                    record.put("state", "ready");
+                    save(record);
+                }
+                File shareDirectory = child(incomingRoot, id);
+                for (File file : children(shareDirectory)) {
+                    if (file.getName().endsWith(".part")) removeTree(incomingRoot, file);
+                }
+                restored.add(record);
+            }
+            restored.sort(Comparator.comparingLong(record -> record.optLong("createdAt", 0)));
+            for (JSObject record : restored) records.put(record.getString("id"), record);
+            for (File outgoing : children(outgoingRoot)) {
+                if (!validId(outgoing.getName())) continue;
+                for (File file : children(outgoing)) {
+                    if (file.getName().endsWith(".part")) {
+                        removeTree(outgoingRoot, outgoing);
+                        break;
+                    }
+                }
+            }
+            maintain();
+        }
+
+        File download(String value, String requestedName) throws IOException, JSONException {
+            URL url = checkedUrl(value);
+            maintain();
+            File destination = directory(child(outgoingRoot, UUID.randomUUID().toString()));
+            boolean complete = false;
+            long deadline = SystemClock.elapsedRealtime() + TRANSFER_TIMEOUT_MS;
+            DownloadCookies cookies;
+            synchronized (CookieHandler.class) {
+                cookies = new DownloadCookies(CookieHandler.getDefault());
+                CookieHandler.setDefault(cookies);
+            }
+            try {
+                for (int redirects = 0; redirects <= 5; redirects++) {
+                    if (SystemClock.elapsedRealtime() >= deadline) throw new ShareFailure("E_DOWNLOAD_TIMEOUT", "下载超时");
+                    HttpsURLConnection connection = connections.open(url);
+                    connection.setInstanceFollowRedirects(false);
+                    connection.setUseCaches(false);
+                    connection.setAllowUserInteraction(false);
+                    connection.setConnectTimeout(20000);
+                    connection.setReadTimeout(20000);
+                    connection.setRequestProperty("Accept-Encoding", "identity");
+                    connection.setRequestProperty("Cookie", "");
+                    connection.setRequestProperty("Authorization", "");
+                    ScheduledFuture<?> timeout = TIMER.schedule(connection::disconnect,
+                        Math.max(1, deadline - SystemClock.elapsedRealtime()), TimeUnit.MILLISECONDS);
+                    try {
+                        int status = connection.getResponseCode();
+                        if (status == 301 || status == 302 || status == 303 || status == 307 || status == 308) {
+                            String location = connection.getHeaderField("Location");
+                            if (location == null || redirects == 5) throw new ShareFailure("E_REDIRECT_LIMIT", "下载重定向无效或次数过多");
+                            url = checkedUrl(new URL(url, location).toExternalForm());
+                            continue;
+                        }
+                        if (status != HttpURLConnection.HTTP_OK) throw new ShareFailure("E_HTTP_STATUS", "下载服务器返回 HTTP " + status);
+                        long advertisedSize = connection.getContentLengthLong();
+                        if (advertisedSize > MAX_FILE_BYTES) throw new ShareFailure("E_FILE_TOO_LARGE", "下载文件超过 800 MiB");
+                        long allowance = allowance(true);
+                        if (advertisedSize > allowance) throw new ShareFailure("E_CACHE_LIMIT", "下载文件超出剩余缓存空间");
+                        String suggested = requestedName == null || requestedName.trim().isEmpty()
+                            ? Uri.parse(url.toExternalForm()).getLastPathSegment() : requestedName;
+                        String mime = completeMime(connection.getContentType(), sanitizeName(suggested));
+                        File target = child(destination, completeName(suggested, mime));
+                        File partial = child(destination, target.getName() + ".part");
+                        long copied;
+                        try (InputStream input = connection.getInputStream(); FileOutputStream output = new FileOutputStream(partial)) {
+                            copied = copyBounded(input, output, allowance, deadline);
+                            output.getFD().sync();
+                        }
+                        if (advertisedSize >= 0 && advertisedSize != copied) throw new ShareFailure("E_DOWNLOAD_INCOMPLETE", "下载长度与服务器声明不一致");
+                        if (!partial.renameTo(target)) throw new IOException("Cannot commit outgoing file");
+                        complete = true;
+                        return target;
+                    } finally {
+                        timeout.cancel(false);
+                        connection.disconnect();
+                    }
+                }
+                throw new ShareFailure("E_REDIRECT_LIMIT", "下载重定向次数过多");
+            } finally {
+                synchronized (CookieHandler.class) {
+                    if (CookieHandler.getDefault() == cookies) CookieHandler.setDefault(cookies.previous);
+                }
+                if (!complete) removeTree(outgoingRoot, destination);
+            }
+        }
+
+        private long allowance(boolean outgoing) throws IOException {
+            long[] incomingUsage = usage(incomingRoot);
+            long[] outgoingUsage = usage(outgoingRoot);
+            if (incomingUsage[1] + outgoingUsage[1] >= MAX_CACHED_FILES
+                || (outgoing && outgoingUsage[1] >= MAX_OUTGOING_FILES)) {
+                throw new ShareFailure("E_CACHE_COUNT", "分享缓存附件数量已达上限,请确认已处理分享或等待缓存过期");
+            }
+            long remaining = MAX_CACHE_BYTES - incomingUsage[0] - outgoingUsage[0];
+            long disk = context.getCacheDir().getUsableSpace() - 32L * 1024 * 1024;
+            long allowance = Math.min(MAX_FILE_BYTES, Math.min(remaining, disk));
+            if (allowance <= 0) throw new ShareFailure("E_CACHE_LIMIT", "分享缓存达到 2 GiB 上限或磁盘剩余空间不足");
+            return allowance;
+        }
+
+        private long[] usage(File root) throws IOException {
+            long bytes = 0;
+            long count = 0;
+            for (File directory : children(root)) {
+                if (!validId(directory.getName())) continue;
+                for (File file : children(directory)) {
+                    if (contained(root, file) && file.isFile()) {
+                        bytes += file.length();
+                        count++;
+                    }
+                }
+            }
+            return new long[] {bytes, count};
+        }
+
+        private String receipt(String id) throws IOException {
+            try {
+                Mac mac = Mac.getInstance("HmacSHA256");
+                mac.init(new SecretKeySpec(receiptKey, "HmacSHA256"));
+                return Base64.encodeToString(mac.doFinal(id.getBytes(StandardCharsets.UTF_8)), Base64.NO_WRAP | Base64.URL_SAFE);
+            } catch (Exception failure) {
+                throw new IOException("Cannot create receipt");
+            }
+        }
+
+        private AtomicFile atomic(String id) throws IOException {
+            return new AtomicFile(child(journal, id + ".json"));
+        }
+
+        private void save(JSObject record) throws IOException {
+            writeAtomic(atomic(record.optString("id")), record.toString().getBytes(StandardCharsets.UTF_8));
+        }
+    }
+
+    private static String incomingError(Exception failure) {
+        if (failure instanceof ShareFailure) return failure.getMessage();
+        if (failure instanceof SecurityException) return "E_URI_PERMISSION: 无临时读取授权或授权已失效,请从来源应用重新分享";
+        if (failure instanceof FileNotFoundException) return "E_URI_NOT_FOUND: 来源附件不存在或不可读取";
+        if (failure instanceof SocketTimeoutException) return "E_TRANSFER_TIMEOUT: 读取附件超时";
+        if (failure instanceof IOException) return "E_COPY_IO: 附件读取、缓存写入或队列持久化失败";
+        return "E_COPY_FAILED: 来源提供器返回异常或附件格式无效";
+    }
+
+    private static void error(JSObject record, String message) {
+        JSONArray errors = record.optJSONArray("errors");
+        if (errors == null) {
+            errors = new JSONArray();
+            record.put("errors", errors);
+        }
+        for (int index = 0; index < errors.length(); index++) {
+            if (message.equals(errors.optString(index))) return;
+        }
+        if (errors.length() < 128) errors.put(message);
+    }
+
+    private static File directory(File file) throws IOException {
+        if (!file.isDirectory() && !file.mkdirs()) throw new IOException("Cannot create private share directory");
+        return file;
+    }
+
+    private static File child(File parent, String name) throws IOException {
+        File result = new File(parent, name);
+        if (!result.getCanonicalFile().getParentFile().equals(parent.getCanonicalFile())) {
+            throw new IOException("Invalid share cache path");
+        }
+        return result;
+    }
+
+    private static boolean contained(File root, File target) throws IOException {
+        return target.getCanonicalPath().startsWith(root.getCanonicalPath() + File.separator);
+    }
+
+    private static File localFile(JSONObject metadata, File root, String id) throws IOException {
+        try {
+            Uri uri = Uri.parse(metadata.optString("path", ""));
+            if (!"file".equals(uri.getScheme()) || uri.getPath() == null) return null;
+            File file = new File(uri.getPath());
+            File directory = child(root, id);
+            return file.getCanonicalFile().getParentFile().equals(directory.getCanonicalFile()) ? file : null;
+        } catch (RuntimeException failure) {
+            return null;
+        }
+    }
+
+    private static File[] children(File directory) throws IOException {
+        if (!directory.exists()) return new File[0];
+        File[] files = directory.listFiles();
+        if (files == null) throw new IOException("Cannot list share directory");
+        return files;
+    }
+
+    private static void removeTree(File root, File target) throws IOException {
+        if (!target.exists()) return;
+        if (!contained(root, target)) throw new IOException("Refusing to delete outside private share directory");
+        if (target.isDirectory()) {
+            for (File child : children(target)) removeTree(root, child);
+        }
+        if (!target.delete()) throw new IOException("Cannot delete share cache");
+    }
+
+    private static byte[] readAtomic(AtomicFile file, int limit) throws IOException {
+        try (FileInputStream input = file.openRead(); ByteArrayOutputStream output = new ByteArrayOutputStream()) {
+            byte[] buffer = new byte[4096];
+            int count;
+            while ((count = input.read(buffer)) != -1) {
+                if (count > limit - output.size()) throw new IOException("Share metadata exceeds limit");
+                output.write(buffer, 0, count);
+            }
+            return output.toByteArray();
+        }
+    }
+
+    private static void writeAtomic(AtomicFile file, byte[] bytes) throws IOException {
+        FileOutputStream output = null;
+        try {
+            output = file.startWrite();
+            output.write(bytes);
+            output.getFD().sync();
+            file.finishWrite(output);
+        } catch (IOException failure) {
+            if (output != null) file.failWrite(output);
+            throw failure;
+        }
+    }
+
+    private static void closeQuietly(InputStream input) {
+        try {
+            input.close();
+        } catch (IOException ignored) {
+        }
+    }
+}

+ 54 - 0
android/app/src/test/java/cn/fmode/app/NativeSharePluginTest.java

@@ -0,0 +1,54 @@
+package cn.fmode.app;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.nio.charset.StandardCharsets;
+import java.util.UUID;
+import org.junit.Test;
+
+public class NativeSharePluginTest {
+    @Test
+    public void outgoingOnlyAllowsExactHttpsHosts() throws Exception {
+        for (String host : new String[] {"s3.fmode.cn", "matrix.fmode.cn", "server.fmode.cn"}) {
+            assertEquals(host, NativeSharePlugin.checkedUrl("https://" + host + "/file.pdf?signature=opaque").getHost());
+        }
+        assertEquals("S3.FMODE.CN", NativeSharePlugin.checkedUrl("https://S3.FMODE.CN:443/a").getHost());
+        for (String value : new String[] {
+            "http://s3.fmode.cn/a", "https://s3.fmode.cn.evil.example/a", "https://evil.s3.fmode.cn/a",
+            "https://s3.fmode.cn@evil.example/a", "https://user:password@s3.fmode.cn/a",
+            "https://s3.fmode.cn:8443/a", "https://s3.fmode.cn./a", "file:///data/a", "content://source/a",
+            "https://s3.fmode.cn/a#fragment", "https://127.0.0.1/a", "//s3.fmode.cn/a", "https://s3.fmode.cn\\@evil.example/a"
+        }) {
+            try {
+                NativeSharePlugin.checkedUrl(value);
+                fail(value);
+            } catch (NativeSharePlugin.ShareFailure failure) {
+                assertEquals("E_URL_NOT_ALLOWED", failure.code);
+            }
+        }
+    }
+
+    @Test
+    public void namesCannotTraverseOrExceedFilesystemLimit() {
+        assertEquals("_.._file.pdf", NativeSharePlugin.sanitizeName("../../file.pdf"));
+        assertEquals("shared-file", NativeSharePlugin.sanitizeName("... "));
+        assertEquals("a_b_c_.pdf", NativeSharePlugin.sanitizeName("a\u0000b:c?.pdf"));
+        String safe = NativeSharePlugin.sanitizeName("文件😀".repeat(100));
+        assertTrue(safe.getBytes(StandardCharsets.UTF_8).length <= 180);
+        assertFalse(safe.endsWith("\uD83D"));
+        assertFalse(safe.contains("/"));
+        assertFalse(safe.contains("\\"));
+    }
+
+    @Test
+    public void acknowledgementRequiresGeneratedUuid() {
+        assertTrue(NativeSharePlugin.validId(UUID.randomUUID().toString()));
+        assertFalse(NativeSharePlugin.validId("../../other"));
+        assertFalse(NativeSharePlugin.validId(null));
+        assertFalse(NativeSharePlugin.validId(""));
+        assertEquals(838860800L, NativeSharePlugin.MAX_FILE_BYTES);
+    }
+}

+ 10 - 0
android/jpush-compile-check.init.gradle

@@ -0,0 +1,10 @@
+def isolatedDirectory = System.getenv('FMODE_JPUSH_TEST_BUILD_DIR')
+if (!isolatedDirectory) {
+    throw new GradleException('FMODE_JPUSH_TEST_BUILD_DIR is required for isolated compilation')
+}
+
+gradle.beforeProject { target ->
+    if (target.path == ':app') {
+        target.layout.buildDirectory.set(new File(isolatedDirectory))
+    }
+}

+ 179 - 0
docs/jpush-integration.md

@@ -0,0 +1,179 @@
+# 极光推送子任务:配置与整合交接
+
+核查日期:2026-11-16。仅 Android;不依赖微信登录、企微 SDK 或分享模块。
+
+## 主源核验与选择
+
+- 优先主源 `ahhxyz/jpush-capacitor-plugin` 的 HEAD 为 `fea7722187bd83e8e521cfe5725638fe273d1a4c`,`package.json` 标为 4.0.6,`plugin.xml` 仍标为 3.8.2。
+- 它实际为 Cordova 插件,入口是 `www/JPushPlugin.js`,依赖回调式 `init`、`getRegistrationID`、`setAlias`、`deleteAlias`,不是现代 Capacitor TypeScript 插件。
+- `src/android/JPushPlugin.java` 直接导入 `cn.fits.plugins.jpush.FitsPushPlugin`,并在 `initialize` 解引用 `FitsPushPlugin.jpushIntent.toString()`;该依赖在 `plugin.xml` 中被注释。不能直接作为当前工程可构建、可冷启动的 Capacitor 8 插件。
+- 主源同时捆绑 JPush Android 4.6.3、JCore 3.2.2、旧厂商 jar/aar,并声明定位、存储、读取电话状态、查询安装列表等权限。未通过真实安装/真机验证;不能把这些事实概括成“所有 Cordova 插件都不支持 Capacitor 8”。
+- `registry.npmjs.org/jpush-capacitor-plugin` 核查返回 404,GitHub API 命中限流;版本和提交来自 raw 主源与 `git ls-remote`,不声称查到了不存在的 npm 发布版本。
+- 因以上具体源码缺口采用用户允许的局部自建 Capacitor 插件,保持现有 Capacitor 8.6.2。官方 Maven Central 当前稳定版本为 JPush 6.3.1(元数据更新 2026-11-10)、JCore 5.6.0(2026-10-26);依赖固定版本,排除 JPush POM 的动态 JCore 范围。
+- 已下载这两个官方 AAR 到系统临时目录,并通过 `javap` 核实实际签名:`JPushInterface.init/getRegistrationID/setAlias/deleteAlias/stopPush/resumePush`、`JPushMessageReceiver`、`JCommonService`、`JCollectionAuth.setAuth`。不将 SDK 二进制提交仓库。
+
+主源与官方资料:
+
+- https://github.com/ahhxyz/jpush-capacitor-plugin
+- https://raw.githubusercontent.com/ahhxyz/jpush-capacitor-plugin/master/package.json
+- https://raw.githubusercontent.com/ahhxyz/jpush-capacitor-plugin/master/plugin.xml
+- https://raw.githubusercontent.com/ahhxyz/jpush-capacitor-plugin/master/src/android/JPushPlugin.java
+- https://docs.jiguang.cn/jpush/client/Android/android_guide
+- https://docs.jiguang.cn/jpush/client/Android/android_api
+- https://repo.maven.apache.org/maven2/cn/jiguang/sdk/jpush/maven-metadata.xml
+- https://repo.maven.apache.org/maven2/cn/jiguang/sdk/jcore/maven-metadata.xml
+
+## 默认安全行为
+
+`JPUSH_OPTIONS.enabled` 默认 `false`;Gradle `fmodeJpushEnabled` 默认 `false`。默认 APK 仅编译 `JPushPlugin` 桥接,不包含 JPush/JCore AAR,也不编译依赖 SDK 的四个 Java 文件。未提供 AppKey 不影响默认构建,SDK 不会启动。
+
+即使显式打开 Gradle 开关,缺少合法 AppKey、声明的 Receiver/Service/点击 Activity,或保留 SDK 自动初始化 Provider,`getStatus()` 也返回不可用,`start()` 拒绝启动。原生 `start` 还要求 `privacyConsent: true`;TS 入口亦要求明确同意,不在启动时自动弹通知权限。
+
+`phase=started` 只表示桥接初始化并完成清理旧别名,不代表已经获得注册 ID、服务器投递成功或具备离线到达能力。`registrationId` 初始为 `null`,仅接受 SDK 查询/注册回调真实返回值,不生成假 ID。`getStatus` 不返回 AppKey、别名、Token 或个人信息。
+
+## 主代理必须完成的整合
+
+以下受限文件本子任务没有修改;未完成整合前保持两端开关关闭。
+
+### 1. MainActivity.java
+
+在现有 `onCreate` 的 `super.onCreate(savedInstanceState)` 之前,与现有插件注册并列添加:
+
+```java
+registerPlugin(JPushPlugin.class);
+```
+
+不需要改 `onNewIntent`,Capacitor 的插件生命周期会把 Intent 交给 `JPushPlugin.handleOnNewIntent`。本插件专用 extra 为 `fmodeJpushPayload`,不复用旧 `deepLink` extra,避免 `FmodeNotifyPlugin` 再导航一次。
+
+### 2. AndroidManifest.xml(仅启用 SDK 的构建)
+
+当前 `android/app/src/main/AndroidManifest.xml` 不需要推送修改,保留主代理的分享/深链等更改。下面三个组件只有开启 Gradle 开关才会编译,不能把它们直接放进默认 main manifest。
+
+请由主代理新建 `android/app/src/jpush/AndroidManifest.xml`,完整内容如下。推送 Gradle 段已实现:仅当 `fmodeJpushEnabled=true` 且此文件存在时,作为 debug/release overlay 合并;默认完全不使用。此文件未创建也能做 SDK 编译检查,但运行门禁会阻止 SDK 启动。
+
+```xml
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools">
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" tools:node="remove" />
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:node="remove" />
+    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" tools:node="remove" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" tools:node="remove" />
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:node="remove" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
+    <application>
+        <receiver android:name=".JPushReceiver" android:exported="false">
+            <intent-filter>
+                <action android:name="cn.jpush.android.intent.RECEIVER_MESSAGE" />
+                <category android:name="${applicationId}" />
+            </intent-filter>
+        </receiver>
+        <service android:name=".JPushService" android:exported="false" android:process=":pushcore">
+            <intent-filter>
+                <action android:name="cn.jiguang.user.service.action" />
+            </intent-filter>
+        </service>
+        <activity
+            android:name=".JPushClickActivity"
+            android:exported="true"
+            android:launchMode="singleTop"
+            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
+        <provider android:name="cn.jpush.android.service.InitProvider" tools:node="remove" />
+    </application>
+</manifest>
+```
+
+SDK AAR 自带 `JPUSH_APPKEY`、`JPUSH_CHANNEL` metadata,Gradle 已提供 placeholders,无需重复 metadata。移除 InitProvider 避免其早于 JS/用户同意执行;原生状态门禁也会检查这一点。
+
+注意 SDK 5.4.0 以后回调 action 是 `RECEIVER_MESSAGE`,不是旧插件中的 `RECEIVE_MESSAGE`;原生门禁会拒绝错误的过滤器。
+
+审查并移除 AAR 带入但本功能不需要的权限:`ACCESS_COARSE_LOCATION`、`ACCESS_FINE_LOCATION`、`ACCESS_BACKGROUND_LOCATION`、`READ_PHONE_STATE`、`QUERY_ALL_PACKAGES`、`WRITE_EXTERNAL_STORAGE`、`READ_EXTERNAL_STORAGE`。使用 `<uses-permission android:name="android.permission.…" tools:node="remove" />`。保留网络与通知所需权限;不要重新加入精确闹钟权限。检查所有最终 merged manifest,不只检查源码。
+
+### 3. Gradle / AppKey
+
+默认验证命令:`android/gradlew.bat :app:assembleDebug`。
+
+准备好推送构建的 manifest 后,由 CI/受保护本机环境注入 `JPUSH_APPKEY`,然后使用 `-PfmodeJpushEnabled=true`。不要在命令参数、仓库文件或构建日志中打印其值。AppKey 是客户端应用标识,不是可保密的服务端凭据;JPush Master Secret 必须只在受信任服务端,绝不放进 APK/TS。
+
+### 4. app.config.ts / 登录生命周期
+
+在 `app.config.ts` 的 imports 中增加:
+
+```ts
+import { provideJPushLifecycle } from './core/jpush.lifecycle';
+```
+
+在现有 `providers` 数组中增加一项,不替换已有 initializer:
+
+```ts
+provideJPushLifecycle(),
+```
+
+该 provider 通过真正的 Angular AppInitializer 调用 `JPushService.start()`,**不传 `true`**。默认禁用立即返回 `false`;即使以后配置 enabled,也会先停在 `privacy-consent-required`,不会把 bootstrap 当作用户同意。它还创建 root 生命周期监听:既有 SessionService 的账号/租户变化或登出会请求 `unbindAccount()`,不需要修改 SessionService,也不读取或发送 Token。
+
+- 启用配置时另导入 `JPUSH_OPTIONS` 并添加 `{ provide: JPUSH_OPTIONS, useValue: { enabled: true } }`;默认不要增加这一项。
+- 用户明确同意极光隐私告知后调用 `JPushService.start(true)`,不要以通知权限等同隐私同意,也不要阻塞应用首屏等待网络。
+- 仅在用户主动申请时调用 `requestPermission()`,其复用现有 `AppNotificationService.request()`;已有权限引导保留。
+- 现有任意登录方式均可用。由受信任后台按已认证账号/租户签发不透明、稳定别名 `fm_` 加 32–60 个小写十六进制字符,再调用 `bindAccount(alias)`。不得传手机号、姓名、邮箱、sessionToken,不建议用这些字段的无盐散列代替不透明别名。
+- `start` 先清理 SDK 留存的旧别名;`bindAccount` 先删除旧别名再设置新别名。所有操作串行,仅收到 SDK 成功回执才返回成功,15 秒超时返回失败。
+- 登出/切号先 `await unbindAccount()`;失败不会伪报解绑成功,会停止推送并显示 `binding=error`。身份登出不应因离线而永远阻塞。下次启动/绑定会先重试清理;后台也必须注销原账号的设备关联,不能只依赖设备在线删别名。
+- 撤回隐私同意或销毁能力调用 `stop()`。它尝试解绑、停止 SDK、撤回本地 SDK 同意标志并移除本服务监听,不动旧本地通知服务。
+- `registrationId()` 仅保存在内存信号;需要设备登记时经已认证后端传输,不打印、不落日志。本子任务不虚构登记接口。
+- `package.json`、锁文件、`capacitor.config.ts` 不需要添加旧插件或降级 Capacitor。
+
+当前可用连接点:隐私同意事件调用 `start(true)`,拒绝/撤回调用 `stop()`,已有通知权限 UI 调用 `requestPermission()`,后台签发别名返回后调用 `bindAccount(alias)`,主动登出可在清会话前 `await unbindAccount()`。root 监听是主动解绑漏接时的补充,不代替需要精确 await 的登出流程。
+
+**当前尚未连接**:没有伪造别名签发后台,没有给现有登录成功逻辑硬编码 alias,也没有现成的极光隐私同意 UI 可擅自复用;这些入口只有在主代理接上实际 UI/已鉴权后台后才可用。主代理只加本节 initializer 并不代表账号推送完整打通。后台返回较慢时,调用方必须确认当前账号/租户仍是发起请求时的身份再绑定。
+
+### 5. 隔离的 enabled 编译检查
+
+`android/jpush-compile-check.init.gradle` 支持通过 `FMODE_JPUSH_TEST_BUILD_DIR` 将 app 编译产物全部放入一次性临时目录。检查时只在子进程环境提供全零、非秘密的 24 位合成 AppKey,关闭 Gradle build/configuration cache,只运行 `:app:compileDebugJavaWithJavac -PfmodeJpushEnabled=true`。不生成发布 APK,不连接设备,不执行 SDK 启动;之后恢复环境并删除经过路径校验的临时目录。合成 AppKey 不写入仓库、文档示例、受保护配置或发布产物。
+
+## 通知内容与点击合同
+
+推荐服务端 notification extras 仅携带:
+
+```json
+{
+  "businessKey": "task-completed:opaque-event-id",
+  "deepLink": "fmode://chat/opaque-agent-id/opaque-session-id"
+}
+```
+
+不得携带 Token、电话号码或不必要的个人信息。服务端还要校验目标账号有权读取目标对象;深链本身不授予权限。
+
+- 收到 SDK notification 只记去重键,不再调用本地通知,避免同一远程通知被二次展示。
+- 收到 data/custom message 且 JS 存活时,复用 `AppNotificationService.notify()`(包括既有权限、渠道、点击与按 key 覆盖)。JS 不存在时不补造“离线数据消息通知”。
+- 冷启动点击:服务端 Android notification 使用 `intent:#Intent;component=cn.fmode.app/cn.fmode.app.JPushClickActivity;end` 作为点击 Intent,SDK 把 `JMessageExtra` 传入该 Activity。解析 `msg_id`/`n_extras` 后转交 MainActivity,插件 `load` 保留事件直至 JS 监听就绪;热启动走插件 `handleOnNewIntent`。
+- `JPushReceiver.onNotifyMessageOpened` 为已存活桥接提供另一路回调;不在 BroadcastReceiver 中拉 Activity,避免 Android 12+ notification trampoline。两路按消息 ID 去重。
+- TS 点击统一调用既有 `DeepLinkService.toRoute()` / `navigate()`。到达不导航;未知 scheme、非法百分号编码等不导航,不新增路由。
+- 点击 Activity 是可导出的入口,数据视作不可信输入,仅允许经过既有深链白名单的内部路由。仍须由既有 auth/对象权限控制页面访问。
+
+## 本地通知去重边界
+
+内存内按业务事件键/消息 ID 去重,TTL 五分钟、上限 256 条;点击和到达使用独立集合。应用重启不声称跨进程持久去重。
+
+本子任务没有修改现有 `AppNotificationService` 或消息生产者。要让既有在线业务与 data message 共享去重,由主代理将相关生产者从 `appNotification.notify(notice)` 改为 `jpush.notifyLocal(notice, businessEventKey)`。`notice.key` 是会话通知覆盖键;`businessEventKey` 必须代表一次具体业务事件,不可把 `task-done:<agentId>` 当永久事件键,否则会误吞后续任务。
+
+SDK notification 在 JS 收到回调前可能已经展示;如果本地生产者先展示,不能仅靠 JS 保证反向顺序不双显。后端必须为同一业务选择唯一投递策略,不同时发 notification 与 data,并在启用远程 notification 后停用同一事件的本地生产者。没有业务事件 ID 或没有主代理迁移时,不声称全链路去重完成。
+
+## 未就绪资源与验收边界
+
+缺少:匹配 `cn.fmode.app` 的 JPush AppKey/控制台应用、后台凭据安全配置、鉴权设备登记与别名签发/撤销接口、业务事件推送触发、通知点击 Intent 配置、厂商通道申请配置、隐私告知与同意入口。
+
+厂商通道当前明确关闭,无华为/小米/OPPO/vivo SDK;不要把极光基础长连接误称为国产 ROM 杀进程后的可靠离线到达。未进行服务端真实发送、真机注册、前后台/杀进程/ROM 回归、通知点击实测。上述由主代理在资源齐备后回归,不属于本次已通过门禁。
+
+## 实际验证记录
+
+- ChromeHeadless 定向执行 `jpush.service.spec.ts` 与 `jpush.lifecycle.spec.ts`:24/24 通过。覆盖默认禁用、隐私门禁、缺 AppKey、启动清理旧别名、注册 ID、监听回收、点击白名单/去重、复用本地通知、别名串行回执/失败、AppInitializer 及登出/切号/租户变化解绑。
+- `tsc -p tsconfig.app.json --noEmit`、`tsc -p tsconfig.spec.json --noEmit` 通过;后加生命周期代码亦经过上述 Angular 测试编译。
+- 默认 `:app:assembleDebug :app:testDebugUnitTest` 通过,后者执行当前共享工程 4 项 JVM 测试,无失败;不是新增 SDK 真机测试。
+- 默认 `debugRuntimeClasspath` 的 `dependencyInsight --dependency cn.jiguang.sdk` 显示无匹配依赖;`apkanalyzer dex packages --defined-only` 确认默认 APK 有本地桥接、没有 JPush/JCore SDK 定义。
+- 开启 `fmodeJpushEnabled=true` 后 `:app:compileDebugJavaWithJavac` 通过;也使用仅子进程环境中的非秘密合成 AppKey、临时 app build 目录、关闭 build/configuration cache 再次编译通过,确认 `JPushSdk.class` 实际产出,APK 数量为 0。未执行任何 SDK 运行任务。
+- scoped `git diff --check` 通过。构建存在原有 flatDir/Gradle 弃用提示与 SDK API 弃用提示,无编译错误。
+- 未运行 ADB、CDP、模拟器或真机操作;未安装/发布含合成 AppKey 的 APK。父代理负责最终 web build、cap sync、APK 与设备回归。
+
+隔离编译临时目录的递归清理被工具执行策略拒绝,**尚未自动清除**。待主代理/用户用文件管理器删除:`C:\Users\11729\AppData\Local\Temp\fmode-jpush-compile-6a53fcb1fdf34f0a8d3bc3e36411a77e`。合成值只在此一次性编译产物和子进程环境中,不在仓库代码/发布 APK;不要复制其 merged manifest 到项目。不能把这个清理项写成已完成。
+
+以上单测与编译不等同于 SDK 注册、远程发送、账号推送或离线到达完整打通。

+ 73 - 0
scripts/android-cdp.mjs

@@ -0,0 +1,73 @@
+import { execFileSync } from 'node:child_process';
+
+export function adb(...args) {
+  const serial = process.env.ADB_SERIAL;
+  return execFileSync(process.env.ADB || 'adb', [...(serial ? ['-s', serial] : []), ...args], {
+    encoding: 'utf8', timeout: 30_000, windowsHide: true,
+  }).trim();
+}
+
+export async function connectAndroidWebView(packageName = 'cn.fmode.app') {
+  const processId = adb('shell', 'pidof', packageName).split(/\s+/)[0];
+  if (!processId) throw new Error('请先启动 Android App');
+  const sockets = adb('shell', 'cat', '/proc/net/unix');
+  const socketName = sockets.split('\n').map((line) => line.trim().split(/\s+/).at(-1))
+    .find((name) => name?.endsWith(`webview_devtools_remote_${processId}`));
+  if (!socketName) throw new Error('未找到 App WebView 调试端口,请安装 debug APK');
+  const port = adb('forward', 'tcp:0', `localabstract:${socketName.replace(/^@/, '')}`);
+  const endpoint = `http://127.0.0.1:${port}`;
+  let socket;
+  try {
+    const targets = await (await fetch(`${endpoint}/json/list`)).json();
+    const target = targets.find((candidate) => candidate.type === 'page' && candidate.url.startsWith('https://localhost'));
+    if (!target) throw new Error('未找到 Fmode 页面');
+    socket = new WebSocket(target.webSocketDebuggerUrl);
+    await new Promise((resolve, reject) => {
+      socket.addEventListener('open', resolve, { once: true });
+      socket.addEventListener('error', () => reject(new Error('WebView 调试连接失败')), { once: true });
+    });
+  } catch (error) {
+    adb('forward', '--remove', `tcp:${port}`);
+    throw error;
+  }
+  let nextId = 0;
+  const pending = new Map();
+  socket.addEventListener('message', (event) => {
+    const message = JSON.parse(event.data);
+    if (!message.id) return;
+    const request = pending.get(message.id);
+    if (!request) return;
+    pending.delete(message.id);
+    clearTimeout(request.timer);
+    if (message.error) request.reject(new Error(message.error.message));
+    else request.resolve(message.result);
+  });
+  socket.addEventListener('close', () => {
+    for (const request of pending.values()) {
+      clearTimeout(request.timer);
+      request.reject(new Error('WebView 调试连接已断开'));
+    }
+    pending.clear();
+  });
+  const send = (method, params = {}) => new Promise((resolve, reject) => {
+    const id = ++nextId;
+    const timer = setTimeout(() => {
+      pending.delete(id);
+      reject(new Error(`WebView 调用超时:${method}`));
+    }, 30_000);
+    pending.set(id, { resolve, reject, timer });
+    socket.send(JSON.stringify({ id, method, params }));
+  });
+  return {
+    send,
+    async evaluate(expression) {
+      const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
+      if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description || 'WebView 脚本执行失败');
+      return result.result?.value;
+    },
+    close() {
+      socket.close();
+      adb('forward', '--remove', `tcp:${port}`);
+    },
+  };
+}