const {withAndroidManifest,withMainApplication,withDangerousMod}=require('expo/config-plugins'); const fs=require('node:fs/promises'),path=require('node:path'); module.exports=config=>{ const pkg=config.android?.package;if(!/^cn\.cmvr\.wms(\.dev)?$/.test(pkg||''))throw Error('Unexpected application package'); config=withAndroidManifest(config,cfg=>{ const m=cfg.modResults.manifest;m.queries=m.queries||[{}];const query=m.queries[0];query.intent=query.intent||[]; if(!query.intent.some(i=>i.data?.some(d=>d.$?.['android:mimeType']==='application/vnd.android.package-archive')))query.intent.push({action:[{$:{'android:name':'android.intent.action.VIEW'}}],data:[{$:{'android:mimeType':'application/vnd.android.package-archive'}}]}); return cfg; }); config=withMainApplication(config,cfg=>{ const marker='add(CmvrApkVerificationPackage())',source=cfg.modResults.contents; if(!source.includes(marker)){const needle='PackageList(this).packages.apply {';if(!source.includes(needle))throw Error('Unexpected MainApplication template');cfg.modResults.contents=source.replace(needle,needle+'\n '+marker);} return cfg; }); return withDangerousMod(config,['android',async cfg=>{ const dir=path.join(cfg.modRequest.platformProjectRoot,'app/src/main/java',...pkg.split('.'));await fs.mkdir(dir,{recursive:true}); const transfer=await fs.readFile(path.join(__dirname,'native/CmvrPackageTransfer.java'),'utf8'); await fs.writeFile(path.join(dir,'CmvrPackageTransfer.java'),transfer.replace('package __CMVR_PACKAGE__;','package '+pkg+';')); await fs.writeFile(path.join(dir,'CmvrApkVerificationPackage.kt'),`package ${pkg} import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.net.Uri import android.os.Build import com.facebook.react.ReactPackage import com.facebook.react.bridge.* import com.facebook.react.uimanager.ViewManager import java.io.File import java.security.MessageDigest import java.net.URI import java.util.concurrent.ConcurrentHashMap class CmvrApkVerificationPackage : ReactPackage { override fun createNativeModules(context: ReactApplicationContext): List = listOf(CmvrApkVerification(context)) override fun createViewManagers(context: ReactApplicationContext): List> = emptyList() } class CmvrApkVerification(private val context: ReactApplicationContext) : ReactContextBaseJavaModule(context) { private val downloads = ConcurrentHashMap() override fun getName() = "CmvrApkVerification" @ReactMethod fun addListener(name: String) { } @ReactMethod fun removeListeners(count: Double) { } @ReactMethod fun cancelDownload(id: String) { downloads[id]?.cancel() } @ReactMethod fun download(id: String, options: ReadableMap, promise: Promise) { try { require(id.matches(Regex("[a-zA-Z0-9-]{1,100}")) && !downloads.containsKey(id)) val hash = requireNotNull(options.getString("sha256")) val size = options.getDouble("size");require(size >= 1 && size <= 250L*1024*1024 && size % 1.0 == 0.0) val url = URI(requireNotNull(options.getString("url"))) val host = requireNotNull(url.host);val ip = host.split('.').mapNotNull { it.toIntOrNull() } val internal = ip.size == 4 && ip.all { it in 0..255 } && (ip[0] == 10 || ip[0] == 192 && ip[1] == 168 || ip[0] == 172 && ip[1] in 16..31) require((url.scheme == "http" || url.scheme == "https") && url.userInfo == null && url.fragment == null && url.query == null) require(internal || host == "localhost" || host == "127.0.0.1" || url.scheme == "https" && host == "wms.svc.cmvr-iot.icu") require(url.path.matches(Regex("/(dev-api/|prod-api/)?system/mobile-release/" + hash + "/content"))) val targetUri = requireNotNull(options.getString("uri"));val parsed = Uri.parse(targetUri);require(parsed.scheme == "file") val file = File(requireNotNull(parsed.path)).canonicalFile;val base = File(context.cacheDir,"app-updates").canonicalFile require(file.parentFile == base && file.name.matches(Regex("[a-f0-9]{64}-[a-z0-9-]+\\\\.apk"))) val headers = mutableMapOf();val source = requireNotNull(options.getMap("headers"));val keys = source.keySetIterator() while(keys.hasNextKey()) { val key=keys.nextKey();require(key in setOf("Authorization","X-CMVR-Dev-Server"));val value=requireNotNull(source.getString(key));require(value.length <= 8192 && !value.contains('\\r') && !value.contains('\\n'));headers[key]=value } require(headers["Authorization"]?.startsWith("Bearer ") == true) val job = CmvrPackageTransfer(url.toString(),headers,file,size.toLong(),hash,4) { phase, bytes, total, connections -> val event=Arguments.createMap();event.putString("id",id);event.putString("phase",phase);event.putDouble("bytes",bytes.toDouble());event.putDouble("total",total.toDouble());event.putInt("connections",connections) context.emitDeviceEvent("CmvrPackageProgress",event) } downloads[id]=job Thread({ try { val connections=job.run();val result=Arguments.createMap();result.putString("uri",targetUri);result.putString("sha256",hash);result.putDouble("size",file.length().toDouble());result.putInt("connections",connections);promise.resolve(result) } catch(error: Exception) { promise.reject(if(error.message == "AUTH_EXPIRED") "AUTH_EXPIRED" else "DOWNLOAD_FAILED",error.message ?: "安装包下载失败,请重试") } finally { downloads.remove(id,job) } },"cmvr-package-download").start() } catch(error: Exception) { promise.reject("INVALID_DOWNLOAD","安装包下载参数无效,请重新检查更新") } } @Suppress("DEPRECATION") private fun signatures(info: PackageInfo): Set { val signatures = if (Build.VERSION.SDK_INT >= 28) info.signingInfo?.apkContentsSigners else info.signatures return signatures?.map { signature -> MessageDigest.getInstance("SHA-256").digest(signature.toByteArray()).joinToString("") { "%02x".format(it) } }?.toSet() ?: emptySet() } @Suppress("DEPRECATION") @ReactMethod fun verify(uri: String, expectedVersion: Double, promise: Promise) { try { val parsed = Uri.parse(uri) require(parsed.scheme == "file") val file = File(requireNotNull(parsed.path)).canonicalFile val base = File(context.cacheDir, "app-updates").canonicalFile require(file.parentFile == base && file.isFile && expectedVersion >= 1 && expectedVersion <= Int.MAX_VALUE && expectedVersion % 1.0 == 0.0) val flags = if (Build.VERSION.SDK_INT >= 28) PackageManager.GET_SIGNING_CERTIFICATES else PackageManager.GET_SIGNATURES val manager = context.packageManager val archive = requireNotNull(manager.getPackageArchiveInfo(file.path, flags)) val current = manager.getPackageInfo(context.packageName, flags) val version = if (Build.VERSION.SDK_INT >= 28) archive.longVersionCode else archive.versionCode.toLong() val archiveSignatures = signatures(archive) val installedSignatures = signatures(current) require(archive.packageName == context.packageName && version == expectedVersion.toLong() && archiveSignatures.isNotEmpty() && archiveSignatures == installedSignatures) promise.resolve(true) } catch (error: Exception) { promise.reject("INVALID_APK", "安装包与当前应用的包名、签名或版本不一致,请联系管理员。") } } } `); return cfg; }]); };